SPB Git

Repository Public

webauthn.test.ts 14.5 KB 192 lines typescript

1/**2 * =============================================================================3 *                  SP BOUCHER | SOFTWARE & RESEARCH4 *             ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING5 * =============================================================================6 *7 * Project          : Note SPBoucher AI8 * File             : tests/unit/webauthn.test.ts9 * Module           : tests10 * Repository       : https://git.spboucher.ai/note-spboucher-ai11 * Project Website  : https://note.spboucher.ai12 * Created          : 2026-11-1713 * Last Modified    : 2026-11-1714 *15 * Author           : Simon-Pierre Boucher16 * Position         : Professor of Finance17 * Institution      : Université du Québec en Outaouais (UQO)18 * Organization     : SP Boucher19 * Website          : https://spboucher.ai20 * Git              : https://git.spboucher.ai21 *22 * Preferred Contact: contact@spboucher.ai23 * Development      : dev@spboucher.ai24 * Support          : support@spboucher.ai25 * Security/Admin   : admin@spboucher.ai26 *27 * Copyright (c) 202628 * Simon-Pierre Boucher29 * All rights reserved where applicable. This file is governed by the30 * applicable project license, copyright notices and relevant law.31 * Existing third-party rights and notices remain unaffected.32 *33 * License          : None specified (no license file in this repository)34 *35 * Do not embed credentials, private keys, access tokens,36 * certificates or confidential personal information.37 *38 * =============================================================================39 * END OF SP BOUCHER SOURCE HEADER40 * =============================================================================41 */4243/**44 * Server-side WebAuthn verification, attacked with a software authenticator. Run: pnpm test (DATABASE_URL must point to a *_dev database).45 */46import "../helpers/testdb";47import { test, before, after } from "node:test";48import assert from "node:assert/strict";49import { eq } from "drizzle-orm";50import { db, schema, sql } from "../../src/db/index";51import { authenticationOptions, registrationOptions, verifyAuthentication, verifyRegistration, CeremonyError } from "../../src/lib/auth/webauthn";52import { allowedOrigins, rpId } from "../../src/lib/auth/config";53import { closeEnrollments, consumeEnrollment, findEnrollment, openEnrollment } from "../../src/lib/auth/enrollment";54import { createSession, resolveSession, revokeAllSessions, revokeSession, rotateSession, ownerRow } from "../../src/lib/auth/sessions";55import { sha256 } from "../../src/lib/auth/tokens";56import { SoftAuthenticator } from "../helpers/softauthn";5758const ORIGIN = allowedOrigins()[0];59let owner: NonNullable<Awaited<ReturnType<typeof ownerRow>>>;60const mine: string[] = []; // credentials created by this file (removed afterwards)61const code = async (p: Promise<unknown>) => { try { await p; return "ok"; } catch (e) { if (e instanceof CeremonyError) return e.code; throw e; } };6263async function enroll(auth = new SoftAuthenticator()) {64  const { options, challengeId } = await registrationOptions("register", owner, { sessionId: null });65  const reg = await verifyRegistration("register", challengeId, auth.register(options, ORIGIN) as any, { userId: owner.id, sessionId: null, label: "unit-test" });66  mine.push(reg.credentialId); return auth;67}68before(async () => { const o = await ownerRow(); assert.ok(o, "owner row missing — run pnpm bootstrap on the test database"); owner = o; });69after(async () => { for (const id of mine) await db.delete(schema.webauthnCredentials).where(eq(schema.webauthnCredentials.id, id)); await sql.end(); });7071test("registration: valid response is accepted and stores only public material", async () => {72  const a = await enroll();73  const [row] = await db.select().from(schema.webauthnCredentials).where(eq(schema.webauthnCredentials.id, a.credentialId.toString("base64url")));74  assert.ok(row); assert.equal(row.userId, owner.id); assert.equal(row.counter, 0); assert.ok(row.publicKey.length > 40);75  assert.deepEqual(Object.keys(row).sort(), ["aaguid", "backedUp", "counter", "createdAt", "deviceType", "id", "label", "lastUsedAt", "publicKey", "transports", "userId"].sort());76});77test("registration: wrong origin, wrong RP ID, wrong type, no user verification are refused", async () => {78  for (const o of [{ origin: "https://evil.example" }, { rpId: "evil.example" }, { type: "webauthn.get" }, { uv: false }, { up: false }]) {79    const a = new SoftAuthenticator(); const { options, challengeId } = await registrationOptions("register", owner, { sessionId: null });80    assert.equal(await code(verifyRegistration("register", challengeId, a.register(options, ORIGIN, o) as any, { userId: owner.id, sessionId: null, label: "x" })), "verification_failed", JSON.stringify(o));81    const rows = await db.select().from(schema.webauthnCredentials).where(eq(schema.webauthnCredentials.id, a.credentialId.toString("base64url"))); assert.equal(rows.length, 0);82  }83});84test("registration: a challenge issued for another session or kind cannot be used", async () => {85  const a = new SoftAuthenticator(); const { options, challengeId } = await registrationOptions("register", owner, { sessionId: "11111111-1111-1111-1111-111111111111" });86  assert.equal(await code(verifyRegistration("register", challengeId, a.register(options, ORIGIN) as any, { userId: owner.id, sessionId: "22222222-2222-2222-2222-222222222222", label: "x" })), "challenge_mismatch");87  const r2 = await registrationOptions("register", owner, { sessionId: null });88  assert.equal(await code(verifyRegistration("enroll", r2.challengeId, a.register(r2.options, ORIGIN) as any, { userId: owner.id, enrollmentId: null, label: "x" })), "challenge_used");89});90test("authentication: valid assertion passes and the counter advances", async () => {91  const a = await enroll(); const { options, challengeId } = await authenticationOptions("login", {});92  assert.equal(options.userVerification, "required"); assert.equal(options.rpId, rpId());93  const v = await verifyAuthentication("login", challengeId, a.assert(options, ORIGIN) as any);94  assert.equal(v.userId, owner.id);95  const [row] = await db.select().from(schema.webauthnCredentials).where(eq(schema.webauthnCredentials.id, v.credentialId)); assert.equal(row.counter, 1); assert.ok(row.lastUsedAt);96});97test("authentication: replay of the same response is refused (single-use challenge)", async () => {98  const a = await enroll(); const { options, challengeId } = await authenticationOptions("login", {}); const response = a.assert(options, ORIGIN) as any;99  await verifyAuthentication("login", challengeId, response);100  assert.equal(await code(verifyAuthentication("login", challengeId, response)), "challenge_used");101});102test("authentication: a failed verification also burns the challenge", async () => {103  const a = await enroll(); const { options, challengeId } = await authenticationOptions("login", {});104  assert.equal(await code(verifyAuthentication("login", challengeId, a.assert(options, ORIGIN, { tamperSignature: true }) as any)), "verification_failed");105  assert.equal(await code(verifyAuthentication("login", challengeId, a.assert(options, ORIGIN) as any)), "challenge_used");106});107test("authentication: expired challenge is refused", async () => {108  const a = await enroll(); const { options, challengeId } = await authenticationOptions("login", {});109  await db.update(schema.webauthnChallenges).set({ expiresAt: new Date(Date.now() - 1000) }).where(eq(schema.webauthnChallenges.id, challengeId));110  assert.equal(await code(verifyAuthentication("login", challengeId, a.assert(options, ORIGIN) as any)), "challenge_expired");111});112test("authentication: wrong origin / RP ID / type / challenge / missing UV / forged signature are refused", async () => {113  const a = await enroll();114  for (const o of [{ origin: "https://evil.example" }, { origin: ORIGIN.replace("://", "://x.") }, { rpId: "evil.example" }, { type: "webauthn.create" }, { challenge: "AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA" }, { uv: false }, { tamperSignature: true }]) {115    const { options, challengeId } = await authenticationOptions("login", {});116    assert.equal(await code(verifyAuthentication("login", challengeId, a.assert(options, ORIGIN, o) as any)), "verification_failed", JSON.stringify(o));117  }118});119test("authentication: unknown credential and missing/garbage challenge ids are refused", async () => {120  const stranger = new SoftAuthenticator(); const { options, challengeId } = await authenticationOptions("login", {});121  assert.equal(await code(verifyAuthentication("login", challengeId, stranger.assert(options, ORIGIN) as any)), "unknown_credential");122  const a = await enroll(); const o2 = await authenticationOptions("login", {});123  assert.equal(await code(verifyAuthentication("login", null, a.assert(o2.options, ORIGIN) as any)), "challenge_missing");124  assert.equal(await code(verifyAuthentication("login", "not-a-uuid", a.assert(o2.options, ORIGIN) as any)), "challenge_missing");125  assert.equal(await code(verifyAuthentication("reauth", o2.challengeId, a.assert(o2.options, ORIGIN) as any)), "challenge_used"); // wrong kind126});127test("authentication: a signature counter that goes backwards is refused (cloned authenticator)", async () => {128  const a = await enroll(); let c = await authenticationOptions("login", {});129  await verifyAuthentication("login", c.challengeId, a.assert(c.options, ORIGIN, { counter: 10 }) as any);130  c = await authenticationOptions("login", {});131  assert.equal(await code(verifyAuthentication("login", c.challengeId, a.assert(c.options, ORIGIN, { counter: 5 }) as any)), "verification_failed");132});133test("step-up: the challenge is bound to the session that asked for it", async () => {134  const a = await enroll(); const s1 = "33333333-3333-3333-3333-333333333333", s2 = "44444444-4444-4444-4444-444444444444";135  const { options, challengeId } = await authenticationOptions("reauth", { userId: owner.id, sessionId: s1 });136  assert.ok((options.allowCredentials ?? []).length >= 1);137  assert.equal(await code(verifyAuthentication("reauth", challengeId, a.assert(options, ORIGIN) as any, { sessionId: s2 })), "challenge_mismatch");138});139140test("sessions: random token, only the hash is stored, revocation is immediate", async () => {141  const s = await createSession({ userId: owner.id, credentialId: null, userAgent: "Mozilla/5.0 (iPhone; CPU iPhone OS 18_0 like Mac OS X) Safari/604.1", ip: "127.0.0.1" });142  assert.match(s.token, /^[A-Za-z0-9_-]{43}$/);143  const [row] = await db.select().from(schema.sessions).where(eq(schema.sessions.id, s.id));144  assert.equal(row.tokenHash, sha256(s.token)); assert.ok(!JSON.stringify(row).includes(s.token)); assert.equal(row.label, "Safari · iPhone");145  const other = await createSession({ userId: owner.id, credentialId: null, userAgent: null, ip: null }); assert.notEqual(other.token, s.token);146  assert.equal((await resolveSession(s.token))?.id, s.id); assert.equal((await resolveSession(s.token))?.fresh, true);147  assert.equal(await resolveSession(s.token.slice(0, -1) + (s.token.endsWith("A") ? "B" : "A")), null);148  assert.equal(await resolveSession(""), null); assert.equal(await resolveSession("x".repeat(43) + "'"), null);149  await revokeSession(s.id, "test"); assert.equal(await resolveSession(s.token), null);150  await revokeSession(other.id, "test");151});152test("sessions: rotation issues a new token; the old one dies after the grace period; freshness expires", async () => {153  const s = await createSession({ userId: owner.id, credentialId: null, userAgent: null, ip: null });154  const r = await rotateSession(s.id, null); assert.ok(r); assert.notEqual(r!.token, s.token);155  assert.equal((await resolveSession(r!.token))?.id, s.id);156  assert.equal((await resolveSession(s.token))?.id, s.id, "old token valid during the 60 s grace");157  await db.update(schema.sessions).set({ prevValidUntil: new Date(Date.now() - 1000) }).where(eq(schema.sessions.id, s.id));158  assert.equal(await resolveSession(s.token), null, "old token dead after grace");159  await db.update(schema.sessions).set({ verifiedAt: new Date(Date.now() - 6 * 60_000) }).where(eq(schema.sessions.id, s.id));160  assert.equal((await resolveSession(r!.token))?.fresh, false);161  await db.update(schema.sessions).set({ expiresAt: new Date(Date.now() - 1000) }).where(eq(schema.sessions.id, s.id));162  assert.equal(await resolveSession(r!.token), null, "idle-expired session is dead");163  await revokeSession(s.id, "test");164});165test("sessions: global revocation spares only the excepted session", async () => {166  const a = await createSession({ userId: owner.id, credentialId: null, userAgent: null, ip: null }); const b = await createSession({ userId: owner.id, credentialId: null, userAgent: null, ip: null });167  // only revoke the two sessions of this test: emulate with exceptId, then clean up168  const before = await resolveSession(a.token); assert.ok(before);169  await revokeSession(b.id, "test"); assert.equal(await resolveSession(b.token), null); assert.ok(await resolveSession(a.token));170  await revokeSession(a.id, "test"); void revokeAllSessions;171});172173test("enrollment: bootstrap is refused once a passkey exists; recovery window is single-use, expiring, token stored hashed", async () => {174  await enroll();175  await assert.rejects(openEnrollment("bootstrap"), /already exists/);176  const w = await openEnrollment("recovery", { minutes: 5 });177  const [row] = await db.select().from(schema.authEnrollments).where(eq(schema.authEnrollments.id, w.id));178  assert.equal(row.tokenHash, sha256(w.token)); assert.ok(!JSON.stringify(row).includes(w.token)); assert.equal(row.revokeExisting, true);179  assert.ok(row.expiresAt.getTime() - Date.now() <= 5 * 60_000 + 1000);180  assert.equal((await findEnrollment(w.token))?.id, w.id);181  assert.equal(await findEnrollment(w.token.slice(0, -2) + "zz"), null); assert.equal(await findEnrollment(""), null);182  assert.equal(await consumeEnrollment(w.id), true); assert.equal(await consumeEnrollment(w.id), false, "second consume loses");183  assert.equal(await findEnrollment(w.token), null, "consumed window is closed");184  const w2 = await openEnrollment("recovery", { minutes: 1 });185  await db.update(schema.authEnrollments).set({ expiresAt: new Date(Date.now() - 1000) }).where(eq(schema.authEnrollments.id, w2.id));186  assert.equal(await findEnrollment(w2.token), null, "expired window is closed");187  const w3 = await openEnrollment("recovery"); const w4 = await openEnrollment("recovery");188  assert.equal(await findEnrollment(w3.token), null, "opening a new window closes the previous one"); assert.ok(await findEnrollment(w4.token));189  assert.equal(await closeEnrollments("test"), 1); assert.equal(await findEnrollment(w4.token), null);190  const w5 = await openEnrollment("recovery", { minutes: 100000 }); assert.equal(w5.minutes, 60, "window length is capped"); await closeEnrollments("test");191});192
Files main
Menu

Theme