test(auth): add end-to-end WebAuthn Passkey registration, login, and step-up tests

This commit is contained in:
tyuXX 2026-11-26 22:08:45 +00:00
parent 9040c426e8
commit c5a5835ae6

341
tests/passkeys.test.ts Normal file
View file

@ -0,0 +1,341 @@
import crypto from 'node:crypto';
import fs from 'node:fs';
import os from 'node:os';
import path from 'node:path';
import * as OTPAuth from 'otpauth';
import { afterEach, describe, expect, it } from 'vitest';
import { createGCoordinatorServer } from '../src/server/app.js';
const cleanups: Array<() => Promise<void> | void> = [];
class CookieJar {
private cookies = new Map<string, string>();
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 () => {
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 baseUrl = `http://127.0.0.1:${server.port}`;
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<string, string> = {
Origin: opts.customOrigin ?? origin,
Host: `localhost:${server.port}`,
};
if (jar.header()) headers.Cookie = jar.header();
if (opts.body !== undefined) headers['Content-Type'] = 'application/json';
if (csrfToken) headers['X-CSRF-Token'] = csrfToken;
const res = await fetch(`${baseUrl}${pathname}`, {
method: opts.method ?? 'GET',
headers,
body: opts.body !== undefined ? JSON.stringify(opts.body) : undefined,
});
jar.updateFrom(res);
const data = (await res.json().catch(() => ({}))) as Record<string, unknown>;
if (typeof data.csrfToken === 'string' && data.csrfToken) {
csrfToken = data.csrfToken;
}
return { status: res.status, data };
};
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);
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
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. Delete passkey factor
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);
});
});