/** * FILES SEALED AT ARRIVAL (e2e rulings R6 with R2, 15 Nov * 2026): a file the object fetches for a person itself (a book's cover, a * film's poster, an album's or a show's artwork: src/artwork.ts `kept`) is * sealed the moment it arrives, to the person's arrival public key (the * `seal_key` row `arrival`, src/arrival.ts). A fresh file key seals the bytes * as a device seals a file (f1); that key is kept only wrapped to the arrival * key, in the file's own head. The object never holds a key that opens what * it stored, and never keeps such a file in the clear: with no arrival key * held, the file is not kept (the artwork engine tries again later). * * "CTA1" || be16(n) || wrap || f1 file * wrap n ASCII bytes: the w1 wrap of (FK || "f1" "\n" object key) to the arrival key, its "w1:" dropped * f1 file "CTF1" || prefix(7) || parts of 64 KiB, AES-256-GCM under FK, * nonce prefix || be32(index) || last, aad "f1|" object key * * The core's twin is crates/cotton-core/src/seal/arrival_file.rs; both answer * crates/cotton-conformance/vectors/seal/arrival_file.json byte for byte. */ import { ARRIVAL_ROW, keyFromText, wrapWith } from "./arrival.ts"; import { SealError } from "./seal.ts"; export const ARRIVAL_FILE_MAGIC = "CTA1"; const F1_MAGIC = "CTF1"; const PART = 64 * 1024; const WRAP_TABLE = "f1"; const utf8 = new TextEncoder(); /** The kinds of a person's files a device seals (crates/cotton-client media::sealed SEALED_KINDS): what arrives under them is sealed too. */ export const SEALED_KINDS = ["photos", "videos", "books", "music", "films", "meetings", "mail", "people"]; /** Whether `key` (`//…`) is a person's file of a kind that is sealed. */ export function sealsAtArrival(databaseId: string, key: string): boolean { const [db, kind, ...rest] = key.split("/"); return db === databaseId && SEALED_KINDS.includes(kind ?? "") && rest.join("/").length > 0; } /** The randomness one file's seal takes. */ export interface ArrivalFileRandom { fileKey: Uint8Array; prefix: Uint8Array; ephemeral: Uint8Array; wrapNonce: Uint8Array; } function fresh(): ArrivalFileRandom { const r = (n: number) => crypto.getRandomValues(new Uint8Array(n)); return { fileKey: r(32), prefix: r(7), ephemeral: r(32), wrapNonce: r(12) }; } function nonce(prefix: Uint8Array, index: number, last: boolean): Uint8Array { const n = new Uint8Array(12); n.set(prefix, 0); new DataView(n.buffer).setUint32(7, index, false); n[11] = last ? 1 : 0; return n; } /** `plain` as a device's f1 file for `objectKey` under `fileKey`. */ export async function sealF1(fileKey: Uint8Array, prefix: Uint8Array, objectKey: string, plain: Uint8Array): Promise { const key = await crypto.subtle.importKey("raw", fileKey, "AES-GCM", false, ["encrypt"]); const aad = utf8.encode(`f1|${objectKey}`); const parts: Uint8Array[] = [utf8.encode(F1_MAGIC), prefix]; const count = Math.max(1, Math.ceil(plain.length / PART)); for (let i = 0; i < count; i++) { const msg = plain.subarray(i * PART, Math.min(plain.length, (i + 1) * PART)); parts.push(new Uint8Array(await crypto.subtle.encrypt({ name: "AES-GCM", iv: nonce(prefix, i, i === count - 1), additionalData: aad }, key, msg))); } return parts; } /** `plain` sealed at arrival for `objectKey` to `arrivalPub`: what the object stores. */ export async function sealFileAtArrival(arrivalPub: Uint8Array, objectKey: string, plain: Uint8Array, random: ArrivalFileRandom = fresh()): Promise { if (random.fileKey.length !== 32 || random.prefix.length !== 7) throw new SealError("seal_bad_input", "a file key is 32 bytes and its prefix 7"); const bound = new Uint8Array(32 + utf8.encode(`${WRAP_TABLE}\n${objectKey}`).length); bound.set(random.fileKey, 0); bound.set(utf8.encode(`${WRAP_TABLE}\n${objectKey}`), 32); const wrap = utf8.encode(await wrapWith(random.ephemeral, random.wrapNonce, arrivalPub, bound)); if (wrap.length > 0xffff) throw new SealError("seal_bad_input", "an object key too long for an arrival head"); const lead = new Uint8Array(6); lead.set(utf8.encode(ARRIVAL_FILE_MAGIC), 0); new DataView(lead.buffer).setUint16(4, wrap.length, false); const pieces = [lead, wrap, ...(await sealF1(random.fileKey, random.prefix, objectKey, plain))]; const out = new Uint8Array(pieces.reduce((n, p) => n + p.length, 0)); let at = 0; for (const p of pieces) { out.set(p, at); at += p.length; } return out; } /** The arrival public key a store holds (`seal_key` row `arrival`), or null while no device has handed it over. */ export function arrivalPublic(get: (table: string, id: string) => { data: Record } | null | undefined): Uint8Array | null { return keyFromText(get("seal_key", ARRIVAL_ROW)?.data.pub); } /** No arrival key is held yet, so a file of a sealed kind is not kept: said by name, tried again later. */ export class NoArrivalKey extends Error { readonly code = "arrival_key_missing"; constructor(key: string) { super(`no device has handed this database its arrival key yet, so ${key.split("/").slice(1).join("/")} is not kept (it is never kept in the clear)`); } } /** * What the object stores for a file it fetched for `databaseId` under `key`: * a file of a sealed kind sealed at arrival (its type the sealed type), any * other as it came. Throws NoArrivalKey for a sealed kind with no key held. */ export async function asArrived(databaseId: string, arrivalPub: Uint8Array | null, key: string, bytes: Uint8Array, contentType: string, sealedType: string): Promise<{ bytes: Uint8Array; contentType: string }> { if (!sealsAtArrival(databaseId, key)) return { bytes, contentType }; if (!arrivalPub) throw new NoArrivalKey(key); return { bytes: await sealFileAtArrival(arrivalPub, key, bytes), contentType: sealedType }; }