- scripts/products/events.sh: packages/auth-client is installed and built (after contracts) when Events uses it, as 3.0.0 does; without it a 3.0 deploy would fail at the first sign-in through Accounts. bats test. - test:accounts runs on real Postgres for both apps with EVENTS_TEST_DATABASE_URL and ACCOUNTS_TEST_DATABASE_URL (14/14); the Accounts test harness takes a real Prisma client. - e2e/excel.spec.ts resolves excelts from the backend (hoisted in the monorepo), so the e2e suite loads again. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
281 lines
17 KiB
TypeScript
281 lines
17 KiB
TypeScript
// Cross Events 3.0 against the real Accounts (docs/EVENTS-3.0-PLAN.md §12): Events' own code (the
|
|
// move, sign-in, sign-out, Accounts' calls) talking to the whole Accounts app on real ports, each with
|
|
// an in-memory database. Run with `npm run test:accounts` (node:test through tsx, not Jest: Accounts
|
|
// is ES modules).
|
|
import assert from 'node:assert/strict';
|
|
import crypto from 'node:crypto';
|
|
import http from 'node:http';
|
|
import type { AddressInfo } from 'node:net';
|
|
import { createRequire } from 'node:module';
|
|
import { after, before, describe, test } from 'node:test';
|
|
import bcrypt from 'bcryptjs';
|
|
import express from 'express';
|
|
import jwt from 'jsonwebtoken';
|
|
import { ed25519PublicToPem, generateEd25519, newLinkSecret } from '@crosscode/contracts/signing';
|
|
import { Browser, startHarness, ACCOUNTS_ID, type Harness } from '../../../../accounts/backend/tests/support/harness.ts';
|
|
import { memoryDb } from '../../../../accounts/backend/tests/support/memoryDb.ts';
|
|
import { codeAt, generateSecret } from '../../../../accounts/backend/src/lib/totp.ts';
|
|
import { runDue } from '../../../../accounts/backend/src/links/deliveries.ts';
|
|
import { signOutEverywhere } from '../../../../accounts/backend/src/oidc/sessions.ts';
|
|
import { profileChanged } from '../../../../accounts/backend/src/accounts/service.ts';
|
|
|
|
const require = createRequire(import.meta.url);
|
|
process.env.NODE_ENV = 'test';
|
|
process.env.JWT_SECRET = 'an-events-test-secret-long-enough-for-the-encryption-key';
|
|
|
|
// With EVENTS_TEST_DATABASE_URL and ACCOUNTS_TEST_DATABASE_URL (empty, migrated databases), both
|
|
// apps use real Postgres; otherwise in-memory stand-ins (Events' with Prisma's `{ increment }`).
|
|
const PG = !!(process.env.EVENTS_TEST_DATABASE_URL && process.env.ACCOUNTS_TEST_DATABASE_URL);
|
|
if (PG) process.env.DATABASE_URL = process.env.EVENTS_TEST_DATABASE_URL;
|
|
const raw = memoryDb();
|
|
const eventsDb = new Proxy(raw, {
|
|
get(target, prop: string) {
|
|
const model = (target as unknown as Record<string, Record<string, (...a: unknown[]) => Promise<unknown>>>)[prop];
|
|
if (prop !== 'user') return model;
|
|
return new Proxy(model, {
|
|
get(m, op: string) {
|
|
if (op !== 'update') return m[op];
|
|
return async (args: { where: Record<string, unknown>; data: Record<string, unknown>; select?: Record<string, boolean> }) => {
|
|
const inc = args.data.tokenVersion as { increment?: number } | undefined;
|
|
if (inc && typeof inc === 'object' && 'increment' in inc) {
|
|
const cur = (await m.findUnique!({ where: args.where })) as { tokenVersion: number };
|
|
args = { ...args, data: { ...args.data, tokenVersion: cur.tokenVersion + inc.increment! } };
|
|
}
|
|
return m.update!(args);
|
|
};
|
|
},
|
|
});
|
|
},
|
|
});
|
|
const dbPath = require.resolve('../../src/config/db.js');
|
|
if (!PG) require.cache[dbPath] = { id: dbPath, filename: dbPath, loaded: true, exports: eventsDb } as never;
|
|
const realEventsDb = PG ? require(dbPath) : null;
|
|
const edb = (realEventsDb ?? eventsDb) as typeof eventsDb;
|
|
|
|
const { encrypt } = require('../../src/utils/encryption.js');
|
|
const { accountsRouter } = require('../../src/accounts/signin.ts');
|
|
const { signInGuard } = require('../../src/accounts/guard.ts');
|
|
const { protect } = require('../../src/middleware/authMiddleware.js');
|
|
const move = require('../../src/accounts/move.ts');
|
|
const mode = require('../../src/accounts/mode.ts');
|
|
const { setAuthClientLoader } = require('../../src/accounts/client.ts');
|
|
|
|
const EVENTS_ID = '6d1f0b2c-8a3e-4c5d-9e7f-1a2b3c4d5e6f';
|
|
let h: Harness;
|
|
let eventsUrl: string;
|
|
let server: http.Server;
|
|
const totpSecret = generateSecret();
|
|
const ids = { thandi: crypto.randomUUID(), sam: crypto.randomUUID(), lerato: crypto.randomUUID(), guest: crypto.randomUUID(), sipho: crypto.randomUUID() };
|
|
|
|
async function eventsUser(data: Record<string, unknown>) {
|
|
return edb.user.create({
|
|
data: {
|
|
accountId: null, role: 'user', isActive: true, tokenVersion: 0, phoneNumber: null, failedAttempts: 0, lockUntil: null, twoFactorEnabled: false, twoFactorMethod: null,
|
|
totpSecret: null, totpLastStep: null, newsEmail: false, newsWhatsApp: false, newsAskedAt: new Date(), noticeVersionAccepted: 0, lastLoginAt: new Date('2026-10-01'),
|
|
notificationPreference: 'email', inactivityWarnedAt: null, ...data,
|
|
},
|
|
});
|
|
}
|
|
|
|
before(async () => {
|
|
if (PG) {
|
|
const { PrismaClient } = await import('../../../../accounts/backend/src/generated/prisma/client.ts');
|
|
const { PrismaPg } = await import('@prisma/adapter-pg');
|
|
h = await startHarness({ db: new PrismaClient({ adapter: new PrismaPg({ connectionString: process.env.ACCOUNTS_TEST_DATABASE_URL! }) }) });
|
|
} else {
|
|
h = await startHarness();
|
|
}
|
|
setAuthClientLoader(() => import('@crosscode/auth-client'));
|
|
|
|
// Events on a real port: the sign-in routes, the guard, and one page that needs signing in.
|
|
const app = express();
|
|
app.use('/api', accountsRouter(protect));
|
|
app.use(express.json());
|
|
app.use((req, res, next) => { signInGuard(req, res, next).catch(next); });
|
|
app.get('/api/v2/me', protect, (req, res) => res.json({ data: { id: (req as unknown as { user: { id: string } }).user.id } }));
|
|
app.post('/api/v2/auth/login', (_req, res) => res.json({ data: { status: 'local' } }));
|
|
server = http.createServer(app);
|
|
await new Promise<void>((r) => server.listen(0, '127.0.0.1', () => r()));
|
|
eventsUrl = `http://127.0.0.1:${(server.address() as AddressInfo).port}`;
|
|
process.env.FRONTEND_URL = eventsUrl;
|
|
|
|
// Connect (as Linked products would): the same secret on both sides.
|
|
const secret = newLinkSecret();
|
|
await h.db.productLink.create({ data: { installId: EVENTS_ID, product: 'events', url: eventsUrl, publicKey: ed25519PublicToPem(generateEd25519().publicKey), secret: h.ctx.secrets.encrypt(secret), connectedAt: new Date() } });
|
|
await edb.productLink.create({ data: { installId: ACCOUNTS_ID, product: 'accounts', url: h.publicUrl, publicKey: 'x', secret: encrypt(secret), connectedAt: new Date(), updatedAt: new Date() } });
|
|
await edb.appSetting.create({ data: { key: 'hub_install_id', value: EVENTS_ID } });
|
|
|
|
// Events' people before the move.
|
|
await eventsUser({ id: ids.thandi, name: 'Thandi Mokoena', email: 'thandi@hope.test', password: await bcrypt.hash('Old-events-pass1', 4), newsEmail: true });
|
|
await eventsUser({ id: ids.sam, name: 'Sam Admin', email: 'sam@hope.test', role: 'admin', password: await bcrypt.hash('Admin-pass-123', 4), twoFactorEnabled: true, twoFactorMethod: 'authenticator', totpSecret: encrypt(totpSecret), totpLastStep: 1 });
|
|
await eventsUser({ id: ids.lerato, name: 'Lerato', email: 'lerato@hope.test', password: await bcrypt.hash('Events-pass-99', 4) });
|
|
await eventsUser({ id: ids.sipho, name: 'Sipho Supervisor', email: 'sipho@hope.test', role: 'supervisor', password: await bcrypt.hash('Sipho-pass-123', 4) });
|
|
await eventsUser({ id: ids.guest, name: 'Door Guest', email: 'guest+ab12cd34@guest.local', password: 'x' });
|
|
// Lerato already made a church account (e.g. on the website) with another password.
|
|
await h.makeAccount({ email: 'lerato@hope.test', password: 'Accounts-pass-1', name: 'Lerato M' });
|
|
});
|
|
after(async () => {
|
|
await new Promise((r) => server.close(r));
|
|
await h.close();
|
|
});
|
|
|
|
/** Signs in through Events: Events → Accounts → Events' callback → /auth/complete#code → handoff. */
|
|
async function signInThroughEvents(browser: Browser, email: string, password: string, returnTo: string, opts: { totp?: string } = {}) {
|
|
const start = `${eventsUrl}/api/auth/signin?returnTo=${encodeURIComponent(returnTo)}`;
|
|
const toComplete = (u: URL) => u.host === new URL(eventsUrl).host && (u.pathname === '/auth/complete' || u.pathname === '/auth/problem');
|
|
let at = await browser.follow(start, (u) => u.pathname === '/signin' || toComplete(u));
|
|
const steps: Record<string, unknown>[] = [];
|
|
for (let i = 0; i < 4 && at.url.pathname === '/signin'; i++) {
|
|
const uid = at.url.searchParams.get('uid')!;
|
|
let step = await h.api(browser, 'GET', `/api/v2/interaction/${uid}/state`);
|
|
if (step.body.stage === 'password') step = await h.api(browser, 'POST', `/api/v2/interaction/${uid}/password`, { email, password });
|
|
if (step.body.stage === 'two_factor') step = await h.api(browser, 'POST', `/api/v2/interaction/${uid}/two-factor`, { code: codeAt(opts.totp!, Math.floor(Date.now() / 30000)) });
|
|
steps.push(step.body);
|
|
assert.equal(step.body.stage, 'done', JSON.stringify(step.body));
|
|
at = await browser.follow(step.body.redirectTo as string, (u) => u.pathname === '/signin' || toComplete(u));
|
|
}
|
|
if (at.url.pathname === '/auth/problem') return { problem: at.url.searchParams.get('code'), steps };
|
|
const code = at.url.hash.slice(1);
|
|
const res = await fetch(`${eventsUrl}/api/auth/handoff`, { method: 'POST', headers: { 'content-type': 'application/json' }, body: JSON.stringify({ code }) });
|
|
const body = (await res.json()) as { data: { token: string; returnTo: string; user: { id: string } } };
|
|
return { ...body.data, code, steps };
|
|
}
|
|
|
|
const me = (token: string) => fetch(`${eventsUrl}/api/v2/me`, { headers: { authorization: `Bearer ${token}` } });
|
|
|
|
describe('moving Events\' sign-in to Accounts', () => {
|
|
test('the check counts people and writes nothing', async () => {
|
|
const r = await move.check();
|
|
assert.equal(r.toMove, 4, 'the guest stays');
|
|
assert.equal(r.skipped, 1);
|
|
assert.equal(r.wouldCreate, 3);
|
|
assert.deepEqual(r.wouldLink.map((l: { email: string }) => l.email), ['lerato@hope.test']);
|
|
assert.deepEqual(r.admins.map((a: { id: string }) => a.id), [ids.sam]);
|
|
assert.equal(await h.db.account.findUnique({ where: { id: ids.thandi } }), null);
|
|
assert.equal(await mode.authMode(), 'local');
|
|
});
|
|
|
|
test('the move copies everyone, links Lerato to her account, and switches', async () => {
|
|
const report = await move.move({ actor: { id: ids.sam, role: 'admin', name: 'Sam Admin' }, adminIds: [ids.sam] });
|
|
assert.equal(report.created, 3);
|
|
assert.equal(report.linked.length, 1);
|
|
mode.forgetMode();
|
|
assert.equal(await mode.authMode(), 'accounts');
|
|
const thandi = await edb.user.findUnique({ where: { id: ids.thandi } }) as { accountId: string };
|
|
assert.equal(thandi.accountId, ids.thandi, 'sub = Events id');
|
|
const lerato = await edb.user.findUnique({ where: { id: ids.lerato } }) as { accountId: string };
|
|
const account = await h.db.account.findUnique({ where: { email: 'lerato@hope.test' } }) as { id: string };
|
|
assert.equal(lerato.accountId, account.id, 'linked to the account she had');
|
|
assert.equal((await edb.user.findUnique({ where: { id: ids.guest } }) as { accountId: string | null }).accountId, null);
|
|
assert.equal((await h.db.account.findUnique({ where: { id: ids.sam } }) as { role: string }).role, 'admin');
|
|
});
|
|
});
|
|
|
|
describe('signing in through Events after the move', () => {
|
|
test('Thandi signs in with her old Events password and lands on the page she started from', async () => {
|
|
const r = await signInThroughEvents(new Browser(), 'thandi@hope.test', 'Old-events-pass1', '/events/youth-camp/register?ticket=adult');
|
|
assert.ok('token' in r && r.token, JSON.stringify(r));
|
|
assert.equal(r.returnTo, '/events/youth-camp/register?ticket=adult');
|
|
assert.equal(r.user.id, ids.thandi);
|
|
assert.equal((await me(r.token)).status, 200);
|
|
// The code is single use.
|
|
const again = await fetch(`${eventsUrl}/api/auth/handoff`, { method: 'POST', headers: { 'content-type': 'application/json' }, body: JSON.stringify({ code: r.code }) });
|
|
assert.equal(again.status, 400);
|
|
});
|
|
|
|
test('a foreign return address lands on the home page instead', async () => {
|
|
const r = await signInThroughEvents(new Browser(), 'thandi@hope.test', 'Old-events-pass1', '//evil.test/steal');
|
|
assert.ok('returnTo' in r);
|
|
assert.equal(r.returnTo, '/');
|
|
});
|
|
|
|
test('the admin signs in with the old authenticator app, gets new recovery codes, and the token says mfa', async () => {
|
|
const r = await signInThroughEvents(new Browser(), 'sam@hope.test', 'Admin-pass-123', '/dashboard/admin', { totp: totpSecret });
|
|
assert.ok('token' in r && r.token, JSON.stringify(r));
|
|
assert.equal((r.steps[0]!.recoveryCodes as string[]).length, 10);
|
|
assert.equal((jwt.decode(r.token) as { mfa: boolean }).mfa, true);
|
|
assert.equal((await me(r.token)).status, 200);
|
|
});
|
|
|
|
test('a supervisor without 2FA is sent back to Accounts to set it up', async () => {
|
|
const browser = new Browser();
|
|
const start = `${eventsUrl}/api/auth/signin?returnTo=/dashboard`;
|
|
let at = await browser.follow(start, (u) => u.pathname === '/signin');
|
|
const uid = at.url.searchParams.get('uid')!;
|
|
const step = await h.api(browser, 'POST', `/api/v2/interaction/${uid}/password`, { email: 'sipho@hope.test', password: 'Sipho-pass-123' });
|
|
assert.equal(step.body.stage, 'done');
|
|
at = await browser.follow(step.body.redirectTo as string, (u) => u.pathname === '/signin' || u.pathname === '/auth/complete');
|
|
assert.equal(at.url.pathname, '/signin', 'back at Accounts for the second step');
|
|
const state = await h.api(browser, 'GET', `/api/v2/interaction/${at.url.searchParams.get('uid')}/state`);
|
|
assert.equal(state.body.stage, 'setup_two_factor');
|
|
});
|
|
|
|
test('Events\' own sign-in now says where to go', async () => {
|
|
const res = await fetch(`${eventsUrl}/api/v2/auth/login`, { method: 'POST', headers: { 'content-type': 'application/json' }, body: '{}' });
|
|
assert.equal(res.status, 409);
|
|
assert.equal(((await res.json()) as { error: { code: string } }).error.code, 'SIGN_IN_MOVED');
|
|
});
|
|
});
|
|
|
|
describe('signing out, and Accounts\' calls', () => {
|
|
test('signing out of Events ends the session here and gives Accounts\' sign-out address', async () => {
|
|
const r = await signInThroughEvents(new Browser(), 'thandi@hope.test', 'Old-events-pass1', '/');
|
|
assert.ok('token' in r);
|
|
const out = await fetch(`${eventsUrl}/api/auth/signout`, { method: 'POST', headers: { authorization: `Bearer ${r.token}`, 'content-type': 'application/json' }, body: '{}' });
|
|
const body = (await out.json()) as { data: { url: string } };
|
|
assert.match(body.data.url, new RegExp(`^${h.publicUrl}/api/oidc/session/end`));
|
|
assert.equal((await me(r.token)).status, 401);
|
|
});
|
|
|
|
test('signing out everywhere in Accounts ends the Events session (back-channel logout)', async () => {
|
|
const r = await signInThroughEvents(new Browser(), 'thandi@hope.test', 'Old-events-pass1', '/');
|
|
assert.ok('token' in r);
|
|
assert.equal((await me(r.token)).status, 200);
|
|
await signOutEverywhere(h.ctx, h.provider, ids.thandi);
|
|
assert.equal((await me(r.token)).status, 401);
|
|
});
|
|
|
|
test('a name changed in Accounts reaches Events (user.updated)', async () => {
|
|
await h.db.account.update({ where: { id: ids.thandi }, data: { name: 'Thandi M. Mokoena' } });
|
|
await profileChanged(h.ctx, ids.thandi);
|
|
await runDue(h.ctx);
|
|
assert.equal((await edb.user.findUnique({ where: { id: ids.thandi } }) as { name: string }).name, 'Thandi M. Mokoena');
|
|
});
|
|
|
|
test('people added here after the move (demo data) are moved too, and can sign in', async () => {
|
|
const id = crypto.randomUUID();
|
|
await eventsUser({ id, name: 'Demo Person', email: 'demo.person@hope.test', password: await bcrypt.hash('Demo-pass-123', 4) });
|
|
const r = await move.moveNewPeople(null);
|
|
assert.equal(r.moved, 1);
|
|
assert.equal((await edb.user.findUnique({ where: { id } }) as { accountId: string }).accountId, id);
|
|
const signed = await signInThroughEvents(new Browser(), 'demo.person@hope.test', 'Demo-pass-123', '/');
|
|
assert.ok('token' in signed && signed.token);
|
|
});
|
|
|
|
test('someone new to Events signs in with a church account they made elsewhere', async () => {
|
|
const a = await h.makeAccount({ email: 'newcomer@hope.test', password: 'Newcomer-pass-1', name: 'Newcomer' });
|
|
const r = await signInThroughEvents(new Browser(), 'newcomer@hope.test', 'Newcomer-pass-1', '/events');
|
|
assert.ok('token' in r && r.token, JSON.stringify(r));
|
|
assert.equal((await edb.user.findUnique({ where: { id: r.user.id } }) as { accountId: string; role: string }).accountId, a.id);
|
|
});
|
|
|
|
test('Undo goes back to Events\' own sign-in', async () => {
|
|
await move.undo({ id: ids.sam, role: 'admin' });
|
|
mode.forgetMode();
|
|
assert.equal(await mode.authMode(), 'local');
|
|
const res = await fetch(`${eventsUrl}/api/v2/auth/login`, { method: 'POST', headers: { 'content-type': 'application/json' }, body: '{}' });
|
|
assert.equal(res.status, 200);
|
|
});
|
|
});
|
|
|
|
describe('moving again after Undo', () => {
|
|
test('works, including someone who joined through Accounts in between', async () => {
|
|
mode.forgetMode();
|
|
assert.equal(await mode.authMode(), 'local');
|
|
const report = await move.move({ actor: { id: ids.sam, role: 'admin' }, adminIds: [] });
|
|
assert.equal(report.created, 0, 'nobody new to move');
|
|
mode.forgetMode();
|
|
assert.equal(await mode.authMode(), 'accounts');
|
|
});
|
|
});
|