/** * THE WAY BACK IN (rulings R7a and R7c): a recovery code the person keeps, and a platform key the * phone's own synced key store keeps: `google` (Block Store) and `apple` (iCloud Keychain), each its own slot, as an * Android phone and an iPhone of one person keep different keys. Either one opens the vault on a new device * with no other device of the person's at hand. The derivation is the device's (crates/cotton-core * vault/recovery_code.rs); this object holds, per kind, only: * * salt, kdf the stretch's salt and parameters, answered to any signed-in device of the person * auth_hash the SHA-256 of the auth key the secret gives: compared, never answered * wrapped the vault master key wrapped under the wrap key the secret gives: answered only after a * matching auth key, inside the try limit * vmk_version the version of the vault key wrapped * code_enc the code itself sealed under the vault key (a device holding the vault shows it again) * * Nothing here opens anything: the wrap key never reaches the object, and the auth key that does is a different HKDF * output of the same stretched secret, so it opens no wrap. A dump of the object is a hash and a wrap under a key * stretched from 110 random bits (a code) or 256 (a platform key). * * Tries are counted per kind: at most FAILS_PER_HOUR wrong ones in an hour and FAILS_PER_DAY in a day, then a wait * said with its seconds. A right one lets the device that made it put a wrap on its own vault_key row for * GRANT_MS (the founding guard otherwise refuses that as a second founding: `granted`). * * Routes (the personal object; the person's own signed-in devices, never a token): * GET /v1/recovery { code, google, apple: Held | null } Held = { salt, kdf, vmk_version, created_at, code_enc? } * POST /v1/recovery/set { kind, salt, kdf, auth_hash, wrapped, vmk_version, code_enc? } → { kind, created_at } * by a device whose own row holds a wrap; replaces (retires) the kind's earlier one * POST /v1/recovery/open { kind, auth } → { wrapped, vmk_version } | 403 recovery_wrong { tries_left } | 429 recovery_wait { retry_after } * POST /v1/recovery/retire { kind } → { retired } by a device whose own row holds a wrap, as `set` * * THE TRUSTED PERSON (R7d). `set` of kind `trusted` also carries the helper's number (one of this person's people), * the object's half of the split secret (`share`, kept in recovery_trust) and the helper's half sealed to the helper's * sharing key (`box`, handed to their object at once and never kept here). Then: * POST /v1/recovery/help/ask { device_key, commit, name? } → { id, name } a new device asks, committing to its * key and a nonce it keeps (`helpCommit`); the ask goes to the helper's object * (ASKS_PER_DAY a day) * GET /v1/recovery/help/ask → { state: none|asked|opened|compare|approved|declined, name, nonce_b?, sealed?, share? } * for the device that asked: the helper's nonce once set; once approved, the helper's * half wrapped to that device's key, and this object's half, released to it alone * POST /v1/recovery/help/reveal { nonce } the device's nonce, once the helper's is set: it must hash to the commit * GET /v1/recovery/help → { asks: [{ id, peer, device_key, commit, nonce_b?, reveal?, box }] } on the helper's * phone: who asks now, with the half kept for them * POST /v1/recovery/help/open { id, nonce } → { nonce } the helper's nonce, set once (a later one answers the first) * POST /v1/recovery/help/answer { id, sealed } | { id, decline: true } the helper answers, `sealed` only once the * device has revealed; carried to the asker's object * * THE SERVER CANNOT CHOOSE THE CODE (TRUSTED RECOVERY BUILD 1, 2). Both phones work out six digits from whose recovery * it is (the person's number, the setup, the place, the ask), the device's key and the two nonces (crates/cotton-core * recovery_code.rs `help_sas`); the helper types the digits the person reads from the new device, and the helper's * phone wraps its half only to the key those digits vouch for. This object relays and checks the reveal against the * commit. It sees everything the digits are made of once revealed, but it cannot choose them: the device committed * before the helper's nonce existed, so a key it swapped would make the two screens disagree. * The helper's half alone and this object's half alone are each 32 random bytes: neither opens anything. */ import { json, readJson, refuse } from "./http.ts"; export const SCHEMA = ` CREATE TABLE IF NOT EXISTS recovery (kind TEXT PRIMARY KEY, salt TEXT NOT NULL, kdf TEXT NOT NULL, auth_hash TEXT NOT NULL, wrapped TEXT NOT NULL, vmk_version INTEGER NOT NULL, code_enc TEXT, made_by TEXT, created_at INTEGER NOT NULL); CREATE TABLE IF NOT EXISTS recovery_try (at INTEGER NOT NULL, kind TEXT NOT NULL, device TEXT, ok INTEGER NOT NULL); CREATE TABLE IF NOT EXISTS recovery_grant (device TEXT PRIMARY KEY, until INTEGER NOT NULL); CREATE TABLE IF NOT EXISTS recovery_trust (id INTEGER PRIMARY KEY CHECK (id = 1), helper TEXT NOT NULL, helper_name TEXT, share TEXT NOT NULL, at INTEGER NOT NULL); CREATE TABLE IF NOT EXISTS recovery_help_ask (id TEXT PRIMARY KEY, device TEXT NOT NULL, device_key TEXT NOT NULL, code TEXT NOT NULL, name TEXT, state TEXT NOT NULL, sealed TEXT, at INTEGER NOT NULL); CREATE TABLE IF NOT EXISTS recovery_help_held (peer TEXT PRIMARY KEY, box TEXT NOT NULL, at INTEGER NOT NULL); CREATE TABLE IF NOT EXISTS recovery_help_in (id TEXT PRIMARY KEY, peer TEXT NOT NULL, device_key TEXT NOT NULL, code TEXT NOT NULL, state TEXT NOT NULL, at INTEGER NOT NULL); CREATE TABLE IF NOT EXISTS recovery_flow_seen (device TEXT PRIMARY KEY, flow INTEGER NOT NULL, at INTEGER NOT NULL); `; /** Columns an earlier build's tables lack, added once at start (the commit, the helper's nonce, the device's reveal). */ const ADDED: Record = { recovery_help_ask: ["commit_hash TEXT", "nonce_b TEXT", "reveal TEXT", "flow INTEGER"], recovery_help_in: ["commit_hash TEXT", "nonce_b TEXT", "reveal TEXT", "flow INTEGER"], recovery_trust: ["gone_at INTEGER"], }; export function migrate(sql: SqlStorage): void { for (const [table, columns] of Object.entries(ADDED)) { const have = new Set(sql.exec<{ name: string }>(`PRAGMA table_info(${table})`).toArray().map((c) => c.name)); for (const column of columns) if (!have.has(column.split(" ")[0]!)) sql.exec(`ALTER TABLE ${table} ADD COLUMN ${column}`); } } export const KINDS = ["code", "google", "apple", "trusted", "circle"] as const; /** How long a trusted person has to answer an ask. */ export const ASK_MS = 24 * 60 * 60 * 1000; /** At most this many asks a day from one person's new devices. */ export const ASKS_PER_DAY = 5; export type Kind = (typeof KINDS)[number]; export const FAILS_PER_HOUR = 5; export const FAILS_PER_DAY = 20; export const GRANT_MS = 10 * 60 * 1000; const HOUR = 60 * 60 * 1000; const DAY = 24 * HOUR; /** Another person's object, as the trusted person's half travels between the two. */ export interface HelpPeer { helpKept(from: string, box: string): Promise; helpAsked(from: string, ask: { id: string; device_key: string; code?: string; commit?: string }): Promise; helpOpened(from: string, opened: { id: string; nonce: string }): Promise; helpRevealed(from: string, revealed: { id: string; nonce: string }): Promise; helpAnswered(from: string, answer: { id: string; sealed?: string; decline?: boolean; legacy?: boolean }): Promise; /** The helper can help no more (they removed or blocked this person, or deleted their account): kept only from them. */ helpGone(from: string): Promise; /** The person no longer counts on this helper (they removed them, chose again, or deleted their account): the half goes. */ helpDropped(from: string): Promise; } export interface RecoveryHost { sql: SqlStorage; now: () => number; /** This person's own number. */ ownerPhone: string | null; /** Whether a number is one of this person's people (accepted both ways, not blocked). */ isPeer: (number: string) => Promise; /** That person's object, or null when they are on no Cotton object. */ peerObject: (number: string) => Promise; /** Whether this device's own vault_key row holds a wrap: only a device that holds the vault sets a way back in. */ holdsVault: (deviceId: string) => boolean; /** The circle's summary for GET (src/recovery_circle.ts `summary`), beside its `circle` row, as told to that device. */ circle?: (device: string) => Record | null; /** Whether a device signed in only by SMS in the last two days. */ freshDevice?: (deviceId: string) => boolean; } /** Who may ask: the person's own signed-in device (role owner, no token). */ export interface RecoveryCaller { deviceId: string | null; owner: boolean; token: boolean; } export async function route(host: RecoveryHost, caller: RecoveryCaller, request: Request, url: URL): Promise { const path = url.pathname; if (path !== "/v1/recovery" && !path.startsWith("/v1/recovery/")) return null; if (!caller.deviceId) refuse(401, "sign_in", "a way back in is asked from a signed-in device"); if (!caller.owner || caller.token) refuse(403, "owner_only", "only the person's own devices reach their way back in"); const device = caller.deviceId; const method = request.method; const flow = flowOf(url); noteFlow(host.sql, device, flow, host.now()); if (method === "GET" && path === "/v1/recovery") return json({ ...held(host, device), device: { fresh: host.freshDevice?.(device) ?? false } }); if (method === "POST" && path === "/v1/recovery/set") return json(await set(host, device, await readJson(request))); if (method === "POST" && path === "/v1/recovery/open") return open(host, device, await readJson(request)); if (method === "POST" && path === "/v1/recovery/retire") return json(await retire(host, device, kindOf((await readJson(request)).kind))); if (method === "POST" && path === "/v1/recovery/help/ask") return json(await ask(host, device, await readJson(request), flow)); if (method === "GET" && path === "/v1/recovery/help/ask") return json(asked(host, device)); if (method === "POST" && path === "/v1/recovery/help/reveal") return json(await reveal(host, device, await readJson(request))); if (method === "POST" && path === "/v1/recovery/help/open") return json(await opening(host, await readJson(request))); if (method === "GET" && path === "/v1/recovery/help") return json(asksIn(host, flow)); if (method === "POST" && path === "/v1/recovery/help/answer") return json(await answer(host, await readJson(request), flow)); refuse(404, "not_found", `nothing answers ${method} ${path}`); } interface Row { kind: string; salt: string; kdf: string; auth_hash: string; wrapped: string; vmk_version: number; code_enc: string | null; created_at: number; [key: string]: SqlStorageValue; } function row(host: RecoveryHost, kind: Kind): Row | null { return (host.sql.exec("SELECT * FROM recovery WHERE kind = ?", kind).toArray()[0] as Row | undefined) ?? null; } function fresh(host: RecoveryHost, device: string): boolean { return host.freshDevice?.(device) ?? false; } /** The helper as a device is told of them: the name the person gave; the number only to a device past the two-day rule. */ function helperShown(host: RecoveryHost, t: Trust, device: string): string { return t.helper_name ?? (fresh(host, device) ? "" : t.helper); } /** What any device of the person reads: never the hash, never the wrap. */ export function held(host: RecoveryHost, device: string): Record | null> { const out = {} as Record | null>; for (const kind of KINDS) { const r = row(host, kind); out[kind] = r ? { salt: r.salt, kdf: r.kdf, vmk_version: r.vmk_version, created_at: new Date(r.created_at).toISOString(), ...(r.code_enc ? { code_enc: r.code_enc } : {}) } : null; // The circle as told to this device; one set and not yet live shows (`pending`) before its wrap is the way in. if (kind === "circle") { const told = host.circle?.(device) ?? null; if (out[kind]) Object.assign(out[kind]!, told ?? {}); else if (told) out[kind] = told; } if (kind === "trusted" && out[kind]) { const t = trust(host); // A device signed in only by SMS in the last two days is told the helper's name, never their number (BUILD 3, LOW). if (t) Object.assign(out[kind]!, { ...(fresh(host, device) ? {} : { helper: t.helper }), helper_name: t.helper_name, ...(t.gone_at ? { gone: true, gone_at: new Date(t.gone_at).toISOString() } : {}) }); } } return out; } function kindOf(value: unknown): Kind { if (typeof value !== "string" || !(KINDS as readonly string[]).includes(value)) refuse(400, "bad_kind", `kind is ${KINDS.join(" or ")}`); return value as Kind; } const B64URL = /^[A-Za-z0-9_-]+$/; /** The salt, stretch, auth hash, wrap and version every way back in carries, checked; refused by name. */ export function checkWrap(kind: Kind, body: Record): void { const salt = body.salt; if (typeof salt !== "string" || !B64URL.test(salt) || salt.length < 22 || salt.length > 64) refuse(400, "bad_salt", "salt is 16 to 48 bytes, base64url"); const kdf = body.kdf; const scrypt = typeof kdf === "string" ? /^scrypt:(\d{1,2}):(\d{1,2}):(\d)$/.exec(kdf) : null; if (kind === "code" && (!scrypt || Number(scrypt[1]) < 14)) refuse(400, "bad_kdf", "a code is stretched with scrypt at 2^14 or more"); if (kind !== "code" && kdf !== "none" && !scrypt) refuse(400, "bad_kdf", "kdf is none or scrypt:::

"); const authHash = body.auth_hash; if (typeof authHash !== "string" || !/^[0-9a-f]{64}$/.test(authHash)) refuse(400, "bad_auth_hash", "auth_hash is a SHA-256 in lower-case hex"); const wrapped = body.wrapped; if (typeof wrapped !== "string" || !wrapped.startsWith("r1:") || !B64URL.test(wrapped.slice(3)) || wrapped.length > 200) refuse(400, "bad_wrap", "wrapped is an r1: wrap of the vault key"); const version = body.vmk_version; if (typeof version !== "number" || !Number.isInteger(version) || version < 1) refuse(400, "bad_version", "vmk_version is a whole number from 1"); } /** A way back in written: one per kind, replacing (retiring) the kind's earlier one. */ export function writeWrap(host: Pick, kind: Kind, device: string, body: Record): number { const at = host.now(); host.sql.exec( "INSERT OR REPLACE INTO recovery (kind, salt, kdf, auth_hash, wrapped, vmk_version, code_enc, made_by, created_at) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)", kind, body.salt as string, body.kdf as string, body.auth_hash as string, body.wrapped as string, body.vmk_version as number, (body.code_enc as string | undefined) ?? null, device, at, ); return at; } /** The one-helper scheme's trusted person let go, as a circle replaces it: their object lets the half go. */ /** * The one-helper scheme's trusted person let go, as a live circle replaces it (TRUSTED RECOVERY BUILD 2, review M2): * the rows go at once, in the same step as the circle goes live; answers the helper to tell, told after. */ export function retireTrustedRows(sql: SqlStorage): string | null { const t = trust({ sql }); sql.exec("DELETE FROM recovery WHERE kind = 'trusted'"); sql.exec("DELETE FROM recovery_trust"); return t?.helper ?? null; } /** The helper of a retired one-helper setup told to let the half go (best effort: the half alone opens nothing). */ export async function tellTrustedDropped(host: RecoveryHost, helper: string): Promise { await (await host.peerObject(helper))?.helpDropped(host.ownerPhone ?? ""); } /** Whether a recovery circle is set on this object, live (id 1) or waiting to go live (id 2). */ function circleSet(sql: SqlStorage): boolean { if (!sql.exec("SELECT 1 FROM sqlite_master WHERE type = 'table' AND name = 'recovery_circle'").toArray().length) return false; return sql.exec("SELECT 1 FROM recovery_circle WHERE id IN (1, 2) LIMIT 1").toArray().length > 0; } async function set(host: RecoveryHost, device: string, body: Record): Promise<{ kind: Kind; created_at: string }> { const kind = kindOf(body.kind); if (kind === "circle") refuse(400, "bad_kind", "a circle is set at /v1/recovery/circle/set"); // AUDIT D: with a circle set (live or waiting), the one-helper way is not set again beside it: that way releases on // one approval, with no 48 hours, no Stop link and no word to the person's phones, so it would undo the circle's rules. if (kind === "trusted" && circleSet(host.sql)) refuse(409, "circle_set", "You have a recovery circle. Change who is in it from the circle instead."); if (!host.holdsVault(device)) refuse(403, "vault_not_held", "only a device that holds the vault sets a way back in"); checkWrap(kind, body); const salt = body.salt as string; const kdf = body.kdf; const authHash = body.auth_hash as string; const wrapped = body.wrapped as string; const version = body.vmk_version as number; if (typeof salt !== "string" || !B64URL.test(salt) || salt.length < 22 || salt.length > 64) refuse(400, "bad_salt", "salt is 16 to 48 bytes, base64url"); const codeEnc = body.code_enc ?? null; if (codeEnc !== null && (typeof codeEnc !== "string" || codeEnc.length > 400)) refuse(400, "bad_code_enc", "code_enc is the code sealed under the vault key"); let helper: { number: string; name: string | null; share: string; box: string } | null = null; if (kind === "trusted") { const number = body.helper; if (typeof number !== "string" || !/^\+\d{6,16}$/.test(number) || number === host.ownerPhone) refuse(400, "bad_helper", "helper is one of your people's numbers"); if (!(await host.isPeer(number))) refuse(403, "not_your_person", "Only one of your people, someone you both accepted on Cotton, can help you back in."); const share = body.share; if (typeof share !== "string" || !B64URL.test(share) || share.length !== 43) refuse(400, "bad_share", "share is this object's 32-byte half, base64url"); const box = body.box; if (typeof box !== "string" || !box.startsWith("p1:") || !B64URL.test(box.slice(3)) || box.length > 400) refuse(400, "bad_box", "box is the helper's half sealed to their sharing key"); const name = typeof body.helper_name === "string" ? body.helper_name.slice(0, 80) : null; helper = { number, name, share, box }; } const at = host.now(); if (helper) { // Kept only where the helper's object took the box (they accepted this person back, and did not block them); every // other case, a number on no account included, answers the same (AUDIT FIX B1, B-4: no word of whether the number // is on Cotton), and the phone never records a helper who holds nothing (B-17). const theirs = await host.peerObject(helper.number); const earlier = trust(host); const kept = theirs ? await theirs.helpKept(host.ownerPhone ?? "", helper.box).catch(() => false) : false; if (!kept) refuse(403, "not_your_person", "Only one of your people, someone you both accepted on Cotton, can help you back in."); // Chosen again: the earlier helper's half goes, only once the new one holds theirs. if (earlier && earlier.helper !== helper.number) await (await host.peerObject(earlier.helper))?.helpDropped(host.ownerPhone ?? ""); host.sql.exec("INSERT OR REPLACE INTO recovery_trust (id, helper, helper_name, share, at) VALUES (1, ?, ?, ?, ?)", helper.number, helper.name, helper.share, at); } // One per kind: a new code retires the old one, which opens nothing from now on. host.sql.exec( "INSERT OR REPLACE INTO recovery (kind, salt, kdf, auth_hash, wrapped, vmk_version, code_enc, made_by, created_at) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)", kind, salt, kdf as string, authHash, wrapped, version, codeEnc, device, at, ); return { kind, created_at: new Date(at).toISOString() }; } /** Only a device that holds the vault takes a way back in away, as only one sets it: a device in by SMS alone (a SIM swapped) cannot strip the owner's ways back. */ async function retire(host: RecoveryHost, device: string, kind: Kind): Promise<{ retired: boolean }> { if (!host.holdsVault(device)) refuse(403, "vault_not_held", "only a device that holds the vault retires a way back in"); const had = row(host, kind) !== null; host.sql.exec("DELETE FROM recovery WHERE kind = ?", kind); if (kind === "trusted") { const t = trust(host); host.sql.exec("DELETE FROM recovery_trust"); if (t) await (await host.peerObject(t.helper))?.helpDropped(host.ownerPhone ?? ""); } return { retired: had }; } function fails(host: RecoveryHost, kind: Kind, since: number): { n: number; oldest: number | null } { const r = host.sql.exec<{ n: number; oldest: number | null }>("SELECT COUNT(*) AS n, MIN(at) AS oldest FROM recovery_try WHERE kind = ? AND ok = 0 AND at > ?", kind, since).one(); return { n: Number(r.n), oldest: r.oldest === null ? null : Number(r.oldest) }; } async function open(host: RecoveryHost, device: string, body: Record): Promise { const kind = kindOf(body.kind); const now = host.now(); host.sql.exec("DELETE FROM recovery_try WHERE at < ?", now - DAY); const hour = fails(host, kind, now - HOUR); const day = fails(host, kind, now - DAY); if (hour.n >= FAILS_PER_HOUR || day.n >= FAILS_PER_DAY) { const until = day.n >= FAILS_PER_DAY ? (day.oldest ?? now) + DAY : (hour.oldest ?? now) + HOUR; const retryAfter = Math.max(1, Math.ceil((until - now) / 1000)); return json({ code: "recovery_wait", message: "Too many tries. Wait a while, then try again.", retry_after: retryAfter }, 429, { "retry-after": String(retryAfter) }); } const r = row(host, kind); if (!r) refuse(404, "recovery_none", kind === "code" ? "No recovery code is set for this account." : "No key is kept in this phone's account store."); const auth = body.auth; if (typeof auth !== "string" || !B64URL.test(auth) || auth.length !== 43) refuse(400, "bad_auth", "auth is the 32-byte auth key, base64url"); const ok = constantTimeEqual(await sha256Hex(fromBase64Url(auth)), r.auth_hash); host.sql.exec("INSERT INTO recovery_try (at, kind, device, ok) VALUES (?, ?, ?, ?)", now, kind, device, ok ? 1 : 0); if (!ok) { const left = Math.max(0, Math.min(FAILS_PER_HOUR - hour.n - 1, FAILS_PER_DAY - day.n - 1)); return json({ code: "recovery_wrong", message: kind === "code" ? "That code does not open this account." : "That key does not open this account.", tries_left: left }, 403); } host.sql.exec("INSERT OR REPLACE INTO recovery_grant (device, until) VALUES (?, ?)", device, now + GRANT_MS); return json({ wrapped: r.wrapped, vmk_version: r.vmk_version }); } interface Trust { helper: string; helper_name: string | null; share: string; gone_at: number | null; [key: string]: SqlStorageValue; } function trust(host: Pick): Trust | null { return host.sql.exec("SELECT helper, helper_name, share, gone_at FROM recovery_trust WHERE id = 1").toArray()[0] ?? null; } const DEVICE_KEY = /^[A-Za-z0-9_-]{43}$/; /** A 32-byte nonce or commit, base64url. */ const NONCE = DEVICE_KEY; /** An ask's id as a new-flow device mints it (it is in the commit, so it exists before the ask). */ const ASK_ID = /^[A-Za-z0-9_-]{16,64}$/; /** * The two flows (TRUSTED RECOVERY BUILD 2, review H1). Flow 1 is what the store's builds before BUILD 1 send: an ask * with no commit and the device key's fingerprint as `code`, and a helper's answer with no compare. Flow 2 sends * `flow=2` on the query of every call and compares six digits. Both are served until the owner retires flow 1: * - an old device and an old helper: exactly as before (the helper sees `code`, answers with no compare); * - a new device and an old helper: the ask carries a commit AND `code`; the old helper answers as before; * - an old device and a new helper: the new helper's phone sees `flow: 1` and never approves (no downgrade); * - both new: the compare, as BUILD 1. * The server never decides that a new helper may skip the digits: the helper's phone does not, whatever is sent. */ export type Flow = 1 | 2; export function flowOf(url: URL): Flow { return url.searchParams.get("flow") === "2" ? 2 : 1; } /** Which flow each device of this person last spoke, for the owner's count of when flow 1 can go. */ export function noteFlow(sql: SqlStorage, device: string, flow: Flow, now: number): void { sql.exec("INSERT INTO recovery_flow_seen (device, flow, at) VALUES (?, ?, ?) ON CONFLICT (device) DO UPDATE SET flow = excluded.flow, at = excluded.at", device, flow, now); } /** Whose recovery a compare is for (crates/cotton-core recovery_code.rs `HelpFor`). */ export interface HelpFor { account: string; setup: string; index: number; request: string; } /** The one-helper scheme's setup, for `HelpFor`. */ export const TRUSTED_SETUP = "trusted"; /** What a new device commits to: the SHA-256 of the domain, whose recovery, its key and its nonce (crates/cotton-core `help_commit`). */ export async function helpCommit(at: HelpFor, deviceKey: string, nonce: string): Promise { const enc = new TextEncoder(); const index = new Uint8Array(4); new DataView(index.buffer).setUint32(0, at.index); const parts: number[] = [...enc.encode("cotton-help-commit-v2")]; for (const field of [enc.encode(at.account), enc.encode(at.setup), index, enc.encode(at.request)]) { const len = new Uint8Array(4); new DataView(len.buffer).setUint32(0, field.length); parts.push(...len, ...field); } parts.push(...fromBase64Url(deviceKey), ...fromBase64Url(nonce)); return toBase64Url(new Uint8Array(await crypto.subtle.digest("SHA-256", new Uint8Array(parts)))); } /** A new device of this person asks their trusted person for help. */ async function ask(host: RecoveryHost, device: string, body: Record, flow: Flow): Promise<{ id: string; name: string }> { const t = trust(host); if (!t || !row(host, "trusted")) refuse(404, "help_none", "Nobody is set to help you back in."); if (t.gone_at) refuse(410, "help_gone", `${helperShown(host, t, device) || "Your helper"} can no longer help you back in.`); const key = body.device_key; if (typeof key !== "string" || !DEVICE_KEY.test(key)) refuse(400, "bad_device_key", "device_key is this device's vault key, 32 bytes base64url"); // The fingerprint an old helper's phone shows (flow 1), sent by both flows' devices. const code = typeof body.code === "string" ? body.code.slice(0, 40) : ""; let commit: string | null = null; let id: string = crypto.randomUUID(); if (flow === 2) { if (typeof body.commit !== "string" || !NONCE.test(body.commit)) refuse(400, "bad_commit", "commit is the 32-byte commit to this device's key and nonce, base64url"); if (typeof body.id !== "string" || !ASK_ID.test(body.id)) refuse(400, "bad_id", "id is the ask's id this device minted"); if (host.sql.exec("SELECT 1 FROM recovery_help_ask WHERE id = ?", body.id).toArray().length) refuse(409, "help_id_used", "That ask was made already."); commit = body.commit; id = body.id; } const now = host.now(); const today = host.sql.exec<{ n: number }>("SELECT COUNT(*) AS n FROM recovery_help_ask WHERE at > ?", now - ASK_MS).one(); if (Number(today.n) >= ASKS_PER_DAY) refuse(429, "help_wait", "Too many asks today. Try again tomorrow."); host.sql.exec( "INSERT INTO recovery_help_ask (id, device, device_key, code, name, state, sealed, at, commit_hash, flow) VALUES (?, ?, ?, ?, ?, 'asked', NULL, ?, ?, ?)", id, device, key, code, typeof body.name === "string" ? body.name.slice(0, 80) : null, now, commit, flow, ); const theirs = await host.peerObject(t.helper); if (theirs) await theirs.helpAsked(host.ownerPhone ?? "", { id, device_key: key, code, ...(commit ? { commit } : {}) }); return { id, name: helperShown(host, t, device) }; } /** Where this device's latest ask stands; once approved, both halves for it alone. */ function asked(host: RecoveryHost, device: string): Record { const t = trust(host); const r = latestAsk(host, device); const name = t ? helperShown(host, t, device) : ""; if (!r) return { state: "none", name }; if (r.state === "asked" && r.nonce_b) return { state: r.reveal ? "compare" : "opened", name, nonce_b: r.nonce_b }; if (r.state !== "approved" || !r.sealed || !t) return { state: r.state, name }; return { state: "approved", name, sealed: r.sealed, share: t.share }; } interface AskRow { id: string; device_key: string; state: string; sealed: string | null; at: number; commit_hash: string | null; nonce_b: string | null; reveal: string | null; [key: string]: SqlStorageValue; } /** This device's latest ask still inside its day, or null. */ function latestAsk(host: RecoveryHost, device: string): AskRow | null { const r = host.sql.exec("SELECT id, device_key, state, sealed, at, commit_hash, nonce_b, reveal FROM recovery_help_ask WHERE device = ? ORDER BY at DESC LIMIT 1", device).toArray()[0]; return r && Number(r.at) >= host.now() - ASK_MS ? r : null; } /** The asking device reveals its nonce, once the helper's is set: it must hash to its commit. Carried to the helper's object. */ async function reveal(host: RecoveryHost, device: string, body: Record): Promise<{ ok: true }> { const r = latestAsk(host, device); if (!r || r.state !== "asked") refuse(404, "help_not_waiting", "That ask is no longer waiting."); if (!r.nonce_b) refuse(409, "help_not_opened", "Your helper has not opened your ask yet."); const nonce = body.nonce; const at = { account: host.ownerPhone ?? "", setup: TRUSTED_SETUP, index: 0, request: r.id }; if (typeof nonce !== "string" || !NONCE.test(nonce) || !r.commit_hash || (await helpCommit(at, r.device_key, nonce)) !== r.commit_hash) refuse(400, "wrong_reveal", "That does not match what this device committed to."); if (r.reveal && r.reveal !== nonce) refuse(409, "help_revealed", "This ask was revealed already."); host.sql.exec("UPDATE recovery_help_ask SET reveal = ? WHERE id = ?", nonce, r.id); const t = trust(host); const theirs = t ? await host.peerObject(t.helper) : null; if (theirs) await theirs.helpRevealed(host.ownerPhone ?? "", { id: r.id, nonce }); return { ok: true }; } /** The helper's phone sets its nonce on an ask, once; a later one answers the first. Carried to the asker's object. */ async function opening(host: RecoveryHost, body: Record): Promise<{ nonce: string }> { const id = typeof body.id === "string" ? body.id : refuse(400, "bad_id", "id: the ask's id"); const r = host.sql.exec<{ peer: string; state: string; nonce_b: string | null; commit_hash: string | null }>("SELECT peer, state, nonce_b, commit_hash FROM recovery_help_in WHERE id = ?", id).toArray()[0]; if (!r || r.state !== "asked") refuse(404, "help_not_waiting", "That ask is no longer waiting."); if (!r.commit_hash) refuse(409, "help_old_flow", "Their new device runs an earlier Cotton: it cannot be checked by the six digits."); if (r.nonce_b) return { nonce: r.nonce_b }; const nonce = body.nonce; if (typeof nonce !== "string" || !NONCE.test(nonce)) refuse(400, "bad_nonce", "nonce is 32 bytes, base64url"); host.sql.exec("UPDATE recovery_help_in SET nonce_b = ? WHERE id = ?", nonce, id); const theirs = await host.peerObject(r.peer); if (theirs) await theirs.helpOpened(host.ownerPhone ?? "", { id, nonce }); return { nonce }; } /** * On the trusted person's object: the asks waiting now, each with the half kept for the person asking. Flow 1 (an * earlier build's phone) gets the shape it always had, `code` the fingerprint to compare; flow 2 gets the compare's * fields, and `flow: 1` on an ask from an earlier build's device, which its phone shows and never approves. */ function asksIn(host: RecoveryHost, flow: Flow): { asks: Record[] } { const since = host.now() - ASK_MS; const rows = host.sql .exec<{ id: string; peer: string; device_key: string; code: string; commit_hash: string | null; nonce_b: string | null; reveal: string | null; box: string | null }>( "SELECT i.id, i.peer, i.device_key, i.code, i.commit_hash, i.nonce_b, i.reveal, h.box FROM recovery_help_in i LEFT JOIN recovery_help_held h ON h.peer = i.peer WHERE i.state = 'asked' AND i.at > ? ORDER BY i.at", since, ) .toArray() .filter((r) => r.box); if (flow === 1) return { asks: rows.map((r) => ({ id: r.id, peer: r.peer, code: r.code, device_key: r.device_key, box: r.box })) }; return { asks: rows.map((r) => r.commit_hash ? { id: r.id, peer: r.peer, device_key: r.device_key, commit: r.commit_hash, ...(r.nonce_b ? { nonce_b: r.nonce_b } : {}), ...(r.reveal ? { reveal: r.reveal } : {}), box: r.box } : { id: r.id, peer: r.peer, device_key: r.device_key, flow: 1, box: r.box }, ), }; } /** * The trusted person's phone answers an ask: carried to the asker's object. Flow 2 answers only a compared ask; flow 1 * (an earlier build's phone, which cannot compare) answers as it always did, and the answer is marked `legacy`. */ async function answer(host: RecoveryHost, body: Record, flow: Flow): Promise<{ ok: true }> { const id = typeof body.id === "string" ? body.id : refuse(400, "bad_id", "id: the ask's id"); const r = host.sql.exec<{ peer: string; state: string; reveal: string | null }>("SELECT peer, state, reveal FROM recovery_help_in WHERE id = ?", id).toArray()[0]; if (!r || r.state !== "asked") refuse(404, "help_not_waiting", "That ask is no longer waiting."); const decline = body.decline === true; if (!decline && flow === 2 && !r.reveal) refuse(409, "help_not_compared", "Compare the code on their new device first."); const sealed = body.sealed; if (!decline && (typeof sealed !== "string" || sealed.length > 400 || !/^[A-Za-z0-9_:.-]+$/.test(sealed))) refuse(400, "bad_sealed", "sealed is the half wrapped to the asking device's key"); host.sql.exec("UPDATE recovery_help_in SET state = ? WHERE id = ?", decline ? "declined" : "approved", id); const theirs = await host.peerObject(r.peer); if (theirs) await theirs.helpAnswered(host.ownerPhone ?? "", decline ? { id, decline: true } : { id, sealed: sealed as string, ...(flow === 1 ? { legacy: true } : {}) }); return { ok: true }; } /** Another object hands this person the half kept for one of their people: kept only from one of their people. */ export async function helpKept(host: RecoveryHost, from: string, box: string): Promise { if (typeof box !== "string" || !box.startsWith("p1:") || box.length > 400 || !(await host.isPeer(from))) return false; host.sql.exec("INSERT OR REPLACE INTO recovery_help_held (peer, box, at) VALUES (?, ?, ?)", from, box, host.now()); return true; } /** One of this person's people asks for help from a new device: with a commit (flow 2) or without (flow 1). */ export async function helpAsked(host: RecoveryHost, from: string, a: { id: string; device_key: string; code?: string; commit?: string }): Promise { if (!(await host.isPeer(from)) || typeof a?.id !== "string" || a.id.length > 64 || !DEVICE_KEY.test(a.device_key ?? "")) return; if (a.commit !== undefined && !NONCE.test(a.commit)) return; if (!host.sql.exec("SELECT 1 FROM recovery_help_held WHERE peer = ?", from).toArray().length) return; host.sql.exec( "INSERT OR IGNORE INTO recovery_help_in (id, peer, device_key, code, state, at, commit_hash, flow) VALUES (?, ?, ?, ?, 'asked', ?, ?, ?)", a.id, from, a.device_key, typeof a.code === "string" ? a.code.slice(0, 40) : "", host.now(), a.commit ?? null, a.commit ? 2 : 1, ); } /** The person this one trusts set their nonce on an ask: kept only from them, once, for an ask still waiting. */ export function helpOpened(host: RecoveryHost, from: string, o: { id: string; nonce: string }): void { const t = trust(host); if (!t || t.helper !== from || typeof o?.id !== "string" || !NONCE.test(o.nonce ?? "")) return; host.sql.exec("UPDATE recovery_help_ask SET nonce_b = ? WHERE id = ? AND state = 'asked' AND nonce_b IS NULL AND commit_hash IS NOT NULL", o.nonce, o.id); } /** The asking device revealed its nonce: kept only from the person who asked, once, if it hashes to the commit. */ export async function helpRevealed(host: RecoveryHost, from: string, r: { id: string; nonce: string }): Promise { if (typeof r?.id !== "string" || !NONCE.test(r.nonce ?? "")) return; const row = host.sql.exec<{ peer: string; device_key: string; commit_hash: string | null; nonce_b: string | null; reveal: string | null; state: string }>( "SELECT peer, device_key, commit_hash, nonce_b, reveal, state FROM recovery_help_in WHERE id = ?", r.id, ).toArray()[0]; if (!row || row.peer !== from || row.state !== "asked" || !row.nonce_b || row.reveal || !row.commit_hash) return; if ((await helpCommit({ account: from, setup: TRUSTED_SETUP, index: 0, request: r.id }, row.device_key, r.nonce)) !== row.commit_hash) return; host.sql.exec("UPDATE recovery_help_in SET reveal = ? WHERE id = ?", r.nonce, r.id); } /** The trusted person answered: kept only from the person this one trusts, for an ask still waiting; compared, or from an earlier build's phone (`legacy`). */ export function helpAnswered(host: RecoveryHost, from: string, a: { id: string; sealed?: string; decline?: boolean; legacy?: boolean }): void { const t = trust(host); if (!t || t.helper !== from) return; const r = host.sql.exec<{ state: string; reveal: string | null }>("SELECT state, reveal FROM recovery_help_ask WHERE id = ?", a.id).toArray()[0]; if (!r || r.state !== "asked") return; if (!a.decline && !r.reveal && a.legacy !== true) return; if (a.decline) host.sql.exec("UPDATE recovery_help_ask SET state = 'declined' WHERE id = ?", a.id); else if (typeof a.sealed === "string" && a.sealed.length <= 400) host.sql.exec("UPDATE recovery_help_ask SET state = 'approved', sealed = ? WHERE id = ?", a.sealed, a.id); } /** * What this person's object tells the directory for the owner's count (`GET /v1/admin/recovery/flows`): whether a * one-helper setup stands, and how many of their devices last spoke each flow in the last 60 days. Counts only. */ export function flowReport(host: Pick): { old_setup: boolean; flow1: number; flow2: number } { const since = host.now() - 60 * DAY; const by = (flow: number) => Number(host.sql.exec<{ n: number }>("SELECT COUNT(*) AS n FROM recovery_flow_seen WHERE flow = ? AND at > ?", flow, since).one().n); return { old_setup: row(host as RecoveryHost, "trusted") !== null, flow1: by(1), flow2: by(2) }; } /** Whether [device] opened a way back in within GRANT_MS: it may put a wrap on its own vault_key row though another device holds one. */ export function granted(sql: SqlStorage, device: string, now: number): boolean { const r = sql.exec<{ until: number }>("SELECT until FROM recovery_grant WHERE device = ?", device).toArray()[0]; return r !== undefined && Number(r.until) > now; } async function sha256Hex(bytes: Uint8Array): Promise { const digest = new Uint8Array(await crypto.subtle.digest("SHA-256", bytes)); return [...digest].map((b) => b.toString(16).padStart(2, "0")).join(""); } function constantTimeEqual(a: string, b: string): boolean { if (a.length !== b.length) return false; let diff = 0; for (let i = 0; i < a.length; i++) diff |= a.charCodeAt(i) ^ b.charCodeAt(i); return diff === 0; } function toBase64Url(bytes: Uint8Array): string { return btoa(String.fromCharCode(...bytes)).replace(/\+/g, "-").replace(/\//g, "_").replace(/=+$/, ""); } function fromBase64Url(text: string): Uint8Array { const b64 = text.replace(/-/g, "+").replace(/_/g, "/"); const bin = atob(b64 + "=".repeat((4 - (b64.length % 4)) % 4)); const out = new Uint8Array(bin.length); for (let i = 0; i < bin.length; i++) out[i] = bin.charCodeAt(i); return out; } /** * TRUSTED RECOVERY BUILD 1, step 2: a way back in never dies silently. This person and `number` stopped being each * other's people (removed or blocked, on either side: src/chat/chat.ts `decide` calls the host's `forget`). If this * person helps `number`, the half kept for them goes and `number`'s object is told (`helpGone`); if `number` helps this * person, the way back in through them is marked gone (said on every device's status) and their object lets the half go. */ export async function forgetPerson(host: RecoveryHost, number: string): Promise { // Everything here first (BUILD 3, LOW): Remove and Block always complete; the other object is told after, and a // telling that fails is kept in recovery_tell (src/recovery_circle.ts makes the table) and tried again (`retryTells`). const tells: ("helpGone" | "helpDropped")[] = []; if (host.sql.exec("SELECT 1 FROM recovery_help_held WHERE peer = ?", number).toArray().length) { host.sql.exec("DELETE FROM recovery_help_held WHERE peer = ?", number); host.sql.exec("DELETE FROM recovery_help_in WHERE peer = ?", number); tells.push("helpGone"); } const t = trust(host); if (t && t.helper === number && !t.gone_at) { host.sql.exec("UPDATE recovery_trust SET gone_at = ? WHERE id = 1", host.now()); tells.push("helpDropped"); } for (const kind of tells) { try { await tellPeer(host, kind, number); } catch (error) { console.error("cottondb: recovery: another object was not told; kept to try again", error instanceof Error ? error.message : "unknown"); host.sql.exec("INSERT INTO recovery_tell (kind, target, payload, tries, next_at) VALUES (?, ?, '{}', 0, ?)", kind, number, host.now() + 60_000); } } } async function tellPeer(host: RecoveryHost, kind: string, number: string): Promise { const peer = await host.peerObject(number); if (kind === "helpGone") await peer?.helpGone(host.ownerPhone ?? ""); else await peer?.helpDropped(host.ownerPhone ?? ""); } /** The one-helper scheme's tellings kept, tried again with a growing wait; after twelve tries one is let go. */ export async function retryTells(host: RecoveryHost): Promise { const due = host.sql.exec<{ id: number; kind: string; target: string; tries: number }>("SELECT id, kind, target, tries FROM recovery_tell WHERE kind LIKE 'help%' AND next_at <= ? ORDER BY id LIMIT 20", host.now()).toArray(); for (const r of due) { try { await tellPeer(host, r.kind, r.target); host.sql.exec("DELETE FROM recovery_tell WHERE id = ?", r.id); } catch { const tries = Number(r.tries) + 1; if (tries > 12) host.sql.exec("DELETE FROM recovery_tell WHERE id = ?", r.id); else host.sql.exec("UPDATE recovery_tell SET tries = ?, next_at = ? WHERE id = ?", tries, host.now() + Math.min(24 * 3_600_000, 60_000 * 2 ** tries), r.id); } } } /** The helper `from` can help this person no more: the way back in through them is marked gone. */ export function helpGone(host: RecoveryHost, from: string): void { host.sql.exec("UPDATE recovery_trust SET gone_at = ? WHERE id = 1 AND helper = ? AND gone_at IS NULL", host.now(), from); } /** The person `from` no longer counts on this one: the half kept for them, and their asks, go. */ export function helpDropped(host: RecoveryHost, from: string): void { host.sql.exec("DELETE FROM recovery_help_held WHERE peer = ?", from); host.sql.exec("DELETE FROM recovery_help_in WHERE peer = ?", from); } /** A short id for a number in an erase receipt: never the number itself. */ export async function shortId(number: string): Promise { const d = new Uint8Array(await crypto.subtle.digest("SHA-256", new TextEncoder().encode(`cotton-recovery-receipt:${number}`))); return Array.from(d.slice(0, 6), (b) => b.toString(16).padStart(2, "0")).join(""); } /** * The account is being erased (src/account_delete.ts, the directory step, while the number is still this database's): * each person this one helps is told (`helpGone`), and this person's helper lets their half go (`helpDropped`). Each is * asked on its own; a row goes only once its person took word. Answers the short ids of those not told (the erase asks * again with its back-off, and after a day records them in the receipt; it never stalls). */ export async function leave(host: RecoveryHost): Promise { const me = host.ownerPhone ?? ""; const notTold: string[] = []; for (const { peer } of host.sql.exec<{ peer: string }>("SELECT peer FROM recovery_help_held").toArray()) { try { await (await host.peerObject(peer))?.helpGone(me); host.sql.exec("DELETE FROM recovery_help_held WHERE peer = ?", peer); host.sql.exec("DELETE FROM recovery_help_in WHERE peer = ?", peer); } catch (error) { console.error("cottondb: account delete: a person helped back in did not take word", error instanceof Error ? error.message : "unknown"); notTold.push(await shortId(peer)); } } const t = trust(host); if (t) { try { await (await host.peerObject(t.helper))?.helpDropped(me); host.sql.exec("DELETE FROM recovery_trust"); } catch (error) { console.error("cottondb: account delete: the helper did not take word", error instanceof Error ? error.message : "unknown"); notTold.push(await shortId(t.helper)); } } return notTold; }