Files
crosscode-platform/apps/app/backend/tests/support/harness.ts
T
joshuaandClaude Opus 5.5 5213bb36c0 app: the House of Prayer's backend (APP-1.0-PLAN §3)
Commitments stored as rules (start, length, once/daily/weekly, end, skips) in the
church's timezone, daylight saving included; the day's coverage as counts only,
cached until a booking changes, live over server-sent events (X-Accel-Buffering
off, a comment every 25 s). Booking, skipping, changing, cancelling within the
8-hour rule, renewing (a signed single-use link), "I prayed" (self-reported).
Campaigns and moderated testimonies; the admin's bookings with names, always
access-logged; booking on a member's behalf. Reminders (every minute) and
renewal notices (14 and 3 days before) queued in an outbox for the messaging
slice. The heartbeat's prayer counts; export and delete for a member's prayer.
Migration 20261202000000_house_of_prayer (checked on PostgreSQL 18: applies, no
diff). 66 backend tests.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-12-01 10:29:39 +02:00

132 lines
6.3 KiB
TypeScript

/**
* The App on an in-memory database, with a stand-in for `@crosscode/auth-client` (the real one is
* tested against Accounts' provider in apps/accounts/backend/tests/authClient.test.ts), linked to a
* church's Accounts and registered with the Hub, and a clock the tests can move.
*/
import type { IdentityClaims } from '@crosscode/contracts';
import type { AuthClientModule } from '../../src/auth/accounts.js';
import { createApp } from '../../src/app.js';
import { createCtx, type Ctx, type Db } from '../../src/context.js';
import { loadConfig } from '../../src/lib/config.js';
import { memoryDb, type MemoryDb } from './memoryDb.js';
export const SITE = 'https://app.hope.test';
export const ACCOUNTS = 'https://accounts.hope.test';
export const ADMIN_EMAIL = 'pastor@hope.test';
export const INSTALL_ID = '6f0c1d2e-3a4b-4c5d-8e6f-7a8b9c0d1e2f';
export const ACCOUNTS_INSTALL_ID = '9a4c2f1e-7b3d-4e5a-8c6f-0d1e2f3a4b5c';
export const PASTOR = '11111111-1111-4111-8111-111111111111';
export const MEMBER = '33333333-3333-4333-8333-333333333333';
/** What the stand-in Accounts answers with at the next callback. */
export type FakeAccounts = {
next: Partial<IdentityClaims> & { sub: string };
started: { returnTo: string; requireTwoFactor: boolean }[];
};
export function claims(over: Partial<IdentityClaims> & { sub: string }): IdentityClaims {
return {
schema: 'crosscode.identity/1',
name: 'Pastor Sam',
given_name: 'Sam',
family_name: null,
email: ADMIN_EMAIL,
email_verified: true,
phone_number: '+27821234567',
phone_number_verified: true,
news_consent: { email: false, whatsapp: false },
amr: ['pwd', 'mfa'],
two_factor: 'totp',
privacy_notice_version: 1,
...over,
} as IdentityClaims;
}
function fakeAuthClient(fake: FakeAccounts): AuthClientModule {
class SignInError extends Error {
constructor(message: string, public code: string) {
super(message);
}
}
return {
SignInError,
accountsClient: async () => ({
startSignIn: async (returnTo: string, opts: { requireTwoFactor?: boolean } = {}) => {
fake.started.push({ returnTo, requireTwoFactor: !!opts.requireTwoFactor });
return { url: `${ACCOUNTS}/api/oidc/auth?mfa=${opts.requireTwoFactor ? 1 : 0}`, cookie: Buffer.from(JSON.stringify({ returnTo })).toString('base64url') };
},
finishSignIn: async (_url: URL, cookie: string | undefined) => {
if (!cookie) throw new SignInError('expired', 'NO_PENDING');
const { returnTo } = JSON.parse(Buffer.from(cookie, 'base64url').toString()) as { returnTo: string };
return { claims: claims(fake.next), returnTo, idToken: `id-token-for-${fake.next.sub}` };
},
signOutUrl: (idToken?: string) => `${ACCOUNTS}/api/oidc/session/end?id_token_hint=${idToken ?? ''}`,
verifyLogoutToken: async (token: string) => {
try {
return JSON.parse(token) as { sub: string; sid: string | null };
} catch {
throw new SignInError('bad', 'BAD_TOKEN');
}
},
verifyAccountsCall: (raw: Buffer, headers: Record<string, unknown>) => {
if (headers['x-test-signed'] !== 'yes') throw new SignInError('That call isn\'t signed by Accounts.', 'BAD_SIGNATURE');
return JSON.parse(raw.toString('utf8'));
},
}),
} as unknown as AuthClientModule;
}
/** A clock the tests move (`clock.add(ms)`); starts on 2026-12-01 08:00 SAST. */
export function testClock(start = '2026-12-01T06:00:00Z') {
let t = new Date(start).getTime();
return { now: () => new Date(t), add: (ms: number) => { t += ms; }, set: (iso: string) => { t = new Date(iso).getTime(); } };
}
export async function harness(opts: { linked?: boolean; env?: Record<string, string> } = {}) {
const db = memoryDb();
const clock = testClock();
const fake: FakeAccounts = { next: { sub: PASTOR }, started: [] };
const config = loadConfig({ APP_URL: SITE, HUB_ADMIN_EMAIL: ADMIN_EMAIL.toUpperCase(), ...opts.env });
const ctx = createCtx(config, db as unknown as Db, { authClient: async () => fakeAuthClient(fake), now: clock.now });
await ctx.settings.set('hub_install_id', INSTALL_ID);
if (opts.linked !== false) {
await db.productLink.create({ data: { installId: ACCOUNTS_INSTALL_ID, product: 'accounts', url: ACCOUNTS, publicKey: 'unused', secret: ctx.secrets.encrypt('link-secret'), connectedAt: new Date() } });
}
return { db, ctx, fake, clock, app: createApp(ctx) };
}
export type Harness = Awaited<ReturnType<typeof harness>> & { db: MemoryDb; ctx: Ctx };
/** `name=value` pairs from a response's Set-Cookie, for the next request. */
export function cookiesFrom(res: { headers: Record<string, unknown> }, keep: Record<string, string> = {}): Record<string, string> {
const out = { ...keep };
for (const line of (res.headers['set-cookie'] as string[] | undefined) ?? []) {
const [pair, ...attrs] = line.split(';');
const i = pair!.indexOf('=');
const name = pair!.slice(0, i).trim();
const value = pair!.slice(i + 1).trim();
const expired = attrs.some((a) => /^\s*expires=Thu, 01 Jan 1970/i.test(a)) || value === '';
if (expired) delete out[name];
else out[name] = value;
}
return out;
}
export const cookieHeader = (c: Record<string, string>) => Object.entries(c).map(([k, v]) => `${k}=${v}`).join('; ');
/**
* Signs `who` in through the stand-in Accounts (with 2FA when `mfa`), creating them as a Member
* with `roles` first if given; answers the cookies to send.
*/
export async function signInAs(h: Harness, who: { sub: string; name?: string; email?: string; roles?: string[] }, mfa = false): Promise<Record<string, string>> {
const { default: request } = await import('supertest');
if (who.roles?.length) {
await h.db.member.upsert({ where: { id: who.sub }, create: { id: who.sub, name: who.name ?? 'Someone', email: who.email ?? `${who.sub}@hope.test`, roles: who.roles }, update: { roles: who.roles } });
}
h.fake.next = { sub: who.sub, name: who.name ?? 'Someone', email: who.email ?? `${who.sub.slice(0, 8)}@hope.test`, amr: mfa ? ['pwd', 'mfa'] : ['pwd'] };
const start = await request(h.app).get(`/api/auth/signin?returnTo=%2F${mfa ? '&mfa=1' : ''}`);
const after = cookiesFrom(start);
const back = await request(h.app).get('/api/auth/callback?code=abc&state=xyz').set('Cookie', cookieHeader(after));
return cookiesFrom(back, after);
}