Cotton code
168 lines · 7.5 KB · TypeScriptRaw
/** * SEALED AT ARRIVAL, FOR AN ACT'S OWN WRITES (e2e rulings R2, lane * e2e-tables): an act the object works itself (booking a statement's lines, * matching another money service's rows, a pull, a fill) may make rows in a * sealed table. The engine's writes are synchronous inside one transaction, * and sealing is not (WebCrypto), so such an act runs twice: * * 1. `capture`: the act runs as usual. Each row it makes in a sealed table *    with sealed columns said in the clear is noted (table, id, values), and *    the transaction is rolled back once the act ends, so nothing of it is *    kept, logged or journalled. * 2. Each noted row is sealed to the person's arrival key (src/arrival.ts). * 3. `apply`: the act runs again; each such row is written as its sealed *    twin, under the id noted, and only its clear columns and seal are held. *    A row that is not the one noted (the act read something else the second *    time) refuses the act, to be asked again: nothing is written. * * An act that makes no such row runs once, as before. With no arrival key * held the act is refused: the object never falls back to the clear. * * A CHANGE TO A SEALED ROW (the arrival patch). The object cannot read a * sealed row's sealed half, so it cannot merge into it. A change it makes to * sealed columns of a sealed row (a pull bringing an event's new title, a * lookup filling a book's details) is kept beside the row as a patch: those * columns alone, sealed to the arrival key exactly as an arrival row's * sealed half is (`sealed_enc` "s1:", `dek_enc` "a1:", bound to the row's * table and id), appended to the row's `arrival_patches` in order. Its clear * columns change as usual. A device opening the row folds each patch over * its sealed half, later over earlier, and seals the row again under the * table's key, which drops the patches (crates/cotton-core seal/arrival.rs * `fold_patches`). A patch marked `fill` (a lookup's details) fills only * the columns the row leaves empty, never over what the person wrote. */import { ARRIVAL_ROW, keyFromText, sealAtArrival } from "./arrival.ts";import type { TableDef } from "./definitions.ts";import { refuse } from "./http.ts";import type { Store } from "./store.ts";type Data = Record<string, unknown>;/** What the engine asks of the seam for one row an act makes in a sealed table with its sealed columns in the clear. */export interface ArrivalSeam {  /** A fresh row id: the second run is handed the ids the first run made, in order, so links between its rows say the same. */  freshId(): string;  /** The row's id and the values to hold for it; `given` says the id is the act's own (derived or imported), not a fresh one. */  made(t: TableDef, id: string, given: boolean, clean: Data): { id: string; data: Data };  /** A change to sealed columns of a sealed row: the patch to append to its `arrival_patches`; `fill` asks the device to fill only what the row leaves empty. */  patched(t: TableDef, id: string, part: Data, fill: boolean): unknown;}/** Where a sealed row keeps the object's changes to it, sealed to the arrival key, until a device folds them in. */export const ARRIVAL_PATCHES = "arrival_patches";/** One patch as a row keeps it. */export interface ArrivalPatch {  sealed_enc: string;  dek_enc: string;  /** Fill only the columns the row leaves empty (a lookup's details), never over what the person wrote. */  fill?: true;}interface Noted {  kind: "row" | "patch";  fill?: boolean;  table: string;  id: string;  said: string;  clean: Data;}/** Canonical JSON, keys sorted, to tell one run's row from the other's. */function canonical(value: unknown): string {  if (Array.isArray(value)) return `[${value.map(canonical).join(",")}]`;  if (value && typeof value === "object") {    const keys = Object.keys(value as Data).sort();    return `{${keys.map((k) => `${JSON.stringify(k)}:${canonical((value as Data)[k])}`).join(",")}}`;  }  return JSON.stringify(value ?? null);}/** The first run: notes each row, holds it as said (the transaction is rolled back). */export class Capture implements ArrivalSeam {  readonly noted: Noted[] = [];  readonly fresh: string[] = [];  freshId(): string {    const id = crypto.randomUUID();    this.fresh.push(id);    return id;  }  made(t: TableDef, id: string, _given: boolean, clean: Data): { id: string; data: Data } {    this.noted.push({ kind: "row", table: t.id, id, said: canonical(clean), clean });    return { id, data: clean };  }  patched(t: TableDef, id: string, part: Data, fill: boolean): unknown {    this.noted.push({ kind: "patch", fill, table: t.id, id, said: canonical(part), clean: part });    return { sealed_enc: "", dek_enc: "" };  }}/** The second run: each row as its sealed twin, in the order the first run made them. */export class Apply implements ArrivalSeam {  private next = 0;  private readonly rows: { noted: Noted; data: Data }[];  private readonly fresh: string[];  constructor(rows: { noted: Noted; data: Data }[], fresh: string[]) {    this.rows = rows;    this.fresh = [...fresh];  }  freshId(): string {    return this.fresh.shift() ?? crypto.randomUUID();  }  made(t: TableDef, id: string, given: boolean, clean: Data): { id: string; data: Data } {    const one = this.rows[this.next++];    if (!one || one.noted.kind !== "row" || one.noted.table !== t.id || one.noted.said !== canonical(clean) || (given && id !== one.noted.id)) moved();    return { id: one.noted.id, data: one.data };  }  patched(t: TableDef, id: string, part: Data, fill: boolean): unknown {    const one = this.rows[this.next++];    if (!one || one.noted.kind !== "patch" || one.noted.table !== t.id || one.noted.id !== id || one.noted.said !== canonical(part) || !!one.noted.fill !== fill) moved();    return { sealed_enc: one.data.sealed_enc, dek_enc: one.data.dek_enc, ...(fill ? { fill: true } : {}) } satisfies Data;  }  /** Every noted row was written again. */  done(): void {    if (this.next !== this.rows.length) moved();  }}function moved(): never {  refuse(409, "moved_while_sealing", "what this write makes changed while its rows were being sealed: ask again");}/** A patch seals every column it carries. */const ALL_SEALED = { clear: [], blind: [], blind_exact: [] };/** The person's arrival key as the object holds it, or a refusal: the object never writes a sealed row in the clear. */export function arrivalKeyOrRefuse(store: Store): Uint8Array {  const key = keyFromText(store.get("seal_key", ARRIVAL_ROW)?.data.pub);  if (!key) refuse(409, "no_arrival_key", "this act writes sealed rows, and no phone has handed the object its arrival key yet: open a Cotton app signed in on the phone that holds the key, then ask again");  return key;}/** Each noted row sealed to the arrival key. */export async function sealNoted(store: Store, databaseId: string, defs: { table(id: string): TableDef | undefined }, noted: Noted[]): Promise<{ noted: Noted; data: Data }[]> {  if (!noted.length) return [];  const key = arrivalKeyOrRefuse(store);  const out: { noted: Noted; data: Data }[] = [];  for (const n of noted) {    const spec = defs.table(n.table)?.seal;    if (!spec) refuse(500, "not_sealed", `${n.table} is not sealed`);    out.push({ noted: n, data: await sealAtArrival(key, databaseId, n.table, n.id, n.kind === "patch" ? ALL_SEALED : spec, n.clean) });  }  return out;}/** Thrown at the end of a capture run that noted rows, to roll its transaction back. */export class RollBack extends Error {  constructor() {    super("rolled back to seal at arrival");  }}