Cotton code
262 lines · 15.7 KB · TypeScriptRaw
/** * A Cotton-account passkey (owner, 17 Nov 2026; src/passkey.ts): added from a * signed-in device, used to sign a new device in with no number typed. The * authenticator is made up here (a P-256 key in WebCrypto), as is every * number and name. */import { SELF } from "cloudflare:test";import { describe, expect, it } from "vitest";import registry from "../../registry.json";import { derToRaw, origins } from "../src/passkey.ts";const OPEN = "https://cottondb.com";const RP = "cottondb.com";type Body = Record<string, unknown>;async function open<T = Body>(method: string, path: string, body?: unknown, headers: Record<string, string> = {}): Promise<{ status: number; body: T }> {  const res = await SELF.fetch(`${OPEN}${path}`, { method, headers: { "content-type": "application/json", ...headers }, body: body === undefined ? undefined : JSON.stringify(body) });  const text = await res.text();  return { status: res.status, body: (text ? JSON.parse(text) : null) as T };}let ips = 0;function network(): Record<string, string> {  ips += 1;  return { "cf-connecting-ip": `198.51.100.${ips}` };}const bearer = (token: string): Record<string, string> => ({ authorization: `Bearer ${token}` });function b64u(bytes: ArrayBuffer | Uint8Array): string {  let s = "";  for (const b of new Uint8Array(bytes)) s += String.fromCharCode(b);  return btoa(s).replace(/\+/g, "-").replace(/\//g, "_").replace(/=+$/, "");}const utf8 = (text: string): Uint8Array => new TextEncoder().encode(text);const sha256 = async (bytes: Uint8Array): Promise<Uint8Array> => new Uint8Array(await crypto.subtle.digest("SHA-256", bytes));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;}// ── a small CBOR writer, as an authenticator writes ───────────────────────type C = number | Uint8Array | string | Map<C, C>;function head(major: number, n: number): Uint8Array {  if (n < 24) return new Uint8Array([(major << 5) | n]);  if (n < 256) return new Uint8Array([(major << 5) | 24, n]);  return new Uint8Array([(major << 5) | 25, n >> 8, n & 255]);}function cbor(value: C): Uint8Array {  if (typeof value === "number") return value >= 0 ? head(0, value) : head(1, -1 - value);  if (typeof value === "string") return concat(head(3, utf8(value).length), utf8(value));  if (value instanceof Uint8Array) return concat(head(2, value.length), value);  return concat(head(5, value.size), ...[...value].flatMap(([k, v]) => [cbor(k), cbor(v)]));}/** P1363 r‖s to DER, as an authenticator sends it. */function rawToDer(raw: Uint8Array): Uint8Array {  const int = (bytes: Uint8Array): Uint8Array => {    let b = bytes;    while (b.length > 1 && b[0] === 0 && b[1]! < 0x80) b = b.slice(1);    if (b[0]! >= 0x80) b = concat(new Uint8Array([0]), b);    return concat(new Uint8Array([0x02, b.length]), b);  };  const body = concat(int(raw.slice(0, 32)), int(raw.slice(32)));  return concat(new Uint8Array([0x30, body.length]), body);}interface Authenticator {  id: Uint8Array;  count: number;  create(challenge: string, opts?: { origin?: string; rp?: string; uv?: boolean }): Promise<Body>;  get(challenge: string, userHandle: string, opts?: { origin?: string; count?: number; tamper?: boolean }): Promise<Body>;}async function authenticator(): Promise<Authenticator> {  const pair = (await crypto.subtle.generateKey({ name: "ECDSA", namedCurve: "P-256" }, true, ["sign", "verify"])) as CryptoKeyPair;  const jwk = (await crypto.subtle.exportKey("jwk", pair.publicKey)) as JsonWebKey;  const fromB64u = (s: string): Uint8Array => Uint8Array.from(atob(s.replace(/-/g, "+").replace(/_/g, "/")), (c) => c.charCodeAt(0));  const id = crypto.getRandomValues(new Uint8Array(16));  const me: Authenticator = {    id,    count: 0,    async create(challenge, opts = {}) {      const clientDataJSON = utf8(JSON.stringify({ type: "webauthn.create", challenge, origin: opts.origin ?? OPEN }));      const cose = cbor(new Map<C, C>([[1, 2], [3, -7], [-1, 1], [-2, fromB64u(jwk.x!)], [-3, fromB64u(jwk.y!)]]));      const flags = 0x41 | (opts.uv === false ? 0 : 0x04);      const authData = concat(await sha256(utf8(opts.rp ?? RP)), new Uint8Array([flags, 0, 0, 0, 0]), new Uint8Array(16), new Uint8Array([0, id.length]), id, cose);      const attestationObject = cbor(new Map<C, C>([["fmt", "none"], ["attStmt", new Map()], ["authData", authData]]));      return { id: b64u(id), rawId: b64u(id), type: "public-key", response: { clientDataJSON: b64u(clientDataJSON), attestationObject: b64u(attestationObject) } };    },    async get(challenge, userHandle, opts = {}) {      const count = opts.count ?? (me.count += 1);      const clientDataJSON = utf8(JSON.stringify({ type: "webauthn.get", challenge, origin: opts.origin ?? OPEN }));      const authData = concat(await sha256(utf8(RP)), new Uint8Array([0x05, (count >> 24) & 255, (count >> 16) & 255, (count >> 8) & 255, count & 255]));      const raw = new Uint8Array(await crypto.subtle.sign({ name: "ECDSA", hash: "SHA-256" }, pair.privateKey, concat(authData, await sha256(clientDataJSON))));      if (opts.tamper) raw[10] = raw[10]! ^ 1;      return { id: b64u(id), rawId: b64u(id), type: "public-key", response: { clientDataJSON: b64u(clientDataJSON), authenticatorData: b64u(authData), signature: b64u(rawToDer(raw)), userHandle } };    },  };  return me;}async function deviceKey(): Promise<string> {  const pair = (await crypto.subtle.generateKey({ name: "Ed25519" }, true, ["sign", "verify"])) as CryptoKeyPair;  return b64u((await crypto.subtle.exportKey("raw", pair.publicKey)) as ArrayBuffer);}async function signedIn(phone: string): Promise<{ credential: string; databaseId: string }> {  const ip = network();  const code = await open<{ challenge_id: string; database_id: string }>("POST", "/v1/code", { phone, device_id: "phone-signed-in" }, ip);  expect(code.status, JSON.stringify(code.body)).toBe(200);  const signed = await open<{ credential: string }>("POST", "/v1/sign-in", { database_id: code.body.database_id, challenge_id: code.body.challenge_id, code: "123456", device_id: "phone-signed-in" }, ip);  expect(signed.status, JSON.stringify(signed.body)).toBe(200);  return { credential: signed.body.credential, databaseId: code.body.database_id };}interface CreationOptions {  challenge: string;  rp: { id: string; name: string };  user: { id: string; name: string };  authenticatorSelection: { residentKey: string; userVerification: string };  excludeCredentials: { id: string }[];}async function add(me: { credential: string }, key: Authenticator): Promise<{ status: number; body: Body }> {  const options = await open<{ request: CreationOptions }>("POST", "/v1/passkeys/options", {}, bearer(me.credential));  expect(options.status, JSON.stringify(options.body)).toBe(200);  return open("POST", "/v1/passkeys", { response: await key.create(options.body.request.challenge), name: "Pixel walk" }, bearer(me.credential));}async function begin(): Promise<{ challenge_id: string; request: { challenge: string; rpId: string; userVerification: string; allowCredentials: unknown[] } }> {  const begun = await open<{ challenge_id: string; request: { challenge: string; rpId: string; userVerification: string; allowCredentials: unknown[] } }>("POST", "/v1/passkey/begin", {}, network());  expect(begun.status, JSON.stringify(begun.body)).toBe(200);  return begun.body;}const signIn = async (challengeId: string, response: Body, deviceId?: string) =>  open<{ credential?: string; database_id?: string; host?: string; code?: string }>("POST", "/v1/passkey/sign-in", { challenge_id: challengeId, device_id: deviceId ?? (await deviceKey()), response }, network());describe("a Cotton passkey", () => {  it("is added from a signed-in device and signs a new device in with no number, once per challenge", async () => {    const me = await signedIn("+919000006001");    const options = await open<{ request: CreationOptions }>("POST", "/v1/passkeys/options", {}, bearer(me.credential));    expect(options.body.request.rp).toEqual({ id: RP, name: "Cotton" });    expect(options.body.request.user.id).toBe(b64u(utf8(me.databaseId)));    expect(options.body.request.authenticatorSelection).toMatchObject({ residentKey: "required", userVerification: "required" });    const key = await authenticator();    const added = await open<Body>("POST", "/v1/passkeys", { response: await key.create(options.body.request.challenge), name: "Pixel walk" }, bearer(me.credential));    expect(added.status, JSON.stringify(added.body)).toBe(200);    expect(added.body.name).toBe("Pixel walk");    const listed = await open<{ passkeys: Body[] }>("GET", "/v1/passkeys", undefined, bearer(me.credential));    expect(listed.body.passkeys).toHaveLength(1);    expect(Object.keys(listed.body.passkeys[0]!).sort()).toEqual(["created_at", "id", "last_used_at", "name"]);    // The next options leave this passkey out, so the sheet does not make a second.    const next = await open<{ request: CreationOptions }>("POST", "/v1/passkeys/options", {}, bearer(me.credential));    expect(next.body.request.excludeCredentials.map((c) => c.id)).toEqual([b64u(key.id)]);    const begun = await begin();    expect(begun.request).toMatchObject({ rpId: RP, userVerification: "required", allowCredentials: [] });    const answer = await key.get(begun.request.challenge, b64u(utf8(me.databaseId)));    const newDevice = await deviceKey();    const signed = await signIn(begun.challenge_id, answer, newDevice);    expect(signed.status, JSON.stringify(signed.body)).toBe(200);    expect(signed.body.database_id).toBe(me.databaseId);    expect(signed.body.host).toBe(OPEN);    expect(signed.body.credential!.startsWith(`ctd_${me.databaseId}_`)).toBe(true);    const mine = await open<{ person: { phone: string } }>("GET", "/v1/me", undefined, bearer(signed.body.credential!));    expect([mine.status, mine.body.person.phone]).toEqual([200, "+919000006001"]);    // Replayed: the challenge is spent.    const replay = await signIn(begun.challenge_id, answer);    expect([replay.status, replay.body.code]).toEqual([401, "passkey_refused"]);  });  it("refuses an add from another origin, for another relying party, or without the person verified", async () => {    const me = await signedIn("+919000006002");    for (const opts of [{ origin: "https://evil.example" }, { rp: "evil.example" }, { uv: false }]) {      const options = await open<{ request: CreationOptions }>("POST", "/v1/passkeys/options", {}, bearer(me.credential));      const refused = await open<{ code: string }>("POST", "/v1/passkeys", { response: await (await authenticator()).create(options.body.request.challenge, opts) }, bearer(me.credential));      expect([refused.status, refused.body.code], JSON.stringify(opts)).toEqual([401, "passkey_refused"]);    }    // A challenge made up by the caller was never this object's.    const madeUp = await open<{ code: string }>("POST", "/v1/passkeys", { response: await (await authenticator()).create("bWFkZS11cA") }, bearer(me.credential));    expect(madeUp.body.code).toBe("passkey_refused");    expect((await open<{ passkeys: unknown[] }>("GET", "/v1/passkeys", undefined, bearer(me.credential))).body.passkeys).toEqual([]);  });  it("answers the same refusal for an unknown passkey, a wrong signature, a counter that went back, another origin and a removed passkey", async () => {    const me = await signedIn("+919000006003");    const key = await authenticator();    const added = await add(me, key);    expect(added.status).toBe(200);    const handle = b64u(utf8(me.databaseId));    const stranger = await authenticator();    let begun = await begin();    expect((await signIn(begun.challenge_id, await stranger.get(begun.request.challenge, handle))).body.code).toBe("passkey_refused");    begun = await begin();    expect((await signIn(begun.challenge_id, await key.get(begun.request.challenge, handle, { tamper: true }))).body.code).toBe("passkey_refused");    begun = await begin();    expect((await signIn(begun.challenge_id, await key.get(begun.request.challenge, handle, { origin: "https://evil.example" }))).body.code).toBe("passkey_refused");    begun = await begin();    expect((await signIn(begun.challenge_id, await key.get(begun.request.challenge, handle, { count: 5 }))).status).toBe(200);    begun = await begin();    expect((await signIn(begun.challenge_id, await key.get(begun.request.challenge, handle, { count: 5 }))).body.code).toBe("passkey_refused");    // A user handle naming no database.    begun = await begin();    expect((await signIn(begun.challenge_id, await key.get(begun.request.challenge, b64u(utf8("00000000-0000-4000-8000-000000000000")), { count: 9 }))).body.code).toBe("passkey_refused");    const id = added.body.id as string;    expect((await open("POST", "/v1/passkeys/remove", { id }, bearer(me.credential))).status).toBe(200);    begun = await begin();    expect((await signIn(begun.challenge_id, await key.get(begun.request.challenge, handle, { count: 10 }))).body.code).toBe("passkey_refused");  });  it("is added and removed only by a signed-in device of its own number", async () => {    const me = await signedIn("+919000006004");    const nobody = await open<{ code: string }>("POST", "/v1/passkeys/options", {});    expect(nobody.status).toBe(401);    const added = await add(me, await authenticator());    const other = await signedIn("+919000006005");    expect((await open<{ passkeys: unknown[] }>("GET", "/v1/passkeys", undefined, bearer(other.credential))).body.passkeys).toEqual([]);    const cross = await open<{ code: string }>("POST", "/v1/passkeys/remove", { id: added.body.id }, bearer(other.credential));    expect([cross.status, cross.body.code]).toEqual([404, "no_such_passkey"]);  });});describe("the open host's apple-app-site-association", () => {  // The live Worker's own var, as wrangler.jsonc holds it (pnpm -s passkey:associations; its guard is  // scripts/__tests__/site-associations.test.ts): every iPhone app cut to phones (development or production), by team and live bundle id.  it("answers with every sign-in iPhone app's webcredentials, as JSON, with no redirect", async () => {    const res = await SELF.fetch(`${OPEN}/.well-known/apple-app-site-association`, { redirect: "manual" });    expect(res.status).toBe(200);    expect(res.headers.get("content-type")).toBe("application/json");    const apps = ((await res.json()) as { webcredentials: { apps: string[] } }).webcredentials.apps;    type App = { phase: string; ios: { live: { flavour: string | null; bundleId: string } } | null };    const active = (registry as { apps: App[] }).apps.filter((app) => (app.phase === "development" || app.phase === "production") && Boolean(app.ios?.live.flavour));    expect(active.length).toBeGreaterThan(0);    expect(apps.map((app) => app.replace(/^[A-Z0-9]{10}\./, ""))).toEqual(active.map((app) => app.ios!.live.bundleId));    expect(apps.every((app) => /^[A-Z0-9]{10}\./.test(app))).toBe(true);  });});describe("the passkey's checks", () => {  it("takes the Android app origins the Worker is given beside its own", () => {    expect([...origins(RP, " android:apk-key-hash:abc , android:apk-key-hash:def")]).toEqual(["https://cottondb.com", "android:apk-key-hash:abc", "android:apk-key-hash:def"]);    expect([...origins(RP, undefined)]).toEqual(["https://cottondb.com"]);  });  it("reads a DER signature with and without leading zeros", () => {    const raw = new Uint8Array(64).map((_, i) => (i === 0 || i === 32 ? 0x80 : i));    expect(derToRaw(rawToDer(raw))).toEqual(raw);    const small = new Uint8Array(64).map((_, i) => (i < 2 || (i >= 32 && i < 33) ? 0 : i));    expect(derToRaw(rawToDer(small))).toEqual(small);  });});