import assert from "node:assert/strict"; import { randomBytes } from "node:crypto"; import { readFile } from "node:fs/promises"; import test from "node:test"; import { exportJWK, generateKeyPair, SignJWT } from "jose"; import { convertV4MiniflareOptions, Miniflare } from "miniflare"; import { createResourceAuth } from "../src/lib/d1-auth.ts"; import { browserSignIn } from "../src/lib/provider-sign-in.ts"; const origin = "https://airesource.example"; const providers = { google: { subject: "google-fixture", email: "google@example.invalid", clientId: "fixture.apps.googleusercontent.com", issuer: "https://accounts.google.com", keys: "https://www.googleapis.com/oauth2/v3/certs" }, apple: { subject: "apple-fixture", email: "apple@example.invalid", clientId: "pro.airesource.example", issuer: "https://appleid.apple.com", keys: "https://appleid.apple.com/auth/keys" }, }; function cookie(response) { return response.headers.getSetCookie().map((entry) => entry.split(";", 1)[0]).join("; "); } test("signed provider tokens preserve migrated account ownership and the login challenge can only be used once", async (t) => { const runtime = new Miniflare(convertV4MiniflareOptions({ modules: true, script: "export default { fetch() { return new Response(); } }", compatibilityDate: "2026-11-24", d1Databases: ["ACCOUNTS_DB"], })); try { const db = await runtime.getD1Database("ACCOUNTS_DB"); for (const file of ["0001_accounts.sql", "0002_better_auth.sql", "0003_sign_in_challenge.sql"]) { const schema = await readFile(new URL(`./migrations/${file}`, import.meta.url), "utf8"); await db.batch(schema.split(";").map((sql) => sql.trim()).filter(Boolean).map((sql) => db.prepare(sql))); } const signingKey = await generateKeyPair("RS256"); const jwk = { ...await exportJWK(signingKey.publicKey), alg: "RS256", kid: "provider-fixture" }; const ids = { google: providers.google.clientId, apple: providers.apple.clientId }; const auth = createResourceAuth(db, origin, randomBytes(48).toString("base64url"), ids); t.mock.method(globalThis, "fetch", async (input) => { const url = input instanceof Request ? input.url : String(input); assert.ok(Object.values(providers).some(({ keys }) => keys === url), `Unexpected OAuth fetch to ${url}`); return Response.json({ keys: [jwk] }); }); function post(path = "", { source = origin, cookies = "", payload } = {}) { return browserSignIn(new Request(origin + "/api/auth/identity" + path, { method: "POST", headers: { Origin: source, "Content-Type": "application/json", Cookie: cookies, "cf-connecting-ip": "192.0.2.1" }, body: payload ? JSON.stringify(payload) : undefined, }), { db, origin, providers: ids, auth }); } async function signedToken(provider, nonce, audience = providers[provider].clientId) { const settings = providers[provider]; // Returning Apple customers may have no email in the provider token. const claims = provider === "google" ? { email: settings.email, email_verified: true, name: "Fixture" } : {}; return new SignJWT({ ...claims, nonce }).setProtectedHeader({ alg: "RS256", kid: jwk.kid }) .setIssuer(settings.issuer).setAudience(audience).setSubject(settings.subject) .setIssuedAt().setExpirationTime("5m").sign(signingKey.privateKey); } assert.equal((await post("/challenge", { source: "https://wrong.example" })).status, 403); for (const [provider, settings] of Object.entries(providers)) { const importedId = `original-${provider}-uuid`; const now = new Date().toISOString(); await db.prepare('INSERT INTO "user" (id,name,email,"emailVerified","createdAt","updatedAt",provider) VALUES (?, ?, ?, 1, ?, ?, ?)') .bind(importedId, "Imported account", settings.email, now, now, provider).run(); await db.prepare('INSERT INTO "account" (id,"accountId","providerId","userId","createdAt","updatedAt") VALUES (?, ?, ?, ?, ?, ?)') .bind(`original-link-${provider}`, settings.subject, provider, importedId, now, now).run(); await db.prepare("INSERT INTO users (id, email, created_at, updated_at) VALUES (?, ?, ?, ?)") .bind(importedId, settings.email, now, now).run(); await db.prepare("INSERT INTO saved_tutorials (user_id,tutorial_slug,created_at) VALUES (?, ?, ?)") .bind(importedId, "claude/example", now).run(); const launch = await post("/challenge"); assert.equal(launch.status, 200); const challenge = await launch.json(); assert.equal(challenge.providers[provider], settings.clientId); assert.match(launch.headers.get("set-cookie"), /Secure; HttpOnly; SameSite=Strict/); const proof = { provider, token: await signedToken(provider, challenge.nonce) }; assert.equal((await post("", { payload: proof })).status, 401); const results = await Promise.all([1, 2].map(() => post("", { cookies: cookie(launch), payload: proof }))); const sessionResponse = results.find((response) => response.ok); assert.ok(sessionResponse); assert.deepEqual(results.map((response) => response.status).sort(), [200, 401]); assert.deepEqual(await sessionResponse.json(), { signedIn: true }); const sessionCookie = cookie(sessionResponse); assert.match(sessionCookie, /__Secure-airesourcepro\.session_token=/); const session = await auth.api.getSession({ headers: new Headers({ Cookie: sessionCookie }) }); assert.equal(session?.user.id, importedId); assert.equal(session?.user.email, settings.email); assert.equal(session?.user.provider, provider); assert.equal(await db.prepare("SELECT tutorial_slug FROM saved_tutorials WHERE user_id = ?") .bind(session.user.id).first("tutorial_slug"), "claude/example"); const signOut = await auth.api.signOut({ headers: new Headers({ Cookie: sessionCookie, Origin: origin }), asResponse: true }); assert.ok(signOut.ok); assert.equal(await auth.api.getSession({ headers: new Headers({ Cookie: sessionCookie }) }), null); } for (const scenario of ["wrong-audience", "wrong-nonce", "expired-challenge"]) { const launch = await post("/challenge"); const { nonce } = await launch.json(); if (scenario === "expired-challenge") await db.prepare("UPDATE sign_in_challenge SET expires_at = 0").run(); const token = await signedToken("google", scenario === "wrong-nonce" ? "wrong" : nonce, scenario === "wrong-audience" ? "other-client.apps.googleusercontent.com" : undefined); assert.equal((await post("", { cookies: cookie(launch), payload: { provider: "google", token } })).status, 401); } assert.equal(await db.prepare('SELECT count(*) AS total FROM "user"').first("total"), 2); } finally { await runtime.dispose(); } });