import { assert, assertEquals } from "@std/assert"; import { Secp256k1Keypair } from "@atproto/crypto"; const ROOT = new URL("../", import.meta.url).pathname; const NSID = "com.fedfork.atprotoOauthQR"; const ROUTE = `/xrpc/${NSID}`; const AUD = "did:web:127.0.0.1"; function b64url(bytes: Uint8Array): string { let s = ""; for (const b of bytes) s += String.fromCharCode(b); return btoa(s).replace(/\+/g, "-").replace(/\//g, "_").replace(/=+$/, ""); } function b64json(value: unknown): string { return b64url(new TextEncoder().encode(JSON.stringify(value))); } function fromB64url(s: string): Uint8Array { const p = s.replace(/-/g, "+").replace(/_/g, "/"); return Uint8Array.from(atob(p + "=".repeat((4 - (p.length % 4)) % 4)), (c) => c.charCodeAt(0)); } interface TokenOpts { signer?: Secp256k1Keypair; iss?: string; aud?: string; alg?: string; iat?: number | null; exp?: number; jti?: string | null; unsigned?: boolean; } async function serviceAuth(key: Secp256k1Keypair, o: TokenOpts = {}): Promise { const now = Math.floor(Date.now() / 1000); const head = b64json({ alg: o.alg ?? "ES256K", typ: "JWT" }); const claims: Record = { iss: o.iss ?? key.did(), aud: o.aud ?? AUD, lxm: NSID, exp: o.exp ?? now + 60, }; if (o.iat !== null) claims.iat = o.iat ?? now; if (o.jti !== null) claims.jti = o.jti ?? b64url(crypto.getRandomValues(new Uint8Array(16))); const body = b64json(claims); if (o.unsigned) return `${head}.${body}.`; const sig = await (o.signer ?? key).sign(new TextEncoder().encode(`${head}.${body}`)); return `${head}.${body}.${b64url(sig)}`; } function nonce(): string { return b64url(crypto.getRandomValues(new Uint8Array(24))); } function plcDid(): string { const abc = "abcdefghijklmnopqrstuvwxyz234567"; return "did:plc:" + Array.from(crypto.getRandomValues(new Uint8Array(24)), (b) => abc[b % 32]).join(""); } interface FakeNet { base: string; tokens: Map; getSessionCalls: () => number; hits: () => number; stop: () => Promise; } async function verifyDpop(req: Request, token: string, htu: string): Promise { const proof = req.headers.get("dpop"); if (!proof) return false; const [h, p, s] = proof.split("."); const head = JSON.parse(new TextDecoder().decode(fromB64url(h))); const body = JSON.parse(new TextDecoder().decode(fromB64url(p))); if (head.typ !== "dpop+jwt" || head.alg !== "ES256" || body.htm !== "GET" || body.htu !== htu) return false; if (typeof body.iat !== "number" || Math.abs(body.iat - Date.now() / 1000) > 60 || typeof body.jti !== "string") return false; const ath = b64url(new Uint8Array(await crypto.subtle.digest("SHA-256", new TextEncoder().encode(token)))); if (body.ath !== ath) return false; const key = await crypto.subtle.importKey("jwk", head.jwk, { name: "ECDSA", namedCurve: "P-256" }, false, ["verify"]); return crypto.subtle.verify({ name: "ECDSA", hash: "SHA-256" }, key, fromB64url(s), new TextEncoder().encode(`${h}.${p}`)); } function startFakeNet(): FakeNet { const tokens = new Map(); let calls = 0; let hits = 0; let base = ""; const server = Deno.serve({ port: 0, hostname: "127.0.0.1", onListen: () => {} }, async (req) => { hits++; const url = new URL(req.url); if (url.pathname.startsWith("/plc/")) { const did = url.pathname.slice(5); return Response.json({ id: did, service: [{ id: "#atproto_pds", type: "AtprotoPersonalDataServer", serviceEndpoint: base }], }); } if (url.pathname === "/.well-known/oauth-protected-resource") { return Response.json({ authorization_servers: [`${base}/entryway`] }); } if (url.pathname === "/xrpc/com.atproto.server.getSession") { calls++; const auth = req.headers.get("authorization") ?? ""; const token = auth.startsWith("DPoP ") ? auth.slice(5) : ""; const body = JSON.parse(new TextDecoder().decode(fromB64url((req.headers.get("dpop") ?? "..").split(".")[1] || "e30"))); if (body.nonce !== "pds-nonce") { return Response.json({ error: "use_dpop_nonce" }, { status: 401, headers: { "dpop-nonce": "pds-nonce" } }); } const did = tokens.get(token); if (!did || !(await verifyDpop(req, token, `${base}/xrpc/com.atproto.server.getSession`))) return Response.json({ error: "InvalidToken" }, { status: 401 }); return Response.json({ did, handle: `${did.slice(8, 14)}.test` }); } return new Response("not found", { status: 404 }); }); base = `http://127.0.0.1:${server.addr.port}`; return { base, tokens, getSessionCalls: () => calls, hits: () => hits, stop: () => server.shutdown() }; } async function account(net: FakeNet, did = plcDid()) { const kp = await crypto.subtle.generateKey({ name: "ECDSA", namedCurve: "P-256" }, true, ["sign"]); const pub = await crypto.subtle.exportKey("jwk", kp.publicKey); const priv = await crypto.subtle.exportKey("jwk", kp.privateKey); const token = `access-${b64url(crypto.getRandomValues(new Uint8Array(12)))}`; net.tokens.set(token, did); return { accessJwt: token, refreshJwt: "refresh-test", userDid: did, handle: "claimed.example.com", pds: net.base, dpopPublicJwk: pub, dpopPrivateJwk: priv, }; } interface Backend { base: string; stop: () => Promise; } async function startBackend(dir: string, net: FakeNet, ttlSeconds: number, extra: Record = {}): Promise { const portFile = `${dir}/port`; await Deno.remove(portFile).catch(() => {}); const child = new Deno.Command(Deno.execPath(), { args: ["run", "--unstable-kv", "-A", `${ROOT}hono-backend/mod.ts`, "--port", "0", "--port-file", portFile], cwd: dir, env: { KV_PATH: `${dir}/kv.db`, LINK_TTL_SECONDS: String(ttlSeconds), PLC_URL: `${net.base}/plc`, INSECURE_LOOPBACK_IDENTITY: "true", SERVICE_DID: AUD, ...extra, }, stdout: "null", stderr: "null", }).spawn(); let port = ""; for (let i = 0; i < 300 && !port; i++) { port = await Deno.readTextFile(portFile).then((s) => s.trim(), () => ""); if (!port) await new Promise((r) => setTimeout(r, 100)); } assert(port, "backend never wrote its port file"); let stopped = false; return { base: `http://127.0.0.1:${port}`, stop: async () => { if (stopped) return; stopped = true; child.kill("SIGTERM"); await child.status; }, }; } type Reply = { status: number; body: Record }; async function post(b: Backend, body: Record, headers: Record = {}): Promise { const res = await fetch(`${b.base}${ROUTE}`, { method: "POST", headers: { "content-type": "application/json", ...headers }, body: JSON.stringify(body), }); return { status: res.status, body: await res.json() }; } async function poll(b: Backend, key: Secp256k1Keypair, n: string, token?: string): Promise { const res = await fetch(`${b.base}${ROUTE}`, { headers: { authorization: `Bearer ${token ?? await serviceAuth(key)}`, "x-oauth-qr-nonce": n }, }); return { status: res.status, body: await res.json() }; } async function withBackend(ttlSeconds: number, fn: (b: Backend, net: FakeNet, dir: string) => Promise, seed?: (kv: Deno.Kv) => Promise) { const dir = await Deno.makeTempDir(); const net = startFakeNet(); try { if (seed) { const kv = await Deno.openKv(`${dir}/kv.db`); await seed(kv); kv.close(); } const b = await startBackend(dir, net, ttlSeconds); try { await fn(b, net, dir); } finally { await b.stop(); } } finally { await net.stop(); await Deno.remove(dir, { recursive: true }); } } Deno.test("a link the device never polled is rejected before any session check", async () => { await withBackend(300, async (b, net) => { const key = await Secp256k1Keypair.create(); const n = nonce(); const res = await post(b, { cliDid: key.did(), nonce: n, ...(await account(net)) }); assertEquals(res.status, 404); assertEquals(res.body.error, "LinkUnknown"); assertEquals(net.getSessionCalls(), 0); assertEquals((await poll(b, key, n)).body.error, "notReady"); }); }); Deno.test("a verified session transfers once, replays are refused and the device collects it once", async () => { await withBackend(300, async (b, net) => { const key = await Secp256k1Keypair.create(); const n = nonce(); const acct = await account(net); assertEquals((await poll(b, key, n)).status, 404); const probe = await post(b, { cliDid: key.did(), nonce: n }); assertEquals(probe.status, 200); assertEquals(probe.body.status, "waiting"); const sent = await post(b, { cliDid: key.did(), nonce: n, ...acct }); assertEquals(sent.status, 200, JSON.stringify(sent.body)); assertEquals(sent.body.did, acct.userDid); const replay = await post(b, { cliDid: key.did(), nonce: n, ...(await account(net)) }); assertEquals(replay.status, 410); assertEquals(replay.body.error, "LinkUsed"); const got = await poll(b, key, n); assertEquals(got.status, 200); assertEquals(got.body.accessJwt, acct.accessJwt); assertEquals(got.body.verifiedDid, acct.userDid); assertEquals(got.body.handle, `${acct.userDid.slice(8, 14)}.test`); const again = await poll(b, key, n); assertEquals(again.status, 404); assertEquals(again.body.error, "consumed"); assertEquals((await post(b, { cliDid: key.did(), nonce: n, ...acct })).body.error, "LinkUsed"); }); }); Deno.test("a session that does not belong to the DID it names is refused and the link stays open", async () => { await withBackend(300, async (b, net) => { const key = await Secp256k1Keypair.create(); const n = nonce(); await poll(b, key, n); const victim = plcDid(); const forged = { ...(await account(net)), userDid: victim }; const res = await post(b, { cliDid: key.did(), nonce: n, ...forged }); assertEquals(res.status, 422); assertEquals(res.body.error, "SessionUnverified"); const badToken = { ...(await account(net)), accessJwt: "not-a-token" }; assertEquals((await post(b, { cliDid: key.did(), nonce: n, ...badToken })).status, 422); const otherPds = { ...(await account(net)), pds: "http://127.0.0.2:9" }; assertEquals((await post(b, { cliDid: key.did(), nonce: n, ...otherPds })).status, 422); const entryway = { ...(await account(net)), pds: `${net.base}/entryway` }; assertEquals((await post(b, { cliDid: key.did(), nonce: n, ...entryway })).status, 200); assertEquals((await poll(b, key, n)).body.pds, `${net.base}/entryway`); }); }); Deno.test("a link expires after the configured ttl from the first device poll", async () => { await withBackend(1, async (b, net) => { const key = await Secp256k1Keypair.create(); const n = nonce(); assertEquals((await poll(b, key, n)).status, 404); await new Promise((r) => setTimeout(r, 1500)); const res = await post(b, { cliDid: key.did(), nonce: n, ...(await account(net)) }); assertEquals(res.status, 410); assertEquals(res.body.error, "LinkExpired"); assertEquals((await poll(b, key, n)).body.error, "expired"); }); }); Deno.test("links are per nonce and older open links of a DID are superseded past the cap", async () => { await withBackend(300, async (b, net) => { const key = await Secp256k1Keypair.create(); const ns = [nonce(), nonce(), nonce(), nonce(), nonce()]; for (const n of ns) await poll(b, key, n); const first = await post(b, { cliDid: key.did(), nonce: ns[0], ...(await account(net)) }); assertEquals(first.status, 410); assertEquals(first.body.error, "LinkSuperseded"); assertEquals((await post(b, { cliDid: key.did(), nonce: ns[1], ...(await account(net)) })).status, 200); assertEquals((await poll(b, key, ns[2])).status, 404); assertEquals((await poll(b, key, ns[1])).status, 200); }); }); Deno.test("the nonce is read from the header or the legacy query and required", async () => { await withBackend(300, async (b) => { const key = await Secp256k1Keypair.create(); const none = await fetch(`${b.base}${ROUTE}`, { headers: { authorization: `Bearer ${await serviceAuth(key)}` } }); assertEquals(none.status, 400); assertEquals((await none.json()).error, "InvalidRequest"); const q = await fetch(`${b.base}${ROUTE}?nonce=${nonce()}`, { headers: { authorization: `Bearer ${await serviceAuth(key)}` } }); assertEquals(q.status, 404); assertEquals((await q.json()).error, "notReady"); }); }); Deno.test("forged, replayed and over-long service auth tokens are refused without any fetch", async () => { await withBackend(300, async (b, net) => { const key = await Secp256k1Keypair.create(); const other = await Secp256k1Keypair.create(); const now = Math.floor(Date.now() / 1000); const cases: [string, string][] = [ ["wrong key", await serviceAuth(key, { signer: other })], ["wrong iss", await serviceAuth(key, { iss: other.did() })], ["wrong aud", await serviceAuth(key, { aud: "did:web:qr.fedfork.com.evil" })], ["alg none", await serviceAuth(key, { alg: "none", unsigned: true })], ["alg ES256 on a k256 key", await serviceAuth(key, { alg: "ES256" })], ["no iat", await serviceAuth(key, { iat: null })], ["no jti", await serviceAuth(key, { jti: null })], ["lifetime 600s", await serviceAuth(key, { iat: now, exp: now + 600 })], ["future iat", await serviceAuth(key, { iat: now + 300, exp: now + 360 })], ["expired", await serviceAuth(key, { iat: now - 120, exp: now - 60 })], ["garbage", "a.b"], ["did:plc issuer", await serviceAuth(key, { iss: plcDid() })], ["did:web issuer", await serviceAuth(key, { iss: "did:web:127.0.0.1" })], ]; const before = net.hits(); const messages = new Set(); for (const [name, token] of cases) { const res = await poll(b, key, nonce(), token); assertEquals(res.status, 401, name); assertEquals(res.body.error, "Unauthorized", name); messages.add(res.body.message); } assertEquals(net.hits(), before, "a poll token made the server fetch something"); const once = await serviceAuth(key); assertEquals((await poll(b, key, nonce(), once)).status, 404); const replayed = await poll(b, key, nonce(), once); assertEquals(replayed.status, 401); messages.add(replayed.body.message); assertEquals([...messages], ["invalid service auth token"]); }); }); Deno.test("concurrent transfers and polls hand out exactly one session exactly once", async () => { await withBackend(300, async (b, net) => { const key = await Secp256k1Keypair.create(); const n = nonce(); await poll(b, key, n); const accts = await Promise.all(Array.from({ length: 6 }, () => account(net))); const posts = await Promise.all(accts.map((a, i) => post(b, { cliDid: key.did(), nonce: n, ...a }, { "x-qr-client-ip": `198.51.100.${i + 1}` }))); const won = posts.filter((r) => r.status === 200); assertEquals(won.length, 1, JSON.stringify(posts.map((r) => r.status))); for (const r of posts.filter((r) => r.status !== 200)) assertEquals(r.body.error, "LinkUsed"); const polls = await Promise.all(Array.from({ length: 6 }, () => poll(b, key, n))); const got = polls.filter((r) => r.status === 200); assertEquals(got.length, 1, JSON.stringify(polls.map((r) => r.status))); assertEquals(got[0].body.userDid, won[0].body.did); }); }); Deno.test("legacy per-did session entries are purged when the store opens", async () => { await withBackend(300, async (b, _net, dir) => { const key = await Secp256k1Keypair.create(); assertEquals((await poll(b, key, nonce())).status, 404); await b.stop(); const kv = await Deno.openKv(`${dir}/kv.db`); try { const left = []; for await (const e of kv.list({ prefix: ["oauthQr"] })) left.push(e.key); assertEquals(left.length, 0); } finally { kv.close(); } }, async (kv) => { await kv.set(["oauthQr", "did:key:zLegacy"], { nonce: "x", session: {}, createdAt: Date.now() }); }); }); Deno.test("a link ttl outside 1..300 seconds stops the backend at startup", async () => { for (const ttl of ["0", "301", "1.5"]) { const dir = await Deno.makeTempDir(); try { const out = await new Deno.Command(Deno.execPath(), { args: ["run", "--unstable-kv", "-A", `${ROOT}hono-backend/mod.ts`, "--port", "0", "--port-file", `${dir}/port`], cwd: dir, env: { KV_PATH: `${dir}/kv.db`, LINK_TTL_SECONDS: ttl }, stdout: "null", stderr: "piped", }).output(); assert(out.code !== 0, `ttl ${ttl} started`); assert(new TextDecoder().decode(out.stderr).includes("link-ttl-seconds"), ttl); } finally { await Deno.remove(dir, { recursive: true }); } } }); Deno.test("interleaved transfers and polls never hand out a session twice or a losing session", async () => { await withBackend(300, async (b, net) => { const key = await Secp256k1Keypair.create(); const n = nonce(); await poll(b, key, n); const accts = await Promise.all(Array.from({ length: 5 }, () => account(net))); const ops: Promise[] = []; for (let i = 0; i < 5; i++) { ops.push(post(b, { cliDid: key.did(), nonce: n, ...accts[i] }, { "x-qr-client-ip": `203.0.113.${i + 1}` }).then((r) => ({ ...r, kind: "post" }))); ops.push(poll(b, key, n).then((r) => ({ ...r, kind: "poll" }))); } const done = await Promise.all(ops); const late = await Promise.all([poll(b, key, n), poll(b, key, n)]); const won = done.filter((r) => r.kind === "post" && r.status === 200); assertEquals(won.length, 1, JSON.stringify(done.map((r) => `${r.kind}:${r.status}`))); const delivered = [...done.filter((r) => r.kind === "poll"), ...late].filter((r) => r.status === 200); assertEquals(delivered.length, 1); assertEquals(delivered[0].body.userDid, won[0].body.did); }); }); Deno.test("an incomplete session is a 400 and does not use the link", async () => { await withBackend(300, async (b, net) => { const key = await Secp256k1Keypair.create(); const n = nonce(); await poll(b, key, n); const { refreshJwt: _r, ...partial } = await account(net); const res = await post(b, { cliDid: key.did(), nonce: n, ...partial }); assertEquals(res.status, 400); assertEquals(net.getSessionCalls(), 0); assertEquals((await post(b, { cliDid: key.did(), nonce: n, ...(await account(net)) })).status, 200); }); }); Deno.test("POST limits key on the edge-set client address, not on X-Forwarded-For", async () => { await withBackend(300, async (b) => { const key = await Secp256k1Keypair.create(); const probe = (headers: Record) => post(b, { cliDid: key.did(), nonce: nonce() }, headers); const codes: number[] = []; for (let i = 0; i < 31; i++) { codes.push((await probe({ "x-qr-client-ip": "192.0.2.7", "x-forwarded-for": `10.9.${i}.1, 192.0.2.7` })).status); } assertEquals(codes.slice(0, 30).every((c) => c === 404), true, JSON.stringify(codes)); assertEquals(codes[30], 429); assertEquals((await probe({ "x-forwarded-for": "10.0.0.1" })).status, 404); assertEquals((await probe({ "x-qr-client-ip": "192.0.2.8" })).status, 404); assertEquals((await probe({ "x-qr-client-ip": "192.0.2.7" })).status, 429); }); }); Deno.test("unsafe startup configs stop the backend", async () => { const net = startFakeNet(); try { const bad: Record[] = [{ ADDR: "0.0.0.0" }, { SERVICE_DID: "did:plc:aaaaaaaaaaaaaaaaaaaaaaaa" }]; for (const extra of bad) { const dir = await Deno.makeTempDir(); try { const out = await new Deno.Command(Deno.execPath(), { args: ["run", "--unstable-kv", "-A", `${ROOT}hono-backend/mod.ts`, "--port", "0", "--port-file", `${dir}/port`], cwd: dir, env: { KV_PATH: `${dir}/kv.db`, PLC_URL: `${net.base}/plc`, INSECURE_LOOPBACK_IDENTITY: "true", SERVICE_DID: AUD, ...extra }, stdout: "null", stderr: "null", }).output(); assert(out.code !== 0, JSON.stringify(extra)); } finally { await Deno.remove(dir, { recursive: true }); } } } finally { await net.stop(); } });