Cotton code
181 lines · 11.3 KB · TypeScriptRaw
/** * THE SERVER DECIDES WHICH VAULT KEY AN ACCOUNT HAS (KEPT FOUR 3 part A, coordinator 27 Nov 2026; VAULT GUARD 2, * 28 Nov 2026), for every build. * * A vault_key row holds a wrap of the account's vault master key (VMK) to one device's key. The object cannot open a * wrap, and two wraps of one key never read the same (each is sealed to a fresh ephemeral key), so it cannot tell a * wrap of the account's key from a wrap of another by looking: a phone holding any wrap could post a different key's * wrap as "its own re-wrap" (`refuseLaterFounding`'s own-key path) and `retireOlderKeyRows` then deleted the real row. * * The identity of the key a wrap holds: a key check value, 16 bytes (base64url) that name one key at one version * without revealing it. A phone that knows the key it wraps may send it beside the write as the act's `vmk_check`; it * is kept here, beside the row, in the object's own tables (never served: the row's columns are unchanged, so no * phone's schema moves). What a phone hashes is the phone's to settle before any build sends one (VAULT GUARD 2 item 3: * the key and its version only, never a copy's database id, which a local copy founded before sign-in names * differently from the account's copies). * * WHO PINS THE ACCOUNT'S IDENTITY (VAULT GUARD 2, the coordinator's decision). Every live row today is undeclared, so * the first declaration cannot be taken as the account's key: it may come from the very phone holding a local key * made before sign-in. * - A NEW wrap never pins. Its identity is kept on its row (for `sameKeySameDevice`) and nothing more. * - The identity is pinned only by a device RE-DECLARING a row it already holds, unchanged (the same device, the same *   public key, the same wrapped bytes and version as stored), when that row is not a founder (`founder:` ids: their *   re-declaration pins nothing and is counted as `founder` for the admin check), and is the device's only live *   wrapped row or its oldest. * - Before a pin, any other row declared at that version naming a different identity (another device's, or a stray *   founder of this one) means NOTHING is pinned; it is counted as `disagreeing` for the admin check ([`standing`]). * - Once pinned, a declaration that differs is refused `vault_key_different`, for every caller and every row. * - Once founded, a wrap at a version above the account's newest, or a row moved to such a version, is refused *   `vault_key_rotation`: changing the account's key is its own act (none exists today), never a side effect of a post. * - A wrap with NO declared identity (today's builds, an MCP write, a restore) cannot be told same from different. It *   is kept as today, so today's approvals and re-wraps go on working, but it never retires a row. * - Retiring removes only a row wrapped to the SAME device (same device id, same public key) with the SAME declared *   identity as the row that retires it. * - The heal (`ownKeyRowsToHeal`): with no pin in the account it copies as it always did (the 22 Nov fix for a device *   stuck waiting for approval); once pinned, only from a donor whose identity is the pin. */import { refuse } from "./http.ts";export const SCHEMA = `CREATE TABLE IF NOT EXISTS vault_key_identity (id TEXT PRIMARY KEY, check_value TEXT NOT NULL, vmk_version INTEGER NOT NULL, device_id TEXT, kind TEXT NOT NULL DEFAULT 'new');CREATE TABLE IF NOT EXISTS vault_key_pin (vmk_version INTEGER PRIMARY KEY, check_value TEXT NOT NULL, row_id TEXT NOT NULL, device_id TEXT NOT NULL, pinned_at INTEGER NOT NULL);`;/** A key check value as a phone writes it: 16 bytes, base64url without padding. */const CHECK = /^[A-Za-z0-9_-]{22}$/;/** The identity a write declares for the key its wrap holds (`args.vmk_check`), or null when it declares none. */export function declared(args: Record<string, unknown>): string | null {  const check = args.vmk_check;  if (check === undefined || check === null) return null;  if (typeof check !== "string" || !CHECK.test(check)) refuse(400, "bad_args", "vmk_check is the key check value of the key the wrap holds: 16 bytes, base64url");  return check;}/** The identity kept for the row `id`, with the version it names, or null when none is known. */export function identityOf(sql: SqlStorage, id: string): { check: string; version: number } | null {  const r = sql.exec<{ check_value: string; vmk_version: number }>("SELECT check_value, vmk_version FROM vault_key_identity WHERE id = ?", id).toArray()[0];  return r ? { check: r.check_value, version: Number(r.vmk_version) } : null;}/** The account's pinned identity at `version`, or null. */export function pinOf(sql: SqlStorage, version: number): string | null {  return sql.exec<{ check_value: string }>("SELECT check_value FROM vault_key_pin WHERE vmk_version = ?", version).toArray()[0]?.check_value ?? null;}/** Whether the account has any pinned identity. */export function pinned(sql: SqlStorage): boolean {  return sql.exec<{ n: number }>("SELECT COUNT(*) AS n FROM vault_key_pin").one().n > 0;}/** What a declaration is: a new wrap, a re-declaration of a row the device holds unchanged, or one of a founder row. */export type Kind = "new" | "redeclared" | "founder";/** The row as stored before the write, as [`kindOf`] reads it. */export interface Held {  id: string;  data: Record<string, unknown>;}/** * What a declaring write is. A re-declaration names the row the caller's own device holds, with nothing changed: the * same wrapped bytes, and no other public key or version than the stored ones. */export function kindOf(held: Held | null, data: Record<string, unknown>, device: string | undefined): Kind {  if (!held || !device || !held.data.wrapped_vmk) return "new";  const unchanged =    held.data.device_id === device &&    data.wrapped_vmk === held.data.wrapped_vmk &&    (data.public_key === undefined || data.public_key === held.data.public_key) &&    (data.device_id === undefined || data.device_id === held.data.device_id) &&    (data.vmk_version === undefined || Number(data.vmk_version) === Number(held.data.vmk_version ?? 0));  if (!unchanged) return "new";  return held.id.startsWith("founder:") ? "founder" : "redeclared";}/** After a write put a wrap on the row `id`: its declared identity is kept, or a wrap with none forgets any it had. */export function noteWrap(sql: SqlStorage, id: string, check: string | null, version: number, device: unknown = null, kind: Kind = "new"): void {  if (check === null) sql.exec("DELETE FROM vault_key_identity WHERE id = ?", id);  else    sql.exec(      "INSERT INTO vault_key_identity (id, check_value, vmk_version, device_id, kind) VALUES (?, ?, ?, ?, ?) ON CONFLICT(id) DO UPDATE SET check_value = excluded.check_value, vmk_version = excluded.vmk_version, device_id = excluded.device_id, kind = excluded.kind",      id,      check,      version,      typeof device === "string" ? device : null,      kind,    );}/** The row `id` is gone, holds no wrap now, or moved to another version under the same bytes: its identity is unknown. */export function forget(sql: SqlStorage, id: string): void {  sql.exec("DELETE FROM vault_key_identity WHERE id = ?", id);}/** A live wrapped vault_key row, as the rules read it. */export interface Wrapped {  id: string;  version: number;}/** * Refuses a wrap the account's key does not allow: `wrapped` is every live row holding a wrap (the written row's own * too), `version` the version the row will be at, `check` its declared identity. */export function refuseDifferentKey(sql: SqlStorage, wrapped: Wrapped[], version: number, check: string | null): void {  if (wrapped.length === 0) return;  const newest = Math.max(...wrapped.map((w) => w.version));  if (version > newest) refuse(409, "vault_key_rotation", "This account's vault key is set; a new one comes only by its own change, never with a device's key.");  if (check === null) return;  const pin = pinOf(sql, version);  if (pin !== null && pin !== check) refuse(409, "vault_key_different", "This is not this account's vault key, so it was not kept. This device waits to be let in with the account's key.");}/** * After a re-declaration was kept on its row: pin the account's identity at its version when nothing stands against * it. `rows` is the declaring device's live wrapped rows (id and when each was made). */export function maybePin(sql: SqlStorage, row: { id: string; device: string; check: string; version: number }, rows: Array<{ id: string; created_at: string }>, now: number): boolean {  if (pinOf(sql, row.version) !== null) return false;  const oldest = [...rows].sort((a, b) => a.created_at.localeCompare(b.created_at) || a.id.localeCompare(b.id))[0];  if (!oldest || oldest.id !== row.id) return false;  // Any other row declared at this version naming another identity (another device's, or a stray of this one's) stands  // against it: nothing is pinned, and the admin check counts it.  const disagree = sql.exec<{ n: number }>("SELECT COUNT(*) AS n FROM vault_key_identity WHERE vmk_version = ? AND check_value <> ? AND id <> ?", row.version, row.check, row.id).one().n;  if (disagree > 0) return false;  sql.exec("INSERT INTO vault_key_pin (vmk_version, check_value, row_id, device_id, pinned_at) VALUES (?, ?, ?, ?, ?)", row.version, row.check, row.id, row.device, now);  return true;}/** * The identity's standing, in kinds and counts only (the admin check, `/vault-key-check`): how many versions are * pinned, how many rows declare each kind, and at how many unpinned versions declarations from different devices * disagree. */export function standing(sql: SqlStorage): { pinned: number; declared: Record<Kind, number>; disagreeing: number } {  const declared: Record<Kind, number> = { new: 0, redeclared: 0, founder: 0 };  for (const r of sql.exec<{ kind: string; n: number }>("SELECT kind, COUNT(*) AS n FROM vault_key_identity GROUP BY kind").toArray()) {    if (r.kind === "new" || r.kind === "redeclared" || r.kind === "founder") declared[r.kind] = Number(r.n);  }  const pinnedVersions = sql.exec<{ n: number }>("SELECT COUNT(*) AS n FROM vault_key_pin").one().n;  const disagreeing = sql    .exec<{ n: number }>("SELECT COUNT(*) AS n FROM (SELECT vmk_version FROM vault_key_identity WHERE vmk_version NOT IN (SELECT vmk_version FROM vault_key_pin) GROUP BY vmk_version HAVING COUNT(DISTINCT check_value) > 1)")    .one().n;  return { pinned: Number(pinnedVersions), declared, disagreeing: Number(disagreeing) };}/** Whether the row `older` may be retired by `kept`: the same key identity, declared on both, wrapped to the same device. */export function sameKeySameDevice(sql: SqlStorage, kept: { id: string; device_id: unknown; public_key: unknown }, older: { id: string; device_id: unknown; public_key: unknown }): boolean {  if (kept.device_id !== older.device_id || kept.public_key !== older.public_key) return false;  const a = identityOf(sql, kept.id);  const b = identityOf(sql, older.id);  return a !== null && b !== null && a.check === b.check && a.version === b.version;}/** Whether a donor's wrap may be copied by the heal: any, with no pin in the account; else only one of the pinned identity. */export function healsFrom(sql: SqlStorage, donorId: string, version: number): boolean {  if (!pinned(sql)) return true;  const pin = pinOf(sql, version);  const own = identityOf(sql, donorId);  return pin !== null && own !== null && own.check === pin && own.version === version;}