app: the Church App's foundation; docs for Hub 2.26.1 and two years of devotionals

apps/app (not released; app@1.0.0 is built in slices, APP-1.0-PLAN §15):
- backend (Express, Prisma, pg-boss, as the Website): the Hub client
  (CCP-, product app, the active-member band in the heartbeat), links
  and church.changed, sign-in through Accounts (everyone a Member; 8 days
  renewed up to 90; every role only with 2FA; the first Owner from
  HUB_ADMIN_EMAIL), Accounts' user.updated/export/deleted, active members
  once a day, modules on and off, GET /api/v1/app. Migration init.
- frontend (Next.js 16): header, tab bar, footer, manifest and icons from
  the church profile, service worker, Add to home screen, Me, the admin's
  first dashboard.
- env.template.json, PM2 template, README, CHANGELOG, WHATS-NEW; 27 tests.

Docs: the Hub runs 2.26.1 with two years of Cross Code's devotionals; an
App gets 2 weeks, today included. HANDOVER lists the App's slices.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
2026-12-01 00:20:07 +02:00
co-authored by Claude Opus 5.5
parent 74dee881e4
commit bb36e06fa4
85 changed files with 4479 additions and 53 deletions
+88
View File
@@ -0,0 +1,88 @@
import { describe, it } from 'node:test';
import assert from 'node:assert/strict';
import request from 'supertest';
import { hub } from '@crosscode/contracts';
import { createApp } from '../src/app.js';
import { createCtx, type Db } from '../src/context.js';
import { stats } from '../src/hub/client.js';
import { loadConfig } from '../src/lib/config.js';
import { appVersion } from '../src/lib/version.js';
import { shortNameFor } from '../src/public/app.js';
import { harness, MEMBER } from './support/harness.js';
const DAY = 24 * 3600e3;
describe('the app', () => {
it('answers /api/health with the product and version', async () => {
const { app } = await harness();
const res = await request(app).get('/api/health');
assert.equal(res.status, 200);
assert.deepEqual(res.body, { status: 'ok', product: 'app', version: appVersion(), db: true });
});
it('says 503 when the database is down', async () => {
const db = { $queryRaw: async () => { throw new Error('down'); } } as unknown as Db;
const res = await request(createApp(createCtx(loadConfig({}), db))).get('/api/health');
assert.equal(res.status, 503);
assert.equal(res.body.db, false);
});
it('answers unknown API paths with a JSON 404 and keeps the API out of search', async () => {
const { app } = await harness();
const res = await request(app).get('/api/nothing');
assert.equal(res.status, 404);
assert.equal(res.body.error.code, 'NOT_FOUND');
assert.equal(res.headers['x-robots-tag'], 'noindex');
assert.equal(res.headers['x-powered-by'], undefined);
});
it('gives every page the church, its colours and the modules on (defaults before a profile)', async () => {
const { app } = await harness();
const res = await request(app).get('/api/v1/app');
assert.equal(res.status, 200);
assert.equal(res.body.church, null);
assert.equal(res.body.shortName, 'Church App');
assert.equal(res.body.palette.brand, '31 78 121');
assert.equal(res.body.palette.notes, undefined);
assert.deepEqual(res.body.style, { fontPairing: 'warm', corners: 'soft' });
assert.deepEqual(res.body.modules, ['house-of-prayer', 'prayer-requests', 'announcements', 'devotionals', 'events']);
assert.equal(res.body.timezone, 'Africa/Johannesburg');
});
it('cuts a long name to 12 characters for the home screen, unless there is a short name', () => {
assert.equal(shortNameFor({ name: 'Acacia Hill Community Church', shortName: null }), 'Acacia Hill…');
assert.equal(shortNameFor({ name: 'Northpoint', shortName: null }), 'Northpoint');
assert.equal(shortNameFor({ name: 'Acacia Hill Community Church', shortName: 'Acacia Hill' }), 'Acacia Hill');
});
});
describe('the heartbeat', () => {
it('reports the active-member band and the modules, never a name', async () => {
const h = await harness();
const now = h.ctx.now().getTime();
for (let i = 0; i < 120; i++) {
await h.db.member.create({ data: { id: `m-${i}`, name: `Person ${i}`, email: `p${i}@hope.test`, lastActiveAt: new Date(now - (i < 101 ? 89 : 91) * DAY) } });
}
await h.db.member.create({ data: { id: MEMBER, name: 'Never used it', email: 'never@hope.test' } });
await h.ctx.settings.set('modules', JSON.stringify({ events: false }));
const s = await stats(h.ctx);
assert.ok(hub.appStatsSchema.safeParse(s).success);
assert.equal(s.activeMembers90d, '101–300');
assert.deepEqual(s.modules, ['house-of-prayer', 'prayer-requests', 'announcements', 'devotionals']);
assert.doesNotMatch(JSON.stringify(s), /Person|hope\.test/);
});
});
describe('config', () => {
it('refuses production without a secret', () => {
assert.throws(() => loadConfig({ NODE_ENV: 'production' }), /APP_SECRET/);
});
it('defaults to the development ports and an 8-day sign-in up to 90 days', () => {
const c = loadConfig({});
assert.equal(c.port, 5400);
assert.equal(c.publicUrl, 'http://localhost:3400');
assert.equal(c.sessionDays, 8);
assert.equal(c.sessionMaxDays, 90);
});
});
+254
View File
@@ -0,0 +1,254 @@
import { describe, it } from 'node:test';
import assert from 'node:assert/strict';
import request from 'supertest';
import { cookieHeader, cookiesFrom, harness, MEMBER, PASTOR, SITE } from './support/harness.js';
const DAY = 24 * 3600e3;
type H = Awaited<ReturnType<typeof harness>>;
/** Signs in from `returnTo` through the stand-in Accounts; returns the callback's response and the cookies after it. */
async function signIn(h: H, returnTo = '/prayer?day=2026-12-02', cookies: Record<string, string> = {}, mfa = false) {
const start = await request(h.app).get(`/api/auth/signin?returnTo=${encodeURIComponent(returnTo)}${mfa ? '&mfa=1' : ''}`).set('Cookie', cookieHeader(cookies));
assert.equal(start.status, 303);
const after = cookiesFrom(start, cookies);
const back = await request(h.app).get('/api/auth/callback?code=abc&state=xyz').set('Cookie', cookieHeader(after));
return { start, back, cookies: cookiesFrom(back, after) };
}
const me = (h: H, cookies: Record<string, string>) => request(h.app).get('/api/auth/me').set('Cookie', cookieHeader(cookies));
describe('signing in through Accounts', () => {
it('sends people to Accounts with the page they were on, and brings them back to it', async () => {
const h = await harness();
h.fake.next = { sub: MEMBER, email: 'thandi@hope.test', name: 'Thandi Mokoena', amr: ['pwd'] };
const { start, back, cookies } = await signIn(h);
assert.match(start.headers.location!, /^https:\/\/accounts\.hope\.test\//);
assert.deepEqual(h.fake.started, [{ returnTo: '/prayer?day=2026-12-02', requireTwoFactor: false }]);
assert.equal(back.headers.location, `${SITE}/prayer?day=2026-12-02`);
assert.match(String(back.headers['set-cookie']), /cca_session=.*HttpOnly/);
const res = await me(h, cookies);
assert.equal(res.status, 200);
assert.deepEqual(res.body.member, { id: MEMBER, name: 'Thandi Mokoena', email: 'thandi@hope.test', roles: [] });
});
it('makes anyone with an account a Member, keeping a copy of their profile', async () => {
const h = await harness();
h.fake.next = { sub: MEMBER, email: 'Thandi@Hope.test', phone_number: '+27820000000', phone_number_verified: false, whatsapp_opted_out: true, amr: ['pwd'] };
await signIn(h);
const m = await h.db.member.findUnique({ where: { id: MEMBER } });
assert.equal(m!.email, 'thandi@hope.test');
assert.equal(m!.phone, null, 'only a verified number is kept');
assert.equal(m!.whatsappOptedOut, true);
assert.deepEqual(m!.roles, []);
});
it('refuses a foreign return address (back to Home instead)', async () => {
const h = await harness();
await request(h.app).get('/api/auth/signin?returnTo=https%3A%2F%2Fevil.test%2F');
assert.equal(h.fake.started[0]!.returnTo, '/');
});
it('says so when the App isn\'t linked to Accounts yet', async () => {
const h = await harness({ linked: false });
const res = await request(h.app).get('/api/auth/signin?returnTo=%2Fme');
assert.equal(res.status, 303);
assert.equal(res.headers.location, `${SITE}/auth/problem?code=ACCOUNTS_NOT_LINKED&returnTo=%2Fme`);
});
});
describe('the first Owner', () => {
it('is whoever signs in with the Hub\'s admin email (verified)', async () => {
const h = await harness();
h.fake.next = { sub: PASTOR, email: 'Pastor@Hope.test' };
const { cookies } = await signIn(h, '/admin');
const res = await me(h, cookies);
assert.deepEqual(res.body.member.roles, ['owner']);
assert.deepEqual(res.body.activeRoles, ['owner']);
assert.equal((await h.db.auditLog.findMany({ where: { action: 'first_owner_signed_in' } })).length, 1);
});
it('never from an unverified email, and never a second one', async () => {
const h = await harness();
h.fake.next = { sub: PASTOR, email_verified: false };
await signIn(h, '/');
assert.deepEqual((await h.db.member.findUnique({ where: { id: PASTOR } }))!.roles, []);
await h.db.member.create({ data: { id: MEMBER, name: 'Owner', email: 'owner@hope.test', roles: ['owner'] } });
h.fake.next = { sub: PASTOR };
await signIn(h, '/');
assert.deepEqual((await h.db.member.findUnique({ where: { id: PASTOR } }))!.roles, []);
});
it('becomes Owner even after signing in as a Member first', async () => {
const h = await harness();
h.fake.next = { sub: PASTOR, email_verified: false };
await signIn(h, '/');
h.fake.next = { sub: PASTOR };
await signIn(h, '/');
assert.deepEqual((await h.db.member.findUnique({ where: { id: PASTOR } }))!.roles, ['owner']);
});
});
describe('2FA for every role (decision 7)', () => {
it('asks Accounts once more for a second step when someone with a role heads for the admin', async () => {
const h = await harness();
await h.db.member.create({ data: { id: PASTOR, name: 'Pastor Sam', email: 'pastor@hope.test', roles: ['prayer_coordinator'] } });
h.fake.next = { sub: PASTOR, amr: ['pwd'] };
const first = await signIn(h, '/admin');
assert.equal(first.back.headers.location, `${SITE}/api/auth/signin?mfa=1&returnTo=%2Fadmin`);
assert.equal(first.cookies.cca_session, undefined);
// Accounts still came back without one: say why.
const second = await signIn(h, '/admin', {}, true);
assert.equal(second.back.headers.location, `${SITE}/auth/problem?code=TWO_FACTOR_NEEDED&returnTo=%2Fadmin`);
});
it('lets someone with a role use the App as a Member without 2FA, but not the admin', async () => {
const h = await harness();
await h.db.member.create({ data: { id: PASTOR, name: 'Pastor Sam', email: 'pastor@hope.test', roles: ['church_admin'] } });
h.fake.next = { sub: PASTOR, amr: ['pwd'] };
const { back, cookies } = await signIn(h, '/prayer');
assert.equal(back.headers.location, `${SITE}/prayer`);
const res = await me(h, cookies);
assert.deepEqual(res.body.activeRoles, []);
const admin = await request(h.app).get('/api/v1/admin/overview').set('Cookie', cookieHeader(cookies));
assert.equal(admin.status, 403);
assert.equal(admin.body.error.code, 'TWO_FACTOR_NEEDED');
});
it('opens the admin with 2FA, and refuses a Member', async () => {
const h = await harness();
await h.db.member.create({ data: { id: PASTOR, name: 'Pastor Sam', email: 'pastor@hope.test', roles: ['devotional_writer'] } });
h.fake.next = { sub: PASTOR };
const staff = await signIn(h, '/admin');
const ok = await request(h.app).get('/api/v1/admin/overview').set('Cookie', cookieHeader(staff.cookies));
assert.equal(ok.status, 200);
assert.deepEqual(ok.body.activeMembers90d, { count: 1, band: '0–100' });
assert.equal(ok.body.accounts.url, 'https://accounts.hope.test');
h.fake.next = { sub: MEMBER, email: 'm@hope.test' };
const member = await signIn(h, '/');
const no = await request(h.app).get('/api/v1/admin/overview').set('Cookie', cookieHeader(member.cookies));
assert.equal(no.status, 403);
assert.equal(no.body.error.code, 'FORBIDDEN');
const out = await request(h.app).get('/api/v1/admin/overview');
assert.equal(out.status, 401);
});
it('lets only an Owner or Church admin switch modules', async () => {
const h = await harness();
await h.db.member.create({ data: { id: PASTOR, name: 'Pastor Sam', email: 'content@hope.test', roles: ['content_admin'] } });
h.fake.next = { sub: PASTOR, email: 'content@hope.test' };
let s = await signIn(h, '/admin');
const put = (cookies: Record<string, string>, body: object) => request(h.app).put('/api/v1/admin/modules').set('Origin', SITE).set('Cookie', cookieHeader(cookies)).send(body);
assert.equal((await put(s.cookies, { events: false })).status, 403);
await h.db.member.update({ where: { id: PASTOR }, data: { roles: ['church_admin'] } });
s = await signIn(h, '/admin');
const res = await put(s.cookies, { events: false, devotionals: false });
assert.equal(res.status, 200);
assert.deepEqual(res.body.modules, ['house-of-prayer', 'prayer-requests', 'announcements']);
assert.equal((await put(s.cookies, { chat: true })).status, 400);
assert.equal((await put(s.cookies, { events: true })).body.modules.includes('events'), true);
const app = await request(h.app).get('/api/v1/app');
assert.deepEqual(app.body.modules, ['house-of-prayer', 'prayer-requests', 'announcements', 'events']);
});
});
describe('staying signed in (decision 7)', () => {
it('lasts 8 days, renewed by each visit, never past 90 days from the sign-in', async () => {
const h = await harness();
h.fake.next = { sub: MEMBER, email: 'm@hope.test', amr: ['pwd'] };
const { cookies } = await signIn(h, '/');
// Every 7 days for 12 weeks: still signed in.
for (let week = 1; week <= 12; week++) {
h.clock.add(7 * DAY);
assert.equal((await me(h, cookies)).status, 200, `week ${week}`);
}
// Day 84 + 7 = 91: past the 90-day limit, even though the last visit was a week ago.
h.clock.add(7 * DAY);
assert.equal((await me(h, cookies)).status, 401);
});
it('ends after 8 days away', async () => {
const h = await harness();
h.fake.next = { sub: MEMBER, email: 'm@hope.test', amr: ['pwd'] };
const { cookies } = await signIn(h, '/');
h.clock.add(7 * DAY);
assert.equal((await me(h, cookies)).status, 200);
h.clock.add(8 * DAY + 60e3);
assert.equal((await me(h, cookies)).status, 401);
});
it('renews the cookie too', async () => {
const h = await harness();
h.fake.next = { sub: MEMBER, email: 'm@hope.test', amr: ['pwd'] };
const { cookies } = await signIn(h, '/');
h.clock.add(3 * DAY);
const res = await me(h, cookies);
const expires = /cca_session=[^;]+;.*Expires=([^;]+)/.exec(String(res.headers['set-cookie']))?.[1];
assert.equal(new Date(expires!).toISOString().slice(0, 10), new Date(h.clock.now().getTime() + 8 * DAY).toISOString().slice(0, 10));
});
it('ends at a back-channel logout from Accounts', async () => {
const h = await harness();
h.fake.next = { sub: MEMBER, email: 'm@hope.test', amr: ['pwd'] };
const { cookies } = await signIn(h, '/');
const res = await request(h.app).post('/api/auth/backchannel-logout').type('form').send({ logout_token: JSON.stringify({ sub: MEMBER, sid: null }) });
assert.equal(res.status, 200);
assert.equal((await me(h, cookies)).status, 401);
});
});
describe('active members (§10)', () => {
it('counts a member once a day, in the church\'s timezone, only when signed in', async () => {
const h = await harness();
h.fake.next = { sub: MEMBER, email: 'm@hope.test', amr: ['pwd'] };
const { cookies } = await signIn(h, '/');
await request(h.app).get('/api/v1/app');
assert.equal((await h.db.member.findUnique({ where: { id: MEMBER } }))!.lastActiveAt, null, 'signing in alone isn\'t using the App');
await me(h, cookies);
const first = (await h.db.member.findUnique({ where: { id: MEMBER } }))!.lastActiveAt as Date;
assert.equal(first.toISOString(), h.clock.now().toISOString());
h.clock.add(3 * 3600e3);
await me(h, cookies);
assert.equal(((await h.db.member.findUnique({ where: { id: MEMBER } }))!.lastActiveAt as Date).toISOString(), first.toISOString(), 'one write a day');
// 23:00 UTC is 01:00 the next day in Johannesburg: a new day.
h.clock.set('2026-12-01T23:00:00Z');
await me(h, cookies);
assert.equal(((await h.db.member.findUnique({ where: { id: MEMBER } }))!.lastActiveAt as Date).toISOString(), '2026-12-01T23:00:00.000Z');
});
});
describe('Accounts\' calls', () => {
const call = (h: H, body: object) => request(h.app).post('/api/accounts/v1/events').set('x-test-signed', 'yes').set('Content-Type', 'application/json').send(JSON.stringify(body));
const base = { schema: 'crosscode.identity/1', callId: '44444444-4444-4444-8444-444444444444', occurredAt: '2026-12-01T06:00:00.000Z', sub: MEMBER };
it('refuses an unsigned call', async () => {
const h = await harness();
const res = await request(h.app).post('/api/accounts/v1/events').set('Content-Type', 'application/json').send('{}');
assert.equal(res.status, 401);
});
it('keeps the profile copy up to date, WhatsApp STOP included', async () => {
const h = await harness();
await h.db.member.create({ data: { id: MEMBER, name: 'Thandi', email: 'thandi@hope.test' } });
const res = await call(h, { ...base, type: 'user.updated', profile: { name: 'Thandi M', given_name: 'Thandi', family_name: 'M', email: 'T@Hope.test', email_verified: true, phone_number: '+27821112222', phone_number_verified: true, news_consent: { email: true, whatsapp: false }, whatsapp_opted_out: true } });
assert.equal(res.status, 200);
const m = await h.db.member.findUnique({ where: { id: MEMBER } });
assert.equal(m!.name, 'Thandi M');
assert.equal(m!.email, 't@hope.test');
assert.equal(m!.phone, '+27821112222');
assert.equal(m!.whatsappOptedOut, true);
});
it('exports what the App keeps about someone, and forgets them when their account is deleted', async () => {
const h = await harness();
h.fake.next = { sub: MEMBER, email: 'm@hope.test', amr: ['pwd'] };
const { cookies } = await signIn(h, '/');
const exp = await call(h, { ...base, type: 'user.export', exportId: '55555555-5555-4555-8555-555555555555' });
assert.equal(exp.body.product, 'app');
assert.equal(exp.body.sections[0].records[0].email, 'm@hope.test');
const del = await call(h, { ...base, type: 'user.deleted' });
assert.equal(del.body.status, 'deleted');
assert.equal(await h.db.member.findUnique({ where: { id: MEMBER } }), null);
assert.equal((await me(h, cookies)).status, 401);
});
});
+115
View File
@@ -0,0 +1,115 @@
/**
* 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('; ');
+181
View File
@@ -0,0 +1,181 @@
/**
* An in-memory stand-in for the Prisma client (from the Website's tests/support/memoryDb.ts): every
* model the App uses, with the schema's defaults and unique fields, generic `where` matching
* (equality, in / notIn, gt / gte / lt / lte, not, contains, has, AND / OR), `include` of the
* relations below and `aggregate` sums. Enough to run the whole app in tests. Each module adds its
* models' defaults here as it arrives.
*/
import crypto from 'node:crypto';
type Row = Record<string, unknown>;
const DEFAULTS: Record<string, () => Row> = {
member: () => ({ phone: null, whatsappOptedOut: false, roles: [], lastActiveAt: null, lastSignInAt: null }),
session: () => ({ sid: null, mfa: false, idToken: null, lastSeenAt: new Date() }),
productLink: () => ({ connectedById: null, lastSyncError: null, showEvents: true, lastSyncAt: null, lastGoodAt: null }),
auditLog: () => ({ actorId: null, targetId: null, metadata: null, ip: null }),
};
const KEYS: Record<string, string> = { appSetting: 'key', productLink: 'installId', linkNonce: 'nonce' };
const UNIQUE: Record<string, string[]> = { session: ['tokenHash'] };
const HAS_UPDATED_AT = new Set(['member', 'appSetting', 'productLink']);
/** `include` support: model → relation → [other model, foreign key on the other (many) or on this row (one)]. */
const RELATIONS: Record<string, Record<string, { model: string; many: boolean; key: string }>> = {
member: { sessions: { model: 'session', many: true, key: 'memberId' } },
};
const v = (x: unknown) => (x instanceof Date ? x.getTime() : x);
function matchValue(actual: unknown, cond: unknown): boolean {
if (cond !== null && typeof cond === 'object' && !(cond instanceof Date) && !Array.isArray(cond)) {
const c = cond as Record<string, unknown>;
const insensitive = c.mode === 'insensitive';
return Object.entries(c).every(([op, x]) => {
switch (op) {
case 'mode': return true;
case 'equals': return v(actual) === v(x);
case 'in': return (x as unknown[]).map(v).includes(v(actual));
case 'notIn': return !(x as unknown[]).map(v).includes(v(actual));
case 'gt': return actual != null && (v(actual) as number) > (v(x) as number);
case 'gte': return actual != null && (v(actual) as number) >= (v(x) as number);
case 'lt': return actual != null && (v(actual) as number) < (v(x) as number);
case 'lte': return actual != null && (v(actual) as number) <= (v(x) as number);
case 'not': return x === null ? actual != null : !matchValue(actual, x);
case 'has': return Array.isArray(actual) && actual.map(v).includes(v(x));
case 'contains': return typeof actual === 'string' && (insensitive ? actual.toLowerCase().includes(String(x).toLowerCase()) : actual.includes(String(x)));
default: throw new Error(`memoryDb: no operator ${op}`);
}
});
}
return v(actual) === v(cond);
}
export function matches(row: Row, where: Row = {}): boolean {
return Object.entries(where ?? {}).every(([k, cond]) => {
if (k === 'AND') return (cond as Row[]).every((w) => matches(row, w));
if (k === 'OR') return (cond as Row[]).some((w) => matches(row, w));
if (k === 'NOT') return !matches(row, cond as Row);
return matchValue(row[k], cond);
});
}
/** Prisma.DbNull / JsonNull (a nullable Json field set to null) are stored as null, as Postgres does. */
const nulls = (x: unknown) => (x && typeof x === 'object' && /^(Db|Json)Null$/.test(x.constructor?.name ?? '') ? null : x);
const clone = <T>(x: T): T => structuredClone(x && typeof x === 'object' && !Array.isArray(x) && !(x instanceof Date) ? Object.fromEntries(Object.entries(x).map(([k, y]) => [k, nulls(y)])) as T : x);
const pick = (row: Row, select?: Row) => (select ? Object.fromEntries(Object.keys(select).filter((k) => select[k]).map((k) => [k, row[k]])) : row);
function order(rows: Row[], orderBy?: Row | Row[]) {
const list = Array.isArray(orderBy) ? orderBy : orderBy ? [orderBy] : [];
return [...rows].sort((a, b) => {
for (const o of list) {
const [k, dir] = Object.entries(o)[0]!;
const x = v(a[k]) as number;
const y = v(b[k]) as number;
const d = x < y ? -1 : x > y ? 1 : 0;
if (d) return dir === 'desc' ? -d : d;
}
return 0;
});
}
function prismaError(code: string, message: string) {
return Object.assign(new Error(message), { code });
}
function model(name: string, tables: Map<string, Map<unknown, Row>>) {
const key = KEYS[name] ?? 'id';
const table = () => {
if (!tables.has(name)) tables.set(name, new Map());
return tables.get(name)!;
};
const findWhere = (where: Row) => {
if (where && key in where && typeof where[key] !== 'object') return table().get(where[key]) ?? null;
for (const u of UNIQUE[name] ?? []) if (where && u in where) return [...table().values()].find((r) => r[u] === where[u]) ?? null;
return [...table().values()].find((r) => matches(r, where)) ?? null;
};
const checkUnique = (row: Row, except?: unknown) => {
for (const u of UNIQUE[name] ?? []) {
if (row[u] == null) continue;
if ([...table().values()].some((r) => r[key] !== except && r[u] === row[u])) throw prismaError('P2002', `Unique constraint failed on ${name}.${u}`);
}
};
const api = {
findUnique: async ({ where, select }: { where: Row; select?: Row }) => { const r = findWhere(where); return r ? pick(clone(r), select) : null; },
findUniqueOrThrow: async (args: { where: Row; select?: Row }) => { const r = await api.findUnique(args); if (!r) throw prismaError('P2025', `${name} not found`); return r; },
findFirst: async ({ where, orderBy, select }: { where?: Row; orderBy?: Row | Row[]; select?: Row } = {}) => { const r = order([...table().values()].filter((x) => matches(x, where)), orderBy)[0]; return r ? pick(clone(r), select) : null; },
findMany: async ({ where, orderBy, take, skip, select, include }: { where?: Row; orderBy?: Row | Row[]; take?: number; skip?: number; select?: Row; include?: Row } = {}) =>
order([...table().values()].filter((x) => matches(x, where)), orderBy).slice(skip ?? 0, (skip ?? 0) + (take ?? Infinity)).map((r) => withIncludes(pick(clone(r), select), include)),
aggregate: async ({ where, _sum }: { where?: Row; _sum: Row }) => {
const rows = [...table().values()].filter((x) => matches(x, where));
return { _sum: Object.fromEntries(Object.keys(_sum).map((k) => [k, rows.length ? rows.reduce((t, r) => t + Number(r[k] ?? 0), 0) : null])) };
},
count: async ({ where }: { where?: Row } = {}) => [...table().values()].filter((x) => matches(x, where)).length,
create: async ({ data }: { data: Row }) => {
const now = new Date();
const row: Row = { ...(DEFAULTS[name]?.() ?? {}), ...(key === 'id' ? { id: crypto.randomUUID() } : {}), createdAt: now, ...(HAS_UPDATED_AT.has(name) ? { updatedAt: now } : {}), ...clone(data) };
if (table().has(row[key])) throw prismaError('P2002', `Unique constraint failed on ${name}.${key}`);
checkUnique(row);
table().set(row[key], row);
return clone(row);
},
update: async ({ where, data }: { where: Row; data: Row }) => {
const r = findWhere(where);
if (!r) throw prismaError('P2025', `Record to update not found (${name})`);
const next = { ...r, ...clone(data), ...(HAS_UPDATED_AT.has(name) ? { updatedAt: new Date() } : {}) };
checkUnique(next, r[key]);
table().set(r[key], next);
return clone(next);
},
updateMany: async ({ where, data }: { where?: Row; data: Row }) => {
let count = 0;
for (const [k, r] of table()) if (matches(r, where)) { table().set(k, { ...r, ...clone(data) }); count++; }
return { count };
},
upsert: async ({ where, create, update }: { where: Row; create: Row; update: Row }) => {
const r = findWhere(where);
return r ? api.update({ where, data: update }) : api.create({ data: create });
},
delete: async ({ where }: { where: Row }) => {
const r = findWhere(where);
if (!r) throw prismaError('P2025', `Record to delete does not exist (${name})`);
table().delete(r[key]);
cascade(name, r[key]);
return clone(r);
},
deleteMany: async ({ where }: { where?: Row } = {}) => {
let count = 0;
for (const [k, r] of [...table()]) if (matches(r, where)) { table().delete(k); cascade(name, k); count++; }
return { count };
},
};
const cascade = (from: string, id: unknown) => {
if (from === 'member') for (const [k, r] of tables.get('session') ?? []) if (r.memberId === id) tables.get('session')!.delete(k);
};
const withIncludes = (row: Row, include?: Row) => {
for (const [rel, on] of Object.entries(include ?? {})) {
const spec = RELATIONS[name]?.[rel];
if (!on || !spec) continue;
const other = [...(tables.get(spec.model)?.values() ?? [])];
const nested = typeof on === 'object' ? (on as { orderBy?: Row | Row[] }).orderBy : undefined;
row[rel] = spec.many ? order(other.filter((o) => o[spec.key] === row.id), nested).map(clone) : clone(other.find((o) => o.id === row[spec.key]) ?? null);
}
return row;
};
return api;
}
export type MemoryDb = Record<string, ReturnType<typeof model>> & { tables: Map<string, Map<unknown, Row>>; $queryRaw: () => Promise<unknown[]>; $disconnect: () => Promise<void> };
export function memoryDb(): MemoryDb {
const tables = new Map<string, Map<unknown, Row>>();
const models = new Map<string, ReturnType<typeof model>>();
return new Proxy({} as MemoryDb, {
get(_t, prop: string) {
if (prop === 'tables') return tables;
if (prop === '$queryRaw' || prop === '$queryRawUnsafe') return async () => [{ ok: 1 }];
if (prop === '$disconnect') return async () => {};
if (prop === 'then') return undefined;
if (!models.has(prop)) models.set(prop, model(prop, tables));
return models.get(prop);
},
});
}