Accounts: Playwright on the real pages; interaction cookie path fix

The interaction address is now /api/v2/interaction/<uid> (redirecting to
the sign-in page): oidc-provider scopes its cookie to that path, so every
step's API call gets it. Before, a real browser never sent it and every
sign-in 'expired'; the test browser now honours cookie paths too.
8 Playwright tests (deep link, wrong password, foreign return address,
sign-up, reset mid-sign-in, 2FA set-up, account page, admin) on the real
backend with an in-memory database, no Postgres needed.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
2026-11-18 15:01:32 +02:00
co-authored by Claude Opus 5.5
parent e1c6a4cce1
commit fdd53ae4db
12 changed files with 250 additions and 8 deletions
+2
View File
@@ -11,6 +11,8 @@ sign-in settings, linked products and the church profile here.
openid-client), `npm run build`.
- `frontend/`: Next.js 16 pages (sign-in steps, account page, admin, setup), strict CSP with a nonce
per page, the church's colours from its profile.
- `e2e/`: Playwright on the real pages (`npx playwright test` in `apps/accounts`): the backend on an
in-memory database with a test product (`e2e/server.ts`), Next on 3210. No database needed.
- Roles stay in each product: Accounts only knows who someone is (plan §2, "Roles stay in each
product").
- Products sign in with `@crosscode/auth-client` (packages/auth-client).
@@ -51,7 +51,13 @@ export function interactionRouter(ctx: Ctx, provider: Provider) {
return next(req, res, extra);
});
r.get('/interaction/:uid', handle(async (req, res) => next(req, res)));
// Where oidc-provider sends the browser (its cookie's path): on to the sign-in page.
r.get('/interaction/:uid', (req, res) => {
const uid = String(req.params.uid);
res.redirect(303, /^[A-Za-z0-9_-]{10,64}$/.test(uid) ? `/signin?uid=${uid}` : '/account');
});
// The page's state for the current step.
r.get('/interaction/:uid/state', handle(async (req, res) => next(req, res)));
r.post('/interaction/:uid/password', limit(20), step(async (req, _res, p) => { await flow.submitPassword(ctx, p, req.body ?? {}, req); }));
r.post('/interaction/:uid/signup', limit(10, 60), step(async (req, _res, p) => { await flow.signUp(ctx, p, req.body ?? {}); }));
r.post('/interaction/:uid/verify-email', limit(20), step(async (req, _res, p) => { await flow.verifyEmail(ctx, p, req.body?.code); }));
+5 -1
View File
@@ -94,7 +94,11 @@ export async function createProvider(ctx: Ctx): Promise<Provider> {
revocation: { enabled: true },
userinfo: { enabled: true },
},
interactions: { url: (_k, interaction) => `/signin?uid=${interaction.uid}`, policy: policy(ctx) },
// oidc-provider scopes the interaction cookie to this address's path, so it's the API's path for
// the sign-in (every step's call is under it); that address sends the browser on to the page
// (interaction/routes.ts). Absolute, so a proxy that doesn't keep the Host header can't send
// people to the backend's own port.
interactions: { url: (_k, interaction) => `${ctx.config.publicUrl}/api/v2/interaction/${interaction.uid}`, policy: policy(ctx) },
loadExistingGrant: async (k) => {
const grantId = k.oidc.result?.consent?.grantId || k.oidc.session!.grantIdFor(k.oidc.client!.clientId);
if (grantId) {
+1 -1
View File
@@ -162,7 +162,7 @@ describe('the steps in between still return to the page', () => {
const { url } = await browser.follow(started.url, (u) => isCallback(u) || u.pathname === '/signin');
assert.equal(url.pathname, '/signin');
const uid = url.searchParams.get('uid')!;
const view = await h.api(browser, 'GET', `/api/v2/interaction/${uid}`);
const view = await h.api(browser, 'GET', `/api/v2/interaction/${uid}/state`);
assert.equal(view.body.stage, 'notice');
const done = await h.api(browser, 'POST', `/api/v2/interaction/${uid}/notice`, { version: n.version });
const back = await browser.follow(done.body.redirectTo as string, isCallback);
+10 -4
View File
@@ -23,22 +23,28 @@ const listen = (server: http.Server) => new Promise<number>((resolve) => server.
/** A browser: cookies per host, redirects followed by hand so each hop can be checked. */
export class Browser {
private jar = new Map<string, Map<string, string>>();
// Per host: name → value and the cookie's Path, sent only on paths under it (as browsers do;
// oidc-provider scopes its interaction cookie to the interaction's address).
private jar = new Map<string, Map<string, { value: string; path: string }>>();
private cookieHeader(url: URL) {
const c = this.jar.get(url.host);
return c ? [...c].map(([k, v]) => `${k}=${v}`).join('; ') : '';
if (!c) return '';
const under = (p: string) => url.pathname === p || url.pathname.startsWith(p.endsWith('/') ? p : `${p}/`) || p === '/';
return [...c].filter(([, v]) => under(v.path)).map(([k, v]) => `${k}=${v.value}`).join('; ');
}
private store(url: URL, res: Response) {
for (const line of res.headers.getSetCookie()) {
const [pair] = line.split(';');
const [pair, ...attrs] = line.split(';');
const i = pair!.indexOf('=');
const name = pair!.slice(0, i).trim();
const value = pair!.slice(i + 1).trim();
const pathAttr = attrs.map((a) => a.trim()).find((a) => /^path=/i.test(a));
const path = pathAttr ? pathAttr.slice(5) : url.pathname.replace(/\/[^/]*$/, '') || '/';
if (!this.jar.has(url.host)) this.jar.set(url.host, new Map());
if (/expires=Thu, 01 Jan 1970/i.test(line) || /max-age=0/i.test(line) || value === '') this.jar.get(url.host)!.delete(name);
else this.jar.get(url.host)!.set(name, value);
else this.jar.get(url.host)!.set(name, { value, path });
}
}
+1
View File
@@ -0,0 +1 @@
test-results/
+4
View File
@@ -0,0 +1,4 @@
{
"private": true,
"type": "module"
}
+73
View File
@@ -0,0 +1,73 @@
/**
* The e2e backend (playwright.config.ts): Accounts on port 5210 with the in-memory database from the
* backend tests (no Postgres needed), and a test product on 5211 that signs people in through it
* with @crosscode/auth-client, as the Website will. The pages run with `next dev` on 3210 and send
* /api here.
*
* Test helpers on the product: GET /test/code?to=<email or phone> (the last code sent),
* GET /test/link?to=<email> (the last link sent), GET /test/totp?secret=… (the current app code).
*/
import http from 'node:http';
import { accountsClient } from '@crosscode/auth-client';
import { ed25519PublicToPem, generateEd25519, newLinkSecret } from '@crosscode/contracts/signing';
import { createApp } from '../backend/src/app.js';
import { createCtx } from '../backend/src/context.js';
import { loadConfig } from '../backend/src/lib/config.js';
import { MemoryMessenger } from '../backend/src/lib/messages.js';
import { hashPassword } from '../backend/src/lib/passwords.js';
import { codeAt } from '../backend/src/lib/totp.js';
import { createProvider } from '../backend/src/oidc/provider.js';
import { memoryDb } from '../backend/tests/support/memoryDb.js';
const WEB = 'http://localhost:3210';
const PRODUCT = 'http://localhost:5211';
const PRODUCT_ID = '3b0f6a52-6c1e-4b7a-9d0e-2f1a8c4b7e02';
const db = memoryDb();
const messenger = new MemoryMessenger();
// Behind Next's rewrite (as behind nginx in production): the public host comes in X-Forwarded-Host.
const ctx = createCtx(loadConfig({ ACCOUNTS_URL: WEB, NODE_ENV: 'test', JOBS_ENABLED: 'false', LINKS_ALLOW_PRIVATE: 'true', HUB_URL: 'http://127.0.0.1:1', TRUST_PROXY: 'true' }), db as never, { messenger });
await ctx.settings.setMany({
hub_install_id: '9a4c2f1e-7b3d-4e5a-8c6f-0d1e2f3a4b5c',
church_profile: JSON.stringify({ name: 'Hope Family Church', shortName: 'Hope', branding: { logoUrl: null, iconUrl: null, colours: { primary: '#7c2d12', accent: '#f2a900' } } }),
});
const linkSecret = newLinkSecret();
await db.productLink.create({ data: { installId: PRODUCT_ID, product: 'website', url: PRODUCT, publicKey: ed25519PublicToPem(generateEd25519().publicKey), secret: ctx.secrets.encrypt(linkSecret), connectedAt: new Date() } });
const seed = (email: string, extra: Record<string, unknown> = {}) => hashPassword('Correct-horse-1').then((passwordHash) =>
db.account.create({ data: { name: 'Thandi Test', email, emailVerified: true, noticeVersionAccepted: 1, newsAskedAt: new Date(), passwordHash, ...extra } }));
await seed('thandi@hope.test');
await seed('admin@hope.test', { name: 'Ada Admin', role: 'admin' });
const provider = await createProvider(ctx);
http.createServer(createApp(ctx, provider)).listen(5210, '127.0.0.1', () => console.log('[e2e] Accounts on 5210'));
// ─── The test product ────────────────────────────────────────────────────────
// Made on the first sign-in: the pages (and so discovery through them) start after this server.
let authP: ReturnType<typeof accountsClient> | null = null;
const getAuth = () => (authP ??= accountsClient({ accountsUrl: WEB, productUrl: PRODUCT, clientId: PRODUCT_ID, linkSecret, allowInsecure: true }));
const cookieOf = (req: http.IncomingMessage, name: string) => String(req.headers.cookie ?? '').split(';').map((c) => c.trim().split('=')).find(([k]) => k === name)?.[1];
http.createServer(async (req, res) => {
const url = new URL(req.url ?? '/', PRODUCT);
const send = (status: number, body: string, type = 'text/html') => res.writeHead(status, { 'content-type': type }).end(body);
try {
if (url.pathname === '/start') {
const { url: to, cookie } = await (await getAuth()).startSignIn(url.searchParams.get('returnTo') ?? '/', { requireTwoFactor: url.searchParams.get('mfa') === '1' });
res.writeHead(302, { location: to, 'set-cookie': `signin=${cookie}; Path=/; HttpOnly; SameSite=Lax` }).end();
return;
}
if (url.pathname === '/api/auth/callback') {
const r = await (await getAuth()).finishSignIn(url, cookieOf(req, 'signin'));
send(200, `<!doctype html><title>Product</title><h1>Signed in to the product</h1><p id="email">${r.claims.email}</p><p id="return">${r.returnTo}</p><p id="amr">${r.claims.amr.join(' ')}</p>`);
return;
}
if (url.pathname === '/test/code') return send(200, messenger.lastCode(url.searchParams.get('to') ?? '') ?? '', 'text/plain');
if (url.pathname === '/test/link') return send(200, messenger.lastLink(url.searchParams.get('to') ?? '') ?? '', 'text/plain');
if (url.pathname === '/test/totp') return send(200, codeAt(url.searchParams.get('secret') ?? '', Math.floor(Date.now() / 30000)), 'text/plain');
if (req.method === 'POST') return send(200, '{}', 'application/json');
send(200, '<!doctype html><title>Product home</title><h1>Product home</h1>');
} catch (e) {
send(500, `<pre>${String((e as Error).message)}</pre>`);
}
}).listen(5211, '127.0.0.1', () => console.log('[e2e] Test product on 5211'));
+103
View File
@@ -0,0 +1,103 @@
import { expect, test, type Page } from "@playwright/test";
// The release checks (ROADMAP-v3 §9) on Accounts' real pages: signing in from a deep link lands
// back on that page, through sign-up, a password reset and two-step sign-in set up on the way; a
// foreign return address is refused. A test product (e2e/server.ts) starts and finishes sign-ins.
const PRODUCT = "http://localhost:5211";
const helper = async (page: Page, path: string) => (await (await page.request.get(`${PRODUCT}${path}`)).text()).trim();
async function signIn(page: Page, email: string, password = "Correct-horse-1") {
await page.getByLabel("Email address").fill(email);
await page.getByLabel("Password").fill(password);
await page.getByRole("button", { name: "Sign in" }).click();
}
test("signing in from a deep link returns to that exact page", async ({ page }) => {
await page.goto(`${PRODUCT}/start?returnTo=${encodeURIComponent("/events/youth-camp/register?ticket=adult")}`);
await expect(page.getByRole("heading", { name: "Sign in to Hope Family Church" })).toBeVisible();
await signIn(page, "thandi@hope.test");
await expect(page.locator("#return")).toHaveText("/events/youth-camp/register?ticket=adult");
await expect(page.locator("#email")).toHaveText("thandi@hope.test");
});
test("a wrong password says so without saying whether the account exists", async ({ page }) => {
await page.goto(`${PRODUCT}/start?returnTo=/`);
await signIn(page, "thandi@hope.test", "not-the-password");
await expect(page.locator("main").getByRole("alert")).toHaveText("That email address and password don't match.");
await signIn(page, "nobody@hope.test", "not-the-password");
await expect(page.locator("main").getByRole("alert")).toHaveText("That email address and password don't match.");
});
test("a foreign return address ends on the product's home page", async ({ page }) => {
await page.goto(`${PRODUCT}/start?returnTo=${encodeURIComponent("//evil.example/steal")}`);
await signIn(page, "thandi@hope.test");
await expect(page.locator("#return")).toHaveText("/");
});
test("sign-up with an emailed code, back to the page", async ({ page }) => {
await page.goto(`${PRODUCT}/start?returnTo=${encodeURIComponent("/give?fund=building")}`);
await page.getByRole("button", { name: "Create an account" }).click();
await page.getByLabel("Your name").fill("New Person");
await page.getByLabel("Email address").fill("new@hope.test");
await page.getByLabel("Password").fill("Correct-horse-2");
await page.getByLabel(/privacy notice/).check();
await page.getByRole("button", { name: "Create account" }).click();
await expect(page.getByRole("heading", { name: "Check your email" })).toBeVisible();
await page.getByLabel("Code").fill(await helper(page, "/test/code?to=new@hope.test"));
await page.getByRole("button", { name: "Continue" }).click();
await expect(page.locator("#return")).toHaveText("/give?fund=building");
await expect(page.locator("#email")).toHaveText("new@hope.test");
});
test("forgot password in the middle of signing in still returns to the page", async ({ page }) => {
await page.goto(`${PRODUCT}/start?returnTo=/my-tickets`);
await page.getByRole("link", { name: "Forgot your password?" }).click();
await page.getByLabel("Email address").fill("thandi@hope.test");
await page.getByRole("button", { name: "Send the link" }).click();
await expect(page.getByRole("status")).toContainText("a link is on its way");
await page.goto(await helper(page, "/test/link?to=thandi@hope.test"));
await page.getByLabel("New password").fill("Correct-horse-1");
await page.getByRole("button", { name: "Save and sign in" }).click();
await signIn(page, "thandi@hope.test");
await expect(page.locator("#return")).toHaveText("/my-tickets");
});
test("a product asking for two-step sign-in: set up with an app, recovery codes, then back", async ({ page }) => {
await page.goto(`${PRODUCT}/start?mfa=1&returnTo=/dashboard`);
await signIn(page, "thandi@hope.test");
await expect(page.getByRole("heading", { name: "Set up two-step sign-in" })).toBeVisible();
await page.getByRole("button", { name: /An authenticator app/ }).click();
const key = (await page.getByText(/Or type this key:/).innerText()).replace(/.*:\s*/, "").trim();
await page.getByLabel("Code").fill(await helper(page, `/test/totp?secret=${key}`));
await page.getByRole("button", { name: "Turn on" }).click();
await expect(page.getByRole("heading", { name: "Save your recovery codes" })).toBeVisible();
await page.getByRole("button", { name: "I've saved them" }).click();
await expect(page.locator("#return")).toHaveText("/dashboard");
await expect(page.locator("#amr")).toHaveText("pwd otp mfa");
});
test("the account page: signs in first, then saves details", async ({ page }) => {
await page.goto("/account");
await expect(page.getByRole("heading", { name: "Sign in to Hope Family Church" })).toBeVisible();
await page.getByLabel("Email address").fill("new@hope.test");
await page.getByLabel("Password").fill("Correct-horse-2");
await page.getByRole("button", { name: "Sign in" }).click();
await expect(page.getByRole("heading", { name: "Your account" })).toBeVisible();
await page.getByLabel("Name").fill("New Person-Smith");
await page.getByRole("button", { name: "Save", exact: true }).click();
await expect(page.getByRole("status")).toContainText("Your details are saved");
});
test("admin: needs two-step sign-in, then lists people", async ({ page }) => {
await page.goto("/admin");
await signIn(page, "admin@hope.test");
await expect(page.getByRole("heading", { name: "Set up two-step sign-in" })).toBeVisible();
await expect(page.getByText("Admins must use a second step")).toBeVisible();
await page.getByRole("button", { name: /An authenticator app/ }).click();
const key = (await page.getByText(/Or type this key:/).innerText()).replace(/.*:\s*/, "").trim();
await page.getByLabel("Code").fill(await helper(page, `/test/totp?secret=${key}`));
await page.getByRole("button", { name: "Turn on" }).click();
await page.getByRole("button", { name: "I've saved them" }).click();
await expect(page.getByRole("heading", { name: "Accounts admin" })).toBeVisible();
await expect(page.getByText("thandi@hope.test")).toBeVisible();
});
+9
View File
@@ -0,0 +1,9 @@
<!-- BEGIN:nextjs-agent-rules -->
## This is NOT the Next.js you know
This version has breaking changes — APIs, conventions, and file structure may all differ from your training data. Read the relevant guide in `node_modules/next/dist/docs/` (resolved from this file's directory; in monorepos the `next` package may not be visible from the repo root) before writing any code. Heed deprecation notices.
This block is written and re-added by `next dev` — verify at `node_modules/next/dist/server/lib/generate-agent-files.js`. Removing it from a diff only re-creates the uncommitted change; committing it with your work keeps the tree clean.
<!-- END:nextjs-agent-rules -->
@@ -48,7 +48,7 @@ export function SignIn({ uid }: { uid: string }) {
useExternalEffect(() => {
let alive = true;
call<State>("GET", `/interaction/${encodeURIComponent(uid)}`).then((r) => {
call<State>("GET", `/interaction/${encodeURIComponent(uid)}/state`).then((r) => {
if (!alive) return;
if (r.ok) apply(r.data);
else setError(r.error);
+34
View File
@@ -0,0 +1,34 @@
import { defineConfig, devices } from "@playwright/test";
// Accounts' pages end to end (docs/ACCOUNTS-1.0-PLAN.md §12): the real backend on an in-memory
// database with a test product (e2e/server.ts), and the Next.js pages. Run with `npm run test:e2e`
// in apps/accounts. Nothing needs a database.
export default defineConfig({
testDir: "./e2e",
testMatch: "**/*.spec.ts",
workers: 1,
fullyParallel: false,
timeout: 120_000,
expect: { timeout: 20_000 },
reporter: "list",
outputDir: "e2e/test-results",
use: { baseURL: "http://localhost:3210", trace: "retain-on-failure", navigationTimeout: 90_000 },
projects: [{ name: "chromium", use: { ...devices["Desktop Chrome"] } }],
webServer: [
{
command: "npx tsx e2e/server.ts",
url: "http://127.0.0.1:5210/api/health",
timeout: 120_000,
reuseExistingServer: false,
stdout: "pipe",
},
{
command: "npx next dev -p 3210",
cwd: "frontend",
url: "http://localhost:3210/privacy",
timeout: 180_000,
reuseExistingServer: false,
env: { ACCOUNTS_API_URL: "http://127.0.0.1:5210" },
},
],
});