People: Owners and Admins add someone by email (people.ensure through Accounts), change roles, remove access; only Owners touch Owners, nobody changes themselves, a lower role ends sessions at once. Messages: from a YouTube channel or playlist every hour (public feed, no key) or by hand with a YouTube or Spotify link; own publish, hide. Simple events: own publish, cancel, remove. Tests and e2e with axe on the new screens. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
113 lines
5.4 KiB
TypeScript
113 lines
5.4 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 }[];
|
|
};
|
|
|
|
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 }) => {
|
|
fake.requests.push(input);
|
|
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('; ');
|