import crypto from 'node:crypto'; import fs from 'node:fs'; import http from 'node:http'; import os from 'node:os'; import path from 'node:path'; import * as OTPAuth from 'otpauth'; import { afterEach, describe, expect, it, vi } from 'vitest'; import { createGCoordinatorServer } from '../src/server/app.js'; const cleanups: Array<() => Promise | void> = []; class CookieJar { private cookies = new Map(); updateFrom(res: Response): void { const getSetCookie = (res.headers as unknown as { getSetCookie?: () => string[] }).getSetCookie; const rawList = typeof getSetCookie === 'function' ? getSetCookie.call(res.headers) : []; for (const line of rawList) { const first = line.split(';')[0] ?? ''; const eq = first.indexOf('='); if (eq > 0) { const name = first.slice(0, eq).trim(); const val = first.slice(eq + 1).trim(); if (val === '') this.cookies.delete(name); else this.cookies.set(name, val); } } } header(): string { return [...this.cookies.entries()].map(([k, v]) => `${k}=${v}`).join('; '); } } function cborBytes(buf: Buffer): Buffer { if (buf.length < 24) return Buffer.concat([Buffer.from([0x40 | buf.length]), buf]); if (buf.length < 256) return Buffer.concat([Buffer.from([0x58, buf.length]), buf]); const hdr = Buffer.allocUnsafe(3); hdr[0] = 0x59; hdr.writeUInt16BE(buf.length, 1); return Buffer.concat([hdr, buf]); } function cborText(str: string): Buffer { const b = Buffer.from(str, 'utf8'); return Buffer.concat([Buffer.from([0x60 | b.length]), b]); } function buildSyntheticAuthenticator(rpID: string, expectedOrigin: string) { const { publicKey, privateKey } = crypto.generateKeyPairSync('ec', { namedCurve: 'prime256v1' }); const jwk = publicKey.export({ format: 'jwk' }) as { x: string; y: string }; const xBuf = Buffer.from(jwk.x, 'base64url'); const yBuf = Buffer.from(jwk.y, 'base64url'); const credIdBuf = crypto.randomBytes(32); const credId = credIdBuf.toString('base64url'); const rpIdHash = crypto.createHash('sha256').update(rpID).digest(); let counter = 1; const createRegistrationResponse = (challenge: string) => { const cosePublicKey = Buffer.concat([ Buffer.from([0xa5]), Buffer.from([0x01, 0x02]), // kty: EC2 (2) Buffer.from([0x03, 0x26]), // alg: ES256 (-7) Buffer.from([0x20, 0x01]), // crv: P-256 (1) Buffer.from([0x21]), cborBytes(xBuf), Buffer.from([0x22]), cborBytes(yBuf), ]); const lenBuf = Buffer.allocUnsafe(2); lenBuf.writeUInt16BE(credIdBuf.length, 0); const cntBuf = Buffer.allocUnsafe(4); cntBuf.writeUInt32BE(counter, 0); const authData = Buffer.concat([ rpIdHash, Buffer.from([0x45]), // UP + UV + AT cntBuf, Buffer.alloc(16, 0), // zero AAGUID lenBuf, credIdBuf, cosePublicKey, ]); const attestationObject = Buffer.concat([ Buffer.from([0xa3]), cborText('fmt'), cborText('none'), cborText('attStmt'), Buffer.from([0xa0]), cborText('authData'), cborBytes(authData), ]); const clientDataJSON = Buffer.from( JSON.stringify({ type: 'webauthn.create', challenge, origin: expectedOrigin, crossOrigin: false, }), ); return { id: credId, rawId: credId, type: 'public-key', clientExtensionResults: {}, response: { clientDataJSON: clientDataJSON.toString('base64url'), attestationObject: attestationObject.toString('base64url'), transports: ['internal'], }, }; }; const createAuthenticationResponse = (challenge: string) => { counter += 1; const cntBuf = Buffer.allocUnsafe(4); cntBuf.writeUInt32BE(counter, 0); const authenticatorData = Buffer.concat([ rpIdHash, Buffer.from([0x05]), // UP + UV cntBuf, ]); const clientDataJSON = Buffer.from( JSON.stringify({ type: 'webauthn.get', challenge, origin: expectedOrigin, crossOrigin: false, }), ); const signedPayload = Buffer.concat([ authenticatorData, crypto.createHash('sha256').update(clientDataJSON).digest(), ]); const signature = crypto.sign('sha256', signedPayload, privateKey); return { id: credId, rawId: credId, type: 'public-key', clientExtensionResults: {}, response: { clientDataJSON: clientDataJSON.toString('base64url'), authenticatorData: authenticatorData.toString('base64url'), signature: signature.toString('base64url'), }, }; }; return { credId, createRegistrationResponse, createAuthenticationResponse }; } afterEach(async () => { vi.useRealTimers(); while (cleanups.length > 0) { await cleanups.pop()!(); } }); describe('WebAuthn Passkey Registration, Login & Step-Up', () => { it('registers a Passkey on localhost, rejects raw IP RP IDs, performs passwordless login & step-up, blocks challenge replay, and deletes passkey', async () => { const dataDir = fs.mkdtempSync(path.join(os.tmpdir(), 'gcoord-passkey-test-')); const server = await createGCoordinatorServer({ dataDir, port: 0, host: '127.0.0.1', publicDir: path.resolve('dist/public'), watchConfig: false, }); cleanups.push(async () => { await server.close(); fs.rmSync(dataDir, { recursive: true, force: true }); }); const origin = `http://localhost:${server.port}`; const jar = new CookieJar(); let csrfToken = ''; const api = async ( pathname: string, opts: { method?: string; body?: unknown; customOrigin?: string } = {}, ) => { const headers: Record = { Origin: opts.customOrigin ?? origin, Host: `localhost:${server.port}`, }; if (jar.header()) headers.Cookie = jar.header(); const payload = opts.body !== undefined ? JSON.stringify(opts.body) : undefined; if (payload !== undefined) { headers['Content-Type'] = 'application/json'; headers['Content-Length'] = String(Buffer.byteLength(payload)); } if (csrfToken) headers['X-CSRF-Token'] = csrfToken; const res = await new Promise<{ status: number; setCookies: string[]; text: string }>( (resolve, reject) => { const req = http.request( { host: '127.0.0.1', port: server.port, path: pathname, method: opts.method ?? 'GET', headers, }, (incoming) => { const chunks: Buffer[] = []; incoming.on('data', (c) => chunks.push(Buffer.from(c))); incoming.on('end', () => { const rawSetCookie = incoming.headers['set-cookie']; resolve({ status: incoming.statusCode ?? 0, setCookies: Array.isArray(rawSetCookie) ? rawSetCookie : [], text: Buffer.concat(chunks).toString('utf8'), }); }); }, ); req.on('error', reject); if (payload !== undefined) req.write(payload); req.end(); }, ); for (const line of res.setCookies) { const first = line.split(';')[0] ?? ''; const eq = first.indexOf('='); if (eq > 0) { const name = first.slice(0, eq).trim(); const val = first.slice(eq + 1).trim(); if (val === '') jar['cookies'].delete(name); else jar['cookies'].set(name, val); } } let data: Record = {}; try { data = JSON.parse(res.text) as Record; } catch { data = {}; } if (typeof data.csrfToken === 'string' && data.csrfToken) { csrfToken = data.csrfToken; } return { status: res.status, data }; }; vi.useFakeTimers({ toFake: ['Date'] }); vi.setSystemTime(Date.now() - 35_000); const bootInfo = await api('/api/auth/bootstrap'); const secretBase32 = String(bootInfo.data.secretBase32); const totp = new OTPAuth.TOTP({ issuer: 'GCoordinator', label: 'admin', algorithm: 'SHA1', digits: 6, period: 30, secret: OTPAuth.Secret.fromBase32(secretBase32), }); expect( ( await api('/api/auth/bootstrap', { method: 'POST', body: { username: 'admin', password: 'passkey-test-password-1', totpCode: totp.generate(), secretBase32, }, }) ).status, ).toBe(201); vi.useRealTimers(); expect( (await api('/api/auth/step-up', { method: 'POST', body: { code: totp.generate() } })).status, ).toBe(200); await api('/api/vault/init', { method: 'POST', body: {} }); await api('/api/vault/generate-ed25519', { method: 'POST', body: { id: 'pk-test-key', name: 'PK Test Key' }, }); // Rejects raw IP RP IDs clearly const ipReject = await api('/api/auth/factors/passkeys/register/options', { method: 'POST', body: { label: 'My Phone' }, customOrigin: `http://127.0.0.1:${server.port}`, }); expect(ipReject.status).toBe(400); expect(ipReject.data.error).toBe('WEBAUTHN_RPID_INVALID'); // 1. Register Passkey on localhost const authn = buildSyntheticAuthenticator('localhost', origin); const regOpts = await api('/api/auth/factors/passkeys/register/options', { method: 'POST', body: { label: 'Pixel Firefox' }, }); expect(regOpts.status).toBe(200); const regChallenge = String((regOpts.data.options as { challenge: string }).challenge); const regVerify = await api('/api/auth/factors/passkeys/register/verify', { method: 'POST', body: { challengeId: String(regOpts.data.challengeId), response: authn.createRegistrationResponse(regChallenge), }, }); expect(regVerify.status).toBe(201); const status1 = await api('/api/auth/status'); expect((status1.data.authRequirements as { passkeyCount: number }).passkeyCount).toBe(1); // 2. Logout & Passwordless Login with Passkey await api('/api/auth/logout', { method: 'POST' }); csrfToken = ''; const loginOpts = await api('/api/auth/passkeys/login/options', { method: 'POST', body: {}, }); expect(loginOpts.status).toBe(200); const loginChallenge = String((loginOpts.data.options as { challenge: string }).challenge); const assertion1 = authn.createAuthenticationResponse(loginChallenge); const loginVerify = await api('/api/auth/passkeys/login/verify', { method: 'POST', body: { challengeId: String(loginOpts.data.challengeId), response: assertion1, }, }); expect(loginVerify.status).toBe(200); expect(loginVerify.data.authenticated).toBe(true); // Replaying exact same challenge must fail (single-use challenge) await api('/api/auth/logout', { method: 'POST' }); csrfToken = ''; const replayVerify = await api('/api/auth/passkeys/login/verify', { method: 'POST', body: { challengeId: String(loginOpts.data.challengeId), response: assertion1, }, }); expect(replayVerify.status).toBe(401); // Re-login cleanly via passkey const loginOpts2 = await api('/api/auth/passkeys/login/options', { method: 'POST', body: {} }); const loginVerify2 = await api('/api/auth/passkeys/login/verify', { method: 'POST', body: { challengeId: String(loginOpts2.data.challengeId), response: authn.createAuthenticationResponse( String((loginOpts2.data.options as { challenge: string }).challenge), ), }, }); expect(loginVerify2.status).toBe(200); // 3. Step-Up Verification via Passkey requires stepUpMethod === 'passkey' await api('/api/auth/drop-elevation', { method: 'POST' }); expect((await api('/api/vault/credentials/pk-test-key/reveal')).status).toBe(403); const deniedOpts = await api('/api/auth/passkeys/step-up/options', { method: 'POST', body: {} }); expect(deniedOpts.status).toBe(200); const deniedVerify = await api('/api/auth/passkeys/step-up/verify', { method: 'POST', body: { challengeId: String(deniedOpts.data.challengeId), response: authn.createAuthenticationResponse( String((deniedOpts.data.options as { challenge: string }).challenge), ), }, }); expect(deniedVerify.status).toBe(403); expect(deniedVerify.data.reason).toBe('passkey_stepup_not_enabled'); // Step up with TOTP in next step, enable stepUpMethod = 'passkey', then drop & verify passkey step-up vi.useFakeTimers({ toFake: ['Date'] }); vi.setSystemTime(Date.now() + 35_000); expect( (await api('/api/auth/step-up', { method: 'POST', body: { code: totp.generate() } })).status, ).toBe(200); expect( ( await api('/api/auth/security-policy', { method: 'PUT', body: { stepUpMethod: 'passkey' }, }) ).status, ).toBe(200); await api('/api/auth/drop-elevation', { method: 'POST' }); expect((await api('/api/vault/credentials/pk-test-key/reveal')).status).toBe(403); const stepOpts = await api('/api/auth/passkeys/step-up/options', { method: 'POST', body: {} }); expect(stepOpts.status).toBe(200); const stepVerify = await api('/api/auth/passkeys/step-up/verify', { method: 'POST', body: { challengeId: String(stepOpts.data.challengeId), response: authn.createAuthenticationResponse( String((stepOpts.data.options as { challenge: string }).challenge), ), }, }); expect(stepVerify.status).toBe(200); expect(typeof stepVerify.data.elevatedUntil).toBe('number'); expect((await api('/api/vault/credentials/pk-test-key/reveal')).status).toBe(200); // 4. Cannot delete the last passkey while stepUpMethod === 'passkey' const blockedDel = await api(`/api/auth/factors/passkeys/${encodeURIComponent(authn.credId)}`, { method: 'DELETE', }); expect(blockedDel.status).toBe(400); // Switch stepUpMethod back to 'totp', then delete passkey cleanly expect( ( await api('/api/auth/security-policy', { method: 'PUT', body: { stepUpMethod: 'totp' }, }) ).status, ).toBe(200); const delRes = await api(`/api/auth/factors/passkeys/${encodeURIComponent(authn.credId)}`, { method: 'DELETE', }); expect(delRes.status).toBe(200); const status2 = await api('/api/auth/status'); expect((status2.data.authRequirements as { passkeyCount: number }).passkeyCount).toBe(0); }); });