Cotton code
678 lines · 35.1 KB · TypeScriptRaw
/** * Sealed tables on the object (the build plan "Sealed tables with a time-boxed * unlock", §2.2 and §4). * * A table whose definition carries a `seal` block keeps only the columns its * `clear` names in `rows.data`; every other column (fail closed: a column * added later is sealed unless someone names it) travels inside one blob a * device sealed: * *     sealed_enc  "s1:" b64url(nonce12 || AES-256-GCM(DEK, padded canonical JSON, aad)) *     dek_enc     "d1:" b64url(nonce12 || AES-256-GCM(TK(table, v), DEK, aad')) *     seal_v      the table key version v the DEK is wrapped under * * The object never holds a key that opens them. What it decides is only the * shape: a sealed row carries all three and no sealed column in the clear; a * device never writes a sealed column in the clear at all; the Worker's own * writes (an MCP create) may land as open rows that a device's sweep seals. * Blind tokens (signed 64-bit integers, said as decimal text) come beside a * sealed write as `args.blind` and land in the `blind` tables, never in data. * * The block's rules mirror the Rust definition's (crates/cotton-core/src/ * definitions/seal.rs): every name a declared column, the sealer's own three * columns never declared, a blind column a sealed one. The object adds what * its SQL needs: the date, sort, order and archive columns stay clear, and a * sealed table's row_key names a clear column (an id taken from a sealed one would leak it). */import RULE from "../../../crates/cotton-core/src/seal/default.json";import STOPWORDS from "../../../crates/cotton-core/src/seal/stopwords.json";import { refuse } from "./http.ts";type Data = Record<string, unknown>;export const SEALED_ENC = "sealed_enc";export const DEK_ENC = "dek_enc";export const SEAL_V = "seal_v";/** The sealer's own columns: no definition declares them, and only a sealed row holds them. */export const SEAL_FIELDS = [SEALED_ENC, DEK_ENC, SEAL_V] as const;/** The mark a row the person keeps open for good carries (Q3): no column, never sealed. */export const KEEP_OPEN = "keep_open";export const BODY_PREFIX = "s1:";export const DEK_PREFIX = "d1:";/** A table's `seal` block, read. */export interface SealSpec {  clear: string[];  blind: string[];  blind_exact: string[];}/** The table shape the seal rules read: the definition's id, columns and raw JSON. */export interface SealedTable {  id: string;  columns: { key: string; computed?: unknown }[];  raw: Data;  seal?: SealSpec | null;}const SPEC_KEYS = new Set(["clear", "blind", "blind_exact"]);/** The block's one map: the most bytes of a `blind` column a device indexes, from its start (sealing plan Q12). The object only checks its shape; the tokens are the device's. */const BLIND_BYTES = "blind_bytes";/** The `seal` block of a definition, or null when it has none; never a guess at a block that does not read (tableProblem refuses it first). */export function parseSeal(raw: Data): SealSpec | null {  const s = raw.seal;  if (!s || typeof s !== "object" || Array.isArray(s)) return null;  const list = (v: unknown): string[] => (Array.isArray(v) ? v.filter((k): k is string => typeof k === "string") : []);  const block = s as Data;  return { clear: list(block.clear), blind: list(block.blind), blind_exact: list(block.blind_exact) };}// ── the rule (e2e rulings R1): every personal table is sealed unless named ──/** Why a personal table stays open by design (R1), by id. */export const OPEN_TABLES: Readonly<Record<string, string>> = RULE.open;/** Why a personal table is still open until the object's own work on its values moves (R2/R3), by id. */export const PENDING_TABLES: Readonly<Record<string, string>> = RULE.pending;const MARKS = new Set<string>(RULE.marks);/** The column types a sort is sealed in (R3): the device sorts its own copy by them. */const SORTED_ON_DEVICE = new Set<string>(RULE.sorted_on_device.types);/** * The seal a personal table with no `seal` block of its own takes (the core's * `cotton_core::seal::rule::default_seal`, the same vectors): its clear * columns are only what the object's SQL needs: the columns the definition * names as its date, order, archive, project, row key, sort and group, its * links, the archive and trash marks, and the columns its computed columns * read; everything else is sealed. Null for a table the rule leaves open (R1, * or still pending), for the object's own `internal` tables, and for one that * has a block (it says itself). */export function defaultSeal(raw: Data): SealSpec | null {  const id = raw.id;  if (typeof id !== "string" || raw.seal !== undefined || raw.internal === true) return null;  if (Object.hasOwn(OPEN_TABLES, id) || Object.hasOwn(PENDING_TABLES, id)) return null;  const columns = Array.isArray(raw.columns) ? (raw.columns as Data[]).filter((c) => c && typeof c.key === "string") : [];  const named = new Set<string>();  const sort = raw.sort as { column?: unknown; tie?: unknown } | null | undefined;  const group = raw.group as { column?: unknown } | null | undefined;  for (const key of [raw.date, raw.order, raw.archived, raw.project, raw.row_key, group?.column]) if (typeof key === "string") named.add(key);  // A sort of words is the device's (R3): only a sort the object can order without reading a word stays clear.  for (const key of [sort?.column, sort?.tie]) {    if (typeof key !== "string") continue;    const kind = columns.find((c) => c.key === key)?.type;    if (!(typeof kind === "string" && SORTED_ON_DEVICE.has(kind))) named.add(key);  }  for (const c of columns) {    const spec = c.computed as Data | null | undefined;    if (!spec || typeof spec !== "object") continue;    const formula = spec.formula as { of?: unknown; flip_when?: { column?: unknown } } | undefined;    if (formula && Array.isArray(formula.of)) for (const k of formula.of) if (typeof k === "string") named.add(k);    if (typeof formula?.flip_when?.column === "string") named.add(formula.flip_when.column);    const lookup = spec.lookup as { through?: unknown } | undefined;    if (typeof lookup?.through === "string") named.add(lookup.through);  }  const clear = columns.filter((c) => !c.computed && c.key !== "id" && (named.has(c.key as string) || c.type === "link" || MARKS.has(c.key as string))).map((c) => c.key as string);  return { clear, blind: [], blind_exact: [] };}/** * A personal database's table definition as the rule makes it: its own * `seal` block, or the default's written out (so what the object serves a * device names it), or itself when the rule leaves it open. Idempotent. */export function ruled(raw: Data): Data {  const seal = defaultSeal(raw);  return seal ? { ...raw, seal: { clear: seal.clear } } : raw;}/** Is `column` sealed under this block? Every column but `id` and the clear ones. */export function seals(spec: SealSpec, column: string): boolean {  return column !== "id" && !spec.clear.includes(column);}/** Why a definition's `seal` block does not read, or null (no block, or one that reads). */export function sealProblem(raw: Data): string | null {  if (raw.seal === undefined || raw.seal === null) return null;  const s = raw.seal;  if (typeof s !== "object" || Array.isArray(s)) return "seal is an object of clear, blind and blind_exact column lists (and blind_bytes)";  const stray = Object.keys(s as Data).find((k) => !SPEC_KEYS.has(k) && k !== BLIND_BYTES);  if (stray !== undefined) return `seal has no ${JSON.stringify(stray)}: it says clear, blind, blind_exact and blind_bytes`;  for (const slot of SPEC_KEYS) {    const v = (s as Data)[slot];    if (v !== undefined && (!Array.isArray(v) || v.some((k) => typeof k !== "string"))) return `seal.${slot} is a list of column keys`;  }  const spec = parseSeal(raw)!;  const columns = Array.isArray(raw.columns) ? (raw.columns as Data[]).filter((c) => c && typeof c.key === "string") : [];  const declared = new Map(columns.map((c) => [c.key as string, c]));  for (const slot of ["clear", "blind", "blind_exact"] as const) {    const missing = spec[slot].find((k) => !declared.has(k));    if (missing !== undefined) return `seal.${slot} names ${JSON.stringify(missing)}, which is no column`;  }  const reserved = columns.find((c) => (SEAL_FIELDS as readonly string[]).includes(c.key as string));  if (reserved) return `a sealed table declares no ${JSON.stringify(reserved.key)}: the sealer writes it`;  for (const slot of ["blind", "blind_exact"] as const) {    const clear = spec[slot].find((k) => !seals(spec, k));    if (clear !== undefined) return `seal.${slot} names ${JSON.stringify(clear)}, which is clear: a clear column needs no token`;  }  const caps = (s as Data)[BLIND_BYTES];  if (caps !== undefined) {    if (!caps || typeof caps !== "object" || Array.isArray(caps)) return "seal.blind_bytes is an object of a blind column's key to a number of bytes";    for (const [k, n] of Object.entries(caps as Data)) {      if (!spec.blind.includes(k) || !Number.isInteger(n) || (n as number) <= 0) return `seal.blind_bytes names ${JSON.stringify(k)}: it caps a seal.blind column by a number of bytes above 0`;    }  }  if (typeof raw.row_key === "string" && seals(spec, raw.row_key)) return `row_key names ${JSON.stringify(raw.row_key)}, which is sealed: a sealed table's id is a clear column's value or random`;  // What the object's SQL reads must be clear: sync windows and ordering by the date, lists by order, the archive.  // A sort may be sealed (R3): each device sorts its own copy, and the object lists the table without it (orderSql).  const sqlRead: [string, unknown][] = [    ["date", raw.date],    ["order", raw.order],    ["archived", raw.archived],    ["project", raw.project],    ["group.column", (raw.group as { column?: unknown } | null | undefined)?.column],  ];  for (const [slot, key] of sqlRead) {    if (typeof key === "string" && declared.has(key) && seals(spec, key)) return `${slot} names ${JSON.stringify(key)}, which is sealed: the object orders and windows by it, so it stays clear`;  }  // A computed column of this table reads its own record: never a sealed column the object cannot see.  for (const c of columns) {    const spec_ = c.computed as Data | undefined | null;    if (!spec_ || typeof spec_ !== "object") continue;    const reads: string[] = [];    const formula = spec_.formula as { of?: unknown; flip_when?: { column?: unknown } } | undefined;    if (formula && Array.isArray(formula.of)) reads.push(...formula.of.filter((k): k is string => typeof k === "string"));    if (formula && typeof formula.flip_when?.column === "string") reads.push(formula.flip_when.column);    const lookup = spec_.lookup as { through?: unknown } | undefined;    if (lookup && typeof lookup.through === "string") reads.push(lookup.through);    const sealedRead = reads.find((k) => declared.has(k) && seals(spec, k) && !declared.get(k)!.computed);    if (sealedRead !== undefined) return `the computed column ${JSON.stringify(c.key)} reads ${JSON.stringify(sealedRead)}, which is sealed: the object cannot compute over it`;  }  return null;}/** * Why a tool's automations read or write a sealed column, or null: the * object runs them on every write, and a sealed row holds no such column to * watch or set. `table` finds a table's definition by id. */export function toolSealProblem(tool: Data, table: (id: string) => SealedTable | undefined): string | null {  // A view's filter is what the object's list reads. Its sort may be sealed (R3): each device sorts its own copy.  const views = Array.isArray(tool.views) ? (tool.views as Data[]) : [];  for (const v of views) {    const read = v?.read as { table?: unknown; where?: unknown } | undefined;    if (typeof read?.table !== "string") continue;    const t = table(read.table);    if (!t?.seal) continue;    const where = read.where && typeof read.where === "object" && !Array.isArray(read.where) ? Object.keys(read.where as Data) : [];    const filtered = where.find((key) => isSealedColumn(t, key));    if (filtered !== undefined) return `the view ${JSON.stringify(v.id)} filters ${t.id} by ${filtered}, which is sealed: the object cannot read it`;  }  const automations = Array.isArray(tool.automations) ? (tool.automations as Data[]) : [];  for (const a of automations) {    const when = a?.when as { table?: unknown; column?: unknown } | undefined;    if (typeof when?.table !== "string") continue;    const t = table(when.table);    if (!t?.seal) continue;    if (typeof when.column === "string" && isSealedColumn(t, when.column)) return `the automation ${JSON.stringify(a.id)} watches ${t.id}.${when.column}, which is sealed: the object cannot read it`;    const then = Array.isArray(a.then) ? (a.then as Data[]) : [];    for (const action of then) {      const set = action?.set as { column?: unknown } | undefined;      if (typeof set?.column === "string" && isSealedColumn(t, set.column)) return `the automation ${JSON.stringify(a.id)} sets ${t.id}.${set.column}, which is sealed: the object cannot write it`;    }  }  return null;}/** * Why the tables `held` with `given` laid over them by id would have the * object read a sealed column it cannot see, or null: a held tool's view or * automation over one ([`toolSealProblem`]). Run before a table definition * is written. Another table's lookup or rollup over a sealed column is no * refusal (e2e rulings R3, 15 Nov 2026): the device works it out on its copy * (cotton-tools derive), and the object answers it unknown (src/engine.ts). */export function sealedSetProblem(held: Data[], given: Data[], tools: Data[]): string | null {  const ids = new Set(given.map((t) => t.id));  const tables = [...held.filter((t) => !ids.has(t.id)), ...given];  const byId = new Map<string, SealedTable>();  for (const raw of tables) {    if (typeof raw?.id !== "string") continue;    const columns = Array.isArray(raw.columns) ? (raw.columns as { key: string; computed?: unknown }[]).filter((c) => c && typeof c.key === "string") : [];    byId.set(raw.id, { id: raw.id, columns, raw, seal: parseSeal(raw) });  }  for (const tool of tools) {    const problem = toolSealProblem(tool, (id) => byId.get(id));    if (problem) return problem;  }  return null;}/** The columns of a sealed table the object never holds in the clear on a sealed row (none for an open table). */export function sealedColumns(t: SealedTable): string[] {  if (!t.seal) return [];  return t.columns.filter((c) => !c.computed && seals(t.seal!, c.key)).map((c) => c.key);}/** Is `column` of `t` sealed (an open table seals nothing)? */export function isSealedColumn(t: SealedTable, column: string): boolean {  return !!t.seal && seals(t.seal, column) && !(SEAL_FIELDS as readonly string[]).includes(column);}/** Does this row's data hold a seal (a blob a device made)? */export function isSealedRow(data: Data): boolean {  return typeof data[SEALED_ENC] === "string";}/** The sealed columns a write says in the clear (a value, even null, under a sealed key). */export function clearSealed(t: SealedTable, data: Data): string[] {  return sealedColumns(t).filter((k) => k in data);}const B64URL = /^[A-Za-z0-9_-]+$/;/** nonce (12) + tag (16) at least; a body is padded to 64 bytes at least. */const MIN_BODY_BYTES = 12 + 16 + 64;const DEK_BYTES = 12 + 32 + 16;/** An arrival row's dek_enc prefix (src/arrival.ts). */const ARRIVAL_DEK_PREFIX = "a1:";/** The ephemeral key, the nonce, the DEK, "t\ni" at least, and the tag. */const ARRIVAL_MIN_BYTES = 32 + 12 + 32 + 3 + 16;/** The byte length a base64url text (no padding) decodes to, or null when it is not one. */function b64urlBytes(text: string): number | null {  if (!B64URL.test(text) || text.length % 4 === 1) return null;  return Math.floor((text.length * 3) / 4);}/** * Check the seal fields a write carries: all three or none, each in its * format. A sealed row's blob is opaque here, but a blob that cannot be one * (the wrong prefix, not base64url, the wrong length) is refused by name, * never stored to fail on a phone later. */export function checkSealFields(t: SealedTable, data: Data): boolean {  const said = SEAL_FIELDS.filter((k) => k in data);  if (!said.length) return false;  if (!t.seal) refuse(400, "not_sealed", `${t.id} is not a sealed table: it takes no ${said.join(", ")}`);  if (said.length !== SEAL_FIELDS.length) {    const missing = SEAL_FIELDS.filter((k) => !(k in data));    refuse(400, "seal_column_missing", `a sealed ${t.id} row carries sealed_enc, dek_enc and seal_v together; this one lacks ${missing.join(", ")}`);  }  const body = data[SEALED_ENC];  const dek = data[DEK_ENC];  const v = data[SEAL_V];  const bodyBytes = typeof body === "string" && body.startsWith(BODY_PREFIX) ? b64urlBytes(body.slice(BODY_PREFIX.length)) : null;  if (bodyBytes === null || bodyBytes < MIN_BODY_BYTES) refuse(400, "bad_seal", `${t.id}.sealed_enc is "s1:" and a base64url blob`);  // Sealed at arrival (src/arrival.ts, e2e rulings R2): the DEK wrapped to the person's arrival key, bound to its table and row, at seal_v 0.  if (typeof dek === "string" && dek.startsWith(ARRIVAL_DEK_PREFIX)) {    const wrapBytes = b64urlBytes(dek.slice(ARRIVAL_DEK_PREFIX.length));    if (wrapBytes === null || wrapBytes < ARRIVAL_MIN_BYTES) refuse(400, "bad_seal", `${t.id}.dek_enc is "a1:" and a base64url wrap to the arrival key`);    if (v !== 0) refuse(400, "bad_seal", `${t.id}.seal_v is 0 on a row sealed at arrival: no table key wraps it yet`);    return true;  }  const dekBytes = typeof dek === "string" && dek.startsWith(DEK_PREFIX) ? b64urlBytes(dek.slice(DEK_PREFIX.length)) : null;  if (dekBytes !== DEK_BYTES) refuse(400, "bad_seal", `${t.id}.dek_enc is "d1:" and a base64url wrapped key of ${DEK_BYTES} bytes`);  if (typeof v !== "number" || !Number.isInteger(v) || v < 1 || v > 0xffff_ffff) refuse(400, "bad_seal", `${t.id}.seal_v is the table key's version, a whole number from 1`);  return true;}// ── blind tokens (§4) ──────────────────────────────────────────────────────const I64_MIN = -(2n ** 63n);const I64_MAX = 2n ** 63n - 1n;/** At most this many tokens per row: a 2 KB email excerpt makes a few hundred, a long note (each word and its prefixes) tens of thousands. */export const BLIND_PER_ROW = 64_000;/** At most this many tokens per query. */export const BLIND_PER_QUERY = 32;/** One token as the wire says it (decimal text of a signed 64-bit integer), checked and put in its one spelling; null when it is not one. */export function blindToken(said: unknown): string | null {  if (typeof said !== "string" || !/^-?(0|[1-9]\d{0,18})$/.test(said)) return null;  const n = BigInt(said);  if (n < I64_MIN || n > I64_MAX || said === "-0") return null;  return n.toString();}/** `args.blind` of a sealed write: a list of tokens, de-duplicated; refused by name when any does not read. *//** * LIVE CPU 4 (24 Nov 2026): the blind tokens one call may land, across its rows. The Mac's texts catch-up sent 500 * sealed messages a call, each with its tokens, tens of thousands of index entries in one transaction on a 3.7 GB * object, and the object was reset for its CPU and the call retried. Over this a call is refused (413 too_large) and * the client splits it; a call of one row alone may carry its row's whole BLIND_PER_ROW (a long mail is one row). */export const BLIND_PER_CALL = 2_000;/** Refuses a call whose rows' `blind` lists hold more than BLIND_PER_CALL tokens together, unless it is one row. */export function blindBudget(rows: unknown[]): void {  if (rows.length <= 1) return;  let n = 0;  for (const r of rows) {    const b = r && typeof r === "object" ? (r as { blind?: unknown }).blind : undefined;    if (Array.isArray(b)) n += b.length;  }  if (n > BLIND_PER_CALL) refuse(413, "too_large", `a call carries at most ${BLIND_PER_CALL} blind tokens across its rows (this one ${n} over ${rows.length} rows): send fewer rows a call`);}export function blindArg(said: unknown, table: string): string[] {  if (!Array.isArray(said)) refuse(400, "bad_blind", `blind is a list of tokens, each the decimal text of a signed 64-bit number`);  if (said.length > BLIND_PER_ROW) refuse(413, "too_many", `a ${table} row carries at most ${BLIND_PER_ROW} blind tokens`);  const out = new Set<string>();  for (const t of said) {    const tok = blindToken(t);    if (tok === null) refuse(400, "bad_blind", `blind is a list of tokens, each the decimal text of a signed 64-bit number; ${JSON.stringify(t)} is not one`);    out.add(tok);  }  return [...out];}// ── what the logs keep (§2.2: the journal and acts.args never hold sealed plaintext) ──/** The mark a scrubbed value is logged as: the column was said, its value is not kept. */export const SCRUBBED = "‹sealed›";/** Data as a log keeps it for a sealed table: each sealed column said in the clear is kept only as a mark. */export function scrubData(t: SealedTable, data: Data): Data {  if (!t.seal) return data;  const out: Data = {};  for (const [k, v] of Object.entries(data)) out[k] = isSealedColumn(t, k) && !t.columns.find((c) => c.key === k)?.computed ? SCRUBBED : v;  return out;}// ── the TypeScript twin (query tokens and row open only) ───────────────────//// The Rust core (crates/cotton-core/src/seal/) seals; the object only opens a// row with a table key a window hands it and makes a query's tokens with a// blind key. Both are checked against the same vectors// (crates/cotton-conformance/vectors/seal/*.json, test/seal-vectors.test.ts).// No fallback to clear: a missing key or a blob that does not open is a// SealError by name, never an empty row./** Why a row did not open or a key was not there, by the Rust core's names (`SealError::code`). */export type SealCode = "seal_key_missing" | "seal_does_not_open" | "seal_column_missing" | "seal_column_clash" | "seal_bad_input";export class SealError extends Error {  readonly code: SealCode;  constructor(code: SealCode, detail?: string) {    super(detail ? `${code}: ${detail}` : code);    this.code = code;  }}export const TABLE_INFO = "cotton-table-v1:";export const BLIND_INFO = "cotton-blind-v1:";const utf8 = new TextEncoder();function unb64url(text: string): Uint8Array | null {  if (!B64URL.test(text) || text.length % 4 === 1) return null;  const b64 = text.replace(/-/g, "+").replace(/_/g, "/") + "=".repeat((4 - (text.length % 4)) % 4);  try {    return Uint8Array.from(atob(b64), (c) => c.charCodeAt(0));  } catch {    return null;  }}/** An aad field holds no separator and is never empty (Rust `plain_field`). */function plainField(what: string, value: string): string {  if (!value || /[\n|,]/.test(value)) throw new SealError("seal_bad_input", `${what} ${JSON.stringify(value)} is empty or holds a separator`);  return value;}export function bodyAad(databaseId: string, table: string, id: string): string {  return `s1|${plainField("database", databaseId)}|${plainField("table", table)}|${plainField("id", id)}`;}export function dekAad(databaseId: string, table: string, id: string, v: number): string {  return `d1|${bodyAad(databaseId, table, id).slice(3)}|${v}`;}/** The padded length for `len` bytes of plaintext: 64, 256, 1024, 4096, then multiples of 4096. */export function bucket(len: number): number {  return [64, 256, 1024, 4096].find((b) => len <= b) ?? Math.ceil(len / 4096) * 4096;}async function hkdf(ikm: Uint8Array, databaseId: string, info: string): Promise<Uint8Array> {  if (ikm.length !== 32) throw new SealError("seal_key_missing", "a data key is 32 bytes");  const key = await crypto.subtle.importKey("raw", ikm, "HKDF", false, ["deriveBits"]);  return new Uint8Array(await crypto.subtle.deriveBits({ name: "HKDF", hash: "SHA-256", salt: utf8.encode(databaseId), info: utf8.encode(info) }, key, 256));}/** TK(t, v) from the DK: the phone's derivation, here for the vectors (the object is handed TKs, never the DK). */export async function tableKey(dk: Uint8Array, databaseId: string, table: string, v: number): Promise<Uint8Array> {  if (!Number.isInteger(v) || v < 1) throw new SealError("seal_bad_input", "a table key version is a whole number from 1");  return hkdf(dk, databaseId, `${TABLE_INFO}${plainField("table", table)}:${v}`);}/** BK(t) from the DK, likewise. */export async function blindKey(dk: Uint8Array, databaseId: string, table: string): Promise<Uint8Array> {  return hkdf(dk, databaseId, `${BLIND_INFO}${plainField("table", table)}`);}async function gcmOpen(key: Uint8Array, blob: Uint8Array, aad: string): Promise<Uint8Array> {  if (key.length !== 32 || blob.length < 12 + 16) throw new SealError("seal_does_not_open");  try {    const k = await crypto.subtle.importKey("raw", key, "AES-GCM", false, ["decrypt"]);    return new Uint8Array(await crypto.subtle.decrypt({ name: "AES-GCM", iv: blob.slice(0, 12), additionalData: utf8.encode(aad) }, k, blob.slice(12)));  } catch {    throw new SealError("seal_does_not_open");  }}/** A sealed row's table key version, required (Rust `version_of`). */export function versionOf(data: Data): number {  const v = data[SEAL_V];  if (typeof v !== "number" || !Number.isInteger(v) || v < 1 || v > 0xffff_ffff) throw new SealError("seal_column_missing", `the row has no ${SEAL_V}`);  return v;}/** * Open a stored sealed row with the table key of its own version (a * window's): its clear columns and its sealed ones as one row, without the * blobs. An open row, a missing column, a wrong key, row, table, version or * database are each refused by name. */export async function openRow(tk: Uint8Array | null | undefined, databaseId: string, table: string, id: string, data: Data): Promise<Data> {  const v = versionOf(data);  if (!tk) throw new SealError("seal_key_missing", `no key for ${table} v${v}`);  const dekEnc = data[DEK_ENC];  if (typeof dekEnc !== "string") throw new SealError("seal_column_missing", `the row has no ${DEK_ENC}`);  const sealedEnc = data[SEALED_ENC];  if (typeof sealedEnc !== "string") throw new SealError("seal_column_missing", `the row has no ${SEALED_ENC}`);  const wrapped = dekEnc.startsWith(DEK_PREFIX) ? unb64url(dekEnc.slice(DEK_PREFIX.length)) : null;  if (!wrapped) throw new SealError("seal_does_not_open");  const dek = await gcmOpen(tk, wrapped, dekAad(databaseId, table, id, v));  if (dek.length !== 32) throw new SealError("seal_does_not_open");  const body = sealedEnc.startsWith(BODY_PREFIX) ? unb64url(sealedEnc.slice(BODY_PREFIX.length)) : null;  if (!body) throw new SealError("seal_does_not_open");  const plain = await gcmOpen(dek, body, bodyAad(databaseId, table, id));  let sealed: unknown;  try {    sealed = JSON.parse(new TextDecoder("utf-8", { fatal: true, ignoreBOM: false }).decode(plain));  } catch {    throw new SealError("seal_does_not_open");  }  if (!sealed || typeof sealed !== "object" || Array.isArray(sealed)) throw new SealError("seal_does_not_open");  const out: Data = {};  for (const [k, value] of Object.entries(data)) if (!(SEAL_FIELDS as readonly string[]).includes(k)) out[k] = value;  for (const [k, value] of Object.entries(sealed as Data)) {    if (k in out) throw new SealError("seal_column_clash", `${k} is both clear and sealed`);    out[k] = value;  }  return out;}// Blind tokens (Rust blind.rs): normalise, cut words, HMAC each.export const MIN_WORD = 2;export const MIN_PREFIX = 3;export const MAX_PREFIX = 6;/** The combining marks Rust drops (blind.rs `is_diacritic`), by code point. */function isDiacritic(c: string): boolean {  const n = c.codePointAt(0)!;  return (n >= 0x0300 && n <= 0x036f) || (n >= 0x1ab0 && n <= 0x1aff) || (n >= 0x1dc0 && n <= 0x1dff) || (n >= 0x20d0 && n <= 0x20ff) || (n >= 0xfe20 && n <= 0xfe2f);}const NOT_WORD = /[^\p{Alphabetic}\p{N}\p{M}]+/u;/** The text a word is cut from: NFKC, lower case, diacritics dropped from its NFD, then NFC. */export function normalise(text: string): string {  return [...text.normalize("NFKC").toLowerCase().normalize("NFD")].filter((c) => !isDiacritic(c)).join("").normalize("NFC");}const STOP = new Set(Object.values(STOPWORDS as Record<string, string[]>).flat().map(normalise));const scalars = (w: string): number => [...w].length;const prefixOf = (w: string, n: number): string => [...w].slice(0, n).join("");/** The words a text is indexed by, in order, repeats kept. */export function words(text: string): string[] {  return normalise(text)    .split(NOT_WORD)    .filter((w) => w !== "" && scalars(w) >= MIN_WORD && !STOP.has(w));}/** One token: the first 8 bytes of HMAC-SHA256(BK, kind "|" column "|" value) as a signed big-endian 64-bit number, in decimal. */async function token(bk: Uint8Array, kind: "w" | "p" | "x", column: string, value: string): Promise<string> {  if (bk.length !== 32) throw new SealError("seal_key_missing", "no blind key");  const key = await crypto.subtle.importKey("raw", bk, { name: "HMAC", hash: "SHA-256" }, false, ["sign"]);  const mac = new DataView(await crypto.subtle.sign("HMAC", key, utf8.encode(`${kind}|${column}|${value}`)));  return mac.getBigInt64(0, false).toString();}/** The exact token of a blind_exact column's value (NFKC, trimmed), or null for an empty one. */export async function exactToken(bk: Uint8Array, column: string, value: string): Promise<string | null> {  const v = value.normalize("NFKC").trim();  return v ? token(bk, "x", column, v) : null;}/** The tokens one text of a blind column adds to its row, de-duplicated (for a window's plaintext check). */export async function textTokens(bk: Uint8Array, column: string, text: string): Promise<Set<string>> {  const out = new Set<string>();  for (const w of words(text)) {    out.add(await token(bk, "w", column, w));    for (let n = MIN_PREFIX; n <= Math.min(scalars(w), MAX_PREFIX); n++) out.add(await token(bk, "p", column, prefixOf(w, n)));  }  return out;}/** The tokens a query over one column intersects: each word's word token, the last word's prefix token when it is 3 or longer; empty when nothing is left. */export async function queryTokens(bk: Uint8Array, column: string, query: string): Promise<string[]> {  const ws = words(query);  const out: string[] = [];  for (const [i, w] of ws.entries()) {    const len = scalars(w);    const t = i + 1 === ws.length && len >= MIN_PREFIX ? await token(bk, "p", column, prefixOf(w, Math.min(len, MAX_PREFIX))) : await token(bk, "w", column, w);    if (!out.includes(t)) out.push(t);  }  return out;}/** * The texts of a cell as the index reads them (Rust blind.rs `cell_texts`): a * string, a number, or the strings and numbers of an array, nested. */export function cellTexts(value: unknown): string[] {  if (typeof value === "string") return [value];  if (typeof value === "number" && Number.isFinite(value)) return [String(value)];  if (Array.isArray(value)) return value.flatMap(cellTexts);  return [];}/** * Whether `text` holds `query` as a blind search means it (Rust blind.rs * `matches`): every query word but the last is a word of the text, and the * last starts one (or is one, at two letters). The words are the index's own * (`words`), so a stopword or a one-letter word asks nothing; a query left * with no word holds nothing. This is the plaintext check a window holds a * token's hit to: a prefix token is the last word's first six letters, so a * longer word's hit ("conferred" for "conference") is dropped here, as is a * truncated token's collision. */export function blindMatches(text: string, query: string): boolean {  const asked = words(query);  if (!asked.length) return false;  const held = words(text);  return asked.every((w, i) => (i + 1 === asked.length && scalars(w) >= MIN_PREFIX ? held.some((h) => h.startsWith(w)) : held.includes(w)));}// Sealing on the object, inside a window only (ruling R4 §5): an// assistant's write to a sealed table is sealed with the window's table key, as a// phone seals it (Rust row.rs `seal_row`, blind.rs `row_tokens`). The object holds// such a key only while the owner's window stands; outside one it seals nothing.function canonicalJson(v: unknown): string {  if (v && typeof v === "object" && !Array.isArray(v)) {    const o = v as Data;    return `{${Object.keys(o)      .sort()      .map((k) => `${JSON.stringify(k)}:${canonicalJson(o[k])}`)      .join(",")}}`;  }  if (Array.isArray(v)) return `[${v.map(canonicalJson).join(",")}]`;  return JSON.stringify(v);}async function gcmSeal(key: Uint8Array, plain: Uint8Array, aad: string): Promise<string> {  const nonce = crypto.getRandomValues(new Uint8Array(12));  const k = await crypto.subtle.importKey("raw", key, "AES-GCM", false, ["encrypt"]);  const body = new Uint8Array(await crypto.subtle.encrypt({ name: "AES-GCM", iv: nonce, additionalData: utf8.encode(aad) }, k, plain));  const out = new Uint8Array(12 + body.length);  out.set(nonce);  out.set(body, 12);  let bin = "";  for (const b of out) bin += String.fromCharCode(b);  return btoa(bin).replace(/\+/g, "-").replace(/\//g, "_").replace(/=+$/, "");}/** The three seal fields for a row's sealed values: the canonical JSON padded with spaces under a fresh DEK, the DEK under TK(t, v). */export async function sealValues(tk: Uint8Array, v: number, databaseId: string, table: string, id: string, sealed: Data): Promise<Data> {  if (tk.length !== 32) throw new SealError("seal_key_missing", "a table key is 32 bytes");  const text = utf8.encode(canonicalJson(sealed));  const padded = new Uint8Array(bucket(text.length)).fill(0x20);  padded.set(text);  const dek = crypto.getRandomValues(new Uint8Array(32));  const out = {    [SEALED_ENC]: `${BODY_PREFIX}${await gcmSeal(dek, padded, bodyAad(databaseId, table, id))}`,    [DEK_ENC]: `${DEK_PREFIX}${await gcmSeal(tk, dek, dekAad(databaseId, table, id, v))}`,    [SEAL_V]: v,  };  dek.fill(0);  return out;}/** A row's values split as the sealer splits them: `id` and the clear columns, and every other one. */export function splitSealed(spec: SealSpec, data: Data): { clear: Data; sealed: Data } {  const clear: Data = {};  const sealed: Data = {};  for (const [k, value] of Object.entries(data)) {    if ((SEAL_FIELDS as readonly string[]).includes(k)) throw new SealError("seal_column_clash", `${k} is written by the sealer`);    if (k === "id" || spec.clear.includes(k)) clear[k] = value;    else sealed[k] = value;  }  return { clear, sealed };}/** Every blind token of a row's plaintext (Rust `row_tokens`): its blind columns' words (capped by blind_bytes) and its blind_exact columns' values. */export async function rowTokens(bk: Uint8Array, raw: Data, spec: SealSpec, row: Data): Promise<string[]> {  const caps = raw.seal && typeof raw.seal === "object" ? ((raw.seal as Data)[BLIND_BYTES] as Record<string, number> | undefined) : undefined;  const out = new Set<string>();  for (const column of spec.blind) {    for (const text of cellTexts(row[column])) {      const cap = caps?.[column];      const bytes = utf8.encode(text);      let said = text;      if (typeof cap === "number" && bytes.length > cap) {        let end = cap;        while (end > 0 && (bytes[end]! & 0xc0) === 0x80) end--;        said = new TextDecoder().decode(bytes.slice(0, end));      }      for (const t of await textTokens(bk, column, said)) out.add(t);    }  }  for (const column of spec.blind_exact) for (const text of cellTexts(row[column])) {    const t = await exactToken(bk, column, text);    if (t) out.add(t);  }  return [...out];}