Cotton code
230 lines · 12.6 KB · TypeScriptRaw
/** * FOUNDER ROW CHECK (coordinator, 27 Nov 2026): read only, the admin token alone. Old phone builds that founded a local * vault before sign-in and then signed in to an EXISTING account posted a vault_key row `founder:<device key>` carrying * the phone's own public key and a wrap of its LOCAL vault key. When that public key was already wrapped on the * device's genuine row (the key survived a reinstall), `refuseLaterFounding` took the post for the device's own re-wrap * and `retireOlderKeyRows` deleted the genuine row, which wrapped the ACCOUNT's vault key (src/business.ts). This says, * for one object, whether its vault_key rows show that. * * Kinds and counts only: never a key, a wrap, a row id, a device id, a name or a number. The object cannot open a wrap, * so "wraps a foreign key" is never known here, only inferred from what the rows and the change log hold: * *   - founder_retired_wrapped_row: a write of a `founder:` row deleted another row that held a wrap under the same *     public key, in the same write (the change log keeps a delete with the whole row; its version is the founder *     row's write). The correct flow is the other way round: the signed-in row retires the founder row. Strong. *   - founder_after_vault_held: the founder row was made while another row already held a wrap ("yes"), no sign of *     that in what is kept ("not_seen"), or its making is older than the change log keeps ("unknown"). Today a founding *     into a held vault is refused `vault_founded` unless the same key is wrapped elsewhere, so "yes" means it came in *     through the own-key path. Strong. *   - founder_only_wrap: the founder row is its device's only wrapped row while other devices hold wraps. Alone this is *     also what a phone that founded a NEW account looks like, so it flags only beside founder_version_behind. *   - founder_version_behind: the founder row's vmk_version is below another wrapped row's, the data key's or the *     person key's: it wraps a version the account has moved past. An account still at version 1 cannot show it. *   - heal_may_copy_founder_wrap: the device has an unwrapped row under the founder row's key, and the founder row is *     a donor `healOwnKeyRows` would copy from on that device's next pull. *   - retired_row_undoable: the retired row's delete is still in the change log and nothing has written the record *     since, so `undo` of that change would bring the genuine row back as it was. *   - seal_key_after_founder / person_key_after_founder: the data key's wrap (seal_key `dk`) or the person key was *     last written after the founder row was made ("yes"), not ("no"), or it cannot be told ("unknown"). A "yes" *     means something may now be sealed under the founder row's key: that row must not be deleted. * * Two wrapped rows of one key with different wraps are counted (same_key_wrapped_groups) but say nothing alone: a wrap * is sealed to a fresh ephemeral key each time, so the same vault key wrapped twice never reads the same. Only a * different vmk_version between them (same_key_version_split) is a disagreement the object can see. */import * as vaultIdentity from "./vault_identity.ts";type Data = Record<string, unknown>;export type Seen = "yes" | "not_seen" | "unknown";export type Told = "yes" | "no" | "unknown";const TABLE = "vault_key";export const FOUNDER_PREFIX = "founder:";export interface FounderFinding {  flagged: boolean;  founder_wrapped: boolean;  founder_retired_wrapped_row: boolean;  retired_rows: number;  retired_row_undoable: number;  founder_after_vault_held: Seen;  founder_only_wrap: boolean;  founder_version_behind: boolean;  heal_may_copy_founder_wrap: boolean;  same_key_live_rows: number;  seal_key_after_founder: Told;  person_key_after_founder: Told;}export interface VaultKeyReport {  vault_key_rows: number;  wrapped_rows: number;  founder_rows: number;  founder_wrapped_rows: number;  retired_rows: number;  devices: number;  devices_flagged: number;  same_key_wrapped_groups: number;  same_key_version_split: number;  change_log_from_version: number | null;  flagged: boolean;  findings: FounderFinding[];  /** The account's key identity (src/vault_identity.ts `standing`): pinned versions, declarations by kind, disagreements. */  identity: ReturnType<typeof vaultIdentity.standing>;}/** What the check over every database answers (KEPT FOUR 3 LOW): counts and kinds only, never a database id. */export interface VaultKeyPage {  objects: number;  flagged: number;  failed: number;  /** How many objects show each kind (a finding true or "yes" on any founder row, or the object's own count above 0). */  kinds: Record<string, number>;  /** Where the next page starts: a position in the directory's order, never an id. */  next: number | null;}/** Adds one object's report to a page's kinds. */export function countKinds(kinds: Record<string, number>, report: VaultKeyReport): void {  const add = (kind: string): void => {    kinds[kind] = (kinds[kind] ?? 0) + 1;  };  for (const kind of ["founder_rows", "founder_wrapped_rows", "retired_rows", "devices_flagged", "same_key_wrapped_groups", "same_key_version_split"] as const) if (report[kind] > 0) add(kind);  const seen = new Set<string>();  for (const finding of report.findings) for (const [kind, value] of Object.entries(finding)) if ((value === true || value === "yes" || (typeof value === "number" && value > 0)) && !seen.has(kind)) seen.add(kind);  for (const kind of seen) add(kind);  if (report.identity.pinned > 0) add("identity_pinned");  if (report.identity.disagreeing > 0) add("identity_disagreeing");  if (report.identity.declared.founder > 0) add("identity_founder_declared");}interface KeyRow {  id: string;  device: string | null;  key: string | null;  wrapped: boolean;  vmk: number;  version: number;}interface Logged {  id: number;  record: string;  kind: string;  version: number;  before: Data | null;  after: Data | null;  undone: boolean;}const parse = (text: string | null): Data | null => {  if (text === null) return null;  try {    const v = JSON.parse(text) as unknown;    return v && typeof v === "object" ? (v as Data) : null;  } catch {    return null;  }};const holdsWrap = (v: unknown): boolean => typeof v === "string" && v !== "";const vmkOf = (v: unknown): number => (typeof v === "number" && Number.isFinite(v) ? v : 0);/** One object's vault_key rows read against the founding bug. Reads only. */export function vaultKeyCheck(sql: SqlStorage): VaultKeyReport {  const live: KeyRow[] = sql    .exec<{ id: string; version: number; device: string | null; key: string | null; wrap: string | null; vmk: number | null }>(      "SELECT id, version, json_extract(data, '$.device_id') AS device, json_extract(data, '$.public_key') AS key, json_extract(data, '$.wrapped_vmk') AS wrap, json_extract(data, '$.vmk_version') AS vmk FROM rows WHERE table_id = ? AND deleted = 0 ORDER BY id",      TABLE,    )    .toArray()    .map((r) => ({ id: r.id, device: r.device, key: r.key, wrapped: holdsWrap(r.wrap), vmk: vmkOf(r.vmk), version: Number(r.version) }));  const tombstones = new Map(    sql.exec<{ id: string; version: number }>("SELECT id, version FROM rows WHERE table_id = ? AND deleted = 1", TABLE).toArray().map((r) => [r.id, Number(r.version)]),  );  const logged: Logged[] = sql    .exec<{ id: number; record_id: string; kind: string; version: number; before: string | null; after: string | null; undone_by: number | null }>(      "SELECT id, record_id, kind, version, before, after, undone_by FROM change WHERE table_id = ? ORDER BY id",      TABLE,    )    .toArray()    .map((c) => ({ id: Number(c.id), record: c.record_id, kind: c.kind, version: Number(c.version), before: parse(c.before), after: parse(c.after), undone: c.undone_by !== null }));  const logFloor = sql.exec<{ v: number | null }>("SELECT MIN(version) AS v FROM change").one().v;  const dk = sql.exec<{ version: number; vmk: number | null }>("SELECT version, json_extract(data, '$.vmk_version') AS vmk FROM rows WHERE table_id = 'seal_key' AND id = 'dk' AND deleted = 0").toArray()[0];  const personKeys = sql.exec<{ version: number; vmk: number | null }>("SELECT version, json_extract(data, '$.vmk_version') AS vmk FROM rows WHERE table_id = 'person_key' AND deleted = 0").toArray();  const wrapped = live.filter((r) => r.wrapped);  const founders = live.filter((r) => r.id.startsWith(FOUNDER_PREFIX));  // The vault's version as the account holds it elsewhere: the data key's wrap and the person key name theirs.  const accountVmk = Math.max(0, dk ? vmkOf(dk.vmk) : 0, ...personKeys.map((p) => vmkOf(p.vmk)));  const findings: FounderFinding[] = founders.map((f) => {    const own = logged.filter((c) => c.record === f.id);    const made = own.find((c) => c.kind === "create" || c.kind === "restore")?.version ?? null;    // Every version this row was written at: what the log keeps, and its standing version (a heal writes unlogged).    const writes = new Set([...own.map((c) => c.version), f.version]);    const retired = logged.filter(      (c) => c.kind === "delete" && c.record !== f.id && c.before !== null && writes.has(c.version) && c.before.public_key === f.key && holdsWrap(c.before.wrapped_vmk),    );    // Undo brings a row back only while its tombstone is as that delete left it (changes.ts `undo`, `changed_since`).    const undoable = retired.filter((c) => !c.undone && tombstones.get(c.record) === c.version && !live.some((r) => r.id === c.record));    let after: Seen = "unknown";    if (made !== null) {      const heldBefore =        retired.some((c) => c.version === made) ||        wrapped.some((r) => r.id !== f.id && r.version < made) ||        logged.some((c) => c.record !== f.id && c.kind === "update" && c.version < made && c.before !== null && "wrapped_vmk" in c.before && !holdsWrap(c.before.wrapped_vmk));      after = heldBefore ? "yes" : "not_seen";    }    const othersWrapped = wrapped.filter((r) => r.device !== f.device);    const onlyWrap = f.wrapped && !wrapped.some((r) => r.id !== f.id && r.device === f.device) && othersWrapped.length > 0;    const newest = Math.max(accountVmk, ...wrapped.filter((r) => r.id !== f.id).map((r) => r.vmk));    const behind = f.wrapped && f.vmk < newest;    // healOwnKeyRows (src/business.ts): an unwrapped row of the device under the same key takes the highest-version donor's wrap.    const donors = live.filter((r) => r.device === f.device && r.key === f.key && r.wrapped);    const topVmk = Math.max(0, ...donors.map((r) => r.vmk));    const heal = f.wrapped && f.vmk === topVmk && live.some((r) => r.device === f.device && r.key === f.key && !r.wrapped);    const lastAfter = (version: number | undefined): Told => {      if (version === undefined) return "no";      if (made !== null) return version > made ? "yes" : "no";      return version > f.version ? "yes" : "unknown";    };    const pk = personKeys.length ? Math.max(...personKeys.map((p) => Number(p.version))) : undefined;    const finding: FounderFinding = {      flagged: false,      founder_wrapped: f.wrapped,      founder_retired_wrapped_row: retired.length > 0,      retired_rows: retired.length,      retired_row_undoable: undoable.length,      founder_after_vault_held: after,      founder_only_wrap: onlyWrap,      founder_version_behind: behind,      heal_may_copy_founder_wrap: heal,      same_key_live_rows: live.filter((r) => r.id !== f.id && r.key === f.key).length,      seal_key_after_founder: dk ? lastAfter(Number(dk.version)) : "no",      person_key_after_founder: lastAfter(pk),    };    finding.flagged = f.wrapped && (finding.founder_retired_wrapped_row || after === "yes" || (onlyWrap && behind));    return finding;  });  const byKey = new Map<string, KeyRow[]>();  for (const r of wrapped) if (r.key) byKey.set(r.key, [...(byKey.get(r.key) ?? []), r]);  const groups = [...byKey.values()].filter((g) => g.length > 1);  const flaggedDevices = new Set(founders.filter((_, i) => findings[i]!.flagged).map((f) => f.device ?? ""));  return {    vault_key_rows: live.length,    wrapped_rows: wrapped.length,    founder_rows: founders.length,    founder_wrapped_rows: founders.filter((f) => f.wrapped).length,    retired_rows: tombstones.size,    devices: new Set(live.map((r) => r.device ?? "")).size,    devices_flagged: flaggedDevices.size,    same_key_wrapped_groups: groups.length,    same_key_version_split: groups.filter((g) => new Set(g.map((r) => r.vmk)).size > 1).length,    change_log_from_version: logFloor === null ? null : Number(logFloor),    flagged: findings.some((x) => x.flagged) || vaultIdentity.standing(sql).disagreeing > 0,    findings,    identity: vaultIdentity.standing(sql),  };}