POST /api/accounts/v1/requests (crosscode.identity-request/1): import.* keeps each person's Events id as sub, password hash and authenticator secret (sealed in transit), consent, notices and lockout; linked when the email already has an account. people.* for product admins, limited to people the product knows. New recovery codes after the first 2FA sign-in for people moved in with 2FA. screen=signup. auth-client: request(), seal(), signUp. 8 new tests (47 in all). Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
187 lines
13 KiB
TypeScript
187 lines
13 KiB
TypeScript
// What a linked product asks of Accounts (crosscode.identity-request/1, contracts 1.8.0,
|
|
// docs/EVENTS-3.0-PLAN.md §4 and §8): moving Cross Events' users in with their passwords and
|
|
// authenticator apps, and the people.* requests an Events admin makes.
|
|
import assert from 'node:assert/strict';
|
|
import crypto from 'node:crypto';
|
|
import { after, before, describe, test } from 'node:test';
|
|
import bcrypt from 'bcryptjs';
|
|
import { ACCOUNTS_REQUEST_PATH, IDENTITY_REQUEST_SCHEMA, type ImportPerson } from '@crosscode/contracts';
|
|
import { ed25519PublicToPem, generateEd25519, importIdsHash, LINK_HEADERS, newLinkSecret, sealLinkValue, signedHeaders } from '@crosscode/contracts/signing';
|
|
import { Browser, PRODUCT_ID, startHarness, type Harness } from './support/harness.js';
|
|
import { codeAt, generateSecret } from '../src/lib/totp.js';
|
|
|
|
const EVENTS_ID = '6d1f0b2c-8a3e-4c5d-9e7f-1a2b3c4d5e6f';
|
|
let h: Harness;
|
|
let eventsSecret: string;
|
|
|
|
before(async () => {
|
|
h = await startHarness();
|
|
eventsSecret = newLinkSecret();
|
|
await h.db.productLink.create({
|
|
data: { installId: EVENTS_ID, product: 'events', url: 'https://events.hope.test', publicKey: ed25519PublicToPem(generateEd25519().publicKey), secret: h.ctx.secrets.encrypt(eventsSecret), connectedAt: new Date() },
|
|
});
|
|
});
|
|
after(async () => { await h.close(); });
|
|
|
|
/** Sends a request as a product (Events unless said otherwise). */
|
|
async function ask(body: Record<string, unknown>, opts: { from?: string; secret?: string; requestId?: string } = {}) {
|
|
const raw = JSON.stringify({ schema: IDENTITY_REQUEST_SCHEMA, requestId: opts.requestId ?? crypto.randomUUID(), actor: null, ...body });
|
|
const headers = signedHeaders(LINK_HEADERS, { senderId: opts.from ?? EVENTS_ID, secret: opts.secret ?? eventsSecret, rawBody: raw });
|
|
const res = await fetch(`${h.publicUrl}${ACCOUNTS_REQUEST_PATH}`, { method: 'POST', body: raw, headers: { 'content-type': 'application/json', ...headers } });
|
|
return { status: res.status, body: (await res.json()) as Record<string, unknown> };
|
|
}
|
|
|
|
function person(over: Partial<ImportPerson> = {}): ImportPerson {
|
|
return {
|
|
id: crypto.randomUUID(), name: 'Moved Person', email: `${crypto.randomUUID().slice(0, 8)}@hope.test`, emailVerified: true, phone: null,
|
|
passwordHash: null, twoFactor: null, totpSecret: null, totpLastStep: null, failedSignIns: 0, lockedUntil: null,
|
|
news: { email: true, whatsapp: false }, newsAskedAt: '2026-01-01T00:00:00.000Z', noticeVersionAccepted: 1,
|
|
noticeAcceptances: [{ version: 1, acceptedAt: '2026-01-01T00:00:00.000Z' }], consentChanges: [{ channel: 'email', granted: true, at: '2026-01-01T00:00:00.000Z' }],
|
|
lastSignInAt: '2026-11-01T00:00:00.000Z', status: 'active', admin: false, createdAt: '2025-01-01T00:00:00.000Z', ...over,
|
|
};
|
|
}
|
|
|
|
const begin = (check = false) => ask({ type: 'import.begin', check, notices: [], church: { name: null, primaryColour: null } });
|
|
|
|
describe('moving Cross Events\' users in', () => {
|
|
test('a batch is refused before import.begin, and a check writes nothing', async () => {
|
|
const p = person();
|
|
const refused = await ask({ type: 'import.batch', check: false, people: [p] });
|
|
assert.equal(refused.status, 409);
|
|
assert.equal(refused.body.code, 'NOT_MOVING');
|
|
const check = await ask({ type: 'import.batch', check: true, people: [p] });
|
|
assert.equal(check.status, 200, JSON.stringify(check.body));
|
|
assert.equal((check.body.results as { outcome: string }[])[0]!.outcome, 'created');
|
|
assert.equal(await h.db.account.findUnique({ where: { id: p.id } }), null);
|
|
});
|
|
|
|
test('people sign in with their old bcrypt password and authenticator app, then get new recovery codes', async () => {
|
|
const totp = generateSecret();
|
|
const thandi = person({ email: 'Thandi.Moved@Hope.test', passwordHash: sealLinkValue(eventsSecret, await bcrypt.hash('Old-events-pass1', 4)), twoFactor: 'totp', totpSecret: sealLinkValue(eventsSecret, totp), totpLastStep: 1 });
|
|
const sipho = person({ email: 'sipho.moved@hope.test', passwordHash: sealLinkValue(eventsSecret, await bcrypt.hash('Sipho-pass-123', 4)) });
|
|
assert.equal((await begin()).status, 200);
|
|
const batch = await ask({ type: 'import.batch', check: false, people: [thandi, sipho] });
|
|
assert.equal(batch.status, 200, JSON.stringify(batch.body));
|
|
assert.deepEqual((batch.body.results as { outcome: string }[]).map((r) => r.outcome), ['created', 'created']);
|
|
|
|
// The sub is Events' user id; the secret is stored encrypted with Accounts' own key.
|
|
const a = (await h.db.account.findUnique({ where: { id: thandi.id } }))!;
|
|
assert.equal(a.email, 'thandi.moved@hope.test');
|
|
assert.notEqual(a.totpSecret, totp);
|
|
assert.equal(a.recoveryCodesNeeded, true);
|
|
assert.equal((await h.db.consentChange.findMany({ where: { accountId: thandi.id } }))[0]!.source, 'events_import');
|
|
|
|
const browser = new Browser();
|
|
const r = await h.signIn(browser, 'thandi.moved@hope.test', 'Old-events-pass1', '/events/camp/register');
|
|
assert.ok('pending' in r, 'asks for the authenticator');
|
|
assert.equal(r.pending.stage, 'two_factor');
|
|
const done = await h.api(browser, 'POST', `/api/v2/interaction/${r.uid}/two-factor`, { code: codeAt(totp, Math.floor(Date.now() / 30000)) });
|
|
assert.equal(done.status, 200, JSON.stringify(done.body));
|
|
assert.equal((done.body.recoveryCodes as string[]).length, 10, 'new recovery codes, shown once');
|
|
assert.equal((await h.db.account.findUnique({ where: { id: thandi.id } }))!.recoveryCodesNeeded, false);
|
|
const back = await browser.follow(done.body.redirectTo as string, (u) => u.pathname === '/api/auth/callback');
|
|
const signed = await h.finishSignIn(back.url, r.started);
|
|
assert.equal(signed.claims.sub, thandi.id);
|
|
assert.equal(signed.returnTo, '/events/camp/register');
|
|
// bcrypt is replaced with Argon2id at the first sign-in.
|
|
assert.match(String((await h.db.account.findUnique({ where: { id: thandi.id } }))!.passwordHash), /^\$argon2id\$/);
|
|
|
|
const finish = await ask({ type: 'import.finish', count: 2, idsHash: importIdsHash([thandi.id, sipho.id]) });
|
|
assert.equal(finish.body.matched, true, JSON.stringify(finish.body));
|
|
assert.equal((await h.db.productLink.findUnique({ where: { installId: EVENTS_ID } }))!.importStartedAt, null);
|
|
});
|
|
|
|
test('an email that already has an account is linked, not overwritten; a repeat updates', async () => {
|
|
const existing = await h.makeAccount({ email: 'already@hope.test', password: 'Accounts-pass-1' });
|
|
await begin();
|
|
const dup = person({ email: 'ALREADY@hope.test', passwordHash: sealLinkValue(eventsSecret, await bcrypt.hash('Events-pass-99', 4)) });
|
|
const again = person({ name: 'Before' });
|
|
const first = await ask({ type: 'import.batch', check: false, people: [dup, again] });
|
|
const [linked, created] = first.body.results as { outcome: string; sub: string }[];
|
|
assert.equal(linked!.outcome, 'linked');
|
|
assert.equal(linked!.sub, existing.id);
|
|
assert.equal(created!.outcome, 'created');
|
|
const still = (await h.db.account.findUnique({ where: { id: existing.id as string } }))!;
|
|
assert.equal(still.passwordHash, existing.passwordHash, 'the Accounts password stays');
|
|
|
|
const repeat = await ask({ type: 'import.batch', check: false, people: [{ ...again, name: 'After' }] });
|
|
assert.equal((repeat.body.results as { outcome: string }[])[0]!.outcome, 'updated');
|
|
assert.equal((await h.db.account.findUnique({ where: { id: again.id } }))!.name, 'After');
|
|
await ask({ type: 'import.abort' });
|
|
});
|
|
|
|
test('a value sealed with another secret, a duplicate email, and a product that isn\'t Events are refused', async () => {
|
|
await begin();
|
|
const bad = person({ passwordHash: sealLinkValue(newLinkSecret(), '$2b$04$abc') });
|
|
assert.equal((await ask({ type: 'import.batch', check: false, people: [bad] })).status, 400);
|
|
const twice = person({ email: 'twice@hope.test' });
|
|
const res = await ask({ type: 'import.batch', check: false, people: [twice, person({ email: 'twice@hope.test' })] });
|
|
assert.deepEqual((res.body.results as { outcome: string }[]).map((r) => r.outcome), ['created', 'refused']);
|
|
const website = await ask({ type: 'import.begin', check: false, notices: [], church: { name: null, primaryColour: null } }, { from: PRODUCT_ID, secret: h.linkSecret });
|
|
assert.equal(website.body.code, 'WRONG_PRODUCT');
|
|
await ask({ type: 'import.abort' });
|
|
});
|
|
|
|
test('Events\' notice versions are taken when Accounts has none, and the church gets its name', async () => {
|
|
const fresh = await startHarness();
|
|
const secret = newLinkSecret();
|
|
await fresh.db.productLink.create({ data: { installId: EVENTS_ID, product: 'events', url: 'https://events.hope.test', publicKey: 'x', secret: fresh.ctx.secrets.encrypt(secret), connectedAt: new Date() } });
|
|
await fresh.ctx.settings.set('church_profile', '{}');
|
|
const raw = JSON.stringify({ schema: IDENTITY_REQUEST_SCHEMA, requestId: crypto.randomUUID(), actor: null, type: 'import.begin', check: false, church: { name: 'Grace Church', primaryColour: '#123456' }, notices: [{ version: 2, title: 'Our notice', body: 'How we use it.', publishedAt: '2026-02-01T00:00:00.000Z' }] });
|
|
const res = await fetch(`${fresh.publicUrl}${ACCOUNTS_REQUEST_PATH}`, { method: 'POST', body: raw, headers: { 'content-type': 'application/json', ...signedHeaders(LINK_HEADERS, { senderId: EVENTS_ID, secret, rawBody: raw }) } });
|
|
const body = (await res.json()) as Record<string, unknown>;
|
|
assert.equal(body.noticesTaken, true, JSON.stringify(body));
|
|
assert.equal((await fresh.db.privacyNotice.findUnique({ where: { version: 2 } }))!.title, 'Our notice');
|
|
const profile = await fresh.ctx.settings.json<{ name: string; branding: { colours: { primary: string } } }>('church_profile', {} as never);
|
|
assert.equal(profile.name, 'Grace Church');
|
|
assert.equal(profile.branding.colours.primary, '#123456');
|
|
await fresh.close();
|
|
});
|
|
});
|
|
|
|
describe('people.* from a product', () => {
|
|
test('people.ensure makes an account and emails a link that sets the password and goes back to the product', async () => {
|
|
const res = await ask({ type: 'people.ensure', name: 'New Staff', email: 'new.staff@hope.test', phone: null, returnUrl: 'https://events.hope.test/dashboard' });
|
|
assert.equal(res.status, 200, JSON.stringify(res.body));
|
|
assert.equal(res.body.created, true);
|
|
const link = new URL(h.messenger.lastLink('new.staff@hope.test')!);
|
|
const browser = new Browser();
|
|
const reset = await h.api(browser, 'POST', '/api/v2/password/reset', { token: link.searchParams.get('token'), password: 'Staff-pass-123' });
|
|
assert.equal(reset.body.returnUrl, 'https://events.hope.test/dashboard');
|
|
assert.equal((await h.db.account.findUnique({ where: { id: res.body.sub as string } }))!.emailVerified, true);
|
|
// The same email again: the same account.
|
|
const again = await ask({ type: 'people.ensure', name: 'New Staff', email: 'NEW.staff@hope.test', phone: null, returnUrl: 'https://evil.test/' });
|
|
assert.deepEqual([again.body.sub, again.body.created], [res.body.sub, false]);
|
|
});
|
|
|
|
test('a product can only change people it knows', async () => {
|
|
const stranger = await h.makeAccount({ email: 'stranger@hope.test' });
|
|
const res = await ask({ type: 'people.unlock', sub: stranger.id });
|
|
assert.equal(res.body.code, 'UNKNOWN_PERSON');
|
|
const known = await ask({ type: 'people.ensure', name: 'Known', email: 'known@hope.test', phone: null, returnUrl: 'https://events.hope.test/' });
|
|
const sub = known.body.sub as string;
|
|
await h.db.account.update({ where: { id: sub }, data: { lockedUntil: new Date(Date.now() + 3600e3), failedSignIns: 9 } });
|
|
assert.equal((await ask({ type: 'people.unlock', sub })).body.ok, true);
|
|
assert.equal((await h.db.account.findUnique({ where: { id: sub } }))!.lockedUntil, null);
|
|
const taken = await ask({ type: 'people.update', sub, email: 'stranger@hope.test' });
|
|
assert.equal(taken.body.code, 'EMAIL_TAKEN');
|
|
assert.equal((await ask({ type: 'people.update', sub, name: 'Known Person' })).body.ok, true);
|
|
assert.equal((await ask({ type: 'people.newsOff', sub, channel: 'all' })).body.ok, true);
|
|
assert.equal((await ask({ type: 'people.setActive', sub, active: false })).body.ok, true);
|
|
assert.equal((await h.db.account.findUnique({ where: { id: sub } }))!.status, 'deactivated');
|
|
});
|
|
|
|
test('a retry with the same request id gets the same answer; a bad signature is refused', async () => {
|
|
const requestId = crypto.randomUUID();
|
|
const body = { type: 'people.ensure', name: 'Retry', email: 'retry@hope.test', phone: null, returnUrl: 'https://events.hope.test/' };
|
|
const one = await ask(body, { requestId });
|
|
const two = await ask(body, { requestId });
|
|
assert.deepEqual(two.body, one.body);
|
|
assert.equal(two.body.created, true, 'the first answer, not "already there"');
|
|
const forged = await ask(body, { secret: newLinkSecret() });
|
|
assert.equal(forged.status, 401);
|
|
const unknown = await ask(body, { from: crypto.randomUUID() });
|
|
assert.equal(unknown.body.code, 'NOT_LINKED');
|
|
});
|
|
});
|