Lumen & Gesso / website · lumengesso.com / 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 { convertV4MiniflareOptions, Miniflare } from 'miniflare'; |
| 6 | import { createD1Auth } from '../app/lib/d1-auth.ts'; |
| 7 | |
| 8 | test('email sign-in preserves the imported ID, consumes the link, and revokes the session on sign-out', async () => { |
| 9 | const runtime = new Miniflare(convertV4MiniflareOptions({ |
| 10 | modules: true, |
| 11 | script: 'export default { fetch: () => new Response() }', |
| 12 | compatibilityDate: '2026-11-24', |
| 13 | d1Databases: ['COMMERCE_DB'], |
| 14 | })); |
| 15 | try { |
| 16 | const database = await runtime.getD1Database('COMMERCE_DB'); |
| 17 | const schema = (await readFile(new URL('./migrations/0002_better_auth.sql', import.meta.url), 'utf8')) |
| 18 | + ';' + (await readFile(new URL('./migrations/0003_passkey.sql', import.meta.url), 'utf8')); |
| 19 | await database.batch(schema.split(';').map((sql) => sql.trim()).filter(Boolean) |
| 20 | .map((sql) => database.prepare(sql))); |
| 21 | const importedId = '00000000-0000-4000-8000-000000000001'; |
| 22 | const email = 'lumen-fixture@example.invalid'; |
| 23 | const now = new Date().toISOString(); |
| 24 | await database.prepare('INSERT INTO "user" (id,name,email,"emailVerified","createdAt","updatedAt") VALUES (?, ?, ?, 0, ?, ?)') |
| 25 | .bind(importedId, 'Fixture', email, now, now).run(); |
| 26 | |
| 27 | const origin = 'https://lumengesso.example'; |
| 28 | const secret = randomBytes(48).toString('base64url'); |
| 29 | const links = []; |
| 30 | const auth = createD1Auth(database, origin, secret, async (link) => { links.push(link); }); |
| 31 | const launch = await auth.handler(new Request(origin + '/api/auth/sign-in/magic-link', { |
| 32 | method: 'POST', |
| 33 | headers: { Origin: origin, 'Content-Type': 'application/json', 'cf-connecting-ip': '192.0.2.1' }, |
| 34 | body: JSON.stringify({ email, callbackURL: '/orders', errorCallbackURL: '/login?error=link_expired' }), |
| 35 | })); |
| 36 | assert.equal(launch.status, 200); |
| 37 | assert.equal(links.length, 1); |
| 38 | assert.equal(links[0].email, email); |
| 39 | |
| 40 | const complete = await auth.handler(new Request(links[0].url)); |
| 41 | assert.ok([302, 303, 307].includes(complete.status)); |
| 42 | assert.equal(new URL(complete.headers.get('location'), origin).pathname, '/orders'); |
| 43 | const cookie = complete.headers.getSetCookie().map((entry) => entry.split(';', 1)[0]).join('; '); |
| 44 | assert.match(cookie, /__Secure-lumen\.session_token=/); |
| 45 | const session = await auth.api.getSession({ headers: new Headers({ Cookie: cookie }) }); |
| 46 | assert.equal(session?.user.id, importedId); |
| 47 | assert.equal(session?.user.emailVerified, true); |
| 48 | |
| 49 | const secondClick = await auth.handler(new Request(links[0].url)); |
| 50 | assert.match(secondClick.headers.get('location'), /error=INVALID_TOKEN/i); |
| 51 | const signedOut = await auth.api.signOut({ headers: new Headers({ Cookie: cookie, Origin: origin }), asResponse: true }); |
| 52 | assert.ok(signedOut.ok); |
| 53 | assert.equal(await auth.api.getSession({ headers: new Headers({ Cookie: cookie }) }), null); |
| 54 | |
| 55 | await auth.handler(new Request(origin + '/api/auth/sign-in/magic-link', { |
| 56 | method: 'POST', |
| 57 | headers: { Origin: origin, 'Content-Type': 'application/json', 'cf-connecting-ip': '192.0.2.1' }, |
| 58 | body: JSON.stringify({ email: 'missing@example.invalid', callbackURL: '/orders' }), |
| 59 | })); |
| 60 | if (links.length > 1) await auth.handler(new Request(links.at(-1).url)); |
| 61 | const count = await database.prepare('SELECT COUNT(*) n FROM "user"').first('n'); |
| 62 | assert.equal(count, 1); |
| 63 | } finally { |
| 64 | await runtime.dispose(); |
| 65 | } |
| 66 | }); |
| 67 | |
| 68 | test('passkeys are the only sign-in: options work without a session, and no email form endpoint exists', async () => { |
| 69 | const runtime = new Miniflare(convertV4MiniflareOptions({ |
| 70 | modules: true, script: 'export default { fetch: () => new Response() }', compatibilityDate: '2026-11-24', d1Databases: ['COMMERCE_DB'], |
| 71 | })); |
| 72 | try { |
| 73 | const database = await runtime.getD1Database('COMMERCE_DB'); |
| 74 | const schema = (await readFile(new URL('./migrations/0002_better_auth.sql', import.meta.url), 'utf8')) |
| 75 | + ';' + (await readFile(new URL('./migrations/0003_passkey.sql', import.meta.url), 'utf8')); |
| 76 | await database.batch(schema.split(';').map((sql) => sql.trim()).filter(Boolean).map((sql) => database.prepare(sql))); |
| 77 | const origin = 'https://lumengesso.example'; |
| 78 | const auth = createD1Auth(database, origin, randomBytes(48).toString('base64url'), async () => {}); |
| 79 | const headers = { Origin: origin, 'Content-Type': 'application/json', 'cf-connecting-ip': '192.0.2.9' }; |
| 80 | const signIn = await auth.handler(new Request(origin + '/api/auth/passkey/generate-authenticate-options', { method: 'GET', headers })); |
| 81 | assert.equal(signIn.status, 200); |
| 82 | const opts = await signIn.json(); |
| 83 | assert.ok(opts.challenge); |
| 84 | assert.equal(opts.rpId, 'lumengesso.example'); |
| 85 | assert.equal(opts.userVerification, 'required'); |
| 86 | const register = await auth.handler(new Request(origin + '/api/auth/passkey/generate-register-options', { method: 'GET', headers })); |
| 87 | assert.equal(register.status, 200); |
| 88 | const reg = await register.json(); |
| 89 | assert.equal(reg.rp.id, 'lumengesso.example'); |
| 90 | assert.equal(reg.authenticatorSelection.residentKey, 'required'); |
| 91 | assert.equal(reg.authenticatorSelection.userVerification, 'required'); |
| 92 | } finally { |
| 93 | await runtime.dispose(); |
| 94 | } |
| 95 | }); |