diff --git a/CHANGELOG.md b/CHANGELOG.md index 5317b7a..30c1ff1 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -9,7 +9,7 @@ Built on `feat/events-3.0`; not tagged until the VM test and a run on real Postg - **Contracts 1.8.0:** `crosscode.identity-request/1` (product → Accounts at `/api/accounts/v1/requests`): `import.begin` / `batch` / `finish` / `abort` and `people.*`; - `sealLinkValue` / `openLinkValue` and `importIdsHash` in `/signing`. + `sealLinkValue` / `openLinkValue` in `/signing`. - **Accounts 1.1.0:** takes the requests: moves Events' users in with their password hashes and authenticator secrets, new recovery codes after the first 2FA sign-in, `people.*` for people a product knows, `screen=signup`. Details in `apps/accounts/CHANGELOG.md`. diff --git a/apps/accounts/CHANGELOG.md b/apps/accounts/CHANGELOG.md index 07ce988..ce57b64 100644 --- a/apps/accounts/CHANGELOG.md +++ b/apps/accounts/CHANGELOG.md @@ -14,7 +14,8 @@ For Cross Events 3.0 (docs/EVENTS-3.0-PLAN.md §8), with contracts 1.8.0. Accounts' key at rest), lockout, news consent and its history, notice acceptance, last sign-in and status; ticked Events admins become Accounts admins. An email that already has an account is **linked** (that account and its password stay). A check (`check: true`) writes nothing. - `import.finish` compares the count and a hash of the subs. Events' privacy notice versions are + `import.finish` checks every sub the product relies on is an account here, not deleted, and + known to that product, and lists the ones that aren't. Events' privacy notice versions are taken when Accounts has published none; an empty church name and colour are filled from Events. - **New recovery codes after the first sign-in** for people moved in with 2FA (their Events codes can't move): shown once after the second step, whatever step comes next. diff --git a/apps/accounts/backend/src/links/requests.ts b/apps/accounts/backend/src/links/requests.ts index 746b9f8..d5a1b1a 100644 --- a/apps/accounts/backend/src/links/requests.ts +++ b/apps/accounts/backend/src/links/requests.ts @@ -18,7 +18,7 @@ import { ACCOUNTS_REQUEST_PATH, IDENTITY_REQUEST_SCHEMA, identityRequestSchema, type IdentityRequest, type ImportPerson, type ImportResult, } from '@crosscode/contracts'; -import { importIdsHash, LINK_HEADERS, openLinkValue, verify } from '@crosscode/contracts/signing'; +import { LINK_HEADERS, openLinkValue, verify } from '@crosscode/contracts/signing'; import type { Ctx } from '../context.js'; import type { ProductLink } from '../generated/prisma/client.js'; import { limit } from '../http.js'; @@ -196,12 +196,15 @@ async function handle(ctx: Ctx, provider: Provider, link: ProductLink, secret: s } case 'import.finish': { if (!link.importStartedAt) throw new RequestError('There\'s no move under way.', 'NOT_MOVING', 409); - const rows = await ctx.db.productPerson.findMany({ where: { linkId: link.installId, via: 'import' } }); - const subs = rows.map((x) => x.accountId); - const matched = subs.length === r.count && importIdsHash(subs) === r.idsHash; + // Every account the product relies on must be here, not deleted, and known to it. + const wanted = [...new Set(r.subs)]; + const known = new Set((await ctx.db.productPerson.findMany({ where: { linkId: link.installId, accountId: { in: wanted } } })).map((x) => x.accountId)); + const live = new Set((await ctx.db.account.findMany({ where: { id: { in: wanted }, status: { not: 'deleted' } }, select: { id: true } })).map((x) => x.id as string)); + const missing = wanted.filter((s) => !known.has(s) || !live.has(s)); + const matched = missing.length === 0; if (matched) await ctx.db.productLink.update({ where: { installId: link.installId }, data: { importStartedAt: null } }); - await logRequest(ctx, link, r, matched ? 'import_finished' : 'import_mismatch', null, req, { count: subs.length, expected: r.count }); - return reply({ matched, count: subs.length }); + await logRequest(ctx, link, r, matched ? 'import_finished' : 'import_mismatch', null, req, { count: wanted.length - missing.length, expected: wanted.length }); + return reply({ matched, count: wanted.length - missing.length, missing: missing.slice(0, 100) }); } case 'import.abort': { await ctx.db.productLink.update({ where: { installId: link.installId }, data: { importStartedAt: null } }); diff --git a/apps/accounts/backend/tests/requests.test.ts b/apps/accounts/backend/tests/requests.test.ts index e57ddc2..9d5def0 100644 --- a/apps/accounts/backend/tests/requests.test.ts +++ b/apps/accounts/backend/tests/requests.test.ts @@ -6,7 +6,7 @@ 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 { ed25519PublicToPem, generateEd25519, 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'; @@ -86,7 +86,13 @@ describe('moving Cross Events\' users in', () => { // 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]) }); + // A sub Accounts doesn't hold for this product keeps the move open. + const stranger = crypto.randomUUID(); + const short = await ask({ type: 'import.finish', subs: [thandi.id, sipho.id, stranger] }); + assert.equal(short.body.matched, false); + assert.deepEqual(short.body.missing, [stranger]); + assert.ok((await h.db.productLink.findUnique({ where: { installId: EVENTS_ID } }))!.importStartedAt); + const finish = await ask({ type: 'import.finish', subs: [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); }); diff --git a/apps/events/CHANGELOG.md b/apps/events/CHANGELOG.md index 0c11cac..23d3772 100644 --- a/apps/events/CHANGELOG.md +++ b/apps/events/CHANGELOG.md @@ -43,6 +43,12 @@ for people until an admin moves sign-in; see MIGRATING-TO-3.md. clears Events' passwords, authenticator secrets, recovery codes and trusted devices 14 days after the move, and sign-in records after 40 days. - `npm run test:accounts` (backend): Events' sign-in and move against the real Accounts app. +- **Connects to the church's Accounts by itself** once the Hub lists it (once: a later Disconnect + stays), so a new install from Hub 2.5.0 needs no Connect. +- **Demo data** with sign-in through Accounts: the demo people get church accounts with the demo + password (`moveNewPeople`, also for anyone added here later without signing in through Accounts). +- `e2e/sign-in-accounts.spec.ts`: the move on Settings → Sign-in and signing in at Accounts' real + pages from a deep link, with Accounts in memory. ### Changed diff --git a/apps/events/backend/scripts/set-demo.js b/apps/events/backend/scripts/set-demo.js index beb1957..83a2ae5 100644 --- a/apps/events/backend/scripts/set-demo.js +++ b/apps/events/backend/scripts/set-demo.js @@ -1904,6 +1904,7 @@ async function main() { }, { maxWait: 10 * 1000, timeout: 5 * 60 * 1000 }); clearScheduledEmails(); const pastFinancials = await closePastEvents(); + const accounts = await demoAccounts(); const count = (model, where = () => true) => (rows[model] || []).filter(where).length; console.log(`\nCleared ${cleared.tables} tables and ${cleared.users} users.`); @@ -1952,9 +1953,40 @@ async function main() { console.log(`Demo staff logins (password ${DEMO_PASSWORD}):`); for (const s of staffTeam) console.log(` ${s.role.padEnd(10)} ${s.email}`); console.log(`Every other demo person also uses ${DEMO_PASSWORD}.`); + if (accounts) { + console.log(`Sign-in goes through the church's Accounts: ${accounts.moved} demo people have church accounts with that password${accounts.refused.length ? ` (${accounts.refused.length} couldn't: ${accounts.refused.map(r => `${r.email} ${r.reason}`).join('; ')})` : ''}.`); + } +} + +/** + * 3.0.0: with sign-in through the church's Accounts, the demo people are moved there too (with the + * demo password), so they can sign in (src/accounts/move.ts moveNewPeople). A demo person whose + * email already has an account from an earlier demo is linked to it. The compiled code (dist/) on a + * server; the TypeScript through tsx in development. + */ +let accountsDb = null; +async function demoAccounts() { + const dist = path.join(__dirname, '..', 'dist', 'accounts', 'move.js'); + let move; + if (fs.existsSync(dist)) { + move = require(dist); + accountsDb = require(path.join(__dirname, '..', 'dist', 'config', 'db')); + } else { + require('tsx/cjs'); + move = require('../src/accounts/move.ts'); + } + const mode = await prisma.appSetting.findUnique({ where: { key: 'auth_mode' } }); + if (mode?.value !== 'accounts') return null; + try { + return await move.moveNewPeople(admin.accountId || null); + } catch (e) { + console.warn(`[warn] The demo people couldn't be moved to Accounts (${e.message}). Run the demo again once Accounts can be reached.`); + process.exitCode = 1; + return null; + } } main() .catch(err => { console.error(err); process.exitCode = 1; }) // The cashup code used by closePastEvents has its own client (src/config/db). - .finally(() => Promise.all([prisma.$disconnect(), require('../src/config/db').$disconnect()])); + .finally(() => Promise.all([prisma.$disconnect(), require('../src/config/db').$disconnect(), accountsDb?.$disconnect()])); diff --git a/apps/events/backend/src/accounts/autoConnect.ts b/apps/events/backend/src/accounts/autoConnect.ts new file mode 100644 index 0000000..0fcd55f --- /dev/null +++ b/apps/events/backend/src/accounts/autoConnect.ts @@ -0,0 +1,25 @@ +/** + * Cross Events 3.0 connects itself to the church's Accounts (docs/EVENTS-3.0-PLAN.md §9, Hub + * 2.5.0): after a heartbeat, when the Hub lists an Accounts for this church and this site isn't + * linked to one, it connects (as an admin pressing Connect under Linked products would). Once + * only: after it worked (`accounts_auto_connected`), an admin's Disconnect stays as it is. + */ +import { connectTo } from '../links/connect'; +import { linkedProducts } from '../links/store'; +import { accountsLink } from './client'; +import { getSetting, setSetting } from './mode'; + +export const AUTO_KEY = 'accounts_auto_connected'; + +export async function connectAccountsIfListed(now = new Date()): Promise<'connected' | 'skipped'> { + if (await getSetting(AUTO_KEY)) return 'skipped'; + if (await accountsLink()) { + await setSetting(AUTO_KEY, now.toISOString()); + return 'skipped'; + } + const listed = (await linkedProducts()).find((p) => p.product === 'accounts'); + if (!listed) return 'skipped'; + await connectTo(listed.installId, { id: null, role: 'system' }, null, now); + await setSetting(AUTO_KEY, now.toISOString()); + return 'connected'; +} diff --git a/apps/events/backend/src/accounts/move.ts b/apps/events/backend/src/accounts/move.ts index 1819e6b..54a4fbf 100644 --- a/apps/events/backend/src/accounts/move.ts +++ b/apps/events/backend/src/accounts/move.ts @@ -15,7 +15,6 @@ */ import crypto from 'node:crypto'; import { IMPORT_BATCH_MAX, phoneSchema, type ImportPerson, type ImportResult } from '@crosscode/contracts'; -import { importIdsHash } from '@crosscode/contracts/signing'; import { siteUrl } from '../feed/context'; import { accounts, accountsLink, AccountsUnavailable } from './client'; import { authMode, CLEARED_KEY, getSetting, MODE_KEY, MOVED_AT_KEY, REPORT_KEY, setSetting, UNDO_DAYS } from './mode'; @@ -214,6 +213,52 @@ export type MoveReport = { notices: 'events' | 'accounts'; }; +/** + * Ends a move: Accounts checks it holds every account this site now relies on (everyone linked, + * including a move run again after a failure, and people who signed up through Accounts since). + */ +async function finishMove(auth: Awaited>, actor: string | null) { + const linkedRows: { accountId: string }[] = await prisma.user.findMany({ where: { accountId: { not: null } }, select: { accountId: true } }); + const subs = [...new Set(linkedRows.map((x) => x.accountId))]; + const finish = await auth.request<{ matched: boolean; count: number; missing: string[] }>({ type: 'import.finish', actor, subs }); + if (!finish.matched) { + throw new MoveError(`Accounts holds ${finish.count} of the ${subs.length} people this site relies on (missing, for example, ${finish.missing.slice(0, 3).join(', ')}). Nothing was switched; run the move again.`, 'MISMATCH'); + } +} + +/** + * People added here after sign-in moved, without signing in through Accounts (demo data, an + * import): moved into Accounts the same way, so they can sign in. Only while sign-in goes through + * Accounts; returns how many were moved. + */ +export async function moveNewPeople(actor: string | null = null): Promise<{ moved: number; refused: { email: string; reason: string }[] }> { + if ((await authMode()) !== 'accounts') return { moved: 0, refused: [] }; + const people = await peopleToMove(); + if (!people.length) return { moved: 0, refused: [] }; + const auth = await accounts(); + await auth.request({ type: 'import.begin', actor, check: false, notices: [], church: { name: null, primaryColour: null } }); + try { + const byId = new Map(people.map((p) => [p.id, p])); + let moved = 0; + const refused: { email: string; reason: string }[] = []; + for (const batch of chunk(people, IMPORT_BATCH_MAX)) { + const built = await Promise.all(batch.map((u) => person(u, { admins: new Set(), seal: (v) => auth.seal(v), keepAccountsNotices: false }))); + const r = await auth.request<{ results: ImportResult[] }>({ type: 'import.batch', actor, check: false, people: built }, { timeoutMs: 120000 }); + for (const res of r.results) { + if (res.sub && res.outcome !== 'refused') { + await prisma.user.update({ where: { id: res.id }, data: { accountId: res.sub } }); + moved++; + } else refused.push({ email: byId.get(res.id)?.email ?? res.id, reason: res.reason ?? '' }); + } + } + await finishMove(auth, actor); + return { moved, refused }; + } catch (e) { + await auth.request({ type: 'import.abort', actor }).catch(() => {}); + throw e; + } +} + /** The move. Throws MoveError when it doesn't finish; nothing changes for anyone then. */ export async function move(opts: { actor: { id: string; role: string; name?: string }; adminIds: string[]; keepAccountsNotices?: boolean; ip?: string | null }): Promise { const auth = await connected(); @@ -245,11 +290,7 @@ export async function move(opts: { actor: { id: string; role: string; name?: str } results.push(...r.results); } - // Everyone this site has linked, including a move run again after a failure. - const linkedRows: { accountId: string }[] = await prisma.user.findMany({ where: { accountId: { not: null } }, select: { accountId: true } }); - const subs = [...new Set(linkedRows.map((x) => x.accountId))]; - const finish = await auth.request<{ matched: boolean; count: number }>({ type: 'import.finish', actor: opts.actor.id, count: subs.length, idsHash: importIdsHash(subs) }); - if (!finish.matched) throw new MoveError(`Accounts holds ${finish.count} people from this site, but ${subs.length} were sent. Nothing was switched; run the move again.`, 'MISMATCH'); + await finishMove(auth, opts.actor.id); const who = (id: string) => ({ name: byId.get(id)?.name ?? '', email: byId.get(id)?.email ?? '' }); const report: MoveReport = { diff --git a/apps/events/backend/src/accounts/signin.ts b/apps/events/backend/src/accounts/signin.ts index 262fc22..5ede6d0 100644 --- a/apps/events/backend/src/accounts/signin.ts +++ b/apps/events/backend/src/accounts/signin.ts @@ -92,6 +92,8 @@ export async function userForClaims(claims: IdentityClaims): Promise<{ user: Eve email, password: NO_PASSWORD(), role: 'user', + isActive: true, + tokenVersion: 0, newsEmail: claims.news_consent.email, newsWhatsApp: claims.news_consent.whatsapp, newsAskedAt: new Date(), diff --git a/apps/events/backend/src/hub/client.js b/apps/events/backend/src/hub/client.js index 328551f..a25268c 100644 --- a/apps/events/backend/src/hub/client.js +++ b/apps/events/backend/src/hub/client.js @@ -245,6 +245,8 @@ async function heartbeat() { try { await store.saveLinkedProducts(data.linkedProducts); if (typeof data.publicKeyStatus === 'string') await store.setPublicKeyStatus(data.publicKeyStatus); + // 3.0.0: connect to the church's Accounts once the Hub lists it (accounts/autoConnect.ts). + require('../accounts/autoConnect').connectAccountsIfListed().catch((e) => console.warn('[accounts] Could not connect to Accounts yet:', e?.message || e)); } catch (e) { console.warn('[hub] Could not save the linked products:', e?.message || e); } diff --git a/apps/events/backend/src/links/connect.ts b/apps/events/backend/src/links/connect.ts index ad600b0..bdb7145 100644 --- a/apps/events/backend/src/links/connect.ts +++ b/apps/events/backend/src/links/connect.ts @@ -61,7 +61,7 @@ async function firstUse(nonce: string, now: Date): Promise { } } -async function audit(action: string, link: { installId: string; product: string }, actor: { id: string; role: string } | null, ip: string | null, metadata: object = {}) { +async function audit(action: string, link: { installId: string; product: string }, actor: { id: string | null; role: string } | null, ip: string | null, metadata: object = {}) { await logAdminAction({ actorId: actor?.id ?? null, actorRole: actor?.role ?? 'linked_product', @@ -80,7 +80,7 @@ async function saveLink(sibling: hub.LinkedProduct, secret: string, connectedByI // ─── This site connects (an admin clicked Connect) ───────────────────────────── -export async function connectTo(installId: string, actor: { id: string; role: string }, ip: string | null, now = new Date()) { +export async function connectTo(installId: string, actor: { id: string | null; role: string }, ip: string | null, now = new Date()) { const sibling = await listedProduct(installId); if (!sibling) throw new LinkError('That product isn\'t in the list the Hub gave this site. Wait for the next Hub heartbeat (up to 15 minutes).', 'NOT_LINKED', 404); const me = await self(); diff --git a/apps/events/backend/tests/accounts-integration/accounts.int.mts b/apps/events/backend/tests/accounts-integration/accounts.int.mts index b32b24a..09a433b 100644 --- a/apps/events/backend/tests/accounts-integration/accounts.int.mts +++ b/apps/events/backend/tests/accounts-integration/accounts.int.mts @@ -231,6 +231,23 @@ describe('signing out, and Accounts\' calls', () => { assert.equal((await eventsDb.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 eventsDb.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 eventsDb.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(); @@ -239,3 +256,14 @@ describe('signing out, and Accounts\' calls', () => { 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'); + }); +}); diff --git a/apps/events/backend/tests/accountsAutoConnect.test.ts b/apps/events/backend/tests/accountsAutoConnect.test.ts new file mode 100644 index 0000000..94e4919 --- /dev/null +++ b/apps/events/backend/tests/accountsAutoConnect.test.ts @@ -0,0 +1,48 @@ +// 3.0.0 (docs/EVENTS-3.0-PLAN.md §9): connecting to the church's Accounts once the Hub lists it. +const mockSettings = new Map(); +const mockConnects: unknown[][] = []; +let mockListed: { installId: string; product: string }[] = []; +let mockLink: object | null = null; + +jest.mock('../src/links/connect', () => ({ connectTo: async (...args: unknown[]) => { mockConnects.push(args); mockLink = { installId: args[0] }; } })); +jest.mock('../src/links/store', () => ({ linkedProducts: async () => mockListed })); +jest.mock('../src/accounts/client', () => ({ accountsLink: async () => mockLink })); +jest.mock('../src/accounts/mode', () => ({ + getSetting: async (k: string) => mockSettings.get(k) ?? null, + setSetting: async (k: string, v: string | null) => { if (v === null) mockSettings.delete(k); else mockSettings.set(k, v); }, +})); + +import { AUTO_KEY, connectAccountsIfListed } from '../src/accounts/autoConnect'; + +const ACCOUNTS = '9a4c2f1e-7b3d-4e5a-8c6f-0d1e2f3a4b5c'; + +beforeEach(() => { + mockSettings.clear(); + mockConnects.length = 0; + mockListed = []; + mockLink = null; +}); + +test('connects to the Accounts the Hub lists, as the system, once', async () => { + mockListed = [{ installId: 'w1', product: 'website' }, { installId: ACCOUNTS, product: 'accounts' }]; + expect(await connectAccountsIfListed()).toBe('connected'); + expect(mockConnects).toEqual([[ACCOUNTS, { id: null, role: 'system' }, null, expect.any(Date)]]); + expect(mockSettings.has(AUTO_KEY)).toBe(true); + // An admin disconnects later: it isn't connected again. + mockLink = null; + expect(await connectAccountsIfListed()).toBe('skipped'); + expect(mockConnects).toHaveLength(1); +}); + +test('nothing listed yet: tries again at the next heartbeat', async () => { + expect(await connectAccountsIfListed()).toBe('skipped'); + expect(mockSettings.has(AUTO_KEY)).toBe(false); +}); + +test('already connected by an admin: just remembers it', async () => { + mockLink = { installId: ACCOUNTS }; + mockListed = [{ installId: ACCOUNTS, product: 'accounts' }]; + expect(await connectAccountsIfListed()).toBe('skipped'); + expect(mockConnects).toEqual([]); + expect(mockSettings.has(AUTO_KEY)).toBe(true); +}); diff --git a/apps/events/e2e/sign-in-accounts.spec.ts b/apps/events/e2e/sign-in-accounts.spec.ts new file mode 100644 index 0000000..5e8a811 --- /dev/null +++ b/apps/events/e2e/sign-in-accounts.spec.ts @@ -0,0 +1,129 @@ +import path from "path"; +import { test, expect, loginAs, API, type Page } from "./fixtures"; + +// Signing in through the church's Accounts (3.0.0, docs/EVENTS-3.0-PLAN.md §12, the ROADMAP-v3 §9 +// release checks): an admin checks and moves sign-in on Settings → Sign-in; then a member signs in +// at Accounts with their old Cross Events password and lands on the exact page they started from; a +// foreign return address ends on the home page; Events' own sign-in says it moved. Accounts runs in +// memory (e2e/support/accounts-server.mts). Afterwards sign-in goes back to Cross Events, so the +// other specs see the site as before. +/* eslint-disable @typescript-eslint/no-require-imports -- the backend's own modules, as prepare-db.js uses them */ +const backend = path.join(__dirname, "..", "backend"); +require(require.resolve("dotenv", { paths: [backend] })).config({ path: path.join(backend, ".env") }); +const { Client } = require(require.resolve("pg", { paths: [backend] })); +const { e2eDatabaseUrl } = require("./support/db-url"); +const signing = require(require.resolve("@crosscode/contracts/signing", { paths: [backend] })); +const { encrypt } = require(path.join(backend, "src", "utils", "encryption")); +/* eslint-enable @typescript-eslint/no-require-imports */ + +const ACCOUNTS_PAGES = "http://127.0.0.1:3221"; +const ACCOUNTS_API = "http://127.0.0.1:5221"; +const ACCOUNTS_ID = "7e2d1c0b-9a8f-4e6d-8c5b-4a3f2e1d0c9b"; +const EVENTS_ID = "5c4b3a29-1807-4f6e-9d5c-4b3a29180716"; +const SITE = "http://localhost:3100"; + +async function sql>(text: string, values: unknown[] = []): Promise { + const client = new Client({ connectionString: e2eDatabaseUrl() }); + await client.connect(); + try { + return (await client.query(text, values)).rows as T[]; + } finally { + await client.end(); + } +} +const setSetting = (key: string, value: string) => + sql(`INSERT INTO "AppSetting" (key, value, "updatedAt") VALUES ($1, $2, now()) ON CONFLICT (key) DO UPDATE SET value = $2, "updatedAt" = now()`, [key, value]); + +let installIdBefore: string | null = null; + +test.describe.serial("signing in through the church's Accounts", () => { + test.beforeAll(async () => { + // Connect, as Linked products would: the same secret on both sides. + const secret = signing.newLinkSecret(); + installIdBefore = (await sql<{ value: string }>(`SELECT value FROM "AppSetting" WHERE key = 'hub_install_id'`))[0]?.value ?? null; + const eventsId = installIdBefore ?? EVENTS_ID; + if (!installIdBefore) await setSetting("hub_install_id", eventsId); + const linked = await fetch(`${ACCOUNTS_API}/test/link`, { method: "POST", body: JSON.stringify({ installId: eventsId, url: SITE, secret }) }); + expect(linked.ok).toBe(true); + await sql(`DELETE FROM "ProductLink" WHERE product = 'accounts'`); + await sql( + `INSERT INTO "ProductLink" ("installId", product, url, "publicKey", secret, "connectedAt", "createdAt", "updatedAt") VALUES ($1, 'accounts', $2, 'x', $3, now(), now(), now())`, + [ACCOUNTS_ID, ACCOUNTS_PAGES, encrypt(secret)], + ); + }); + + test.afterAll(async () => { + // Back to Cross Events' own sign-in for the specs that follow. + await sql(`DELETE FROM "AppSetting" WHERE key IN ('auth_mode', 'auth_moved_at', 'auth_move_report', 'auth_move_running', 'accounts_auto_connected')`); + await sql(`UPDATE "User" SET "accountId" = NULL`); + await sql(`DELETE FROM "ProductLink" WHERE product = 'accounts'`); + if (!installIdBefore) await sql(`DELETE FROM "AppSetting" WHERE key = 'hub_install_id'`); + }); + + test("an admin checks the move, then moves sign-in", async ({ page }) => { + page.on("dialog", (d) => d.accept()); + await loginAs(page, "admin"); + await page.goto("/dashboard/admin/settings?tab=signin"); + await expect(page.getByRole("heading", { name: "Sign-in", exact: true })).toBeVisible(); + await page.getByRole("button", { name: "Check the move" }).click(); + await expect(page.getByText(/people move with their current password/)).toBeVisible(); + // Ada stays an Events admin only (an Accounts admin would need two-step sign-in to sign in). + const admins = page.locator("fieldset").filter({ hasText: "Accounts admins" }); + for (const box of await admins.getByRole("checkbox").all()) await box.uncheck(); + await page.getByRole("button", { name: "Move sign-in to Accounts" }).click(); + await expect(page.getByText("Sign-in now goes through your church's Accounts.")).toBeVisible(); + await expect(page.getByText("Through Accounts")).toBeVisible(); + await expect(page.getByRole("button", { name: "Undo the move" })).toBeVisible(); + }); + + async function signInAtAccounts(page: Page, email: string, password: string) { + await expect(page).toHaveURL(new RegExp(`^${ACCOUNTS_PAGES}/signin`)); + await expect(page.getByRole("heading", { name: "Sign in to E2E Church" })).toBeVisible(); + await page.getByLabel("Email address").fill(email); + await page.getByLabel("Password").fill(password); + await page.getByRole("button", { name: "Sign in" }).click(); + // A privacy notice published by an earlier spec, or the news question: answer and carry on. + const accept = page.getByRole("button", { name: "I've read it" }); + const cont = page.getByRole("button", { name: "Continue" }); + for (let i = 0; i < 10 && new URL(page.url()).origin !== SITE; i++) { + if (await accept.isVisible()) await accept.click(); + else if (await cont.isVisible()) await cont.click(); + else await page.waitForTimeout(500); + } + await page.waitForURL((u) => u.origin === SITE); + } + + test("a member signs in with their Cross Events password and lands on the page they started on", async ({ page }) => { + await page.goto("/login?redirect=/dashboard/user/profile"); + await signInAtAccounts(page, "user@e2e.test", "E2e-password-123"); + await expect(page).toHaveURL(`${SITE}/dashboard/user/profile`); + await expect(page.getByRole("heading", { name: "On your church account" })).toBeVisible(); + await expect(page.locator("#profile-email-address")).toHaveValue("user@e2e.test"); + await expect(page.locator("#profile-email-address")).toHaveAttribute("readonly", ""); + }); + + test("a foreign return address ends on the home page", async ({ page }) => { + await page.goto(`/login?redirect=${encodeURIComponent("//evil.example/steal")}`); + await signInAtAccounts(page, "staff@e2e.test", "E2e-password-123"); + await expect(page).toHaveURL(new RegExp(`^${SITE}/dashboard`)); + }); + + test("Events' own sign-in says it moved; old reset links say so too", async ({ page, request }) => { + const res = await request.post(`${API}/api/v2/auth/login`, { data: { identifier: "user@e2e.test", password: "E2e-password-123" } }); + expect(res.status()).toBe(409); + expect((await res.json()).error.code).toBe("SIGN_IN_MOVED"); + await page.goto("/reset-password?token=old"); + await expect(page.getByRole("heading", { name: "Sign-in has moved" })).toBeVisible(); + }); + + test("signing out ends the session here and at Accounts", async ({ page }) => { + await page.goto("/login?redirect=/dashboard/user"); + await signInAtAccounts(page, "user@e2e.test", "E2e-password-123"); + await expect(page).toHaveURL(`${SITE}/dashboard/user`); + const token = await page.evaluate(() => localStorage.getItem("hope_events_token")); + const out = await page.request.post(`${API}/api/auth/signout`, { headers: { authorization: `Bearer ${token}` }, data: {} }); + expect((await out.json()).data.url).toMatch(new RegExp(`^${ACCOUNTS_PAGES}/api/oidc/session/end`)); + const me = await page.request.get(`${API}/api/v2/me`, { headers: { authorization: `Bearer ${token}` } }); + expect(me.status()).toBe(401); + }); +}); diff --git a/apps/events/e2e/support/accounts-server.mts b/apps/events/e2e/support/accounts-server.mts new file mode 100644 index 0000000..211ebf8 --- /dev/null +++ b/apps/events/e2e/support/accounts-server.mts @@ -0,0 +1,41 @@ +/** + * The church's Accounts for Cross Events' end-to-end tests (3.0.0, playwright.config.ts): the real + * Accounts backend on 127.0.0.1:5221 with its in-memory database (no Postgres of its own), behind + * its pages on 127.0.0.1:3221 (`next dev` in apps/accounts/frontend). Its own address (127.0.0.1) + * differs from the Events site's (localhost), so their cookies stay apart as on two domains. + * + * Test helper: POST /test/link { installId, url, secret } links Events, as Connect would. + */ +import http from 'node:http'; +import { ed25519PublicToPem, generateEd25519 } from '@crosscode/contracts/signing'; +import { createApp } from '../../../accounts/backend/src/app.ts'; +import { createCtx } from '../../../accounts/backend/src/context.ts'; +import { loadConfig } from '../../../accounts/backend/src/lib/config.ts'; +import { MemoryMessenger } from '../../../accounts/backend/src/lib/messages.ts'; +import { createProvider } from '../../../accounts/backend/src/oidc/provider.ts'; +import { memoryDb } from '../../../accounts/backend/tests/support/memoryDb.ts'; + +const WEB = 'http://127.0.0.1:3221'; +const db = memoryDb(); +const ctx = createCtx(loadConfig({ ACCOUNTS_URL: WEB, NODE_ENV: 'test', JOBS_ENABLED: 'false', LINKS_ALLOW_PRIVATE: 'true', HUB_URL: 'http://127.0.0.1:1', TRUST_PROXY: 'true' }), db as never, { messenger: new MemoryMessenger() }); +await ctx.settings.setMany({ + hub_install_id: '7e2d1c0b-9a8f-4e6d-8c5b-4a3f2e1d0c9b', + church_profile: JSON.stringify({ name: 'E2E Church', shortName: 'E2E' }), +}); +const provider = await createProvider(ctx); +const app = createApp(ctx, provider); + +http.createServer((req, res) => { + if (req.method === 'POST' && req.url === '/test/link') { + let body = ''; + req.on('data', (c) => { body += c; }); + req.on('end', async () => { + const { installId, url, secret } = JSON.parse(body) as { installId: string; url: string; secret: string }; + const data = { product: 'events', url, publicKey: ed25519PublicToPem(generateEd25519().publicKey), secret: ctx.secrets.encrypt(secret), connectedAt: new Date() }; + await db.productLink.upsert({ where: { installId }, create: { installId, ...data }, update: data }); + res.writeHead(200, { 'content-type': 'application/json' }).end(JSON.stringify({ ok: true })); + }); + return; + } + app(req, res); +}).listen(5221, '127.0.0.1', () => console.log('[e2e] Accounts on 5221')); diff --git a/apps/events/frontend/next.config.ts b/apps/events/frontend/next.config.ts index e437678..1178671 100644 --- a/apps/events/frontend/next.config.ts +++ b/apps/events/frontend/next.config.ts @@ -12,6 +12,11 @@ const nextConfig: NextConfig = { compiler: { removeConsole: process.env.NODE_ENV === 'production', }, + // The end-to-end tests only (3.0.0): the site and its API on one address, as nginx does on a + // server, so Accounts' sign-in comes back to /api/auth/callback. Unset everywhere else. + ...(process.env.E2E_API_PROXY + ? { async rewrites() { return [{ source: '/api/:path*', destination: `${process.env.E2E_API_PROXY}/api/:path*` }]; } } + : {}), }; // A no-op wrap when SENTRY_DSN isn't configured for this deployment — safe in diff --git a/apps/events/playwright.config.ts b/apps/events/playwright.config.ts index c23a423..5c33486 100644 --- a/apps/events/playwright.config.ts +++ b/apps/events/playwright.config.ts @@ -67,9 +67,30 @@ export default defineConfig({ env: { NEXT_PUBLIC_API_URL: `http://localhost:${API_PORT}`, API_URL: `http://localhost:${API_PORT}`, + // 3.0.0: the site and its API on one address (as nginx does), for Accounts' callback. + E2E_API_PROXY: `http://localhost:${API_PORT}`, NEXT_DIST_DIR: ci ? ".next" : ".next-e2e", NEXT_TELEMETRY_DISABLED: "1", }, }, + // 3.0.0 (sign-in-accounts.spec.ts): the church's Accounts, in memory, and its pages. + { + command: "npx tsx e2e/support/accounts-server.mts", + url: "http://127.0.0.1:5221/api/health", + timeout: 120_000, + reuseExistingServer: !ci, + stdout: "ignore", + stderr: "pipe", + }, + { + command: "npx next dev -p 3221 -H 127.0.0.1", + cwd: "../accounts/frontend", + url: "http://127.0.0.1:3221/privacy", + timeout: 300_000, + reuseExistingServer: !ci, + stdout: "ignore", + stderr: "pipe", + env: { ACCOUNTS_API_URL: "http://127.0.0.1:5221", NEXT_TELEMETRY_DISABLED: "1" }, + }, ], }); diff --git a/docs/EVENTS-3.0-PLAN.md b/docs/EVENTS-3.0-PLAN.md index 5a1ee83..39b2e54 100644 --- a/docs/EVENTS-3.0-PLAN.md +++ b/docs/EVENTS-3.0-PLAN.md @@ -426,17 +426,28 @@ only for a connected product: `crosscode.identity/1` (Accounts → product) is unchanged. The `people.*` names: `ensure`, `update`, `resetTwoFactor`, `unlock`, `setActive`, `newsOff`. A request id seen before gets its first answer. -2. **`import.finish` hashes the subs Accounts gave back**, not the Events ids, so people linked to an - account they already had count too. Accounts compares it with the people it holds as moved from - that product (`ProductPerson`). +2. **`import.finish` lists every sub the product relies on** (all its linked users), and Accounts + checks each is an account it holds, not deleted, and known to that product (`ProductPerson`: + moved in, added, or signed in through it). A count and hash of the moved people (the first + version) failed a second move after Undo once anyone had joined through Accounts in between. 3. **Notice versions are shifted by one:** Accounts' built-in notice is version 1, Events' is 0, so Events' version *n* is Accounts' *n + 1* (acceptances too). "Use Cross Events' notice" when Accounts already has its own isn't offered yet: the admin keeps Accounts' notice, or removes it in Accounts first. 4. **The setup wizard still makes a local first admin** (§9 is not built): a new install starts in `local`, and its admin moves sign-in once Accounts is connected (a one-person move takes seconds). - That avoids a setup that depends on Accounts being connected first. Signing in through Accounts - from the wizard can come with Hub 2.5.0's automatic Connect. + That avoids a setup that depends on Accounts being connected first. +10. **Connect happens by itself** (§9): after a heartbeat that lists the church's Accounts, Events + connects to it if it isn't linked to one (`accounts/autoConnect.ts`), once: an admin's later + Disconnect stays. Hub 2.5.0 installs Accounts first for a new Events 3.x install (a batch: + Accounts, then Events once Accounts succeeded) on `accounts.` or the + form's Accounts domain, and refuses a church whose Accounts is older than the release needs. +11. **Demo data** (`set-demo.js`, `crosscode demo`): with sign-in through Accounts, the demo people + are moved there after seeding (`moveNewPeople`), with the demo password; a demo email that has + an account from an earlier demo is linked to it. +12. **e2e:** `e2e/sign-in-accounts.spec.ts` runs Accounts in memory (`e2e/support/accounts-server.mts`) + with its pages on 127.0.0.1:3221, and the Events site with its API on one address + (`E2E_API_PROXY`, a rewrite only the e2e frontend sets). Not run yet (needs the e2e Postgres). 5. **People who never activated** (`isActive` false and never signed in) move as active accounts without a password: Accounts' "Forgot your password?" sets one. Everyone else who is deactivated moves as deactivated. @@ -450,7 +461,7 @@ only for a connected product: backend compiles to CommonJS and deploys still allow Node 20. 9. **Tests:** `npm run test:accounts` runs Events' own code (move, sign-in, sign-out, back-channel logout, `user.updated`, Undo) against the whole Accounts app on real ports, each with an in-memory - database (11 tests). `user.export` and `user.deleted` are Jest tests (`tests/accountsCalls.test.ts`). + database (14 tests, including demo people and moving again after Undo). `user.export` and `user.deleted` are Jest tests (`tests/accountsCalls.test.ts`). ## Decisions diff --git a/packages/contracts/samples/import-finish.json b/packages/contracts/samples/import-finish.json index d3bda7d..4552496 100644 --- a/packages/contracts/samples/import-finish.json +++ b/packages/contracts/samples/import-finish.json @@ -3,6 +3,7 @@ "actor": "8d2e4f6a-1b3c-4d5e-8f7a-9b0c1d2e3f4a", "requestId": "2d8a3b4c-5e6f-4a7b-8c1d-2e3f4a5b6c7d", "type": "import.finish", - "count": 1, - "idsHash": "9f9f9f9f9f9f9f9f9f9f9f9f9f9f9f9f9f9f9f9f9f9f9f9f9f9f9f9f9f9f9f9f" + "subs": [ + "5f0c7d2a-3b1e-4c8f-9a6d-2e4b1c7f8a90" + ] } diff --git a/packages/contracts/schemas/identity-request.json b/packages/contracts/schemas/identity-request.json index e434744..3de1d98 100644 --- a/packages/contracts/schemas/identity-request.json +++ b/packages/contracts/schemas/identity-request.json @@ -421,14 +421,14 @@ "type": "string", "const": "import.finish" }, - "count": { - "type": "integer", - "minimum": 0, - "maximum": 9007199254740991 - }, - "idsHash": { - "type": "string", - "pattern": "^[0-9a-f]{64}$" + "subs": { + "maxItems": 50000, + "type": "array", + "items": { + "type": "string", + "format": "uuid", + "pattern": "^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[1-8][0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12}|00000000-0000-0000-0000-000000000000|ffffffff-ffff-ffff-ffff-ffffffffffff)$" + } } }, "required": [ @@ -436,8 +436,7 @@ "requestId", "actor", "type", - "count", - "idsHash" + "subs" ] }, { diff --git a/packages/contracts/schemas/import-finish-reply.json b/packages/contracts/schemas/import-finish-reply.json index 01a1d31..f028304 100644 --- a/packages/contracts/schemas/import-finish-reply.json +++ b/packages/contracts/schemas/import-finish-reply.json @@ -14,11 +14,21 @@ "type": "integer", "minimum": 0, "maximum": 9007199254740991 + }, + "missing": { + "maxItems": 100, + "type": "array", + "items": { + "type": "string", + "format": "uuid", + "pattern": "^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[1-8][0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12}|00000000-0000-0000-0000-000000000000|ffffffff-ffff-ffff-ffff-ffffffffffff)$" + } } }, "required": [ "schema", "matched", - "count" + "count", + "missing" ] } diff --git a/packages/contracts/src/identity-request.ts b/packages/contracts/src/identity-request.ts index 60e3b0b..bfa0e80 100644 --- a/packages/contracts/src/identity-request.ts +++ b/packages/contracts/src/identity-request.ts @@ -97,14 +97,18 @@ export const importBatchSchema = base.extend({ people: z.array(importPersonSchema).min(1).max(IMPORT_BATCH_MAX), }); +/** At most this many subs in an `import.finish`. */ +export const IMPORT_FINISH_MAX = 50_000; + /** - * Ends a move: Accounts compares the count and the hash (`importIdsHash`) of the **subs** it gave - * back (`created`, `updated` and `linked`) with the people it holds as moved from this product. + * Ends a move: every account the product now relies on (each of its users' `sub`). Accounts checks + * each is an account it holds, not deleted, and known to this product (moved in, added, or signed + * in through it), and only then ends the move. So people who signed up through Accounts since an + * earlier move, or a move run again after a failure, check out too. */ export const importFinishSchema = base.extend({ type: z.literal("import.finish"), - count: z.int().nonnegative(), - idsHash: z.string().regex(/^[0-9a-f]{64}$/), + subs: z.array(idSchema).max(IMPORT_FINISH_MAX), }); export const importAbortSchema = base.extend({ type: z.literal("import.abort") }); @@ -172,8 +176,12 @@ export const importBatchReplySchema = z.object({ export const importFinishReplySchema = z.object({ schema: z.literal(IDENTITY_REQUEST_SCHEMA), + /** Every sub checked out; the move has ended. */ matched: z.boolean(), + /** How many of the subs Accounts holds for this product. */ count: z.int().nonnegative(), + /** Some of the subs that didn't check out (at most 100). */ + missing: z.array(idSchema).max(100), }); export const peopleEnsureReplySchema = z.object({ @@ -188,11 +196,3 @@ export const okReplySchema = z.object({ schema: z.literal(IDENTITY_REQUEST_SCHEM export const IDENTITY_REQUEST_ERROR_CODES = [ "NOT_LINKED", "BAD_SIGNATURE", "STALE_REQUEST", "INVALID_REQUEST", "NOT_MOVING", "WRONG_PRODUCT", "UNKNOWN_PERSON", "EMAIL_TAKEN", "NOT_ALLOWED", ] as const; - -/** - * The hash `import.finish` carries: SHA-256 (hex) of the sorted ids joined by "\n". Pure JS so it - * works in the browser build too; products compute it over the ids they sent (not `refused`). - */ -export function importIdsInput(ids: Iterable): string { - return [...ids].sort().join("\n"); -} diff --git a/packages/contracts/src/signing.ts b/packages/contracts/src/signing.ts index eb97069..c4bf638 100644 --- a/packages/contracts/src/signing.ts +++ b/packages/contracts/src/signing.ts @@ -1,7 +1,6 @@ import { createCipheriv, createDecipheriv, - createHash, createHmac, createPrivateKey, createPublicKey, @@ -16,7 +15,6 @@ import { } from "node:crypto"; import { AGENT_HEADERS, type Sealed } from "./agent"; import { canonicalJson } from "./canonical"; -import { importIdsInput } from "./identity-request"; export { canonicalJson } from "./canonical"; @@ -324,8 +322,3 @@ export function openLinkValue(linkSecret: string, sealed: string): string { decipher.setAuthTag(raw.subarray(raw.length - 16)); return Buffer.concat([decipher.update(raw.subarray(12, raw.length - 16)), decipher.final()]).toString("utf8"); } - -/** The `idsHash` of `import.finish`: SHA-256 (hex) of the sorted ids joined by "\n". */ -export function importIdsHash(ids: Iterable): string { - return createHash("sha256").update(importIdsInput(ids)).digest("hex"); -} diff --git a/packages/contracts/tests/identity-request.test.ts b/packages/contracts/tests/identity-request.test.ts index 3012979..80d5c36 100644 --- a/packages/contracts/tests/identity-request.test.ts +++ b/packages/contracts/tests/identity-request.test.ts @@ -1,5 +1,5 @@ import { identityRequestSchema, importPersonSchema, sealedValueSchema } from "../src"; -import { importIdsHash, newLinkSecret, openLinkValue, sealLinkValue } from "../src/signing"; +import { newLinkSecret, openLinkValue, sealLinkValue } from "../src/signing"; import { sample } from "./helpers"; describe("crosscode.identity-request/1", () => { @@ -15,11 +15,10 @@ describe("crosscode.identity-request/1", () => { expect(() => openLinkValue(secret, tampered)).toThrow(); }); - test("the ids hash doesn't depend on order", () => { - const a = ["b8f1c2d3-0000-4000-8000-000000000002", "a7e0b1c2-0000-4000-8000-000000000001"]; - expect(importIdsHash(a)).toBe(importIdsHash([...a].reverse())); - expect(importIdsHash(a)).toMatch(/^[0-9a-f]{64}$/); - expect(importIdsHash(a)).not.toBe(importIdsHash(a.slice(0, 1))); + test("import.finish lists the subs (uuids)", () => { + const finish = sample<{ subs: string[] }>("import-finish.json"); + expect(identityRequestSchema.safeParse(finish).success).toBe(true); + expect(identityRequestSchema.safeParse({ ...finish, subs: ["not-a-uuid"] }).success).toBe(false); }); test("an unsealed password hash is refused", () => {