Cotton code
793 lines · 33.7 KB · RustRaw
//! Portable data definitions, signed with the caller's existing device identity.use super::automations::said;use super::{refusal_words, TableDefinition, ToolDefinition};use base64::{engine::general_purpose::URL_SAFE_NO_PAD, Engine};use ed25519_dalek::{Signature as Ed25519Signature, VerifyingKey};use serde_json::Value;use std::collections::{BTreeMap, BTreeSet};pub const MAX_PACKAGE_BYTES: usize = 16 * 1024 * 1024;const MAX_ENTRIES: usize = 512;const DOMAIN: &[u8] = b"CottonDB.cottontool.v1\0";#[derive(Debug, Clone)]pub struct ToolPackage {    pub board: Option<super::board::BoardDefinition>,    pub tool: ToolDefinition,    pub tables: Vec<TableDefinition>,    /// Relative names beneath pictures/, including the raster extension.    pub pictures: BTreeMap<String, Vec<u8>>,    /// Sample rows beneath records/, keyed by table id: data objects a    /// person may ask to have created on import ("with sample rows"), each    /// already checked against its table the way a create is.    pub samples: BTreeMap<String, Vec<Value>>,}#[derive(Debug, Clone)]pub struct ImportedPackage {    pub package: ToolPackage,    pub signature: Signature,}/// Who signed a package: nobody, or the device key its signature verified/// against. A typed value, never a sentence: it travels as/// `{"signature":"unsigned"}` or `{"signature":"signed","by":"<key>"}`, and/// whatever a person reads about it is said where it is drawn.#[derive(Debug, Clone, PartialEq, Eq)]pub enum Signature {    Unsigned,    SignedBy { key: String },}impl Signature {    /// The signature a tool definition carries: its author's device key when    /// it is signed. [`decode_package`] verifies a signature before a package    /// is answered at all, so a held definition says what was verified.    pub fn of(tool: &ToolDefinition) -> Self {        match tool.signature {            Some(_) => Self::SignedBy { key: tool.author.device.clone() },            None => Self::Unsigned,        }    }    /// The fields it adds to an answer: `signature`, and `by` when signed.    pub fn fields(&self) -> serde_json::Map<String, Value> {        match serde_json::to_value(self) {            Ok(Value::Object(fields)) => fields,            _ => serde_json::Map::new(),        }    }}/// The machine form a signature is written in. Nothing reads it back: a/// signature is worked out from the verified package each time it is/// answered ([`Signature::of`]), never stored.#[derive(serde::Serialize)]#[serde(tag = "signature", rename_all = "lowercase")]enum SignatureWire {    Unsigned,    Signed { by: String },}impl serde::Serialize for Signature {    fn serialize<S: serde::Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {        match self {            Self::Unsigned => SignatureWire::Unsigned,            Self::SignedBy { key } => SignatureWire::Signed { by: key.clone() },        }        .serialize(serializer)    }}#[derive(Debug, thiserror::Error)]#[error("cottontool: {0}")]pub struct PackageError(pub String);fn error(e: impl ToString) -> PackageError {    PackageError(e.to_string())}/// Package tables contain no local overlay bookkeeping. Unchanged built-ins,/// and unchanged tables a kit package carries of its own (Books' book), retain/// their shipped bytes; definition-file shipping uses `definition_file`.pub fn product_table(table: &TableDefinition) -> Result<Vec<u8>, serde_json::Error> {    let mut table = table.clone();    table.edited.clear();    table.base_hash = None;    let shipped = super::BUILTIN_DEFINITION_FILES        .iter()        .find(|(id, _)| *id == table.id)        .map(|(_, raw)| raw.as_bytes())        .or_else(|| crate::kit::table_file(&table.id));    if let Some(raw) = shipped {        let unchanged = std::str::from_utf8(raw).ok().and_then(|raw| TableDefinition::from_json(raw).ok());        if unchanged.as_ref() == Some(&table) {            return Ok(raw.to_vec());        }    }    let mut bytes = serde_json::to_vec_pretty(&table)?;    bytes.push(b'\n');    Ok(bytes)}/// Write a shipped definition by changing only typed fields that differ from/// its shipped copy. Default expansion and package DDL are not author edits.pub fn definition_file(table: &TableDefinition, raw: &str) -> Result<Vec<u8>, serde_json::Error> {    let mut resolved = table.clone();    resolved.edited.clear();    resolved.base_hash = None;    let shipped: TableDefinition = serde_json::from_str(raw)?;    if resolved == shipped { return Ok(raw.as_bytes().to_vec()); }    let base = serde_json::to_value(&shipped)?;    let theirs = serde_json::to_value(&resolved)?;    let mut file: Value = serde_json::from_str(raw)?;    fn carry(base: &Value, theirs: &Value, file: &mut Value) {        if base == theirs { return; }        if let (Some(base), Some(theirs), Some(file)) = (base.as_object(), theirs.as_object(), file.as_object_mut()) {            for key in base.keys().chain(theirs.keys()).collect::<BTreeSet<_>>() {                if base.get(key) == theirs.get(key) { continue; }                match theirs.get(key) {                    None => { file.remove(key); }                    Some(value) => {                        if let (Some(before), Some(current)) = (base.get(key), file.get_mut(key)) {                            carry(before, value, current);                        } else { file.insert(key.clone(), value.clone()); }                    }                }            }        } else if let (Some(base), Some(theirs), Some(file)) = (base.as_array(), theirs.as_array(), file.as_array_mut()) {            let key = ["key", "id", "name", "column", "act", "fact", "method"].into_iter().find(|key| {                [base, theirs, &*file].into_iter().all(|items| {                    let ids: Option<BTreeSet<_>> = items.iter().map(|item| item.get(*key)?.as_str()).collect();                    ids.is_some_and(|ids| ids.len() == items.len())                })            });            if let Some(key) = key {                *file = theirs.iter().map(|next| {                    let id = next.get(key);                    let before = base.iter().find(|item| item.get(key) == id);                    let current = file.iter().find(|item| item.get(key) == id);                    if let (Some(before), Some(current)) = (before, current) {                        let mut current = current.clone(); carry(before, next, &mut current); current                    } else { next.clone() }                }).collect();            } else { *file = theirs.clone(); }        } else { *file = theirs.clone(); }    }    carry(&base, &theirs, &mut file);    let mut bytes = serde_json::to_vec_pretty(&file)?;    bytes.push(b'\n');    Ok(bytes)}pub fn product_board(board: &super::board::BoardDefinition) -> Result<Vec<u8>, serde_json::Error> {    if let Some((_, raw)) = super::board::BUILTIN_BOARD_FILES.iter().find(|(id, _)| *id == board.id) {        if super::board::BoardDefinition::from_json(raw).ok().as_ref() == Some(board) {            return Ok(raw.as_bytes().to_vec());        }    }    let mut bytes = serde_json::to_vec_pretty(board)?;    bytes.push(b'\n');    Ok(bytes)}/// A manifest as a package carries it: pretty, one key per line, as a/// person reads and edits it (`kits/personal/tools/<tool>/manifest.json`).fn manifest(tool: &ToolDefinition) -> Result<Vec<u8>, PackageError> {    let mut bytes = serde_json::to_vec_pretty(tool).map_err(error)?;    bytes.push(b'\n');    Ok(bytes)}/// A table's sample rows as a package carries them (`records/<table>.json`):/// pretty, one key per line, as its manifest and tables are, so a kit/// package's rows are the file a person reads and edits.fn sample_rows(rows: &[Value]) -> Result<Vec<u8>, PackageError> {    let mut bytes = serde_json::to_vec_pretty(rows).map_err(error)?;    bytes.push(b'\n');    Ok(bytes)}/// A package's files (`kits/<kit>/tools/<tool>/`, instructions.md written from the/// manifest) as the archive `import_tool` takes, checked as an import is.pub fn archive_files(files: &BTreeMap<String, Vec<u8>>) -> Result<Vec<u8>, PackageError> {    decode_entries(files)?;    write_entries(files)}/// The callback must use the SAME device signer used for pairing and approvals.pub fn encode_package(    package: &ToolPackage,    signer: impl FnOnce(&[u8]) -> [u8; 64],) -> Result<Vec<u8>, PackageError> {    let mut entries = BTreeMap::new();    let mut tool = package.tool.clone();    tool.signature = None;    entries.insert("manifest.json".into(), manifest(&tool)?);    entries.insert(        "instructions.md".into(),        tool.instructions.as_bytes().to_vec(),    );    if let Some(board) = &package.board {        entries.insert("board.json".into(), product_board(board).map_err(error)?);    }    for table in &package.tables {        if entries            .insert(                format!("tables/{}.json", table.id),                product_table(table).map_err(error)?,            )            .is_some()        {            return Err(error(said("duplicate_table", &[("id", &table.id)])));        }    }    for (name, bytes) in &package.pictures {        entries.insert(format!("pictures/{name}"), bytes.clone());    }    for (table, rows) in &package.samples {        entries.insert(            format!("records/{table}.json"),            sample_rows(rows)?,        );    }    // Validate exports through the exact same boundary as imports before signing.    decode_entries(&entries)?;    tool.signature = Some(URL_SAFE_NO_PAD.encode(signer(&payload(&entries)?)));    entries.insert("manifest.json".into(), manifest(&tool)?);    let bytes = write_entries(&entries)?;    decode_package(&bytes)?;    Ok(bytes)}/// Fixtures and data authored without an identity may explicitly travel unsigned.pub fn encode_unsigned_package(package: &ToolPackage) -> Result<Vec<u8>, PackageError> {    let mut entries = BTreeMap::new();    let mut tool = package.tool.clone();    tool.signature = None;    entries.insert("manifest.json".into(), manifest(&tool)?);    entries.insert(        "instructions.md".into(),        tool.instructions.as_bytes().to_vec(),    );    if let Some(board) = &package.board {        entries.insert("board.json".into(), product_board(board).map_err(error)?);    }    for table in &package.tables {        if entries            .insert(                format!("tables/{}.json", table.id),                product_table(table).map_err(error)?,            )            .is_some()        {            return Err(error(said("duplicate_table", &[("id", &table.id)])));        }    }    for (name, bytes) in &package.pictures {        entries.insert(format!("pictures/{name}"), bytes.clone());    }    for (table, rows) in &package.samples {        entries.insert(            format!("records/{table}.json"),            sample_rows(rows)?,        );    }    decode_entries(&entries)?;    write_entries(&entries)}/// Whether a package's `table` names a built-in whose commands this build/// cannot judge: a compiled engine with no definition shipped (the kit/// retired it to the database's own row). Its commands and `on_open` are/// taken only as exactly the ones the database already holds for that table/// — nothing new — which the import checks, holding the row the package/// would replace (`cotton_tools` `tool_packages::preflight`).pub fn commands_held_by_the_database(table: &TableDefinition) -> bool {    // A table Cotton itself carries keeps its commands as code: never a    // package's, whatever a database holds.    !super::commands::CARRIED_COMMAND_TABLES.contains(&table.id.as_str())        && super::is_builtin_table(&table.id)        && !super::builtin_table_definitions().iter().any(|built| built.id == table.id)        && !crate::toolkits::kit_packages().iter().flat_map(|package| &package.tables).any(|built| built.id == table.id)        && crate::kit::table(&table.id).is_none()}/// The refusal of a package whose retired built-in `table` carries commands/// the database does not hold for it.pub fn commands_not_held(table: &str) -> String {    said("commands_not_held", &[("table", &table)])}pub fn decode_package(bytes: &[u8]) -> Result<ImportedPackage, PackageError> {    decode_entries(&read_entries(bytes)?)}/// [`decode_package`] of a package's files as the archive would hold them,/// by name, with no archive between: the compiled kit's own files, decoded/// once per process (`crate::kit::decoded`) without a zip written and read/// back, which decoded each package twice.pub fn decode_files(files: &BTreeMap<String, Vec<u8>>) -> Result<ImportedPackage, PackageError> {    decode_entries(files)}fn safety(value: &Value) -> Result<(), PackageError> {    // Bindings belong to the authored document, not arbitrary data maps    // inside it (an Email caption legitimately has a column named `code`).    // Typed validation below owns nested structure and data actions.    if let Value::Object(map) = value {        for (property, value) in map {            if matches!(property.as_str(), "connection" | "connections" | "code" | "engine_binding" | "engineBinding")                || (property == "engine" && !value.is_null() && !value.is_string())            {                return Err(error(said("forbidden_key", &[("key", &property)])));            }        }    }    Ok(())}fn json<T: serde::de::DeserializeOwned>(bytes: &[u8]) -> Result<T, PackageError> {    let value: Value = serde_json::from_slice(bytes).map_err(error)?;    safety(&value)?;    serde_json::from_value(value).map_err(error)}/// A package is AUTHORED: every key in it must be one this build names/// (`super::tolerant`), so a typo is refused at import rather than carried.fn authored<T: serde::Serialize + serde::de::DeserializeOwned>(bytes: &[u8], typed: &T, kept: &super::tolerant::Unknown) -> Result<(), PackageError> {    let raw: Value = serde_json::from_slice(bytes).map_err(error)?;    super::tolerant::refuse_unknown(&raw, typed, kept).map_err(error)}fn directory_marker(name: &str) -> bool {    matches!(name, "tables/" | "pictures/" | "records/")}fn allowed_name(name: &str) -> bool {    if directory_marker(name) {        return true;    }    if name.contains('\\')        || name            .split('/')            .any(|s| s.is_empty() || s == "." || s == "..")    {        return false;    }    if matches!(name, "manifest.json" | "instructions.md" | "board.json") {        return true;    }    if let Some(id) = name        .strip_prefix("tables/")        .or_else(|| name.strip_prefix("records/"))        .and_then(|n| n.strip_suffix(".json"))    {        return super::is_valid_id(id);    }    if let Some(file) = name.strip_prefix("pictures/") {        return !file.contains('/')            && file.rsplit_once('.').is_some_and(|(_, extension)| {                matches!(extension, "png" | "jpg" | "jpeg" | "gif" | "webp")            });    }    false}fn decode_entries(entries: &BTreeMap<String, Vec<u8>>) -> Result<ImportedPackage, PackageError> {    for (name, content) in entries {        if directory_marker(name) && !content.is_empty() {            return Err(error(said("nonempty_directory_marker", &[("name", &name)])));        }        if !allowed_name(name) {            return Err(error(said("forbidden_entry", &[("name", &name)])));        }    }    let required = |name: &str| {        entries            .get(name)            .ok_or_else(|| error(said("missing", &[("name", &name)])))    };    let manifest = required("manifest.json")?;    let tool: ToolDefinition = json(manifest)?;    tool.validate().map_err(error)?;    authored(manifest, &tool, &tool.unknown)?;    if required("instructions.md")?.as_slice() != tool.instructions.as_bytes() {        return Err(error(refusal_words("instructions_md_differs_from_manifest_instructions")));    }    let mut ids = BTreeSet::new();    let mut tables = Vec::new();    for id in &tool.tables {        if !ids.insert(id) {            return Err(error(said("duplicate_tables_key", &[("id", &id)])));        }        // A tool may list a built-in table without carrying it: its card is a        // view over that table, which stays the built-in's (a card over a        // built-in table). A file at a built-in id is still read, and the        // install refuses it as built in.        if super::is_builtin_table(id) && !entries.contains_key(&format!("tables/{id}.json")) {            continue;        }        let file = required(&format!("tables/{id}.json"))?;        let table: TableDefinition = json(file)?;        authored(file, &table, &table.unknown)?;        if table.id != *id {            return Err(error(format!(                "table id {} differs from key {id}",                table.id            )));        }        // Engines travel by name only. A package cannot invent a code binding        // or executable command: these must match code this build ships.        if table.builtin || table.engine.is_some() || table.commands.is_some() || table.on_open.is_some() {            // A built-in's schema and engine are code: a package names them,            // never invents them. Where this build carries the table's            // definition — a toolkit's, or the kit's own file (a Film's Keep            // on phone) — its commands are that definition's too.            if !super::is_builtin_table(&table.id) && !crate::toolkits::kit_packages().iter()                .flat_map(|package| &package.tables).any(|built| built.id == table.id)                && crate::kit::table(&table.id).is_none() {                return Err(error(refusal_words("forbidden_builtin_engine_or_commands_on_an")));            }            let compiled = cotton_store::schema::package_tables::compiled_engine(&table.id).map(str::to_owned);            let shipped = super::builtin_table_definitions().iter().find(|built| built.id == table.id).cloned()                .or_else(|| crate::toolkits::kit_packages().iter()                    .flat_map(|package| &package.tables).find(|built| built.id == table.id).cloned())                .or_else(|| crate::kit::table(&table.id));            let engine = shipped.as_ref().map_or(compiled, |shipped| shipped.engine.clone());            if table.engine != engine {                return Err(error(refusal_words("forbidden_builtin_engine_or_commands_must_name")));            }            // A built-in this build ships no definition of (retired to the            // database's own row) has no commands here to hold a package's            // to: the import holds them to that row instead, and takes            // exactly the ones it keeps ([`commands_held_by_the_database`]).            let (commands, on_open) = match shipped {                Some(shipped) => (shipped.commands, shipped.on_open),                None if commands_held_by_the_database(&table) => (table.commands.clone(), table.on_open.clone()),                None => (None, None),            };            if table.commands != commands || table.on_open != on_open {                return Err(error(refusal_words("forbidden_builtin_engine_or_commands_must_name")));            }        }        table.validate_import().map_err(error)?;        tables.push(table);    }    let read = super::tool_views::with_contributions(&tables, &tool).map_err(error)?;    super::tool_views::validate_public_reads(&tool.views, &read).map_err(error)?;    for table in &tables {        table.views_hold(&tables).map_err(error)?;    }    super::automations::validate_tables(&tool, &tables).map_err(error)?;    super::card::validate_openings(&tables).map_err(error)?;    // A rollup may read a table another tool brings (Customers counting the    // Orders tool's orders): what is not here is the install's to check,    // against the database's own tables.    if tables.iter().any(TableDefinition::has_computed) {        let builtins = super::builtin_table_definitions();        let own: Vec<&TableDefinition> = tables.iter().collect();        let beside: Vec<&TableDefinition> = builtins.iter().collect();        super::computed::validate_beside(&own, &beside, super::computed::AbsentTable::Defer)            .map_err(error)?;    }    for name in entries        .keys()        .filter(|n| n.starts_with("tables/") && !directory_marker(n))    {        let id = name.trim_start_matches("tables/").trim_end_matches(".json");        if !ids.contains(&id.to_owned()) {            return Err(error(said("unlisted_table_key", &[("name", &name)])));        }    }    // Sample rows: an array of data objects per listed table, each one a    // create its table accepts (defaults filled, every value of its type).    let mut samples: BTreeMap<String, Vec<Value>> = BTreeMap::new();    for (name, bytes) in entries        .iter()        .filter(|(n, _)| n.starts_with("records/") && !directory_marker(n))    {        let id = name.trim_start_matches("records/").trim_end_matches(".json");        let Some(table) = tables.iter().find(|table| table.id == id) else {            return Err(error(said("sample_rows_name_no_listed_table", &[("name", &name)])));        };        let rows: Vec<Value> = json(bytes)?;        for (at, row) in rows.iter().enumerate() {            crate::records::validate_create(table, row)                .map_err(|why| error(format!("{name}[{at}]: {why}")))?;        }        samples.insert(id.to_owned(), rows);    }    for (name, bytes) in entries        .iter()        .filter(|(n, _)| n.starts_with("pictures/") && !directory_marker(n))    {        let valid = match name.rsplit_once('.').map(|(_, e)| e) {            Some("png") => bytes.starts_with(b"\x89PNG\r\n\x1a\n"),            Some("jpg" | "jpeg") => bytes.starts_with(&[0xff, 0xd8, 0xff]),            Some("gif") => bytes.starts_with(b"GIF87a") || bytes.starts_with(b"GIF89a"),            Some("webp") => bytes.starts_with(b"RIFF") && bytes.get(8..12) == Some(b"WEBP"),            _ => false,        };        if !valid {            return Err(error(said("invalid_raster_picture", &[("name", &name)])));        }    }    if let Some(super::ToolPicture::Photo(photo)) = &tool.picture {        use sha2::{Digest, Sha256};        let hash = photo            .photo            .strip_prefix("photo:")            .filter(|hash| {                hash.len() == 64                    && hash                        .bytes()                        .all(|b| b.is_ascii_digit() || (b'a'..=b'f').contains(&b))            })            .ok_or_else(|| error(refusal_words("picture_photo_must_be_photo_lowercase_sha")))?;        let prefix = format!("pictures/{hash}.");        let mut matches = entries.iter().filter(|(name, _)| name.starts_with(&prefix));        let (_, content) = matches            .next()            .ok_or_else(|| error(refusal_words("picture_photo_has_no_carried_picture")))?;        if matches.next().is_some() {            return Err(error(refusal_words("picture_photo_names_more_than_one_carried")));        }        if hex::encode(Sha256::digest(content)) != hash {            return Err(error(refusal_words("picture_photo_content_hash_mismatch")));        }    }    // A tool's fan tile names kit pictures the same way: each one carried,    // its bytes its name; each act and door one its tables offer.    if let Some(tile) = &tool.fan_tile {        use sha2::{Digest, Sha256};        for photo in tile.photos() {            let hash = photo.sha256().ok_or_else(|| error(refusal_words("a_fan_tile_picture_is_a_kit_photo")))?;            let prefix = format!("pictures/{hash}.");            let mut matches = entries.iter().filter(|(name, _)| name.starts_with(&prefix));            let (_, content) = matches                .next()                .ok_or_else(|| error(said("a_fan_tile_picture_is_carried", &[("photo", &photo.photo)])))?;            if matches.next().is_some() {                return Err(error(refusal_words("picture_photo_names_more_than_one_carried")));            }            if hex::encode(Sha256::digest(content)) != hash {                return Err(error(refusal_words("picture_photo_content_hash_mismatch")));            }        }        let acts: Vec<&str> = tool.acts.iter().map(|act| act.id.as_str())            .chain(tables.iter().flat_map(|table| table.commands.iter().flatten()).map(|command| command.id.as_str()))            .collect();        let doors: Vec<&str> = tables.iter().filter_map(|table| table.create.as_ref())            .flat_map(|create| create.doors.iter()).map(|door| door.id.as_str()).collect();        tile.validate_names(&acts, &doors).map_err(error)?;    }    let board = entries.get("board.json").map(|bytes| {        let value: Value = serde_json::from_slice(bytes).map_err(error)?;        safety(&value)?;        let board = super::board::BoardDefinition::strict(&value).map_err(error)?;        if board.id != tool.id { return Err(error(refusal_words("board_id_differs_from_tool_id"))); }        Ok(board)    }).transpose()?;    let signature = if let Some(signature) = &tool.signature {        let key: [u8; 32] = URL_SAFE_NO_PAD            .decode(&tool.author.device)            .map_err(error)?            .try_into()            .map_err(|_| error(refusal_words("invalid_author_device_key")))?;        let sig: [u8; 64] = URL_SAFE_NO_PAD            .decode(signature)            .map_err(error)?            .try_into()            .map_err(|_| error(refusal_words("invalid_signature")))?;        VerifyingKey::from_bytes(&key)            .map_err(error)?            .verify_strict(&payload(entries)?, &Ed25519Signature::from_bytes(&sig))            .map_err(|_| error(refusal_words("signature_verification_failed")))?;        Signature::SignedBy { key: tool.author.device.clone() }    } else {        Signature::Unsigned    };    let pictures = entries        .iter()        .filter(|(name, _)| !directory_marker(name))        .filter_map(|(name, bytes)| {            name.strip_prefix("pictures/")                .map(|n| (n.to_owned(), bytes.clone()))        })        .collect();    Ok(ImportedPackage {        package: ToolPackage {            board, tool,            tables,            pictures,            samples,        },        signature,    })}fn payload(entries: &BTreeMap<String, Vec<u8>>) -> Result<Vec<u8>, PackageError> {    let mut bytes = DOMAIN.to_vec();    for (name, data) in entries {        if directory_marker(name) {            continue;        }        let data = if name == "manifest.json" {            let mut tool: ToolDefinition = json(data)?;            tool.signature = None;            serde_json::to_vec(&tool).map_err(error)?        } else {            data.clone()        };        bytes.extend_from_slice(&(name.len() as u64).to_be_bytes());        bytes.extend_from_slice(name.as_bytes());        bytes.extend_from_slice(&(data.len() as u64).to_be_bytes());        bytes.extend_from_slice(&data);    }    Ok(bytes)}fn read_entries(bytes: &[u8]) -> Result<BTreeMap<String, Vec<u8>>, PackageError> {    if bytes.len() > MAX_PACKAGE_BYTES {        return Err(error(refusal_words("archive_exceeds_package_size_bound")));    }    let archive = crate::import::zip::list_zip_entries(bytes).map_err(error)?;    if archive.len() > MAX_ENTRIES {        return Err(error(refusal_words("archive_exceeds_entry_count_bound")));    }    let mut entries = BTreeMap::new();    let mut total = 0u64;    let mut seen = BTreeSet::new();    for entry in archive {        let name = entry.name.clone();        if !allowed_name(&name) {            return Err(error(said("forbidden_entry", &[("name", &name)])));        }        if !seen.insert(name.clone()) {            return Err(error(said("duplicate_entry", &[("name", &name)])));        }        total = total            .checked_add(entry.uncompressed_size)            .ok_or_else(|| error(refusal_words("size_overflow")))?;        if total > MAX_PACKAGE_BYTES as u64 {            return Err(error(said("uncompressed_bound_exceeded_at", &[("name", &name)])));        }        let body = crate::import::zip::read_zip_entry(bytes, &entry).map_err(error)?;        if body.len() as u64 != entry.uncompressed_size {            return Err(error(said("size_mismatch", &[("name", &name)])));        }        if directory_marker(&name) {            if !body.is_empty() {                return Err(error(said("nonempty_directory_marker", &[("name", &name)])));            }            continue;        }        entries.insert(name, body);    }    Ok(entries)}// Stored ZIP records are written to bytes only; the existing reader handles deflated imports.fn write_entries(entries: &BTreeMap<String, Vec<u8>>) -> Result<Vec<u8>, PackageError> {    fn u16le(out: &mut Vec<u8>, value: u16) {        out.extend_from_slice(&value.to_le_bytes());    }    fn u32le(out: &mut Vec<u8>, value: u32) {        out.extend_from_slice(&value.to_le_bytes());    }    fn crc32(bytes: &[u8]) -> u32 {        let mut crc = !0u32;        for byte in bytes {            crc ^= *byte as u32;            for _ in 0..8 {                crc = (crc >> 1) ^ (0xedb88320 & 0u32.wrapping_sub(crc & 1));            }        }        !crc    }    let mut out = Vec::new();    let mut central = Vec::new();    if entries.len() > MAX_ENTRIES        || entries            .iter()            .map(|(n, b)| n.len() + b.len() + 100)            .sum::<usize>()            > MAX_PACKAGE_BYTES    {        return Err(error(refusal_words("archive_exceeds_package_size_bound")));    }    for (name, body) in entries {        let offset = out.len() as u32;        let crc = crc32(body);        let size = body.len() as u32;        u32le(&mut out, 0x04034b50);        u16le(&mut out, 20);        u16le(&mut out, 0);        u16le(&mut out, 0);        u16le(&mut out, 0);        u16le(&mut out, 0);        u32le(&mut out, crc);        u32le(&mut out, size);        u32le(&mut out, size);        u16le(&mut out, name.len() as u16);        u16le(&mut out, 0);        out.extend_from_slice(name.as_bytes());        out.extend_from_slice(body);        u32le(&mut central, 0x02014b50);        u16le(&mut central, 20);        u16le(&mut central, 20);        for _ in 0..4 {            u16le(&mut central, 0);        }        u32le(&mut central, crc);        u32le(&mut central, size);        u32le(&mut central, size);        u16le(&mut central, name.len() as u16);        for _ in 0..4 {            u16le(&mut central, 0);        }        u32le(&mut central, 0);        u32le(&mut central, offset);        central.extend_from_slice(name.as_bytes());    }    let offset = out.len() as u32;    let size = central.len() as u32;    out.extend(central);    u32le(&mut out, 0x06054b50);    u16le(&mut out, 0);    u16le(&mut out, 0);    u16le(&mut out, entries.len() as u16);    u16le(&mut out, entries.len() as u16);    u32le(&mut out, size);    u32le(&mut out, offset);    u16le(&mut out, 0);    Ok(out)}#[cfg(test)]#[path = "package_tests.rs"]mod tests;/// The prefix of a sample row's link to an earlier sample row:/// `sample:<table>#<n>`, the `n`th row (from 0) of `records/<table>.json`.pub const SAMPLE_REF: &str = "sample:";/// A value that is a sample ref, `sample:<table>#<n>` whole: its table and/// row; any other text, "sample: a word" among them, is no ref.fn sample_ref(text: &str) -> Option<(&str, usize)> {    let (table, at) = text.strip_prefix(SAMPLE_REF)?.split_once('#')?;    let named = !table.is_empty() && table.bytes().all(|byte| byte.is_ascii_lowercase() || byte.is_ascii_digit() || byte == b'_');    let at = at.bytes().all(|byte| byte.is_ascii_digit()).then(|| at.parse().ok()).flatten()?;    named.then_some((table, at))}/// The order a package's sample tables are made in: a table whose rows link/// another's samples (`sample:<table>#<n>`) after that table, else by name./// Story's scenes link their story (`story_story`, which sorts after them),/// so name order alone cannot carry it (story-core, 17 Nov 2026). A ref/// round, or to a table with no samples, leaves the rest in name order and/// is refused in words when its row is made.pub fn sample_order(samples: &BTreeMap<String, Vec<Value>>) -> Vec<(&String, &Vec<Value>)> {    let needs = |rows: &Vec<Value>| -> std::collections::BTreeSet<String> {        rows.iter()            .filter_map(Value::as_object)            .flat_map(|row| row.values())            .filter_map(|value| value.as_str().and_then(sample_ref).map(|(table, _)| table.to_string()))            .collect()    };    let mut waiting: Vec<(&String, &Vec<Value>, std::collections::BTreeSet<String>)> =        samples.iter().map(|(table, rows)| (table, rows, needs(rows))).collect();    let mut out = Vec::with_capacity(waiting.len());    while !waiting.is_empty() {        let ready = waiting            .iter()            .position(|(table, _, needed)| needed.iter().all(|other| other == *table || !samples.contains_key(other) || out.iter().any(|(made, _): &(&String, &Vec<Value>)| *made == other)))            .unwrap_or(0);        let (table, rows, _) = waiting.remove(ready);        out.push((table, rows));    }    out}/// `row` with every `sample:<table>#<n>` value answered by the id `made`/// holds for that sample, so a sample ticket links its sample trip; a ref to/// a sample not made yet is refused in words. A package's sample tables are/// made in [`sample_order`].pub fn resolve_sample_refs(row: &Value, made: &BTreeMap<String, Vec<String>>) -> Result<Value, String> {    let Some(data) = row.as_object() else { return Ok(row.clone()) };    let mut out = data.clone();    for (key, value) in out.iter_mut() {        let Some((table, at)) = value.as_str().and_then(sample_ref) else { continue };        let id = made.get(table).and_then(|ids| ids.get(at)).ok_or_else(|| {            super::refusal_said("sample_ref_not_made", &[("key", key.clone()), ("table", table.to_string()), ("at", at.to_string())])        })?;        *value = Value::from(id.clone());    }    Ok(Value::Object(out))}