Files
crosscode-platform/apps/website/backend/tests/support/harness.ts
T
joshuaandClaude Opus 5.5 085265392e feat(website): church details, settings, audit log, search engine data, safer editing
Church details saved through Accounts' church.update (live at once).
Settings: Search Console and Bing codes, Coming soon line, menu order.
Audit log and recent edits. A made share image, Event / VideoObject /
PodcastEpisode / BreadcrumbList structured data, permanent redirects
from old page addresses. Saves refused when someone else saved in
between; Ministry leaders' events; templates previewed with the
church's own content before choosing.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-25 15:30:27 +02:00

118 lines
5.8 KiB
TypeScript

/**
* The Website's 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.
*/
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://www.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';
/** What the stand-in Accounts answers with at the next callback. */
export type FakeAccounts = {
next: Partial<IdentityClaims> & { sub: string };
started: { returnTo: string; requireTwoFactor: boolean }[];
/** Requests to Accounts (people.ensure, …). */
requests: { type: string; email?: string; actor?: string | null; church?: Record<string, unknown> }[];
};
export function claims(over: Partial<IdentityClaims> & { sub: string }): IdentityClaims {
return {
schema: 'crosscode.identity/1',
name: 'Pastor Sam',
email: ADMIN_EMAIL,
email_verified: true,
phone_number: null,
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');
}
},
/** people.ensure: the same sub for the same email; "new@…" is a new account. */
request: async (input: { type: string; email?: string; actor?: string | null; church?: Record<string, unknown>; ifUpdatedAt?: string }) => {
fake.requests.push(input);
if (input.type === 'church.update') {
// An old ifUpdatedAt: someone saved in between.
if (input.ifUpdatedAt === '2000-01-01T00:00:00.000Z') throw Object.assign(new Error('changed'), { code: 'PROFILE_CHANGED', status: 409 });
return { schema: 'crosscode.identity-request/1', church: { name: 'Hope', ...input.church } };
}
if (input.type !== 'people.ensure') throw new Error(`not faked: ${input.type}`);
const hex = Buffer.from(input.email ?? '').toString('hex').padEnd(12, '0').slice(0, 12);
return { schema: 'crosscode.identity-request/1', sub: `22222222-2222-4222-8222-${hex}`, created: input.email?.startsWith('new@') ?? false, emailSent: true };
},
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;
}
export async function harness(opts: { linked?: boolean; env?: Record<string, string> } = {}) {
const db = memoryDb();
const fake: FakeAccounts = { next: { sub: '11111111-1111-4111-8111-111111111111' }, started: [], requests: [] };
const config = loadConfig({ WEBSITE_URL: SITE, HUB_ADMIN_EMAIL: ADMIN_EMAIL.toUpperCase(), ...opts.env });
const ctx = createCtx(config, db as unknown as Db, { authClient: async () => fakeAuthClient(fake) });
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, 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('; ');