Files
crosscode-platform/apps/accounts/e2e/server.ts
T
joshuaandClaude Opus 5.5 fdd53ae4db 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>
2026-11-18 15:01:32 +02:00

74 lines
5.0 KiB
TypeScript

/**
* 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'));