diff --git a/apps/accounts/backend/.gitignore b/apps/accounts/backend/.gitignore new file mode 100644 index 0000000..72d0c56 --- /dev/null +++ b/apps/accounts/backend/.gitignore @@ -0,0 +1,6 @@ +node_modules/ +dist/ +src/generated/ +.env +uploads/ +exports/ diff --git a/apps/accounts/backend/package.json b/apps/accounts/backend/package.json new file mode 100644 index 0000000..c2b5314 --- /dev/null +++ b/apps/accounts/backend/package.json @@ -0,0 +1,49 @@ +{ + "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": { + "@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" + } +} diff --git a/apps/accounts/backend/prisma.config.ts b/apps/accounts/backend/prisma.config.ts new file mode 100644 index 0000000..86e9836 --- /dev/null +++ b/apps/accounts/backend/prisma.config.ts @@ -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 ?? '' }, +}); diff --git a/apps/accounts/backend/prisma/migrations/20261120000000_init/migration.sql b/apps/accounts/backend/prisma/migrations/20261120000000_init/migration.sql new file mode 100644 index 0000000..8236cf3 --- /dev/null +++ b/apps/accounts/backend/prisma/migrations/20261120000000_init/migration.sql @@ -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; + diff --git a/apps/accounts/backend/prisma/migrations/migration_lock.toml b/apps/accounts/backend/prisma/migrations/migration_lock.toml new file mode 100644 index 0000000..044d57c --- /dev/null +++ b/apps/accounts/backend/prisma/migrations/migration_lock.toml @@ -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" diff --git a/apps/accounts/backend/prisma/schema.prisma b/apps/accounts/backend/prisma/schema.prisma new file mode 100644 index 0000000..984e2dc --- /dev/null +++ b/apps/accounts/backend/prisma/schema.prisma @@ -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 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]) +} diff --git a/apps/accounts/backend/src/accounts/service.ts b/apps/accounts/backend/src/accounts/service.ts new file mode 100644 index 0000000..020d52f --- /dev/null +++ b/apps/accounts/backend/src/accounts/service.ts @@ -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> { + 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 { + 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(); diff --git a/apps/accounts/backend/src/accounts/twoFactor.ts b/apps/accounts/backend/src/accounts/twoFactor.ts new file mode 100644 index 0000000..8ac221a --- /dev/null +++ b/apps/accounts/backend/src/accounts/twoFactor.ts @@ -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 { + 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 { + 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 { + 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 { + 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 { + return ctx.db.recoveryCode.count({ where: { accountId, usedAt: null } }); +} diff --git a/apps/accounts/backend/src/admin/routes.ts b/apps/accounts/backend/src/admin/routes.ts new file mode 100644 index 0000000..218c080 --- /dev/null +++ b/apps/accounts/backend/src/admin/routes.ts @@ -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 = {}; + 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; +} diff --git a/apps/accounts/backend/src/app.ts b/apps/accounts/backend/src/app.ts new file mode 100644 index 0000000..8f94147 --- /dev/null +++ b/apps/accounts/backend/src/app.ts @@ -0,0 +1,67 @@ +/** + * 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'; + +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: process.env.npm_package_version || '1.0.0', 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; +} diff --git a/apps/accounts/backend/src/church/profile.ts b/apps/accounts/backend/src/church/profile.ts new file mode 100644 index 0000000..66cfb53 --- /dev/null +++ b/apps/accounts/backend/src/church/profile.ts @@ -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 { 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; + +type Stored = Partial> & { updatedAt?: string }; + +const DEFAULTS = (ctx: Ctx): Omit => ({ + 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 { + return ctx.settings.json('church_profile', {}); +} + +/** Whether `/setup` has given the church its name yet. */ +export async function profileSet(ctx: Ctx): Promise { + return !!(await storedProfile(ctx)).name; +} + +export async function church(ctx: Ctx): Promise { + 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) { + 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 { + 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), + }; +} diff --git a/apps/accounts/backend/src/context.ts b/apps/accounts/backend/src/context.ts new file mode 100644 index 0000000..92b4756 --- /dev/null +++ b/apps/accounts/backend/src/context.ts @@ -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; +} diff --git a/apps/accounts/backend/src/http.ts b/apps/accounts/backend/src/http.ts new file mode 100644 index 0000000..c3c2070 --- /dev/null +++ b/apps/accounts/backend/src/http.ts @@ -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) { + super(message); + } +} + +type Fielded = { status?: number; code?: string; fields?: Record; 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): 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.' } }), +}); diff --git a/apps/accounts/backend/src/hub/client.ts b/apps/accounts/backend/src/hub/client.ts new file mode 100644 index 0000000..d19f617 --- /dev/null +++ b/apps/accounts/backend/src/hub/client.ts @@ -0,0 +1,173 @@ +/** + * 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'; + +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> { + const raw = JSON.stringify(body); + const headers: Record = { '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; + if (!res.ok) throw new HubError(String(data.message || `The Hub answered ${res.status}`), String(data.code || 'HUB_ERROR'), res.status); + return data; +} + +function version(): string { + return process.env.npm_package_version || '1.0.0'; +} + +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' }; +} diff --git a/apps/accounts/backend/src/hub/licence.ts b/apps/accounts/backend/src/hub/licence.ts new file mode 100644 index 0000000..07fc05b --- /dev/null +++ b/apps/accounts/backend/src/hub/licence.ts @@ -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): 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 { + return (await licenceStatus(ctx)).claims?.customerId ?? null; +} diff --git a/apps/accounts/backend/src/index.ts b/apps/accounts/backend/src/index.ts new file mode 100644 index 0000000..9c71b40 --- /dev/null +++ b/apps/accounts/backend/src/index.ts @@ -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); +}); diff --git a/apps/accounts/backend/src/interaction/flow.ts b/apps/accounts/backend/src/interaction/flow.ts new file mode 100644 index 0000000..e2470ba --- /dev/null +++ b/apps/accounts/backend/src/interaction/flow.ts @@ -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) { + super(message); + } +} + +type Details = Awaited>; + +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 { + 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 { + 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): Promise { + return ctx.db.pendingSignIn.update({ where: { uid: pending.uid }, data: data as never }); +} + +async function account(ctx: Ctx, pending: PendingSignIn): Promise { + 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'); + pending = await save(ctx, pending, { codeHash: sent.codeHash, codeSentAt: ctx.now(), attempts: 0 }); + } + const extra: Record = { 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) { + 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 = {}; + 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 } }; +} diff --git a/apps/accounts/backend/src/interaction/routes.ts b/apps/accounts/backend/src/interaction/routes.ts new file mode 100644 index 0000000..b869561 --- /dev/null +++ b/apps/accounts/backend/src/interaction/routes.ts @@ -0,0 +1,145 @@ +/** + * 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 = {}) { + 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>['pending']) => Promise | void>) => + handle(async (req, res) => { + const { pending } = await load(req, res); + const extra = (await fn(req, res, pending)) ?? {}; + return next(req, res, extra); + }); + + r.get('/interaction/:uid', 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; + 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; +} diff --git a/apps/accounts/backend/src/jobs.ts b/apps/accounts/backend/src/jobs.ts new file mode 100644 index 0000000..5bb0750 --- /dev/null +++ b/apps/accounts/backend/src/jobs.ts @@ -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 }; + +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> { + 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); }; + } +} diff --git a/apps/accounts/backend/src/lib/audit.ts b/apps/accounts/backend/src/lib/audit.ts new file mode 100644 index 0000000..de6f0c3 --- /dev/null +++ b/apps/accounts/backend/src/lib/audit.ts @@ -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); + } +} diff --git a/apps/accounts/backend/src/lib/config.ts b/apps/accounts/backend/src/lib/config.ts new file mode 100644 index 0000000..2f497e5 --- /dev/null +++ b/apps/accounts/backend/src/lib/config.ts @@ -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 = 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), + }; +} diff --git a/apps/accounts/backend/src/lib/crypto.ts b/apps/accounts/backend/src/lib/crypto.ts new file mode 100644 index 0000000..57659ba --- /dev/null +++ b/apps/accounts/backend/src/lib/crypto.ts @@ -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); +} diff --git a/apps/accounts/backend/src/lib/messages.ts b/apps/accounts/backend/src/lib/messages.ts new file mode 100644 index 0000000..4899587 --- /dev/null +++ b/apps/accounts/backend/src/lib/messages.ts @@ -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; + whatsapp(msg: WhatsApp): Promise; + /** Whether WhatsApp is set up, so it's offered as a 2FA method. */ + whatsappReady(): Promise; +} + +/** 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) {} + + 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 { + 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 { + return !!((await this.ctx.settings.get('wawp_access_token')) && (await this.ctx.settings.get('wawp_instance_id'))); + } + + async whatsapp(msg: WhatsApp): Promise { + 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; + } +} diff --git a/apps/accounts/backend/src/lib/passwords.ts b/apps/accounts/backend/src/lib/passwords.ts new file mode 100644 index 0000000..e102cea --- /dev/null +++ b/apps/accounts/backend/src/lib/passwords.ts @@ -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 { + return argon2.hash(password, OPTIONS); +} + +export async function verifyPassword(password: string, hash: string | null | undefined): Promise { + 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 | null = null; +export function dummyHash(): Promise { + 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; +} diff --git a/apps/accounts/backend/src/lib/recoveryCodes.ts b/apps/accounts/backend/src/lib/recoveryCodes.ts new file mode 100644 index 0000000..5d6e7a9 --- /dev/null +++ b/apps/accounts/backend/src/lib/recoveryCodes.ts @@ -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)); diff --git a/apps/accounts/backend/src/lib/settings.ts b/apps/accounts/backend/src/lib/settings.ts new file mode 100644 index 0000000..73c78d9 --- /dev/null +++ b/apps/accounts/backend/src/lib/settings.ts @@ -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(); + + constructor(private readonly ctx: Pick) {} + + async get(key: string): Promise { + 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 { + const v = await this.get(key); + return v === null || v === '' ? fallback : v === 'true'; + } + + async json(key: string, fallback: T): Promise { + 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 { + 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): Promise { + for (const [k, v] of Object.entries(values)) await this.set(k, v); + } + + forget(): void { + this.cache.clear(); + } +} diff --git a/apps/accounts/backend/src/lib/totp.ts b/apps/accounts/backend/src/lib/totp.ts new file mode 100644 index 0000000..ff6a773 --- /dev/null +++ b/apps/accounts/backend/src/lib/totp.ts @@ -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}`; +} diff --git a/apps/accounts/backend/src/links/connect.ts b/apps/accounts/backend/src/links/connect.ts new file mode 100644 index 0000000..f437b70 --- /dev/null +++ b/apps/accounts/backend/src/links/connect.ts @@ -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 { + 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>({ + 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, 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 { + 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, 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>({ + 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>({ 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 { + 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, 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); +} diff --git a/apps/accounts/backend/src/links/deliveries.ts b/apps/accounts/backend/src/links/deliveries.ts new file mode 100644 index 0000000..f5dd372 --- /dev/null +++ b/apps/accounts/backend/src/links/deliveries.ts @@ -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; +const handlers = new Map(); +/** 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 { + 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 }; +} diff --git a/apps/accounts/backend/src/links/http.ts b/apps/accounts/backend/src/links/http.ts new file mode 100644 index 0000000..ede8f04 --- /dev/null +++ b/apps/accounts/backend/src/links/http.ts @@ -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 { + 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 }): Promise { + 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; +} diff --git a/apps/accounts/backend/src/links/store.ts b/apps/accounts/backend/src/links/store.ts new file mode 100644 index 0000000..48bb1a6 --- /dev/null +++ b/apps/accounts/backend/src/links/store.ts @@ -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 { + const list = await ctx.settings.json('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 { + 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 { + return (await linkedProducts(ctx)).find((l) => l.installId === installId) ?? null; +} diff --git a/apps/accounts/backend/src/me/routes.ts b/apps/accounts/backend/src/me/routes.ts new file mode 100644 index 0000000..3479f3e --- /dev/null +++ b/apps/accounts/backend/src/me/routes.ts @@ -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; +} diff --git a/apps/accounts/backend/src/oidc/adapter.ts b/apps/accounts/backend/src/oidc/adapter.ts new file mode 100644 index 0000000..8fee756 --- /dev/null +++ b/apps/accounts/backend/src/oidc/adapter.ts @@ -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 { + 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 { + 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() } } }); +} diff --git a/apps/accounts/backend/src/oidc/clients.ts b/apps/accounts/backend/src/oidc/clients.ts new file mode 100644 index 0000000..0d74fb4 --- /dev/null +++ b/apps/accounts/backend/src/oidc/clients.ts @@ -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 = { 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 { + 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'; +} diff --git a/apps/accounts/backend/src/oidc/pages.ts b/apps/accounts/backend/src/oidc/pages.ts new file mode 100644 index 0000000..514379d --- /dev/null +++ b/apps/accounts/backend/src/oidc/pages.ts @@ -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 { + const b = await branding(ctx).catch(() => ({ name: 'Sign in', colours: { primary: '#1f4e79' }, logoUrl: null })); + return ` +${esc(title)} · ${esc(b.name)} + +
${b.logoUrl ? `` : ''}

