The church's one set of settings from Accounts (messaging.get; the SMTP password and WAWP token sealed with the link's secret, kept encrypted in AppSetting messaging_settings), fetched when the App links to Accounts, on Accounts' signed messaging.changed, once a day and on the admin's Fetch again. messages-send (every minute): the outbox by email (nodemailer) and WhatsApp (WAWP), STOP checked before every WhatsApp (the member and anyone with the same number), email instead for what a member asked for (never announcements), retries after 2, 4, 8 and 16 minutes, a reminder never after its slot started, nothing more than 3 days late. announcement-sends and devotional-sends queue "Also send it" at the publish time and today's devotional at each member's time. Members' choices (NotificationSettings), news consent kept from Accounts, MessageCount for the heartbeat's messages, the admin's Email and WhatsApp API with Send a test. Migration messaging (checked on PostgreSQL 18). 110 backend tests. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
174 lines
8.5 KiB
TypeScript
174 lines
8.5 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 { IDENTITY_REQUEST_SCHEMA, type IdentityClaims } from '@crosscode/contracts';
|
|
import { sealLinkValue } from '@crosscode/contracts/signing';
|
|
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 type { Email, Smtp, Transport, Wawp, WhatsApp } from '../../src/messaging/transport.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 }[];
|
|
/** Requests the App sent Accounts (`crosscode.identity-request/1`). */
|
|
requests: Record<string, unknown>[];
|
|
/** What `messaging.get` answers: the church's settings in the clear (sealed on the way), or an error. */
|
|
messaging: { email: (Omit<Smtp, 'pass'> & { pass: string | null }) | null; whatsapp: Wawp | null } | Error;
|
|
};
|
|
|
|
/** The link secret the tests' Accounts link has. */
|
|
export const LINK_SECRET = 'link-secret';
|
|
|
|
export const CHURCH_SMTP = { host: 'smtp.hope.test', port: 587, secure: false, user: 'app@hope.test', pass: 'smtp-pass', from: 'app@hope.test' };
|
|
export const CHURCH_WAWP = { accessToken: 'wawp-token', instanceId: 'HOPE1' };
|
|
|
|
/** Keeps what would have been sent; `fail` makes a channel throw. */
|
|
export class MemoryTransport implements Transport {
|
|
emails: (Email & { settings: Smtp })[] = [];
|
|
whatsapps: (WhatsApp & { settings: Wawp })[] = [];
|
|
fail: { email?: string; whatsapp?: string } = {};
|
|
async email(settings: Smtp, msg: Email) {
|
|
if (this.fail.email) throw new Error(this.fail.email);
|
|
this.emails.push({ ...msg, settings });
|
|
}
|
|
async whatsapp(settings: Wawp, msg: WhatsApp) {
|
|
if (this.fail.whatsapp) throw new Error(this.fail.whatsapp);
|
|
this.whatsapps.push({ ...msg, settings });
|
|
}
|
|
}
|
|
|
|
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');
|
|
}
|
|
},
|
|
request: async (input: Record<string, unknown>) => {
|
|
fake.requests.push(input);
|
|
if (input.type === 'messaging.get') {
|
|
if (fake.messaging instanceof Error) throw fake.messaging;
|
|
const { email, whatsapp } = fake.messaging;
|
|
return {
|
|
schema: IDENTITY_REQUEST_SCHEMA,
|
|
email: email ? { ...email, pass: email.pass ? sealLinkValue(LINK_SECRET, email.pass) : null } : null,
|
|
whatsapp: whatsapp ? { instanceId: whatsapp.instanceId, accessToken: sealLinkValue(LINK_SECRET, whatsapp.accessToken) } : null,
|
|
updatedAt: '2026-11-30T10:00:00.000Z',
|
|
};
|
|
}
|
|
return { schema: IDENTITY_REQUEST_SCHEMA, ok: 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;
|
|
}
|
|
|
|
/** 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: [], requests: [], messaging: { email: CHURCH_SMTP, whatsapp: CHURCH_WAWP } };
|
|
const transport = new MemoryTransport();
|
|
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, transport });
|
|
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, transport, 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);
|
|
}
|