Compare commits
15
Commits
contracts@1.4.0
...
main
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
06222fd94a | ||
|
|
43189c599a | ||
|
|
2aab5918f7 | ||
|
|
21c60ac99e | ||
|
|
1318ba38bd | ||
|
|
fdd53ae4db | ||
|
|
e1c6a4cce1 | ||
|
|
7f34e184e1 | ||
|
|
a3e3921b4f | ||
|
|
f202a5a88e | ||
|
|
a888260f01 | ||
|
|
069b66fd30 | ||
|
|
45c6539bf1 | ||
|
|
6c284099ef | ||
|
|
6bdabeb871 |
+30
-2
@@ -2,10 +2,38 @@
|
|||||||
|
|
||||||
Each package and app has its own section and its own tags (`contracts@1.0.0`, `accounts@1.0.0`, …).
|
Each package and app has its own section and its own tags (`contracts@1.0.0`, `accounts@1.0.0`, …).
|
||||||
|
|
||||||
## events@2.4.0, contracts@1.4.0 - unreleased
|
## agent@1.1.1 - 2026-11-18
|
||||||
|
|
||||||
|
- **Stats keep going while a job runs.** The agent sent stats and polled in one loop, so during
|
||||||
|
a job (an install or update can take 30 minutes) the Hub heard nothing and alerted, by email,
|
||||||
|
that the server was down. Stats now go every minute on their own timer, job or not (Hub 2.3.1
|
||||||
|
also treats a server running a job as busy, for agents not updated yet).
|
||||||
|
- The agent reports its real version: 1.1.0 still said 1.0.1 (a test now keeps it equal to
|
||||||
|
package.json).
|
||||||
|
|
||||||
|
## accounts@1.0.0, contracts@1.5.0, agent@1.1.0 - 2026-11-18
|
||||||
|
|
||||||
|
Phase 3 (docs/ACCOUNTS-1.0-PLAN.md). Released before the VM test and a run on real Postgres (both still to do).
|
||||||
|
|
||||||
|
- **Accounts 1.0.0** (`apps/accounts`): the church's OpenID Connect provider, sign-in pages,
|
||||||
|
account page and admin. Details in `apps/accounts/CHANGELOG.md`.
|
||||||
|
- **Contracts 1.5.0:** `OIDC_CLIENT_PATHS` / `oidcClientAddresses`, `oidcClientSecret` (derived from
|
||||||
|
a link secret), `ACCOUNTS_CALL_PATH`, `OIDC_SCOPES`, `ACR_MFA`, `CHURCH_PATHS`,
|
||||||
|
`churchChangedSchema`, `churchObjectSchema`.
|
||||||
|
- **`packages/auth-client`** (new): the product side of signing in. **`packages/ui`**: first
|
||||||
|
components.
|
||||||
|
- **Scripts:** `products/accounts.sh`; `accounts` in `SUPPORTED_PRODUCTS`; `crosscode install
|
||||||
|
--products accounts` (one product per install) and `crosscode add <church> <product>`.
|
||||||
|
|
||||||
|
### Agent (1.1.0)
|
||||||
|
|
||||||
|
- Install jobs for Accounts, and `add-product` jobs (a product next to a church's others).
|
||||||
|
|
||||||
|
## events@2.4.0, contracts@1.4.0 - 2026-11-18
|
||||||
|
|
||||||
Phase 2 (docs/EVENTS-2.4-PLAN.md): protocol v2, Linked products, the event feed and
|
Phase 2 (docs/EVENTS-2.4-PLAN.md): protocol v2, Linked products, the event feed and
|
||||||
`packages/seo`. With Hub 2.2.0 (events-hub). Not tagged yet: the e2e run and the VM test come first.
|
`packages/seo`. With Hub 2.2.0 (events-hub). Released before the e2e run on Postgres and the VM test; do both
|
||||||
|
before updating a church.
|
||||||
|
|
||||||
### Events (2.4.0)
|
### Events (2.4.0)
|
||||||
|
|
||||||
|
|||||||
@@ -0,0 +1,27 @@
|
|||||||
|
# Changelog — Accounts
|
||||||
|
|
||||||
|
## [1.0.0] - 2026-11-18
|
||||||
|
|
||||||
|
The first release (docs/ACCOUNTS-1.0-PLAN.md), with Hub 2.3.0 and agent 1.1.0. Released before the
|
||||||
|
VM test and a run on real Postgres; do both before installing it for a church.
|
||||||
|
|
||||||
|
### Added
|
||||||
|
|
||||||
|
- OpenID Connect provider (oidc-provider 9.13.3): authorization code with PKCE (S256) required,
|
||||||
|
ES256 keys made on first start, `crosscode.identity/1` claims in the ID token, no refresh tokens,
|
||||||
|
RP-initiated logout and OIDC Back-Channel Logout. Clients are the linked products (Connect,
|
||||||
|
`crosscode.link/1`), with exact redirect addresses and the client secret derived from the link.
|
||||||
|
- Sign-in steps that all return to the product and page they started from: password, sign-up with
|
||||||
|
an emailed code, two-step sign-in (authenticator app, email, WhatsApp, recovery codes) and setting
|
||||||
|
it up when a product asks (`acr_values=mfa`) or for admins, privacy notice (asked again when a new
|
||||||
|
version is published), news question, forgot / reset password.
|
||||||
|
- The account page: details, email change by link, password, two-step sign-in, recovery codes,
|
||||||
|
news consent, recent activity, sign out everywhere, download my data (bundled from every linked
|
||||||
|
product), delete my account (approved by an admin, then every product, retried when a product
|
||||||
|
says "not yet").
|
||||||
|
- Admin: people (access-logged), deletion requests, the church profile (`crosscode.church/1`,
|
||||||
|
served at `/api/church/v1`, `church.changed` to products), linked products, sign-in settings,
|
||||||
|
email and WhatsApp, privacy notice versions, licence, audit log. First-run `/setup`.
|
||||||
|
- Hub protocol v2 (product `accounts`, `CCA-` licence; never read-only), registering by itself from
|
||||||
|
`HUB_LICENCE_KEY`.
|
||||||
|
- `crosscode` hooks (`scripts/products/accounts.sh`), `env.template.json`, PM2 example.
|
||||||
+20
-1
@@ -1,3 +1,22 @@
|
|||||||
# Accounts
|
# Accounts
|
||||||
|
|
||||||
Placeholder: the per-church sign-in (OpenID Connect). Built in phase 3 of ROADMAP-v3 (see §3 there).
|
The church's sign-in for every Cross Code product (ROADMAP-v3 §3, phase 3; plan and decisions in
|
||||||
|
[docs/ACCOUNTS-1.0-PLAN.md](../../docs/ACCOUNTS-1.0-PLAN.md)). A small OpenID Connect provider per
|
||||||
|
church at `accounts.<address>`: people sign in once and are signed in to all the church's products,
|
||||||
|
coming back to the page they started on. Members never see it as a product; admins manage people,
|
||||||
|
sign-in settings, linked products and the church profile here.
|
||||||
|
|
||||||
|
- `backend/`: Express + oidc-provider 9 + Prisma (ES modules). `npm run dev`, `npm test` (Node's test
|
||||||
|
runner through tsx: the whole app against an in-memory database, with a test product on
|
||||||
|
openid-client), `npm run build`.
|
||||||
|
- `frontend/`: Next.js 16 pages (sign-in steps, account page, admin, setup), strict CSP with a nonce
|
||||||
|
per page, the church's colours from its profile.
|
||||||
|
- `e2e/`: Playwright on the real pages (`npx playwright test` in `apps/accounts`): the backend on an
|
||||||
|
in-memory database with a test product (`e2e/server.ts`), Next on 3210. No database needed.
|
||||||
|
- Roles stay in each product: Accounts only knows who someone is (plan §2, "Roles stay in each
|
||||||
|
product").
|
||||||
|
- Products sign in with `@crosscode/auth-client` (packages/auth-client).
|
||||||
|
|
||||||
|
Local development: Postgres in `backend/.env` (`DATABASE_URL`, `ACCOUNTS_URL=http://localhost:3200`,
|
||||||
|
`LINKS_ALLOW_PRIVATE=true`), `npx prisma migrate deploy`, then `npm run dev` in both folders (the
|
||||||
|
frontend runs on 3200 with `next dev -p 3200` and sends /api to the backend on 5200).
|
||||||
|
|||||||
@@ -0,0 +1,14 @@
|
|||||||
|
# What's new in Accounts
|
||||||
|
|
||||||
|
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.0.0
|
||||||
|
|
||||||
|
- **One sign-in for all your church's sites and apps.** People sign in once with their own account
|
||||||
|
and are signed in to the church website, the app and Cross Events, and come back to the page they
|
||||||
|
were on.
|
||||||
|
- **Secure by default:** two-step sign-in with an authenticator app, email or WhatsApp, recovery
|
||||||
|
codes, and required for admins.
|
||||||
|
- **People control their own information:** they change their details, choose their news, download
|
||||||
|
their data or ask for their account to be deleted, all in one place.
|
||||||
@@ -0,0 +1,6 @@
|
|||||||
|
node_modules/
|
||||||
|
dist/
|
||||||
|
src/generated/
|
||||||
|
.env
|
||||||
|
uploads/
|
||||||
|
exports/
|
||||||
@@ -0,0 +1,50 @@
|
|||||||
|
{
|
||||||
|
"name": "@crosscode/accounts-backend",
|
||||||
|
"version": "1.0.0",
|
||||||
|
"description": "Cross Code Accounts: the church's sign-in (OpenID Connect provider), account pages API and admin API",
|
||||||
|
"private": true,
|
||||||
|
"type": "module",
|
||||||
|
"main": "dist/index.js",
|
||||||
|
"scripts": {
|
||||||
|
"start": "node dist/index.js",
|
||||||
|
"dev": "tsx watch src/index.ts",
|
||||||
|
"build": "tsc -p tsconfig.build.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",
|
||||||
|
"test": "node --import tsx --test --test-reporter=spec \"tests/**/*.test.ts\"",
|
||||||
|
"postinstall": "prisma generate",
|
||||||
|
"prisma:generate": "prisma generate",
|
||||||
|
"prisma:deploy": "prisma migrate deploy && prisma generate",
|
||||||
|
"prisma:status": "prisma migrate status"
|
||||||
|
},
|
||||||
|
"dependencies": {
|
||||||
|
"@crosscode/contracts": "*",
|
||||||
|
"@node-rs/argon2": "^2.2.2",
|
||||||
|
"@prisma/adapter-pg": "^7.10.1",
|
||||||
|
"@prisma/client": "^7.10.1",
|
||||||
|
"bcryptjs": "^2.4.3",
|
||||||
|
"dotenv": "^16.3.1",
|
||||||
|
"express": "^5.3.0",
|
||||||
|
"express-rate-limit": "^8.6.2",
|
||||||
|
"nodemailer": "^10.3.0",
|
||||||
|
"oidc-provider": "9.13.3",
|
||||||
|
"pg-boss": "^11.1.2",
|
||||||
|
"zod": "^4.6.7"
|
||||||
|
},
|
||||||
|
"devDependencies": {
|
||||||
|
"@crosscode/auth-client": "*",
|
||||||
|
"@types/bcryptjs": "^2.4.6",
|
||||||
|
"@types/express": "^5.0.6",
|
||||||
|
"@types/node": "^20.19.43",
|
||||||
|
"@types/nodemailer": "^6.4.17",
|
||||||
|
"@types/oidc-provider": "^9.13.1",
|
||||||
|
"@types/supertest": "^7.2.1",
|
||||||
|
"openid-client": "6.8.9",
|
||||||
|
"prisma": "^7.10.1",
|
||||||
|
"supertest": "^7.3.1",
|
||||||
|
"tsx": "^4.23.15",
|
||||||
|
"typescript": "^5.9.3"
|
||||||
|
},
|
||||||
|
"engines": {
|
||||||
|
"node": ">=22"
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,10 @@
|
|||||||
|
// Prisma CLI config (migrate, generate). Prisma 7 doesn't load .env or read the URL from the schema.
|
||||||
|
import 'dotenv/config';
|
||||||
|
import { defineConfig } from 'prisma/config';
|
||||||
|
|
||||||
|
export default defineConfig({
|
||||||
|
schema: 'prisma/schema.prisma',
|
||||||
|
migrations: { path: 'prisma/migrations' },
|
||||||
|
// process.env, so `prisma generate` works on a machine with no DATABASE_URL (it never connects).
|
||||||
|
datasource: { url: process.env.DATABASE_URL ?? '' },
|
||||||
|
});
|
||||||
@@ -0,0 +1,342 @@
|
|||||||
|
-- Accounts 1.0.0: the first schema (docs/ACCOUNTS-1.0-PLAN.md §2).
|
||||||
|
|
||||||
|
-- CreateEnum
|
||||||
|
CREATE TYPE "AccountRole" AS ENUM ('member', 'admin');
|
||||||
|
|
||||||
|
-- CreateEnum
|
||||||
|
CREATE TYPE "AccountStatus" AS ENUM ('active', 'deactivated', 'deleted');
|
||||||
|
|
||||||
|
-- CreateEnum
|
||||||
|
CREATE TYPE "TwoFactorMethod" AS ENUM ('email', 'whatsapp', 'totp');
|
||||||
|
|
||||||
|
-- CreateTable
|
||||||
|
CREATE TABLE "Account" (
|
||||||
|
"id" TEXT NOT NULL,
|
||||||
|
"name" TEXT NOT NULL,
|
||||||
|
"givenName" TEXT,
|
||||||
|
"familyName" TEXT,
|
||||||
|
"email" TEXT NOT NULL,
|
||||||
|
"emailVerified" BOOLEAN NOT NULL DEFAULT false,
|
||||||
|
"phone" TEXT,
|
||||||
|
"phoneVerified" BOOLEAN NOT NULL DEFAULT false,
|
||||||
|
"passwordHash" TEXT,
|
||||||
|
"role" "AccountRole" NOT NULL DEFAULT 'member',
|
||||||
|
"status" "AccountStatus" NOT NULL DEFAULT 'active',
|
||||||
|
"twoFactorMethod" "TwoFactorMethod",
|
||||||
|
"totpSecret" TEXT,
|
||||||
|
"totpLastStep" INTEGER,
|
||||||
|
"newsEmail" BOOLEAN NOT NULL DEFAULT false,
|
||||||
|
"newsWhatsApp" BOOLEAN NOT NULL DEFAULT false,
|
||||||
|
"newsAskedAt" TIMESTAMP(3),
|
||||||
|
"noticeVersionAccepted" INTEGER NOT NULL DEFAULT 0,
|
||||||
|
"failedSignIns" INTEGER NOT NULL DEFAULT 0,
|
||||||
|
"lockedUntil" TIMESTAMP(3),
|
||||||
|
"lastSignInAt" TIMESTAMP(3),
|
||||||
|
"deactivatedAt" TIMESTAMP(3),
|
||||||
|
"anonymisedAt" TIMESTAMP(3),
|
||||||
|
"createdAt" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
|
||||||
|
"updatedAt" TIMESTAMP(3) NOT NULL,
|
||||||
|
|
||||||
|
CONSTRAINT "Account_pkey" PRIMARY KEY ("id")
|
||||||
|
);
|
||||||
|
|
||||||
|
-- CreateTable
|
||||||
|
CREATE TABLE "RecoveryCode" (
|
||||||
|
"id" TEXT NOT NULL,
|
||||||
|
"accountId" TEXT NOT NULL,
|
||||||
|
"codeHash" TEXT NOT NULL,
|
||||||
|
"usedAt" TIMESTAMP(3),
|
||||||
|
"createdAt" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
|
||||||
|
|
||||||
|
CONSTRAINT "RecoveryCode_pkey" PRIMARY KEY ("id")
|
||||||
|
);
|
||||||
|
|
||||||
|
-- CreateTable
|
||||||
|
CREATE TABLE "PendingSignIn" (
|
||||||
|
"uid" TEXT NOT NULL,
|
||||||
|
"accountId" TEXT,
|
||||||
|
"stage" TEXT NOT NULL,
|
||||||
|
"codeHash" TEXT,
|
||||||
|
"codeSentAt" TIMESTAMP(3),
|
||||||
|
"attempts" INTEGER NOT NULL DEFAULT 0,
|
||||||
|
"amr" TEXT[],
|
||||||
|
"pendingTotpSecret" TEXT,
|
||||||
|
"remember" BOOLEAN NOT NULL DEFAULT false,
|
||||||
|
"expiresAt" TIMESTAMP(3) NOT NULL,
|
||||||
|
"createdAt" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
|
||||||
|
|
||||||
|
CONSTRAINT "PendingSignIn_pkey" PRIMARY KEY ("uid")
|
||||||
|
);
|
||||||
|
|
||||||
|
-- CreateTable
|
||||||
|
CREATE TABLE "EmailToken" (
|
||||||
|
"id" TEXT NOT NULL,
|
||||||
|
"accountId" TEXT NOT NULL,
|
||||||
|
"purpose" TEXT NOT NULL,
|
||||||
|
"tokenHash" TEXT NOT NULL,
|
||||||
|
"interactionUid" TEXT,
|
||||||
|
"expiresAt" TIMESTAMP(3) NOT NULL,
|
||||||
|
"usedAt" TIMESTAMP(3),
|
||||||
|
"createdAt" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
|
||||||
|
|
||||||
|
CONSTRAINT "EmailToken_pkey" PRIMARY KEY ("id")
|
||||||
|
);
|
||||||
|
|
||||||
|
-- CreateTable
|
||||||
|
CREATE TABLE "LoginEvent" (
|
||||||
|
"id" TEXT NOT NULL,
|
||||||
|
"accountId" TEXT,
|
||||||
|
"type" TEXT NOT NULL,
|
||||||
|
"clientId" TEXT,
|
||||||
|
"ip" TEXT,
|
||||||
|
"userAgent" TEXT,
|
||||||
|
"detail" JSONB,
|
||||||
|
"createdAt" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
|
||||||
|
|
||||||
|
CONSTRAINT "LoginEvent_pkey" PRIMARY KEY ("id")
|
||||||
|
);
|
||||||
|
|
||||||
|
-- CreateTable
|
||||||
|
CREATE TABLE "PrivacyNotice" (
|
||||||
|
"version" INTEGER NOT NULL,
|
||||||
|
"title" TEXT NOT NULL,
|
||||||
|
"body" TEXT NOT NULL,
|
||||||
|
"publishedAt" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
|
||||||
|
"publishedById" TEXT,
|
||||||
|
|
||||||
|
CONSTRAINT "PrivacyNotice_pkey" PRIMARY KEY ("version")
|
||||||
|
);
|
||||||
|
|
||||||
|
-- CreateTable
|
||||||
|
CREATE TABLE "NoticeAcceptance" (
|
||||||
|
"id" TEXT NOT NULL,
|
||||||
|
"accountId" TEXT NOT NULL,
|
||||||
|
"version" INTEGER NOT NULL,
|
||||||
|
"acceptedAt" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
|
||||||
|
|
||||||
|
CONSTRAINT "NoticeAcceptance_pkey" PRIMARY KEY ("id")
|
||||||
|
);
|
||||||
|
|
||||||
|
-- CreateTable
|
||||||
|
CREATE TABLE "ConsentChange" (
|
||||||
|
"id" TEXT NOT NULL,
|
||||||
|
"accountId" TEXT NOT NULL,
|
||||||
|
"channel" TEXT NOT NULL,
|
||||||
|
"granted" BOOLEAN NOT NULL,
|
||||||
|
"source" TEXT NOT NULL,
|
||||||
|
"createdAt" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
|
||||||
|
|
||||||
|
CONSTRAINT "ConsentChange_pkey" PRIMARY KEY ("id")
|
||||||
|
);
|
||||||
|
|
||||||
|
-- CreateTable
|
||||||
|
CREATE TABLE "AccessLog" (
|
||||||
|
"id" TEXT NOT NULL,
|
||||||
|
"actorId" TEXT NOT NULL,
|
||||||
|
"targetId" TEXT NOT NULL,
|
||||||
|
"action" TEXT NOT NULL,
|
||||||
|
"ip" TEXT,
|
||||||
|
"createdAt" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
|
||||||
|
|
||||||
|
CONSTRAINT "AccessLog_pkey" PRIMARY KEY ("id")
|
||||||
|
);
|
||||||
|
|
||||||
|
-- CreateTable
|
||||||
|
CREATE TABLE "AuditLog" (
|
||||||
|
"id" TEXT NOT NULL,
|
||||||
|
"actorId" TEXT,
|
||||||
|
"actorRole" TEXT NOT NULL,
|
||||||
|
"action" TEXT NOT NULL,
|
||||||
|
"targetType" TEXT NOT NULL,
|
||||||
|
"targetId" TEXT,
|
||||||
|
"metadata" JSONB,
|
||||||
|
"ip" TEXT,
|
||||||
|
"createdAt" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
|
||||||
|
|
||||||
|
CONSTRAINT "AuditLog_pkey" PRIMARY KEY ("id")
|
||||||
|
);
|
||||||
|
|
||||||
|
-- CreateTable
|
||||||
|
CREATE TABLE "AppSetting" (
|
||||||
|
"key" TEXT NOT NULL,
|
||||||
|
"value" TEXT NOT NULL,
|
||||||
|
"updatedAt" TIMESTAMP(3) NOT NULL,
|
||||||
|
|
||||||
|
CONSTRAINT "AppSetting_pkey" PRIMARY KEY ("key")
|
||||||
|
);
|
||||||
|
|
||||||
|
-- CreateTable
|
||||||
|
CREATE TABLE "ProductLink" (
|
||||||
|
"installId" TEXT NOT NULL,
|
||||||
|
"product" TEXT NOT NULL,
|
||||||
|
"url" TEXT NOT NULL,
|
||||||
|
"publicKey" TEXT NOT NULL,
|
||||||
|
"secret" TEXT NOT NULL,
|
||||||
|
"connectedAt" TIMESTAMP(3) NOT NULL,
|
||||||
|
"connectedById" TEXT,
|
||||||
|
"createdAt" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
|
||||||
|
"updatedAt" TIMESTAMP(3) NOT NULL,
|
||||||
|
|
||||||
|
CONSTRAINT "ProductLink_pkey" PRIMARY KEY ("installId")
|
||||||
|
);
|
||||||
|
|
||||||
|
-- CreateTable
|
||||||
|
CREATE TABLE "LinkNonce" (
|
||||||
|
"nonce" TEXT NOT NULL,
|
||||||
|
"seenAt" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
|
||||||
|
|
||||||
|
CONSTRAINT "LinkNonce_pkey" PRIMARY KEY ("nonce")
|
||||||
|
);
|
||||||
|
|
||||||
|
-- CreateTable
|
||||||
|
CREATE TABLE "OidcPayload" (
|
||||||
|
"id" TEXT NOT NULL,
|
||||||
|
"model" TEXT NOT NULL,
|
||||||
|
"payload" JSONB NOT NULL,
|
||||||
|
"grantId" TEXT,
|
||||||
|
"userCode" TEXT,
|
||||||
|
"uid" TEXT,
|
||||||
|
"accountId" TEXT,
|
||||||
|
"expiresAt" TIMESTAMP(3),
|
||||||
|
"consumedAt" TIMESTAMP(3),
|
||||||
|
|
||||||
|
CONSTRAINT "OidcPayload_pkey" PRIMARY KEY ("id")
|
||||||
|
);
|
||||||
|
|
||||||
|
-- CreateTable
|
||||||
|
CREATE TABLE "Delivery" (
|
||||||
|
"id" TEXT NOT NULL,
|
||||||
|
"linkId" TEXT NOT NULL,
|
||||||
|
"callId" TEXT NOT NULL,
|
||||||
|
"type" TEXT NOT NULL,
|
||||||
|
"path" TEXT NOT NULL,
|
||||||
|
"body" JSONB NOT NULL,
|
||||||
|
"status" TEXT NOT NULL DEFAULT 'pending',
|
||||||
|
"attempts" INTEGER NOT NULL DEFAULT 0,
|
||||||
|
"nextAttemptAt" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
|
||||||
|
"lastError" TEXT,
|
||||||
|
"reply" JSONB,
|
||||||
|
"deliveredAt" TIMESTAMP(3),
|
||||||
|
"createdAt" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
|
||||||
|
|
||||||
|
CONSTRAINT "Delivery_pkey" PRIMARY KEY ("id")
|
||||||
|
);
|
||||||
|
|
||||||
|
-- CreateTable
|
||||||
|
CREATE TABLE "DataExport" (
|
||||||
|
"id" TEXT NOT NULL,
|
||||||
|
"accountId" TEXT NOT NULL,
|
||||||
|
"status" TEXT NOT NULL DEFAULT 'collecting',
|
||||||
|
"parts" JSONB NOT NULL DEFAULT '{}',
|
||||||
|
"file" TEXT,
|
||||||
|
"createdAt" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
|
||||||
|
"readyAt" TIMESTAMP(3),
|
||||||
|
"expiresAt" TIMESTAMP(3) NOT NULL,
|
||||||
|
|
||||||
|
CONSTRAINT "DataExport_pkey" PRIMARY KEY ("id")
|
||||||
|
);
|
||||||
|
|
||||||
|
-- CreateTable
|
||||||
|
CREATE TABLE "DeletionRequest" (
|
||||||
|
"id" TEXT NOT NULL,
|
||||||
|
"accountId" TEXT NOT NULL,
|
||||||
|
"status" TEXT NOT NULL DEFAULT 'waiting_approval',
|
||||||
|
"requestedAt" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
|
||||||
|
"approvedAt" TIMESTAMP(3),
|
||||||
|
"approvedById" TEXT,
|
||||||
|
"products" JSONB NOT NULL DEFAULT '{}',
|
||||||
|
"completedAt" TIMESTAMP(3),
|
||||||
|
|
||||||
|
CONSTRAINT "DeletionRequest_pkey" PRIMARY KEY ("id")
|
||||||
|
);
|
||||||
|
|
||||||
|
-- CreateIndex
|
||||||
|
CREATE UNIQUE INDEX "Account_email_key" ON "Account"("email");
|
||||||
|
|
||||||
|
-- CreateIndex
|
||||||
|
CREATE INDEX "Account_status_idx" ON "Account"("status");
|
||||||
|
|
||||||
|
-- CreateIndex
|
||||||
|
CREATE UNIQUE INDEX "RecoveryCode_codeHash_key" ON "RecoveryCode"("codeHash");
|
||||||
|
|
||||||
|
-- CreateIndex
|
||||||
|
CREATE INDEX "RecoveryCode_accountId_idx" ON "RecoveryCode"("accountId");
|
||||||
|
|
||||||
|
-- CreateIndex
|
||||||
|
CREATE INDEX "PendingSignIn_expiresAt_idx" ON "PendingSignIn"("expiresAt");
|
||||||
|
|
||||||
|
-- CreateIndex
|
||||||
|
CREATE UNIQUE INDEX "EmailToken_tokenHash_key" ON "EmailToken"("tokenHash");
|
||||||
|
|
||||||
|
-- CreateIndex
|
||||||
|
CREATE INDEX "EmailToken_accountId_purpose_idx" ON "EmailToken"("accountId", "purpose");
|
||||||
|
|
||||||
|
-- CreateIndex
|
||||||
|
CREATE INDEX "LoginEvent_accountId_createdAt_idx" ON "LoginEvent"("accountId", "createdAt");
|
||||||
|
|
||||||
|
-- CreateIndex
|
||||||
|
CREATE INDEX "NoticeAcceptance_accountId_idx" ON "NoticeAcceptance"("accountId");
|
||||||
|
|
||||||
|
-- CreateIndex
|
||||||
|
CREATE INDEX "ConsentChange_accountId_idx" ON "ConsentChange"("accountId");
|
||||||
|
|
||||||
|
-- CreateIndex
|
||||||
|
CREATE INDEX "AccessLog_targetId_createdAt_idx" ON "AccessLog"("targetId", "createdAt");
|
||||||
|
|
||||||
|
-- CreateIndex
|
||||||
|
CREATE INDEX "AuditLog_createdAt_idx" ON "AuditLog"("createdAt");
|
||||||
|
|
||||||
|
-- CreateIndex
|
||||||
|
CREATE INDEX "LinkNonce_seenAt_idx" ON "LinkNonce"("seenAt");
|
||||||
|
|
||||||
|
-- CreateIndex
|
||||||
|
CREATE INDEX "OidcPayload_grantId_idx" ON "OidcPayload"("grantId");
|
||||||
|
|
||||||
|
-- CreateIndex
|
||||||
|
CREATE INDEX "OidcPayload_uid_idx" ON "OidcPayload"("uid");
|
||||||
|
|
||||||
|
-- CreateIndex
|
||||||
|
CREATE INDEX "OidcPayload_accountId_idx" ON "OidcPayload"("accountId");
|
||||||
|
|
||||||
|
-- CreateIndex
|
||||||
|
CREATE INDEX "OidcPayload_expiresAt_idx" ON "OidcPayload"("expiresAt");
|
||||||
|
|
||||||
|
-- CreateIndex
|
||||||
|
CREATE UNIQUE INDEX "Delivery_callId_key" ON "Delivery"("callId");
|
||||||
|
|
||||||
|
-- CreateIndex
|
||||||
|
CREATE INDEX "Delivery_status_nextAttemptAt_idx" ON "Delivery"("status", "nextAttemptAt");
|
||||||
|
|
||||||
|
-- CreateIndex
|
||||||
|
CREATE INDEX "Delivery_linkId_idx" ON "Delivery"("linkId");
|
||||||
|
|
||||||
|
-- CreateIndex
|
||||||
|
CREATE INDEX "DataExport_accountId_idx" ON "DataExport"("accountId");
|
||||||
|
|
||||||
|
-- CreateIndex
|
||||||
|
CREATE INDEX "DeletionRequest_status_idx" ON "DeletionRequest"("status");
|
||||||
|
|
||||||
|
-- AddForeignKey
|
||||||
|
ALTER TABLE "RecoveryCode" ADD CONSTRAINT "RecoveryCode_accountId_fkey" FOREIGN KEY ("accountId") REFERENCES "Account"("id") ON DELETE CASCADE ON UPDATE CASCADE;
|
||||||
|
|
||||||
|
-- AddForeignKey
|
||||||
|
ALTER TABLE "EmailToken" ADD CONSTRAINT "EmailToken_accountId_fkey" FOREIGN KEY ("accountId") REFERENCES "Account"("id") ON DELETE CASCADE ON UPDATE CASCADE;
|
||||||
|
|
||||||
|
-- AddForeignKey
|
||||||
|
ALTER TABLE "LoginEvent" ADD CONSTRAINT "LoginEvent_accountId_fkey" FOREIGN KEY ("accountId") REFERENCES "Account"("id") ON DELETE CASCADE ON UPDATE CASCADE;
|
||||||
|
|
||||||
|
-- AddForeignKey
|
||||||
|
ALTER TABLE "NoticeAcceptance" ADD CONSTRAINT "NoticeAcceptance_accountId_fkey" FOREIGN KEY ("accountId") REFERENCES "Account"("id") ON DELETE CASCADE ON UPDATE CASCADE;
|
||||||
|
|
||||||
|
-- AddForeignKey
|
||||||
|
ALTER TABLE "ConsentChange" ADD CONSTRAINT "ConsentChange_accountId_fkey" FOREIGN KEY ("accountId") REFERENCES "Account"("id") ON DELETE CASCADE ON UPDATE CASCADE;
|
||||||
|
|
||||||
|
-- AddForeignKey
|
||||||
|
ALTER TABLE "Delivery" ADD CONSTRAINT "Delivery_linkId_fkey" FOREIGN KEY ("linkId") REFERENCES "ProductLink"("installId") ON DELETE CASCADE ON UPDATE CASCADE;
|
||||||
|
|
||||||
|
-- AddForeignKey
|
||||||
|
ALTER TABLE "DataExport" ADD CONSTRAINT "DataExport_accountId_fkey" FOREIGN KEY ("accountId") REFERENCES "Account"("id") ON DELETE CASCADE ON UPDATE CASCADE;
|
||||||
|
|
||||||
|
-- AddForeignKey
|
||||||
|
ALTER TABLE "DeletionRequest" ADD CONSTRAINT "DeletionRequest_accountId_fkey" FOREIGN KEY ("accountId") REFERENCES "Account"("id") ON DELETE CASCADE ON UPDATE CASCADE;
|
||||||
|
|
||||||
@@ -0,0 +1,3 @@
|
|||||||
|
# Please do not edit this file manually
|
||||||
|
# It should be added in your version-control system (e.g., Git)
|
||||||
|
provider = "postgresql"
|
||||||
@@ -0,0 +1,287 @@
|
|||||||
|
// Accounts 1.0.0 (docs/ACCOUNTS-1.0-PLAN.md). One database per church.
|
||||||
|
|
||||||
|
generator client {
|
||||||
|
provider = "prisma-client"
|
||||||
|
// Its own output, so hoisted clients of other apps never overwrite it (EVENTS-2.2-PLAN §2).
|
||||||
|
output = "../src/generated/prisma"
|
||||||
|
moduleFormat = "esm"
|
||||||
|
importFileExtension = "js"
|
||||||
|
}
|
||||||
|
|
||||||
|
datasource db {
|
||||||
|
provider = "postgresql"
|
||||||
|
}
|
||||||
|
|
||||||
|
enum AccountRole {
|
||||||
|
member
|
||||||
|
admin
|
||||||
|
}
|
||||||
|
|
||||||
|
enum AccountStatus {
|
||||||
|
active
|
||||||
|
deactivated
|
||||||
|
deleted
|
||||||
|
}
|
||||||
|
|
||||||
|
enum TwoFactorMethod {
|
||||||
|
email
|
||||||
|
whatsapp
|
||||||
|
totp
|
||||||
|
}
|
||||||
|
|
||||||
|
// A person. `id` is the OIDC `sub` every product keys its own records on.
|
||||||
|
model Account {
|
||||||
|
id String @id @default(uuid())
|
||||||
|
name String
|
||||||
|
givenName String?
|
||||||
|
familyName String?
|
||||||
|
email String @unique // lower-case
|
||||||
|
emailVerified Boolean @default(false)
|
||||||
|
phone String?
|
||||||
|
phoneVerified Boolean @default(false)
|
||||||
|
// Argon2id; bcrypt hashes imported from Cross Events verify too and are re-hashed at sign-in.
|
||||||
|
passwordHash String?
|
||||||
|
role AccountRole @default(member)
|
||||||
|
status AccountStatus @default(active)
|
||||||
|
twoFactorMethod TwoFactorMethod?
|
||||||
|
totpSecret String? // encrypted
|
||||||
|
totpLastStep Int?
|
||||||
|
newsEmail Boolean @default(false)
|
||||||
|
newsWhatsApp Boolean @default(false)
|
||||||
|
newsAskedAt DateTime?
|
||||||
|
noticeVersionAccepted Int @default(0)
|
||||||
|
failedSignIns Int @default(0)
|
||||||
|
lockedUntil DateTime?
|
||||||
|
lastSignInAt DateTime?
|
||||||
|
deactivatedAt DateTime?
|
||||||
|
anonymisedAt DateTime?
|
||||||
|
createdAt DateTime @default(now())
|
||||||
|
updatedAt DateTime @updatedAt
|
||||||
|
|
||||||
|
recoveryCodes RecoveryCode[]
|
||||||
|
tokens EmailToken[]
|
||||||
|
loginEvents LoginEvent[]
|
||||||
|
acceptances NoticeAcceptance[]
|
||||||
|
consentChanges ConsentChange[]
|
||||||
|
exports DataExport[]
|
||||||
|
deletionRequests DeletionRequest[]
|
||||||
|
|
||||||
|
@@index([status])
|
||||||
|
}
|
||||||
|
|
||||||
|
model RecoveryCode {
|
||||||
|
id String @id @default(uuid())
|
||||||
|
accountId String
|
||||||
|
account Account @relation(fields: [accountId], references: [id], onDelete: Cascade)
|
||||||
|
codeHash String @unique
|
||||||
|
usedAt DateTime?
|
||||||
|
createdAt DateTime @default(now())
|
||||||
|
|
||||||
|
@@index([accountId])
|
||||||
|
}
|
||||||
|
|
||||||
|
// One sign-in in progress (an oidc-provider interaction), through every step: password, 2FA,
|
||||||
|
// verifying a new email, the news question and the privacy notice. Keyed by the interaction uid.
|
||||||
|
model PendingSignIn {
|
||||||
|
uid String @id
|
||||||
|
accountId String?
|
||||||
|
stage String // password | two_factor | setup_two_factor | verify_email | notice | news | done
|
||||||
|
codeHash String?
|
||||||
|
codeSentAt DateTime?
|
||||||
|
attempts Int @default(0)
|
||||||
|
amr String[]
|
||||||
|
pendingTotpSecret String? // encrypted, while setting up an authenticator app during sign-in
|
||||||
|
remember Boolean @default(false)
|
||||||
|
expiresAt DateTime
|
||||||
|
createdAt DateTime @default(now())
|
||||||
|
|
||||||
|
@@index([expiresAt])
|
||||||
|
}
|
||||||
|
|
||||||
|
// Links sent by email: verify an address, reset a password. Only the hash is kept.
|
||||||
|
model EmailToken {
|
||||||
|
id String @id @default(uuid())
|
||||||
|
accountId String
|
||||||
|
account Account @relation(fields: [accountId], references: [id], onDelete: Cascade)
|
||||||
|
purpose String // verify_email | reset_password
|
||||||
|
tokenHash String @unique
|
||||||
|
// The sign-in the link belongs to, so it carries on to the product afterwards (§5).
|
||||||
|
interactionUid String?
|
||||||
|
expiresAt DateTime
|
||||||
|
usedAt DateTime?
|
||||||
|
createdAt DateTime @default(now())
|
||||||
|
|
||||||
|
@@index([accountId, purpose])
|
||||||
|
}
|
||||||
|
|
||||||
|
// Sign-ins and changes to how someone signs in (the person and admins see these).
|
||||||
|
model LoginEvent {
|
||||||
|
id String @id @default(uuid())
|
||||||
|
accountId String?
|
||||||
|
account Account? @relation(fields: [accountId], references: [id], onDelete: Cascade)
|
||||||
|
type String // sign_in | sign_in_failed | locked | password_reset | password_changed | two_factor_on | two_factor_off | recovery_code_used | recovery_codes_replaced | signed_out_everywhere
|
||||||
|
clientId String? // the product it was for
|
||||||
|
ip String?
|
||||||
|
userAgent String?
|
||||||
|
detail Json?
|
||||||
|
createdAt DateTime @default(now())
|
||||||
|
|
||||||
|
@@index([accountId, createdAt])
|
||||||
|
}
|
||||||
|
|
||||||
|
model PrivacyNotice {
|
||||||
|
version Int @id
|
||||||
|
title String
|
||||||
|
body String
|
||||||
|
publishedAt DateTime @default(now())
|
||||||
|
publishedById String?
|
||||||
|
}
|
||||||
|
|
||||||
|
model NoticeAcceptance {
|
||||||
|
id String @id @default(uuid())
|
||||||
|
accountId String
|
||||||
|
account Account @relation(fields: [accountId], references: [id], onDelete: Cascade)
|
||||||
|
version Int
|
||||||
|
acceptedAt DateTime @default(now())
|
||||||
|
|
||||||
|
@@index([accountId])
|
||||||
|
}
|
||||||
|
|
||||||
|
// Proof of news consent (POPIA): every change, with where it was given.
|
||||||
|
model ConsentChange {
|
||||||
|
id String @id @default(uuid())
|
||||||
|
accountId String
|
||||||
|
account Account @relation(fields: [accountId], references: [id], onDelete: Cascade)
|
||||||
|
channel String // email | whatsapp
|
||||||
|
granted Boolean
|
||||||
|
source String // sign_up | news_question | account_page | admin
|
||||||
|
createdAt DateTime @default(now())
|
||||||
|
|
||||||
|
@@index([accountId])
|
||||||
|
}
|
||||||
|
|
||||||
|
// Admins viewing or exporting a person.
|
||||||
|
model AccessLog {
|
||||||
|
id String @id @default(uuid())
|
||||||
|
actorId String
|
||||||
|
targetId String
|
||||||
|
action String // view | export
|
||||||
|
ip String?
|
||||||
|
createdAt DateTime @default(now())
|
||||||
|
|
||||||
|
@@index([targetId, createdAt])
|
||||||
|
}
|
||||||
|
|
||||||
|
model AuditLog {
|
||||||
|
id String @id @default(uuid())
|
||||||
|
actorId String?
|
||||||
|
actorRole String
|
||||||
|
action String
|
||||||
|
targetType String
|
||||||
|
targetId String?
|
||||||
|
metadata Json?
|
||||||
|
ip String?
|
||||||
|
createdAt DateTime @default(now())
|
||||||
|
|
||||||
|
@@index([createdAt])
|
||||||
|
}
|
||||||
|
|
||||||
|
model AppSetting {
|
||||||
|
key String @id
|
||||||
|
value String
|
||||||
|
updatedAt DateTime @updatedAt
|
||||||
|
}
|
||||||
|
|
||||||
|
// 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[]
|
||||||
|
}
|
||||||
|
|
||||||
|
model LinkNonce {
|
||||||
|
nonce String @id
|
||||||
|
seenAt DateTime @default(now())
|
||||||
|
|
||||||
|
@@index([seenAt])
|
||||||
|
}
|
||||||
|
|
||||||
|
// oidc-provider's storage (sessions, grants, codes, interactions…), one row per model and id.
|
||||||
|
model OidcPayload {
|
||||||
|
id String @id // "<model>:<id>"
|
||||||
|
model String
|
||||||
|
payload Json
|
||||||
|
grantId String?
|
||||||
|
userCode String?
|
||||||
|
uid String?
|
||||||
|
// Sessions only: whose, so "sign out everywhere" can find them.
|
||||||
|
accountId String?
|
||||||
|
expiresAt DateTime?
|
||||||
|
consumedAt DateTime?
|
||||||
|
|
||||||
|
@@index([grantId])
|
||||||
|
@@index([uid])
|
||||||
|
@@index([accountId])
|
||||||
|
@@index([expiresAt])
|
||||||
|
}
|
||||||
|
|
||||||
|
// Back-channel calls to linked products (user.updated, user.deleted, user.export, church.changed),
|
||||||
|
// retried until they're answered.
|
||||||
|
model Delivery {
|
||||||
|
id String @id @default(uuid())
|
||||||
|
linkId String
|
||||||
|
link ProductLink @relation(fields: [linkId], references: [installId], onDelete: Cascade)
|
||||||
|
callId String @unique
|
||||||
|
type String
|
||||||
|
path String
|
||||||
|
body Json
|
||||||
|
status String @default("pending") // pending | delivered | failed
|
||||||
|
attempts Int @default(0)
|
||||||
|
nextAttemptAt DateTime @default(now())
|
||||||
|
lastError String?
|
||||||
|
reply Json?
|
||||||
|
deliveredAt DateTime?
|
||||||
|
createdAt DateTime @default(now())
|
||||||
|
|
||||||
|
@@index([status, nextAttemptAt])
|
||||||
|
@@index([linkId])
|
||||||
|
}
|
||||||
|
|
||||||
|
// "Download my data": Accounts' part plus each product's (user.export), bundled into one file.
|
||||||
|
model DataExport {
|
||||||
|
id String @id @default(uuid())
|
||||||
|
accountId String
|
||||||
|
account Account @relation(fields: [accountId], references: [id], onDelete: Cascade)
|
||||||
|
status String @default("collecting") // collecting | ready | expired
|
||||||
|
parts Json @default("{}")
|
||||||
|
file String?
|
||||||
|
createdAt DateTime @default(now())
|
||||||
|
readyAt DateTime?
|
||||||
|
expiresAt DateTime
|
||||||
|
|
||||||
|
@@index([accountId])
|
||||||
|
}
|
||||||
|
|
||||||
|
// "Delete my account": deactivated at once, then an admin approves, then every product answers.
|
||||||
|
model DeletionRequest {
|
||||||
|
id String @id @default(uuid())
|
||||||
|
accountId String
|
||||||
|
account Account @relation(fields: [accountId], references: [id], onDelete: Cascade)
|
||||||
|
status String @default("waiting_approval") // waiting_approval | approved | done | cancelled
|
||||||
|
requestedAt DateTime @default(now())
|
||||||
|
approvedAt DateTime?
|
||||||
|
approvedById String?
|
||||||
|
// { [installId]: { status: "pending" | "deleted" | "deferred", reason?, retryAfter? } }
|
||||||
|
products Json @default("{}")
|
||||||
|
completedAt DateTime?
|
||||||
|
|
||||||
|
@@index([status])
|
||||||
|
}
|
||||||
@@ -0,0 +1,42 @@
|
|||||||
|
/**
|
||||||
|
* Accounts' part of a church's export when it leaves (`crosscode export` / uninstall, AGENT-1.0-PLAN
|
||||||
|
* §9): `accounts.json` in --out-dir, with the church profile and the people in plain terms (the
|
||||||
|
* same person fields as `crosscode.church-export/1`; no passwords, 2FA secrets or sign-in logs).
|
||||||
|
*
|
||||||
|
* npx tsx scripts/export-church.ts --out-dir <dir>
|
||||||
|
*/
|
||||||
|
import 'dotenv/config';
|
||||||
|
import fs from 'node:fs';
|
||||||
|
import path from 'node:path';
|
||||||
|
import { PrismaPg } from '@prisma/adapter-pg';
|
||||||
|
import { PrismaClient } from '../src/generated/prisma/client.js';
|
||||||
|
import { createCtx } from '../src/context.js';
|
||||||
|
import { loadConfig } from '../src/lib/config.js';
|
||||||
|
import { church } from '../src/church/profile.js';
|
||||||
|
|
||||||
|
const i = process.argv.indexOf('--out-dir');
|
||||||
|
const out = i > 0 ? process.argv[i + 1] : null;
|
||||||
|
if (!out) {
|
||||||
|
console.error('Usage: export-church.ts --out-dir <dir>');
|
||||||
|
process.exit(2);
|
||||||
|
}
|
||||||
|
|
||||||
|
const db = new PrismaClient({ adapter: new PrismaPg({ connectionString: process.env.DATABASE_URL! }) });
|
||||||
|
const ctx = createCtx(loadConfig(), db);
|
||||||
|
const people = await db.account.findMany({ where: { status: { not: 'deleted' } }, orderBy: { name: 'asc' } });
|
||||||
|
const acceptances = await db.noticeAcceptance.findMany({ orderBy: { acceptedAt: 'asc' } });
|
||||||
|
const accepted = new Map(acceptances.map((a) => [a.accountId, a.acceptedAt]));
|
||||||
|
const data = {
|
||||||
|
product: 'accounts',
|
||||||
|
generatedAt: new Date().toISOString(),
|
||||||
|
church: await church(ctx),
|
||||||
|
people: people.map((p, n) => ({
|
||||||
|
ref: `p${n + 1}`, name: p.name, email: p.email, phone: p.phone, role: p.role === 'admin' ? 'accounts admin' : 'member',
|
||||||
|
createdAt: p.createdAt.toISOString(),
|
||||||
|
consent: { email: p.newsEmail, whatsapp: p.newsWhatsApp, privacyNoticeAcceptedAt: accepted.get(p.id)?.toISOString() ?? null },
|
||||||
|
})),
|
||||||
|
};
|
||||||
|
fs.mkdirSync(out, { recursive: true });
|
||||||
|
fs.writeFileSync(path.join(out, 'accounts.json'), JSON.stringify(data, null, 2), { mode: 0o600 });
|
||||||
|
console.log(` accounts.json: ${data.people.length} people`);
|
||||||
|
await db.$disconnect();
|
||||||
@@ -0,0 +1,120 @@
|
|||||||
|
/**
|
||||||
|
* People's accounts: what the products are told about someone (`crosscode.identity/1`), consent,
|
||||||
|
* lockout, and the codes sent for 2FA and verifying an address.
|
||||||
|
*/
|
||||||
|
import crypto from 'node:crypto';
|
||||||
|
import { IDENTITY_SCHEMA, type IdentityClaims, type Profile } from '@crosscode/contracts';
|
||||||
|
import type { Request } from 'express';
|
||||||
|
import type { Ctx } from '../context.js';
|
||||||
|
import type { Account } from '../generated/prisma/client.js';
|
||||||
|
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';
|
||||||
|
|
||||||
|
export const MAX_FAILED_SIGN_INS = 10;
|
||||||
|
export const LOCK_MINUTES = 15;
|
||||||
|
export const CODE_MINUTES = 10;
|
||||||
|
|
||||||
|
export const normaliseEmail = (e: unknown) => String(e ?? '').trim().toLowerCase();
|
||||||
|
|
||||||
|
export function emailProblem(email: string): string | null {
|
||||||
|
return /^[^\s@]+@[^\s@]+\.[^\s@]{2,}$/.test(email) && email.length <= 254 ? null : 'Enter a valid email address.';
|
||||||
|
}
|
||||||
|
|
||||||
|
/** +27821234567 from 0821234567 and the like; null when it can't be read. */
|
||||||
|
export function normalisePhone(raw: unknown): string | null {
|
||||||
|
const s = String(raw ?? '').trim();
|
||||||
|
if (!s) return null;
|
||||||
|
let d = s.replace(/\D/g, '');
|
||||||
|
if (s.startsWith('+')) return d.length >= 8 && d.length <= 15 ? `+${d}` : null;
|
||||||
|
if (d.startsWith('0') && d.length === 10) d = `27${d.slice(1)}`;
|
||||||
|
return d.length >= 8 && d.length <= 15 ? `+${d}` : null;
|
||||||
|
}
|
||||||
|
|
||||||
|
export function profileOf(a: Account): Profile {
|
||||||
|
return {
|
||||||
|
name: a.name,
|
||||||
|
given_name: a.givenName,
|
||||||
|
family_name: a.familyName,
|
||||||
|
email: a.email,
|
||||||
|
email_verified: a.emailVerified,
|
||||||
|
phone_number: a.phone,
|
||||||
|
phone_number_verified: a.phoneVerified,
|
||||||
|
news_consent: { email: a.newsEmail, whatsapp: a.newsWhatsApp },
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
/** The `crosscode.identity/1` claims (without `amr`, which comes from the sign-in itself). */
|
||||||
|
export async function identityClaims(ctx: Ctx, a: Account): Promise<Omit<IdentityClaims, 'amr'>> {
|
||||||
|
return {
|
||||||
|
schema: IDENTITY_SCHEMA,
|
||||||
|
sub: a.id,
|
||||||
|
...profileOf(a),
|
||||||
|
two_factor: a.twoFactorMethod,
|
||||||
|
privacy_notice_version: Math.max(1, a.noticeVersionAccepted || (await currentNoticeVersion(ctx))),
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Tell every linked product the profile or consent changed (`user.updated`). */
|
||||||
|
export async function profileChanged(ctx: Ctx, accountId: string) {
|
||||||
|
const a = await ctx.db.account.findUnique({ where: { id: accountId } });
|
||||||
|
if (!a || a.status !== 'active') return;
|
||||||
|
await queueCall(ctx, 'user.updated', (callId) => ({ schema: IDENTITY_SCHEMA, type: 'user.updated', callId, occurredAt: ctx.now().toISOString(), sub: a.id, profile: profileOf(a) }));
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Records news consent (POPIA proof of each change) and returns whether anything changed. */
|
||||||
|
export async function setNewsConsent(ctx: Ctx, a: Account, next: { email?: boolean; whatsapp?: boolean }, source: string): Promise<boolean> {
|
||||||
|
const changes: { channel: string; granted: boolean }[] = [];
|
||||||
|
if (next.email !== undefined && next.email !== a.newsEmail) changes.push({ channel: 'email', granted: next.email });
|
||||||
|
if (next.whatsapp !== undefined && next.whatsapp !== a.newsWhatsApp) changes.push({ channel: 'whatsapp', granted: next.whatsapp });
|
||||||
|
await ctx.db.account.update({
|
||||||
|
where: { id: a.id },
|
||||||
|
data: { ...(next.email !== undefined ? { newsEmail: next.email } : {}), ...(next.whatsapp !== undefined ? { newsWhatsApp: next.whatsapp } : {}), newsAskedAt: a.newsAskedAt ?? ctx.now() },
|
||||||
|
});
|
||||||
|
for (const c of changes) await ctx.db.consentChange.create({ data: { accountId: a.id, ...c, source, createdAt: ctx.now() } });
|
||||||
|
return changes.length > 0;
|
||||||
|
}
|
||||||
|
|
||||||
|
// ─── Lockout ──────────────────────────────────────────────────────────────────
|
||||||
|
|
||||||
|
export const isLocked = (ctx: Ctx, a: Account) => !!a.lockedUntil && a.lockedUntil > ctx.now();
|
||||||
|
|
||||||
|
export async function signInFailed(ctx: Ctx, a: Account, req?: Request) {
|
||||||
|
const failed = a.failedSignIns + 1;
|
||||||
|
const lock = failed >= MAX_FAILED_SIGN_INS;
|
||||||
|
await ctx.db.account.update({ where: { id: a.id }, data: { failedSignIns: lock ? 0 : failed, ...(lock ? { lockedUntil: new Date(ctx.now().getTime() + LOCK_MINUTES * 60e3) } : {}) } });
|
||||||
|
await loginEvent(ctx, a.id, lock ? 'locked' : 'sign_in_failed', req);
|
||||||
|
}
|
||||||
|
|
||||||
|
export async function signInSucceeded(ctx: Ctx, a: Account) {
|
||||||
|
await ctx.db.account.update({ where: { id: a.id }, data: { failedSignIns: 0, lockedUntil: null, lastSignInAt: ctx.now() } });
|
||||||
|
}
|
||||||
|
|
||||||
|
// ─── Codes by email or WhatsApp ───────────────────────────────────────────────
|
||||||
|
|
||||||
|
/** Where a code goes, partly hidden for the screen: "j***@hope.co.za", "+27 ** *** 4567". */
|
||||||
|
export function maskedTarget(a: Account, method: 'email' | 'whatsapp'): string {
|
||||||
|
if (method === 'whatsapp') return a.phone ? `${a.phone.slice(0, 3)} ** *** ${a.phone.slice(-4)}` : 'your phone';
|
||||||
|
const [user, domain] = a.email.split('@');
|
||||||
|
return `${user!.slice(0, 1)}***@${domain}`;
|
||||||
|
}
|
||||||
|
|
||||||
|
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 });
|
||||||
|
}
|
||||||
|
return { codeHash: hashToken(code), sentTo: maskedTarget(a, method) };
|
||||||
|
}
|
||||||
|
|
||||||
|
export const codeMatches = (code: unknown, hash: string | null | undefined) =>
|
||||||
|
!!hash && safeEqual(hashToken(String(code ?? '').replace(/\D/g, '')), hash);
|
||||||
|
|
||||||
|
export const newId = () => crypto.randomUUID();
|
||||||
@@ -0,0 +1,98 @@
|
|||||||
|
/**
|
||||||
|
* Two-factor sign-in (as Cross Events 2.3): an authenticator app (TOTP), or a code by email or
|
||||||
|
* WhatsApp, with 10 single-use recovery codes. Used by the sign-in flow and the account page.
|
||||||
|
*/
|
||||||
|
import type { Request } from 'express';
|
||||||
|
import type { Ctx } from '../context.js';
|
||||||
|
import type { Account } from '../generated/prisma/client.js';
|
||||||
|
import { codeMatches, sendCode, CODE_MINUTES } from './service.js';
|
||||||
|
import { loginEvent } from '../lib/audit.js';
|
||||||
|
import { hashRecoveryCode, newRecoveryCodes } from '../lib/recoveryCodes.js';
|
||||||
|
import { generateSecret, matchStep, otpauthUrl } from '../lib/totp.js';
|
||||||
|
|
||||||
|
export class TwoFactorError extends Error {
|
||||||
|
status = 400;
|
||||||
|
constructor(message: string, public code = 'BAD_CODE') {
|
||||||
|
super(message);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
const METHODS = new Set(['totp', 'email', 'whatsapp']);
|
||||||
|
|
||||||
|
/** After a second factor: RFC 8176 `otp` and `mfa`. */
|
||||||
|
export const accessAfterTwoFactor = (amr: string[]) => [...new Set([...amr, 'otp', 'mfa'])];
|
||||||
|
|
||||||
|
export async function verifyTotp(ctx: Ctx, a: Account, code: unknown): Promise<boolean> {
|
||||||
|
if (!a.totpSecret) return false;
|
||||||
|
const step = matchStep(ctx.secrets.decrypt(a.totpSecret), code, { now: ctx.now().getTime(), afterStep: a.totpLastStep ?? -1 });
|
||||||
|
if (step === null) return false;
|
||||||
|
await ctx.db.account.update({ where: { id: a.id }, data: { totpLastStep: step } });
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
|
||||||
|
export async function useRecoveryCode(ctx: Ctx, a: Account, code: unknown, req?: Request): Promise<boolean> {
|
||||||
|
const row = await ctx.db.recoveryCode.findUnique({ where: { codeHash: hashRecoveryCode(String(code)) } });
|
||||||
|
if (!row || row.accountId !== a.id || row.usedAt) return false;
|
||||||
|
await ctx.db.recoveryCode.update({ where: { id: row.id }, data: { usedAt: ctx.now() } });
|
||||||
|
await loginEvent(ctx, a.id, 'recovery_code_used', req);
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Starts setting up a method: an app gets a new secret to scan; email or WhatsApp gets a code. */
|
||||||
|
export async function startTwoFactorSetup(ctx: Ctx, a: Account, method: unknown) {
|
||||||
|
if (!METHODS.has(String(method))) throw new TwoFactorError('Choose how you want to get your codes.', 'BAD_METHOD');
|
||||||
|
if (method === 'whatsapp' && (!a.phone || !(await ctx.messenger.whatsappReady()))) throw new TwoFactorError('WhatsApp codes need a phone number on your account.', 'BAD_METHOD');
|
||||||
|
if (method === 'totp') {
|
||||||
|
const secret = generateSecret();
|
||||||
|
const issuer = (await ctx.settings.json<{ shortName?: string; name?: string }>('church_profile', {}));
|
||||||
|
return {
|
||||||
|
encryptedSecret: ctx.secrets.encrypt(secret),
|
||||||
|
codeHash: null as string | null,
|
||||||
|
forScreen: { method: 'totp', secret, otpauthUrl: otpauthUrl(secret, a.email, issuer.shortName || issuer.name || 'Church') },
|
||||||
|
};
|
||||||
|
}
|
||||||
|
const sent = await sendCode(ctx, a, method as 'email' | 'whatsapp', 'setup');
|
||||||
|
return { encryptedSecret: null as string | null, codeHash: sent.codeHash, forScreen: { method, sentTo: sent.sentTo } };
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Confirms the first code, turns the method on and returns new recovery codes (shown once). */
|
||||||
|
export async function confirmTwoFactorSetup(
|
||||||
|
ctx: Ctx, a: Account,
|
||||||
|
s: { method: unknown; code: unknown; pendingSecret: string | null; codeHash: string | null; codeSentAt: Date | null },
|
||||||
|
req?: Request,
|
||||||
|
): Promise<string[]> {
|
||||||
|
const method = String(s.method);
|
||||||
|
if (!METHODS.has(method)) throw new TwoFactorError('Choose how you want to get your codes.', 'BAD_METHOD');
|
||||||
|
let totpSecret: string | null = null;
|
||||||
|
let totpLastStep: number | null = null;
|
||||||
|
if (method === 'totp') {
|
||||||
|
if (!s.pendingSecret) throw new TwoFactorError('Start again: scan the QR code first.', 'RESTART');
|
||||||
|
const step = matchStep(ctx.secrets.decrypt(s.pendingSecret), s.code, { now: ctx.now().getTime() });
|
||||||
|
if (step === null) throw new TwoFactorError('That code isn\'t right. Check your authenticator app\'s time is correct.');
|
||||||
|
totpSecret = s.pendingSecret;
|
||||||
|
totpLastStep = step;
|
||||||
|
} else {
|
||||||
|
const fresh = s.codeSentAt && ctx.now().getTime() - s.codeSentAt.getTime() < CODE_MINUTES * 60e3;
|
||||||
|
if (!fresh || !codeMatches(s.code, s.codeHash)) throw new TwoFactorError('That code isn\'t right, or it has expired.');
|
||||||
|
}
|
||||||
|
await ctx.db.account.update({ where: { id: a.id }, data: { twoFactorMethod: method as 'totp' | 'email' | 'whatsapp', totpSecret, totpLastStep } });
|
||||||
|
const codes = await replaceRecoveryCodes(ctx, a.id);
|
||||||
|
await loginEvent(ctx, a.id, 'two_factor_on', req, { detail: { method } });
|
||||||
|
return codes;
|
||||||
|
}
|
||||||
|
|
||||||
|
export async function replaceRecoveryCodes(ctx: Ctx, accountId: string): Promise<string[]> {
|
||||||
|
const { codes, hashes } = newRecoveryCodes();
|
||||||
|
await ctx.db.recoveryCode.deleteMany({ where: { accountId } });
|
||||||
|
for (const codeHash of hashes) await ctx.db.recoveryCode.create({ data: { accountId, codeHash, createdAt: ctx.now() } });
|
||||||
|
return codes;
|
||||||
|
}
|
||||||
|
|
||||||
|
export async function turnOff(ctx: Ctx, accountId: string) {
|
||||||
|
await ctx.db.account.update({ where: { id: accountId }, data: { twoFactorMethod: null, totpSecret: null, totpLastStep: null } });
|
||||||
|
await ctx.db.recoveryCode.deleteMany({ where: { accountId } });
|
||||||
|
}
|
||||||
|
|
||||||
|
export async function recoveryCodesLeft(ctx: Ctx, accountId: string): Promise<number> {
|
||||||
|
return ctx.db.recoveryCode.count({ where: { accountId, usedAt: null } });
|
||||||
|
}
|
||||||
@@ -0,0 +1,260 @@
|
|||||||
|
/**
|
||||||
|
* Accounts' admin (`/api/v2/admin/…`, docs/ACCOUNTS-1.0-PLAN.md §8): people, sign-in settings,
|
||||||
|
* linked products, the church profile, privacy notices and deletions, email and WhatsApp, the
|
||||||
|
* licence and the audit log. Admins only, signed in with 2FA; viewing a person is access-logged.
|
||||||
|
*/
|
||||||
|
import express, { type Request, type Response } from 'express';
|
||||||
|
import type Provider from 'oidc-provider';
|
||||||
|
import type { Ctx } from '../context.js';
|
||||||
|
import { ApiError, handle, limit } from '../http.js';
|
||||||
|
import { accessLog, audit, clientIp, loginEvent } from '../lib/audit.js';
|
||||||
|
import { ADMIN_SETTINGS, SECRET_SETTINGS } from '../lib/settings.js';
|
||||||
|
import { currentSession } from '../oidc/sessions.js';
|
||||||
|
import { signOutEverywhere } from '../oidc/sessions.js';
|
||||||
|
import { recoveryCodesLeft, turnOff } from '../accounts/twoFactor.js';
|
||||||
|
import { church, updateProfile } from '../church/profile.js';
|
||||||
|
import { connectTo, disconnectFrom } from '../links/connect.js';
|
||||||
|
import { linkedProducts } from '../links/store.js';
|
||||||
|
import { approveDeletion, cancelDeletion } from '../privacy/deletion.js';
|
||||||
|
import { currentNotice, publish } from '../privacy/notice.js';
|
||||||
|
import { licenceStatus } from '../hub/licence.js';
|
||||||
|
import { connect as connectHub } from '../hub/client.js';
|
||||||
|
import { productName } from '../oidc/clients.js';
|
||||||
|
|
||||||
|
const PAGE = 50;
|
||||||
|
|
||||||
|
export function adminRouter(ctx: Ctx, provider: Provider) {
|
||||||
|
const r = express.Router();
|
||||||
|
|
||||||
|
const admin = async (req: Request, res: Response) => {
|
||||||
|
const s = await currentSession(ctx, provider, req, res);
|
||||||
|
if (!s) throw new ApiError(401, 'UNAUTHENTICATED', 'Please sign in.');
|
||||||
|
if (s.account.role !== 'admin') throw new ApiError(403, 'FORBIDDEN', 'Only Accounts admins can do that.');
|
||||||
|
if ((await ctx.settings.bool('two_factor_required_for_admins', true)) && !s.amr.includes('mfa')) throw new ApiError(403, 'MFA_REQUIRED', 'Sign in again with your second step to use admin.');
|
||||||
|
return { id: s.account.id, role: 'admin' };
|
||||||
|
};
|
||||||
|
|
||||||
|
// ─── People ────────────────────────────────────────────────────────────────
|
||||||
|
|
||||||
|
r.get('/people', handle(async (req, res) => {
|
||||||
|
await admin(req, res);
|
||||||
|
const q = String(req.query.q ?? '').trim();
|
||||||
|
const page = Math.max(1, Number(req.query.page) || 1);
|
||||||
|
const where = {
|
||||||
|
status: { not: 'deleted' as const },
|
||||||
|
...(q ? { OR: [{ name: { contains: q, mode: 'insensitive' as const } }, { email: { contains: q.toLowerCase() } }] } : {}),
|
||||||
|
};
|
||||||
|
const [items, total] = await Promise.all([
|
||||||
|
ctx.db.account.findMany({ where, orderBy: { name: 'asc' }, skip: (page - 1) * PAGE, take: PAGE }),
|
||||||
|
ctx.db.account.count({ where }),
|
||||||
|
]);
|
||||||
|
return {
|
||||||
|
items: items.map((a) => ({ id: a.id, name: a.name, email: a.email, role: a.role, status: a.status, twoFactor: a.twoFactorMethod, lastSignInAt: a.lastSignInAt })),
|
||||||
|
total, page, pages: Math.max(1, Math.ceil(total / PAGE)),
|
||||||
|
};
|
||||||
|
}));
|
||||||
|
|
||||||
|
r.get('/people/:id', handle(async (req, res) => {
|
||||||
|
const me = await admin(req, res);
|
||||||
|
const a = await ctx.db.account.findUnique({ where: { id: String(req.params.id) } });
|
||||||
|
if (!a || a.status === 'deleted') throw new ApiError(404, 'NOT_FOUND', 'That person wasn\'t found.');
|
||||||
|
await accessLog(ctx, me.id, a.id, 'view', req);
|
||||||
|
const [signIns, deletion, consents] = await Promise.all([
|
||||||
|
ctx.db.loginEvent.findMany({ where: { accountId: a.id }, orderBy: { createdAt: 'desc' }, take: 20 }),
|
||||||
|
ctx.db.deletionRequest.findFirst({ where: { accountId: a.id }, orderBy: { requestedAt: 'desc' } }),
|
||||||
|
ctx.db.consentChange.findMany({ where: { accountId: a.id }, orderBy: { createdAt: 'desc' }, take: 20 }),
|
||||||
|
]);
|
||||||
|
return {
|
||||||
|
id: a.id, name: a.name, email: a.email, emailVerified: a.emailVerified, phone: a.phone, role: a.role, status: a.status,
|
||||||
|
twoFactor: a.twoFactorMethod, recoveryCodesLeft: await recoveryCodesLeft(ctx, a.id), news: { email: a.newsEmail, whatsapp: a.newsWhatsApp },
|
||||||
|
noticeVersionAccepted: a.noticeVersionAccepted, createdAt: a.createdAt, lastSignInAt: a.lastSignInAt, lockedUntil: a.lockedUntil,
|
||||||
|
signIns: signIns.map((e) => ({ type: e.type, at: e.createdAt, ip: e.ip })),
|
||||||
|
consents: consents.map((c) => ({ channel: c.channel, granted: c.granted, source: c.source, at: c.createdAt })),
|
||||||
|
deletion: deletion ? { id: deletion.id, status: deletion.status, requestedAt: deletion.requestedAt, products: deletion.products } : null,
|
||||||
|
};
|
||||||
|
}));
|
||||||
|
|
||||||
|
r.post('/people/:id/reset-two-factor', handle(async (req, res) => {
|
||||||
|
const me = await admin(req, res);
|
||||||
|
const id = String(req.params.id);
|
||||||
|
if (id === me.id) throw new ApiError(400, 'SELF', 'Change your own two-factor sign-in on your account page.');
|
||||||
|
await turnOff(ctx, id);
|
||||||
|
await signOutEverywhere(ctx, provider, id);
|
||||||
|
await loginEvent(ctx, id, 'two_factor_off', req, { detail: { by: 'admin' } });
|
||||||
|
await audit(ctx, { actorId: me.id, actorRole: 'admin', action: 'two_factor_reset', targetType: 'account', targetId: id, ip: clientIp(req) });
|
||||||
|
return { reset: true };
|
||||||
|
}));
|
||||||
|
|
||||||
|
r.post('/people/:id/unlock', handle(async (req, res) => {
|
||||||
|
const me = await admin(req, res);
|
||||||
|
await ctx.db.account.update({ where: { id: String(req.params.id) }, data: { lockedUntil: null, failedSignIns: 0 } });
|
||||||
|
await audit(ctx, { actorId: me.id, actorRole: 'admin', action: 'account_unlocked', targetType: 'account', targetId: String(req.params.id), ip: clientIp(req) });
|
||||||
|
return { unlocked: true };
|
||||||
|
}));
|
||||||
|
|
||||||
|
r.put('/people/:id/role', handle(async (req, res) => {
|
||||||
|
const me = await admin(req, res);
|
||||||
|
const role = req.body?.role === 'admin' ? 'admin' : 'member';
|
||||||
|
const id = String(req.params.id);
|
||||||
|
if (id === me.id && role !== 'admin') throw new ApiError(400, 'SELF', 'Ask another admin to change your role.');
|
||||||
|
await ctx.db.account.update({ where: { id }, data: { role } });
|
||||||
|
await audit(ctx, { actorId: me.id, actorRole: 'admin', action: 'role_changed', targetType: 'account', targetId: id, metadata: { role }, ip: clientIp(req) });
|
||||||
|
return { role };
|
||||||
|
}));
|
||||||
|
|
||||||
|
r.put('/people/:id/status', handle(async (req, res) => {
|
||||||
|
const me = await admin(req, res);
|
||||||
|
const id = String(req.params.id);
|
||||||
|
if (id === me.id) throw new ApiError(400, 'SELF', 'You can\'t deactivate your own account here.');
|
||||||
|
const active = req.body?.active === true;
|
||||||
|
await ctx.db.account.update({ where: { id }, data: active ? { status: 'active', deactivatedAt: null } : { status: 'deactivated', deactivatedAt: ctx.now() } });
|
||||||
|
if (!active) await signOutEverywhere(ctx, provider, id);
|
||||||
|
await audit(ctx, { actorId: me.id, actorRole: 'admin', action: active ? 'account_reactivated' : 'account_deactivated', targetType: 'account', targetId: id, ip: clientIp(req) });
|
||||||
|
return { active };
|
||||||
|
}));
|
||||||
|
|
||||||
|
// ─── Deletion requests ─────────────────────────────────────────────────────
|
||||||
|
|
||||||
|
r.get('/deletions', handle(async (req, res) => {
|
||||||
|
await admin(req, res);
|
||||||
|
const list = await ctx.db.deletionRequest.findMany({ where: { status: { in: ['waiting_approval', 'approved'] } }, orderBy: { requestedAt: 'asc' } });
|
||||||
|
const people = await ctx.db.account.findMany({ where: { id: { in: list.map((d) => d.accountId) } } });
|
||||||
|
const byId = new Map(people.map((p) => [p.id, p]));
|
||||||
|
return { items: list.map((d) => ({ id: d.id, status: d.status, requestedAt: d.requestedAt, approvedAt: d.approvedAt, products: d.products, person: { id: d.accountId, name: byId.get(d.accountId)?.name ?? '', email: byId.get(d.accountId)?.email ?? '' } })) };
|
||||||
|
}));
|
||||||
|
|
||||||
|
r.post('/deletions/:id/approve', handle(async (req, res) => {
|
||||||
|
const me = await admin(req, res);
|
||||||
|
if (!(await approveDeletion(ctx, String(req.params.id), me, req))) throw new ApiError(409, 'NOT_WAITING', 'That request isn\'t waiting for approval.');
|
||||||
|
return { approved: true };
|
||||||
|
}));
|
||||||
|
|
||||||
|
r.post('/deletions/:id/cancel', handle(async (req, res) => {
|
||||||
|
const me = await admin(req, res);
|
||||||
|
if (!(await cancelDeletion(ctx, String(req.params.id), me, req))) throw new ApiError(409, 'NOT_WAITING', 'That request isn\'t waiting for approval.');
|
||||||
|
return { cancelled: true };
|
||||||
|
}));
|
||||||
|
|
||||||
|
// ─── Privacy notice ────────────────────────────────────────────────────────
|
||||||
|
|
||||||
|
r.get('/notices', handle(async (req, res) => {
|
||||||
|
await admin(req, res);
|
||||||
|
const list = await ctx.db.privacyNotice.findMany({ orderBy: { version: 'desc' } });
|
||||||
|
return { current: await currentNotice(ctx), items: list };
|
||||||
|
}));
|
||||||
|
|
||||||
|
r.post('/notices', handle(async (req, res) => {
|
||||||
|
const me = await admin(req, res);
|
||||||
|
const title = String(req.body?.title ?? '').trim();
|
||||||
|
const body = String(req.body?.body ?? '').trim();
|
||||||
|
if (!title || body.length < 50) throw new ApiError(400, 'VALIDATION', 'Give the notice a title and its full text.');
|
||||||
|
const n = await publish(ctx, { title, body }, me.id);
|
||||||
|
await audit(ctx, { actorId: me.id, actorRole: 'admin', action: 'notice_published', targetType: 'notice', targetId: String(n.version), ip: clientIp(req) });
|
||||||
|
return n;
|
||||||
|
}));
|
||||||
|
|
||||||
|
// ─── Church profile ────────────────────────────────────────────────────────
|
||||||
|
|
||||||
|
r.get('/church', handle(async (req, res) => {
|
||||||
|
await admin(req, res);
|
||||||
|
return church(ctx);
|
||||||
|
}));
|
||||||
|
|
||||||
|
r.put('/church', handle(async (req, res) => {
|
||||||
|
const me = await admin(req, res);
|
||||||
|
const c = await updateProfile(ctx, req.body ?? {});
|
||||||
|
await audit(ctx, { actorId: me.id, actorRole: 'admin', action: 'church_profile_changed', targetType: 'setting', targetId: 'church_profile', ip: clientIp(req) });
|
||||||
|
return c;
|
||||||
|
}));
|
||||||
|
|
||||||
|
// ─── Settings (sign-in, email, WhatsApp) ────────────────────────────────────
|
||||||
|
|
||||||
|
r.get('/settings', handle(async (req, res) => {
|
||||||
|
await admin(req, res);
|
||||||
|
const out: Record<string, string | boolean | null> = {};
|
||||||
|
for (const key of ADMIN_SETTINGS) {
|
||||||
|
const v = await ctx.settings.get(key);
|
||||||
|
out[key] = SECRET_SETTINGS.has(key) ? !!v : v;
|
||||||
|
}
|
||||||
|
return out;
|
||||||
|
}));
|
||||||
|
|
||||||
|
r.put('/settings', handle(async (req, res) => {
|
||||||
|
const me = await admin(req, res);
|
||||||
|
const changed: string[] = [];
|
||||||
|
for (const [key, value] of Object.entries(req.body ?? {})) {
|
||||||
|
if (!ADMIN_SETTINGS.has(key)) continue;
|
||||||
|
// A secret left empty keeps what's there.
|
||||||
|
if (SECRET_SETTINGS.has(key) && (value === '' || value === true)) continue;
|
||||||
|
await ctx.settings.set(key, value === null || value === undefined ? null : String(value));
|
||||||
|
changed.push(key);
|
||||||
|
}
|
||||||
|
await audit(ctx, { actorId: me.id, actorRole: 'admin', action: 'settings_changed', targetType: 'setting', metadata: { keys: changed }, ip: clientIp(req) });
|
||||||
|
return { changed };
|
||||||
|
}));
|
||||||
|
|
||||||
|
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.' });
|
||||||
|
return { sent: true };
|
||||||
|
}));
|
||||||
|
|
||||||
|
// ─── Linked products ───────────────────────────────────────────────────────
|
||||||
|
|
||||||
|
r.get('/linked-products', handle(async (req, res) => {
|
||||||
|
await admin(req, res);
|
||||||
|
const [listed, links] = await Promise.all([linkedProducts(ctx), ctx.db.productLink.findMany()]);
|
||||||
|
const ids = [...new Set([...listed.map((l) => l.installId), ...links.map((l) => l.installId)])];
|
||||||
|
return {
|
||||||
|
hubConnected: !!(await ctx.settings.get('hub_install_id')),
|
||||||
|
items: ids.map((id) => {
|
||||||
|
const hubRow = listed.find((l) => l.installId === id);
|
||||||
|
const link = links.find((l) => l.installId === id);
|
||||||
|
const product = hubRow?.product ?? link!.product;
|
||||||
|
return { installId: id, product, name: productName(product), url: hubRow?.url ?? link!.url, listed: !!hubRow, connectedAt: link?.connectedAt ?? null, signsInHere: !!link };
|
||||||
|
}),
|
||||||
|
};
|
||||||
|
}));
|
||||||
|
|
||||||
|
r.post('/linked-products/:installId/connect', handle(async (req, res) => {
|
||||||
|
const me = await admin(req, res);
|
||||||
|
await connectTo(ctx, String(req.params.installId), me, req);
|
||||||
|
return { connected: true };
|
||||||
|
}));
|
||||||
|
|
||||||
|
r.post('/linked-products/:installId/disconnect', handle(async (req, res) => {
|
||||||
|
const me = await admin(req, res);
|
||||||
|
return disconnectFrom(ctx, String(req.params.installId), me, req);
|
||||||
|
}));
|
||||||
|
|
||||||
|
// ─── Licence, audit ────────────────────────────────────────────────────────
|
||||||
|
|
||||||
|
r.get('/licence', handle(async (req, res) => {
|
||||||
|
await admin(req, res);
|
||||||
|
const s = await licenceStatus(ctx);
|
||||||
|
return { connected: s.connected, state: s.state, customer: s.claims?.customer ?? null, endsAt: s.endsAt, daysLeft: s.daysLeft, lastHeartbeatAt: await ctx.settings.get('hub_last_heartbeat_at'), lastError: await ctx.settings.get('hub_last_error') };
|
||||||
|
}));
|
||||||
|
|
||||||
|
r.post('/licence', limit(5), handle(async (req, res) => {
|
||||||
|
const me = await admin(req, res);
|
||||||
|
const a = await ctx.db.account.findUniqueOrThrow({ where: { id: me.id } });
|
||||||
|
await connectHub(ctx, String(req.body?.licenceKey ?? ''), { name: a.name, email: a.email });
|
||||||
|
await audit(ctx, { actorId: me.id, actorRole: 'admin', action: 'hub_connected', targetType: 'setting', ip: clientIp(req) });
|
||||||
|
return { connected: true };
|
||||||
|
}));
|
||||||
|
|
||||||
|
r.get('/audit', handle(async (req, res) => {
|
||||||
|
await admin(req, res);
|
||||||
|
const items = await ctx.db.auditLog.findMany({ orderBy: { createdAt: 'desc' }, take: 200 });
|
||||||
|
return { items };
|
||||||
|
}));
|
||||||
|
|
||||||
|
r.get('/deliveries', handle(async (req, res) => {
|
||||||
|
await admin(req, res);
|
||||||
|
const items = await ctx.db.delivery.findMany({ where: { status: { not: 'delivered' } }, orderBy: { createdAt: 'desc' }, take: 100 });
|
||||||
|
return { items: items.map((d) => ({ id: d.id, type: d.type, linkId: d.linkId, status: d.status, attempts: d.attempts, lastError: d.lastError, nextAttemptAt: d.nextAttemptAt })) };
|
||||||
|
}));
|
||||||
|
|
||||||
|
return r;
|
||||||
|
}
|
||||||
@@ -0,0 +1,68 @@
|
|||||||
|
/**
|
||||||
|
* The Express app (docs/ACCOUNTS-1.0-PLAN.md §1). Everything is under /api, so the site and its API
|
||||||
|
* share one address (as Events 2.2): nginx sends /api to this backend and the rest to Next.js.
|
||||||
|
*
|
||||||
|
* /api/health version and database, for monitoring and the Hub
|
||||||
|
* /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/v2/… the pages' API (sign-in steps, account, admin, setup)
|
||||||
|
*/
|
||||||
|
import express from 'express';
|
||||||
|
import type Provider from 'oidc-provider';
|
||||||
|
import type { Ctx } from './context.js';
|
||||||
|
import { sameOrigin, sendError } from './http.js';
|
||||||
|
import { adminRouter } from './admin/routes.js';
|
||||||
|
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 { setupRouter } from './setup/routes.js';
|
||||||
|
import { health } from './hub/client.js';
|
||||||
|
import { appVersion } from './lib/version.js';
|
||||||
|
|
||||||
|
export function createApp(ctx: Ctx, provider: Provider) {
|
||||||
|
const app = express();
|
||||||
|
app.disable('x-powered-by');
|
||||||
|
if (ctx.config.trustProxy) app.set('trust proxy', 1);
|
||||||
|
|
||||||
|
app.use((_req, res, next) => {
|
||||||
|
res.setHeader('X-Content-Type-Options', 'nosniff');
|
||||||
|
res.setHeader('Referrer-Policy', 'same-origin');
|
||||||
|
res.setHeader('X-Frame-Options', 'DENY');
|
||||||
|
res.setHeader('X-Robots-Tag', 'noindex, nofollow');
|
||||||
|
next();
|
||||||
|
});
|
||||||
|
|
||||||
|
app.get('/api/health', async (_req, res) => {
|
||||||
|
const h = await health(ctx);
|
||||||
|
res.status(h.db ? 200 : 503).json({ status: h.db ? 'ok' : 'error', product: 'accounts', version: appVersion(), db: h.db });
|
||||||
|
});
|
||||||
|
|
||||||
|
app.get('/api/static/logout.js', (_req, res) => {
|
||||||
|
res.type('application/javascript').set('Cache-Control', 'public, max-age=3600').send(LOGOUT_JS);
|
||||||
|
});
|
||||||
|
|
||||||
|
// 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', publicRouter(ctx));
|
||||||
|
|
||||||
|
const v2 = express.Router();
|
||||||
|
v2.use(express.json({ limit: '64kb' }));
|
||||||
|
v2.use(sameOrigin(ctx));
|
||||||
|
v2.use(interactionRouter(ctx, provider));
|
||||||
|
v2.use(setupRouter(ctx));
|
||||||
|
v2.use(meRouter(ctx, provider));
|
||||||
|
v2.use('/admin', adminRouter(ctx, provider));
|
||||||
|
v2.use((_req, res) => res.status(404).json({ error: { code: 'NOT_FOUND', message: 'There is no such API endpoint.' } }));
|
||||||
|
app.use('/api/v2', v2);
|
||||||
|
|
||||||
|
app.use((err: unknown, _req: express.Request, res: express.Response, next: express.NextFunction) => {
|
||||||
|
if (res.headersSent) return next(err);
|
||||||
|
const e = err as { type?: string };
|
||||||
|
if (e?.type === 'entity.parse.failed') return res.status(400).json({ error: { code: 'VALIDATION', message: 'The body must be JSON.' } });
|
||||||
|
return sendError(res, err);
|
||||||
|
});
|
||||||
|
return app;
|
||||||
|
}
|
||||||
@@ -0,0 +1,97 @@
|
|||||||
|
/**
|
||||||
|
* The church profile (`crosscode.church/1`), owned by Accounts (docs/ACCOUNTS-1.0-PLAN.md §7,
|
||||||
|
* decision 1). Admins edit it; it brands the sign-in pages; `GET /api/church/v1` serves it to the
|
||||||
|
* church's products; a change sends `church.changed` to each linked product.
|
||||||
|
*
|
||||||
|
* Stored as `church_profile` (the editable fields). `customerId` comes from the licence, `links`
|
||||||
|
* from the linked products, so neither can be typed in wrong.
|
||||||
|
*/
|
||||||
|
import { churchObjectSchema, churchSchema, CHURCH_SCHEMA, type Church } from '@crosscode/contracts';
|
||||||
|
import type { z } from 'zod';
|
||||||
|
import type { Ctx } from '../context.js';
|
||||||
|
import { customerId } from '../hub/licence.js';
|
||||||
|
import { queueCall } from '../links/deliveries.js';
|
||||||
|
|
||||||
|
/** Before the Hub has given a customer id (a site not connected yet). */
|
||||||
|
export const NO_CUSTOMER = '00000000-0000-4000-8000-000000000000';
|
||||||
|
|
||||||
|
/** The fields an admin edits: the contract minus what Accounts fills in itself. */
|
||||||
|
export const profileInputSchema = churchObjectSchema.omit({ schema: true, customerId: true, updatedAt: true, links: true }).partial({
|
||||||
|
shortName: true, campuses: true, serviceTimes: true, social: true,
|
||||||
|
});
|
||||||
|
export type ProfileInput = z.input<typeof profileInputSchema>;
|
||||||
|
|
||||||
|
type Stored = Partial<Omit<Church, 'schema' | 'customerId' | 'links'>> & { updatedAt?: string };
|
||||||
|
|
||||||
|
const DEFAULTS = (ctx: Ctx): Omit<Church, 'schema' | 'customerId' | 'links' | 'updatedAt'> => ({
|
||||||
|
name: 'Our church',
|
||||||
|
shortName: null,
|
||||||
|
timezone: ctx.config.timezone,
|
||||||
|
locale: 'en-ZA',
|
||||||
|
branding: { logoUrl: null, iconUrl: null, colours: { primary: '#1f4e79', accent: '#f2a900' } },
|
||||||
|
campuses: [],
|
||||||
|
serviceTimes: [],
|
||||||
|
contact: { email: null, phone: null, whatsapp: null, address: null },
|
||||||
|
social: [],
|
||||||
|
} as never);
|
||||||
|
|
||||||
|
export async function storedProfile(ctx: Ctx): Promise<Stored> {
|
||||||
|
return ctx.settings.json<Stored>('church_profile', {});
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Whether `/setup` has given the church its name yet. */
|
||||||
|
export async function profileSet(ctx: Ctx): Promise<boolean> {
|
||||||
|
return !!(await storedProfile(ctx)).name;
|
||||||
|
}
|
||||||
|
|
||||||
|
export async function church(ctx: Ctx): Promise<Church> {
|
||||||
|
const stored = await storedProfile(ctx);
|
||||||
|
const links = await ctx.db.productLink.findMany();
|
||||||
|
const url = (product: string) => links.find((l) => l.product === product)?.url ?? null;
|
||||||
|
const merged = {
|
||||||
|
...DEFAULTS(ctx),
|
||||||
|
...stored,
|
||||||
|
schema: CHURCH_SCHEMA,
|
||||||
|
customerId: (await customerId(ctx)) ?? NO_CUSTOMER,
|
||||||
|
updatedAt: stored.updatedAt ?? new Date(0).toISOString(),
|
||||||
|
links: { website: url('website'), events: url('events'), app: url('app'), accounts: ctx.config.publicUrl },
|
||||||
|
};
|
||||||
|
const parsed = churchSchema.safeParse(merged);
|
||||||
|
// Never serve something the contract refuses: fall back to the name and defaults.
|
||||||
|
return parsed.success ? parsed.data : churchSchema.parse({ ...DEFAULTS(ctx), name: stored.name || 'Our church', schema: CHURCH_SCHEMA, customerId: merged.customerId, updatedAt: merged.updatedAt, links: merged.links });
|
||||||
|
}
|
||||||
|
|
||||||
|
export class ProfileError extends Error {
|
||||||
|
status = 400;
|
||||||
|
code = 'VALIDATION';
|
||||||
|
constructor(message: string, public fields: Record<string, string>) {
|
||||||
|
super(message);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Saves an admin's changes (merged onto what's there), and tells the linked products. */
|
||||||
|
export async function updateProfile(ctx: Ctx, input: unknown): Promise<Church> {
|
||||||
|
const current = await storedProfile(ctx);
|
||||||
|
const next = { ...DEFAULTS(ctx), ...current, ...(input && typeof input === 'object' ? input : {}) };
|
||||||
|
const check = profileInputSchema.safeParse(next);
|
||||||
|
if (!check.success) {
|
||||||
|
const fields = Object.fromEntries(check.error.issues.map((i) => [i.path.join('.'), i.message]));
|
||||||
|
throw new ProfileError('Some details need fixing.', fields);
|
||||||
|
}
|
||||||
|
const updatedAt = ctx.now().toISOString();
|
||||||
|
await ctx.settings.set('church_profile', JSON.stringify({ ...check.data, updatedAt }));
|
||||||
|
await queueCall(ctx, 'church.changed', () => ({ schema: CHURCH_SCHEMA, type: 'church.changed', occurredAt: updatedAt, updatedAt }));
|
||||||
|
return church(ctx);
|
||||||
|
}
|
||||||
|
|
||||||
|
/** What the sign-in pages need to look like the church's own (public). */
|
||||||
|
export async function branding(ctx: Ctx) {
|
||||||
|
const c = await church(ctx);
|
||||||
|
return {
|
||||||
|
name: c.name,
|
||||||
|
shortName: c.shortName,
|
||||||
|
logoUrl: c.branding.logoUrl,
|
||||||
|
colours: c.branding.colours,
|
||||||
|
signupEnabled: await ctx.settings.bool('signup_enabled', true),
|
||||||
|
};
|
||||||
|
}
|
||||||
@@ -0,0 +1,29 @@
|
|||||||
|
/**
|
||||||
|
* Everything a request handler or job needs, passed in rather than imported, so tests can run the
|
||||||
|
* whole app against an in-memory database and messenger (tests/support/).
|
||||||
|
*/
|
||||||
|
import type { PrismaClient } from './generated/prisma/client.js';
|
||||||
|
import type { Config } from './lib/config.js';
|
||||||
|
import { Secrets } from './lib/crypto.js';
|
||||||
|
import { LiveMessenger, type Messenger } from './lib/messages.js';
|
||||||
|
import { Settings } from './lib/settings.js';
|
||||||
|
|
||||||
|
export type Db = PrismaClient;
|
||||||
|
|
||||||
|
export type Ctx = {
|
||||||
|
config: Config;
|
||||||
|
db: Db;
|
||||||
|
secrets: Secrets;
|
||||||
|
settings: Settings;
|
||||||
|
messenger: Messenger;
|
||||||
|
now: () => Date;
|
||||||
|
};
|
||||||
|
|
||||||
|
export function createCtx(config: Config, db: Db, opts: { messenger?: Messenger; now?: () => Date } = {}): Ctx {
|
||||||
|
const secrets = new Secrets(config.secret);
|
||||||
|
const partial = { config, db, secrets } as Ctx;
|
||||||
|
partial.settings = new Settings(partial);
|
||||||
|
partial.messenger = opts.messenger ?? new LiveMessenger(partial);
|
||||||
|
partial.now = opts.now ?? (() => new Date());
|
||||||
|
return partial;
|
||||||
|
}
|
||||||
@@ -0,0 +1,53 @@
|
|||||||
|
/**
|
||||||
|
* Shared bits for the API: errors as `{ error: { code, message, fields? } }` (as Events' /api/v2),
|
||||||
|
* async handlers, a same-origin check on everything that changes something, and rate limits.
|
||||||
|
*/
|
||||||
|
import type { NextFunction, Request, RequestHandler, Response } from 'express';
|
||||||
|
import rateLimit from 'express-rate-limit';
|
||||||
|
import type { Ctx } from './context.js';
|
||||||
|
|
||||||
|
export class ApiError extends Error {
|
||||||
|
constructor(public status: number, public code: string, message: string, public fields?: Record<string, string>) {
|
||||||
|
super(message);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
type Fielded = { status?: number; code?: string; fields?: Record<string, string>; message: string };
|
||||||
|
|
||||||
|
/** Known errors from the services carry a status and code; anything else is a 500. */
|
||||||
|
export function sendError(res: Response, e: unknown) {
|
||||||
|
const err = e as Fielded;
|
||||||
|
if (e instanceof ApiError || (typeof err?.status === 'number' && typeof err?.code === 'string')) {
|
||||||
|
return res.status(err.status!).json({ error: { code: err.code, message: err.message, ...(err.fields ? { fields: err.fields } : {}) } });
|
||||||
|
}
|
||||||
|
console.error('[api]', e);
|
||||||
|
return res.status(500).json({ error: { code: 'INTERNAL', message: 'Something went wrong. Please try again.' } });
|
||||||
|
}
|
||||||
|
|
||||||
|
export const handle = (fn: (req: Request, res: Response) => Promise<unknown>): RequestHandler => (req, res) => {
|
||||||
|
fn(req, res).then((out) => {
|
||||||
|
if (out !== undefined && !res.headersSent) res.json(out);
|
||||||
|
}).catch((e) => sendError(res, e));
|
||||||
|
};
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Changes only from the site itself: an `Origin` (or `Referer`) on the site's own address. With
|
||||||
|
* SameSite=Lax cookies this stops another site posting on someone's behalf.
|
||||||
|
*/
|
||||||
|
export function sameOrigin(ctx: Ctx): RequestHandler {
|
||||||
|
const own = new URL(ctx.config.publicUrl).origin;
|
||||||
|
return (req: Request, res: Response, next: NextFunction) => {
|
||||||
|
if (['GET', 'HEAD', 'OPTIONS'].includes(req.method)) return next();
|
||||||
|
const origin = req.get('origin') || (req.get('referer') ? new URL(req.get('referer')!).origin : null);
|
||||||
|
if (origin === own || (!ctx.config.production && origin && /^https?:\/\/localhost(:\d+)?$/.test(origin))) return next();
|
||||||
|
return res.status(403).json({ error: { code: 'FORBIDDEN', message: 'That request didn\'t come from this site.' } });
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
export const limit = (max: number, minutes = 15): RequestHandler => rateLimit({
|
||||||
|
windowMs: minutes * 60e3,
|
||||||
|
limit: max,
|
||||||
|
standardHeaders: true,
|
||||||
|
legacyHeaders: false,
|
||||||
|
handler: (_req, res) => res.status(429).json({ error: { code: 'RATE_LIMITED', message: 'Too many tries. Please wait a few minutes.' } }),
|
||||||
|
});
|
||||||
@@ -0,0 +1,172 @@
|
|||||||
|
/**
|
||||||
|
* Accounts and the Hub (docs/hub-protocol.md §6, protocol v2 from the start, product `accounts`):
|
||||||
|
* register with a `CCA-` licence key (from `/setup`, or by itself from HUB_LICENCE_KEY on a Hub
|
||||||
|
* install), then a signed heartbeat every 15 minutes with aggregate counts only. The reply's
|
||||||
|
* `linkedProducts` (the church's other installs) is cached for Connect.
|
||||||
|
*/
|
||||||
|
import crypto from 'node:crypto';
|
||||||
|
import { hub } from '@crosscode/contracts';
|
||||||
|
import type { Ctx } from '../context.js';
|
||||||
|
import { hubPublicKey, verifyToken } from './licence.js';
|
||||||
|
import { keyPair, saveLinkedProducts } from '../links/store.js';
|
||||||
|
import { appVersion } from '../lib/version.js';
|
||||||
|
|
||||||
|
export const PROTOCOL_VERSION = 2;
|
||||||
|
const TIMEOUT_MS = 15000;
|
||||||
|
const DAY = 24 * 60 * 60 * 1000;
|
||||||
|
const STARTED_AT = Date.now();
|
||||||
|
|
||||||
|
export class HubError extends Error {
|
||||||
|
constructor(message: string, public code: string, public status: number) {
|
||||||
|
super(message);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
async function post(ctx: Ctx, path: string, body: unknown, sign?: { installId: string; secret: string }): Promise<Record<string, unknown>> {
|
||||||
|
const raw = JSON.stringify(body);
|
||||||
|
const headers: Record<string, string> = { 'Content-Type': 'application/json' };
|
||||||
|
if (sign) {
|
||||||
|
const timestamp = ctx.now().toISOString();
|
||||||
|
headers['X-Hub-Install'] = sign.installId;
|
||||||
|
headers['X-Hub-Timestamp'] = timestamp;
|
||||||
|
headers['X-Hub-Signature'] = crypto.createHmac('sha256', sign.secret).update(`${timestamp}.${raw}`).digest('hex');
|
||||||
|
}
|
||||||
|
let res: Response;
|
||||||
|
try {
|
||||||
|
res = await fetch(`${ctx.config.hubUrl}${path}`, { method: 'POST', headers, body: raw, signal: AbortSignal.timeout(TIMEOUT_MS) });
|
||||||
|
} catch (e) {
|
||||||
|
throw new HubError(`The Hub (${ctx.config.hubUrl}) could not be reached: ${(e as Error).message}`, 'HUB_UNREACHABLE', 502);
|
||||||
|
}
|
||||||
|
const data = (await res.json().catch(() => ({}))) as Record<string, unknown>;
|
||||||
|
if (!res.ok) throw new HubError(String(data.message || `The Hub answered ${res.status}`), String(data.code || 'HUB_ERROR'), res.status);
|
||||||
|
return data;
|
||||||
|
}
|
||||||
|
|
||||||
|
const version = appVersion;
|
||||||
|
|
||||||
|
export async function health(ctx: Ctx) {
|
||||||
|
let db = true;
|
||||||
|
try {
|
||||||
|
await ctx.db.$queryRawUnsafe('SELECT 1');
|
||||||
|
} catch {
|
||||||
|
db = false;
|
||||||
|
}
|
||||||
|
return {
|
||||||
|
uptimeSeconds: Math.round((Date.now() - STARTED_AT) / 1000),
|
||||||
|
db,
|
||||||
|
jobs: { mode: ctx.config.jobsEnabled ? 'queue' : 'off', failedLast24h: 0 },
|
||||||
|
lastBackupAt: null,
|
||||||
|
disk: null,
|
||||||
|
errorsLast24h: null,
|
||||||
|
pendingMigrations: 0,
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Aggregate counts only (hub.accountsStatsSchema): never anyone's details. */
|
||||||
|
export async function stats(ctx: Ctx) {
|
||||||
|
const since = new Date(ctx.now().getTime() - 90 * DAY);
|
||||||
|
const active = { status: 'active' as const };
|
||||||
|
const [total, active90d, email, whatsapp, totp, off, links] = await Promise.all([
|
||||||
|
ctx.db.account.count({ where: active }),
|
||||||
|
ctx.db.account.count({ where: { ...active, lastSignInAt: { gte: since } } }),
|
||||||
|
ctx.db.account.count({ where: { ...active, twoFactorMethod: 'email' } }),
|
||||||
|
ctx.db.account.count({ where: { ...active, twoFactorMethod: 'whatsapp' } }),
|
||||||
|
ctx.db.account.count({ where: { ...active, twoFactorMethod: 'totp' } }),
|
||||||
|
ctx.db.account.count({ where: { ...active, twoFactorMethod: null } }),
|
||||||
|
ctx.db.productLink.count(),
|
||||||
|
]);
|
||||||
|
return { accounts: { total, active90d }, twoFactor: { email, whatsapp, totp, off }, linkedProducts: links };
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Register with a licence key (from /setup or HUB_LICENCE_KEY). */
|
||||||
|
export async function connect(ctx: Ctx, licenceKey: string, adminContact: { name: string | null; email: string | null } | null) {
|
||||||
|
if (!/^https?:\/\//.test(ctx.config.publicUrl)) throw new HubError('ACCOUNTS_URL isn\'t set.', 'NO_SITE_URL', 400);
|
||||||
|
const { publicKeyPem } = await keyPair(ctx);
|
||||||
|
const profile = await ctx.settings.json<{ name?: string }>('church_profile', {});
|
||||||
|
const body = {
|
||||||
|
protocolVersion: PROTOCOL_VERSION,
|
||||||
|
licenceKey: licenceKey.trim().toUpperCase(),
|
||||||
|
product: 'accounts',
|
||||||
|
install: {
|
||||||
|
name: profile.name || 'Accounts',
|
||||||
|
url: ctx.config.publicUrl,
|
||||||
|
adminContact,
|
||||||
|
version: version(),
|
||||||
|
timezone: ctx.config.timezone,
|
||||||
|
server: { node: process.versions.node, postgres: null, os: `${process.platform}` },
|
||||||
|
features: { whatsapp: await ctx.messenger.whatsappReady() },
|
||||||
|
publicKey: publicKeyPem,
|
||||||
|
},
|
||||||
|
};
|
||||||
|
const check = hub.registerRequestSchema.safeParse(body);
|
||||||
|
if (!check.success) throw new HubError(`That doesn't look like an Accounts licence key (CCA-…).`, 'INVALID_REQUEST', 400);
|
||||||
|
const data = await post(ctx, '/api/installs/register', check.data);
|
||||||
|
const claims = verifyToken(String(data.licence || ''), hubPublicKey(ctx));
|
||||||
|
if (!claims || claims.installId !== data.installId) throw new HubError('The Hub answered with a licence this install can\'t verify. Is HUB_URL right?', 'BAD_LICENCE', 502);
|
||||||
|
await ctx.settings.setMany({
|
||||||
|
hub_install_id: String(data.installId),
|
||||||
|
hub_install_secret: String(data.installSecret),
|
||||||
|
hub_licence: String(data.licence),
|
||||||
|
hub_last_heartbeat_at: ctx.now().toISOString(),
|
||||||
|
hub_last_error: null,
|
||||||
|
hub_public_key_status: 'matches',
|
||||||
|
});
|
||||||
|
await saveLinkedProducts(ctx, data.linkedProducts);
|
||||||
|
return claims;
|
||||||
|
}
|
||||||
|
|
||||||
|
/** The `hub-heartbeat` job. Skips quietly when not connected. */
|
||||||
|
export async function heartbeat(ctx: Ctx) {
|
||||||
|
const installId = await ctx.settings.get('hub_install_id');
|
||||||
|
const secret = await ctx.settings.get('hub_install_secret');
|
||||||
|
if (!installId || !secret) return { skipped: 'not connected' };
|
||||||
|
const status = await ctx.settings.get('hub_public_key_status');
|
||||||
|
const { publicKeyPem } = await keyPair(ctx);
|
||||||
|
const body = {
|
||||||
|
protocolVersion: PROTOCOL_VERSION,
|
||||||
|
product: 'accounts',
|
||||||
|
version: version(),
|
||||||
|
health: await health(ctx),
|
||||||
|
stats: await stats(ctx),
|
||||||
|
...(status === 'saved' || status === 'matches' ? {} : { publicKey: publicKeyPem }),
|
||||||
|
};
|
||||||
|
try {
|
||||||
|
const data = await post(ctx, '/api/installs/heartbeat', body, { installId, secret });
|
||||||
|
const claims = verifyToken(String(data.licence || ''), hubPublicKey(ctx));
|
||||||
|
await ctx.settings.setMany({
|
||||||
|
...(claims && claims.installId === installId ? { hub_licence: String(data.licence) } : {}),
|
||||||
|
hub_last_heartbeat_at: ctx.now().toISOString(),
|
||||||
|
hub_last_error: null,
|
||||||
|
...(typeof data.publicKeyStatus === 'string' ? { hub_public_key_status: data.publicKeyStatus } : {}),
|
||||||
|
});
|
||||||
|
await saveLinkedProducts(ctx, data.linkedProducts);
|
||||||
|
return { ok: true };
|
||||||
|
} catch (e) {
|
||||||
|
const err = e as HubError;
|
||||||
|
await ctx.settings.set('hub_last_error', `${ctx.now().toISOString()} ${err.code || ''} ${err.message}`.slice(0, 500));
|
||||||
|
if (err.code === 'INSTALL_NOT_FOUND') {
|
||||||
|
await ctx.settings.setMany({ hub_install_id: null, hub_install_secret: null, hub_licence: null });
|
||||||
|
return { ok: false, reconnect: true };
|
||||||
|
}
|
||||||
|
throw e;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/** A Hub install registers by itself on first start from HUB_LICENCE_KEY (as Events 2.3). Never throws. */
|
||||||
|
export async function connectFromEnv(ctx: Ctx, { attempts = 5, delayMs = 60_000 } = {}) {
|
||||||
|
const key = ctx.config.hubLicenceKey;
|
||||||
|
if (!key) return { connected: false, reason: 'no_key' };
|
||||||
|
for (let i = 1; i <= attempts; i++) {
|
||||||
|
try {
|
||||||
|
if (await ctx.settings.get('hub_install_id')) return { connected: false, reason: 'already' };
|
||||||
|
await connect(ctx, key, ctx.config.hubAdminName || ctx.config.hubAdminEmail ? { name: ctx.config.hubAdminName, email: ctx.config.hubAdminEmail } : null);
|
||||||
|
return { connected: true };
|
||||||
|
} catch (e) {
|
||||||
|
const err = e as HubError;
|
||||||
|
console.warn(`[hub] Registering with HUB_LICENCE_KEY failed (attempt ${i} of ${attempts}):`, err.message);
|
||||||
|
if (err.status >= 400 && err.status < 500) return { connected: false, reason: err.code };
|
||||||
|
if (i < attempts) await new Promise((r) => setTimeout(r, delayMs).unref?.());
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return { connected: false, reason: 'unreachable' };
|
||||||
|
}
|
||||||
@@ -0,0 +1,69 @@
|
|||||||
|
/**
|
||||||
|
* The licence token from the Hub (docs/hub-protocol.md §4), checked offline with the Hub's public
|
||||||
|
* key, as Cross Events does. **Accounts never goes read-only** (docs/ACCOUNTS-1.0-PLAN.md §9,
|
||||||
|
* decision 4): a lapsed licence only shows admins a banner, so members can always sign in.
|
||||||
|
*/
|
||||||
|
import crypto from 'node:crypto';
|
||||||
|
import type { Ctx } from '../context.js';
|
||||||
|
|
||||||
|
/** The production Hub's licence key (as in Cross Events' hub/publicKey.js). HUB_PUBLIC_KEY overrides it. */
|
||||||
|
export const PRODUCTION_PUBLIC_KEY = 'MCowBQYDK2VwAyEAcKpEo/JdS96wR3r9yh8uFUxBlzPUd2YKbC60fNRUhoU=';
|
||||||
|
|
||||||
|
const DAY = 24 * 60 * 60 * 1000;
|
||||||
|
|
||||||
|
/** A public key as PEM, however it was pasted (real line breaks, "\n", one line, or only the base64). */
|
||||||
|
export function normalisePem(input: string | null | undefined): string | null {
|
||||||
|
const text = String(input || '').replace(/\\n/g, '\n').trim();
|
||||||
|
if (!text) return null;
|
||||||
|
const body = text.replace(/-----BEGIN PUBLIC KEY-----/, '').replace(/-----END PUBLIC KEY-----/, '').replace(/\s+/g, '');
|
||||||
|
if (!/^[A-Za-z0-9+/]+={0,2}$/.test(body)) return text;
|
||||||
|
return `-----BEGIN PUBLIC KEY-----\n${body.match(/.{1,64}/g)!.join('\n')}\n-----END PUBLIC KEY-----\n`;
|
||||||
|
}
|
||||||
|
|
||||||
|
export function hubPublicKey(ctx: Pick<Ctx, 'config'>): string | null {
|
||||||
|
return normalisePem(ctx.config.hubPublicKey) || normalisePem(PRODUCTION_PUBLIC_KEY);
|
||||||
|
}
|
||||||
|
|
||||||
|
export type LicenceClaims = {
|
||||||
|
v: number; installId: string; customerId?: string; product?: string; customer: string; status: string;
|
||||||
|
licenceExpiresAt: string | null; validUntil: string; graceDays: number;
|
||||||
|
};
|
||||||
|
|
||||||
|
export function verifyToken(token: string | null | undefined, pem: string | null): LicenceClaims | null {
|
||||||
|
if (!pem) return null;
|
||||||
|
const parts = String(token || '').split('.');
|
||||||
|
if (parts.length !== 3 || parts[0] !== 'hel1') return null;
|
||||||
|
try {
|
||||||
|
const ok = crypto.verify(null, Buffer.from(`${parts[0]}.${parts[1]}`), crypto.createPublicKey(pem), Buffer.from(parts[2]!, 'base64url'));
|
||||||
|
return ok ? (JSON.parse(Buffer.from(parts[1]!, 'base64url').toString('utf8')) as LicenceClaims) : null;
|
||||||
|
} catch {
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
export type LicenceState = 'active' | 'grace' | 'lapsed' | 'revoked' | 'unlicensed';
|
||||||
|
|
||||||
|
/** The state for verified claims. Pure. */
|
||||||
|
export function stateFor(claims: LicenceClaims | null, installId: string | null, now = new Date()): { state: LicenceState; endsAt: Date | null; daysLeft: number | null } {
|
||||||
|
if (!claims || (installId && claims.installId !== installId)) return { state: 'unlicensed', endsAt: null, daysLeft: null };
|
||||||
|
const ends = [claims.licenceExpiresAt, claims.validUntil].filter(Boolean).map((d) => new Date(d!));
|
||||||
|
const endsAt = ends.length ? new Date(Math.min(...ends.map((d) => d.getTime()))) : null;
|
||||||
|
const graceEnds = endsAt ? new Date(endsAt.getTime() + (claims.graceDays || 0) * DAY) : null;
|
||||||
|
if (claims.status === 'revoked') return { state: 'revoked', endsAt, daysLeft: null };
|
||||||
|
if (claims.status === 'suspended') return { state: 'lapsed', endsAt, daysLeft: null };
|
||||||
|
if (!endsAt || now < endsAt) return { state: 'active', endsAt, daysLeft: null };
|
||||||
|
if (graceEnds && now < graceEnds) return { state: 'grace', endsAt, daysLeft: Math.ceil((graceEnds.getTime() - now.getTime()) / DAY) };
|
||||||
|
return { state: 'lapsed', endsAt, daysLeft: null };
|
||||||
|
}
|
||||||
|
|
||||||
|
export async function licenceStatus(ctx: Ctx) {
|
||||||
|
const [installId, token] = await Promise.all([ctx.settings.get('hub_install_id'), ctx.settings.get('hub_licence')]);
|
||||||
|
const claims = verifyToken(token, hubPublicKey(ctx));
|
||||||
|
const valid = claims && claims.installId === installId ? claims : null;
|
||||||
|
return { connected: !!installId, installId, claims: valid, ...stateFor(valid, installId, ctx.now()) };
|
||||||
|
}
|
||||||
|
|
||||||
|
/** The church's Hub customer id (the same for every product), once the licence says it. */
|
||||||
|
export async function customerId(ctx: Ctx): Promise<string | null> {
|
||||||
|
return (await licenceStatus(ctx)).claims?.customerId ?? null;
|
||||||
|
}
|
||||||
@@ -0,0 +1,43 @@
|
|||||||
|
/**
|
||||||
|
* Starts Accounts: database, OIDC provider, HTTP server, jobs, and (on a Hub install) registering
|
||||||
|
* with the Hub from HUB_LICENCE_KEY.
|
||||||
|
*/
|
||||||
|
import 'dotenv/config';
|
||||||
|
import { PrismaPg } from '@prisma/adapter-pg';
|
||||||
|
import { PrismaClient } from './generated/prisma/client.js';
|
||||||
|
import { createApp } from './app.js';
|
||||||
|
import { createCtx } from './context.js';
|
||||||
|
import { connectFromEnv, heartbeat } from './hub/client.js';
|
||||||
|
import { startJobs } from './jobs.js';
|
||||||
|
import { loadConfig } from './lib/config.js';
|
||||||
|
import { createProvider } from './oidc/provider.js';
|
||||||
|
|
||||||
|
async function main() {
|
||||||
|
const config = loadConfig();
|
||||||
|
const url = process.env.DATABASE_URL;
|
||||||
|
if (!url) throw new Error('DATABASE_URL isn\'t set.');
|
||||||
|
const db = new PrismaClient({ adapter: new PrismaPg({ connectionString: url, connectionTimeoutMillis: 5000 }) });
|
||||||
|
const ctx = createCtx(config, db);
|
||||||
|
const provider = await createProvider(ctx);
|
||||||
|
const app = createApp(ctx, provider);
|
||||||
|
const server = app.listen(config.port, () => console.log(`[accounts] Listening on ${config.port} (${config.publicUrl}).`));
|
||||||
|
const stopJobs = await startJobs(ctx, url);
|
||||||
|
|
||||||
|
connectFromEnv(ctx).then((r) => {
|
||||||
|
if (r.connected) heartbeat(ctx).catch(() => {});
|
||||||
|
}).catch(() => {});
|
||||||
|
|
||||||
|
const stop = async () => {
|
||||||
|
server.close();
|
||||||
|
await stopJobs();
|
||||||
|
await db.$disconnect();
|
||||||
|
process.exit(0);
|
||||||
|
};
|
||||||
|
process.on('SIGTERM', stop);
|
||||||
|
process.on('SIGINT', stop);
|
||||||
|
}
|
||||||
|
|
||||||
|
main().catch((e) => {
|
||||||
|
console.error('[accounts] Failed to start:', e);
|
||||||
|
process.exit(1);
|
||||||
|
});
|
||||||
@@ -0,0 +1,246 @@
|
|||||||
|
/**
|
||||||
|
* One sign-in, step by step (docs/ACCOUNTS-1.0-PLAN.md §5). oidc-provider hands us an interaction
|
||||||
|
* (`uid`); `PendingSignIn` keeps where the person is in it, so every step — password, 2FA, setting
|
||||||
|
* up 2FA, verifying a new email, the privacy notice, the news question, and a password reset in
|
||||||
|
* between — carries on to the product they came from.
|
||||||
|
*
|
||||||
|
* password ─┬─ verify_email ─ two_factor | setup_two_factor ─ notice ─ news ─ done
|
||||||
|
* sign-up ──┘
|
||||||
|
*
|
||||||
|
* A session that's already signed in skips the password (the provider asked again only because a
|
||||||
|
* product wants 2FA, or the notice changed).
|
||||||
|
*/
|
||||||
|
import { ACR_MFA } from '@crosscode/contracts';
|
||||||
|
import type { Request } from 'express';
|
||||||
|
import type Provider from 'oidc-provider';
|
||||||
|
import type { Ctx } from '../context.js';
|
||||||
|
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 { loginEvent } from '../lib/audit.js';
|
||||||
|
import { dummyHash, hashPassword, needsRehash, passwordProblem, verifyPassword } from '../lib/passwords.js';
|
||||||
|
import { accept as acceptNotice, currentNotice } from '../privacy/notice.js';
|
||||||
|
import { productName } from '../oidc/clients.js';
|
||||||
|
|
||||||
|
export type Stage = 'password' | 'verify_email' | 'two_factor' | 'setup_two_factor' | 'notice' | 'news' | 'done';
|
||||||
|
|
||||||
|
export class FlowError extends Error {
|
||||||
|
constructor(message: string, public code = 'INVALID', public status = 400, public fields?: Record<string, string>) {
|
||||||
|
super(message);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
type Details = Awaited<ReturnType<Provider['interactionDetails']>>;
|
||||||
|
|
||||||
|
const PENDING_MINUTES = 60;
|
||||||
|
|
||||||
|
export function mfaRequested(details: Details): boolean {
|
||||||
|
return String(details.params.acr_values ?? '').split(' ').includes(ACR_MFA);
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Where someone goes next, from what's done so far. */
|
||||||
|
export async function nextStage(ctx: Ctx, pending: PendingSignIn, details: Details): Promise<Stage> {
|
||||||
|
if (!pending.accountId) return 'password';
|
||||||
|
const a = await ctx.db.account.findUnique({ where: { id: pending.accountId } });
|
||||||
|
if (!a || a.status !== 'active') return 'password';
|
||||||
|
if (!a.emailVerified) return 'verify_email';
|
||||||
|
const adminNeeds2fa = a.role === 'admin' && (await ctx.settings.bool('two_factor_required_for_admins', true));
|
||||||
|
const wants2fa = !!a.twoFactorMethod || mfaRequested(details) || adminNeeds2fa;
|
||||||
|
if (wants2fa && !pending.amr.includes('mfa')) return a.twoFactorMethod ? 'two_factor' : 'setup_two_factor';
|
||||||
|
if (a.noticeVersionAccepted < (await currentNotice(ctx)).version) return 'notice';
|
||||||
|
if (!a.newsAskedAt) return 'news';
|
||||||
|
return 'done';
|
||||||
|
}
|
||||||
|
|
||||||
|
/** The interaction's pending sign-in, made on first sight (signed in already: the session's account and how it signed in). */
|
||||||
|
export async function pendingFor(ctx: Ctx, details: Details): Promise<PendingSignIn> {
|
||||||
|
const existing = await ctx.db.pendingSignIn.findUnique({ where: { uid: details.uid } });
|
||||||
|
if (existing && existing.expiresAt > ctx.now()) return existing;
|
||||||
|
const reasons = (details.prompt?.reasons ?? []) as string[];
|
||||||
|
// Only skip the password when the provider asked again for one of our own reasons.
|
||||||
|
const trustSession = !!details.session?.accountId && reasons.every((r) => r === 'mfa_required' || r === 'account_needs_attention');
|
||||||
|
const data = {
|
||||||
|
uid: details.uid,
|
||||||
|
accountId: trustSession ? details.session!.accountId : null,
|
||||||
|
stage: 'password',
|
||||||
|
amr: trustSession ? ((details.session as { amr?: string[] }).amr ?? ['pwd']) : [],
|
||||||
|
attempts: 0,
|
||||||
|
expiresAt: new Date(ctx.now().getTime() + PENDING_MINUTES * 60e3),
|
||||||
|
};
|
||||||
|
return ctx.db.pendingSignIn.upsert({ where: { uid: details.uid }, create: data, update: data });
|
||||||
|
}
|
||||||
|
|
||||||
|
async function save(ctx: Ctx, pending: PendingSignIn, data: Partial<PendingSignIn>): Promise<PendingSignIn> {
|
||||||
|
return ctx.db.pendingSignIn.update({ where: { uid: pending.uid }, data: data as never });
|
||||||
|
}
|
||||||
|
|
||||||
|
async function account(ctx: Ctx, pending: PendingSignIn): Promise<Account> {
|
||||||
|
const a = pending.accountId ? await ctx.db.account.findUnique({ where: { id: pending.accountId } }) : null;
|
||||||
|
if (!a || a.status !== 'active') throw new FlowError('Please sign in again.', 'RESTART', 409);
|
||||||
|
return a;
|
||||||
|
}
|
||||||
|
|
||||||
|
/** What the page for the current step needs. Sends the code when a step needs one and none was sent. */
|
||||||
|
export async function describe(ctx: Ctx, details: Details, pending: PendingSignIn) {
|
||||||
|
const stage = await nextStage(ctx, pending, details);
|
||||||
|
if (stage !== pending.stage) pending = await save(ctx, pending, { stage, codeHash: null, codeSentAt: null, attempts: 0 });
|
||||||
|
const client = details.params.client_id ? await ctx.db.productLink.findUnique({ where: { installId: String(details.params.client_id) } }) : null;
|
||||||
|
const base = {
|
||||||
|
uid: details.uid,
|
||||||
|
stage,
|
||||||
|
product: client ? productName(client.product) : 'your account',
|
||||||
|
signupEnabled: await ctx.settings.bool('signup_enabled', true),
|
||||||
|
mfaRequested: mfaRequested(details),
|
||||||
|
loginHint: typeof details.params.login_hint === 'string' ? details.params.login_hint : null,
|
||||||
|
};
|
||||||
|
if (stage === 'password' || stage === 'done') return base;
|
||||||
|
const a = await account(ctx, pending);
|
||||||
|
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 });
|
||||||
|
}
|
||||||
|
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');
|
||||||
|
}
|
||||||
|
if (stage === 'setup_two_factor') {
|
||||||
|
extra.methods = ['totp', 'email', ...((await ctx.messenger.whatsappReady()) && a.phone ? ['whatsapp'] : [])];
|
||||||
|
extra.why = a.role === 'admin' ? 'admin' : 'product';
|
||||||
|
}
|
||||||
|
if (stage === 'notice') {
|
||||||
|
const n = await currentNotice(ctx);
|
||||||
|
extra.notice = { version: n.version, title: n.title, body: n.body };
|
||||||
|
extra.updated = a.noticeVersionAccepted > 0;
|
||||||
|
}
|
||||||
|
return { ...base, ...extra };
|
||||||
|
}
|
||||||
|
|
||||||
|
// ─── Steps ────────────────────────────────────────────────────────────────────
|
||||||
|
|
||||||
|
const CODE_ATTEMPTS = 5;
|
||||||
|
|
||||||
|
export async function submitPassword(ctx: Ctx, pending: PendingSignIn, input: { email?: unknown; password?: unknown; remember?: unknown }, req?: Request) {
|
||||||
|
const email = normaliseEmail(input.email);
|
||||||
|
const password = String(input.password ?? '');
|
||||||
|
const a = email ? await ctx.db.account.findUnique({ where: { email } }) : null;
|
||||||
|
const generic = new FlowError('That email address and password don\'t match.', 'BAD_CREDENTIALS', 401);
|
||||||
|
if (!a || a.status !== 'active' || !a.passwordHash) {
|
||||||
|
await verifyPassword(password, await dummyHash());
|
||||||
|
throw generic;
|
||||||
|
}
|
||||||
|
if (isLocked(ctx, a)) throw new FlowError(`Too many tries. Wait ${15} minutes, or reset your password.`, 'LOCKED', 429);
|
||||||
|
if (!(await verifyPassword(password, a.passwordHash))) {
|
||||||
|
await signInFailed(ctx, a, req);
|
||||||
|
throw generic;
|
||||||
|
}
|
||||||
|
await signInSucceeded(ctx, a);
|
||||||
|
if (needsRehash(a.passwordHash)) await ctx.db.account.update({ where: { id: a.id }, data: { passwordHash: await hashPassword(password) } });
|
||||||
|
return save(ctx, pending, { accountId: a.id, amr: ['pwd'], remember: input.remember === true, stage: 'password', codeHash: null, codeSentAt: null, attempts: 0 });
|
||||||
|
}
|
||||||
|
|
||||||
|
export async function signUp(ctx: Ctx, pending: PendingSignIn, input: Record<string, unknown>) {
|
||||||
|
if (!(await ctx.settings.bool('signup_enabled', true))) throw new FlowError('New accounts are made by the church\'s office. Please ask them.', 'SIGNUP_OFF', 403);
|
||||||
|
const fields: Record<string, string> = {};
|
||||||
|
const name = String(input.name ?? '').trim().replace(/\s+/g, ' ');
|
||||||
|
const email = normaliseEmail(input.email);
|
||||||
|
const phone = input.phone ? normalisePhone(input.phone) : null;
|
||||||
|
if (name.length < 2 || name.length > 200) fields.name = 'Enter your name.';
|
||||||
|
const ep = emailProblem(email);
|
||||||
|
if (ep) fields.email = ep;
|
||||||
|
const pp = passwordProblem(input.password);
|
||||||
|
if (pp) fields.password = pp;
|
||||||
|
if (input.phone && !phone) fields.phone = 'Enter a phone number like 082 123 4567.';
|
||||||
|
if (input.acceptNotice !== true) fields.acceptNotice = 'Please read and accept the privacy notice.';
|
||||||
|
if (Object.keys(fields).length) throw new FlowError('Some details need fixing.', 'VALIDATION', 400, fields);
|
||||||
|
if (await ctx.db.account.findUnique({ where: { email } })) {
|
||||||
|
throw new FlowError('There\'s already an account with that email address. Sign in, or reset your password if you\'ve forgotten it.', 'EXISTS', 409, { email: 'Already has an account.' });
|
||||||
|
}
|
||||||
|
const notice = await currentNotice(ctx);
|
||||||
|
const parts = name.split(' ');
|
||||||
|
const a = await ctx.db.account.create({
|
||||||
|
data: {
|
||||||
|
name, givenName: parts[0] ?? null, familyName: parts.length > 1 ? parts.slice(1).join(' ') : null, email, phone,
|
||||||
|
passwordHash: await hashPassword(String(input.password)), noticeVersionAccepted: notice.version, lastSignInAt: ctx.now(),
|
||||||
|
},
|
||||||
|
});
|
||||||
|
await ctx.db.noticeAcceptance.create({ data: { accountId: a.id, version: notice.version, acceptedAt: ctx.now() } });
|
||||||
|
await setNewsConsent(ctx, a, { email: input.newsEmail === true, whatsapp: input.newsWhatsApp === true && !!phone }, 'sign_up');
|
||||||
|
await loginEvent(ctx, a.id, 'account_created');
|
||||||
|
return save(ctx, pending, { accountId: a.id, amr: ['pwd'], remember: input.remember === true, codeHash: null, codeSentAt: null, attempts: 0 });
|
||||||
|
}
|
||||||
|
|
||||||
|
async function checkCode(ctx: Ctx, pending: PendingSignIn, code: unknown) {
|
||||||
|
if (!pending.codeHash || !pending.codeSentAt || ctx.now().getTime() - pending.codeSentAt.getTime() > CODE_MINUTES * 60e3) {
|
||||||
|
throw new FlowError('That code has expired. Send a new one.', 'CODE_EXPIRED', 400);
|
||||||
|
}
|
||||||
|
if (pending.attempts >= CODE_ATTEMPTS) throw new FlowError('Too many wrong codes. Send a new one.', 'TOO_MANY', 429);
|
||||||
|
if (!codeMatches(code, pending.codeHash)) {
|
||||||
|
await save(ctx, pending, { attempts: pending.attempts + 1 });
|
||||||
|
throw new FlowError('That code isn\'t right.', 'BAD_CODE', 400);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
export async function resendCode(ctx: Ctx, pending: PendingSignIn) {
|
||||||
|
if (pending.codeSentAt && ctx.now().getTime() - pending.codeSentAt.getTime() < 30e3) throw new FlowError('Wait half a minute before asking for another code.', 'TOO_SOON', 429);
|
||||||
|
return save(ctx, pending, { codeHash: null, codeSentAt: null, attempts: 0 });
|
||||||
|
}
|
||||||
|
|
||||||
|
export async function verifyEmail(ctx: Ctx, pending: PendingSignIn, code: unknown) {
|
||||||
|
await checkCode(ctx, pending, code);
|
||||||
|
await ctx.db.account.update({ where: { id: pending.accountId! }, data: { emailVerified: true } });
|
||||||
|
return save(ctx, pending, { codeHash: null, codeSentAt: null, attempts: 0 });
|
||||||
|
}
|
||||||
|
|
||||||
|
export async function twoFactor(ctx: Ctx, pending: PendingSignIn, input: { code?: unknown; recoveryCode?: unknown }, req?: Request) {
|
||||||
|
const a = await account(ctx, pending);
|
||||||
|
if (input.recoveryCode) {
|
||||||
|
if (!(await useRecoveryCode(ctx, a, input.recoveryCode, req))) throw new FlowError('That recovery code isn\'t right, or it was used already.', 'BAD_CODE', 400);
|
||||||
|
} else if (a.twoFactorMethod === 'totp') {
|
||||||
|
if (pending.attempts >= CODE_ATTEMPTS) throw new FlowError('Too many wrong codes. Wait a few minutes.', 'TOO_MANY', 429);
|
||||||
|
if (!(await verifyTotp(ctx, a, input.code))) {
|
||||||
|
await save(ctx, pending, { attempts: pending.attempts + 1 });
|
||||||
|
throw new FlowError('That code isn\'t right. Check your authenticator app\'s time is correct.', 'BAD_CODE', 400);
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
await checkCode(ctx, pending, input.code);
|
||||||
|
}
|
||||||
|
return save(ctx, pending, { amr: accessAfterTwoFactor(pending.amr), codeHash: null, codeSentAt: null, attempts: 0 });
|
||||||
|
}
|
||||||
|
|
||||||
|
export async function setupStart(ctx: Ctx, pending: PendingSignIn, method: unknown) {
|
||||||
|
const a = await account(ctx, pending);
|
||||||
|
const started = await startTwoFactorSetup(ctx, a, method);
|
||||||
|
await save(ctx, pending, { pendingTotpSecret: started.encryptedSecret, codeHash: started.codeHash, codeSentAt: started.codeHash ? ctx.now() : null, attempts: 0 });
|
||||||
|
return started.forScreen;
|
||||||
|
}
|
||||||
|
|
||||||
|
export async function setupConfirm(ctx: Ctx, pending: PendingSignIn, input: { method?: unknown; code?: unknown }, req?: Request) {
|
||||||
|
const a = await account(ctx, pending);
|
||||||
|
const recoveryCodes = await confirmTwoFactorSetup(ctx, a, { method: input.method, code: input.code, pendingSecret: pending.pendingTotpSecret, codeHash: pending.codeHash, codeSentAt: pending.codeSentAt }, req);
|
||||||
|
const next = await save(ctx, pending, { amr: accessAfterTwoFactor(pending.amr), pendingTotpSecret: null, codeHash: null, codeSentAt: null, attempts: 0 });
|
||||||
|
return { pending: next, recoveryCodes };
|
||||||
|
}
|
||||||
|
|
||||||
|
export async function notice(ctx: Ctx, pending: PendingSignIn, version: unknown) {
|
||||||
|
const current = await currentNotice(ctx);
|
||||||
|
if (Number(version) !== current.version) throw new FlowError('The notice changed while you were reading it. Please read it again.', 'STALE', 409);
|
||||||
|
await acceptNotice(ctx, pending.accountId!, current.version);
|
||||||
|
return pending;
|
||||||
|
}
|
||||||
|
|
||||||
|
export async function news(ctx: Ctx, pending: PendingSignIn, input: { email?: unknown; whatsapp?: unknown }) {
|
||||||
|
const a = await account(ctx, pending);
|
||||||
|
await setNewsConsent(ctx, a, { email: input.email === true, whatsapp: input.whatsapp === true && !!a.phone }, 'news_question');
|
||||||
|
return pending;
|
||||||
|
}
|
||||||
|
|
||||||
|
/** The result oidc-provider needs to finish the sign-in. */
|
||||||
|
export function loginResult(pending: PendingSignIn) {
|
||||||
|
const mfa = pending.amr.includes('mfa');
|
||||||
|
return { login: { accountId: pending.accountId!, amr: pending.amr, acr: mfa ? ACR_MFA : 'pwd', remember: pending.remember } };
|
||||||
|
}
|
||||||
@@ -0,0 +1,151 @@
|
|||||||
|
/**
|
||||||
|
* The sign-in pages' API (`/api/v2/interaction/:uid/…`), forgot / reset password, and Accounts'
|
||||||
|
* own sign-in for the account page (`/api/self/…`, an OIDC client of itself).
|
||||||
|
*/
|
||||||
|
import crypto from 'node:crypto';
|
||||||
|
import express, { type Request, type Response } from 'express';
|
||||||
|
import type Provider from 'oidc-provider';
|
||||||
|
import { decodeState, encodeState, safeReturnPath } from '@crosscode/contracts';
|
||||||
|
import type { Ctx } from '../context.js';
|
||||||
|
import { ApiError, handle, limit } from '../http.js';
|
||||||
|
import { loginEvent } from '../lib/audit.js';
|
||||||
|
import { hashToken, randomToken } from '../lib/crypto.js';
|
||||||
|
import { hashPassword, passwordProblem } from '../lib/passwords.js';
|
||||||
|
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';
|
||||||
|
|
||||||
|
const RESET_MINUTES = 60;
|
||||||
|
|
||||||
|
export function interactionRouter(ctx: Ctx, provider: Provider) {
|
||||||
|
const r = express.Router();
|
||||||
|
|
||||||
|
/** The interaction behind `uid`, from this browser's interaction cookie. */
|
||||||
|
async function load(req: Request, res: Response) {
|
||||||
|
let details;
|
||||||
|
try {
|
||||||
|
details = await provider.interactionDetails(req, res);
|
||||||
|
} catch {
|
||||||
|
throw new ApiError(410, 'EXPIRED', 'This sign-in has expired. Go back to the site you came from and sign in again.');
|
||||||
|
}
|
||||||
|
if (details.uid !== req.params.uid) throw new ApiError(410, 'EXPIRED', 'This sign-in has expired. Go back to the site you came from and sign in again.');
|
||||||
|
return { details, pending: await flow.pendingFor(ctx, details) };
|
||||||
|
}
|
||||||
|
|
||||||
|
/** After a step: the next step's page data, or the address to finish at (the product). */
|
||||||
|
async function next(req: Request, res: Response, extra: Record<string, unknown> = {}) {
|
||||||
|
const { details, pending } = await load(req, res);
|
||||||
|
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 } });
|
||||||
|
await ctx.db.pendingSignIn.deleteMany({ where: { uid: pending.uid } });
|
||||||
|
return { stage: 'done', redirectTo, ...extra };
|
||||||
|
}
|
||||||
|
|
||||||
|
const step = (fn: (req: Request, res: Response, pending: Awaited<ReturnType<typeof load>>['pending']) => Promise<Record<string, unknown> | void>) =>
|
||||||
|
handle(async (req, res) => {
|
||||||
|
const { pending } = await load(req, res);
|
||||||
|
const extra = (await fn(req, res, pending)) ?? {};
|
||||||
|
return next(req, res, extra);
|
||||||
|
});
|
||||||
|
|
||||||
|
// Where oidc-provider sends the browser (its cookie's path): on to the sign-in page.
|
||||||
|
r.get('/interaction/:uid', (req, res) => {
|
||||||
|
const uid = String(req.params.uid);
|
||||||
|
res.redirect(303, /^[A-Za-z0-9_-]{10,64}$/.test(uid) ? `/signin?uid=${uid}` : '/account');
|
||||||
|
});
|
||||||
|
// The page's state for the current step.
|
||||||
|
r.get('/interaction/:uid/state', handle(async (req, res) => next(req, res)));
|
||||||
|
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/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);
|
||||||
|
return flow.setupStart(ctx, pending, req.body?.method);
|
||||||
|
}));
|
||||||
|
r.post('/interaction/:uid/two-factor/setup/confirm', limit(20), step(async (req, _res, p) => {
|
||||||
|
const { recoveryCodes } = await flow.setupConfirm(ctx, p, req.body ?? {}, req);
|
||||||
|
return { recoveryCodes };
|
||||||
|
}));
|
||||||
|
r.post('/interaction/:uid/notice', step(async (req, _res, p) => { await flow.notice(ctx, p, req.body?.version); }));
|
||||||
|
r.post('/interaction/:uid/news', step(async (req, _res, p) => { await flow.news(ctx, p, req.body ?? {}); }));
|
||||||
|
r.post('/interaction/:uid/cancel', handle(async (req, res) => {
|
||||||
|
await load(req, res);
|
||||||
|
const redirectTo = await provider.interactionResult(req, res, { error: 'access_denied', error_description: 'The person cancelled signing in.' }, { mergeWithLastSubmission: false });
|
||||||
|
return { stage: 'done', redirectTo };
|
||||||
|
}));
|
||||||
|
|
||||||
|
// ─── Forgot / reset password ───────────────────────────────────────────────
|
||||||
|
|
||||||
|
r.post('/password/forgot', limit(5), handle(async (req) => {
|
||||||
|
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).
|
||||||
|
if (a && a.status === 'active') {
|
||||||
|
const token = randomToken();
|
||||||
|
const uid = typeof req.body?.uid === 'string' && /^[A-Za-z0-9_-]{10,64}$/.test(req.body.uid) ? req.body.uid : null;
|
||||||
|
await ctx.db.emailToken.create({ data: { accountId: a.id, purpose: 'reset_password', tokenHash: hashToken(token), interactionUid: uid, expiresAt: new Date(ctx.now().getTime() + RESET_MINUTES * 60e3) } });
|
||||||
|
await ctx.messenger.email({
|
||||||
|
to: a.email,
|
||||||
|
subject: 'Reset your password',
|
||||||
|
text: `Someone (we hope you) asked to reset the password for your account.\n\nChoose a new password here (the link works for ${RESET_MINUTES} minutes):\n${ctx.config.publicUrl}/reset?token=${token}\n\nIf you didn't ask, you can ignore this email: your password stays the same.`,
|
||||||
|
});
|
||||||
|
}
|
||||||
|
return { sent: true };
|
||||||
|
}));
|
||||||
|
|
||||||
|
r.post('/password/reset', limit(10), handle(async (req) => {
|
||||||
|
const token = String(req.body?.token ?? '');
|
||||||
|
const row = token ? await ctx.db.emailToken.findUnique({ where: { tokenHash: hashToken(token) } }) : null;
|
||||||
|
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 } });
|
||||||
|
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 };
|
||||||
|
}));
|
||||||
|
|
||||||
|
return r;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* The account page signs in like any product: `/api/self/signin?returnTo=/account` starts an
|
||||||
|
* authorization request for `accounts-self`; the callback only needs the session the sign-in made.
|
||||||
|
*/
|
||||||
|
export function selfRouter(ctx: Ctx) {
|
||||||
|
const r = express.Router();
|
||||||
|
const callback = `${ctx.config.publicUrl}${SELF_CALLBACK}`;
|
||||||
|
|
||||||
|
r.get('/signin', (req, res) => {
|
||||||
|
const nonce = crypto.randomBytes(16).toString('base64url');
|
||||||
|
const verifier = crypto.randomBytes(32).toString('base64url');
|
||||||
|
const challenge = crypto.createHash('sha256').update(verifier).digest('base64url');
|
||||||
|
const state = encodeState({ nonce, returnTo: safeReturnPath(req.query.returnTo, '/account') });
|
||||||
|
res.cookie('acc_self', nonce, { httpOnly: true, sameSite: 'lax', secure: ctx.config.production, maxAge: 3600e3, path: '/api/self' });
|
||||||
|
const url = new URL(`${issuerOf(ctx)}/auth`);
|
||||||
|
url.search = new URLSearchParams({
|
||||||
|
client_id: SELF_CLIENT_ID, response_type: 'code', scope: 'openid', redirect_uri: callback, state,
|
||||||
|
code_challenge: challenge, code_challenge_method: 'S256', nonce,
|
||||||
|
...(req.query.prompt === 'login' ? { prompt: 'login' } : {}),
|
||||||
|
...(req.query.acr === 'mfa' ? { acr_values: 'mfa' } : {}),
|
||||||
|
}).toString();
|
||||||
|
res.redirect(url.toString());
|
||||||
|
});
|
||||||
|
|
||||||
|
r.get('/callback', (req, res) => {
|
||||||
|
const state = decodeState(req.query.state);
|
||||||
|
const cookies = Object.fromEntries(String(req.get('cookie') || '').split(';').map((c) => c.trim().split('=')).filter((p) => p.length === 2)) as Record<string, string>;
|
||||||
|
res.clearCookie('acc_self', { path: '/api/self' });
|
||||||
|
if (!state || state.nonce !== cookies.acc_self || req.query.error) return res.redirect('/account');
|
||||||
|
return res.redirect(safeReturnPath(state.returnTo, '/account'));
|
||||||
|
});
|
||||||
|
|
||||||
|
return r;
|
||||||
|
}
|
||||||
@@ -0,0 +1,54 @@
|
|||||||
|
/**
|
||||||
|
* Background jobs on pg-boss (as Cross Events): one run per schedule however many processes run,
|
||||||
|
* and timers in this process if the queue can't start. JOBS_ENABLED=false turns them all off.
|
||||||
|
*/
|
||||||
|
import PgBoss from 'pg-boss';
|
||||||
|
import type { Ctx } from './context.js';
|
||||||
|
import { heartbeat } from './hub/client.js';
|
||||||
|
import { runDue } from './links/deliveries.js';
|
||||||
|
import { deleteExpired } from './oidc/adapter.js';
|
||||||
|
import { runDeletionJob } from './privacy/deletion.js';
|
||||||
|
import { runExportsJob } from './privacy/export.js';
|
||||||
|
|
||||||
|
type Job = { name: string; cron: string; everyMs: number; run: (ctx: Ctx) => Promise<unknown> };
|
||||||
|
|
||||||
|
export const JOBS: Job[] = [
|
||||||
|
{ name: 'deliveries', cron: '* * * * *', everyMs: 60e3, run: (ctx) => runDue(ctx) },
|
||||||
|
{ name: 'exports', cron: '*/5 * * * *', everyMs: 5 * 60e3, run: (ctx) => runExportsJob(ctx) },
|
||||||
|
{ name: 'deletions', cron: '*/15 * * * *', everyMs: 15 * 60e3, run: (ctx) => runDeletionJob(ctx) },
|
||||||
|
{ name: 'hub-heartbeat', cron: '*/15 * * * *', everyMs: 15 * 60e3, run: (ctx) => heartbeat(ctx) },
|
||||||
|
{
|
||||||
|
name: 'cleanup', cron: '17 * * * *', everyMs: 3600e3,
|
||||||
|
run: async (ctx) => {
|
||||||
|
const now = ctx.now();
|
||||||
|
const [oidc, pending, tokens, nonces] = 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) } } }),
|
||||||
|
]);
|
||||||
|
return { oidc: oidc.count, pending: pending.count, tokens: tokens.count, nonces: nonces.count };
|
||||||
|
},
|
||||||
|
},
|
||||||
|
];
|
||||||
|
|
||||||
|
export async function startJobs(ctx: Ctx, connectionString: string): Promise<() => Promise<void>> {
|
||||||
|
if (!ctx.config.jobsEnabled) return async () => {};
|
||||||
|
const tz = ctx.config.timezone;
|
||||||
|
try {
|
||||||
|
const boss = new PgBoss({ connectionString, schema: 'pgboss_accounts', application_name: 'crosscode-accounts-jobs' });
|
||||||
|
boss.on('error', (e: Error) => console.warn('[jobs]', e.message));
|
||||||
|
await boss.start();
|
||||||
|
for (const job of JOBS) {
|
||||||
|
await boss.createQueue(job.name, { policy: 'stately' }).catch(() => {});
|
||||||
|
await boss.schedule(job.name, job.cron, undefined, { tz });
|
||||||
|
await boss.work(job.name, async () => job.run(ctx));
|
||||||
|
}
|
||||||
|
console.log(`[jobs] Job queue started: ${JOBS.map((j) => j.name).join(', ')}.`);
|
||||||
|
return async () => { await boss.stop({ graceful: true }); };
|
||||||
|
} catch (e) {
|
||||||
|
console.warn('[jobs] Job queue unavailable, using timers:', (e as Error).message);
|
||||||
|
const timers = JOBS.map((job) => setInterval(() => { job.run(ctx).catch((err) => console.warn(`[jobs] ${job.name}:`, (err as Error).message)); }, job.everyMs));
|
||||||
|
return async () => { timers.forEach(clearInterval); };
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,48 @@
|
|||||||
|
/**
|
||||||
|
* The admin audit log, the per-person sign-in log and the access log. Logging never breaks the
|
||||||
|
* action it records.
|
||||||
|
*/
|
||||||
|
import type { Request } from 'express';
|
||||||
|
import type { Ctx } from '../context.js';
|
||||||
|
|
||||||
|
export function clientIp(req: Request | undefined): string | null {
|
||||||
|
return req ? (req.ip ?? req.socket?.remoteAddress ?? null) : null;
|
||||||
|
}
|
||||||
|
|
||||||
|
export async function audit(ctx: Ctx, entry: { actorId: string | null; actorRole: string; action: string; targetType: string; targetId?: string | null; metadata?: object; ip?: string | null }) {
|
||||||
|
try {
|
||||||
|
await ctx.db.auditLog.create({ data: { ...entry, targetId: entry.targetId ?? null, metadata: (entry.metadata ?? undefined) as never, ip: entry.ip ?? null } });
|
||||||
|
} catch (e) {
|
||||||
|
console.error('[audit]', (e as Error).message);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
export type LoginEventType =
|
||||||
|
| 'sign_in' | 'sign_in_failed' | 'locked' | 'password_reset' | 'password_changed' | 'two_factor_on' | 'two_factor_off'
|
||||||
|
| 'recovery_code_used' | 'recovery_codes_replaced' | 'signed_out_everywhere' | 'email_changed' | 'account_created';
|
||||||
|
|
||||||
|
export async function loginEvent(ctx: Ctx, accountId: string | null, type: LoginEventType, req?: Request, extra: { clientId?: string | null; detail?: object } = {}) {
|
||||||
|
try {
|
||||||
|
await ctx.db.loginEvent.create({
|
||||||
|
data: {
|
||||||
|
accountId,
|
||||||
|
type,
|
||||||
|
clientId: extra.clientId ?? null,
|
||||||
|
ip: clientIp(req),
|
||||||
|
userAgent: req?.get('user-agent')?.slice(0, 300) ?? null,
|
||||||
|
detail: (extra.detail ?? undefined) as never,
|
||||||
|
createdAt: ctx.now(),
|
||||||
|
},
|
||||||
|
});
|
||||||
|
} catch (e) {
|
||||||
|
console.error('[login-event]', (e as Error).message);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
export async function accessLog(ctx: Ctx, actorId: string, targetId: string, action: 'view' | 'export', req?: Request) {
|
||||||
|
try {
|
||||||
|
await ctx.db.accessLog.create({ data: { actorId, targetId, action, ip: clientIp(req), createdAt: ctx.now() } });
|
||||||
|
} catch (e) {
|
||||||
|
console.error('[access-log]', (e as Error).message);
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,51 @@
|
|||||||
|
/**
|
||||||
|
* The server's settings, from the environment (`.env`, built from `env.template.json`). Read once;
|
||||||
|
* tests pass their own with `loadConfig({...})`.
|
||||||
|
*/
|
||||||
|
export type Config = {
|
||||||
|
/** The public address, e.g. https://accounts.hopefamily.co.za (no trailing slash). */
|
||||||
|
publicUrl: string;
|
||||||
|
port: number;
|
||||||
|
/** Encrypts secrets at rest and signs cookies. Generated on the server, never sent anywhere. */
|
||||||
|
secret: string;
|
||||||
|
production: boolean;
|
||||||
|
/** Behind nginx/frp: trust X-Forwarded-* (as Events' TRUST_PROXY). */
|
||||||
|
trustProxy: boolean;
|
||||||
|
hubUrl: string;
|
||||||
|
hubLicenceKey: string | null;
|
||||||
|
hubPublicKey: string | null;
|
||||||
|
hubAdminName: string | null;
|
||||||
|
hubAdminEmail: string | null;
|
||||||
|
timezone: string;
|
||||||
|
smtp: { host: string; port: number; user: string; pass: string; from: string; secure: boolean } | null;
|
||||||
|
/** Local testing only: linked products on http or private addresses. */
|
||||||
|
allowPrivateLinks: boolean;
|
||||||
|
jobsEnabled: boolean;
|
||||||
|
};
|
||||||
|
|
||||||
|
const bool = (v: string | undefined, def: boolean) => (v === undefined || v === '' ? def : String(v).toLowerCase() === 'true');
|
||||||
|
|
||||||
|
export function loadConfig(env: Record<string, string | undefined> = process.env): Config {
|
||||||
|
const publicUrl = String(env.ACCOUNTS_URL || env.PUBLIC_URL || 'http://localhost:3200').replace(/\/+$/, '');
|
||||||
|
const production = env.NODE_ENV === 'production';
|
||||||
|
const secret = env.ACCOUNTS_SECRET || '';
|
||||||
|
if (production && secret.length < 32) throw new Error('ACCOUNTS_SECRET must be set (at least 32 characters) in production.');
|
||||||
|
return {
|
||||||
|
publicUrl,
|
||||||
|
port: Number(env.PORT || 5200),
|
||||||
|
secret: secret || 'development-only-secret-change-me-0123456789',
|
||||||
|
production,
|
||||||
|
trustProxy: bool(env.TRUST_PROXY, production),
|
||||||
|
hubUrl: String(env.HUB_URL || 'https://hub.crosscode.co.za').replace(/\/+$/, ''),
|
||||||
|
hubLicenceKey: env.HUB_LICENCE_KEY?.trim() || null,
|
||||||
|
hubPublicKey: env.HUB_PUBLIC_KEY?.trim() || null,
|
||||||
|
hubAdminName: env.HUB_ADMIN_NAME?.trim() || null,
|
||||||
|
hubAdminEmail: env.HUB_ADMIN_EMAIL?.trim() || null,
|
||||||
|
timezone: env.APP_TIMEZONE || 'Africa/Johannesburg',
|
||||||
|
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,
|
||||||
|
allowPrivateLinks: bool(env.LINKS_ALLOW_PRIVATE, false),
|
||||||
|
jobsEnabled: bool(env.JOBS_ENABLED, true),
|
||||||
|
};
|
||||||
|
}
|
||||||
@@ -0,0 +1,53 @@
|
|||||||
|
/**
|
||||||
|
* Secrets at rest (AES-256-GCM, as Events' utils/encryption.js), tokens and codes.
|
||||||
|
* The key comes from ACCOUNTS_SECRET; encrypted values start with "enc:".
|
||||||
|
*/
|
||||||
|
import crypto from 'node:crypto';
|
||||||
|
|
||||||
|
const SENTINEL = 'enc:';
|
||||||
|
|
||||||
|
export class Secrets {
|
||||||
|
private readonly key: Buffer;
|
||||||
|
|
||||||
|
constructor(secret: string) {
|
||||||
|
this.key = crypto.scryptSync(secret, 'crosscode-accounts-aes256gcm-v1', 32);
|
||||||
|
}
|
||||||
|
|
||||||
|
encrypt(plain: string): string {
|
||||||
|
if (plain.startsWith(SENTINEL)) return plain;
|
||||||
|
const iv = crypto.randomBytes(12);
|
||||||
|
const cipher = crypto.createCipheriv('aes-256-gcm', this.key, iv);
|
||||||
|
const data = Buffer.concat([cipher.update(plain, 'utf8'), cipher.final()]);
|
||||||
|
return `${SENTINEL}${iv.toString('hex')}:${cipher.getAuthTag().toString('hex')}:${data.toString('hex')}`;
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Throws if the value was changed or encrypted with another key. */
|
||||||
|
decrypt(value: string): string {
|
||||||
|
if (!value.startsWith(SENTINEL)) return value;
|
||||||
|
const [iv, tag, data] = value.slice(SENTINEL.length).split(':');
|
||||||
|
if (!iv || !tag || data === undefined) throw new Error('Invalid encrypted value');
|
||||||
|
const decipher = crypto.createDecipheriv('aes-256-gcm', this.key, Buffer.from(iv, 'hex'));
|
||||||
|
decipher.setAuthTag(Buffer.from(tag, 'hex'));
|
||||||
|
return Buffer.concat([decipher.update(Buffer.from(data, 'hex')), decipher.final()]).toString('utf8');
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Keys for signing cookies (oidc-provider and our own), derived so they're stable per install. */
|
||||||
|
cookieKeys(): string[] {
|
||||||
|
return [crypto.createHmac('sha256', this.key).update('cookies-v1').digest('base64url')];
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/** A random token for a link sent by email (32 bytes, base64url). */
|
||||||
|
export const randomToken = () => crypto.randomBytes(32).toString('base64url');
|
||||||
|
|
||||||
|
/** A 6-digit code sent by email or WhatsApp. */
|
||||||
|
export const randomCode = () => String(crypto.randomInt(0, 1_000_000)).padStart(6, '0');
|
||||||
|
|
||||||
|
/** What's stored for a token or code: only its SHA-256. */
|
||||||
|
export const hashToken = (token: string) => crypto.createHash('sha256').update(token).digest('hex');
|
||||||
|
|
||||||
|
export function safeEqual(a: string, b: string): boolean {
|
||||||
|
const x = Buffer.from(a);
|
||||||
|
const y = Buffer.from(b);
|
||||||
|
return x.length === y.length && crypto.timingSafeEqual(x, y);
|
||||||
|
}
|
||||||
@@ -0,0 +1,94 @@
|
|||||||
|
/**
|
||||||
|
* Email (SMTP, from the admin's settings or the server's .env) and WhatsApp (WAWP, as Cross
|
||||||
|
* Events). In tests a `MemoryMessenger` keeps what would have been sent.
|
||||||
|
*/
|
||||||
|
import nodemailer from 'nodemailer';
|
||||||
|
import type { Ctx } from '../context.js';
|
||||||
|
|
||||||
|
export type Email = { to: string; subject: string; text: string };
|
||||||
|
export type WhatsApp = { to: string; text: string };
|
||||||
|
|
||||||
|
export interface Messenger {
|
||||||
|
email(msg: Email): Promise<void>;
|
||||||
|
whatsapp(msg: WhatsApp): Promise<void>;
|
||||||
|
/** Whether WhatsApp is set up, so it's offered as a 2FA method. */
|
||||||
|
whatsappReady(): Promise<boolean>;
|
||||||
|
}
|
||||||
|
|
||||||
|
/** 0821234567 / +27 82 123 4567 → 27821234567 (South African mobiles; others as given, digits only). */
|
||||||
|
export function waNumber(raw: string): string | null {
|
||||||
|
let d = String(raw || '').replace(/\D/g, '');
|
||||||
|
if (d.startsWith('0') && d.length === 10) d = `27${d.slice(1)}`;
|
||||||
|
return d.length >= 10 && d.length <= 15 ? d : null;
|
||||||
|
}
|
||||||
|
|
||||||
|
export class LiveMessenger implements Messenger {
|
||||||
|
constructor(private readonly ctx: Pick<Ctx, 'settings' | 'config'>) {}
|
||||||
|
|
||||||
|
private async smtp() {
|
||||||
|
const s = this.ctx.settings;
|
||||||
|
const host = (await s.get('smtp_host')) || this.ctx.config.smtp?.host;
|
||||||
|
if (!host) return null;
|
||||||
|
const port = Number((await s.get('smtp_port')) || this.ctx.config.smtp?.port || 587);
|
||||||
|
return {
|
||||||
|
transport: nodemailer.createTransport({
|
||||||
|
host,
|
||||||
|
port,
|
||||||
|
secure: (await s.get('smtp_secure')) === 'true' || (this.ctx.config.smtp?.secure ?? port === 465),
|
||||||
|
auth: { user: (await s.get('smtp_user')) || this.ctx.config.smtp?.user || '', pass: (await s.get('smtp_pass')) || this.ctx.config.smtp?.pass || '' },
|
||||||
|
}),
|
||||||
|
from: (await s.get('smtp_from')) || this.ctx.config.smtp?.from || '',
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
async email(msg: Email): Promise<void> {
|
||||||
|
const smtp = await this.smtp();
|
||||||
|
if (!smtp) {
|
||||||
|
if (this.ctx.config.production) throw new Error('Email isn\'t set up (Admin → Email and WhatsApp).');
|
||||||
|
console.log(`[email] (no SMTP) to ${msg.to}: ${msg.subject}\n${msg.text}`);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
const church = (await this.ctx.settings.json<{ name?: string }>('church_profile', {})).name;
|
||||||
|
await smtp.transport.sendMail({ from: church ? `"${church.replace(/"/g, '')}" <${smtp.from}>` : smtp.from, to: msg.to, subject: msg.subject, text: msg.text });
|
||||||
|
}
|
||||||
|
|
||||||
|
async whatsappReady(): Promise<boolean> {
|
||||||
|
return !!((await this.ctx.settings.get('wawp_access_token')) && (await this.ctx.settings.get('wawp_instance_id')));
|
||||||
|
}
|
||||||
|
|
||||||
|
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}).`);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
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); }
|
||||||
|
async whatsappReady() { return this.whatsappOn; }
|
||||||
|
/** 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)];
|
||||||
|
const m = /\b(\d{6})\b/.exec(all[all.length - 1] ?? '');
|
||||||
|
return m ? m[1]! : null;
|
||||||
|
}
|
||||||
|
/** The last link sent to `to` (tests). */
|
||||||
|
lastLink(to: string): string | null {
|
||||||
|
const e = this.emails.filter((x) => x.to === to).at(-1);
|
||||||
|
const m = /(https?:\/\/\S+)/.exec(e?.text ?? '');
|
||||||
|
return m ? m[1]! : null;
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,43 @@
|
|||||||
|
/**
|
||||||
|
* Passwords: Argon2id with Events' parameters. bcrypt hashes (imported from Cross Events, whose
|
||||||
|
* older accounts still have them) verify too, and `needsRehash` tells the caller to store a new
|
||||||
|
* Argon2id hash after a successful sign-in, as Events does.
|
||||||
|
*/
|
||||||
|
import argon2 from '@node-rs/argon2';
|
||||||
|
import bcrypt from 'bcryptjs';
|
||||||
|
|
||||||
|
const OPTIONS = { algorithm: 2 as const /* Argon2id */, memoryCost: 19456, timeCost: 2, parallelism: 1 };
|
||||||
|
const PREFIX = `$argon2id$v=19$m=${OPTIONS.memoryCost},t=${OPTIONS.timeCost},p=${OPTIONS.parallelism}$`;
|
||||||
|
|
||||||
|
export const MIN_PASSWORD_LENGTH = 8;
|
||||||
|
export const MAX_PASSWORD_LENGTH = 200;
|
||||||
|
|
||||||
|
export function hashPassword(password: string): Promise<string> {
|
||||||
|
return argon2.hash(password, OPTIONS);
|
||||||
|
}
|
||||||
|
|
||||||
|
export async function verifyPassword(password: string, hash: string | null | undefined): Promise<boolean> {
|
||||||
|
if (!hash) return false;
|
||||||
|
try {
|
||||||
|
if (hash.startsWith('$argon2')) return await argon2.verify(hash, password);
|
||||||
|
if (/^\$2[aby]\$/.test(hash)) return await bcrypt.compare(password, hash);
|
||||||
|
} catch {
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
|
||||||
|
export const needsRehash = (hash: string) => !hash.startsWith(PREFIX);
|
||||||
|
|
||||||
|
/** A hash to compare against when there's no account, so a missing account takes as long. */
|
||||||
|
let dummy: Promise<string> | null = null;
|
||||||
|
export function dummyHash(): Promise<string> {
|
||||||
|
if (!dummy) dummy = hashPassword('no-such-account-placeholder');
|
||||||
|
return dummy;
|
||||||
|
}
|
||||||
|
|
||||||
|
export function passwordProblem(password: unknown): string | null {
|
||||||
|
if (typeof password !== 'string' || password.length < MIN_PASSWORD_LENGTH) return `Use at least ${MIN_PASSWORD_LENGTH} characters.`;
|
||||||
|
if (password.length > MAX_PASSWORD_LENGTH) return 'That password is too long.';
|
||||||
|
return null;
|
||||||
|
}
|
||||||
@@ -0,0 +1,27 @@
|
|||||||
|
/**
|
||||||
|
* Recovery codes: 10 single-use codes each time 2FA is turned on, shown once ("abcd-efgh-jkmn").
|
||||||
|
* Only their hashes are kept. Letters that are easy to mix up are left out.
|
||||||
|
*/
|
||||||
|
import crypto from 'node:crypto';
|
||||||
|
import { hashToken } from './crypto.js';
|
||||||
|
|
||||||
|
const ALPHABET = 'abcdefghjkmnpqrstuvwxyz23456789';
|
||||||
|
export const RECOVERY_CODE_COUNT = 10;
|
||||||
|
|
||||||
|
function one(): string {
|
||||||
|
const chars = Array.from({ length: 12 }, () => ALPHABET[crypto.randomInt(0, ALPHABET.length)]);
|
||||||
|
return `${chars.slice(0, 4).join('')}-${chars.slice(4, 8).join('')}-${chars.slice(8).join('')}`;
|
||||||
|
}
|
||||||
|
|
||||||
|
export function newRecoveryCodes(): { codes: string[]; hashes: string[] } {
|
||||||
|
const codes = Array.from({ length: RECOVERY_CODE_COUNT }, one);
|
||||||
|
return { codes, hashes: codes.map(hashRecoveryCode) };
|
||||||
|
}
|
||||||
|
|
||||||
|
/** As typed: case and dashes or spaces don't matter. */
|
||||||
|
export function normaliseRecoveryCode(input: unknown): string {
|
||||||
|
const clean = String(input ?? '').toLowerCase().replace(/[^a-z0-9]/g, '');
|
||||||
|
return clean.length === 12 ? `${clean.slice(0, 4)}-${clean.slice(4, 8)}-${clean.slice(8)}` : clean;
|
||||||
|
}
|
||||||
|
|
||||||
|
export const hashRecoveryCode = (code: string) => hashToken(normaliseRecoveryCode(code));
|
||||||
@@ -0,0 +1,71 @@
|
|||||||
|
/**
|
||||||
|
* Site settings in `AppSetting` (key → string). Secret ones are encrypted at rest. A short cache
|
||||||
|
* keeps sign-in pages from reading the table on every request.
|
||||||
|
*/
|
||||||
|
import type { Ctx } from '../context.js';
|
||||||
|
|
||||||
|
/** Encrypted at rest; never sent to the browser. */
|
||||||
|
export const SECRET_SETTINGS = new Set(['smtp_pass', 'wawp_access_token', 'hub_install_secret', 'hub_private_key', 'oidc_jwks']);
|
||||||
|
|
||||||
|
/** The settings an admin may read and change through the generic settings API. */
|
||||||
|
export const ADMIN_SETTINGS = new Set([
|
||||||
|
'signup_enabled', 'two_factor_required_for_admins', 'session_days',
|
||||||
|
'smtp_host', 'smtp_port', 'smtp_user', 'smtp_pass', 'smtp_from', 'smtp_secure',
|
||||||
|
'wawp_access_token', 'wawp_instance_id',
|
||||||
|
]);
|
||||||
|
|
||||||
|
const TTL_MS = 30_000;
|
||||||
|
|
||||||
|
export class Settings {
|
||||||
|
private cache = new Map<string, { value: string | null; at: number }>();
|
||||||
|
|
||||||
|
constructor(private readonly ctx: Pick<Ctx, 'db' | 'secrets'>) {}
|
||||||
|
|
||||||
|
async get(key: string): Promise<string | null> {
|
||||||
|
const hit = this.cache.get(key);
|
||||||
|
if (hit && Date.now() - hit.at < TTL_MS) return hit.value;
|
||||||
|
const row = await this.ctx.db.appSetting.findUnique({ where: { key } });
|
||||||
|
let value = row?.value ?? null;
|
||||||
|
if (value !== null && SECRET_SETTINGS.has(key)) {
|
||||||
|
try {
|
||||||
|
value = this.ctx.secrets.decrypt(value);
|
||||||
|
} catch {
|
||||||
|
value = null;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
this.cache.set(key, { value, at: Date.now() });
|
||||||
|
return value;
|
||||||
|
}
|
||||||
|
|
||||||
|
async bool(key: string, fallback: boolean): Promise<boolean> {
|
||||||
|
const v = await this.get(key);
|
||||||
|
return v === null || v === '' ? fallback : v === 'true';
|
||||||
|
}
|
||||||
|
|
||||||
|
async json<T>(key: string, fallback: T): Promise<T> {
|
||||||
|
const v = await this.get(key);
|
||||||
|
if (!v) return fallback;
|
||||||
|
try {
|
||||||
|
return JSON.parse(v) as T;
|
||||||
|
} catch {
|
||||||
|
return fallback;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
async set(key: string, value: string | null): Promise<void> {
|
||||||
|
if (value === null) await this.ctx.db.appSetting.deleteMany({ where: { key } });
|
||||||
|
else {
|
||||||
|
const stored = SECRET_SETTINGS.has(key) ? this.ctx.secrets.encrypt(value) : value;
|
||||||
|
await this.ctx.db.appSetting.upsert({ where: { key }, update: { value: stored }, create: { key, value: stored } });
|
||||||
|
}
|
||||||
|
this.cache.delete(key);
|
||||||
|
}
|
||||||
|
|
||||||
|
async setMany(values: Record<string, string | null>): Promise<void> {
|
||||||
|
for (const [k, v] of Object.entries(values)) await this.set(k, v);
|
||||||
|
}
|
||||||
|
|
||||||
|
forget(): void {
|
||||||
|
this.cache.clear();
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,71 @@
|
|||||||
|
/**
|
||||||
|
* Authenticator-app codes (RFC 6238: SHA-1, 6 digits, 30 seconds), as Cross Events 2.3 and the Hub,
|
||||||
|
* so secrets moved from Events keep working. `matchStep` returns the step a code belongs to, so a
|
||||||
|
* code that was used once is refused the second time.
|
||||||
|
*/
|
||||||
|
import crypto from 'node:crypto';
|
||||||
|
|
||||||
|
const BASE32 = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ234567';
|
||||||
|
export const STEP = 30;
|
||||||
|
|
||||||
|
export function base32Encode(buf: Uint8Array): string {
|
||||||
|
let bits = 0;
|
||||||
|
let value = 0;
|
||||||
|
let out = '';
|
||||||
|
for (const byte of buf) {
|
||||||
|
value = (value << 8) | byte;
|
||||||
|
bits += 8;
|
||||||
|
while (bits >= 5) {
|
||||||
|
out += BASE32[(value >>> (bits - 5)) & 31];
|
||||||
|
bits -= 5;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if (bits > 0) out += BASE32[(value << (5 - bits)) & 31];
|
||||||
|
return out;
|
||||||
|
}
|
||||||
|
|
||||||
|
export function base32Decode(str: string): Buffer {
|
||||||
|
let bits = 0;
|
||||||
|
let value = 0;
|
||||||
|
const out: number[] = [];
|
||||||
|
for (const ch of String(str).toUpperCase().replace(/=+$/, '')) {
|
||||||
|
const idx = BASE32.indexOf(ch);
|
||||||
|
if (idx === -1) continue;
|
||||||
|
value = (value << 5) | idx;
|
||||||
|
bits += 5;
|
||||||
|
if (bits >= 8) {
|
||||||
|
out.push((value >>> (bits - 8)) & 255);
|
||||||
|
bits -= 8;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return Buffer.from(out);
|
||||||
|
}
|
||||||
|
|
||||||
|
export const generateSecret = () => base32Encode(crypto.randomBytes(20));
|
||||||
|
|
||||||
|
export function codeAt(secret: string, counter: number): string {
|
||||||
|
const buf = Buffer.alloc(8);
|
||||||
|
buf.writeBigUInt64BE(BigInt(counter));
|
||||||
|
const hmac = crypto.createHmac('sha1', base32Decode(secret)).update(buf).digest();
|
||||||
|
const offset = hmac[hmac.length - 1]! & 0xf;
|
||||||
|
const num = ((hmac[offset]! & 0x7f) << 24) | (hmac[offset + 1]! << 16) | (hmac[offset + 2]! << 8) | hmac[offset + 3]!;
|
||||||
|
return String(num % 1_000_000).padStart(6, '0');
|
||||||
|
}
|
||||||
|
|
||||||
|
/** The step `code` is right for (now, or one either side for clock drift), or null. Steps up to `afterStep` were used. */
|
||||||
|
export function matchStep(secret: string, code: unknown, { now = Date.now(), afterStep = -1 } = {}): number | null {
|
||||||
|
const clean = String(code ?? '').replace(/\D/g, '');
|
||||||
|
if (clean.length !== 6) return null;
|
||||||
|
const counter = Math.floor(now / 1000 / STEP);
|
||||||
|
for (const c of [counter - 1, counter, counter + 1]) {
|
||||||
|
if (c <= afterStep) continue;
|
||||||
|
if (crypto.timingSafeEqual(Buffer.from(codeAt(secret, c)), Buffer.from(clean))) return c;
|
||||||
|
}
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
|
||||||
|
/** The otpauth:// link an authenticator app scans as a QR code. */
|
||||||
|
export function otpauthUrl(secret: string, account: string, issuer: string): string {
|
||||||
|
const label = `${issuer}:${account}`;
|
||||||
|
return `otpauth://totp/${encodeURIComponent(label)}?secret=${secret}&issuer=${encodeURIComponent(issuer)}&algorithm=SHA1&digits=6&period=${STEP}`;
|
||||||
|
}
|
||||||
@@ -0,0 +1,22 @@
|
|||||||
|
/**
|
||||||
|
* The running version, from the backend's package.json (src/lib → ../../package.json in development,
|
||||||
|
* dist/lib → ../../package.json when built), so /api/health tells `crosscode deploy` the truth
|
||||||
|
* however the process was started (PM2 doesn't set npm_package_version).
|
||||||
|
*/
|
||||||
|
import fs from 'node:fs';
|
||||||
|
import path from 'node:path';
|
||||||
|
import { fileURLToPath } from 'node:url';
|
||||||
|
|
||||||
|
let cached: string | null = null;
|
||||||
|
|
||||||
|
export function appVersion(): string {
|
||||||
|
if (!cached) {
|
||||||
|
try {
|
||||||
|
const file = path.resolve(path.dirname(fileURLToPath(import.meta.url)), '..', '..', 'package.json');
|
||||||
|
cached = (JSON.parse(fs.readFileSync(file, 'utf8')) as { version: string }).version;
|
||||||
|
} catch {
|
||||||
|
cached = '0.0.0';
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return cached;
|
||||||
|
}
|
||||||
@@ -0,0 +1,133 @@
|
|||||||
|
/**
|
||||||
|
* Connect and Disconnect (`crosscode.link/1`, as Cross Events 2.4). On Accounts a link is also the
|
||||||
|
* product's **OIDC client** (docs/ACCOUNTS-1.0-PLAN.md §4, oidc/clients.ts): connecting registers
|
||||||
|
* it, disconnecting removes it. Usually the product connects (an admin there clicks Connect on
|
||||||
|
* Accounts); an Accounts admin can connect from here too.
|
||||||
|
*/
|
||||||
|
import {
|
||||||
|
LINK_PATHS, LINK_SCHEMA, linkConnectedSchema, linkConnectSchema, linkDisconnectSchema,
|
||||||
|
type hub, type LinkConnect, type LinkConnected, type LinkDisconnect,
|
||||||
|
} from '@crosscode/contracts';
|
||||||
|
import { newLinkNonce, newLinkSecret, signLink, verifyLink } from '@crosscode/contracts/signing';
|
||||||
|
import type { Request } from 'express';
|
||||||
|
import type { Ctx } from '../context.js';
|
||||||
|
import { audit, clientIp } from '../lib/audit.js';
|
||||||
|
import { callSibling, LinkCallError, siblingUrl } from './http.js';
|
||||||
|
import { keyPair, listedProduct } from './store.js';
|
||||||
|
|
||||||
|
export class LinkError extends Error {
|
||||||
|
constructor(message: string, public code: string, public status = 400) {
|
||||||
|
super(message);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Products that sign people in through Accounts. */
|
||||||
|
const CLIENT_PRODUCTS = new Set(['events', 'website', 'app']);
|
||||||
|
const NONCE_KEEP_MS = 60 * 60 * 1000;
|
||||||
|
|
||||||
|
async function self(ctx: Ctx) {
|
||||||
|
const installId = await ctx.settings.get('hub_install_id');
|
||||||
|
if (!installId) throw new LinkError('Accounts isn\'t connected to the Hub yet, so it can\'t link to other products.', 'LINKS_UNAVAILABLE', 503);
|
||||||
|
const { privateKeyPem } = await keyPair(ctx);
|
||||||
|
return { installId, url: ctx.config.publicUrl, privateKeyPem };
|
||||||
|
}
|
||||||
|
|
||||||
|
const party = (s: { installId: string; url: string }) => ({ product: 'accounts' as const, installId: s.installId, url: s.url });
|
||||||
|
|
||||||
|
async function firstUse(ctx: Ctx, nonce: string): Promise<boolean> {
|
||||||
|
const now = ctx.now();
|
||||||
|
await ctx.db.linkNonce.deleteMany({ where: { seenAt: { lt: new Date(now.getTime() - NONCE_KEEP_MS) } } }).catch(() => {});
|
||||||
|
try {
|
||||||
|
await ctx.db.linkNonce.create({ data: { nonce, seenAt: now } });
|
||||||
|
return true;
|
||||||
|
} catch (e) {
|
||||||
|
if ((e as { code?: string }).code === 'P2002') return false;
|
||||||
|
throw e;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
async function saveLink(ctx: Ctx, sibling: hub.LinkedProduct, secret: string, connectedById: string | null) {
|
||||||
|
const data = { product: sibling.product, url: sibling.url.replace(/\/+$/, ''), publicKey: sibling.publicKey, secret: ctx.secrets.encrypt(secret), connectedAt: ctx.now(), connectedById };
|
||||||
|
return ctx.db.productLink.upsert({ where: { installId: sibling.installId }, create: { installId: sibling.installId, ...data }, update: data });
|
||||||
|
}
|
||||||
|
|
||||||
|
const logLink = (ctx: Ctx, action: string, link: { installId: string; product: string }, actor: { id: string; role: string } | null, req: Request | undefined, by: string) =>
|
||||||
|
audit(ctx, { actorId: actor?.id ?? null, actorRole: actor?.role ?? 'linked_product', action, targetType: 'product_link', targetId: link.installId, metadata: { product: link.product, by }, ip: clientIp(req) });
|
||||||
|
|
||||||
|
export async function connectTo(ctx: Ctx, installId: string, actor: { id: string; role: string }, req?: Request) {
|
||||||
|
const sibling = await listedProduct(ctx, installId);
|
||||||
|
if (!sibling || !CLIENT_PRODUCTS.has(sibling.product)) throw new LinkError('That product isn\'t in the list the Hub gave Accounts. Wait for the next Hub heartbeat (up to 15 minutes).', 'NOT_LINKED', 404);
|
||||||
|
const me = await self(ctx);
|
||||||
|
const secret = newLinkSecret();
|
||||||
|
const message = signLink<Omit<LinkConnect, 'signature'>>({
|
||||||
|
schema: LINK_SCHEMA, type: 'link.connect', from: party(me), to: { installId: sibling.installId }, secret, issuedAt: ctx.now().toISOString(), nonce: newLinkNonce(),
|
||||||
|
}, me.privateKeyPem);
|
||||||
|
let reply: unknown;
|
||||||
|
try {
|
||||||
|
reply = await callSibling(await siblingUrl(ctx, sibling.url, LINK_PATHS.connect), { method: 'POST', body: JSON.stringify(message) });
|
||||||
|
} catch (e) {
|
||||||
|
if (e instanceof LinkCallError) throw new LinkError(`${sibling.url} refused to connect: ${e.message}`, e.code, 502);
|
||||||
|
throw e;
|
||||||
|
}
|
||||||
|
const parsed = linkConnectedSchema.safeParse(reply);
|
||||||
|
if (!parsed.success) throw new LinkError(`${sibling.url} answered in a way Accounts doesn't understand.`, 'BAD_REPLY', 502);
|
||||||
|
const r: LinkConnected = parsed.data;
|
||||||
|
if (!verifyLink(r as unknown as Record<string, unknown>, sibling.publicKey).ok || r.inReplyTo !== message.nonce || r.from.installId !== sibling.installId || r.to.installId !== me.installId) {
|
||||||
|
throw new LinkError(`${sibling.url}'s answer isn't signed with the key the Hub listed for it.`, 'BAD_SIGNATURE', 502);
|
||||||
|
}
|
||||||
|
const link = await saveLink(ctx, sibling, secret, actor.id);
|
||||||
|
await logLink(ctx, 'product_link_connected', link, actor, req, 'accounts');
|
||||||
|
return link;
|
||||||
|
}
|
||||||
|
|
||||||
|
export async function acceptConnect(ctx: Ctx, body: unknown, req?: Request): Promise<LinkConnected> {
|
||||||
|
const parsed = linkConnectSchema.safeParse(body);
|
||||||
|
if (!parsed.success) throw new LinkError('That isn\'t a crosscode.link/1 connect message.', 'INVALID_REQUEST', 400);
|
||||||
|
const m = parsed.data;
|
||||||
|
const me = await self(ctx);
|
||||||
|
if (m.to.installId !== me.installId) throw new LinkError('That message is for another install.', 'WRONG_INSTALL', 400);
|
||||||
|
const sibling = await listedProduct(ctx, m.from.installId);
|
||||||
|
if (!sibling || sibling.product !== m.from.product || !CLIENT_PRODUCTS.has(sibling.product)) {
|
||||||
|
throw new LinkError('Accounts doesn\'t know that install yet: the Hub lists the church\'s products in its next heartbeat (up to 15 minutes).', 'NOT_LINKED', 403);
|
||||||
|
}
|
||||||
|
const check = verifyLink(m as unknown as Record<string, unknown>, sibling.publicKey, { now: ctx.now() });
|
||||||
|
if (!check.ok) throw new LinkError(check.code === 'STALE_REQUEST' ? 'The message is too old, or a clock is wrong.' : 'The signature doesn\'t match the key the Hub listed.', check.code, 401);
|
||||||
|
if (!(await firstUse(ctx, m.nonce))) throw new LinkError('That message was already used.', 'REPLAYED', 409);
|
||||||
|
const link = await saveLink(ctx, sibling, m.secret, null);
|
||||||
|
await logLink(ctx, 'product_link_connected', link, null, req, sibling.product);
|
||||||
|
return signLink<Omit<LinkConnected, 'signature'>>({
|
||||||
|
schema: LINK_SCHEMA, type: 'link.connected', from: party(me), to: { installId: sibling.installId }, inReplyTo: m.nonce, issuedAt: ctx.now().toISOString(), nonce: newLinkNonce(),
|
||||||
|
}, me.privateKeyPem);
|
||||||
|
}
|
||||||
|
|
||||||
|
export async function disconnectFrom(ctx: Ctx, installId: string, actor: { id: string; role: string }, req?: Request) {
|
||||||
|
const link = await ctx.db.productLink.findUnique({ where: { installId } });
|
||||||
|
if (!link) throw new LinkError('That product isn\'t connected.', 'NOT_LINKED', 404);
|
||||||
|
let told = false;
|
||||||
|
let problem: string | null = null;
|
||||||
|
try {
|
||||||
|
const me = await self(ctx);
|
||||||
|
const message = signLink<Omit<LinkDisconnect, 'signature'>>({ schema: LINK_SCHEMA, type: 'link.disconnect', from: party(me), to: { installId }, issuedAt: ctx.now().toISOString(), nonce: newLinkNonce() }, me.privateKeyPem);
|
||||||
|
await callSibling(await siblingUrl(ctx, link.url, LINK_PATHS.disconnect), { method: 'POST', body: JSON.stringify(message) });
|
||||||
|
told = true;
|
||||||
|
} catch (e) {
|
||||||
|
problem = (e as Error).message;
|
||||||
|
}
|
||||||
|
await ctx.db.productLink.delete({ where: { installId } });
|
||||||
|
await logLink(ctx, 'product_link_disconnected', link, actor, req, 'accounts');
|
||||||
|
return { told, problem };
|
||||||
|
}
|
||||||
|
|
||||||
|
export async function acceptDisconnect(ctx: Ctx, body: unknown, req?: Request): Promise<void> {
|
||||||
|
const parsed = linkDisconnectSchema.safeParse(body);
|
||||||
|
if (!parsed.success) throw new LinkError('That isn\'t a crosscode.link/1 disconnect message.', 'INVALID_REQUEST', 400);
|
||||||
|
const m = parsed.data;
|
||||||
|
const me = await self(ctx);
|
||||||
|
if (m.to.installId !== me.installId) throw new LinkError('That message is for another install.', 'WRONG_INSTALL', 400);
|
||||||
|
const link = await ctx.db.productLink.findUnique({ where: { installId: m.from.installId } });
|
||||||
|
if (!link) return;
|
||||||
|
if (!verifyLink(m as unknown as Record<string, unknown>, link.publicKey, { now: ctx.now() }).ok) throw new LinkError('The signature doesn\'t match this link.', 'BAD_SIGNATURE', 401);
|
||||||
|
if (!(await firstUse(ctx, m.nonce))) throw new LinkError('That message was already used.', 'REPLAYED', 409);
|
||||||
|
await ctx.db.productLink.delete({ where: { installId: link.installId } });
|
||||||
|
await logLink(ctx, 'product_link_disconnected', link, null, req, link.product);
|
||||||
|
}
|
||||||
@@ -0,0 +1,69 @@
|
|||||||
|
/**
|
||||||
|
* Back-channel calls to linked products (docs/ACCOUNTS-1.0-PLAN.md §6): `crosscode.identity/1`
|
||||||
|
* user.updated / user.deleted / user.export at `ACCOUNTS_CALL_PATH`, and `church.changed`. Each is a
|
||||||
|
* `Delivery`, signed with the link's secret (`LINK_HEADERS`), retried after 1 min, 5 min, 30 min,
|
||||||
|
* 2 h, 12 h, then daily for a week. The reply is kept, and `onReply` acts on it (deletion,
|
||||||
|
* export).
|
||||||
|
*/
|
||||||
|
import crypto from 'node:crypto';
|
||||||
|
import { ACCOUNTS_CALL_PATH, CHURCH_PATHS } from '@crosscode/contracts';
|
||||||
|
import { LINK_HEADERS, signedHeaders } from '@crosscode/contracts/signing';
|
||||||
|
import type { Ctx } from '../context.js';
|
||||||
|
import { callSibling, siblingUrl } from './http.js';
|
||||||
|
|
||||||
|
const RETRY_MS = [60e3, 5 * 60e3, 30 * 60e3, 2 * 3600e3, 12 * 3600e3, ...Array(7).fill(24 * 3600e3)] as number[];
|
||||||
|
export const MAX_ATTEMPTS = RETRY_MS.length + 1;
|
||||||
|
|
||||||
|
export type CallType = 'user.updated' | 'user.deleted' | 'user.export' | 'church.changed';
|
||||||
|
|
||||||
|
/** Queues a call to every linked product (or the ones given). Returns the deliveries made. */
|
||||||
|
export async function queueCall(ctx: Ctx, type: CallType, makeBody: (callId: string) => object, opts: { linkIds?: string[] } = {}) {
|
||||||
|
const links = await ctx.db.productLink.findMany(opts.linkIds ? { where: { installId: { in: opts.linkIds } } } : undefined);
|
||||||
|
const made = [];
|
||||||
|
for (const link of links) {
|
||||||
|
const callId = crypto.randomUUID();
|
||||||
|
made.push(await ctx.db.delivery.create({
|
||||||
|
data: { linkId: link.installId, callId, type, path: type === 'church.changed' ? CHURCH_PATHS.changed : ACCOUNTS_CALL_PATH, body: makeBody(callId) as never, nextAttemptAt: ctx.now() },
|
||||||
|
}));
|
||||||
|
}
|
||||||
|
return made;
|
||||||
|
}
|
||||||
|
|
||||||
|
type ReplyHandler = (ctx: Ctx, delivery: { id: string; linkId: string; type: string; body: unknown }, reply: unknown) => Promise<void>;
|
||||||
|
const handlers = new Map<string, ReplyHandler>();
|
||||||
|
/** What to do with a product's answer to a call type (privacy/deletion.ts, privacy/export.ts). */
|
||||||
|
export function onReply(type: CallType, handler: ReplyHandler) {
|
||||||
|
handlers.set(type, handler);
|
||||||
|
}
|
||||||
|
|
||||||
|
export async function send(ctx: Ctx, deliveryId: string): Promise<boolean> {
|
||||||
|
const d = await ctx.db.delivery.findUnique({ where: { id: deliveryId } });
|
||||||
|
if (!d || d.status !== 'pending') return false;
|
||||||
|
const link = await ctx.db.productLink.findUnique({ where: { installId: d.linkId } });
|
||||||
|
const sender = await ctx.settings.get('hub_install_id');
|
||||||
|
const attempts = d.attempts + 1;
|
||||||
|
try {
|
||||||
|
if (!link || !sender) throw new Error(link ? 'Accounts isn\'t connected to the Hub' : 'The product is no longer linked');
|
||||||
|
const raw = JSON.stringify(d.body);
|
||||||
|
const headers = signedHeaders(LINK_HEADERS, { senderId: sender, secret: ctx.secrets.decrypt(link.secret), rawBody: raw, now: ctx.now() });
|
||||||
|
const reply = await callSibling(await siblingUrl(ctx, link.url, d.path), { method: 'POST', body: raw, headers });
|
||||||
|
await ctx.db.delivery.update({ where: { id: d.id }, data: { status: 'delivered', attempts, deliveredAt: ctx.now(), reply: (reply ?? null) as never, lastError: null } });
|
||||||
|
await handlers.get(d.type)?.(ctx, d, reply);
|
||||||
|
return true;
|
||||||
|
} catch (e) {
|
||||||
|
const failed = attempts >= MAX_ATTEMPTS || !link;
|
||||||
|
await ctx.db.delivery.update({
|
||||||
|
where: { id: d.id },
|
||||||
|
data: { attempts, lastError: String((e as Error).message).slice(0, 500), status: failed ? 'failed' : 'pending', nextAttemptAt: new Date(ctx.now().getTime() + (RETRY_MS[attempts - 1] ?? RETRY_MS.at(-1)!)) },
|
||||||
|
});
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/** The `deliveries` job (every minute): everything due, oldest first. */
|
||||||
|
export async function runDue(ctx: Ctx, limit = 50) {
|
||||||
|
const due = await ctx.db.delivery.findMany({ where: { status: 'pending', nextAttemptAt: { lte: ctx.now() } }, orderBy: { nextAttemptAt: 'asc' }, take: limit });
|
||||||
|
let sent = 0;
|
||||||
|
for (const d of due) if (await send(ctx, d.id)) sent++;
|
||||||
|
return { due: due.length, sent };
|
||||||
|
}
|
||||||
@@ -0,0 +1,76 @@
|
|||||||
|
/**
|
||||||
|
* Calls to a linked product: https only, never a private address (unless LINKS_ALLOW_PRIVATE for
|
||||||
|
* local testing), no redirects, a timeout and a size limit (as Cross Events 2.4's links/http.ts).
|
||||||
|
*/
|
||||||
|
import dns from 'node:dns/promises';
|
||||||
|
import net from 'node:net';
|
||||||
|
import type { Ctx } from '../context.js';
|
||||||
|
|
||||||
|
const TIMEOUT_MS = 15000;
|
||||||
|
const MAX_BYTES = 5 * 1024 * 1024;
|
||||||
|
|
||||||
|
export class LinkCallError extends Error {
|
||||||
|
constructor(message: string, public code: string, public status = 502, public data: unknown = null) {
|
||||||
|
super(message);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
export function isPrivateAddress(ip: string): boolean {
|
||||||
|
if (net.isIPv4(ip)) {
|
||||||
|
const [a, b] = ip.split('.').map(Number) as [number, number];
|
||||||
|
return a === 10 || a === 127 || a === 0 || (a === 169 && b === 254) || (a === 172 && b >= 16 && b <= 31) || (a === 192 && b === 168) || (a === 100 && b >= 64 && b <= 127) || a >= 224;
|
||||||
|
}
|
||||||
|
if (net.isIPv6(ip)) {
|
||||||
|
const v = ip.toLowerCase();
|
||||||
|
if (v === '::1' || v === '::') return true;
|
||||||
|
const mapped = /^::ffff:(\d+\.\d+\.\d+\.\d+)$/.exec(v);
|
||||||
|
if (mapped) return isPrivateAddress(mapped[1]!);
|
||||||
|
return /^f[cd]/.test(v) || /^fe[89ab]/.test(v);
|
||||||
|
}
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
|
||||||
|
export async function siblingUrl(ctx: Ctx, base: string, path: string): Promise<URL> {
|
||||||
|
let url: URL;
|
||||||
|
try {
|
||||||
|
url = new URL(path, base.endsWith('/') ? base : `${base}/`);
|
||||||
|
} catch {
|
||||||
|
throw new LinkCallError(`${base} isn't a web address`, 'BAD_ADDRESS', 400);
|
||||||
|
}
|
||||||
|
const allow = ctx.config.allowPrivateLinks;
|
||||||
|
if (url.protocol !== 'https:' && !(url.protocol === 'http:' && allow)) throw new LinkCallError(`${base} doesn't use https`, 'BAD_ADDRESS', 400);
|
||||||
|
if (!allow) {
|
||||||
|
const addrs = net.isIP(url.hostname) ? [{ address: url.hostname }] : await dns.lookup(url.hostname, { all: true }).catch(() => []);
|
||||||
|
if (!addrs.length || addrs.some((a) => isPrivateAddress(a.address))) throw new LinkCallError(`${url.hostname} points to a private network address`, 'PRIVATE_ADDRESS', 400);
|
||||||
|
}
|
||||||
|
return url;
|
||||||
|
}
|
||||||
|
|
||||||
|
export async function callSibling(url: URL, init: { method: 'GET' | 'POST'; body?: string; headers?: Record<string, string> }): Promise<unknown> {
|
||||||
|
let res: Response;
|
||||||
|
try {
|
||||||
|
res = await fetch(url, {
|
||||||
|
method: init.method,
|
||||||
|
headers: { Accept: 'application/json', ...(init.body !== undefined ? { 'Content-Type': 'application/json' } : {}), ...init.headers },
|
||||||
|
body: init.body,
|
||||||
|
redirect: 'manual',
|
||||||
|
signal: AbortSignal.timeout(TIMEOUT_MS),
|
||||||
|
});
|
||||||
|
} catch (e) {
|
||||||
|
throw new LinkCallError(`${url.host} could not be reached: ${(e as Error).message}`, 'UNREACHABLE');
|
||||||
|
}
|
||||||
|
if (res.status >= 300 && res.status < 400) throw new LinkCallError(`${url.host} answered with a redirect`, 'REDIRECTED');
|
||||||
|
const text = await res.text();
|
||||||
|
if (text.length > MAX_BYTES) throw new LinkCallError('The answer is too large', 'TOO_LARGE');
|
||||||
|
let data: unknown = null;
|
||||||
|
try {
|
||||||
|
data = text ? JSON.parse(text) : null;
|
||||||
|
} catch {
|
||||||
|
if (res.ok) throw new LinkCallError(`${url.host} didn't answer with JSON`, 'NOT_JSON');
|
||||||
|
}
|
||||||
|
if (!res.ok) {
|
||||||
|
const d = (data && typeof data === 'object' ? data : {}) as { message?: string; code?: string; error?: { message?: string; code?: string } };
|
||||||
|
throw new LinkCallError(d.message || d.error?.message || `${url.host} answered ${res.status}`, d.code || d.error?.code || `HTTP_${res.status}`, res.status >= 500 ? 502 : res.status, data);
|
||||||
|
}
|
||||||
|
return data;
|
||||||
|
}
|
||||||
@@ -0,0 +1,34 @@
|
|||||||
|
/**
|
||||||
|
* This install's Ed25519 key pair and the church's other installs as the Hub last listed them
|
||||||
|
* (as Cross Events 2.4's links/store.ts). Settings: hub_private_key (encrypted), hub_public_key,
|
||||||
|
* hub_linked_products.
|
||||||
|
*/
|
||||||
|
import { hub } from '@crosscode/contracts';
|
||||||
|
import { ed25519PublicToPem, generateEd25519 } from '@crosscode/contracts/signing';
|
||||||
|
import type { Ctx } from '../context.js';
|
||||||
|
|
||||||
|
type LinkedProduct = hub.LinkedProduct;
|
||||||
|
|
||||||
|
export async function keyPair(ctx: Ctx): Promise<{ publicKeyPem: string; privateKeyPem: string }> {
|
||||||
|
const [priv, pub] = await Promise.all([ctx.settings.get('hub_private_key'), ctx.settings.get('hub_public_key')]);
|
||||||
|
if (priv && pub) return { privateKeyPem: priv, publicKeyPem: pub };
|
||||||
|
const pair = generateEd25519();
|
||||||
|
const publicKeyPem = ed25519PublicToPem(pair.publicKey);
|
||||||
|
await ctx.settings.setMany({ hub_private_key: pair.privateKeyPem, hub_public_key: publicKeyPem });
|
||||||
|
return { privateKeyPem: pair.privateKeyPem, publicKeyPem };
|
||||||
|
}
|
||||||
|
|
||||||
|
export async function linkedProducts(ctx: Ctx): Promise<LinkedProduct[]> {
|
||||||
|
const list = await ctx.settings.json<unknown[]>('hub_linked_products', []);
|
||||||
|
return Array.isArray(list) ? (list.filter((l) => hub.linkedProductSchema.safeParse(l).success) as LinkedProduct[]) : [];
|
||||||
|
}
|
||||||
|
|
||||||
|
export async function saveLinkedProducts(ctx: Ctx, list: unknown): Promise<void> {
|
||||||
|
if (!Array.isArray(list)) return;
|
||||||
|
const clean = list.map((l) => hub.linkedProductSchema.safeParse(l)).filter((r) => r.success).map((r) => r.data).slice(0, 10);
|
||||||
|
await ctx.settings.set('hub_linked_products', JSON.stringify(clean));
|
||||||
|
}
|
||||||
|
|
||||||
|
export async function listedProduct(ctx: Ctx, installId: string): Promise<LinkedProduct | null> {
|
||||||
|
return (await linkedProducts(ctx)).find((l) => l.installId === installId) ?? null;
|
||||||
|
}
|
||||||
@@ -0,0 +1,212 @@
|
|||||||
|
/**
|
||||||
|
* The account page's API (`/api/v2/me/…`): profile, password, 2FA, sign-ins, news consent,
|
||||||
|
* download my data, delete my account, sign out everywhere. Signed in with the Accounts session.
|
||||||
|
*/
|
||||||
|
import fs from 'node:fs/promises';
|
||||||
|
import express, { type Request, type Response } from 'express';
|
||||||
|
import type Provider from 'oidc-provider';
|
||||||
|
import type { Ctx } from '../context.js';
|
||||||
|
import { ApiError, handle, limit } from '../http.js';
|
||||||
|
import { loginEvent } from '../lib/audit.js';
|
||||||
|
import { hashPassword, passwordProblem, verifyPassword } from '../lib/passwords.js';
|
||||||
|
import { emailProblem, normaliseEmail, normalisePhone, profileChanged, setNewsConsent } from '../accounts/service.js';
|
||||||
|
import { confirmTwoFactorSetup, recoveryCodesLeft, replaceRecoveryCodes, startTwoFactorSetup, turnOff } from '../accounts/twoFactor.js';
|
||||||
|
import { currentSession, signOutEverywhere, type SignedIn } from '../oidc/sessions.js';
|
||||||
|
import { currentNotice } from '../privacy/notice.js';
|
||||||
|
import { requestExport } from '../privacy/export.js';
|
||||||
|
import { requestDeletion } from '../privacy/deletion.js';
|
||||||
|
import { hashToken, randomToken } from '../lib/crypto.js';
|
||||||
|
|
||||||
|
export function meView(a: SignedIn['account'], extra: { recoveryCodesLeft: number; noticeVersion: number }) {
|
||||||
|
return {
|
||||||
|
id: a.id, name: a.name, givenName: a.givenName, familyName: a.familyName, email: a.email, emailVerified: a.emailVerified,
|
||||||
|
phone: a.phone, role: a.role, twoFactor: a.twoFactorMethod, recoveryCodesLeft: extra.recoveryCodesLeft,
|
||||||
|
news: { email: a.newsEmail, whatsapp: a.newsWhatsApp }, noticeVersionAccepted: a.noticeVersionAccepted, noticeVersion: extra.noticeVersion,
|
||||||
|
createdAt: a.createdAt, lastSignInAt: a.lastSignInAt,
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
export function meRouter(ctx: Ctx, provider: Provider) {
|
||||||
|
const r = express.Router();
|
||||||
|
|
||||||
|
const signedIn = async (req: Request, res: Response) => {
|
||||||
|
const s = await currentSession(ctx, provider, req, res);
|
||||||
|
if (!s) throw new ApiError(401, 'UNAUTHENTICATED', 'Please sign in.');
|
||||||
|
return s;
|
||||||
|
};
|
||||||
|
const view = async (s: SignedIn) => {
|
||||||
|
const a = (await ctx.db.account.findUnique({ where: { id: s.account.id } }))!;
|
||||||
|
return meView(a, { recoveryCodesLeft: await recoveryCodesLeft(ctx, a.id), noticeVersion: (await currentNotice(ctx)).version });
|
||||||
|
};
|
||||||
|
const needPassword = async (s: SignedIn, password: unknown) => {
|
||||||
|
if (!(await verifyPassword(String(password ?? ''), s.account.passwordHash))) throw new ApiError(400, 'BAD_PASSWORD', 'That isn\'t your current password.', { password: 'That isn\'t your current password.' });
|
||||||
|
};
|
||||||
|
|
||||||
|
r.get('/me', handle(async (req, res) => view(await signedIn(req, res))));
|
||||||
|
|
||||||
|
r.put('/me', handle(async (req, res) => {
|
||||||
|
const s = await signedIn(req, res);
|
||||||
|
const name = req.body?.name !== undefined ? String(req.body.name).trim().replace(/\s+/g, ' ') : s.account.name;
|
||||||
|
if (name.length < 2 || name.length > 200) throw new ApiError(400, 'VALIDATION', 'Enter your name.', { name: 'Enter your name.' });
|
||||||
|
const phone = req.body?.phone !== undefined ? (req.body.phone ? normalisePhone(req.body.phone) : null) : s.account.phone;
|
||||||
|
if (req.body?.phone && !phone) throw new ApiError(400, 'VALIDATION', 'Enter a phone number like 082 123 4567.', { phone: 'Enter a phone number like 082 123 4567.' });
|
||||||
|
const parts = name.split(' ');
|
||||||
|
await ctx.db.account.update({
|
||||||
|
where: { id: s.account.id },
|
||||||
|
data: {
|
||||||
|
name, givenName: req.body?.givenName ?? parts[0] ?? null, familyName: req.body?.familyName ?? (parts.length > 1 ? parts.slice(1).join(' ') : null), phone,
|
||||||
|
...(phone !== s.account.phone ? { phoneVerified: false } : {}),
|
||||||
|
// No phone, no WhatsApp news.
|
||||||
|
...(phone ? {} : { newsWhatsApp: false }),
|
||||||
|
},
|
||||||
|
});
|
||||||
|
await profileChanged(ctx, s.account.id);
|
||||||
|
return view(s);
|
||||||
|
}));
|
||||||
|
|
||||||
|
// A new email address is confirmed by a link sent to it; the old one keeps working until then.
|
||||||
|
r.post('/me/email', limit(5), handle(async (req, res) => {
|
||||||
|
const s = await signedIn(req, res);
|
||||||
|
await needPassword(s, req.body?.password);
|
||||||
|
const email = normaliseEmail(req.body?.email);
|
||||||
|
const problem = emailProblem(email);
|
||||||
|
if (problem) throw new ApiError(400, 'VALIDATION', problem, { email: problem });
|
||||||
|
if (await ctx.db.account.findUnique({ where: { email } })) throw new ApiError(409, 'EXISTS', 'Another account uses that email address.', { email: 'Another account uses that email address.' });
|
||||||
|
const token = randomToken();
|
||||||
|
await ctx.db.emailToken.create({ data: { accountId: s.account.id, purpose: `change_email:${email}`, tokenHash: hashToken(token), expiresAt: new Date(ctx.now().getTime() + 24 * 3600e3) } });
|
||||||
|
await ctx.messenger.email({ to: email, subject: 'Confirm your new email address', text: `Confirm this is your new email address for signing in:\n${ctx.config.publicUrl}/account/confirm-email?token=${token}\n\nThe link works for 24 hours.` });
|
||||||
|
return { sent: true };
|
||||||
|
}));
|
||||||
|
|
||||||
|
r.post('/me/email/confirm', handle(async (req, res) => {
|
||||||
|
const s = await signedIn(req, res);
|
||||||
|
const row = await ctx.db.emailToken.findUnique({ where: { tokenHash: hashToken(String(req.body?.token ?? '')) } });
|
||||||
|
if (!row || row.accountId !== s.account.id || !row.purpose.startsWith('change_email:') || row.usedAt || row.expiresAt < ctx.now()) throw new ApiError(400, 'BAD_TOKEN', 'This link has expired or was already used.');
|
||||||
|
const email = row.purpose.slice('change_email:'.length);
|
||||||
|
if (await ctx.db.account.findUnique({ where: { email } })) throw new ApiError(409, 'EXISTS', 'Another account uses that email address now.');
|
||||||
|
await ctx.db.account.update({ where: { id: s.account.id }, data: { email, emailVerified: true } });
|
||||||
|
await ctx.db.emailToken.update({ where: { id: row.id }, data: { usedAt: ctx.now() } });
|
||||||
|
await ctx.messenger.email({ to: s.account.email, subject: 'Your sign-in email address changed', text: `Your account now signs in with ${email}. If you didn't do this, contact the church office straight away.` });
|
||||||
|
await loginEvent(ctx, s.account.id, 'email_changed', req);
|
||||||
|
await profileChanged(ctx, s.account.id);
|
||||||
|
return view(s);
|
||||||
|
}));
|
||||||
|
|
||||||
|
r.post('/me/password', limit(10), handle(async (req, res) => {
|
||||||
|
const s = await signedIn(req, res);
|
||||||
|
await needPassword(s, req.body?.current);
|
||||||
|
const problem = passwordProblem(req.body?.password);
|
||||||
|
if (problem) throw new ApiError(400, 'VALIDATION', problem, { password: problem });
|
||||||
|
await ctx.db.account.update({ where: { id: s.account.id }, data: { passwordHash: await hashPassword(String(req.body.password)) } });
|
||||||
|
await loginEvent(ctx, s.account.id, 'password_changed', req);
|
||||||
|
return { changed: true };
|
||||||
|
}));
|
||||||
|
|
||||||
|
// ─── Two-factor ────────────────────────────────────────────────────────────
|
||||||
|
|
||||||
|
const setupKey = (id: string) => `me:${id}`;
|
||||||
|
|
||||||
|
r.post('/me/two-factor/setup', limit(10), handle(async (req, res) => {
|
||||||
|
const s = await signedIn(req, res);
|
||||||
|
const started = await startTwoFactorSetup(ctx, s.account, req.body?.method);
|
||||||
|
const data = { uid: setupKey(s.account.id), accountId: s.account.id, stage: 'setup', pendingTotpSecret: started.encryptedSecret, codeHash: started.codeHash, codeSentAt: started.codeHash ? ctx.now() : null, amr: [], attempts: 0, expiresAt: new Date(ctx.now().getTime() + 3600e3) };
|
||||||
|
await ctx.db.pendingSignIn.upsert({ where: { uid: data.uid }, create: data, update: data });
|
||||||
|
return started.forScreen;
|
||||||
|
}));
|
||||||
|
|
||||||
|
r.post('/me/two-factor/confirm', limit(20), handle(async (req, res) => {
|
||||||
|
const s = await signedIn(req, res);
|
||||||
|
const p = await ctx.db.pendingSignIn.findUnique({ where: { uid: setupKey(s.account.id) } });
|
||||||
|
if (!p || p.expiresAt < ctx.now()) throw new ApiError(400, 'RESTART', 'Start setting it up again.');
|
||||||
|
const recoveryCodes = await confirmTwoFactorSetup(ctx, s.account, { method: req.body?.method, code: req.body?.code, pendingSecret: p.pendingTotpSecret, codeHash: p.codeHash, codeSentAt: p.codeSentAt }, req);
|
||||||
|
await ctx.db.pendingSignIn.deleteMany({ where: { uid: p.uid } });
|
||||||
|
await profileChanged(ctx, s.account.id);
|
||||||
|
return { ...(await view(s)), recoveryCodes };
|
||||||
|
}));
|
||||||
|
|
||||||
|
r.post('/me/two-factor/off', limit(10), handle(async (req, res) => {
|
||||||
|
const s = await signedIn(req, res);
|
||||||
|
await needPassword(s, req.body?.password);
|
||||||
|
if (s.account.role === 'admin' && (await ctx.settings.bool('two_factor_required_for_admins', true))) throw new ApiError(400, 'REQUIRED', 'Admins must keep two-factor sign-in on. You can change how you get your codes instead.');
|
||||||
|
await turnOff(ctx, s.account.id);
|
||||||
|
await loginEvent(ctx, s.account.id, 'two_factor_off', req);
|
||||||
|
await profileChanged(ctx, s.account.id);
|
||||||
|
return view(s);
|
||||||
|
}));
|
||||||
|
|
||||||
|
r.post('/me/recovery-codes', limit(5), handle(async (req, res) => {
|
||||||
|
const s = await signedIn(req, res);
|
||||||
|
await needPassword(s, req.body?.password);
|
||||||
|
if (!s.account.twoFactorMethod) throw new ApiError(400, 'NO_2FA', 'Turn on two-factor sign-in first.');
|
||||||
|
const codes = await replaceRecoveryCodes(ctx, s.account.id);
|
||||||
|
await loginEvent(ctx, s.account.id, 'recovery_codes_replaced', req);
|
||||||
|
return { recoveryCodes: codes };
|
||||||
|
}));
|
||||||
|
|
||||||
|
// ─── Activity, consent, privacy ─────────────────────────────────────────────
|
||||||
|
|
||||||
|
r.get('/me/sign-ins', handle(async (req, res) => {
|
||||||
|
const s = await signedIn(req, res);
|
||||||
|
const events = await ctx.db.loginEvent.findMany({ where: { accountId: s.account.id }, orderBy: { createdAt: 'desc' }, take: 50 });
|
||||||
|
const links = await ctx.db.productLink.findMany();
|
||||||
|
const names = new Map(links.map((l) => [l.installId, l.url]));
|
||||||
|
return { items: events.map((e) => ({ type: e.type, at: e.createdAt, ip: e.ip, device: e.userAgent, site: e.clientId ? names.get(e.clientId) ?? null : null })) };
|
||||||
|
}));
|
||||||
|
|
||||||
|
r.put('/me/news', handle(async (req, res) => {
|
||||||
|
const s = await signedIn(req, res);
|
||||||
|
const changed = await setNewsConsent(ctx, s.account, { email: req.body?.email === true, whatsapp: req.body?.whatsapp === true && !!s.account.phone }, 'account_page');
|
||||||
|
if (changed) await profileChanged(ctx, s.account.id);
|
||||||
|
return view(s);
|
||||||
|
}));
|
||||||
|
|
||||||
|
r.get('/me/notice', handle(async (req, res) => {
|
||||||
|
await signedIn(req, res);
|
||||||
|
const n = await currentNotice(ctx);
|
||||||
|
return { version: n.version, title: n.title, body: n.body, publishedAt: n.publishedAt };
|
||||||
|
}));
|
||||||
|
|
||||||
|
r.post('/me/sign-out-everywhere', handle(async (req, res) => {
|
||||||
|
const s = await signedIn(req, res);
|
||||||
|
const told = await signOutEverywhere(ctx, provider, s.account.id);
|
||||||
|
await loginEvent(ctx, s.account.id, 'signed_out_everywhere', req, { detail: { productsTold: told } });
|
||||||
|
return { signedOut: true };
|
||||||
|
}));
|
||||||
|
|
||||||
|
r.get('/me/exports', handle(async (req, res) => {
|
||||||
|
const s = await signedIn(req, res);
|
||||||
|
const list = await ctx.db.dataExport.findMany({ where: { accountId: s.account.id }, orderBy: { createdAt: 'desc' }, take: 5 });
|
||||||
|
return { items: list.map((e) => ({ id: e.id, status: e.status, createdAt: e.createdAt, readyAt: e.readyAt, expiresAt: e.expiresAt })) };
|
||||||
|
}));
|
||||||
|
|
||||||
|
r.post('/me/exports', limit(3, 60), handle(async (req, res) => {
|
||||||
|
const s = await signedIn(req, res);
|
||||||
|
const e = await requestExport(ctx, s.account.id);
|
||||||
|
return { id: e.id, status: (await ctx.db.dataExport.findUnique({ where: { id: e.id } }))!.status };
|
||||||
|
}));
|
||||||
|
|
||||||
|
r.get('/me/exports/:id/download', async (req, res) => {
|
||||||
|
try {
|
||||||
|
const s = await signedIn(req, res);
|
||||||
|
const e = await ctx.db.dataExport.findUnique({ where: { id: String(req.params.id) } });
|
||||||
|
if (!e || e.accountId !== s.account.id || e.status !== 'ready' || !e.file) throw new ApiError(404, 'NOT_FOUND', 'That download isn\'t available any more.');
|
||||||
|
res.setHeader('Content-Type', 'application/json; charset=utf-8');
|
||||||
|
res.setHeader('Content-Disposition', `attachment; filename="my-data-${e.createdAt.toISOString().slice(0, 10)}.json"`);
|
||||||
|
res.send(await fs.readFile(e.file));
|
||||||
|
} catch (err) {
|
||||||
|
const { sendError } = await import('../http.js');
|
||||||
|
sendError(res, err);
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
r.post('/me/delete', limit(3, 60), handle(async (req, res) => {
|
||||||
|
const s = await signedIn(req, res);
|
||||||
|
await needPassword(s, req.body?.password);
|
||||||
|
const admins = await ctx.db.account.count({ where: { role: 'admin', status: 'active' } });
|
||||||
|
if (s.account.role === 'admin' && admins <= 1) throw new ApiError(400, 'LAST_ADMIN', 'You\'re the only admin. Make someone else an admin first.');
|
||||||
|
await requestDeletion(ctx, provider, s.account.id, req);
|
||||||
|
return { requested: true };
|
||||||
|
}));
|
||||||
|
|
||||||
|
return r;
|
||||||
|
}
|
||||||
@@ -0,0 +1,69 @@
|
|||||||
|
/**
|
||||||
|
* oidc-provider's storage in Postgres (`OidcPayload`, one row per model and id), so sessions and
|
||||||
|
* codes survive restarts and work with more than one process. Clients aren't stored here: they're
|
||||||
|
* the linked products (oidc/clients.ts).
|
||||||
|
*/
|
||||||
|
import type { Adapter, AdapterPayload } from 'oidc-provider';
|
||||||
|
import type { Ctx } from '../context.js';
|
||||||
|
import { clientMetadataFor } from './clients.js';
|
||||||
|
|
||||||
|
/** Models whose rows are found by grant (revoked together). */
|
||||||
|
const GRANTABLE = new Set(['AccessToken', 'AuthorizationCode', 'RefreshToken', 'DeviceCode', 'BackchannelAuthenticationRequest']);
|
||||||
|
|
||||||
|
export function adapterFor(ctx: Ctx) {
|
||||||
|
return class PrismaAdapter implements Adapter {
|
||||||
|
constructor(private readonly model: string) {}
|
||||||
|
|
||||||
|
private key(id: string) {
|
||||||
|
return `${this.model}:${id}`;
|
||||||
|
}
|
||||||
|
|
||||||
|
async upsert(id: string, payload: AdapterPayload, expiresIn: number): Promise<void> {
|
||||||
|
const data = {
|
||||||
|
model: this.model,
|
||||||
|
payload: payload as never,
|
||||||
|
grantId: payload.grantId ?? null,
|
||||||
|
userCode: payload.userCode ?? null,
|
||||||
|
uid: payload.uid ?? null,
|
||||||
|
accountId: this.model === 'Session' ? (payload.accountId ?? null) : null,
|
||||||
|
expiresAt: expiresIn ? new Date(ctx.now().getTime() + expiresIn * 1000) : null,
|
||||||
|
};
|
||||||
|
await ctx.db.oidcPayload.upsert({ where: { id: this.key(id) }, create: { id: this.key(id), ...data }, update: data });
|
||||||
|
}
|
||||||
|
|
||||||
|
private live(row: { payload: unknown; expiresAt: Date | null; consumedAt: Date | null } | null): AdapterPayload | undefined {
|
||||||
|
if (!row || (row.expiresAt && row.expiresAt <= ctx.now())) return undefined;
|
||||||
|
return { ...(row.payload as AdapterPayload), ...(row.consumedAt ? { consumed: Math.floor(row.consumedAt.getTime() / 1000) } : {}) };
|
||||||
|
}
|
||||||
|
|
||||||
|
async find(id: string): Promise<AdapterPayload | undefined> {
|
||||||
|
if (this.model === 'Client') return (await clientMetadataFor(ctx, id)) as AdapterPayload | undefined;
|
||||||
|
return this.live(await ctx.db.oidcPayload.findUnique({ where: { id: this.key(id) } }));
|
||||||
|
}
|
||||||
|
|
||||||
|
async findByUserCode(userCode: string) {
|
||||||
|
return this.live(await ctx.db.oidcPayload.findFirst({ where: { model: this.model, userCode } }));
|
||||||
|
}
|
||||||
|
|
||||||
|
async findByUid(uid: string) {
|
||||||
|
return this.live(await ctx.db.oidcPayload.findFirst({ where: { model: this.model, uid } }));
|
||||||
|
}
|
||||||
|
|
||||||
|
async consume(id: string) {
|
||||||
|
await ctx.db.oidcPayload.update({ where: { id: this.key(id) }, data: { consumedAt: ctx.now() } }).catch(() => {});
|
||||||
|
}
|
||||||
|
|
||||||
|
async destroy(id: string) {
|
||||||
|
await ctx.db.oidcPayload.deleteMany({ where: { id: this.key(id) } });
|
||||||
|
}
|
||||||
|
|
||||||
|
async revokeByGrantId(grantId: string) {
|
||||||
|
if (GRANTABLE.has(this.model) || this.model === 'Grant') await ctx.db.oidcPayload.deleteMany({ where: { grantId } });
|
||||||
|
}
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
/** The `oidc-cleanup` job: rows past their expiry. */
|
||||||
|
export async function deleteExpired(ctx: Ctx) {
|
||||||
|
return ctx.db.oidcPayload.deleteMany({ where: { expiresAt: { lt: ctx.now() } } });
|
||||||
|
}
|
||||||
@@ -0,0 +1,51 @@
|
|||||||
|
/**
|
||||||
|
* OIDC clients (docs/ACCOUNTS-1.0-PLAN.md §4): every linked product is one, with no registration
|
||||||
|
* screen. `client_id` is its Hub install id, the secret is derived from its link's secret, and its
|
||||||
|
* addresses are the fixed paths on the address the Hub listed for it (exact matches only).
|
||||||
|
*
|
||||||
|
* Plus Accounts' own pages (`accounts-self`): the account page signs in through the same flow.
|
||||||
|
*/
|
||||||
|
import { oidcClientAddresses } from '@crosscode/contracts';
|
||||||
|
import { oidcClientSecret } from '@crosscode/contracts/signing';
|
||||||
|
import type { ClientMetadata } from 'oidc-provider';
|
||||||
|
import type { Ctx } from '../context.js';
|
||||||
|
|
||||||
|
export const SELF_CLIENT_ID = 'accounts-self';
|
||||||
|
export const SELF_CALLBACK = '/api/self/callback';
|
||||||
|
|
||||||
|
const PRODUCT_NAMES: Record<string, string> = { events: 'Cross Events', website: 'the church website', app: 'the church app' };
|
||||||
|
|
||||||
|
export function selfClient(ctx: Ctx): ClientMetadata {
|
||||||
|
return {
|
||||||
|
client_id: SELF_CLIENT_ID,
|
||||||
|
client_name: 'Your account',
|
||||||
|
token_endpoint_auth_method: 'none',
|
||||||
|
grant_types: ['authorization_code'],
|
||||||
|
response_types: ['code'],
|
||||||
|
redirect_uris: [`${ctx.config.publicUrl}${SELF_CALLBACK}`],
|
||||||
|
post_logout_redirect_uris: [`${ctx.config.publicUrl}/signed-out`],
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
export async function clientMetadataFor(ctx: Ctx, clientId: string): Promise<ClientMetadata | undefined> {
|
||||||
|
const link = await ctx.db.productLink.findUnique({ where: { installId: clientId } }).catch(() => null);
|
||||||
|
if (!link) return undefined;
|
||||||
|
const a = oidcClientAddresses(link.url);
|
||||||
|
return {
|
||||||
|
client_id: link.installId,
|
||||||
|
client_secret: oidcClientSecret(ctx.secrets.decrypt(link.secret)),
|
||||||
|
client_name: PRODUCT_NAMES[link.product] ?? link.product,
|
||||||
|
token_endpoint_auth_method: 'client_secret_basic',
|
||||||
|
grant_types: ['authorization_code'],
|
||||||
|
response_types: ['code'],
|
||||||
|
redirect_uris: [a.redirectUri],
|
||||||
|
post_logout_redirect_uris: [a.postLogoutRedirectUri],
|
||||||
|
backchannel_logout_uri: a.backchannelLogoutUri,
|
||||||
|
backchannel_logout_session_required: true,
|
||||||
|
'crosscode.product': link.product,
|
||||||
|
} as ClientMetadata;
|
||||||
|
}
|
||||||
|
|
||||||
|
export function productName(product: string | undefined): string {
|
||||||
|
return (product && PRODUCT_NAMES[product]) || 'this site';
|
||||||
|
}
|
||||||
@@ -0,0 +1,51 @@
|
|||||||
|
/**
|
||||||
|
* The few pages oidc-provider renders itself (an error, the sign-out confirmation, "signed out"),
|
||||||
|
* in the church's colours. No inline scripts (the CSP forbids them): the sign-out page submits
|
||||||
|
* itself with /api/static/logout.js.
|
||||||
|
*/
|
||||||
|
import type { KoaContextWithOIDC } from 'oidc-provider';
|
||||||
|
import type { Ctx } from '../context.js';
|
||||||
|
import { branding } from '../church/profile.js';
|
||||||
|
|
||||||
|
const esc = (s: unknown) => String(s ?? '').replace(/[&<>"']/g, (c) => ({ '&': '&', '<': '<', '>': '>', '"': '"', "'": ''' })[c]!);
|
||||||
|
|
||||||
|
async function page(ctx: Ctx, title: string, body: string): Promise<string> {
|
||||||
|
const b = await branding(ctx).catch(() => ({ name: 'Sign in', colours: { primary: '#1f4e79' }, logoUrl: null }));
|
||||||
|
return `<!doctype html><html lang="en-ZA"><head><meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1"><meta name="robots" content="noindex">
|
||||||
|
<title>${esc(title)} · ${esc(b.name)}</title>
|
||||||
|
<style>body{font-family:system-ui,sans-serif;background:#f7f7f8;color:#1f2937;margin:0;display:flex;min-height:100vh;align-items:center;justify-content:center;padding:16px}
|
||||||
|
main{background:#fff;border-radius:16px;box-shadow:0 1px 3px rgba(0,0,0,.08);padding:32px;max-width:420px;width:100%;text-align:center}
|
||||||
|
h1{font-size:1.25rem;margin:0 0 12px}p{color:#4b5563;line-height:1.5}button,a.btn{display:inline-block;background:${esc(b.colours.primary)};color:#fff;border:0;border-radius:10px;padding:10px 20px;font-size:1rem;text-decoration:none;cursor:pointer}
|
||||||
|
img{max-height:56px;margin-bottom:16px}</style></head>
|
||||||
|
<body><main>${b.logoUrl ? `<img src="${esc(b.logoUrl)}" alt="">` : ''}<p style="margin:0 0 8px;font-weight:600">${esc(b.name)}</p>${body}</main></body></html>`;
|
||||||
|
}
|
||||||
|
|
||||||
|
export function renderError(ctx: Ctx) {
|
||||||
|
return async (k: KoaContextWithOIDC, out: { error: string; error_description?: string }, err?: Error) => {
|
||||||
|
console.warn(`[oidc] ${out.error}: ${out.error_description ?? ''}${err && !(err as { expose?: boolean }).expose ? ` (${err.stack})` : ''}`);
|
||||||
|
k.type = 'html';
|
||||||
|
const message = out.error === 'invalid_redirect_uri' || out.error === 'invalid_client'
|
||||||
|
? 'This sign-in link isn\'t from one of the church\'s sites, so it was stopped.'
|
||||||
|
: out.error_description || 'Something went wrong with signing in.';
|
||||||
|
k.body = await page(ctx, 'Sign-in problem', `<h1>We couldn't sign you in</h1><p>${esc(message)}</p><a class="btn" href="/account">Go to your account</a>`);
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
export function renderLogout(ctx: Ctx) {
|
||||||
|
return async (k: KoaContextWithOIDC, form: string) => {
|
||||||
|
k.type = 'html';
|
||||||
|
k.body = await page(ctx, 'Signing out', `${form}<h1>Signing you out…</h1><p>You'll be signed out of all the church's sites.</p>
|
||||||
|
<button form="op.logoutForm" type="submit" name="logout" value="yes">Sign out</button>
|
||||||
|
<script src="/api/static/logout.js"></script>`);
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
export function renderLoggedOut(ctx: Ctx) {
|
||||||
|
return async (k: KoaContextWithOIDC) => {
|
||||||
|
k.type = 'html';
|
||||||
|
k.body = await page(ctx, 'Signed out', '<h1>You\'re signed out</h1><p>You\'ve been signed out of all the church\'s sites.</p><a class="btn" href="/account">Sign in again</a>');
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Submits the sign-out form straight away (the person already chose to sign out on the product). */
|
||||||
|
export const LOGOUT_JS = 'document.addEventListener("DOMContentLoaded",function(){var f=document.getElementById("op.logoutForm");if(f){var i=document.createElement("input");i.type="hidden";i.name="logout";i.value="yes";f.appendChild(i);f.submit();}});';
|
||||||
@@ -0,0 +1,142 @@
|
|||||||
|
/**
|
||||||
|
* The OpenID Connect provider (oidc-provider 9, docs/ACCOUNTS-1.0-PLAN.md §3): authorization code
|
||||||
|
* with PKCE (S256) for every client, no implicit or hybrid flows, no refresh tokens, ES256 keys
|
||||||
|
* made on first start, `crosscode.identity/1` claims, RP-initiated and back-channel logout.
|
||||||
|
*
|
||||||
|
* Sign-in steps happen in our own pages (interaction/): the provider sends people to
|
||||||
|
* `/signin?uid=…`. Products of the church are first-party, so there's no consent screen: a grant
|
||||||
|
* for the scopes asked for is made when they sign in (`loadExistingGrant`).
|
||||||
|
*/
|
||||||
|
import crypto from 'node:crypto';
|
||||||
|
import Provider, { interactionPolicy, type Configuration, type KoaContextWithOIDC } from 'oidc-provider';
|
||||||
|
import { ACR_MFA, OIDC_PROVIDER_PATHS, OIDC_SCOPES } from '@crosscode/contracts';
|
||||||
|
import type { Ctx } from '../context.js';
|
||||||
|
import { identityClaims } from '../accounts/service.js';
|
||||||
|
import { currentNoticeVersion } from '../privacy/notice.js';
|
||||||
|
import { adapterFor } from './adapter.js';
|
||||||
|
import { selfClient } from './clients.js';
|
||||||
|
import { renderError, renderLogout, renderLoggedOut } from './pages.js';
|
||||||
|
|
||||||
|
const DAY = 24 * 60 * 60;
|
||||||
|
|
||||||
|
export const issuerOf = (ctx: Ctx) => `${ctx.config.publicUrl}${OIDC_PROVIDER_PATHS.issuer}`;
|
||||||
|
|
||||||
|
type Jwk = crypto.JsonWebKey & { kid: string; alg: string; use: string };
|
||||||
|
|
||||||
|
/** The signing keys (newest first), made the first time. `rotateKeys` adds a new one. */
|
||||||
|
export async function signingKeys(ctx: Ctx): Promise<Jwk[]> {
|
||||||
|
const keys = await ctx.settings.json<Jwk[]>('oidc_jwks', []);
|
||||||
|
if (keys.length) return keys;
|
||||||
|
return rotateKeys(ctx);
|
||||||
|
}
|
||||||
|
|
||||||
|
/** A new ES256 key in front; the previous one stays for checking tokens it signed (they last minutes). */
|
||||||
|
export async function rotateKeys(ctx: Ctx): Promise<Jwk[]> {
|
||||||
|
const old = await ctx.settings.json<Jwk[]>('oidc_jwks', []);
|
||||||
|
const { privateKey } = crypto.generateKeyPairSync('ec', { namedCurve: 'P-256' });
|
||||||
|
const jwk = { ...privateKey.export({ format: 'jwk' }), kid: crypto.randomBytes(8).toString('hex'), alg: 'ES256', use: 'sig' } as Jwk;
|
||||||
|
const keys = [jwk, ...old].slice(0, 2);
|
||||||
|
await ctx.settings.set('oidc_jwks', JSON.stringify(keys));
|
||||||
|
return keys;
|
||||||
|
}
|
||||||
|
|
||||||
|
/** The interaction policy: the usual login checks, plus ours (§2, §6). */
|
||||||
|
function policy(ctx: Ctx) {
|
||||||
|
const { base, Check } = interactionPolicy;
|
||||||
|
const p = base();
|
||||||
|
const login = p.get('login')!;
|
||||||
|
// A product asked for 2FA (`acr_values=mfa`) and this session signed in without it.
|
||||||
|
login.checks.add(new Check('mfa_required', 'This sign-in needs a second step', async (k: KoaContextWithOIDC) => {
|
||||||
|
const wanted = String(k.oidc.params?.acr_values ?? '').split(' ').includes(ACR_MFA);
|
||||||
|
return wanted && k.oidc.session?.acr !== ACR_MFA ? Check.REQUEST_PROMPT : Check.NO_NEED_TO_PROMPT;
|
||||||
|
}));
|
||||||
|
// A newer privacy notice since this person last accepted one, or their account changed.
|
||||||
|
login.checks.add(new Check('account_needs_attention', 'The privacy notice changed', async (k: KoaContextWithOIDC) => {
|
||||||
|
const sub = k.oidc.session?.accountId;
|
||||||
|
if (!sub) return Check.NO_NEED_TO_PROMPT;
|
||||||
|
const a = await ctx.db.account.findUnique({ where: { id: sub } });
|
||||||
|
if (!a || a.status !== 'active') return Check.REQUEST_PROMPT;
|
||||||
|
return a.noticeVersionAccepted < (await currentNoticeVersion(ctx)) ? Check.REQUEST_PROMPT : Check.NO_NEED_TO_PROMPT;
|
||||||
|
}));
|
||||||
|
return p;
|
||||||
|
}
|
||||||
|
|
||||||
|
export async function createProvider(ctx: Ctx): Promise<Provider> {
|
||||||
|
const keys = await signingKeys(ctx);
|
||||||
|
const sessionDays = Number((await ctx.settings.get('session_days')) || 30);
|
||||||
|
const config: Configuration = {
|
||||||
|
adapter: adapterFor(ctx),
|
||||||
|
clients: [selfClient(ctx)],
|
||||||
|
extraClientMetadata: { properties: ['crosscode.product'] },
|
||||||
|
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 } });
|
||||||
|
if (!a || a.status !== 'active') return undefined;
|
||||||
|
return { accountId: sub, claims: async () => identityClaims(ctx, a) as never };
|
||||||
|
},
|
||||||
|
claims: {
|
||||||
|
openid: ['sub', 'acr', 'amr', 'auth_time'],
|
||||||
|
profile: ['name', 'given_name', 'family_name'],
|
||||||
|
email: ['email', 'email_verified'],
|
||||||
|
phone: ['phone_number', 'phone_number_verified'],
|
||||||
|
crosscode: ['schema', 'news_consent', 'two_factor', 'privacy_notice_version'],
|
||||||
|
},
|
||||||
|
scopes: [...OIDC_SCOPES],
|
||||||
|
acrValues: ['pwd', ACR_MFA],
|
||||||
|
// The claims go in the ID token too, so a product has everything without calling userinfo.
|
||||||
|
conformIdTokenClaims: false,
|
||||||
|
responseTypes: ['code'],
|
||||||
|
pkce: { required: () => true },
|
||||||
|
features: {
|
||||||
|
devInteractions: { enabled: false },
|
||||||
|
rpInitiatedLogout: { enabled: true, logoutSource: renderLogout(ctx), postLogoutSuccessSource: renderLoggedOut(ctx) },
|
||||||
|
backchannelLogout: { enabled: true },
|
||||||
|
revocation: { enabled: true },
|
||||||
|
userinfo: { enabled: true },
|
||||||
|
},
|
||||||
|
// oidc-provider scopes the interaction cookie to this address's path, so it's the API's path for
|
||||||
|
// the sign-in (every step's call is under it); that address sends the browser on to the page
|
||||||
|
// (interaction/routes.ts). Absolute, so a proxy that doesn't keep the Host header can't send
|
||||||
|
// people to the backend's own port.
|
||||||
|
interactions: { url: (_k, interaction) => `${ctx.config.publicUrl}/api/v2/interaction/${interaction.uid}`, policy: policy(ctx) },
|
||||||
|
loadExistingGrant: async (k) => {
|
||||||
|
const grantId = k.oidc.result?.consent?.grantId || k.oidc.session!.grantIdFor(k.oidc.client!.clientId);
|
||||||
|
if (grantId) {
|
||||||
|
const existing = await k.oidc.provider.Grant.find(grantId);
|
||||||
|
if (existing) return existing;
|
||||||
|
}
|
||||||
|
// The church's own products: no consent screen.
|
||||||
|
const grant = new k.oidc.provider.Grant({ clientId: k.oidc.client!.clientId, accountId: k.oidc.session!.accountId! });
|
||||||
|
grant.addOIDCScope(OIDC_SCOPES.join(' '));
|
||||||
|
await grant.save();
|
||||||
|
return grant;
|
||||||
|
},
|
||||||
|
cookies: {
|
||||||
|
keys: ctx.secrets.cookieKeys(),
|
||||||
|
long: { signed: true, httpOnly: true, sameSite: 'lax' },
|
||||||
|
short: { signed: true, httpOnly: true, sameSite: 'lax' },
|
||||||
|
},
|
||||||
|
jwks: { keys: keys as never },
|
||||||
|
enabledJWA: { idTokenSigningAlgValues: ['ES256'], userinfoSigningAlgValues: ['ES256'] },
|
||||||
|
ttl: {
|
||||||
|
AccessToken: 600,
|
||||||
|
AuthorizationCode: 60,
|
||||||
|
IdToken: 600,
|
||||||
|
Interaction: 3600,
|
||||||
|
Grant: sessionDays * DAY,
|
||||||
|
// "Keep me signed in": `sessionDays`; otherwise until the browser closes (a transient cookie), at most a day.
|
||||||
|
Session: (_k, session) => (session.transient ? DAY : sessionDays * DAY),
|
||||||
|
},
|
||||||
|
renderError: renderError(ctx),
|
||||||
|
// oidc-provider refuses private addresses for back-channel logout (its SSRF protection). Local
|
||||||
|
// testing only (LINKS_ALLOW_PRIVATE): send without that check, as for the other link calls.
|
||||||
|
...(ctx.config.allowPrivateLinks && !ctx.config.production
|
||||||
|
? { fetch: (input: string | URL | Request, init?: RequestInit) => { const { dispatcher: _d, ...rest } = (init ?? {}) as RequestInit & { dispatcher?: unknown }; return fetch(input, rest); } }
|
||||||
|
: {}),
|
||||||
|
rotateRefreshToken: false,
|
||||||
|
issueRefreshToken: () => false,
|
||||||
|
};
|
||||||
|
const provider = new Provider(issuerOf(ctx), config);
|
||||||
|
provider.proxy = ctx.config.trustProxy;
|
||||||
|
return provider;
|
||||||
|
}
|
||||||
@@ -0,0 +1,45 @@
|
|||||||
|
/**
|
||||||
|
* The Accounts session (oidc-provider's own cookie) for the account pages and admin, and signing
|
||||||
|
* someone out everywhere: every session of theirs ends, and each product that session signed in to
|
||||||
|
* is told by OIDC Back-Channel Logout (docs/ACCOUNTS-1.0-PLAN.md §3).
|
||||||
|
*/
|
||||||
|
import type { Request, Response } from 'express';
|
||||||
|
import type Provider from 'oidc-provider';
|
||||||
|
import type { Ctx } from '../context.js';
|
||||||
|
import type { Account } from '../generated/prisma/client.js';
|
||||||
|
|
||||||
|
export type SignedIn = { account: Account; amr: string[]; acr: string | null; sessionId: string };
|
||||||
|
|
||||||
|
export async function currentSession(ctx: Ctx, provider: Provider, req: Request, res: Response): Promise<SignedIn | null> {
|
||||||
|
const k = provider.createContext(req, res);
|
||||||
|
const session = await provider.Session.get(k);
|
||||||
|
if (!session?.accountId) return null;
|
||||||
|
const account = await ctx.db.account.findUnique({ where: { id: session.accountId } });
|
||||||
|
if (!account || account.status !== 'active') return null;
|
||||||
|
return { account, amr: (session.amr as string[] | undefined) ?? [], acr: (session.acr as string | undefined) ?? null, sessionId: session.jti };
|
||||||
|
}
|
||||||
|
|
||||||
|
type StoredSession = { authorizations?: Record<string, { sid?: string; grantId?: string }> };
|
||||||
|
|
||||||
|
/** Ends every session of the account and tells the products. Returns how many products were told. */
|
||||||
|
export async function signOutEverywhere(ctx: Ctx, provider: Provider, accountId: string): Promise<number> {
|
||||||
|
const rows = await ctx.db.oidcPayload.findMany({ where: { model: 'Session', accountId } });
|
||||||
|
let told = 0;
|
||||||
|
for (const row of rows) {
|
||||||
|
const auths = (row.payload as StoredSession).authorizations ?? {};
|
||||||
|
for (const [clientId, auth] of Object.entries(auths)) {
|
||||||
|
if (auth.grantId) await ctx.db.oidcPayload.deleteMany({ where: { grantId: auth.grantId } });
|
||||||
|
try {
|
||||||
|
const client = await provider.Client.find(clientId);
|
||||||
|
if (client?.backchannelLogoutUri) {
|
||||||
|
await (client as unknown as { backchannelLogout(sub: string, sid: string): Promise<void> }).backchannelLogout(accountId, auth.sid ?? '');
|
||||||
|
told++;
|
||||||
|
}
|
||||||
|
} catch (e) {
|
||||||
|
console.warn(`[sessions] back-channel logout to ${clientId} failed:`, (e as Error).message, (e as { cause?: Error }).cause?.message ?? '');
|
||||||
|
}
|
||||||
|
}
|
||||||
|
await ctx.db.oidcPayload.deleteMany({ where: { id: row.id } });
|
||||||
|
}
|
||||||
|
return told;
|
||||||
|
}
|
||||||
@@ -0,0 +1,112 @@
|
|||||||
|
/**
|
||||||
|
* "Delete my account" (docs/ACCOUNTS-1.0-PLAN.md §6, as Cross Events): the account is deactivated
|
||||||
|
* and signed out everywhere at once; an admin approves; then every linked product gets
|
||||||
|
* `user.deleted`. A product that answers `deferred` (e.g. an open registration for an upcoming
|
||||||
|
* event) is asked again after its `retryAfter`. Once every product has answered `deleted`, the
|
||||||
|
* account is anonymised.
|
||||||
|
*/
|
||||||
|
import { IDENTITY_SCHEMA, userDeletedReplySchema } from '@crosscode/contracts';
|
||||||
|
import type { Request } from 'express';
|
||||||
|
import type Provider from 'oidc-provider';
|
||||||
|
import type { Ctx } from '../context.js';
|
||||||
|
import { audit, clientIp, loginEvent } from '../lib/audit.js';
|
||||||
|
import { onReply, queueCall } from '../links/deliveries.js';
|
||||||
|
import { signOutEverywhere } from '../oidc/sessions.js';
|
||||||
|
|
||||||
|
type ProductState = { status: 'pending' | 'deleted' | 'deferred'; reason?: string; retryAfter?: string; product?: string };
|
||||||
|
type States = Record<string, ProductState>;
|
||||||
|
|
||||||
|
export async function requestDeletion(ctx: Ctx, provider: Provider, accountId: string, req?: Request) {
|
||||||
|
const open = await ctx.db.deletionRequest.findFirst({ where: { accountId, status: { in: ['waiting_approval', 'approved'] } } });
|
||||||
|
await ctx.db.account.update({ where: { id: accountId }, data: { status: 'deactivated', deactivatedAt: ctx.now() } });
|
||||||
|
await signOutEverywhere(ctx, provider, accountId);
|
||||||
|
await loginEvent(ctx, accountId, 'signed_out_everywhere', req, { detail: { reason: 'deletion_requested' } });
|
||||||
|
return open ?? ctx.db.deletionRequest.create({ data: { accountId, requestedAt: ctx.now() } });
|
||||||
|
}
|
||||||
|
|
||||||
|
export async function cancelDeletion(ctx: Ctx, requestId: string, actor: { id: string; role: string }, req?: Request) {
|
||||||
|
const r = await ctx.db.deletionRequest.findUnique({ where: { id: requestId } });
|
||||||
|
if (!r || r.status !== 'waiting_approval') return null;
|
||||||
|
await ctx.db.deletionRequest.update({ where: { id: r.id }, data: { status: 'cancelled', completedAt: ctx.now() } });
|
||||||
|
await ctx.db.account.update({ where: { id: r.accountId }, data: { status: 'active', deactivatedAt: null } });
|
||||||
|
await audit(ctx, { actorId: actor.id, actorRole: actor.role, action: 'deletion_cancelled', targetType: 'account', targetId: r.accountId, ip: clientIp(req) });
|
||||||
|
return r;
|
||||||
|
}
|
||||||
|
|
||||||
|
export async function approveDeletion(ctx: Ctx, requestId: string, actor: { id: string; role: string }, req?: Request) {
|
||||||
|
const r = await ctx.db.deletionRequest.findUnique({ where: { id: requestId } });
|
||||||
|
if (!r || r.status !== 'waiting_approval') return null;
|
||||||
|
const links = await ctx.db.productLink.findMany();
|
||||||
|
const states: States = Object.fromEntries(links.map((l) => [l.installId, { status: 'pending', product: l.product }]));
|
||||||
|
await ctx.db.deletionRequest.update({ where: { id: r.id }, data: { status: 'approved', approvedAt: ctx.now(), approvedById: actor.id, products: states as never } });
|
||||||
|
await audit(ctx, { actorId: actor.id, actorRole: actor.role, action: 'deletion_approved', targetType: 'account', targetId: r.accountId, ip: clientIp(req) });
|
||||||
|
await askProducts(ctx, r.id, r.accountId, links.map((l) => l.installId));
|
||||||
|
await finishIfDone(ctx, r.id);
|
||||||
|
return r;
|
||||||
|
}
|
||||||
|
|
||||||
|
async function askProducts(ctx: Ctx, requestId: string, accountId: string, linkIds: string[]) {
|
||||||
|
if (!linkIds.length) return;
|
||||||
|
await queueCall(ctx, 'user.deleted', (callId) => ({ schema: IDENTITY_SCHEMA, type: 'user.deleted', callId, occurredAt: ctx.now().toISOString(), sub: accountId, approvedAt: ctx.now().toISOString(), requestId }), { linkIds });
|
||||||
|
}
|
||||||
|
|
||||||
|
onReply('user.deleted', async (ctx, delivery, reply) => {
|
||||||
|
const body = delivery.body as { requestId?: string };
|
||||||
|
if (!body.requestId) return;
|
||||||
|
const r = await ctx.db.deletionRequest.findUnique({ where: { id: body.requestId } });
|
||||||
|
if (!r || r.status !== 'approved') return;
|
||||||
|
const parsed = userDeletedReplySchema.safeParse(reply);
|
||||||
|
const states = { ...(r.products as States) };
|
||||||
|
const prev = states[delivery.linkId] ?? { status: 'pending' };
|
||||||
|
states[delivery.linkId] = !parsed.success
|
||||||
|
? { ...prev, status: 'deferred', reason: 'The product answered in a way Accounts doesn\'t understand; asking again tomorrow.', retryAfter: new Date(ctx.now().getTime() + 24 * 3600e3).toISOString() }
|
||||||
|
: parsed.data.status === 'deleted'
|
||||||
|
? { ...prev, status: 'deleted' }
|
||||||
|
: { ...prev, status: 'deferred', reason: parsed.data.reason, retryAfter: parsed.data.retryAfter };
|
||||||
|
await ctx.db.deletionRequest.update({ where: { id: r.id }, data: { products: states as never } });
|
||||||
|
await finishIfDone(ctx, r.id);
|
||||||
|
});
|
||||||
|
|
||||||
|
/** Anonymises the account once every product has deleted its part. */
|
||||||
|
export async function finishIfDone(ctx: Ctx, requestId: string) {
|
||||||
|
const r = await ctx.db.deletionRequest.findUnique({ where: { id: requestId } });
|
||||||
|
if (!r || r.status !== 'approved') return false;
|
||||||
|
const states = r.products as States;
|
||||||
|
// A product disconnected since has nothing left to delete here.
|
||||||
|
const linked = new Set((await ctx.db.productLink.findMany({ select: { installId: true } })).map((l) => l.installId));
|
||||||
|
if (Object.entries(states).some(([id, s]) => linked.has(id) && s.status !== 'deleted')) return false;
|
||||||
|
await anonymise(ctx, r.accountId);
|
||||||
|
await ctx.db.deletionRequest.update({ where: { id: r.id }, data: { status: 'done', completedAt: ctx.now() } });
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
|
||||||
|
export async function anonymise(ctx: Ctx, accountId: string) {
|
||||||
|
await ctx.db.recoveryCode.deleteMany({ where: { accountId } });
|
||||||
|
await ctx.db.emailToken.deleteMany({ where: { accountId } });
|
||||||
|
await ctx.db.account.update({
|
||||||
|
where: { id: accountId },
|
||||||
|
data: {
|
||||||
|
name: 'Deleted account', givenName: null, familyName: null, email: `deleted-${accountId}@deleted.invalid`, emailVerified: false,
|
||||||
|
phone: null, phoneVerified: false, passwordHash: null, twoFactorMethod: null, totpSecret: null, totpLastStep: null,
|
||||||
|
newsEmail: false, newsWhatsApp: false, status: 'deleted', anonymisedAt: ctx.now(),
|
||||||
|
},
|
||||||
|
});
|
||||||
|
// Sign-in history held IP addresses and devices: gone with the person.
|
||||||
|
await ctx.db.loginEvent.deleteMany({ where: { accountId } });
|
||||||
|
}
|
||||||
|
|
||||||
|
/** The `deletions` job: ask products that deferred again once their `retryAfter` has passed. */
|
||||||
|
export async function runDeletionJob(ctx: Ctx) {
|
||||||
|
const open = await ctx.db.deletionRequest.findMany({ where: { status: 'approved' } });
|
||||||
|
let asked = 0;
|
||||||
|
for (const r of open) {
|
||||||
|
const states = { ...(r.products as States) };
|
||||||
|
const due = Object.entries(states).filter(([, s]) => s.status === 'deferred' && s.retryAfter && new Date(s.retryAfter) <= ctx.now()).map(([id]) => id);
|
||||||
|
if (!due.length) continue;
|
||||||
|
for (const id of due) states[id] = { ...states[id]!, status: 'pending' };
|
||||||
|
await ctx.db.deletionRequest.update({ where: { id: r.id }, data: { products: states as never } });
|
||||||
|
await askProducts(ctx, r.id, r.accountId, due);
|
||||||
|
asked += due.length;
|
||||||
|
}
|
||||||
|
return { asked };
|
||||||
|
}
|
||||||
@@ -0,0 +1,88 @@
|
|||||||
|
/**
|
||||||
|
* "Download my data" (docs/ACCOUNTS-1.0-PLAN.md §6): Accounts' own part, plus a `user.export` call
|
||||||
|
* to every linked product; their answers (`crosscode.identity/1` export sections) are put together
|
||||||
|
* in one file. It's ready once every product has answered, or after 24 hours with the missing ones
|
||||||
|
* listed; the person gets an email and downloads it from their account page for 7 days.
|
||||||
|
*/
|
||||||
|
import fs from 'node:fs/promises';
|
||||||
|
import path from 'node:path';
|
||||||
|
import { IDENTITY_SCHEMA, userExportReplySchema } from '@crosscode/contracts';
|
||||||
|
import type { Ctx } from '../context.js';
|
||||||
|
import { onReply, queueCall } from '../links/deliveries.js';
|
||||||
|
|
||||||
|
const WAIT_MS = 24 * 3600e3;
|
||||||
|
const KEEP_MS = 7 * 24 * 3600e3;
|
||||||
|
export const exportsDir = () => path.resolve(process.env.EXPORTS_DIR || 'exports');
|
||||||
|
|
||||||
|
type Parts = Record<string, unknown>;
|
||||||
|
|
||||||
|
async function ownPart(ctx: Ctx, accountId: string) {
|
||||||
|
const a = await ctx.db.account.findUniqueOrThrow({ where: { id: accountId } });
|
||||||
|
const [signIns, consents, notices] = await Promise.all([
|
||||||
|
ctx.db.loginEvent.findMany({ where: { accountId }, orderBy: { createdAt: 'desc' }, take: 500 }),
|
||||||
|
ctx.db.consentChange.findMany({ where: { accountId }, orderBy: { createdAt: 'asc' } }),
|
||||||
|
ctx.db.noticeAcceptance.findMany({ where: { accountId }, orderBy: { acceptedAt: 'asc' } }),
|
||||||
|
]);
|
||||||
|
return {
|
||||||
|
product: 'accounts',
|
||||||
|
sections: [
|
||||||
|
{ key: 'profile', title: 'Your account', records: [{ name: a.name, givenName: a.givenName, familyName: a.familyName, email: a.email, emailVerified: a.emailVerified, phone: a.phone, twoFactor: a.twoFactorMethod, createdAt: a.createdAt, lastSignInAt: a.lastSignInAt }] },
|
||||||
|
{ key: 'news_consent', title: 'News consent', records: consents.map((c) => ({ channel: c.channel, granted: c.granted, source: c.source, at: c.createdAt })) },
|
||||||
|
{ key: 'privacy_notice', title: 'Privacy notices accepted', records: notices.map((n) => ({ version: n.version, acceptedAt: n.acceptedAt })) },
|
||||||
|
{ key: 'sign_ins', title: 'Sign-ins and changes', records: signIns.map((e) => ({ type: e.type, at: e.createdAt, ip: e.ip, device: e.userAgent })) },
|
||||||
|
],
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
export async function requestExport(ctx: Ctx, accountId: string) {
|
||||||
|
const open = await ctx.db.dataExport.findFirst({ where: { accountId, status: 'collecting' } });
|
||||||
|
if (open) return open;
|
||||||
|
const exp = await ctx.db.dataExport.create({ data: { accountId, parts: { accounts: await ownPart(ctx, accountId) } as never, createdAt: ctx.now(), expiresAt: new Date(ctx.now().getTime() + WAIT_MS + KEEP_MS) } });
|
||||||
|
await queueCall(ctx, 'user.export', (callId) => ({ schema: IDENTITY_SCHEMA, type: 'user.export', callId, occurredAt: ctx.now().toISOString(), sub: accountId, exportId: exp.id }));
|
||||||
|
await finishIfComplete(ctx, exp.id);
|
||||||
|
return exp;
|
||||||
|
}
|
||||||
|
|
||||||
|
onReply('user.export', async (ctx, delivery, reply) => {
|
||||||
|
const parsed = userExportReplySchema.safeParse(reply);
|
||||||
|
const body = delivery.body as { exportId?: string };
|
||||||
|
if (!body.exportId) return;
|
||||||
|
const exp = await ctx.db.dataExport.findUnique({ where: { id: body.exportId } });
|
||||||
|
if (!exp || exp.status !== 'collecting') return;
|
||||||
|
const parts = { ...(exp.parts as Parts), [delivery.linkId]: parsed.success ? parsed.data : { error: 'The product answered in a way Accounts doesn\'t understand.' } };
|
||||||
|
await ctx.db.dataExport.update({ where: { id: exp.id }, data: { parts: parts as never } });
|
||||||
|
await finishIfComplete(ctx, exp.id);
|
||||||
|
});
|
||||||
|
|
||||||
|
/** Writes the file and emails the person once every product answered (or the wait is over). */
|
||||||
|
export async function finishIfComplete(ctx: Ctx, exportId: string, force = false) {
|
||||||
|
const exp = await ctx.db.dataExport.findUnique({ where: { id: exportId } });
|
||||||
|
if (!exp || exp.status !== 'collecting') return false;
|
||||||
|
const links = await ctx.db.productLink.findMany();
|
||||||
|
const parts = exp.parts as Parts;
|
||||||
|
const missing = links.filter((l) => !(l.installId in parts));
|
||||||
|
if (missing.length && !force) return false;
|
||||||
|
const file = path.join(exportsDir(), `${exp.id}.json`);
|
||||||
|
await fs.mkdir(exportsDir(), { recursive: true });
|
||||||
|
await fs.writeFile(file, JSON.stringify({
|
||||||
|
schema: IDENTITY_SCHEMA, exportId: exp.id, generatedAt: ctx.now().toISOString(),
|
||||||
|
parts: Object.values(parts),
|
||||||
|
missing: missing.map((l) => ({ product: l.product, url: l.url, note: 'Didn\'t answer within 24 hours. Ask the church for this part.' })),
|
||||||
|
}, null, 2), { mode: 0o600 });
|
||||||
|
await ctx.db.dataExport.update({ where: { id: exp.id }, data: { status: 'ready', file, readyAt: ctx.now(), expiresAt: new Date(ctx.now().getTime() + KEEP_MS) } });
|
||||||
|
const a = await ctx.db.account.findUnique({ where: { id: exp.accountId } });
|
||||||
|
if (a) await ctx.messenger.email({ to: a.email, subject: 'Your data is ready to download', text: `The copy of your data you asked for is ready. Download it from your account page (it's kept for 7 days):\n${ctx.config.publicUrl}/account/privacy` });
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
|
||||||
|
/** The `exports` job: finish exports that waited long enough, delete expired files. */
|
||||||
|
export async function runExportsJob(ctx: Ctx) {
|
||||||
|
const stale = await ctx.db.dataExport.findMany({ where: { status: 'collecting', createdAt: { lt: new Date(ctx.now().getTime() - WAIT_MS) } } });
|
||||||
|
for (const e of stale) await finishIfComplete(ctx, e.id, true);
|
||||||
|
const expired = await ctx.db.dataExport.findMany({ where: { status: 'ready', expiresAt: { lt: ctx.now() } } });
|
||||||
|
for (const e of expired) {
|
||||||
|
if (e.file) await fs.rm(e.file, { force: true });
|
||||||
|
await ctx.db.dataExport.update({ where: { id: e.id }, data: { status: 'expired', file: null } });
|
||||||
|
}
|
||||||
|
return { finished: stale.length, expired: expired.length };
|
||||||
|
}
|
||||||
@@ -0,0 +1,45 @@
|
|||||||
|
/**
|
||||||
|
* The privacy notice (ROADMAP-v3 §3, as Cross Events): versions an admin publishes, and who
|
||||||
|
* accepted which. Version 1 is the built-in notice; published versions are 2, 3, … Someone who
|
||||||
|
* accepted an older version is asked again before signing in to a product (§5 of the plan).
|
||||||
|
*/
|
||||||
|
import type { Ctx } from '../context.js';
|
||||||
|
import { church } from '../church/profile.js';
|
||||||
|
|
||||||
|
export const BUILT_IN_VERSION = 1;
|
||||||
|
|
||||||
|
export async function builtInNotice(ctx: Ctx) {
|
||||||
|
const c = await church(ctx);
|
||||||
|
const contact = c.contact.email ? ` You can reach us at ${c.contact.email}.` : '';
|
||||||
|
return {
|
||||||
|
version: BUILT_IN_VERSION,
|
||||||
|
title: `How ${c.name} looks after your information`,
|
||||||
|
body: [
|
||||||
|
`${c.name} keeps your name, email address and (if you give it) phone number so you can sign in to the church's websites and apps, and so we can contact you about what you've signed up for.`,
|
||||||
|
'We only send you news if you say yes, and you can change that at any time on your account page.',
|
||||||
|
'You can download everything we hold about you, or ask us to delete your account, from your account page. We keep a record of sign-ins to protect your account.',
|
||||||
|
`We don't sell or share your information. The services that store it for us are bound to keep it safe.${contact}`,
|
||||||
|
].join('\n\n'),
|
||||||
|
publishedAt: null as Date | null,
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
export async function currentNotice(ctx: Ctx) {
|
||||||
|
const latest = await ctx.db.privacyNotice.findFirst({ orderBy: { version: 'desc' } });
|
||||||
|
return latest ?? (await builtInNotice(ctx));
|
||||||
|
}
|
||||||
|
|
||||||
|
export async function currentNoticeVersion(ctx: Ctx): Promise<number> {
|
||||||
|
return (await currentNotice(ctx)).version;
|
||||||
|
}
|
||||||
|
|
||||||
|
export async function accept(ctx: Ctx, accountId: string, version: number) {
|
||||||
|
await ctx.db.noticeAcceptance.create({ data: { accountId, version, acceptedAt: ctx.now() } });
|
||||||
|
await ctx.db.account.update({ where: { id: accountId }, data: { noticeVersionAccepted: version } });
|
||||||
|
}
|
||||||
|
|
||||||
|
export async function publish(ctx: Ctx, input: { title: string; body: string }, actorId: string) {
|
||||||
|
const latest = await ctx.db.privacyNotice.findFirst({ orderBy: { version: 'desc' } });
|
||||||
|
const version = Math.max(BUILT_IN_VERSION, latest?.version ?? BUILT_IN_VERSION) + 1;
|
||||||
|
return ctx.db.privacyNotice.create({ data: { version, title: input.title, body: input.body, publishedAt: ctx.now(), publishedById: actorId } });
|
||||||
|
}
|
||||||
@@ -0,0 +1,57 @@
|
|||||||
|
/**
|
||||||
|
* Public endpoints: the church's branding for the sign-in pages, the church profile for its
|
||||||
|
* products (`GET /api/church/v1`, contracts 1.5.0), and Connect (`/api/links/v1/*`, as Events 2.4).
|
||||||
|
*/
|
||||||
|
import express, { type Response } from 'express';
|
||||||
|
import { CHURCH_PATHS, LINK_PATHS, LINK_SCHEMA } from '@crosscode/contracts';
|
||||||
|
import type { Ctx } from '../context.js';
|
||||||
|
import { handle, limit } from '../http.js';
|
||||||
|
import { branding, church } from '../church/profile.js';
|
||||||
|
import { acceptConnect, acceptDisconnect, LinkError } from '../links/connect.js';
|
||||||
|
import { setupNeeded } from '../setup/routes.js';
|
||||||
|
import { currentNotice } from '../privacy/notice.js';
|
||||||
|
|
||||||
|
const strip = (p: string) => p.replace(/^\/api/, '');
|
||||||
|
|
||||||
|
function linkError(res: Response, e: unknown) {
|
||||||
|
if (e instanceof LinkError) return res.status(e.status).json({ message: e.message, code: e.code });
|
||||||
|
console.error('[links]', e);
|
||||||
|
return res.status(500).json({ message: 'Something went wrong.', code: 'SERVER_ERROR' });
|
||||||
|
}
|
||||||
|
|
||||||
|
export function publicRouter(ctx: Ctx) {
|
||||||
|
const r = express.Router();
|
||||||
|
const json = express.json({ limit: '16kb' });
|
||||||
|
|
||||||
|
r.get('/v2/branding', handle(async () => ({ ...(await branding(ctx)), setupNeeded: await setupNeeded(ctx) })));
|
||||||
|
|
||||||
|
// The privacy notice, for the sign-up page's link (public).
|
||||||
|
r.get('/v2/notice', handle(async () => {
|
||||||
|
const n = await currentNotice(ctx);
|
||||||
|
return { version: n.version, title: n.title, body: n.body, publishedAt: n.publishedAt };
|
||||||
|
}));
|
||||||
|
|
||||||
|
r.get(strip(CHURCH_PATHS.profile), limit(600), handle(async (_req, res) => {
|
||||||
|
res.set('Cache-Control', 'public, max-age=60');
|
||||||
|
return church(ctx);
|
||||||
|
}));
|
||||||
|
|
||||||
|
r.post(strip(LINK_PATHS.connect), limit(30), json, async (req, res) => {
|
||||||
|
try {
|
||||||
|
res.json(await acceptConnect(ctx, req.body, req));
|
||||||
|
} catch (e) {
|
||||||
|
linkError(res, e);
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
r.post(strip(LINK_PATHS.disconnect), limit(30), json, async (req, res) => {
|
||||||
|
try {
|
||||||
|
await acceptDisconnect(ctx, req.body, req);
|
||||||
|
res.json({ schema: LINK_SCHEMA, type: 'link.disconnected' });
|
||||||
|
} catch (e) {
|
||||||
|
linkError(res, e);
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
return r;
|
||||||
|
}
|
||||||
@@ -0,0 +1,70 @@
|
|||||||
|
/**
|
||||||
|
* First run (`/setup`): the church's name, the first admin and (unless the Hub installed it with
|
||||||
|
* HUB_LICENCE_KEY) the licence key. Only while there's no admin. On a Hub install the first admin
|
||||||
|
* must use the email address the Hub was given (HUB_ADMIN_EMAIL), so nobody else can take it.
|
||||||
|
*/
|
||||||
|
import express from 'express';
|
||||||
|
import type { Ctx } from '../context.js';
|
||||||
|
import { ApiError, handle, limit } from '../http.js';
|
||||||
|
import { audit, clientIp, loginEvent } from '../lib/audit.js';
|
||||||
|
import { hashPassword, passwordProblem } from '../lib/passwords.js';
|
||||||
|
import { emailProblem, normaliseEmail } from '../accounts/service.js';
|
||||||
|
import { updateProfile } from '../church/profile.js';
|
||||||
|
import { connect as connectHub } from '../hub/client.js';
|
||||||
|
import { currentNotice } from '../privacy/notice.js';
|
||||||
|
|
||||||
|
export async function setupNeeded(ctx: Ctx): Promise<boolean> {
|
||||||
|
return (await ctx.db.account.count({ where: { role: 'admin', status: 'active' } })) === 0;
|
||||||
|
}
|
||||||
|
|
||||||
|
export function setupRouter(ctx: Ctx) {
|
||||||
|
const r = express.Router();
|
||||||
|
|
||||||
|
r.get('/setup', handle(async () => ({
|
||||||
|
needed: await setupNeeded(ctx),
|
||||||
|
hubConnected: !!(await ctx.settings.get('hub_install_id')),
|
||||||
|
adminEmail: ctx.config.hubAdminEmail,
|
||||||
|
})));
|
||||||
|
|
||||||
|
r.post('/setup', limit(10, 60), handle(async (req) => {
|
||||||
|
if (!(await setupNeeded(ctx))) throw new ApiError(409, 'DONE', 'Accounts is already set up. Sign in instead.');
|
||||||
|
const b = req.body ?? {};
|
||||||
|
const fields: Record<string, string> = {};
|
||||||
|
const churchName = String(b.churchName ?? '').trim();
|
||||||
|
const name = String(b.name ?? '').trim();
|
||||||
|
const email = normaliseEmail(b.email);
|
||||||
|
if (churchName.length < 2) fields.churchName = 'Enter the church\'s name.';
|
||||||
|
if (name.length < 2) fields.name = 'Enter your name.';
|
||||||
|
const ep = emailProblem(email);
|
||||||
|
if (ep) fields.email = ep;
|
||||||
|
else if (ctx.config.hubAdminEmail && email !== normaliseEmail(ctx.config.hubAdminEmail)) fields.email = 'Use the email address your provider set up this site for.';
|
||||||
|
const pp = passwordProblem(b.password);
|
||||||
|
if (pp) fields.password = pp;
|
||||||
|
const hubConnected = !!(await ctx.settings.get('hub_install_id'));
|
||||||
|
if (!hubConnected && !String(b.licenceKey ?? '').trim()) fields.licenceKey = 'Enter the licence key from your provider (CCA-…).';
|
||||||
|
if (Object.keys(fields).length) throw new ApiError(400, 'VALIDATION', 'Some details need fixing.', fields);
|
||||||
|
|
||||||
|
if (!hubConnected) {
|
||||||
|
try {
|
||||||
|
await connectHub(ctx, String(b.licenceKey), { name, email });
|
||||||
|
} catch (e) {
|
||||||
|
const msg = (e as Error).message;
|
||||||
|
throw new ApiError(400, 'LICENCE', msg, { licenceKey: msg });
|
||||||
|
}
|
||||||
|
}
|
||||||
|
await updateProfile(ctx, { name: churchName });
|
||||||
|
const parts = name.split(/\s+/);
|
||||||
|
const notice = await currentNotice(ctx);
|
||||||
|
const a = await ctx.db.account.upsert({
|
||||||
|
where: { email },
|
||||||
|
create: { name, givenName: parts[0] ?? null, familyName: parts.slice(1).join(' ') || null, email, role: 'admin', passwordHash: await hashPassword(String(b.password)), noticeVersionAccepted: notice.version, newsAskedAt: ctx.now() },
|
||||||
|
update: { role: 'admin', status: 'active', passwordHash: await hashPassword(String(b.password)) },
|
||||||
|
});
|
||||||
|
await loginEvent(ctx, a.id, 'account_created', req);
|
||||||
|
await audit(ctx, { actorId: a.id, actorRole: 'admin', action: 'setup_completed', targetType: 'account', targetId: a.id, ip: clientIp(req) });
|
||||||
|
// Signing in sets up 2FA (admins must have it) and verifies the email address.
|
||||||
|
return { done: true, next: '/api/self/signin?returnTo=/admin' };
|
||||||
|
}));
|
||||||
|
|
||||||
|
return r;
|
||||||
|
}
|
||||||
@@ -0,0 +1,85 @@
|
|||||||
|
// @crosscode/auth-client (the product side, packages/auth-client) against the real provider:
|
||||||
|
// what the Website, App and Events 3.0 will run.
|
||||||
|
import assert from 'node:assert/strict';
|
||||||
|
import { after, before, describe, test } from 'node:test';
|
||||||
|
import { OIDC_CLIENT_PATHS } from '@crosscode/contracts';
|
||||||
|
import { accountsClient, type AccountsClient } from '@crosscode/auth-client';
|
||||||
|
import { Browser, PRODUCT_ID, startHarness, type Harness } from './support/harness.js';
|
||||||
|
import { runDue } from '../src/links/deliveries.js';
|
||||||
|
import { signOutEverywhere } from '../src/oidc/sessions.js';
|
||||||
|
|
||||||
|
let h: Harness;
|
||||||
|
let auth: AccountsClient;
|
||||||
|
before(async () => {
|
||||||
|
h = await startHarness();
|
||||||
|
auth = await accountsClient({ accountsUrl: h.publicUrl, productUrl: h.productUrl, clientId: PRODUCT_ID, linkSecret: h.linkSecret, allowInsecure: true });
|
||||||
|
await h.makeAccount({ email: 'client@hope.test', password: 'Correct-horse-1' });
|
||||||
|
});
|
||||||
|
after(async () => { await h.close(); });
|
||||||
|
|
||||||
|
async function signInWith(returnTo: string) {
|
||||||
|
const browser = new Browser();
|
||||||
|
const { url, cookie } = await auth.startSignIn(returnTo);
|
||||||
|
const signin = await browser.follow(url, (u) => u.pathname === '/signin');
|
||||||
|
const uid = signin.url.searchParams.get('uid')!;
|
||||||
|
const step = await h.api(browser, 'POST', `/api/v2/interaction/${uid}/password`, { email: 'client@hope.test', password: 'Correct-horse-1' });
|
||||||
|
const back = await browser.follow(step.body.redirectTo as string, (u) => u.pathname === OIDC_CLIENT_PATHS.callback);
|
||||||
|
return auth.finishSignIn(back.url, cookie);
|
||||||
|
}
|
||||||
|
|
||||||
|
describe('@crosscode/auth-client', () => {
|
||||||
|
test('signs in and returns to the page', async () => {
|
||||||
|
const r = await signInWith('/sermons/2026/advent?part=2');
|
||||||
|
assert.equal(r.claims.email, 'client@hope.test');
|
||||||
|
assert.equal(r.returnTo, '/sermons/2026/advent?part=2');
|
||||||
|
assert.ok(r.idToken);
|
||||||
|
});
|
||||||
|
|
||||||
|
test('a foreign return address is never followed', async () => {
|
||||||
|
for (const evil of ['//evil.example/x', 'https://evil.example/', '/\\evil.example']) {
|
||||||
|
assert.equal((await signInWith(evil)).returnTo, '/', evil);
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
test('without the cookie from starting, finishing fails', async () => {
|
||||||
|
await assert.rejects(auth.finishSignIn(`${h.productUrl}${OIDC_CLIENT_PATHS.callback}?code=x&state=y`, undefined), /expired/);
|
||||||
|
});
|
||||||
|
|
||||||
|
test('checks Accounts\' signed calls and refuses changed ones', async () => {
|
||||||
|
const { profileChanged } = await import('../src/accounts/service.js');
|
||||||
|
const a = (await h.db.account.findUnique({ where: { email: 'client@hope.test' } }))!;
|
||||||
|
h.received.length = 0;
|
||||||
|
await profileChanged(h.ctx, a.id as string);
|
||||||
|
await runDue(h.ctx);
|
||||||
|
const call = h.received.find((r) => r.path === '/api/accounts/v1/events')!;
|
||||||
|
const read = auth.verifyAccountsCall(call.body, call.headers as Record<string, string>);
|
||||||
|
assert.equal(read.type, 'user.updated');
|
||||||
|
assert.equal(read.sub, a.id);
|
||||||
|
assert.throws(() => auth.verifyAccountsCall(call.body.replace('client@hope.test', 'attacker@evil.test'), call.headers as Record<string, string>), /isn't signed/);
|
||||||
|
});
|
||||||
|
|
||||||
|
test('checks a back-channel logout token', async () => {
|
||||||
|
const browser = new Browser();
|
||||||
|
const { url, cookie } = await auth.startSignIn('/');
|
||||||
|
const signin = await browser.follow(url, (u) => u.pathname === '/signin');
|
||||||
|
const step = await h.api(browser, 'POST', `/api/v2/interaction/${signin.url.searchParams.get('uid')}/password`, { email: 'client@hope.test', password: 'Correct-horse-1' });
|
||||||
|
const back = await browser.follow(step.body.redirectTo as string, (u) => u.pathname === OIDC_CLIENT_PATHS.callback);
|
||||||
|
const { claims } = await auth.finishSignIn(back.url, cookie);
|
||||||
|
h.received.length = 0;
|
||||||
|
await signOutEverywhere(h.ctx, h.provider, claims.sub);
|
||||||
|
const logout = h.received.find((r) => r.path === OIDC_CLIENT_PATHS.backchannelLogout)!;
|
||||||
|
const token = new URLSearchParams(logout.body).get('logout_token')!;
|
||||||
|
const out = await auth.verifyLogoutToken(token);
|
||||||
|
assert.equal(out.sub, claims.sub);
|
||||||
|
assert.ok(out.sid);
|
||||||
|
const [hd, p, s] = token.split('.');
|
||||||
|
const forged = `${hd}.${Buffer.from(JSON.stringify({ ...JSON.parse(Buffer.from(p!, 'base64url').toString()), sub: 'someone-else' })).toString('base64url')}.${s}`;
|
||||||
|
await assert.rejects(auth.verifyLogoutToken(forged), /isn't valid/);
|
||||||
|
});
|
||||||
|
|
||||||
|
test('the sign-out address ends at the product', () => {
|
||||||
|
const u = new URL(auth.signOutUrl('id-token'));
|
||||||
|
assert.equal(u.pathname, '/api/oidc/session/end');
|
||||||
|
assert.equal(u.searchParams.get('post_logout_redirect_uri'), `${h.productUrl}/`);
|
||||||
|
});
|
||||||
|
});
|
||||||
@@ -0,0 +1,95 @@
|
|||||||
|
// The small pieces: passwords (including bcrypt hashes Cross Events 3.0 will bring across), codes,
|
||||||
|
// recovery codes, secrets at rest, licence states, the church profile rules.
|
||||||
|
import assert from 'node:assert/strict';
|
||||||
|
import { describe, test } from 'node:test';
|
||||||
|
import bcrypt from 'bcryptjs';
|
||||||
|
import { hashPassword, needsRehash, passwordProblem, verifyPassword } from '../src/lib/passwords.js';
|
||||||
|
import { codeAt, generateSecret, matchStep, otpauthUrl } from '../src/lib/totp.js';
|
||||||
|
import { hashRecoveryCode, newRecoveryCodes, normaliseRecoveryCode } from '../src/lib/recoveryCodes.js';
|
||||||
|
import { Secrets } from '../src/lib/crypto.js';
|
||||||
|
import { stateFor, type LicenceClaims } from '../src/hub/licence.js';
|
||||||
|
import { normalisePhone } from '../src/accounts/service.js';
|
||||||
|
import { waNumber } from '../src/lib/messages.js';
|
||||||
|
|
||||||
|
describe('passwords', () => {
|
||||||
|
test('Argon2id hashes verify, wrong passwords don\'t', async () => {
|
||||||
|
const h = await hashPassword('Correct-horse-1');
|
||||||
|
assert.match(h, /^\$argon2id\$/);
|
||||||
|
assert.equal(await verifyPassword('Correct-horse-1', h), true);
|
||||||
|
assert.equal(await verifyPassword('wrong-password', h), false);
|
||||||
|
assert.equal(needsRehash(h), false);
|
||||||
|
});
|
||||||
|
|
||||||
|
test('bcrypt hashes from Cross Events verify and are marked for re-hashing', async () => {
|
||||||
|
const h = await bcrypt.hash('Old-events-password', 4);
|
||||||
|
assert.equal(await verifyPassword('Old-events-password', h), true);
|
||||||
|
assert.equal(needsRehash(h), true);
|
||||||
|
assert.equal(await verifyPassword('anything', null), false);
|
||||||
|
assert.equal(await verifyPassword('anything', 'not-a-hash'), false);
|
||||||
|
});
|
||||||
|
|
||||||
|
test('at least 8 characters', () => {
|
||||||
|
assert.ok(passwordProblem('short'));
|
||||||
|
assert.equal(passwordProblem('long-enough'), null);
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
describe('authenticator codes', () => {
|
||||||
|
test('a code works once, with a step either side for clock drift', () => {
|
||||||
|
const secret = generateSecret();
|
||||||
|
const now = Date.now();
|
||||||
|
const step = Math.floor(now / 30000);
|
||||||
|
assert.equal(matchStep(secret, codeAt(secret, step), { now }), step);
|
||||||
|
assert.equal(matchStep(secret, codeAt(secret, step - 1), { now }), step - 1);
|
||||||
|
assert.equal(matchStep(secret, codeAt(secret, step - 3), { now }), null);
|
||||||
|
assert.equal(matchStep(secret, codeAt(secret, step), { now, afterStep: step }), null);
|
||||||
|
assert.match(otpauthUrl(secret, 'a@b.co', 'Hope Family'), /^otpauth:\/\/totp\/Hope%20Family%3Aa%40b\.co\?secret=/);
|
||||||
|
});
|
||||||
|
|
||||||
|
test('the same codes as Cross Events 2.3 for the same secret (RFC 6238 test vector)', () => {
|
||||||
|
// RFC 6238 SHA-1 secret "12345678901234567890" in base32, T = 59 s → 94287082 (last 6 digits).
|
||||||
|
assert.equal(codeAt('GEZDGNBVGY3TQOJQGEZDGNBVGY3TQOJQ', 1), '287082');
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
describe('recovery codes', () => {
|
||||||
|
test('ten, readable, matched whatever the case and dashes', () => {
|
||||||
|
const { codes, hashes } = newRecoveryCodes();
|
||||||
|
assert.equal(codes.length, 10);
|
||||||
|
assert.match(codes[0]!, /^[a-z2-9]{4}-[a-z2-9]{4}-[a-z2-9]{4}$/);
|
||||||
|
assert.equal(hashRecoveryCode(codes[0]!.toUpperCase().replace(/-/g, ' ')), hashes[0]);
|
||||||
|
assert.equal(normaliseRecoveryCode('ABCD EFGH JKMN'), 'abcd-efgh-jkmn');
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
describe('secrets at rest', () => {
|
||||||
|
test('round trip; another key can\'t read it; changed data fails', () => {
|
||||||
|
const a = new Secrets('one-secret-that-is-long-enough-for-tests');
|
||||||
|
const enc = a.encrypt('totp-secret');
|
||||||
|
assert.match(enc, /^enc:/);
|
||||||
|
assert.equal(a.decrypt(enc), 'totp-secret');
|
||||||
|
assert.throws(() => new Secrets('another-secret-that-is-long-enough').decrypt(enc));
|
||||||
|
assert.throws(() => a.decrypt(`${enc.slice(0, -2)}00`));
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
describe('licence states (Accounts never goes read-only)', () => {
|
||||||
|
const base: LicenceClaims = { v: 1, installId: 'i', customer: 'Hope', status: 'active', licenceExpiresAt: null, validUntil: '2026-12-01T00:00:00Z', graceDays: 14 };
|
||||||
|
test('active, grace, lapsed, revoked, unlicensed', () => {
|
||||||
|
assert.equal(stateFor(base, 'i', new Date('2026-11-20')).state, 'active');
|
||||||
|
assert.equal(stateFor(base, 'i', new Date('2026-12-05')).state, 'grace');
|
||||||
|
assert.equal(stateFor(base, 'i', new Date('2027-01-01')).state, 'lapsed');
|
||||||
|
assert.equal(stateFor({ ...base, status: 'revoked' }, 'i').state, 'revoked');
|
||||||
|
assert.equal(stateFor(null, null).state, 'unlicensed');
|
||||||
|
assert.equal(stateFor(base, 'other').state, 'unlicensed');
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
describe('phone numbers', () => {
|
||||||
|
test('South African numbers in every common format', () => {
|
||||||
|
assert.equal(normalisePhone('082 123 4567'), '+27821234567');
|
||||||
|
assert.equal(normalisePhone('+27 82 123 4567'), '+27821234567');
|
||||||
|
assert.equal(normalisePhone('hello'), null);
|
||||||
|
assert.equal(waNumber('+27821234567'), '27821234567');
|
||||||
|
});
|
||||||
|
});
|
||||||
@@ -0,0 +1,210 @@
|
|||||||
|
// Accounts and the church's products (docs/ACCOUNTS-1.0-PLAN.md §3–§7): signing out everywhere,
|
||||||
|
// signed back-channel calls, deletion with a product that says "not yet", "download my data", the
|
||||||
|
// church profile, Connect, and admin and setup rules.
|
||||||
|
import assert from 'node:assert/strict';
|
||||||
|
import { after, before, beforeEach, describe, test } from 'node:test';
|
||||||
|
import { churchSchema, IDENTITY_SCHEMA, LINK_SCHEMA, OIDC_CLIENT_PATHS } from '@crosscode/contracts';
|
||||||
|
import { generateEd25519, ed25519PublicToPem, newLinkNonce, newLinkSecret, signLink } from '@crosscode/contracts/signing';
|
||||||
|
import { Browser, PRODUCT_ID, ACCOUNTS_ID, startHarness, type Harness } from './support/harness.js';
|
||||||
|
import { runDue } from '../src/links/deliveries.js';
|
||||||
|
import { approveDeletion, runDeletionJob } from '../src/privacy/deletion.js';
|
||||||
|
import { finishIfComplete } from '../src/privacy/export.js';
|
||||||
|
import { codeAt } from '../src/lib/totp.js';
|
||||||
|
|
||||||
|
let h: Harness;
|
||||||
|
before(async () => { h = await startHarness(); });
|
||||||
|
after(async () => { await h.close(); });
|
||||||
|
beforeEach(() => { h.received.length = 0; for (const k of Object.keys(h.productReplies)) delete h.productReplies[k]; });
|
||||||
|
|
||||||
|
const isCallback = (u: URL) => u.pathname === OIDC_CLIENT_PATHS.callback;
|
||||||
|
|
||||||
|
/** Signs into Accounts' own pages (the account page). */
|
||||||
|
async function accountPage(email: string, password: string) {
|
||||||
|
const browser = new Browser();
|
||||||
|
const { url } = await browser.follow(`${h.publicUrl}/api/self/signin?returnTo=/account`, (u) => u.pathname === '/signin');
|
||||||
|
const uid = url.searchParams.get('uid')!;
|
||||||
|
const step = await h.api(browser, 'POST', `/api/v2/interaction/${uid}/password`, { email, password });
|
||||||
|
return { browser, uid, step };
|
||||||
|
}
|
||||||
|
|
||||||
|
describe('signing out everywhere', () => {
|
||||||
|
test('ends the session and tells each product it signed in to (back-channel logout)', async () => {
|
||||||
|
const a = await h.makeAccount({ email: 'out@hope.test', password: 'Correct-horse-1' });
|
||||||
|
const browser = new Browser();
|
||||||
|
await h.signIn(browser, 'out@hope.test', 'Correct-horse-1');
|
||||||
|
const res = await h.api(browser, 'POST', '/api/v2/me/sign-out-everywhere');
|
||||||
|
assert.equal(res.status, 200, JSON.stringify(res.body));
|
||||||
|
const logout = h.received.find((r) => r.path === OIDC_CLIENT_PATHS.backchannelLogout);
|
||||||
|
assert.ok(logout, 'the product was told');
|
||||||
|
const token = new URLSearchParams(logout.body).get('logout_token')!;
|
||||||
|
const payload = JSON.parse(Buffer.from(token.split('.')[1]!, 'base64url').toString());
|
||||||
|
assert.equal(payload.sub, a.id);
|
||||||
|
assert.ok(payload.events['http://schemas.openid.net/event/backchannel-logout']);
|
||||||
|
// Signed out: the account page asks to sign in again.
|
||||||
|
assert.equal((await h.api(browser, 'GET', '/api/v2/me')).status, 401);
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
describe('back-channel calls', () => {
|
||||||
|
test('a profile change reaches the product as user.updated, signed with the link\'s secret', async () => {
|
||||||
|
await h.makeAccount({ email: 'thandi2@hope.test', password: 'Correct-horse-2' });
|
||||||
|
const page = await accountPage('thandi2@hope.test', 'Correct-horse-2');
|
||||||
|
assert.equal(page.step.body.stage, 'done', JSON.stringify(page.step.body));
|
||||||
|
await page.browser.follow(page.step.body.redirectTo as string, (u) => u.pathname === '/account');
|
||||||
|
const put = await h.api(page.browser, 'PUT', '/api/v2/me', { name: 'Thandi Mokoena', phone: '082 123 4567' });
|
||||||
|
assert.equal(put.status, 200, JSON.stringify(put.body));
|
||||||
|
assert.equal(put.body.phone, '+27821234567');
|
||||||
|
await runDue(h.ctx);
|
||||||
|
const call = h.received.find((r) => r.path === '/api/accounts/v1/events');
|
||||||
|
assert.ok(call);
|
||||||
|
assert.ok(h.signedByLink(call), 'signed with the link secret');
|
||||||
|
const body = JSON.parse(call.body);
|
||||||
|
assert.equal(body.type, 'user.updated');
|
||||||
|
assert.equal(body.profile.name, 'Thandi Mokoena');
|
||||||
|
});
|
||||||
|
|
||||||
|
test('a product that can\'t be reached is tried again later, not lost', async () => {
|
||||||
|
const { queueCall } = await import('../src/links/deliveries.js');
|
||||||
|
const link = (await h.db.productLink.findUnique({ where: { installId: PRODUCT_ID } }))!;
|
||||||
|
await h.db.productLink.update({ where: { installId: PRODUCT_ID }, data: { url: 'http://127.0.0.1:9' } });
|
||||||
|
const [d] = await queueCall(h.ctx, 'church.changed', () => ({ schema: 'crosscode.church/1', type: 'church.changed' }));
|
||||||
|
await runDue(h.ctx);
|
||||||
|
const after1 = (await h.db.delivery.findUnique({ where: { id: d!.id } }))!;
|
||||||
|
assert.equal(after1.status, 'pending');
|
||||||
|
assert.equal(after1.attempts, 1);
|
||||||
|
assert.ok((after1.nextAttemptAt as Date) > new Date());
|
||||||
|
await h.db.productLink.update({ where: { installId: PRODUCT_ID }, data: { url: link.url } });
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
describe('deleting an account', () => {
|
||||||
|
test('deactivated at once; after approval each product is asked, "not yet" is asked again, then anonymised', async () => {
|
||||||
|
const a = await h.makeAccount({ email: 'leaving@hope.test', password: 'Correct-horse-3' });
|
||||||
|
const page = await accountPage('leaving@hope.test', 'Correct-horse-3');
|
||||||
|
await page.browser.follow(page.step.body.redirectTo as string, (u) => u.pathname === '/account');
|
||||||
|
const del = await h.api(page.browser, 'POST', '/api/v2/me/delete', { password: 'Correct-horse-3' });
|
||||||
|
assert.equal(del.status, 200, JSON.stringify(del.body));
|
||||||
|
assert.equal((await h.db.account.findUnique({ where: { id: a.id } }))!.status, 'deactivated');
|
||||||
|
|
||||||
|
const req = (await h.db.deletionRequest.findFirst({ where: { accountId: a.id } }))!;
|
||||||
|
let answer: unknown = { schema: IDENTITY_SCHEMA, status: 'deferred', reason: 'Has a registration for Youth Camp (14 March)', retryAfter: new Date(Date.now() - 1000).toISOString() };
|
||||||
|
h.productReplies['user.deleted'] = () => answer;
|
||||||
|
await approveDeletion(h.ctx, req.id as string, { id: 'admin', role: 'admin' });
|
||||||
|
await runDue(h.ctx);
|
||||||
|
let state = (await h.db.deletionRequest.findUnique({ where: { id: req.id } }))!;
|
||||||
|
assert.equal(state.status, 'approved');
|
||||||
|
assert.equal((state.products as Record<string, { status: string }>)[PRODUCT_ID]!.status, 'deferred');
|
||||||
|
|
||||||
|
answer = { schema: IDENTITY_SCHEMA, status: 'deleted' };
|
||||||
|
await runDeletionJob(h.ctx);
|
||||||
|
await runDue(h.ctx);
|
||||||
|
state = (await h.db.deletionRequest.findUnique({ where: { id: req.id } }))!;
|
||||||
|
assert.equal(state.status, 'done');
|
||||||
|
const gone = (await h.db.account.findUnique({ where: { id: a.id } }))!;
|
||||||
|
assert.equal(gone.status, 'deleted');
|
||||||
|
assert.equal(gone.email, `deleted-${a.id}@deleted.invalid`);
|
||||||
|
assert.equal(gone.passwordHash, null);
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
describe('download my data', () => {
|
||||||
|
test('bundles Accounts\' part and the product\'s', async () => {
|
||||||
|
const a = await h.makeAccount({ email: 'mydata@hope.test', password: 'Correct-horse-4' });
|
||||||
|
h.productReplies['user.export'] = (body) => ({
|
||||||
|
schema: IDENTITY_SCHEMA, exportId: body.exportId, sub: a.id, product: 'website', generatedAt: new Date().toISOString(),
|
||||||
|
sections: [{ key: 'pages', title: 'Pages you edited', records: [{ title: 'Home' }] }],
|
||||||
|
});
|
||||||
|
const page = await accountPage('mydata@hope.test', 'Correct-horse-4');
|
||||||
|
await page.browser.follow(page.step.body.redirectTo as string, (u) => u.pathname === '/account');
|
||||||
|
const made = await h.api(page.browser, 'POST', '/api/v2/me/exports');
|
||||||
|
assert.equal(made.status, 200);
|
||||||
|
await runDue(h.ctx);
|
||||||
|
await finishIfComplete(h.ctx, made.body.id as string);
|
||||||
|
const list = await h.api(page.browser, 'GET', '/api/v2/me/exports');
|
||||||
|
assert.equal((list.body.items as { status: string }[])[0]!.status, 'ready');
|
||||||
|
const dl = await page.browser.request(`${h.publicUrl}/api/v2/me/exports/${made.body.id}/download`);
|
||||||
|
const file = await dl.json() as { parts: { product: string }[] };
|
||||||
|
assert.deepEqual(file.parts.map((p) => p.product).sort(), ['accounts', 'website']);
|
||||||
|
assert.ok(h.messenger.emails.some((e) => e.to === 'mydata@hope.test' && /ready/.test(e.subject)));
|
||||||
|
// Someone else can't download it.
|
||||||
|
assert.equal((await new Browser().request(`${h.publicUrl}/api/v2/me/exports/${made.body.id}/download`)).status, 401);
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
describe('the church profile', () => {
|
||||||
|
test('is served as crosscode.church/1 with the product links', async () => {
|
||||||
|
const res = await fetch(`${h.publicUrl}/api/church/v1`);
|
||||||
|
const body = (await res.json()) as { name: string; links: Record<string, string> };
|
||||||
|
assert.equal(churchSchema.safeParse(body).success, true, JSON.stringify(body));
|
||||||
|
assert.equal(body.name, 'Hope Family Church');
|
||||||
|
assert.equal(body.links.website, h.productUrl);
|
||||||
|
assert.equal(body.links.accounts, h.publicUrl);
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
describe('Connect from a product', () => {
|
||||||
|
test('a product the Hub listed connects and becomes a client; an unlisted one can\'t', async () => {
|
||||||
|
const appKey = generateEd25519();
|
||||||
|
const APP_ID = '3b0f6a52-6c1e-4b7a-9d0e-2f1a8c4b7e04';
|
||||||
|
await h.ctx.settings.set('hub_linked_products', JSON.stringify([{ product: 'app', installId: APP_ID, url: 'http://127.0.0.1:7', publicKey: ed25519PublicToPem(appKey.publicKey) }]));
|
||||||
|
const msg = (key = appKey) => signLink({ schema: LINK_SCHEMA, type: 'link.connect', from: { product: 'app', installId: APP_ID, url: 'http://127.0.0.1:7' }, to: { installId: ACCOUNTS_ID }, secret: newLinkSecret(), issuedAt: new Date().toISOString(), nonce: newLinkNonce() }, key.privateKeyPem);
|
||||||
|
const bad = await fetch(`${h.publicUrl}/api/links/v1/connect`, { method: 'POST', headers: { 'content-type': 'application/json' }, body: JSON.stringify(msg(generateEd25519())) });
|
||||||
|
assert.equal(bad.status, 401);
|
||||||
|
const ok = await fetch(`${h.publicUrl}/api/links/v1/connect`, { method: 'POST', headers: { 'content-type': 'application/json' }, body: JSON.stringify(msg()) });
|
||||||
|
assert.equal(ok.status, 200);
|
||||||
|
assert.equal(((await ok.json()) as { type: string }).type, 'link.connected');
|
||||||
|
const client = await h.provider.Client.find(APP_ID);
|
||||||
|
assert.deepEqual(client?.redirectUris, ['http://127.0.0.1:7/api/auth/callback']);
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
describe('admin and setup', () => {
|
||||||
|
test('admin needs the admin role and a 2FA sign-in', async () => {
|
||||||
|
await h.makeAccount({ email: 'member@hope.test', password: 'Correct-horse-5' });
|
||||||
|
const member = await accountPage('member@hope.test', 'Correct-horse-5');
|
||||||
|
await member.browser.follow(member.step.body.redirectTo as string, (u) => u.pathname === '/account');
|
||||||
|
assert.equal((await h.api(member.browser, 'GET', '/api/v2/admin/people')).status, 403);
|
||||||
|
|
||||||
|
await h.makeAccount({ email: 'admin@hope.test', password: 'Correct-horse-6', role: 'admin' });
|
||||||
|
const admin = await accountPage('admin@hope.test', 'Correct-horse-6');
|
||||||
|
assert.equal(admin.step.body.stage, 'setup_two_factor', 'admins must have 2FA');
|
||||||
|
const setup = await h.api(admin.browser, 'POST', `/api/v2/interaction/${admin.uid}/two-factor/setup`, { method: 'totp' });
|
||||||
|
const done = await h.api(admin.browser, 'POST', `/api/v2/interaction/${admin.uid}/two-factor/setup/confirm`, { method: 'totp', code: codeAt(String(setup.body.secret), Math.floor(Date.now() / 30000)) });
|
||||||
|
await admin.browser.follow(done.body.redirectTo as string, (u) => u.pathname === '/admin' || u.pathname === '/account');
|
||||||
|
const people = await h.api(admin.browser, 'GET', '/api/v2/admin/people?q=member');
|
||||||
|
assert.equal(people.status, 200, JSON.stringify(people.body));
|
||||||
|
assert.deepEqual((people.body.items as { email: string }[]).map((p) => p.email), ['member@hope.test']);
|
||||||
|
// Viewing a person is access-logged.
|
||||||
|
const id = (people.body.items as { id: string }[])[0]!.id;
|
||||||
|
await h.api(admin.browser, 'GET', `/api/v2/admin/people/${id}`);
|
||||||
|
assert.equal(await h.db.accessLog.count({ where: { targetId: id } }), 1);
|
||||||
|
});
|
||||||
|
|
||||||
|
test('changes only from the site itself', async () => {
|
||||||
|
const res = await new Browser().request(`${h.publicUrl}/api/v2/password/forgot`, { body: { email: 'x@hope.test' }, origin: 'https://evil.example' });
|
||||||
|
assert.equal(res.status, 403);
|
||||||
|
});
|
||||||
|
|
||||||
|
test('setup only while there\'s no admin', async () => {
|
||||||
|
const res = await h.api(new Browser(), 'POST', '/api/v2/setup', { churchName: 'Other', name: 'Someone', email: 'someone@hope.test', password: 'Correct-horse-7' });
|
||||||
|
assert.equal(res.status, 409);
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
describe('the sign-out page', () => {
|
||||||
|
test('signing out from a product ends at that product\'s address', async () => {
|
||||||
|
const browser = new Browser();
|
||||||
|
const r = await h.signIn(browser, 'member@hope.test', 'Correct-horse-5');
|
||||||
|
assert.ok('tokens' in r);
|
||||||
|
const end = new URL(`${h.publicUrl}/api/oidc/session/end`);
|
||||||
|
end.search = new URLSearchParams({ id_token_hint: r.tokens.id_token!, post_logout_redirect_uri: `${h.productUrl}/` }).toString();
|
||||||
|
const page = await browser.request(end.toString());
|
||||||
|
const html = await page.text();
|
||||||
|
assert.match(html, /logout\.js/);
|
||||||
|
const xsrf = /name="xsrf" value="([^"]+)"/.exec(html)![1]!;
|
||||||
|
const confirm = await browser.request(`${h.publicUrl}/api/oidc/session/end/confirm`, { form: { xsrf, logout: 'yes' } });
|
||||||
|
const loc = confirm.headers.get('location') ?? '';
|
||||||
|
assert.equal(loc, `${h.productUrl}/`);
|
||||||
|
void isCallback;
|
||||||
|
});
|
||||||
|
});
|
||||||
@@ -0,0 +1,173 @@
|
|||||||
|
// Signing in through Accounts end to end (docs/ACCOUNTS-1.0-PLAN.md §3–5, ROADMAP-v3 §9 release
|
||||||
|
// checks): a real oidc-provider, the real app, a test product on openid-client.
|
||||||
|
import assert from 'node:assert/strict';
|
||||||
|
import { after, before, describe, test } from 'node:test';
|
||||||
|
import { identityClaimsSchema, OIDC_CLIENT_PATHS } from '@crosscode/contracts';
|
||||||
|
import { Browser, startHarness, type Harness } from './support/harness.js';
|
||||||
|
import { codeAt } from '../src/lib/totp.js';
|
||||||
|
|
||||||
|
let h: Harness;
|
||||||
|
before(async () => { h = await startHarness(); });
|
||||||
|
after(async () => { await h.close(); });
|
||||||
|
|
||||||
|
const isCallback = (u: URL) => u.pathname === OIDC_CLIENT_PATHS.callback;
|
||||||
|
|
||||||
|
describe('signing in from a product', () => {
|
||||||
|
test('returns to the exact page, with crosscode.identity/1 claims', async () => {
|
||||||
|
await h.makeAccount({ email: 'thandi@hope.test', password: 'Correct-horse-1', phone: '+27821234567' });
|
||||||
|
const r = await h.signIn(new Browser(), 'thandi@hope.test', 'Correct-horse-1');
|
||||||
|
assert.ok('claims' in r, JSON.stringify(r));
|
||||||
|
assert.equal(r.returnTo, '/events/youth-camp?ticket=adult');
|
||||||
|
const claims = identityClaimsSchema.safeParse(r.claims);
|
||||||
|
assert.deepEqual(claims.error?.issues ?? [], []);
|
||||||
|
assert.equal(r.claims.email, 'thandi@hope.test');
|
||||||
|
assert.deepEqual(r.claims.amr, ['pwd']);
|
||||||
|
assert.equal(r.claims.two_factor, null);
|
||||||
|
});
|
||||||
|
|
||||||
|
test('a wrong password is refused without saying whether the account exists', async () => {
|
||||||
|
const browser = new Browser();
|
||||||
|
const started = await h.startSignIn('/');
|
||||||
|
const { url } = await browser.follow(started.url, (u) => u.pathname === '/signin');
|
||||||
|
const uid = url.searchParams.get('uid')!;
|
||||||
|
const wrong = await h.api(browser, 'POST', `/api/v2/interaction/${uid}/password`, { email: 'thandi@hope.test', password: 'nope-nope-nope' });
|
||||||
|
const nobody = await h.api(browser, 'POST', `/api/v2/interaction/${uid}/password`, { email: 'nobody@hope.test', password: 'nope-nope-nope' });
|
||||||
|
assert.equal(wrong.status, 401);
|
||||||
|
assert.deepEqual(wrong.body, nobody.body);
|
||||||
|
});
|
||||||
|
|
||||||
|
test('a second sign-in from the same browser goes straight back (one sign-in for every product)', async () => {
|
||||||
|
const browser = new Browser();
|
||||||
|
await h.signIn(browser, 'thandi@hope.test', 'Correct-horse-1');
|
||||||
|
const started = await h.startSignIn('/give');
|
||||||
|
const { url } = await browser.follow(started.url, (u) => isCallback(u) || u.pathname === '/signin');
|
||||||
|
assert.ok(isCallback(url), `expected the callback, got ${url}`);
|
||||||
|
const r = await h.finishSignIn(url, started);
|
||||||
|
assert.equal(r.returnTo, '/give');
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
describe('what the provider refuses', () => {
|
||||||
|
test('PKCE is required', async () => {
|
||||||
|
const started = await h.startSignIn('/');
|
||||||
|
const u = new URL(started.url);
|
||||||
|
u.searchParams.delete('code_challenge');
|
||||||
|
u.searchParams.delete('code_challenge_method');
|
||||||
|
const res = await new Browser().request(u.toString());
|
||||||
|
const loc = res.headers.get('location') ?? '';
|
||||||
|
assert.ok(res.status === 400 || /error=invalid_request/.test(loc), `status ${res.status} ${loc}`);
|
||||||
|
});
|
||||||
|
|
||||||
|
test('a redirect_uri that isn\'t the registered one is refused and never followed', async () => {
|
||||||
|
const started = await h.startSignIn('/');
|
||||||
|
const u = new URL(started.url);
|
||||||
|
u.searchParams.set('redirect_uri', 'https://evil.example/api/auth/callback');
|
||||||
|
const res = await new Browser().request(u.toString());
|
||||||
|
assert.equal(res.status, 400);
|
||||||
|
assert.equal(res.headers.get('location'), null);
|
||||||
|
});
|
||||||
|
|
||||||
|
test('an unknown client is refused', async () => {
|
||||||
|
const started = await h.startSignIn('/');
|
||||||
|
const u = new URL(started.url);
|
||||||
|
u.searchParams.set('client_id', '00000000-0000-4000-8000-00000000dead');
|
||||||
|
assert.equal((await new Browser().request(u.toString())).status, 400);
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
describe('two-factor', () => {
|
||||||
|
test('a product asking for 2FA (acr_values=mfa) gets it set up first, then amr says mfa', async () => {
|
||||||
|
await h.makeAccount({ email: 'sam@hope.test', password: 'Correct-horse-2', name: 'Sam Supervisor' });
|
||||||
|
const browser = new Browser();
|
||||||
|
const r = await h.signIn(browser, 'sam@hope.test', 'Correct-horse-2', '/dashboard', { acr_values: 'mfa' });
|
||||||
|
assert.ok('pending' in r);
|
||||||
|
assert.equal(r.pending.stage, 'setup_two_factor');
|
||||||
|
const setup = await h.api(browser, 'POST', `/api/v2/interaction/${r.uid}/two-factor/setup`, { method: 'totp' });
|
||||||
|
const code = codeAt(String(setup.body.secret), Math.floor(Date.now() / 30000));
|
||||||
|
const done = await h.api(browser, 'POST', `/api/v2/interaction/${r.uid}/two-factor/setup/confirm`, { method: 'totp', code });
|
||||||
|
assert.equal(done.body.stage, 'done', JSON.stringify(done.body));
|
||||||
|
assert.equal((done.body.recoveryCodes as string[]).length, 10);
|
||||||
|
const back = await browser.follow(done.body.redirectTo as string, isCallback);
|
||||||
|
const signed = await h.finishSignIn(back.url, r.started);
|
||||||
|
assert.deepEqual(signed.claims.amr, ['pwd', 'otp', 'mfa']);
|
||||||
|
assert.equal(signed.claims.acr, 'mfa');
|
||||||
|
assert.equal(signed.returnTo, '/dashboard');
|
||||||
|
});
|
||||||
|
|
||||||
|
test('someone with 2FA by email enters the emailed code; a recovery code works instead', async () => {
|
||||||
|
const a = await h.makeAccount({ email: 'lerato@hope.test', password: 'Correct-horse-3', twoFactorMethod: 'email' });
|
||||||
|
const { replaceRecoveryCodes } = await import('../src/accounts/twoFactor.js');
|
||||||
|
const codes = await replaceRecoveryCodes(h.ctx, a.id as string);
|
||||||
|
|
||||||
|
const browser = new Browser();
|
||||||
|
const r = await h.signIn(browser, 'lerato@hope.test', 'Correct-horse-3');
|
||||||
|
assert.ok('pending' in r);
|
||||||
|
assert.equal(r.pending.stage, 'two_factor');
|
||||||
|
const wrong = await h.api(browser, 'POST', `/api/v2/interaction/${r.uid}/two-factor`, { code: '000000' });
|
||||||
|
assert.equal(wrong.status, 400);
|
||||||
|
const ok = await h.api(browser, 'POST', `/api/v2/interaction/${r.uid}/two-factor`, { code: h.messenger.lastCode('lerato@hope.test') });
|
||||||
|
assert.equal(ok.body.stage, 'done');
|
||||||
|
|
||||||
|
const b2 = new Browser();
|
||||||
|
const r2 = await h.signIn(b2, 'lerato@hope.test', 'Correct-horse-3');
|
||||||
|
assert.ok('pending' in r2);
|
||||||
|
const rec = await h.api(b2, 'POST', `/api/v2/interaction/${r2.uid}/two-factor`, { recoveryCode: codes[0]!.toUpperCase() });
|
||||||
|
assert.equal(rec.body.stage, 'done');
|
||||||
|
const again = await h.api(new Browser(), 'POST', `/api/v2/interaction/${r2.uid}/two-factor`, { recoveryCode: codes[0] });
|
||||||
|
assert.notEqual(again.status, 200);
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
describe('the steps in between still return to the page', () => {
|
||||||
|
test('sign-up: verify the email, then back to the product', async () => {
|
||||||
|
const browser = new Browser();
|
||||||
|
const started = await h.startSignIn('/events/camp/register?ticket=child');
|
||||||
|
const { url } = await browser.follow(started.url, (u) => u.pathname === '/signin');
|
||||||
|
const uid = url.searchParams.get('uid')!;
|
||||||
|
const signup = await h.api(browser, 'POST', `/api/v2/interaction/${uid}/signup`, { name: 'New Person', email: 'New@Hope.test', password: 'Correct-horse-4', acceptNotice: true, newsEmail: true });
|
||||||
|
assert.equal(signup.body.stage, 'verify_email', JSON.stringify(signup.body));
|
||||||
|
const verified = await h.api(browser, 'POST', `/api/v2/interaction/${uid}/verify-email`, { code: h.messenger.lastCode('new@hope.test') });
|
||||||
|
assert.equal(verified.body.stage, 'done', JSON.stringify(verified.body));
|
||||||
|
const back = await browser.follow(verified.body.redirectTo as string, isCallback);
|
||||||
|
const r = await h.finishSignIn(back.url, started);
|
||||||
|
assert.equal(r.returnTo, '/events/camp/register?ticket=child');
|
||||||
|
assert.equal(r.claims.email_verified, true);
|
||||||
|
assert.deepEqual(r.claims.news_consent, { email: true, whatsapp: false });
|
||||||
|
});
|
||||||
|
|
||||||
|
test('a password reset in the middle carries on to the product', async () => {
|
||||||
|
await h.makeAccount({ email: 'forgot@hope.test', password: 'Old-password-1' });
|
||||||
|
const browser = new Browser();
|
||||||
|
const started = await h.startSignIn('/my-tickets');
|
||||||
|
const { url } = await browser.follow(started.url, (u) => u.pathname === '/signin');
|
||||||
|
const uid = url.searchParams.get('uid')!;
|
||||||
|
await h.api(browser, 'POST', '/api/v2/password/forgot', { email: 'forgot@hope.test', uid });
|
||||||
|
const link = new URL(h.messenger.lastLink('forgot@hope.test')!);
|
||||||
|
const reset = await h.api(browser, 'POST', '/api/v2/password/reset', { token: link.searchParams.get('token'), password: 'New-password-1' });
|
||||||
|
assert.equal(reset.body.uid, uid);
|
||||||
|
const step = await h.api(browser, 'POST', `/api/v2/interaction/${uid}/password`, { email: 'forgot@hope.test', password: 'New-password-1' });
|
||||||
|
const back = await browser.follow(step.body.redirectTo as string, isCallback);
|
||||||
|
assert.equal((await h.finishSignIn(back.url, started)).returnTo, '/my-tickets');
|
||||||
|
// The link is single-use.
|
||||||
|
assert.equal((await h.api(browser, 'POST', '/api/v2/password/reset', { token: link.searchParams.get('token'), password: 'Other-password-1' })).status, 400);
|
||||||
|
});
|
||||||
|
|
||||||
|
test('a new privacy notice is accepted before going back, even when already signed in', async () => {
|
||||||
|
await h.makeAccount({ email: 'notice@hope.test', password: 'Correct-horse-5' });
|
||||||
|
const browser = new Browser();
|
||||||
|
await h.signIn(browser, 'notice@hope.test', 'Correct-horse-5');
|
||||||
|
const { publish } = await import('../src/privacy/notice.js');
|
||||||
|
const n = await publish(h.ctx, { title: 'Our new notice', body: 'x'.repeat(80) }, 'admin');
|
||||||
|
const started = await h.startSignIn('/after-notice');
|
||||||
|
const { url } = await browser.follow(started.url, (u) => isCallback(u) || u.pathname === '/signin');
|
||||||
|
assert.equal(url.pathname, '/signin');
|
||||||
|
const uid = url.searchParams.get('uid')!;
|
||||||
|
const view = await h.api(browser, 'GET', `/api/v2/interaction/${uid}/state`);
|
||||||
|
assert.equal(view.body.stage, 'notice');
|
||||||
|
const done = await h.api(browser, 'POST', `/api/v2/interaction/${uid}/notice`, { version: n.version });
|
||||||
|
const back = await browser.follow(done.body.redirectTo as string, isCallback);
|
||||||
|
const r = await h.finishSignIn(back.url, started);
|
||||||
|
assert.equal(r.returnTo, '/after-notice');
|
||||||
|
assert.equal(r.claims.privacy_notice_version, n.version);
|
||||||
|
});
|
||||||
|
});
|
||||||
@@ -0,0 +1,172 @@
|
|||||||
|
/**
|
||||||
|
* The whole of Accounts on a real port with an in-memory database and messenger, plus a test
|
||||||
|
* product (an OIDC client built on openid-client, as the Website will be) that's linked and
|
||||||
|
* signs people in. Browser requests go through a small cookie jar, following redirects by hand.
|
||||||
|
*/
|
||||||
|
import http from 'node:http';
|
||||||
|
import type { AddressInfo } from 'node:net';
|
||||||
|
import * as oidc from 'openid-client';
|
||||||
|
import { encodeState, decodeState, IDENTITY_SCHEMA, OIDC_CLIENT_PATHS } from '@crosscode/contracts';
|
||||||
|
import { ed25519PublicToPem, generateEd25519, LINK_HEADERS, newLinkSecret, oidcClientSecret, verify } from '@crosscode/contracts/signing';
|
||||||
|
import { createApp } from '../../src/app.js';
|
||||||
|
import { createCtx, type Ctx } from '../../src/context.js';
|
||||||
|
import { loadConfig } from '../../src/lib/config.js';
|
||||||
|
import { MemoryMessenger } from '../../src/lib/messages.js';
|
||||||
|
import { hashPassword } from '../../src/lib/passwords.js';
|
||||||
|
import { createProvider } from '../../src/oidc/provider.js';
|
||||||
|
import { memoryDb, type MemoryDb } from './memoryDb.js';
|
||||||
|
|
||||||
|
export const ACCOUNTS_ID = '9a4c2f1e-7b3d-4e5a-8c6f-0d1e2f3a4b5c';
|
||||||
|
export const PRODUCT_ID = '3b0f6a52-6c1e-4b7a-9d0e-2f1a8c4b7e02';
|
||||||
|
|
||||||
|
const listen = (server: http.Server) => new Promise<number>((resolve) => server.listen(0, '127.0.0.1', () => resolve((server.address() as AddressInfo).port)));
|
||||||
|
|
||||||
|
/** A browser: cookies per host, redirects followed by hand so each hop can be checked. */
|
||||||
|
export class Browser {
|
||||||
|
// Per host: name → value and the cookie's Path, sent only on paths under it (as browsers do;
|
||||||
|
// oidc-provider scopes its interaction cookie to the interaction's address).
|
||||||
|
private jar = new Map<string, Map<string, { value: string; path: string }>>();
|
||||||
|
|
||||||
|
private cookieHeader(url: URL) {
|
||||||
|
const c = this.jar.get(url.host);
|
||||||
|
if (!c) return '';
|
||||||
|
const under = (p: string) => url.pathname === p || url.pathname.startsWith(p.endsWith('/') ? p : `${p}/`) || p === '/';
|
||||||
|
return [...c].filter(([, v]) => under(v.path)).map(([k, v]) => `${k}=${v.value}`).join('; ');
|
||||||
|
}
|
||||||
|
|
||||||
|
private store(url: URL, res: Response) {
|
||||||
|
for (const line of res.headers.getSetCookie()) {
|
||||||
|
const [pair, ...attrs] = line.split(';');
|
||||||
|
const i = pair!.indexOf('=');
|
||||||
|
const name = pair!.slice(0, i).trim();
|
||||||
|
const value = pair!.slice(i + 1).trim();
|
||||||
|
const pathAttr = attrs.map((a) => a.trim()).find((a) => /^path=/i.test(a));
|
||||||
|
const path = pathAttr ? pathAttr.slice(5) : url.pathname.replace(/\/[^/]*$/, '') || '/';
|
||||||
|
if (!this.jar.has(url.host)) this.jar.set(url.host, new Map());
|
||||||
|
if (/expires=Thu, 01 Jan 1970/i.test(line) || /max-age=0/i.test(line) || value === '') this.jar.get(url.host)!.delete(name);
|
||||||
|
else this.jar.get(url.host)!.set(name, { value, path });
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
async request(url: string, init: { method?: string; body?: unknown; form?: Record<string, string>; origin?: string } = {}) {
|
||||||
|
const u = new URL(url);
|
||||||
|
const headers: Record<string, string> = { cookie: this.cookieHeader(u) };
|
||||||
|
let body: string | undefined;
|
||||||
|
if (init.body !== undefined) { headers['content-type'] = 'application/json'; body = JSON.stringify(init.body); }
|
||||||
|
if (init.form) { headers['content-type'] = 'application/x-www-form-urlencoded'; body = new URLSearchParams(init.form).toString(); }
|
||||||
|
if (init.origin) headers.origin = init.origin;
|
||||||
|
const res = await fetch(u, { method: init.method ?? (body ? 'POST' : 'GET'), headers, body, redirect: 'manual' });
|
||||||
|
this.store(u, res);
|
||||||
|
return res;
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Follows redirects until a page that isn't one; returns every URL visited and the last response. */
|
||||||
|
async follow(url: string, stopAt?: (u: URL) => boolean) {
|
||||||
|
const visited: URL[] = [];
|
||||||
|
let current = new URL(url);
|
||||||
|
for (let i = 0; i < 10; i++) {
|
||||||
|
visited.push(current);
|
||||||
|
if (stopAt?.(current)) return { visited, res: null as Response | null, url: current };
|
||||||
|
const res = await this.request(current.toString());
|
||||||
|
const loc = res.headers.get('location');
|
||||||
|
if (res.status >= 300 && res.status < 400 && loc) {
|
||||||
|
current = new URL(loc, current);
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
return { visited, res, url: current };
|
||||||
|
}
|
||||||
|
throw new Error('Too many redirects');
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
export type Received = { path: string; headers: http.IncomingHttpHeaders; body: string };
|
||||||
|
|
||||||
|
export type Harness = Awaited<ReturnType<typeof startHarness>>;
|
||||||
|
|
||||||
|
export async function startHarness(opts: { now?: () => Date } = {}) {
|
||||||
|
// 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 messenger = new MemoryMessenger();
|
||||||
|
const ctx: Ctx = createCtx(config, db as never, { messenger, now: opts.now });
|
||||||
|
const provider = await createProvider(ctx);
|
||||||
|
server.on('request', createApp(ctx, provider));
|
||||||
|
await ctx.settings.setMany({ hub_install_id: ACCOUNTS_ID, church_profile: JSON.stringify({ name: 'Hope Family Church', shortName: 'Hope' }) });
|
||||||
|
|
||||||
|
// The test product: answers back-channel calls and logout, and is linked (so it's a client).
|
||||||
|
const received: Received[] = [];
|
||||||
|
const productReplies: Record<string, (body: Record<string, unknown>) => unknown> = {};
|
||||||
|
const productServer = http.createServer((req, res) => {
|
||||||
|
let body = '';
|
||||||
|
req.on('data', (c) => { body += c; });
|
||||||
|
req.on('end', () => {
|
||||||
|
received.push({ path: req.url ?? '', headers: req.headers, body });
|
||||||
|
const parsed = (() => { try { return JSON.parse(body); } catch { return {}; } })() as Record<string, unknown>;
|
||||||
|
const answer = productReplies[String(parsed.type ?? req.url)]?.(parsed) ?? { schema: IDENTITY_SCHEMA, ok: true };
|
||||||
|
res.writeHead(200, { 'content-type': 'application/json' }).end(JSON.stringify(answer));
|
||||||
|
});
|
||||||
|
});
|
||||||
|
const productPort = await listen(productServer);
|
||||||
|
const productUrl = `http://127.0.0.1:${productPort}`;
|
||||||
|
const linkSecret = newLinkSecret();
|
||||||
|
const productKey = generateEd25519();
|
||||||
|
await db.productLink.create({ data: { installId: PRODUCT_ID, product: 'website', url: productUrl, publicKey: ed25519PublicToPem(productKey.publicKey), secret: ctx.secrets.encrypt(linkSecret), connectedAt: new Date() } });
|
||||||
|
|
||||||
|
const issuer = new URL(`${publicUrl}/api/oidc`);
|
||||||
|
const client = await oidc.discovery(issuer, PRODUCT_ID, oidcClientSecret(linkSecret), undefined, { execute: [oidc.allowInsecureRequests] });
|
||||||
|
|
||||||
|
/** The product starts a sign-in from `returnTo`; returns the URL to send the browser to and what to check on return. */
|
||||||
|
async function startSignIn(returnTo: string, extra: Record<string, string> = {}) {
|
||||||
|
const verifier = oidc.randomPKCECodeVerifier();
|
||||||
|
const nonce = oidc.randomNonce();
|
||||||
|
const state = encodeState({ nonce, returnTo });
|
||||||
|
const url = oidc.buildAuthorizationUrl(client, {
|
||||||
|
redirect_uri: `${productUrl}${OIDC_CLIENT_PATHS.callback}`, scope: 'openid profile email phone crosscode', state, nonce,
|
||||||
|
code_challenge: await oidc.calculatePKCECodeChallenge(verifier), code_challenge_method: 'S256', ...extra,
|
||||||
|
});
|
||||||
|
return { url: url.toString(), verifier, nonce, state };
|
||||||
|
}
|
||||||
|
|
||||||
|
/** The product's callback: exchange the code; returns the claims and where it would send the person. */
|
||||||
|
async function finishSignIn(callbackUrl: URL, started: { verifier: string; nonce: string; state: string }) {
|
||||||
|
const tokens = await oidc.authorizationCodeGrant(client, callbackUrl, { pkceCodeVerifier: started.verifier, expectedState: started.state, expectedNonce: started.nonce, idTokenExpected: true });
|
||||||
|
const st = decodeState(callbackUrl.searchParams.get('state'));
|
||||||
|
return { claims: tokens.claims()!, tokens, returnTo: st?.returnTo ?? '/' };
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Runs a whole sign-in for `email` / `password` and returns the claims. */
|
||||||
|
async function signIn(browser: Browser, email: string, password: string, returnTo = '/events/youth-camp?ticket=adult', extra: Record<string, string> = {}) {
|
||||||
|
const started = await startSignIn(returnTo, extra);
|
||||||
|
const { url } = await browser.follow(started.url, (u) => u.pathname === '/signin' || u.pathname === OIDC_CLIENT_PATHS.callback);
|
||||||
|
if (url.pathname === OIDC_CLIENT_PATHS.callback) return finishSignIn(url, started);
|
||||||
|
const uid = url.searchParams.get('uid')!;
|
||||||
|
const step = await api(browser, 'POST', `/api/v2/interaction/${uid}/password`, { email, password });
|
||||||
|
if (step.body.stage !== 'done') return { pending: step.body, uid, started };
|
||||||
|
const back = await browser.follow(step.body.redirectTo as string, (u) => u.pathname === OIDC_CLIENT_PATHS.callback);
|
||||||
|
return finishSignIn(back.url, started);
|
||||||
|
}
|
||||||
|
|
||||||
|
async function api(browser: Browser, method: string, path: string, body?: unknown) {
|
||||||
|
const res = await browser.request(`${publicUrl}${path}`, { method, body, origin: publicUrl });
|
||||||
|
const json = (await res.json().catch(() => ({}))) as Record<string, unknown>;
|
||||||
|
return { status: res.status, body: json };
|
||||||
|
}
|
||||||
|
|
||||||
|
async function makeAccount(data: Record<string, unknown> & { email: string; password?: string }) {
|
||||||
|
const { password, ...rest } = data;
|
||||||
|
return db.account.create({ data: { name: 'Thandi Test', emailVerified: true, noticeVersionAccepted: 1, newsAskedAt: new Date(), passwordHash: await hashPassword(password ?? 'Correct-horse-1'), ...rest } });
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Checks a back-channel call was signed with the link's secret. */
|
||||||
|
const signedByLink = (r: Received) => verify({ secret: linkSecret, timestamp: r.headers[LINK_HEADERS.timestamp], signature: r.headers[LINK_HEADERS.signature], rawBody: r.body }).ok;
|
||||||
|
|
||||||
|
async function close() {
|
||||||
|
await new Promise((r) => server.close(r));
|
||||||
|
await new Promise((r) => productServer.close(r));
|
||||||
|
}
|
||||||
|
|
||||||
|
return { ctx, db: db as MemoryDb, messenger, provider, publicUrl, productUrl, client, received, productReplies, linkSecret, productKey, startSignIn, finishSignIn, signIn, api, makeAccount, signedByLink, close };
|
||||||
|
}
|
||||||
@@ -0,0 +1,172 @@
|
|||||||
|
/**
|
||||||
|
* An in-memory stand-in for the Prisma client: every model the app uses, with the schema's
|
||||||
|
* defaults and unique fields, and generic `where` matching (equality, in / notIn, gt / gte / lt /
|
||||||
|
* lte, not, contains with mode insensitive, AND / OR). Enough to run the whole app in tests,
|
||||||
|
* including oidc-provider's storage.
|
||||||
|
*/
|
||||||
|
import crypto from 'node:crypto';
|
||||||
|
|
||||||
|
type Row = Record<string, unknown>;
|
||||||
|
|
||||||
|
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,
|
||||||
|
}),
|
||||||
|
recoveryCode: () => ({ usedAt: null }),
|
||||||
|
pendingSignIn: () => ({ accountId: null, codeHash: null, codeSentAt: null, attempts: 0, amr: [], pendingTotpSecret: null, remember: false }),
|
||||||
|
emailToken: () => ({ interactionUid: 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 }),
|
||||||
|
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 UNIQUE: Record<string, string[]> = { account: ['email'], recoveryCode: ['codeHash'], emailToken: ['tokenHash'], delivery: ['callId'] };
|
||||||
|
const HAS_UPDATED_AT = new Set(['account', 'appSetting', 'productLink']);
|
||||||
|
|
||||||
|
const v = (x: unknown) => (x instanceof Date ? x.getTime() : x);
|
||||||
|
|
||||||
|
function matchValue(actual: unknown, cond: unknown): boolean {
|
||||||
|
if (cond !== null && typeof cond === 'object' && !(cond instanceof Date) && !Array.isArray(cond)) {
|
||||||
|
const c = cond as Record<string, unknown>;
|
||||||
|
const insensitive = c.mode === 'insensitive';
|
||||||
|
return Object.entries(c).every(([op, x]) => {
|
||||||
|
switch (op) {
|
||||||
|
case 'mode': return true;
|
||||||
|
case 'equals': return v(actual) === v(x);
|
||||||
|
case 'in': return (x as unknown[]).map(v).includes(v(actual));
|
||||||
|
case 'notIn': return !(x as unknown[]).map(v).includes(v(actual));
|
||||||
|
case 'gt': return actual != null && (v(actual) as number) > (v(x) as number);
|
||||||
|
case 'gte': return actual != null && (v(actual) as number) >= (v(x) as number);
|
||||||
|
case 'lt': return actual != null && (v(actual) as number) < (v(x) as number);
|
||||||
|
case 'lte': return actual != null && (v(actual) as number) <= (v(x) as number);
|
||||||
|
case 'not': return x === null ? actual != null : !matchValue(actual, x);
|
||||||
|
case 'contains': return typeof actual === 'string' && (insensitive ? actual.toLowerCase().includes(String(x).toLowerCase()) : actual.includes(String(x)));
|
||||||
|
default: throw new Error(`memoryDb: no operator ${op}`);
|
||||||
|
}
|
||||||
|
});
|
||||||
|
}
|
||||||
|
return v(actual) === v(cond);
|
||||||
|
}
|
||||||
|
|
||||||
|
export function matches(row: Row, where: Row = {}): boolean {
|
||||||
|
return Object.entries(where ?? {}).every(([k, cond]) => {
|
||||||
|
if (k === 'AND') return (cond as Row[]).every((w) => matches(row, w));
|
||||||
|
if (k === 'OR') return (cond as Row[]).some((w) => matches(row, w));
|
||||||
|
if (k === 'NOT') return !matches(row, cond as Row);
|
||||||
|
return matchValue(row[k], cond);
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
const clone = <T>(x: T): T => structuredClone(x);
|
||||||
|
const pick = (row: Row, select?: Row) => (select ? Object.fromEntries(Object.keys(select).filter((k) => select[k]).map((k) => [k, row[k]])) : row);
|
||||||
|
|
||||||
|
function order(rows: Row[], orderBy?: Row | Row[]) {
|
||||||
|
const list = Array.isArray(orderBy) ? orderBy : orderBy ? [orderBy] : [];
|
||||||
|
return [...rows].sort((a, b) => {
|
||||||
|
for (const o of list) {
|
||||||
|
const [k, dir] = Object.entries(o)[0]!;
|
||||||
|
const x = v(a[k]) as number;
|
||||||
|
const y = v(b[k]) as number;
|
||||||
|
const d = x < y ? -1 : x > y ? 1 : 0;
|
||||||
|
if (d) return dir === 'desc' ? -d : d;
|
||||||
|
}
|
||||||
|
return 0;
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
function prismaError(code: string, message: string) {
|
||||||
|
return Object.assign(new Error(message), { code });
|
||||||
|
}
|
||||||
|
|
||||||
|
function model(name: string, tables: Map<string, Map<unknown, Row>>) {
|
||||||
|
const key = KEYS[name] ?? 'id';
|
||||||
|
const table = () => {
|
||||||
|
if (!tables.has(name)) tables.set(name, new Map());
|
||||||
|
return tables.get(name)!;
|
||||||
|
};
|
||||||
|
const findWhere = (where: Row) => {
|
||||||
|
if (where && key in where && typeof where[key] !== 'object') return table().get(where[key]) ?? null;
|
||||||
|
for (const u of UNIQUE[name] ?? []) if (where && u in where) return [...table().values()].find((r) => r[u] === where[u]) ?? null;
|
||||||
|
return [...table().values()].find((r) => matches(r, where)) ?? null;
|
||||||
|
};
|
||||||
|
const checkUnique = (row: Row, except?: unknown) => {
|
||||||
|
for (const u of UNIQUE[name] ?? []) {
|
||||||
|
if (row[u] == null) continue;
|
||||||
|
if ([...table().values()].some((r) => r[key] !== except && r[u] === row[u])) throw prismaError('P2002', `Unique constraint failed on ${name}.${u}`);
|
||||||
|
}
|
||||||
|
};
|
||||||
|
const api = {
|
||||||
|
findUnique: async ({ where, select }: { where: Row; select?: Row }) => { const r = findWhere(where); return r ? pick(clone(r), select) : null; },
|
||||||
|
findUniqueOrThrow: async (args: { where: Row; select?: Row }) => { const r = await api.findUnique(args); if (!r) throw prismaError('P2025', `${name} not found`); return r; },
|
||||||
|
findFirst: async ({ where, orderBy }: { where?: Row; orderBy?: Row | Row[] } = {}) => { const r = order([...table().values()].filter((x) => matches(x, where)), orderBy)[0]; return r ? clone(r) : null; },
|
||||||
|
findMany: async ({ where, orderBy, take, skip, select }: { where?: Row; orderBy?: Row | Row[]; take?: number; skip?: number; select?: Row } = {}) =>
|
||||||
|
order([...table().values()].filter((x) => matches(x, where)), orderBy).slice(skip ?? 0, (skip ?? 0) + (take ?? Infinity)).map((r) => pick(clone(r), select)),
|
||||||
|
count: async ({ where }: { where?: Row } = {}) => [...table().values()].filter((x) => matches(x, where)).length,
|
||||||
|
create: async ({ data }: { data: Row }) => {
|
||||||
|
const now = new Date();
|
||||||
|
const row: Row = { ...(DEFAULTS[name]?.() ?? {}), ...(key === 'id' ? { id: crypto.randomUUID() } : {}), createdAt: now, ...(HAS_UPDATED_AT.has(name) ? { updatedAt: now } : {}), ...clone(data) };
|
||||||
|
if (table().has(row[key])) throw prismaError('P2002', `Unique constraint failed on ${name}.${key}`);
|
||||||
|
checkUnique(row);
|
||||||
|
table().set(row[key], row);
|
||||||
|
return clone(row);
|
||||||
|
},
|
||||||
|
update: async ({ where, data }: { where: Row; data: Row }) => {
|
||||||
|
const r = findWhere(where);
|
||||||
|
if (!r) throw prismaError('P2025', `Record to update not found (${name})`);
|
||||||
|
const next = { ...r, ...clone(data), ...(HAS_UPDATED_AT.has(name) ? { updatedAt: new Date() } : {}) };
|
||||||
|
checkUnique(next, r[key]);
|
||||||
|
table().set(r[key], next);
|
||||||
|
return clone(next);
|
||||||
|
},
|
||||||
|
updateMany: async ({ where, data }: { where?: Row; data: Row }) => {
|
||||||
|
let count = 0;
|
||||||
|
for (const [k, r] of table()) if (matches(r, where)) { table().set(k, { ...r, ...clone(data) }); count++; }
|
||||||
|
return { count };
|
||||||
|
},
|
||||||
|
upsert: async ({ where, create, update }: { where: Row; create: Row; update: Row }) => {
|
||||||
|
const r = findWhere(where);
|
||||||
|
return r ? api.update({ where, data: update }) : api.create({ data: create });
|
||||||
|
},
|
||||||
|
delete: async ({ where }: { where: Row }) => {
|
||||||
|
const r = findWhere(where);
|
||||||
|
if (!r) throw prismaError('P2025', `Record to delete does not exist (${name})`);
|
||||||
|
table().delete(r[key]);
|
||||||
|
cascade(name, r[key]);
|
||||||
|
return clone(r);
|
||||||
|
},
|
||||||
|
deleteMany: async ({ where }: { where?: Row } = {}) => {
|
||||||
|
let count = 0;
|
||||||
|
for (const [k, r] of [...table()]) if (matches(r, where)) { table().delete(k); cascade(name, k); count++; }
|
||||||
|
return { count };
|
||||||
|
},
|
||||||
|
};
|
||||||
|
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);
|
||||||
|
};
|
||||||
|
return api;
|
||||||
|
}
|
||||||
|
|
||||||
|
export type MemoryDb = Record<string, ReturnType<typeof model>> & { tables: Map<string, Map<unknown, Row>>; $queryRawUnsafe: () => Promise<unknown[]>; $disconnect: () => Promise<void> };
|
||||||
|
|
||||||
|
export function memoryDb(): MemoryDb {
|
||||||
|
const tables = new Map<string, Map<unknown, Row>>();
|
||||||
|
const models = new Map<string, ReturnType<typeof model>>();
|
||||||
|
return new Proxy({} as MemoryDb, {
|
||||||
|
get(_t, prop: string) {
|
||||||
|
if (prop === 'tables') return tables;
|
||||||
|
if (prop === '$queryRawUnsafe') return async () => [{ ok: 1 }];
|
||||||
|
if (prop === '$disconnect') return async () => {};
|
||||||
|
if (prop === 'then') return undefined;
|
||||||
|
if (!models.has(prop)) models.set(prop, model(prop, tables));
|
||||||
|
return models.get(prop);
|
||||||
|
},
|
||||||
|
});
|
||||||
|
}
|
||||||
@@ -0,0 +1,5 @@
|
|||||||
|
{
|
||||||
|
"extends": "./tsconfig.json",
|
||||||
|
"compilerOptions": { "rootDir": "src", "outDir": "dist" },
|
||||||
|
"include": ["src"]
|
||||||
|
}
|
||||||
@@ -0,0 +1,21 @@
|
|||||||
|
{
|
||||||
|
// ES modules throughout (oidc-provider and openid-client are ESM only; docs/ACCOUNTS-1.0-PLAN.md §3).
|
||||||
|
"compilerOptions": {
|
||||||
|
"target": "ES2023",
|
||||||
|
"module": "nodenext",
|
||||||
|
"moduleResolution": "nodenext",
|
||||||
|
"lib": ["ES2023"],
|
||||||
|
"strict": true,
|
||||||
|
"noImplicitOverride": true,
|
||||||
|
"noFallthroughCasesInSwitch": true,
|
||||||
|
"esModuleInterop": true,
|
||||||
|
"resolveJsonModule": true,
|
||||||
|
"skipLibCheck": true,
|
||||||
|
"forceConsistentCasingInFileNames": true,
|
||||||
|
"sourceMap": true,
|
||||||
|
"rootDir": ".",
|
||||||
|
"outDir": "dist",
|
||||||
|
"types": ["node"]
|
||||||
|
},
|
||||||
|
"include": ["src", "tests", "scripts", "prisma.config.ts"]
|
||||||
|
}
|
||||||
@@ -0,0 +1 @@
|
|||||||
|
test-results/
|
||||||
@@ -0,0 +1,4 @@
|
|||||||
|
{
|
||||||
|
"private": true,
|
||||||
|
"type": "module"
|
||||||
|
}
|
||||||
@@ -0,0 +1,73 @@
|
|||||||
|
/**
|
||||||
|
* The e2e backend (playwright.config.ts): Accounts on port 5210 with the in-memory database from the
|
||||||
|
* backend tests (no Postgres needed), and a test product on 5211 that signs people in through it
|
||||||
|
* with @crosscode/auth-client, as the Website will. The pages run with `next dev` on 3210 and send
|
||||||
|
* /api here.
|
||||||
|
*
|
||||||
|
* Test helpers on the product: GET /test/code?to=<email or phone> (the last code sent),
|
||||||
|
* GET /test/link?to=<email> (the last link sent), GET /test/totp?secret=… (the current app code).
|
||||||
|
*/
|
||||||
|
import http from 'node:http';
|
||||||
|
import { accountsClient } from '@crosscode/auth-client';
|
||||||
|
import { ed25519PublicToPem, generateEd25519, newLinkSecret } from '@crosscode/contracts/signing';
|
||||||
|
import { createApp } from '../backend/src/app.js';
|
||||||
|
import { createCtx } from '../backend/src/context.js';
|
||||||
|
import { loadConfig } from '../backend/src/lib/config.js';
|
||||||
|
import { MemoryMessenger } from '../backend/src/lib/messages.js';
|
||||||
|
import { hashPassword } from '../backend/src/lib/passwords.js';
|
||||||
|
import { codeAt } from '../backend/src/lib/totp.js';
|
||||||
|
import { createProvider } from '../backend/src/oidc/provider.js';
|
||||||
|
import { memoryDb } from '../backend/tests/support/memoryDb.js';
|
||||||
|
|
||||||
|
const WEB = 'http://localhost:3210';
|
||||||
|
const PRODUCT = 'http://localhost:5211';
|
||||||
|
const PRODUCT_ID = '3b0f6a52-6c1e-4b7a-9d0e-2f1a8c4b7e02';
|
||||||
|
|
||||||
|
const db = memoryDb();
|
||||||
|
const messenger = new MemoryMessenger();
|
||||||
|
// Behind Next's rewrite (as behind nginx in production): the public host comes in X-Forwarded-Host.
|
||||||
|
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: '9a4c2f1e-7b3d-4e5a-8c6f-0d1e2f3a4b5c',
|
||||||
|
church_profile: JSON.stringify({ name: 'Hope Family Church', shortName: 'Hope', branding: { logoUrl: null, iconUrl: null, colours: { primary: '#7c2d12', accent: '#f2a900' } } }),
|
||||||
|
});
|
||||||
|
const linkSecret = newLinkSecret();
|
||||||
|
await db.productLink.create({ data: { installId: PRODUCT_ID, product: 'website', url: PRODUCT, publicKey: ed25519PublicToPem(generateEd25519().publicKey), secret: ctx.secrets.encrypt(linkSecret), connectedAt: new Date() } });
|
||||||
|
const seed = (email: string, extra: Record<string, unknown> = {}) => hashPassword('Correct-horse-1').then((passwordHash) =>
|
||||||
|
db.account.create({ data: { name: 'Thandi Test', email, emailVerified: true, noticeVersionAccepted: 1, newsAskedAt: new Date(), passwordHash, ...extra } }));
|
||||||
|
await seed('thandi@hope.test');
|
||||||
|
await seed('admin@hope.test', { name: 'Ada Admin', role: 'admin' });
|
||||||
|
|
||||||
|
const provider = await createProvider(ctx);
|
||||||
|
http.createServer(createApp(ctx, provider)).listen(5210, '127.0.0.1', () => console.log('[e2e] Accounts on 5210'));
|
||||||
|
|
||||||
|
// ─── The test product ────────────────────────────────────────────────────────
|
||||||
|
|
||||||
|
// Made on the first sign-in: the pages (and so discovery through them) start after this server.
|
||||||
|
let authP: ReturnType<typeof accountsClient> | null = null;
|
||||||
|
const getAuth = () => (authP ??= accountsClient({ accountsUrl: WEB, productUrl: PRODUCT, clientId: PRODUCT_ID, linkSecret, allowInsecure: true }));
|
||||||
|
const cookieOf = (req: http.IncomingMessage, name: string) => String(req.headers.cookie ?? '').split(';').map((c) => c.trim().split('=')).find(([k]) => k === name)?.[1];
|
||||||
|
|
||||||
|
http.createServer(async (req, res) => {
|
||||||
|
const url = new URL(req.url ?? '/', PRODUCT);
|
||||||
|
const send = (status: number, body: string, type = 'text/html') => res.writeHead(status, { 'content-type': type }).end(body);
|
||||||
|
try {
|
||||||
|
if (url.pathname === '/start') {
|
||||||
|
const { url: to, cookie } = await (await getAuth()).startSignIn(url.searchParams.get('returnTo') ?? '/', { requireTwoFactor: url.searchParams.get('mfa') === '1' });
|
||||||
|
res.writeHead(302, { location: to, 'set-cookie': `signin=${cookie}; Path=/; HttpOnly; SameSite=Lax` }).end();
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
if (url.pathname === '/api/auth/callback') {
|
||||||
|
const r = await (await getAuth()).finishSignIn(url, cookieOf(req, 'signin'));
|
||||||
|
send(200, `<!doctype html><title>Product</title><h1>Signed in to the product</h1><p id="email">${r.claims.email}</p><p id="return">${r.returnTo}</p><p id="amr">${r.claims.amr.join(' ')}</p>`);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
if (url.pathname === '/test/code') return send(200, messenger.lastCode(url.searchParams.get('to') ?? '') ?? '', 'text/plain');
|
||||||
|
if (url.pathname === '/test/link') return send(200, messenger.lastLink(url.searchParams.get('to') ?? '') ?? '', 'text/plain');
|
||||||
|
if (url.pathname === '/test/totp') return send(200, codeAt(url.searchParams.get('secret') ?? '', Math.floor(Date.now() / 30000)), 'text/plain');
|
||||||
|
if (req.method === 'POST') return send(200, '{}', 'application/json');
|
||||||
|
send(200, '<!doctype html><title>Product home</title><h1>Product home</h1>');
|
||||||
|
} catch (e) {
|
||||||
|
send(500, `<pre>${String((e as Error).message)}</pre>`);
|
||||||
|
}
|
||||||
|
}).listen(5211, '127.0.0.1', () => console.log('[e2e] Test product on 5211'));
|
||||||
@@ -0,0 +1,103 @@
|
|||||||
|
import { expect, test, type Page } from "@playwright/test";
|
||||||
|
|
||||||
|
// The release checks (ROADMAP-v3 §9) on Accounts' real pages: signing in from a deep link lands
|
||||||
|
// back on that page, through sign-up, a password reset and two-step sign-in set up on the way; a
|
||||||
|
// foreign return address is refused. A test product (e2e/server.ts) starts and finishes sign-ins.
|
||||||
|
const PRODUCT = "http://localhost:5211";
|
||||||
|
const helper = async (page: Page, path: string) => (await (await page.request.get(`${PRODUCT}${path}`)).text()).trim();
|
||||||
|
|
||||||
|
async function signIn(page: Page, email: string, password = "Correct-horse-1") {
|
||||||
|
await page.getByLabel("Email address").fill(email);
|
||||||
|
await page.getByLabel("Password").fill(password);
|
||||||
|
await page.getByRole("button", { name: "Sign in" }).click();
|
||||||
|
}
|
||||||
|
|
||||||
|
test("signing in from a deep link returns to that exact page", async ({ page }) => {
|
||||||
|
await page.goto(`${PRODUCT}/start?returnTo=${encodeURIComponent("/events/youth-camp/register?ticket=adult")}`);
|
||||||
|
await expect(page.getByRole("heading", { name: "Sign in to Hope Family Church" })).toBeVisible();
|
||||||
|
await signIn(page, "thandi@hope.test");
|
||||||
|
await expect(page.locator("#return")).toHaveText("/events/youth-camp/register?ticket=adult");
|
||||||
|
await expect(page.locator("#email")).toHaveText("thandi@hope.test");
|
||||||
|
});
|
||||||
|
|
||||||
|
test("a wrong password says so without saying whether the account exists", async ({ page }) => {
|
||||||
|
await page.goto(`${PRODUCT}/start?returnTo=/`);
|
||||||
|
await signIn(page, "thandi@hope.test", "not-the-password");
|
||||||
|
await expect(page.locator("main").getByRole("alert")).toHaveText("That email address and password don't match.");
|
||||||
|
await signIn(page, "nobody@hope.test", "not-the-password");
|
||||||
|
await expect(page.locator("main").getByRole("alert")).toHaveText("That email address and password don't match.");
|
||||||
|
});
|
||||||
|
|
||||||
|
test("a foreign return address ends on the product's home page", async ({ page }) => {
|
||||||
|
await page.goto(`${PRODUCT}/start?returnTo=${encodeURIComponent("//evil.example/steal")}`);
|
||||||
|
await signIn(page, "thandi@hope.test");
|
||||||
|
await expect(page.locator("#return")).toHaveText("/");
|
||||||
|
});
|
||||||
|
|
||||||
|
test("sign-up with an emailed code, back to the page", async ({ page }) => {
|
||||||
|
await page.goto(`${PRODUCT}/start?returnTo=${encodeURIComponent("/give?fund=building")}`);
|
||||||
|
await page.getByRole("button", { name: "Create an account" }).click();
|
||||||
|
await page.getByLabel("Your name").fill("New Person");
|
||||||
|
await page.getByLabel("Email address").fill("new@hope.test");
|
||||||
|
await page.getByLabel("Password").fill("Correct-horse-2");
|
||||||
|
await page.getByLabel(/privacy notice/).check();
|
||||||
|
await page.getByRole("button", { name: "Create account" }).click();
|
||||||
|
await expect(page.getByRole("heading", { name: "Check your email" })).toBeVisible();
|
||||||
|
await page.getByLabel("Code").fill(await helper(page, "/test/code?to=new@hope.test"));
|
||||||
|
await page.getByRole("button", { name: "Continue" }).click();
|
||||||
|
await expect(page.locator("#return")).toHaveText("/give?fund=building");
|
||||||
|
await expect(page.locator("#email")).toHaveText("new@hope.test");
|
||||||
|
});
|
||||||
|
|
||||||
|
test("forgot password in the middle of signing in still returns to the page", async ({ page }) => {
|
||||||
|
await page.goto(`${PRODUCT}/start?returnTo=/my-tickets`);
|
||||||
|
await page.getByRole("link", { name: "Forgot your password?" }).click();
|
||||||
|
await page.getByLabel("Email address").fill("thandi@hope.test");
|
||||||
|
await page.getByRole("button", { name: "Send the link" }).click();
|
||||||
|
await expect(page.getByRole("status")).toContainText("a link is on its way");
|
||||||
|
await page.goto(await helper(page, "/test/link?to=thandi@hope.test"));
|
||||||
|
await page.getByLabel("New password").fill("Correct-horse-1");
|
||||||
|
await page.getByRole("button", { name: "Save and sign in" }).click();
|
||||||
|
await signIn(page, "thandi@hope.test");
|
||||||
|
await expect(page.locator("#return")).toHaveText("/my-tickets");
|
||||||
|
});
|
||||||
|
|
||||||
|
test("a product asking for two-step sign-in: set up with an app, recovery codes, then back", async ({ page }) => {
|
||||||
|
await page.goto(`${PRODUCT}/start?mfa=1&returnTo=/dashboard`);
|
||||||
|
await signIn(page, "thandi@hope.test");
|
||||||
|
await expect(page.getByRole("heading", { name: "Set up two-step sign-in" })).toBeVisible();
|
||||||
|
await page.getByRole("button", { name: /An authenticator app/ }).click();
|
||||||
|
const key = (await page.getByText(/Or type this key:/).innerText()).replace(/.*:\s*/, "").trim();
|
||||||
|
await page.getByLabel("Code").fill(await helper(page, `/test/totp?secret=${key}`));
|
||||||
|
await page.getByRole("button", { name: "Turn on" }).click();
|
||||||
|
await expect(page.getByRole("heading", { name: "Save your recovery codes" })).toBeVisible();
|
||||||
|
await page.getByRole("button", { name: "I've saved them" }).click();
|
||||||
|
await expect(page.locator("#return")).toHaveText("/dashboard");
|
||||||
|
await expect(page.locator("#amr")).toHaveText("pwd otp mfa");
|
||||||
|
});
|
||||||
|
|
||||||
|
test("the account page: signs in first, then saves details", async ({ page }) => {
|
||||||
|
await page.goto("/account");
|
||||||
|
await expect(page.getByRole("heading", { name: "Sign in to Hope Family Church" })).toBeVisible();
|
||||||
|
await page.getByLabel("Email address").fill("new@hope.test");
|
||||||
|
await page.getByLabel("Password").fill("Correct-horse-2");
|
||||||
|
await page.getByRole("button", { name: "Sign in" }).click();
|
||||||
|
await expect(page.getByRole("heading", { name: "Your account" })).toBeVisible();
|
||||||
|
await page.getByLabel("Name").fill("New Person-Smith");
|
||||||
|
await page.getByRole("button", { name: "Save", exact: true }).click();
|
||||||
|
await expect(page.getByRole("status")).toContainText("Your details are saved");
|
||||||
|
});
|
||||||
|
|
||||||
|
test("admin: needs two-step sign-in, then lists people", async ({ page }) => {
|
||||||
|
await page.goto("/admin");
|
||||||
|
await signIn(page, "admin@hope.test");
|
||||||
|
await expect(page.getByRole("heading", { name: "Set up two-step sign-in" })).toBeVisible();
|
||||||
|
await expect(page.getByText("Admins must use a second step")).toBeVisible();
|
||||||
|
await page.getByRole("button", { name: /An authenticator app/ }).click();
|
||||||
|
const key = (await page.getByText(/Or type this key:/).innerText()).replace(/.*:\s*/, "").trim();
|
||||||
|
await page.getByLabel("Code").fill(await helper(page, `/test/totp?secret=${key}`));
|
||||||
|
await page.getByRole("button", { name: "Turn on" }).click();
|
||||||
|
await page.getByRole("button", { name: "I've saved them" }).click();
|
||||||
|
await expect(page.getByRole("heading", { name: "Accounts admin" })).toBeVisible();
|
||||||
|
await expect(page.getByText("thandi@hope.test")).toBeVisible();
|
||||||
|
});
|
||||||
@@ -0,0 +1,22 @@
|
|||||||
|
// PM2 config template. Each install keeps its own copy as ecosystem.config.cjs (not in git, so
|
||||||
|
// deploys never change it); crosscode creates it from this file the first time with the church's
|
||||||
|
// PM2 names and ports.
|
||||||
|
module.exports = {
|
||||||
|
apps: [
|
||||||
|
{
|
||||||
|
name: 'accounts-backend',
|
||||||
|
cwd: __dirname + '/backend',
|
||||||
|
script: 'dist/index.js',
|
||||||
|
env: { NODE_ENV: 'production' },
|
||||||
|
max_memory_restart: '400M',
|
||||||
|
},
|
||||||
|
{
|
||||||
|
name: 'accounts-frontend',
|
||||||
|
cwd: __dirname + '/frontend',
|
||||||
|
script: 'npm',
|
||||||
|
args: 'start -- -p 3200',
|
||||||
|
env: { NODE_ENV: 'production' },
|
||||||
|
max_memory_restart: '400M',
|
||||||
|
},
|
||||||
|
],
|
||||||
|
};
|
||||||
@@ -0,0 +1,24 @@
|
|||||||
|
{
|
||||||
|
"schema": "crosscode.env-template/1",
|
||||||
|
"product": "accounts",
|
||||||
|
"files": {
|
||||||
|
"backend/.env": [
|
||||||
|
{ "name": "NODE_ENV", "layer": "generated", "required": true, "description": "production" },
|
||||||
|
{ "name": "PORT", "layer": "install", "from": "{apiPort}", "required": true, "description": "The backend's port (from the Hub's port list)" },
|
||||||
|
{ "name": "DATABASE_URL", "layer": "generated", "required": true, "description": "Made on the server with a new password; never leaves it" },
|
||||||
|
{ "name": "ACCOUNTS_SECRET", "layer": "generated", "required": true, "description": "Encrypts stored secrets (signing keys, 2FA secrets, link secrets) and signs cookies: never change it" },
|
||||||
|
{ "name": "ACCOUNTS_URL", "layer": "install", "from": "https://{domain}", "required": true, "description": "The public address; the OIDC issuer is <this>/api/oidc" },
|
||||||
|
{ "name": "TRUST_PROXY", "layer": "server", "required": true, "description": "Behind frp: loopback" },
|
||||||
|
{ "name": "APP_TIMEZONE", "layer": "install", "default": "Africa/Johannesburg" },
|
||||||
|
{ "name": "HUB_URL", "layer": "defaults", "default": "https://hub.crosscode.co.za" },
|
||||||
|
{ "name": "HUB_PUBLIC_KEY", "layer": "defaults", "description": "Only for a Hub other than production" },
|
||||||
|
{ "name": "HUB_LICENCE_KEY", "layer": "install", "description": "A Hub install registers by itself with this (CCA-…)" },
|
||||||
|
{ "name": "HUB_ADMIN_NAME", "layer": "install" },
|
||||||
|
{ "name": "HUB_ADMIN_EMAIL", "layer": "install", "description": "Setup only lets this address become the first admin" },
|
||||||
|
{ "name": "JOBS_ENABLED", "layer": "defaults", "default": "true" }
|
||||||
|
],
|
||||||
|
"frontend/.env.production": [
|
||||||
|
{ "name": "ACCOUNTS_API_URL", "layer": "install", "from": "http://127.0.0.1:{apiPort}", "required": true, "description": "Where the pages reach the backend on this server" }
|
||||||
|
]
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,4 @@
|
|||||||
|
node_modules/
|
||||||
|
.next/
|
||||||
|
next-env.d.ts
|
||||||
|
.env*
|
||||||
@@ -0,0 +1,9 @@
|
|||||||
|
<!-- BEGIN:nextjs-agent-rules -->
|
||||||
|
|
||||||
|
## This is NOT the Next.js you know
|
||||||
|
|
||||||
|
This version has breaking changes — APIs, conventions, and file structure may all differ from your training data. Read the relevant guide in `node_modules/next/dist/docs/` (resolved from this file's directory; in monorepos the `next` package may not be visible from the repo root) before writing any code. Heed deprecation notices.
|
||||||
|
|
||||||
|
This block is written and re-added by `next dev` — verify at `node_modules/next/dist/server/lib/generate-agent-files.js`. Removing it from a diff only re-creates the uncommitted change; committing it with your work keeps the tree clean.
|
||||||
|
|
||||||
|
<!-- END:nextjs-agent-rules -->
|
||||||
@@ -0,0 +1,17 @@
|
|||||||
|
import { defineConfig, globalIgnores } from "eslint/config";
|
||||||
|
import nextVitals from "eslint-config-next/core-web-vitals";
|
||||||
|
import nextTs from "eslint-config-next/typescript";
|
||||||
|
|
||||||
|
// Next.js 16's own flat configs, as Cross Events. Run with `npm run lint`.
|
||||||
|
export default defineConfig([
|
||||||
|
...nextVitals,
|
||||||
|
...nextTs,
|
||||||
|
{
|
||||||
|
rules: {
|
||||||
|
"react-hooks/exhaustive-deps": ["warn", { additionalHooks: "^useExternalEffect$" }],
|
||||||
|
// Logos and QR codes are small and come from the church's own settings.
|
||||||
|
"@next/next/no-img-element": "off",
|
||||||
|
},
|
||||||
|
},
|
||||||
|
globalIgnores([".next/**", "out/**", "next-env.d.ts"]),
|
||||||
|
]);
|
||||||
@@ -0,0 +1,25 @@
|
|||||||
|
import type { NextConfig } from "next";
|
||||||
|
|
||||||
|
// Everything under /api is the backend (docs/ACCOUNTS-1.0-PLAN.md §1). On a server nginx sends it
|
||||||
|
// there; in development (and when Next is reached directly) this rewrite does.
|
||||||
|
const api = (process.env.ACCOUNTS_API_URL || "http://127.0.0.1:5200").replace(/\/+$/, "");
|
||||||
|
|
||||||
|
const nextConfig: NextConfig = {
|
||||||
|
poweredByHeader: false,
|
||||||
|
transpilePackages: ["@crosscode/ui"],
|
||||||
|
async rewrites() {
|
||||||
|
return [{ source: "/api/:path*", destination: `${api}/api/:path*` }];
|
||||||
|
},
|
||||||
|
async headers() {
|
||||||
|
return [{
|
||||||
|
source: "/:path*",
|
||||||
|
headers: [
|
||||||
|
{ key: "X-Robots-Tag", value: "noindex, nofollow" },
|
||||||
|
{ key: "Referrer-Policy", value: "same-origin" },
|
||||||
|
{ key: "X-Content-Type-Options", value: "nosniff" },
|
||||||
|
],
|
||||||
|
}];
|
||||||
|
},
|
||||||
|
};
|
||||||
|
|
||||||
|
export default nextConfig;
|
||||||
@@ -0,0 +1,35 @@
|
|||||||
|
{
|
||||||
|
"name": "@crosscode/accounts-frontend",
|
||||||
|
"version": "1.0.0",
|
||||||
|
"private": true,
|
||||||
|
"description": "Cross Code Accounts: the church's sign-in pages, the account page and admin",
|
||||||
|
"scripts": {
|
||||||
|
"dev": "next dev",
|
||||||
|
"build": "next build",
|
||||||
|
"start": "next start",
|
||||||
|
"lint": "eslint src",
|
||||||
|
"typecheck": "tsc --noEmit"
|
||||||
|
},
|
||||||
|
"dependencies": {
|
||||||
|
"@crosscode/contracts": "*",
|
||||||
|
"@crosscode/ui": "*",
|
||||||
|
"lucide-react": "^0.536.0",
|
||||||
|
"next": "^16.4.6",
|
||||||
|
"qrcode": "^1.5.4",
|
||||||
|
"react": "^19.3.1",
|
||||||
|
"react-dom": "^19.3.1"
|
||||||
|
},
|
||||||
|
"devDependencies": {
|
||||||
|
"@eslint/eslintrc": "^3",
|
||||||
|
"@types/node": "^20",
|
||||||
|
"@types/qrcode": "^1.5.5",
|
||||||
|
"@types/react": "^19.3.0",
|
||||||
|
"@types/react-dom": "^19.3.0",
|
||||||
|
"autoprefixer": "^10.4.21",
|
||||||
|
"eslint": "^10.13.0",
|
||||||
|
"eslint-config-next": "^16.4.6",
|
||||||
|
"postcss": "^8.5.6",
|
||||||
|
"tailwindcss": "3.4",
|
||||||
|
"typescript": "^5"
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1 @@
|
|||||||
|
module.exports = { plugins: { tailwindcss: {}, autoprefixer: {} } };
|
||||||
@@ -0,0 +1,269 @@
|
|||||||
|
"use client";
|
||||||
|
|
||||||
|
import React, { useCallback, useState } from "react";
|
||||||
|
import QRCode from "qrcode";
|
||||||
|
import { Button, Card, Checkbox, Field, Heading, Notice, Shell } from "@crosscode/ui";
|
||||||
|
import { useBranding } from "@/components/BrandingProvider";
|
||||||
|
import { call, selfSignIn } from "@/lib/api";
|
||||||
|
import { useExternalEffect } from "@/lib/hooks";
|
||||||
|
|
||||||
|
type Me = {
|
||||||
|
id: string; name: string; email: string; emailVerified: boolean; phone: string | null; role: "member" | "admin";
|
||||||
|
twoFactor: "totp" | "email" | "whatsapp" | null; recoveryCodesLeft: number; news: { email: boolean; whatsapp: boolean };
|
||||||
|
noticeVersionAccepted: number; noticeVersion: number; lastSignInAt: string | null;
|
||||||
|
};
|
||||||
|
type SignIn = { type: string; at: string; ip: string | null; device: string | null; site: string | null };
|
||||||
|
type Export = { id: string; status: string; createdAt: string; readyAt: string | null; expiresAt: string };
|
||||||
|
|
||||||
|
const METHOD = { totp: "an authenticator app", email: "a code by email", whatsapp: "a code on WhatsApp" } as const;
|
||||||
|
const EVENT: Record<string, string> = {
|
||||||
|
sign_in: "Signed in", sign_in_failed: "Wrong password", locked: "Locked after too many tries", password_reset: "Password reset", password_changed: "Password changed",
|
||||||
|
two_factor_on: "Two-step sign-in turned on", two_factor_off: "Two-step sign-in turned off", recovery_code_used: "Recovery code used", recovery_codes_replaced: "New recovery codes",
|
||||||
|
signed_out_everywhere: "Signed out everywhere", email_changed: "Email address changed", account_created: "Account created",
|
||||||
|
};
|
||||||
|
const when = (iso: string | null) => (iso ? new Date(iso).toLocaleString("en-ZA", { day: "numeric", month: "short", year: "numeric", hour: "2-digit", minute: "2-digit" }) : "—");
|
||||||
|
|
||||||
|
/** The account page (docs/ACCOUNTS-1.0-PLAN.md §8): everything about one's own account. */
|
||||||
|
export function Account() {
|
||||||
|
const branding = useBranding();
|
||||||
|
const [me, setMe] = useState<Me | null>(null);
|
||||||
|
const [msg, setMsg] = useState<{ tone: "success" | "error"; text: string } | null>(null);
|
||||||
|
|
||||||
|
const load = useCallback(async () => {
|
||||||
|
const r = await call<Me>("GET", "/me");
|
||||||
|
if (r.status === 401) return window.location.assign(selfSignIn("/account"));
|
||||||
|
if (r.ok) setMe(r.data);
|
||||||
|
}, []);
|
||||||
|
useExternalEffect(() => { void load(); }, [load]);
|
||||||
|
|
||||||
|
const done = (text: string) => { setMsg({ tone: "success", text }); void load(); };
|
||||||
|
const fail = (text: string) => setMsg({ tone: "error", text });
|
||||||
|
|
||||||
|
if (!me) return <Shell branding={branding}><p className="text-gray-600">Loading…</p></Shell>;
|
||||||
|
|
||||||
|
const signOut = <a href={`/api/oidc/session/end?client_id=accounts-self&post_logout_redirect_uri=${encodeURIComponent(`${window.location.origin}/signed-out`)}`} className="text-sm text-brand underline">Sign out</a>;
|
||||||
|
return (
|
||||||
|
<Shell branding={branding} wide aside={<div className="flex gap-4">{me.role === "admin" && <a href="/admin" className="text-sm text-brand underline">Admin</a>}{signOut}</div>}>
|
||||||
|
<h1 className="mb-1 text-2xl font-semibold">Your account</h1>
|
||||||
|
<p className="mb-6 text-sm text-gray-600">One account for all of {branding.name}'s sites and apps.</p>
|
||||||
|
{msg && <Notice tone={msg.tone}>{msg.text}</Notice>}
|
||||||
|
<div className="grid gap-6 md:grid-cols-2">
|
||||||
|
<Profile me={me} onDone={done} onFail={fail} />
|
||||||
|
<Security me={me} onDone={done} onFail={fail} />
|
||||||
|
<Privacy me={me} onDone={done} onFail={fail} />
|
||||||
|
<Activity onDone={done} />
|
||||||
|
</div>
|
||||||
|
</Shell>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
type Props = { me: Me; onDone: (t: string) => void; onFail: (t: string) => void };
|
||||||
|
|
||||||
|
function Profile({ me, onDone, onFail }: Props) {
|
||||||
|
const [busy, setBusy] = useState(false);
|
||||||
|
const [changingEmail, setChangingEmail] = useState(false);
|
||||||
|
return (
|
||||||
|
<Card>
|
||||||
|
<Heading>Your details</Heading>
|
||||||
|
<form onSubmit={async (e) => {
|
||||||
|
e.preventDefault();
|
||||||
|
const f = new FormData(e.currentTarget);
|
||||||
|
setBusy(true);
|
||||||
|
const r = await call("PUT", "/me", { name: f.get("name"), phone: f.get("phone") || null });
|
||||||
|
setBusy(false);
|
||||||
|
if (r.ok) onDone("Your details are saved, and the church's sites have them too.");
|
||||||
|
else onFail(r.error.message);
|
||||||
|
}}>
|
||||||
|
<Field label="Name" name="name" defaultValue={me.name} required autoComplete="name" />
|
||||||
|
<Field label="Mobile number" name="phone" type="tel" defaultValue={me.phone ?? ""} autoComplete="tel" />
|
||||||
|
<Button type="submit" busy={busy}>Save</Button>
|
||||||
|
</form>
|
||||||
|
<div className="mt-6 border-t pt-4">
|
||||||
|
<p className="text-sm text-gray-700">Email address: <strong>{me.email}</strong></p>
|
||||||
|
{!changingEmail ? (
|
||||||
|
<Button variant="link" className="mt-1 text-sm" onClick={() => setChangingEmail(true)}>Change it</Button>
|
||||||
|
) : (
|
||||||
|
<form className="mt-3" onSubmit={async (e) => {
|
||||||
|
e.preventDefault();
|
||||||
|
const f = new FormData(e.currentTarget);
|
||||||
|
const r = await call("POST", "/me/email", { email: f.get("email"), password: f.get("password") });
|
||||||
|
if (r.ok) { setChangingEmail(false); onDone("Check your new email address for a link to confirm it. Until then you sign in with the old one."); } else onFail(r.error.message);
|
||||||
|
}}>
|
||||||
|
<Field label="New email address" name="email" type="email" required />
|
||||||
|
<Field label="Your password" name="password" type="password" required autoComplete="current-password" />
|
||||||
|
<Button type="submit">Send the link</Button>
|
||||||
|
</form>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
</Card>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
function Security({ me, onDone, onFail }: Props) {
|
||||||
|
const [setup, setSetup] = useState<{ method: string; secret?: string; otpauthUrl?: string; sentTo?: string; qr?: string } | null>(null);
|
||||||
|
const [codes, setCodes] = useState<string[] | null>(null);
|
||||||
|
|
||||||
|
const start = async (method: string) => {
|
||||||
|
const r = await call<{ method: string; secret?: string; otpauthUrl?: string; sentTo?: string }>("POST", "/me/two-factor/setup", { method });
|
||||||
|
if (!r.ok) return onFail(r.error.message);
|
||||||
|
setSetup({ ...r.data, qr: r.data.otpauthUrl ? await QRCode.toDataURL(r.data.otpauthUrl, { margin: 1, width: 200 }) : undefined });
|
||||||
|
};
|
||||||
|
|
||||||
|
return (
|
||||||
|
<Card>
|
||||||
|
<Heading>Signing in</Heading>
|
||||||
|
<p className="mb-3 text-sm text-gray-700">
|
||||||
|
Two-step sign-in: {me.twoFactor ? <strong>on, with {METHOD[me.twoFactor]}</strong> : <strong>off</strong>}
|
||||||
|
{me.twoFactor && <span className="text-gray-500"> · {me.recoveryCodesLeft} recovery codes left</span>}
|
||||||
|
</p>
|
||||||
|
{codes && (
|
||||||
|
<Notice tone="warning">
|
||||||
|
Save these recovery codes somewhere safe. Each works once; they won't be shown again.
|
||||||
|
<pre className="mt-2 font-mono">{codes.join("\n")}</pre>
|
||||||
|
</Notice>
|
||||||
|
)}
|
||||||
|
{setup ? (
|
||||||
|
<form onSubmit={async (e) => {
|
||||||
|
e.preventDefault();
|
||||||
|
const r = await call<{ recoveryCodes: string[] }>("POST", "/me/two-factor/confirm", { method: setup.method, code: new FormData(e.currentTarget).get("code") });
|
||||||
|
if (!r.ok) return onFail(r.error.message);
|
||||||
|
setSetup(null);
|
||||||
|
setCodes(r.data.recoveryCodes);
|
||||||
|
onDone("Two-step sign-in is on.");
|
||||||
|
}}>
|
||||||
|
{setup.qr && <img src={setup.qr} alt="QR code for your authenticator app" className="mb-2 h-40 w-40" />}
|
||||||
|
{setup.secret && <p className="mb-3 break-all font-mono text-xs text-gray-600">Key: {setup.secret}</p>}
|
||||||
|
{setup.sentTo && <p className="mb-3 text-sm">We sent a code to <strong>{setup.sentTo}</strong>.</p>}
|
||||||
|
<Field label="Code" name="code" inputMode="numeric" autoComplete="one-time-code" required />
|
||||||
|
<div className="flex gap-2"><Button type="submit">Turn on</Button><Button type="button" variant="secondary" onClick={() => setSetup(null)}>Cancel</Button></div>
|
||||||
|
</form>
|
||||||
|
) : (
|
||||||
|
<div className="mb-4 flex flex-wrap gap-2">
|
||||||
|
<Button variant="secondary" onClick={() => start("totp")}>{me.twoFactor ? "Use an authenticator app" : "Turn on with an app"}</Button>
|
||||||
|
<Button variant="secondary" onClick={() => start("email")}>{me.twoFactor ? "Use email codes" : "Turn on with email"}</Button>
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
{me.twoFactor && !setup && (
|
||||||
|
<PasswordAction label="New recovery codes" button="Make new codes" onSubmit={async (password) => {
|
||||||
|
const r = await call<{ recoveryCodes: string[] }>("POST", "/me/recovery-codes", { password });
|
||||||
|
if (r.ok) { setCodes(r.data.recoveryCodes); onDone("New recovery codes made; the old ones no longer work."); } else onFail(r.error.message);
|
||||||
|
}} />
|
||||||
|
)}
|
||||||
|
{me.twoFactor && !setup && me.role !== "admin" && (
|
||||||
|
<PasswordAction label="Turn off two-step sign-in" button="Turn off" danger onSubmit={async (password) => {
|
||||||
|
const r = await call("POST", "/me/two-factor/off", { password });
|
||||||
|
if (r.ok) onDone("Two-step sign-in is off."); else onFail(r.error.message);
|
||||||
|
}} />
|
||||||
|
)}
|
||||||
|
<div className="mt-4 border-t pt-4">
|
||||||
|
<form onSubmit={async (e) => {
|
||||||
|
e.preventDefault();
|
||||||
|
const f = new FormData(e.currentTarget);
|
||||||
|
const r = await call("POST", "/me/password", { current: f.get("current"), password: f.get("password") });
|
||||||
|
if (r.ok) { e.currentTarget.reset(); onDone("Your password is changed."); } else onFail(r.error.message);
|
||||||
|
}}>
|
||||||
|
<Field label="Current password" name="current" type="password" autoComplete="current-password" required />
|
||||||
|
<Field label="New password" name="password" type="password" autoComplete="new-password" minLength={8} required />
|
||||||
|
<Button type="submit" variant="secondary">Change password</Button>
|
||||||
|
</form>
|
||||||
|
</div>
|
||||||
|
</Card>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
function PasswordAction({ label, button, danger, onSubmit }: { label: string; button: string; danger?: boolean; onSubmit: (password: string) => void }) {
|
||||||
|
const [open, setOpen] = useState(false);
|
||||||
|
if (!open) return <p className="mb-2"><Button variant="link" className="text-sm" onClick={() => setOpen(true)}>{label}</Button></p>;
|
||||||
|
return (
|
||||||
|
<form className="mb-3 rounded-lg border p-3" onSubmit={(e) => { e.preventDefault(); onSubmit(String(new FormData(e.currentTarget).get("password"))); setOpen(false); }}>
|
||||||
|
<Field label="Your password" name="password" type="password" autoComplete="current-password" required />
|
||||||
|
<div className="flex gap-2"><Button type="submit" variant={danger ? "danger" : "primary"}>{button}</Button><Button type="button" variant="secondary" onClick={() => setOpen(false)}>Cancel</Button></div>
|
||||||
|
</form>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
function Privacy({ me, onDone, onFail }: Props) {
|
||||||
|
const [exports, setExports] = useState<Export[]>([]);
|
||||||
|
const [confirmDelete, setConfirmDelete] = useState(false);
|
||||||
|
const loadExports = useCallback(async () => {
|
||||||
|
const r = await call<{ items: Export[] }>("GET", "/me/exports");
|
||||||
|
if (r.ok) setExports(r.data.items);
|
||||||
|
}, []);
|
||||||
|
useExternalEffect(() => { void loadExports(); }, [loadExports]);
|
||||||
|
|
||||||
|
return (
|
||||||
|
<Card>
|
||||||
|
<Heading>Privacy</Heading>
|
||||||
|
<form onChange={async (e) => {
|
||||||
|
const f = new FormData(e.currentTarget);
|
||||||
|
const r = await call("PUT", "/me/news", { email: f.get("email") === "on", whatsapp: f.get("whatsapp") === "on" });
|
||||||
|
if (r.ok) onDone("Your news choices are saved."); else onFail(r.error.message);
|
||||||
|
}}>
|
||||||
|
<Checkbox name="email" label="Church news by email" defaultChecked={me.news.email} />
|
||||||
|
<Checkbox name="whatsapp" label="Church news on WhatsApp" defaultChecked={me.news.whatsapp} disabled={!me.phone} hint={!me.phone ? "Add your mobile number first." : undefined} />
|
||||||
|
</form>
|
||||||
|
<p className="mb-4 text-sm"><a href="/privacy" className="text-brand underline">Read the privacy notice</a></p>
|
||||||
|
|
||||||
|
<div className="border-t pt-4">
|
||||||
|
<p className="mb-2 text-sm font-medium">Download my data</p>
|
||||||
|
<p className="mb-3 text-sm text-gray-600">Everything the church's sites hold about you, in one file. It takes a few minutes; we'll email you when it's ready.</p>
|
||||||
|
{exports.map((x) => (
|
||||||
|
<p key={x.id} className="mb-2 text-sm">
|
||||||
|
{when(x.createdAt)}: {x.status === "ready" ? <a className="text-brand underline" href={`/api/v2/me/exports/${x.id}/download`}>Download</a> : x.status === "collecting" ? "being put together…" : "expired"}
|
||||||
|
</p>
|
||||||
|
))}
|
||||||
|
<Button variant="secondary" onClick={async () => {
|
||||||
|
const r = await call("POST", "/me/exports");
|
||||||
|
if (r.ok) { onDone("We're putting your data together. We'll email you when it's ready."); void loadExports(); } else onFail(r.error.message);
|
||||||
|
}}>Ask for a copy</Button>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div className="mt-4 border-t pt-4">
|
||||||
|
<p className="mb-2 text-sm font-medium">Delete my account</p>
|
||||||
|
{!confirmDelete ? (
|
||||||
|
<Button variant="link" className="text-sm text-red-700" onClick={() => setConfirmDelete(true)}>Delete my account…</Button>
|
||||||
|
) : (
|
||||||
|
<form onSubmit={async (e) => {
|
||||||
|
e.preventDefault();
|
||||||
|
const r = await call("POST", "/me/delete", { password: new FormData(e.currentTarget).get("password") });
|
||||||
|
// A full page load: the signed-out page has nothing of this session left.
|
||||||
|
// eslint-disable-next-line @next/next/no-location-assign-relative-destination
|
||||||
|
if (r.ok) window.location.assign("/signed-out"); else onFail(r.error.message);
|
||||||
|
}}>
|
||||||
|
<Notice tone="warning">You'll be signed out of all the church's sites straight away. An admin then confirms the deletion, and each site removes what it holds about you (a site may wait until an event you're booked for is over).</Notice>
|
||||||
|
<Field label="Your password" name="password" type="password" autoComplete="current-password" required />
|
||||||
|
<div className="flex gap-2"><Button type="submit" variant="danger">Delete my account</Button><Button type="button" variant="secondary" onClick={() => setConfirmDelete(false)}>Cancel</Button></div>
|
||||||
|
</form>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
</Card>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
function Activity({ onDone }: { onDone: (t: string) => void }) {
|
||||||
|
const [items, setItems] = useState<SignIn[]>([]);
|
||||||
|
useExternalEffect(() => {
|
||||||
|
let alive = true;
|
||||||
|
call<{ items: SignIn[] }>("GET", "/me/sign-ins").then((r) => { if (alive && r.ok) setItems(r.data.items); });
|
||||||
|
return () => { alive = false; };
|
||||||
|
}, []);
|
||||||
|
return (
|
||||||
|
<Card>
|
||||||
|
<Heading sub="If you see something you don't recognise, change your password and sign out everywhere.">Recent activity</Heading>
|
||||||
|
<ul className="mb-4 max-h-72 space-y-2 overflow-y-auto text-sm">
|
||||||
|
{items.map((e, i) => (
|
||||||
|
<li key={i} className="flex justify-between gap-3 border-b pb-2 last:border-0">
|
||||||
|
<span>{EVENT[e.type] ?? e.type}{e.site ? <span className="text-gray-500"> · {e.site.replace(/^https?:\/\//, "")}</span> : null}</span>
|
||||||
|
<span className="shrink-0 text-gray-500">{when(e.at)}</span>
|
||||||
|
</li>
|
||||||
|
))}
|
||||||
|
{!items.length && <li className="text-gray-500">Nothing yet.</li>}
|
||||||
|
</ul>
|
||||||
|
<Button variant="secondary" onClick={async () => {
|
||||||
|
const r = await call("POST", "/me/sign-out-everywhere");
|
||||||
|
// eslint-disable-next-line @next/next/no-location-assign-relative-destination
|
||||||
|
if (r.ok) { onDone("You're signed out everywhere."); window.location.assign("/signed-out"); }
|
||||||
|
}}>Sign out everywhere</Button>
|
||||||
|
</Card>
|
||||||
|
);
|
||||||
|
}
|
||||||
@@ -0,0 +1,30 @@
|
|||||||
|
"use client";
|
||||||
|
|
||||||
|
import { useState } from "react";
|
||||||
|
import { Card, Heading, Notice, Shell } from "@crosscode/ui";
|
||||||
|
import { useBranding } from "@/components/BrandingProvider";
|
||||||
|
import { call, selfSignIn } from "@/lib/api";
|
||||||
|
import { useExternalEffect } from "@/lib/hooks";
|
||||||
|
|
||||||
|
export function ConfirmEmail({ token }: { token: string }) {
|
||||||
|
const branding = useBranding();
|
||||||
|
const [state, setState] = useState<{ ok: boolean; text: string } | null>(null);
|
||||||
|
useExternalEffect(() => {
|
||||||
|
let alive = true;
|
||||||
|
call("POST", "/me/email/confirm", { token }).then((r) => {
|
||||||
|
if (!alive) return;
|
||||||
|
if (r.status === 401) return window.location.assign(selfSignIn(`/account/confirm-email?token=${encodeURIComponent(token)}`));
|
||||||
|
setState(r.ok ? { ok: true, text: "Your new email address is confirmed. Sign in with it from now on." } : { ok: false, text: r.error.message });
|
||||||
|
});
|
||||||
|
return () => { alive = false; };
|
||||||
|
}, [token]);
|
||||||
|
return (
|
||||||
|
<Shell branding={branding}>
|
||||||
|
<Card>
|
||||||
|
<Heading>Your email address</Heading>
|
||||||
|
{state ? <Notice tone={state.ok ? "success" : "error"}>{state.text}</Notice> : <p className="text-gray-600">Confirming…</p>}
|
||||||
|
<a href="/account" className="text-brand underline">Back to your account</a>
|
||||||
|
</Card>
|
||||||
|
</Shell>
|
||||||
|
);
|
||||||
|
}
|
||||||
@@ -0,0 +1,8 @@
|
|||||||
|
import { ConfirmEmail } from "./ConfirmEmail";
|
||||||
|
|
||||||
|
export const metadata = { title: "Confirm your email address" };
|
||||||
|
|
||||||
|
export default async function Page({ searchParams }: { searchParams: Promise<{ token?: string }> }) {
|
||||||
|
const { token } = await searchParams;
|
||||||
|
return <ConfirmEmail token={token ?? ""} />;
|
||||||
|
}
|
||||||
@@ -0,0 +1,7 @@
|
|||||||
|
import { Account } from "./Account";
|
||||||
|
|
||||||
|
export const metadata = { title: "Your account" };
|
||||||
|
|
||||||
|
export default function AccountPage() {
|
||||||
|
return <Account />;
|
||||||
|
}
|
||||||
@@ -0,0 +1,369 @@
|
|||||||
|
"use client";
|
||||||
|
|
||||||
|
import React, { useCallback, useState } from "react";
|
||||||
|
import { Button, Card, Checkbox, Field, Heading, Notice, Shell } from "@crosscode/ui";
|
||||||
|
import { useBranding } from "@/components/BrandingProvider";
|
||||||
|
import { call, selfSignIn } from "@/lib/api";
|
||||||
|
import { useExternalEffect } from "@/lib/hooks";
|
||||||
|
|
||||||
|
const TABS = [
|
||||||
|
["people", "People"], ["deletions", "Deletion requests"], ["church", "Church profile"], ["linked", "Linked products"],
|
||||||
|
["signin", "Sign-in settings"], ["messages", "Email and WhatsApp"], ["notice", "Privacy notice"], ["licence", "Licence"], ["audit", "Audit log"],
|
||||||
|
] as const;
|
||||||
|
type Tab = (typeof TABS)[number][0];
|
||||||
|
|
||||||
|
const when = (iso: string | null | undefined) => (iso ? new Date(iso).toLocaleString("en-ZA", { day: "numeric", month: "short", year: "numeric", hour: "2-digit", minute: "2-digit" }) : "—");
|
||||||
|
|
||||||
|
type Flash = (tone: "success" | "error", text: string) => void;
|
||||||
|
|
||||||
|
/** Accounts' admin (docs/ACCOUNTS-1.0-PLAN.md §8). Admins only, signed in with their second step. */
|
||||||
|
export function Admin() {
|
||||||
|
const branding = useBranding();
|
||||||
|
const [tab, setTab] = useState<Tab>("people");
|
||||||
|
const [allowed, setAllowed] = useState<boolean | null>(null);
|
||||||
|
const [msg, setMsg] = useState<{ tone: "success" | "error"; text: string } | null>(null);
|
||||||
|
|
||||||
|
useExternalEffect(() => {
|
||||||
|
let alive = true;
|
||||||
|
call("GET", "/admin/licence").then((r) => {
|
||||||
|
if (!alive) return;
|
||||||
|
if (r.status === 401) return window.location.assign(selfSignIn("/admin"));
|
||||||
|
if (!r.ok && r.error.code === "MFA_REQUIRED") return window.location.assign(selfSignIn("/admin", "&acr=mfa"));
|
||||||
|
setAllowed(r.ok);
|
||||||
|
});
|
||||||
|
return () => { alive = false; };
|
||||||
|
}, []);
|
||||||
|
|
||||||
|
const flash: Flash = (tone, text) => setMsg({ tone, text });
|
||||||
|
if (allowed === null) return <Shell branding={branding} wide><p className="text-gray-600">Loading…</p></Shell>;
|
||||||
|
if (!allowed) return <Shell branding={branding}><Card><Notice tone="error">Only Accounts admins can open this page.</Notice><a href="/account" className="text-brand underline">Your account</a></Card></Shell>;
|
||||||
|
|
||||||
|
return (
|
||||||
|
<Shell branding={branding} wide aside={<a href="/account" className="text-sm text-brand underline">Your account</a>}>
|
||||||
|
<h1 className="mb-4 text-2xl font-semibold">Accounts admin</h1>
|
||||||
|
<nav className="mb-6 flex flex-wrap gap-2" aria-label="Admin sections">
|
||||||
|
{TABS.map(([id, label]) => (
|
||||||
|
<button key={id} type="button" onClick={() => { setTab(id); setMsg(null); }} aria-current={tab === id ? "page" : undefined}
|
||||||
|
className={`rounded-full px-3 py-1.5 text-sm ${tab === id ? "bg-brand text-white" : "border bg-white text-gray-700"}`}>{label}</button>
|
||||||
|
))}
|
||||||
|
</nav>
|
||||||
|
{msg && <Notice tone={msg.tone}>{msg.text}</Notice>}
|
||||||
|
{tab === "people" && <People flash={flash} />}
|
||||||
|
{tab === "deletions" && <Deletions flash={flash} />}
|
||||||
|
{tab === "church" && <Church flash={flash} />}
|
||||||
|
{tab === "linked" && <Linked flash={flash} />}
|
||||||
|
{tab === "signin" && <Settings flash={flash} keys={["signup_enabled", "two_factor_required_for_admins", "session_days"]} />}
|
||||||
|
{tab === "messages" && <Settings flash={flash} keys={["smtp_host", "smtp_port", "smtp_user", "smtp_pass", "smtp_from", "smtp_secure", "wawp_access_token", "wawp_instance_id"]} />}
|
||||||
|
{tab === "notice" && <NoticeTab flash={flash} />}
|
||||||
|
{tab === "licence" && <Licence flash={flash} />}
|
||||||
|
{tab === "audit" && <Audit />}
|
||||||
|
</Shell>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
// ─── People ──────────────────────────────────────────────────────────────────
|
||||||
|
|
||||||
|
type Person = { id: string; name: string; email: string; role: string; status: string; twoFactor: string | null; lastSignInAt: string | null };
|
||||||
|
type PersonDetail = Person & { phone: string | null; emailVerified: boolean; recoveryCodesLeft: number; createdAt: string; lockedUntil: string | null; signIns: { type: string; at: string; ip: string | null }[] };
|
||||||
|
|
||||||
|
function People({ flash }: { flash: Flash }) {
|
||||||
|
const [q, setQ] = useState("");
|
||||||
|
const [list, setList] = useState<{ items: Person[]; total: number } | null>(null);
|
||||||
|
const [open, setOpen] = useState<PersonDetail | null>(null);
|
||||||
|
const search = useCallback(async (query: string) => {
|
||||||
|
const r = await call<{ items: Person[]; total: number }>("GET", `/admin/people?q=${encodeURIComponent(query)}`);
|
||||||
|
if (r.ok) setList(r.data);
|
||||||
|
}, []);
|
||||||
|
useExternalEffect(() => { void search(""); }, [search]);
|
||||||
|
const show = async (id: string) => {
|
||||||
|
const r = await call<PersonDetail>("GET", `/admin/people/${id}`);
|
||||||
|
if (r.ok) setOpen(r.data);
|
||||||
|
};
|
||||||
|
const act = async (path: string, body: unknown, ok: string) => {
|
||||||
|
const r = await call(path.endsWith("/role") || path.endsWith("/status") ? "PUT" : "POST", path, body);
|
||||||
|
if (r.ok) { flash("success", ok); if (open) void show(open.id); void search(q); } else flash("error", r.error.message);
|
||||||
|
};
|
||||||
|
|
||||||
|
return (
|
||||||
|
<div className="grid gap-6 md:grid-cols-2">
|
||||||
|
<Card>
|
||||||
|
<form onSubmit={(e) => { e.preventDefault(); void search(q); }} className="mb-4 flex gap-2">
|
||||||
|
<input aria-label="Search people" value={q} onChange={(e) => setQ(e.target.value)} placeholder="Name or email" className="flex-1 rounded-lg border px-3 py-2" />
|
||||||
|
<Button type="submit" variant="secondary">Search</Button>
|
||||||
|
</form>
|
||||||
|
<p className="mb-2 text-sm text-gray-500">{list?.total ?? 0} people</p>
|
||||||
|
<ul className="divide-y">
|
||||||
|
{list?.items.map((p) => (
|
||||||
|
<li key={p.id}>
|
||||||
|
<button type="button" onClick={() => show(p.id)} className="w-full py-2 text-left hover:bg-gray-50">
|
||||||
|
<span className="block font-medium">{p.name}{p.role === "admin" && <span className="ml-2 rounded bg-brand/10 px-1.5 text-xs text-brand">admin</span>}{p.status !== "active" && <span className="ml-2 text-xs text-amber-700">{p.status}</span>}</span>
|
||||||
|
<span className="block text-sm text-gray-500">{p.email}</span>
|
||||||
|
</button>
|
||||||
|
</li>
|
||||||
|
))}
|
||||||
|
</ul>
|
||||||
|
</Card>
|
||||||
|
{open && (
|
||||||
|
<Card>
|
||||||
|
<Heading sub={open.email}>{open.name}</Heading>
|
||||||
|
<dl className="mb-4 grid grid-cols-2 gap-y-1 text-sm">
|
||||||
|
<dt className="text-gray-500">Phone</dt><dd>{open.phone ?? "—"}</dd>
|
||||||
|
<dt className="text-gray-500">Email confirmed</dt><dd>{open.emailVerified ? "yes" : "no"}</dd>
|
||||||
|
<dt className="text-gray-500">Two-step sign-in</dt><dd>{open.twoFactor ?? "off"}{open.twoFactor ? ` (${open.recoveryCodesLeft} codes left)` : ""}</dd>
|
||||||
|
<dt className="text-gray-500">Account since</dt><dd>{when(open.createdAt)}</dd>
|
||||||
|
<dt className="text-gray-500">Locked until</dt><dd>{when(open.lockedUntil)}</dd>
|
||||||
|
</dl>
|
||||||
|
<div className="mb-4 flex flex-wrap gap-2">
|
||||||
|
{open.twoFactor && <Button variant="secondary" onClick={() => act(`/admin/people/${open.id}/reset-two-factor`, {}, "Two-step sign-in reset. They'll set it up again when they next sign in, if they need it.")}>Reset two-step sign-in</Button>}
|
||||||
|
{open.lockedUntil && <Button variant="secondary" onClick={() => act(`/admin/people/${open.id}/unlock`, {}, "Unlocked.")}>Unlock</Button>}
|
||||||
|
<Button variant="secondary" onClick={() => act(`/admin/people/${open.id}/role`, { role: open.role === "admin" ? "member" : "admin" }, "Role changed.")}>{open.role === "admin" ? "Remove admin" : "Make Accounts admin"}</Button>
|
||||||
|
<Button variant={open.status === "active" ? "danger" : "secondary"} onClick={() => act(`/admin/people/${open.id}/status`, { active: open.status !== "active" }, open.status === "active" ? "Deactivated and signed out everywhere." : "Reactivated.")}>{open.status === "active" ? "Deactivate" : "Reactivate"}</Button>
|
||||||
|
</div>
|
||||||
|
<p className="mb-1 text-xs text-gray-500">Roles in each product (an Events supervisor, for example) are set in that product, not here.</p>
|
||||||
|
<p className="mb-2 mt-4 text-sm font-medium">Recent sign-ins</p>
|
||||||
|
<ul className="space-y-1 text-sm text-gray-700">{open.signIns.map((s, i) => <li key={i}>{s.type} · {when(s.at)} {s.ip && <span className="text-gray-400">· {s.ip}</span>}</li>)}</ul>
|
||||||
|
</Card>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
// ─── Deletions ───────────────────────────────────────────────────────────────
|
||||||
|
|
||||||
|
type Deletion = { id: string; status: string; requestedAt: string; products: Record<string, { status: string; product?: string; reason?: string; retryAfter?: string }>; person: { name: string; email: string } };
|
||||||
|
|
||||||
|
function Deletions({ flash }: { flash: Flash }) {
|
||||||
|
const [items, setItems] = useState<Deletion[]>([]);
|
||||||
|
const load = useCallback(async () => {
|
||||||
|
const r = await call<{ items: Deletion[] }>("GET", "/admin/deletions");
|
||||||
|
if (r.ok) setItems(r.data.items);
|
||||||
|
}, []);
|
||||||
|
useExternalEffect(() => { void load(); }, [load]);
|
||||||
|
return (
|
||||||
|
<Card>
|
||||||
|
<Heading sub="People who asked to delete their account. They're signed out and can't sign in while this is open.">Deletion requests</Heading>
|
||||||
|
{!items.length && <p className="text-sm text-gray-500">None waiting.</p>}
|
||||||
|
<ul className="divide-y">
|
||||||
|
{items.map((d) => (
|
||||||
|
<li key={d.id} className="py-3">
|
||||||
|
<p className="font-medium">{d.person.name} <span className="text-sm font-normal text-gray-500">{d.person.email} · asked {when(d.requestedAt)}</span></p>
|
||||||
|
{d.status === "waiting_approval" ? (
|
||||||
|
<div className="mt-2 flex gap-2">
|
||||||
|
<Button variant="danger" onClick={async () => { const r = await call("POST", `/admin/deletions/${d.id}/approve`); if (r.ok) { flash("success", "Approved: each site is deleting what it holds."); void load(); } else flash("error", r.error.message); }}>Approve</Button>
|
||||||
|
<Button variant="secondary" onClick={async () => { const r = await call("POST", `/admin/deletions/${d.id}/cancel`); if (r.ok) { flash("success", "Cancelled; the account works again."); void load(); } else flash("error", r.error.message); }}>Cancel</Button>
|
||||||
|
</div>
|
||||||
|
) : (
|
||||||
|
<ul className="mt-2 text-sm text-gray-700">
|
||||||
|
{Object.entries(d.products).map(([id, s]) => <li key={id}>{s.product ?? id}: {s.status === "deferred" ? `waiting — ${s.reason} (asking again ${when(s.retryAfter)})` : s.status}</li>)}
|
||||||
|
</ul>
|
||||||
|
)}
|
||||||
|
</li>
|
||||||
|
))}
|
||||||
|
</ul>
|
||||||
|
</Card>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
// ─── Church profile ──────────────────────────────────────────────────────────
|
||||||
|
|
||||||
|
type ChurchData = { name: string; shortName: string | null; branding: { logoUrl: string | null; colours: { primary: string; accent: string | null } }; contact: { email: string | null; phone: string | null; whatsapp: string | null } };
|
||||||
|
|
||||||
|
function Church({ flash }: { flash: Flash }) {
|
||||||
|
const [c, setC] = useState<ChurchData | null>(null);
|
||||||
|
const [fields, setFields] = useState<Record<string, string>>({});
|
||||||
|
useExternalEffect(() => {
|
||||||
|
let alive = true;
|
||||||
|
call<ChurchData>("GET", "/admin/church").then((r) => { if (alive && r.ok) setC(r.data); });
|
||||||
|
return () => { alive = false; };
|
||||||
|
}, []);
|
||||||
|
if (!c) return <p className="text-gray-600">Loading…</p>;
|
||||||
|
const nul = (v: FormDataEntryValue | null) => (v ? String(v) : null);
|
||||||
|
return (
|
||||||
|
<Card>
|
||||||
|
<Heading sub="Shared with all the church's products: the sign-in pages, the website and the app use it.">Church profile</Heading>
|
||||||
|
<form onSubmit={async (e) => {
|
||||||
|
e.preventDefault();
|
||||||
|
const f = new FormData(e.currentTarget);
|
||||||
|
const r = await call<ChurchData>("PUT", "/admin/church", {
|
||||||
|
name: f.get("name"), shortName: nul(f.get("shortName")),
|
||||||
|
branding: { ...c.branding, logoUrl: nul(f.get("logoUrl")), colours: { primary: f.get("primary"), accent: nul(f.get("accent")) } },
|
||||||
|
contact: { ...c.contact, email: nul(f.get("email")), phone: nul(f.get("phone")), whatsapp: nul(f.get("whatsapp")) },
|
||||||
|
});
|
||||||
|
if (r.ok) { setC(r.data); setFields({}); flash("success", "Saved. The church's products are told about the change."); } else { setFields(r.error.fields ?? {}); flash("error", r.error.message); }
|
||||||
|
}}>
|
||||||
|
<Field label="Name" name="name" defaultValue={c.name} required error={fields.name} />
|
||||||
|
<Field label="Short name" name="shortName" defaultValue={c.shortName ?? ""} maxLength={30} hint="For small spaces, like the authenticator app's label." error={fields.shortName} />
|
||||||
|
<Field label="Logo address (https://…)" name="logoUrl" type="url" defaultValue={c.branding.logoUrl ?? ""} error={fields["branding.logoUrl"]} />
|
||||||
|
<div className="grid grid-cols-2 gap-4">
|
||||||
|
<Field label="Main colour" name="primary" type="color" defaultValue={c.branding.colours.primary} />
|
||||||
|
<Field label="Accent colour" name="accent" type="color" defaultValue={c.branding.colours.accent ?? "#f2a900"} />
|
||||||
|
</div>
|
||||||
|
<Field label="Office email" name="email" type="email" defaultValue={c.contact.email ?? ""} error={fields["contact.email"]} />
|
||||||
|
<Field label="Office phone" name="phone" defaultValue={c.contact.phone ?? ""} hint="With the country code, e.g. +27161234567." error={fields["contact.phone"]} />
|
||||||
|
<Field label="WhatsApp" name="whatsapp" defaultValue={c.contact.whatsapp ?? ""} error={fields["contact.whatsapp"]} />
|
||||||
|
<Button type="submit">Save</Button>
|
||||||
|
</form>
|
||||||
|
</Card>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
// ─── Linked products ─────────────────────────────────────────────────────────
|
||||||
|
|
||||||
|
type LinkedItem = { installId: string; product: string; name: string; url: string; listed: boolean; connectedAt: string | null; signsInHere: boolean };
|
||||||
|
|
||||||
|
function Linked({ flash }: { flash: Flash }) {
|
||||||
|
const [data, setData] = useState<{ hubConnected: boolean; items: LinkedItem[] } | null>(null);
|
||||||
|
const load = useCallback(async () => {
|
||||||
|
const r = await call<{ hubConnected: boolean; items: LinkedItem[] }>("GET", "/admin/linked-products");
|
||||||
|
if (r.ok) setData(r.data);
|
||||||
|
}, []);
|
||||||
|
useExternalEffect(() => { void load(); }, [load]);
|
||||||
|
if (!data) return <p className="text-gray-600">Loading…</p>;
|
||||||
|
return (
|
||||||
|
<Card>
|
||||||
|
<Heading sub="Connected products sign people in here. Usually each product connects from its own settings; you can connect from here too.">Linked products</Heading>
|
||||||
|
{!data.hubConnected && <Notice tone="warning">Accounts isn't connected to the Hub yet (Licence).</Notice>}
|
||||||
|
{!data.items.length && <p className="text-sm text-gray-500">The church has no other Cross Code products yet.</p>}
|
||||||
|
<ul className="divide-y">
|
||||||
|
{data.items.map((l) => (
|
||||||
|
<li key={l.installId} className="flex flex-wrap items-center justify-between gap-2 py-3">
|
||||||
|
<span><span className="font-medium">{l.name}</span> <span className="text-sm text-gray-500">{l.url.replace(/^https?:\/\//, "")}</span><br />
|
||||||
|
<span className="text-sm text-gray-600">{l.signsInHere ? `Connected ${when(l.connectedAt)}` : "Not connected"}{!l.listed && " · no longer listed by the Hub"}</span></span>
|
||||||
|
{l.signsInHere
|
||||||
|
? <Button variant="secondary" onClick={async () => { if (!window.confirm(`Disconnect ${l.name}? People won't be able to sign in to it until it's connected again.`)) return; const r = await call("POST", `/admin/linked-products/${l.installId}/disconnect`); if (r.ok) { flash("success", "Disconnected."); void load(); } else flash("error", r.error.message); }}>Disconnect</Button>
|
||||||
|
: <Button disabled={!l.listed} onClick={async () => { const r = await call("POST", `/admin/linked-products/${l.installId}/connect`); if (r.ok) { flash("success", `Connected: ${l.name} signs people in here now.`); void load(); } else flash("error", r.error.message); }}>Connect</Button>}
|
||||||
|
</li>
|
||||||
|
))}
|
||||||
|
</ul>
|
||||||
|
</Card>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
// ─── Settings ────────────────────────────────────────────────────────────────
|
||||||
|
|
||||||
|
const SETTING_LABELS: Record<string, [string, "bool" | "text" | "secret" | "number"]> = {
|
||||||
|
signup_enabled: ["Members can create their own account", "bool"],
|
||||||
|
two_factor_required_for_admins: ["Admins must use two-step sign-in", "bool"],
|
||||||
|
session_days: ['Days "Keep me signed in" lasts', "number"],
|
||||||
|
smtp_host: ["SMTP server", "text"], smtp_port: ["SMTP port", "number"], smtp_user: ["SMTP user name", "text"], smtp_pass: ["SMTP password", "secret"],
|
||||||
|
smtp_from: ["Send from (email address)", "text"], smtp_secure: ["Use TLS from the start (port 465)", "bool"],
|
||||||
|
wawp_access_token: ["WAWP access token", "secret"], wawp_instance_id: ["WAWP instance id", "text"],
|
||||||
|
};
|
||||||
|
|
||||||
|
function Settings({ flash, keys }: { flash: Flash; keys: string[] }) {
|
||||||
|
const [values, setValues] = useState<Record<string, string | boolean | null> | null>(null);
|
||||||
|
useExternalEffect(() => {
|
||||||
|
let alive = true;
|
||||||
|
call<Record<string, string | boolean | null>>("GET", "/admin/settings").then((r) => { if (alive && r.ok) setValues(r.data); });
|
||||||
|
return () => { alive = false; };
|
||||||
|
}, []);
|
||||||
|
if (!values) return <p className="text-gray-600">Loading…</p>;
|
||||||
|
const defaults: Record<string, boolean> = { signup_enabled: true, two_factor_required_for_admins: true };
|
||||||
|
return (
|
||||||
|
<Card>
|
||||||
|
<form onSubmit={async (e) => {
|
||||||
|
e.preventDefault();
|
||||||
|
const f = new FormData(e.currentTarget);
|
||||||
|
const body: Record<string, string> = {};
|
||||||
|
for (const k of keys) {
|
||||||
|
const kind = SETTING_LABELS[k]![1];
|
||||||
|
if (kind === "bool") body[k] = f.get(k) === "on" ? "true" : "false";
|
||||||
|
else body[k] = String(f.get(k) ?? "");
|
||||||
|
}
|
||||||
|
const r = await call("PUT", "/admin/settings", body);
|
||||||
|
if (r.ok) flash("success", "Saved."); else flash("error", r.error.message);
|
||||||
|
}}>
|
||||||
|
{keys.map((k) => {
|
||||||
|
const [label, kind] = SETTING_LABELS[k]!;
|
||||||
|
const v = values[k];
|
||||||
|
if (kind === "bool") return <Checkbox key={k} name={k} label={label} defaultChecked={v === null ? defaults[k] ?? false : v === "true"} />;
|
||||||
|
if (kind === "secret") return <Field key={k} name={k} label={label} type="password" autoComplete="off" placeholder={v ? "Saved — leave empty to keep it" : ""} />;
|
||||||
|
return <Field key={k} name={k} label={label} type={kind === "number" ? "number" : "text"} defaultValue={typeof v === "string" ? v : ""} />;
|
||||||
|
})}
|
||||||
|
<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>}
|
||||||
|
</div>
|
||||||
|
</form>
|
||||||
|
</Card>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
// ─── Privacy notice, licence, audit ───────────────────────────────────────────
|
||||||
|
|
||||||
|
function NoticeTab({ flash }: { flash: Flash }) {
|
||||||
|
const [current, setCurrent] = useState<{ version: number; title: string; body: string } | null>(null);
|
||||||
|
const load = useCallback(async () => {
|
||||||
|
const r = await call<{ current: { version: number; title: string; body: string } }>("GET", "/admin/notices");
|
||||||
|
if (r.ok) setCurrent(r.data.current);
|
||||||
|
}, []);
|
||||||
|
useExternalEffect(() => { void load(); }, [load]);
|
||||||
|
if (!current) return <p className="text-gray-600">Loading…</p>;
|
||||||
|
return (
|
||||||
|
<Card>
|
||||||
|
<Heading sub={`Version ${current.version}. Publishing a new version asks everyone to read it the next time they sign in.`}>Privacy notice</Heading>
|
||||||
|
<form onSubmit={async (e) => {
|
||||||
|
e.preventDefault();
|
||||||
|
if (!window.confirm("Publish this as a new version? Everyone will be asked to read it when they next sign in.")) return;
|
||||||
|
const f = new FormData(e.currentTarget);
|
||||||
|
const r = await call("POST", "/admin/notices", { title: f.get("title"), body: f.get("body") });
|
||||||
|
if (r.ok) { flash("success", "Published."); void load(); } else flash("error", r.error.message);
|
||||||
|
}}>
|
||||||
|
<Field label="Title" name="title" defaultValue={current.title} required />
|
||||||
|
<label htmlFor="notice-body" className="mb-1 block text-sm font-medium">Text</label>
|
||||||
|
<textarea id="notice-body" name="body" defaultValue={current.body} rows={14} className="mb-4 w-full rounded-lg border p-3 text-sm" required />
|
||||||
|
<Button type="submit">Publish a new version</Button>
|
||||||
|
</form>
|
||||||
|
</Card>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
function Licence({ flash }: { flash: Flash }) {
|
||||||
|
const [s, setS] = useState<{ connected: boolean; state: string; customer: string | null; endsAt: string | null; lastHeartbeatAt: string | null; lastError: string | null } | null>(null);
|
||||||
|
const load = useCallback(async () => {
|
||||||
|
const r = await call<NonNullable<typeof s>>("GET", "/admin/licence");
|
||||||
|
if (r.ok) setS(r.data);
|
||||||
|
}, []);
|
||||||
|
useExternalEffect(() => { void load(); }, [load]);
|
||||||
|
if (!s) return <p className="text-gray-600">Loading…</p>;
|
||||||
|
return (
|
||||||
|
<Card>
|
||||||
|
<Heading sub="Accounts is free with the church's other products. Members can always sign in, whatever the licence says.">Licence</Heading>
|
||||||
|
<dl className="mb-4 grid grid-cols-2 gap-y-1 text-sm">
|
||||||
|
<dt className="text-gray-500">Connected to the Hub</dt><dd>{s.connected ? "yes" : "no"}</dd>
|
||||||
|
<dt className="text-gray-500">Licence</dt><dd>{s.state}</dd>
|
||||||
|
<dt className="text-gray-500">Customer</dt><dd>{s.customer ?? "—"}</dd>
|
||||||
|
<dt className="text-gray-500">Last heartbeat</dt><dd>{when(s.lastHeartbeatAt)}</dd>
|
||||||
|
</dl>
|
||||||
|
{s.lastError && <Notice tone="warning">{s.lastError}</Notice>}
|
||||||
|
{!s.connected && (
|
||||||
|
<form onSubmit={async (e) => {
|
||||||
|
e.preventDefault();
|
||||||
|
const r = await call("POST", "/admin/licence", { licenceKey: new FormData(e.currentTarget).get("licenceKey") });
|
||||||
|
if (r.ok) { flash("success", "Connected to the Hub."); void load(); } else flash("error", r.error.message);
|
||||||
|
}}>
|
||||||
|
<Field label="Licence key" name="licenceKey" placeholder="CCA-XXXX-XXXX-XXXX-XXXX" required />
|
||||||
|
<Button type="submit">Connect</Button>
|
||||||
|
</form>
|
||||||
|
)}
|
||||||
|
</Card>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
function Audit() {
|
||||||
|
const [items, setItems] = useState<{ id: string; action: string; actorRole: string; targetType: string; targetId: string | null; createdAt: string }[]>([]);
|
||||||
|
useExternalEffect(() => {
|
||||||
|
let alive = true;
|
||||||
|
call<{ items: typeof items }>("GET", "/admin/audit").then((r) => { if (alive && r.ok) setItems(r.data.items); });
|
||||||
|
return () => { alive = false; };
|
||||||
|
}, []);
|
||||||
|
return (
|
||||||
|
<Card>
|
||||||
|
<Heading>Audit log</Heading>
|
||||||
|
<ul className="divide-y text-sm">
|
||||||
|
{items.map((a) => <li key={a.id} className="flex justify-between gap-3 py-2"><span>{a.action.replace(/_/g, " ")} <span className="text-gray-500">({a.actorRole}{a.targetId ? ` · ${a.targetType}` : ""})</span></span><span className="shrink-0 text-gray-500">{when(a.createdAt)}</span></li>)}
|
||||||
|
{!items.length && <li className="py-2 text-gray-500">Nothing yet.</li>}
|
||||||
|
</ul>
|
||||||
|
</Card>
|
||||||
|
);
|
||||||
|
}
|
||||||
@@ -0,0 +1,7 @@
|
|||||||
|
import { Admin } from "./Admin";
|
||||||
|
|
||||||
|
export const metadata = { title: "Admin" };
|
||||||
|
|
||||||
|
export default function AdminPage() {
|
||||||
|
return <Admin />;
|
||||||
|
}
|
||||||
@@ -0,0 +1,36 @@
|
|||||||
|
"use client";
|
||||||
|
|
||||||
|
import React, { useState } from "react";
|
||||||
|
import { Button, Card, Field, Heading, Notice, Shell } from "@crosscode/ui";
|
||||||
|
import { useBranding } from "@/components/BrandingProvider";
|
||||||
|
import { call } from "@/lib/api";
|
||||||
|
|
||||||
|
export function Forgot({ uid }: { uid: string | null }) {
|
||||||
|
const branding = useBranding();
|
||||||
|
const [sent, setSent] = useState(false);
|
||||||
|
const [busy, setBusy] = useState(false);
|
||||||
|
const [error, setError] = useState<string | null>(null);
|
||||||
|
return (
|
||||||
|
<Shell branding={branding}>
|
||||||
|
<Card>
|
||||||
|
<Heading 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>
|
||||||
|
) : (
|
||||||
|
<form onSubmit={async (e) => {
|
||||||
|
e.preventDefault();
|
||||||
|
setBusy(true);
|
||||||
|
const r = await call("POST", "/password/forgot", { email: new FormData(e.currentTarget).get("email"), uid: uid ?? undefined });
|
||||||
|
setBusy(false);
|
||||||
|
if (r.ok) setSent(true); else setError(r.error.message);
|
||||||
|
}}>
|
||||||
|
{error && <Notice tone="error">{error}</Notice>}
|
||||||
|
<Field label="Email address" name="email" type="email" autoComplete="email" required autoFocus />
|
||||||
|
<Button type="submit" busy={busy} className="w-full">Send the link</Button>
|
||||||
|
</form>
|
||||||
|
)}
|
||||||
|
{uid && <p className="mt-4 text-sm"><a href={`/signin?uid=${encodeURIComponent(uid)}`} className="text-brand underline">Back to sign in</a></p>}
|
||||||
|
</Card>
|
||||||
|
</Shell>
|
||||||
|
);
|
||||||
|
}
|
||||||
@@ -0,0 +1,8 @@
|
|||||||
|
import { Forgot } from "./Forgot";
|
||||||
|
|
||||||
|
export const metadata = { title: "Forgot your password" };
|
||||||
|
|
||||||
|
export default async function Page({ searchParams }: { searchParams: Promise<{ uid?: string }> }) {
|
||||||
|
const { uid } = await searchParams;
|
||||||
|
return <Forgot uid={uid ?? null} />;
|
||||||
|
}
|
||||||
@@ -0,0 +1,13 @@
|
|||||||
|
@tailwind base;
|
||||||
|
@tailwind components;
|
||||||
|
@tailwind utilities;
|
||||||
|
|
||||||
|
/* Defaults until the church profile's colour is set (layout.tsx overrides them per request). */
|
||||||
|
:root {
|
||||||
|
--brand: 31 78 121;
|
||||||
|
--brand-dark: 21 55 85;
|
||||||
|
}
|
||||||
|
|
||||||
|
body {
|
||||||
|
@apply bg-gray-50 text-gray-900 antialiased;
|
||||||
|
}
|
||||||
@@ -0,0 +1,29 @@
|
|||||||
|
import type { Metadata } from "next";
|
||||||
|
import { headers } from "next/headers";
|
||||||
|
import "./globals.css";
|
||||||
|
import { BrandingProvider } from "@/components/BrandingProvider";
|
||||||
|
import { loadBranding, rgbVars } from "@/lib/branding";
|
||||||
|
|
||||||
|
export async function generateMetadata(): Promise<Metadata> {
|
||||||
|
const b = await loadBranding();
|
||||||
|
// Sign-in pages never belong in search results (ROADMAP-v3 §11).
|
||||||
|
return { title: { default: `Sign in · ${b.name}`, template: `%s · ${b.name}` }, robots: { index: false, follow: false } };
|
||||||
|
}
|
||||||
|
|
||||||
|
export default async function RootLayout({ children }: { children: React.ReactNode }) {
|
||||||
|
const nonce = (await headers()).get("x-nonce") ?? undefined;
|
||||||
|
const b = await loadBranding();
|
||||||
|
const vars = rgbVars(b.colours.primary);
|
||||||
|
return (
|
||||||
|
<html lang="en-ZA">
|
||||||
|
<head>
|
||||||
|
<style nonce={nonce}>{`:root{--brand:${vars.brand};--brand-dark:${vars.dark}}`}</style>
|
||||||
|
</head>
|
||||||
|
<body>
|
||||||
|
<BrandingProvider value={{ name: b.name, shortName: b.shortName, logoUrl: b.logoUrl, signupEnabled: b.signupEnabled, setupNeeded: b.setupNeeded }}>
|
||||||
|
{children}
|
||||||
|
</BrandingProvider>
|
||||||
|
</body>
|
||||||
|
</html>
|
||||||
|
);
|
||||||
|
}
|
||||||
@@ -0,0 +1,6 @@
|
|||||||
|
import { redirect } from "next/navigation";
|
||||||
|
|
||||||
|
// Opening Accounts directly shows the account page (signing in first if needed).
|
||||||
|
export default function Home() {
|
||||||
|
redirect("/account");
|
||||||
|
}
|
||||||
@@ -0,0 +1,19 @@
|
|||||||
|
import { Card, Heading, Shell } from "@crosscode/ui";
|
||||||
|
import { loadBranding } from "@/lib/branding";
|
||||||
|
|
||||||
|
export const metadata = { title: "Privacy notice" };
|
||||||
|
|
||||||
|
const api = (process.env.ACCOUNTS_API_URL || "http://127.0.0.1:5200").replace(/\/+$/, "");
|
||||||
|
|
||||||
|
export default async function PrivacyPage() {
|
||||||
|
const branding = await loadBranding();
|
||||||
|
const n = await fetch(`${api}/api/v2/notice`, { cache: "no-store" }).then((r) => r.json()).catch(() => null) as { title: string; body: string } | null;
|
||||||
|
return (
|
||||||
|
<Shell branding={branding}>
|
||||||
|
<Card>
|
||||||
|
<Heading>{n?.title ?? "Privacy notice"}</Heading>
|
||||||
|
<div className="whitespace-pre-line text-sm leading-6 text-gray-700">{n?.body ?? "The privacy notice couldn't be loaded. Please try again."}</div>
|
||||||
|
</Card>
|
||||||
|
</Shell>
|
||||||
|
);
|
||||||
|
}
|
||||||
@@ -0,0 +1,32 @@
|
|||||||
|
"use client";
|
||||||
|
|
||||||
|
import React, { useState } from "react";
|
||||||
|
import { Button, Card, Field, Heading, Notice, Shell } from "@crosscode/ui";
|
||||||
|
import { useBranding } from "@/components/BrandingProvider";
|
||||||
|
import { call, selfSignIn } from "@/lib/api";
|
||||||
|
|
||||||
|
export function Reset({ token }: { token: string | null }) {
|
||||||
|
const branding = useBranding();
|
||||||
|
const [busy, setBusy] = useState(false);
|
||||||
|
const [error, setError] = useState<string | null>(null);
|
||||||
|
return (
|
||||||
|
<Shell branding={branding}>
|
||||||
|
<Card>
|
||||||
|
<Heading 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") });
|
||||||
|
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"));
|
||||||
|
}}>
|
||||||
|
<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>
|
||||||
|
</form>
|
||||||
|
</Card>
|
||||||
|
</Shell>
|
||||||
|
);
|
||||||
|
}
|
||||||
@@ -0,0 +1,8 @@
|
|||||||
|
import { Reset } from "./Reset";
|
||||||
|
|
||||||
|
export const metadata = { title: "Choose a new password" };
|
||||||
|
|
||||||
|
export default async function Page({ searchParams }: { searchParams: Promise<{ token?: string }> }) {
|
||||||
|
const { token } = await searchParams;
|
||||||
|
return <Reset token={token ?? null} />;
|
||||||
|
}
|
||||||
@@ -0,0 +1,6 @@
|
|||||||
|
import type { MetadataRoute } from "next";
|
||||||
|
|
||||||
|
// Accounts is never indexed (ROADMAP-v3 §11).
|
||||||
|
export default function robots(): MetadataRoute.Robots {
|
||||||
|
return { rules: [{ userAgent: "*", disallow: "/" }] };
|
||||||
|
}
|
||||||
@@ -0,0 +1,52 @@
|
|||||||
|
"use client";
|
||||||
|
|
||||||
|
import React, { useState } from "react";
|
||||||
|
import { Button, Card, Field, Heading, Notice, Shell } from "@crosscode/ui";
|
||||||
|
import { useBranding } from "@/components/BrandingProvider";
|
||||||
|
import { call, type ApiError } from "@/lib/api";
|
||||||
|
import { useExternalEffect } from "@/lib/hooks";
|
||||||
|
|
||||||
|
type Status = { needed: boolean; hubConnected: boolean; adminEmail: string | null };
|
||||||
|
|
||||||
|
/** First run: the church's name, the first admin and the licence key (docs/ACCOUNTS-1.0-PLAN.md §8). */
|
||||||
|
export function Setup() {
|
||||||
|
const branding = useBranding();
|
||||||
|
const [status, setStatus] = useState<Status | null>(null);
|
||||||
|
const [error, setError] = useState<ApiError | null>(null);
|
||||||
|
const [busy, setBusy] = useState(false);
|
||||||
|
useExternalEffect(() => {
|
||||||
|
let alive = true;
|
||||||
|
call<Status>("GET", "/setup").then((r) => { if (alive && r.ok) setStatus(r.data); });
|
||||||
|
return () => { alive = false; };
|
||||||
|
}, []);
|
||||||
|
|
||||||
|
const f = (n: string) => error?.fields?.[n] ?? null;
|
||||||
|
return (
|
||||||
|
<Shell branding={branding}>
|
||||||
|
<Card>
|
||||||
|
<Heading sub="Your church's sign-in for its website, app and Cross Events.">Set up Accounts</Heading>
|
||||||
|
{!status ? <p className="text-gray-600">Loading…</p> : !status.needed ? (
|
||||||
|
<Notice tone="info">Accounts is already set up. <a href="/account" className="underline">Sign in</a></Notice>
|
||||||
|
) : (
|
||||||
|
<form onSubmit={async (e) => {
|
||||||
|
e.preventDefault();
|
||||||
|
const d = new FormData(e.currentTarget);
|
||||||
|
setBusy(true);
|
||||||
|
setError(null);
|
||||||
|
const r = await call<{ next: string }>("POST", "/setup", { churchName: d.get("churchName"), name: d.get("name"), email: d.get("email"), password: d.get("password"), licenceKey: d.get("licenceKey") || undefined });
|
||||||
|
setBusy(false);
|
||||||
|
if (r.ok) window.location.assign(r.data.next); else setError(r.error);
|
||||||
|
}}>
|
||||||
|
{error && !error.fields && <Notice tone="error">{error.message}</Notice>}
|
||||||
|
<Field label="The church's name" name="churchName" required error={f("churchName")} />
|
||||||
|
<Field label="Your name" name="name" required autoComplete="name" error={f("name")} />
|
||||||
|
<Field label="Your email address" name="email" type="email" required autoComplete="email" defaultValue={status.adminEmail ?? ""} error={f("email")} />
|
||||||
|
<Field label="Password" name="password" type="password" required minLength={8} autoComplete="new-password" error={f("password")} hint="At least 8 characters. You'll also set up two-step sign-in." />
|
||||||
|
{!status.hubConnected && <Field label="Licence key" name="licenceKey" required placeholder="CCA-XXXX-XXXX-XXXX-XXXX" error={f("licenceKey")} hint="From your provider." />}
|
||||||
|
<Button type="submit" busy={busy} className="w-full">Set up and sign in</Button>
|
||||||
|
</form>
|
||||||
|
)}
|
||||||
|
</Card>
|
||||||
|
</Shell>
|
||||||
|
);
|
||||||
|
}
|
||||||
@@ -0,0 +1,7 @@
|
|||||||
|
import { Setup } from "./Setup";
|
||||||
|
|
||||||
|
export const metadata = { title: "Set up Accounts" };
|
||||||
|
|
||||||
|
export default function SetupPage() {
|
||||||
|
return <Setup />;
|
||||||
|
}
|
||||||
@@ -0,0 +1,17 @@
|
|||||||
|
"use client";
|
||||||
|
|
||||||
|
import { Card, Heading, Shell } from "@crosscode/ui";
|
||||||
|
import { useBranding } from "@/components/BrandingProvider";
|
||||||
|
import { selfSignIn } from "@/lib/api";
|
||||||
|
|
||||||
|
export default function SignedOutPage() {
|
||||||
|
const branding = useBranding();
|
||||||
|
return (
|
||||||
|
<Shell branding={branding}>
|
||||||
|
<Card>
|
||||||
|
<Heading 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>
|
||||||
|
);
|
||||||
|
}
|
||||||
@@ -0,0 +1,265 @@
|
|||||||
|
"use client";
|
||||||
|
|
||||||
|
import React, { useState } from "react";
|
||||||
|
import QRCode from "qrcode";
|
||||||
|
import { Button, Card, Checkbox, Field, Heading, Notice, Shell } from "@crosscode/ui";
|
||||||
|
import { useBranding } from "@/components/BrandingProvider";
|
||||||
|
import { call, type ApiError } from "@/lib/api";
|
||||||
|
import { useExternalEffect } from "@/lib/hooks";
|
||||||
|
|
||||||
|
type State = {
|
||||||
|
uid: string;
|
||||||
|
stage: "password" | "verify_email" | "two_factor" | "setup_two_factor" | "notice" | "news" | "done";
|
||||||
|
product: string;
|
||||||
|
signupEnabled: boolean;
|
||||||
|
loginHint?: string | null;
|
||||||
|
name?: string;
|
||||||
|
email?: string;
|
||||||
|
sentTo?: string;
|
||||||
|
method?: "totp" | "email" | "whatsapp";
|
||||||
|
methods?: string[];
|
||||||
|
why?: "admin" | "product";
|
||||||
|
notice?: { version: number; title: string; body: string };
|
||||||
|
updated?: boolean;
|
||||||
|
redirectTo?: string;
|
||||||
|
recoveryCodes?: string[];
|
||||||
|
};
|
||||||
|
|
||||||
|
/**
|
||||||
|
* One sign-in, step by step (docs/ACCOUNTS-1.0-PLAN.md §5). The backend says which step comes next;
|
||||||
|
* when it's done, the browser goes back to the product it came from.
|
||||||
|
*/
|
||||||
|
export function SignIn({ uid }: { uid: string }) {
|
||||||
|
const branding = useBranding();
|
||||||
|
const [state, setState] = useState<State | null>(null);
|
||||||
|
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 apply = (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);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
setState(s);
|
||||||
|
};
|
||||||
|
|
||||||
|
useExternalEffect(() => {
|
||||||
|
let alive = true;
|
||||||
|
call<State>("GET", `/interaction/${encodeURIComponent(uid)}/state`).then((r) => {
|
||||||
|
if (!alive) return;
|
||||||
|
if (r.ok) apply(r.data);
|
||||||
|
else setError(r.error);
|
||||||
|
});
|
||||||
|
return () => { alive = false; };
|
||||||
|
}, [uid]);
|
||||||
|
|
||||||
|
const submit = async (path: string, body: unknown) => {
|
||||||
|
setBusy(true);
|
||||||
|
setError(null);
|
||||||
|
const r = await call<State>("POST", `/interaction/${encodeURIComponent(uid)}${path}`, body);
|
||||||
|
setBusy(false);
|
||||||
|
if (r.ok) apply(r.data);
|
||||||
|
else setError(r.error);
|
||||||
|
return r;
|
||||||
|
};
|
||||||
|
|
||||||
|
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)} />);
|
||||||
|
}
|
||||||
|
if (!state) {
|
||||||
|
return frame(error ? (
|
||||||
|
<>
|
||||||
|
<Heading>We couldn't continue</Heading>
|
||||||
|
<Notice tone="error">{error.message}</Notice>
|
||||||
|
</>
|
||||||
|
) : <p className="text-gray-600">Loading…</p>);
|
||||||
|
}
|
||||||
|
|
||||||
|
const err = error ? <Notice tone="error">{error.message}</Notice> : null;
|
||||||
|
const fieldError = (name: string) => error?.fields?.[name] ?? null;
|
||||||
|
|
||||||
|
switch (state.stage) {
|
||||||
|
case "password":
|
||||||
|
return frame(mode === "signin"
|
||||||
|
? <PasswordStep state={state} busy={busy} err={err} onSubmit={(b) => submit("/password", b)} onSignUp={() => { setError(null); setMode("signup"); }} />
|
||||||
|
: <SignUpStep busy={busy} err={err} fieldError={fieldError} onSubmit={(b) => submit("/signup", b)} onBack={() => { setError(null); setMode("signin"); }} />);
|
||||||
|
case "verify_email":
|
||||||
|
return frame(<CodeStep title="Check your email" sub={<>We sent a 6-digit code to <strong>{state.sentTo}</strong>. Enter it to confirm your email address.</>} busy={busy} err={err} onSubmit={(code) => submit("/verify-email", { code })} onResend={() => submit("/resend", {})} />);
|
||||||
|
case "two_factor":
|
||||||
|
return frame(<TwoFactorStep state={state} busy={busy} err={err} onSubmit={(b) => submit("/two-factor", b)} onResend={() => submit("/resend", {})} />);
|
||||||
|
case "setup_two_factor":
|
||||||
|
return frame(<SetupStep uid={uid} state={state} busy={busy} err={err} setError={setError} onConfirm={(b) => submit("/two-factor/setup/confirm", b)} />);
|
||||||
|
case "notice":
|
||||||
|
return frame(<NoticeStep state={state} busy={busy} err={err} onAccept={() => submit("/notice", { version: state.notice!.version })} />);
|
||||||
|
case "news":
|
||||||
|
return frame(<NewsStep busy={busy} err={err} onSubmit={(b) => submit("/news", b)} />);
|
||||||
|
default:
|
||||||
|
return frame(<p className="text-gray-600">Taking you back…</p>);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
function PasswordStep({ state, busy, err, onSubmit, onSignUp }: { state: State; busy: boolean; err: React.ReactNode; onSubmit: (b: object) => void; onSignUp: () => void }) {
|
||||||
|
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>
|
||||||
|
{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 />
|
||||||
|
<Checkbox name="remember" label="Keep me signed in on this device" defaultChecked />
|
||||||
|
<Button type="submit" busy={busy} className="w-full">Sign in</Button>
|
||||||
|
<div className="mt-4 flex flex-wrap justify-between gap-2 text-sm">
|
||||||
|
<a href={`/forgot?uid=${encodeURIComponent(state.uid)}`} className="text-brand underline">Forgot your password?</a>
|
||||||
|
{state.signupEnabled && <button type="button" onClick={onSignUp} className="text-brand underline">Create an account</button>}
|
||||||
|
</div>
|
||||||
|
</form>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
function SignUpStep({ busy, err, fieldError, onSubmit, onBack }: { busy: boolean; err: React.ReactNode; fieldError: (n: string) => string | null; onSubmit: (b: object) => void; onBack: () => void }) {
|
||||||
|
const branding = useBranding();
|
||||||
|
const [phone, setPhone] = useState("");
|
||||||
|
return (
|
||||||
|
<form onSubmit={(e) => {
|
||||||
|
e.preventDefault();
|
||||||
|
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>
|
||||||
|
{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")} />
|
||||||
|
<Field label="Mobile number (optional)" name="phone" type="tel" autoComplete="tel" value={phone} onChange={(e) => setPhone(e.target.value)} error={fieldError("phone")} hint="For WhatsApp messages, if you'd like them." />
|
||||||
|
<Field label="Password" name="password" type="password" autoComplete="new-password" required minLength={8} error={fieldError("password")} hint="At least 8 characters." />
|
||||||
|
<Checkbox name="newsEmail" label="Send me church news by email" />
|
||||||
|
{phone && <Checkbox name="newsWhatsApp" label="Send me church news on WhatsApp" />}
|
||||||
|
<Checkbox name="acceptNotice" required label={<>I've read the <a href="/privacy" target="_blank" className="text-brand underline">privacy notice</a></>} hint={fieldError("acceptNotice") ?? undefined} />
|
||||||
|
<Button type="submit" busy={busy} className="w-full">Create account</Button>
|
||||||
|
<p className="mt-4 text-sm"><button type="button" onClick={onBack} className="text-brand underline">I already have an account</button></p>
|
||||||
|
</form>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
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>
|
||||||
|
{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>
|
||||||
|
{onResend && <p className="mt-4 text-sm"><button type="button" onClick={onResend} className="text-brand underline">Send a new code</button></p>}
|
||||||
|
</form>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
function TwoFactorStep({ state, busy, err, onSubmit, onResend }: { state: State; busy: boolean; err: React.ReactNode; onSubmit: (b: object) => void; onResend: () => void }) {
|
||||||
|
const [recovery, setRecovery] = useState(false);
|
||||||
|
if (recovery) {
|
||||||
|
return (
|
||||||
|
<form onSubmit={(e) => { e.preventDefault(); onSubmit({ recoveryCode: new FormData(e.currentTarget).get("recoveryCode") }); }}>
|
||||||
|
<Heading sub="One of the recovery codes you saved when you turned on two-step sign-in. Each works once.">Use a recovery code</Heading>
|
||||||
|
{err}
|
||||||
|
<Field label="Recovery code" name="recoveryCode" autoComplete="off" required autoFocus />
|
||||||
|
<Button type="submit" busy={busy} className="w-full">Continue</Button>
|
||||||
|
<p className="mt-4 text-sm"><button type="button" onClick={() => setRecovery(false)} className="text-brand underline">Use a code instead</button></p>
|
||||||
|
</form>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
const sub = state.method === "totp" ? "Enter the 6-digit code from your authenticator app." : <>We sent a 6-digit code to <strong>{state.sentTo}</strong>.</>;
|
||||||
|
return (
|
||||||
|
<>
|
||||||
|
<CodeStep title="Second step" sub={sub} busy={busy} err={err} onSubmit={(code) => onSubmit({ code })} onResend={state.method === "totp" ? undefined : onResend} />
|
||||||
|
<p className="mt-2 text-sm"><button type="button" onClick={() => setRecovery(true)} className="text-brand underline">Use a recovery code</button></p>
|
||||||
|
</>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
function SetupStep({ uid, state, busy, err, setError, onConfirm }: { uid: string; state: State; busy: boolean; err: React.ReactNode; setError: (e: ApiError | null) => void; onConfirm: (b: object) => void }) {
|
||||||
|
const [started, setStarted] = useState<{ method: string; secret?: string; otpauthUrl?: string; sentTo?: string } | null>(null);
|
||||||
|
const [qr, setQr] = useState<string | null>(null);
|
||||||
|
const start = async (method: string) => {
|
||||||
|
setError(null);
|
||||||
|
const r = await call<{ method: string; secret?: string; otpauthUrl?: string; sentTo?: string }>("POST", `/interaction/${encodeURIComponent(uid)}/two-factor/setup`, { method });
|
||||||
|
if (!r.ok) return setError(r.error);
|
||||||
|
setStarted(r.data);
|
||||||
|
if (r.data.otpauthUrl) setQr(await QRCode.toDataURL(r.data.otpauthUrl, { margin: 1, width: 200 }));
|
||||||
|
};
|
||||||
|
const why = state.why === "admin" ? "Admins must use a second step when they sign in." : `${state.product} asks for a second step when you sign in.`;
|
||||||
|
if (!started) {
|
||||||
|
const labels: Record<string, [string, string]> = {
|
||||||
|
totp: ["An authenticator app", "Google Authenticator, Microsoft Authenticator, 1Password… Most secure, works without signal."],
|
||||||
|
email: ["A code by email", `Sent to ${state.email}.`],
|
||||||
|
whatsapp: ["A code on WhatsApp", "Sent to your mobile number."],
|
||||||
|
};
|
||||||
|
return (
|
||||||
|
<>
|
||||||
|
<Heading sub={why}>Set up two-step sign-in</Heading>
|
||||||
|
{err}
|
||||||
|
<div className="space-y-2">
|
||||||
|
{(state.methods ?? []).map((m) => (
|
||||||
|
<button key={m} type="button" onClick={() => start(m)} className="w-full rounded-lg border p-3 text-left hover:border-brand">
|
||||||
|
<span className="block font-medium">{labels[m]?.[0] ?? m}</span>
|
||||||
|
<span className="block text-sm text-gray-600">{labels[m]?.[1]}</span>
|
||||||
|
</button>
|
||||||
|
))}
|
||||||
|
</div>
|
||||||
|
</>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
return (
|
||||||
|
<form onSubmit={(e) => { e.preventDefault(); onConfirm({ method: started.method, code: new FormData(e.currentTarget).get("code") }); }}>
|
||||||
|
<Heading sub={started.method === "totp" ? "Scan this with your authenticator app, then enter the code it shows." : <>We sent a code to <strong>{started.sentTo}</strong>.</>}>
|
||||||
|
{started.method === "totp" ? "Scan the QR code" : "Enter the code"}
|
||||||
|
</Heading>
|
||||||
|
{err}
|
||||||
|
{qr && <img src={qr} alt="QR code for your authenticator app" className="mx-auto mb-3 h-48 w-48" />}
|
||||||
|
{started.secret && <p className="mb-4 break-all text-center font-mono text-sm text-gray-600">Or type this key: {started.secret}</p>}
|
||||||
|
<Field label="Code" name="code" inputMode="numeric" autoComplete="one-time-code" required autoFocus />
|
||||||
|
<Button type="submit" busy={busy} className="w-full">Turn on</Button>
|
||||||
|
</form>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
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>
|
||||||
|
<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>
|
||||||
|
<a className="rounded-lg border px-4 py-2.5 text-sm" download="recovery-codes.txt" href={`data:text/plain;charset=utf-8,${encodeURIComponent(text)}`}>Download</a>
|
||||||
|
</div>
|
||||||
|
<Button type="button" className="w-full" onClick={onDone}>I've saved them</Button>
|
||||||
|
</>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
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>
|
||||||
|
{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>
|
||||||
|
</>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
function NewsStep({ busy, err, onSubmit }: { busy: boolean; err: React.ReactNode; onSubmit: (b: object) => void }) {
|
||||||
|
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>
|
||||||
|
{err}
|
||||||
|
<Checkbox name="email" label="Yes, by email" />
|
||||||
|
<Checkbox name="whatsapp" label="Yes, on WhatsApp" hint="If your mobile number is on your account." />
|
||||||
|
<Button type="submit" busy={busy} className="w-full">Continue</Button>
|
||||||
|
</form>
|
||||||
|
);
|
||||||
|
}
|
||||||
@@ -0,0 +1,11 @@
|
|||||||
|
import { redirect } from "next/navigation";
|
||||||
|
import { SignIn } from "./SignIn";
|
||||||
|
|
||||||
|
export const metadata = { title: "Sign in" };
|
||||||
|
|
||||||
|
// /signin?uid=… is a sign-in a product started; without one, sign in to the account page.
|
||||||
|
export default async function SignInPage({ searchParams }: { searchParams: Promise<{ uid?: string }> }) {
|
||||||
|
const { uid } = await searchParams;
|
||||||
|
if (!uid || !/^[A-Za-z0-9_-]{10,64}$/.test(uid)) redirect("/api/self/signin?returnTo=%2Faccount");
|
||||||
|
return <SignIn uid={uid} />;
|
||||||
|
}
|
||||||
@@ -0,0 +1,13 @@
|
|||||||
|
"use client";
|
||||||
|
|
||||||
|
import React, { createContext, useContext } from "react";
|
||||||
|
|
||||||
|
export type ClientBranding = { name: string; shortName: string | null; logoUrl: string | null; signupEnabled: boolean; setupNeeded: boolean };
|
||||||
|
|
||||||
|
const Ctx = createContext<ClientBranding>({ name: "Sign in", shortName: null, logoUrl: null, signupEnabled: true, setupNeeded: false });
|
||||||
|
|
||||||
|
export function BrandingProvider({ value, children }: { value: ClientBranding; children: React.ReactNode }) {
|
||||||
|
return <Ctx.Provider value={value}>{children}</Ctx.Provider>;
|
||||||
|
}
|
||||||
|
|
||||||
|
export const useBranding = () => useContext(Ctx);
|
||||||
@@ -0,0 +1,26 @@
|
|||||||
|
/**
|
||||||
|
* Calls to the backend from the browser (same address, under /api). Errors come back as
|
||||||
|
* { error: { code, message, fields? } }; `call` returns them instead of throwing.
|
||||||
|
*/
|
||||||
|
export type ApiError = { code: string; message: string; fields?: Record<string, string> };
|
||||||
|
export type ApiResult<T> = { ok: true; status: number; data: T } | { ok: false; status: number; error: ApiError };
|
||||||
|
|
||||||
|
export async function call<T = Record<string, unknown>>(method: "GET" | "POST" | "PUT" | "DELETE", path: string, body?: unknown): Promise<ApiResult<T>> {
|
||||||
|
let res: Response;
|
||||||
|
try {
|
||||||
|
res = await fetch(`/api/v2${path}`, {
|
||||||
|
method,
|
||||||
|
credentials: "same-origin",
|
||||||
|
headers: body !== undefined ? { "Content-Type": "application/json" } : undefined,
|
||||||
|
body: body !== undefined ? JSON.stringify(body) : undefined,
|
||||||
|
});
|
||||||
|
} catch {
|
||||||
|
return { ok: false, status: 0, error: { code: "OFFLINE", message: "We couldn't reach the server. Check your connection and try again." } };
|
||||||
|
}
|
||||||
|
const json = (await res.json().catch(() => ({}))) as { error?: ApiError };
|
||||||
|
if (!res.ok) return { ok: false, status: res.status, error: json.error ?? { code: "ERROR", message: "Something went wrong. Please try again." } };
|
||||||
|
return { ok: true, status: res.status, data: json as T };
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Where to sign in to Accounts' own pages, coming back to `returnTo`. */
|
||||||
|
export const selfSignIn = (returnTo: string, extra = "") => `/api/self/signin?returnTo=${encodeURIComponent(returnTo)}${extra}`;
|
||||||
@@ -0,0 +1,30 @@
|
|||||||
|
/** The church's branding from the backend, for the server-rendered frame of every page. */
|
||||||
|
export type BrandingData = {
|
||||||
|
name: string;
|
||||||
|
shortName: string | null;
|
||||||
|
logoUrl: string | null;
|
||||||
|
colours: { primary: string; accent: string | null };
|
||||||
|
signupEnabled: boolean;
|
||||||
|
setupNeeded: boolean;
|
||||||
|
};
|
||||||
|
|
||||||
|
const api = (process.env.ACCOUNTS_API_URL || "http://127.0.0.1:5200").replace(/\/+$/, "");
|
||||||
|
|
||||||
|
export async function loadBranding(): Promise<BrandingData> {
|
||||||
|
try {
|
||||||
|
const res = await fetch(`${api}/api/v2/branding`, { cache: "no-store" });
|
||||||
|
if (res.ok) return (await res.json()) as BrandingData;
|
||||||
|
} catch {
|
||||||
|
// The backend is starting or down: plain defaults, the page still works.
|
||||||
|
}
|
||||||
|
return { name: "Sign in", shortName: null, logoUrl: null, colours: { primary: "#1f4e79", accent: null }, signupEnabled: true, setupNeeded: false };
|
||||||
|
}
|
||||||
|
|
||||||
|
/** "#1f4e79" → "31 78 121" (Tailwind's rgb(var(--brand) / alpha)), and a darker shade for hover. */
|
||||||
|
export function rgbVars(hex: string): { brand: string; dark: string } {
|
||||||
|
const m = /^#([0-9a-f]{6})$/i.exec(hex) ?? ["", "1f4e79"];
|
||||||
|
const n = parseInt(m[1]!, 16);
|
||||||
|
const [r, g, b] = [(n >> 16) & 255, (n >> 8) & 255, n & 255];
|
||||||
|
const d = (x: number) => Math.round(x * 0.8);
|
||||||
|
return { brand: `${r} ${g} ${b}`, dark: `${d(r)} ${d(g)} ${d(b)}` };
|
||||||
|
}
|
||||||
@@ -0,0 +1,14 @@
|
|||||||
|
import { useEffect, type DependencyList } from "react";
|
||||||
|
|
||||||
|
/**
|
||||||
|
* `useEffect` for loading from the API and setting state from it (as Cross Events' lib/hooks.ts):
|
||||||
|
* the React Compiler lint can't tell that apart from state derived from other state.
|
||||||
|
*/
|
||||||
|
export function useExternalEffect(run: () => void | (() => void) | Promise<unknown>, deps: DependencyList) {
|
||||||
|
useEffect(() => {
|
||||||
|
const out = run();
|
||||||
|
return typeof out === "function" ? out : undefined;
|
||||||
|
// The caller's deps, checked at the call site by exhaustive-deps (additionalHooks).
|
||||||
|
// eslint-disable-next-line react-hooks/exhaustive-deps
|
||||||
|
}, deps);
|
||||||
|
}
|
||||||
@@ -0,0 +1,33 @@
|
|||||||
|
import { NextResponse, type NextRequest } from "next/server";
|
||||||
|
|
||||||
|
/**
|
||||||
|
* A strict Content-Security-Policy with a fresh nonce per page (docs/ACCOUNTS-1.0-PLAN.md §10):
|
||||||
|
* no inline scripts or styles except Next's own and the church's colours, both carrying the nonce.
|
||||||
|
* Sign-in pages never load anything from another site.
|
||||||
|
*/
|
||||||
|
export function proxy(request: NextRequest) {
|
||||||
|
const nonce = Buffer.from(crypto.randomUUID()).toString("base64");
|
||||||
|
const dev = process.env.NODE_ENV === "development";
|
||||||
|
const csp = [
|
||||||
|
"default-src 'self'",
|
||||||
|
`script-src 'self' 'nonce-${nonce}' 'strict-dynamic'${dev ? " 'unsafe-eval'" : ""}`,
|
||||||
|
`style-src 'self' 'nonce-${nonce}'`,
|
||||||
|
"img-src 'self' https: data:",
|
||||||
|
"font-src 'self'",
|
||||||
|
"connect-src 'self'",
|
||||||
|
"object-src 'none'",
|
||||||
|
"base-uri 'self'",
|
||||||
|
"form-action 'self'",
|
||||||
|
"frame-ancestors 'none'",
|
||||||
|
].join("; ");
|
||||||
|
const headers = new Headers(request.headers);
|
||||||
|
headers.set("x-nonce", nonce);
|
||||||
|
headers.set("Content-Security-Policy", csp);
|
||||||
|
const res = NextResponse.next({ request: { headers } });
|
||||||
|
res.headers.set("Content-Security-Policy", csp);
|
||||||
|
return res;
|
||||||
|
}
|
||||||
|
|
||||||
|
export const config = {
|
||||||
|
matcher: [{ source: "/((?!api|_next/static|_next/image|favicon.ico).*)", missing: [{ type: "header", key: "next-router-prefetch" }] }],
|
||||||
|
};
|
||||||
@@ -0,0 +1,13 @@
|
|||||||
|
/** @type {import('tailwindcss').Config} */
|
||||||
|
// The church's colour is a CSS variable set per request in layout.tsx (from the church profile).
|
||||||
|
module.exports = {
|
||||||
|
content: ["./src/**/*.{ts,tsx}", "../../../packages/ui/src/**/*.{ts,tsx}"],
|
||||||
|
theme: {
|
||||||
|
extend: {
|
||||||
|
colors: {
|
||||||
|
brand: { DEFAULT: "rgb(var(--brand) / <alpha-value>)", dark: "rgb(var(--brand-dark) / <alpha-value>)" },
|
||||||
|
},
|
||||||
|
},
|
||||||
|
},
|
||||||
|
plugins: [],
|
||||||
|
};
|
||||||
@@ -0,0 +1,21 @@
|
|||||||
|
{
|
||||||
|
"compilerOptions": {
|
||||||
|
"target": "ES2020",
|
||||||
|
"lib": ["dom", "dom.iterable", "esnext"],
|
||||||
|
"allowJs": false,
|
||||||
|
"skipLibCheck": true,
|
||||||
|
"strict": true,
|
||||||
|
"noEmit": true,
|
||||||
|
"esModuleInterop": true,
|
||||||
|
"module": "esnext",
|
||||||
|
"moduleResolution": "bundler",
|
||||||
|
"resolveJsonModule": true,
|
||||||
|
"isolatedModules": true,
|
||||||
|
"jsx": "react-jsx",
|
||||||
|
"incremental": true,
|
||||||
|
"plugins": [{ "name": "next" }],
|
||||||
|
"paths": { "@/*": ["./src/*"] }
|
||||||
|
},
|
||||||
|
"include": ["next-env.d.ts", "**/*.ts", "**/*.tsx", ".next/types/**/*.ts", ".next/dev/types/**/*.ts"],
|
||||||
|
"exclude": ["node_modules"]
|
||||||
|
}
|
||||||
@@ -0,0 +1,34 @@
|
|||||||
|
import { defineConfig, devices } from "@playwright/test";
|
||||||
|
|
||||||
|
// Accounts' pages end to end (docs/ACCOUNTS-1.0-PLAN.md §12): the real backend on an in-memory
|
||||||
|
// database with a test product (e2e/server.ts), and the Next.js pages. Run with `npm run test:e2e`
|
||||||
|
// in apps/accounts. Nothing needs a database.
|
||||||
|
export default defineConfig({
|
||||||
|
testDir: "./e2e",
|
||||||
|
testMatch: "**/*.spec.ts",
|
||||||
|
workers: 1,
|
||||||
|
fullyParallel: false,
|
||||||
|
timeout: 120_000,
|
||||||
|
expect: { timeout: 20_000 },
|
||||||
|
reporter: "list",
|
||||||
|
outputDir: "e2e/test-results",
|
||||||
|
use: { baseURL: "http://localhost:3210", trace: "retain-on-failure", navigationTimeout: 90_000 },
|
||||||
|
projects: [{ name: "chromium", use: { ...devices["Desktop Chrome"] } }],
|
||||||
|
webServer: [
|
||||||
|
{
|
||||||
|
command: "npx tsx e2e/server.ts",
|
||||||
|
url: "http://127.0.0.1:5210/api/health",
|
||||||
|
timeout: 120_000,
|
||||||
|
reuseExistingServer: false,
|
||||||
|
stdout: "pipe",
|
||||||
|
},
|
||||||
|
{
|
||||||
|
command: "npx next dev -p 3210",
|
||||||
|
cwd: "frontend",
|
||||||
|
url: "http://localhost:3210/privacy",
|
||||||
|
timeout: 180_000,
|
||||||
|
reuseExistingServer: false,
|
||||||
|
env: { ACCOUNTS_API_URL: "http://127.0.0.1:5210" },
|
||||||
|
},
|
||||||
|
],
|
||||||
|
});
|
||||||
@@ -1,6 +1,6 @@
|
|||||||
{
|
{
|
||||||
"name": "@crosscode/agent",
|
"name": "@crosscode/agent",
|
||||||
"version": "1.0.1",
|
"version": "1.1.1",
|
||||||
"private": true,
|
"private": true,
|
||||||
"description": "The server agent: runs the crosscode script for signed jobs from Cross Code Hub, reports stats (docs/AGENT-1.0-PLAN.md)",
|
"description": "The server agent: runs the crosscode script for signed jobs from Cross Code Hub, reports stats (docs/AGENT-1.0-PLAN.md)",
|
||||||
"license": "UNLICENSED",
|
"license": "UNLICENSED",
|
||||||
|
|||||||
+17
-11
@@ -11,21 +11,27 @@ export function crosscodeArgs(job: agent.AgentJob, opts: { exportFile?: string }
|
|||||||
switch (job.type) {
|
switch (job.type) {
|
||||||
case "install": {
|
case "install": {
|
||||||
const a = job.args;
|
const a = job.args;
|
||||||
if (a.products.length !== 1 || a.products[0] !== "events") throw new Error("This agent can only install Events so far.");
|
const product = a.products[0];
|
||||||
const domain = a.domains.events;
|
if (a.products.length !== 1 || (product !== "events" && product !== "accounts")) throw new Error("This agent installs one product at a time: Events or Accounts.");
|
||||||
const ports = a.ports.events;
|
const domain = a.domains[product];
|
||||||
if (!domain || !ports) throw new Error("An Events install needs its domain and ports.");
|
const ports = a.ports[product];
|
||||||
// The church's address: the Events domain without "events." (crosscode uses it for the
|
if (!domain || !ports) throw new Error(`An install of ${product} needs its domain and ports.`);
|
||||||
// church.env ADDRESS; the domain itself goes in --events-domain).
|
// The church's address: the product's domain without "<product>." (crosscode keeps it in
|
||||||
const address = domain.startsWith("events.") ? domain.slice("events.".length) : domain;
|
// church.env ADDRESS for the products added later; the domain itself goes in --<product>-domain).
|
||||||
const out = ["install", a.church, "--products", "events", "--domain", address, "--events-domain", domain,
|
const address = domain.startsWith(`${product}.`) ? domain.slice(product.length + 1) : domain;
|
||||||
|
const out = ["install", a.church, "--products", product, "--domain", address, `--${product}-domain`, domain,
|
||||||
"--api-port", String(ports.api), "--web-port", String(ports.web), "--frp"];
|
"--api-port", String(ports.api), "--web-port", String(ports.web), "--frp"];
|
||||||
const v = a.versions?.events;
|
const v = a.versions?.[product];
|
||||||
if (v) out.push("--version", v);
|
if (v) out.push("--version", v);
|
||||||
return out;
|
return out;
|
||||||
}
|
}
|
||||||
case "add-product":
|
case "add-product": {
|
||||||
return ["add", job.args.church, job.args.product];
|
// A product next to the church's others (phase 3: Accounts next to Events), behind frp.
|
||||||
|
const a = job.args;
|
||||||
|
const out = ["add", a.church, a.product, "--domain", a.domain, "--api-port", String(a.ports.api), "--web-port", String(a.ports.web), "--frp"];
|
||||||
|
if (a.version) out.push("--version", a.version);
|
||||||
|
return out;
|
||||||
|
}
|
||||||
case "deploy": {
|
case "deploy": {
|
||||||
const out = ["deploy", job.args.church, ...job.args.products];
|
const out = ["deploy", job.args.church, ...job.args.products];
|
||||||
for (const v of job.args.versions ?? []) out.push("--version", v);
|
for (const v of job.args.versions ?? []) out.push("--version", v);
|
||||||
|
|||||||
+22
-6
@@ -214,17 +214,33 @@ export class Agent {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
/** Runs until stopped: polls and stats on their own timers, never at the same time as a job. */
|
/**
|
||||||
|
* Runs until stopped. Stats go on their own timer, every `statsSeconds`, also while a job runs:
|
||||||
|
* an install or update can take 30 minutes, and before 1.1.1 the agent went quiet for all of it,
|
||||||
|
* so the Hub reported it as down (and emailed) though it was busy. Polls wait for the job.
|
||||||
|
*/
|
||||||
async start(): Promise<void> {
|
async start(): Promise<void> {
|
||||||
log(`[agent] ${AGENT_VERSION} (${this.deps.config.mode}) for ${this.deps.config.serverId}, Hub ${this.deps.config.hubUrl}`);
|
log(`[agent] ${AGENT_VERSION} (${this.deps.config.mode}) for ${this.deps.config.serverId}, Hub ${this.deps.config.hubUrl}`);
|
||||||
let nextStats = 0;
|
let sending = false;
|
||||||
while (!this.stopped) {
|
const statsTick = async () => {
|
||||||
if (Date.now() >= nextStats) {
|
if (sending || this.stopped) return;
|
||||||
|
sending = true;
|
||||||
|
try {
|
||||||
await this.statsOnce();
|
await this.statsOnce();
|
||||||
nextStats = Date.now() + this.deps.config.statsSeconds * 1000;
|
} finally {
|
||||||
|
sending = false;
|
||||||
}
|
}
|
||||||
|
};
|
||||||
|
void statsTick();
|
||||||
|
const timer = setInterval(() => void statsTick(), this.deps.config.statsSeconds * 1000);
|
||||||
|
try {
|
||||||
|
while (!this.stopped) {
|
||||||
const delay = await this.pollOnce();
|
const delay = await this.pollOnce();
|
||||||
await new Promise((r) => setTimeout(r, Math.max(5, Math.min(delay, this.deps.config.statsSeconds)) * 1000));
|
if (this.stopped) break;
|
||||||
|
await new Promise((r) => setTimeout(r, Math.max(5, delay) * 1000));
|
||||||
|
}
|
||||||
|
} finally {
|
||||||
|
clearInterval(timer);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -12,7 +12,7 @@ import { paths } from "./paths";
|
|||||||
* the tools that are there; anything missing is null rather than an error.
|
* the tools that are there; anything missing is null rather than an error.
|
||||||
*/
|
*/
|
||||||
|
|
||||||
export const AGENT_VERSION = "1.0.1";
|
export const AGENT_VERSION = "1.1.1";
|
||||||
|
|
||||||
function run(cmd: string, args: string[], timeoutMs = 10_000): Promise<string | null> {
|
function run(cmd: string, args: string[], timeoutMs = 10_000): Promise<string | null> {
|
||||||
return new Promise((resolve) => {
|
return new Promise((resolve) => {
|
||||||
|
|||||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user