diff --git a/apps/accounts/README.md b/apps/accounts/README.md index f86d3b6..d68d974 100644 --- a/apps/accounts/README.md +++ b/apps/accounts/README.md @@ -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). diff --git a/apps/accounts/backend/src/interaction/routes.ts b/apps/accounts/backend/src/interaction/routes.ts index b869561..20ffe5c 100644 --- a/apps/accounts/backend/src/interaction/routes.ts +++ b/apps/accounts/backend/src/interaction/routes.ts @@ -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); })); diff --git a/apps/accounts/backend/src/oidc/provider.ts b/apps/accounts/backend/src/oidc/provider.ts index d167353..001e6de 100644 --- a/apps/accounts/backend/src/oidc/provider.ts +++ b/apps/accounts/backend/src/oidc/provider.ts @@ -94,7 +94,11 @@ export async function createProvider(ctx: Ctx): Promise { 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) { diff --git a/apps/accounts/backend/tests/signin.test.ts b/apps/accounts/backend/tests/signin.test.ts index cc335b5..16118f6 100644 --- a/apps/accounts/backend/tests/signin.test.ts +++ b/apps/accounts/backend/tests/signin.test.ts @@ -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); diff --git a/apps/accounts/backend/tests/support/harness.ts b/apps/accounts/backend/tests/support/harness.ts index de46e43..55a6937 100644 --- a/apps/accounts/backend/tests/support/harness.ts +++ b/apps/accounts/backend/tests/support/harness.ts @@ -23,22 +23,28 @@ const listen = (server: http.Server) => new Promise((resolve) => server. /** A browser: cookies per host, redirects followed by hand so each hop can be checked. */ export class Browser { - private jar = new Map>(); + // 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>(); 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 }); } } diff --git a/apps/accounts/e2e/.gitignore b/apps/accounts/e2e/.gitignore new file mode 100644 index 0000000..51511d1 --- /dev/null +++ b/apps/accounts/e2e/.gitignore @@ -0,0 +1 @@ +test-results/ diff --git a/apps/accounts/e2e/package.json b/apps/accounts/e2e/package.json new file mode 100644 index 0000000..e986b24 --- /dev/null +++ b/apps/accounts/e2e/package.json @@ -0,0 +1,4 @@ +{ + "private": true, + "type": "module" +} diff --git a/apps/accounts/e2e/server.ts b/apps/accounts/e2e/server.ts new file mode 100644 index 0000000..09badc9 --- /dev/null +++ b/apps/accounts/e2e/server.ts @@ -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= (the last code sent), + * GET /test/link?to= (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 = {}) => 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 | 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, `Product

Signed in to the product

${r.claims.email}

${r.returnTo}

${r.claims.amr.join(' ')}

`); + 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, 'Product home

Product home

'); + } catch (e) { + send(500, `
${String((e as Error).message)}
`); + } +}).listen(5211, '127.0.0.1', () => console.log('[e2e] Test product on 5211')); diff --git a/apps/accounts/e2e/signin.spec.ts b/apps/accounts/e2e/signin.spec.ts new file mode 100644 index 0000000..a7fcb02 --- /dev/null +++ b/apps/accounts/e2e/signin.spec.ts @@ -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(); +}); diff --git a/apps/accounts/frontend/AGENTS.md b/apps/accounts/frontend/AGENTS.md new file mode 100644 index 0000000..af3b7c8 --- /dev/null +++ b/apps/accounts/frontend/AGENTS.md @@ -0,0 +1,9 @@ + + +## 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. + + diff --git a/apps/accounts/frontend/src/app/signin/SignIn.tsx b/apps/accounts/frontend/src/app/signin/SignIn.tsx index 3d5a463..884e446 100644 --- a/apps/accounts/frontend/src/app/signin/SignIn.tsx +++ b/apps/accounts/frontend/src/app/signin/SignIn.tsx @@ -48,7 +48,7 @@ export function SignIn({ uid }: { uid: string }) { useExternalEffect(() => { let alive = true; - call("GET", `/interaction/${encodeURIComponent(uid)}`).then((r) => { + call("GET", `/interaction/${encodeURIComponent(uid)}/state`).then((r) => { if (!alive) return; if (r.ok) apply(r.data); else setError(r.error); diff --git a/apps/accounts/playwright.config.ts b/apps/accounts/playwright.config.ts new file mode 100644 index 0000000..513f58d --- /dev/null +++ b/apps/accounts/playwright.config.ts @@ -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" }, + }, + ], +});