diff --git a/apps/accounts/CHANGELOG.md b/apps/accounts/CHANGELOG.md index 9ed245c..07ce988 100644 --- a/apps/accounts/CHANGELOG.md +++ b/apps/accounts/CHANGELOG.md @@ -1,5 +1,34 @@ # Changelog — Accounts +## [1.1.0] - unreleased + +For Cross Events 3.0 (docs/EVENTS-3.0-PLAN.md §8), with contracts 1.8.0. + +### Added + +- **`POST /api/accounts/v1/requests`** (`crosscode.identity-request/1`), signed with the link's + secret: what a linked product asks of Accounts. A request id seen before gets its first answer. +- **Moving a product's users in** (`import.begin` / `batch` / `finish` / `abort`, Cross Events + only): each person keeps their Events id as their `sub`, their bcrypt or Argon2id password hash, + 2FA method and authenticator secret (sealed with the link's secret on the way, encrypted with + 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 + 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. +- **`people.*`**: `ensure` (find or make an account; a new one gets a "choose your password" email + whose link ends on the product), `update`, `resetTwoFactor`, `unlock`, `setActive`, `newsOff`. + Only for people the product knows (moved in, added, or signed in through it), never an Accounts + admin's 2FA or status, and audited with the product and the product admin's `sub`. +- **`screen=signup`** on an authorization request opens the sign-in page on "Create an account" + (`startSignIn(…, { signUp: true })` in `@crosscode/auth-client`). + +### Changed + +- Setting a password from an emailed link also confirms the email address. + ## [1.0.1] - 2026-11-19 ### Fixed diff --git a/apps/accounts/WHATS-NEW.md b/apps/accounts/WHATS-NEW.md index 43d114c..1cb1c13 100644 --- a/apps/accounts/WHATS-NEW.md +++ b/apps/accounts/WHATS-NEW.md @@ -3,6 +3,14 @@ What each version changes for the church, in plain language (read by the Hub like Cross Events' WHATS-NEW.md; a section shows once its version is tagged). +## 1.1.0 + +- **Ready for Cross Events 3.0:** Cross Events can move its people into your church's accounts, + with their passwords and authenticator apps, so nobody has to reset anything. People who use + two-step sign-in get new recovery codes the first time they sign in. +- Cross Events admins can add people, fix their details, unlock them and reset two-step sign-in + without leaving Cross Events. + ## 1.0.1 - **Fix:** sign-in limits and the activity log now see each visitor's own address on servers diff --git a/apps/accounts/backend/package.json b/apps/accounts/backend/package.json index e357bf9..7a40031 100644 --- a/apps/accounts/backend/package.json +++ b/apps/accounts/backend/package.json @@ -1,6 +1,6 @@ { "name": "@crosscode/accounts-backend", - "version": "1.0.1", + "version": "1.1.0", "description": "Cross Code Accounts: the church's sign-in (OpenID Connect provider), account pages API and admin API", "private": true, "type": "module", diff --git a/apps/accounts/backend/prisma/migrations/20261119120000_accounts_1_1/migration.sql b/apps/accounts/backend/prisma/migrations/20261119120000_accounts_1_1/migration.sql new file mode 100644 index 0000000..057dd15 --- /dev/null +++ b/apps/accounts/backend/prisma/migrations/20261119120000_accounts_1_1/migration.sql @@ -0,0 +1,50 @@ +-- Accounts 1.1.0 (docs/EVENTS-3.0-PLAN.md §8): moving a product's users in, and its people.* requests. + +-- AlterTable +ALTER TABLE "Account" ADD COLUMN "recoveryCodesNeeded" BOOLEAN NOT NULL DEFAULT false; + +-- AlterTable +ALTER TABLE "EmailToken" ADD COLUMN "returnUrl" TEXT; + +-- AlterTable +ALTER TABLE "ProductLink" ADD COLUMN "importStartedAt" TIMESTAMP(3); + +-- CreateTable +CREATE TABLE "ProductPerson" ( + "id" TEXT NOT NULL, + "linkId" TEXT NOT NULL, + "accountId" TEXT NOT NULL, + "via" TEXT NOT NULL, + "createdAt" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP, + + CONSTRAINT "ProductPerson_pkey" PRIMARY KEY ("id") +); + +-- CreateTable +CREATE TABLE "ProductRequest" ( + "requestId" TEXT NOT NULL, + "linkId" TEXT NOT NULL, + "type" TEXT NOT NULL, + "reply" JSONB NOT NULL, + "createdAt" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP, + + CONSTRAINT "ProductRequest_pkey" PRIMARY KEY ("requestId") +); + +-- CreateIndex +CREATE UNIQUE INDEX "ProductPerson_linkId_accountId_key" ON "ProductPerson"("linkId", "accountId"); + +-- CreateIndex +CREATE INDEX "ProductPerson_accountId_idx" ON "ProductPerson"("accountId"); + +-- CreateIndex +CREATE INDEX "ProductRequest_createdAt_idx" ON "ProductRequest"("createdAt"); + +-- AddForeignKey +ALTER TABLE "ProductPerson" ADD CONSTRAINT "ProductPerson_linkId_fkey" FOREIGN KEY ("linkId") REFERENCES "ProductLink"("installId") ON DELETE CASCADE ON UPDATE CASCADE; + +-- AddForeignKey +ALTER TABLE "ProductPerson" ADD CONSTRAINT "ProductPerson_accountId_fkey" FOREIGN KEY ("accountId") REFERENCES "Account"("id") ON DELETE CASCADE ON UPDATE CASCADE; + +-- AddForeignKey +ALTER TABLE "ProductRequest" ADD CONSTRAINT "ProductRequest_linkId_fkey" FOREIGN KEY ("linkId") REFERENCES "ProductLink"("installId") ON DELETE CASCADE ON UPDATE CASCADE; diff --git a/apps/accounts/backend/prisma/schema.prisma b/apps/accounts/backend/prisma/schema.prisma index 984e2dc..b2f4f0a 100644 --- a/apps/accounts/backend/prisma/schema.prisma +++ b/apps/accounts/backend/prisma/schema.prisma @@ -55,6 +55,9 @@ model Account { lastSignInAt DateTime? deactivatedAt DateTime? anonymisedAt DateTime? + // 1.1.0: moved in from a product with 2FA but without recovery codes (Events keys its codes with + // its own secret, so they can't move): new ones are shown after the next sign-in's second step. + recoveryCodesNeeded Boolean @default(false) createdAt DateTime @default(now()) updatedAt DateTime @updatedAt @@ -65,6 +68,7 @@ model Account { consentChanges ConsentChange[] exports DataExport[] deletionRequests DeletionRequest[] + products ProductPerson[] @@index([status]) } @@ -107,6 +111,8 @@ model EmailToken { tokenHash String @unique // The sign-in the link belongs to, so it carries on to the product afterwards (§5). interactionUid String? + // 1.1.0: a "set your password" link a product asked for (people.ensure) ends on that product. + returnUrl String? expiresAt DateTime usedAt DateTime? createdAt DateTime @default(now()) @@ -195,16 +201,47 @@ model AppSetting { // A linked product (Connect, crosscode.link/1). Each is also an OIDC client (§4): client_id is // installId, the client secret is derived from `secret`, the addresses are fixed paths on `url`. model ProductLink { - installId String @id - product String // events | website | app - url String - publicKey String - secret String // encrypted - connectedAt DateTime - connectedById String? - createdAt DateTime @default(now()) - updatedAt DateTime @updatedAt - deliveries Delivery[] + installId String @id + product String // events | website | app + url String + publicKey String + secret String // encrypted + connectedAt DateTime + connectedById String? + // 1.1.0: a move of this product's users into Accounts is under way (import.begin … finish). + importStartedAt DateTime? + createdAt DateTime @default(now()) + updatedAt DateTime @updatedAt + deliveries Delivery[] + people ProductPerson[] + requests ProductRequest[] +} + +// 1.1.0: the people a linked product knows (imported by it, added by it, or signed in through it). +// A product's people.* requests only reach these. +model ProductPerson { + id String @id @default(uuid()) + linkId String + link ProductLink @relation(fields: [linkId], references: [installId], onDelete: Cascade) + accountId String + account Account @relation(fields: [accountId], references: [id], onDelete: Cascade) + via String // import | ensure | sign_in + createdAt DateTime @default(now()) + + @@unique([linkId, accountId]) + @@index([accountId]) +} + +// 1.1.0: crosscode.identity-request/1 requests already handled, so a retry gets the same answer. +model ProductRequest { + requestId String @id + linkId String + link ProductLink @relation(fields: [linkId], references: [installId], onDelete: Cascade) + type String + reply Json + createdAt DateTime @default(now()) + + @@index([createdAt]) } model LinkNonce { diff --git a/apps/accounts/backend/src/app.ts b/apps/accounts/backend/src/app.ts index 0442389..a4a268c 100644 --- a/apps/accounts/backend/src/app.ts +++ b/apps/accounts/backend/src/app.ts @@ -6,6 +6,7 @@ * /api/oidc/… the OpenID Connect provider (discovery, auth, token, …) * /api/self/… the account page's own sign-in * /api/church/v1, /api/links/v1/… for the church's other products + * /api/accounts/v1/requests what a linked product asks (import, people.*; contracts 1.8.0) * /api/v2/… the pages' API (sign-in steps, account, admin, setup) */ import express from 'express'; @@ -17,6 +18,7 @@ import { interactionRouter, selfRouter } from './interaction/routes.js'; import { meRouter } from './me/routes.js'; import { LOGOUT_JS } from './oidc/pages.js'; import { publicRouter } from './public/routes.js'; +import { requestsRouter } from './links/requests.js'; import { setupRouter } from './setup/routes.js'; import { health } from './hub/client.js'; import { appVersion } from './lib/version.js'; @@ -46,6 +48,7 @@ export function createApp(ctx: Ctx, provider: Provider) { // The provider parses its own bodies: mounted before express.json. app.use('/api/oidc', provider.callback()); app.use('/api/self', selfRouter(ctx)); + app.use('/api', requestsRouter(ctx, provider)); app.use('/api', publicRouter(ctx)); const v2 = express.Router(); diff --git a/apps/accounts/backend/src/interaction/flow.ts b/apps/accounts/backend/src/interaction/flow.ts index 9a38ec7..1eba886 100644 --- a/apps/accounts/backend/src/interaction/flow.ts +++ b/apps/accounts/backend/src/interaction/flow.ts @@ -18,7 +18,7 @@ import type { Account, PendingSignIn } from '../generated/prisma/client.js'; import { codeMatches, emailProblem, isLocked, maskedTarget, normaliseEmail, normalisePhone, sendCode, setNewsConsent, signInFailed, signInSucceeded, CODE_MINUTES, } from '../accounts/service.js'; -import { accessAfterTwoFactor, confirmTwoFactorSetup, startTwoFactorSetup, useRecoveryCode, verifyTotp } from '../accounts/twoFactor.js'; +import { accessAfterTwoFactor, confirmTwoFactorSetup, replaceRecoveryCodes, startTwoFactorSetup, useRecoveryCode, verifyTotp } from '../accounts/twoFactor.js'; import { loginEvent } from '../lib/audit.js'; import { dummyHash, hashPassword, needsRehash, passwordProblem, verifyPassword } from '../lib/passwords.js'; import { accept as acceptNotice, currentNotice } from '../privacy/notice.js'; @@ -94,6 +94,8 @@ export async function describe(ctx: Ctx, details: Details, pending: PendingSignI signupEnabled: await ctx.settings.bool('signup_enabled', true), mfaRequested: mfaRequested(details), loginHint: typeof details.params.login_hint === 'string' ? details.params.login_hint : null, + // 1.1.0: a product's "Create an account" link opens on sign-up (`screen=signup`). + screen: details.params.screen === 'signup' ? 'signup' : 'signin', }; if (stage === 'password' || stage === 'done') return base; const a = await account(ctx, pending); @@ -209,7 +211,16 @@ export async function twoFactor(ctx: Ctx, pending: PendingSignIn, input: { code? } else { await checkCode(ctx, pending, input.code); } - return save(ctx, pending, { amr: accessAfterTwoFactor(pending.amr), codeHash: null, codeSentAt: null, attempts: 0 }); + const next = await save(ctx, pending, { amr: accessAfterTwoFactor(pending.amr), codeHash: null, codeSentAt: null, attempts: 0 }); + // Moved in from a product without its recovery codes (EVENTS-3.0-PLAN decision 2): new ones now, + // shown once on the next page. + if (a.recoveryCodesNeeded) { + const recoveryCodes = await replaceRecoveryCodes(ctx, a.id); + await ctx.db.account.update({ where: { id: a.id }, data: { recoveryCodesNeeded: false } }); + await loginEvent(ctx, a.id, 'recovery_codes_replaced', req, { detail: { by: 'move' } }); + return { pending: next, recoveryCodes }; + } + return { pending: next, recoveryCodes: null as string[] | null }; } export async function setupStart(ctx: Ctx, pending: PendingSignIn, method: unknown) { diff --git a/apps/accounts/backend/src/interaction/routes.ts b/apps/accounts/backend/src/interaction/routes.ts index 20ffe5c..8e1beac 100644 --- a/apps/accounts/backend/src/interaction/routes.ts +++ b/apps/accounts/backend/src/interaction/routes.ts @@ -15,6 +15,7 @@ import { normaliseEmail } from '../accounts/service.js'; import { SELF_CALLBACK, SELF_CLIENT_ID } from '../oidc/clients.js'; import { issuerOf } from '../oidc/provider.js'; import * as flow from './flow.js'; +import { signedInThrough } from '../links/requests.js'; const RESET_MINUTES = 60; @@ -39,7 +40,9 @@ export function interactionRouter(ctx: Ctx, provider: Provider) { const state = await flow.describe(ctx, details, pending); if (state.stage !== 'done') return { ...state, ...extra }; const redirectTo = await provider.interactionResult(req, res, flow.loginResult(pending), { mergeWithLastSubmission: false }); - await loginEvent(ctx, pending.accountId, 'sign_in', req, { clientId: String(details.params.client_id ?? '') || null, detail: { amr: pending.amr } }); + const clientId = String(details.params.client_id ?? '') || null; + await loginEvent(ctx, pending.accountId, 'sign_in', req, { clientId, detail: { amr: pending.amr } }); + await signedInThrough(ctx, clientId, pending.accountId); await ctx.db.pendingSignIn.deleteMany({ where: { uid: pending.uid } }); return { stage: 'done', redirectTo, ...extra }; } @@ -61,7 +64,10 @@ export function interactionRouter(ctx: Ctx, provider: Provider) { r.post('/interaction/:uid/password', limit(20), step(async (req, _res, p) => { await flow.submitPassword(ctx, p, req.body ?? {}, req); })); r.post('/interaction/:uid/signup', limit(10, 60), step(async (req, _res, p) => { await flow.signUp(ctx, p, req.body ?? {}); })); r.post('/interaction/:uid/verify-email', limit(20), step(async (req, _res, p) => { await flow.verifyEmail(ctx, p, req.body?.code); })); - r.post('/interaction/:uid/two-factor', limit(20), step(async (req, _res, p) => { await flow.twoFactor(ctx, p, req.body ?? {}, req); })); + r.post('/interaction/:uid/two-factor', limit(20), step(async (req, _res, p) => { + const { recoveryCodes } = await flow.twoFactor(ctx, p, req.body ?? {}, req); + return recoveryCodes ? { recoveryCodes } : undefined; + })); r.post('/interaction/:uid/resend', limit(10), step(async (_req, _res, p) => { await flow.resendCode(ctx, p); })); r.post('/interaction/:uid/two-factor/setup', limit(10), handle(async (req, res) => { const { pending } = await load(req, res); @@ -104,12 +110,14 @@ export function interactionRouter(ctx: Ctx, provider: Provider) { if (!row || row.purpose !== 'reset_password' || row.usedAt || row.expiresAt < ctx.now()) throw new ApiError(400, 'BAD_TOKEN', 'This link has expired or was already used. Ask for a new one.'); const problem = passwordProblem(req.body?.password); if (problem) throw new ApiError(400, 'VALIDATION', problem, { password: problem }); - await ctx.db.account.update({ where: { id: row.accountId }, data: { passwordHash: await hashPassword(String(req.body.password)), failedSignIns: 0, lockedUntil: null } }); + // Setting a password from an emailed link also proves the address. + await ctx.db.account.update({ where: { id: row.accountId }, data: { passwordHash: await hashPassword(String(req.body.password)), failedSignIns: 0, lockedUntil: null, emailVerified: true } }); await ctx.db.emailToken.update({ where: { id: row.id }, data: { usedAt: ctx.now() } }); await ctx.db.emailToken.deleteMany({ where: { accountId: row.accountId, purpose: 'reset_password', usedAt: null } }); await loginEvent(ctx, row.accountId, 'password_reset', req); // Back to the sign-in it started from, if this browser still has it (§5). - return { reset: true, uid: row.interactionUid }; + // A "set your password" link a product asked for (people.ensure) ends on that product, which signs them in. + return { reset: true, uid: row.interactionUid, returnUrl: row.returnUrl ?? null }; })); return r; diff --git a/apps/accounts/backend/src/jobs.ts b/apps/accounts/backend/src/jobs.ts index 5bb0750..b0f6e56 100644 --- a/apps/accounts/backend/src/jobs.ts +++ b/apps/accounts/backend/src/jobs.ts @@ -6,6 +6,7 @@ import PgBoss from 'pg-boss'; import type { Ctx } from './context.js'; import { heartbeat } from './hub/client.js'; import { runDue } from './links/deliveries.js'; +import { forgetOldRequests } from './links/requests.js'; import { deleteExpired } from './oidc/adapter.js'; import { runDeletionJob } from './privacy/deletion.js'; import { runExportsJob } from './privacy/export.js'; @@ -21,13 +22,14 @@ export const JOBS: Job[] = [ name: 'cleanup', cron: '17 * * * *', everyMs: 3600e3, run: async (ctx) => { const now = ctx.now(); - const [oidc, pending, tokens, nonces] = await Promise.all([ + const [oidc, pending, tokens, nonces, requests] = await Promise.all([ deleteExpired(ctx), ctx.db.pendingSignIn.deleteMany({ where: { expiresAt: { lt: now } } }), ctx.db.emailToken.deleteMany({ where: { expiresAt: { lt: new Date(now.getTime() - 7 * 24 * 3600e3) } } }), ctx.db.linkNonce.deleteMany({ where: { seenAt: { lt: new Date(now.getTime() - 3600e3) } } }), + forgetOldRequests(ctx), ]); - return { oidc: oidc.count, pending: pending.count, tokens: tokens.count, nonces: nonces.count }; + return { oidc: oidc.count, pending: pending.count, tokens: tokens.count, nonces: nonces.count, requests: requests.count }; }, }, ]; diff --git a/apps/accounts/backend/src/links/requests.ts b/apps/accounts/backend/src/links/requests.ts new file mode 100644 index 0000000..746b9f8 --- /dev/null +++ b/apps/accounts/backend/src/links/requests.ts @@ -0,0 +1,333 @@ +/** + * What a linked product asks of Accounts (`crosscode.identity-request/1`, contracts 1.8.0, + * docs/EVENTS-3.0-PLAN.md §4 and §8), at `POST /api/accounts/v1/requests`, signed with the link's + * secret (`LINK_HEADERS`, the sender header carrying the product's install id): + * + * - `import.*`: moving the product's users in (Cross Events 3.0) with their password hashes and + * authenticator secrets, which arrive sealed with the link's secret. Only Events imports, and + * only between `import.begin` and `import.finish` / `import.abort`. + * - `people.*`: what the product's admins can do to an account from the product. Only for people + * the product knows (`ProductPerson`: imported, added or signed in through it). + * + * A request id seen before gets the first answer again, so a product can retry safely. + */ +import crypto from 'node:crypto'; +import express, { type Request, type Response } from 'express'; +import type Provider from 'oidc-provider'; +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 type { Ctx } from '../context.js'; +import type { ProductLink } from '../generated/prisma/client.js'; +import { limit } from '../http.js'; +import { audit, clientIp, loginEvent } from '../lib/audit.js'; +import { hashToken, randomToken } from '../lib/crypto.js'; +import { appVersion } from '../lib/version.js'; +import { BUILT_IN_VERSION } from '../privacy/notice.js'; +import { emailProblem, normaliseEmail, profileChanged, setNewsConsent } from '../accounts/service.js'; +import { turnOff } from '../accounts/twoFactor.js'; +import { signOutEverywhere } from '../oidc/sessions.js'; + +export class RequestError extends Error { + constructor(message: string, public code: string, public status = 400) { + super(message); + } +} + +/** Products that may move their users in. */ +const IMPORTERS = new Set(['events']); +const SET_PASSWORD_DAYS = 7; +const KEEP_REQUESTS_DAYS = 30; + +const reply = (body: T) => ({ schema: IDENTITY_REQUEST_SCHEMA, ...body }); +const header = (req: Request, name: string) => { + const v = req.headers[name]; + return Array.isArray(v) ? v[0] : v; +}; + +/** The link the request came from, after checking its signature. */ +async function linkFor(ctx: Ctx, req: Request, raw: Buffer): Promise<{ link: ProductLink; secret: string }> { + const sender = header(req, LINK_HEADERS.sender); + const link = sender ? await ctx.db.productLink.findUnique({ where: { installId: String(sender) } }) : null; + if (!link) throw new RequestError('That product isn\'t connected to Accounts.', 'NOT_LINKED', 403); + const secret = ctx.secrets.decrypt(link.secret); + const check = verify({ secret, timestamp: header(req, LINK_HEADERS.timestamp), signature: header(req, LINK_HEADERS.signature), rawBody: raw, now: ctx.now() }); + if (!check.ok) throw new RequestError(check.code === 'STALE_REQUEST' ? 'The request is too old, or a clock is wrong.' : 'The request isn\'t signed with this link\'s secret.', check.code, 401); + return { link, secret }; +} + +async function knows(ctx: Ctx, linkId: string, accountId: string, via: string, opts: { upgrade?: boolean } = {}) { + const existing = await ctx.db.productPerson.findFirst({ where: { linkId, accountId } }); + if (!existing) await ctx.db.productPerson.create({ data: { linkId, accountId, via, createdAt: ctx.now() } }); + else if (opts.upgrade && existing.via !== via) await ctx.db.productPerson.update({ where: { id: existing.id }, data: { via } }); +} + +/** Records that a product signed someone in (so its people.* requests reach them). */ +export async function signedInThrough(ctx: Ctx, clientId: string | null, accountId: string | null) { + if (!clientId || !accountId) return; + const link = await ctx.db.productLink.findUnique({ where: { installId: clientId } }); + if (link) await knows(ctx, link.installId, accountId, 'sign_in').catch(() => {}); +} + +async function knownAccount(ctx: Ctx, link: ProductLink, sub: string) { + const known = await ctx.db.productPerson.findFirst({ where: { linkId: link.installId, accountId: sub } }); + const a = known ? await ctx.db.account.findUnique({ where: { id: sub } }) : null; + if (!a || a.status === 'deleted') throw new RequestError('That person isn\'t known to Accounts through this product.', 'UNKNOWN_PERSON', 404); + return a; +} + +const logRequest = (ctx: Ctx, link: ProductLink, r: IdentityRequest, action: string, targetId: string | null, req: Request, metadata: object = {}) => + audit(ctx, { actorId: r.actor, actorRole: 'linked_product', action, targetType: targetId ? 'account' : 'product_link', targetId: targetId ?? link.installId, metadata: { product: link.product, installId: link.installId, ...metadata }, ip: clientIp(req) }); + +// ─── import.* ──────────────────────────────────────────────────────────────── + +const HASH = /^(\$argon2(id|i|d)\$|\$2[aby]\$)/; + +function opened(secret: string, sealed: string | null, what: string): string | null { + if (sealed === null) return null; + try { + return openLinkValue(secret, sealed); + } catch { + throw new RequestError(`A ${what} couldn't be opened with this link's secret.`, 'INVALID_REQUEST', 400); + } +} + +/** What happens to one person; writes only when `write`. */ +async function importOne(ctx: Ctx, link: ProductLink, secret: string, p: ImportPerson, write: boolean): Promise { + const email = normaliseEmail(p.email); + if (emailProblem(email)) return { id: p.id, outcome: 'refused', sub: null, reason: 'The email address isn\'t valid.' }; + const passwordHash = opened(secret, p.passwordHash, 'password hash'); + if (passwordHash !== null && !HASH.test(passwordHash)) return { id: p.id, outcome: 'refused', sub: null, reason: 'The password hash isn\'t bcrypt or Argon2.' }; + const totp = p.twoFactor === 'totp' ? opened(secret, p.totpSecret, 'authenticator secret') : null; + if (p.twoFactor === 'totp' && !totp) return { id: p.id, outcome: 'refused', sub: null, reason: 'An authenticator app is on but its secret is missing.' }; + + const byId = await ctx.db.account.findUnique({ where: { id: p.id } }); + const byEmail = await ctx.db.account.findUnique({ where: { email } }); + + // Already moved by this product (a move run again): bring it up to date. + if (byId) { + const mine = await ctx.db.productPerson.findFirst({ where: { linkId: link.installId, accountId: byId.id, via: 'import' } }); + if (!mine) return { id: p.id, outcome: 'refused', sub: null, reason: 'Accounts already has a different account with this id.' }; + if (byEmail && byEmail.id !== byId.id) return { id: p.id, outcome: 'refused', sub: null, reason: 'Another account has this email address.' }; + if (write) await ctx.db.account.update({ where: { id: byId.id }, data: fields(ctx, p, email, passwordHash, totp) }); + return { id: p.id, outcome: 'updated', sub: byId.id, reason: null }; + } + // The email already has an account (made before the move): link to it, change nothing. + if (byEmail) { + if (write) await knows(ctx, link.installId, byEmail.id, 'import', { upgrade: true }); + return { id: p.id, outcome: 'linked', sub: byEmail.id, reason: null }; + } + if (write) { + const a = await ctx.db.account.create({ data: { id: p.id, ...fields(ctx, p, email, passwordHash, totp), createdAt: new Date(p.createdAt) } }); + for (const n of p.noticeAcceptances) await ctx.db.noticeAcceptance.create({ data: { accountId: a.id, version: n.version, acceptedAt: new Date(n.acceptedAt) } }); + for (const c of p.consentChanges) await ctx.db.consentChange.create({ data: { accountId: a.id, channel: c.channel, granted: c.granted, source: 'events_import', createdAt: new Date(c.at) } }); + await knows(ctx, link.installId, a.id, 'import', { upgrade: true }); + await loginEvent(ctx, a.id, 'account_created', undefined, { clientId: link.installId, detail: { by: 'import', product: link.product } }); + } + return { id: p.id, outcome: 'created', sub: p.id, reason: null }; +} + +function fields(ctx: Ctx, p: ImportPerson, email: string, passwordHash: string | null, totp: string | null) { + return { + name: p.name, + email, + emailVerified: p.emailVerified, + phone: p.phone, + passwordHash, + twoFactorMethod: p.twoFactor, + totpSecret: totp ? ctx.secrets.encrypt(totp) : null, + totpLastStep: totp ? p.totpLastStep : null, + // Their old recovery codes can't move (EVENTS-3.0-PLAN decision 2): new ones after the next sign-in. + recoveryCodesNeeded: p.twoFactor !== null, + failedSignIns: p.failedSignIns, + lockedUntil: p.lockedUntil ? new Date(p.lockedUntil) : null, + newsEmail: p.news.email, + newsWhatsApp: p.news.whatsapp, + newsAskedAt: p.newsAskedAt ? new Date(p.newsAskedAt) : null, + noticeVersionAccepted: p.noticeVersionAccepted, + lastSignInAt: p.lastSignInAt ? new Date(p.lastSignInAt) : null, + status: p.status, + deactivatedAt: p.status === 'deactivated' ? ctx.now() : null, + role: p.admin ? ('admin' as const) : ('member' as const), + }; +} + +async function handle(ctx: Ctx, provider: Provider, link: ProductLink, secret: string, r: IdentityRequest, req: Request): Promise { + switch (r.type) { + case 'import.begin': { + if (!IMPORTERS.has(link.product)) throw new RequestError('Only Cross Events moves its users into Accounts.', 'WRONG_PRODUCT', 403); + const own = await ctx.db.privacyNotice.findMany({ orderBy: { version: 'asc' } }); + const noticesTaken = own.length === 0; + if (!r.check) { + if (noticesTaken) { + for (const n of r.notices.filter((x) => x.version > BUILT_IN_VERSION)) { + await ctx.db.privacyNotice.create({ data: { version: n.version, title: n.title, body: n.body, publishedAt: new Date(n.publishedAt), publishedById: null } }); + } + } + const stored = await ctx.settings.json & { branding?: { colours?: { primary?: string; accent?: string } } }>('church_profile', {}); + const next = { ...stored }; + if (!stored.name && r.church.name) next.name = r.church.name; + if (!stored.branding?.colours?.primary && r.church.primaryColour) { + next.branding = { logoUrl: null, iconUrl: null, ...(stored.branding ?? {}), colours: { accent: '#f2a900', ...(stored.branding?.colours ?? {}), primary: r.church.primaryColour } } as never; + } + if (JSON.stringify(next) !== JSON.stringify(stored)) await ctx.settings.set('church_profile', JSON.stringify(next)); + await ctx.db.productLink.update({ where: { installId: link.installId }, data: { importStartedAt: ctx.now() } }); + await logRequest(ctx, link, r, 'import_started', null, req, { notices: noticesTaken ? r.notices.length : 0 }); + } + return reply({ noticesTaken, accountsNoticeVersions: own.map((n) => n.version), accountsVersion: appVersion() }); + } + case 'import.batch': { + if (!IMPORTERS.has(link.product)) throw new RequestError('Only Cross Events moves its users into Accounts.', 'WRONG_PRODUCT', 403); + if (!r.check && !link.importStartedAt) throw new RequestError('Start the move first (import.begin).', 'NOT_MOVING', 409); + const seen = new Set(); + const results: ImportResult[] = []; + for (const p of r.people) { + const email = normaliseEmail(p.email); + if (seen.has(email)) { + results.push({ id: p.id, outcome: 'refused', sub: null, reason: 'The same email address is twice in this move.' }); + continue; + } + seen.add(email); + results.push(await importOne(ctx, link, secret, p, !r.check)); + } + return reply({ results }); + } + 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; + 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 }); + } + case 'import.abort': { + await ctx.db.productLink.update({ where: { installId: link.installId }, data: { importStartedAt: null } }); + await logRequest(ctx, link, r, 'import_aborted', null, req); + return reply({ ok: true as const }); + } + case 'people.ensure': { + const email = normaliseEmail(r.email); + const existing = await ctx.db.account.findUnique({ where: { email } }); + if (existing && existing.status === 'deleted') throw new RequestError('That email address belonged to a deleted account.', 'NOT_ALLOWED', 409); + if (existing) { + await knows(ctx, link.installId, existing.id, 'ensure'); + await logRequest(ctx, link, r, 'person_linked_by_product', existing.id, req); + return reply({ sub: existing.id, created: false }); + } + const a = await ctx.db.account.create({ data: { name: r.name, email, phone: r.phone, passwordHash: null, emailVerified: false } }); + await knows(ctx, link.installId, a.id, 'ensure'); + const token = randomToken(); + // Only the product's own address: never somewhere else. + const returnUrl = new URL(r.returnUrl).origin === new URL(link.url).origin ? r.returnUrl : link.url; + await ctx.db.emailToken.create({ data: { accountId: a.id, purpose: 'reset_password', tokenHash: hashToken(token), returnUrl, expiresAt: new Date(ctx.now().getTime() + SET_PASSWORD_DAYS * 86400e3) } }); + const churchName = (await ctx.settings.json<{ name?: string }>('church_profile', {})).name || 'your church'; + await ctx.messenger.email({ + to: email, + subject: `Your account at ${churchName}`, + text: `Hello ${r.name},\n\n${churchName} has made you an account. Choose your password here (the link works for ${SET_PASSWORD_DAYS} days):\n${ctx.config.publicUrl}/reset?token=${token}\n\nIf you weren't expecting this, you can ignore this email.`, + }); + await loginEvent(ctx, a.id, 'account_created', req, { clientId: link.installId, detail: { by: 'product', product: link.product } }); + await logRequest(ctx, link, r, 'person_created_by_product', a.id, req); + return reply({ sub: a.id, created: true }); + } + case 'people.update': { + const a = await knownAccount(ctx, link, r.sub); + const data: Record = {}; + if (r.name !== undefined) data.name = r.name; + if (r.phone !== undefined) { data.phone = r.phone; if (r.phone !== a.phone) data.phoneVerified = false; } + if (r.email !== undefined) { + const email = normaliseEmail(r.email); + if (email !== a.email) { + const other = await ctx.db.account.findUnique({ where: { email } }); + if (other) throw new RequestError('Another account has that email address.', 'EMAIL_TAKEN', 409); + data.email = email; + data.emailVerified = false; + } + } + if (Object.keys(data).length) { + await ctx.db.account.update({ where: { id: a.id }, data }); + if (data.email) await loginEvent(ctx, a.id, 'email_changed', req, { clientId: link.installId, detail: { by: 'product' } }); + await profileChanged(ctx, a.id); + } + await logRequest(ctx, link, r, 'person_updated_by_product', a.id, req, { fields: Object.keys(data) }); + return reply({ ok: true as const }); + } + case 'people.resetTwoFactor': { + const a = await knownAccount(ctx, link, r.sub); + if (a.role === 'admin') throw new RequestError('An Accounts admin\'s two-factor sign-in can only be reset in Accounts.', 'NOT_ALLOWED', 403); + await turnOff(ctx, a.id); + await ctx.db.account.update({ where: { id: a.id }, data: { recoveryCodesNeeded: false } }); + await signOutEverywhere(ctx, provider, a.id); + await loginEvent(ctx, a.id, 'two_factor_off', req, { clientId: link.installId, detail: { by: 'product' } }); + await logRequest(ctx, link, r, 'two_factor_reset_by_product', a.id, req); + return reply({ ok: true as const }); + } + case 'people.unlock': { + const a = await knownAccount(ctx, link, r.sub); + await ctx.db.account.update({ where: { id: a.id }, data: { lockedUntil: null, failedSignIns: 0 } }); + await logRequest(ctx, link, r, 'account_unlocked_by_product', a.id, req); + return reply({ ok: true as const }); + } + case 'people.setActive': { + const a = await knownAccount(ctx, link, r.sub); + if (a.role === 'admin' && !r.active) throw new RequestError('An Accounts admin can only be deactivated in Accounts.', 'NOT_ALLOWED', 403); + await ctx.db.account.update({ where: { id: a.id }, data: r.active ? { status: 'active', deactivatedAt: null } : { status: 'deactivated', deactivatedAt: ctx.now() } }); + if (!r.active) await signOutEverywhere(ctx, provider, a.id); + await logRequest(ctx, link, r, r.active ? 'account_reactivated_by_product' : 'account_deactivated_by_product', a.id, req); + return reply({ ok: true as const }); + } + case 'people.newsOff': { + const a = await knownAccount(ctx, link, r.sub); + const off = r.channel === 'all' ? { email: false, whatsapp: false } : { [r.channel]: false }; + if (await setNewsConsent(ctx, a, off, 'product_unsubscribe')) await profileChanged(ctx, a.id); + await logRequest(ctx, link, r, 'news_off_by_product', a.id, req, { channel: r.channel }); + return reply({ ok: true as const }); + } + } +} + +export function requestsRouter(ctx: Ctx, provider: Provider) { + const r = express.Router(); + r.post(ACCOUNTS_REQUEST_PATH.replace(/^\/api/, ''), limit(600), express.raw({ type: '*/*', limit: '4mb' }), async (req: Request, res: Response) => { + try { + const raw = Buffer.isBuffer(req.body) ? req.body : Buffer.from(''); + const { link, secret } = await linkFor(ctx, req, raw); + let body: unknown; + try { + body = JSON.parse(raw.toString('utf8')); + } catch { + throw new RequestError('The body must be JSON.', 'INVALID_REQUEST'); + } + const parsed = identityRequestSchema.safeParse(body); + if (!parsed.success) throw new RequestError(`Not a crosscode.identity-request/1 request: ${parsed.error.issues[0]?.path.join('.') || ''} ${parsed.error.issues[0]?.message ?? ''}`.trim(), 'INVALID_REQUEST'); + const request = parsed.data; + const before = await ctx.db.productRequest.findUnique({ where: { requestId: request.requestId } }); + if (before) { + if (before.linkId !== link.installId) throw new RequestError('That request id was used by another product.', 'INVALID_REQUEST', 409); + return res.json(before.reply); + } + const out = await handle(ctx, provider, link, secret, request, req); + // Checks write nothing, so they needn't be remembered. + const isCheck = 'check' in request && request.check; + if (!isCheck) { + await ctx.db.productRequest.create({ data: { requestId: request.requestId, linkId: link.installId, type: request.type, reply: out as never, createdAt: ctx.now() } }).catch(() => {}); + } + return res.json(out); + } catch (e) { + if (e instanceof RequestError) return res.status(e.status).json({ message: e.message, code: e.code }); + console.error('[requests]', e); + return res.status(500).json({ message: 'Something went wrong.', code: 'SERVER_ERROR' }); + } + }); + return r; +} + +/** Old remembered requests (the `cleanup` job). */ +export async function forgetOldRequests(ctx: Ctx) { + return ctx.db.productRequest.deleteMany({ where: { createdAt: { lt: new Date(ctx.now().getTime() - KEEP_REQUESTS_DAYS * 86400e3) } } }); +} + +export const newRequestId = () => crypto.randomUUID(); diff --git a/apps/accounts/backend/src/oidc/provider.ts b/apps/accounts/backend/src/oidc/provider.ts index 001e6de..5086495 100644 --- a/apps/accounts/backend/src/oidc/provider.ts +++ b/apps/accounts/backend/src/oidc/provider.ts @@ -68,6 +68,8 @@ export async function createProvider(ctx: Ctx): Promise { adapter: adapterFor(ctx), clients: [selfClient(ctx)], extraClientMetadata: { properties: ['crosscode.product'] }, + // 1.1.0: `screen=signup` opens the sign-in page on "Create an account". + extraParams: ['screen'], clientDefaults: { id_token_signed_response_alg: 'ES256', grant_types: ['authorization_code'], response_types: ['code'], token_endpoint_auth_method: 'client_secret_basic' }, findAccount: async (_k, sub) => { const a = await ctx.db.account.findUnique({ where: { id: sub } }); diff --git a/apps/accounts/backend/tests/requests.test.ts b/apps/accounts/backend/tests/requests.test.ts new file mode 100644 index 0000000..e57ddc2 --- /dev/null +++ b/apps/accounts/backend/tests/requests.test.ts @@ -0,0 +1,186 @@ +// 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, 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 }; +} + +function person(over: Partial = {}): 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; + 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'); + }); +}); diff --git a/apps/accounts/backend/tests/support/memoryDb.ts b/apps/accounts/backend/tests/support/memoryDb.ts index 795c3e0..9901f00 100644 --- a/apps/accounts/backend/tests/support/memoryDb.ts +++ b/apps/accounts/backend/tests/support/memoryDb.ts @@ -12,21 +12,21 @@ const DEFAULTS: Record Row> = { account: () => ({ givenName: null, familyName: null, emailVerified: false, phone: null, phoneVerified: false, passwordHash: null, role: 'member', status: 'active', twoFactorMethod: null, totpSecret: null, totpLastStep: null, newsEmail: false, newsWhatsApp: false, newsAskedAt: null, noticeVersionAccepted: 0, - failedSignIns: 0, lockedUntil: null, lastSignInAt: null, deactivatedAt: null, anonymisedAt: null, + failedSignIns: 0, lockedUntil: null, lastSignInAt: null, deactivatedAt: null, anonymisedAt: null, recoveryCodesNeeded: false, }), recoveryCode: () => ({ usedAt: null }), pendingSignIn: () => ({ accountId: null, codeHash: null, codeSentAt: null, attempts: 0, amr: [], pendingTotpSecret: null, remember: false }), - emailToken: () => ({ interactionUid: null, usedAt: null }), + emailToken: () => ({ interactionUid: null, returnUrl: null, usedAt: null }), loginEvent: () => ({ accountId: null, clientId: null, ip: null, userAgent: null, detail: null }), privacyNotice: () => ({ publishedById: null }), auditLog: () => ({ actorId: null, targetId: null, metadata: null, ip: null }), - productLink: () => ({ connectedById: null }), + productLink: () => ({ connectedById: null, importStartedAt: null }), oidcPayload: () => ({ grantId: null, userCode: null, uid: null, accountId: null, expiresAt: null, consumedAt: null }), delivery: () => ({ status: 'pending', attempts: 0, lastError: null, reply: null, deliveredAt: null }), dataExport: () => ({ status: 'collecting', parts: {}, file: null, readyAt: null }), deletionRequest: () => ({ status: 'waiting_approval', approvedAt: null, approvedById: null, products: {}, completedAt: null }), }; -const KEYS: Record = { appSetting: 'key', productLink: 'installId', linkNonce: 'nonce', pendingSignIn: 'uid', privacyNotice: 'version' }; +const KEYS: Record = { appSetting: 'key', productLink: 'installId', linkNonce: 'nonce', pendingSignIn: 'uid', privacyNotice: 'version', productRequest: 'requestId' }; const UNIQUE: Record = { account: ['email'], recoveryCode: ['codeHash'], emailToken: ['tokenHash'], delivery: ['callId'] }; const HAS_UPDATED_AT = new Set(['account', 'appSetting', 'productLink']); @@ -148,8 +148,8 @@ function model(name: string, tables: Map>) { }, }; const cascade = (from: string, id: unknown) => { - if (from === 'productLink') for (const [k, r] of tables.get('delivery') ?? []) if (r.linkId === id) tables.get('delivery')!.delete(k); - if (from === 'account') for (const t of ['recoveryCode', 'emailToken', 'loginEvent', 'noticeAcceptance', 'consentChange', 'dataExport', 'deletionRequest']) for (const [k, r] of tables.get(t) ?? []) if (r.accountId === id) tables.get(t)!.delete(k); + if (from === 'productLink') for (const t of ['delivery', 'productPerson', 'productRequest']) for (const [k, r] of tables.get(t) ?? []) if (r.linkId === id) tables.get(t)!.delete(k); + if (from === 'account') for (const t of ['recoveryCode', 'emailToken', 'loginEvent', 'noticeAcceptance', 'consentChange', 'dataExport', 'deletionRequest', 'productPerson']) for (const [k, r] of tables.get(t) ?? []) if (r.accountId === id) tables.get(t)!.delete(k); }; return api; } diff --git a/apps/accounts/frontend/package.json b/apps/accounts/frontend/package.json index 8ae85ca..f2ea86f 100644 --- a/apps/accounts/frontend/package.json +++ b/apps/accounts/frontend/package.json @@ -1,6 +1,6 @@ { "name": "@crosscode/accounts-frontend", - "version": "1.0.1", + "version": "1.1.0", "private": true, "description": "Cross Code Accounts: the church's sign-in pages, the account page and admin", "scripts": { diff --git a/apps/accounts/frontend/src/app/reset/Reset.tsx b/apps/accounts/frontend/src/app/reset/Reset.tsx index 5396faf..5a76a4e 100644 --- a/apps/accounts/frontend/src/app/reset/Reset.tsx +++ b/apps/accounts/frontend/src/app/reset/Reset.tsx @@ -17,11 +17,12 @@ export function Reset({ token }: { token: string | null }) {
{ e.preventDefault(); setBusy(true); - const r = await call<{ uid: string | null }>("POST", "/password/reset", { token, password: new FormData(e.currentTarget).get("password") }); + const r = await call<{ uid: string | null; returnUrl: string | null }>("POST", "/password/reset", { token, password: new FormData(e.currentTarget).get("password") }); setBusy(false); if (!r.ok) return setError(r.error.message); - // Back to the sign-in it started from (and on to that site), or to the account page. - window.location.assign(r.data.uid ? `/signin?uid=${encodeURIComponent(r.data.uid)}` : selfSignIn("/account")); + // Back to the sign-in it started from (and on to that site), to the product that made the + // account (its sign-in brings them straight back here signed in), or to the account page. + window.location.assign(r.data.uid ? `/signin?uid=${encodeURIComponent(r.data.uid)}` : r.data.returnUrl ?? selfSignIn("/account")); }}> diff --git a/apps/accounts/frontend/src/app/signin/SignIn.tsx b/apps/accounts/frontend/src/app/signin/SignIn.tsx index 884e446..e802860 100644 --- a/apps/accounts/frontend/src/app/signin/SignIn.tsx +++ b/apps/accounts/frontend/src/app/signin/SignIn.tsx @@ -13,6 +13,7 @@ type State = { product: string; signupEnabled: boolean; loginHint?: string | null; + screen?: "signin" | "signup"; name?: string; email?: string; sentTo?: string; @@ -35,16 +36,29 @@ export function SignIn({ uid }: { uid: string }) { const [error, setError] = useState(null); const [busy, setBusy] = useState(false); const [mode, setMode] = useState<"signin" | "signup">("signin"); - const [codes, setCodes] = useState<{ codes: string[]; next: string } | null>(null); + const [codes, setCodes] = useState<{ codes: string[]; next: State } | null>(null); + const [opened, setOpened] = useState(false); - const apply = (s: State) => { + // New recovery codes (2FA just set up, or moved in from Cross Events without them) are shown + // first, whatever comes next. + const go = (s: State) => { if (s.stage === "done" && s.redirectTo) { - if (s.recoveryCodes?.length) setCodes({ codes: s.recoveryCodes, next: s.redirectTo }); - else window.location.assign(s.redirectTo); + window.location.assign(s.redirectTo); return; } setState(s); }; + const apply = (s: State) => { + if (!opened) { + setOpened(true); + if (s.screen === "signup" && s.signupEnabled) setMode("signup"); + } + if (s.recoveryCodes?.length) { + setCodes({ codes: s.recoveryCodes, next: s }); + return; + } + go(s); + }; useExternalEffect(() => { let alive = true; @@ -69,7 +83,7 @@ export function SignIn({ uid }: { uid: string }) { const frame = (children: React.ReactNode) => {children}; if (codes) { - return frame( window.location.assign(codes.next)} />); + return frame( { const next = codes.next; setCodes(null); go(next); }} />); } if (!state) { return frame(error ? ( diff --git a/exports/f6b37ff7-057a-4d31-980d-a01aa1a2509f.json b/exports/f6b37ff7-057a-4d31-980d-a01aa1a2509f.json new file mode 100644 index 0000000..bb47078 --- /dev/null +++ b/exports/f6b37ff7-057a-4d31-980d-a01aa1a2509f.json @@ -0,0 +1,70 @@ +{ + "schema": "crosscode.identity/1", + "exportId": "f6b37ff7-057a-4d31-980d-a01aa1a2509f", + "generatedAt": "2026-11-19T11:39:46.247Z", + "parts": [ + { + "product": "accounts", + "sections": [ + { + "key": "profile", + "title": "Your account", + "records": [ + { + "name": "Thandi Test", + "givenName": null, + "familyName": null, + "email": "mydata@hope.test", + "emailVerified": true, + "phone": null, + "twoFactor": null, + "createdAt": "2026-11-19T11:39:45.934Z", + "lastSignInAt": "2026-11-19T11:39:46.130Z" + } + ] + }, + { + "key": "news_consent", + "title": "News consent", + "records": [] + }, + { + "key": "privacy_notice", + "title": "Privacy notices accepted", + "records": [] + }, + { + "key": "sign_ins", + "title": "Sign-ins and changes", + "records": [ + { + "type": "sign_in", + "at": "2026-11-19T11:39:46.132Z", + "ip": "127.0.0.1", + "device": "node" + } + ] + } + ] + }, + { + "schema": "crosscode.identity/1", + "exportId": "f6b37ff7-057a-4d31-980d-a01aa1a2509f", + "sub": "ab5df919-e6bc-4158-bb65-7cf251561c9a", + "product": "website", + "generatedAt": "2026-11-19T11:39:46.237Z", + "sections": [ + { + "key": "pages", + "title": "Pages you edited", + "records": [ + { + "title": "Home" + } + ] + } + ] + } + ], + "missing": [] +} \ No newline at end of file diff --git a/packages/auth-client/src/index.ts b/packages/auth-client/src/index.ts index f165ea9..f9aa075 100644 --- a/packages/auth-client/src/index.ts +++ b/packages/auth-client/src/index.ts @@ -12,6 +12,8 @@ * const { sub, sid } = await auth.verifyLogoutToken(form.logout_token); // end that person's sessions * // POST /api/accounts/v1/events: * const call = auth.verifyAccountsCall(rawBody, headers); // user.updated / user.deleted / user.export + * // Asking Accounts something (contracts 1.8.0, crosscode.identity-request/1): + * const { sub } = await auth.request({ type: 'people.ensure', actor, name, email, phone: null, returnUrl }); * * The client secret is derived from the product's link with Accounts (Connect), so a product only * keeps its link secret. Roles are never in the claims: each product keeps its own, keyed by `sub`. @@ -19,10 +21,10 @@ import crypto from 'node:crypto'; import * as oidc from 'openid-client'; import { - accountsCallSchema, ACR_MFA, decodeState, encodeState, identityClaimsSchema, OIDC_CLIENT_PATHS, OIDC_PROVIDER_PATHS, OIDC_SCOPES, - safeReturnPath, type AccountsCall, type IdentityClaims, + accountsCallSchema, ACCOUNTS_REQUEST_PATH, ACR_MFA, decodeState, encodeState, IDENTITY_REQUEST_SCHEMA, identityClaimsSchema, OIDC_CLIENT_PATHS, + OIDC_PROVIDER_PATHS, OIDC_SCOPES, safeReturnPath, type AccountsCall, type IdentityClaims, type IdentityRequest, } from '@crosscode/contracts'; -import { LINK_HEADERS, oidcClientSecret, verify } from '@crosscode/contracts/signing'; +import { LINK_HEADERS, oidcClientSecret, sealLinkValue, signedHeaders, verify } from '@crosscode/contracts/signing'; export type AccountsClientOptions = { /** The church's Accounts address, e.g. https://accounts.hopefamily.co.za */ @@ -46,6 +48,16 @@ export class SignInError extends Error { } } +/** Accounts refused or couldn't answer a request (`code` from IDENTITY_REQUEST_ERROR_CODES, or UNREACHABLE / BAD_REPLY). */ +export class AccountsRequestError extends Error { + constructor(message: string, public code: string, public status: number) { + super(message); + } +} + +/** A request without its envelope: `schema` and `requestId` are filled in (pass `requestId` to retry the same one). */ +export type RequestInput = IdentityRequest extends infer R ? R extends IdentityRequest ? Omit & { requestId?: string } : never : never; + export async function accountsClient(o: AccountsClientOptions) { const base = o.productUrl.replace(/\/+$/, ''); const issuer = new URL(`${o.accountsUrl.replace(/\/+$/, '')}${OIDC_PROVIDER_PATHS.issuer}`); @@ -56,7 +68,7 @@ export async function accountsClient(o: AccountsClientOptions) { config, /** Starts a sign-in that comes back to `returnTo` (the page the person was on). `requireTwoFactor` for staff roles. */ - async startSignIn(returnTo: string, opts: { requireTwoFactor?: boolean; loginHint?: string } = {}) { + async startSignIn(returnTo: string, opts: { requireTwoFactor?: boolean; loginHint?: string; signUp?: boolean } = {}) { const nonce = oidc.randomNonce(); const verifier = oidc.randomPKCECodeVerifier(); const state = encodeState({ nonce: crypto.randomBytes(16).toString('base64url'), returnTo: safeReturnPath(returnTo) }); @@ -69,6 +81,8 @@ export async function accountsClient(o: AccountsClientOptions) { code_challenge_method: 'S256', ...(opts.requireTwoFactor ? { acr_values: ACR_MFA } : {}), ...(opts.loginHint ? { login_hint: opts.loginHint } : {}), + // Accounts 1.1.0: open on "Create an account". + ...(opts.signUp ? { screen: 'signup' } : {}), }); const pending: Pending = { nonce, verifier, state }; return { url: url.toString(), cookie: Buffer.from(JSON.stringify(pending)).toString('base64url') }; @@ -129,6 +143,30 @@ export async function accountsClient(o: AccountsClientOptions) { return { sub: String(payload.sub), sid: payload.sid ? String(payload.sid) : null }; }, + /** Seals a secret for an `import.batch` (a password hash, an authenticator secret) with the link's secret. */ + seal(value: string): string { + return sealLinkValue(o.linkSecret, value); + }, + + /** Sends a `crosscode.identity-request/1` request to Accounts, signed with the link's secret, and returns its answer. */ + async request>(input: RequestInput, opts: { timeoutMs?: number } = {}): Promise { + const body = JSON.stringify({ schema: IDENTITY_REQUEST_SCHEMA, requestId: crypto.randomUUID(), ...input }); + const headers = signedHeaders(LINK_HEADERS, { senderId: o.clientId, secret: o.linkSecret, rawBody: body }); + let res: Response; + try { + res = await fetch(`${o.accountsUrl.replace(/\/+$/, '')}${ACCOUNTS_REQUEST_PATH}`, { + method: 'POST', body, redirect: 'manual', signal: AbortSignal.timeout(opts.timeoutMs ?? 30000), + headers: { 'content-type': 'application/json', accept: 'application/json', ...headers }, + }); + } catch (e) { + throw new AccountsRequestError(`Accounts could not be reached: ${(e as Error).message}`, 'UNREACHABLE', 502); + } + const data = (await res.json().catch(() => null)) as (Record & { message?: string; code?: string }) | null; + if (!res.ok) throw new AccountsRequestError(data?.message || `Accounts answered ${res.status}`, data?.code || `HTTP_${res.status}`, res.status); + if (!data || data.schema !== IDENTITY_REQUEST_SCHEMA) throw new AccountsRequestError('Accounts answered in a way this product doesn\'t understand.', 'BAD_REPLY', 502); + return data as T; + }, + /** Checks and reads a back-channel call from Accounts (signed with the link secret). */ verifyAccountsCall(rawBody: string | Uint8Array, headers: Record): AccountsCall { const get = (n: string) => { diff --git a/packages/contracts/src/identity-request.ts b/packages/contracts/src/identity-request.ts index 3713858..60e3b0b 100644 --- a/packages/contracts/src/identity-request.ts +++ b/packages/contracts/src/identity-request.ts @@ -97,7 +97,10 @@ export const importBatchSchema = base.extend({ people: z.array(importPersonSchema).min(1).max(IMPORT_BATCH_MAX), }); -/** Ends a move: Accounts compares the count and the ids' hash (`importIdsHash`) with what it holds. */ +/** + * 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. + */ export const importFinishSchema = base.extend({ type: z.literal("import.finish"), count: z.int().nonnegative(),