SPB Git

Repository Public

auth.spec.ts 14.2 KB 167 lines typescript

1/**2 * =============================================================================3 *                  SP BOUCHER | SOFTWARE & RESEARCH4 *             ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING5 * =============================================================================6 *7 * Project          : Note SPBoucher AI8 * File             : tests/e2e/auth.spec.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-1914 *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 */4243import { test, expect } from "@playwright/test";44import fs from "node:fs";45import { cli, enrollmentToken, sql, STATE, virtualAuthenticator, withSavedPasskey, saveState, expectNoHorizontalOverflow, ORIGIN } from "./helpers";4647const saved = () => JSON.parse(fs.readFileSync(STATE, "utf8"));48test.describe.configure({ mode: "serial" });4950test("nothing private is reachable without a session", async ({ page, request }) => {51  await page.goto("/"); await expect(page).toHaveURL(/\/login$/);52  await expect(page.getByRole("heading", { name: "Private space" })).toBeVisible();53  const html = await page.content(); expect(html).not.toMatch(/Workspace|sidebar|note-editor/i);54  await page.goto("/p/00000000-0000-0000-0000-000000000000"); await expect(page).toHaveURL(/\/login\?next=/);55  for (const u of ["/api/tree", "/api/pages", "/api/search?q=a", "/api/settings", "/api/auth/passkeys", "/api/auth/sessions", "/api/auth/state", "/api/export?format=json", "/api/files/00000000-0000-0000-0000-000000000000", "/api/backups", "/api/dashboard"]) expect((await request.get(u)).status(), u).toBe(401);56  for (const u of ["/gate", "/unlock/abcdefgh", "/api/gate", "/api/lock"]) expect((await request.get(u)).status(), u).toBe(404);57  expect((await request.get("/api/health")).status()).toBe(200);58  await expectNoHorizontalOverflow(page);59});60test("every API route refuses anonymous reads and writes", async ({ request }) => {61  const routes: string[] = []; const walk = (d: string) => { for (const e of fs.readdirSync(d, { withFileTypes: true })) { if (e.isDirectory()) walk(`${d}/${e.name}`); else if (e.name === "route.ts") routes.push(d.replace("src/app", "").replace(/\[[^\]]+\]/g, "00000000-0000-0000-0000-000000000000")); } }; walk("src/app/api");62  const open = new Set(["/api/health", "/api/auth/login/options", "/api/auth/login/verify", "/api/auth/enroll/options", "/api/auth/enroll/verify", "/api/auth/logout"]);63  expect(routes.length).toBeGreaterThan(50);64  for (const r of routes.filter((r) => !open.has(r))) {65    const g = await request.get(r); expect([401], `GET ${r} → ${g.status()}`).toContain(g.status());66    const p = await request.post(r, { data: {}, headers: { origin: ORIGIN } }); expect([401], `POST ${r} → ${p.status()}`).toContain(p.status());67  }68});69test("ceremony endpoints refuse cross-site callers and unknown tokens", async ({ request }) => {70  expect((await request.post("/api/auth/login/options", { headers: { origin: "https://evil.example" } })).status()).toBe(403);71  expect((await request.post("/api/auth/login/options", { headers: { origin: ORIGIN, "sec-fetch-site": "cross-site" } })).status()).toBe(403);72  const r = await request.post("/api/auth/enroll/options", { headers: { origin: ORIGIN }, data: { token: "A".repeat(43) } }); expect(r.status()).toBe(403); expect((await r.json()).code).toBe("enrollment_closed");73  // a forged assertion (well-formed, unknown credential) is refused, burns its challenge and is audited74  const ctx = await request.post("/api/auth/login/options", { headers: { origin: ORIGIN } }); expect(ctx.status()).toBe(200);75  const forged = { id: "Zm9yZ2VkLWNyZWRlbnRpYWwtaWQ", rawId: "Zm9yZ2VkLWNyZWRlbnRpYWwtaWQ", type: "public-key", response: { clientDataJSON: "e30", authenticatorData: "AAAA", signature: "AAAA" }, clientExtensionResults: {} };76  const v = await request.post("/api/auth/login/verify", { headers: { origin: ORIGIN }, data: { response: forged } }); expect(v.status()).toBe(400); expect((await v.json()).code).toBe("unknown_credential");77  const v2 = await request.post("/api/auth/login/verify", { headers: { origin: ORIGIN }, data: { response: forged } }); expect((await v2.json()).code).toBe("challenge_used");78  const bad = await request.post("/api/auth/login/verify", { headers: { origin: ORIGIN }, data: { response: { id: "x" } } }); expect(bad.status()).toBe(400);79  expect((v.headers()["set-cookie"] ?? "")).not.toContain("note_session");80  await sql`delete from login_attempts`;81});82test("first-passkey window is closed for good once a passkey exists", async ({ page }) => {83  let out = ""; try { out = cli("open-enrollment"); } catch (e: any) { out = String(e.stderr ?? e.message); }84  expect(out).toMatch(/already exists/);85  await page.goto("/enroll#" + "B".repeat(43)); await expect(page.getByRole("heading", { name: "Link closed" })).toBeVisible();86  expect(page.url()).not.toContain("#"); // the token is removed from the address bar87});88test("sign in with the passkey, then lock this device", async ({ page, context }) => {89  await withSavedPasskey(page);90  await page.goto("/settings"); await expect(page).toHaveURL(/\/login\?next=%2Fsettings/);91  await page.getByRole("button", { name: /Continue with/ }).click();92  await expect(page).toHaveURL(/\/settings$/);93  const cookies = await context.cookies(); const c = cookies.find((x) => x.name.endsWith("note_session"))!;94  expect(c.httpOnly).toBe(true); expect(c.sameSite).toBe("Lax"); expect(c.value).toMatch(/^[A-Za-z0-9_-]{43}$/);95  expect(c.expires - Date.now() / 1000).toBeLessThan(91 * 86400);96  const [row] = await sql`select token_hash from sessions where revoked_at is null order by created_at desc limit 1`; expect(row.token_hash).not.toBe(c.value); expect(row.token_hash).toHaveLength(64);97  await page.goto("/settings#security"); await page.getByRole("button", { name: /^Lock$/ }).click(); await page.getByRole("dialog").getByRole("button", { name: "Lock" }).click();98  await expect(page).toHaveURL(/\/login$/);99  expect((await page.request.get("/api/tree")).status()).toBe(401);100  // the revoked token is dead even if replayed by hand101  expect((await page.request.get("/api/tree", { headers: { cookie: `${c.name}=${c.value}` } })).status()).toBe(401);102});103test("a passkey prompt without user verification is refused", async ({ page }) => {104  const a = await virtualAuthenticator(page, { userVerified: false });105  await a.cdp.send("WebAuthn.addCredential", { authenticatorId: a.id, credential: { ...JSON.parse(fs.readFileSync("test-results/.auth/credential.json", "utf8")), signCount: Math.floor((Date.now() - 1_794_000_000_000) / 10) } });106  await page.goto("/login"); await page.getByRole("button", { name: /Continue with/ }).click();107  await expect(page.getByText(/could not be verified|Cancelled\. Tap the button/i)).toBeVisible(); // the browser itself refuses: verification is required and was not performed108  await expect(page).toHaveURL(/\/login/);109  expect((await page.request.get("/api/tree")).status()).toBe(401);110  await sql`delete from login_attempts`;111});112test("sensitive actions need a fresh passkey: add, rename, remove; the last passkey cannot be removed", async ({ browser }) => {113  const ctx = await browser.newContext({ storageState: saved(), viewport: { width: 390, height: 844 }, hasTouch: true, isMobile: true }); const page = await ctx.newPage(); const va = await withSavedPasskey(page);114  await sql`update sessions set verified_at = now() - interval '10 minutes' where revoked_at is null`;115  const stale = await page.request.post("/api/auth/passkeys/options", { headers: { origin: ORIGIN } }); expect(stale.status()).toBe(403); expect((await stale.json()).code).toBe("reauth_required");116  const [cur] = await sql`select id from webauthn_credentials`;117  const only = await page.request.delete(`/api/auth/passkeys/${cur.id}`, { headers: { origin: ORIGIN } }); expect(only.status(), "stale session cannot delete").toBe(403);118  await page.goto("/settings#security");119  const pk = page.locator("#sec-passkeys"); await expect(pk.getByText("E2E phone", { exact: true })).toBeVisible(); await expect(page.getByRole("button", { name: "Remove E2E phone" })).toBeDisabled();120  const before = saved().cookies.find((x: any) => x.name.endsWith("note_session")).value;121  // the same authenticator already holds a passkey: the browser refuses a duplicate and the UI says so122  await page.getByRole("button", { name: "Add a passkey" }).click(); await page.getByRole("dialog").getByLabel("Name").fill("Dup"); await page.getByRole("button", { name: "Continue" }).click();123  await expect(page.getByText(/already holds a passkey/)).toBeVisible();124  const after = (await ctx.cookies()).find((x) => x.name.endsWith("note_session"))!.value; expect(after, "step-up rotates the session token").not.toBe(before);125  expect((await page.request.get("/api/auth/state").then((r) => r.json())).fresh).toBe(true);126  // "second device": an authenticator that does not hold the first passkey127  await va.cdp.send("WebAuthn.clearCredentials", { authenticatorId: va.id });128  await page.getByRole("dialog").getByLabel("Name").fill("Second key"); await page.getByRole("button", { name: "Continue" }).click();129  await expect(pk.getByText("Second key", { exact: true })).toBeVisible();130  await page.getByRole("button", { name: "Rename Second key" }).click(); await page.getByLabel("Passkey name").fill("Spare key"); await page.getByRole("button", { name: "Save" }).click();131  await expect(pk.getByText("Spare key", { exact: true })).toBeVisible();132  await page.getByRole("button", { name: "Remove Spare key" }).click(); await page.getByRole("dialog").getByRole("button", { name: "Remove passkey" }).click();133  await expect(pk.getByText("Spare key", { exact: true })).toHaveCount(0);134  const [{ n }] = await sql`select count(*)::int as n from webauthn_credentials`; expect(n).toBe(1);135  // with a fresh verification the server still refuses to delete the only passkey136  const [c] = await sql`select id from webauthn_credentials`; const last = await page.request.delete(`/api/auth/passkeys/${c.id}`, { headers: { origin: ORIGIN } }); expect(last.status()).toBe(409); expect((await last.json()).code).toBe("last_passkey");137  await saveState(ctx); await expectNoHorizontalOverflow(page); await ctx.close();138});139test("another device can be signed out; global revocation ends every session", async ({ browser }) => {140  const a = await browser.newContext({ storageState: saved() }); const pa = await a.newPage(); await withSavedPasskey(pa);141  const b = await browser.newContext(); const pb = await b.newPage(); await withSavedPasskey(pb);142  await pb.goto("/login"); await pb.getByRole("button", { name: /Continue with/ }).click(); await expect(pb).toHaveURL(/localhost:\d+\/$/);143  await pa.goto("/settings#security"); await expect(pa.locator("#sec-sessions").getByText("this device", { exact: true })).toBeVisible();144  await pa.getByRole("button", { name: "Others" }).click(); await pa.getByRole("dialog").getByRole("button", { name: "Sign out" }).click();145  await expect(pa.getByText(/\d+ sessions? ended/).first()).toBeVisible();146  expect((await pb.request.get("/api/tree")).status(), "other device is out").toBe(401); expect((await pa.request.get("/api/tree")).status()).toBe(200);147  await saveState(a); await a.close(); await b.close();148});149test("recovery: a CLI window replaces every passkey and signs every device out", async ({ browser }) => {150  const old = await browser.newContext({ storageState: saved() }); const po = await old.newPage(); expect((await po.request.get("/api/tree")).status()).toBe(200);151  const token = enrollmentToken(cli("recover", "5"));152  const ctx = await browser.newContext({ viewport: { width: 390, height: 844 }, hasTouch: true, isMobile: true }); const page = await ctx.newPage(); const va = await virtualAuthenticator(page);153  await page.goto(`/enroll#${token}`); await expect(page.getByText(/every previous passkey is deleted/)).toBeVisible();154  await page.getByLabel("Name of this device").fill("E2E phone"); await page.getByRole("button", { name: /Create passkey/ }).click(); await page.getByText("Passkey registered").waitFor(); await page.waitForURL(/\/settings/);155  expect((await po.request.get("/api/tree")).status(), "old session revoked by recovery").toBe(401);156  const rows = await sql`select label from webauthn_credentials`; expect(rows.length).toBe(1);157  const again = await page.request.post("/api/auth/enroll/options", { headers: { origin: ORIGIN }, data: { token } }); expect(again.status(), "window is single use").toBe(403);158  const { credentials } = await va.cdp.send("WebAuthn.getCredentials", { authenticatorId: va.id }); fs.writeFileSync("test-results/.auth/credential.json", JSON.stringify(credentials[0]), { mode: 0o600 });159  await saveState(ctx); await ctx.close(); await old.close(); await sql`delete from login_attempts`;160});161test("audit trail records the security events", async () => {162  const rows = await sql`select distinct action from audit_logs where action like 'auth.%' and created_at > now() - interval '10 minutes'`;163  const got = rows.map((r) => r.action);164  for (const a of ["auth.enrollment_opened", "auth.passkey_bootstrap", "auth.login", "auth.logout", "auth.step_up", "auth.passkey_added", "auth.passkey_renamed", "auth.passkey_revoked", "auth.sessions_revoked_all", "auth.recovery_completed", "auth.login_failed"]) expect(got, a).toContain(a);165});166test.afterAll(async () => { await sql.end(); });167
Files main
Menu

Theme