Cotton code
388 lines · 20.7 KB · TypeScriptRaw
/** * A new device approved from one already signed in (owner, 17 Nov 2026: * signing in should not need an SMS every time; SMS stays for the first * device and for recovery). On the open host, beside "send a code": * *   POST /v1/approval/ask { phone, device_id, device_name?, vault_key?, commit } *        → { ask_id, expires_in, poll_seconds } *        The directory routes the ask (src/directory.ts `ask`). It NEVER makes *        a database: a number with none gets an ask that waits like any other *        and expires, so the answer is the same whether or not the number is *        on Cotton and whether or not any device of it is signed in. *   POST /v1/approval/poll { ask_id } → { state: waiting | approved | refused | expired | used, nonce_b?, challenge? } *        `waiting` carries the approving device's nonce once one is set; *        `approved` carries a one-time challenge for the claim. *   POST /v1/approval/reveal { ask_id, nonce } → { ok: true } *        The asking device's nonce, once the approver's is set: it must hash *        to the ask's `commit` (`askCommit`). Set once. *   POST /v1/approval/claim { ask_id, sig } *        `sig` is the asking device's Ed25519 signature (its device id IS the *        public half) over `claimStatement(ask_id, challenge)`. The object *        grants the device its credential once; the ask is then `used`. * * On the person's object, for a device signed in with its own credential * (never a Cotton MCP token, never the admin token: no path approves from the * server): * *   GET  /v1/approvals → { now, asks: [{ ask_id, device_id, device_name, vault_key, commit, nonce_b, reveal, asked_at, expires_at }] } *   POST /v1/approvals/nonce   { ask_id, nonce } → { nonce_b }  (set once: a later one answers the first) *   POST /v1/approvals/approve { ask_id, scanned? } → { ok: true } *        `scanned`: the nonce the new device's QR code carries (GETTING-IN.md), in place of a compared reveal. *        An ask naming a vault key is approved, and opened (`nonce`), only by a device that holds the vault *        itself (`approver_locked` otherwise); GET says so as `holds`. *   POST /v1/approvals/refuse  { ask_id } → { ok: true } *   POST /v1/approvals/wrong   { ask_id } → { left, ended } *        A code typed wrong on any signed-in device of the number. The object *        counts them: the third, across every device and *        every restart, refuses the ask. * * NOTHING SAYS WHETHER A NUMBER IS ON COTTON (owner rule, * 19 Nov 2026). Until a person on a signed-in phone taps "This is me, show the * code" (which sets `nonce_b`), the asking device sees the same answers, in the * same timing class, for a number not on Cotton, one on Cotton with no device * open and one with a device open: every ask is held by an object (a number not * on Cotton by NOBODY, src/directory.ts), so every answer is one object call, * and the open host holds each answer to ANSWER_FLOOR_MS (src/open.ts). * * NO DEVICE INTO THE VAULT ON A TAP. A wrap written onto * another device's vault_key row is kept only when this object holds an ask * that the writing device approved after the codes were compared, naming that * device and that key ([Asks.admitted]); an app from before is told `update_app`. * * THE CODE BOTH SCREENS SHOW IS NOT THE SERVER'S (19 Nov * 2026): it is a short authentication string over a commit and two nonces * (`askSas`, the Bluetooth numeric-comparison construction), so a server that * swapped the asking device's key or vault key would make the two screens * disagree. The asking device commits to its keys and nonce before the * approver's nonce exists, and reveals it only after; this side relays and * checks the reveal against the commit, and never learns the code. The * approving device's core checks the code the person typed, and with it may * wrap the vault's key for `vault_key` (crates/cotton-ffi signin_approval.rs). * * An ask lives ASK_TTL_SECONDS, is decided once, claimed once, and binds the * device key it named: a claim signed by any other key is refused and spends * nothing. Its words and the card each side draws are the core's * (crates/cotton-ffi/src/phone/signin_approval.rs). */import { fromBase64Url } from "./vault.ts";export const ASK_TTL_SECONDS = 180;/** After Approve, the asking device has this long to claim, however late in the ask it came. */export const CLAIM_SECONDS = 60;/** How often the asking device should poll. */export const POLL_SECONDS = 3;/** Asks per number per hour, counted whether or not the number is on Cotton. */export const ASKS_PER_HOUR = 5;/** Wrong codes an ask takes, across every device of the number, before it is refused. */export const WRONG_TRIES = 3;/** How long after a compared approval its approver may write the new device's vault wrap. */export const ADMIT_SECONDS = 600;/** The open host answers an asking device no sooner than this after its request came, whatever the number. */export const ANSWER_FLOOR_MS = 300;/** The object that holds asks for numbers on no database: the same code path, never a person's. */export const NOBODY = "approval-nobody";/** A device id: an Ed25519 public key, 32 bytes as unpadded base64url. */export const DEVICE_KEY = /^[A-Za-z0-9_-]{43}$/;/** A commit or a nonce: 32 bytes as unpadded base64url. */export const BYTES32 = DEVICE_KEY;/** An ask id: the directory's, opaque, the same shape for every number. */export const ASK_ID = /^cta_[A-Za-z0-9_-]{32}$/;export type AskState = "waiting" | "approved" | "refused" | "expired" | "used";export function claimStatement(askId: string, challenge: string): string {  return `cotton-approval-claim-v1\n${askId}\n${challenge}`;}/** What the asking device commits to before the approver's nonce exists. */export async function askCommit(deviceId: string, vaultKey: string | null, nonce: string): Promise<string> {  return base64url(await sha256(concat(utf8("cotton-ask-commit-v1"), fromBase64Url(deviceId), vaultKey ? fromBase64Url(vaultKey) : new Uint8Array(32), fromBase64Url(nonce))));}/** The six digits both screens show: neither side alone, nor the server, chooses them. */export async function askSas(deviceId: string, vaultKey: string | null, nonceA: string, nonceB: string): Promise<string> {  const digest = await sha256(concat(utf8("cotton-ask-sas-v1"), fromBase64Url(deviceId), vaultKey ? fromBase64Url(vaultKey) : new Uint8Array(32), fromBase64Url(nonceA), fromBase64Url(nonceB)));  const n = new DataView(digest.buffer).getUint32(0, false) % 1_000_000;  return String(n).padStart(6, "0");}function utf8(text: string): Uint8Array {  return new TextEncoder().encode(text);}function concat(...parts: Uint8Array[]): Uint8Array {  const out = new Uint8Array(parts.reduce((n, p) => n + p.length, 0));  let at = 0;  for (const p of parts) {    out.set(p, at);    at += p.length;  }  return out;}async function sha256(bytes: Uint8Array): Promise<Uint8Array> {  return new Uint8Array(await crypto.subtle.digest("SHA-256", bytes));}/** A fresh ask id. */export function newAskId(): string {  return `cta_${base64url(crypto.getRandomValues(new Uint8Array(24)))}`;}export function newChallenge(): string {  return base64url(crypto.getRandomValues(new Uint8Array(24)));}/** A device name as the asking device said it: trimmed, at most 60 characters, or null. */export function deviceName(value: unknown): string | null {  if (typeof value !== "string") return null;  const name = value.replace(/\s+/g, " ").trim().slice(0, 60);  return name || null;}export async function verifyDevice(deviceId: string, signature: string, text: string): Promise<boolean> {  let pub: Uint8Array;  let sig: Uint8Array;  try {    pub = fromBase64Url(deviceId);    sig = fromBase64Url(signature);  } catch {    return false;  }  if (pub.length !== 32 || sig.length !== 64) return false;  try {    const key = await crypto.subtle.importKey("raw", pub, { name: "Ed25519" }, false, ["verify"]);    return await crypto.subtle.verify({ name: "Ed25519" }, key, sig, new TextEncoder().encode(text));  } catch {    return false;  }}function base64url(bytes: Uint8Array): string {  let s = "";  for (const b of bytes) s += String.fromCharCode(b);  return btoa(s).replace(/\+/g, "-").replace(/\//g, "_").replace(/=+$/, "");}// ── the object's half ─────────────────────────────────────────────────────const SCHEMA = `CREATE TABLE IF NOT EXISTS approval_ask (  id TEXT PRIMARY KEY, phone TEXT NOT NULL, device_id TEXT NOT NULL, device_name TEXT,  code TEXT NOT NULL, created_at INTEGER NOT NULL, expires_at INTEGER NOT NULL,  state TEXT NOT NULL DEFAULT 'waiting', decided_by TEXT, decided_at INTEGER, challenge TEXT);CREATE INDEX IF NOT EXISTS approval_ask_by_phone ON approval_ask (phone, expires_at);`;/** Columns an object made before the commit–reveal gains (add-only). */const ADDED = ["vault_key TEXT", "commit_hash TEXT", "nonce_b TEXT", "reveal TEXT", "wrong_tries INTEGER NOT NULL DEFAULT 0", "device_kind TEXT"];/** What the asking device says it is, so the card can say "Your Mac" (assets/design/shared/GETTING-IN.md). */export const DEVICE_KINDS = ["mac", "iphone", "ipad", "android", "computer"] as const;export type DeviceKind = (typeof DEVICE_KINDS)[number];/** A device kind as the asking device said it, or null for any other value. */export function deviceKind(value: unknown): DeviceKind | null {  return typeof value === "string" && (DEVICE_KINDS as readonly string[]).includes(value) ? (value as DeviceKind) : null;}export interface Ask {  id: string;  phone: string;  deviceId: string;  deviceName: string | null;  vaultKey: string | null;  commit: string;  createdAt: number;  expiresAt: number;  /** Absent from an app before 22 Nov 2026. */  deviceKind?: DeviceKind | null;}type Row = {  id: string;  phone: string;  device_id: string;  device_name: string | null;  device_kind: string | null;  vault_key: string | null;  commit_hash: string | null;  nonce_b: string | null;  reveal: string | null;  created_at: number;  expires_at: number;  state: string;  decided_by: string | null;  challenge: string | null;  wrong_tries: number;  decided_at: number | null;};export type Refusal = { status: number; code: string; message: string };/** The asks of one object, in its own SQLite. Every time is unix seconds. */export class Asks {  private readonly sql: SqlStorage;  constructor(sql: SqlStorage) {    this.sql = sql;    sql.exec(SCHEMA);    const have = new Set(sql.exec<{ name: string }>("PRAGMA table_info(approval_ask)").toArray().map((c) => c.name));    for (const column of ADDED) if (!have.has(column.split(" ")[0]!)) sql.exec(`ALTER TABLE approval_ask ADD COLUMN ${column}`);  }  /**   * A second ask from the same device replaces the first (GETTING-IN.md): the earlier one, still waiting, expires   * now, so its poll says `expired`, no approver sees it, and nothing can approve or claim it.   */  add(ask: Ask): void {    this.sql.exec("DELETE FROM approval_ask WHERE expires_at < ?", ask.createdAt - 24 * 3600);    this.sql.exec(      "UPDATE approval_ask SET expires_at = ? WHERE phone = ? AND device_id = ? AND state = 'waiting' AND expires_at >= ?",      ask.createdAt - 1, ask.phone, ask.deviceId, ask.createdAt,    );    this.sql.exec(      "INSERT INTO approval_ask (id, phone, device_id, device_name, device_kind, code, vault_key, commit_hash, created_at, expires_at) VALUES (?, ?, ?, ?, ?, '', ?, ?, ?, ?)",      ask.id, ask.phone, ask.deviceId, ask.deviceName, ask.deviceKind ?? null, ask.vaultKey, ask.commit, ask.createdAt, ask.expiresAt,    );  }  private row(id: string): Row | undefined {    return this.sql.exec<Row>("SELECT * FROM approval_ask WHERE id = ?", id).toArray()[0] as Row | undefined;  }  /** What a poll sees. A first look at an approved ask mints its claim's challenge. */  state(id: string, now: number): { state: AskState; nonce_b?: string; challenge?: string; why?: "wrong" } {    const r = this.row(id);    if (!r) return { state: "waiting" };    if (r.state === "used") return { state: "used" };    // Three wrong codes refused it, not a person: the new device says so (GETTING-IN.md).    if (r.state === "refused") return r.wrong_tries >= WRONG_TRIES ? { state: "refused", why: "wrong" } : { state: "refused" };    if (r.expires_at < now) return { state: "expired" };    if (r.state === "approved") {      let challenge = r.challenge;      if (!challenge) {        challenge = newChallenge();        this.sql.exec("UPDATE approval_ask SET challenge = ? WHERE id = ?", challenge, id);      }      return { state: "approved", challenge };    }    return r.nonce_b ? { state: "waiting", nonce_b: r.nonce_b } : { state: "waiting" };  }  /** The approving device's nonce: the first one set stands, and is what every later call answers. */  nonce(id: string, phone: string, deviceId: string, nonce: string, now: number, approverHolds = true): Refusal | { nonce_b: string } {    const r = this.row(id);    const open = this.open(r, phone, deviceId, now);    if (open) return open;    if (r!.vault_key && !approverHolds) return { status: 403, code: "approver_locked", message: "This device cannot open your data itself, so it cannot let another one in." };    this.sql.exec("UPDATE approval_ask SET nonce_b = ? WHERE id = ? AND nonce_b IS NULL", nonce, id);    return { nonce_b: this.row(id)!.nonce_b! };  }  /** The asking device reveals its nonce: after the approver's, once, and only one that hashes to the commit. */  async reveal(id: string, nonce: string, now: number): Promise<Refusal | null> {    const r = this.row(id);    if (!r || r.state !== "waiting" || r.expires_at < now) return { status: 409, code: "ask_closed", message: "That sign-in ask is no longer waiting." };    if (!r.nonce_b) return { status: 409, code: "too_early", message: "No device has opened this sign-in ask yet." };    if (r.reveal) return r.reveal === nonce ? null : { status: 409, code: "already_revealed", message: "This sign-in ask was already answered from the asking device." };    if (!r.commit_hash || (await askCommit(r.device_id, r.vault_key, nonce)) !== r.commit_hash) return { status: 400, code: "wrong_reveal", message: "That does not match what this device asked with." };    this.sql.exec("UPDATE approval_ask SET reveal = ? WHERE id = ? AND reveal IS NULL", nonce, id);    return null;  }  private open(r: Row | undefined, phone: string, deviceId: string, now: number): Refusal | null {    if (!r || r.phone !== phone) return { status: 404, code: "no_such_ask", message: "That sign-in ask is not here." };    if (r.device_id === deviceId) return { status: 403, code: "own_ask", message: "A device cannot approve its own sign-in." };    if (r.state !== "waiting") return { status: 409, code: "ask_decided", message: "That sign-in ask was already answered." };    if (r.expires_at < now) return { status: 410, code: "ask_expired", message: "That sign-in ask has expired." };    return null;  }  /** The asks a signed-in device of `phone` may decide: waiting, not expired, never its own. */  waiting(phone: string, deviceId: string, now: number): Row[] {    return this.sql      .exec<Row>("SELECT * FROM approval_ask WHERE phone = ? AND state = 'waiting' AND expires_at >= ? AND device_id != ? ORDER BY created_at", phone, now, deviceId)      .toArray() as Row[];  }  /**   * Approve or refuse, once, from another signed-in device of the same number.   *   * Approve needs the asking device's nonce in the open: revealed by it after the approver's nonce (the six digits   * were compared), or `scanned` from the code its screen shows (GETTING-IN.md: the QR carries the nonce the ask   * committed to, over a channel the server never sees, so it binds the approval to the device in the person's   * hands as the digits do). A scanned nonce must hash to the commit with the ask's own keys.   *   * An ask that names a vault key is approved only by a device that can open the person's data itself   * (`approverHolds`): one that cannot would let nobody in, and must never seem to.   */  async decide(id: string, phone: string, deviceId: string, verdict: "approved" | "refused", now: number, scanned: string | null = null, approverHolds = true): Promise<Refusal | null> {    const r = this.row(id);    const open = this.open(r, phone, deviceId, now);    if (open || !r) return open;    if (verdict === "approved" && r.vault_key && !approverHolds) return { status: 403, code: "approver_locked", message: "This device cannot open your data itself, so it cannot let another one in." };    if (verdict === "approved" && scanned !== null) {      if (r.reveal && r.reveal !== scanned) return { status: 409, code: "wrong_scan", message: "That code is not the one this ask was made with." };      if (!r.commit_hash || (await askCommit(r.device_id, r.vault_key, scanned)) !== r.commit_hash) return { status: 409, code: "wrong_scan", message: "That code is not the one this ask was made with." };      this.sql.exec("UPDATE approval_ask SET reveal = ? WHERE id = ? AND reveal IS NULL", scanned, id);      r.reveal = scanned;    }    // Approve only after the codes were compared: no blind tap lets a device in.    if (verdict === "approved" && !r.reveal) return { status: 409, code: "not_compared", message: "Compare the code on the new device first." };    const expires = verdict === "approved" ? Math.max(r.expires_at, now + CLAIM_SECONDS) : r.expires_at;    this.sql.exec("UPDATE approval_ask SET state = ?, decided_by = ?, decided_at = ?, expires_at = ? WHERE id = ?", verdict, deviceId, now, expires, id);    return null;  }  /**   * A code typed wrong on a signed-in device: counted here, so every device of the number and every restart shares   * the WRONG_TRIES. The last one refuses the ask. Only an ask being compared counts.   */  wrong(id: string, phone: string, deviceId: string, now: number): Refusal | { left: number; ended: boolean } {    const r = this.row(id);    const open = this.open(r, phone, deviceId, now);    if (open || !r) return open!;    if (!r.reveal) return { status: 409, code: "not_compared", message: "Compare the code on the new device first." };    const tries = this.sql.exec<{ wrong_tries: number }>("UPDATE approval_ask SET wrong_tries = wrong_tries + 1 WHERE id = ? AND state = 'waiting' RETURNING wrong_tries", id).toArray()[0]?.wrong_tries ?? WRONG_TRIES;    if (tries < WRONG_TRIES) return { left: WRONG_TRIES - tries, ended: false };    this.sql.exec("UPDATE approval_ask SET state = 'refused', decided_by = ?, decided_at = ? WHERE id = ? AND state = 'waiting'", deviceId, now, id);    return { left: 0, ended: true };  }  /**   * Whether `approver` let `deviceId` in with `vaultKey` after the codes were compared: an ask naming that device and   * key, revealed, approved (or claimed since) by `approver` in the last ADMIT_SECONDS. What a wrap onto another   * device's vault row needs.   */  admitted(deviceId: string, vaultKey: string, approver: string, now: number): boolean {    return (      this.sql        .exec(          "SELECT 1 FROM approval_ask WHERE device_id = ? AND vault_key = ? AND reveal IS NOT NULL AND state IN ('approved', 'used') AND decided_by = ? AND decided_at >= ? LIMIT 1",          deviceId, vaultKey, approver, now - ADMIT_SECONDS,        )        .toArray().length > 0    );  }  /**   * The asking device claims its credential: the ask approved and unexpired,   * a challenge minted by a poll, and `sig` the ask's own device key over the   * claim statement. Answers the phone and device to grant to; the ask is used.   */  async claim(id: string, sig: string, now: number): Promise<{ refused: Refusal } | { phone: string; deviceId: string }> {    const r = this.row(id);    const notApproved: Refusal = { status: 409, code: "not_approved", message: "That sign-in has not been approved." };    if (!r) return { refused: notApproved };    if (r.state === "used") return { refused: { status: 410, code: "ask_used", message: "That sign-in was already used." } };    if (r.state !== "approved" || !r.challenge) return { refused: notApproved };    if (r.expires_at < now) return { refused: { status: 410, code: "ask_expired", message: "That sign-in ask has expired." } };    if (!(await verifyDevice(r.device_id, sig, claimStatement(id, r.challenge)))) return { refused: { status: 401, code: "wrong_device", message: "That sign-in was asked for from another device." } };    // Single use: only the first claim to flip the row wins.    const changed = this.sql.exec("UPDATE approval_ask SET state = 'used', challenge = NULL WHERE id = ? AND state = 'approved'", id).rowsWritten;    if (!changed) return { refused: { status: 410, code: "ask_used", message: "That sign-in was already used." } };    return { phone: r.phone, deviceId: r.device_id };  }}