- scripts/products/events.sh: packages/auth-client is installed and built (after contracts) when Events uses it, as 3.0.0 does; without it a 3.0 deploy would fail at the first sign-in through Accounts. bats test. - test:accounts runs on real Postgres for both apps with EVENTS_TEST_DATABASE_URL and ACCOUNTS_TEST_DATABASE_URL (14/14); the Accounts test harness takes a real Prisma client. - e2e/excel.spec.ts resolves excelts from the backend (hoisted in the monorepo), so the e2e suite loads again. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
174 lines
9.9 KiB
TypeScript
174 lines
9.9 KiB
TypeScript
/**
|
|
* The whole of Accounts on a real port with an in-memory database and messenger, plus a test
|
|
* product (an OIDC client built on openid-client, as the Website will be) that's linked and
|
|
* signs people in. Browser requests go through a small cookie jar, following redirects by hand.
|
|
*/
|
|
import http from 'node:http';
|
|
import type { AddressInfo } from 'node:net';
|
|
import * as oidc from 'openid-client';
|
|
import { encodeState, decodeState, IDENTITY_SCHEMA, OIDC_CLIENT_PATHS } from '@crosscode/contracts';
|
|
import { ed25519PublicToPem, generateEd25519, LINK_HEADERS, newLinkSecret, oidcClientSecret, verify } from '@crosscode/contracts/signing';
|
|
import { createApp } from '../../src/app.js';
|
|
import { createCtx, type Ctx } from '../../src/context.js';
|
|
import { loadConfig } from '../../src/lib/config.js';
|
|
import { MemoryMessenger } from '../../src/lib/messages.js';
|
|
import { hashPassword } from '../../src/lib/passwords.js';
|
|
import { createProvider } from '../../src/oidc/provider.js';
|
|
import { memoryDb, type MemoryDb } from './memoryDb.js';
|
|
|
|
export const ACCOUNTS_ID = '9a4c2f1e-7b3d-4e5a-8c6f-0d1e2f3a4b5c';
|
|
export const PRODUCT_ID = '3b0f6a52-6c1e-4b7a-9d0e-2f1a8c4b7e02';
|
|
|
|
const listen = (server: http.Server) => new Promise<number>((resolve) => server.listen(0, '127.0.0.1', () => resolve((server.address() as AddressInfo).port)));
|
|
|
|
/** A browser: cookies per host, redirects followed by hand so each hop can be checked. */
|
|
export class Browser {
|
|
// 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);
|
|
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, ...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, path });
|
|
}
|
|
}
|
|
|
|
async request(url: string, init: { method?: string; body?: unknown; form?: Record<string, string>; origin?: string } = {}) {
|
|
const u = new URL(url);
|
|
const headers: Record<string, string> = { cookie: this.cookieHeader(u) };
|
|
let body: string | undefined;
|
|
if (init.body !== undefined) { headers['content-type'] = 'application/json'; body = JSON.stringify(init.body); }
|
|
if (init.form) { headers['content-type'] = 'application/x-www-form-urlencoded'; body = new URLSearchParams(init.form).toString(); }
|
|
if (init.origin) headers.origin = init.origin;
|
|
const res = await fetch(u, { method: init.method ?? (body ? 'POST' : 'GET'), headers, body, redirect: 'manual' });
|
|
this.store(u, res);
|
|
return res;
|
|
}
|
|
|
|
/** Follows redirects until a page that isn't one; returns every URL visited and the last response. */
|
|
async follow(url: string, stopAt?: (u: URL) => boolean) {
|
|
const visited: URL[] = [];
|
|
let current = new URL(url);
|
|
for (let i = 0; i < 10; i++) {
|
|
visited.push(current);
|
|
if (stopAt?.(current)) return { visited, res: null as Response | null, url: current };
|
|
const res = await this.request(current.toString());
|
|
const loc = res.headers.get('location');
|
|
if (res.status >= 300 && res.status < 400 && loc) {
|
|
current = new URL(loc, current);
|
|
continue;
|
|
}
|
|
return { visited, res, url: current };
|
|
}
|
|
throw new Error('Too many redirects');
|
|
}
|
|
}
|
|
|
|
export type Received = { path: string; headers: http.IncomingHttpHeaders; body: string };
|
|
|
|
export type Harness = Awaited<ReturnType<typeof startHarness>>;
|
|
|
|
/** `db`: a real Prisma client instead of the in-memory one (an empty, migrated database). */
|
|
export async function startHarness(opts: { now?: () => Date; db?: unknown } = {}) {
|
|
// Accounts.
|
|
const server = http.createServer();
|
|
const port = await listen(server);
|
|
const publicUrl = `http://127.0.0.1:${port}`;
|
|
const config = { ...loadConfig({ ACCOUNTS_URL: publicUrl, NODE_ENV: 'test', JOBS_ENABLED: 'false', LINKS_ALLOW_PRIVATE: 'true', HUB_URL: 'http://127.0.0.1:1' }) };
|
|
const db = (opts.db ?? memoryDb()) as MemoryDb;
|
|
const messenger = new MemoryMessenger();
|
|
const ctx: Ctx = createCtx(config, db as never, { messenger, now: opts.now });
|
|
const provider = await createProvider(ctx);
|
|
server.on('request', createApp(ctx, provider));
|
|
await ctx.settings.setMany({ hub_install_id: ACCOUNTS_ID, church_profile: JSON.stringify({ name: 'Hope Family Church', shortName: 'Hope' }) });
|
|
|
|
// The test product: answers back-channel calls and logout, and is linked (so it's a client).
|
|
const received: Received[] = [];
|
|
const productReplies: Record<string, (body: Record<string, unknown>) => unknown> = {};
|
|
const productServer = http.createServer((req, res) => {
|
|
let body = '';
|
|
req.on('data', (c) => { body += c; });
|
|
req.on('end', () => {
|
|
received.push({ path: req.url ?? '', headers: req.headers, body });
|
|
const parsed = (() => { try { return JSON.parse(body); } catch { return {}; } })() as Record<string, unknown>;
|
|
const answer = productReplies[String(parsed.type ?? req.url)]?.(parsed) ?? { schema: IDENTITY_SCHEMA, ok: true };
|
|
res.writeHead(200, { 'content-type': 'application/json' }).end(JSON.stringify(answer));
|
|
});
|
|
});
|
|
const productPort = await listen(productServer);
|
|
const productUrl = `http://127.0.0.1:${productPort}`;
|
|
const linkSecret = newLinkSecret();
|
|
const productKey = generateEd25519();
|
|
await db.productLink.create({ data: { installId: PRODUCT_ID, product: 'website', url: productUrl, publicKey: ed25519PublicToPem(productKey.publicKey), secret: ctx.secrets.encrypt(linkSecret), connectedAt: new Date() } });
|
|
|
|
const issuer = new URL(`${publicUrl}/api/oidc`);
|
|
const client = await oidc.discovery(issuer, PRODUCT_ID, oidcClientSecret(linkSecret), undefined, { execute: [oidc.allowInsecureRequests] });
|
|
|
|
/** The product starts a sign-in from `returnTo`; returns the URL to send the browser to and what to check on return. */
|
|
async function startSignIn(returnTo: string, extra: Record<string, string> = {}) {
|
|
const verifier = oidc.randomPKCECodeVerifier();
|
|
const nonce = oidc.randomNonce();
|
|
const state = encodeState({ nonce, returnTo });
|
|
const url = oidc.buildAuthorizationUrl(client, {
|
|
redirect_uri: `${productUrl}${OIDC_CLIENT_PATHS.callback}`, scope: 'openid profile email phone crosscode', state, nonce,
|
|
code_challenge: await oidc.calculatePKCECodeChallenge(verifier), code_challenge_method: 'S256', ...extra,
|
|
});
|
|
return { url: url.toString(), verifier, nonce, state };
|
|
}
|
|
|
|
/** The product's callback: exchange the code; returns the claims and where it would send the person. */
|
|
async function finishSignIn(callbackUrl: URL, started: { verifier: string; nonce: string; state: string }) {
|
|
const tokens = await oidc.authorizationCodeGrant(client, callbackUrl, { pkceCodeVerifier: started.verifier, expectedState: started.state, expectedNonce: started.nonce, idTokenExpected: true });
|
|
const st = decodeState(callbackUrl.searchParams.get('state'));
|
|
return { claims: tokens.claims()!, tokens, returnTo: st?.returnTo ?? '/' };
|
|
}
|
|
|
|
/** Runs a whole sign-in for `email` / `password` and returns the claims. */
|
|
async function signIn(browser: Browser, email: string, password: string, returnTo = '/events/youth-camp?ticket=adult', extra: Record<string, string> = {}) {
|
|
const started = await startSignIn(returnTo, extra);
|
|
const { url } = await browser.follow(started.url, (u) => u.pathname === '/signin' || u.pathname === OIDC_CLIENT_PATHS.callback);
|
|
if (url.pathname === OIDC_CLIENT_PATHS.callback) return finishSignIn(url, started);
|
|
const uid = url.searchParams.get('uid')!;
|
|
const step = await api(browser, 'POST', `/api/v2/interaction/${uid}/password`, { email, password });
|
|
if (step.body.stage !== 'done') return { pending: step.body, uid, started };
|
|
const back = await browser.follow(step.body.redirectTo as string, (u) => u.pathname === OIDC_CLIENT_PATHS.callback);
|
|
return finishSignIn(back.url, started);
|
|
}
|
|
|
|
async function api(browser: Browser, method: string, path: string, body?: unknown) {
|
|
const res = await browser.request(`${publicUrl}${path}`, { method, body, origin: publicUrl });
|
|
const json = (await res.json().catch(() => ({}))) as Record<string, unknown>;
|
|
return { status: res.status, body: json };
|
|
}
|
|
|
|
async function makeAccount(data: Record<string, unknown> & { email: string; password?: string }) {
|
|
const { password, ...rest } = data;
|
|
return db.account.create({ data: { name: 'Thandi Test', emailVerified: true, noticeVersionAccepted: 1, newsAskedAt: new Date(), passwordHash: await hashPassword(password ?? 'Correct-horse-1'), ...rest } });
|
|
}
|
|
|
|
/** Checks a back-channel call was signed with the link's secret. */
|
|
const signedByLink = (r: Received) => verify({ secret: linkSecret, timestamp: r.headers[LINK_HEADERS.timestamp], signature: r.headers[LINK_HEADERS.signature], rawBody: r.body }).ok;
|
|
|
|
async function close() {
|
|
await new Promise((r) => server.close(r));
|
|
await new Promise((r) => productServer.close(r));
|
|
}
|
|
|
|
return { ctx, db: db as MemoryDb, messenger, provider, publicUrl, productUrl, client, received, productReplies, linkSecret, productKey, startSignIn, finishSignIn, signIn, api, makeAccount, signedByLink, close };
|
|
}
|