AI Resource Pro / website / d1 / auth.test.mjs
| 1 | import assert from "node:assert/strict"; |
| 2 | import { randomBytes } from "node:crypto"; |
| 3 | import { readFile } from "node:fs/promises"; |
| 4 | import test from "node:test"; |
| 5 | import { exportJWK, generateKeyPair, SignJWT } from "jose"; |
| 6 | import { convertV4MiniflareOptions, Miniflare } from "miniflare"; |
| 7 | import { createResourceAuth } from "../src/lib/d1-auth.ts"; |
| 8 | import { browserSignIn } from "../src/lib/provider-sign-in.ts"; |
| 9 | |
| 10 | const origin = "https://airesource.example"; |
| 11 | const providers = { |
| 12 | google: { subject: "google-fixture", email: "google@example.invalid", clientId: "fixture.apps.googleusercontent.com", |
| 13 | issuer: "https://accounts.google.com", keys: "https://www.googleapis.com/oauth2/v3/certs" }, |
| 14 | apple: { subject: "apple-fixture", email: "apple@example.invalid", clientId: "pro.airesource.example", |
| 15 | issuer: "https://appleid.apple.com", keys: "https://appleid.apple.com/auth/keys" }, |
| 16 | }; |
| 17 | |
| 18 | function cookie(response) { |
| 19 | return response.headers.getSetCookie().map((entry) => entry.split(";", 1)[0]).join("; "); |
| 20 | } |
| 21 | |
| 22 | test("signed provider tokens preserve migrated account ownership and the login challenge can only be used once", async (t) => { |
| 23 | const runtime = new Miniflare(convertV4MiniflareOptions({ |
| 24 | modules: true, |
| 25 | script: "export default { fetch() { return new Response(); } }", |
| 26 | compatibilityDate: "2026-11-24", |
| 27 | d1Databases: ["ACCOUNTS_DB"], |
| 28 | })); |
| 29 | |
| 30 | try { |
| 31 | const db = await runtime.getD1Database("ACCOUNTS_DB"); |
| 32 | for (const file of ["0001_accounts.sql", "0002_better_auth.sql", "0003_sign_in_challenge.sql"]) { |
| 33 | const schema = await readFile(new URL(`./migrations/${file}`, import.meta.url), "utf8"); |
| 34 | await db.batch(schema.split(";").map((sql) => sql.trim()).filter(Boolean).map((sql) => db.prepare(sql))); |
| 35 | } |
| 36 | const signingKey = await generateKeyPair("RS256"); |
| 37 | const jwk = { ...await exportJWK(signingKey.publicKey), alg: "RS256", kid: "provider-fixture" }; |
| 38 | const ids = { google: providers.google.clientId, apple: providers.apple.clientId }; |
| 39 | const auth = createResourceAuth(db, origin, randomBytes(48).toString("base64url"), ids); |
| 40 | t.mock.method(globalThis, "fetch", async (input) => { |
| 41 | const url = input instanceof Request ? input.url : String(input); |
| 42 | assert.ok(Object.values(providers).some(({ keys }) => keys === url), `Unexpected OAuth fetch to ${url}`); |
| 43 | return Response.json({ keys: [jwk] }); |
| 44 | }); |
| 45 | |
| 46 | function post(path = "", { source = origin, cookies = "", payload } = {}) { |
| 47 | return browserSignIn(new Request(origin + "/api/auth/identity" + path, { |
| 48 | method: "POST", |
| 49 | headers: { Origin: source, "Content-Type": "application/json", Cookie: cookies, "cf-connecting-ip": "192.0.2.1" }, |
| 50 | body: payload ? JSON.stringify(payload) : undefined, |
| 51 | }), { db, origin, providers: ids, auth }); |
| 52 | } |
| 53 | |
| 54 | async function signedToken(provider, nonce, audience = providers[provider].clientId) { |
| 55 | const settings = providers[provider]; |
| 56 | // Returning Apple customers may have no email in the provider token. |
| 57 | const claims = provider === "google" ? { email: settings.email, email_verified: true, name: "Fixture" } : {}; |
| 58 | return new SignJWT({ ...claims, nonce }).setProtectedHeader({ alg: "RS256", kid: jwk.kid }) |
| 59 | .setIssuer(settings.issuer).setAudience(audience).setSubject(settings.subject) |
| 60 | .setIssuedAt().setExpirationTime("5m").sign(signingKey.privateKey); |
| 61 | } |
| 62 | |
| 63 | assert.equal((await post("/challenge", { source: "https://wrong.example" })).status, 403); |
| 64 | |
| 65 | for (const [provider, settings] of Object.entries(providers)) { |
| 66 | const importedId = `original-${provider}-uuid`; |
| 67 | const now = new Date().toISOString(); |
| 68 | await db.prepare('INSERT INTO "user" (id,name,email,"emailVerified","createdAt","updatedAt",provider) VALUES (?, ?, ?, 1, ?, ?, ?)') |
| 69 | .bind(importedId, "Imported account", settings.email, now, now, provider).run(); |
| 70 | await db.prepare('INSERT INTO "account" (id,"accountId","providerId","userId","createdAt","updatedAt") VALUES (?, ?, ?, ?, ?, ?)') |
| 71 | .bind(`original-link-${provider}`, settings.subject, provider, importedId, now, now).run(); |
| 72 | await db.prepare("INSERT INTO users (id, email, created_at, updated_at) VALUES (?, ?, ?, ?)") |
| 73 | .bind(importedId, settings.email, now, now).run(); |
| 74 | await db.prepare("INSERT INTO saved_tutorials (user_id,tutorial_slug,created_at) VALUES (?, ?, ?)") |
| 75 | .bind(importedId, "claude/example", now).run(); |
| 76 | |
| 77 | const launch = await post("/challenge"); |
| 78 | assert.equal(launch.status, 200); |
| 79 | const challenge = await launch.json(); |
| 80 | assert.equal(challenge.providers[provider], settings.clientId); |
| 81 | assert.match(launch.headers.get("set-cookie"), /Secure; HttpOnly; SameSite=Strict/); |
| 82 | const proof = { provider, token: await signedToken(provider, challenge.nonce) }; |
| 83 | assert.equal((await post("", { payload: proof })).status, 401); |
| 84 | const results = await Promise.all([1, 2].map(() => post("", { cookies: cookie(launch), payload: proof }))); |
| 85 | const sessionResponse = results.find((response) => response.ok); |
| 86 | assert.ok(sessionResponse); |
| 87 | assert.deepEqual(results.map((response) => response.status).sort(), [200, 401]); |
| 88 | assert.deepEqual(await sessionResponse.json(), { signedIn: true }); |
| 89 | const sessionCookie = cookie(sessionResponse); |
| 90 | assert.match(sessionCookie, /__Secure-airesourcepro\.session_token=/); |
| 91 | const session = await auth.api.getSession({ headers: new Headers({ Cookie: sessionCookie }) }); |
| 92 | assert.equal(session?.user.id, importedId); |
| 93 | assert.equal(session?.user.email, settings.email); |
| 94 | assert.equal(session?.user.provider, provider); |
| 95 | assert.equal(await db.prepare("SELECT tutorial_slug FROM saved_tutorials WHERE user_id = ?") |
| 96 | .bind(session.user.id).first("tutorial_slug"), "claude/example"); |
| 97 | const signOut = await auth.api.signOut({ headers: new Headers({ Cookie: sessionCookie, Origin: origin }), asResponse: true }); |
| 98 | assert.ok(signOut.ok); |
| 99 | assert.equal(await auth.api.getSession({ headers: new Headers({ Cookie: sessionCookie }) }), null); |
| 100 | } |
| 101 | |
| 102 | for (const scenario of ["wrong-audience", "wrong-nonce", "expired-challenge"]) { |
| 103 | const launch = await post("/challenge"); |
| 104 | const { nonce } = await launch.json(); |
| 105 | if (scenario === "expired-challenge") await db.prepare("UPDATE sign_in_challenge SET expires_at = 0").run(); |
| 106 | const token = await signedToken("google", scenario === "wrong-nonce" ? "wrong" : nonce, |
| 107 | scenario === "wrong-audience" ? "other-client.apps.googleusercontent.com" : undefined); |
| 108 | assert.equal((await post("", { cookies: cookie(launch), payload: { provider: "google", token } })).status, 401); |
| 109 | } |
| 110 | assert.equal(await db.prepare('SELECT count(*) AS total FROM "user"').first("total"), 2); |
| 111 | } finally { |
| 112 | await runtime.dispose(); |
| 113 | } |
| 114 | }); |