${esc(b.name)}

${body}
`; +} + +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', `

We couldn't sign you in

${esc(message)}

Go to your account`); + }; +} + +export function renderLogout(ctx: Ctx) { + return async (k: KoaContextWithOIDC, form: string) => { + k.type = 'html'; + k.body = await page(ctx, 'Signing out', `${form}

Signing you out…

You'll be signed out of all the church's sites.

+ +`); + }; +} + +export function renderLoggedOut(ctx: Ctx) { + return async (k: KoaContextWithOIDC) => { + k.type = 'html'; + k.body = await page(ctx, 'Signed out', '

You\'re signed out

You\'ve been signed out of all the church\'s sites.

Sign in again'); + }; +} + +/** 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();}});'; diff --git a/apps/accounts/backend/src/oidc/provider.ts b/apps/accounts/backend/src/oidc/provider.ts new file mode 100644 index 0000000..963a193 --- /dev/null +++ b/apps/accounts/backend/src/oidc/provider.ts @@ -0,0 +1,133 @@ +/** + * 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 { + const keys = await ctx.settings.json('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 { + const old = await ctx.settings.json('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 { + 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 }, + }, + interactions: { url: (_k, interaction) => `/signin?uid=${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), + rotateRefreshToken: false, + issueRefreshToken: () => false, + }; + const provider = new Provider(issuerOf(ctx), config); + provider.proxy = ctx.config.trustProxy; + return provider; +} diff --git a/apps/accounts/backend/src/oidc/sessions.ts b/apps/accounts/backend/src/oidc/sessions.ts new file mode 100644 index 0000000..96cdb81 --- /dev/null +++ b/apps/accounts/backend/src/oidc/sessions.ts @@ -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 { + 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 }; + +/** 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 { + 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 }).backchannelLogout(accountId, auth.sid ?? ''); + told++; + } + } catch (e) { + console.warn(`[sessions] back-channel logout to ${clientId} failed:`, (e as Error).message); + } + } + await ctx.db.oidcPayload.deleteMany({ where: { id: row.id } }); + } + return told; +} diff --git a/apps/accounts/backend/src/privacy/deletion.ts b/apps/accounts/backend/src/privacy/deletion.ts new file mode 100644 index 0000000..e5a3cfb --- /dev/null +++ b/apps/accounts/backend/src/privacy/deletion.ts @@ -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; + +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 }; +} diff --git a/apps/accounts/backend/src/privacy/export.ts b/apps/accounts/backend/src/privacy/export.ts new file mode 100644 index 0000000..79bc34e --- /dev/null +++ b/apps/accounts/backend/src/privacy/export.ts @@ -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; + +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 }; +} diff --git a/apps/accounts/backend/src/privacy/notice.ts b/apps/accounts/backend/src/privacy/notice.ts new file mode 100644 index 0000000..e359c23 --- /dev/null +++ b/apps/accounts/backend/src/privacy/notice.ts @@ -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 { + 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 } }); +} diff --git a/apps/accounts/backend/src/public/routes.ts b/apps/accounts/backend/src/public/routes.ts new file mode 100644 index 0000000..870f3f4 --- /dev/null +++ b/apps/accounts/backend/src/public/routes.ts @@ -0,0 +1,50 @@ +/** + * 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'; + +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) }))); + + 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; +} diff --git a/apps/accounts/backend/src/setup/routes.ts b/apps/accounts/backend/src/setup/routes.ts new file mode 100644 index 0000000..6a5f1b1 --- /dev/null +++ b/apps/accounts/backend/src/setup/routes.ts @@ -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 { + 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 = {}; + 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; +} diff --git a/apps/accounts/backend/tests/signin.test.ts b/apps/accounts/backend/tests/signin.test.ts new file mode 100644 index 0000000..997429d --- /dev/null +++ b/apps/accounts/backend/tests/signin.test.ts @@ -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); + + 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}`); + 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); + }); +}); diff --git a/apps/accounts/backend/tests/support/harness.ts b/apps/accounts/backend/tests/support/harness.ts new file mode 100644 index 0000000..650de35 --- /dev/null +++ b/apps/accounts/backend/tests/support/harness.ts @@ -0,0 +1,166 @@ +/** + * 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((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 { + private jar = new Map>(); + + private cookieHeader(url: URL) { + const c = this.jar.get(url.host); + return c ? [...c].map(([k, v]) => `${k}=${v}`).join('; ') : ''; + } + + private store(url: URL, res: Response) { + for (const line of res.headers.getSetCookie()) { + const [pair] = line.split(';'); + const i = pair!.indexOf('='); + const name = pair!.slice(0, i).trim(); + const value = pair!.slice(i + 1).trim(); + 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); + } + } + + async request(url: string, init: { method?: string; body?: unknown; form?: Record; origin?: string } = {}) { + const u = new URL(url); + const headers: Record = { 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>; + +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) => 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; + 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 = {}) { + 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 = {}) { + 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')!; + let 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; + return { status: res.status, body: json }; + } + + async function makeAccount(data: Record & { 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 }; +} diff --git a/apps/accounts/backend/tests/support/memoryDb.ts b/apps/accounts/backend/tests/support/memoryDb.ts new file mode 100644 index 0000000..795c3e0 --- /dev/null +++ b/apps/accounts/backend/tests/support/memoryDb.ts @@ -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; + +const DEFAULTS: Record Row> = { + account: () => ({ + givenName: null, familyName: null, emailVerified: false, phone: null, phoneVerified: false, passwordHash: null, role: 'member', status: 'active', + twoFactorMethod: null, totpSecret: null, totpLastStep: null, newsEmail: false, newsWhatsApp: false, newsAskedAt: null, noticeVersionAccepted: 0, + failedSignIns: 0, lockedUntil: null, lastSignInAt: null, deactivatedAt: null, anonymisedAt: null, + }), + 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 = { appSetting: 'key', productLink: 'installId', linkNonce: 'nonce', pendingSignIn: 'uid', privacyNotice: 'version' }; +const UNIQUE: Record = { 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; + 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 = (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>) { + 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> & { tables: Map>; $queryRawUnsafe: () => Promise; $disconnect: () => Promise }; + +export function memoryDb(): MemoryDb { + const tables = new Map>(); + const models = new Map>(); + 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); + }, + }); +} diff --git a/apps/accounts/backend/tsconfig.build.json b/apps/accounts/backend/tsconfig.build.json new file mode 100644 index 0000000..077691c --- /dev/null +++ b/apps/accounts/backend/tsconfig.build.json @@ -0,0 +1,5 @@ +{ + "extends": "./tsconfig.json", + "compilerOptions": { "rootDir": "src", "outDir": "dist" }, + "include": ["src"] +} diff --git a/apps/accounts/backend/tsconfig.json b/apps/accounts/backend/tsconfig.json new file mode 100644 index 0000000..c4d0000 --- /dev/null +++ b/apps/accounts/backend/tsconfig.json @@ -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", "prisma.config.ts"] +} diff --git a/apps/accounts/frontend/package.json b/apps/accounts/frontend/package.json new file mode 100644 index 0000000..67efc1c --- /dev/null +++ b/apps/accounts/frontend/package.json @@ -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" + } +} diff --git a/package-lock.json b/package-lock.json index 1c0ab05..f0bdd08 100644 --- a/package-lock.json +++ b/package-lock.json @@ -11,8 +11,11 @@ "packages/*", "apps/*", "!apps/events", + "!apps/accounts", "apps/events/backend", - "apps/events/frontend" + "apps/events/frontend", + "apps/accounts/backend", + "apps/accounts/frontend" ], "devDependencies": { "@axe-core/playwright": "^4.14.0", @@ -36,7 +39,71 @@ }, "apps/accounts": { "name": "@crosscode/accounts", - "version": "0.0.0" + "version": "0.0.0", + "dev": true, + "optional": true, + "peer": true + }, + "apps/accounts/backend": { + "name": "@crosscode/accounts-backend", + "version": "1.0.0", + "hasInstallScript": true, + "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": { + "@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" + } + }, + "apps/accounts/frontend": { + "name": "@crosscode/accounts-frontend", + "version": "1.0.0", + "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" + } }, "apps/agent": { "name": "@crosscode/agent", @@ -892,8 +959,12 @@ "node": ">=22.0.0" } }, - "node_modules/@crosscode/accounts": { - "resolved": "apps/accounts", + "node_modules/@crosscode/accounts-backend": { + "resolved": "apps/accounts/backend", + "link": true + }, + "node_modules/@crosscode/accounts-frontend": { + "resolved": "apps/accounts/frontend", "link": true }, "node_modules/@crosscode/agent": { @@ -6626,6 +6697,16 @@ "dev": true, "license": "MIT" }, + "node_modules/@types/accepts": { + "version": "1.3.7", + "resolved": "https://registry.npmjs.org/@types/accepts/-/accepts-1.3.7.tgz", + "integrity": "sha512-Pay9fq2lM2wXPWbteBsRAGiWH2hig4ZE2asK+mm7kUzlxRTfL961rj89I6zV/E3PcIkDqyuBEcMxFT7rccugeQ==", + "dev": true, + "license": "MIT", + "dependencies": { + "@types/node": "*" + } + }, "node_modules/@types/babel__core": { "version": "7.20.5", "resolved": "https://registry.npmjs.org/@types/babel__core/-/babel__core-7.20.5.tgz", @@ -6671,6 +6752,13 @@ "@babel/types": "^7.28.2" } }, + "node_modules/@types/bcryptjs": { + "version": "2.4.6", + "resolved": "https://registry.npmjs.org/@types/bcryptjs/-/bcryptjs-2.4.6.tgz", + "integrity": "sha512-9xlo6R2qDs5uixm0bcIqCeMCE6HiQsIyel9KQySStiyqNl2tnj2mP3DX1Nf56MD6KMenNNlBBsy3LJ7gUEQPXQ==", + "dev": true, + "license": "MIT" + }, "node_modules/@types/body-parser": { "version": "1.19.6", "resolved": "https://registry.npmjs.org/@types/body-parser/-/body-parser-1.19.6.tgz", @@ -6692,6 +6780,13 @@ "@types/node": "*" } }, + "node_modules/@types/content-disposition": { + "version": "0.5.9", + "resolved": "https://registry.npmjs.org/@types/content-disposition/-/content-disposition-0.5.9.tgz", + "integrity": "sha512-8uYXI3Gw35MhiVYhG3s295oihrxRyytcRHjSjqnqZVDDy/xcGBRny7+Xj1Wgfhv5QzRtN2hB2dVRBUX9XW3UcQ==", + "dev": true, + "license": "MIT" + }, "node_modules/@types/cookiejar": { "version": "2.1.5", "resolved": "https://registry.npmjs.org/@types/cookiejar/-/cookiejar-2.1.5.tgz", @@ -6699,6 +6794,19 @@ "dev": true, "license": "MIT" }, + "node_modules/@types/cookies": { + "version": "0.9.2", + "resolved": "https://registry.npmjs.org/@types/cookies/-/cookies-0.9.2.tgz", + "integrity": "sha512-1AvkDdZM2dbyFybL4fxpuNCaWyv//0AwsuUk2DWeXyM1/5ZKm6W3z6mQi24RZ4l2ucY+bkSHzbDVpySqPGuV8A==", + "dev": true, + "license": "MIT", + "dependencies": { + "@types/connect": "*", + "@types/express": "*", + "@types/keygrip": "*", + "@types/node": "*" + } + }, "node_modules/@types/d3-array": { "version": "3.0.3", "resolved": "https://registry.npmjs.org/@types/d3-array/-/d3-array-3.0.3.tgz", @@ -6860,6 +6968,13 @@ "@types/unist": "*" } }, + "node_modules/@types/http-assert": { + "version": "1.5.6", + "resolved": "https://registry.npmjs.org/@types/http-assert/-/http-assert-1.5.6.tgz", + "integrity": "sha512-TTEwmtjgVbYAzZYWyeHPrrtWnfVkm8tQkP8P21uQifPgMRgjrow3XDEYqucuC8SKZJT7pUnhU/JymvjggxO9vw==", + "dev": true, + "license": "MIT" + }, "node_modules/@types/http-errors": { "version": "2.0.5", "resolved": "https://registry.npmjs.org/@types/http-errors/-/http-errors-2.0.5.tgz", @@ -6929,6 +7044,40 @@ "@types/node": "*" } }, + "node_modules/@types/keygrip": { + "version": "1.0.6", + "resolved": "https://registry.npmjs.org/@types/keygrip/-/keygrip-1.0.6.tgz", + "integrity": "sha512-lZuNAY9xeJt7Bx4t4dx0rYCDqGPW8RXhQZK1td7d4H6E9zYbLoOtjBvfwdTKpsyxQI/2jv+armjX/RW+ZNpXOQ==", + "dev": true, + "license": "MIT" + }, + "node_modules/@types/koa": { + "version": "3.0.3", + "resolved": "https://registry.npmjs.org/@types/koa/-/koa-3.0.3.tgz", + "integrity": "sha512-TdtNEJ7sYSrFQcVuS2ySsVqnq5EyE3oJbnfFJvkC9UtGP4Kpem5KE7r+ivHIbIAQAofSqnlB5D3vkfYO69TQpg==", + "dev": true, + "license": "MIT", + "dependencies": { + "@types/accepts": "*", + "@types/content-disposition": "*", + "@types/cookies": "*", + "@types/http-assert": "*", + "@types/http-errors": "^2", + "@types/keygrip": "*", + "@types/koa-compose": "*", + "@types/node": "*" + } + }, + "node_modules/@types/koa-compose": { + "version": "3.2.9", + "resolved": "https://registry.npmjs.org/@types/koa-compose/-/koa-compose-3.2.9.tgz", + "integrity": "sha512-BroAZ9FTvPiCy0Pi8tjD1OfJ7bgU1gQf0eR6e1Vm+JJATy9eKOG3hQMFtMciMawiSOVnLMdmUOC46s7HBhSTsA==", + "dev": true, + "license": "MIT", + "dependencies": { + "@types/koa": "*" + } + }, "node_modules/@types/lodash": { "version": "4.17.27", "resolved": "https://registry.npmjs.org/@types/lodash/-/lodash-4.17.27.tgz", @@ -6967,6 +7116,28 @@ "undici-types": "~6.21.0" } }, + "node_modules/@types/nodemailer": { + "version": "6.4.24", + "resolved": "https://registry.npmjs.org/@types/nodemailer/-/nodemailer-6.4.24.tgz", + "integrity": "sha512-Ww4u0rT9wQNXh4JiQaIwx3QWdcOFXzOjQA2zc+jtFYNmQiT4mIUqcDin51bDFdkzKubFnQCZNK7FIHlPKQ/q9w==", + "dev": true, + "license": "MIT", + "dependencies": { + "@types/node": "*" + } + }, + "node_modules/@types/oidc-provider": { + "version": "9.13.1", + "resolved": "https://registry.npmjs.org/@types/oidc-provider/-/oidc-provider-9.13.1.tgz", + "integrity": "sha512-RZqzlnjeU1py4ujgP3Q5eZkcGQyyCj4Dt2x8B9rw0QP2u1L4f3xnH8Buj2JyOrbCAdRa2QM6ylmW2TupemjpUQ==", + "dev": true, + "license": "MIT", + "dependencies": { + "@types/keygrip": "*", + "@types/koa": "*", + "@types/node": "*" + } + }, "node_modules/@types/pg": { "version": "8.23.1", "resolved": "https://registry.npmjs.org/@types/pg/-/pg-8.23.1.tgz", @@ -9753,6 +9924,19 @@ "dev": true, "license": "MIT" }, + "node_modules/cookies": { + "version": "0.9.2", + "resolved": "https://registry.npmjs.org/cookies/-/cookies-0.9.2.tgz", + "integrity": "sha512-8BIbcC6tPZMv2/PD4PrB3CtKks7LmAWhA7FRZK/6/b/WJ2RUz00KCga7gq50S4/RhZ22kxefRFGgsuts0v3eoA==", + "license": "MIT", + "dependencies": { + "depd": "~2.0.0", + "keygrip": "~1.1.0" + }, + "engines": { + "node": ">= 0.8" + } + }, "node_modules/core-util-is": { "version": "1.0.3", "resolved": "https://registry.npmjs.org/core-util-is/-/core-util-is-1.0.3.tgz", @@ -10302,6 +10486,12 @@ } } }, + "node_modules/deep-equal": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/deep-equal/-/deep-equal-1.0.1.tgz", + "integrity": "sha512-bHtC0iYvWhyaTzvV3CZgPeZQqCOBGyGsVV7v4eevpdkLHfiSrXUdBG+qAuSz4RI70sszvjQ1QSZ98An1yNwpSw==", + "license": "MIT" + }, "node_modules/deep-is": { "version": "0.1.4", "resolved": "https://registry.npmjs.org/deep-is/-/deep-is-0.1.4.tgz", @@ -10401,6 +10591,12 @@ "node": ">=0.4.0" } }, + "node_modules/delegates": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/delegates/-/delegates-1.0.0.tgz", + "integrity": "sha512-bd2L678uiWATM6m5Z1VzNCErI3jiGzt6HGY8OVICs40JQq/HALfbyNJmp0UDakEY4pMMaN0Ly5om/B1VI/+xfQ==", + "license": "MIT" + }, "node_modules/depd": { "version": "2.0.0", "resolved": "https://registry.npmjs.org/depd/-/depd-2.0.0.tgz", @@ -10426,6 +10622,16 @@ "devOptional": true, "license": "MIT" }, + "node_modules/destroy": { + "version": "1.2.0", + "resolved": "https://registry.npmjs.org/destroy/-/destroy-1.2.0.tgz", + "integrity": "sha512-2sJGJTaXIIaR1w4iJSNoN0hnMY7Gpc/n8D4qSCJw8QqFWXf7cuAgnEHxBpweaVcPevC2l3KpjYCx3NypQQgaJg==", + "license": "MIT", + "engines": { + "node": ">= 0.8", + "npm": "1.2.8000 || >= 1.4.16" + } + }, "node_modules/detect-libc": { "version": "2.1.2", "resolved": "https://registry.npmjs.org/detect-libc/-/detect-libc-2.1.2.tgz", @@ -12667,6 +12873,53 @@ "url": "https://opencollective.com/unified" } }, + "node_modules/http-assert": { + "version": "1.5.0", + "resolved": "https://registry.npmjs.org/http-assert/-/http-assert-1.5.0.tgz", + "integrity": "sha512-uPpH7OKX4H25hBmU6G1jWNaqJGpTXxey+YOUizJUAgu0AjLUeC8D73hTrhvDS5D+GJN1DN1+hhc/eF/wpxtp0w==", + "license": "MIT", + "dependencies": { + "deep-equal": "~1.0.1", + "http-errors": "~1.8.0" + }, + "engines": { + "node": ">= 0.8" + } + }, + "node_modules/http-assert/node_modules/depd": { + "version": "1.1.2", + "resolved": "https://registry.npmjs.org/depd/-/depd-1.1.2.tgz", + "integrity": "sha512-7emPTl6Dpo6JRXOXjLRxck+FlLRX5847cLKEn00PLAgc3g2hTZZgr+e4c2v6QpSmLeFP3n5yUo7ft6avBK/5jQ==", + "license": "MIT", + "engines": { + "node": ">= 0.6" + } + }, + "node_modules/http-assert/node_modules/http-errors": { + "version": "1.8.1", + "resolved": "https://registry.npmjs.org/http-errors/-/http-errors-1.8.1.tgz", + "integrity": "sha512-Kpk9Sm7NmI+RHhnj6OIWDI1d6fIoFAtFt9RLaTMRlg/8w49juAStsrBgp0Dp4OdxdVbRIeKhtCUvoi/RuAhO4g==", + "license": "MIT", + "dependencies": { + "depd": "~1.1.2", + "inherits": "2.0.4", + "setprototypeof": "1.2.0", + "statuses": ">= 1.5.0 < 2", + "toidentifier": "1.0.1" + }, + "engines": { + "node": ">= 0.6" + } + }, + "node_modules/http-assert/node_modules/statuses": { + "version": "1.5.0", + "resolved": "https://registry.npmjs.org/statuses/-/statuses-1.5.0.tgz", + "integrity": "sha512-OpZ3zP+jT1PI7I8nemJX4AKmAX070ZkYPVWV/AaKTJl+tXCTGyVdC1a4SL8RUQYEwk/f34ZX8UTykN68FwrqAA==", + "license": "MIT", + "engines": { + "node": ">= 0.6" + } + }, "node_modules/http-errors": { "version": "2.0.1", "resolved": "https://registry.npmjs.org/http-errors/-/http-errors-2.0.1.tgz", @@ -14198,6 +14451,15 @@ "jiti": "lib/jiti-cli.mjs" } }, + "node_modules/jose": { + "version": "6.2.17", + "resolved": "https://registry.npmjs.org/jose/-/jose-6.2.17.tgz", + "integrity": "sha512-wOuK9V1yujQFH5S0ZWmLcDZN7+IKh9bUCC2ZPCf2HDlol3WWHy+PPyNjEI75FXRLMp3vDKQcupP59xhVU95hcg==", + "license": "MIT", + "funding": { + "url": "https://github.com/sponsors/panva" + } + }, "node_modules/joycon": { "version": "3.1.1", "resolved": "https://registry.npmjs.org/joycon/-/joycon-3.1.1.tgz", @@ -14368,6 +14630,18 @@ "safe-buffer": "^5.0.1" } }, + "node_modules/keygrip": { + "version": "1.1.0", + "resolved": "https://registry.npmjs.org/keygrip/-/keygrip-1.1.0.tgz", + "integrity": "sha512-iYSchDJ+liQ8iwbSI2QqsQOvqv58eJCEanyJPJi+Khyu8smkcKSFUCbPwzFcL7YVtZ6eONjqRX/38caJ7QjRAQ==", + "license": "MIT", + "dependencies": { + "tsscmp": "1.0.6" + }, + "engines": { + "node": ">= 0.6" + } + }, "node_modules/keyv": { "version": "5.6.0", "resolved": "https://registry.npmjs.org/keyv/-/keyv-5.6.0.tgz", @@ -14378,6 +14652,115 @@ "@keyv/serialize": "^1.1.1" } }, + "node_modules/koa": { + "version": "3.3.0", + "resolved": "https://registry.npmjs.org/koa/-/koa-3.3.0.tgz", + "integrity": "sha512-NdsWJYxVzUuYt718DtEQRhUXqqsAPA4VlaUGrlidjh/T2TP/4OQXqQg4ouUHfHD9f+tgmwLZWPm+JQLgqM9YbA==", + "license": "MIT", + "dependencies": { + "accepts": "^1.3.8", + "content-disposition": "~1.0.1", + "content-type": "^1.0.5", + "cookies": "~0.9.1", + "delegates": "^1.0.0", + "destroy": "^1.2.0", + "encodeurl": "^2.0.0", + "escape-html": "^1.0.3", + "fresh": "~0.5.2", + "http-assert": "^1.5.0", + "http-errors": "^2.0.0", + "koa-compose": "^4.1.0", + "mime-types": "^3.0.1", + "on-finished": "^2.4.1", + "parseurl": "^1.3.3", + "statuses": "^2.0.1", + "type-is": "^2.0.1", + "vary": "^1.1.2" + }, + "engines": { + "node": ">= 18" + } + }, + "node_modules/koa-compose": { + "version": "4.1.0", + "resolved": "https://registry.npmjs.org/koa-compose/-/koa-compose-4.1.0.tgz", + "integrity": "sha512-8ODW8TrDuMYvXRwra/Kh7/rJo9BtOfPc6qO8eAfC80CnCvSjSl0bkRM24X6/XBBEyj0v1nRUQ1LyOy3dbqOWXw==", + "license": "MIT" + }, + "node_modules/koa/node_modules/accepts": { + "version": "1.3.8", + "resolved": "https://registry.npmjs.org/accepts/-/accepts-1.3.8.tgz", + "integrity": "sha512-PYAthTa2m2VKxuvSD3DPC/Gy+U+sOA1LAuT8mkmRuvw+NACSaeXEQ+NHcVF7rONl6qcaxV3Uuemwawk+7+SJLw==", + "license": "MIT", + "dependencies": { + "mime-types": "~2.1.34", + "negotiator": "0.6.3" + }, + "engines": { + "node": ">= 0.6" + } + }, + "node_modules/koa/node_modules/accepts/node_modules/mime-types": { + "version": "2.1.35", + "resolved": "https://registry.npmjs.org/mime-types/-/mime-types-2.1.35.tgz", + "integrity": "sha512-ZDY+bPm5zTTF+YpCrAU9nK0UgICYPT0QtT1NZWFv4s++TNkcgVaT0g6+4R2uI4MjQjzysHB1zxuWL50hzaeXiw==", + "license": "MIT", + "dependencies": { + "mime-db": "1.52.0" + }, + "engines": { + "node": ">= 0.6" + } + }, + "node_modules/koa/node_modules/content-disposition": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/content-disposition/-/content-disposition-1.0.1.tgz", + "integrity": "sha512-oIXISMynqSqm241k6kcQ5UwttDILMK4BiurCfGEREw6+X9jkkpEe5T9FZaApyLGGOnFuyMWZpdolTXMtvEJ08Q==", + "license": "MIT", + "engines": { + "node": ">=18" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/express" + } + }, + "node_modules/koa/node_modules/content-type": { + "version": "1.0.5", + "resolved": "https://registry.npmjs.org/content-type/-/content-type-1.0.5.tgz", + "integrity": "sha512-nTjqfcBFEipKdXCv4YDQWCfmcLZKm81ldF0pAopTvyrFGVbcR6P/VAAd5G7N+0tTr8QqiU0tFadD6FK4NtJwOA==", + "license": "MIT", + "engines": { + "node": ">= 0.6" + } + }, + "node_modules/koa/node_modules/fresh": { + "version": "0.5.2", + "resolved": "https://registry.npmjs.org/fresh/-/fresh-0.5.2.tgz", + "integrity": "sha512-zJ2mQYM18rEFOudeV4GShTGIQ7RbzA7ozbU9I/XBpm7kqgMywgmylMwXHxZJmkVoYkna9d2pVXVXPdYTP9ej8Q==", + "license": "MIT", + "engines": { + "node": ">= 0.6" + } + }, + "node_modules/koa/node_modules/mime-db": { + "version": "1.52.0", + "resolved": "https://registry.npmjs.org/mime-db/-/mime-db-1.52.0.tgz", + "integrity": "sha512-sPU4uV7dYlvtWJxwwxHD0PuihVNiE7TyAbQ5SWxDCB9mUYvOgroQOwYQQOKPJ8CIbE+1ETVlOoK1UC2nU3gYvg==", + "license": "MIT", + "engines": { + "node": ">= 0.6" + } + }, + "node_modules/koa/node_modules/negotiator": { + "version": "0.6.3", + "resolved": "https://registry.npmjs.org/negotiator/-/negotiator-0.6.3.tgz", + "integrity": "sha512-+EUsqGPLsM+j/zdChZjsnX51g4XrHFOIXwfnCVPGlQk/k5giakcKsuxCObBRu6DSm9opw/O6slWbJdghQM4bBg==", + "license": "MIT", + "engines": { + "node": ">= 0.6" + } + }, "node_modules/language-subtag-registry": { "version": "0.3.23", "resolved": "https://registry.npmjs.org/language-subtag-registry/-/language-subtag-registry-0.3.23.tgz", @@ -15910,6 +16293,16 @@ "node": ">=8" } }, + "node_modules/oauth4webapi": { + "version": "3.8.8", + "resolved": "https://registry.npmjs.org/oauth4webapi/-/oauth4webapi-3.8.8.tgz", + "integrity": "sha512-8N28E+a/oxfXWBgOMt+ZP/JUf/XR+IFbvkAEPP3gznXOMv9BpAAwiIj0TFNz3tGTPc0ZQ8zmWBNgN1nAys0gng==", + "dev": true, + "license": "MIT", + "funding": { + "url": "https://github.com/sponsors/panva" + } + }, "node_modules/object-assign": { "version": "4.1.1", "resolved": "https://registry.npmjs.org/object-assign/-/object-assign-4.1.1.tgz", @@ -16061,6 +16454,20 @@ "devOptional": true, "license": "MIT" }, + "node_modules/oidc-provider": { + "version": "9.13.3", + "resolved": "https://registry.npmjs.org/oidc-provider/-/oidc-provider-9.13.3.tgz", + "integrity": "sha512-WmNDX9dLeItBmIqGqspmX5u6Cc7VVMrKUw2InX2T16+bwUJ8m/N5rJ3Ed+YKxE5aZqLp4YqwEi6kMJx4Ui5ffw==", + "license": "MIT", + "dependencies": { + "debug": "^4.4.3", + "jose": "^6.2.13", + "koa": "^3.2.1" + }, + "funding": { + "url": "https://github.com/sponsors/panva" + } + }, "node_modules/on-finished": { "version": "2.4.2", "resolved": "https://registry.npmjs.org/on-finished/-/on-finished-2.4.2.tgz", @@ -16167,6 +16574,20 @@ "url": "https://github.com/sponsors/sindresorhus" } }, + "node_modules/openid-client": { + "version": "6.8.9", + "resolved": "https://registry.npmjs.org/openid-client/-/openid-client-6.8.9.tgz", + "integrity": "sha512-6mXMRNJxDOf6BflEWLXul1UwzLFz++9Ofz1PYwPwwsJsyXBsbfkO+Jo255SW1qnFNLYz4EJWHz42X4OJJrya/g==", + "dev": true, + "license": "MIT", + "dependencies": { + "jose": "^6.2.15", + "oauth4webapi": "^3.8.8" + }, + "funding": { + "url": "https://github.com/sponsors/panva" + } + }, "node_modules/optionator": { "version": "0.9.4", "resolved": "https://registry.npmjs.org/optionator/-/optionator-0.9.4.tgz", @@ -19748,6 +20169,15 @@ "integrity": "sha512-a4Ux9VKuIMHsOS7ENbEq6hK2ZGYIT27Rtl0E4eD9KqwxhKiQeMZE/9xb3IdYwWaSOyIBQLExhQgXDTYoiCxnWA==", "license": "0BSD" }, + "node_modules/tsscmp": { + "version": "1.0.6", + "resolved": "https://registry.npmjs.org/tsscmp/-/tsscmp-1.0.6.tgz", + "integrity": "sha512-LxhtAkPDTkVCMQjt2h6eBVY28KCjikZqZfMcC15YBeNjkgUpdCfBu5HoiOTDu86v6smE8yOjyEktJ8hlbANHQA==", + "license": "MIT", + "engines": { + "node": ">=0.6.x" + } + }, "node_modules/tsup": { "version": "9.0.0", "resolved": "https://registry.npmjs.org/tsup/-/tsup-9.0.0.tgz", @@ -20833,7 +21263,7 @@ }, "packages/contracts": { "name": "@crosscode/contracts", - "version": "1.4.0", + "version": "1.5.0", "license": "UNLICENSED", "dependencies": { "zod": "^4.6.7" diff --git a/package.json b/package.json index 8be20d1..71ee06f 100644 --- a/package.json +++ b/package.json @@ -7,8 +7,11 @@ "packages/*", "apps/*", "!apps/events", + "!apps/accounts", "apps/events/backend", - "apps/events/frontend" + "apps/events/frontend", + "apps/accounts/backend", + "apps/accounts/frontend" ], "scripts": { "build": "npm run build --workspaces --if-present", diff --git a/packages/contracts/src/church.ts b/packages/contracts/src/church.ts index 5c7791e..9712bbe 100644 --- a/packages/contracts/src/church.ts +++ b/packages/contracts/src/church.ts @@ -47,7 +47,8 @@ export const serviceTimeSchema = z.object({ note: z.string().trim().max(300).nullable(), }); -export const churchSchema = z +/** The profile's fields without the cross-field checks, for building forms that edit part of it (contracts 1.5.0). */ +export const churchObjectSchema = z .object({ schema: z.literal(CHURCH_SCHEMA), /** The Hub customer id: the same for every product of the church. */ @@ -85,8 +86,9 @@ export const churchSchema = z app: urlSchema.nullable(), accounts: urlSchema, }), - }) - .superRefine((church, ctx) => { + }); + +export const churchSchema = churchObjectSchema.superRefine((church, ctx) => { const slugs = new Set(church.campuses.map((c) => c.slug)); if (slugs.size !== church.campuses.length) ctx.addIssue({ code: "custom", path: ["campuses"], message: "Campus slugs must be unique" }); church.serviceTimes.forEach((s, i) => {