313 lines · 15.4 KB · TypeScriptRaw
/** * A Cotton-account passkey (owner, 17 Nov 2026: after "approve from a signed-in * app", a passkey; SMS stays for the first device and for recovery). The open * host is the WebAuthn relying party: `cottondb.com` on production, the * Worker's own host on development. Only ES256, user verification required, * attestation `none`: Cotton trusts the signed-in device that adds a passkey, * not an attestation chain. * * On the person's object, for a device signed in with its own credential: * * POST /v1/passkeys/options → { request } (PublicKeyCredentialCreationOptions, base64url fields) * POST /v1/passkeys { response, name? } → { id, name, created_at } * GET /v1/passkeys → { passkeys: [{ id, name, created_at, last_used_at }] } * POST /v1/passkeys/remove { id } → { ok: true } * * On the open host, signed out, no number typed (a discoverable passkey's * user handle is the database id): * * POST /v1/passkey/begin → { challenge_id, request } (PublicKeyCredentialRequestOptions) * POST /v1/passkey/sign-in { challenge_id, device_id, device_name?, response } * → { credential, person, version, expires_in, database_id, host } * * Every challenge is single use and lives CHALLENGE_SECONDS. An unknown * passkey, a wrong signature, a wrong origin and a spent challenge are all * refused the same way (`passkey_refused`), so nothing says which passkeys * exist. Origins: `https://<rp host>` and each Android app origin * (`android:apk-key-hash:…`) in the var PASSKEY_ANDROID_ORIGINS; the open host * serves `/.well-known/assetlinks.json` from ANDROID_ASSET_LINKS. */import { fromBase64Url } from "./vault.ts";export const CHALLENGE_SECONDS = 300;export const RP_NAME = "Cotton";/** COSE algorithm ES256. */export const ES256 = -7;export type Refusal = { status: number; code: string; message: string };export const REFUSED: Refusal = { status: 401, code: "passkey_refused", message: "That passkey did not sign in here. Try another way." };export function b64url(bytes: Uint8Array): string { let s = ""; for (const b of bytes) s += String.fromCharCode(b); return btoa(s).replace(/\+/g, "-").replace(/\//g, "_").replace(/=+$/, "");}export function newChallenge(): string { return b64url(crypto.getRandomValues(new Uint8Array(32)));}/** The origins a passkey's clientData may name for this relying party. */export function origins(rpId: string, android: string | undefined): Set<string> { const out = new Set([`https://${rpId}`]); for (const one of (android ?? "").split(",").map((s) => s.trim()).filter(Boolean)) out.add(one); return out;}// ── CBOR, as much as WebAuthn needs ───────────────────────────────────────type Cbor = number | bigint | Uint8Array | string | Cbor[] | Map<Cbor, Cbor> | boolean | null | undefined;export function decodeCbor(bytes: Uint8Array): { value: Cbor; end: number } { let at = 0; const view = new DataView(bytes.buffer, bytes.byteOffset, bytes.byteLength); const length = (info: number): number => { if (info < 24) return info; if (info === 24) return view.getUint8(at++); if (info === 25) { const v = view.getUint16(at); at += 2; return v; } if (info === 26) { const v = view.getUint32(at); at += 4; return v; } if (info === 27) { const v = Number(view.getBigUint64(at)); at += 8; return v; } throw new Error("cbor: indefinite lengths are not taken"); }; const item = (): Cbor => { if (at >= bytes.length) throw new Error("cbor: short"); const head = view.getUint8(at++); const major = head >> 5; const info = head & 31; switch (major) { case 0: return length(info); case 1: return -1 - length(info); case 2: { const n = length(info); const out = bytes.slice(at, at + n); if (out.length !== n) throw new Error("cbor: short"); at += n; return out; } case 3: { const n = length(info); const out = new TextDecoder().decode(bytes.slice(at, at + n)); at += n; return out; } case 4: { const n = length(info); const out: Cbor[] = []; for (let i = 0; i < n; i++) out.push(item()); return out; } case 5: { const n = length(info); const out = new Map<Cbor, Cbor>(); for (let i = 0; i < n; i++) { const k = item(); out.set(k, item()); } return out; } case 7: if (info === 20) return false; if (info === 21) return true; if (info === 22) return null; if (info === 23) return undefined; throw new Error("cbor: floats are not taken"); default: throw new Error("cbor: tags are not taken"); } }; const value = item(); return { value, end: at };}// ── authenticator data ────────────────────────────────────────────────────export interface AuthData { rpIdHash: Uint8Array; up: boolean; uv: boolean; signCount: number; credentialId?: Uint8Array; /** The credential's COSE key as a P-256 JWK's x and y, base64url. */ key?: { x: string; y: string };}export function parseAuthData(bytes: Uint8Array): AuthData { if (bytes.length < 37) throw new Error("authData: short"); const view = new DataView(bytes.buffer, bytes.byteOffset, bytes.byteLength); const flags = bytes[32]!; const out: AuthData = { rpIdHash: bytes.slice(0, 32), up: (flags & 0x01) !== 0, uv: (flags & 0x04) !== 0, signCount: view.getUint32(33) }; if (flags & 0x40) { const idLength = view.getUint16(53); out.credentialId = bytes.slice(55, 55 + idLength); const { value } = decodeCbor(bytes.slice(55 + idLength)); if (!(value instanceof Map)) throw new Error("authData: no key"); // COSE: 1 kty (2 = EC2), 3 alg (-7 = ES256), -1 crv (1 = P-256), -2 x, -3 y. const x = value.get(-2); const y = value.get(-3); if (value.get(1) !== 2 || value.get(3) !== ES256 || value.get(-1) !== 1 || !(x instanceof Uint8Array) || !(y instanceof Uint8Array) || x.length !== 32 || y.length !== 32) throw new Error("authData: not an ES256 key"); out.key = { x: b64url(x), y: b64url(y) }; } return out;}async function sha256(bytes: Uint8Array): Promise<Uint8Array> { return new Uint8Array(await crypto.subtle.digest("SHA-256", bytes));}function equal(a: Uint8Array, b: Uint8Array): boolean { return a.length === b.length && a.every((v, i) => v === b[i]);}interface ClientData { type: string; challenge: string; origin: string;}function clientData(text: string): ClientData { const parsed = JSON.parse(new TextDecoder().decode(fromBase64Url(text))) as ClientData; if (typeof parsed.type !== "string" || typeof parsed.challenge !== "string" || typeof parsed.origin !== "string") throw new Error("clientData: incomplete"); return parsed;}/** An ECDSA signature as DER (what an authenticator sends) to the raw r‖s WebCrypto verifies. */export function derToRaw(der: Uint8Array): Uint8Array { if (der[0] !== 0x30) throw new Error("signature: not DER"); let at = 2; const part = (): Uint8Array => { if (der[at] !== 0x02) throw new Error("signature: not DER"); const n = der[at + 1]!; let bytes = der.slice(at + 2, at + 2 + n); at += 2 + n; while (bytes.length > 32 && bytes[0] === 0) bytes = bytes.slice(1); if (bytes.length > 32) throw new Error("signature: too long"); const out = new Uint8Array(32); out.set(bytes, 32 - bytes.length); return out; }; const r = part(); const s = part(); const raw = new Uint8Array(64); raw.set(r, 0); raw.set(s, 32); return raw;}export interface Registered { credentialId: string; x: string; y: string; signCount: number;}/** A passkey being added: `navigator.credentials.create`'s answer, checked against the challenge this object made. */export async function verifyCreate(response: Record<string, unknown>, challenge: string, rpId: string, allowed: Set<string>): Promise<Registered> { const inner = response.response as Record<string, unknown> | undefined; if (!inner || typeof inner.clientDataJSON !== "string" || typeof inner.attestationObject !== "string") throw new Error("create: incomplete"); const data = clientData(inner.clientDataJSON); if (data.type !== "webauthn.create" || data.challenge !== challenge || !allowed.has(data.origin)) throw new Error("create: not this challenge"); const { value } = decodeCbor(fromBase64Url(inner.attestationObject)); if (!(value instanceof Map)) throw new Error("create: no attestation"); const authData = value.get("authData"); if (!(authData instanceof Uint8Array)) throw new Error("create: no authData"); const parsed = parseAuthData(authData); if (!equal(parsed.rpIdHash, await sha256(new TextEncoder().encode(rpId)))) throw new Error("create: another relying party"); if (!parsed.up || !parsed.uv) throw new Error("create: the person was not verified"); if (!parsed.credentialId || !parsed.key) throw new Error("create: no credential"); return { credentialId: b64url(parsed.credentialId), x: parsed.key.x, y: parsed.key.y, signCount: parsed.signCount };}/** A sign-in: `navigator.credentials.get`'s answer, checked against the challenge and the passkey's stored key. */export async function verifyGet(response: Record<string, unknown>, challenge: string, rpId: string, allowed: Set<string>, key: { x: string; y: string; signCount: number }): Promise<{ signCount: number }> { const inner = response.response as Record<string, unknown> | undefined; if (!inner || typeof inner.clientDataJSON !== "string" || typeof inner.authenticatorData !== "string" || typeof inner.signature !== "string") throw new Error("get: incomplete"); const data = clientData(inner.clientDataJSON); if (data.type !== "webauthn.get" || data.challenge !== challenge || !allowed.has(data.origin)) throw new Error("get: not this challenge"); const authData = fromBase64Url(inner.authenticatorData); const parsed = parseAuthData(authData); if (!equal(parsed.rpIdHash, await sha256(new TextEncoder().encode(rpId)))) throw new Error("get: another relying party"); if (!parsed.up || !parsed.uv) throw new Error("get: the person was not verified"); // A counter that is kept must only rise: one that does not is a copied authenticator. if ((parsed.signCount !== 0 || key.signCount !== 0) && parsed.signCount <= key.signCount) throw new Error("get: the counter went back"); const signed = new Uint8Array(authData.length + 32); signed.set(authData, 0); signed.set(await sha256(fromBase64Url(inner.clientDataJSON)), authData.length); const pub = await crypto.subtle.importKey("jwk", { kty: "EC", crv: "P-256", x: key.x, y: key.y, ext: true }, { name: "ECDSA", namedCurve: "P-256" }, false, ["verify"]); const ok = await crypto.subtle.verify({ name: "ECDSA", hash: "SHA-256" }, pub, derToRaw(fromBase64Url(inner.signature)), signed); if (!ok) throw new Error("get: wrong signature"); return { signCount: parsed.signCount };}// ── the object's half ─────────────────────────────────────────────────────const SCHEMA = `CREATE TABLE IF NOT EXISTS account_passkey ( id TEXT PRIMARY KEY, credential_id TEXT NOT NULL UNIQUE, x TEXT NOT NULL, y TEXT NOT NULL, sign_count INTEGER NOT NULL DEFAULT 0, name TEXT, person_id TEXT NOT NULL, created_by_device TEXT, created_at INTEGER NOT NULL, last_used_at INTEGER, removed_at INTEGER);CREATE TABLE IF NOT EXISTS account_passkey_challenge ( challenge TEXT PRIMARY KEY, device_id TEXT NOT NULL, expires_at INTEGER NOT NULL);`;export type PasskeyRow = { id: string; credential_id: string; x: string; y: string; sign_count: number; name: string | null; person_id: string; created_at: number; last_used_at: number | null;};/** The passkeys of one object, in its own SQLite: auth state, like `sessions`, never a synced table. */export class Passkeys { private readonly sql: SqlStorage; constructor(sql: SqlStorage) { this.sql = sql; sql.exec(SCHEMA); } /** A challenge for one signed-in device to add a passkey with. */ challenge(deviceId: string, now: number): string { this.sql.exec("DELETE FROM account_passkey_challenge WHERE expires_at < ?", now); const challenge = newChallenge(); this.sql.exec("INSERT INTO account_passkey_challenge (challenge, device_id, expires_at) VALUES (?, ?, ?)", challenge, deviceId, now + CHALLENGE_SECONDS); return challenge; } /** Spend the device's challenge the clientData names: true once, for that device, in time. */ spend(challenge: string, deviceId: string, now: number): boolean { return this.sql.exec("DELETE FROM account_passkey_challenge WHERE challenge = ? AND device_id = ? AND expires_at >= ?", challenge, deviceId, now).rowsWritten > 0; } add(row: { credentialId: string; x: string; y: string; signCount: number; name: string | null; personId: string; deviceId: string }, now: number): PasskeyRow { const id = crypto.randomUUID(); this.sql.exec( "INSERT INTO account_passkey (id, credential_id, x, y, sign_count, name, person_id, created_by_device, created_at) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)", id, row.credentialId, row.x, row.y, row.signCount, row.name, row.personId, row.deviceId, now, ); return this.byId(id)!; } byId(id: string): PasskeyRow | undefined { return this.sql.exec<PasskeyRow>("SELECT * FROM account_passkey WHERE id = ? AND removed_at IS NULL", id).toArray()[0] as PasskeyRow | undefined; } byCredential(credentialId: string): PasskeyRow | undefined { return this.sql.exec<PasskeyRow>("SELECT * FROM account_passkey WHERE credential_id = ? AND removed_at IS NULL", credentialId).toArray()[0] as PasskeyRow | undefined; } has(credentialId: string): boolean { return this.sql.exec("SELECT 1 FROM account_passkey WHERE credential_id = ?", credentialId).toArray().length > 0; } list(personId: string): PasskeyRow[] { return this.sql.exec<PasskeyRow>("SELECT * FROM account_passkey WHERE person_id = ? AND removed_at IS NULL ORDER BY created_at", personId).toArray() as PasskeyRow[]; } remove(id: string, personId: string, now: number): boolean { return this.sql.exec("UPDATE account_passkey SET removed_at = ? WHERE id = ? AND person_id = ? AND removed_at IS NULL", now, id, personId).rowsWritten > 0; } used(id: string, signCount: number, now: number): void { this.sql.exec("UPDATE account_passkey SET sign_count = ?, last_used_at = ? WHERE id = ?", signCount, now, id); }}/** A passkey as a signed-in device lists it: never its key. */export function wirePasskey(row: PasskeyRow): Record<string, unknown> { return { id: row.id, name: row.name, created_at: row.created_at, last_used_at: row.last_used_at };}/** The creation options the platform's passkey sheet takes, for the person signed in on `databaseId`. */export function creationOptions(challenge: string, rpId: string, databaseId: string, phone: string, existing: string[]): Record<string, unknown> { return { challenge, rp: { id: rpId, name: RP_NAME }, user: { id: b64url(new TextEncoder().encode(databaseId)), name: phone, displayName: phone }, pubKeyCredParams: [{ type: "public-key", alg: ES256 }], timeout: CHALLENGE_SECONDS * 1000, attestation: "none", authenticatorSelection: { residentKey: "required", requireResidentKey: true, userVerification: "required" }, excludeCredentials: existing.map((id) => ({ type: "public-key", id })), };}export function requestOptions(challenge: string, rpId: string): Record<string, unknown> { return { challenge, rpId, timeout: CHALLENGE_SECONDS * 1000, userVerification: "required", allowCredentials: [] };}