Cross Events 3.0.0: sign-in through the church's Accounts
Settings -> Sign-in: check, move (everyone into Accounts with their password hashes and authenticator apps, count/hash check, then switch) and undo for 14 days. Sign-in through auth-client with a one-time handoff to Events' own token; staff roles stepped up to mfa; sign-out and back-channel logout; user.updated/export/deleted; admin 2FA reset, unlock and profile changes via Accounts; /login, /register, /forgot-password forward once moved; Events' own sign-in endpoints answer SIGN_IN_MOVED. User.accountId, AccountsSignIn. npm run test:accounts runs Events' code against the real Accounts app (11 tests); 5 new Jest tests. MIGRATING-TO-3.md, plan "Changes while building". Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
@@ -0,0 +1,241 @@
|
||||
// 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';
|
||||
|
||||
// Events' database: the in-memory stand-in, with Prisma's `{ increment }` for tokenVersion.
|
||||
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');
|
||||
require.cache[dbPath] = { id: dbPath, filename: dbPath, loaded: true, exports: eventsDb } as never;
|
||||
|
||||
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 eventsDb.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 () => {
|
||||
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 eventsDb.productLink.create({ data: { installId: ACCOUNTS_ID, product: 'accounts', url: h.publicUrl, publicKey: 'x', secret: encrypt(secret), connectedAt: new Date(), updatedAt: new Date() } });
|
||||
await eventsDb.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 eventsDb.user.findUnique({ where: { id: ids.thandi } }) as { accountId: string };
|
||||
assert.equal(thandi.accountId, ids.thandi, 'sub = Events id');
|
||||
const lerato = await eventsDb.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 eventsDb.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 eventsDb.user.findUnique({ where: { id: ids.thandi } }) as { name: string }).name, 'Thandi M. Mokoena');
|
||||
});
|
||||
|
||||
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);
|
||||
});
|
||||
});
|
||||
Reference in New Issue
Block a user