/** * The IP allowlist, the personal object's second lock (sealing plan §6). * * WHAT IT LOCKS. `/v1/admin/*`, `/v1/import/*`, the importer's `PUT`/`HEAD` * of `/v1/media/*`, and `/mcp` for every token the owner minted (owner, * coordinator, lane and the rest). An OAuth connector's token is not locked: * nobody has checked that the connector calls from fixed addresses (plan Q20). * Phone routes are never locked, because a phone's address changes. * * THE LIST. An internal table of the object, never synced and never in `rows`. * An empty list locks nothing, which is how every object starts: nothing live * changes until the owner sets one. The address checked is * `CF-Connecting-IP`, which only Cloudflare sets on a request to a Worker. * * CHANGING IT. `POST /v1/allowlist` takes the whole new list and a statement * signed by the person key (Ed25519, behind Face ID on the phone): * * "cotton-allowlist-v1\n" database_id "\n" sha256hex(canonical list) "\n" nonce "\n" issued_at * * The canonical list is the JSON array of `{"cidr","label"}` sorted by cidr, * each cidr already canonical (see `canonicalCidr`). The statement must be * issued within 5 minutes of the Worker's clock and its nonce is used once. * The route itself is never locked, so a phone can always undo a lockout: * the signature is its guard. * * The statement is a local copy until seal-core (L1) lands its Rust twin and * shared vectors; the bytes here are the plan's. */ import { refuse, sha256Hex } from "./http.ts"; import { fromBase64Url } from "./vault.ts"; export const SCHEMA = ` CREATE TABLE IF NOT EXISTS allowlist (cidr TEXT PRIMARY KEY, label TEXT NOT NULL, added_at TEXT NOT NULL, added_by_fp TEXT NOT NULL); CREATE TABLE IF NOT EXISTS allowlist_nonce (nonce TEXT PRIMARY KEY, seen_at TEXT NOT NULL); `; /** The kit table the person key's public half is read from: the row whose id is the fingerprint, its `public_key` base64url (the phone publishes it from its cotton_person_keys). */ export const PERSON_KEY_TABLE = "person_key"; const STATEMENT_TAG = "cotton-allowlist-v1"; const FRESH_MS = 5 * 60_000; const NONCE = /^[A-Za-z0-9_-]{16,64}$/; const MAX_ENTRIES = 64; export interface Entry { cidr: string; label: string; } export interface HeldEntry extends Entry { added_at: string; added_by_fp: string; } // ── addresses ──────────────────────────────────────────────────────────── interface Address { v: 4 | 6; n: bigint; } function parseV4(text: string): bigint | null { const parts = text.split("."); if (parts.length !== 4) return null; let n = 0n; for (const p of parts) { if (!/^(0|[1-9][0-9]{0,2})$/.test(p) || Number(p) > 255) return null; n = (n << 8n) | BigInt(p); } return n; } function parseV6(text: string): bigint | null { const halves = text.toLowerCase().split("::"); if (halves.length > 2) return null; const groups = (s: string): string[] | null => (s === "" ? [] : s.split(":")); const head = groups(halves[0]!); const tail = halves.length === 2 ? groups(halves[1]!) : []; if (!head || !tail) return null; const missing = 8 - head.length - tail.length; if (halves.length === 2 ? missing < 1 : missing !== 0) return null; let n = 0n; for (const g of [...head, ...Array(halves.length === 2 ? missing : 0).fill("0"), ...tail]) { if (!/^[0-9a-f]{1,4}$/.test(g)) return null; n = (n << 16n) | BigInt(`0x${g}`); } return n; } function parseAddress(text: string): Address | null { const v4 = parseV4(text); if (v4 !== null) return { v: 4, n: v4 }; const v6 = text.includes(":") ? parseV6(text) : null; return v6 === null ? null : { v: 6, n: v6 }; } function formatV6(n: bigint): string { const g = Array.from({ length: 8 }, (_, i) => Number((n >> BigInt(16 * (7 - i))) & 0xffffn)); // RFC 5952: the longest run of two or more zero groups becomes "::", the first one on a tie. let best = -1; let bestLen = 1; for (let i = 0; i < 8; ) { if (g[i] !== 0) { i++; continue; } let j = i; while (j < 8 && g[j] === 0) j++; if (j - i > bestLen) [best, bestLen] = [i, j - i]; i = j; } const hex = g.map((x) => x.toString(16)); if (best < 0) return hex.join(":"); return `${hex.slice(0, best).join(":")}::${hex.slice(best + bestLen).join(":")}`; } function bits(v: 4 | 6): number { return v === 4 ? 32 : 128; } /** A cidr in its one spelling (`203.0.113.0/24`, `2001:db8::/32`, a lone address with its full prefix), or null when it is not one. Host bits must be zero. */ export function canonicalCidr(text: string): string | null { const m = /^([^/]+)(?:\/([0-9]{1,3}))?$/.exec(text.trim()); if (!m) return null; const address = parseAddress(m[1]!); if (!address) return null; const width = bits(address.v); const prefix = m[2] === undefined ? width : Number(m[2]); if (prefix > width) return null; const host = width - prefix; if (host > 0 && address.n & ((1n << BigInt(host)) - 1n)) return null; return `${address.v === 4 ? m[1]!.split(".").map(Number).join(".") : formatV6(address.n)}/${prefix}`; } function contains(cidr: string, ip: Address): boolean { const [net, p] = cidr.split("/") as [string, string]; const network = parseAddress(net); if (!network || network.v !== ip.v) return false; const shift = BigInt(bits(ip.v) - Number(p)); return network.n >> shift === ip.n >> shift; } /** Whether `ip` may pass `list`: every address passes an empty list; an address that cannot be read passes no other. */ export function allows(list: readonly Entry[], ip: string | null): boolean { if (!list.length) return true; const address = ip ? parseAddress(ip.trim()) : null; return address !== null && list.some((e) => contains(e.cidr, address)); } // ── the statement ─────────────────────────────────────────────────────── /** The list's one serialisation: `{"cidr","label"}` entries sorted by cidr, no spaces. */ export function canonicalList(list: readonly Entry[]): string { const sorted = [...list].sort((a, b) => (a.cidr < b.cidr ? -1 : a.cidr > b.cidr ? 1 : 0)); return JSON.stringify(sorted.map((e) => ({ cidr: e.cidr, label: e.label }))); } /** The exact text the person key signs for a change of the list. */ export async function statement(databaseId: string, list: readonly Entry[], nonce: string, issuedAt: string): Promise { return [STATEMENT_TAG, databaseId, await sha256Hex(canonicalList(list)), nonce, issuedAt].join("\n"); } // ── the object's side ─────────────────────────────────────────────────── export function held(sql: SqlStorage): HeldEntry[] { return sql.exec<{ cidr: string; label: string; added_at: string; added_by_fp: string }>("SELECT cidr, label, added_at, added_by_fp FROM allowlist ORDER BY cidr").toArray(); } /** Refuses a request whose address is not on a non-empty list, naming the address seen. */ export function guard(sql: SqlStorage, request: Request): void { const list = held(sql); const ip = request.headers.get("cf-connecting-ip"); if (!allows(list, ip)) refuse(403, "address_not_allowed", `This address (${ip ?? "unknown"}) is not on this database's allowlist. Change the list from Cotton on the phone.`); } function readEntries(value: unknown): Entry[] { if (!Array.isArray(value)) refuse(400, "bad_list", "list is a list of { cidr, label }"); if (value.length > MAX_ENTRIES) refuse(400, "bad_list", `a list holds at most ${MAX_ENTRIES} entries`); const seen = new Set(); return value.map((raw) => { const e = raw as Record | null; if (!e || typeof e !== "object" || typeof e.cidr !== "string" || typeof e.label !== "string") refuse(400, "bad_list", "list is a list of { cidr, label }"); const cidr = canonicalCidr(e.cidr); if (!cidr) refuse(400, "bad_cidr", `${JSON.stringify(e.cidr)} is not an address or a cidr with its host bits zero`); if (cidr !== e.cidr) refuse(400, "bad_cidr", `${JSON.stringify(e.cidr)} is spelt ${JSON.stringify(cidr)}: the signed list names each cidr in its one spelling`); if (seen.has(cidr)) refuse(400, "bad_list", `${cidr} is named twice`); seen.add(cidr); const label = e.label; if (!label.trim() || label.length > 60 || /[\n\r]/.test(label)) refuse(400, "bad_label", "a label is one line of 1 to 60 characters"); return { cidr, label }; }); } async function verify(publicKey: string, signature: string, text: string): Promise { let pub: Uint8Array; let sig: Uint8Array; try { pub = fromBase64Url(publicKey); sig = fromBase64Url(signature); } catch { return false; } if (pub.length !== 32 || sig.length !== 64) return false; const key = await crypto.subtle.importKey("raw", pub, { name: "Ed25519" }, false, ["verify"]); return crypto.subtle.verify({ name: "Ed25519" }, key, sig, new TextEncoder().encode(text)); } export interface ChangeHost { sql: SqlStorage; databaseId: string; /** The person key's public half (base64url) under this fingerprint, or null. */ personKey(fingerprint: string): string | null; now: Date; transact(fn: () => T): T; } /** `POST /v1/allowlist { list, nonce, issued_at, signer, sig }`: replaces the whole list once the person key's signature holds. */ export async function change(host: ChangeHost, body: Record): Promise { const list = readEntries(body.list); const { nonce, issued_at: issuedAt, signer, sig } = body; if (typeof nonce !== "string" || !NONCE.test(nonce)) refuse(400, "bad_nonce", "nonce is 16 to 64 base64url characters"); if (typeof issuedAt !== "string" || Number.isNaN(Date.parse(issuedAt))) refuse(400, "bad_issued_at", "issued_at is an ISO 8601 time"); if (typeof signer !== "string" || !signer) refuse(400, "bad_signer", "signer is the person key's fingerprint"); if (typeof sig !== "string" || !sig) refuse(400, "bad_sig", "sig is the Ed25519 signature, base64url"); if (Math.abs(host.now.getTime() - Date.parse(issuedAt)) > FRESH_MS) refuse(403, "stale_statement", "the statement was not issued within 5 minutes of now: sign the change again"); const publicKey = host.personKey(signer); if (!publicKey) refuse(409, "no_person_key", `this database holds no person key ${signer} to check the change against`); if (!(await verify(publicKey, sig, await statement(host.databaseId, list, nonce, issuedAt)))) refuse(403, "bad_signature", "the signature does not hold for this list under the person key"); const now = host.now.toISOString(); return host.transact(() => { host.sql.exec("DELETE FROM allowlist_nonce WHERE seen_at < ?", new Date(host.now.getTime() - 2 * FRESH_MS).toISOString()); if (host.sql.exec("SELECT 1 FROM allowlist_nonce WHERE nonce = ?", nonce).toArray().length) refuse(403, "nonce_used", "this statement was used already: sign the change again"); host.sql.exec("INSERT INTO allowlist_nonce (nonce, seen_at) VALUES (?, ?)", nonce, now); const before = new Map(held(host.sql).map((e) => [e.cidr, e])); host.sql.exec("DELETE FROM allowlist"); for (const e of list) { const kept = before.get(e.cidr); host.sql.exec("INSERT INTO allowlist (cidr, label, added_at, added_by_fp) VALUES (?, ?, ?, ?)", e.cidr, e.label, kept?.added_at ?? now, kept?.added_by_fp ?? signer); } return held(host.sql); }); }