Compare commits
19
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
88b3e1fb36 | ||
|
|
70c471666b | ||
|
|
cc18b7b514 | ||
|
|
4b28fc485b | ||
|
|
793831ca44 | ||
|
|
4b033a1d1d | ||
|
|
9bcd24bbbd | ||
|
|
c9f8cad13f | ||
|
|
5819ea87fb | ||
|
|
cbd7965fcc | ||
|
|
be5b56673a | ||
|
|
63d36c3ecf | ||
|
|
c627c61de1 | ||
|
|
56cbef1d9b | ||
|
|
733992e917 | ||
|
|
08fef930c1 | ||
|
|
ac017395df | ||
|
|
258f8b820d | ||
|
|
9985444937 |
@@ -2,6 +2,53 @@
|
||||
|
||||
Each package and app has its own section and its own tags (`contracts@1.0.0`, `accounts@1.0.0`, …).
|
||||
|
||||
## events@3.1.0, accounts@1.2.0, contracts@1.9.0 - 2026-11-19
|
||||
|
||||
A church moved Cross Events' sign-in to Accounts without email set up in Accounts: Accounts couldn't
|
||||
send codes or password links, sign-in failed with a 500, and nobody could get in.
|
||||
|
||||
- **Contracts 1.9.0:** `messaging.status`, `messaging.test`, `messaging.set` in
|
||||
`crosscode.identity-request/1` (SMTP and WAWP settings, secrets sealed); `people.ensure` answers
|
||||
`emailSent`.
|
||||
- **Accounts 1.2.0:** a code or link that can't be sent shows a message instead of a 500 (WhatsApp
|
||||
codes fall back to email); forgot password says email isn't set up; the `messaging.*` requests
|
||||
(test, and save only what worked); a test WhatsApp in its admin; WAWP from the `.env` too.
|
||||
- **The sign-in pages look like the church's site:** `@crosscode/ui` Shell / Card / Heading redone
|
||||
(colour wash, logo and name, cards edged in the church's colour, icons); Events sends its logo and
|
||||
colours (`church.branding`, and with a move).
|
||||
- **Events 3.1.0:** Settings → Sign-in shows what Accounts can send and sets it up by copying this
|
||||
site's SMTP / WAWP (its secrets stay on the server), with a test before saving; the move needs
|
||||
Accounts' email (disabled, and refused by the server, without it).
|
||||
|
||||
## crosscode script - 2026-11-19 (no tag: servers run `main`)
|
||||
|
||||
- **A church with Accounts couldn't be updated.** `crosscode install` / `add` writes Accounts' PM2
|
||||
config to `apps/accounts/ecosystem.config.cjs`, which no `.gitignore` covered, so the next
|
||||
`deploy` stopped at "files … were changed or added by hand: ?? apps/accounts/ecosystem.config.cjs".
|
||||
The PM2 configs crosscode makes (`apps/events/ecosystem.config.js`, `apps/accounts/ecosystem.config.cjs`)
|
||||
no longer count as changes by hand, also in checkouts of releases that don't ignore them, and
|
||||
`apps/accounts/.gitignore` ignores it from the next Accounts release on. bats test.
|
||||
|
||||
## events@3.0.0, accounts@1.1.0, contracts@1.8.0, crosscode script - 2026-11-19
|
||||
|
||||
Cross Events signs in through the church's Accounts (ROADMAP-v3 phase 4, docs/EVENTS-3.0-PLAN.md).
|
||||
Tested on Postgres 18 (both apps' migrations, `test:accounts` on real databases, the Events e2e
|
||||
suite with the new sign-in spec); not VM tested yet.
|
||||
|
||||
- **Scripts:** `products/events.sh` installs and builds `packages/auth-client` (after contracts)
|
||||
when the checkout's Events uses it, as 3.0.0 does.
|
||||
|
||||
- **Contracts 1.8.0:** `crosscode.identity-request/1` (product → Accounts at
|
||||
`/api/accounts/v1/requests`): `import.begin` / `batch` / `finish` / `abort` and `people.*`;
|
||||
`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`.
|
||||
- **`@crosscode/auth-client` 1.1.0:** `request()`, `seal()`, `startSignIn(…, { signUp })`.
|
||||
- **Events 3.0.0:** Settings → Sign-in (check, move, undo), sign-in and sign-out through Accounts,
|
||||
Accounts' calls, admin actions through Accounts. Details in `apps/events/CHANGELOG.md` and
|
||||
`apps/events/MIGRATING-TO-3.md`.
|
||||
|
||||
## events@2.4.1, contracts@1.7.0, agent@1.2.0, crosscode script - 2026-11-19
|
||||
|
||||
Demo data from the Hub, for installs marked as demo sites (Hub 2.4.0).
|
||||
|
||||
@@ -9,7 +9,7 @@ things stand is in [`docs/HANDOVER.md`](./docs/HANDOVER.md).
|
||||
| `packages/contracts` | `@crosscode/contracts`: the shared JSON formats (zod schemas, JSON Schema, TypeScript types, sample payloads) used by every product, including Cross Events and the Hub | Phase 0, in progress |
|
||||
| `packages/ui` | `@crosscode/ui`: shared UI for the Website, App and Accounts | Placeholder, filled in during the Website phase |
|
||||
| `apps/accounts` | Accounts: the per-church sign-in (OpenID Connect) | Placeholder (phase 3) |
|
||||
| `apps/website` | Church Website | Placeholder (phase 4) |
|
||||
| `apps/website` | Church Website | Placeholder (phase 5) |
|
||||
| `apps/app` | Church App (PWA) | Placeholder (phase 6) |
|
||||
|
||||
Cross Events (`joshua/hope-events`) moves in as `apps/events` in Events 2.2.0
|
||||
|
||||
@@ -0,0 +1,2 @@
|
||||
# this install's PM2 config (made from ecosystem.config.example.cjs by the crosscode script)
|
||||
/ecosystem.config.cjs
|
||||
@@ -1,5 +1,71 @@
|
||||
# Changelog — Accounts
|
||||
|
||||
## [1.2.0] - 2026-11-19
|
||||
|
||||
Found after a church moved Cross Events' sign-in here without email set up in Accounts: every
|
||||
sign-in that needed an emailed code failed with a 500, and nobody could get in.
|
||||
|
||||
### Fixed
|
||||
|
||||
- **A code that can't be sent no longer fails the sign-in (500).** The page says the church's email
|
||||
isn't working and to tell the office (`CODE_NOT_SENT`, 503). A WhatsApp sign-in code that can't go
|
||||
is sent by email instead (as Cross Events); setting WhatsApp up still needs WhatsApp to work.
|
||||
- **Forgot password** says plainly that email isn't set up (`EMAIL_NOT_READY`, the same for every
|
||||
address) instead of failing.
|
||||
- Setting up two-step sign-in only offers email when email works (an app always does).
|
||||
- `people.ensure` makes the account even when its "choose your password" email can't go, and tells
|
||||
the product (`emailSent: false`).
|
||||
|
||||
### Changed
|
||||
|
||||
- **The sign-in pages look like the church's other sites:** a wash of the church's colour, its logo
|
||||
and name across the top (its first letter on its colour while there's no logo), the form in a card
|
||||
edged in that colour with an icon per step, and a footer (`@crosscode/ui` Shell, Card, Heading,
|
||||
ChurchMark; the account and admin pages get the same frame).
|
||||
- **The church's logo and colours come from Cross Events:** a move fills the logo, colours and name
|
||||
Accounts doesn't have yet (`import.begin` now carries the logo and accent colour), and
|
||||
`church.branding` (contracts 1.9.0) replaces them when an admin asks.
|
||||
|
||||
### Added
|
||||
|
||||
- **`messaging.*` requests** (contracts 1.9.0) for a linked product's sign-in settings: `status`
|
||||
(what can be sent, no secrets), `test` (sends a test email / WhatsApp with the settings given,
|
||||
saves nothing) and `set` (tests, then saves each part only if its test worked). The SMTP password
|
||||
and WAWP token come sealed with the link's secret, are stored encrypted, and `null` keeps the saved one.
|
||||
- Admin → Email and WhatsApp: **Send a test WhatsApp** (to the admin's own phone), next to the test email.
|
||||
- WAWP from the server's `.env` (`WAWP_ACCESS_TOKEN`, `WAWP_INSTANCE_ID`) when the database has
|
||||
none, as Cross Events and as SMTP already did.
|
||||
|
||||
## [1.1.0] - 2026-11-19
|
||||
|
||||
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` 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.
|
||||
- **`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
|
||||
|
||||
@@ -3,6 +3,23 @@
|
||||
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.2.0
|
||||
|
||||
- **Fix:** when the church's email isn't working, signing in tells people so (and to let the office
|
||||
know) instead of showing an error page. Codes by WhatsApp are sent by email if WhatsApp is down.
|
||||
- Email and WhatsApp for sign-in can be set up from Cross Events (Settings → Sign-in), copying its
|
||||
own settings, with a test before they're saved.
|
||||
- Admins can send a test WhatsApp message from Email and WhatsApp.
|
||||
- **A nicer sign-in page** with your church's logo and colours, taken from Cross Events.
|
||||
|
||||
## 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
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "@crosscode/accounts-backend",
|
||||
"version": "1.0.1",
|
||||
"version": "1.2.0",
|
||||
"description": "Cross Code Accounts: the church's sign-in (OpenID Connect provider), account pages API and admin API",
|
||||
"private": true,
|
||||
"type": "module",
|
||||
|
||||
@@ -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;
|
||||
@@ -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 {
|
||||
|
||||
@@ -11,6 +11,7 @@ import { hashToken, randomCode, safeEqual } from '../lib/crypto.js';
|
||||
import { loginEvent } from '../lib/audit.js';
|
||||
import { queueCall } from '../links/deliveries.js';
|
||||
import { currentNoticeVersion } from '../privacy/notice.js';
|
||||
import { SendError } from '../lib/messages.js';
|
||||
|
||||
export const MAX_FAILED_SIGN_INS = 10;
|
||||
export const LOCK_MINUTES = 15;
|
||||
@@ -100,18 +101,33 @@ export function maskedTarget(a: Account, method: 'email' | 'whatsapp'): string {
|
||||
return `${user!.slice(0, 1)}***@${domain}`;
|
||||
}
|
||||
|
||||
/**
|
||||
* Sends a code. 1.2.0: a WhatsApp code that can't go is sent by email instead (as Cross Events), and
|
||||
* when nothing can send it the person is told so (`SendError`, shown on the page) instead of the
|
||||
* sign-in failing.
|
||||
*/
|
||||
export async function sendCode(ctx: Ctx, a: Account, method: 'email' | 'whatsapp', purpose: 'sign_in' | 'verify_email' | 'setup'): Promise<{ codeHash: string; sentTo: string }> {
|
||||
const code = randomCode();
|
||||
const churchName = (await ctx.settings.json<{ name?: string }>('church_profile', {})).name || 'your church';
|
||||
const what = purpose === 'verify_email' ? 'confirm your email address' : 'sign in';
|
||||
const text = `Your code to ${what} at ${churchName} is ${code}. It works for ${CODE_MINUTES} minutes. If you didn't ask for it, you can ignore this message.`;
|
||||
if (method === 'whatsapp') {
|
||||
if (!a.phone) throw new Error('There\'s no phone number on this account.');
|
||||
await ctx.messenger.whatsapp({ to: a.phone, text });
|
||||
} else {
|
||||
await ctx.messenger.email({ to: a.email, subject: `Your code: ${code}`, text });
|
||||
if (method === 'whatsapp' && a.phone) {
|
||||
try {
|
||||
await ctx.messenger.whatsapp({ to: a.phone, text });
|
||||
return { codeHash: hashToken(code), sentTo: maskedTarget(a, 'whatsapp') };
|
||||
} catch (e) {
|
||||
// Setting WhatsApp up has to prove WhatsApp works, so no email instead then.
|
||||
if (purpose !== 'sign_in') throw new SendError('We couldn\'t send a code by WhatsApp. Choose another way to get your codes.', 'CODE_NOT_SENT');
|
||||
console.warn('[codes] WhatsApp failed, trying email:', (e as Error).message);
|
||||
}
|
||||
}
|
||||
return { codeHash: hashToken(code), sentTo: maskedTarget(a, method) };
|
||||
try {
|
||||
await ctx.messenger.email({ to: a.email, subject: `Your code: ${code}`, text });
|
||||
} catch (e) {
|
||||
console.error('[codes] could not send a code:', (e as Error).message);
|
||||
throw new SendError(`We couldn't send your code: ${churchName}'s email isn't working right now. Please let the church office know, and try again later.`, 'CODE_NOT_SENT');
|
||||
}
|
||||
return { codeHash: hashToken(code), sentTo: maskedTarget(a, 'email') };
|
||||
}
|
||||
|
||||
export const codeMatches = (code: unknown, hash: string | null | undefined) =>
|
||||
|
||||
@@ -196,7 +196,24 @@ export function adminRouter(ctx: Ctx, provider: Provider) {
|
||||
r.post('/settings/test-email', limit(5), handle(async (req, res) => {
|
||||
const me = await admin(req, res);
|
||||
const a = await ctx.db.account.findUniqueOrThrow({ where: { id: me.id } });
|
||||
await ctx.messenger.email({ to: a.email, subject: 'Test email from Accounts', text: 'Email from Accounts works.' });
|
||||
try {
|
||||
await ctx.messenger.email({ to: a.email, subject: 'Test email from Accounts', text: 'Email from Accounts works.' });
|
||||
} catch (e) {
|
||||
throw new ApiError(502, 'NOT_SENT', `The test email couldn't be sent: ${(e as Error).message}`);
|
||||
}
|
||||
return { sent: true };
|
||||
}));
|
||||
|
||||
// 1.2.0: as the test email, for WhatsApp (WAWP), to the admin's own phone.
|
||||
r.post('/settings/test-whatsapp', limit(5), handle(async (req, res) => {
|
||||
const me = await admin(req, res);
|
||||
const a = await ctx.db.account.findUniqueOrThrow({ where: { id: me.id } });
|
||||
if (!a.phone) throw new ApiError(400, 'NO_PHONE', 'Add your mobile number on your account page first.');
|
||||
try {
|
||||
await ctx.messenger.whatsapp({ to: a.phone, text: 'WhatsApp from Accounts works.' });
|
||||
} catch (e) {
|
||||
throw new ApiError(502, 'NOT_SENT', `The test message couldn't be sent: ${(e as Error).message}`);
|
||||
}
|
||||
return { sent: true };
|
||||
}));
|
||||
|
||||
|
||||
@@ -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();
|
||||
|
||||
@@ -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,22 +94,28 @@ 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);
|
||||
let sentNow: string | null = null;
|
||||
if ((stage === 'verify_email' || (stage === 'two_factor' && a.twoFactorMethod !== 'totp')) && !pending.codeSentAt) {
|
||||
const method = stage === 'verify_email' ? 'email' : (a.twoFactorMethod as 'email' | 'whatsapp');
|
||||
const sent = await sendCode(ctx, a, method, stage === 'verify_email' ? 'verify_email' : 'sign_in');
|
||||
await save(ctx, pending, { codeHash: sent.codeHash, codeSentAt: ctx.now(), attempts: 0 });
|
||||
sentNow = sent.sentTo;
|
||||
}
|
||||
const extra: Record<string, unknown> = { name: a.name, email: a.email };
|
||||
if (stage === 'verify_email') extra.sentTo = maskedTarget(a, 'email');
|
||||
if (stage === 'two_factor') {
|
||||
extra.method = a.twoFactorMethod;
|
||||
if (a.twoFactorMethod !== 'totp') extra.sentTo = maskedTarget(a, a.twoFactorMethod as 'email' | 'whatsapp');
|
||||
// Where it actually went (a WhatsApp code that couldn't go was sent by email).
|
||||
if (a.twoFactorMethod !== 'totp') extra.sentTo = sentNow ?? maskedTarget(a, a.twoFactorMethod as 'email' | 'whatsapp');
|
||||
}
|
||||
if (stage === 'setup_two_factor') {
|
||||
extra.methods = ['totp', 'email', ...((await ctx.messenger.whatsappReady()) && a.phone ? ['whatsapp'] : [])];
|
||||
// Only the ways that can deliver a code now (1.2.0): an app always works.
|
||||
extra.methods = ['totp', ...((await ctx.messenger.emailReady()) ? ['email'] : []), ...((await ctx.messenger.whatsappReady()) && a.phone ? ['whatsapp'] : [])];
|
||||
extra.why = a.role === 'admin' ? 'admin' : 'product';
|
||||
}
|
||||
if (stage === 'notice') {
|
||||
@@ -209,7 +215,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) {
|
||||
|
||||
@@ -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);
|
||||
@@ -82,6 +88,8 @@ export function interactionRouter(ctx: Ctx, provider: Provider) {
|
||||
// ─── Forgot / reset password ───────────────────────────────────────────────
|
||||
|
||||
r.post('/password/forgot', limit(5), handle(async (req) => {
|
||||
// 1.2.0: without email nobody gets a link; say so (the same answer whoever asks).
|
||||
if (!(await ctx.messenger.emailReady())) throw new ApiError(503, 'EMAIL_NOT_READY', 'Password reset links can\'t be sent right now: the church\'s email isn\'t set up. Please let the church office know.');
|
||||
const email = normaliseEmail(req.body?.email);
|
||||
const a = email ? await ctx.db.account.findUnique({ where: { email } }) : null;
|
||||
// The same answer either way, so nobody can find out who has an account (Events 1.51.17).
|
||||
@@ -104,12 +112,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;
|
||||
|
||||
@@ -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 };
|
||||
},
|
||||
},
|
||||
];
|
||||
|
||||
@@ -20,6 +20,8 @@ export type Config = {
|
||||
hubAdminEmail: string | null;
|
||||
timezone: string;
|
||||
smtp: { host: string; port: number; user: string; pass: string; from: string; secure: boolean } | null;
|
||||
/** 1.2.0: WAWP from the .env when the database has none (as Cross Events). */
|
||||
wawp: { accessToken: string; instanceId: string } | null;
|
||||
/** Local testing only: linked products on http or private addresses. */
|
||||
allowPrivateLinks: boolean;
|
||||
jobsEnabled: boolean;
|
||||
@@ -67,6 +69,7 @@ export function loadConfig(env: Record<string, string | undefined> = process.env
|
||||
smtp: env.SMTP_HOST
|
||||
? { host: env.SMTP_HOST, port: Number(env.SMTP_PORT || 587), user: env.SMTP_USER || '', pass: env.SMTP_PASS || '', from: env.SMTP_FROM || env.SMTP_USER || '', secure: bool(env.SMTP_SECURE, Number(env.SMTP_PORT) === 465) }
|
||||
: null,
|
||||
wawp: env.WAWP_ACCESS_TOKEN && env.WAWP_INSTANCE_ID ? { accessToken: env.WAWP_ACCESS_TOKEN, instanceId: env.WAWP_INSTANCE_ID } : null,
|
||||
allowPrivateLinks: bool(env.LINKS_ALLOW_PRIVATE, false),
|
||||
jobsEnabled: bool(env.JOBS_ENABLED, true),
|
||||
};
|
||||
|
||||
@@ -8,11 +8,49 @@ import type { Ctx } from '../context.js';
|
||||
export type Email = { to: string; subject: string; text: string };
|
||||
export type WhatsApp = { to: string; text: string };
|
||||
|
||||
/** SMTP settings to try before saving them (1.2.0), as kept in `smtp_*`. */
|
||||
export type SmtpTry = { host: string; port: number; secure: boolean; user: string; pass: string; from: string };
|
||||
/** WAWP settings to try before saving them (1.2.0). */
|
||||
export type WawpTry = { accessToken: string; instanceId: string };
|
||||
|
||||
export interface Messenger {
|
||||
email(msg: Email): Promise<void>;
|
||||
whatsapp(msg: WhatsApp): Promise<void>;
|
||||
/** Whether email is set up (sign-in codes, password links and new accounts need it). */
|
||||
emailReady(): Promise<boolean>;
|
||||
/** Whether WhatsApp is set up, so it's offered as a 2FA method. */
|
||||
whatsappReady(): Promise<boolean>;
|
||||
/** Sends one email with settings that aren't saved (a test before saving them). Throws why it failed. */
|
||||
emailWith(settings: SmtpTry, msg: Email): Promise<void>;
|
||||
/** Sends one WhatsApp message with settings that aren't saved. Throws why it failed. */
|
||||
whatsappWith(settings: WawpTry, msg: WhatsApp): Promise<void>;
|
||||
}
|
||||
|
||||
/** Thrown when a message can't be sent: the sign-in pages show it instead of failing. */
|
||||
export class SendError extends Error {
|
||||
status = 503;
|
||||
constructor(message: string, public code = 'NOT_SENT') {
|
||||
super(message);
|
||||
}
|
||||
}
|
||||
|
||||
function transportFor(s: SmtpTry) {
|
||||
return nodemailer.createTransport({
|
||||
host: s.host, port: s.port, secure: s.secure, auth: s.user ? { user: s.user, pass: s.pass } : undefined,
|
||||
connectionTimeout: 15000, greetingTimeout: 15000, socketTimeout: 20000,
|
||||
});
|
||||
}
|
||||
|
||||
async function wawpSend(s: WawpTry, msg: WhatsApp) {
|
||||
const number = waNumber(msg.to);
|
||||
if (!number) throw new Error('That isn\'t a WhatsApp number.');
|
||||
const res = await fetch('https://api.wawp.net/v2/send/text', {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify({ access_token: s.accessToken, instance_id: s.instanceId, chatId: `${number}@c.us`, message: msg.text }),
|
||||
signal: AbortSignal.timeout(15000),
|
||||
});
|
||||
if (!res.ok) throw new Error(`WhatsApp couldn't send the message (${res.status}).`);
|
||||
}
|
||||
|
||||
/** 0821234567 / +27 82 123 4567 → 27821234567 (South African mobiles; others as given, digits only). */
|
||||
@@ -52,23 +90,33 @@ export class LiveMessenger implements Messenger {
|
||||
await smtp.transport.sendMail({ from: church ? `"${church.replace(/"/g, '')}" <${smtp.from}>` : smtp.from, to: msg.to, subject: msg.subject, text: msg.text });
|
||||
}
|
||||
|
||||
async emailReady(): Promise<boolean> {
|
||||
return !!(await this.smtp());
|
||||
}
|
||||
|
||||
private async wawp(): Promise<WawpTry | null> {
|
||||
const accessToken = (await this.ctx.settings.get('wawp_access_token')) || this.ctx.config.wawp?.accessToken;
|
||||
const instanceId = (await this.ctx.settings.get('wawp_instance_id')) || this.ctx.config.wawp?.instanceId;
|
||||
return accessToken && instanceId ? { accessToken, instanceId } : null;
|
||||
}
|
||||
|
||||
async whatsappReady(): Promise<boolean> {
|
||||
return !!((await this.ctx.settings.get('wawp_access_token')) && (await this.ctx.settings.get('wawp_instance_id')));
|
||||
return !!(await this.wawp());
|
||||
}
|
||||
|
||||
async whatsapp(msg: WhatsApp): Promise<void> {
|
||||
const token = await this.ctx.settings.get('wawp_access_token');
|
||||
const instance = await this.ctx.settings.get('wawp_instance_id');
|
||||
const number = waNumber(msg.to);
|
||||
if (!token || !instance) throw new Error('WhatsApp isn\'t set up.');
|
||||
if (!number) throw new Error('That isn\'t a WhatsApp number.');
|
||||
const res = await fetch('https://api.wawp.net/v2/send/text', {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify({ access_token: token, instance_id: instance, chatId: `${number}@c.us`, message: msg.text }),
|
||||
signal: AbortSignal.timeout(15000),
|
||||
});
|
||||
if (!res.ok) throw new Error(`WhatsApp couldn't send the message (${res.status}).`);
|
||||
const s = await this.wawp();
|
||||
if (!s) throw new Error('WhatsApp isn\'t set up.');
|
||||
await wawpSend(s, msg);
|
||||
}
|
||||
|
||||
async emailWith(settings: SmtpTry, msg: Email): Promise<void> {
|
||||
const church = (await this.ctx.settings.json<{ name?: string }>('church_profile', {})).name;
|
||||
await transportFor(settings).sendMail({ from: church ? `"${church.replace(/"/g, '')}" <${settings.from}>` : settings.from, to: msg.to, subject: msg.subject, text: msg.text });
|
||||
}
|
||||
|
||||
async whatsappWith(settings: WawpTry, msg: WhatsApp): Promise<void> {
|
||||
await wawpSend(settings, msg);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -76,9 +124,30 @@ export class MemoryMessenger implements Messenger {
|
||||
emails: Email[] = [];
|
||||
whatsapps: WhatsApp[] = [];
|
||||
whatsappOn = false;
|
||||
async email(msg: Email) { this.emails.push(msg); }
|
||||
async whatsapp(msg: WhatsApp) { this.whatsapps.push(msg); }
|
||||
/** Tests: false makes email fail as an unset SMTP does in production. */
|
||||
emailOn = true;
|
||||
/** Tests: settings tried with emailWith / whatsappWith, and a host that fails. */
|
||||
tried: { kind: 'email' | 'whatsapp'; settings: SmtpTry | WawpTry; to: string }[] = [];
|
||||
failHost: string | null = null;
|
||||
async email(msg: Email) {
|
||||
if (!this.emailOn) throw new Error('Email isn\'t set up (Admin → Email and WhatsApp).');
|
||||
this.emails.push(msg);
|
||||
}
|
||||
async whatsapp(msg: WhatsApp) {
|
||||
if (!this.whatsappOn) throw new Error('WhatsApp isn\'t set up.');
|
||||
this.whatsapps.push(msg);
|
||||
}
|
||||
async emailReady() { return this.emailOn; }
|
||||
async whatsappReady() { return this.whatsappOn; }
|
||||
async emailWith(settings: SmtpTry, msg: Email) {
|
||||
this.tried.push({ kind: 'email', settings, to: msg.to });
|
||||
if (settings.host === this.failHost) throw new Error(`connect ECONNREFUSED ${settings.host}:${settings.port}`);
|
||||
this.emails.push(msg);
|
||||
}
|
||||
async whatsappWith(settings: WawpTry, msg: WhatsApp) {
|
||||
this.tried.push({ kind: 'whatsapp', settings, to: msg.to });
|
||||
this.whatsapps.push(msg);
|
||||
}
|
||||
/** The last 6-digit code sent to `to` (tests). */
|
||||
lastCode(to: string): string | null {
|
||||
const all = [...this.emails.filter((e) => e.to === to).map((e) => e.text), ...this.whatsapps.filter((w) => w.to === to).map((w) => w.text)];
|
||||
|
||||
@@ -0,0 +1,417 @@
|
||||
/**
|
||||
* 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 ChurchLook, type IdentityRequest, type ImportPerson, type ImportResult,
|
||||
} from '@crosscode/contracts';
|
||||
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';
|
||||
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 = <T extends object>(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<ImportResult> {
|
||||
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<object> {
|
||||
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 } });
|
||||
}
|
||||
}
|
||||
await applyLook(ctx, r.church, false);
|
||||
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<string>();
|
||||
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);
|
||||
// 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: 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 } });
|
||||
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';
|
||||
// 1.2.0: the account stands even when the email can't go (they can use "Forgot your password?"
|
||||
// once email works); the product is told.
|
||||
let emailSent = true;
|
||||
try {
|
||||
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.`,
|
||||
});
|
||||
} catch (e) {
|
||||
emailSent = false;
|
||||
console.warn('[people.ensure] the "choose your password" email could not be sent:', (e as Error).message);
|
||||
}
|
||||
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, { emailSent });
|
||||
return reply({ sub: a.id, created: true, emailSent });
|
||||
}
|
||||
case 'people.update': {
|
||||
const a = await knownAccount(ctx, link, r.sub);
|
||||
const data: Record<string, unknown> = {};
|
||||
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 'church.branding': {
|
||||
const changed = await applyLook(ctx, r.church, r.overwrite);
|
||||
await logRequest(ctx, link, r, 'church_look_from_product', null, req, { changed, overwrite: r.overwrite });
|
||||
return reply({ ok: true as const });
|
||||
}
|
||||
case 'messaging.status':
|
||||
return reply(await messagingStatus(ctx));
|
||||
case 'messaging.test':
|
||||
case 'messaging.set': {
|
||||
const save = r.type === 'messaging.set';
|
||||
const church = (await ctx.settings.json<{ name?: string }>('church_profile', {})).name || 'your church';
|
||||
let email: { ok: boolean; error: string | null; saved: boolean } | null = null;
|
||||
let whatsapp: { ok: boolean; error: string | null; saved: boolean } | null = null;
|
||||
if (r.email) {
|
||||
const s = r.email.settings;
|
||||
const pass = s.pass === null ? ((await ctx.settings.get('smtp_pass')) ?? '') : opened(secret, s.pass, 'SMTP password');
|
||||
const tryWith = { host: s.host, port: s.port, secure: s.secure, user: s.user, pass: pass ?? '', from: s.from };
|
||||
try {
|
||||
await ctx.messenger.emailWith(tryWith, { to: r.email.to, subject: `Test email from ${church}'s sign-in`, text: `This is a test from ${church}'s sign-in (Accounts), sent from ${link.product === 'events' ? 'Cross Events' : link.product}. Email works: sign-in codes and password links can be sent.` });
|
||||
email = { ok: true, error: null, saved: false };
|
||||
if (save) {
|
||||
await ctx.settings.setMany({ smtp_host: s.host, smtp_port: String(s.port), smtp_secure: String(s.secure), smtp_user: s.user, smtp_from: s.from, ...(s.pass === null ? {} : { smtp_pass: pass }) });
|
||||
email.saved = true;
|
||||
}
|
||||
} catch (e) {
|
||||
email = { ok: false, error: String((e as Error).message || e).slice(0, 500), saved: false };
|
||||
}
|
||||
}
|
||||
if (r.whatsapp) {
|
||||
const s = r.whatsapp.settings;
|
||||
const token = s.accessToken === null ? ((await ctx.settings.get('wawp_access_token')) ?? '') : opened(secret, s.accessToken, 'WAWP access token');
|
||||
try {
|
||||
if (!token) throw new Error('Give the WAWP access token.');
|
||||
await ctx.messenger.whatsappWith({ accessToken: token, instanceId: s.instanceId }, { to: r.whatsapp.to, text: `This is a test from ${church}'s sign-in. WhatsApp works: sign-in codes can be sent.` });
|
||||
whatsapp = { ok: true, error: null, saved: false };
|
||||
if (save) {
|
||||
await ctx.settings.setMany({ wawp_instance_id: s.instanceId, ...(s.accessToken === null ? {} : { wawp_access_token: token }) });
|
||||
whatsapp.saved = true;
|
||||
}
|
||||
} catch (e) {
|
||||
whatsapp = { ok: false, error: String((e as Error).message || e).slice(0, 500), saved: false };
|
||||
}
|
||||
}
|
||||
await logRequest(ctx, link, r, save ? 'messaging_set_by_product' : 'messaging_tested_by_product', null, req, { email: email && { ok: email.ok, saved: email.saved }, whatsapp: whatsapp && { ok: whatsapp.ok, saved: whatsapp.saved } });
|
||||
const status = await messagingStatus(ctx);
|
||||
return reply({ email, whatsapp, status: { email: status.email, whatsapp: status.whatsapp } });
|
||||
}
|
||||
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;
|
||||
}
|
||||
|
||||
/**
|
||||
* The church's look on Accounts' pages from a product's (1.9.0): its name, logo and colours.
|
||||
* `overwrite: false` (a move) fills only what's empty; `true` (an admin's button) replaces them.
|
||||
* Returns the fields changed.
|
||||
*/
|
||||
async function applyLook(ctx: Ctx, look: ChurchLook, overwrite: boolean): Promise<string[]> {
|
||||
type Stored = Record<string, unknown> & { name?: string; branding?: { logoUrl?: string | null; iconUrl?: string | null; colours?: { primary?: string; accent?: string | null } } };
|
||||
const stored = await ctx.settings.json<Stored>('church_profile', {});
|
||||
const branding = { logoUrl: null as string | null, iconUrl: null as string | null, ...(stored.branding ?? {}), colours: { primary: '#1f4e79', accent: '#f2a900', ...(stored.branding?.colours ?? {}) } };
|
||||
const changed: string[] = [];
|
||||
const take = (has: unknown, value: unknown) => value !== null && value !== undefined && value !== '' && (overwrite || !has);
|
||||
const next: Stored = { ...stored };
|
||||
if (take(stored.name, look.name)) { next.name = look.name!; changed.push('name'); }
|
||||
if (take(stored.branding?.logoUrl, look.logoUrl)) { branding.logoUrl = look.logoUrl!; changed.push('logo'); }
|
||||
if (take(stored.branding?.colours?.primary, look.primaryColour)) { branding.colours.primary = look.primaryColour!; changed.push('primary colour'); }
|
||||
if (take(stored.branding?.colours?.accent && stored.branding?.colours?.accent !== '#f2a900', look.accentColour)) { branding.colours.accent = look.accentColour!; changed.push('accent colour'); }
|
||||
if (!changed.length) return changed;
|
||||
next.branding = branding;
|
||||
next.updatedAt = ctx.now().toISOString();
|
||||
await ctx.settings.set('church_profile', JSON.stringify(next));
|
||||
return changed;
|
||||
}
|
||||
|
||||
/** What can be sent now (no secrets), for a product's sign-in settings page. */
|
||||
async function messagingStatus(ctx: Ctx) {
|
||||
const emailReady = await ctx.messenger.emailReady();
|
||||
return {
|
||||
email: { ready: emailReady, host: emailReady ? ((await ctx.settings.get('smtp_host')) || ctx.config.smtp?.host || null) : null, from: emailReady ? ((await ctx.settings.get('smtp_from')) || ctx.config.smtp?.from || null) : null },
|
||||
whatsapp: { ready: await ctx.messenger.whatsappReady(), instanceId: (await ctx.settings.get('wawp_instance_id')) || ctx.config.wawp?.instanceId || null },
|
||||
};
|
||||
}
|
||||
|
||||
/** 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();
|
||||
@@ -68,6 +68,8 @@ export async function createProvider(ctx: Ctx): Promise<Provider> {
|
||||
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 } });
|
||||
|
||||
@@ -0,0 +1,125 @@
|
||||
// Accounts 1.2.0: sign-in never fails with a 500 when a code can't be sent, WhatsApp codes fall back
|
||||
// to email, and a linked product can check, test and set Accounts' email and WhatsApp
|
||||
// (crosscode.identity-request/1 messaging.*, contracts 1.9.0).
|
||||
import assert from 'node:assert/strict';
|
||||
import crypto from 'node:crypto';
|
||||
import { after, before, beforeEach, describe, test } from 'node:test';
|
||||
import { ACCOUNTS_REQUEST_PATH, IDENTITY_REQUEST_SCHEMA } from '@crosscode/contracts';
|
||||
import { ed25519PublicToPem, generateEd25519, LINK_HEADERS, newLinkSecret, sealLinkValue, signedHeaders } from '@crosscode/contracts/signing';
|
||||
import { Browser, startHarness, type Harness } from './support/harness.js';
|
||||
import type { MemoryMessenger } from '../src/lib/messages.js';
|
||||
|
||||
const EVENTS_ID = '6d1f0b2c-8a3e-4c5d-9e7f-1a2b3c4d5e6f';
|
||||
let h: Harness;
|
||||
let secret: string;
|
||||
let messenger: MemoryMessenger;
|
||||
|
||||
before(async () => {
|
||||
h = await startHarness();
|
||||
messenger = h.messenger as MemoryMessenger;
|
||||
secret = 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(secret), connectedAt: new Date() } });
|
||||
});
|
||||
after(async () => { await h.close(); });
|
||||
beforeEach(() => { messenger.emailOn = true; messenger.whatsappOn = false; messenger.failHost = null; });
|
||||
|
||||
async function ask(body: Record<string, unknown>) {
|
||||
const raw = JSON.stringify({ schema: IDENTITY_REQUEST_SCHEMA, requestId: crypto.randomUUID(), actor: null, ...body });
|
||||
const res = await fetch(`${h.publicUrl}${ACCOUNTS_REQUEST_PATH}`, { method: 'POST', body: raw, headers: { 'content-type': 'application/json', ...signedHeaders(LINK_HEADERS, { senderId: EVENTS_ID, secret, rawBody: raw }) } });
|
||||
return { status: res.status, body: (await res.json()) as Record<string, unknown> };
|
||||
}
|
||||
|
||||
const smtp = (over: Record<string, unknown> = {}) => ({ host: 'smtp.hope.test', port: 587, secure: false, user: 'events@hope.test', pass: sealLinkValue(secret, 'mail-pass'), from: 'events@hope.test', ...over });
|
||||
|
||||
describe('a code that can\'t be sent', () => {
|
||||
test('without email, the page says so (503 with a message), never a 500', async () => {
|
||||
messenger.emailOn = false;
|
||||
await h.makeAccount({ email: 'unverified@hope.test', password: 'Correct-horse-1', emailVerified: false });
|
||||
const r = await h.signIn(new Browser(), 'unverified@hope.test', 'Correct-horse-1');
|
||||
// The password step answers with the error of the next step: the email code couldn't go.
|
||||
assert.ok('pending' in r);
|
||||
assert.equal(r.pending.error && (r.pending.error as { code: string }).code, 'CODE_NOT_SENT', JSON.stringify(r.pending));
|
||||
});
|
||||
|
||||
test('a WhatsApp code that can\'t go is sent by email', async () => {
|
||||
await h.makeAccount({ email: 'wa@hope.test', password: 'Correct-horse-1', phone: '+27821230000', twoFactorMethod: 'whatsapp' });
|
||||
const r = await h.signIn(new Browser(), 'wa@hope.test', 'Correct-horse-1');
|
||||
assert.ok('pending' in r);
|
||||
assert.equal(r.pending.stage, 'two_factor', JSON.stringify(r.pending));
|
||||
assert.match(String(r.pending.sentTo), /@hope\.test$/);
|
||||
assert.ok(messenger.lastCode('wa@hope.test'));
|
||||
});
|
||||
|
||||
test('forgot password says email isn\'t set up, for any address', async () => {
|
||||
messenger.emailOn = false;
|
||||
const res = await h.api(new Browser(), 'POST', '/api/v2/password/forgot', { email: 'nobody@hope.test' });
|
||||
assert.equal(res.status, 503);
|
||||
assert.equal((res.body.error as { code: string }).code, 'EMAIL_NOT_READY');
|
||||
});
|
||||
});
|
||||
|
||||
describe('messaging.* from a product', () => {
|
||||
test('status says what can be sent, without secrets', async () => {
|
||||
messenger.emailOn = false;
|
||||
const r = await ask({ type: 'messaging.status' });
|
||||
assert.equal(r.status, 200, JSON.stringify(r.body));
|
||||
assert.deepEqual(r.body.email, { ready: false, host: null, from: null });
|
||||
assert.equal(JSON.stringify(r.body).includes('pass'), false);
|
||||
});
|
||||
|
||||
test('test sends with the settings given and saves nothing; a failure says why', async () => {
|
||||
const ok = await ask({ type: 'messaging.test', email: { settings: smtp(), to: 'office@hope.test' } });
|
||||
assert.deepEqual(ok.body.email, { ok: true, error: null, saved: false });
|
||||
assert.deepEqual(messenger.tried.at(-1), { kind: 'email', settings: { host: 'smtp.hope.test', port: 587, secure: false, user: 'events@hope.test', pass: 'mail-pass', from: 'events@hope.test' }, to: 'office@hope.test' });
|
||||
assert.equal(await h.ctx.settings.get('smtp_host'), null);
|
||||
messenger.failHost = 'bad.hope.test';
|
||||
const bad = await ask({ type: 'messaging.test', email: { settings: smtp({ host: 'bad.hope.test' }), to: 'office@hope.test' } });
|
||||
assert.equal((bad.body.email as { ok: boolean }).ok, false);
|
||||
assert.match(String((bad.body.email as { error: string }).error), /ECONNREFUSED/);
|
||||
});
|
||||
|
||||
test('set saves only what worked, with the password encrypted; null keeps the saved password', async () => {
|
||||
messenger.failHost = 'bad.hope.test';
|
||||
const failed = await ask({ type: 'messaging.set', email: { settings: smtp({ host: 'bad.hope.test' }), to: 'office@hope.test' } });
|
||||
assert.equal((failed.body.email as { saved: boolean }).saved, false);
|
||||
assert.equal(await h.ctx.settings.get('smtp_host'), null);
|
||||
|
||||
const saved = await ask({ type: 'messaging.set', email: { settings: smtp(), to: 'office@hope.test' }, whatsapp: { settings: { accessToken: sealLinkValue(secret, 'wawp-token'), instanceId: 'INST1' }, to: '+27821234567' } });
|
||||
assert.deepEqual([saved.body.email, saved.body.whatsapp].map((x) => (x as { saved: boolean }).saved), [true, true]);
|
||||
assert.equal(await h.ctx.settings.get('smtp_pass'), 'mail-pass');
|
||||
const row = await h.db.appSetting.findUnique({ where: { key: 'smtp_pass' } });
|
||||
assert.notEqual(row!.value, 'mail-pass', 'encrypted at rest');
|
||||
assert.equal(await h.ctx.settings.get('wawp_instance_id'), 'INST1');
|
||||
|
||||
const kept = await ask({ type: 'messaging.set', email: { settings: smtp({ pass: null, from: 'office@hope.test' }), to: 'office@hope.test' } });
|
||||
assert.equal((kept.body.email as { saved: boolean }).saved, true);
|
||||
assert.equal(await h.ctx.settings.get('smtp_pass'), 'mail-pass');
|
||||
assert.equal(await h.ctx.settings.get('smtp_from'), 'office@hope.test');
|
||||
});
|
||||
|
||||
test('people.ensure still makes the account when its email can\'t go, and says so', async () => {
|
||||
messenger.emailOn = false;
|
||||
const r = await ask({ type: 'people.ensure', name: 'No Mail', email: 'nomail@hope.test', phone: null, returnUrl: 'https://events.hope.test/' });
|
||||
assert.equal(r.status, 200, JSON.stringify(r.body));
|
||||
assert.equal(r.body.created, true);
|
||||
assert.equal(r.body.emailSent, false);
|
||||
});
|
||||
});
|
||||
|
||||
describe('the church\'s look from a product (1.9.0)', () => {
|
||||
test('a move fills only what\'s empty; the button replaces it', async () => {
|
||||
await h.ctx.settings.set('church_profile', JSON.stringify({ name: 'Hope Family Church', shortName: 'Hope' }));
|
||||
const look = { name: 'Other Name', primaryColour: '#123456', accentColour: '#abcdef', logoUrl: 'https://events.hope.test/uploads/logo.png' };
|
||||
assert.equal((await ask({ type: 'church.branding', church: look, overwrite: false })).status, 200);
|
||||
const filled = await h.ctx.settings.json<{ name: string; branding: { logoUrl: string; colours: { primary: string; accent: string } } }>('church_profile', {} as never);
|
||||
assert.equal(filled.name, 'Hope Family Church', 'kept');
|
||||
assert.equal(filled.branding.logoUrl, 'https://events.hope.test/uploads/logo.png');
|
||||
assert.equal(filled.branding.colours.primary, '#123456');
|
||||
await ask({ type: 'church.branding', church: { ...look, primaryColour: '#654321', logoUrl: 'https://events.hope.test/new.png' }, overwrite: true });
|
||||
const replaced = await h.ctx.settings.json<{ name: string; branding: { logoUrl: string; colours: { primary: string } } }>('church_profile', {} as never);
|
||||
assert.deepEqual([replaced.name, replaced.branding.logoUrl, replaced.branding.colours.primary], ['Other Name', 'https://events.hope.test/new.png', '#654321']);
|
||||
// The sign-in pages get it.
|
||||
const b = await h.api(new Browser(), 'GET', '/api/v2/branding');
|
||||
assert.equal(b.body.logoUrl, 'https://events.hope.test/new.png');
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,192 @@
|
||||
// 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, LINK_HEADERS, newLinkSecret, sealLinkValue, signedHeaders } from '@crosscode/contracts/signing';
|
||||
import { Browser, PRODUCT_ID, startHarness, type Harness } from './support/harness.js';
|
||||
import { codeAt, generateSecret } from '../src/lib/totp.js';
|
||||
|
||||
const EVENTS_ID = '6d1f0b2c-8a3e-4c5d-9e7f-1a2b3c4d5e6f';
|
||||
let h: Harness;
|
||||
let eventsSecret: string;
|
||||
|
||||
before(async () => {
|
||||
h = await startHarness();
|
||||
eventsSecret = newLinkSecret();
|
||||
await h.db.productLink.create({
|
||||
data: { installId: EVENTS_ID, product: 'events', url: 'https://events.hope.test', publicKey: ed25519PublicToPem(generateEd25519().publicKey), secret: h.ctx.secrets.encrypt(eventsSecret), connectedAt: new Date() },
|
||||
});
|
||||
});
|
||||
after(async () => { await h.close(); });
|
||||
|
||||
/** Sends a request as a product (Events unless said otherwise). */
|
||||
async function ask(body: Record<string, unknown>, opts: { from?: string; secret?: string; requestId?: string } = {}) {
|
||||
const raw = JSON.stringify({ schema: IDENTITY_REQUEST_SCHEMA, requestId: opts.requestId ?? crypto.randomUUID(), actor: null, ...body });
|
||||
const headers = signedHeaders(LINK_HEADERS, { senderId: opts.from ?? EVENTS_ID, secret: opts.secret ?? eventsSecret, rawBody: raw });
|
||||
const res = await fetch(`${h.publicUrl}${ACCOUNTS_REQUEST_PATH}`, { method: 'POST', body: raw, headers: { 'content-type': 'application/json', ...headers } });
|
||||
return { status: res.status, body: (await res.json()) as Record<string, unknown> };
|
||||
}
|
||||
|
||||
function person(over: Partial<ImportPerson> = {}): ImportPerson {
|
||||
return {
|
||||
id: crypto.randomUUID(), name: 'Moved Person', email: `${crypto.randomUUID().slice(0, 8)}@hope.test`, emailVerified: true, phone: null,
|
||||
passwordHash: null, twoFactor: null, totpSecret: null, totpLastStep: null, failedSignIns: 0, lockedUntil: null,
|
||||
news: { email: true, whatsapp: false }, newsAskedAt: '2026-01-01T00:00:00.000Z', noticeVersionAccepted: 1,
|
||||
noticeAcceptances: [{ version: 1, acceptedAt: '2026-01-01T00:00:00.000Z' }], consentChanges: [{ channel: 'email', granted: true, at: '2026-01-01T00:00:00.000Z' }],
|
||||
lastSignInAt: '2026-11-01T00:00:00.000Z', status: 'active', admin: false, createdAt: '2025-01-01T00:00:00.000Z', ...over,
|
||||
};
|
||||
}
|
||||
|
||||
const begin = (check = false) => ask({ type: 'import.begin', check, notices: [], church: { name: null, primaryColour: null } });
|
||||
|
||||
describe('moving Cross Events\' users in', () => {
|
||||
test('a batch is refused before import.begin, and a check writes nothing', async () => {
|
||||
const p = person();
|
||||
const refused = await ask({ type: 'import.batch', check: false, people: [p] });
|
||||
assert.equal(refused.status, 409);
|
||||
assert.equal(refused.body.code, 'NOT_MOVING');
|
||||
const check = await ask({ type: 'import.batch', check: true, people: [p] });
|
||||
assert.equal(check.status, 200, JSON.stringify(check.body));
|
||||
assert.equal((check.body.results as { outcome: string }[])[0]!.outcome, 'created');
|
||||
assert.equal(await h.db.account.findUnique({ where: { id: p.id } }), null);
|
||||
});
|
||||
|
||||
test('people sign in with their old bcrypt password and authenticator app, then get new recovery codes', async () => {
|
||||
const totp = generateSecret();
|
||||
const thandi = person({ email: 'Thandi.Moved@Hope.test', passwordHash: sealLinkValue(eventsSecret, await bcrypt.hash('Old-events-pass1', 4)), twoFactor: 'totp', totpSecret: sealLinkValue(eventsSecret, totp), totpLastStep: 1 });
|
||||
const sipho = person({ email: 'sipho.moved@hope.test', passwordHash: sealLinkValue(eventsSecret, await bcrypt.hash('Sipho-pass-123', 4)) });
|
||||
assert.equal((await begin()).status, 200);
|
||||
const batch = await ask({ type: 'import.batch', check: false, people: [thandi, sipho] });
|
||||
assert.equal(batch.status, 200, JSON.stringify(batch.body));
|
||||
assert.deepEqual((batch.body.results as { outcome: string }[]).map((r) => r.outcome), ['created', 'created']);
|
||||
|
||||
// The sub is Events' user id; the secret is stored encrypted with Accounts' own key.
|
||||
const a = (await h.db.account.findUnique({ where: { id: thandi.id } }))!;
|
||||
assert.equal(a.email, 'thandi.moved@hope.test');
|
||||
assert.notEqual(a.totpSecret, totp);
|
||||
assert.equal(a.recoveryCodesNeeded, true);
|
||||
assert.equal((await h.db.consentChange.findMany({ where: { accountId: thandi.id } }))[0]!.source, 'events_import');
|
||||
|
||||
const browser = new Browser();
|
||||
const r = await h.signIn(browser, 'thandi.moved@hope.test', 'Old-events-pass1', '/events/camp/register');
|
||||
assert.ok('pending' in r, 'asks for the authenticator');
|
||||
assert.equal(r.pending.stage, 'two_factor');
|
||||
const done = await h.api(browser, 'POST', `/api/v2/interaction/${r.uid}/two-factor`, { code: codeAt(totp, Math.floor(Date.now() / 30000)) });
|
||||
assert.equal(done.status, 200, JSON.stringify(done.body));
|
||||
assert.equal((done.body.recoveryCodes as string[]).length, 10, 'new recovery codes, shown once');
|
||||
assert.equal((await h.db.account.findUnique({ where: { id: thandi.id } }))!.recoveryCodesNeeded, false);
|
||||
const back = await browser.follow(done.body.redirectTo as string, (u) => u.pathname === '/api/auth/callback');
|
||||
const signed = await h.finishSignIn(back.url, r.started);
|
||||
assert.equal(signed.claims.sub, thandi.id);
|
||||
assert.equal(signed.returnTo, '/events/camp/register');
|
||||
// bcrypt is replaced with Argon2id at the first sign-in.
|
||||
assert.match(String((await h.db.account.findUnique({ where: { id: thandi.id } }))!.passwordHash), /^\$argon2id\$/);
|
||||
|
||||
// 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);
|
||||
});
|
||||
|
||||
test('an email that already has an account is linked, not overwritten; a repeat updates', async () => {
|
||||
const existing = await h.makeAccount({ email: 'already@hope.test', password: 'Accounts-pass-1' });
|
||||
await begin();
|
||||
const dup = person({ email: 'ALREADY@hope.test', passwordHash: sealLinkValue(eventsSecret, await bcrypt.hash('Events-pass-99', 4)) });
|
||||
const again = person({ name: 'Before' });
|
||||
const first = await ask({ type: 'import.batch', check: false, people: [dup, again] });
|
||||
const [linked, created] = first.body.results as { outcome: string; sub: string }[];
|
||||
assert.equal(linked!.outcome, 'linked');
|
||||
assert.equal(linked!.sub, existing.id);
|
||||
assert.equal(created!.outcome, 'created');
|
||||
const still = (await h.db.account.findUnique({ where: { id: existing.id as string } }))!;
|
||||
assert.equal(still.passwordHash, existing.passwordHash, 'the Accounts password stays');
|
||||
|
||||
const repeat = await ask({ type: 'import.batch', check: false, people: [{ ...again, name: 'After' }] });
|
||||
assert.equal((repeat.body.results as { outcome: string }[])[0]!.outcome, 'updated');
|
||||
assert.equal((await h.db.account.findUnique({ where: { id: again.id } }))!.name, 'After');
|
||||
await ask({ type: 'import.abort' });
|
||||
});
|
||||
|
||||
test('a value sealed with another secret, a duplicate email, and a product that isn\'t Events are refused', async () => {
|
||||
await begin();
|
||||
const bad = person({ passwordHash: sealLinkValue(newLinkSecret(), '$2b$04$abc') });
|
||||
assert.equal((await ask({ type: 'import.batch', check: false, people: [bad] })).status, 400);
|
||||
const twice = person({ email: 'twice@hope.test' });
|
||||
const res = await ask({ type: 'import.batch', check: false, people: [twice, person({ email: 'twice@hope.test' })] });
|
||||
assert.deepEqual((res.body.results as { outcome: string }[]).map((r) => r.outcome), ['created', 'refused']);
|
||||
const website = await ask({ type: 'import.begin', check: false, notices: [], church: { name: null, primaryColour: null } }, { from: PRODUCT_ID, secret: h.linkSecret });
|
||||
assert.equal(website.body.code, 'WRONG_PRODUCT');
|
||||
await ask({ type: 'import.abort' });
|
||||
});
|
||||
|
||||
test('Events\' notice versions are taken when Accounts has none, and the church gets its name', async () => {
|
||||
const fresh = await startHarness();
|
||||
const secret = newLinkSecret();
|
||||
await fresh.db.productLink.create({ data: { installId: EVENTS_ID, product: 'events', url: 'https://events.hope.test', publicKey: 'x', secret: fresh.ctx.secrets.encrypt(secret), connectedAt: new Date() } });
|
||||
await fresh.ctx.settings.set('church_profile', '{}');
|
||||
const raw = JSON.stringify({ schema: IDENTITY_REQUEST_SCHEMA, requestId: crypto.randomUUID(), actor: null, type: 'import.begin', check: false, church: { name: 'Grace Church', primaryColour: '#123456' }, notices: [{ version: 2, title: 'Our notice', body: 'How we use it.', publishedAt: '2026-02-01T00:00:00.000Z' }] });
|
||||
const res = await fetch(`${fresh.publicUrl}${ACCOUNTS_REQUEST_PATH}`, { method: 'POST', body: raw, headers: { 'content-type': 'application/json', ...signedHeaders(LINK_HEADERS, { senderId: EVENTS_ID, secret, rawBody: raw }) } });
|
||||
const body = (await res.json()) as Record<string, unknown>;
|
||||
assert.equal(body.noticesTaken, true, JSON.stringify(body));
|
||||
assert.equal((await fresh.db.privacyNotice.findUnique({ where: { version: 2 } }))!.title, 'Our notice');
|
||||
const profile = await fresh.ctx.settings.json<{ name: string; branding: { colours: { primary: string } } }>('church_profile', {} as never);
|
||||
assert.equal(profile.name, 'Grace Church');
|
||||
assert.equal(profile.branding.colours.primary, '#123456');
|
||||
await fresh.close();
|
||||
});
|
||||
});
|
||||
|
||||
describe('people.* from a product', () => {
|
||||
test('people.ensure makes an account and emails a link that sets the password and goes back to the product', async () => {
|
||||
const res = await ask({ type: 'people.ensure', name: 'New Staff', email: 'new.staff@hope.test', phone: null, returnUrl: 'https://events.hope.test/dashboard' });
|
||||
assert.equal(res.status, 200, JSON.stringify(res.body));
|
||||
assert.equal(res.body.created, true);
|
||||
const link = new URL(h.messenger.lastLink('new.staff@hope.test')!);
|
||||
const browser = new Browser();
|
||||
const reset = await h.api(browser, 'POST', '/api/v2/password/reset', { token: link.searchParams.get('token'), password: 'Staff-pass-123' });
|
||||
assert.equal(reset.body.returnUrl, 'https://events.hope.test/dashboard');
|
||||
assert.equal((await h.db.account.findUnique({ where: { id: res.body.sub as string } }))!.emailVerified, true);
|
||||
// The same email again: the same account.
|
||||
const again = await ask({ type: 'people.ensure', name: 'New Staff', email: 'NEW.staff@hope.test', phone: null, returnUrl: 'https://evil.test/' });
|
||||
assert.deepEqual([again.body.sub, again.body.created], [res.body.sub, false]);
|
||||
});
|
||||
|
||||
test('a product can only change people it knows', async () => {
|
||||
const stranger = await h.makeAccount({ email: 'stranger@hope.test' });
|
||||
const res = await ask({ type: 'people.unlock', sub: stranger.id });
|
||||
assert.equal(res.body.code, 'UNKNOWN_PERSON');
|
||||
const known = await ask({ type: 'people.ensure', name: 'Known', email: 'known@hope.test', phone: null, returnUrl: 'https://events.hope.test/' });
|
||||
const sub = known.body.sub as string;
|
||||
await h.db.account.update({ where: { id: sub }, data: { lockedUntil: new Date(Date.now() + 3600e3), failedSignIns: 9 } });
|
||||
assert.equal((await ask({ type: 'people.unlock', sub })).body.ok, true);
|
||||
assert.equal((await h.db.account.findUnique({ where: { id: sub } }))!.lockedUntil, null);
|
||||
const taken = await ask({ type: 'people.update', sub, email: 'stranger@hope.test' });
|
||||
assert.equal(taken.body.code, 'EMAIL_TAKEN');
|
||||
assert.equal((await ask({ type: 'people.update', sub, name: 'Known Person' })).body.ok, true);
|
||||
assert.equal((await ask({ type: 'people.newsOff', sub, channel: 'all' })).body.ok, true);
|
||||
assert.equal((await ask({ type: 'people.setActive', sub, active: false })).body.ok, true);
|
||||
assert.equal((await h.db.account.findUnique({ where: { id: sub } }))!.status, 'deactivated');
|
||||
});
|
||||
|
||||
test('a retry with the same request id gets the same answer; a bad signature is refused', async () => {
|
||||
const requestId = crypto.randomUUID();
|
||||
const body = { type: 'people.ensure', name: 'Retry', email: 'retry@hope.test', phone: null, returnUrl: 'https://events.hope.test/' };
|
||||
const one = await ask(body, { requestId });
|
||||
const two = await ask(body, { requestId });
|
||||
assert.deepEqual(two.body, one.body);
|
||||
assert.equal(two.body.created, true, 'the first answer, not "already there"');
|
||||
const forged = await ask(body, { secret: newLinkSecret() });
|
||||
assert.equal(forged.status, 401);
|
||||
const unknown = await ask(body, { from: crypto.randomUUID() });
|
||||
assert.equal(unknown.body.code, 'NOT_LINKED');
|
||||
});
|
||||
});
|
||||
@@ -83,13 +83,14 @@ export type Received = { path: string; headers: http.IncomingHttpHeaders; body:
|
||||
|
||||
export type Harness = Awaited<ReturnType<typeof startHarness>>;
|
||||
|
||||
export async function startHarness(opts: { now?: () => Date } = {}) {
|
||||
/** `db`: a real Prisma client instead of the in-memory one (an empty, migrated database). */
|
||||
export async function startHarness(opts: { now?: () => Date; db?: unknown } = {}) {
|
||||
// Accounts.
|
||||
const server = http.createServer();
|
||||
const port = await listen(server);
|
||||
const publicUrl = `http://127.0.0.1:${port}`;
|
||||
const config = { ...loadConfig({ ACCOUNTS_URL: publicUrl, NODE_ENV: 'test', JOBS_ENABLED: 'false', LINKS_ALLOW_PRIVATE: 'true', HUB_URL: 'http://127.0.0.1:1' }) };
|
||||
const db = memoryDb();
|
||||
const db = (opts.db ?? memoryDb()) as MemoryDb;
|
||||
const messenger = new MemoryMessenger();
|
||||
const ctx: Ctx = createCtx(config, db as never, { messenger, now: opts.now });
|
||||
const provider = await createProvider(ctx);
|
||||
|
||||
@@ -12,21 +12,21 @@ const DEFAULTS: Record<string, () => 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<string, string> = { appSetting: 'key', productLink: 'installId', linkNonce: 'nonce', pendingSignIn: 'uid', privacyNotice: 'version' };
|
||||
const KEYS: Record<string, string> = { appSetting: 'key', productLink: 'installId', linkNonce: 'nonce', pendingSignIn: 'uid', privacyNotice: 'version', productRequest: 'requestId' };
|
||||
const UNIQUE: Record<string, string[]> = { 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<string, Map<unknown, Row>>) {
|
||||
},
|
||||
};
|
||||
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;
|
||||
}
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "@crosscode/accounts-frontend",
|
||||
"version": "1.0.1",
|
||||
"version": "1.2.0",
|
||||
"private": true,
|
||||
"description": "Cross Code Accounts: the church's sign-in pages, the account page and admin",
|
||||
"scripts": {
|
||||
|
||||
@@ -283,6 +283,7 @@ function Settings({ flash, keys }: { flash: Flash; keys: string[] }) {
|
||||
<div className="flex gap-2">
|
||||
<Button type="submit">Save</Button>
|
||||
{keys.includes("smtp_host") && <Button type="button" variant="secondary" onClick={async () => { const r = await call("POST", "/admin/settings/test-email"); flash(r.ok ? "success" : "error", r.ok ? "A test email is on its way to you." : r.error.message); }}>Send a test email</Button>}
|
||||
{keys.includes("wawp_instance_id") && <Button type="button" variant="secondary" onClick={async () => { const r = await call("POST", "/admin/settings/test-whatsapp"); flash(r.ok ? "success" : "error", r.ok ? "A test WhatsApp message is on its way to your phone." : r.error.message); }}>Send a test WhatsApp</Button>}
|
||||
</div>
|
||||
</form>
|
||||
</Card>
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
"use client";
|
||||
|
||||
import { KeyRound } from "lucide-react";
|
||||
import React, { useState } from "react";
|
||||
import { Button, Card, Field, Heading, Notice, Shell } from "@crosscode/ui";
|
||||
import { useBranding } from "@/components/BrandingProvider";
|
||||
@@ -13,7 +14,7 @@ export function Forgot({ uid }: { uid: string | null }) {
|
||||
return (
|
||||
<Shell branding={branding}>
|
||||
<Card>
|
||||
<Heading sub="We'll email you a link to choose a new one.">Forgot your password?</Heading>
|
||||
<Heading icon={<KeyRound className="h-5 w-5" />} sub="We'll email you a link to choose a new one.">Forgot your password?</Heading>
|
||||
{sent ? (
|
||||
<Notice tone="success">If there's an account with that email address, a link is on its way. It works for an hour. You can close this page: the link brings you back.</Notice>
|
||||
) : (
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
"use client";
|
||||
|
||||
import { KeyRound } from "lucide-react";
|
||||
import React, { useState } from "react";
|
||||
import { Button, Card, Field, Heading, Notice, Shell } from "@crosscode/ui";
|
||||
import { useBranding } from "@/components/BrandingProvider";
|
||||
@@ -12,16 +13,17 @@ export function Reset({ token }: { token: string | null }) {
|
||||
return (
|
||||
<Shell branding={branding}>
|
||||
<Card>
|
||||
<Heading sub="At least 8 characters.">Choose a new password</Heading>
|
||||
<Heading icon={<KeyRound className="h-5 w-5" />} sub="At least 8 characters.">Choose a new password</Heading>
|
||||
{error && <Notice tone="error">{error}</Notice>}
|
||||
<form onSubmit={async (e) => {
|
||||
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"));
|
||||
}}>
|
||||
<Field label="New password" name="password" type="password" autoComplete="new-password" required minLength={8} autoFocus />
|
||||
<Button type="submit" busy={busy} className="w-full">Save and sign in</Button>
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
"use client";
|
||||
|
||||
import { LogOut } from "lucide-react";
|
||||
import { Card, Heading, Shell } from "@crosscode/ui";
|
||||
import { useBranding } from "@/components/BrandingProvider";
|
||||
import { selfSignIn } from "@/lib/api";
|
||||
@@ -9,7 +10,7 @@ export default function SignedOutPage() {
|
||||
return (
|
||||
<Shell branding={branding}>
|
||||
<Card>
|
||||
<Heading sub={`You've been signed out of all of ${branding.name}'s sites.`}>You're signed out</Heading>
|
||||
<Heading icon={<LogOut className="h-5 w-5" />} sub={`You've been signed out of all of ${branding.name}'s sites.`}>You're signed out</Heading>
|
||||
<a href={selfSignIn("/account")} className="text-brand underline">Sign in again</a>
|
||||
</Card>
|
||||
</Shell>
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
"use client";
|
||||
|
||||
import { AlertTriangle, FileText, KeyRound, LogIn, Mail, Megaphone, ShieldCheck, UserPlus } from "lucide-react";
|
||||
import React, { useState } from "react";
|
||||
import QRCode from "qrcode";
|
||||
import { Button, Card, Checkbox, Field, Heading, Notice, Shell } from "@crosscode/ui";
|
||||
@@ -13,6 +14,7 @@ type State = {
|
||||
product: string;
|
||||
signupEnabled: boolean;
|
||||
loginHint?: string | null;
|
||||
screen?: "signin" | "signup";
|
||||
name?: string;
|
||||
email?: string;
|
||||
sentTo?: string;
|
||||
@@ -35,16 +37,29 @@ export function SignIn({ uid }: { uid: string }) {
|
||||
const [error, setError] = useState<ApiError | null>(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,12 +84,12 @@ export function SignIn({ uid }: { uid: string }) {
|
||||
const frame = (children: React.ReactNode) => <Shell branding={branding}><Card>{children}</Card></Shell>;
|
||||
|
||||
if (codes) {
|
||||
return frame(<RecoveryCodes codes={codes.codes} onDone={() => window.location.assign(codes.next)} />);
|
||||
return frame(<RecoveryCodes codes={codes.codes} onDone={() => { const next = codes.next; setCodes(null); go(next); }} />);
|
||||
}
|
||||
if (!state) {
|
||||
return frame(error ? (
|
||||
<>
|
||||
<Heading>We couldn't continue</Heading>
|
||||
<Heading icon={<AlertTriangle className="h-5 w-5" />}>We couldn't continue</Heading>
|
||||
<Notice tone="error">{error.message}</Notice>
|
||||
</>
|
||||
) : <p className="text-gray-600">Loading…</p>);
|
||||
@@ -107,7 +122,7 @@ function PasswordStep({ state, busy, err, onSubmit, onSignUp }: { state: State;
|
||||
const branding = useBranding();
|
||||
return (
|
||||
<form onSubmit={(e) => { e.preventDefault(); const f = new FormData(e.currentTarget); onSubmit({ email: f.get("email"), password: f.get("password"), remember: f.get("remember") === "on" }); }}>
|
||||
<Heading sub={`to continue to ${state.product}`}>Sign in to {branding.name}</Heading>
|
||||
<Heading icon={<LogIn className="h-5 w-5" />} sub={`to continue to ${state.product}`}>Sign in to {branding.name}</Heading>
|
||||
{err}
|
||||
<Field label="Email address" name="email" type="email" autoComplete="username" required defaultValue={state.loginHint ?? ""} />
|
||||
<Field label="Password" name="password" type="password" autoComplete="current-password" required />
|
||||
@@ -130,7 +145,7 @@ function SignUpStep({ busy, err, fieldError, onSubmit, onBack }: { busy: boolean
|
||||
const f = new FormData(e.currentTarget);
|
||||
onSubmit({ name: f.get("name"), email: f.get("email"), phone: f.get("phone") || undefined, password: f.get("password"), acceptNotice: f.get("acceptNotice") === "on", newsEmail: f.get("newsEmail") === "on", newsWhatsApp: f.get("newsWhatsApp") === "on", remember: true });
|
||||
}}>
|
||||
<Heading sub={`One account for all of ${branding.name}'s sites and apps.`}>Create your account</Heading>
|
||||
<Heading icon={<UserPlus className="h-5 w-5" />} sub={`One account for all of ${branding.name}'s sites and apps.`}>Create your account</Heading>
|
||||
{err}
|
||||
<Field label="Your name" name="name" autoComplete="name" required error={fieldError("name")} />
|
||||
<Field label="Email address" name="email" type="email" autoComplete="email" required error={fieldError("email")} />
|
||||
@@ -148,7 +163,7 @@ function SignUpStep({ busy, err, fieldError, onSubmit, onBack }: { busy: boolean
|
||||
function CodeStep({ title, sub, busy, err, onSubmit, onResend }: { title: string; sub: React.ReactNode; busy: boolean; err: React.ReactNode; onSubmit: (code: string) => void; onResend?: () => void }) {
|
||||
return (
|
||||
<form onSubmit={(e) => { e.preventDefault(); onSubmit(String(new FormData(e.currentTarget).get("code") ?? "")); }}>
|
||||
<Heading sub={sub}>{title}</Heading>
|
||||
<Heading icon={<Mail className="h-5 w-5" />} sub={sub}>{title}</Heading>
|
||||
{err}
|
||||
<Field label="Code" name="code" inputMode="numeric" autoComplete="one-time-code" pattern="[0-9 ]{6,7}" required autoFocus />
|
||||
<Button type="submit" busy={busy} className="w-full">Continue</Button>
|
||||
@@ -198,7 +213,7 @@ function SetupStep({ uid, state, busy, err, setError, onConfirm }: { uid: string
|
||||
};
|
||||
return (
|
||||
<>
|
||||
<Heading sub={why}>Set up two-step sign-in</Heading>
|
||||
<Heading icon={<ShieldCheck className="h-5 w-5" />} sub={why}>Set up two-step sign-in</Heading>
|
||||
{err}
|
||||
<div className="space-y-2">
|
||||
{(state.methods ?? []).map((m) => (
|
||||
@@ -229,7 +244,7 @@ function RecoveryCodes({ codes, onDone }: { codes: string[]; onDone: () => void
|
||||
const text = codes.join("\n");
|
||||
return (
|
||||
<>
|
||||
<Heading sub="If you lose your phone, one of these lets you sign in. Each works once. Keep them somewhere safe: we can't show them again.">Save your recovery codes</Heading>
|
||||
<Heading icon={<KeyRound className="h-5 w-5" />} sub="If you lose your phone, one of these lets you sign in. Each works once. Keep them somewhere safe: we can't show them again.">Save your recovery codes</Heading>
|
||||
<pre className="mb-4 rounded-lg bg-gray-50 p-4 text-center font-mono text-sm leading-7">{text}</pre>
|
||||
<div className="mb-4 flex gap-2">
|
||||
<Button type="button" variant="secondary" onClick={() => navigator.clipboard?.writeText(text)}>Copy</Button>
|
||||
@@ -243,7 +258,7 @@ function RecoveryCodes({ codes, onDone }: { codes: string[]; onDone: () => void
|
||||
function NoticeStep({ state, busy, err, onAccept }: { state: State; busy: boolean; err: React.ReactNode; onAccept: () => void }) {
|
||||
return (
|
||||
<>
|
||||
<Heading sub={state.updated ? "Our privacy notice has changed. Please read it before you carry on." : "Please read our privacy notice before you carry on."}>{state.notice!.title}</Heading>
|
||||
<Heading icon={<FileText className="h-5 w-5" />} sub={state.updated ? "Our privacy notice has changed. Please read it before you carry on." : "Please read our privacy notice before you carry on."}>{state.notice!.title}</Heading>
|
||||
{err}
|
||||
<div className="mb-4 max-h-80 overflow-y-auto whitespace-pre-line rounded-lg border bg-gray-50 p-4 text-sm text-gray-700">{state.notice!.body}</div>
|
||||
<Button type="button" busy={busy} className="w-full" onClick={onAccept}>I've read it</Button>
|
||||
@@ -255,7 +270,7 @@ function NewsStep({ busy, err, onSubmit }: { busy: boolean; err: React.ReactNode
|
||||
const branding = useBranding();
|
||||
return (
|
||||
<form onSubmit={(e) => { e.preventDefault(); const f = new FormData(e.currentTarget); onSubmit({ email: f.get("email") === "on", whatsapp: f.get("whatsapp") === "on" }); }}>
|
||||
<Heading sub="You can change this at any time on your account page.">Would you like news from {branding.name}?</Heading>
|
||||
<Heading icon={<Megaphone className="h-5 w-5" />} sub="You can change this at any time on your account page.">Would you like news from {branding.name}?</Heading>
|
||||
{err}
|
||||
<Checkbox name="email" label="Yes, by email" />
|
||||
<Checkbox name="whatsapp" label="Yes, on WhatsApp" hint="If your mobile number is on your account." />
|
||||
|
||||
@@ -5,6 +5,91 @@ All notable changes to this project are documented in this file.
|
||||
The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/),
|
||||
and this project follows [Semantic Versioning](https://semver.org/).
|
||||
|
||||
## [3.1.0] - 2026-11-19
|
||||
|
||||
Found after a church moved sign-in without email set up in Accounts: Accounts couldn't send codes or
|
||||
password links, sign-in failed with a 500, and nobody could get in. Requires Accounts 1.2.0
|
||||
(`— requires accounts 1.2.0`) and contracts 1.9.0.
|
||||
|
||||
### Added
|
||||
|
||||
- **Settings → Sign-in → Email and WhatsApp for the church's sign-in** (`src/accounts/messaging.ts`,
|
||||
`components/admin/AccountsMessaging.tsx`): what Accounts can send, and this site's SMTP and WAWP
|
||||
settings to copy into it. The password and access token never reach the page: left blank, this
|
||||
site's own are used, sealed with the link's secret on the way. **Send a test** has Accounts send a
|
||||
test email / WhatsApp with those settings (nothing saved); **Save in Accounts** tests again and
|
||||
saves each part only if its test worked. Shown whenever Accounts is connected, so a church that
|
||||
already moved can mend it. `GET /api/v2/settings/sign-in/messaging`, `POST …/messaging/test`,
|
||||
`POST …/messaging`.
|
||||
|
||||
- **"Use this site's logo and colours"** on Settings → Sign-in (`POST /api/v2/settings/sign-in/look`):
|
||||
the church's sign-in pages get this site's name, logo (made a full address) and colours
|
||||
(`church.branding`); a move sends them too, filling only what Accounts doesn't have
|
||||
(`src/accounts/look.ts`).
|
||||
|
||||
### Changed
|
||||
|
||||
- **The move needs Accounts' email.** Check reports what Accounts can send (and how many people get
|
||||
WhatsApp codes, which go by email while Accounts' WhatsApp isn't set up); Move is disabled, and
|
||||
refused by the server (`EMAIL_NOT_READY`), until Accounts' email works.
|
||||
|
||||
## [3.0.0] - 2026-11-19
|
||||
|
||||
Sign-in through the church's Accounts (ROADMAP-v3 phase 4, docs/EVENTS-3.0-PLAN.md). Requires
|
||||
Accounts 1.1.0 (`— requires accounts 1.1.0` in WHATS-NEW.md) and contracts 1.8.0. Nothing changes
|
||||
for people until an admin moves sign-in; see MIGRATING-TO-3.md.
|
||||
|
||||
### Added
|
||||
|
||||
- **Settings → Sign-in** (`/api/v2/settings/sign-in`, `…/check`, `…/move`, `…/undo`): Check (a dry
|
||||
run in Accounts: who moves, who is linked to an account they already have, who is refused or
|
||||
skipped), Move and Undo (14 days). The move sends everyone with a real email address to Accounts
|
||||
(`crosscode.identity-request/1`, batches of 200, password hashes and authenticator secrets sealed
|
||||
with the link's secret), checks Accounts holds the same people (count and hash of the subs), and
|
||||
only then switches `auth_mode` to `accounts`. A move that fails switches nothing and can be run
|
||||
again. The admin who ran it gets the report by email; it's in the audit log.
|
||||
- **Signing in through Accounts** (`src/accounts/`): `GET /api/auth/signin?returnTo=` (PKCE, the
|
||||
state carries the page), `GET /api/auth/callback` (finds the user by `accountId`, links a guest or
|
||||
unlinked user with the same verified email, or makes a new `user`; keeps Events' copy of the
|
||||
profile, news consent and 2FA method), then `/auth/complete#<one-time code>`, which the page swaps
|
||||
for Events' own token at `POST /api/auth/handoff` (60 seconds, single use). Staff roles that need
|
||||
2FA are sent straight back with `acr_values=mfa` when Accounts didn't ask for it. The token carries
|
||||
`asi` (the sign-in) and `mfa`, which `protect` checks for staff roles; tokens from before the move
|
||||
keep working under the old rules.
|
||||
- **Signing out** (`POST /api/auth/signout`) ends Events' sessions and sends the browser to Accounts'
|
||||
sign-out, which signs out of every product; **back-channel logout** from Accounts
|
||||
(`/api/auth/backchannel-logout`) ends that person's Events sessions.
|
||||
- **Accounts' calls** at `/api/accounts/v1/events`: `user.updated` (the local copy), `user.export`
|
||||
(Events' export as sections), `user.deleted` (anonymise, or `deferred` while there's a registration
|
||||
for an event that hasn't ended).
|
||||
- **Admin, through Accounts:** `/api/v2/users/:id/account/reset-two-factor`, `…/unlock`, `…/active`;
|
||||
changing someone's name, email or phone (`PATCH /users/:id`) changes their account first. People
|
||||
staff add (ticket transfers, registrations at the door) get their account from Accounts
|
||||
(`people.ensure`, a "choose your password" email) instead of an Events activation link.
|
||||
- `GET /api/v2/auth/mode` (public): `local` or `accounts`, and the church account page.
|
||||
- `User.accountId` (decision 1), `AccountsSignIn`, six audit actions; the `accounts-secrets` job
|
||||
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
|
||||
|
||||
- With sign-in through Accounts: `/login`, `/register` and `/forgot-password` forward there (every
|
||||
`/login?redirect=` link keeps working); old reset and activation links say sign-in has moved; Events'
|
||||
own sign-in, password, 2FA and close-account endpoints answer `409 SIGN_IN_MOVED`; Profile shows the
|
||||
details read-only and links to the church account for password, 2FA and closing the account; the
|
||||
privacy centre links there for news, "download my data" and deletion. An unsubscribe link or a
|
||||
WhatsApp STOP turns news off in Accounts too (`people.newsOff`).
|
||||
- `useRequireAuth` sends people to `/login?redirect=<this page>`, so they come back to it.
|
||||
- The inactive-account retention rule skips people linked to Accounts (Accounts keeps or removes
|
||||
them).
|
||||
|
||||
## [2.4.1] - 2026-11-19
|
||||
|
||||
### Fixed
|
||||
|
||||
@@ -0,0 +1,64 @@
|
||||
# Moving to Cross Events 3.0
|
||||
|
||||
Cross Events 3.0 can sign people in with the **church's account** (Accounts), the one they'll use
|
||||
for the church website and app too. It's a major version because it needs Accounts 1.1.0 or later
|
||||
next to it. **Updating to 3.0 changes nothing for anyone**: people keep signing in with their Cross
|
||||
Events password until an admin moves sign-in (step 4). The plan behind it is
|
||||
[docs/EVENTS-3.0-PLAN.md](../../docs/EVENTS-3.0-PLAN.md).
|
||||
|
||||
## For whoever runs the server
|
||||
|
||||
1. **Accounts first.** The church needs Accounts 1.1.0 or later on the same server: in the Hub,
|
||||
New install → Accounts for this church (an `add-product` job), or update its Accounts. The Hub
|
||||
won't offer the Events 3.0 update before that (`requires accounts 1.1.0`), and `crosscode deploy`
|
||||
refuses it too.
|
||||
2. **Connect them.** In Cross Events, Site settings → Linked products → Accounts → **Connect**. This
|
||||
also registers Events as a sign-in client of Accounts; nothing else is typed in.
|
||||
3. **Update Events to 3.0** as usual (scheduled update from the Hub). There's one migration
|
||||
(`User.accountId`, `AccountsSignIn`, six audit actions) and no new `.env` variable.
|
||||
4. **Move sign-in** when the church is ready (below).
|
||||
|
||||
## For the church's admin: moving sign-in
|
||||
|
||||
Site settings → **Sign-in**:
|
||||
|
||||
1. **Set up the church account's email** (Email and WhatsApp for the church's sign-in, on the same
|
||||
page, from 3.1.0). Accounts sends sign-in codes and password links itself, so without email there
|
||||
nobody could sign in after the move; Move stays disabled until it works. The page copies this
|
||||
site's email settings (leave the password blank to use this site's), **Send a test email**, check
|
||||
it arrived, then **Save in Accounts**. WhatsApp the same way, if you use it.
|
||||
2. **Check the move.** Nothing changes. It lists how many people move, who already has a church
|
||||
account (they're linked to it and keep that account's password), anyone who can't move and why,
|
||||
and the guests and deleted people who stay in Cross Events only.
|
||||
3. Tick which Cross Events admins should also be **Accounts admins** (they can manage everyone's
|
||||
sign-in). By default every admin is ticked.
|
||||
4. **Move sign-in to Accounts** at a quiet time (not the evening before a big event's registration
|
||||
closes). It takes about a minute. People already signed in stay signed in.
|
||||
|
||||
What people notice afterwards:
|
||||
|
||||
- "Sign in" opens the church's sign-in page (with the church's name and colours) and comes back to
|
||||
the page they were on.
|
||||
- **Same password, same authenticator app.** People with two-step sign-in get 10 new recovery codes
|
||||
after their first sign-in (the old ones can't move); they should save them.
|
||||
- Supervisors and admins still need two-step sign-in; Accounts asks them to set it up if they don't
|
||||
have it.
|
||||
- Password, two-step sign-in, news choices, "download my data" and deleting an account are on the
|
||||
church account (Profile and Privacy link there).
|
||||
|
||||
**Undo** (same page) goes back to Cross Events' own sign-in for 14 days. People then sign in with
|
||||
the password they had at the move; anything changed in Accounts since (a new password, two-step
|
||||
sign-in set up) doesn't come back. After 14 days Cross Events removes the old passwords and Undo
|
||||
goes away.
|
||||
|
||||
## For integrations
|
||||
|
||||
- `POST /api/v2/auth/login`, `…/login/code`, `…/signup`, `…/password/forgot`, `…/password/reset`,
|
||||
`…/activate`, `/me/two-factor/*`, `/me/verify-password` and `/me/close` answer **`409`** with
|
||||
`{ "error": { "code": "SIGN_IN_MOVED", "signInUrl": "/api/auth/signin" } }` once sign-in has moved.
|
||||
A script that signed in with a password needs another way in (ask Cross Code).
|
||||
- `GET /api/v2/auth/mode` says `local` or `accounts`.
|
||||
- Tokens are the same as before (`Authorization: Bearer …`, 30 days, ended by signing out). A token
|
||||
from a sign-in through Accounts also carries `asi` and `mfa`.
|
||||
- `PATCH /api/v2/me` ignores `name`, `email` and `phone` (they're changed in Accounts) and refuses a
|
||||
password.
|
||||
@@ -12,6 +12,30 @@ Write for church admins, not developers: no environment variables, endpoints or
|
||||
developer log is CHANGELOG.md. A tagged version without a section here shows "No details given".
|
||||
-->
|
||||
|
||||
## 3.1.0 — requires accounts 1.2.0
|
||||
|
||||
- **Fix:** moving sign-in to your church's Accounts now needs Accounts' email to work first, so
|
||||
people can always get their sign-in codes and password links. Settings → Sign-in shows whether it
|
||||
does, and sets it up for you: it copies this site's email settings (your password stays where it
|
||||
is), sends a test, and only saves them in Accounts once the test arrived. The same for WhatsApp.
|
||||
- If your church already moved without it, the same page sets it up now.
|
||||
- The church's sign-in page now has your logo and colours: they're taken from this site when you
|
||||
move, and **Use this site's logo and colours** (Settings → Sign-in) updates them any time.
|
||||
|
||||
## 3.0.0 — requires accounts 1.1.0
|
||||
|
||||
- **One sign-in for all your church's sites and apps.** People can now sign in to Cross Events with
|
||||
their church account, the same one they'll use for the church website and app. Nothing changes
|
||||
until an admin chooses **Move sign-in to Accounts** under Site settings → Sign-in.
|
||||
- **Nobody has to reset anything.** Everyone keeps their password and their authenticator app.
|
||||
People who use two-step sign-in get new recovery codes the first time they sign in.
|
||||
- After signing in, people come back to exactly the page they were on, such as an event's
|
||||
registration form.
|
||||
- Passwords, two-step sign-in, news choices, "download my data" and deleting an account are on the
|
||||
church account from then on, for all the church's sites at once.
|
||||
- Admins can still reset someone's two-step sign-in or unlock them from the People page.
|
||||
- Changed your mind? **Undo** goes back to Cross Events' own sign-in for 14 days after the move.
|
||||
|
||||
## 2.4.1
|
||||
|
||||
- Until you upload your own logo (Site settings → Branding), the site now shows the Cross Code
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "@crosscode/events-backend",
|
||||
"version": "2.4.1",
|
||||
"version": "3.1.0",
|
||||
"description": "Event Management System Backend",
|
||||
"main": "src/index.js",
|
||||
"scripts": {
|
||||
@@ -18,10 +18,12 @@
|
||||
"build": "tsc -p tsconfig.json && node -e \"require('fs').writeFileSync('dist/build.json', JSON.stringify({ version: require('./package.json').version, builtAt: new Date().toISOString() }))\"",
|
||||
"typecheck": "tsc -p tsconfig.json --noEmit",
|
||||
"openapi": "tsx scripts/openapi.ts",
|
||||
"ai:eval": "tsx scripts/ai-eval.ts"
|
||||
"ai:eval": "tsx scripts/ai-eval.ts",
|
||||
"test:accounts": "node --import tsx --test --test-reporter=spec tests/accounts-integration/*.int.mts"
|
||||
},
|
||||
"dependencies": {
|
||||
"@cj-tech-master/excelts": "^10.2.0",
|
||||
"@crosscode/auth-client": "*",
|
||||
"@crosscode/contracts": "*",
|
||||
"@node-rs/argon2": "^2.2.2",
|
||||
"@prisma/adapter-pg": "^7.10.1",
|
||||
|
||||
@@ -0,0 +1,41 @@
|
||||
-- 3.0.0: signing in through the church's Accounts (docs/EVENTS-3.0-PLAN.md).
|
||||
ALTER TYPE "AdminAuditAction" ADD VALUE 'sign_in_move_started';
|
||||
ALTER TYPE "AdminAuditAction" ADD VALUE 'sign_in_move_finished';
|
||||
ALTER TYPE "AdminAuditAction" ADD VALUE 'sign_in_move_failed';
|
||||
ALTER TYPE "AdminAuditAction" ADD VALUE 'sign_in_move_undone';
|
||||
ALTER TYPE "AdminAuditAction" ADD VALUE 'sign_in_secrets_cleared';
|
||||
ALTER TYPE "AdminAuditAction" ADD VALUE 'account_changed_in_accounts';
|
||||
|
||||
-- AlterTable
|
||||
ALTER TABLE "User" ADD COLUMN "accountId" TEXT;
|
||||
|
||||
-- CreateIndex
|
||||
CREATE UNIQUE INDEX "User_accountId_key" ON "User"("accountId");
|
||||
|
||||
-- CreateTable
|
||||
CREATE TABLE "AccountsSignIn" (
|
||||
"id" TEXT NOT NULL,
|
||||
"userId" TEXT NOT NULL,
|
||||
"codeHash" TEXT,
|
||||
"codeExpires" TIMESTAMP(3),
|
||||
"codeUsedAt" TIMESTAMP(3),
|
||||
"returnTo" TEXT NOT NULL,
|
||||
"idToken" TEXT,
|
||||
"sid" TEXT,
|
||||
"mfa" BOOLEAN NOT NULL DEFAULT false,
|
||||
"createdAt" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
|
||||
|
||||
CONSTRAINT "AccountsSignIn_pkey" PRIMARY KEY ("id")
|
||||
);
|
||||
|
||||
-- CreateIndex
|
||||
CREATE UNIQUE INDEX "AccountsSignIn_codeHash_key" ON "AccountsSignIn"("codeHash");
|
||||
|
||||
-- CreateIndex
|
||||
CREATE INDEX "AccountsSignIn_userId_idx" ON "AccountsSignIn"("userId");
|
||||
|
||||
-- CreateIndex
|
||||
CREATE INDEX "AccountsSignIn_createdAt_idx" ON "AccountsSignIn"("createdAt");
|
||||
|
||||
-- AddForeignKey
|
||||
ALTER TABLE "AccountsSignIn" ADD CONSTRAINT "AccountsSignIn_userId_fkey" FOREIGN KEY ("userId") REFERENCES "User"("id") ON DELETE CASCADE ON UPDATE CASCADE;
|
||||
@@ -66,6 +66,10 @@ enum TwoFactorMethod {
|
||||
|
||||
model User {
|
||||
id String @id @default(uuid())
|
||||
// 3.0.0: the church's account (Accounts' `sub`) this user signs in with. Equal to `id` for
|
||||
// everyone moved in (docs/EVENTS-3.0-PLAN.md §2); another sub when their email already had an
|
||||
// account; null for guests, deleted people, and everyone before the move.
|
||||
accountId String? @unique
|
||||
name String
|
||||
email String @unique
|
||||
password String
|
||||
@@ -108,76 +112,77 @@ model User {
|
||||
Event Event[]
|
||||
FormDraft FormDraft[]
|
||||
|
||||
eventsClosed Event[] @relation("EventClosedBy")
|
||||
eventsReopened Event[] @relation("EventReopenedBy")
|
||||
eventsClosed Event[] @relation("EventClosedBy")
|
||||
eventsReopened Event[] @relation("EventReopenedBy")
|
||||
cashupsPerformed EventCashup[]
|
||||
pendingResolved EventCashupPendingResolution[] @relation("PendingResolutionBy")
|
||||
notifyForEvents Event[] @relation("EventNotifyRecipients")
|
||||
notifyForEvents Event[] @relation("EventNotifyRecipients")
|
||||
|
||||
personCashCountsFor EventCashupPersonCount[] @relation("EventCashupPersonCountFor")
|
||||
personCashCountsEntered EventCashupPersonCount[] @relation("EventCashupPersonCountEnteredBy")
|
||||
|
||||
securityEvents SecurityEvent[]
|
||||
adminAuditLogs AdminAuditLog[] @relation("AdminAuditActor")
|
||||
securityEvents SecurityEvent[]
|
||||
accountsSignIns AccountsSignIn[]
|
||||
adminAuditLogs AdminAuditLog[] @relation("AdminAuditActor")
|
||||
|
||||
couponsCreated Coupon[] @relation("CouponCreatedBy")
|
||||
couponAccess CouponUser[]
|
||||
couponRedemptions CouponRedemption[] @relation("CouponRedemptionUser")
|
||||
couponsApplied CouponRedemption[] @relation("CouponRedemptionAppliedBy")
|
||||
|
||||
attendeeProfiles Attendee[]
|
||||
heldTickets Ticket[] @relation("TicketHolder")
|
||||
waitlistEntries WaitlistEntry[]
|
||||
scanLocks ScanLock[] @relation("ScanLockOwner")
|
||||
transfersTo TicketTransfer[] @relation("TransferRecipient")
|
||||
transfersBy TicketTransfer[] @relation("TransferActor")
|
||||
ledGroups AllocationGroup[] @relation("AllocationGroupLeader")
|
||||
feedbackInvites FeedbackInvite[]
|
||||
feedbackGiven FeedbackResponse[]
|
||||
impersonationsDone ImpersonationSession[] @relation("ImpersonationAdmin")
|
||||
attendeeProfiles Attendee[]
|
||||
heldTickets Ticket[] @relation("TicketHolder")
|
||||
waitlistEntries WaitlistEntry[]
|
||||
scanLocks ScanLock[] @relation("ScanLockOwner")
|
||||
transfersTo TicketTransfer[] @relation("TransferRecipient")
|
||||
transfersBy TicketTransfer[] @relation("TransferActor")
|
||||
ledGroups AllocationGroup[] @relation("AllocationGroupLeader")
|
||||
feedbackInvites FeedbackInvite[]
|
||||
feedbackGiven FeedbackResponse[]
|
||||
impersonationsDone ImpersonationSession[] @relation("ImpersonationAdmin")
|
||||
transferRequests TicketTransferRequest[] @relation("TransferRequester")
|
||||
impersonatedIn ImpersonationSession[] @relation("ImpersonationTarget")
|
||||
scanLocksForced ScanLock[] @relation("ScanLockForcedBy")
|
||||
syncReportsDone OfflineSyncReport[] @relation("SyncReportReviewer")
|
||||
impersonatedIn ImpersonationSession[] @relation("ImpersonationTarget")
|
||||
scanLocksForced ScanLock[] @relation("ScanLockForcedBy")
|
||||
syncReportsDone OfflineSyncReport[] @relation("SyncReportReviewer")
|
||||
|
||||
twoFactorChallenges TwoFactorChallenge[]
|
||||
trustedDevices TrustedDevice[]
|
||||
certificates Certificate[]
|
||||
certificatesIssued Certificate[] @relation("CertificateIssuedBy")
|
||||
twoFactorChallenges TwoFactorChallenge[]
|
||||
trustedDevices TrustedDevice[]
|
||||
certificates Certificate[]
|
||||
certificatesIssued Certificate[] @relation("CertificateIssuedBy")
|
||||
communicationConsents CommunicationConsent[]
|
||||
dataRequests DataRequest[]
|
||||
dataRequestsHandled DataRequest[] @relation("DataRequestHandledBy")
|
||||
noticesPublished PrivacyNotice[]
|
||||
noticeAcceptances NoticeAcceptance[]
|
||||
dataAccessLogs DataAccessLog[]
|
||||
breachesRecorded SecurityBreach[]
|
||||
dataRequests DataRequest[]
|
||||
dataRequestsHandled DataRequest[] @relation("DataRequestHandledBy")
|
||||
noticesPublished PrivacyNotice[]
|
||||
noticeAcceptances NoticeAcceptance[]
|
||||
dataAccessLogs DataAccessLog[]
|
||||
breachesRecorded SecurityBreach[]
|
||||
|
||||
// Multi-campus (only used while Site settings → Campuses is on).
|
||||
homeCampusId String?
|
||||
homeCampus Campus? @relation("UserHomeCampus", fields: [homeCampusId], references: [id], onDelete: SetNull)
|
||||
campusSummaries Campus[] @relation("CampusNotifyRecipients")
|
||||
homeCampusId String?
|
||||
homeCampus Campus? @relation("UserHomeCampus", fields: [homeCampusId], references: [id], onDelete: SetNull)
|
||||
campusSummaries Campus[] @relation("CampusNotifyRecipients")
|
||||
// Campus-scoped staff (1.44.0): a supervisor/staff member limited to these campuses (their
|
||||
// events plus events for all campuses). Empty = unscoped. Ignored for admins and while
|
||||
// campuses are off (utils/campusScope.js).
|
||||
scopedCampuses Campus[] @relation("UserCampusScope")
|
||||
scopedCampuses Campus[] @relation("UserCampusScope")
|
||||
|
||||
// Kids check-in (1.45.0): the family this person is a parent in (at most one).
|
||||
familyMembership FamilyMember?
|
||||
kidsCheckInsDone KidsCheckIn[] @relation("KidsCheckInBy")
|
||||
kidsCheckOutsDone KidsCheckIn[] @relation("KidsCheckOutBy")
|
||||
kidsAlertsRaised KidsAlert[]
|
||||
kidsRoomDuties KidsRoomDuty[]
|
||||
familyMembership FamilyMember?
|
||||
kidsCheckInsDone KidsCheckIn[] @relation("KidsCheckInBy")
|
||||
kidsCheckOutsDone KidsCheckIn[] @relation("KidsCheckOutBy")
|
||||
kidsAlertsRaised KidsAlert[]
|
||||
kidsRoomDuties KidsRoomDuty[]
|
||||
|
||||
// Volunteer rosters (1.46.0)
|
||||
volunteerSlots VolunteerSlot[] @relation("VolunteerSlotUser")
|
||||
volunteersAssigned VolunteerSlot[] @relation("VolunteerSlotAssignedBy")
|
||||
volunteersCheckedIn VolunteerSlot[] @relation("VolunteerSlotCheckedInBy")
|
||||
volunteerSlots VolunteerSlot[] @relation("VolunteerSlotUser")
|
||||
volunteersAssigned VolunteerSlot[] @relation("VolunteerSlotAssignedBy")
|
||||
volunteersCheckedIn VolunteerSlot[] @relation("VolunteerSlotCheckedInBy")
|
||||
seriesFollows SeriesFollow[]
|
||||
seasonPassPurchases SeasonPassPurchase[]
|
||||
savedFilters SavedFilter[]
|
||||
aiCalls AiCall[]
|
||||
swapsAsked VolunteerSwap[] @relation("VolunteerSwapFrom")
|
||||
swapsTaken VolunteerSwap[] @relation("VolunteerSwapTo")
|
||||
swapsAsked VolunteerSwap[] @relation("VolunteerSwapFrom")
|
||||
swapsTaken VolunteerSwap[] @relation("VolunteerSwapTo")
|
||||
|
||||
@@index([homeCampusId])
|
||||
}
|
||||
@@ -318,27 +323,27 @@ model Event {
|
||||
// tickets. Each child gets a free place on `kidsOptionId` (a main-ticket option of this
|
||||
// event) the first time, so they show on the attendance register; rooms are the groups of
|
||||
// the allocation set `kidsRoomSetId`. Plain ids (checked in utils/kids.js), not relations.
|
||||
kidsCheckIn Boolean @default(false)
|
||||
kidsOptionId String?
|
||||
kidsRoomSetId String?
|
||||
kidsPickupCodes KidsPickupCode[]
|
||||
kidsCheckIns KidsCheckIn[]
|
||||
kidsAlerts KidsAlert[]
|
||||
kidsCheckIn Boolean @default(false)
|
||||
kidsOptionId String?
|
||||
kidsRoomSetId String?
|
||||
kidsPickupCodes KidsPickupCode[]
|
||||
kidsCheckIns KidsCheckIn[]
|
||||
kidsAlerts KidsAlert[]
|
||||
|
||||
// Volunteer rosters (1.46.0): serving roles for the event or one of its sessions. When
|
||||
// `volunteerOptionId` is set (a main ticket of this event; off by default), each volunteer
|
||||
// gets a free place on it. `volunteerCheckInToken` is in the check-in QR code volunteers scan
|
||||
// on the day (made the first time the QR code is shown). Plain id, checked in utils/volunteers.js.
|
||||
servingRoles ServingRole[]
|
||||
volunteerOptionId String?
|
||||
volunteerCheckInToken String? @unique
|
||||
servingRoles ServingRole[]
|
||||
volunteerOptionId String?
|
||||
volunteerCheckInToken String? @unique
|
||||
|
||||
// Event series (1.47.1): separate events grouped on one series page (Camp 2025, Camp 2026).
|
||||
// seriesAnnouncedAt: when followers were emailed that this event is out (once, when it goes live).
|
||||
seriesId String?
|
||||
series EventSeries? @relation(fields: [seriesId], references: [id], onDelete: SetNull)
|
||||
seasonPassItems SeasonPassItem[]
|
||||
seriesAnnouncedAt DateTime?
|
||||
seriesId String?
|
||||
series EventSeries? @relation(fields: [seriesId], references: [id], onDelete: SetNull)
|
||||
seasonPassItems SeasonPassItem[]
|
||||
seriesAnnouncedAt DateTime?
|
||||
|
||||
@@index([createdById])
|
||||
@@index([closedById])
|
||||
@@ -502,47 +507,47 @@ model OptionVariant {
|
||||
}
|
||||
|
||||
model Registration {
|
||||
id String @id @default(uuid())
|
||||
userId String
|
||||
eventId String
|
||||
status RegistrationStatus @default(pending)
|
||||
checkoutId String? @unique
|
||||
id String @id @default(uuid())
|
||||
userId String
|
||||
eventId String
|
||||
status RegistrationStatus @default(pending)
|
||||
checkoutId String? @unique
|
||||
// Sum of this registration's discounts: bundle deals plus active coupon discounts,
|
||||
// kept in step with bundleApplications and couponRedemptions. Stored here so every
|
||||
// total-due calculation sees it no matter which relations the caller loaded (see
|
||||
// utils/pricing.js computeRegistrationTotalDue).
|
||||
discountTotal Float @default(0)
|
||||
discountTotal Float @default(0)
|
||||
// The bundle-deal part of discountTotal (the rest is coupons).
|
||||
bundleDiscount Float @default(0)
|
||||
bundleDiscount Float @default(0)
|
||||
// Where named attendees' tickets go: all to the payer, or each to the attendee.
|
||||
ticketDelivery TicketDelivery @default(payer)
|
||||
ticketDelivery TicketDelivery @default(payer)
|
||||
// Corrections (1.52.0). The attendee form can come later: tickets don't wait for it ("Fill in
|
||||
// later" at the door or in Manual registrations, or an admin in Corrections).
|
||||
formWaivedAt DateTime?
|
||||
formWaivedById String?
|
||||
formWaivedAt DateTime?
|
||||
formWaivedById String?
|
||||
// An admin issued the tickets before it was paid ("pay later"): the balance is still owed.
|
||||
ticketsReleasedAt DateTime?
|
||||
ticketsReleasedById String?
|
||||
ticketsReleasedAt DateTime?
|
||||
ticketsReleasedById String?
|
||||
// A balance an admin wrote off ("make it free"); part of discountTotal (utils/coupons.js).
|
||||
complimentaryDiscount Float @default(0)
|
||||
analyticsSessionId String?
|
||||
createdAt DateTime @default(now())
|
||||
updatedAt DateTime @updatedAt
|
||||
user User @relation(fields: [userId], references: [id], onDelete: Restrict)
|
||||
event Event @relation(fields: [eventId], references: [id], onDelete: Restrict)
|
||||
registrationOptions RegistrationOption[]
|
||||
payments Payment[]
|
||||
formResponses FormResponse[]
|
||||
formDrafts FormDraft[]
|
||||
couponRedemptions CouponRedemption[]
|
||||
bundleApplications RegistrationBundle[]
|
||||
complimentaryDiscount Float @default(0)
|
||||
analyticsSessionId String?
|
||||
createdAt DateTime @default(now())
|
||||
updatedAt DateTime @updatedAt
|
||||
user User @relation(fields: [userId], references: [id], onDelete: Restrict)
|
||||
event Event @relation(fields: [eventId], references: [id], onDelete: Restrict)
|
||||
registrationOptions RegistrationOption[]
|
||||
payments Payment[]
|
||||
formResponses FormResponse[]
|
||||
formDrafts FormDraft[]
|
||||
couponRedemptions CouponRedemption[]
|
||||
bundleApplications RegistrationBundle[]
|
||||
// Season pass (1.47.3): one registration per event on the pass, its line priced at that
|
||||
// event's share of the pass price (never repriced, no coupons, options not editable).
|
||||
seasonPassPurchaseId String?
|
||||
seasonPassPurchase SeasonPassPurchase? @relation(fields: [seasonPassPurchaseId], references: [id], onDelete: SetNull)
|
||||
attendees Attendee[]
|
||||
waitlistEntries WaitlistEntry[]
|
||||
volunteerSlots VolunteerSlot[]
|
||||
seasonPassPurchaseId String?
|
||||
seasonPassPurchase SeasonPassPurchase? @relation(fields: [seasonPassPurchaseId], references: [id], onDelete: SetNull)
|
||||
attendees Attendee[]
|
||||
waitlistEntries WaitlistEntry[]
|
||||
volunteerSlots VolunteerSlot[]
|
||||
|
||||
@@index([userId])
|
||||
@@index([eventId])
|
||||
@@ -603,37 +608,37 @@ model RegistrationOptionTranche {
|
||||
}
|
||||
|
||||
model Payment {
|
||||
id String @id @default(uuid())
|
||||
amount Float
|
||||
method String
|
||||
userId String
|
||||
recordedById String?
|
||||
registrationId String?
|
||||
eventId String?
|
||||
isDonation Boolean @default(false)
|
||||
id String @id @default(uuid())
|
||||
amount Float
|
||||
method String
|
||||
userId String
|
||||
recordedById String?
|
||||
registrationId String?
|
||||
eventId String?
|
||||
isDonation Boolean @default(false)
|
||||
// A "sponsor a spot" donation (also isDonation): goes into the event's sponsorship pool.
|
||||
isSponsorship Boolean @default(false)
|
||||
sponsorName String?
|
||||
sponsorMessage String?
|
||||
sponsorAnonymous Boolean @default(false)
|
||||
externalId String? @unique
|
||||
status String?
|
||||
originalPaymentId String?
|
||||
isSponsorship Boolean @default(false)
|
||||
sponsorName String?
|
||||
sponsorMessage String?
|
||||
sponsorAnonymous Boolean @default(false)
|
||||
externalId String? @unique
|
||||
status String?
|
||||
originalPaymentId String?
|
||||
// Online payments: the payment provider that took it (src/payments, e.g. "yoco"). Null for
|
||||
// payments recorded by staff. Payment.method stays the wallet type (card, apple_pay, …).
|
||||
provider String?
|
||||
createdAt DateTime @default(now())
|
||||
user User @relation(fields: [userId], references: [id], onDelete: Restrict)
|
||||
recordedBy User? @relation("PaymentRecordedBy", fields: [recordedById], references: [id], onDelete: SetNull)
|
||||
registration Registration? @relation(fields: [registrationId], references: [id], onDelete: SetNull)
|
||||
event Event? @relation(fields: [eventId], references: [id], onDelete: SetNull)
|
||||
originalPayment Payment? @relation("SplitPayments", fields: [originalPaymentId], references: [id], onDelete: SetNull)
|
||||
splitPayments Payment[] @relation("SplitPayments")
|
||||
provider String?
|
||||
createdAt DateTime @default(now())
|
||||
user User @relation(fields: [userId], references: [id], onDelete: Restrict)
|
||||
recordedBy User? @relation("PaymentRecordedBy", fields: [recordedById], references: [id], onDelete: SetNull)
|
||||
registration Registration? @relation(fields: [registrationId], references: [id], onDelete: SetNull)
|
||||
event Event? @relation(fields: [eventId], references: [id], onDelete: SetNull)
|
||||
originalPayment Payment? @relation("SplitPayments", fields: [originalPaymentId], references: [id], onDelete: SetNull)
|
||||
splitPayments Payment[] @relation("SplitPayments")
|
||||
providerTransactions ProviderTransaction[]
|
||||
// Season pass: one provider payment is recorded as one Payment per event on the pass (its
|
||||
// share), all linked to the purchase. Only the first carries the provider's externalId.
|
||||
seasonPassPurchaseId String?
|
||||
seasonPassPurchase SeasonPassPurchase? @relation(fields: [seasonPassPurchaseId], references: [id], onDelete: SetNull)
|
||||
seasonPassPurchase SeasonPassPurchase? @relation(fields: [seasonPassPurchaseId], references: [id], onDelete: SetNull)
|
||||
|
||||
@@index([userId])
|
||||
@@index([recordedById])
|
||||
@@ -644,25 +649,25 @@ model Payment {
|
||||
}
|
||||
|
||||
model Ticket {
|
||||
id String @id @default(uuid())
|
||||
qrCode String @unique
|
||||
id String @id @default(uuid())
|
||||
qrCode String @unique
|
||||
registrationOptionId String
|
||||
userId String
|
||||
eventId String
|
||||
quantity Int @default(1)
|
||||
isUsed Boolean @default(false)
|
||||
emailSent Boolean @default(false)
|
||||
quantity Int @default(1)
|
||||
isUsed Boolean @default(false)
|
||||
emailSent Boolean @default(false)
|
||||
// Set on a named (group) ticket: the person it's for, and their account when it
|
||||
// matched one. userId stays the payer.
|
||||
attendeeId String? @unique
|
||||
attendee Attendee? @relation(fields: [attendeeId], references: [id], onDelete: SetNull)
|
||||
attendeeId String? @unique
|
||||
attendee Attendee? @relation(fields: [attendeeId], references: [id], onDelete: SetNull)
|
||||
holderUserId String?
|
||||
holder User? @relation("TicketHolder", fields: [holderUserId], references: [id], onDelete: SetNull)
|
||||
createdAt DateTime @default(now())
|
||||
updatedAt DateTime @updatedAt
|
||||
registrationOption RegistrationOption @relation(fields: [registrationOptionId], references: [id], onDelete: Restrict)
|
||||
user User @relation(fields: [userId], references: [id], onDelete: Restrict)
|
||||
event Event @relation(fields: [eventId], references: [id], onDelete: Restrict)
|
||||
holder User? @relation("TicketHolder", fields: [holderUserId], references: [id], onDelete: SetNull)
|
||||
createdAt DateTime @default(now())
|
||||
updatedAt DateTime @updatedAt
|
||||
registrationOption RegistrationOption @relation(fields: [registrationOptionId], references: [id], onDelete: Restrict)
|
||||
user User @relation(fields: [userId], references: [id], onDelete: Restrict)
|
||||
event Event @relation(fields: [eventId], references: [id], onDelete: Restrict)
|
||||
usages TicketUsage[]
|
||||
transfers TicketTransfer[]
|
||||
transferRequests TicketTransferRequest[]
|
||||
@@ -676,25 +681,25 @@ model Ticket {
|
||||
}
|
||||
|
||||
model TicketUsage {
|
||||
id String @id @default(uuid())
|
||||
id String @id @default(uuid())
|
||||
ticketId String
|
||||
scannedById String
|
||||
scannedAt DateTime @default(now())
|
||||
quantityRedeemed Int @default(1)
|
||||
scannedAt DateTime @default(now())
|
||||
quantityRedeemed Int @default(1)
|
||||
// Offline scanning: the device's id for the scan (makes syncing idempotent), and
|
||||
// the offline lock it was made under.
|
||||
clientScanId String? @unique
|
||||
offline Boolean @default(false)
|
||||
clientScanId String? @unique
|
||||
offline Boolean @default(false)
|
||||
scanLockId String?
|
||||
syncedAt DateTime?
|
||||
// Multi-day events: the session this check-in counts for (null on single-date events).
|
||||
sessionId String?
|
||||
session EventSession? @relation(fields: [sessionId], references: [id], onDelete: Restrict)
|
||||
// Ticked present by a supervisor from the attendance register, not scanned.
|
||||
manual Boolean @default(false)
|
||||
ticket Ticket @relation(fields: [ticketId], references: [id], onDelete: Restrict)
|
||||
scannedBy User @relation(fields: [scannedById], references: [id], onDelete: Restrict)
|
||||
scanLock ScanLock? @relation(fields: [scanLockId], references: [id], onDelete: SetNull)
|
||||
manual Boolean @default(false)
|
||||
ticket Ticket @relation(fields: [ticketId], references: [id], onDelete: Restrict)
|
||||
scannedBy User @relation(fields: [scannedById], references: [id], onDelete: Restrict)
|
||||
scanLock ScanLock? @relation(fields: [scanLockId], references: [id], onDelete: SetNull)
|
||||
|
||||
@@index([ticketId])
|
||||
@@index([scannedAt])
|
||||
@@ -718,19 +723,19 @@ model PasswordReset {
|
||||
// ('login') or to prove the channel works before 2FA is switched on ('enable').
|
||||
// Only the HMAC of the code is stored (see backend/src/utils/twoFactor.js).
|
||||
model TwoFactorChallenge {
|
||||
id String @id @default(uuid())
|
||||
userId String
|
||||
user User @relation(fields: [userId], references: [id], onDelete: Cascade)
|
||||
purpose String // 'login' | 'enable'
|
||||
method TwoFactorMethod
|
||||
id String @id @default(uuid())
|
||||
userId String
|
||||
user User @relation(fields: [userId], references: [id], onDelete: Cascade)
|
||||
purpose String // 'login' | 'enable'
|
||||
method TwoFactorMethod
|
||||
// 2.3.0: an authenticator app being set up: its secret (encrypted) until the first code confirms it.
|
||||
pendingSecret String?
|
||||
codeHash String
|
||||
attempts Int @default(0)
|
||||
lastSentAt DateTime @default(now())
|
||||
expiresAt DateTime
|
||||
usedAt DateTime?
|
||||
createdAt DateTime @default(now())
|
||||
codeHash String
|
||||
attempts Int @default(0)
|
||||
lastSentAt DateTime @default(now())
|
||||
expiresAt DateTime
|
||||
usedAt DateTime?
|
||||
createdAt DateTime @default(now())
|
||||
|
||||
@@index([userId])
|
||||
}
|
||||
@@ -851,6 +856,12 @@ enum AdminAuditAction {
|
||||
product_link_disconnected
|
||||
feed_publish_toggled
|
||||
feed_show_toggled
|
||||
sign_in_move_started
|
||||
sign_in_move_finished
|
||||
sign_in_move_failed
|
||||
sign_in_move_undone
|
||||
sign_in_secrets_cleared
|
||||
account_changed_in_accounts
|
||||
}
|
||||
|
||||
// Append-only audit trail for admin/supervisor-initiated actions with money or
|
||||
@@ -970,7 +981,7 @@ model FormDraft {
|
||||
model ProviderTransaction {
|
||||
id String @id @default(uuid())
|
||||
provider String @default("yoco") // payment provider id (src/payments)
|
||||
externalId String // the provider's payment/event id
|
||||
externalId String // the provider's payment/event id
|
||||
amount Int?
|
||||
currency String?
|
||||
createdDate DateTime?
|
||||
@@ -995,19 +1006,19 @@ model ProviderTransaction {
|
||||
// can be checked against it. Its id is the payer's link (/pay/<id>) and, for PayFast, the
|
||||
// m_payment_id. `provider` is null until the payer picks one (when several are enabled).
|
||||
model ProviderCheckout {
|
||||
id String @id @default(uuid())
|
||||
id String @id @default(uuid())
|
||||
provider String?
|
||||
// The provider's own checkout id (Yoco) and where it sends the payer.
|
||||
externalId String?
|
||||
redirectUrl String?
|
||||
amountCents Int
|
||||
currency String @default("ZAR")
|
||||
currency String @default("ZAR")
|
||||
// Who/what the payment is for: registrationId, userId, eventId, type, donationAmount, …
|
||||
metadata Json
|
||||
// Everything needed to start the checkout with any provider: lineItems, return URLs, payer.
|
||||
request Json
|
||||
createdAt DateTime @default(now())
|
||||
updatedAt DateTime @updatedAt
|
||||
createdAt DateTime @default(now())
|
||||
updatedAt DateTime @updatedAt
|
||||
|
||||
@@index([provider, externalId])
|
||||
}
|
||||
@@ -1461,16 +1472,16 @@ model FeedbackField {
|
||||
|
||||
/// Who was asked. tokenHash is the HMAC of the link token (the token itself isn't stored).
|
||||
model FeedbackInvite {
|
||||
id String @id @default(uuid())
|
||||
formId String
|
||||
userId String
|
||||
tokenHash String @unique
|
||||
sentAt DateTime @default(now())
|
||||
remindedAt DateTime? // the last reminder (automatic or by hand)
|
||||
reminderCount Int @default(0)
|
||||
respondedAt DateTime?
|
||||
form FeedbackForm @relation(fields: [formId], references: [id], onDelete: Cascade)
|
||||
user User @relation(fields: [userId], references: [id], onDelete: Cascade)
|
||||
id String @id @default(uuid())
|
||||
formId String
|
||||
userId String
|
||||
tokenHash String @unique
|
||||
sentAt DateTime @default(now())
|
||||
remindedAt DateTime? // the last reminder (automatic or by hand)
|
||||
reminderCount Int @default(0)
|
||||
respondedAt DateTime?
|
||||
form FeedbackForm @relation(fields: [formId], references: [id], onDelete: Cascade)
|
||||
user User @relation(fields: [userId], references: [id], onDelete: Cascade)
|
||||
|
||||
@@unique([formId, userId])
|
||||
@@index([userId])
|
||||
@@ -1603,7 +1614,7 @@ model TicketTransfer {
|
||||
}
|
||||
|
||||
model Attendee {
|
||||
id String @id @default(uuid())
|
||||
id String @id @default(uuid())
|
||||
registrationId String
|
||||
registrationOptionId String?
|
||||
eventOptionId String
|
||||
@@ -1617,12 +1628,12 @@ model Attendee {
|
||||
parentName String?
|
||||
parentEmail String?
|
||||
parentPhone String?
|
||||
order Int @default(0)
|
||||
createdAt DateTime @default(now())
|
||||
updatedAt DateTime @updatedAt
|
||||
registration Registration @relation(fields: [registrationId], references: [id], onDelete: Cascade)
|
||||
registrationOption RegistrationOption? @relation(fields: [registrationOptionId], references: [id], onDelete: SetNull)
|
||||
user User? @relation(fields: [userId], references: [id], onDelete: SetNull)
|
||||
order Int @default(0)
|
||||
createdAt DateTime @default(now())
|
||||
updatedAt DateTime @updatedAt
|
||||
registration Registration @relation(fields: [registrationId], references: [id], onDelete: Cascade)
|
||||
registrationOption RegistrationOption? @relation(fields: [registrationOptionId], references: [id], onDelete: SetNull)
|
||||
user User? @relation(fields: [userId], references: [id], onDelete: SetNull)
|
||||
ticket Ticket?
|
||||
formResponses FormResponse[]
|
||||
consentRequests ConsentRequest[]
|
||||
@@ -1795,23 +1806,23 @@ enum CheckInWindow {
|
||||
|
||||
// One date/time of a multi-day event.
|
||||
model EventSession {
|
||||
id String @id @default(uuid())
|
||||
eventId String
|
||||
label String?
|
||||
startsAt DateTime
|
||||
endsAt DateTime
|
||||
location String?
|
||||
id String @id @default(uuid())
|
||||
eventId String
|
||||
label String?
|
||||
startsAt DateTime
|
||||
endsAt DateTime
|
||||
location String?
|
||||
// Cancelled sessions are kept (they may have check-ins) but hidden from the schedule
|
||||
// and left out of attendance totals.
|
||||
cancelledAt DateTime?
|
||||
order Int @default(0)
|
||||
cancelledAt DateTime?
|
||||
order Int @default(0)
|
||||
// Optional limit on people at this session (picked places + whole-course tickets).
|
||||
capacity Int?
|
||||
createdAt DateTime @default(now())
|
||||
updatedAt DateTime @updatedAt
|
||||
event Event @relation(fields: [eventId], references: [id], onDelete: Cascade)
|
||||
usages TicketUsage[]
|
||||
reminders SessionReminderLog[]
|
||||
capacity Int?
|
||||
createdAt DateTime @default(now())
|
||||
updatedAt DateTime @updatedAt
|
||||
event Event @relation(fields: [eventId], references: [id], onDelete: Cascade)
|
||||
usages TicketUsage[]
|
||||
reminders SessionReminderLog[]
|
||||
registrationOptions RegistrationOption[]
|
||||
waitlistEntries WaitlistEntry[]
|
||||
servingRoles ServingRole[]
|
||||
@@ -1834,24 +1845,24 @@ model SessionReminderLog {
|
||||
|
||||
// A completion certificate for one ticket (one person).
|
||||
model Certificate {
|
||||
id String @id @default(uuid())
|
||||
eventId String
|
||||
ticketId String
|
||||
userId String?
|
||||
name String
|
||||
id String @id @default(uuid())
|
||||
eventId String
|
||||
ticketId String
|
||||
userId String?
|
||||
name String
|
||||
// Short code printed on the certificate and checked on the public verify page.
|
||||
code String @unique
|
||||
sessionsAttended Int @default(0)
|
||||
totalSessions Int @default(0)
|
||||
manual Boolean @default(false)
|
||||
issuedById String?
|
||||
issuedAt DateTime @default(now())
|
||||
emailedAt DateTime?
|
||||
revokedAt DateTime?
|
||||
event Event @relation(fields: [eventId], references: [id], onDelete: Cascade)
|
||||
ticket Ticket @relation(fields: [ticketId], references: [id], onDelete: Cascade)
|
||||
user User? @relation(fields: [userId], references: [id], onDelete: SetNull)
|
||||
issuedBy User? @relation("CertificateIssuedBy", fields: [issuedById], references: [id], onDelete: SetNull)
|
||||
code String @unique
|
||||
sessionsAttended Int @default(0)
|
||||
totalSessions Int @default(0)
|
||||
manual Boolean @default(false)
|
||||
issuedById String?
|
||||
issuedAt DateTime @default(now())
|
||||
emailedAt DateTime?
|
||||
revokedAt DateTime?
|
||||
event Event @relation(fields: [eventId], references: [id], onDelete: Cascade)
|
||||
ticket Ticket @relation(fields: [ticketId], references: [id], onDelete: Cascade)
|
||||
user User? @relation(fields: [userId], references: [id], onDelete: SetNull)
|
||||
issuedBy User? @relation("CertificateIssuedBy", fields: [issuedById], references: [id], onDelete: SetNull)
|
||||
|
||||
@@unique([eventId, ticketId])
|
||||
@@index([userId])
|
||||
@@ -2187,16 +2198,16 @@ model KidsAlert {
|
||||
|
||||
// A leader on duty in a kids room for an occasion ("I'm on duty"), for the ratio.
|
||||
model KidsRoomDuty {
|
||||
id String @id @default(uuid())
|
||||
roomId String
|
||||
occasion String
|
||||
userId String
|
||||
startedAt DateTime @default(now())
|
||||
endedAt DateTime?
|
||||
id String @id @default(uuid())
|
||||
roomId String
|
||||
occasion String
|
||||
userId String
|
||||
startedAt DateTime @default(now())
|
||||
endedAt DateTime?
|
||||
// Volunteer rosters (1.46.0): started by a rostered volunteer checking in, not "I'm on duty".
|
||||
fromRoster Boolean @default(false)
|
||||
room AllocationGroup @relation(fields: [roomId], references: [id], onDelete: Cascade)
|
||||
user User @relation(fields: [userId], references: [id], onDelete: Cascade)
|
||||
fromRoster Boolean @default(false)
|
||||
room AllocationGroup @relation(fields: [roomId], references: [id], onDelete: Cascade)
|
||||
user User @relation(fields: [userId], references: [id], onDelete: Cascade)
|
||||
|
||||
@@index([roomId, occasion])
|
||||
@@index([userId])
|
||||
@@ -2288,21 +2299,21 @@ model VolunteerSwap {
|
||||
/// Outbound webhooks (1.48.0): a URL that is sent what happens here (registrations, payments,
|
||||
/// check-ins, new accounts, published events), signed with its own secret.
|
||||
model WebhookEndpoint {
|
||||
id String @id @default(uuid())
|
||||
name String
|
||||
url String
|
||||
id String @id @default(uuid())
|
||||
name String
|
||||
url String
|
||||
// HMAC secret, encrypted (utils/encryption.js); shown to the admin once, when made or rotated.
|
||||
secret String
|
||||
secret String
|
||||
// Event types it gets, e.g. ["registration.paid", "ticket.checked_in"].
|
||||
events String[]
|
||||
isActive Boolean @default(true)
|
||||
events String[]
|
||||
isActive Boolean @default(true)
|
||||
// The operator register entry made for it (POPIA), if any.
|
||||
operatorId String?
|
||||
operatorId String?
|
||||
lastSuccessAt DateTime?
|
||||
lastFailureAt DateTime?
|
||||
createdAt DateTime @default(now())
|
||||
updatedAt DateTime @updatedAt
|
||||
deliveries WebhookDelivery[]
|
||||
createdAt DateTime @default(now())
|
||||
updatedAt DateTime @updatedAt
|
||||
deliveries WebhookDelivery[]
|
||||
}
|
||||
|
||||
/// One message to one endpoint, with its retries. Kept 30 days.
|
||||
@@ -2442,3 +2453,23 @@ model ImportedEvent {
|
||||
@@index([linkId])
|
||||
@@index([endsAt])
|
||||
}
|
||||
|
||||
// 3.0.0 (docs/EVENTS-3.0-PLAN.md §3): one sign-in through the church's Accounts. The callback
|
||||
// makes it with a one-time handoff code (hashed, 60 seconds) that the page swaps for Events' own
|
||||
// token; the token carries this row's id (`asi`), so signing out can send Accounts the ID token.
|
||||
model AccountsSignIn {
|
||||
id String @id @default(uuid())
|
||||
userId String
|
||||
user User @relation(fields: [userId], references: [id], onDelete: Cascade)
|
||||
codeHash String? @unique
|
||||
codeExpires DateTime?
|
||||
codeUsedAt DateTime?
|
||||
returnTo String
|
||||
idToken String? // encrypted (utils/encryption)
|
||||
sid String?
|
||||
mfa Boolean @default(false)
|
||||
createdAt DateTime @default(now())
|
||||
|
||||
@@index([userId])
|
||||
@@index([createdAt])
|
||||
}
|
||||
|
||||
@@ -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()]));
|
||||
|
||||
@@ -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';
|
||||
}
|
||||
@@ -0,0 +1,91 @@
|
||||
/**
|
||||
* Accounts' signed calls to Events (`crosscode.identity/1`, 3.0.0, docs/EVENTS-3.0-PLAN.md §7):
|
||||
*
|
||||
* - `user.updated`: keep Events' copy of the profile and news consent current.
|
||||
* - `user.export`: Events' part of "Download my data", from the same export Events' own privacy
|
||||
* page gives (utils/privacy.exportUserData), as sections.
|
||||
* - `user.deleted`: Events' existing rules: anonymise, keeping financial records without the name;
|
||||
* `deferred` while the person has a registration for an event that hasn't ended.
|
||||
*
|
||||
* A call for someone Events doesn't know is answered as done: there's nothing here to change.
|
||||
*/
|
||||
import { IDENTITY_SCHEMA, type AccountsCall, type UserDeletedReply, type UserExportReply } from '@crosscode/contracts';
|
||||
import { updateLocalCopy, endEventsSessions } from './signin';
|
||||
|
||||
/* eslint-disable @typescript-eslint/no-require-imports -- CommonJS */
|
||||
const prisma = require('../config/db');
|
||||
const privacy = require('../utils/privacy') as {
|
||||
exportUserData(userId: string): Promise<Record<string, unknown> | null>;
|
||||
deletionBlockers(userId: string): Promise<{ eventTitle: string; endDate: Date }[]>;
|
||||
anonymiseUser(userId: string): Promise<unknown>;
|
||||
};
|
||||
/* eslint-enable @typescript-eslint/no-require-imports */
|
||||
|
||||
const TITLES: Record<string, string> = {
|
||||
account: 'Your Cross Events details',
|
||||
registrations: 'Registrations',
|
||||
payments: 'Payments',
|
||||
tickets: 'Tickets and check-ins',
|
||||
waitlist: 'Waiting lists',
|
||||
certificates: 'Certificates',
|
||||
feedback: 'Feedback you gave',
|
||||
consents: 'Message preferences (history)',
|
||||
accountActivity: 'Sign-ins to Cross Events before the move',
|
||||
dataRequests: 'Privacy requests',
|
||||
notices: 'Privacy notices accepted',
|
||||
kidsFamily: 'Family and children',
|
||||
volunteering: 'Volunteering',
|
||||
seriesFollowed: 'Series you follow',
|
||||
seasonPasses: 'Season passes',
|
||||
};
|
||||
|
||||
const sectionKey = (k: string) => k.replace(/([A-Z])/g, '_$1').toLowerCase().replace(/[^a-z0-9_]/g, '').replace(/^[^a-z]+/, '').slice(0, 50) || 'other';
|
||||
const asRecords = (v: unknown): Record<string, unknown>[] =>
|
||||
(Array.isArray(v) ? v : v && typeof v === 'object' ? [v] : []).map((x) => (x && typeof x === 'object' ? (JSON.parse(JSON.stringify(x)) as Record<string, unknown>) : { value: x }));
|
||||
|
||||
/** Events' export as `crosscode.identity/1` sections (at most 100). */
|
||||
export function exportSections(data: Record<string, unknown>) {
|
||||
return Object.entries(data)
|
||||
.filter(([, v]) => v !== null && v !== undefined)
|
||||
.map(([k, v]) => ({ key: sectionKey(k), title: TITLES[k] ?? k, records: asRecords(v) }))
|
||||
.filter((s) => s.records.length > 0)
|
||||
.slice(0, 100);
|
||||
}
|
||||
|
||||
const DEFER_HOURS = 24;
|
||||
|
||||
export async function handleAccountsCall(call: AccountsCall): Promise<object> {
|
||||
const user = await prisma.user.findUnique({ where: { accountId: call.sub }, select: { id: true } });
|
||||
switch (call.type) {
|
||||
case 'user.updated': {
|
||||
if (user) await updateLocalCopy(user.id, call.profile);
|
||||
return { schema: IDENTITY_SCHEMA, ok: true };
|
||||
}
|
||||
case 'user.export': {
|
||||
const data = user ? await privacy.exportUserData(user.id) : null;
|
||||
const reply: UserExportReply = {
|
||||
schema: IDENTITY_SCHEMA, exportId: call.exportId, sub: call.sub, product: 'events', generatedAt: new Date().toISOString(),
|
||||
sections: data ? exportSections(data) : [],
|
||||
};
|
||||
return reply;
|
||||
}
|
||||
case 'user.deleted': {
|
||||
if (!user) return { schema: IDENTITY_SCHEMA, status: 'deleted' } satisfies UserDeletedReply;
|
||||
const blockers = await privacy.deletionBlockers(user.id);
|
||||
if (blockers.length) {
|
||||
const first = blockers[0]!;
|
||||
const end = new Date(Math.max(new Date(first.endDate).getTime(), Date.now()) + DEFER_HOURS * 3600e3);
|
||||
const more = blockers.length > 1 ? ` and ${blockers.length - 1} more` : '';
|
||||
return {
|
||||
schema: IDENTITY_SCHEMA, status: 'deferred',
|
||||
reason: `Has a registration for ${first.eventTitle} (${new Date(first.endDate).toISOString().slice(0, 10)})${more}`.slice(0, 500),
|
||||
retryAfter: end.toISOString(),
|
||||
} satisfies UserDeletedReply;
|
||||
}
|
||||
await endEventsSessions(user.id);
|
||||
await privacy.anonymiseUser(user.id);
|
||||
await prisma.user.update({ where: { id: user.id }, data: { accountId: null } }).catch(() => {});
|
||||
return { schema: IDENTITY_SCHEMA, status: 'deleted' } satisfies UserDeletedReply;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,74 @@
|
||||
/**
|
||||
* The church's Accounts, as this site's OIDC client (3.0.0, docs/EVENTS-3.0-PLAN.md §1): built on
|
||||
* `@crosscode/auth-client` from the Accounts link that Connect made (Settings → Linked products).
|
||||
* Its address is the one the Hub listed; its client id is this site's Hub install id and its client
|
||||
* secret comes from the link's secret, so there's no `.env` setting for any of it.
|
||||
*
|
||||
* `@crosscode/auth-client` and `openid-client` are ES modules and this backend is CommonJS, which
|
||||
* compiles `import()` into `require()`. The loader below keeps a real dynamic import, so it works on
|
||||
* every Node the servers run (20+), not only where `require()` of ES modules is allowed.
|
||||
*/
|
||||
import type { AccountsClient } from '@crosscode/auth-client';
|
||||
import { hubInstallId, siteUrl } from '../feed/context';
|
||||
|
||||
/* eslint-disable @typescript-eslint/no-require-imports -- CommonJS */
|
||||
const prisma = require('../config/db');
|
||||
const { decrypt } = require('../utils/encryption') as { decrypt(v: string): string };
|
||||
/* eslint-enable @typescript-eslint/no-require-imports */
|
||||
|
||||
export type AuthClientModule = typeof import('@crosscode/auth-client');
|
||||
|
||||
// eslint-disable-next-line @typescript-eslint/no-implied-eval -- a real import(), see above
|
||||
const importEsm = new Function('specifier', 'return import(specifier)') as (s: string) => Promise<AuthClientModule>;
|
||||
let loader: () => Promise<AuthClientModule> = () => importEsm('@crosscode/auth-client');
|
||||
|
||||
/** Tests: use another auth-client (a fake, or the real one loaded another way). */
|
||||
export function setAuthClientLoader(next: () => Promise<AuthClientModule>): void {
|
||||
loader = next;
|
||||
cached = null;
|
||||
}
|
||||
|
||||
export class AccountsUnavailable extends Error {
|
||||
status = 503;
|
||||
code = 'ACCOUNTS_UNAVAILABLE';
|
||||
}
|
||||
|
||||
export type AccountsLink = { installId: string; url: string; secret: string; updatedAt: Date };
|
||||
|
||||
/** The Accounts link, or null when Accounts isn't connected. */
|
||||
export async function accountsLink(): Promise<AccountsLink | null> {
|
||||
return prisma.productLink.findFirst({ where: { product: 'accounts' }, orderBy: { connectedAt: 'desc' } });
|
||||
}
|
||||
|
||||
let cached: { key: string; client: Promise<AccountsClient> } | null = null;
|
||||
|
||||
/** The client for the church's Accounts (discovery done once per link). Throws AccountsUnavailable. */
|
||||
export async function accounts(): Promise<AccountsClient> {
|
||||
const link = await accountsLink();
|
||||
if (!link) throw new AccountsUnavailable('Accounts isn\'t connected. Connect it under Settings → Linked products.');
|
||||
const [clientId, productUrl] = await Promise.all([hubInstallId(), siteUrl()]);
|
||||
if (!clientId) throw new AccountsUnavailable('This site isn\'t connected to the Hub yet.');
|
||||
const key = `${link.installId}|${new Date(link.updatedAt).getTime()}|${clientId}|${productUrl}`;
|
||||
if (!cached || cached.key !== key) {
|
||||
const client = loader().then((m) => m.accountsClient({
|
||||
accountsUrl: link.url,
|
||||
productUrl,
|
||||
clientId,
|
||||
linkSecret: decrypt(link.secret),
|
||||
allowInsecure: process.env.NODE_ENV !== 'production' && link.url.startsWith('http:'),
|
||||
}));
|
||||
// A failed discovery (Accounts down for a moment) is tried again next time.
|
||||
client.catch(() => { if (cached?.key === key) cached = null; });
|
||||
cached = { key, client };
|
||||
}
|
||||
try {
|
||||
return await cached.client;
|
||||
} catch (e) {
|
||||
throw new AccountsUnavailable(`Accounts can't be reached right now (${(e as Error).message}). Please try again in a minute.`);
|
||||
}
|
||||
}
|
||||
|
||||
/** The module itself (for its error classes). */
|
||||
export function authClientModule(): Promise<AuthClientModule> {
|
||||
return loader();
|
||||
}
|
||||
@@ -0,0 +1,106 @@
|
||||
/**
|
||||
* Cross Events' own sign-in, once sign-in goes through Accounts (3.0.0, docs/EVENTS-3.0-PLAN.md §6).
|
||||
* Mounted after express.json, before the API:
|
||||
*
|
||||
* - Signing in, signing up, passwords, activation and 2FA here answer 409 `SIGN_IN_MOVED` with
|
||||
* where to go instead (the frontend forwards there).
|
||||
* - While a move runs, Events' own sign-in waits (503 `SIGN_IN_MOVING`).
|
||||
* - Changing my name, email or phone is done in Accounts (`PATCH /me` keeps the rest).
|
||||
* - An admin changing someone's name, email or phone (`PATCH /users/:id`) changes their account in
|
||||
* Accounts first (`people.update`), then Events' copy; a password or 2FA change is refused.
|
||||
*/
|
||||
import type { NextFunction, Request, Response } from 'express';
|
||||
import { accounts, AccountsUnavailable } from './client';
|
||||
import { getSetting, viaAccounts } from './mode';
|
||||
import { RUNNING_KEY } from './move';
|
||||
|
||||
/* eslint-disable @typescript-eslint/no-require-imports -- CommonJS */
|
||||
const prisma = require('../config/db');
|
||||
/* eslint-enable @typescript-eslint/no-require-imports */
|
||||
|
||||
const MOVED = [
|
||||
'POST /api/v2/auth/login', 'POST /api/v2/auth/login/code', 'POST /api/v2/auth/login/code/resend', 'POST /api/v2/auth/signup',
|
||||
'POST /api/v2/auth/password/forgot', 'POST /api/v2/auth/password/reset', 'POST /api/v2/auth/activate',
|
||||
'POST /api/v2/me/verify-password', 'POST /api/v2/me/close',
|
||||
];
|
||||
const MOVED_PREFIXES = ['POST /api/v2/me/two-factor/'];
|
||||
const LOCAL_SIGN_IN = ['POST /api/v2/auth/login', 'POST /api/v2/auth/login/code', 'POST /api/v2/auth/signup', 'POST /api/v2/auth/activate'];
|
||||
|
||||
const movedAnswer = (res: Response) => res.status(409).json({
|
||||
error: {
|
||||
code: 'SIGN_IN_MOVED',
|
||||
message: 'Signing in, passwords and two-step sign-in are now on your church account. Use "Sign in" to continue.',
|
||||
signInUrl: '/api/auth/signin',
|
||||
},
|
||||
});
|
||||
|
||||
export async function signInGuard(req: Request, res: Response, next: NextFunction) {
|
||||
const key = `${req.method} ${req.path.replace(/\/+$/, '')}`;
|
||||
const isMoved = MOVED.includes(key) || MOVED_PREFIXES.some((p) => key.startsWith(p));
|
||||
const isMe = key === 'PATCH /api/v2/me';
|
||||
const isAdminEdit = /^PATCH \/api\/v2\/users\/[^/]+$/.test(key);
|
||||
if (!isMoved && !isMe && !isAdminEdit) return next();
|
||||
try {
|
||||
if (!(await viaAccounts())) {
|
||||
if (LOCAL_SIGN_IN.includes(key)) {
|
||||
const running = await getSetting(RUNNING_KEY);
|
||||
if (running && Date.now() - new Date(running).getTime() < 30 * 60e3) {
|
||||
return res.status(503).json({ error: { code: 'SIGN_IN_MOVING', message: 'One moment, we\'re updating the sign-in. Please try again in a minute.' } });
|
||||
}
|
||||
}
|
||||
return next();
|
||||
}
|
||||
if (isMoved) return movedAnswer(res);
|
||||
const body = (req.body ?? {}) as Record<string, unknown>;
|
||||
if (isMe) {
|
||||
if (body.password !== undefined || body.currentPassword !== undefined) return movedAnswer(res);
|
||||
delete body.name;
|
||||
delete body.email;
|
||||
delete body.phone;
|
||||
return next();
|
||||
}
|
||||
// An admin's change to someone (the route itself checks they're an admin).
|
||||
if (body.password !== undefined || body.twoFactorEnabled !== undefined) return movedAnswer(res);
|
||||
const changes: { name?: string; email?: string; phone?: string | null } = {};
|
||||
if (typeof body.name === 'string') changes.name = body.name.trim();
|
||||
if (typeof body.email === 'string') changes.email = body.email.trim().toLowerCase();
|
||||
if (body.phoneNumber !== undefined) changes.phone = body.phoneNumber ? String(body.phoneNumber) : null;
|
||||
if (!Object.keys(changes).length) return next();
|
||||
const target = await prisma.user.findUnique({ where: { id: String(req.params?.id ?? req.path.split('/').pop()) }, select: { id: true, accountId: true, name: true, email: true, phoneNumber: true } });
|
||||
if (!target?.accountId) return next();
|
||||
const differs = (changes.name !== undefined && changes.name !== target.name) || (changes.email !== undefined && changes.email !== target.email) || (changes.phone !== undefined && changes.phone !== target.phoneNumber);
|
||||
if (!differs) return next();
|
||||
// Only for a signed-in admin: anyone else is refused by the route itself, untouched here.
|
||||
const admin = await signedInAdmin(req);
|
||||
if (!admin) return next();
|
||||
await (await accounts()).request({ type: 'people.update', actor: admin.accountId, sub: target.accountId, ...changes });
|
||||
return next();
|
||||
} catch (e) {
|
||||
if (e instanceof AccountsUnavailable) return res.status(503).json({ error: { code: 'UNAVAILABLE', message: e.message } });
|
||||
const err = e as { code?: string; message: string };
|
||||
if (err.code === 'EMAIL_TAKEN') return res.status(409).json({ error: { code: 'CONFLICT', message: 'Another account has that email address.' } });
|
||||
if (err.code) return res.status(502).json({ error: { code: 'UNAVAILABLE', message: `Accounts didn't accept the change: ${err.message}` } });
|
||||
return next(e);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* The request's user when it's a valid, current admin token (as `protect` + `admin` would accept,
|
||||
* not viewing as someone else), or null. Their `accountId` goes to Accounts' audit log.
|
||||
*/
|
||||
async function signedInAdmin(req: Request): Promise<{ id: string; accountId: string | null } | null> {
|
||||
try {
|
||||
const header = String(req.headers.authorization || '');
|
||||
if (!header.startsWith('Bearer ')) return null;
|
||||
// eslint-disable-next-line @typescript-eslint/no-require-imports
|
||||
const jwt = require('jsonwebtoken');
|
||||
const decoded = jwt.verify(header.slice(7), process.env.JWT_SECRET, { algorithms: ['HS256'] }) as { id?: string; tokenVersion?: number; imp?: string; asi?: string; mfa?: boolean };
|
||||
// Viewing as someone, or an Accounts sign-in without the second step admins need.
|
||||
if (!decoded.id || decoded.imp || (decoded.asi && decoded.mfa !== true)) return null;
|
||||
const u = await prisma.user.findUnique({ where: { id: decoded.id }, select: { id: true, accountId: true, role: true, isActive: true, tokenVersion: true } });
|
||||
if (!u || !u.isActive || u.role !== 'admin' || (decoded.tokenVersion ?? 0) !== u.tokenVersion) return null;
|
||||
return { id: u.id, accountId: u.accountId };
|
||||
} catch {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,31 @@
|
||||
/**
|
||||
* This site's look (3.1.0) for the church's Accounts sign-in pages: its name, logo and colours, so
|
||||
* signing in looks like the church's own site. Sent with a move (filling what Accounts doesn't have
|
||||
* yet) and by Settings → Sign-in → "Use this site's logo and colours" (replacing it).
|
||||
*/
|
||||
import type { ChurchLook } from '@crosscode/contracts';
|
||||
import { siteUrl } from '../feed/context';
|
||||
|
||||
/* eslint-disable @typescript-eslint/no-require-imports -- CommonJS */
|
||||
const { getSetting } = require('../utils/settingsCache') as { getSetting(k: string, f?: string): Promise<string> };
|
||||
/* eslint-enable @typescript-eslint/no-require-imports */
|
||||
|
||||
const hex = (v: string) => (/^#[0-9a-fA-F]{6}$/.test(v) ? v : null);
|
||||
|
||||
export async function churchLook(): Promise<ChurchLook> {
|
||||
const name = (await getSetting('org_name', '')) || (await getSetting('site_name', '')) || null;
|
||||
const primary = hex(await getSetting('primary_color', '')) || hex(await getSetting('brand_color', ''));
|
||||
const accent = hex(await getSetting('accent_color', '')) || hex(await getSetting('secondary_color', ''));
|
||||
// The logo as an address anyone can load: an uploaded one is a path on this site.
|
||||
const raw = String(await getSetting('logo_url', '')).trim();
|
||||
let logoUrl: string | null = null;
|
||||
if (raw) {
|
||||
try {
|
||||
const u = new URL(raw, `${(await siteUrl()).replace(/\/+$/, '')}/`);
|
||||
if (/^https?:$/.test(u.protocol)) logoUrl = u.toString();
|
||||
} catch {
|
||||
logoUrl = null;
|
||||
}
|
||||
}
|
||||
return { name: name ? name.slice(0, 200) : null, primaryColour: primary, accentColour: accent, logoUrl };
|
||||
}
|
||||
@@ -0,0 +1,85 @@
|
||||
/**
|
||||
* Email and WhatsApp for the church's Accounts (3.1.0). Accounts sends its own sign-in codes and
|
||||
* password links, with its own settings, which a move doesn't bring along: a church that moved
|
||||
* sign-in without them couldn't sign in at all. Settings → Sign-in therefore shows what Accounts can
|
||||
* send, offers this site's own SMTP and WAWP settings to copy (the password and token stay on the
|
||||
* server: blank means "use this site's"), tests them through Accounts, and saves them there only
|
||||
* once the test worked (`crosscode.identity-request/1` messaging.*, contracts 1.9.0). The move
|
||||
* itself needs Accounts' email to work (move.ts).
|
||||
*/
|
||||
import type { MessagingStatusReply, MessagingTestReply } from '@crosscode/contracts';
|
||||
import { accounts } from './client';
|
||||
|
||||
/* eslint-disable @typescript-eslint/no-require-imports -- CommonJS */
|
||||
const { getSetting } = require('../utils/settingsCache') as { getSetting(k: string, f?: string): Promise<string> };
|
||||
const whatsapp = require('../utils/whatsapp') as { getConfig(): Promise<{ token: string; instanceId: string }> };
|
||||
/* eslint-enable @typescript-eslint/no-require-imports */
|
||||
|
||||
type Smtp = { host: string; port: number; secure: boolean; user: string; pass: string; from: string };
|
||||
|
||||
/** This site's SMTP settings, as utils/email.js reads them (the database, then the .env). */
|
||||
async function eventsSmtp(): Promise<Smtp | null> {
|
||||
const env = process.env;
|
||||
const host = await getSetting('smtp_host', env.SMTP_HOST || env.EMAIL_HOST || '');
|
||||
if (!host) return null;
|
||||
const port = parseInt(await getSetting('smtp_port', env.SMTP_PORT || env.EMAIL_PORT || '587'), 10) || 587;
|
||||
return {
|
||||
host,
|
||||
port,
|
||||
secure: String(await getSetting('smtp_secure', env.SMTP_SECURE || env.EMAIL_SECURE || 'false')).toLowerCase() === 'true',
|
||||
user: await getSetting('smtp_user', env.SMTP_USER || env.EMAIL_USER || ''),
|
||||
pass: await getSetting('smtp_pass', env.SMTP_PASS || env.EMAIL_PASS || ''),
|
||||
from: await getSetting('smtp_from', env.MAIL_FROM || env.EMAIL_FROM || ''),
|
||||
};
|
||||
}
|
||||
|
||||
/** What this site has, to offer for copying: never the password or token themselves. */
|
||||
export async function eventsMessaging() {
|
||||
const smtp = await eventsSmtp();
|
||||
const wa = await whatsapp.getConfig().catch(() => ({ token: '', instanceId: '' }));
|
||||
return {
|
||||
email: smtp ? { host: smtp.host, port: smtp.port, secure: smtp.secure, user: smtp.user, from: smtp.from || smtp.user, hasPass: !!smtp.pass } : null,
|
||||
whatsapp: wa.instanceId ? { instanceId: wa.instanceId, hasToken: !!wa.token } : null,
|
||||
};
|
||||
}
|
||||
|
||||
/** What Accounts can send now. */
|
||||
export async function accountsMessaging(): Promise<Omit<MessagingStatusReply, 'schema'>> {
|
||||
const r = await (await accounts()).request<MessagingStatusReply>({ type: 'messaging.status', actor: null });
|
||||
return { email: r.email, whatsapp: r.whatsapp };
|
||||
}
|
||||
|
||||
export type MessagingInput = {
|
||||
email?: { host: string; port: number; secure: boolean; user: string; from: string; pass?: string | null; to: string };
|
||||
whatsapp?: { instanceId: string; accessToken?: string | null; to: string };
|
||||
};
|
||||
|
||||
/**
|
||||
* Tests (and with `save`, saves) settings in Accounts. A blank password or token means this site's
|
||||
* own; Accounts gets it sealed with the link's secret. Returns Accounts' answer per part.
|
||||
*/
|
||||
export async function sendToAccounts(input: MessagingInput, opts: { save: boolean; actor: string | null }): Promise<Omit<MessagingTestReply, 'schema'>> {
|
||||
const auth = await accounts();
|
||||
let email;
|
||||
if (input.email) {
|
||||
const own = await eventsSmtp();
|
||||
const pass = input.email.pass ? input.email.pass : (own?.pass ?? '');
|
||||
email = {
|
||||
settings: { host: input.email.host.trim(), port: input.email.port, secure: input.email.secure, user: input.email.user.trim(), from: input.email.from.trim(), pass: pass ? auth.seal(pass) : null },
|
||||
to: input.email.to.trim(),
|
||||
};
|
||||
}
|
||||
let wa;
|
||||
if (input.whatsapp) {
|
||||
const own = await whatsapp.getConfig().catch(() => ({ token: '', instanceId: '' }));
|
||||
const token = input.whatsapp.accessToken ? input.whatsapp.accessToken : own.token;
|
||||
wa = { settings: { instanceId: input.whatsapp.instanceId.trim(), accessToken: token ? auth.seal(token) : null }, to: input.whatsapp.to.trim() };
|
||||
}
|
||||
const r = await auth.request<MessagingTestReply>({
|
||||
type: opts.save ? 'messaging.set' : 'messaging.test',
|
||||
actor: opts.actor,
|
||||
...(email ? { email } : {}),
|
||||
...(wa ? { whatsapp: wa } : {}),
|
||||
}, { timeoutMs: 60000 });
|
||||
return { email: r.email, whatsapp: r.whatsapp, status: r.status };
|
||||
}
|
||||
@@ -0,0 +1,49 @@
|
||||
/**
|
||||
* Where people sign in (3.0.0, docs/EVENTS-3.0-PLAN.md §5): `local` (Cross Events' own sign-in, as
|
||||
* 2.x, before the move or after Undo) or `accounts` (through the church's Accounts). Kept in
|
||||
* AppSetting `auth_mode`; read with a short cache, so every PM2 process follows a move within
|
||||
* seconds. A new install starts in `accounts` (§9); everyone else starts in `local`.
|
||||
*
|
||||
* Other keys: `auth_moved_at` (ISO, when the move finished: Undo is allowed for 14 days, then the
|
||||
* old secrets are cleared), `auth_move_report` (JSON), `auth_secrets_cleared_at` (ISO).
|
||||
*/
|
||||
/* eslint-disable @typescript-eslint/no-require-imports -- CommonJS */
|
||||
const prisma = require('../config/db');
|
||||
/* eslint-enable @typescript-eslint/no-require-imports */
|
||||
|
||||
export type AuthMode = 'local' | 'accounts';
|
||||
export const MODE_KEY = 'auth_mode';
|
||||
export const MOVED_AT_KEY = 'auth_moved_at';
|
||||
export const REPORT_KEY = 'auth_move_report';
|
||||
export const CLEARED_KEY = 'auth_secrets_cleared_at';
|
||||
export const UNDO_DAYS = 14;
|
||||
|
||||
const TTL_MS = 5000;
|
||||
let cache: { mode: AuthMode; at: number } | null = null;
|
||||
|
||||
export async function authMode(): Promise<AuthMode> {
|
||||
if (cache && Date.now() - cache.at < TTL_MS) return cache.mode;
|
||||
const row = await prisma.appSetting.findUnique({ where: { key: MODE_KEY } }).catch(() => null);
|
||||
const mode: AuthMode = row?.value === 'accounts' ? 'accounts' : 'local';
|
||||
cache = { mode, at: Date.now() };
|
||||
return mode;
|
||||
}
|
||||
|
||||
export async function viaAccounts(): Promise<boolean> {
|
||||
return (await authMode()) === 'accounts';
|
||||
}
|
||||
|
||||
export async function setSetting(key: string, value: string | null): Promise<void> {
|
||||
if (value === null) await prisma.appSetting.deleteMany({ where: { key } });
|
||||
else await prisma.appSetting.upsert({ where: { key }, update: { value }, create: { key, value } });
|
||||
if (key === MODE_KEY) cache = null;
|
||||
}
|
||||
|
||||
export async function getSetting(key: string): Promise<string | null> {
|
||||
return (await prisma.appSetting.findUnique({ where: { key } }))?.value ?? null;
|
||||
}
|
||||
|
||||
/** For tests. */
|
||||
export function forgetMode(): void {
|
||||
cache = null;
|
||||
}
|
||||
@@ -0,0 +1,378 @@
|
||||
/**
|
||||
* Moving sign-in to the church's Accounts (3.0.0, docs/EVENTS-3.0-PLAN.md §4–§5), from
|
||||
* Settings → Sign-in:
|
||||
*
|
||||
* check() a dry run: who would be moved, linked to an existing account, skipped or refused
|
||||
* move() copies everyone into Accounts (crosscode.identity-request/1, batches of 200, secrets
|
||||
* sealed with the link's secret), checks Accounts holds the same people, then switches
|
||||
* `auth_mode` to `accounts`. Idempotent: a failed move can be run again
|
||||
* undo() back to Cross Events' own sign-in, for 14 days (the old passwords are still here)
|
||||
* clearOldSecrets() after those 14 days: Events' password hashes, authenticator secrets,
|
||||
* recovery codes and trusted devices go (the `accounts-secrets` job)
|
||||
*
|
||||
* Who moves: everyone with a real email address who isn't linked yet. Guests (`@guest.local`) and
|
||||
* deleted people stay Events-only. Recovery codes don't move (decision 2): Accounts shows new ones.
|
||||
*/
|
||||
import crypto from 'node:crypto';
|
||||
import { IMPORT_BATCH_MAX, phoneSchema, type ImportPerson, type ImportResult } from '@crosscode/contracts';
|
||||
import { siteUrl } from '../feed/context';
|
||||
import { accounts, accountsLink, AccountsUnavailable } from './client';
|
||||
import { accountsMessaging } from './messaging';
|
||||
import { churchLook } from './look';
|
||||
import { authMode, CLEARED_KEY, getSetting, MODE_KEY, MOVED_AT_KEY, REPORT_KEY, setSetting, UNDO_DAYS } from './mode';
|
||||
|
||||
/* eslint-disable @typescript-eslint/no-require-imports -- CommonJS */
|
||||
const prisma = require('../config/db');
|
||||
const { decrypt } = require('../utils/encryption') as { decrypt(v: string): string };
|
||||
const { logAdminAction } = require('../utils/adminAudit') as { logAdminAction(entry: object): Promise<void> };
|
||||
/* eslint-enable @typescript-eslint/no-require-imports */
|
||||
|
||||
export class MoveError extends Error {
|
||||
constructor(message: string, public code = 'MOVE_FAILED', public status = 409) {
|
||||
super(message);
|
||||
}
|
||||
}
|
||||
|
||||
/** While a move runs, Cross Events' own sign-in waits (people already signed in stay signed in). */
|
||||
export const RUNNING_KEY = 'auth_move_running';
|
||||
const MIN_ACCOUNTS = [1, 1, 0];
|
||||
|
||||
const NOT_MOVED = /@(guest\.local|deleted\.invalid|deleted\.local)$/i;
|
||||
const HASH = /^(\$argon2(id|i|d)\$|\$2[aby]\$)/;
|
||||
const iso = (d: Date | string | null | undefined) => (d ? new Date(d).toISOString() : null);
|
||||
|
||||
type Row = {
|
||||
id: string; name: string; email: string; phoneNumber: string | null; password: string; role: string; isActive: boolean; createdAt: Date;
|
||||
failedAttempts: number; lockUntil: Date | null; twoFactorEnabled: boolean; twoFactorMethod: string | null; totpSecret: string | null; totpLastStep: number | null;
|
||||
newsEmail: boolean; newsWhatsApp: boolean; newsAskedAt: Date | null; noticeVersionAccepted: number | null; lastLoginAt: Date | null;
|
||||
};
|
||||
|
||||
const SELECT = {
|
||||
id: true, name: true, email: true, phoneNumber: true, password: true, role: true, isActive: true, createdAt: true, failedAttempts: true, lockUntil: true,
|
||||
twoFactorEnabled: true, twoFactorMethod: true, totpSecret: true, totpLastStep: true, newsEmail: true, newsWhatsApp: true, newsAskedAt: true,
|
||||
noticeVersionAccepted: true, lastLoginAt: true,
|
||||
} as const;
|
||||
|
||||
/** The people who move: a real email, not linked yet. */
|
||||
async function peopleToMove(): Promise<Row[]> {
|
||||
const rows: Row[] = await prisma.user.findMany({ where: { accountId: null }, select: SELECT, orderBy: { createdAt: 'asc' } });
|
||||
return rows.filter((u) => !NOT_MOVED.test(u.email));
|
||||
}
|
||||
|
||||
async function skippedCount(): Promise<number> {
|
||||
const rows: { email: string }[] = await prisma.user.findMany({ where: { accountId: null }, select: { email: true } });
|
||||
return rows.filter((u) => NOT_MOVED.test(u.email)).length;
|
||||
}
|
||||
|
||||
/** Accounts' notice versions are Events' + 1: its built-in notice is 1, Events' is 0 (null: never accepted). */
|
||||
const toAccountsVersion = (v: number | null) => (v === null || v === undefined ? 0 : v + 1);
|
||||
|
||||
/** Never activated (made by staff, the link not used yet): Accounts' "choose your password" instead. */
|
||||
const pendingActivation = (u: Row) => !u.isActive && !u.lastLoginAt;
|
||||
|
||||
async function person(u: Row, opts: { admins: Set<string>; seal: (v: string) => string; keepAccountsNotices: boolean }): Promise<ImportPerson> {
|
||||
const [acceptances, consents] = await Promise.all([
|
||||
prisma.noticeAcceptance.findMany({ where: { userId: u.id }, select: { version: true, createdAt: true }, orderBy: { createdAt: 'asc' }, take: 100 }),
|
||||
prisma.communicationConsent.findMany({ where: { userId: u.id }, select: { channel: true, granted: true, createdAt: true }, orderBy: { createdAt: 'asc' }, take: 500 }),
|
||||
]);
|
||||
const totp = u.twoFactorEnabled && u.twoFactorMethod === 'authenticator' && u.totpSecret ? (() => { try { return decrypt(u.totpSecret!); } catch { return null; } })() : null;
|
||||
// An authenticator whose secret can't be read moves without 2FA rather than locking them out.
|
||||
const twoFactor = !u.twoFactorEnabled ? null : u.twoFactorMethod === 'authenticator' ? (totp ? 'totp' as const : null) : u.twoFactorMethod === 'whatsapp' ? 'whatsapp' as const : 'email' as const;
|
||||
const phone = u.phoneNumber && phoneSchema.safeParse(u.phoneNumber).success ? u.phoneNumber : null;
|
||||
return {
|
||||
id: u.id,
|
||||
name: (u.name || '').trim().slice(0, 200) || u.email,
|
||||
email: u.email.trim().toLowerCase(),
|
||||
emailVerified: !!u.lastLoginAt,
|
||||
phone,
|
||||
passwordHash: !pendingActivation(u) && HASH.test(u.password) ? opts.seal(u.password) : null,
|
||||
twoFactor: twoFactor === 'whatsapp' && !phone ? 'email' : twoFactor,
|
||||
totpSecret: totp ? opts.seal(totp) : null,
|
||||
totpLastStep: totp ? u.totpLastStep ?? null : null,
|
||||
failedSignIns: Math.min(1000, Math.max(0, u.failedAttempts || 0)),
|
||||
lockedUntil: iso(u.lockUntil),
|
||||
news: { email: !!u.newsEmail, whatsapp: !!u.newsWhatsApp },
|
||||
newsAskedAt: iso(u.newsAskedAt),
|
||||
noticeVersionAccepted: opts.keepAccountsNotices ? 0 : toAccountsVersion(u.noticeVersionAccepted),
|
||||
noticeAcceptances: opts.keepAccountsNotices ? [] : acceptances.map((a: { version: number; createdAt: Date }) => ({ version: a.version + 1, acceptedAt: iso(a.createdAt)! })),
|
||||
consentChanges: consents.filter((c: { channel: string }) => c.channel === 'email' || c.channel === 'whatsapp').map((c: { channel: 'email' | 'whatsapp'; granted: boolean; createdAt: Date }) => ({ channel: c.channel, granted: c.granted, at: iso(c.createdAt)! })),
|
||||
lastSignInAt: iso(u.lastLoginAt),
|
||||
status: u.isActive || pendingActivation(u) ? 'active' : 'deactivated',
|
||||
admin: opts.admins.has(u.id) && u.role === 'admin',
|
||||
createdAt: iso(u.createdAt)!,
|
||||
};
|
||||
}
|
||||
|
||||
/** Events' published notice versions, as Accounts numbers them. */
|
||||
async function notices() {
|
||||
const rows: { version: number; sections: unknown; publishedAt: Date }[] = await prisma.privacyNotice.findMany({ orderBy: { version: 'asc' }, take: 100 });
|
||||
return rows.map((n) => {
|
||||
const sections = Array.isArray(n.sections) ? (n.sections as { title?: string; body?: string }[]) : [];
|
||||
const body = sections.map((s) => [s.title ? `${s.title}` : '', s.body ?? ''].filter(Boolean).join('\n\n')).join('\n\n').slice(0, 200_000) || 'Privacy notice';
|
||||
return { version: n.version + 1, title: 'Privacy notice', body, publishedAt: iso(n.publishedAt)! };
|
||||
});
|
||||
}
|
||||
|
||||
function versionAtLeast(v: string, min: number[]) {
|
||||
const parts = String(v).split('.').map((x) => parseInt(x, 10) || 0);
|
||||
for (let i = 0; i < min.length; i++) {
|
||||
if ((parts[i] ?? 0) !== min[i]) return (parts[i] ?? 0) > min[i]!;
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
const chunk = <T,>(list: T[], n: number) => Array.from({ length: Math.ceil(list.length / n) }, (_, i) => list.slice(i * n, i * n + n));
|
||||
|
||||
export type MoveSummary = {
|
||||
mode: 'local' | 'accounts';
|
||||
accountsConnected: boolean;
|
||||
accountsUrl: string | null;
|
||||
movedAt: string | null;
|
||||
undoUntil: string | null;
|
||||
secretsCleared: boolean;
|
||||
running: boolean;
|
||||
report: unknown;
|
||||
};
|
||||
|
||||
export async function status(): Promise<MoveSummary> {
|
||||
const [mode, link, movedAt, cleared, report, running] = await Promise.all([authMode(), accountsLink(), getSetting(MOVED_AT_KEY), getSetting(CLEARED_KEY), getSetting(REPORT_KEY), getSetting(RUNNING_KEY)]);
|
||||
const undoUntil = movedAt && !cleared ? new Date(new Date(movedAt).getTime() + UNDO_DAYS * 86400e3).toISOString() : null;
|
||||
return {
|
||||
mode, accountsConnected: !!link, accountsUrl: link?.url ?? null, movedAt, undoUntil, secretsCleared: !!cleared,
|
||||
running: !!running && Date.now() - new Date(running).getTime() < 30 * 60e3,
|
||||
report: report ? JSON.parse(report) : null,
|
||||
};
|
||||
}
|
||||
|
||||
|
||||
export type CheckResult = {
|
||||
accountsVersion: string;
|
||||
toMove: number;
|
||||
wouldCreate: number;
|
||||
wouldLink: { name: string; email: string }[];
|
||||
refused: { name: string; email: string; reason: string }[];
|
||||
skipped: number;
|
||||
admins: { id: string; name: string; email: string }[];
|
||||
noticeConflict: { accountsVersions: number[]; eventsVersions: number[] } | null;
|
||||
withTwoFactor: number;
|
||||
/** 3.1.0: what Accounts can send. The move needs email (codes and password links); WhatsApp codes go by email when WhatsApp can't. */
|
||||
messaging: { email: boolean; whatsapp: boolean; whatsappTwoFactor: number };
|
||||
};
|
||||
|
||||
async function connected() {
|
||||
if ((await authMode()) === 'accounts') throw new MoveError('Sign-in already goes through Accounts.', 'ALREADY_MOVED');
|
||||
try {
|
||||
return await accounts();
|
||||
} catch (e) {
|
||||
if (e instanceof AccountsUnavailable) throw new MoveError(e.message, 'ACCOUNTS_UNAVAILABLE', 503);
|
||||
throw e;
|
||||
}
|
||||
}
|
||||
|
||||
/** The dry run: nothing is written, here or in Accounts. */
|
||||
export async function check(): Promise<CheckResult> {
|
||||
const auth = await connected();
|
||||
const begin = await auth.request<{ noticesTaken: boolean; accountsNoticeVersions: number[]; accountsVersion: string }>({ type: 'import.begin', actor: null, check: true, notices: [], church: await churchLook() });
|
||||
if (!versionAtLeast(begin.accountsVersion, MIN_ACCOUNTS)) {
|
||||
throw new MoveError(`The church's Accounts is version ${begin.accountsVersion}; moving sign-in needs 1.1.0 or later. Update Accounts first.`, 'ACCOUNTS_TOO_OLD');
|
||||
}
|
||||
const people = await peopleToMove();
|
||||
const seal = (v: string) => auth.seal(v);
|
||||
const byId = new Map(people.map((p) => [p.id, p]));
|
||||
const results: ImportResult[] = [];
|
||||
for (const batch of chunk(people, IMPORT_BATCH_MAX)) {
|
||||
const built = await Promise.all(batch.map((u) => person(u, { admins: new Set(), seal, keepAccountsNotices: false })));
|
||||
const r = await auth.request<{ results: ImportResult[] }>({ type: 'import.batch', actor: null, check: true, people: built });
|
||||
results.push(...r.results);
|
||||
}
|
||||
const eventsNotices = await notices();
|
||||
const who = (id: string) => ({ name: byId.get(id)?.name ?? '', email: byId.get(id)?.email ?? '' });
|
||||
return {
|
||||
accountsVersion: begin.accountsVersion,
|
||||
toMove: people.length,
|
||||
wouldCreate: results.filter((r) => r.outcome === 'created' || r.outcome === 'updated').length,
|
||||
wouldLink: results.filter((r) => r.outcome === 'linked').map((r) => who(r.id)),
|
||||
refused: results.filter((r) => r.outcome === 'refused').map((r) => ({ ...who(r.id), reason: r.reason ?? '' })),
|
||||
skipped: await skippedCount(),
|
||||
admins: people.filter((p) => p.role === 'admin').map((p) => ({ id: p.id, name: p.name, email: p.email })),
|
||||
noticeConflict: !begin.noticesTaken && eventsNotices.length ? { accountsVersions: begin.accountsNoticeVersions, eventsVersions: eventsNotices.map((n) => n.version - 1) } : null,
|
||||
withTwoFactor: people.filter((p) => p.twoFactorEnabled).length,
|
||||
messaging: await messagingNow(people),
|
||||
};
|
||||
}
|
||||
|
||||
async function messagingNow(people: Row[]) {
|
||||
const status = await accountsMessaging();
|
||||
return { email: status.email.ready, whatsapp: status.whatsapp.ready, whatsappTwoFactor: people.filter((p) => p.twoFactorEnabled && p.twoFactorMethod === 'whatsapp').length };
|
||||
}
|
||||
|
||||
export type MoveReport = {
|
||||
movedAt: string;
|
||||
by: string;
|
||||
created: number;
|
||||
linked: { name: string; email: string }[];
|
||||
refused: { name: string; email: string; reason: string }[];
|
||||
skipped: number;
|
||||
accountsAdmins: { name: string; email: string }[];
|
||||
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<ReturnType<typeof accounts>>, 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<MoveReport> {
|
||||
const auth = await connected();
|
||||
// 3.1.0: without email in Accounts nobody can get a code or a password link there, so nobody
|
||||
// could sign in after the move. Set it up first (Settings → Sign-in → Email and WhatsApp).
|
||||
const messaging = await accountsMessaging();
|
||||
if (!messaging.email.ready) {
|
||||
throw new MoveError("The church's Accounts can't send email yet, so people couldn't get their sign-in codes or password links there. Set up its email first (copy this site's, test it, save it), then move.", 'EMAIL_NOT_READY');
|
||||
}
|
||||
const running = await getSetting(RUNNING_KEY);
|
||||
if (running && Date.now() - new Date(running).getTime() < 30 * 60e3) throw new MoveError('A move is already running.', 'RUNNING');
|
||||
await setSetting(RUNNING_KEY, new Date().toISOString());
|
||||
const audit = (action: string, metadata: object) => logAdminAction({ actorId: opts.actor.id, actorRole: opts.actor.role, action, targetType: 'setting', targetId: MODE_KEY, metadata, ip: opts.ip ?? null });
|
||||
await audit('sign_in_move_started', { adminIds: opts.adminIds });
|
||||
let begun = false;
|
||||
try {
|
||||
const eventsNotices = await notices();
|
||||
const begin = await auth.request<{ noticesTaken: boolean; accountsVersion: string }>({
|
||||
type: 'import.begin', actor: opts.actor.id, check: false, notices: opts.keepAccountsNotices ? [] : eventsNotices, church: await churchLook(),
|
||||
});
|
||||
begun = true;
|
||||
if (!versionAtLeast(begin.accountsVersion, MIN_ACCOUNTS)) throw new MoveError(`The church's Accounts is version ${begin.accountsVersion}; moving sign-in needs 1.1.0 or later.`, 'ACCOUNTS_TOO_OLD');
|
||||
if (!begin.noticesTaken && eventsNotices.length && !opts.keepAccountsNotices) {
|
||||
throw new MoveError('Accounts already has its own privacy notice. Choose which notice to keep, then move again.', 'NOTICE_CONFLICT');
|
||||
}
|
||||
const people = await peopleToMove();
|
||||
const byId = new Map(people.map((p) => [p.id, p]));
|
||||
const admins = new Set(opts.adminIds);
|
||||
const results: ImportResult[] = [];
|
||||
for (const batch of chunk(people, IMPORT_BATCH_MAX)) {
|
||||
const built = await Promise.all(batch.map((u) => person(u, { admins, seal: (v) => auth.seal(v), keepAccountsNotices: !!opts.keepAccountsNotices })));
|
||||
const r = await auth.request<{ results: ImportResult[] }>({ type: 'import.batch', actor: opts.actor.id, 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 } });
|
||||
}
|
||||
results.push(...r.results);
|
||||
}
|
||||
await finishMove(auth, opts.actor.id);
|
||||
|
||||
const who = (id: string) => ({ name: byId.get(id)?.name ?? '', email: byId.get(id)?.email ?? '' });
|
||||
const report: MoveReport = {
|
||||
movedAt: new Date().toISOString(),
|
||||
by: opts.actor.name ?? opts.actor.id,
|
||||
created: results.filter((r) => r.outcome === 'created' || r.outcome === 'updated').length,
|
||||
linked: results.filter((r) => r.outcome === 'linked').map((r) => who(r.id)),
|
||||
refused: results.filter((r) => r.outcome === 'refused').map((r) => ({ ...who(r.id), reason: r.reason ?? '' })),
|
||||
skipped: await skippedCount(),
|
||||
accountsAdmins: people.filter((p) => admins.has(p.id) && p.role === 'admin').map((p) => ({ name: p.name, email: p.email })),
|
||||
notices: opts.keepAccountsNotices ? 'accounts' : 'events',
|
||||
};
|
||||
await setSetting(REPORT_KEY, JSON.stringify(report));
|
||||
await setSetting(MOVED_AT_KEY, report.movedAt);
|
||||
await setSetting(CLEARED_KEY, null);
|
||||
await setSetting(MODE_KEY, 'accounts');
|
||||
await audit('sign_in_move_finished', { created: report.created, linked: report.linked.length, refused: report.refused.length, skipped: report.skipped });
|
||||
emailReport(opts.actor.id, report).catch(() => {});
|
||||
return report;
|
||||
} catch (e) {
|
||||
if (begun) await auth.request({ type: 'import.abort', actor: opts.actor.id }).catch(() => {});
|
||||
await audit('sign_in_move_failed', { message: (e as Error).message });
|
||||
if (e instanceof MoveError) throw e;
|
||||
throw new MoveError(`The move stopped: ${(e as Error).message}. Nothing was switched; you can run it again.`, (e as { code?: string }).code ?? 'MOVE_FAILED', 502);
|
||||
} finally {
|
||||
await setSetting(RUNNING_KEY, null);
|
||||
}
|
||||
}
|
||||
|
||||
async function emailReport(actorId: string, report: MoveReport) {
|
||||
const admin = await prisma.user.findUnique({ where: { id: actorId }, select: { email: true, name: true } });
|
||||
if (!admin?.email || NOT_MOVED.test(admin.email)) return;
|
||||
const { sendMail } = require('../utils/email') as { sendMail(m: object): Promise<void> };
|
||||
const lines = [
|
||||
`Hello ${admin.name || 'there'},`,
|
||||
'',
|
||||
`Sign-in for ${await siteUrl()} now goes through your church's Accounts.`,
|
||||
'',
|
||||
`Moved: ${report.created}`,
|
||||
`Linked to an account they already had: ${report.linked.length}${report.linked.length ? ` (${report.linked.map((l) => l.email).join(', ')})` : ''}`,
|
||||
`Not moved: ${report.refused.length}${report.refused.length ? ` (${report.refused.map((r) => `${r.email}: ${r.reason}`).join('; ')})` : ''}`,
|
||||
`Guests and deleted people (stay in Cross Events only): ${report.skipped}`,
|
||||
`Also Accounts admins: ${report.accountsAdmins.map((a) => a.name).join(', ') || 'nobody'}`,
|
||||
'',
|
||||
`You can undo this under Settings → Sign-in for ${UNDO_DAYS} days.`,
|
||||
];
|
||||
await sendMail({ to: admin.email, subject: 'Sign-in has moved to your church\'s Accounts', text: lines.join('\n'), html: lines.map((l) => (l ? `<p>${l.replace(/</g, '<')}</p>` : '')).join('') });
|
||||
}
|
||||
|
||||
export async function undo(actor: { id: string; role: string }, ip: string | null = null) {
|
||||
const s = await status();
|
||||
if (s.mode !== 'accounts') throw new MoveError('Sign-in is already in Cross Events.', 'NOT_MOVED');
|
||||
if (!s.undoUntil || new Date(s.undoUntil) < new Date()) throw new MoveError(`Undo was possible for ${UNDO_DAYS} days after the move; the old passwords have been removed since.`, 'TOO_LATE');
|
||||
await setSetting(MODE_KEY, 'local');
|
||||
await logAdminAction({ actorId: actor.id, actorRole: actor.role, action: 'sign_in_move_undone', targetType: 'setting', targetId: MODE_KEY, metadata: { movedAt: s.movedAt }, ip });
|
||||
return status();
|
||||
}
|
||||
|
||||
/** The `accounts-secrets` job: 14 days after the move, Events stops holding passwords and 2FA secrets. */
|
||||
export async function clearOldSecrets(now = new Date()) {
|
||||
const [mode, movedAt, cleared] = await Promise.all([authMode(), getSetting(MOVED_AT_KEY), getSetting(CLEARED_KEY)]);
|
||||
if (mode !== 'accounts' || !movedAt || cleared) return { cleared: 0 };
|
||||
if (now.getTime() - new Date(movedAt).getTime() < UNDO_DAYS * 86400e3) return { cleared: 0 };
|
||||
const linked: { id: string }[] = await prisma.user.findMany({ where: { accountId: { not: null } }, select: { id: true } });
|
||||
const ids = linked.map((u) => u.id);
|
||||
for (const id of ids) {
|
||||
await prisma.user.update({ where: { id }, data: { password: `!accounts:${crypto.randomBytes(12).toString('hex')}`, totpSecret: null, totpLastStep: null } });
|
||||
}
|
||||
await prisma.recoveryCode.deleteMany({ where: { userId: { in: ids } } });
|
||||
await prisma.trustedDevice.deleteMany({ where: { userId: { in: ids } } });
|
||||
await prisma.passwordReset.updateMany({ where: { userId: { in: ids }, used: false }, data: { used: true } });
|
||||
await setSetting(CLEARED_KEY, now.toISOString());
|
||||
await logAdminAction({ actorId: null, actorRole: 'system', action: 'sign_in_secrets_cleared', targetType: 'setting', targetId: MODE_KEY, metadata: { people: ids.length } });
|
||||
return { cleared: ids.length };
|
||||
}
|
||||
@@ -0,0 +1,25 @@
|
||||
/**
|
||||
* News consent lives in the church's Accounts once sign-in goes through it (3.0.0,
|
||||
* docs/EVENTS-3.0-PLAN.md decision 7). An unsubscribe link or a WhatsApp STOP here turns news off
|
||||
* there too (`people.newsOff`), so it's off for every product, and Accounts' next `user.updated`
|
||||
* doesn't turn it back on here. Never fails the unsubscribe itself.
|
||||
*/
|
||||
import { accounts } from './client';
|
||||
import { viaAccounts } from './mode';
|
||||
|
||||
/* eslint-disable @typescript-eslint/no-require-imports -- CommonJS */
|
||||
const prisma = require('../config/db');
|
||||
/* eslint-enable @typescript-eslint/no-require-imports */
|
||||
|
||||
export async function newsOffInAccounts(userId: string, channels: string[]): Promise<void> {
|
||||
try {
|
||||
if (!(await viaAccounts())) return;
|
||||
const u = await prisma.user.findUnique({ where: { id: userId }, select: { accountId: true } });
|
||||
if (!u?.accountId) return;
|
||||
const both = channels.includes('email') && channels.includes('whatsapp');
|
||||
const channel = both ? 'all' : channels.includes('whatsapp') ? 'whatsapp' : 'email';
|
||||
await (await accounts()).request({ type: 'people.newsOff', actor: null, sub: u.accountId, channel });
|
||||
} catch (e) {
|
||||
console.warn('[accounts] news off not passed on:', (e as Error).message);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,282 @@
|
||||
/**
|
||||
* Signing in through the church's Accounts (3.0.0, docs/EVENTS-3.0-PLAN.md §3), under /api:
|
||||
*
|
||||
* GET /auth/signin?returnTo=…[&signup=1][&mfa=1] start: PKCE + state, a pending cookie, off to Accounts
|
||||
* GET /auth/callback back from Accounts: find or link the user, then
|
||||
* /auth/complete#<one-time code>
|
||||
* POST /auth/handoff { code } the page swaps the code for Events' own token
|
||||
* POST /auth/signout ends Events' sessions; answers Accounts' sign-out address
|
||||
* POST /auth/backchannel-logout Accounts: this person signed out somewhere
|
||||
* POST /accounts/v1/events Accounts: user.updated / user.export / user.deleted
|
||||
*
|
||||
* Events keeps its own session (the 30-day token with `tokenVersion`), so the rest of the API is
|
||||
* unchanged; only how a token is obtained changes. The token carries `asi` (this sign-in's row) and
|
||||
* `mfa` (whether Accounts asked for a second step), which `protect` checks for staff roles.
|
||||
*/
|
||||
import crypto from 'node:crypto';
|
||||
import express, { type Request, type Response } from 'express';
|
||||
import { ACCOUNTS_CALL_PATH, OIDC_CLIENT_PATHS, safeReturnPath, type IdentityClaims } from '@crosscode/contracts';
|
||||
import { siteUrl } from '../feed/context';
|
||||
import { accounts, AccountsUnavailable } from './client';
|
||||
import { viaAccounts } from './mode';
|
||||
import { handleAccountsCall } from './calls';
|
||||
|
||||
/* eslint-disable @typescript-eslint/no-require-imports -- CommonJS */
|
||||
const prisma = require('../config/db');
|
||||
const { generateToken } = require('../config/auth') as { generateToken(id: string, role: string, v: number, extra?: object): string };
|
||||
const { encrypt, decrypt } = require('../utils/encryption') as { encrypt(v: string): string; decrypt(v: string): string };
|
||||
const { requiresTwoFactor } = require('../utils/twoFactor') as { requiresTwoFactor(u: { role: string }): boolean };
|
||||
const { logSecurityEvent } = require('../utils/securityEvents') as { logSecurityEvent(e: object): Promise<void> };
|
||||
const { getClientIp } = require('../utils/requestUtils') as { getClientIp(req: unknown): string | null };
|
||||
/* eslint-enable @typescript-eslint/no-require-imports */
|
||||
|
||||
const PENDING_COOKIE = 'ev_signin';
|
||||
const MFA_COOKIE = 'ev_signin_mfa';
|
||||
const COOKIE_PATH = '/api/auth';
|
||||
const PENDING_MINUTES = 10;
|
||||
const HANDOFF_SECONDS = 60;
|
||||
|
||||
const hash = (s: string) => crypto.createHash('sha256').update(s).digest('hex');
|
||||
|
||||
function cookies(req: Request): Record<string, string> {
|
||||
const out: Record<string, string> = {};
|
||||
for (const part of String(req.headers.cookie || '').split(';')) {
|
||||
const i = part.indexOf('=');
|
||||
if (i > 0) out[part.slice(0, i).trim()] = decodeURIComponent(part.slice(i + 1).trim());
|
||||
}
|
||||
return out;
|
||||
}
|
||||
|
||||
const cookieOptions = () => ({ httpOnly: true, sameSite: 'lax' as const, secure: process.env.NODE_ENV === 'production', path: COOKIE_PATH });
|
||||
|
||||
/** A page of this site (absolute: in development the API and the pages are on different ports). */
|
||||
async function page(path: string): Promise<string> {
|
||||
return `${(await siteUrl()).replace(/\/+$/, '')}${path}`;
|
||||
}
|
||||
|
||||
/** Where a problem page sends people: a short reason and "Try again" with the same return path. */
|
||||
const problem = async (res: Response, code: string, returnTo = '/') =>
|
||||
res.redirect(303, await page(`/auth/problem?code=${encodeURIComponent(code)}&returnTo=${encodeURIComponent(safeReturnPath(returnTo))}`));
|
||||
|
||||
/** A placeholder for `User.password` (required by the schema): never a valid hash, so never a password. */
|
||||
const NO_PASSWORD = () => `!accounts:${crypto.randomBytes(12).toString('hex')}`;
|
||||
|
||||
type EventsUser = { id: string; name: string; email: string; role: string; tokenVersion: number; isActive: boolean; accountId: string | null; phoneNumber: string | null };
|
||||
|
||||
const USER_SELECT = { id: true, name: true, email: true, role: true, tokenVersion: true, isActive: true, accountId: true, phoneNumber: true } as const;
|
||||
|
||||
const isGuestEmail = (e: string) => /@(guest\.local|deleted\.invalid|deleted\.local)$/.test(e);
|
||||
|
||||
/**
|
||||
* The Events user for an Accounts sign-in (§2): by `accountId`; else a user (often a guest
|
||||
* record from the door) with the same **verified** email that isn't linked yet; else a new `user`.
|
||||
*/
|
||||
export async function userForClaims(claims: IdentityClaims): Promise<{ user: EventsUser | null; problem?: string; linked?: boolean; created?: boolean }> {
|
||||
const byAccount = await prisma.user.findUnique({ where: { accountId: claims.sub }, select: USER_SELECT });
|
||||
if (byAccount) return { user: byAccount };
|
||||
const email = claims.email.toLowerCase();
|
||||
const byEmail = await prisma.user.findFirst({ where: { email: { equals: email, mode: 'insensitive' } }, select: USER_SELECT });
|
||||
if (byEmail) {
|
||||
if (byEmail.accountId) return { user: null, problem: 'EMAIL_IN_USE' };
|
||||
if (!claims.email_verified) return { user: null, problem: 'EMAIL_NOT_VERIFIED' };
|
||||
const linked = await prisma.user.update({ where: { id: byEmail.id }, data: { accountId: claims.sub }, select: USER_SELECT });
|
||||
return { user: linked, linked: true };
|
||||
}
|
||||
// New to Events. Its id is the sub when that's free, as for everyone moved in.
|
||||
const taken = await prisma.user.findUnique({ where: { id: claims.sub }, select: { id: true } });
|
||||
const created = await prisma.user.create({
|
||||
data: {
|
||||
...(taken ? {} : { id: claims.sub }),
|
||||
accountId: claims.sub,
|
||||
name: claims.name,
|
||||
email,
|
||||
password: NO_PASSWORD(),
|
||||
role: 'user',
|
||||
isActive: true,
|
||||
tokenVersion: 0,
|
||||
newsEmail: claims.news_consent.email,
|
||||
newsWhatsApp: claims.news_consent.whatsapp,
|
||||
newsAskedAt: new Date(),
|
||||
// Accounts' notice versions are Events' + 1 (its built-in notice is 1, Events' is 0).
|
||||
noticeVersionAccepted: Math.max(0, claims.privacy_notice_version - 1),
|
||||
},
|
||||
select: USER_SELECT,
|
||||
});
|
||||
return { user: created, created: true };
|
||||
}
|
||||
|
||||
/** Keeps Events' copy of the profile (for lists and messages) as Accounts has it. */
|
||||
export async function updateLocalCopy(userId: string, profile: Pick<IdentityClaims, 'name' | 'email' | 'phone_number' | 'news_consent'> & { privacy_notice_version?: number; two_factor?: IdentityClaims['two_factor'] }) {
|
||||
const data: Record<string, unknown> = {
|
||||
name: profile.name,
|
||||
// The 2FA method, for admins' list of staff (2.3.0); Accounts' `totp` is Events' `authenticator`.
|
||||
...(profile.two_factor !== undefined ? { twoFactorEnabled: profile.two_factor !== null, twoFactorMethod: profile.two_factor === 'totp' ? 'authenticator' : profile.two_factor } : {}),
|
||||
newsEmail: profile.news_consent.email,
|
||||
newsWhatsApp: profile.news_consent.whatsapp,
|
||||
...(profile.privacy_notice_version ? { noticeVersionAccepted: Math.max(0, profile.privacy_notice_version - 1) } : {}),
|
||||
};
|
||||
const email = profile.email.toLowerCase();
|
||||
const sameEmail = await prisma.user.findFirst({ where: { email: { equals: email, mode: 'insensitive' }, NOT: { id: userId } }, select: { id: true } });
|
||||
if (!sameEmail && !isGuestEmail(email)) data.email = email;
|
||||
if (profile.phone_number) {
|
||||
const samePhone = await prisma.user.findFirst({ where: { phoneNumber: profile.phone_number, NOT: { id: userId } }, select: { id: true } });
|
||||
if (!samePhone) data.phoneNumber = profile.phone_number;
|
||||
} else {
|
||||
data.phoneNumber = null;
|
||||
}
|
||||
await prisma.user.update({ where: { id: userId }, data });
|
||||
}
|
||||
|
||||
async function startSignIn(req: Request, res: Response) {
|
||||
const returnTo = safeReturnPath(req.query.returnTo);
|
||||
if (!(await viaAccounts())) return res.redirect(303, await page(`/login?redirect=${encodeURIComponent(returnTo)}&local=1`));
|
||||
try {
|
||||
const auth = await accounts();
|
||||
const requireTwoFactor = req.query.mfa === '1';
|
||||
const { url, cookie } = await auth.startSignIn(returnTo, {
|
||||
requireTwoFactor,
|
||||
signUp: req.query.signup === '1',
|
||||
...(typeof req.query.email === 'string' && req.query.email.length < 200 ? { loginHint: req.query.email } : {}),
|
||||
});
|
||||
res.cookie(PENDING_COOKIE, cookie, { ...cookieOptions(), maxAge: PENDING_MINUTES * 60e3 });
|
||||
if (requireTwoFactor) res.cookie(MFA_COOKIE, '1', { ...cookieOptions(), maxAge: PENDING_MINUTES * 60e3 });
|
||||
else res.clearCookie(MFA_COOKIE, cookieOptions());
|
||||
return res.redirect(303, url);
|
||||
} catch (e) {
|
||||
console.warn('[accounts] sign-in could not start:', (e as Error).message);
|
||||
return problem(res, e instanceof AccountsUnavailable ? 'ACCOUNTS_UNAVAILABLE' : 'START_FAILED', returnTo);
|
||||
}
|
||||
}
|
||||
|
||||
async function callback(req: Request, res: Response) {
|
||||
const jar = cookies(req);
|
||||
const askedMfa = jar[MFA_COOKIE] === '1';
|
||||
res.clearCookie(PENDING_COOKIE, cookieOptions());
|
||||
res.clearCookie(MFA_COOKIE, cookieOptions());
|
||||
// Cancelled at Accounts: back to the home page, signed out.
|
||||
if (req.query.error === 'access_denied') return res.redirect(303, await page('/'));
|
||||
let auth;
|
||||
try {
|
||||
auth = await accounts();
|
||||
} catch {
|
||||
return problem(res, 'ACCOUNTS_UNAVAILABLE');
|
||||
}
|
||||
let signed;
|
||||
try {
|
||||
// The address Accounts sent the browser to, as it registered it (never the backend's own port).
|
||||
signed = await auth.finishSignIn(`${(await siteUrl()).replace(/\/+$/, '')}${req.originalUrl}`, jar[PENDING_COOKIE]);
|
||||
} catch (e) {
|
||||
const code = (e as { code?: string }).code;
|
||||
console.warn('[accounts] sign-in could not finish:', (e as Error).message);
|
||||
return problem(res, code === 'NO_PENDING' ? 'EXPIRED' : 'FINISH_FAILED');
|
||||
}
|
||||
const { claims, returnTo, idToken } = signed;
|
||||
|
||||
const found = await userForClaims(claims);
|
||||
if (!found.user) return problem(res, found.problem ?? 'NO_USER', returnTo);
|
||||
const user = found.user;
|
||||
if (!user.isActive) return problem(res, 'EVENTS_OFF', returnTo);
|
||||
|
||||
// Staff roles need a second step (§3): ask Accounts for it once; a second miss is a problem.
|
||||
const mfa = claims.amr.includes('mfa');
|
||||
if (requiresTwoFactor(user) && !mfa) {
|
||||
if (askedMfa) return problem(res, 'MFA_REQUIRED', returnTo);
|
||||
return res.redirect(303, `/api/auth/signin?mfa=1&returnTo=${encodeURIComponent(returnTo)}`);
|
||||
}
|
||||
|
||||
await updateLocalCopy(user.id, claims).catch((e: Error) => console.warn('[accounts] profile copy:', e.message));
|
||||
await prisma.user.update({ where: { id: user.id }, data: { lastLoginAt: new Date(), inactivityWarnedAt: null } }).catch(() => {});
|
||||
logSecurityEvent({ userId: user.id, type: 'login', ip: getClientIp(req), userAgent: req.headers['user-agent'] }).catch(() => {});
|
||||
|
||||
const code = crypto.randomBytes(32).toString('base64url');
|
||||
const sid = (claims as unknown as { sid?: string }).sid ?? null;
|
||||
await prisma.accountsSignIn.create({
|
||||
data: { userId: user.id, codeHash: hash(code), codeUsedAt: null, codeExpires: new Date(Date.now() + HANDOFF_SECONDS * 1000), returnTo, idToken: encrypt(idToken), sid, mfa },
|
||||
});
|
||||
return res.redirect(303, await page(`/auth/complete#${code}`));
|
||||
}
|
||||
|
||||
async function handoff(req: Request, res: Response) {
|
||||
const code = typeof req.body?.code === 'string' ? req.body.code : '';
|
||||
const row = code ? await prisma.accountsSignIn.findUnique({ where: { codeHash: hash(code) } }) : null;
|
||||
if (!row || row.codeUsedAt || !row.codeExpires || row.codeExpires < new Date()) {
|
||||
return res.status(400).json({ error: { code: 'EXPIRED', message: 'This sign-in has expired. Please sign in again.' } });
|
||||
}
|
||||
// Single use, whatever happens next.
|
||||
const used = await prisma.accountsSignIn.updateMany({ where: { id: row.id, codeUsedAt: null }, data: { codeUsedAt: new Date(), codeHash: null } });
|
||||
if (!used.count) return res.status(400).json({ error: { code: 'EXPIRED', message: 'This sign-in has expired. Please sign in again.' } });
|
||||
const user = await prisma.user.findUnique({ where: { id: row.userId }, select: USER_SELECT });
|
||||
if (!user || !user.isActive) return res.status(401).json({ error: { code: 'UNAUTHENTICATED', message: 'Please sign in again.' } });
|
||||
return res.json({
|
||||
data: {
|
||||
status: 'signed_in',
|
||||
token: generateToken(user.id, user.role, user.tokenVersion, { asi: row.id, mfa: row.mfa }),
|
||||
user: { id: user.id, name: user.name, email: user.email, role: user.role },
|
||||
newsPromptPending: false,
|
||||
noticePromptPending: false,
|
||||
returnTo: safeReturnPath(row.returnTo),
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
/** Ends this person's Events sessions (every token they hold stops working at the next request). */
|
||||
export async function endEventsSessions(userId: string) {
|
||||
await prisma.user.update({ where: { id: userId }, data: { tokenVersion: { increment: 1 } } });
|
||||
}
|
||||
|
||||
async function signOut(req: Request, res: Response) {
|
||||
// `protect` ran: req.user is the person; the token's `asi` finds the ID token for Accounts.
|
||||
const user = (req as unknown as { user?: { id: string } }).user;
|
||||
const asi = (req as unknown as { tokenClaims?: { asi?: string } }).tokenClaims?.asi;
|
||||
if (!user) return res.status(401).json({ error: { code: 'UNAUTHENTICATED', message: 'Not signed in.' } });
|
||||
await endEventsSessions(user.id);
|
||||
let url: string | null = null;
|
||||
if (await viaAccounts()) {
|
||||
try {
|
||||
const row = asi ? await prisma.accountsSignIn.findUnique({ where: { id: asi } }) : null;
|
||||
const idToken = row?.idToken ? (() => { try { return decrypt(row.idToken); } catch { return undefined; } })() : undefined;
|
||||
url = (await accounts()).signOutUrl(idToken);
|
||||
} catch (e) {
|
||||
console.warn('[accounts] sign-out address:', (e as Error).message);
|
||||
}
|
||||
}
|
||||
return res.json({ data: { signedOut: true, url } });
|
||||
}
|
||||
|
||||
async function backchannelLogout(req: Request, res: Response) {
|
||||
try {
|
||||
const { sub } = await (await accounts()).verifyLogoutToken(String(req.body?.logout_token ?? ''));
|
||||
const user = await prisma.user.findUnique({ where: { accountId: sub }, select: { id: true } });
|
||||
if (user) await endEventsSessions(user.id);
|
||||
return res.status(200).end();
|
||||
} catch (e) {
|
||||
console.warn('[accounts] back-channel logout refused:', (e as Error).message);
|
||||
return res.status(400).json({ error: 'invalid_request' });
|
||||
}
|
||||
}
|
||||
|
||||
async function accountsCall(req: Request, res: Response) {
|
||||
try {
|
||||
const raw = Buffer.isBuffer(req.body) ? req.body : Buffer.from('');
|
||||
const call = (await accounts()).verifyAccountsCall(raw, req.headers as Record<string, string | string[] | undefined>);
|
||||
return res.json(await handleAccountsCall(call));
|
||||
} catch (e) {
|
||||
const err = e as { code?: string; message: string; status?: number };
|
||||
const status = err.code === 'BAD_SIGNATURE' || err.code === 'STALE_REQUEST' ? 401 : err.code === 'INVALID_REQUEST' ? 400 : err.status ?? 500;
|
||||
if (status >= 500) console.warn('[accounts] call failed:', err.message);
|
||||
return res.status(status).json({ message: err.message, code: err.code ?? 'SERVER_ERROR' });
|
||||
}
|
||||
}
|
||||
|
||||
/** Mounted at /api before express.json (the Accounts calls need the exact bytes). */
|
||||
export function accountsRouter(protect: express.RequestHandler) {
|
||||
const r = express.Router();
|
||||
const strip = (p: string) => p.replace(/^\/api/, '');
|
||||
r.get('/auth/signin', startSignIn);
|
||||
r.get(strip(OIDC_CLIENT_PATHS.callback), callback);
|
||||
r.post('/auth/handoff', express.json({ limit: '4kb' }), handoff);
|
||||
r.post('/auth/signout', express.json({ limit: '4kb' }), protect, signOut);
|
||||
r.post(strip(OIDC_CLIENT_PATHS.backchannelLogout), express.urlencoded({ extended: false, limit: '16kb' }), backchannelLogout);
|
||||
r.post(strip(ACCOUNTS_CALL_PATH), express.raw({ type: () => true, limit: '256kb' }), accountsCall);
|
||||
return r;
|
||||
}
|
||||
@@ -138,6 +138,9 @@ app.use('/api/v2/webhooks', webhooksRouter);
|
||||
// The church's other products (2.4.0): the event feed, event.changed and Connect
|
||||
// (/api/feed/v1, /api/links/v1; src/links/routes.ts). Its own parsers (raw for the webhook).
|
||||
app.use('/api', require('./links/routes').crossProductRouter());
|
||||
// 3.0.0: signing in through the church's Accounts (/api/auth/*, Accounts' calls at
|
||||
// /api/accounts/v1/events; src/accounts/signin.ts). Its own parsers (raw for Accounts' calls).
|
||||
app.use('/api', require('./accounts/signin').accountsRouter(require('./middleware/authMiddleware').protect));
|
||||
|
||||
// Apply JSON body parser for all non-webhook routes
|
||||
app.use(express.json());
|
||||
@@ -146,6 +149,9 @@ app.use((req, res, next) => {
|
||||
if (req.body === undefined) req.body = {};
|
||||
next();
|
||||
});
|
||||
// 3.0.0: once sign-in goes through Accounts, Events' own sign-in, password and 2FA endpoints say
|
||||
// where to go instead, and profile changes go to Accounts (src/accounts/guard.ts).
|
||||
app.use((req, res, next) => { require('./accounts/guard').signInGuard(req, res, next).catch(next); });
|
||||
|
||||
// Count server errors (any 5xx response) for the Hub heartbeat.
|
||||
app.use((req, res, next) => {
|
||||
|
||||
@@ -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);
|
||||
}
|
||||
|
||||
@@ -95,6 +95,17 @@ const JOBS = [
|
||||
name: 'backup', label: 'Database backup', cron: '0 2 * * *', env: 'BACKUP_ENABLED',
|
||||
run: async () => ({ file: (await require('../utils/backupUtils').runBackup()).filename }),
|
||||
},
|
||||
{
|
||||
// 3.0.0 (docs/EVENTS-3.0-PLAN.md §5): 14 days after sign-in moved to Accounts, Events' old
|
||||
// passwords and 2FA secrets go; sign-in records (for signing out of Accounts) after 40 days.
|
||||
name: 'accounts-secrets', label: 'Accounts: clear old passwords 14 days after the move, and old sign-in records', cron: '45 3 * * *', env: null,
|
||||
run: async () => {
|
||||
const { clearOldSecrets } = require('../accounts/move');
|
||||
const prisma = require('../config/db');
|
||||
const old = await prisma.accountsSignIn.deleteMany({ where: { createdAt: { lt: new Date(Date.now() - 40 * 24 * 3600e3) } } });
|
||||
return { ...(await clearOldSecrets(new Date())), signInsRemoved: old.count };
|
||||
},
|
||||
},
|
||||
{
|
||||
name: 'temp-cleanup', label: 'Delete temp files older than 7 days', cron: '0 3 * * *', env: null,
|
||||
run: async () => require('../utils/cleanupTemp').cleanupTempFiles(),
|
||||
|
||||
@@ -61,7 +61,7 @@ async function firstUse(nonce: string, now: Date): Promise<boolean> {
|
||||
}
|
||||
}
|
||||
|
||||
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();
|
||||
|
||||
@@ -2,7 +2,7 @@ const rateLimit = require("express-rate-limit");
|
||||
|
||||
const jwt = require('jsonwebtoken');
|
||||
const prisma = require('../config/db');
|
||||
const { mustEnrolTwoFactor } = require('../utils/twoFactor');
|
||||
const { mustEnrolTwoFactor, requiresTwoFactor } = require('../utils/twoFactor');
|
||||
|
||||
// The setup wizard's token may finish setup without 2FA for this long.
|
||||
const SETUP_TOKEN_GRACE_SECONDS = 2 * 60 * 60;
|
||||
@@ -71,8 +71,14 @@ const protect = async (req, res, next) => {
|
||||
// requirement (or the user's promotion) is sent back to log in, where they
|
||||
// enrol. The setup wizard's own token gets a short grace period.
|
||||
const inSetupGrace = decoded.setup === true && Date.now() / 1000 - (decoded.iat || 0) < SETUP_TOKEN_GRACE_SECONDS;
|
||||
// 3.0.0: a token from a sign-in through Accounts (`asi`) says whether Accounts asked for the
|
||||
// second step (`mfa`); Events' own 2FA settings don't apply to it. A token from Events' own
|
||||
// sign-in (before the move) is checked as before, so nobody is signed out by the move.
|
||||
const viaAccounts = typeof decoded.asi === 'string';
|
||||
const needsTwoFactor = viaAccounts ? requiresTwoFactor(req.user) && decoded.mfa !== true : await mustEnrolTwoFactor(req.user);
|
||||
req.tokenClaims = decoded;
|
||||
// (An impersonating admin has already passed 2FA themselves.)
|
||||
if (!inSetupGrace && !req.impersonation && (await mustEnrolTwoFactor(req.user))) {
|
||||
if (!inSetupGrace && !req.impersonation && needsTwoFactor) {
|
||||
return res.status(401).json({
|
||||
message: 'Two-factor authentication is required for your role. Please log in again to set it up.',
|
||||
code: 'TWO_FACTOR_REQUIRED',
|
||||
|
||||
@@ -48,6 +48,13 @@ const frontendUrl = () => (process.env.FRONTEND_URL || process.env.APP_BASE_URL
|
||||
export async function sendActivationLink(user: { id: string; name?: string | null; email?: string | null; phoneNumber?: string | null }): Promise<void> {
|
||||
const hasRealEmail = !!(user?.email && !user.email.endsWith('@guest.local'));
|
||||
if (!hasRealEmail && !user?.phoneNumber) return;
|
||||
// 3.0.0: once sign-in goes through the church's Accounts, Accounts makes (or finds) their account
|
||||
// and emails them a link to choose a password; there's no Events activation any more.
|
||||
if (hasRealEmail && (await (require('../accounts/mode') as typeof import('../accounts/mode')).viaAccounts())) {
|
||||
ensureAccount(user as { id: string; name?: string | null; email: string; phoneNumber?: string | null })
|
||||
.catch((e: any) => console.warn('[accounts] Could not make the account:', e?.message || e));
|
||||
return;
|
||||
}
|
||||
try {
|
||||
const token = uuidv4();
|
||||
const expiresAt = new Date(Date.now() + 24 * 60 * 60 * 1000);
|
||||
@@ -81,6 +88,20 @@ export async function sendActivationLink(user: { id: string; name?: string | nul
|
||||
}
|
||||
}
|
||||
|
||||
/** Asks Accounts for this person's account (people.ensure) and links it; they can then sign in. */
|
||||
export async function ensureAccount(user: { id: string; name?: string | null; email: string; phoneNumber?: string | null }): Promise<string | null> {
|
||||
const { accounts } = require('../accounts/client') as typeof import('../accounts/client');
|
||||
const { siteUrl } = require('../feed/context') as typeof import('../feed/context');
|
||||
const { phoneSchema } = require('@crosscode/contracts') as typeof import('@crosscode/contracts');
|
||||
const phone = user.phoneNumber && phoneSchema.safeParse(user.phoneNumber).success ? user.phoneNumber : null;
|
||||
const r = await (await accounts()).request<{ sub: string; created: boolean }>({
|
||||
type: 'people.ensure', actor: null, name: (user.name || user.email).slice(0, 200), email: user.email.toLowerCase(), phone, returnUrl: `${(await siteUrl()).replace(/\/+$/, '')}/`,
|
||||
});
|
||||
const other = await prisma.user.findUnique({ where: { accountId: r.sub }, select: { id: true } });
|
||||
if (!other) await prisma.user.update({ where: { id: user.id }, data: { accountId: r.sub, isActive: true } });
|
||||
return r.sub;
|
||||
}
|
||||
|
||||
// Fire-and-forget: a login notice with the approximate place it came from.
|
||||
async function sendLoginNotification(user: any, info: RequestInfo): Promise<void> {
|
||||
try {
|
||||
|
||||
@@ -156,7 +156,10 @@ async function unsubscribe(token, { channels = CHANNELS, source = 'unsubscribe_l
|
||||
if (target.userId) {
|
||||
const prefs = {};
|
||||
for (const c of channels) if (CHANNELS.includes(c)) prefs[c] = false;
|
||||
return setNewsPreferences(target.userId, prefs, { source, ip });
|
||||
const state = await setNewsPreferences(target.userId, prefs, { source, ip });
|
||||
// 3.0.0: off in the church's Accounts too, when sign-in goes through it.
|
||||
await require('../accounts/news').newsOffInAccounts(target.userId, Object.keys(prefs));
|
||||
return state;
|
||||
}
|
||||
await optOutAddress(target.channel, target.address, { source, ip });
|
||||
return { optedOut: true };
|
||||
@@ -281,6 +284,7 @@ async function whatsAppStop(rawPhone) {
|
||||
const user = await prisma.user.findFirst({ where: { phoneNumber: phone }, select: { id: true } });
|
||||
if (user) {
|
||||
await setNewsPreferences(user.id, { whatsapp: false }, { source: 'whatsapp_stop' });
|
||||
await require('../accounts/news').newsOffInAccounts(user.id, ['whatsapp']);
|
||||
return 'account';
|
||||
}
|
||||
await optOutAddress('whatsapp', phone, { source: 'whatsapp_stop' });
|
||||
|
||||
@@ -123,6 +123,9 @@ async function inactiveAccounts(before, { warned, warnedBefore, limit }, db = pr
|
||||
FROM "User" u
|
||||
WHERE u."role" = 'user'
|
||||
AND u."email" NOT LIKE '%@deleted.invalid' AND u."email" NOT LIKE '%@deleted.local'
|
||||
-- 3.0.0: people who sign in through the church's Accounts are kept or removed there
|
||||
-- (EVENTS-3.0-PLAN §7); Events still cleans up guests and anyone not linked.
|
||||
AND u."accountId" IS NULL
|
||||
) x
|
||||
WHERE last_active < $1
|
||||
AND ${warned === false ? '(warned_at IS NULL OR warned_at < last_active)' : 'warned_at >= last_active AND warned_at <= $2'}
|
||||
|
||||
@@ -25,6 +25,7 @@ import './resources/auth';
|
||||
import './resources/ai';
|
||||
import './resources/feedback';
|
||||
import './resources/linkedProducts';
|
||||
import './resources/signIn';
|
||||
|
||||
const pkg = require('../../package.json') as { version: string };
|
||||
|
||||
|
||||
@@ -0,0 +1,314 @@
|
||||
import { z } from 'zod';
|
||||
import { defineRoute } from '../route';
|
||||
import { ApiError, notFound } from '../errors';
|
||||
import { single } from '../paging';
|
||||
import { authMode } from '../../accounts/mode';
|
||||
import { check, move, MoveError, status, undo } from '../../accounts/move';
|
||||
import { accounts, accountsLink, AccountsUnavailable } from '../../accounts/client';
|
||||
import { accountsMessaging, eventsMessaging, sendToAccounts } from '../../accounts/messaging';
|
||||
import { churchLook } from '../../accounts/look';
|
||||
|
||||
/* eslint-disable @typescript-eslint/no-require-imports -- CommonJS */
|
||||
const prisma = require('../../config/db');
|
||||
const { logAdminAction } = require('../../utils/adminAudit') as { logAdminAction(entry: object): Promise<void> };
|
||||
const { getClientIp } = require('../../utils/requestUtils') as { getClientIp(req: unknown): string | null };
|
||||
/* eslint-enable @typescript-eslint/no-require-imports */
|
||||
|
||||
/**
|
||||
* Settings → Sign-in (3.0.0, docs/EVENTS-3.0-PLAN.md §5): where people sign in, the move to the
|
||||
* church's Accounts (check, move, undo), and what an admin can do to someone's account from here
|
||||
* once sign-in goes through Accounts (§6). And, for every page, where to send someone to sign in.
|
||||
*/
|
||||
|
||||
function asApiError(e: unknown): never {
|
||||
if (e instanceof MoveError) {
|
||||
const code = e.status === 503 || e.status === 502 ? 'UNAVAILABLE' : 'CONFLICT';
|
||||
throw new ApiError(code, e.message);
|
||||
}
|
||||
if (e instanceof AccountsUnavailable) throw new ApiError('UNAVAILABLE', e.message);
|
||||
const err = e as { code?: string; message?: string; status?: number };
|
||||
if (err?.code && typeof err.status === 'number') {
|
||||
if (err.code === 'UNKNOWN_PERSON') throw new ApiError('NOT_FOUND', 'Accounts doesn\'t know this person through Cross Events yet. They need to sign in once first.');
|
||||
if (err.code === 'NOT_ALLOWED') throw new ApiError('FORBIDDEN', err.message ?? 'Accounts didn\'t allow that.');
|
||||
throw new ApiError('UNAVAILABLE', `Accounts didn't accept that: ${err.message}`);
|
||||
}
|
||||
throw e;
|
||||
}
|
||||
|
||||
const person = z.object({ name: z.string(), email: z.string() });
|
||||
|
||||
const statusSchema = z.object({
|
||||
mode: z.enum(['local', 'accounts']).describe('local: Cross Events\' own sign-in; accounts: through the church\'s Accounts'),
|
||||
accountsConnected: z.boolean(),
|
||||
accountsUrl: z.string().nullable(),
|
||||
movedAt: z.string().nullable(),
|
||||
undoUntil: z.string().nullable().describe('Undo is possible until then (14 days after the move)'),
|
||||
secretsCleared: z.boolean().describe('The old passwords have been removed (Undo is no longer possible)'),
|
||||
running: z.boolean(),
|
||||
report: z.unknown().nullable(),
|
||||
});
|
||||
|
||||
export const signInMode = defineRoute({
|
||||
method: 'get',
|
||||
path: '/auth/mode',
|
||||
tag: 'Accounts',
|
||||
summary: 'Where people sign in',
|
||||
description: '`accounts`: send people to `GET /api/auth/signin?returnTo=<this page>` (the church\'s Accounts). `local`: Cross Events\' own sign-in.',
|
||||
access: 'public',
|
||||
response: single(z.object({
|
||||
mode: z.enum(['local', 'accounts']),
|
||||
signInUrl: z.string(),
|
||||
accountUrl: z.string().nullable().describe('With `accounts`: the church account page (profile, password, two-step sign-in, privacy)'),
|
||||
})),
|
||||
async handler() {
|
||||
const mode = await authMode();
|
||||
const link = mode === 'accounts' ? await accountsLink() : null;
|
||||
return { data: { mode, signInUrl: '/api/auth/signin', accountUrl: link ? `${link.url.replace(/\/+$/, '')}/api/self/signin?returnTo=/account` : null } };
|
||||
},
|
||||
});
|
||||
|
||||
export const signInStatus = defineRoute({
|
||||
method: 'get',
|
||||
path: '/settings/sign-in',
|
||||
tag: 'Accounts',
|
||||
summary: 'Sign-in: where it is and the move to Accounts',
|
||||
access: 'admin',
|
||||
response: single(statusSchema),
|
||||
async handler() {
|
||||
return { data: await status() };
|
||||
},
|
||||
});
|
||||
|
||||
export const signInCheck = defineRoute({
|
||||
method: 'post',
|
||||
path: '/settings/sign-in/check',
|
||||
tag: 'Accounts',
|
||||
summary: 'Check the move to Accounts (nothing changes)',
|
||||
description: 'Who would move, who already has an account (they\'re linked to it), who is skipped (guests, deleted) and anything that would stop the move.',
|
||||
access: 'admin',
|
||||
response: single(z.object({
|
||||
accountsVersion: z.string(),
|
||||
toMove: z.number().int(),
|
||||
wouldCreate: z.number().int(),
|
||||
wouldLink: z.array(person),
|
||||
refused: z.array(person.extend({ reason: z.string() })),
|
||||
skipped: z.number().int(),
|
||||
admins: z.array(person.extend({ id: z.string() })),
|
||||
noticeConflict: z.object({ accountsVersions: z.array(z.number()), eventsVersions: z.array(z.number()) }).nullable(),
|
||||
withTwoFactor: z.number().int(),
|
||||
messaging: z.object({ email: z.boolean(), whatsapp: z.boolean(), whatsappTwoFactor: z.number().int() }).describe('3.1.0: what Accounts can send; the move needs email'),
|
||||
})),
|
||||
async handler() {
|
||||
return { data: await check().catch(asApiError) };
|
||||
},
|
||||
});
|
||||
|
||||
export const signInMove = defineRoute({
|
||||
method: 'post',
|
||||
path: '/settings/sign-in/move',
|
||||
tag: 'Accounts',
|
||||
summary: 'Move sign-in to Accounts',
|
||||
description: 'Copies everyone into the church\'s Accounts with their passwords and authenticator apps, checks the count, then switches. Nothing switches if anything fails, and it can be run again. Undo for 14 days.',
|
||||
access: 'admin',
|
||||
body: z.object({
|
||||
adminIds: z.array(z.uuid()).max(500).describe('Events admins who also become Accounts admins'),
|
||||
keepAccountsNotices: z.boolean().optional().describe('When Accounts has its own privacy notice: keep it (everyone accepts it at their next sign-in) instead of Events\''),
|
||||
}),
|
||||
response: single(statusSchema),
|
||||
async handler({ body, user, req }) {
|
||||
const me = await prisma.user.findUnique({ where: { id: user!.id }, select: { name: true } });
|
||||
await move({ actor: { id: user!.id, role: user!.role, name: me?.name }, adminIds: body.adminIds, keepAccountsNotices: body.keepAccountsNotices, ip: getClientIp(req) }).catch(asApiError);
|
||||
return { data: await status() };
|
||||
},
|
||||
});
|
||||
|
||||
export const signInUndo = defineRoute({
|
||||
method: 'post',
|
||||
path: '/settings/sign-in/undo',
|
||||
tag: 'Accounts',
|
||||
summary: 'Undo the move (back to Cross Events\' own sign-in)',
|
||||
description: 'Within 14 days of the move. People sign in with the password they had at the move; changes made in Accounts since then don\'t come back here.',
|
||||
access: 'admin',
|
||||
response: single(statusSchema),
|
||||
async handler({ user, req }) {
|
||||
return { data: await undo({ id: user!.id, role: user!.role }, getClientIp(req)).catch(asApiError) };
|
||||
},
|
||||
});
|
||||
|
||||
// ─── Email and WhatsApp for Accounts (3.1.0) ────────────────────────────────
|
||||
|
||||
const messagingOverview = z.object({
|
||||
events: z.object({
|
||||
email: z.object({ host: z.string(), port: z.number().int(), secure: z.boolean(), user: z.string(), from: z.string(), hasPass: z.boolean() }).nullable(),
|
||||
whatsapp: z.object({ instanceId: z.string(), hasToken: z.boolean() }).nullable(),
|
||||
}).describe("This site's own settings, to copy (never the password or token)"),
|
||||
accounts: z.object({
|
||||
email: z.object({ ready: z.boolean(), host: z.string().nullable(), from: z.string().nullable() }),
|
||||
whatsapp: z.object({ ready: z.boolean(), instanceId: z.string().nullable() }),
|
||||
}).nullable().describe("What the church's Accounts can send (null: it can't be reached)"),
|
||||
accountsError: z.string().nullable(),
|
||||
});
|
||||
|
||||
export const signInMessaging = defineRoute({
|
||||
method: 'get',
|
||||
path: '/settings/sign-in/messaging',
|
||||
tag: 'Accounts',
|
||||
summary: "Email and WhatsApp: this site's, and what Accounts can send",
|
||||
access: 'admin',
|
||||
response: single(messagingOverview),
|
||||
async handler() {
|
||||
const events = await eventsMessaging();
|
||||
try {
|
||||
return { data: { events, accounts: await accountsMessaging(), accountsError: null } };
|
||||
} catch (e) {
|
||||
return { data: { events, accounts: null, accountsError: (e as Error).message } };
|
||||
}
|
||||
},
|
||||
});
|
||||
|
||||
/** 082 123 4567 → +27821234567 (as Accounts keeps phone numbers). */
|
||||
const toE164 = (raw: string) => {
|
||||
const d = raw.replace(/\D/g, '');
|
||||
if (raw.trim().startsWith('+')) return `+${d}`;
|
||||
return d.startsWith('0') && d.length === 10 ? `+27${d.slice(1)}` : `+${d}`;
|
||||
};
|
||||
|
||||
const messagingBody = z.object({
|
||||
email: z.object({
|
||||
host: z.string().trim().min(1).max(253),
|
||||
port: z.number().int().min(1).max(65535),
|
||||
secure: z.boolean(),
|
||||
user: z.string().max(254),
|
||||
from: z.string().trim().min(3).max(320),
|
||||
pass: z.string().max(500).nullable().optional().describe("Blank: this site's own password"),
|
||||
to: z.email().describe('Where the test email goes'),
|
||||
}).optional(),
|
||||
whatsapp: z.object({
|
||||
instanceId: z.string().trim().min(1).max(200),
|
||||
accessToken: z.string().max(500).nullable().optional().describe("Blank: this site's own token"),
|
||||
to: z.string().trim().min(8).max(30).describe('The phone the test message goes to'),
|
||||
}).optional(),
|
||||
});
|
||||
|
||||
const messagingResult = z.object({ ok: z.boolean(), error: z.string().nullable(), saved: z.boolean() }).nullable();
|
||||
const messagingAnswer = single(z.object({ email: messagingResult, whatsapp: messagingResult, status: z.object({ email: z.object({ ready: z.boolean(), host: z.string().nullable(), from: z.string().nullable() }), whatsapp: z.object({ ready: z.boolean(), instanceId: z.string().nullable() }) }) }));
|
||||
|
||||
async function messagingFor(body: z.infer<typeof messagingBody>, user: { id: string; role: string }, req: unknown, save: boolean) {
|
||||
if (!body.email && !body.whatsapp) throw new ApiError('VALIDATION_FAILED', 'Give email or WhatsApp settings.');
|
||||
const actor = (await prisma.user.findUnique({ where: { id: user.id }, select: { accountId: true } }))?.accountId ?? null;
|
||||
const input = { ...(body.email ? { email: body.email } : {}), ...(body.whatsapp ? { whatsapp: { ...body.whatsapp, to: toE164(body.whatsapp.to) } } : {}) };
|
||||
const out = await sendToAccounts(input, { save, actor }).catch(asApiError);
|
||||
if (save) {
|
||||
await logAdminAction({ actorId: user.id, actorRole: user.role, action: 'account_changed_in_accounts', targetType: 'setting', targetId: 'accounts_messaging', metadata: { email: out.email && { ok: out.email.ok, saved: out.email.saved, host: body.email?.host }, whatsapp: out.whatsapp && { ok: out.whatsapp.ok, saved: out.whatsapp.saved } }, ip: getClientIp(req) });
|
||||
}
|
||||
return { data: out };
|
||||
}
|
||||
|
||||
export const signInMessagingTest = defineRoute({
|
||||
method: 'post',
|
||||
path: '/settings/sign-in/messaging/test',
|
||||
tag: 'Accounts',
|
||||
summary: 'Test email / WhatsApp settings through Accounts (nothing saved)',
|
||||
description: "Accounts sends a test email to `email.to` and a WhatsApp message to `whatsapp.to` with the settings given. A blank password or token uses this site's own.",
|
||||
access: 'admin',
|
||||
body: messagingBody,
|
||||
response: messagingAnswer,
|
||||
async handler({ body, user, req }) {
|
||||
return messagingFor(body, user!, req, false);
|
||||
},
|
||||
});
|
||||
|
||||
export const signInMessagingSave = defineRoute({
|
||||
method: 'post',
|
||||
path: '/settings/sign-in/messaging',
|
||||
tag: 'Accounts',
|
||||
summary: 'Save email / WhatsApp settings in Accounts (after a test)',
|
||||
description: 'Accounts tests each part as /test does, and saves it only if its test worked.',
|
||||
access: 'admin',
|
||||
body: messagingBody,
|
||||
response: messagingAnswer,
|
||||
async handler({ body, user, req }) {
|
||||
return messagingFor(body, user!, req, true);
|
||||
},
|
||||
});
|
||||
|
||||
export const signInLook = defineRoute({
|
||||
method: 'post',
|
||||
path: '/settings/sign-in/look',
|
||||
tag: 'Accounts',
|
||||
summary: "Use this site's logo and colours on the church's sign-in pages",
|
||||
description: "Sends this site's name, logo and colours to the church's Accounts, replacing what its sign-in pages had.",
|
||||
access: 'admin',
|
||||
response: single(z.object({ name: z.string().nullable(), logoUrl: z.string().nullable(), primaryColour: z.string().nullable(), accentColour: z.string().nullable() })),
|
||||
async handler({ user, req }) {
|
||||
const look = await churchLook();
|
||||
const actor = (await prisma.user.findUnique({ where: { id: user!.id }, select: { accountId: true } }))?.accountId ?? null;
|
||||
await (await accounts().catch(asApiError)).request({ type: 'church.branding', actor, church: look, overwrite: true }).catch(asApiError);
|
||||
await logAdminAction({ actorId: user!.id, actorRole: user!.role, action: 'account_changed_in_accounts', targetType: 'setting', targetId: 'accounts_look', metadata: look, ip: getClientIp(req) });
|
||||
return { data: { name: look.name, logoUrl: look.logoUrl ?? null, primaryColour: look.primaryColour, accentColour: look.accentColour ?? null } };
|
||||
},
|
||||
});
|
||||
|
||||
// ─── An admin, for someone's account (sign-in through Accounts) ─────────────
|
||||
|
||||
const idParams = z.object({ id: z.uuid() });
|
||||
|
||||
async function targetFor(id: string) {
|
||||
const u = await prisma.user.findUnique({ where: { id }, select: { id: true, accountId: true, name: true } });
|
||||
if (!u) throw notFound('That person');
|
||||
if (!u.accountId) throw new ApiError('CONFLICT', `${u.name} doesn't sign in through the church's account yet.`);
|
||||
return u as { id: string; accountId: string; name: string };
|
||||
}
|
||||
|
||||
async function forAccount(id: string, admin: { id: string; role: string }, req: unknown, what: 'people.resetTwoFactor' | 'people.unlock' | 'people.setActive', extra: object = {}) {
|
||||
if ((await authMode()) !== 'accounts') throw new ApiError('CONFLICT', 'Sign-in is still in Cross Events: use the account\'s own settings here.');
|
||||
const target = await targetFor(id);
|
||||
const actor = (await prisma.user.findUnique({ where: { id: admin.id }, select: { accountId: true } }))?.accountId ?? null;
|
||||
await (await accounts().catch(asApiError)).request({ type: what, actor, sub: target.accountId, ...extra } as never).catch(asApiError);
|
||||
await logAdminAction({ actorId: admin.id, actorRole: admin.role, action: 'account_changed_in_accounts', targetType: 'user', targetId: target.id, metadata: { request: what, ...extra }, ip: getClientIp(req) });
|
||||
return { data: { ok: true as const } };
|
||||
}
|
||||
|
||||
const ok = single(z.object({ ok: z.literal(true) }));
|
||||
|
||||
export const accountResetTwoFactor = defineRoute({
|
||||
method: 'post',
|
||||
path: '/users/:id/account/reset-two-factor',
|
||||
tag: 'Accounts',
|
||||
summary: 'Reset someone\'s two-step sign-in (in Accounts)',
|
||||
description: 'They set it up again at their next sign-in, and are signed out everywhere.',
|
||||
access: 'admin',
|
||||
params: idParams,
|
||||
response: ok,
|
||||
async handler({ params, user, req }) {
|
||||
return forAccount(params.id, user!, req, 'people.resetTwoFactor');
|
||||
},
|
||||
});
|
||||
|
||||
export const accountUnlock = defineRoute({
|
||||
method: 'post',
|
||||
path: '/users/:id/account/unlock',
|
||||
tag: 'Accounts',
|
||||
summary: 'Unlock someone after too many wrong passwords (in Accounts)',
|
||||
access: 'admin',
|
||||
params: idParams,
|
||||
response: ok,
|
||||
async handler({ params, user, req }) {
|
||||
return forAccount(params.id, user!, req, 'people.unlock');
|
||||
},
|
||||
});
|
||||
|
||||
export const accountSetActive = defineRoute({
|
||||
method: 'post',
|
||||
path: '/users/:id/account/active',
|
||||
tag: 'Accounts',
|
||||
summary: 'Turn someone\'s church account off or on everywhere (in Accounts)',
|
||||
description: 'Off signs them out of every product of the church. To only stop them using Cross Events, deactivate them here instead.',
|
||||
access: 'admin',
|
||||
params: idParams,
|
||||
body: z.object({ active: z.boolean() }),
|
||||
response: ok,
|
||||
async handler({ params, body, user, req }) {
|
||||
return forAccount(params.id, user!, req, 'people.setActive', { active: body.active });
|
||||
},
|
||||
});
|
||||
@@ -0,0 +1,313 @@
|
||||
// Cross Events 3.0 against the real Accounts (docs/EVENTS-3.0-PLAN.md §12): Events' own code (the
|
||||
// move, sign-in, sign-out, Accounts' calls) talking to the whole Accounts app on real ports, each with
|
||||
// an in-memory database. Run with `npm run test:accounts` (node:test through tsx, not Jest: Accounts
|
||||
// is ES modules).
|
||||
import assert from 'node:assert/strict';
|
||||
import crypto from 'node:crypto';
|
||||
import http from 'node:http';
|
||||
import type { AddressInfo } from 'node:net';
|
||||
import { createRequire } from 'node:module';
|
||||
import { after, before, describe, test } from 'node:test';
|
||||
import bcrypt from 'bcryptjs';
|
||||
import express from 'express';
|
||||
import jwt from 'jsonwebtoken';
|
||||
import { ed25519PublicToPem, generateEd25519, newLinkSecret } from '@crosscode/contracts/signing';
|
||||
import { Browser, startHarness, ACCOUNTS_ID, type Harness } from '../../../../accounts/backend/tests/support/harness.ts';
|
||||
import { memoryDb } from '../../../../accounts/backend/tests/support/memoryDb.ts';
|
||||
import { codeAt, generateSecret } from '../../../../accounts/backend/src/lib/totp.ts';
|
||||
import { runDue } from '../../../../accounts/backend/src/links/deliveries.ts';
|
||||
import { signOutEverywhere } from '../../../../accounts/backend/src/oidc/sessions.ts';
|
||||
import { profileChanged } from '../../../../accounts/backend/src/accounts/service.ts';
|
||||
|
||||
const require = createRequire(import.meta.url);
|
||||
process.env.NODE_ENV = 'test';
|
||||
process.env.JWT_SECRET = 'an-events-test-secret-long-enough-for-the-encryption-key';
|
||||
|
||||
// With EVENTS_TEST_DATABASE_URL and ACCOUNTS_TEST_DATABASE_URL (empty, migrated databases), both
|
||||
// apps use real Postgres; otherwise in-memory stand-ins (Events' with Prisma's `{ increment }`).
|
||||
const PG = !!(process.env.EVENTS_TEST_DATABASE_URL && process.env.ACCOUNTS_TEST_DATABASE_URL);
|
||||
if (PG) process.env.DATABASE_URL = process.env.EVENTS_TEST_DATABASE_URL;
|
||||
const raw = memoryDb();
|
||||
const eventsDb = new Proxy(raw, {
|
||||
get(target, prop: string) {
|
||||
const model = (target as unknown as Record<string, Record<string, (...a: unknown[]) => Promise<unknown>>>)[prop];
|
||||
if (prop !== 'user') return model;
|
||||
return new Proxy(model, {
|
||||
get(m, op: string) {
|
||||
if (op !== 'update') return m[op];
|
||||
return async (args: { where: Record<string, unknown>; data: Record<string, unknown>; select?: Record<string, boolean> }) => {
|
||||
const inc = args.data.tokenVersion as { increment?: number } | undefined;
|
||||
if (inc && typeof inc === 'object' && 'increment' in inc) {
|
||||
const cur = (await m.findUnique!({ where: args.where })) as { tokenVersion: number };
|
||||
args = { ...args, data: { ...args.data, tokenVersion: cur.tokenVersion + inc.increment! } };
|
||||
}
|
||||
return m.update!(args);
|
||||
};
|
||||
},
|
||||
});
|
||||
},
|
||||
});
|
||||
const dbPath = require.resolve('../../src/config/db.js');
|
||||
if (!PG) require.cache[dbPath] = { id: dbPath, filename: dbPath, loaded: true, exports: eventsDb } as never;
|
||||
const realEventsDb = PG ? require(dbPath) : null;
|
||||
const edb = (realEventsDb ?? eventsDb) as typeof eventsDb;
|
||||
|
||||
const { encrypt } = require('../../src/utils/encryption.js');
|
||||
const { accountsRouter } = require('../../src/accounts/signin.ts');
|
||||
const { signInGuard } = require('../../src/accounts/guard.ts');
|
||||
const { protect } = require('../../src/middleware/authMiddleware.js');
|
||||
const move = require('../../src/accounts/move.ts');
|
||||
const mode = require('../../src/accounts/mode.ts');
|
||||
const messaging = require('../../src/accounts/messaging.ts');
|
||||
const { setAuthClientLoader } = require('../../src/accounts/client.ts');
|
||||
|
||||
const EVENTS_ID = '6d1f0b2c-8a3e-4c5d-9e7f-1a2b3c4d5e6f';
|
||||
let h: Harness;
|
||||
let eventsUrl: string;
|
||||
let server: http.Server;
|
||||
const totpSecret = generateSecret();
|
||||
const ids = { thandi: crypto.randomUUID(), sam: crypto.randomUUID(), lerato: crypto.randomUUID(), guest: crypto.randomUUID(), sipho: crypto.randomUUID() };
|
||||
|
||||
async function eventsUser(data: Record<string, unknown>) {
|
||||
return edb.user.create({
|
||||
data: {
|
||||
accountId: null, role: 'user', isActive: true, tokenVersion: 0, phoneNumber: null, failedAttempts: 0, lockUntil: null, twoFactorEnabled: false, twoFactorMethod: null,
|
||||
totpSecret: null, totpLastStep: null, newsEmail: false, newsWhatsApp: false, newsAskedAt: new Date(), noticeVersionAccepted: 0, lastLoginAt: new Date('2026-10-01'),
|
||||
notificationPreference: 'email', inactivityWarnedAt: null, ...data,
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
before(async () => {
|
||||
if (PG) {
|
||||
const { PrismaClient } = await import('../../../../accounts/backend/src/generated/prisma/client.ts');
|
||||
const { PrismaPg } = await import('@prisma/adapter-pg');
|
||||
h = await startHarness({ db: new PrismaClient({ adapter: new PrismaPg({ connectionString: process.env.ACCOUNTS_TEST_DATABASE_URL! }) }) });
|
||||
} else {
|
||||
h = await startHarness();
|
||||
}
|
||||
setAuthClientLoader(() => import('@crosscode/auth-client'));
|
||||
|
||||
// Events on a real port: the sign-in routes, the guard, and one page that needs signing in.
|
||||
const app = express();
|
||||
app.use('/api', accountsRouter(protect));
|
||||
app.use(express.json());
|
||||
app.use((req, res, next) => { signInGuard(req, res, next).catch(next); });
|
||||
app.get('/api/v2/me', protect, (req, res) => res.json({ data: { id: (req as unknown as { user: { id: string } }).user.id } }));
|
||||
app.post('/api/v2/auth/login', (_req, res) => res.json({ data: { status: 'local' } }));
|
||||
server = http.createServer(app);
|
||||
await new Promise<void>((r) => server.listen(0, '127.0.0.1', () => r()));
|
||||
eventsUrl = `http://127.0.0.1:${(server.address() as AddressInfo).port}`;
|
||||
process.env.FRONTEND_URL = eventsUrl;
|
||||
|
||||
// Connect (as Linked products would): the same secret on both sides.
|
||||
const secret = newLinkSecret();
|
||||
await h.db.productLink.create({ data: { installId: EVENTS_ID, product: 'events', url: eventsUrl, publicKey: ed25519PublicToPem(generateEd25519().publicKey), secret: h.ctx.secrets.encrypt(secret), connectedAt: new Date() } });
|
||||
await edb.productLink.create({ data: { installId: ACCOUNTS_ID, product: 'accounts', url: h.publicUrl, publicKey: 'x', secret: encrypt(secret), connectedAt: new Date(), updatedAt: new Date() } });
|
||||
await edb.appSetting.create({ data: { key: 'hub_install_id', value: EVENTS_ID } });
|
||||
// This site's own email settings (3.1.0: copied to Accounts before the move).
|
||||
for (const [key, value] of Object.entries({ smtp_host: 'smtp.hope.test', smtp_port: '587', smtp_secure: 'false', smtp_user: 'events@hope.test', smtp_pass: 'events-mail-pass', smtp_from: 'events@hope.test' })) {
|
||||
await edb.appSetting.create({ data: { key, value } });
|
||||
}
|
||||
|
||||
// Events' people before the move.
|
||||
await eventsUser({ id: ids.thandi, name: 'Thandi Mokoena', email: 'thandi@hope.test', password: await bcrypt.hash('Old-events-pass1', 4), newsEmail: true });
|
||||
await eventsUser({ id: ids.sam, name: 'Sam Admin', email: 'sam@hope.test', role: 'admin', password: await bcrypt.hash('Admin-pass-123', 4), twoFactorEnabled: true, twoFactorMethod: 'authenticator', totpSecret: encrypt(totpSecret), totpLastStep: 1 });
|
||||
await eventsUser({ id: ids.lerato, name: 'Lerato', email: 'lerato@hope.test', password: await bcrypt.hash('Events-pass-99', 4) });
|
||||
await eventsUser({ id: ids.sipho, name: 'Sipho Supervisor', email: 'sipho@hope.test', role: 'supervisor', password: await bcrypt.hash('Sipho-pass-123', 4) });
|
||||
await eventsUser({ id: ids.guest, name: 'Door Guest', email: 'guest+ab12cd34@guest.local', password: 'x' });
|
||||
// Lerato already made a church account (e.g. on the website) with another password.
|
||||
await h.makeAccount({ email: 'lerato@hope.test', password: 'Accounts-pass-1', name: 'Lerato M' });
|
||||
});
|
||||
after(async () => {
|
||||
await new Promise((r) => server.close(r));
|
||||
await h.close();
|
||||
});
|
||||
|
||||
/** Signs in through Events: Events → Accounts → Events' callback → /auth/complete#code → handoff. */
|
||||
async function signInThroughEvents(browser: Browser, email: string, password: string, returnTo: string, opts: { totp?: string } = {}) {
|
||||
const start = `${eventsUrl}/api/auth/signin?returnTo=${encodeURIComponent(returnTo)}`;
|
||||
const toComplete = (u: URL) => u.host === new URL(eventsUrl).host && (u.pathname === '/auth/complete' || u.pathname === '/auth/problem');
|
||||
let at = await browser.follow(start, (u) => u.pathname === '/signin' || toComplete(u));
|
||||
const steps: Record<string, unknown>[] = [];
|
||||
for (let i = 0; i < 4 && at.url.pathname === '/signin'; i++) {
|
||||
const uid = at.url.searchParams.get('uid')!;
|
||||
let step = await h.api(browser, 'GET', `/api/v2/interaction/${uid}/state`);
|
||||
if (step.body.stage === 'password') step = await h.api(browser, 'POST', `/api/v2/interaction/${uid}/password`, { email, password });
|
||||
if (step.body.stage === 'two_factor') step = await h.api(browser, 'POST', `/api/v2/interaction/${uid}/two-factor`, { code: codeAt(opts.totp!, Math.floor(Date.now() / 30000)) });
|
||||
steps.push(step.body);
|
||||
assert.equal(step.body.stage, 'done', JSON.stringify(step.body));
|
||||
at = await browser.follow(step.body.redirectTo as string, (u) => u.pathname === '/signin' || toComplete(u));
|
||||
}
|
||||
if (at.url.pathname === '/auth/problem') return { problem: at.url.searchParams.get('code'), steps };
|
||||
const code = at.url.hash.slice(1);
|
||||
const res = await fetch(`${eventsUrl}/api/auth/handoff`, { method: 'POST', headers: { 'content-type': 'application/json' }, body: JSON.stringify({ code }) });
|
||||
const body = (await res.json()) as { data: { token: string; returnTo: string; user: { id: string } } };
|
||||
return { ...body.data, code, steps };
|
||||
}
|
||||
|
||||
const me = (token: string) => fetch(`${eventsUrl}/api/v2/me`, { headers: { authorization: `Bearer ${token}` } });
|
||||
|
||||
describe('Accounts\' email before the move (3.1.0)', () => {
|
||||
test('without email in Accounts, the check says so and the move is refused', async () => {
|
||||
(h.messenger as unknown as { emailOn: boolean }).emailOn = false;
|
||||
const r = await move.check();
|
||||
assert.equal(r.messaging.email, false);
|
||||
await assert.rejects(move.move({ actor: { id: ids.sam, role: 'admin' }, adminIds: [] }), (e: { code?: string }) => e.code === 'EMAIL_NOT_READY');
|
||||
mode.forgetMode();
|
||||
assert.equal(await mode.authMode(), 'local');
|
||||
});
|
||||
|
||||
test('this site\'s SMTP is copied (its own password, never sent to the page), tested, then saved in Accounts', async () => {
|
||||
const own = await messaging.eventsMessaging();
|
||||
assert.deepEqual(own.email, { host: 'smtp.hope.test', port: 587, secure: false, user: 'events@hope.test', from: 'events@hope.test', hasPass: true });
|
||||
const email = { host: own.email.host, port: own.email.port, secure: own.email.secure, user: own.email.user, from: own.email.from, pass: null, to: 'sam@hope.test' };
|
||||
const tested = await messaging.sendToAccounts({ email }, { save: false, actor: null });
|
||||
assert.deepEqual(tested.email, { ok: true, error: null, saved: false });
|
||||
const tried = (h.messenger as unknown as { tried: { settings: { pass: string } }[] }).tried.at(-1)!;
|
||||
assert.equal(tried.settings.pass, 'events-mail-pass', 'this site\'s own password, sealed on the way');
|
||||
assert.equal(await h.ctx.settings.get('smtp_host'), null, 'a test saves nothing');
|
||||
const saved = await messaging.sendToAccounts({ email }, { save: true, actor: null });
|
||||
assert.equal(saved.email.saved, true);
|
||||
assert.equal(await h.ctx.settings.get('smtp_pass'), 'events-mail-pass');
|
||||
// (The in-memory messenger stands for a working SMTP from here.)
|
||||
(h.messenger as unknown as { emailOn: boolean }).emailOn = true;
|
||||
assert.equal((await messaging.accountsMessaging()).email.ready, true);
|
||||
});
|
||||
});
|
||||
|
||||
describe('moving Events\' sign-in to Accounts', () => {
|
||||
test('the check counts people and writes nothing', async () => {
|
||||
const r = await move.check();
|
||||
assert.equal(r.toMove, 4, 'the guest stays');
|
||||
assert.equal(r.skipped, 1);
|
||||
assert.equal(r.wouldCreate, 3);
|
||||
assert.deepEqual(r.wouldLink.map((l: { email: string }) => l.email), ['lerato@hope.test']);
|
||||
assert.deepEqual(r.admins.map((a: { id: string }) => a.id), [ids.sam]);
|
||||
assert.equal(await h.db.account.findUnique({ where: { id: ids.thandi } }), null);
|
||||
assert.equal(await mode.authMode(), 'local');
|
||||
});
|
||||
|
||||
test('the move copies everyone, links Lerato to her account, and switches', async () => {
|
||||
const report = await move.move({ actor: { id: ids.sam, role: 'admin', name: 'Sam Admin' }, adminIds: [ids.sam] });
|
||||
assert.equal(report.created, 3);
|
||||
assert.equal(report.linked.length, 1);
|
||||
mode.forgetMode();
|
||||
assert.equal(await mode.authMode(), 'accounts');
|
||||
const thandi = await edb.user.findUnique({ where: { id: ids.thandi } }) as { accountId: string };
|
||||
assert.equal(thandi.accountId, ids.thandi, 'sub = Events id');
|
||||
const lerato = await edb.user.findUnique({ where: { id: ids.lerato } }) as { accountId: string };
|
||||
const account = await h.db.account.findUnique({ where: { email: 'lerato@hope.test' } }) as { id: string };
|
||||
assert.equal(lerato.accountId, account.id, 'linked to the account she had');
|
||||
assert.equal((await edb.user.findUnique({ where: { id: ids.guest } }) as { accountId: string | null }).accountId, null);
|
||||
assert.equal((await h.db.account.findUnique({ where: { id: ids.sam } }) as { role: string }).role, 'admin');
|
||||
});
|
||||
});
|
||||
|
||||
describe('signing in through Events after the move', () => {
|
||||
test('Thandi signs in with her old Events password and lands on the page she started from', async () => {
|
||||
const r = await signInThroughEvents(new Browser(), 'thandi@hope.test', 'Old-events-pass1', '/events/youth-camp/register?ticket=adult');
|
||||
assert.ok('token' in r && r.token, JSON.stringify(r));
|
||||
assert.equal(r.returnTo, '/events/youth-camp/register?ticket=adult');
|
||||
assert.equal(r.user.id, ids.thandi);
|
||||
assert.equal((await me(r.token)).status, 200);
|
||||
// The code is single use.
|
||||
const again = await fetch(`${eventsUrl}/api/auth/handoff`, { method: 'POST', headers: { 'content-type': 'application/json' }, body: JSON.stringify({ code: r.code }) });
|
||||
assert.equal(again.status, 400);
|
||||
});
|
||||
|
||||
test('a foreign return address lands on the home page instead', async () => {
|
||||
const r = await signInThroughEvents(new Browser(), 'thandi@hope.test', 'Old-events-pass1', '//evil.test/steal');
|
||||
assert.ok('returnTo' in r);
|
||||
assert.equal(r.returnTo, '/');
|
||||
});
|
||||
|
||||
test('the admin signs in with the old authenticator app, gets new recovery codes, and the token says mfa', async () => {
|
||||
const r = await signInThroughEvents(new Browser(), 'sam@hope.test', 'Admin-pass-123', '/dashboard/admin', { totp: totpSecret });
|
||||
assert.ok('token' in r && r.token, JSON.stringify(r));
|
||||
assert.equal((r.steps[0]!.recoveryCodes as string[]).length, 10);
|
||||
assert.equal((jwt.decode(r.token) as { mfa: boolean }).mfa, true);
|
||||
assert.equal((await me(r.token)).status, 200);
|
||||
});
|
||||
|
||||
test('a supervisor without 2FA is sent back to Accounts to set it up', async () => {
|
||||
const browser = new Browser();
|
||||
const start = `${eventsUrl}/api/auth/signin?returnTo=/dashboard`;
|
||||
let at = await browser.follow(start, (u) => u.pathname === '/signin');
|
||||
const uid = at.url.searchParams.get('uid')!;
|
||||
const step = await h.api(browser, 'POST', `/api/v2/interaction/${uid}/password`, { email: 'sipho@hope.test', password: 'Sipho-pass-123' });
|
||||
assert.equal(step.body.stage, 'done');
|
||||
at = await browser.follow(step.body.redirectTo as string, (u) => u.pathname === '/signin' || u.pathname === '/auth/complete');
|
||||
assert.equal(at.url.pathname, '/signin', 'back at Accounts for the second step');
|
||||
const state = await h.api(browser, 'GET', `/api/v2/interaction/${at.url.searchParams.get('uid')}/state`);
|
||||
assert.equal(state.body.stage, 'setup_two_factor');
|
||||
});
|
||||
|
||||
test('Events\' own sign-in now says where to go', async () => {
|
||||
const res = await fetch(`${eventsUrl}/api/v2/auth/login`, { method: 'POST', headers: { 'content-type': 'application/json' }, body: '{}' });
|
||||
assert.equal(res.status, 409);
|
||||
assert.equal(((await res.json()) as { error: { code: string } }).error.code, 'SIGN_IN_MOVED');
|
||||
});
|
||||
});
|
||||
|
||||
describe('signing out, and Accounts\' calls', () => {
|
||||
test('signing out of Events ends the session here and gives Accounts\' sign-out address', async () => {
|
||||
const r = await signInThroughEvents(new Browser(), 'thandi@hope.test', 'Old-events-pass1', '/');
|
||||
assert.ok('token' in r);
|
||||
const out = await fetch(`${eventsUrl}/api/auth/signout`, { method: 'POST', headers: { authorization: `Bearer ${r.token}`, 'content-type': 'application/json' }, body: '{}' });
|
||||
const body = (await out.json()) as { data: { url: string } };
|
||||
assert.match(body.data.url, new RegExp(`^${h.publicUrl}/api/oidc/session/end`));
|
||||
assert.equal((await me(r.token)).status, 401);
|
||||
});
|
||||
|
||||
test('signing out everywhere in Accounts ends the Events session (back-channel logout)', async () => {
|
||||
const r = await signInThroughEvents(new Browser(), 'thandi@hope.test', 'Old-events-pass1', '/');
|
||||
assert.ok('token' in r);
|
||||
assert.equal((await me(r.token)).status, 200);
|
||||
await signOutEverywhere(h.ctx, h.provider, ids.thandi);
|
||||
assert.equal((await me(r.token)).status, 401);
|
||||
});
|
||||
|
||||
test('a name changed in Accounts reaches Events (user.updated)', async () => {
|
||||
await h.db.account.update({ where: { id: ids.thandi }, data: { name: 'Thandi M. Mokoena' } });
|
||||
await profileChanged(h.ctx, ids.thandi);
|
||||
await runDue(h.ctx);
|
||||
assert.equal((await edb.user.findUnique({ where: { id: ids.thandi } }) as { name: string }).name, 'Thandi M. Mokoena');
|
||||
});
|
||||
|
||||
test('people added here after the move (demo data) are moved too, and can sign in', async () => {
|
||||
const id = crypto.randomUUID();
|
||||
await eventsUser({ id, name: 'Demo Person', email: 'demo.person@hope.test', password: await bcrypt.hash('Demo-pass-123', 4) });
|
||||
const r = await move.moveNewPeople(null);
|
||||
assert.equal(r.moved, 1);
|
||||
assert.equal((await edb.user.findUnique({ where: { id } }) as { accountId: string }).accountId, id);
|
||||
const signed = await signInThroughEvents(new Browser(), 'demo.person@hope.test', 'Demo-pass-123', '/');
|
||||
assert.ok('token' in signed && signed.token);
|
||||
});
|
||||
|
||||
test('someone new to Events signs in with a church account they made elsewhere', async () => {
|
||||
const a = await h.makeAccount({ email: 'newcomer@hope.test', password: 'Newcomer-pass-1', name: 'Newcomer' });
|
||||
const r = await signInThroughEvents(new Browser(), 'newcomer@hope.test', 'Newcomer-pass-1', '/events');
|
||||
assert.ok('token' in r && r.token, JSON.stringify(r));
|
||||
assert.equal((await edb.user.findUnique({ where: { id: r.user.id } }) as { accountId: string; role: string }).accountId, a.id);
|
||||
});
|
||||
|
||||
test('Undo goes back to Events\' own sign-in', async () => {
|
||||
await move.undo({ id: ids.sam, role: 'admin' });
|
||||
mode.forgetMode();
|
||||
assert.equal(await mode.authMode(), 'local');
|
||||
const res = await fetch(`${eventsUrl}/api/v2/auth/login`, { method: 'POST', headers: { 'content-type': 'application/json' }, body: '{}' });
|
||||
assert.equal(res.status, 200);
|
||||
});
|
||||
});
|
||||
|
||||
describe('moving again after Undo', () => {
|
||||
test('works, including someone who joined through Accounts in between', async () => {
|
||||
mode.forgetMode();
|
||||
assert.equal(await mode.authMode(), 'local');
|
||||
const report = await move.move({ actor: { id: ids.sam, role: 'admin' }, adminIds: [] });
|
||||
assert.equal(report.created, 0, 'nobody new to move');
|
||||
mode.forgetMode();
|
||||
assert.equal(await mode.authMode(), 'accounts');
|
||||
});
|
||||
});
|
||||
@@ -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<string, string>();
|
||||
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);
|
||||
});
|
||||
@@ -0,0 +1,71 @@
|
||||
// 3.0.0 (docs/EVENTS-3.0-PLAN.md §7): Accounts' user.export and user.deleted calls, answered with
|
||||
// Events' existing export and deletion rules. The sign-in itself, the move and the other calls run
|
||||
// against the real Accounts in tests/accounts-integration (npm run test:accounts).
|
||||
const mockUsers = new Map<string, { id: string; accountId: string | null; tokenVersion: number }>();
|
||||
const mockAnonymised: string[] = [];
|
||||
let mockBlockers: { eventTitle: string; endDate: Date }[] = [];
|
||||
|
||||
jest.mock('../src/config/db', () => ({
|
||||
user: {
|
||||
findUnique: async ({ where }: { where: { accountId?: string; id?: string } }) =>
|
||||
[...mockUsers.values()].find((u) => (where.accountId ? u.accountId === where.accountId : u.id === where.id)) ?? null,
|
||||
update: async ({ where, data }: { where: { id: string }; data: Record<string, unknown> }) => {
|
||||
const u = mockUsers.get(where.id)!;
|
||||
if (data.tokenVersion && typeof data.tokenVersion === 'object') u.tokenVersion += 1;
|
||||
if ('accountId' in data) u.accountId = data.accountId as string | null;
|
||||
return u;
|
||||
},
|
||||
},
|
||||
}));
|
||||
jest.mock('../src/utils/privacy', () => ({
|
||||
exportUserData: async (id: string) => ({ account: { id, name: 'Thandi' }, registrations: [{ event: 'Youth Camp' }], payments: [], seasonPasses: [] }),
|
||||
deletionBlockers: async () => mockBlockers,
|
||||
anonymiseUser: async (id: string) => { mockAnonymised.push(id); },
|
||||
}));
|
||||
|
||||
import { IDENTITY_SCHEMA, userDeletedReplySchema, userExportReplySchema } from '@crosscode/contracts';
|
||||
import { exportSections, handleAccountsCall } from '../src/accounts/calls';
|
||||
|
||||
const SUB = '5f0c7d2a-3b1e-4c8f-9a6d-2e4b1c7f8a90';
|
||||
const base = { schema: IDENTITY_SCHEMA, callId: '0b6e1f2a-3c4d-4e5f-8a9b-0c1d2e3f4a5b', occurredAt: '2026-11-20T10:00:00.000Z', sub: SUB } as const;
|
||||
|
||||
beforeEach(() => {
|
||||
mockUsers.clear();
|
||||
mockUsers.set('u1', { id: 'u1', accountId: SUB, tokenVersion: 0 });
|
||||
mockAnonymised.length = 0;
|
||||
mockBlockers = [];
|
||||
});
|
||||
|
||||
test('user.export answers with Events\' export as sections, empty ones left out', async () => {
|
||||
const reply = await handleAccountsCall({ ...base, type: 'user.export', exportId: '1c7f2a3b-4d5e-4f6a-9b0c-1d2e3f4a5b6c' });
|
||||
expect(userExportReplySchema.safeParse(reply).success).toBe(true);
|
||||
const sections = (reply as { sections: { key: string; title: string }[] }).sections;
|
||||
expect(sections.map((s) => s.key)).toEqual(['account', 'registrations']);
|
||||
expect(sections[1]!.title).toBe('Registrations');
|
||||
});
|
||||
|
||||
test('section keys fit the contract', () => {
|
||||
expect(exportSections({ seasonPasses: [{}], kidsFamily: { a: 1 } }).map((s) => s.key)).toEqual(['season_passes', 'kids_family']);
|
||||
});
|
||||
|
||||
test('user.deleted waits while there is a registration for an event that has not ended', async () => {
|
||||
mockBlockers = [{ eventTitle: 'Youth Camp', endDate: new Date('2027-03-14T12:00:00Z') }];
|
||||
const reply = await handleAccountsCall({ ...base, type: 'user.deleted', approvedAt: base.occurredAt });
|
||||
expect(userDeletedReplySchema.parse(reply)).toMatchObject({ status: 'deferred', reason: 'Has a registration for Youth Camp (2027-03-14)' });
|
||||
expect(new Date((reply as { retryAfter: string }).retryAfter).getTime()).toBeGreaterThan(new Date('2027-03-14T12:00:00Z').getTime());
|
||||
expect(mockAnonymised).toEqual([]);
|
||||
});
|
||||
|
||||
test('user.deleted anonymises, signs them out here and unlinks the account', async () => {
|
||||
const reply = await handleAccountsCall({ ...base, type: 'user.deleted', approvedAt: base.occurredAt });
|
||||
expect(reply).toEqual({ schema: IDENTITY_SCHEMA, status: 'deleted' });
|
||||
expect(mockAnonymised).toEqual(['u1']);
|
||||
expect(mockUsers.get('u1')).toMatchObject({ accountId: null, tokenVersion: 1 });
|
||||
});
|
||||
|
||||
test('a call for someone Events doesn\'t know is answered as done', async () => {
|
||||
const other = { ...base, sub: '8d2e4f6a-1b3c-4d5e-8f7a-9b0c1d2e3f4a' };
|
||||
expect(await handleAccountsCall({ ...other, type: 'user.deleted', approvedAt: base.occurredAt })).toEqual({ schema: IDENTITY_SCHEMA, status: 'deleted' });
|
||||
const exp = await handleAccountsCall({ ...other, type: 'user.export', exportId: '1c7f2a3b-4d5e-4f6a-9b0c-1d2e3f4a5b6c' });
|
||||
expect((exp as { sections: unknown[] }).sections).toEqual([]);
|
||||
});
|
||||
@@ -4,7 +4,7 @@ import { test, expect, seed, API } from "./fixtures";
|
||||
// Excel exports (ExcelTS since 1.51.6): a styled report and the attendance register come back as
|
||||
// real workbooks that open and hold what was asked for.
|
||||
// eslint-disable-next-line @typescript-eslint/no-require-imports
|
||||
const { Workbook } = require(path.join(__dirname, "..", "backend", "node_modules", "@cj-tech-master", "excelts"));
|
||||
const { Workbook } = require(require.resolve("@cj-tech-master/excelts", { paths: [path.join(__dirname, "..", "backend")] }));
|
||||
|
||||
const XLSX = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet";
|
||||
|
||||
|
||||
@@ -113,15 +113,21 @@ test.describe.serial("linked products and the event feed", () => {
|
||||
expect(connects).toHaveLength(1);
|
||||
expect(connects[0]).toMatchObject({ type: "link.connect", from: { product: "events", installId: EVENTS_ID }, to: { installId: WEBSITE_ID } });
|
||||
|
||||
await row.getByLabel(/Show events from Church Website/).check();
|
||||
// The box follows the server's answer (after the first fetch), so click and wait for it.
|
||||
const show = row.getByLabel(/Show events from Church Website/);
|
||||
await show.click();
|
||||
await expect(page.getByRole("status")).toContainText("events are fetched");
|
||||
await expect(show).toBeChecked();
|
||||
await expect(row).toContainText("1 event");
|
||||
});
|
||||
|
||||
test("its event is on /events, with its own page pointing back to the website", async ({ page }) => {
|
||||
await page.goto("/events");
|
||||
// The page fetches linked events with a 60-second cache: reload until the new one shows.
|
||||
const card = page.getByTestId("linked-event-card").filter({ hasText: "Carols by Candlelight" });
|
||||
await expect(card).toContainText("From the Church Website");
|
||||
await expect(async () => {
|
||||
await page.goto("/events");
|
||||
await expect(card).toContainText("From the Church Website", { timeout: 5000 });
|
||||
}).toPass({ timeout: 90_000, intervals: [5000] });
|
||||
await card.getByRole("link", { name: "View details" }).click();
|
||||
|
||||
await expect(page).toHaveURL(new RegExp(`/events/linked/website/${EVENT_ID}$`));
|
||||
@@ -157,7 +163,10 @@ test.describe.serial("linked products and the event feed", () => {
|
||||
page.once("dialog", d => d.accept());
|
||||
await page.getByTestId("linked-website").getByRole("button", { name: "Disconnect" }).click();
|
||||
await expect(page.getByRole("status")).toContainText("Disconnected from Church Website.");
|
||||
await page.goto("/events");
|
||||
await expect(page.getByTestId("linked-event-card")).toHaveCount(0);
|
||||
// The 60-second cache again: reload until it's gone.
|
||||
await expect(async () => {
|
||||
await page.goto("/events");
|
||||
await expect(page.getByTestId("linked-event-card")).toHaveCount(0, { timeout: 5000 });
|
||||
}).toPass({ timeout: 90_000, intervals: [5000] });
|
||||
});
|
||||
});
|
||||
|
||||
@@ -0,0 +1,136 @@
|
||||
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<T = Record<string, unknown>>(text: string, values: unknown[] = []): Promise<T[]> {
|
||||
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();
|
||||
// Someone who never signed in to Events confirms their email with the code Accounts sends; 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" });
|
||||
const checkEmail = page.getByRole("heading", { name: "Check your email" });
|
||||
for (let i = 0; i < 10 && new URL(page.url()).origin !== SITE; i++) {
|
||||
if (await checkEmail.isVisible()) {
|
||||
const code = (await (await page.request.get(`${ACCOUNTS_API}/test/code?to=${encodeURIComponent(email)}`)).text()).trim();
|
||||
await page.getByLabel("Code").fill(code);
|
||||
await cont.click();
|
||||
await expect(checkEmail).toBeHidden();
|
||||
} else 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);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,48 @@
|
||||
/**
|
||||
* 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 helpers: POST /test/link { installId, url, secret } links Events, as Connect would;
|
||||
* GET /test/code?to=<email> answers the last code emailed to that address.
|
||||
*/
|
||||
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 messenger = new MemoryMessenger();
|
||||
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 });
|
||||
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 === 'GET' && req.url?.startsWith('/test/code?')) {
|
||||
const to = new URL(req.url, WEB).searchParams.get('to') ?? '';
|
||||
res.writeHead(200, { 'content-type': 'text/plain' }).end(messenger.lastCode(to) ?? '');
|
||||
return;
|
||||
}
|
||||
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'));
|
||||
@@ -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 <site>/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
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "@crosscode/events-frontend",
|
||||
"version": "2.4.1",
|
||||
"version": "3.1.0",
|
||||
"private": true,
|
||||
"scripts": {
|
||||
"dev": "next dev",
|
||||
|
||||
@@ -1,4 +1,5 @@
|
||||
"use client";
|
||||
import { AccountsGate } from "@/components/auth/AccountsGate";
|
||||
import { useState } from "react";
|
||||
import { Navbar } from "@/components/layout/Navbar";
|
||||
import { Footer } from "@/components/layout/Footer";
|
||||
@@ -6,7 +7,7 @@ import { KeyRound } from "lucide-react";
|
||||
import { errorMessage } from "@/lib/utils";
|
||||
import { apiV2Data } from "@/lib/apiV2";
|
||||
|
||||
export default function ForgotPasswordPage() {
|
||||
function ForgotPasswordPageLocal() {
|
||||
const [email, setEmail] = useState("");
|
||||
const [status, setStatus] = useState<string | null>(null);
|
||||
const [loading, setLoading] = useState(false);
|
||||
@@ -59,3 +60,8 @@ export default function ForgotPasswordPage() {
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
// 3.0.0: forwards to the church's Accounts once sign-in has moved there (components/auth/AccountsGate).
|
||||
export default function ForgotPasswordPage() {
|
||||
return <AccountsGate kind="forgot"><ForgotPasswordPageLocal /></AccountsGate>;
|
||||
}
|
||||
|
||||
@@ -1,11 +1,12 @@
|
||||
"use client";
|
||||
import { AccountsGate } from "@/components/auth/AccountsGate";
|
||||
import React, { Suspense } from "react";
|
||||
import { Navbar } from "@/components/layout/Navbar";
|
||||
import { Footer } from "@/components/layout/Footer";
|
||||
import { LoginForm } from "@/components/auth/LoginForm";
|
||||
import { LogIn } from "lucide-react";
|
||||
|
||||
export default function LoginPage() {
|
||||
function LoginPageLocal() {
|
||||
return (
|
||||
<div className="min-h-screen flex flex-col">
|
||||
<Navbar />
|
||||
@@ -29,3 +30,8 @@ export default function LoginPage() {
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
// 3.0.0: forwards to the church's Accounts once sign-in has moved there (components/auth/AccountsGate).
|
||||
export default function LoginPage() {
|
||||
return <AccountsGate kind="login"><LoginPageLocal /></AccountsGate>;
|
||||
}
|
||||
|
||||
@@ -1,11 +1,12 @@
|
||||
"use client";
|
||||
import { AccountsGate } from "@/components/auth/AccountsGate";
|
||||
import React, { Suspense } from "react";
|
||||
import { Navbar } from "@/components/layout/Navbar";
|
||||
import { Footer } from "@/components/layout/Footer";
|
||||
import { RegisterForm } from "@/components/auth/RegisterForm";
|
||||
import { UserPlus } from "lucide-react";
|
||||
|
||||
export default function RegisterPage() {
|
||||
function RegisterPageLocal() {
|
||||
return (
|
||||
<div className="min-h-screen flex flex-col">
|
||||
<Navbar />
|
||||
@@ -29,3 +30,8 @@ export default function RegisterPage() {
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
// 3.0.0: forwards to the church's Accounts once sign-in has moved there (components/auth/AccountsGate).
|
||||
export default function RegisterPage() {
|
||||
return <AccountsGate kind="register"><RegisterPageLocal /></AccountsGate>;
|
||||
}
|
||||
|
||||
@@ -1,4 +1,5 @@
|
||||
"use client";
|
||||
import { AccountsGate } from "@/components/auth/AccountsGate";
|
||||
import React, { Suspense, useMemo, useState } from "react";
|
||||
import Link from "next/link";
|
||||
import { Navbar } from "@/components/layout/Navbar";
|
||||
@@ -89,10 +90,14 @@ function ActivateAccountContent() {
|
||||
);
|
||||
}
|
||||
|
||||
export default function ActivateAccountPage() {
|
||||
function ActivateAccountPageLocal() {
|
||||
return (
|
||||
<Suspense fallback={<div className="p-6">Loading...</div>}>
|
||||
<ActivateAccountContent />
|
||||
</Suspense>
|
||||
);
|
||||
}
|
||||
}
|
||||
// 3.0.0: forwards to the church's Accounts once sign-in has moved there (components/auth/AccountsGate).
|
||||
export default function ActivateAccountPage() {
|
||||
return <AccountsGate kind="activate"><ActivateAccountPageLocal /></AccountsGate>;
|
||||
}
|
||||
|
||||
@@ -0,0 +1,46 @@
|
||||
"use client";
|
||||
|
||||
import React, { useEffect, useState } from "react";
|
||||
import { API_BASE } from "@/lib/api";
|
||||
import { saveToken } from "@/lib/auth";
|
||||
import { safePath, signInHref } from "@/lib/signIn";
|
||||
|
||||
/**
|
||||
* Back from the church's Accounts (3.0.0, docs/EVENTS-3.0-PLAN.md §3): the one-time code in the
|
||||
* address's fragment (never sent to a server or in a Referer) is swapped for Events' own token,
|
||||
* then on to the page the person started on.
|
||||
*/
|
||||
export default function SignInCompletePage() {
|
||||
const [failed, setFailed] = useState<string | null>(null);
|
||||
useEffect(() => {
|
||||
const code = window.location.hash.slice(1);
|
||||
// Out of the address bar and the history straight away.
|
||||
window.history.replaceState(null, "", "/auth/complete");
|
||||
if (!code) {
|
||||
setFailed("This sign-in link has already been used.");
|
||||
return;
|
||||
}
|
||||
fetch(`${API_BASE}/api/auth/handoff`, { method: "POST", headers: { "Content-Type": "application/json" }, body: JSON.stringify({ code }) })
|
||||
.then(async (r) => {
|
||||
const j = await r.json().catch(() => null);
|
||||
if (!r.ok || !j?.data?.token) throw new Error(j?.error?.message || "This sign-in has expired. Please sign in again.");
|
||||
saveToken(j.data.token);
|
||||
// A full page load, so the whole app starts signed in.
|
||||
window.location.replace(safePath(j.data.returnTo));
|
||||
})
|
||||
.catch((e: Error) => setFailed(e.message));
|
||||
}, []);
|
||||
return (
|
||||
<div className="min-h-screen flex items-center justify-center p-6">
|
||||
{failed ? (
|
||||
<div className="w-full max-w-md border rounded-2xl p-8 bg-white shadow-sm">
|
||||
<h1 className="text-xl font-semibold text-gray-900 mb-2">We couldn't sign you in</h1>
|
||||
<p className="text-sm text-gray-600 mb-6">{failed}</p>
|
||||
<a href={signInHref("/dashboard")} className="inline-block w-full text-center px-4 py-2.5 rounded-lg bg-brand-600 text-white text-sm font-medium">Sign in again</a>
|
||||
</div>
|
||||
) : (
|
||||
<p className="text-sm text-gray-500" role="status">Signing you in…</p>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,44 @@
|
||||
"use client";
|
||||
|
||||
import React, { Suspense } from "react";
|
||||
import { useSearchParams } from "next/navigation";
|
||||
import { Navbar } from "@/components/layout/Navbar";
|
||||
import { Footer } from "@/components/layout/Footer";
|
||||
import { safePath, signInHref } from "@/lib/signIn";
|
||||
|
||||
/** When signing in through the church's Accounts didn't work (3.0.0): what happened, and Try again. */
|
||||
const MESSAGES: Record<string, { title: string; text: string; retry?: boolean }> = {
|
||||
EXPIRED: { title: "That sign-in expired", text: "It took too long, or it was opened in another browser. Please try again.", retry: true },
|
||||
ACCOUNTS_UNAVAILABLE: { title: "Sign-in isn’t available right now", text: "We couldn’t reach the church’s sign-in. Please try again in a minute.", retry: true },
|
||||
START_FAILED: { title: "Sign-in isn’t available right now", text: "Please try again in a minute.", retry: true },
|
||||
FINISH_FAILED: { title: "We couldn’t finish signing you in", text: "Please try again.", retry: true },
|
||||
EVENTS_OFF: { title: "Your access to events is turned off", text: "Your church account is fine, but you can’t use this site at the moment. Please ask the church office." },
|
||||
MFA_REQUIRED: { title: "Two-step sign-in is needed", text: "Your role here needs a second step when you sign in. Please try again and set it up when asked.", retry: true },
|
||||
EMAIL_IN_USE: { title: "That email address belongs to someone else here", text: "Please ask the church office to sort it out." },
|
||||
EMAIL_NOT_VERIFIED: { title: "Please confirm your email address", text: "Confirm the email address on your church account, then sign in again.", retry: true },
|
||||
};
|
||||
|
||||
function Problem() {
|
||||
const search = useSearchParams();
|
||||
const m = MESSAGES[search.get("code") || ""] ?? { title: "Something went wrong signing in", text: "Please try again.", retry: true };
|
||||
return (
|
||||
<div className="w-full max-w-md border rounded-2xl p-8 bg-white shadow-sm">
|
||||
<h1 className="text-xl font-semibold text-gray-900 mb-2">{m.title}</h1>
|
||||
<p className="text-sm text-gray-600 mb-6">{m.text}</p>
|
||||
{m.retry && <a href={signInHref(safePath(search.get("returnTo"), "/"))} className="inline-block w-full text-center px-4 py-2.5 rounded-lg bg-brand-600 text-white text-sm font-medium">Try again</a>}
|
||||
<a href="/" className="block mt-3 text-center text-sm text-gray-500 underline">Home page</a>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
export default function SignInProblemPage() {
|
||||
return (
|
||||
<div className="min-h-screen flex flex-col">
|
||||
<Navbar />
|
||||
<main className="flex-1 flex items-center justify-center p-6">
|
||||
<Suspense fallback={<div />}><Problem /></Suspense>
|
||||
</main>
|
||||
<Footer />
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -8,7 +8,7 @@ import { ApiError, resolveToApiOrigin } from "@/lib/api";
|
||||
import { apiV2Raw, apiV2Data } from "@/lib/apiV2";
|
||||
import { useSiteSettings } from "@/contexts/SiteSettingsContext";
|
||||
import { useDismissingState } from "@/hooks/useDismissingState";
|
||||
import { Building2, Palette, Bell, Mail, Scale, MessageCircle, CreditCard, DatabaseBackup, Timer, KeyRound, MapPinned, type LucideIcon, Webhook, Sparkles, Link2 } from "lucide-react";
|
||||
import { Building2, Palette, Bell, Mail, Scale, MessageCircle, CreditCard, DatabaseBackup, Timer, KeyRound, MapPinned, type LucideIcon, Webhook, Sparkles, Link2, LogIn } from "lucide-react";
|
||||
import { ColorPickerField } from "@/components/admin/ColorPickerField";
|
||||
import { BrandingPreviewPanel } from "@/components/admin/BrandingPreviewPanel";
|
||||
import { BackupsTab } from "@/components/admin/BackupsTab";
|
||||
@@ -18,6 +18,7 @@ import { LicenceTab } from "@/components/admin/LicenceTab";
|
||||
import { WebhooksTab } from "@/components/admin/WebhooksTab";
|
||||
import { AiTab } from "@/components/admin/AiTab";
|
||||
import { LinkedProductsTab } from "@/components/admin/LinkedProductsTab";
|
||||
import { SignInTab } from "@/components/admin/SignInTab";
|
||||
import { CampusesTab } from "@/components/admin/CampusesTab";
|
||||
import { extractDominantColors } from "@/lib/extractColors";
|
||||
import { mapsSearchUrl } from "@/lib/maps";
|
||||
@@ -26,7 +27,7 @@ import { BackLink } from "@/components/shared/BackLink";
|
||||
import { uploadImage } from "@/lib/eventSetup";
|
||||
import { useExternalEffect } from "@/lib/hooks";
|
||||
|
||||
type TabId = "organisation" | "campuses" | "branding" | "notifications" | "email" | "legal" | "whatsapp" | "payments" | "webhooks" | "linked" | "backups" | "jobs" | "licence" | "ai";
|
||||
type TabId = "organisation" | "campuses" | "branding" | "notifications" | "email" | "legal" | "whatsapp" | "payments" | "webhooks" | "linked" | "signin" | "backups" | "jobs" | "licence" | "ai";
|
||||
|
||||
const TABS: { id: TabId; label: string; icon: LucideIcon }[] = [
|
||||
{ id: "organisation", label: "Organisation", icon: Building2 },
|
||||
@@ -39,6 +40,7 @@ const TABS: { id: TabId; label: string; icon: LucideIcon }[] = [
|
||||
{ id: "payments", label: "Payments", icon: CreditCard },
|
||||
{ id: "webhooks", label: "Webhooks", icon: Webhook },
|
||||
{ id: "linked", label: "Linked products", icon: Link2 },
|
||||
{ id: "signin", label: "Sign-in", icon: LogIn },
|
||||
{ id: "backups", label: "Backups", icon: DatabaseBackup },
|
||||
{ id: "jobs", label: "Background jobs", icon: Timer },
|
||||
{ id: "licence", label: "Licence", icon: KeyRound },
|
||||
@@ -721,6 +723,7 @@ function SiteSettingsPageInner() {
|
||||
{activeTab === "backups" && <BackupsTab active={activeTab === "backups"} />}
|
||||
{activeTab === "webhooks" && <WebhooksTab active={activeTab === "webhooks"} />}
|
||||
{activeTab === "linked" && <LinkedProductsTab active={activeTab === "linked"} />}
|
||||
{activeTab === "signin" && <SignInTab active={activeTab === "signin"} />}
|
||||
{activeTab === "jobs" && <JobsTab active={activeTab === "jobs"} />}
|
||||
{activeTab === "licence" && <LicenceTab active={activeTab === "licence"} />}
|
||||
{activeTab === "ai" && <AiTab active={activeTab === "ai"} />}
|
||||
|
||||
@@ -1,4 +1,5 @@
|
||||
"use client";
|
||||
import { useAuthInfo } from "@/components/auth/ChurchAccountNotice";
|
||||
|
||||
import React, { useCallback, useEffect, useMemo, useState } from "react";
|
||||
import { useAuth } from "@/hooks/useAuth";
|
||||
@@ -39,6 +40,9 @@ const TWO_FACTOR_LABEL: Record<"email" | "whatsapp" | "authenticator", string> =
|
||||
|
||||
export default function AdminUsersPage() {
|
||||
const { user, loading, token } = useAuth();
|
||||
// 3.0.0: signed in through the church's Accounts, 2FA and lockouts are reset there.
|
||||
const authInfo = useAuthInfo();
|
||||
const viaAccounts = authInfo?.mode === "accounts";
|
||||
const router = useRouter();
|
||||
|
||||
const isAdmin = useMemo(() => user?.role === "admin", [user]);
|
||||
@@ -234,15 +238,25 @@ export default function AdminUsersPage() {
|
||||
const message = role === "admin" || role === "supervisor"
|
||||
? `Reset two-factor authentication for ${name}? Their sessions end, and they'll set it up again with a new code at their next login.`
|
||||
: `Turn off two-factor authentication for ${name}? They will be able to log in with just their password until they turn it back on.`;
|
||||
if (!confirm(message)) return;
|
||||
if (!confirm(viaAccounts ? `Reset two-step sign-in for ${name} on their church account? They're signed out everywhere and set it up again at their next sign-in.` : message)) return;
|
||||
try {
|
||||
await apiV2Data("patch", "/users/{id}", { params: { id: id }, authToken: token, body: { twoFactorEnabled: false } });
|
||||
if (viaAccounts) await apiV2Data("post", "/users/{id}/account/reset-two-factor", { params: { id }, authToken: token });
|
||||
else await apiV2Data("patch", "/users/{id}", { params: { id: id }, authToken: token, body: { twoFactorEnabled: false } });
|
||||
await loadUsers(page);
|
||||
} catch (e) {
|
||||
setError(errorMessage(e) || "Failed to reset two-factor authentication");
|
||||
}
|
||||
};
|
||||
|
||||
const unlockAccount = async (id: string, name: string) => {
|
||||
try {
|
||||
await apiV2Data("post", "/users/{id}/account/unlock", { params: { id }, authToken: token });
|
||||
alert(`${name} can sign in again.`);
|
||||
} catch (e) {
|
||||
setError(errorMessage(e) || "Failed to unlock the account");
|
||||
}
|
||||
};
|
||||
|
||||
const deactivate = async (id: string) => {
|
||||
if (!confirm("Deactivate this user? Their account will be disabled.")) return;
|
||||
try {
|
||||
@@ -447,7 +461,10 @@ export default function AdminUsersPage() {
|
||||
{u.twoFactorEnabled && (
|
||||
<button className="px-2 py-1 text-xs rounded bg-amber-500 text-white hover:bg-amber-600" onClick={() => resetTwoFactor(u.id, u.name, u.role)} title={u.role === "admin" || u.role === "supervisor" ? "Reset two-factor authentication — they set it up again at their next login" : "Turn off two-factor authentication for a user who can no longer receive their codes"}>Reset 2FA</button>
|
||||
)}
|
||||
<button className="px-2 py-1 text-xs rounded bg-orange-500 text-white hover:bg-orange-600" onClick={() => deactivate(u.id)} title="Deactivate account">Deactivate</button>
|
||||
{viaAccounts && (
|
||||
<button className="px-2 py-1 text-xs rounded bg-gray-100 hover:bg-gray-200" onClick={() => unlockAccount(u.id, u.name)} title="After too many wrong passwords: let them try again now">Unlock</button>
|
||||
)}
|
||||
<button className="px-2 py-1 text-xs rounded bg-orange-500 text-white hover:bg-orange-600" onClick={() => deactivate(u.id)} title={viaAccounts ? "Stop them using Cross Events (their church account stays)" : "Deactivate account"}>Deactivate</button>
|
||||
<button className="px-2 py-1 text-xs rounded bg-red-700 text-white hover:bg-red-800" onClick={() => deleteUserData(u.id, u.name)} title="Erase personal data">Delete data</button>
|
||||
</div>
|
||||
</td>
|
||||
|
||||
@@ -1,4 +1,5 @@
|
||||
"use client";
|
||||
import { ChurchAccountNotice, useAuthInfo } from "@/components/auth/ChurchAccountNotice";
|
||||
|
||||
import React, { useCallback, useState } from "react";
|
||||
import Link from "next/link";
|
||||
@@ -77,6 +78,10 @@ function Toggle({ label, hint, checked, disabled, onChange }: { label: string; h
|
||||
|
||||
export default function PrivacyCentrePage() {
|
||||
const { token, logout } = useAuth();
|
||||
// 3.0.0: signed in through the church's Accounts, news choices, "download my data" (with this
|
||||
// site's part in it) and deleting the account are on the church account.
|
||||
const authInfo = useAuthInfo();
|
||||
const viaAccounts = authInfo?.mode === "accounts";
|
||||
const [info, setInfo] = useState<PrivacyInfo | null>(null);
|
||||
const [loadError, setLoadError] = useState<string | null>(null);
|
||||
|
||||
@@ -202,7 +207,14 @@ export default function PrivacyCentrePage() {
|
||||
|
||||
<div className="grid lg:grid-cols-2 gap-6 items-start">
|
||||
<div className="space-y-6">
|
||||
{viaAccounts && (
|
||||
<ChurchAccountNotice
|
||||
accountUrl={authInfo?.accountUrl ?? null}
|
||||
what="Your news choices, downloading everything the church holds about you (including your events, tickets and payments here), and deleting your account are on your church account, for all the church's sites and apps at once."
|
||||
/>
|
||||
)}
|
||||
{/* ── News & announcements ───────────────────────────────────────── */}
|
||||
{!viaAccounts && (<>
|
||||
<section className="border rounded-xl p-5 bg-white shadow-sm">
|
||||
<SectionHeader icon={Megaphone} title="News & announcements" />
|
||||
<p className="text-sm text-gray-500 mb-4">
|
||||
@@ -255,6 +267,7 @@ export default function PrivacyCentrePage() {
|
||||
{downloadMsg && <Alert msg={downloadMsg} />}
|
||||
</section>
|
||||
|
||||
</>)}
|
||||
{/* ── My requests ────────────────────────────────────────────────── */}
|
||||
{info && info.requests.length > 0 && (
|
||||
<section className="border rounded-xl p-5 bg-white shadow-sm">
|
||||
@@ -300,6 +313,7 @@ export default function PrivacyCentrePage() {
|
||||
</section>
|
||||
|
||||
{/* ── Delete my account ──────────────────────────────────────────── */}
|
||||
{!viaAccounts && (
|
||||
<section className="border border-red-200 rounded-xl p-5 bg-white shadow-sm">
|
||||
<SectionHeader icon={Trash2} title="Delete my account" tone="red" />
|
||||
<p className="text-sm text-gray-500 mb-4">
|
||||
@@ -337,6 +351,7 @@ export default function PrivacyCentrePage() {
|
||||
)}
|
||||
{deleteMsg && <Alert msg={deleteMsg} />}
|
||||
</section>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
@@ -1,4 +1,5 @@
|
||||
"use client";
|
||||
import { ChurchAccountNotice, useAuthInfo } from "@/components/auth/ChurchAccountNotice";
|
||||
|
||||
import React, { useCallback, useEffect, useState } from "react";
|
||||
import { useAuth } from "@/hooks/useAuth";
|
||||
@@ -50,6 +51,10 @@ const SectionHeader = ({ icon: Icon, title, tone = "brand" }: { icon: typeof Use
|
||||
export default function UserProfilePage() {
|
||||
const { user, token, logout, updateToken } = useAuth();
|
||||
const router = useRouter();
|
||||
// 3.0.0: signed in through the church's Accounts, the details, password, two-step sign-in and
|
||||
// closing the account are on the church account.
|
||||
const authInfo = useAuthInfo();
|
||||
const viaAccounts = authInfo?.mode === "accounts";
|
||||
|
||||
useEffect(() => {
|
||||
if (!user && !token) router.replace("/login");
|
||||
@@ -372,16 +377,21 @@ export default function UserProfilePage() {
|
||||
<form onSubmit={saveProfile} className="space-y-4">
|
||||
<div>
|
||||
<label htmlFor="profile-full-name" className="block text-sm font-medium text-gray-700 mb-1">Full name</label>
|
||||
<input id="profile-full-name" className={inputCls} value={name} onChange={e => setName(e.target.value)} required />
|
||||
<input id="profile-full-name" className={inputCls} value={name} onChange={e => setName(e.target.value)} required readOnly={viaAccounts} />
|
||||
</div>
|
||||
<div>
|
||||
<label htmlFor="profile-email-address" className="block text-sm font-medium text-gray-700 mb-1">Email address</label>
|
||||
<input id="profile-email-address" type="email" className={inputCls} value={email} onChange={e => setEmail(e.target.value)} required />
|
||||
<input id="profile-email-address" type="email" className={inputCls} value={email} onChange={e => setEmail(e.target.value)} required readOnly={viaAccounts} />
|
||||
</div>
|
||||
<div>
|
||||
<label htmlFor="profile-phone-number" className="block text-sm font-medium text-gray-700 mb-1">Phone number</label>
|
||||
<input id="profile-phone-number" type="tel" className={inputCls} value={phone} onChange={e => setPhone(e.target.value)} placeholder="e.g. 082 123 4567" />
|
||||
<input id="profile-phone-number" type="tel" className={inputCls} value={phone} onChange={e => setPhone(e.target.value)} placeholder="e.g. 082 123 4567" readOnly={viaAccounts} />
|
||||
</div>
|
||||
{viaAccounts && (
|
||||
<p className="text-xs text-gray-500">
|
||||
Your name, email and phone are on your church account{authInfo?.accountUrl ? <>: <a href={authInfo.accountUrl} className="text-brand-600 hover:underline">change them there</a></> : null}. Changes show here the next time you sign in.
|
||||
</p>
|
||||
)}
|
||||
|
||||
{campusInfo.enabled && campusInfo.campuses.length > 0 && (
|
||||
<div>
|
||||
@@ -443,6 +453,13 @@ export default function UserProfilePage() {
|
||||
</div>
|
||||
|
||||
<div className="space-y-6">
|
||||
{viaAccounts && (
|
||||
<ChurchAccountNotice
|
||||
accountUrl={authInfo?.accountUrl ?? null}
|
||||
what="Your password, two-step sign-in, recovery codes, recent sign-ins and closing your account are on your church account, the same one you use for the church's other sites and apps."
|
||||
/>
|
||||
)}
|
||||
{!viaAccounts && (<>
|
||||
{/* ── Password ─────────────────────────────────────────────────── */}
|
||||
<section className="border rounded-xl p-5 bg-white shadow-sm">
|
||||
<SectionHeader icon={Lock} title="Change password" />
|
||||
@@ -706,6 +723,7 @@ export default function UserProfilePage() {
|
||||
</form>
|
||||
)}
|
||||
</section>
|
||||
</>)}
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
@@ -1,4 +1,5 @@
|
||||
"use client";
|
||||
import { AccountsGate } from "@/components/auth/AccountsGate";
|
||||
import React, { Suspense, useMemo, useState } from "react";
|
||||
import { Navbar } from "@/components/layout/Navbar";
|
||||
import { Footer } from "@/components/layout/Footer";
|
||||
@@ -68,10 +69,15 @@ function ResetPasswordContent() {
|
||||
);
|
||||
}
|
||||
|
||||
export default function ResetPasswordPage() {
|
||||
function ResetPasswordPageLocal() {
|
||||
return (
|
||||
<Suspense fallback={<div className="p-6">Loading...</div>}>
|
||||
<ResetPasswordContent />
|
||||
</Suspense>
|
||||
);
|
||||
}
|
||||
|
||||
// 3.0.0: forwards to the church's Accounts once sign-in has moved there (components/auth/AccountsGate).
|
||||
export default function ResetPasswordPage() {
|
||||
return <AccountsGate kind="reset"><ResetPasswordPageLocal /></AccountsGate>;
|
||||
}
|
||||
|
||||
@@ -0,0 +1,145 @@
|
||||
"use client";
|
||||
|
||||
import React, { useEffect, useState } from "react";
|
||||
import { Mail, MessageCircle } from "lucide-react";
|
||||
import { useAuth } from "@/hooks/useAuth";
|
||||
import { apiV2, type V2Result } from "@/lib/apiV2";
|
||||
import { errorMessage } from "@/lib/utils";
|
||||
|
||||
type Overview = V2Result<"/settings/sign-in/messaging", "get">["data"];
|
||||
type Answer = V2Result<"/settings/sign-in/messaging", "post">["data"];
|
||||
type Result = { ok: boolean; error: string | null; saved: boolean } | null;
|
||||
|
||||
/**
|
||||
* Email and WhatsApp for the church's Accounts (3.1.0): Accounts sends its own sign-in codes and
|
||||
* password links, with its own settings, so they're set up before sign-in moves there. This site's
|
||||
* own settings are offered to copy (its password and WAWP token stay on the server: leave the field
|
||||
* blank to use them), tested through Accounts, and saved there only once the test worked.
|
||||
*/
|
||||
export function AccountsMessaging({ onReady }: { onReady: (ready: { email: boolean; whatsapp: boolean }) => void }) {
|
||||
const { token, user } = useAuth();
|
||||
const [data, setData] = useState<Overview | null>(null);
|
||||
const [err, setErr] = useState<string | null>(null);
|
||||
const [email, setEmail] = useState({ host: "", port: "587", secure: false, user: "", from: "", pass: "", to: "" });
|
||||
const [wa, setWa] = useState({ instanceId: "", accessToken: "", to: "" });
|
||||
const [emailResult, setEmailResult] = useState<Result>(null);
|
||||
const [waResult, setWaResult] = useState<Result>(null);
|
||||
const [testedEmail, setTestedEmail] = useState<string | null>(null);
|
||||
const [testedWa, setTestedWa] = useState<string | null>(null);
|
||||
const [busy, setBusy] = useState<string | null>(null);
|
||||
|
||||
const load = () => {
|
||||
if (!token) return;
|
||||
apiV2("get", "/settings/sign-in/messaging", { authToken: token })
|
||||
.then(({ data: d }) => {
|
||||
setData(d);
|
||||
if (d.accounts) onReady({ email: d.accounts.email.ready, whatsapp: d.accounts.whatsapp.ready });
|
||||
const e = d.events.email;
|
||||
if (e) setEmail((x) => (x.host ? x : { ...x, host: e.host, port: String(e.port), secure: e.secure, user: e.user, from: e.from }));
|
||||
if (d.events.whatsapp) setWa((x) => (x.instanceId ? x : { ...x, instanceId: d.events.whatsapp!.instanceId }));
|
||||
})
|
||||
.catch((e) => setErr(errorMessage(e) || "Could not load the email settings."));
|
||||
};
|
||||
// eslint-disable-next-line react-hooks/exhaustive-deps -- once per sign-in
|
||||
useEffect(load, [token]);
|
||||
useEffect(() => {
|
||||
setEmail((x) => (x.to ? x : { ...x, to: user?.email || "" }));
|
||||
setWa((x) => (x.to ? x : { ...x, to: user?.phoneNumber || "" }));
|
||||
}, [user]);
|
||||
|
||||
if (!token) return null;
|
||||
if (!data) return err ? <p className="text-sm text-red-700">{err}</p> : <p className="text-sm text-gray-500">Loading email settings…</p>;
|
||||
|
||||
const emailKey = JSON.stringify({ ...email, to: undefined });
|
||||
const waKey = JSON.stringify({ ...wa, to: undefined });
|
||||
const emailBody = () => ({ email: { host: email.host, port: parseInt(email.port, 10) || 587, secure: email.secure, user: email.user, from: email.from, pass: email.pass || null, to: email.to } });
|
||||
const waBody = () => ({ whatsapp: { instanceId: wa.instanceId, accessToken: wa.accessToken || null, to: wa.to } });
|
||||
|
||||
const run = async (key: string, save: boolean, body: object, after: (a: Answer) => void) => {
|
||||
setBusy(key);
|
||||
setErr(null);
|
||||
try {
|
||||
const { data: a } = save
|
||||
? await apiV2("post", "/settings/sign-in/messaging", { authToken: token, body: body as never })
|
||||
: await apiV2("post", "/settings/sign-in/messaging/test", { authToken: token, body: body as never });
|
||||
after(a);
|
||||
setData((d) => (d ? { ...d, accounts: { email: a.status.email, whatsapp: a.status.whatsapp }, accountsError: null } : d));
|
||||
onReady({ email: a.status.email.ready, whatsapp: a.status.whatsapp.ready });
|
||||
} catch (e) {
|
||||
setErr(errorMessage(e) || "That didn't work.");
|
||||
}
|
||||
setBusy(null);
|
||||
};
|
||||
|
||||
const acc = data.accounts;
|
||||
const input = "w-full rounded-lg border px-3 py-2 text-sm";
|
||||
const line = (r: Result, what: string) => r && (
|
||||
<p className={`text-sm ${r.ok ? "text-green-800" : "text-red-800"}`} role="status">
|
||||
{r.ok ? (r.saved ? `Saved in Accounts: ${what} works there now.` : `The test ${what} went. Check it arrived, then save.`) : `The test didn't work: ${r.error}`}
|
||||
</p>
|
||||
);
|
||||
|
||||
return (
|
||||
<section className="border rounded-xl p-4 space-y-4">
|
||||
<div>
|
||||
<h3 className="font-medium">Email and WhatsApp for the church's sign-in</h3>
|
||||
<p className="text-sm text-gray-600">Accounts sends sign-in codes and password links itself, with its own settings. Without email there, nobody can sign in after the move.</p>
|
||||
</div>
|
||||
{data.accountsError ? (
|
||||
<p className="text-sm text-red-700">Accounts can't be reached: {data.accountsError}</p>
|
||||
) : acc && (
|
||||
<ul className="text-sm space-y-1">
|
||||
<li className="flex items-center gap-2"><Mail className="h-4 w-4" aria-hidden /> Email: {acc.email.ready ? <span className="text-green-800">works{acc.email.from ? ` (from ${acc.email.from})` : ""}</span> : <span className="font-medium text-red-800">not set up</span>}</li>
|
||||
<li className="flex items-center gap-2"><MessageCircle className="h-4 w-4" aria-hidden /> WhatsApp: {acc.whatsapp.ready ? <span className="text-green-800">works</span> : <span className="text-amber-800">not set up (WhatsApp codes then go by email)</span>}</li>
|
||||
</ul>
|
||||
)}
|
||||
{err && <p className="text-sm text-red-800">{err}</p>}
|
||||
|
||||
<details open={!!acc && !acc.email.ready} className="rounded-lg border p-3">
|
||||
<summary className="cursor-pointer text-sm font-medium">{acc?.email.ready ? "Change Accounts' email" : "Set up Accounts' email"}{data.events.email ? " (copied from this site)" : ""}</summary>
|
||||
<div className="mt-3 grid gap-3 md:grid-cols-2">
|
||||
<label className="text-sm">SMTP server<input className={input} value={email.host} onChange={(e) => setEmail({ ...email, host: e.target.value })} /></label>
|
||||
<label className="text-sm">Port<input className={input} inputMode="numeric" value={email.port} onChange={(e) => setEmail({ ...email, port: e.target.value })} /></label>
|
||||
<label className="text-sm">User name<input className={input} value={email.user} onChange={(e) => setEmail({ ...email, user: e.target.value })} autoComplete="off" /></label>
|
||||
<label className="text-sm">Password<input className={input} type="password" value={email.pass} onChange={(e) => setEmail({ ...email, pass: e.target.value })} autoComplete="new-password" placeholder={data.events.email?.hasPass ? "Leave blank to use this site's password" : ""} /></label>
|
||||
<label className="text-sm">Send from<input className={input} value={email.from} onChange={(e) => setEmail({ ...email, from: e.target.value })} /></label>
|
||||
<label className="flex items-center gap-2 text-sm md:mt-6"><input type="checkbox" checked={email.secure} onChange={(e) => setEmail({ ...email, secure: e.target.checked })} /> TLS from the start (port 465)</label>
|
||||
<label className="text-sm md:col-span-2">Send the test email to<input className={input} type="email" value={email.to} onChange={(e) => setEmail({ ...email, to: e.target.value })} /></label>
|
||||
</div>
|
||||
<div className="mt-3 flex flex-wrap gap-2">
|
||||
<button type="button" className="px-3 py-2 rounded-lg border text-sm" disabled={!!busy || !email.host || !email.to}
|
||||
onClick={() => run("email-test", false, emailBody(), (a) => { setEmailResult(a.email); if (a.email?.ok) setTestedEmail(emailKey); })}>
|
||||
{busy === "email-test" ? "Sending…" : "Send a test email"}
|
||||
</button>
|
||||
<button type="button" className="px-3 py-2 rounded-lg bg-brand-600 text-white text-sm disabled:opacity-50" disabled={!!busy || testedEmail !== emailKey}
|
||||
title={testedEmail !== emailKey ? "Send a test with these settings first" : undefined}
|
||||
onClick={() => run("email-save", true, emailBody(), (a) => setEmailResult(a.email))}>
|
||||
{busy === "email-save" ? "Saving…" : "Save in Accounts"}
|
||||
</button>
|
||||
</div>
|
||||
<div className="mt-2">{line(emailResult, "email")}</div>
|
||||
</details>
|
||||
|
||||
<details className="rounded-lg border p-3">
|
||||
<summary className="cursor-pointer text-sm font-medium">{acc?.whatsapp.ready ? "Change Accounts' WhatsApp (WAWP)" : "Set up Accounts' WhatsApp (WAWP), optional"}{data.events.whatsapp ? " (copied from this site)" : ""}</summary>
|
||||
<div className="mt-3 grid gap-3 md:grid-cols-2">
|
||||
<label className="text-sm">WAWP instance id<input className={input} value={wa.instanceId} onChange={(e) => setWa({ ...wa, instanceId: e.target.value })} /></label>
|
||||
<label className="text-sm">WAWP access token<input className={input} type="password" value={wa.accessToken} onChange={(e) => setWa({ ...wa, accessToken: e.target.value })} autoComplete="new-password" placeholder={data.events.whatsapp?.hasToken ? "Leave blank to use this site's token" : ""} /></label>
|
||||
<label className="text-sm md:col-span-2">Send the test message to<input className={input} type="tel" value={wa.to} onChange={(e) => setWa({ ...wa, to: e.target.value })} placeholder="082 123 4567" /></label>
|
||||
</div>
|
||||
<div className="mt-3 flex flex-wrap gap-2">
|
||||
<button type="button" className="px-3 py-2 rounded-lg border text-sm" disabled={!!busy || !wa.instanceId || !wa.to}
|
||||
onClick={() => run("wa-test", false, waBody(), (a) => { setWaResult(a.whatsapp); if (a.whatsapp?.ok) setTestedWa(waKey); })}>
|
||||
{busy === "wa-test" ? "Sending…" : "Send a test WhatsApp"}
|
||||
</button>
|
||||
<button type="button" className="px-3 py-2 rounded-lg bg-brand-600 text-white text-sm disabled:opacity-50" disabled={!!busy || testedWa !== waKey}
|
||||
title={testedWa !== waKey ? "Send a test with these settings first" : undefined}
|
||||
onClick={() => run("wa-save", true, waBody(), (a) => setWaResult(a.whatsapp))}>
|
||||
{busy === "wa-save" ? "Saving…" : "Save in Accounts"}
|
||||
</button>
|
||||
</div>
|
||||
<div className="mt-2">{line(waResult, "WhatsApp")}</div>
|
||||
</details>
|
||||
</section>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,202 @@
|
||||
"use client";
|
||||
|
||||
import React, { useEffect, useState } from "react";
|
||||
import { LogIn } from "lucide-react";
|
||||
import { useAuth } from "@/hooks/useAuth";
|
||||
import { apiV2, type V2Result } from "@/lib/apiV2";
|
||||
import { errorMessage } from "@/lib/utils";
|
||||
import { AccountsMessaging } from "@/components/admin/AccountsMessaging";
|
||||
|
||||
type Status = V2Result<"/settings/sign-in", "get">["data"];
|
||||
type Check = V2Result<"/settings/sign-in/check", "post">["data"];
|
||||
type Report = { created: number; linked: { name: string; email: string }[]; refused: { name: string; email: string; reason: string }[]; skipped: number; accountsAdmins: { name: string }[]; by: string; movedAt: string };
|
||||
|
||||
const when = (iso: string | null | undefined) =>
|
||||
iso ? new Date(iso).toLocaleString("en-ZA", { day: "numeric", month: "long", year: "numeric", hour: "2-digit", minute: "2-digit" }) : "";
|
||||
|
||||
/**
|
||||
* Site settings → Sign-in (3.0.0, docs/EVENTS-3.0-PLAN.md §5): where people sign in, and moving
|
||||
* sign-in to the church's Accounts: Check (nothing changes), Move (with which admins also manage
|
||||
* Accounts), and Undo for 14 days.
|
||||
*/
|
||||
export function SignInTab({ active }: { active: boolean }) {
|
||||
const { token } = useAuth();
|
||||
const [status, setStatus] = useState<Status | null>(null);
|
||||
const [checked, setChecked] = useState<Check | null>(null);
|
||||
const [admins, setAdmins] = useState<Set<string>>(new Set());
|
||||
const [keepAccountsNotices, setKeepAccountsNotices] = useState(false);
|
||||
const [busy, setBusy] = useState<string | null>(null);
|
||||
const [msg, setMsg] = useState<{ ok: boolean; text: string } | null>(null);
|
||||
// 3.1.0: what Accounts can send (the move needs its email).
|
||||
const [sending, setSending] = useState<{ email: boolean; whatsapp: boolean } | null>(null);
|
||||
|
||||
useEffect(() => {
|
||||
if (!active || !token) return;
|
||||
let alive = true;
|
||||
apiV2("get", "/settings/sign-in", { authToken: token })
|
||||
.then(({ data }) => { if (alive) setStatus(data); })
|
||||
.catch((e) => { if (alive) setMsg({ ok: false, text: errorMessage(e) || "Could not load the sign-in settings." }); });
|
||||
return () => { alive = false; };
|
||||
}, [active, token]);
|
||||
|
||||
if (!token) return null;
|
||||
if (!status) return msg ? <p className="text-sm text-red-700">{msg.text}</p> : <p className="text-sm text-gray-500">Loading…</p>;
|
||||
const auth = { authToken: token };
|
||||
|
||||
const runCheck = async () => {
|
||||
setBusy("check");
|
||||
setMsg(null);
|
||||
try {
|
||||
const { data } = await apiV2("post", "/settings/sign-in/check", auth);
|
||||
setChecked(data);
|
||||
setAdmins(new Set(data.admins.map((a) => a.id)));
|
||||
} catch (e) {
|
||||
setMsg({ ok: false, text: errorMessage(e) || "The check didn't work." });
|
||||
}
|
||||
setBusy(null);
|
||||
};
|
||||
|
||||
const runMove = async () => {
|
||||
if (!checked) return;
|
||||
if (!window.confirm(`Move sign-in to your church's Accounts now? ${checked.toMove} people will sign in there from now on, with the passwords they have today.`)) return;
|
||||
setBusy("move");
|
||||
setMsg(null);
|
||||
try {
|
||||
const { data } = await apiV2("post", "/settings/sign-in/move", { ...auth, body: { adminIds: [...admins], ...(checked.noticeConflict ? { keepAccountsNotices } : {}) } });
|
||||
setStatus(data);
|
||||
setChecked(null);
|
||||
setMsg({ ok: true, text: "Sign-in now goes through your church's Accounts. People already signed in stay signed in." });
|
||||
} catch (e) {
|
||||
setMsg({ ok: false, text: errorMessage(e) || "The move didn't finish. Nothing was switched; you can try again." });
|
||||
}
|
||||
setBusy(null);
|
||||
};
|
||||
|
||||
const runUndo = async () => {
|
||||
if (!window.confirm("Go back to Cross Events' own sign-in? People sign in with the password they had at the move. Changes made in Accounts since then (a new password, two-step sign-in) don't come back here.")) return;
|
||||
setBusy("undo");
|
||||
setMsg(null);
|
||||
try {
|
||||
const { data } = await apiV2("post", "/settings/sign-in/undo", auth);
|
||||
setStatus(data);
|
||||
setMsg({ ok: true, text: "Sign-in is back in Cross Events." });
|
||||
} catch (e) {
|
||||
setMsg({ ok: false, text: errorMessage(e) || "Undo didn't work." });
|
||||
}
|
||||
setBusy(null);
|
||||
};
|
||||
|
||||
const report = status.report as Report | null;
|
||||
|
||||
return (
|
||||
<div className="space-y-6">
|
||||
<div>
|
||||
<h2 className="flex items-center gap-2 text-lg font-semibold"><LogIn className="h-5 w-5 text-brand-600" aria-hidden /> Sign-in</h2>
|
||||
<p className="text-sm text-gray-600 mt-1">
|
||||
{status.mode === "accounts"
|
||||
? "People sign in with their church account, the same one they use for the church's other sites and apps. Passwords and two-step sign-in are managed there."
|
||||
: "People sign in with a Cross Events password. You can move sign-in to your church's Accounts, so one account works for all the church's sites and apps."}
|
||||
</p>
|
||||
</div>
|
||||
|
||||
{msg && <p className={`text-sm rounded-lg px-3 py-2 ${msg.ok ? "bg-green-50 text-green-800" : "bg-red-50 text-red-800"}`} role="status">{msg.text}</p>}
|
||||
|
||||
{status.accountsConnected && <AccountsMessaging onReady={setSending} />}
|
||||
|
||||
{status.accountsConnected && (
|
||||
<section className="border rounded-xl p-4 flex flex-wrap items-center gap-3">
|
||||
<div className="flex-1 min-w-[16rem]">
|
||||
<h3 className="font-medium">How the sign-in page looks</h3>
|
||||
<p className="text-sm text-gray-600">The church's sign-in page uses its name, logo and colours. Moving sign-in copies this site's when it has none; this replaces them with this site's now.</p>
|
||||
</div>
|
||||
<button type="button" className="px-3 py-2 rounded-lg border text-sm" disabled={!!busy} onClick={async () => {
|
||||
setBusy("look");
|
||||
setMsg(null);
|
||||
try {
|
||||
await apiV2("post", "/settings/sign-in/look", auth);
|
||||
setMsg({ ok: true, text: "The sign-in page now uses this site's logo and colours." });
|
||||
} catch (e) {
|
||||
setMsg({ ok: false, text: errorMessage(e) || "That didn't work." });
|
||||
}
|
||||
setBusy(null);
|
||||
}}>{busy === "look" ? "Sending…" : "Use this site's logo and colours"}</button>
|
||||
</section>
|
||||
)}
|
||||
|
||||
{status.mode === "accounts" ? (
|
||||
<section className="border rounded-xl p-4 space-y-3">
|
||||
<p className="text-sm"><span className="font-medium">Through Accounts</span>{status.accountsUrl ? <> at <a className="underline" href={status.accountsUrl} target="_blank" rel="noreferrer">{status.accountsUrl.replace(/^https?:\/\//, "")}</a></> : null}{status.movedAt ? `, since ${when(status.movedAt)}` : ""}.</p>
|
||||
{report && (
|
||||
<ul className="text-sm text-gray-700 list-disc pl-5 space-y-1">
|
||||
<li>{report.created} people moved{report.by ? ` (by ${report.by})` : ""}.</li>
|
||||
{report.linked.length > 0 && <li>{report.linked.length} already had an account and were linked to it: {report.linked.map((l) => l.email).join(", ")}.</li>}
|
||||
{report.refused.length > 0 && <li>{report.refused.length} couldn't move: {report.refused.map((r) => `${r.email} (${r.reason})`).join("; ")}.</li>}
|
||||
<li>{report.skipped} guests and deleted people stay in Cross Events only.</li>
|
||||
<li>Also Accounts admins: {report.accountsAdmins.map((a) => a.name).join(", ") || "nobody"}.</li>
|
||||
</ul>
|
||||
)}
|
||||
{status.undoUntil && !status.secretsCleared ? (
|
||||
<div className="flex flex-wrap items-center gap-3">
|
||||
<button type="button" onClick={runUndo} disabled={!!busy} className="px-3 py-2 rounded-lg border text-sm">{busy === "undo" ? "Going back…" : "Undo the move"}</button>
|
||||
<span className="text-xs text-gray-500">Possible until {when(status.undoUntil)}. After that, Cross Events removes the old passwords.</span>
|
||||
</div>
|
||||
) : <p className="text-xs text-gray-500">Cross Events no longer holds anyone's password.</p>}
|
||||
</section>
|
||||
) : !status.accountsConnected ? (
|
||||
<section className="border rounded-xl p-4">
|
||||
<p className="text-sm text-gray-700">Connect your church's Accounts first, under <span className="font-medium">Linked products</span>. Ask Cross Code to install Accounts if it isn't listed there.</p>
|
||||
</section>
|
||||
) : (
|
||||
<section className="border rounded-xl p-4 space-y-4">
|
||||
<div className="flex flex-wrap items-center gap-3">
|
||||
<button type="button" onClick={runCheck} disabled={!!busy || status.running} className="px-3 py-2 rounded-lg border text-sm">{busy === "check" ? "Checking…" : checked ? "Check again" : "Check the move"}</button>
|
||||
<span className="text-xs text-gray-500">Nothing changes until you press Move.</span>
|
||||
</div>
|
||||
{checked && (
|
||||
<div className="space-y-4">
|
||||
<ul className="text-sm text-gray-700 list-disc pl-5 space-y-1">
|
||||
<li>{checked.wouldCreate} people move with their current password{checked.withTwoFactor ? `; ${checked.withTwoFactor} use two-step sign-in and keep their method (they get new recovery codes the first time)` : ""}.</li>
|
||||
{checked.wouldLink.length > 0 && <li>{checked.wouldLink.length} already have a church account and will be linked to it (they keep that account's password): {checked.wouldLink.map((l) => l.email).join(", ")}.</li>}
|
||||
{checked.refused.length > 0 && <li className="text-red-700">{checked.refused.length} can't move: {checked.refused.map((r) => `${r.email} (${r.reason})`).join("; ")}. Fix these first, or they won't be able to sign in.</li>}
|
||||
<li>{checked.skipped} guests and deleted people stay in Cross Events only.</li>
|
||||
<li>Accounts {checked.accountsVersion}.</li>
|
||||
</ul>
|
||||
{checked.admins.length > 0 && (
|
||||
<fieldset>
|
||||
<legend className="text-sm font-medium mb-1">Also make these admins Accounts admins (they can manage everyone's sign-in)</legend>
|
||||
{checked.admins.map((a) => (
|
||||
<label key={a.id} className="flex items-center gap-2 text-sm py-0.5">
|
||||
<input type="checkbox" checked={admins.has(a.id)} onChange={(e) => {
|
||||
const next = new Set(admins);
|
||||
if (e.target.checked) next.add(a.id); else next.delete(a.id);
|
||||
setAdmins(next);
|
||||
}} />
|
||||
{a.name} <span className="text-gray-500">({a.email})</span>
|
||||
</label>
|
||||
))}
|
||||
</fieldset>
|
||||
)}
|
||||
{checked.noticeConflict && (
|
||||
<fieldset>
|
||||
<legend className="text-sm font-medium mb-1">Accounts already has its own privacy notice. Which one should people see?</legend>
|
||||
<label className="flex items-center gap-2 text-sm py-0.5"><input type="radio" name="notice" checked={keepAccountsNotices} onChange={() => setKeepAccountsNotices(true)} /> Keep Accounts' notice (everyone accepts it at their next sign-in)</label>
|
||||
<label className="flex items-center gap-2 text-sm py-0.5 text-gray-400"><input type="radio" name="notice" disabled checked={!keepAccountsNotices} readOnly /> Use Cross Events' notice (remove Accounts' notice in Accounts first)</label>
|
||||
</fieldset>
|
||||
)}
|
||||
{!(sending?.email ?? checked.messaging.email) && (
|
||||
<p className="text-sm font-medium text-red-800">Set up Accounts' email above first (copy this site's, test it, save it): without it nobody could get a sign-in code or password link after the move.</p>
|
||||
)}
|
||||
{!!checked.messaging.whatsappTwoFactor && !(sending?.whatsapp ?? checked.messaging.whatsapp) && (
|
||||
<p className="text-sm text-amber-800">{checked.messaging.whatsappTwoFactor} people get their codes by WhatsApp, which Accounts can't send yet: their codes will go by email until you set it up.</p>
|
||||
)}
|
||||
<button type="button" onClick={runMove} disabled={!!busy || (!!checked.noticeConflict && !keepAccountsNotices) || !(sending?.email ?? checked.messaging.email)} className="px-4 py-2 rounded-lg bg-brand-600 text-white text-sm font-medium disabled:opacity-50">
|
||||
{busy === "move" ? "Moving… (don't close this page)" : "Move sign-in to Accounts"}
|
||||
</button>
|
||||
<p className="text-xs text-gray-500">Pick a quiet time. It takes about a minute; people already signed in stay signed in. You can undo it for 14 days.</p>
|
||||
</div>
|
||||
)}
|
||||
</section>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,54 @@
|
||||
"use client";
|
||||
|
||||
import React, { useEffect, useState } from "react";
|
||||
import { fetchAuthMode, safePath, signInHref, type AuthMode } from "@/lib/signIn";
|
||||
|
||||
type Kind = "login" | "register" | "forgot" | "reset" | "activate";
|
||||
|
||||
/**
|
||||
* Cross Events' own sign-in pages (3.0.0). With sign-in through Accounts, the sign-in, sign-up and
|
||||
* forgot-password pages forward there (keeping where to come back to), and old reset and activation
|
||||
* links say sign-in has moved. Otherwise (`local`, or `?local=1` from the backend) the page as before.
|
||||
*/
|
||||
export function AccountsGate({ kind, children }: { kind: Kind; children: React.ReactNode }) {
|
||||
const [mode, setMode] = useState<AuthMode | null>(null);
|
||||
useEffect(() => {
|
||||
let alive = true;
|
||||
const params = new URLSearchParams(window.location.search);
|
||||
if (params.get("local") === "1") {
|
||||
setMode("local");
|
||||
return;
|
||||
}
|
||||
fetchAuthMode().then((m) => {
|
||||
if (!alive) return;
|
||||
if (m === "accounts" && (kind === "login" || kind === "register" || kind === "forgot")) {
|
||||
window.location.replace(signInHref(safePath(params.get("redirect")), { signUp: kind === "register" }));
|
||||
return;
|
||||
}
|
||||
setMode(m);
|
||||
});
|
||||
return () => { alive = false; };
|
||||
}, [kind]);
|
||||
|
||||
if (mode === null) {
|
||||
return <div className="min-h-[50vh] flex items-center justify-center text-sm text-gray-500" role="status">Loading…</div>;
|
||||
}
|
||||
if (mode === "accounts") return <SignInMoved kind={kind} />;
|
||||
return <>{children}</>;
|
||||
}
|
||||
|
||||
function SignInMoved({ kind }: { kind: Kind }) {
|
||||
return (
|
||||
<div className="min-h-[60vh] flex items-center justify-center p-6">
|
||||
<div className="w-full max-w-md border rounded-2xl p-8 bg-white shadow-sm">
|
||||
<h1 className="text-xl font-semibold text-gray-900 mb-2">Sign-in has moved</h1>
|
||||
<p className="text-sm text-gray-600 mb-6">
|
||||
{kind === "activate"
|
||||
? "You now sign in with your church account. To get started, use “Forgot your password?” there with your email address to choose a password."
|
||||
: "You now sign in with your church account, so this link no longer works. Use “Forgot your password?” there to choose a new one."}
|
||||
</p>
|
||||
<a href={signInHref("/dashboard")} className="inline-block w-full text-center px-4 py-2.5 rounded-lg bg-brand-600 text-white text-sm font-medium">Sign in</a>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,28 @@
|
||||
"use client";
|
||||
|
||||
import React, { useEffect, useState } from "react";
|
||||
import { fetchAuthInfo, type AuthInfo } from "@/lib/signIn";
|
||||
|
||||
/** Whether sign-in goes through the church's Accounts (3.0.0), and its account page; null while loading. */
|
||||
export function useAuthInfo(): AuthInfo | null {
|
||||
const [info, setInfo] = useState<AuthInfo | null>(null);
|
||||
useEffect(() => {
|
||||
let alive = true;
|
||||
fetchAuthInfo().then((i) => { if (alive) setInfo(i); });
|
||||
return () => { alive = false; };
|
||||
}, []);
|
||||
return info;
|
||||
}
|
||||
|
||||
/** "Your sign-in and security are on your church account", with a link to it. */
|
||||
export function ChurchAccountNotice({ accountUrl, what }: { accountUrl: string | null; what: string }) {
|
||||
return (
|
||||
<section className="border rounded-xl p-5 bg-white shadow-sm">
|
||||
<h2 className="text-lg font-semibold text-gray-900 mb-2">On your church account</h2>
|
||||
<p className="text-sm text-gray-600 mb-4">{what}</p>
|
||||
{accountUrl && (
|
||||
<a href={accountUrl} className="inline-block px-4 py-2 rounded-lg bg-brand-600 text-white text-sm font-medium hover:bg-brand-700">Open my church account</a>
|
||||
)}
|
||||
</section>
|
||||
);
|
||||
}
|
||||
@@ -4,6 +4,8 @@ import React, { createContext, useCallback, useContext, useEffect, useMemo, useS
|
||||
import { ApiError } from "@/lib/api";
|
||||
import { AuthResponse, AuthUser, TwoFactorChallenge, clearToken, getDeviceToken, getToken, saveDeviceToken, saveToken } from "@/lib/auth";
|
||||
import { apiV2, type V2Result, apiV2Data } from "@/lib/apiV2";
|
||||
import { API_BASE } from "@/lib/api";
|
||||
import { fetchAuthMode } from "@/lib/signIn";
|
||||
|
||||
// A v2 "signed_in" answer as the session the app keeps (the user's fields plus the token).
|
||||
type V2Session = Extract<V2Result<"/auth/login", "post">["data"], { status: "signed_in" }>;
|
||||
@@ -142,10 +144,21 @@ export function AuthProvider({ children }: { children: React.ReactNode }) {
|
||||
}, []);
|
||||
|
||||
const logout = useCallback(() => {
|
||||
const t = getToken();
|
||||
clearToken();
|
||||
cacheUser(null);
|
||||
setToken(null);
|
||||
setUser(null);
|
||||
// 3.0.0: signed in through the church's Accounts, signing out here signs out there too (and of
|
||||
// the church's other products), then comes back to this site's home page.
|
||||
if (t) {
|
||||
fetchAuthMode()
|
||||
.then((m) => (m === "accounts"
|
||||
? fetch(`${API_BASE}/api/auth/signout`, { method: "POST", headers: { Authorization: `Bearer ${t}`, "Content-Type": "application/json" }, body: "{}" }).then((r) => r.json())
|
||||
: null))
|
||||
.then((j: { data?: { url?: string | null } } | null) => { if (j?.data?.url) window.location.assign(j.data.url); })
|
||||
.catch(() => { /* signed out here either way */ });
|
||||
}
|
||||
}, []);
|
||||
|
||||
// Some endpoints (profile update, password change, session revocation) issue a
|
||||
|
||||
@@ -3,6 +3,7 @@
|
||||
import { useEffect } from "react";
|
||||
import { useRouter } from "next/navigation";
|
||||
import { useAuth } from "@/hooks/useAuth";
|
||||
import { currentPage } from "@/lib/signIn";
|
||||
|
||||
/**
|
||||
* Use inside any client component that requires authentication.
|
||||
@@ -19,7 +20,9 @@ export function useRequireAuth(redirectTo = "/login") {
|
||||
|
||||
useEffect(() => {
|
||||
if (loading) return;
|
||||
if (!user) router.replace(redirectTo);
|
||||
// Back to this exact page after signing in (3.0.0: through the church's Accounts, which
|
||||
// `/login` forwards to).
|
||||
if (!user) router.replace(redirectTo === "/login" ? `/login?redirect=${encodeURIComponent(currentPage())}` : redirectTo);
|
||||
}, [user, loading, router, redirectTo]);
|
||||
|
||||
const ready = !loading && !!user;
|
||||
|
||||
File diff suppressed because it is too large
Load Diff
+1029
File diff suppressed because it is too large
Load Diff
@@ -0,0 +1,57 @@
|
||||
/**
|
||||
* Signing in through the church's Accounts (3.0.0, docs/EVENTS-3.0-PLAN.md §3). Once an admin has
|
||||
* moved sign-in (Settings → Sign-in), `/login`, `/register` and `/forgot-password` forward to
|
||||
* `GET /api/auth/signin?returnTo=…`, which sends the browser to Accounts and back to the same page.
|
||||
* Every existing `/login?redirect=…` link keeps working that way.
|
||||
*/
|
||||
import { API_BASE } from "@/lib/api";
|
||||
|
||||
export type AuthMode = "local" | "accounts";
|
||||
|
||||
export type AuthInfo = { mode: AuthMode; accountUrl: string | null };
|
||||
|
||||
let infoPromise: Promise<AuthInfo> | null = null;
|
||||
|
||||
/**
|
||||
* Where people sign in, and (through Accounts) the church account page, asked once per page load
|
||||
* (it only changes when an admin moves sign-in).
|
||||
*/
|
||||
export function fetchAuthInfo(): Promise<AuthInfo> {
|
||||
if (!infoPromise) {
|
||||
infoPromise = fetch(`${API_BASE}/api/v2/auth/mode`, { headers: { Accept: "application/json" } })
|
||||
.then((r) => (r.ok ? r.json() : null))
|
||||
.then((j: { data?: { mode?: AuthMode; accountUrl?: string | null } } | null): AuthInfo => ({
|
||||
mode: j?.data?.mode === "accounts" ? "accounts" : "local",
|
||||
accountUrl: j?.data?.accountUrl ?? null,
|
||||
}))
|
||||
.catch(() => {
|
||||
infoPromise = null;
|
||||
return { mode: "local" as const, accountUrl: null };
|
||||
});
|
||||
}
|
||||
return infoPromise;
|
||||
}
|
||||
|
||||
export function fetchAuthMode(): Promise<AuthMode> {
|
||||
return fetchAuthInfo().then((i) => i.mode);
|
||||
}
|
||||
|
||||
/** A relative path on this site, or the fallback: never another site (the backend checks too). */
|
||||
export function safePath(raw: string | null | undefined, fallback = "/dashboard"): string {
|
||||
const s = String(raw ?? "");
|
||||
return s.startsWith("/") && !s.startsWith("//") && !s.startsWith("/\\") ? s : fallback;
|
||||
}
|
||||
|
||||
/** The address that signs someone in through Accounts and brings them back to `returnTo`. */
|
||||
export function signInHref(returnTo: string, opts: { signUp?: boolean; email?: string } = {}): string {
|
||||
const q = new URLSearchParams({ returnTo: safePath(returnTo) });
|
||||
if (opts.signUp) q.set("signup", "1");
|
||||
if (opts.email) q.set("email", opts.email);
|
||||
return `${API_BASE}/api/auth/signin?${q.toString()}`;
|
||||
}
|
||||
|
||||
/** The page someone is on now (path and query), to come back to after signing in. */
|
||||
export function currentPage(): string {
|
||||
if (typeof window === "undefined") return "/";
|
||||
return `${window.location.pathname}${window.location.search}`;
|
||||
}
|
||||
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "@crosscode/events",
|
||||
"version": "2.4.1",
|
||||
"version": "3.1.0",
|
||||
"main": "index.js",
|
||||
"scripts": {
|
||||
"dev:backend": "cd backend && npm run dev",
|
||||
|
||||
@@ -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" },
|
||||
},
|
||||
],
|
||||
});
|
||||
|
||||
@@ -11,10 +11,10 @@ as a product: its pages carry the church's name and colours ("Sign in to Hope Fa
|
||||
Admins see it as **Accounts** (people, sign-in settings, linked products, the church profile).
|
||||
Each product keeps its own roles and data, keyed by the account's `sub`.
|
||||
|
||||
**Who uses 1.0:** the Church Website (phase 4) is built on it from its first release. Cross Events
|
||||
keeps its own sign-in until **3.0** (phase 5), which moves its users across with their password
|
||||
hashes and 2FA. So 1.0 is tested against a test product (a small OIDC client in the e2e tests), and
|
||||
everything Events 3.0 will need (bcrypt and Argon2id hashes, authenticator secrets, recovery codes,
|
||||
**Who uses 1.0:** Cross Events **3.0** (phase 4, moved before the Website on 2026-11-19, ROADMAP
|
||||
decision 38) moves its users across with their password hashes and 2FA; until then Events keeps its
|
||||
own sign-in. The Church Website (phase 5) is built on it from its first release. 1.0 itself is
|
||||
tested against a test product (a small OIDC client in the e2e tests), and everything Events 3.0 will need (bcrypt and Argon2id hashes, authenticator secrets, recovery codes,
|
||||
notice versions) is supported from the start.
|
||||
|
||||
**Done when:**
|
||||
@@ -215,7 +215,7 @@ and its sign-in pages need the name, logo and colours before anything else exist
|
||||
under **Accounts → Church profile** (name, short name, logo, colours, campuses, service times,
|
||||
contact details, social links). It's served at `GET /api/church/v1` (public, cached; the
|
||||
`links` filled in from the linked products) and announced to linked products with a signed
|
||||
`church.updated` call. The Website (phase 4) reads it and shows its own form for it, saving
|
||||
`church.updated` call. The Website (phase 5) reads it and shows its own form for it, saving
|
||||
through Accounts' API with the admin's token. Events keeps its own settings until 3.0, then reads
|
||||
the profile too.
|
||||
|
||||
@@ -297,7 +297,7 @@ phone-first.
|
||||
1. `contracts@1.5.0`, then Hub `v2.3.0` (vendored contracts) deployed.
|
||||
2. `accounts@1.0.0` tagged after the e2e and VM runs.
|
||||
3. crosscode-site `v1.5.0`.
|
||||
4. **Churches get Accounts with the Website** (phase 4) or with Events 3.0, whichever comes first
|
||||
4. **Churches get Accounts with Events 3.0** (phase 4) or with the Website (phase 5), whichever comes first
|
||||
for them (decision 6). Until then nothing uses it, so it isn't installed for its own sake.
|
||||
|
||||
## Changes while building
|
||||
@@ -354,6 +354,6 @@ Confirmed by Joshua on 2026-11-18 (1, 4, 5 and 6 asked directly; the rest as pro
|
||||
## Still open
|
||||
|
||||
- Whether the Website's admin edits the church profile through Accounts' API (as proposed in §7)
|
||||
or Accounts' own screen is the only place. Decide with the Website plan (phase 4).
|
||||
or Accounts' own screen is the only place. Decide with the Website plan (phase 5).
|
||||
- Session lengths (30 days with "Keep me signed in") are a starting point; check them with Joshua
|
||||
before release.
|
||||
|
||||
@@ -14,7 +14,7 @@ feed, **shows** events from linked products, and builds its SEO data with the ne
|
||||
settings page that says "No other products yet".
|
||||
|
||||
The Website and App don't exist yet, so the "show events from" side is built and tested against
|
||||
sample feeds (§8). It's ready for the Website (phase 4) without another Events release.
|
||||
sample feeds (§8). It's ready for the Website (phase 5) without another Events release.
|
||||
|
||||
**Done when:**
|
||||
|
||||
@@ -422,7 +422,7 @@ Proposed in this plan, to confirm before building:
|
||||
|
||||
- **Who owns the church profile (`crosscode.church/1`)** once there's more than one product?
|
||||
Events builds one from its own settings for its JSON-LD in 2.4.0, but doesn't serve it to
|
||||
siblings. The Website (phase 4) is the natural owner; decide before phase 4.
|
||||
siblings. The Website (phase 5) is the natural owner; decide before phase 5.
|
||||
- **Event `summary` and `tags`** go out empty because Events has no such fields. Add them in a
|
||||
later 2.x if the Website's event cards need them.
|
||||
- **A "cancelled" state in Events** (shown as cancelled rather than disappearing) would map to
|
||||
|
||||
@@ -0,0 +1,513 @@
|
||||
# Cross Events 3.0.0 — signing in through Accounts
|
||||
|
||||
Phase **4** of [ROADMAP-v3.md](./ROADMAP-v3.md) (§3 "Moving Cross Events onto Accounts", §8, §9;
|
||||
decisions 2, 14, 15, 17, 24, 38). Written 2026-11-19. **Decisions confirmed 2026-11-19** (all as proposed). **Released
|
||||
2026-11-19** (`events@3.0.0`, `accounts@1.1.0`, `contracts@1.8.0`, Hub `v2.5.0`, crosscode-site
|
||||
`v1.6.0`), tested on Postgres 18; the VM test is still to do. Moved before the Website on 2026-11-19 (decision 38), so this is the first product
|
||||
that really signs people in through [Accounts](./ACCOUNTS-1.0-PLAN.md).
|
||||
|
||||
**What 3.0.0 is:** Cross Events stops keeping passwords. Sign-in, sign-up, forgot password, 2FA,
|
||||
the news question and the privacy notice move to the church's Accounts
|
||||
(`accounts.<church's address>`), and Events signs people in as an OIDC client with
|
||||
`packages/auth-client`. Every existing Events user is copied into Accounts **with their password
|
||||
hash, 2FA method and authenticator secret, consent and notice acceptance**, so nobody resets
|
||||
anything. Roles, campus scopes, registrations, tickets and every other piece of Events data stay
|
||||
in Events, keyed by the account's `sub`.
|
||||
|
||||
It's a major version because it can't run without Accounts: a church needs Accounts installed and
|
||||
connected before its Events can move.
|
||||
|
||||
**Done when:**
|
||||
|
||||
- `events@3.0.0`, `accounts@1.1.0` and `contracts@1.8.0` are tagged and pushed; the Hub refuses
|
||||
to update an Events install to 3.0 until its church has Accounts 1.1.0 (decision 24).
|
||||
- An Events 2.4.x install with real-looking data (the `ministry` and `multicampus` demo profiles)
|
||||
updates to 3.0 and moves its users to Accounts with one admin action; afterwards every
|
||||
imported person signs in with their **old password**, and an authenticator user with their
|
||||
**old authenticator**, without resetting anything.
|
||||
- Signing in from any Events page (an event page, `register?ticket=…`, the dashboard, a ticket
|
||||
link) lands back on that exact page, through 2FA, a password reset, sign-up and a new privacy
|
||||
notice; old `/login?redirect=…` links still work (ROADMAP §9 "Release checks").
|
||||
- Supervisors and admins can't use Events without 2FA (`acr_values=mfa`).
|
||||
- Signing out of Events signs the person out of Accounts and every other product, and signing
|
||||
out elsewhere ends their Events session.
|
||||
- "Download my data" in Accounts includes Events' part; "Delete my account" waits while the
|
||||
person has an open registration for an upcoming event (Events answers `deferred`).
|
||||
- It updates and installs through the agent on the VM next to Accounts.
|
||||
- crosscode-site says Cross Events signs in through the church's shared account, with updated
|
||||
screenshots (ROADMAP §9, "Updating crosscode-site").
|
||||
|
||||
## Contents
|
||||
|
||||
1. [Before starting](#before-starting)
|
||||
2. [The shape](#1-the-shape)
|
||||
3. [Users: `sub`, guests and roles](#2-users-sub-guests-and-roles)
|
||||
4. [Signing in and out](#3-signing-in-and-out)
|
||||
5. [Moving the users (the import)](#4-moving-the-users-the-import)
|
||||
6. [Turning it on: the move, step by step](#5-turning-it-on-the-move-step-by-step)
|
||||
7. [What moves to Accounts, page by page](#6-what-moves-to-accounts-page-by-page)
|
||||
8. [Privacy: export, delete, retention](#7-privacy-export-delete-retention)
|
||||
9. [Accounts 1.1.0](#8-accounts-110)
|
||||
10. [New installs](#9-new-installs)
|
||||
11. [Security](#10-security)
|
||||
12. [What changes in each repo](#11-what-changes-in-each-repo)
|
||||
13. [Testing](#12-testing)
|
||||
14. [Releasing and rolling it out](#13-releasing-and-rolling-it-out)
|
||||
15. [Changes while building](#changes-while-building)
|
||||
16. [Decisions](#decisions)
|
||||
17. [Still open](#still-open)
|
||||
|
||||
---
|
||||
|
||||
## Before starting
|
||||
|
||||
- **Accounts 1.0.x is proven first:** its VM test and a run on real Postgres
|
||||
(ACCOUNTS-1.0-PLAN, "Not yet"). 3.0 is the first thing that puts real people on it, so those
|
||||
have to pass before any 3.0 code is merged.
|
||||
- **Events 2.4.x's e2e run on Postgres and VM test** (EVENTS-2.4-PLAN §8) are done: 3.0 builds on
|
||||
2.4's Linked products and Connect, which are what register Events as an OIDC client.
|
||||
- `apps/events` and `apps/accounts` build and test clean on `main` (`npm run check`).
|
||||
- **Module format:** `@crosscode/auth-client` and `openid-client` 6 are ESM only, and the Events
|
||||
backend is CommonJS. Check the Node version on the servers allows `require()` of ESM (Node 22.12+
|
||||
/ 20.19+); otherwise give `auth-client` a CommonJS build too (`tsup --format esm,cjs`). Decide
|
||||
this first, since every sign-in path goes through it.
|
||||
|
||||
## 1. The shape
|
||||
|
||||
```
|
||||
Events (events.hopefamily.co.za) Accounts (accounts.hopefamily.co.za)
|
||||
───────────────────────────────── ─────────────────────────────────────
|
||||
/login?redirect=/events/camp/register ──302──▶ /api/auth/signin?returnTo=… (Events backend)
|
||||
│ PKCE + state(returnTo), pending cookie
|
||||
▼
|
||||
──302──▶ authorize → /signin?uid=… (password, 2FA,
|
||||
reset, sign-up, notice, news: all Accounts)
|
||||
/api/auth/callback ◀──302── code ──────────────── ┘
|
||||
│ finishSignIn → claims (sub, name, email, phone, news, notice)
|
||||
│ find or make the Events User by sub, update the local copy, check role / 2FA
|
||||
▼
|
||||
/auth/complete#handoff → frontend swaps the one-time handoff for Events' own token
|
||||
▼
|
||||
/events/camp/register (the exact page the person started on)
|
||||
|
||||
Accounts → Events (signed with the link's secret, ACCOUNTS-1.0-PLAN §6):
|
||||
POST /api/auth/backchannel-logout end that person's Events sessions
|
||||
POST /api/accounts/v1/events user.updated · user.export · user.deleted
|
||||
```
|
||||
|
||||
- **Events keeps its own session** (ACCOUNTS-1.0 decision 3: products keep their own sessions, no
|
||||
refresh tokens). That is today's Events token, with `tokenVersion`, so every API route, the
|
||||
check-in scanner, impersonation and `protect` keep working unchanged. Only how a token is
|
||||
*obtained* changes (§3).
|
||||
- **No password, 2FA secret or recovery code is kept in Events** once the move is finished (§5).
|
||||
The columns stay in 3.0 so the move can be undone; 3.1 drops them.
|
||||
- Accounts' address comes from Linked products (the Hub-listed URL Events 2.4 already connects
|
||||
to), so there is **no new `.env` variable** for the address. The link secret is the one Connect
|
||||
already stores.
|
||||
|
||||
## 2. Users: `sub`, guests and roles
|
||||
|
||||
**Recommended change from ROADMAP §3:** instead of making `User.id` equal the account's `sub`,
|
||||
Events gets a new column **`User.accountId`** (nullable, unique). See decision 1.
|
||||
|
||||
- For every imported user, Accounts **creates the account with the Events user's id as its `sub`**
|
||||
(`Account.id = User.id`), and Events sets `accountId = id`. So for everyone who exists today,
|
||||
`sub` and `User.id` are equal, which is what the roadmap wanted, and no foreign key in Events
|
||||
is rewritten.
|
||||
- The column matters for the cases where they can't be equal:
|
||||
- **Guests** (`guest+…@guest.local`, made by staff at the door or by a registration without an
|
||||
account, `utils/accountMatch.js`, `registrationAdmin.ts`) are not people who sign in. They are
|
||||
**not imported** and keep `accountId = null`. When someone later signs in through Accounts with
|
||||
the same **verified** email as a guest record, Events links them (`accountId` set on the guest
|
||||
row), as `accountMatch.js` already matches today.
|
||||
- **An email already in Accounts** under another `sub` (a person who made an account before the
|
||||
move, e.g. through a test product or another product): the import doesn't overwrite it. Events
|
||||
links that User to the existing account (`accountId` = the existing `sub`), and the person
|
||||
keeps the **Accounts** password. These are listed in the move report (§5).
|
||||
- **Deleted** (`@deleted.invalid`, `@deleted.local`) and anonymised users: not imported,
|
||||
`accountId = null`, nothing changes.
|
||||
- **Roles stay in Events** (`admin`, `supervisor`, `staff`, `user`) with campus scopes, as today
|
||||
(ACCOUNTS-1.0-PLAN §2). Someone new to Events who signs in through Accounts arrives as `user`.
|
||||
- **Accounts admins:** the move asks which Events admins should also be Accounts admins (default:
|
||||
every Events `admin`, ticked; decision 4). They need 2FA, which Events admins already have.
|
||||
- `isActive = false` users are imported as `deactivated`; they can't sign in anywhere until an
|
||||
Accounts admin reactivates them (an Events admin reactivating them in Events calls Accounts, §8).
|
||||
|
||||
## 3. Signing in and out
|
||||
|
||||
### Starting a sign-in
|
||||
|
||||
- **One backend route:** `GET /api/auth/signin?returnTo=<path>` calls
|
||||
`auth.startSignIn(returnTo, { requireTwoFactor, loginHint })`, sets the pending cookie
|
||||
(`HttpOnly; Secure; SameSite=Lax; Path=/api/auth`, 10 minutes) and redirects to Accounts.
|
||||
`returnTo` goes through `safeReturnPath` (a relative path starting with a single `/`; anything
|
||||
else becomes `/`).
|
||||
- **`/login` stays a page** in the frontend, but only forwards: `/login?redirect=…` →
|
||||
`/api/auth/signin?returnTo=…`. So every old link, email, PDF and QR code with
|
||||
`/login?redirect=` keeps working (ROADMAP §3).
|
||||
- `useRequireAuth` and every "Sign in" link (49 files reference `/login`) use one helper,
|
||||
`signInHref(returnTo = current path + query)`, so they all return to the page they were on.
|
||||
- `/register` forwards the same way with `prompt=create` (Accounts opens on sign-up) and the same
|
||||
return path. Sign-up being off in Accounts (staff-only churches) shows Accounts' own message.
|
||||
- `/forgot-password` forwards to Accounts' forgot-password, with the return path.
|
||||
- `/reset-password` and `/activate-account` links already in people's inboxes: the page says the
|
||||
church's sign-in has moved and offers "Set a new password" (Accounts' forgot-password, email
|
||||
filled in when the token still identifies the person).
|
||||
|
||||
### 2FA for staff
|
||||
|
||||
`requiresTwoFactor(user)` is unchanged (supervisors and admins always; settings may add staff).
|
||||
Events doesn't know the person's role until after the callback, so:
|
||||
|
||||
1. The first sign-in asks for nothing extra.
|
||||
2. At the callback, if the Events user's role needs 2FA and the ID token's `acr` / `amr` (`mfa`) doesn't
|
||||
show it, Events starts **a second sign-in with `acr_values=mfa`** straight away (same
|
||||
`returnTo`). Accounts asks for 2FA, or sets it up first if the person has none. The person sees
|
||||
one 2FA prompt, not two sign-ins, because the Accounts session is already there.
|
||||
3. A user whose role is raised to supervisor in Events gets step 2 on their next sign-in.
|
||||
|
||||
The Events "trusted device" (`TrustedDevice`, skip 2FA for 30 days) goes away: that decision is
|
||||
Accounts' now ("Keep me signed in").
|
||||
|
||||
### The callback
|
||||
|
||||
`GET /api/auth/callback`:
|
||||
|
||||
1. `auth.finishSignIn(url, pendingCookie)`; clear the cookie. Errors (expired, refused, bad
|
||||
claims) show a short page with "Try again" (a fresh sign-in with the same `returnTo`).
|
||||
2. Find the User by `accountId = sub`. Not found: link a guest with the same verified email (§2),
|
||||
or make a new `user`.
|
||||
3. Update the local copy from the claims: name, email, phone, `newsEmail` / `newsWhatsApp`,
|
||||
`noticeVersionAccepted`, `lastLoginAt`. Keep the ID token (for sign-out's `id_token_hint`) in
|
||||
a server-side row keyed to the Events session, not in the browser.
|
||||
4. `isActive = false` in Events: a "Your access to Events has been turned off, ask the office"
|
||||
page (the Accounts account is fine; it's Events access that's off).
|
||||
5. Make a **one-time handoff code** (random, 60 seconds, single use, hashed in the database) and
|
||||
redirect to `/auth/complete#<code>`. The page posts it to `POST /api/auth/handoff`, which
|
||||
answers with Events' usual token and user, exactly as `/auth/login` did. The frontend stores it
|
||||
as today and goes to `returnTo`.
|
||||
|
||||
The fragment keeps the code out of server logs and `Referer`. A handoff can't be swapped twice.
|
||||
|
||||
### Signing out
|
||||
|
||||
- **Sign out** in Events: bump the user's `tokenVersion` (ends their Events sessions), then send
|
||||
the browser to `auth.signOutUrl(idToken)`. Accounts ends its session and the back-channel logout
|
||||
reaches every product; the browser comes back to Events' home page signed out.
|
||||
- **Back-channel logout** (`POST /api/auth/backchannel-logout`): `auth.verifyLogoutToken`, then bump
|
||||
that user's `tokenVersion`. Events tokens are short-lived and checked against `tokenVersion` on
|
||||
every request, so the next API call fails and the frontend shows signed out.
|
||||
- **Impersonation** is unchanged: it's an Events session an admin starts in Events, not a sign-in.
|
||||
|
||||
## 4. Moving the users (the import)
|
||||
|
||||
### What's copied
|
||||
|
||||
| Events | Accounts | Notes |
|
||||
|--------|----------|-------|
|
||||
| `User.id` | `Account.id` (the `sub`) | §2 |
|
||||
| name, email (lower-case), `phoneNumber` | name, email, phone | `givenName` / `familyName` left empty |
|
||||
| `password` (bcrypt or Argon2id) | `passwordHash` | Accounts already verifies both and re-hashes bcrypt on sign-in |
|
||||
| — | `emailVerified` | `true` if they have ever signed in (`lastLoginAt` set) or activated; otherwise `false`, and Accounts verifies the email on first sign-in |
|
||||
| `twoFactorEnabled` + `twoFactorMethod` | `twoFactorMethod` | `authenticator` → `totp`; email / WhatsApp as they are |
|
||||
| `totpSecret` (encrypted with Events' key), `totpLastStep` | `totpSecret` (encrypted with Accounts' key), `totpLastStep` | decrypted in Events, sent encrypted (§10), encrypted again by Accounts |
|
||||
| unused `RecoveryCode`s | — | **Not copied**, see decision 2. People with 2FA get new codes after their first sign-in |
|
||||
| `failedAttempts`, `lockUntil` | `failedSignIns`, `lockedUntil` | so a lockout in progress isn't lifted by moving |
|
||||
| `newsEmail`, `newsWhatsApp`, `newsAskedAt` | the same | |
|
||||
| `CommunicationConsent` history | `ConsentChange` | `source: "events_import"`; POPIA proof isn't lost |
|
||||
| `noticeVersionAccepted`, `NoticeAcceptance` | `noticeVersionAccepted`, `NoticeAcceptance` | |
|
||||
| `PrivacyNotice` versions | `PrivacyNotice` (same version numbers) | only if Accounts has published none of its own yet; otherwise the move stops and asks (decision 5) |
|
||||
| `lastLoginAt`, `isActive` | `lastSignInAt`, `status` | |
|
||||
| `role = admin` | `role = admin` | only those ticked (§2) |
|
||||
|
||||
**Not copied:** `SecurityEvent` (Events' login history) stays in Events, readable as before and
|
||||
expiring under its retention rule; Accounts' `LoginEvent` starts at the move. `TrustedDevice`,
|
||||
`PasswordReset` and pending 2FA challenges are dropped. Events' notification preference
|
||||
(`notificationPreference`: how Events itself sends tickets and reminders) stays in Events.
|
||||
|
||||
**The church profile:** if Accounts' church profile has no name or logo yet, the move fills them
|
||||
from Events' site settings (organisation name, logo, primary colour), so the sign-in page looks
|
||||
like the church straight away. Events keeps its own settings in 3.0 (see Still open).
|
||||
|
||||
### How it's sent
|
||||
|
||||
- A new **link call**, `POST <accounts>/api/accounts/v1/import` (contracts 1.8.0,
|
||||
`crosscode.identity-import/1`), signed with the link secret like every other link call
|
||||
(`LINK_HEADERS`), in **batches of 200 people**.
|
||||
- Secrets in the payload (password hashes, TOTP secrets) are additionally **encrypted with a key
|
||||
derived from the link secret** (AES-256-GCM, `HKDF(linkSecret, "crosscode.identity-import/1")`),
|
||||
so they never show up in a proxy log or an error report even if TLS is terminated in between.
|
||||
- **Idempotent:** Accounts upserts by `id`; sending a batch twice changes nothing. A batch answers
|
||||
per person: `created`, `updated`, `linked` (email already there under another `sub`, with that
|
||||
`sub`), or `refused` (with why: bad email, duplicate email in the batch).
|
||||
- Only allowed **while the move is in progress** for that link (Accounts 1.1.0 keeps a flag per
|
||||
linked product, set by the move's first call and cleared by its last), and only from a product
|
||||
of type `events`.
|
||||
|
||||
## 5. Turning it on: the move, step by step
|
||||
|
||||
**3.0.0 starts with local sign-in still working**, so updating a church to 3.0 changes nothing
|
||||
for its people until an admin moves sign-in (decision 3). Then:
|
||||
|
||||
1. **Settings → Sign-in** (new, admins only) says where sign-in stands: *In Cross Events* →
|
||||
*Moving* → *Through Accounts*. It needs Accounts **connected** under Linked products; if it
|
||||
isn't, it says so with a link there.
|
||||
2. **Check:** a dry run, nothing written. It shows how many people would be created, linked to an
|
||||
existing account, skipped (guests, deleted), and anything that would stop the move (Accounts
|
||||
older than 1.1.0, a notice conflict, emails Accounts would refuse). The admin ticks which Events
|
||||
admins also become Accounts admins.
|
||||
3. **Move:** Events stops new sign-ins for a moment (people already signed in stay signed in;
|
||||
the sign-in page says "One moment, we're updating the sign-in"), sends every batch, then
|
||||
**checks** by asking Accounts for the count and a hash of the imported ids. Only when they
|
||||
match does it switch: `auth_mode = accounts`. Typically under a minute for a few thousand people
|
||||
(Argon2 isn't run; hashes are copied).
|
||||
4. If anything fails, it stays on *In Cross Events* with the error, and the move can be run again
|
||||
(it's idempotent).
|
||||
5. **After the switch:** existing Events sessions keep working (the token didn't change), so
|
||||
nobody is thrown out mid-registration. Their next sign-in goes through Accounts.
|
||||
6. A **move report** (also in the audit log): counts, the people linked to an existing account,
|
||||
and the admins made Accounts admins. Emailed to the admin who ran it.
|
||||
7. **Undo**, for 14 days: switches `auth_mode` back to `local`. The Events password columns were
|
||||
kept, so people sign in with the password they had **at the move**; changes made in Accounts
|
||||
since then (a new password, 2FA set up) don't come back to Events, and the page says so. After
|
||||
14 days, a job clears Events' password hashes, TOTP secrets and recovery codes, and Undo goes.
|
||||
|
||||
The Hub can also start the move (decision 3 alternative): not in 3.0; the button is in Events.
|
||||
|
||||
## 6. What moves to Accounts, page by page
|
||||
|
||||
| Events today | 3.0 |
|
||||
|--------------|-----|
|
||||
| `/login`, `/register`, `/forgot-password` | Forward to Accounts with the return path (§3) |
|
||||
| `/reset-password`, `/activate-account` | "Sign-in has moved" + Set a new password (§3) |
|
||||
| Login code page (2FA challenge) | Gone; Accounts asks |
|
||||
| Profile: name, email, phone | Shown read-only, with **Change in your account** (Accounts' account page, coming back to the Events profile). Notification preference stays editable in Events |
|
||||
| Profile: password, 2FA, recovery codes, trusted devices | **Your sign-in and security** → Accounts' account page |
|
||||
| News question and notice prompts after login | Gone; Accounts asks before coming back (`newsPromptPending` / `noticePromptPending` are always false in `auth_mode = accounts`) |
|
||||
| Privacy centre: download my data, delete my account | Link to Accounts (§7). The Events-only items stay (what Events holds, consent history for Events messages) |
|
||||
| Privacy centre: my login history | Events' old history, plus "Recent sign-ins are in your account" |
|
||||
| Admin → Users: add a person | Creates or finds the account in Accounts (§8, `people.ensure`), then sets the Events role. Accounts sends the "set your password" email instead of Events' activation link |
|
||||
| Admin → Users: reset 2FA, unlock, resend activation | Call Accounts (§8), audited in both |
|
||||
| Admin → Users: deactivate | Turns off **Events** access (`isActive`); "also deactivate their account everywhere" is a separate tick that asks Accounts |
|
||||
| Admin → Users: change email / name | Through Accounts (`people.update`), then `user.updated` updates Events' copy |
|
||||
| Admin → 2FA methods per staff account (2.3.0) | Read from the claims at sign-in (`two_factor`), shown as before |
|
||||
| Settings → Privacy notice versions | Managed in Accounts; Events' screen links there |
|
||||
| Settings → 2FA for staff roles | Stays in Events (it decides when Events sends `acr_values=mfa`) |
|
||||
| Broadcasts "News & announcements" audience | Unchanged: uses the local `newsEmail` / `newsWhatsApp`, kept current from the claims and `user.updated` |
|
||||
| Unsubscribe links in news messages | Turn news off in Accounts through `people.consent` (§8), so it's off for every product; the page still works without signing in |
|
||||
| Setup wizard (new install) | §9 |
|
||||
|
||||
All of this applies only in `auth_mode = accounts`; in `local` (before the move, or after Undo)
|
||||
Events works as 2.4.
|
||||
|
||||
## 7. Privacy: export, delete, retention
|
||||
|
||||
Events answers Accounts' signed calls at `POST /api/accounts/v1/events` (`auth.verifyAccountsCall`):
|
||||
|
||||
- **`user.updated`:** update the local copy (name, email, phone, news consent, notice version).
|
||||
Unknown `sub`: answer ok and ignore.
|
||||
- **`user.export`:** Events' part as `crosscode.identity/1` export sections: registrations, tickets,
|
||||
payments, check-ins, certificates, form answers, Events-only consent history, login history
|
||||
before the move. This is what Events' own "Download my data" bundles today
|
||||
(`churchExport.ts`, the privacy centre export), reshaped into sections.
|
||||
- **`user.deleted`:** the existing Events rules (anonymise; refunds and financial records kept as
|
||||
the law requires). **`deferred`** with `retryAfter` while the person has an open registration
|
||||
for an upcoming event, as Events does today; Accounts asks again.
|
||||
- **Retention of inactive accounts** moves to Accounts (ACCOUNTS-1.0-PLAN §6). Events' inactivity
|
||||
job stops warning and deleting people with an `accountId`; it still cleans up guests and old
|
||||
Events-only data as today.
|
||||
- **Access log:** Events keeps logging admins viewing a person's Events data; Accounts logs the
|
||||
account side.
|
||||
|
||||
## 8. Accounts 1.1.0
|
||||
|
||||
What Events 3.0 needs from Accounts, all as link calls signed with the link secret and allowed
|
||||
only for a connected product:
|
||||
|
||||
- **`POST /api/accounts/v1/import`** (§4), with the per-link "move in progress" flag, the
|
||||
dry-run mode (`check: true`) and the final count / hash check.
|
||||
- **`people.ensure`:** find an account by email or make one (no password; sends the church's "set
|
||||
your password" email with a link back to the product). For Admin → Users → Add.
|
||||
- **`people.update`**, **`people.resetTwoFactor`**, **`people.unlock`**, **`people.deactivate`**,
|
||||
**`people.consent`** (news off, from an unsubscribe link): what an Events admin can already do,
|
||||
done to the account. Each is checked against the calling product's link, audited in Accounts
|
||||
with the product and the Events admin's `sub`, and limited to people that product knows.
|
||||
- **`prompt=create`** opens sign-up directly (sign-up is in 1.0; this is the entry point).
|
||||
- **Legacy reset and activation tokens:** none; Events shows "Set a new password" instead (§3).
|
||||
- **The ID token's `amr` / `acr`** say whether 2FA was used on this sign-in (already in 1.0; make
|
||||
sure `acr` is `mfa` exactly when a second factor was used, which §3 relies on).
|
||||
- Accounts' WHATS-NEW notes the Events move; Events 3.0's WHATS-NEW says
|
||||
`## 3.0.0 — requires accounts 1.1.0` (decision 24, the Hub and the `crosscode` script refuse the
|
||||
update until it's met).
|
||||
|
||||
## 9. New installs
|
||||
|
||||
- **Hub New install of Events 3.x** installs **Accounts first** if the church doesn't have it
|
||||
(an `install` job for Accounts, then an `add-product` job for Events), as New install already
|
||||
does for a church's first product (Hub 2.3.0).
|
||||
- **Connect happens by itself** for a new install: the setup wizard (or the Hub's install
|
||||
record) connects Events to the church's Accounts using the Hub's Linked products, so no admin
|
||||
has to find the button.
|
||||
- **The setup wizard** no longer makes an admin with a password. Its last step is **Sign in with
|
||||
your church account**: the person who completes the wizard (holding the setup token) signs in
|
||||
through Accounts (making an account if needed), and that `sub` becomes Events' first `admin`.
|
||||
`SETUP_TOKEN_GRACE_SECONDS` still lets them finish before 2FA is set up; Accounts then asks for
|
||||
2FA because Events sends `acr_values=mfa` for admins.
|
||||
- A new install starts in `auth_mode = accounts`; there's nobody to move.
|
||||
- Demo data (`crosscode demo`, `npm run demo:*`): demo people are made in Accounts too (through
|
||||
the import call with the demo's known password), so a demo site can be signed in to as before.
|
||||
|
||||
## 10. Security
|
||||
|
||||
- Exact-match redirect URIs (Connect registers `<events url>/api/auth/callback`), PKCE, `nonce`,
|
||||
state checked, `safeReturnPath` on every return: all from `auth-client` and Accounts 1.0.
|
||||
- The pending-sign-in cookie and the handoff code are single use and short-lived; the handoff goes
|
||||
in the URL fragment, never the query.
|
||||
- Import payloads: signed **and** encrypted (§4); only while a move is in progress; only from a
|
||||
connected Events install; every batch audited in both apps. A stolen link secret already allows
|
||||
the 1.0 calls; the import adds no new secret.
|
||||
- After the move, Events holds **no password hash or 2FA secret** once Undo expires (14 days).
|
||||
- `/api/auth/*` rate-limited as `/auth/login` is today.
|
||||
- Tokens: Events' existing token rules (pinned HS256, `tokenVersion`) are unchanged; back-channel
|
||||
logout makes `tokenVersion` the single switch for "this person is signed out".
|
||||
|
||||
## 11. What changes in each repo
|
||||
|
||||
| Repo | Change | Version |
|
||||
|------|--------|---------|
|
||||
| `crosscode-platform` `apps/events` | §2–§7 and §9: `User.accountId`, `/api/auth/*`, the handoff, `auth_mode`, Settings → Sign-in (check / move / undo), `/api/accounts/v1/events`, forwarding pages, profile and privacy centre links, admin user actions through Accounts, setup wizard, demo data. Migration guide (`MIGRATING-TO-3.md`, as `MIGRATING-TO-2.md`) | `events@3.0.0` |
|
||||
| `crosscode-platform` `apps/accounts` | §8: import, `people.*` calls, `prompt=create`, per-link move flag | `accounts@1.1.0` |
|
||||
| `crosscode-platform` `packages/contracts` | `crosscode.identity-import/1` (batch, per-person result, check), the `people.*` call schemas, paths | `contracts@1.8.0` |
|
||||
| `crosscode-platform` `packages/auth-client` | `verifyAccountsCall` already there; add `callAccounts()` (signed link calls to Accounts) and, if needed, a CommonJS build (Before starting) | workspace |
|
||||
| `crosscode-platform` `scripts/` | Nothing new expected: `deploy` already updates Accounts first and checks `requires accounts …`. Check `crosscode demo` for §9 | — |
|
||||
| `events-hub` | New install of Events 3.x adds Accounts first and connects them (§9); release requirements already work (decision 24). Vendored contracts 1.8.0 | Hub `v2.5.0` |
|
||||
| `crosscode-site` | Cross Events page: sign-in through the church's shared account; screenshots of the sign-in (ROADMAP §9) | `v1.6.0` |
|
||||
|
||||
## 12. Testing
|
||||
|
||||
- **Unit (Jest, Events):** the callback (new user, existing by `sub`, guest linked by verified
|
||||
email, unverified email not linked, deactivated in Events), the 2FA step-up decision from
|
||||
`acr`, handoff (single use, expiry), `safeReturnPath` on every entry point, back-channel logout
|
||||
bumping `tokenVersion`, `user.*` handlers including `deferred`, the import batch builder
|
||||
(mapping `authenticator` → `totp`, guests and deleted skipped, secrets encrypted).
|
||||
- **Unit (Jest, Accounts):** import upsert and idempotency, `linked` on an existing email, refused
|
||||
outside a move or from a non-Events link, imported bcrypt and Argon2id passwords sign in, an
|
||||
imported TOTP secret produces valid codes, `people.*` limited to the product's people.
|
||||
- **The move, end to end, on Postgres:** load the `multicampus` demo into Events 2.4.1, update to
|
||||
3.0, run Check then Move, then sign in as a sample of the demo people (bcrypt, Argon2id,
|
||||
authenticator, email 2FA, a locked-out person stays locked), then Undo and sign in locally.
|
||||
- **Playwright (the release checks, ROADMAP §9):** Events and Accounts running together (Accounts'
|
||||
`e2e/server.ts` approach for Accounts, the Events e2e Postgres for Events). From a deep link
|
||||
(`/events/<slug>/register?ticket=…`): sign in, sign in with 2FA, password reset, sign-up, a new
|
||||
notice: each lands back on that page. `/login?redirect=` still works; `?redirect=https://evil`
|
||||
and `//evil` land on `/`. A supervisor without 2FA is made to set it up. Signing out of Events
|
||||
signs out of Accounts and the test product; signing out of the test product ends the Events
|
||||
session.
|
||||
- **VM:** a church with Events 2.4.1 (adopted) gets Accounts through the Hub (`add-product`),
|
||||
Connect, update Events to 3.0 through the agent (refused before Accounts 1.1.0), Move, sign in
|
||||
through the real proxies; then a New install of Events 3.0 for a second church (Accounts first,
|
||||
connected, setup wizard). Uninstall exports include both.
|
||||
|
||||
## 13. Releasing and rolling it out
|
||||
|
||||
1. `contracts@1.8.0` → Hub `v2.5.0` (vendored contracts) deployed.
|
||||
2. `accounts@1.1.0` tagged after its tests and the move test.
|
||||
3. `events@3.0.0` tagged after the e2e and VM runs, with `MIGRATING-TO-3.md`.
|
||||
4. crosscode-site `v1.6.0`.
|
||||
5. **Per church:** install Accounts (`add-product` from the Hub) → Connect → update Events to
|
||||
3.0 (nothing changes for members yet) → tell the church office → **Move** at a quiet time, not
|
||||
the day before a big event's registrations close → watch the first day's sign-ins (Accounts'
|
||||
login events, Events' audit log) → after 14 days the Undo window closes and the old secrets are
|
||||
cleared. **The demo site first, then Hope Family Church**, then the rest.
|
||||
|
||||
## Changes while building
|
||||
|
||||
1. **One request schema for product → Accounts:** `crosscode.identity-request/1` at
|
||||
`POST /api/accounts/v1/requests` carries both `import.*` and `people.*` (contracts 1.8.0), so
|
||||
`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` 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.
|
||||
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.<rest of the domain>` 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.
|
||||
6. **`/login` forwards instead of a new `signInHref` in every link:** every existing
|
||||
`/login?redirect=` link (and `useRequireAuth`, which now passes the current page) goes through it,
|
||||
so the 49 files that link to `/login` didn't change.
|
||||
7. **Events' own sign-in endpoints answer 409 `SIGN_IN_MOVED`** from one guard
|
||||
(`src/accounts/guard.ts`) rather than in each controller. The guard only passes an admin's change
|
||||
of someone's name, email or phone to Accounts for a valid, current admin token with its second step.
|
||||
8. **The `auth-client` loader** uses a real dynamic `import()` (`src/accounts/client.ts`), since the
|
||||
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 (14 tests, including demo people and moving again after Undo). `user.export` and `user.deleted` are Jest tests (`tests/accountsCalls.test.ts`).
|
||||
|
||||
13. **3.1.0 (after the first church moved):** Accounts has its own email and WhatsApp settings,
|
||||
which a move doesn't bring, and it failed with a 500 when a code couldn't be sent, so nobody
|
||||
could sign in. Now the move needs Accounts' email; Settings → Sign-in copies Events' SMTP / WAWP
|
||||
into Accounts (secrets sealed, never on the page), with a test first (`messaging.*`, contracts
|
||||
1.9.0); Accounts 1.2.0 shows a message instead of a 500 and sends WhatsApp codes by email when
|
||||
WhatsApp is down.
|
||||
|
||||
## Decisions
|
||||
|
||||
Confirmed by Joshua on 2026-11-19, all as proposed.
|
||||
|
||||
1. **`User.accountId` instead of rewriting `User.id`** (§2). Every imported person still gets
|
||||
`sub = User.id`; the column handles guests, deleted people and emails already in Accounts
|
||||
without rewriting every foreign key in Events. *Changes the wording of ROADMAP §3 ("keeps its
|
||||
id, now equal to the account sub"), which stays true for every imported person.*
|
||||
2. **Recovery codes are not carried over** (§4). Events stores them as an HMAC keyed with its
|
||||
`JWT_SECRET` (10 characters), and Accounts as a SHA-256 (12 characters), so Accounts can't
|
||||
check an Events code without being given Events' `JWT_SECRET`, which also signs Events' tokens
|
||||
and encrypts its settings. Instead, people with 2FA are shown 10 new recovery codes in
|
||||
Accounts right after their first sign-in (their authenticator itself carries over, so they're
|
||||
never locked out). *Changes ROADMAP §3 ("unused recovery codes" carried over).* The
|
||||
alternative is a legacy-code check that calls Events, which keeps Events in every recovery
|
||||
sign-in forever.
|
||||
3. **The move is an admin action after the update, with 14 days' Undo** (§5), not part of the
|
||||
database migration when 3.0 is deployed. Updating and moving can then be done on different
|
||||
days, a failed move changes nothing, and `crosscode deploy` stays a normal deploy. The cost is
|
||||
that 3.0 carries the local sign-in for one more release (removed in 3.1).
|
||||
4. **Every Events admin becomes an Accounts admin by default** at the move (ticked, can be
|
||||
unticked), so the church office can manage sign-in from day one.
|
||||
5. **Events' privacy notice versions become Accounts' versions**, numbers kept, when Accounts
|
||||
has none of its own; otherwise the move stops and an admin chooses which wins.
|
||||
6. **Events keeps its own session token** (not a new cookie session) and gets it through a
|
||||
one-time handoff after the callback (§3), so the whole API, the scanner and impersonation are
|
||||
untouched. Moving Events' token from `localStorage` to an HttpOnly cookie is worth doing, but
|
||||
separately.
|
||||
7. **Unsubscribe from news turns it off in Accounts** (every product), since consent lives there
|
||||
now (§6).
|
||||
|
||||
## Still open
|
||||
|
||||
- Whether Events reads the church profile from Accounts (name, logo, colours, campuses) instead
|
||||
of its own site settings. Not needed for sign-in; suggested for 3.1 together with the Website
|
||||
plan (ACCOUNTS-1.0-PLAN "Still open").
|
||||
- Session lengths in Accounts (30 days with "Keep me signed in") against Events' current token
|
||||
lifetime: people shouldn't be signed out of Events more often than today.
|
||||
- How Hub stats for Events report 2FA per staff account after the move (from the claims Events
|
||||
saves at sign-in, or only from Accounts).
|
||||
+3
-2
@@ -1,6 +1,6 @@
|
||||
# Handover — Cross Code, all products
|
||||
|
||||
Last updated: 2026-11-18. **The plan is [ROADMAP-v3.md](./ROADMAP-v3.md)** (decided 2026-11-03,
|
||||
Last updated: 2026-11-19. **The plan is [ROADMAP-v3.md](./ROADMAP-v3.md)** (decided 2026-11-03,
|
||||
decisions table near the end). This file says where each phase stands and what comes next.
|
||||
Product-specific notes (where the code lives, known gaps) stay with each product: Cross Events'
|
||||
are in [`apps/events/docs/HANDOVER.md`](../apps/events/docs/HANDOVER.md), and the Hub's are in
|
||||
@@ -32,7 +32,8 @@ every release).
|
||||
| 1d | Agent 1.0.x + Hub 2.1.x (+ contracts 1.3.0) | **Released** 2026-11-17 (`agent@1.0.0`, `contracts@1.3.0`, Hub `v2.1.0`). **VM tested** end to end (AGENT-1.0-PLAN §13: joins, installs behind frp, scheduled / batch / missed updates, uninstall with export and purge, forged and replayed jobs). 2026-11-18: **`agent@1.0.1`** (the agent answers status on the central server itself) and Hub **`v2.1.1`** (adopt passes the church's address; Link takes the short name as a name). **Not rolled out**: use agent 1.0.1 and Hub 2.1.1 |
|
||||
| 2 | Cross Events 2.4.0: protocol v2, Linked products, event feed, `packages/seo` (+ contracts 1.4.0, Hub 2.2.0) | **Released** 2026-11-18 (`events@2.4.0`, `contracts@1.4.0`, Hub `v2.2.0`, crosscode-site `v1.4.0`; [EVENTS-2.4-PLAN.md](./EVENTS-2.4-PLAN.md)). **Before any church gets it:** the Events e2e run on Postgres and the VM test (EVENTS-2.4-PLAN §8) |
|
||||
| 3 | Accounts 1.0.0 (+ contracts 1.5.0, agent 1.1.0, Hub 2.3.0) | **Released** 2026-11-18 (`accounts@1.0.0`, `contracts@1.5.0`, `agent@1.1.0`, Hub `v2.3.0`, crosscode-site `v1.5.0`; [ACCOUNTS-1.0-PLAN.md](./ACCOUNTS-1.0-PLAN.md)). 37 backend and 8 Playwright tests pass without Postgres. **Before installing it for a church:** the VM test and a run on real Postgres; a Hub release source for `accounts@` tags |
|
||||
| 4–7 | Website 1.0.0 → Events 3.0.0 → App 1.0.0 → App 1.x | Not started |
|
||||
| 4 | Cross Events 3.0.0: sign-in through Accounts, users migrated with their password hashes and 2FA | **Released** 2026-11-19 (`events@3.0.0`, `accounts@1.1.0`, `contracts@1.8.0`, Hub `v2.5.0`, crosscode-site `v1.6.0`; [EVENTS-3.0-PLAN.md](./EVENTS-3.0-PLAN.md)). Tested on Postgres 18: both migrations, `test:accounts` on real databases (14/14), the Events e2e suite (111, incl. `sign-in-accounts.spec.ts`). **Not VM tested yet.** Roll out: Hub 2.5.0 deployed first, then per church Accounts 1.1.0 → Events 3.0 → Move (MIGRATING-TO-3.md); crosscode-site 1.6.0 once the first church has moved |
|
||||
| 5–7 | Website 1.0.0 → App 1.0.0 → App 1.x | Not started |
|
||||
|
||||
## Next up
|
||||
|
||||
|
||||
+19
-7
@@ -26,6 +26,9 @@ The Hub can now trigger changes, but no site depends on it to keep running and t
|
||||
polls (it has no URL or open port). Rule 2 (§1), §5, §8 and §9 are updated; decisions 27–37
|
||||
change decisions 10 and 23.
|
||||
|
||||
**Updated 2026-11-19:** phases 4 and 5 swapped: **Cross Events 3.0.0** (sign-in through Accounts)
|
||||
comes before the **Church Website** (§9, decision 38).
|
||||
|
||||
---
|
||||
|
||||
## Contents
|
||||
@@ -180,8 +183,11 @@ touching anyone's account.
|
||||
This is a breaking change, so it's a major version.
|
||||
|
||||
- A migration copies every Events user into Accounts **with their existing password hash**, 2FA
|
||||
setting (including authenticator secrets and unused recovery codes), consent and notice acceptance, so nobody has to reset anything. The Events `User`
|
||||
table keeps its id (now equal to the account `sub`), role, campus scope and product data.
|
||||
setting (including authenticator secrets), consent and notice acceptance, so nobody has to reset anything. Recovery codes
|
||||
can't move (Events keys them with its own secret), so people with 2FA get new ones at their first
|
||||
sign-in through Accounts (EVENTS-3.0-PLAN decision 2). The Events `User` table keeps its id
|
||||
(equal to the account `sub` for everyone moved; a new `accountId` column links guests and
|
||||
existing accounts, decision 1), role, campus scope and product data.
|
||||
- Sign-in, forgot password, 2FA, the news question and the notice re-acceptance move to Accounts.
|
||||
The Events privacy centre links to Accounts for account-level items.
|
||||
- Every place Events sends someone to sign in today (`/login?redirect=…`, `useRequireAuth`, the
|
||||
@@ -617,9 +623,9 @@ Planned in [AGENT-1.0-PLAN.md](./AGENT-1.0-PLAN.md). In short:
|
||||
| 1c | **Cross Events 2.3.0** | **Authenticator app 2FA** (TOTP) next to email and WhatsApp, with recovery codes; admins can see which method each staff account uses. **Released 2026-11-17** (`events@2.3.0`) | Independent and useful now; the Accounts migration later carries it over |
|
||||
| 1d | **Agent 1.0.0 + Hub 2.1.0** (contracts 1.3.0) | **Server agent** on every server (polls only, signed jobs, runs the `crosscode` script); Hub: Servers page with stats and alerts, server configuration, frp port list, New install with a choice of server, scheduled / emergency / batch updates with notice to the church, uninstall with an encrypted JSON export, emailed reports. [AGENT-1.0-PLAN.md](./AGENT-1.0-PLAN.md). **Released 2026-11-17** after the VM test; rollout in [ROLLOUT-1.0.md](./ROLLOUT-1.0.md) | Right after 1b (it runs the `crosscode` script), so every new church from then on is installed from the Hub. Can run alongside 1c |
|
||||
| 2 | **Cross Events 2.4.0** | Reports `product: "events"` (protocol v2), **Linked products**, the event feed (publish + show events from siblings), `packages/seo` (§11) with canonical links for imported events. **Planned and built 2026-11-18:** [EVENTS-2.4-PLAN.md](./EVENTS-2.4-PLAN.md) (also needs contracts 1.4.0 and Hub 2.2.0, for a public key in the v2 heartbeat); not tagged yet | Small; ready for when the Website exists |
|
||||
| 3 | **Accounts 1.0.0** | OIDC provider, sign-in, 2FA (email, WhatsApp, authenticator app), password reset, consent and notice, export / delete fan-out, admin, install script. **Planned 2026-11-18:** [ACCOUNTS-1.0-PLAN.md](./ACCOUNTS-1.0-PLAN.md) (with contracts 1.5.0, `packages/auth-client`, Hub 2.3.0) | The Website is built on it from day one |
|
||||
| 4 | **Church Website 1.0.0** | Public site with the **four templates** (§6), admin, simple events + feed, SEO (§11), Hope Family Church as the first church, then a second test church on a different template to prove it repeats | More churches need a website than an app; it also covers the "website only" case |
|
||||
| 5 | **Cross Events 3.0.0** | Sign-in moves to Accounts; user migration keeping password hashes; migration guide | Breaking change, so a major version, after Accounts is proven on the Website |
|
||||
| 3 | **Accounts 1.0.0** | OIDC provider, sign-in, 2FA (email, WhatsApp, authenticator app), password reset, consent and notice, export / delete fan-out, admin, install script. [ACCOUNTS-1.0-PLAN.md](./ACCOUNTS-1.0-PLAN.md) (with contracts 1.5.0, `packages/auth-client`, Hub 2.3.0). **Released 2026-11-18** (`accounts@1.0.0`, 1.0.1 on 2026-11-19); the VM test and a run on real Postgres are still to do before a church gets it | Every later product signs in through it |
|
||||
| 4 | **Cross Events 3.0.0** | Sign-in moves to Accounts; user migration keeping password hashes; migration guide. **Planned 2026-11-19:** [EVENTS-3.0-PLAN.md](./EVENTS-3.0-PLAN.md) (with contracts 1.8.0, Accounts 1.1.0, Hub 2.5.0; decisions confirmed 2026-11-19) | Breaking change, so a major version. **Moved before the Website on 2026-11-19** (decision 38): Events is the product churches use today, so Accounts is proven on real users first, and the Website then starts with a church whose people already have accounts |
|
||||
| 5 | **Church Website 1.0.0** | Public site with the **four templates** (§6), admin, simple events + feed, SEO (§11), Hope Family Church as the first church, then a second test church on a different template to prove it repeats | More churches need a website than an app; it also covers the "website only" case. Built on Accounts from day one |
|
||||
| 6 | **Church App 1.0.0** | Foundation (PWA, branding, Accounts), House of Prayer, announcements, devotionals, events (simple + feed) | Starts with shared users and the feed already in place |
|
||||
| 7 | Church App 1.x | Reading plans, sermons, groups, pastoral care, serving, giving links, directory | After House of Prayer is in use |
|
||||
|
||||
@@ -641,8 +647,8 @@ At the end of each phase, update it in the same sitting and deploy it (its `DEPL
|
||||
| 1d Agent 1.0.0 + Hub 2.1.0 | Nothing (it changes how installs are run, not what churches buy) |
|
||||
| 2 Events 2.4.0 | "Works with the Church Website and App" (event feed, Linked products) on the Cross Events page, as "coming" until those ship |
|
||||
| 3 Accounts 1.0.0 | "One sign-in for all your church's products" on the Products page. Accounts isn't sold, so no page or price of its own |
|
||||
| 4 Website 1.0.0 | **Church Website goes on sale:** `status: "available"` and its own page in `src/data/products.mjs` / `src/pages/products/`, R99 + storage add-on in `pricing.mjs`, **a showcase of the four templates** (a page per template with screenshots of the same demo church in each), screenshots from a demo church (fictional people only), FAQ, home page, contact form product list, `SoftwareApplication` JSON-LD (§11) |
|
||||
| 5 Events 3.0.0 | Cross Events page: sign-in through the church's shared account. Update screenshots that show the login |
|
||||
| 4 Events 3.0.0 | Cross Events page: sign-in through the church's shared account. Update screenshots that show the login |
|
||||
| 5 Website 1.0.0 | **Church Website goes on sale:** `status: "available"` and its own page in `src/data/products.mjs` / `src/pages/products/`, R99 + storage add-on in `pricing.mjs`, **a showcase of the four templates** (a page per template with screenshots of the same demo church in each), screenshots from a demo church (fictional people only), FAQ, home page, contact form product list, `SoftwareApplication` JSON-LD (§11) |
|
||||
| 6 App 1.0.0 | **Church App goes on sale:** own page, active-member tiers in `pricing.mjs`, House of Prayer screenshots, the bundle examples from §10 |
|
||||
| 7 App 1.x | New modules added to the App page's feature list as each one ships |
|
||||
|
||||
@@ -846,6 +852,12 @@ ranking.
|
||||
| 36 | `.env` configuration | **Database and other server values are set once per server in the Hub**, stored encrypted and sent encrypted to that server's agent with each job. `.env` files come from a per-product template; updates only append new variables; secrets are generated on the server and never leave it |
|
||||
| 37 | Server stats | Every agent reports RAM, CPU, disk and PM2 processes every minute; the Hub keeps minutes for 7 days and hours for 90 days, shows spikes, and emails alerts |
|
||||
|
||||
**Added 2026-11-19**
|
||||
|
||||
| # | Question | Decision |
|
||||
|---|----------|----------|
|
||||
| 38 | Order after Accounts | **Cross Events 3.0.0 (sign-in through Accounts) is phase 4, the Church Website phase 5** (swapped). Events is what churches use today, so Accounts is proven on real users and their migrated passwords and 2FA first; the Website then starts with a church whose people already have accounts |
|
||||
|
||||
## Still open
|
||||
|
||||
Nothing. crosscode-site is updated at the end of each phase (§9, "Updating crosscode-site"); the
|
||||
|
||||
+32
-7
@@ -10,12 +10,12 @@ separately below; the two often differ.
|
||||
|
||||
| What | Repo | Latest | Tag | Released |
|
||||
|------|------|--------|-----|----------|
|
||||
| Cross Events | `crosscode-platform` (`apps/events`) | **2.4.1** | `events@2.4.1` | 2026-11-19 |
|
||||
| Accounts | `crosscode-platform` (`apps/accounts`) | **1.0.1** | `accounts@1.0.1` | 2026-11-19 |
|
||||
| Cross Events | `crosscode-platform` (`apps/events`) | **3.1.0** | `events@3.1.0` | 2026-11-19 |
|
||||
| Accounts | `crosscode-platform` (`apps/accounts`) | **1.2.0** | `accounts@1.2.0` | 2026-11-19 |
|
||||
| Server agent | `crosscode-platform` (`apps/agent`) | **1.2.0** | `agent@1.2.0` | 2026-11-19 |
|
||||
| Contracts | `crosscode-platform` (`packages/contracts`) | **1.7.0** | `contracts@1.7.0` | 2026-11-19 |
|
||||
| Cross Code Hub | `events-hub` | **2.4.0** | `v2.4.0` | 2026-11-19 |
|
||||
| crosscode.co.za | `crosscode-site` | **1.5.0** | `v1.5.0` | 2026-11-18 |
|
||||
| Contracts | `crosscode-platform` (`packages/contracts`) | **1.9.0** | `contracts@1.9.0` | 2026-11-19 |
|
||||
| Cross Code Hub | `events-hub` | **2.6.0** | `v2.6.0` | 2026-11-19 |
|
||||
| crosscode.co.za | `crosscode-site` | **1.6.0** | `v1.6.0` | 2026-11-19 |
|
||||
| `crosscode` script | `crosscode-platform` (`scripts/`) | `main` | none | 2026-11-19 (last change) |
|
||||
|
||||
The `crosscode` script has no version: every server's copy (`/opt/crosscode/tools`) pulls `main`
|
||||
@@ -26,10 +26,10 @@ on each run, so merging to `main` and pushing releases it. Its changes are liste
|
||||
|
||||
| What | Where | Version in package.json |
|
||||
|------|-------|-------------------------|
|
||||
| `@crosscode/auth-client` | `packages/auth-client` | 1.0.0 (released with Accounts 1.0.0) |
|
||||
| `@crosscode/auth-client` | `packages/auth-client` | 1.1.0 (released with Events 3.0.0 and Accounts 1.1.0) |
|
||||
| `@crosscode/seo` | `packages/seo` | 1.0.0 (released with Events 2.4.0) |
|
||||
| `@crosscode/ui` | `packages/ui` | 0.1.0 |
|
||||
| Website | `apps/website` | 0.0.0 (not started, phase 4) |
|
||||
| Website | `apps/website` | 0.0.0 (not started, phase 5) |
|
||||
| App | `apps/app` | 0.0.0 (not started, phase 6) |
|
||||
|
||||
These shared packages ship inside the apps that use them, from the same checkout, so they don't
|
||||
@@ -37,6 +37,31 @@ need their own tags until something outside this repo depends on them.
|
||||
|
||||
## What each latest release was for
|
||||
|
||||
- **Events 3.1.0 + Accounts 1.2.0 + contracts 1.9.0:** the move to Accounts needs Accounts' email
|
||||
(Settings → Sign-in sets it up by copying Events' SMTP / WAWP, tests, then saves); Accounts shows a
|
||||
message instead of a 500 when a code can't be sent. **Use these instead of 3.0.0 / 1.1.0.**
|
||||
|
||||
- **Hub 2.6.0:** paged lists (jobs, audit log and alerts on the server), job filters for every
|
||||
status, updates for one product at a time with that product's releases, an Events update that
|
||||
keeps (or updates, or first installs) the church's Accounts explicitly, and installs found on a
|
||||
server tied to their registration. No migration. **Deploy it** (after 2.5.0, or straight to it).
|
||||
- **`crosscode` script (2026-11-19, later):** Accounts' own `ecosystem.config.cjs` no longer stops
|
||||
a deploy as "changed by hand".
|
||||
|
||||
- **Events 3.0.0** (phase 4, [EVENTS-3.0-PLAN.md](./EVENTS-3.0-PLAN.md)): sign-in through the
|
||||
church's Accounts. Needs Accounts 1.1.0 (`requires accounts 1.1.0`). Nothing changes for a
|
||||
church until an admin moves sign-in (Settings → Sign-in); see `apps/events/MIGRATING-TO-3.md`.
|
||||
Tested on Postgres 18 (migrations, `test:accounts` on real databases, the e2e suite); **not VM
|
||||
tested**.
|
||||
- **Accounts 1.1.0:** takes Events' users with their passwords and authenticator apps, and Events'
|
||||
`people.*` requests. **Contracts 1.8.0:** `crosscode.identity-request/1`.
|
||||
- **Hub 2.5.0:** a New install of Events 3.x installs the church's Accounts first. **Deploy it before
|
||||
any church gets Events 3.0** (it has the vendored contracts 1.8.0; no migration).
|
||||
- **crosscode.co.za 1.6.0:** Cross Events signs in with the church account. Tagged; deploy it when
|
||||
the first church is on Events 3.0.
|
||||
|
||||
Earlier:
|
||||
|
||||
- **Events 2.4.1:** the default logo is the Cross Code logo; the demo script says to run as the
|
||||
site's user (instead of "client password must be a string") and keeps the site's oldest admin.
|
||||
2.4.0: protocol v2, Linked products, the event feed, `packages/seo`
|
||||
|
||||
@@ -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": []
|
||||
}
|
||||
Generated
+7
-6
@@ -46,7 +46,7 @@
|
||||
},
|
||||
"apps/accounts/backend": {
|
||||
"name": "@crosscode/accounts-backend",
|
||||
"version": "1.0.1",
|
||||
"version": "1.2.0",
|
||||
"hasInstallScript": true,
|
||||
"dependencies": {
|
||||
"@crosscode/contracts": "*",
|
||||
@@ -82,7 +82,7 @@
|
||||
},
|
||||
"apps/accounts/frontend": {
|
||||
"name": "@crosscode/accounts-frontend",
|
||||
"version": "1.0.1",
|
||||
"version": "1.2.0",
|
||||
"dependencies": {
|
||||
"@crosscode/contracts": "*",
|
||||
"@crosscode/ui": "*",
|
||||
@@ -127,10 +127,11 @@
|
||||
},
|
||||
"apps/events/backend": {
|
||||
"name": "@crosscode/events-backend",
|
||||
"version": "2.4.1",
|
||||
"version": "3.1.0",
|
||||
"hasInstallScript": true,
|
||||
"dependencies": {
|
||||
"@cj-tech-master/excelts": "^10.2.0",
|
||||
"@crosscode/auth-client": "*",
|
||||
"@crosscode/contracts": "*",
|
||||
"@node-rs/argon2": "^2.2.2",
|
||||
"@prisma/adapter-pg": "^7.10.1",
|
||||
@@ -176,7 +177,7 @@
|
||||
},
|
||||
"apps/events/frontend": {
|
||||
"name": "@crosscode/events-frontend",
|
||||
"version": "2.4.1",
|
||||
"version": "3.1.0",
|
||||
"dependencies": {
|
||||
"@crosscode/contracts": "*",
|
||||
"@crosscode/seo": "*",
|
||||
@@ -21266,7 +21267,7 @@
|
||||
},
|
||||
"packages/auth-client": {
|
||||
"name": "@crosscode/auth-client",
|
||||
"version": "1.0.0",
|
||||
"version": "1.1.0",
|
||||
"dependencies": {
|
||||
"@crosscode/contracts": "*",
|
||||
"openid-client": "6.8.9"
|
||||
@@ -21274,7 +21275,7 @@
|
||||
},
|
||||
"packages/contracts": {
|
||||
"name": "@crosscode/contracts",
|
||||
"version": "1.7.0",
|
||||
"version": "1.9.0",
|
||||
"license": "UNLICENSED",
|
||||
"dependencies": {
|
||||
"zod": "^4.6.7"
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "@crosscode/auth-client",
|
||||
"version": "1.0.0",
|
||||
"version": "1.1.0",
|
||||
"private": true,
|
||||
"description": "The product side of signing in through the church's Accounts (docs/ACCOUNTS-1.0-PLAN.md §5): start a sign-in with the return path, finish it, back-channel logout and Accounts' signed calls",
|
||||
"type": "module",
|
||||
|
||||
@@ -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<R, 'schema' | 'requestId'> & { 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<T = Record<string, unknown>>(input: RequestInput, opts: { timeoutMs?: number } = {}): Promise<T> {
|
||||
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<string, unknown> & { 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<string, string | string[] | undefined>): AccountsCall {
|
||||
const get = (n: string) => {
|
||||
|
||||
@@ -10,6 +10,7 @@ Events and the Hub, uses it, so the key fields are the same in every product's J
|
||||
| Event feed | `crosscode.event-feed/1` | `GET /api/feed/v1/events?updatedSince=` and the `event.changed` webhook | `src/event.ts` |
|
||||
| Church | `crosscode.church/1` | The church profile: name, branding, campuses, service times, contact details, product links | `src/church.ts` |
|
||||
| Identity | `crosscode.identity/1` | Accounts' sign-in claims and back-channel calls (`user.updated`, `user.deleted`, `user.export`) and their replies | `src/identity.ts` |
|
||||
| Identity requests | `crosscode.identity-request/1` | From 1.8.0: what a product asks of its Accounts at `POST /api/accounts/v1/requests`: moving its users in (`import.begin` / `batch` / `finish` / `abort`, secrets sealed with `sealLinkValue`) and `people.*` (ensure, update, reset 2FA, unlock, set active, news off); from 1.9.0 `messaging.*` (status, test, set Accounts' email and WhatsApp) | `src/identity-request.ts` |
|
||||
| Sign-in return | — | The return-path check and OIDC `state` every product uses (ROADMAP-v3 §3) | `src/return-to.ts` |
|
||||
| Product link | `crosscode.link/1` | **Connect** under Settings → Linked products: the signed handshake that sets up a link's secret (`link.connect`, `link.connected`, `link.disconnect`) | `src/link.ts` |
|
||||
| Hub protocol v2 | `protocolVersion: 2` | Register, heartbeat (stats per product), linked products, update requests, AI, licence token | `src/hub.ts` (exported as `hub`) |
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "@crosscode/contracts",
|
||||
"version": "1.7.0",
|
||||
"version": "1.9.0",
|
||||
"description": "The shared JSON formats used by every Cross Code product: zod schemas, JSON Schema, TypeScript types and sample payloads",
|
||||
"license": "UNLICENSED",
|
||||
"type": "commonjs",
|
||||
|
||||
@@ -0,0 +1,11 @@
|
||||
{
|
||||
"schema": "crosscode.identity-request/1",
|
||||
"results": [
|
||||
{
|
||||
"id": "5f0c7d2a-3b1e-4c8f-9a6d-2e4b1c7f8a90",
|
||||
"outcome": "created",
|
||||
"sub": "5f0c7d2a-3b1e-4c8f-9a6d-2e4b1c7f8a90",
|
||||
"reason": null
|
||||
}
|
||||
]
|
||||
}
|
||||
@@ -0,0 +1,49 @@
|
||||
{
|
||||
"schema": "crosscode.identity-request/1",
|
||||
"actor": "8d2e4f6a-1b3c-4d5e-8f7a-9b0c1d2e3f4a",
|
||||
"requestId": "1c7f2a3b-4d5e-4f6a-9b0c-1d2e3f4a5b6c",
|
||||
"type": "import.batch",
|
||||
"check": false,
|
||||
"people": [
|
||||
{
|
||||
"id": "5f0c7d2a-3b1e-4c8f-9a6d-2e4b1c7f8a90",
|
||||
"name": "Thandi Mokoena",
|
||||
"email": "thandi@hopefamily.co.za",
|
||||
"emailVerified": true,
|
||||
"phone": "+27821234567",
|
||||
"passwordHash": "sealed1.AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA",
|
||||
"twoFactor": "totp",
|
||||
"totpSecret": "sealed1.AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA",
|
||||
"totpLastStep": 59012345,
|
||||
"failedSignIns": 0,
|
||||
"lockedUntil": null,
|
||||
"news": {
|
||||
"email": true,
|
||||
"whatsapp": false
|
||||
},
|
||||
"newsAskedAt": "2026-03-01T08:00:00.000Z",
|
||||
"noticeVersionAccepted": 2,
|
||||
"noticeAcceptances": [
|
||||
{
|
||||
"version": 1,
|
||||
"acceptedAt": "2025-06-01T08:00:00.000Z"
|
||||
},
|
||||
{
|
||||
"version": 2,
|
||||
"acceptedAt": "2026-03-01T08:00:00.000Z"
|
||||
}
|
||||
],
|
||||
"consentChanges": [
|
||||
{
|
||||
"channel": "email",
|
||||
"granted": true,
|
||||
"at": "2026-03-01T08:00:00.000Z"
|
||||
}
|
||||
],
|
||||
"lastSignInAt": "2026-11-18T17:30:00.000Z",
|
||||
"status": "active",
|
||||
"admin": true,
|
||||
"createdAt": "2025-06-01T08:00:00.000Z"
|
||||
}
|
||||
]
|
||||
}
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user