From 2bffb1b8a1a67dc68b0083e24b892af0e3e1bf49 Mon Sep 17 00:00:00 2001 From: Claude Date: Wed, 28 Oct 2026 19:39:20 +0000 Subject: [PATCH] feat(cms): account pages in the Payload admin (PX2) The account pages of the old console move into the Payload admin, as views behind the Lumen sign-in: Profile (/admin/account), Security (/admin/account/security), Organization (/admin/organization) and Notifications (/admin/organization/notifications), linked from the admin nav. Each reads and writes the signed-in Lumen account through api-edge with the session cookie's bearer; a profile name change is also written to the `users` row. - forms post to same-origin routes (/lumen/profile, /lumen/notifications) and land back on their page with a status; no client-side token - session lookups are shared per token, and a session api-edge confirmed in the last 5 minutes survives api-edge being unable to answer, until it expires - the admin cannot be framed by another origin (frame-ancestors 'self') - identity-worker: security events take the user's UUID, not the public usr_ id, which made the endpoint answer 503 for everyone - api-edge: a bearer's own session, profile and security-events reads get an `account` rate family (60/min); sign-in stays on `auth` (10/min) - docs: runbook, architecture, overview, operations guide; epic status Orun-Task: PX-3 Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_013JuHbkZCjDrGgHdzCrCRqG --- ai/context/operations.md | 5 + apps/api-edge/src/auth-facade.ts | 16 +- apps/api-edge/src/rate-limit.ts | 11 ++ apps/cms/docs/architecture.md | 27 +++- apps/cms/docs/overview.md | 7 +- apps/cms/docs/runbook.md | 27 +++- apps/cms/next.config.ts | 14 ++ apps/cms/package.json | 1 + apps/cms/src/app/(payload)/admin/importMap.js | 10 ++ .../app/(site)/lumen/notifications/route.ts | 9 ++ .../cms/src/app/(site)/lumen/profile/route.ts | 9 ++ .../components/admin/account/AccountNav.tsx | 39 +++++ .../components/admin/account/AccountPage.tsx | 92 +++++++++++ .../admin/account/NotificationsView.tsx | 59 +++++++ .../admin/account/OrganizationView.tsx | 54 +++++++ .../components/admin/account/ProfileView.tsx | 75 +++++++++ .../components/admin/account/SecurityView.tsx | 69 ++++++++ apps/cms/src/lib/access.ts | 3 + apps/cms/src/lib/lumen/account-api.ts | 81 ++++++++++ apps/cms/src/lib/lumen/client.ts | 6 +- apps/cms/src/lib/lumen/form-deps.ts | 20 +++ apps/cms/src/lib/lumen/forms.ts | 105 ++++++++++++ apps/cms/src/lib/lumen/models/preferences.ts | 60 +++++++ apps/cms/src/lib/lumen/models/profile.ts | 65 ++++++++ .../src/lib/lumen/models/security-events.ts | 149 ++++++++++++++++++ apps/cms/src/lib/lumen/session.ts | 57 +++++-- apps/cms/src/lib/lumen/status.ts | 28 ++++ apps/cms/src/payload.config.ts | 12 ++ .../src/handlers/security-events.ts | 9 +- pnpm-lock.yaml | 6 + .../IMPLEMENTATION-STATUS.md | 27 +++- tasks/PX-3.TaskContract.yaml | 26 +++ tests/api-edge/src/rate-limit.test.ts | 27 +++- tests/cms/docs/overview.md | 5 +- tests/cms/package.json | 1 + tests/cms/src/lumen-account-api.test.ts | 61 +++++++ tests/cms/src/lumen-forms.test.ts | 120 ++++++++++++++ tests/cms/src/lumen-model-preferences.test.ts | 48 ++++++ tests/cms/src/lumen-model-profile.test.ts | 53 +++++++ .../src/lumen-model-security-events.test.ts | 148 +++++++++++++++++ tests/cms/src/lumen-session.test.ts | 40 ++++- .../src/security-events.test.ts | 32 +++- 42 files changed, 1682 insertions(+), 31 deletions(-) create mode 100644 apps/cms/src/app/(site)/lumen/notifications/route.ts create mode 100644 apps/cms/src/app/(site)/lumen/profile/route.ts create mode 100644 apps/cms/src/components/admin/account/AccountNav.tsx create mode 100644 apps/cms/src/components/admin/account/AccountPage.tsx create mode 100644 apps/cms/src/components/admin/account/NotificationsView.tsx create mode 100644 apps/cms/src/components/admin/account/OrganizationView.tsx create mode 100644 apps/cms/src/components/admin/account/ProfileView.tsx create mode 100644 apps/cms/src/components/admin/account/SecurityView.tsx create mode 100644 apps/cms/src/lib/lumen/account-api.ts create mode 100644 apps/cms/src/lib/lumen/form-deps.ts create mode 100644 apps/cms/src/lib/lumen/forms.ts create mode 100644 apps/cms/src/lib/lumen/models/preferences.ts create mode 100644 apps/cms/src/lib/lumen/models/profile.ts create mode 100644 apps/cms/src/lib/lumen/models/security-events.ts create mode 100644 apps/cms/src/lib/lumen/status.ts create mode 100644 tasks/PX-3.TaskContract.yaml create mode 100644 tests/cms/src/lumen-account-api.test.ts create mode 100644 tests/cms/src/lumen-forms.test.ts create mode 100644 tests/cms/src/lumen-model-preferences.test.ts create mode 100644 tests/cms/src/lumen-model-profile.test.ts create mode 100644 tests/cms/src/lumen-model-security-events.test.ts diff --git a/ai/context/operations.md b/ai/context/operations.md index 7cc900e..9fd65e5 100644 --- a/ai/context/operations.md +++ b/ai/context/operations.md @@ -164,6 +164,11 @@ it through `api-edge`, and no worker calls it. served at `/api/media/file/`. SVG is refused. The bucket component runs with `CLOUDFLARE_R2_TOKEN` (project rung, from the Cloudflare connection's `r2-data` template, rotated by the platform every 30 days). +- **Sign-in and account:** the admin signs in with a Lumen account (no CMS + passwords; a new account is pending until an admin gives it a role, and + admins invite people by creating a user with their email). Its *Account* + nav group holds the Lumen account pages: Profile, Security activity, + Organization and Notifications. - **Secrets:** `CMS_PAYLOAD_SECRET` is generated and published by `cloudflare-hyperdrive-cms` (nobody chooses or sees it) and pushed to the Worker as `PAYLOAD_SECRET`. `CMS_SETUP_TOKEN` exists only if the owner sets diff --git a/apps/api-edge/src/auth-facade.ts b/apps/api-edge/src/auth-facade.ts index 654359c..0b6e9a7 100644 --- a/apps/api-edge/src/auth-facade.ts +++ b/apps/api-edge/src/auth-facade.ts @@ -2,6 +2,7 @@ import type { Env } from "./env"; import { errorResponse } from "./http"; import { replayOrExecute } from "./idempotency"; import { cacheApiStore, bearerToken } from "./actor-cache"; +import type { RouteFamily } from "./rate-limit"; const LOGOUT_PATH = "/v1/auth/logout"; @@ -44,6 +45,19 @@ const FORWARDED_HEADERS = [ "cookie", ]; +/** Routes a signed-in person uses for their own account: rate-limited as `account`, not `auth`. */ +const ACCOUNT_ROUTES = new Set(["/v1/auth/session", "/v1/auth/profile", "/v1/auth/security-events"]); + +/** + * The rate-limit family of an auth route: `account` for a bearer reading its + * own session, profile or security events (or saving its profile), `auth` + * for everything else — sign-in, OAuth, logout and anonymous calls. + */ +export function authRouteFamily(request: Request, pathname: string): RouteFamily { + if (!ACCOUNT_ROUTES.has(pathname)) return "auth"; + return bearerToken(request.headers.get("authorization")) ? "account" : "auth"; +} + export function isAuthRoute(pathname: string): boolean { return pathname in AUTH_ROUTES || pathname in AUTH_MULTI_METHOD_ROUTES || isOAuthRoute(pathname); } @@ -72,7 +86,7 @@ export async function handleAuthRoute( return errorResponse("unsupported", "Method not allowed", 405, requestId); } - return replayOrExecute(request, requestId, env, "auth", async () => { + return replayOrExecute(request, requestId, env, authRouteFamily(request, pathname), async () => { if (!env.IDENTITY_WORKER) { return errorResponse( "internal_error", diff --git a/apps/api-edge/src/rate-limit.ts b/apps/api-edge/src/rate-limit.ts index d6fc39e..f7a22de 100644 --- a/apps/api-edge/src/rate-limit.ts +++ b/apps/api-edge/src/rate-limit.ts @@ -49,6 +49,7 @@ import type { Env } from "./env.js"; export type RouteFamily = | "auth" + | "account" | "org" | "project" | "config" @@ -76,6 +77,12 @@ interface FamilyConfig { * blunting abuse. Tunable; no per-tenant overrides yet (B5 territory). * * - `auth`: tighter — login/logout flows are the brute-force target. + * - `account`: a signed-in person reading their own session, profile and + * security events (and saving their profile). The bucket is keyed on the + * bearer itself, so the tight `auth` cap never slowed token guessing — + * every guess gets a fresh bucket — and it only throttled a real session; + * the Payload admin re-checks its session and reads the profile on page + * loads (lumen-payload-console PX2). * - everything else (writes/reads): 60/300 per minute identity/org. * - `audit` is read-only and trusted further; raised to 120/600. */ @@ -84,6 +91,10 @@ const LIMITS: Record = { identity: { limit: 10, windowSec: 60 }, org: { limit: 60, windowSec: 60 }, }, + account: { + identity: { limit: 60, windowSec: 60 }, + org: { limit: 300, windowSec: 60 }, + }, org: { identity: { limit: 60, windowSec: 60 }, org: { limit: 300, windowSec: 60 }, diff --git a/apps/cms/docs/architecture.md b/apps/cms/docs/architecture.md index 1bc6e37..fcedc74 100644 --- a/apps/cms/docs/architecture.md +++ b/apps/cms/docs/architecture.md @@ -15,8 +15,11 @@ browser ──► lumen-payload-cms- (Worker) /api/media/file/* uploaded files └──────► R2_MEDIA ─► lumen-payload-cms-media- /setup opens first-admin setup (owner only) /auth/lumen/* the Lumen session in, out, and the OAuth return + /admin/account… the Lumen account pages (custom admin views) + /lumen/* their forms │ - lumen strategy ──┴──► LUMEN_API (service binding) ─► api-edge ─► identity + lumen strategy, account pages ──► LUMEN_API (service binding) ─► api-edge ─► identity, + membership, notifications ``` ## Bindings and secrets @@ -61,19 +64,34 @@ browser ──► lumen-payload-cms- (Worker) there are no CMS passwords, and `login`, `first-register` and password reset answer 403. The `lumen` strategy reads the `lumen_session` cookie, asks api-edge `GET /v1/auth/session` over the service binding (answers cached - 30 s per token, keyed by its hash; failures are not cached), and finds, + 30 s per token, keyed by its hash; concurrent requests share one lookup; + when api-edge cannot answer, a session it confirmed in the last 5 minutes + still stands until it expires, and an unconfirmed one fails closed), and finds, links (by email) or creates the `users` row by `lumenUserId`. The token stays in the HttpOnly cookie: it is never on `req.user`, so the admin's browser code never sees it. A request that names another origin gets no user, so no other page can write through the API with the cookie, not even a sibling Worker on the same workers.dev site, which SameSite does not separate. This stands in for Payload's `csrf` allowlist, which applies only to Payload's - own cookie and is off with it. `/auth/lumen/session` takes a token only from + own cookie and is off with it. Every response also carries + `frame-ancestors 'self'` (and `X-Frame-Options: SAMEORIGIN`), so no other + page can frame the admin and click through it. `/auth/lumen/session` takes a token only from a same-origin form post. - **Roles stay Payload's.** A new row has no role: pending, which the admin's `unauthorized` view tells them. The first admin needs the owner's setup token (`src/lib/setup-gate.ts`, `src/app/setup/route.ts`): while no admin exists, the account that signs in with it becomes admin. Admins grant the rest. +- **The account pages are admin views over api-edge** (`src/components/admin/account/`, + `src/lib/lumen/account-api.ts`, `src/lib/lumen/forms.ts`; design §4). + Payload's `account` view is replaced, so Payload still keeps pending + accounts out of it; the other three are custom views, which Payload does not + guard, so each checks for a staff role itself and brings Payload's default + template. They read per request, uncached, with the person's own token, and + render on the server: the browser never calls api-edge for them. Forms post + to `/lumen/*` route handlers that accept only a same-origin post from staff + and answer `303` back to the page. The console's framework-free models + (`src/lib/lumen/models/`) are copied, not shared: the console is retired in + PX4. - **Pinned versions.** Payload 3.89.0 hashes passwords with 25,000 PBKDF2 iterations; 3.90.0 hard-codes 600,000, which workerd rejects. Next 16.3.3, React 19.2.6, OpenNext 1.20.1 and wrangler 4.116 are the combination Payload's @@ -85,7 +103,6 @@ browser ──► lumen-payload-cms- (Worker) ## Out of scope here -Lumen's account pages in the admin (PX2, PX3), the console URL opening the -admin (PX4), serving content through `api-edge`, per-tenant content, and image derivatives: resizing, cropping and focal +Billing and plan in the admin (PX3), the console URL opening the admin (PX4), serving content through `api-edge`, per-tenant content, and image derivatives: resizing, cropping and focal points need `sharp`, which does not run on Workers, so files are stored and served as uploaded. diff --git a/apps/cms/docs/overview.md b/apps/cms/docs/overview.md index aa30d87..700c011 100644 --- a/apps/cms/docs/overview.md +++ b/apps/cms/docs/overview.md @@ -27,6 +27,10 @@ Published pages, posts and categories, and all media, are readable by anyone through the API. Drafts, accounts and everything else need a staff session. Staff upload media; only admins delete it. +The admin also has the person's **Lumen account pages** (Profile, Security +activity, Organization, Notifications), read from and saved to Lumen through +`api-edge`; nothing of them is stored in the CMS but the display name. + ## Depends on - **cloudflare-hyperdrive-cms**: its database path (cache disabled) and its @@ -35,7 +39,8 @@ Staff upload media; only admins delete it. - **db-migrate**: applies schema `cms` (migrations `200_cms_payload_core`, `205_cms_media` and `206_cms_lumen_identity`) before the CMS deploys. - **api-edge**: the CMS asks it, over a service binding, whose Lumen session a - request carries, and ends the session on sign-out. Its CORS lets the CMS's + request carries, ends the session on sign-out, and reads and changes the + account pages' data with the person's session. Its CORS lets the CMS's sign-in page call the auth routes, and identity-worker's OAuth return allowlist includes the CMS. diff --git a/apps/cms/docs/runbook.md b/apps/cms/docs/runbook.md index 4ddec93..46511da 100644 --- a/apps/cms/docs/runbook.md +++ b/apps/cms/docs/runbook.md @@ -23,8 +23,27 @@ a `users` row by `lumenUserId`, creating the row the first time. A new row has **no role**, which means *pending*: the person is signed in but sees "Waiting for access" until an admin opens *Users* and makes them an `editor` or `admin`. A row an admin created beforehand with the same email -(an invitation) is linked on that person's first sign-in and keeps its role. -Signing out (the admin's log-out button) revokes the Lumen session too. +(an invitation) is linked on that person's first sign-in and keeps its role: +to invite someone, open *Users → Create new*, enter their email and pick a +role. Signing out (the admin's log-out button) revokes the Lumen session too. + +## Your account + +The admin's nav has an **Account** group: the same Lumen account pages the +console had, for admins and editors (a pending account sees none of them). +Each page reads Lumen through `api-edge` with the person's own session when it +loads; forms post to `/lumen/*` on the CMS, which calls `api-edge` and comes +back to the page with *Saved.* or what went wrong. + +| Page | Path | Shows | Changes | +|---|---|---|---| +| Profile | `/admin/account` (Payload's account page, replaced) | email, CMS role, Lumen user id | display name (copied onto the `users` row) | +| Security activity | `/admin/account/security` | sign-ins, codes and sessions, newest first, 50 a page | — | +| Organization | `/admin/organization` | the Lumen organization (Solo: the personal one) | — (renaming is not in the API) | +| Notifications | `/admin/organization/notifications` | email categories for that organization | which categories Lumen emails | + +A page that cannot reach Lumen says so (for example *The CMS could not reach +Lumen*) instead of failing: check `api-edge` and the `LUMEN_API` binding. ## Open the admin (first admin) @@ -147,6 +166,10 @@ real R2 adapter. environment and published `WIRING_CLOUDFLARE_R2_CMS`, then redeploy the CMS. - **An upload answers 413.** It is over 10 MiB (`MEDIA_MAX_BYTES` in `src/collections/Media.ts`). +- **An account page says "Lumen answered with an error (internal_error)".** + api-edge or the worker behind it failed; its logs carry the request id. + Security activity answered 503 for everyone until identity-worker queried + events by the user's UUID rather than its public `usr_` id (PX2). - **Deploy: "exceeds the size limit" or CPU errors (1102).** The account is on Workers Free. The CMS needs Workers Paid. - **Requests hang for 10 s, then 500.** A regression to a shared pool: the diff --git a/apps/cms/next.config.ts b/apps/cms/next.config.ts index 758f590..90faab1 100644 --- a/apps/cms/next.config.ts +++ b/apps/cms/next.config.ts @@ -23,6 +23,20 @@ const nextConfig: NextConfig = { output: 'standalone', outputFileTracingRoot: path.join(dirname, '../..'), serverExternalPackages: ['jose', 'pg', 'pg-cloudflare'], + // Nobody frames the CMS (lumen-payload-console design §6): sibling Workers + // on the same workers.dev site get the Lax session cookie, so a framed + // admin page could be clicked through from one of them. + async headers() { + return [ + { + source: '/:path*', + headers: [ + { key: 'Content-Security-Policy', value: "frame-ancestors 'self'" }, + { key: 'X-Frame-Options', value: 'SAMEORIGIN' }, + ], + }, + ] + }, webpack: (webpackConfig) => { webpackConfig.resolve.extensionAlias = { '.cjs': ['.cts', '.cjs'], diff --git a/apps/cms/package.json b/apps/cms/package.json index 4f7a0cc..69153dd 100644 --- a/apps/cms/package.json +++ b/apps/cms/package.json @@ -29,6 +29,7 @@ }, "devDependencies": { "@cloudflare/workers-types": "^4.20250508.0", + "@saas/contracts": "workspace:*", "@types/node": "22.19.9", "@types/pg": "8.20.0", "@types/react": "19.2.14", diff --git a/apps/cms/src/app/(payload)/admin/importMap.js b/apps/cms/src/app/(payload)/admin/importMap.js index fd7d088..563e397 100644 --- a/apps/cms/src/app/(payload)/admin/importMap.js +++ b/apps/cms/src/app/(payload)/admin/importMap.js @@ -21,10 +21,15 @@ import { StrikethroughFeatureClient as StrikethroughFeatureClient_e70f5e05f09f93 import { UnderlineFeatureClient as UnderlineFeatureClient_e70f5e05f09f93e00b997edb1ef0c864 } from '@payloadcms/richtext-lexical/client' import { BoldFeatureClient as BoldFeatureClient_e70f5e05f09f93e00b997edb1ef0c864 } from '@payloadcms/richtext-lexical/client' import { ItalicFeatureClient as ItalicFeatureClient_e70f5e05f09f93e00b997edb1ef0c864 } from '@payloadcms/richtext-lexical/client' +import { AccountNav as AccountNav_d70fd73be0c9b3a7c754123a7e679b3d } from '../../../components/admin/account/AccountNav' import { R2ClientUploadHandler as R2ClientUploadHandler_85cc02ed84006fcc91d3aff39dda669d } from '@payloadcms/storage-r2/client' import { LumenLogin as LumenLogin_7ffca7fd7bddfb9b50fd712bb1cc26c1 } from '../../../components/admin/LumenLogin' import { PendingAccess as PendingAccess_44e69ba3ff986b78d5b2450d962466d0 } from '../../../components/admin/PendingAccess' import { LumenSignOut as LumenSignOut_1a9f4ebe5bf28ed00539f5d97c7f7af6 } from '../../../components/admin/LumenSignOut' +import { ProfileView as ProfileView_277e3ece63d7b343699a9b408a007eb3 } from '../../../components/admin/account/ProfileView' +import { SecurityView as SecurityView_b295470aeebb099452f0f0106181edbc } from '../../../components/admin/account/SecurityView' +import { OrganizationView as OrganizationView_c762e34a568e64979d425a844ff81df5 } from '../../../components/admin/account/OrganizationView' +import { NotificationsView as NotificationsView_aa0b52d1d262a686350346369dcc5c62 } from '../../../components/admin/account/NotificationsView' import { CollectionCards as CollectionCards_f9c02e79a4aed9a3924487c0cd4cafb1 } from '@payloadcms/next/rsc' /** @type import('payload').ImportMap */ @@ -52,9 +57,14 @@ export const importMap = { "@payloadcms/richtext-lexical/client#UnderlineFeatureClient": UnderlineFeatureClient_e70f5e05f09f93e00b997edb1ef0c864, "@payloadcms/richtext-lexical/client#BoldFeatureClient": BoldFeatureClient_e70f5e05f09f93e00b997edb1ef0c864, "@payloadcms/richtext-lexical/client#ItalicFeatureClient": ItalicFeatureClient_e70f5e05f09f93e00b997edb1ef0c864, + "/components/admin/account/AccountNav#AccountNav": AccountNav_d70fd73be0c9b3a7c754123a7e679b3d, "@payloadcms/storage-r2/client#R2ClientUploadHandler": R2ClientUploadHandler_85cc02ed84006fcc91d3aff39dda669d, "/components/admin/LumenLogin#LumenLogin": LumenLogin_7ffca7fd7bddfb9b50fd712bb1cc26c1, "/components/admin/PendingAccess#PendingAccess": PendingAccess_44e69ba3ff986b78d5b2450d962466d0, "/components/admin/LumenSignOut#LumenSignOut": LumenSignOut_1a9f4ebe5bf28ed00539f5d97c7f7af6, + "/components/admin/account/ProfileView#ProfileView": ProfileView_277e3ece63d7b343699a9b408a007eb3, + "/components/admin/account/SecurityView#SecurityView": SecurityView_b295470aeebb099452f0f0106181edbc, + "/components/admin/account/OrganizationView#OrganizationView": OrganizationView_c762e34a568e64979d425a844ff81df5, + "/components/admin/account/NotificationsView#NotificationsView": NotificationsView_aa0b52d1d262a686350346369dcc5c62, "@payloadcms/next/rsc#CollectionCards": CollectionCards_f9c02e79a4aed9a3924487c0cd4cafb1 } diff --git a/apps/cms/src/app/(site)/lumen/notifications/route.ts b/apps/cms/src/app/(site)/lumen/notifications/route.ts new file mode 100644 index 0000000..9db2ea4 --- /dev/null +++ b/apps/cms/src/app/(site)/lumen/notifications/route.ts @@ -0,0 +1,9 @@ +import { formDeps } from '@/lib/lumen/form-deps' +import { notificationsForm } from '@/lib/lumen/forms' + +export const dynamic = 'force-dynamic' + +// The Notifications page's form (lumen-payload-console design §4). +export function POST(request: Request): Promise { + return notificationsForm(request, formDeps) +} diff --git a/apps/cms/src/app/(site)/lumen/profile/route.ts b/apps/cms/src/app/(site)/lumen/profile/route.ts new file mode 100644 index 0000000..60a1316 --- /dev/null +++ b/apps/cms/src/app/(site)/lumen/profile/route.ts @@ -0,0 +1,9 @@ +import { formDeps } from '@/lib/lumen/form-deps' +import { profileForm } from '@/lib/lumen/forms' + +export const dynamic = 'force-dynamic' + +// The Profile page's form (lumen-payload-console design §4). +export function POST(request: Request): Promise { + return profileForm(request, formDeps) +} diff --git a/apps/cms/src/components/admin/account/AccountNav.tsx b/apps/cms/src/components/admin/account/AccountNav.tsx new file mode 100644 index 0000000..f96305a --- /dev/null +++ b/apps/cms/src/components/admin/account/AccountNav.tsx @@ -0,0 +1,39 @@ +'use client' + +import { Link, NavGroup } from '@payloadcms/ui' +import { usePathname } from 'next/navigation' + +// The Account group in the admin's nav (design §4), styled as Payload's own +// links. The nav only renders for people who can use the admin. +const LINKS = [ + { href: '/admin/account', label: 'Profile' }, + { href: '/admin/account/security', label: 'Security activity' }, + { href: '/admin/organization', label: 'Organization' }, + { href: '/admin/organization/notifications', label: 'Notifications' }, +] + +export function AccountNav() { + const pathname = usePathname() + return ( + + {LINKS.map(({ href, label }) => { + const active = pathname === href + const inner = ( + <> + {active ?
: null} + {label} + + ) + return active ? ( +
+ {inner} +
+ ) : ( + + {inner} + + ) + })} + + ) +} diff --git a/apps/cms/src/components/admin/account/AccountPage.tsx b/apps/cms/src/components/admin/account/AccountPage.tsx new file mode 100644 index 0000000..4927b1a --- /dev/null +++ b/apps/cms/src/components/admin/account/AccountPage.tsx @@ -0,0 +1,92 @@ +import { DefaultTemplate } from '@payloadcms/next/templates' +import { Banner, Gutter } from '@payloadcms/ui' +import { redirect } from 'next/navigation' +import type { AdminViewServerProps } from 'payload' +import type React from 'react' + +import { staffRoleOf } from '@/lib/access' +import { LUMEN_SESSION_COOKIE, readCookie } from '@/lib/lumen/cookies' +import { statusMessage } from '@/lib/lumen/status' + +// What every account page shares (lumen-payload-console design §4). Payload +// leaves custom views to check access themselves and to bring their own +// template, so: signed out → the sign-in, pending → the pending page, staff +// → the page inside the admin's own template. + +/** The session token of a staff member viewing `path`, or a redirect away. */ +export function requireStaff({ initPageResult }: AdminViewServerProps, path: string): string { + const { user, headers } = initPageResult.req + const token = readCookie(headers, LUMEN_SESSION_COOKIE) + if (!user || !token) redirect(`/admin/login?redirect=${encodeURIComponent(path)}`) + if (!staffRoleOf(user)) redirect('/admin/unauthorized') + return token +} + +const first = (value: string | string[] | undefined) => (Array.isArray(value) ? value[0] : value) + +export function param(props: AdminViewServerProps, name: string): string | undefined { + return first(props.searchParams?.[name] as string | string[] | undefined) +} + +/** The line a form's redirect asked for: saved, or what went wrong. */ +export function StatusLine({ props }: { props: AdminViewServerProps }) { + const status = statusMessage({ saved: param(props, 'saved'), error: param(props, 'error') }) + if (!status) return null + return ( +
+ {status.text} +
+ ) +} + +/** A page that could not load its data from Lumen. */ +export function LoadError({ code }: { code: string }) { + return ( +
+ {statusMessage({ error: code })?.text} +
+ ) +} + +export function AccountHeading({ title, description }: { title: string; description: string }) { + return ( +
+

{title}

+

{description}

+
+ ) +} + +/** A custom admin view inside Payload's default template (nav, header). */ +export function AccountTemplate({ props, children }: { props: AdminViewServerProps; children: React.ReactNode }) { + const { initPageResult, params, searchParams } = props + const { req } = initPageResult + return ( + + {children} + + ) +} + +export const card: React.CSSProperties = { + border: '1px solid var(--theme-elevation-150)', + borderRadius: 'var(--style-radius-m)', + padding: 'calc(var(--base) * 1.25)', + marginBottom: 'var(--base)', + maxWidth: 720, +} + +export const row: React.CSSProperties = { display: 'grid', gridTemplateColumns: '10rem 1fr', gap: 'calc(var(--base) / 2)', margin: 0 } diff --git a/apps/cms/src/components/admin/account/NotificationsView.tsx b/apps/cms/src/components/admin/account/NotificationsView.tsx new file mode 100644 index 0000000..8db6341 --- /dev/null +++ b/apps/cms/src/components/admin/account/NotificationsView.tsx @@ -0,0 +1,59 @@ +import type { AdminViewServerProps } from 'payload' + +import { getPreferences, listOrganizations, pickOrganization } from '@/lib/lumen/account-api' +import { effectiveCategories, PREFERENCE_CATEGORIES } from '@/lib/lumen/models/preferences' +import { lumenTransport } from '@/lib/lumen/transport' + +import { AccountHeading, AccountTemplate, card, LoadError, param, requireStaff, StatusLine } from './AccountPage' + +// Notifications (design §4): which kinds of email Lumen sends this account +// for an organization. A category is on unless it was turned off. +export async function NotificationsView(props: AdminViewServerProps) { + const token = requireStaff(props, '/admin/organization/notifications') + const transport = await lumenTransport() + const orgs = await listOrganizations(transport, token) + const org = orgs.ok === true ? pickOrganization(orgs.value, param(props, 'org')) : null + const prefs = org ? await getPreferences(transport, token, org.id) : null + const effective = effectiveCategories(prefs?.ok === true ? prefs.value : []) + return ( + +
+ + + {orgs.ok === false ? ( + + ) : !org ? ( +

Your account does not belong to an organization yet.

+ ) : prefs && prefs.ok === false ? ( + + ) : ( +
+ +

+ For {org.name} +

+ {PREFERENCE_CATEGORIES.map(({ key, label, description }) => { + const on = effective[key] + return ( + + ) + })} + +
+ )} +
+
+ ) +} diff --git a/apps/cms/src/components/admin/account/OrganizationView.tsx b/apps/cms/src/components/admin/account/OrganizationView.tsx new file mode 100644 index 0000000..792595f --- /dev/null +++ b/apps/cms/src/components/admin/account/OrganizationView.tsx @@ -0,0 +1,54 @@ +import type { AdminViewServerProps } from 'payload' + +import { listOrganizations } from '@/lib/lumen/account-api' +import { formatSecurityTimestamp } from '@/lib/lumen/models/security-events' +import { lumenTransport } from '@/lib/lumen/transport' + +import { AccountHeading, AccountTemplate, card, LoadError, requireStaff, row } from './AccountPage' + +// Organization (design §4): the Lumen organization the account works in. In +// Solo mode that is the one personal organization Lumen made at sign-up. +// Renaming is not in the API, so the page only reads. +export async function OrganizationView(props: AdminViewServerProps) { + const token = requireStaff(props, '/admin/organization') + const result = await listOrganizations(await lumenTransport(), token) + return ( + +
+ + {result.ok === false ? ( + + ) : result.value.length === 0 ? ( +

Your account does not belong to an organization yet.

+ ) : ( + result.value.map((org) => ( +
+

{org.name}

+
+
Slug
+
+ {org.slug} +
+
ID
+
+ {org.id} +
+
Created
+
{formatSecurityTimestamp(org.createdAt)}
+ {org.status ? ( + <> +
Status
+
{org.status}
+ + ) : null} +
+

+ Notification settings +

+
+ )) + )} +
+
+ ) +} diff --git a/apps/cms/src/components/admin/account/ProfileView.tsx b/apps/cms/src/components/admin/account/ProfileView.tsx new file mode 100644 index 0000000..a2290f3 --- /dev/null +++ b/apps/cms/src/components/admin/account/ProfileView.tsx @@ -0,0 +1,75 @@ +import { Gutter } from '@payloadcms/ui' +import type { AdminViewServerProps } from 'payload' + +import { getProfile } from '@/lib/lumen/account-api' +import { DISPLAY_NAME_MAX } from '@/lib/lumen/models/profile' +import { lumenTransport } from '@/lib/lumen/transport' + +import { AccountHeading, card, LoadError, requireStaff, row, StatusLine } from './AccountPage' + +// Payload's account view, replaced (design §4): the person's Lumen profile. +// Payload puts this view in its default template and keeps pending accounts +// out of it, as for any admin page; the gutter is the view's own. +export async function ProfileView(props: AdminViewServerProps) { + const token = requireStaff(props, '/admin/account') + const result = await getProfile(await lumenTransport(), token) + const role = (props.initPageResult.req.user as { role?: string | null } | null)?.role + return ( + +
+ + + {result.ok === false ? ( + + ) : ( + <> +
+
+
Email
+
{result.value.email}
+
CMS role
+
{role ?? 'none'}
+
Lumen user ID
+
+ {result.value.id} +
+
+
+
+ +

+ Shown in the CMS and in email Lumen sends you. Leave it empty to use your email. +

+ +
+ +
+
+ + )} +
+

+ See where and when your account signed in on the Security activity page. +

+
+ +
+
+
+
+ ) +} diff --git a/apps/cms/src/components/admin/account/SecurityView.tsx b/apps/cms/src/components/admin/account/SecurityView.tsx new file mode 100644 index 0000000..fcbd0b6 --- /dev/null +++ b/apps/cms/src/components/admin/account/SecurityView.tsx @@ -0,0 +1,69 @@ +import type { AdminViewServerProps } from 'payload' + +import { listSecurityEvents } from '@/lib/lumen/account-api' +import { toSecurityRow } from '@/lib/lumen/models/security-events' +import { lumenTransport } from '@/lib/lumen/transport' + +import { AccountHeading, AccountTemplate, LoadError, param, requireStaff } from './AccountPage' + +const cell = { padding: 'calc(var(--base) / 2)', borderBottom: '1px solid var(--theme-elevation-100)', textAlign: 'left' as const } + +// Security activity (design §4): the person's own sign-in and session +// events, newest first, a page at a time. The cursor is api-edge's. +export async function SecurityView(props: AdminViewServerProps) { + const token = requireStaff(props, '/admin/account/security') + const cursor = param(props, 'cursor') ?? null + const result = await listSecurityEvents(await lumenTransport(), token, cursor) + return ( + +
+ + {result.ok === false ? ( + + ) : result.value.events.length === 0 ? ( +

No security events yet.

+ ) : ( + + + + + + + + + + + + {result.value.events.map(toSecurityRow).map((r) => ( + + + + + + + + ))} + +
WhenEventOutcomeIPBrowser
+ + + {r.eventType} + {r.badge.label}{r.ip} + {r.userAgent} +
+ )} + +
+
+ ) +} diff --git a/apps/cms/src/lib/access.ts b/apps/cms/src/lib/access.ts index f65cc21..a2cf6bd 100644 --- a/apps/cms/src/lib/access.ts +++ b/apps/cms/src/lib/access.ts @@ -6,6 +6,9 @@ type StaffUser = { collection?: string; role?: Role | null } | null | undefined const roleOf = (user: StaffUser): Role | undefined => user && (user.collection === undefined || user.collection === 'users') ? (user.role ?? undefined) : undefined +/** The Payload role of a request's user, or undefined (signed out, pending, or not a `users` row). */ +export const staffRoleOf = (user: unknown): Role | undefined => roleOf(user as StaffUser) + export const anyone: Access = () => true // Boolean-only (not Access): Payload's `access.admin` must answer yes or no. export const isStaff = ({ req: { user } }: { req: PayloadRequest }): boolean => Boolean(roleOf(user as StaffUser)) diff --git a/apps/cms/src/lib/lumen/account-api.ts b/apps/cms/src/lib/lumen/account-api.ts new file mode 100644 index 0000000..260f611 --- /dev/null +++ b/apps/cms/src/lib/lumen/account-api.ts @@ -0,0 +1,81 @@ +import type { AuthUser, ProfileResponse, UpdateProfileRequest } from '@saas/contracts/auth' +import type { ListOrganizationsResponse, PublicOrganization } from '@saas/contracts/membership' +import type { + GetNotificationPreferencesResponse, + NotificationCategoryPreferences, + NotificationPreference, + UpdateNotificationPreferencesResponse, +} from '@saas/contracts/notifications' +import type { PublicSecurityEvent, SecurityEventListResponse } from '@saas/contracts/security-events' + +import { lumenCall, type LumenResult, type LumenTransport } from './client' + +// The Lumen calls behind the account pages (lumen-payload-console design §4), +// made by the CMS server with the signed-in person's session token. Each is +// the same api-edge route the console calls; Solo mode decides what exists. + +export type Failure = Extract, { ok: false }> +export type Outcome = { ok: true; value: T } | Failure + +// Comparisons with `=== false`, not `!ok`: the CMS compiles without +// strictNullChecks, where only an equality check narrows the union. +function unwrap(result: LumenResult, pick: (data: T) => R): Outcome { + if (result.ok === false) return result + return { ok: true, value: pick(result.data) } +} + +export async function getProfile(transport: LumenTransport, token: string): Promise> { + return unwrap(await lumenCall(transport, '/v1/auth/profile', { token }), (d) => d.user) +} + +export async function updateProfile( + transport: LumenTransport, + token: string, + patch: UpdateProfileRequest, +): Promise> { + return unwrap(await lumenCall(transport, '/v1/auth/profile', { token, method: 'PATCH', body: patch }), (d) => d.user) +} + +export type SecurityPage = { events: PublicSecurityEvent[]; nextCursor: string | null } + +/** One page of the person's own security events; `cursor` is api-edge's, passed back as given. */ +export async function listSecurityEvents( + transport: LumenTransport, + token: string, + cursor?: string | null, +): Promise> { + const query = cursor ? `?cursor=${encodeURIComponent(cursor)}` : '' + const result = await lumenCall(transport, `/v1/auth/security-events${query}`, { token }) + if (result.ok === false) return result + return { ok: true, value: { events: result.data?.securityEvents ?? [], nextCursor: result.cursor } } +} + +export async function listOrganizations(transport: LumenTransport, token: string): Promise> { + return unwrap(await lumenCall(transport, '/v1/organizations', { token }), (d) => d?.organizations ?? []) +} + +/** The organization a page is about: the one asked for if the person belongs to it, else their first (Solo: their only one). */ +export function pickOrganization(orgs: PublicOrganization[], wanted?: string | null): PublicOrganization | null { + return (wanted ? orgs.find((o) => o.id === wanted) : undefined) ?? orgs[0] ?? null +} + +export async function getPreferences( + transport: LumenTransport, + token: string, + orgId: string, +): Promise> { + const path = `/v1/notifications/preferences?orgId=${encodeURIComponent(orgId)}` + return unwrap(await lumenCall(transport, path, { token }), (d) => d?.preferences ?? []) +} + +export async function updatePreferences( + transport: LumenTransport, + token: string, + input: { orgId: string; userId: string; categories: NotificationCategoryPreferences }, +): Promise> { + const body = { orgId: input.orgId, subjectKind: 'user', subjectId: input.userId, channel: 'email', categories: input.categories } + return unwrap( + await lumenCall(transport, '/v1/notifications/preferences', { token, method: 'PUT', body }), + (d) => d.preference, + ) +} diff --git a/apps/cms/src/lib/lumen/client.ts b/apps/cms/src/lib/lumen/client.ts index 1b7a6bb..a387338 100644 --- a/apps/cms/src/lib/lumen/client.ts +++ b/apps/cms/src/lib/lumen/client.ts @@ -6,7 +6,7 @@ export type LumenTransport = (path: string, init: RequestInit) => Promise export type LumenResult = - | { ok: true; status: number; data: T } + | { ok: true; status: number; data: T; cursor: string | null } | { ok: false; status: number; code: string; message: string } export type LumenUser = { id: string; email: string; displayName: string | null; lastOrgSlug?: string | null } @@ -37,8 +37,8 @@ export async function lumenCall( parsed = null } if (response.ok) { - const data = (parsed as { data?: T } | null)?.data - return { ok: true, status: response.status, data: (data ?? null) as T } + const envelope = parsed as { data?: T; meta?: { cursor?: string | null } } | null + return { ok: true, status: response.status, data: (envelope?.data ?? null) as T, cursor: envelope?.meta?.cursor ?? null } } const error = (parsed as { error?: { code?: string; message?: string } } | null)?.error return { ok: false, status: response.status, code: error?.code ?? 'error', message: error?.message ?? `HTTP ${response.status}` } diff --git a/apps/cms/src/lib/lumen/form-deps.ts b/apps/cms/src/lib/lumen/form-deps.ts new file mode 100644 index 0000000..b9c0ecf --- /dev/null +++ b/apps/cms/src/lib/lumen/form-deps.ts @@ -0,0 +1,20 @@ +import config from '@payload-config' +import { getPayload } from 'payload' + +import type { FormDeps, FormUser } from './forms' +import { lumenTransport } from './transport' + +// The runtime side of the account forms: Payload signs the request in (the +// lumen strategy), and the display name is copied onto the users row. +export const formDeps: FormDeps = { + transport: lumenTransport, + authenticate: async (headers) => { + const payload = await getPayload({ config }) + const { user } = await payload.auth({ headers }) + return (user as FormUser | null) ?? null + }, + syncName: async (userId, name) => { + const payload = await getPayload({ config }) + await payload.update({ collection: 'users', id: userId, data: { name }, overrideAccess: true }) + }, +} diff --git a/apps/cms/src/lib/lumen/forms.ts b/apps/cms/src/lib/lumen/forms.ts new file mode 100644 index 0000000..13d1aae --- /dev/null +++ b/apps/cms/src/lib/lumen/forms.ts @@ -0,0 +1,105 @@ +import type { NotificationCategoryPreferences } from '@saas/contracts/notifications' + +import { staffRoleOf } from '../access' +import { updatePreferences, updateProfile } from './account-api' +import type { LumenTransport } from './client' +import { isSameOrigin, LUMEN_SESSION_COOKIE, readCookie } from './cookies' +import { DISPLAY_NAME_MAX, toDisplayNameValue, validateDisplayName } from './models/profile' +import { PREFERENCE_CATEGORIES } from './models/preferences' + +// The CMS route handlers behind the account pages' forms (design §4): each +// accepts a same-origin form post from a signed-in admin or editor, calls +// api-edge with their session, and answers 303 back to the page with a +// status the page shows. Pure: the routes inject Payload and the transport. + +export const ACCOUNT_PAGES = { + profile: '/admin/account', + security: '/admin/account/security', + organization: '/admin/organization', + notifications: '/admin/organization/notifications', +} as const + +export type FormUser = { id: string | number; role?: string | null; lumenUserId?: string | null; collection?: string } + +export type FormDeps = { + transport: () => Promise + /** The Payload user the request's cookie signs in, or null. */ + authenticate: (headers: Headers) => Promise + /** Keep the CMS's copy of the display name in step (users.name). */ + syncName?: (userId: FormUser['id'], name: string | null) => Promise +} + +const seeOther = (location: string) => + new Response(null, { status: 303, headers: { location, 'cache-control': 'no-store' } }) + +/** Where a form goes back to, with what happened. */ +export function backTo(page: string, outcome: { saved: true } | { error: string }, extra: Record = {}): string { + const params = new URLSearchParams(extra) + if ('saved' in outcome) params.set('saved', '1') + else params.set('error', outcome.error) + return `${page}?${params.toString()}` +} + +type Action = (input: { form: FormData; token: string; user: FormUser; transport: LumenTransport }) => Promise< + { location: string } +> + +async function handle(request: Request, deps: FormDeps, page: string, action: Action): Promise { + if (!isSameOrigin(request.headers, request.url)) { + return new Response('Forbidden: this form only accepts posts from the CMS itself.\n', { + status: 403, + headers: { 'content-type': 'text/plain; charset=utf-8', 'cache-control': 'no-store' }, + }) + } + const token = readCookie(request.headers, LUMEN_SESSION_COOKIE) + const user = token ? await deps.authenticate(request.headers) : null + if (!token || !user) return seeOther(`/admin/login?redirect=${encodeURIComponent(page)}`) + if (!staffRoleOf(user)) return seeOther('/admin/unauthorized') + let form: FormData + try { + form = await request.formData() + } catch { + return seeOther(backTo(page, { error: 'bad_request' })) + } + const { location } = await action({ form, token, user, transport: await deps.transport() }) + return seeOther(location) +} + +/** POST /lumen/profile: the display name. */ +export function profileForm(request: Request, deps: FormDeps): Promise { + const page = ACCOUNT_PAGES.profile + return handle(request, deps, page, async ({ form, token, user, transport }) => { + const raw = String(form.get('displayName') ?? '') + if (!validateDisplayName(raw).ok) return { location: backTo(page, { error: 'too_long' }) } + const displayName = toDisplayNameValue(raw) + const result = await updateProfile(transport, token, { displayName }) + if (result.ok === false) return { location: backTo(page, { error: result.code }) } + await deps.syncName?.(user.id, result.value.displayName ?? null) + return { location: backTo(page, { saved: true }) } + }) +} + +/** The categories a notifications form asks for: a ticked box delivers, an unticked one does not. */ +export function categoriesFromForm(form: FormData): NotificationCategoryPreferences { + const categories: NotificationCategoryPreferences = {} + for (const { key } of PREFERENCE_CATEGORIES) categories[key] = form.get(key) === 'on' + return categories +} + +/** POST /lumen/notifications: email categories for one organization. */ +export function notificationsForm(request: Request, deps: FormDeps): Promise { + const page = ACCOUNT_PAGES.notifications + return handle(request, deps, page, async ({ form, token, user, transport }) => { + const orgId = String(form.get('orgId') ?? '') + const back = orgId ? { org: orgId } : undefined + if (!orgId || !user.lumenUserId) return { location: backTo(page, { error: 'bad_request' }, back) } + const result = await updatePreferences(transport, token, { + orgId, + userId: user.lumenUserId, + categories: categoriesFromForm(form), + }) + return { location: backTo(page, result.ok === false ? { error: result.code } : { saved: true }, back) } + }) +} + +export { DISPLAY_NAME_MAX } diff --git a/apps/cms/src/lib/lumen/models/preferences.ts b/apps/cms/src/lib/lumen/models/preferences.ts new file mode 100644 index 0000000..31e14ed --- /dev/null +++ b/apps/cms/src/lib/lumen/models/preferences.ts @@ -0,0 +1,60 @@ +// Copied from apps/web-console-next/src/components/notifications/preferences.ts with its tests +// (lumen-payload-console PX2): the console is retired in PX4, so this copy +// is the one that stays. Framework-free. + +import type { + NotificationCategory, + NotificationCategoryPreferences, + NotificationPreference, +} from "@saas/contracts/notifications"; + +/** + * Pure model for the notification-preferences page. Dependency-free so the + * default/merge semantics are unit-testable (settings-nav.ts convention). + * + * Semantics mirror the worker: a missing preference row — or a missing/null + * category entry — means "deliver" (opt-out model). Only an explicit `false` + * suppresses a category. + */ + +export const PREFERENCE_CATEGORIES: Array<{ + key: NotificationCategory; + label: string; + description: string; +}> = [ + { key: "invitation", label: "Invitations", description: "Membership invites and acceptances." }, + { key: "billing", label: "Billing", description: "Receipts, plan changes, and payment issues." }, + { + key: "security", + label: "Security", + description: "Sign-in codes and account alerts. Critical security email may still be delivered.", + }, + { key: "support", label: "Support", description: "Replies to your support requests." }, + { key: "product", label: "Product", description: "Feature announcements and product updates." }, +]; + +/** Resolve the effective on/off state per category from the stored rows. */ +export function effectiveCategories( + preferences: NotificationPreference[] | null | undefined, +): Record { + const row = preferences?.find((p) => p.channel === "email"); + const result = {} as Record; + for (const { key } of PREFERENCE_CATEGORIES) { + const v = row?.categories?.[key]; + result[key] = v !== false; // null/undefined/true → deliver + } + return result; +} + +/** Build the full categories payload for an update, flipping one category. */ +export function buildUpdatedCategories( + current: Record, + category: NotificationCategory, + enabled: boolean, +): NotificationCategoryPreferences { + const next: NotificationCategoryPreferences = {}; + for (const { key } of PREFERENCE_CATEGORIES) { + next[key] = key === category ? enabled : current[key]; + } + return next; +} diff --git a/apps/cms/src/lib/lumen/models/profile.ts b/apps/cms/src/lib/lumen/models/profile.ts new file mode 100644 index 0000000..5830ebd --- /dev/null +++ b/apps/cms/src/lib/lumen/models/profile.ts @@ -0,0 +1,65 @@ +// Copied from apps/web-console-next/src/components/account/profile.ts with its tests +// (lumen-payload-console PX2): the console is retired in PX4, so this copy +// is the one that stays. Framework-free. + +/** + * Pure helpers for the account profile surface (Task 0127 / U11). + * + * Dependency-free so display-name validation/normalization can be unit-tested. + * React wiring lives in `app/(app)/account/page.tsx`; wire I/O goes through + * `@saas/sdk` (`auth.getProfile` / `updateProfile` / `logout`). + */ + +import type { UpdateProfileRequest } from "@saas/contracts/auth"; + +export const DISPLAY_NAME_MAX = 80; + +export interface FieldValidation { + ok: boolean; + message?: string; +} + +/** + * Validate a display name. Empty is allowed (clears the name → null). Bounded + * length; the worker is the authoritative validator. + */ +export function validateDisplayName(raw: string): FieldValidation { + const value = (raw ?? "").trim(); + if (value.length > DISPLAY_NAME_MAX) { + return { ok: false, message: `Keep it under ${DISPLAY_NAME_MAX} characters` }; + } + return { ok: true }; +} + +/** Normalize a form display name to the request shape (empty → null clear). */ +export function toDisplayNameValue(raw: string): string | null { + const value = (raw ?? "").trim(); + return value.length === 0 ? null : value; +} + +/** + * Build the PATCH body for a profile update, or `null` when nothing changed + * (so the caller can short-circuit the network call). `current` is the stored + * displayName (may be null). + */ +export function buildProfilePatch( + current: string | null, + nextRaw: string, +): UpdateProfileRequest | null { + const next = toDisplayNameValue(nextRaw); + if (next === (current ?? null)) return null; + return { displayName: next }; +} + +/** + * A short avatar seed (initials) from a display name or email local-part. + * Tolerates a missing/empty email (some accounts have none) without throwing. + */ +export function initials(displayName: string | null, email: string | null | undefined): string { + const safeEmail = (email ?? "").trim(); + const source = (displayName && displayName.trim()) || safeEmail.split("@")[0] || safeEmail; + const parts = source.split(/[\s._-]+/).filter(Boolean); + if (parts.length === 0) return "?"; + if (parts.length === 1) return parts[0]!.slice(0, 2).toUpperCase(); + return (parts[0]![0]! + parts[1]![0]!).toUpperCase(); +} diff --git a/apps/cms/src/lib/lumen/models/security-events.ts b/apps/cms/src/lib/lumen/models/security-events.ts new file mode 100644 index 0000000..381aea7 --- /dev/null +++ b/apps/cms/src/lib/lumen/models/security-events.ts @@ -0,0 +1,149 @@ +// Copied from apps/web-console-next/src/components/security/security-events.ts with its tests +// (lumen-payload-console PX2): the console is retired in PX4, so this copy +// is the one that stays. Framework-free. + +/** + * Pure helpers for the account-scoped security-events panel. + * + * Kept dependency-free (no React, no `next/*`, no DOM) so the row view-model + * shaping, "Load more" pagination accumulation, and outcome-badge logic can be + * unit-tested in isolation. The React wiring lives in the account security page + * (`app/(app)/account/security/page.tsx`); this file owns: + * + * - outcome → badge-variant mapping (`securityOutcomeBadge`) + * - the row view-model shaper (`toSecurityRow`) + * - the "Load more" accumulation reducer (`appendSecurityPage`) + * - the timestamp shaper (`formatSecurityTimestamp`) + * + * Cursor handling mirrors the SDK contract: the continuation cursor is an + * opaque base64 token surfaced by `SecurityEventsClient.listPage` as + * `nextCursor` (sourced from `meta.cursor`, NOT a body field). Callers MUST + * pass it back verbatim — never construct or parse it. + * + * The surface is account/actor-scoped (NOT org-scoped); the worker has already + * stripped secrets/codes/credential material and applied redaction, so only + * the safe `PublicSecurityEvent` fields are rendered. + */ + +import type { PublicSecurityEvent } from "@saas/contracts/security-events"; + +/** Badge variants available in `components/ui/badge.tsx`. */ +export type SecurityBadgeVariant = + | "default" + | "secondary" + | "destructive" + | "warning" + | "success" + | "outline"; + +/** + * Map a security-event outcome to a badge variant + label. + * + * - success → green success badge + * - failure → red destructive badge + * + * The `default` arm guards against a wire value that drifts ahead of the + * contract and renders it as a neutral outline rather than throwing in the + * render path. + */ +export function securityOutcomeBadge(outcome: string): { + variant: SecurityBadgeVariant; + label: string; +} { + switch (outcome) { + case "success": + return { variant: "success", label: "Success" }; + case "failure": + return { variant: "destructive", label: "Failure" }; + default: + return { variant: "outline", label: String(outcome) }; + } +} + +/** A flat view-model for a single security-event table row. */ +export interface SecurityRow { + id: string; + eventType: string; + outcome: string; + badge: { variant: SecurityBadgeVariant; label: string }; + /** Absolute local timestamp of the event, or "—" when unparseable. */ + occurredAtLabel: string; + /** Client IP, or "—" when the worker did not record one. */ + ip: string; + /** User-agent string, or "—" when absent. */ + userAgent: string; +} + +/** + * Format an ISO timestamp to a short local date+time, tolerating null and + * malformed values (returns the supplied fallback rather than "Invalid Date"). + */ +export function formatSecurityTimestamp( + value: string | null | undefined, + fallback = "—", +): string { + if (!value) return fallback; + const d = new Date(value); + if (Number.isNaN(d.getTime())) return fallback; + return d.toLocaleString(); +} + +/** Shape a raw security event into a display row (safe fields only). */ +export function toSecurityRow(ev: PublicSecurityEvent): SecurityRow { + return { + id: ev.id, + eventType: ev.eventType, + outcome: ev.outcome, + badge: securityOutcomeBadge(ev.outcome), + occurredAtLabel: formatSecurityTimestamp(ev.occurredAt), + ip: ev.ip ?? "—", + userAgent: ev.userAgent ?? "—", + }; +} + +/** Accumulated state for the cursor-paginated security-events list. */ +export interface SecurityEventsState { + events: ReadonlyArray; + /** Opaque continuation cursor; null when the last page has been reached. */ + cursor: string | null; +} + +export const EMPTY_SECURITY_EVENTS: SecurityEventsState = { + events: [], + cursor: null, +}; + +/** + * Fold a freshly-fetched page into the accumulated state. + * + * `reset` distinguishes the initial / refreshed load (replace the list) from a + * "Load more" append (concatenate). De-duplication by event id guards against + * a boundary event appearing on two adjacent pages — append is idempotent on + * id. + */ +export function appendSecurityPage( + prev: SecurityEventsState, + page: { + securityEvents: ReadonlyArray; + nextCursor: string | null; + }, + reset = false, +): SecurityEventsState { + if (reset) { + return { events: page.securityEvents.slice(), cursor: page.nextCursor }; + } + const seen = new Set(prev.events.map((e) => e.id)); + const merged = prev.events.slice(); + for (const e of page.securityEvents) { + if (!seen.has(e.id)) { + seen.add(e.id); + merged.push(e); + } + } + return { events: merged, cursor: page.nextCursor }; +} + +/** Whether a "Load more" affordance should be shown. */ +export function hasMoreSecurityEvents(state: SecurityEventsState): boolean { + return state.cursor !== null; +} diff --git a/apps/cms/src/lib/lumen/session.ts b/apps/cms/src/lib/lumen/session.ts index 57c7c27..c976d2a 100644 --- a/apps/cms/src/lib/lumen/session.ts +++ b/apps/cms/src/lib/lumen/session.ts @@ -4,24 +4,39 @@ import { lumenCall, type LumenSessionResponse, type LumenTransport, type LumenUs // and remembered per isolate for SESSION_CACHE_MS, the same window api-edge // gives its own actor cache. Keyed on the token's SHA-256, never the token. // A revoked session therefore stops working within that window. +// +// Two things keep a busy admin from asking too often or being signed out by a +// blip: concurrent requests with one token share a single lookup, and when +// api-edge cannot answer (rate limited, an error, unreachable) a session it +// confirmed in the last STALE_MAX_MS is still honoured until it expires. export type LumenSession = { user: LumenUser; expiresAt: string } export const SESSION_CACHE_MS = 30_000 +/** How long a confirmed session survives api-edge being unable to answer. */ +export const STALE_MAX_MS = 5 * 60_000 +/** After api-edge fails to answer, how long to keep using the confirmed session before asking again. */ +export const RETRY_AFTER_MS = 5_000 const MAX_ENTRIES = 1000 -type Entry = { at: number; value: LumenSession | null } +type Entry = { at: number; value: LumenSession | null; retryAt?: number } const cache = new Map() +const inFlight = new Map>() export async function tokenKey(token: string): Promise { const digest = await crypto.subtle.digest('SHA-256', new TextEncoder().encode(token)) return Array.from(new Uint8Array(digest), (b) => b.toString(16).padStart(2, '0')).join('') } +function remember(key: string, entry: Entry): void { + if (!cache.has(key) && cache.size >= MAX_ENTRIES) cache.delete(cache.keys().next().value as string) + cache.set(key, entry) +} + /** * The session behind a token, or null when api-edge says it is not one (401, - * 403) or cannot be asked. Only answers api-edge actually gave are cached: an - * outage fails closed for this request and is asked again on the next. + * 403), or cannot be asked and has not confirmed it recently. Only answers + * api-edge actually gave are cached. */ export async function resolveSession( transport: LumenTransport, @@ -31,19 +46,38 @@ export async function resolveSession( const key = await tokenKey(token) const hit = cache.get(key) if (hit && now - hit.at < SESSION_CACHE_MS) return hit.value + if (hit?.retryAt && now < hit.retryAt && usable(hit, now)) return hit.value + + const pending = inFlight.get(key) + if (pending) return pending + const lookup = ask(transport, token, key, hit, now).finally(() => inFlight.delete(key)) + inFlight.set(key, lookup) + return lookup +} +async function ask(transport: LumenTransport, token: string, key: string, previous: Entry | undefined, now: number) { const result = await lumenCall(transport, '/v1/auth/session', { token }) - let value: LumenSession | null if (result.ok && result.data?.user?.id && result.data.user.email) { - value = { user: result.data.user, expiresAt: result.data.session.expiresAt } - } else if (!result.ok && (result.status === 401 || result.status === 403)) { - value = null - } else { + const value = { user: result.data.user, expiresAt: result.data.session.expiresAt } + remember(key, { at: now, value }) + return value + } + if (result.ok === false && (result.status === 401 || result.status === 403)) { + remember(key, { at: now, value: null }) return null } - if (cache.size >= MAX_ENTRIES) cache.delete(cache.keys().next().value as string) - cache.set(key, { at: now, value }) - return value + // api-edge could not answer: fail closed, unless it confirmed this session + // recently and the session has not expired since. + if (previous && usable(previous, now)) { + remember(key, { at: previous.at, value: previous.value, retryAt: now + RETRY_AFTER_MS }) + return previous.value + } + return null +} + +/** A confirmed session still inside the stale window and not expired. */ +function usable(entry: Entry, now: number): boolean { + return entry.value !== null && now - entry.at < STALE_MAX_MS && Date.parse(entry.value.expiresAt) > now } /** Drop a token from the cache (sign-out), so the next request asks api-edge again. */ @@ -54,4 +88,5 @@ export async function forgetSession(token: string): Promise { /** For tests. */ export function clearSessionCache(): void { cache.clear() + inFlight.clear() } diff --git a/apps/cms/src/lib/lumen/status.ts b/apps/cms/src/lib/lumen/status.ts new file mode 100644 index 0000000..5b99b35 --- /dev/null +++ b/apps/cms/src/lib/lumen/status.ts @@ -0,0 +1,28 @@ +// What the account pages say after a form or a failed read (design §4). +// api-edge's error codes become sentences; anything unknown is reported as is. + +const MESSAGES: Record = { + too_long: 'That name is too long. Keep it under 80 characters.', + bad_request: 'The form was incomplete. Reload the page and try again.', + unauthenticated: 'Your session ended. Sign in again.', + forbidden: 'Your account is not allowed to do that.', + not_found: 'Lumen does not have that any more. Reload the page.', + rate_limited: 'Too many requests just now. Wait a minute and try again.', + validation_failed: 'Lumen refused the change. Check the values and try again.', + conflict: 'Something changed at the same time. Reload the page and try again.', + internal_error: 'Lumen had a problem. Try again in a moment.', + unreachable: 'The CMS could not reach Lumen. Try again in a moment.', +} + +export type Status = { kind: 'saved' | 'error'; text: string } + +export function statusMessage(query: { saved?: string | undefined; error?: string | undefined }): Status | null { + if (query.error) { + const code = query.error.replace(/[^a-z0-9_.-]/gi, '').slice(0, 64) + // Own keys only: `?error=constructor` must not reach the page as a function. + const known = Object.hasOwn(MESSAGES, code) ? MESSAGES[code] : undefined + return { kind: 'error', text: known ?? `Lumen answered with an error (${code || 'unknown'}).` } + } + if (query.saved === '1') return { kind: 'saved', text: 'Saved.' } + return null +} diff --git a/apps/cms/src/payload.config.ts b/apps/cms/src/payload.config.ts index 6029bfa..9e69926 100644 --- a/apps/cms/src/payload.config.ts +++ b/apps/cms/src/payload.config.ts @@ -46,10 +46,22 @@ export default buildConfig({ // Lumen sign-in replaces Payload's password views (lumen-payload-console // design §1, §3): Payload's local strategy is off on `users`. components: { + // The Lumen account pages (design §4): Payload's account view becomes + // the Lumen profile, and the rest are custom views under an Account + // group in the nav. + afterNavLinks: ['/components/admin/account/AccountNav#AccountNav'], views: { login: { Component: '/components/admin/LumenLogin#LumenLogin' }, unauthorized: { Component: '/components/admin/PendingAccess#PendingAccess' }, logout: { Component: '/components/admin/LumenSignOut#LumenSignOut' }, + account: { Component: '/components/admin/account/ProfileView#ProfileView' }, + lumenSecurity: { Component: '/components/admin/account/SecurityView#SecurityView', path: '/account/security', exact: true }, + lumenOrganization: { Component: '/components/admin/account/OrganizationView#OrganizationView', path: '/organization', exact: true }, + lumenNotifications: { + Component: '/components/admin/account/NotificationsView#NotificationsView', + path: '/organization/notifications', + exact: true, + }, }, }, }, diff --git a/apps/identity-worker/src/handlers/security-events.ts b/apps/identity-worker/src/handlers/security-events.ts index 30dec1b..aa23b59 100644 --- a/apps/identity-worker/src/handlers/security-events.ts +++ b/apps/identity-worker/src/handlers/security-events.ts @@ -6,6 +6,7 @@ import { createIdentityRepository } from "@saas/db/identity"; import { createAuthService } from "../services/auth.js"; import { errorResponse, extractBearerToken, validationError } from "../http.js"; import { parsePageParams, encodeCursor } from "../pagination.js"; +import { parseUserPublicId } from "../ids.js"; /** Secret-bearing metadata keys that must never appear in public responses. */ const SENSITIVE_KEYS = new Set([ @@ -112,7 +113,13 @@ export async function handleSecurityEvents( return errorResponse(sessionResult.error, sessionResult.message, 401, requestId); } - const userId = sessionResult.user.id; + // The session names the user by public id (usr_); events are stored + // under the bare UUID (user_id is a UUID column), as every other handler + // that queries by user does. + const userId = parseUserPublicId(sessionResult.user.id); + if (!userId) { + return errorResponse("internal_error", "Invalid user ID format", 500, requestId); + } const { limit, cursor } = pageResult.value; const dbCursor = cursor ? { occurredAt: cursor.occurredAt, id: cursor.id } : null; diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml index e90f60d..4431945 100644 --- a/pnpm-lock.yaml +++ b/pnpm-lock.yaml @@ -147,6 +147,9 @@ importers: '@cloudflare/workers-types': specifier: ^4.20250508.0 version: 4.20260702.1 + '@saas/contracts': + specifier: workspace:* + version: link:../../packages/contracts '@types/node': specifier: 22.19.9 version: 22.19.9 @@ -807,6 +810,9 @@ importers: tests/cms: devDependencies: + '@saas/contracts': + specifier: workspace:* + version: link:../../packages/contracts '@saas/eslint-config': specifier: workspace:* version: link:../../tooling/eslint diff --git a/specs/epics/lumen-payload-console/IMPLEMENTATION-STATUS.md b/specs/epics/lumen-payload-console/IMPLEMENTATION-STATUS.md index 247608e..fc81eef 100644 --- a/specs/epics/lumen-payload-console/IMPLEMENTATION-STATUS.md +++ b/specs/epics/lumen-payload-console/IMPLEMENTATION-STATUS.md @@ -6,8 +6,8 @@ the code departed from `design.md`. | Milestone | State | PR | |---|---|---| | PX0 — the spec | Merged | sourceplane/lumen-payload#21 | -| PX1 — Lumen sign-in | In review | — | -| PX2 — your account and organization | Not started | — | +| PX1 — Lumen sign-in | Merged; stage partly deployed, the rest waits on the credential-mint quota | sourceplane/lumen-payload#22 | +| PX2 — your account and organization | In review | — | | PX3 — billing and plan | Not started | — | | PX4 — the front door | Not started | — | | PX5 — the record | Not started | — | @@ -28,3 +28,26 @@ the code departed from `design.md`. - **PX1, migration 206.** Payload adds `lumen_user_id` at the end of `users`, while its push of a fresh schema puts it after `role`. The two schemas are identical apart from that column order, which nothing reads. +- **PX2, the API client.** Design §4 calls api-edge "through `@saas/sdk`". + The CMS uses its own small client (`src/lib/lumen/client.ts`, from PX1), + which takes the service binding as its transport, and types from + `@saas/contracts` (a type-only dependency): the SDK would be a second HTTP + layer for the same handful of routes. +- **PX2, identity-worker fix.** `GET /v1/auth/security-events` answered 503 + for everyone: it queried the UUID `user_id` column with the public `usr_` + id. It now converts the id first, as every other handler does. The + baseline's identity-worker has the same bug. +- **PX2, api-edge rate limits.** The design left api-edge unchanged, but its + `auth` family allowed a bearer 10 requests a minute, shared by the CMS's + session re-checks and the account pages, which could sign a busy editor + out. A bearer reading its own session, profile or security events (or + saving its profile) is now the `account` family, 60 a minute; sign-in, + OAuth, logout and anonymous calls keep 10. The tight cap never slowed + token guessing, since the bucket is keyed on the bearer itself. The CMS + also shares one lookup between concurrent requests and keeps a session + api-edge confirmed in the last 5 minutes while api-edge cannot answer. +- **PX2, framing.** Every CMS response carries `frame-ancestors 'self'`; + design §6 had not covered framing by a sibling Worker on the same site. +- **PX2, signed-out redirects.** A custom view's redirect to the sign-in is + sent inside the streamed page (Next's `NEXT_REDIRECT`), which the browser + follows; the response itself is `200`, as for Payload's own guarded views. diff --git a/tasks/PX-3.TaskContract.yaml b/tasks/PX-3.TaskContract.yaml new file mode 100644 index 0000000..4c5770e --- /dev/null +++ b/tasks/PX-3.TaskContract.yaml @@ -0,0 +1,26 @@ +apiVersion: orun.io/v1 +kind: TaskContract +metadata: + name: PX-3 + title: "PX2: your account and organization in the Payload admin" +spec: + goal: "Admins and editors read and change their Lumen account from the Payload admin: Profile (display name), Security activity, Organization and Notifications, under an Account group in the nav, through api-edge with their own session." + affects: + - "apps/cms/**" + - "tests/cms/**" + - "apps/identity-worker/src/handlers/security-events.ts" + - "apps/api-edge/src/rate-limit.ts" + - "apps/api-edge/src/auth-facade.ts" + - "tests/api-edge/src/rate-limit.test.ts" + - "tests/identity-worker/src/security-events.test.ts" + - "pnpm-lock.yaml" + - "ai/context/operations.md" + - "specs/epics/lumen-payload-console/IMPLEMENTATION-STATUS.md" + - "tasks/PX-3.TaskContract.yaml" + doneWhen: + - "on stage, the display name changes from the admin and reads back through GET /v1/auth/profile" + - "on stage, a notification category turns off from the admin and reads back through GET /v1/notifications/preferences" + - "on stage, the Organization and Security activity pages render the person's organization and sign-in events" + - "a pending or signed-out visitor cannot open the pages or post their forms" + - "a signed-in bearer reading its own account is rate-limited at 60 a minute, sign-in at 10" + gates: [] diff --git a/tests/api-edge/src/rate-limit.test.ts b/tests/api-edge/src/rate-limit.test.ts index d541c26..803e62b 100644 --- a/tests/api-edge/src/rate-limit.test.ts +++ b/tests/api-edge/src/rate-limit.test.ts @@ -14,7 +14,7 @@ // - rate-limit fires BEFORE replayOrExecute KV touch (denied request never // reaches the idempotency cache) -import { handleAuthRoute } from "@api-edge/auth-facade"; +import { authRouteFamily, handleAuthRoute } from "@api-edge/auth-facade"; import { enforceRateLimit, __rateLimitConfigForTest, @@ -105,6 +105,31 @@ describe("api-edge rate limiter (Task 0097)", () => { }); }); + describe("account family (lumen-payload-console PX2)", () => { + const get = (path: string, bearer?: string) => + makeRequest({ url: `https://api.example.com${path}`, method: "GET", ...(bearer ? { bearer } : {}) }); + + it("a bearer reading its own session, profile or security events is account, not auth", () => { + for (const path of ["/v1/auth/session", "/v1/auth/profile", "/v1/auth/security-events"]) { + expect(authRouteFamily(get(path, "tok_x"), path)).toBe("account"); + } + const patch = makeRequest({ url: "https://api.example.com/v1/auth/profile", method: "PATCH", bearer: "tok_x" }); + expect(authRouteFamily(patch, "/v1/auth/profile")).toBe("account"); + }); + + it("sign-in, OAuth, logout and anything without a bearer stay on the tight auth family", () => { + expect(authRouteFamily(makeRequest({}), "/v1/auth/login/start")).toBe("auth"); + expect(authRouteFamily(get("/v1/auth/oauth/github/start"), "/v1/auth/oauth/github/start")).toBe("auth"); + expect(authRouteFamily(makeRequest({ url: "https://api.example.com/v1/auth/logout", bearer: "tok_x" }), "/v1/auth/logout")).toBe("auth"); + expect(authRouteFamily(get("/v1/auth/session"), "/v1/auth/session")).toBe("auth"); + }); + + it("lets a signed-in session make the admin's page loads, still capped", () => { + expect(__rateLimitConfigForTest.account.identity.limit).toBeGreaterThanOrEqual(60); + expect(__rateLimitConfigForTest.auth.identity.limit).toBeLessThan(__rateLimitConfigForTest.account.identity.limit); + }); + }); + describe("under-limit allows + emits headers", () => { it("allowed result carries X-RateLimit-Limit/Remaining/Reset for active scopes", async () => { const kv = createFakeKv(); diff --git a/tests/cms/docs/overview.md b/tests/cms/docs/overview.md index 0b3c1df..443101a 100644 --- a/tests/cms/docs/overview.md +++ b/tests/cms/docs/overview.md @@ -15,7 +15,10 @@ this component changed. A red suite blocks the merge. | `users` | No CMS passwords (the local strategy is off, `lumen` is the strategy); a role is optional and no role means pending; `lumenUserId` is unique and no request sets it; a pending account reads only itself. | | `lumen-strategy` | Only a live Lumen session in the cookie signs anyone in, never a background request from another site; the token is never on the user; the first admin needs the setup cookie; sign-out revokes the session and clears the cookie. | | `lumen-accounts` | A Lumen user is found by link, linked once by email (an invitation keeps its role) or created pending; nobody becomes admin without setup while no admin exists; a create race reads the row back. | -| `lumen-session` | api-edge is asked with the bearer token; answers are remembered 30 s per token; api-edge being down fails closed and is not remembered. | +| `lumen-session` | api-edge is asked with the bearer token; answers are remembered 30 s per token; concurrent requests share one lookup; a confirmed session survives api-edge being unable to answer for up to 5 minutes (until it expires), and anything else fails closed. | +| `lumen-account-api` | The account pages call api-edge's own routes with the person's token; the security-events cursor goes back as given; a requested organization is used only if it is the person's. | +| `lumen-forms` | The account forms accept only same-origin posts from staff (a pending account goes to the pending page), save at Lumen with the person's session, copy the display name onto the `users` row, save every email category, and report Lumen's refusals. | +| `lumen-model-*` | The console's profile, notification-preference and security-event models, copied with their tests. | | `lumen-cookies` | The session cookie is HttpOnly, Lax, at most 30 days; a redirect never leaves `/admin`; the origin checks refuse other sites. | | `access` | Published pages, posts and categories are public; drafts and everything else need staff; only admins delete or manage accounts; an editor cannot change a role. | | `request-scoped-pool` | Every query and transaction opens its own Postgres client and closes it, so no request awaits a socket another request opened (workerd forbids that). | diff --git a/tests/cms/package.json b/tests/cms/package.json index 70f384d..b04cb0f 100644 --- a/tests/cms/package.json +++ b/tests/cms/package.json @@ -10,6 +10,7 @@ "lint": "eslint src" }, "devDependencies": { + "@saas/contracts": "workspace:*", "@saas/eslint-config": "workspace:*", "@saas/tsconfig": "workspace:*", "@types/jest": "^29.5.14", diff --git a/tests/cms/src/lumen-account-api.test.ts b/tests/cms/src/lumen-account-api.test.ts new file mode 100644 index 0000000..4338888 --- /dev/null +++ b/tests/cms/src/lumen-account-api.test.ts @@ -0,0 +1,61 @@ +import { getPreferences, listOrganizations, listSecurityEvents, pickOrganization, updatePreferences, updateProfile } from '@cms/lib/lumen/account-api' +import type { LumenTransport } from '@cms/lib/lumen/client' + +// The Lumen calls behind the account pages (lumen-payload-console design §4). + +function fake(status: number, body: unknown) { + const calls: { path: string; method: string; auth: string | null; body: unknown }[] = [] + const transport: LumenTransport = async (path, init) => { + const headers = new Headers(init.headers) + calls.push({ path, method: init.method ?? 'GET', auth: headers.get('authorization'), body: init.body ? JSON.parse(String(init.body)) : undefined }) + return new Response(JSON.stringify(body), { status }) + } + return { transport, calls } +} + +const org = (id: string) => ({ id, name: id, slug: id, createdAt: '2026-10-28T00:00:00Z' }) + +describe('account api', () => { + it('sends the session token and reads the envelope', async () => { + const f = fake(200, { data: { organizations: [org('org_1')] }, meta: { requestId: 'r' } }) + await expect(listOrganizations(f.transport, 'tok')).resolves.toEqual({ ok: true, value: [org('org_1')] }) + expect(f.calls).toEqual([{ path: '/v1/organizations', method: 'GET', auth: 'Bearer tok', body: undefined }]) + }) + + it('passes the security-events cursor back as given and returns the next one from meta', async () => { + const f = fake(200, { data: { securityEvents: [{ id: 'e1' }] }, meta: { requestId: 'r', cursor: 'b+/=' } }) + const page = await listSecurityEvents(f.transport, 'tok', 'a+/=') + expect(f.calls[0]!.path).toBe('/v1/auth/security-events?cursor=a%2B%2F%3D') + expect(page).toEqual({ ok: true, value: { events: [{ id: 'e1' }], nextCursor: 'b+/=' } }) + const last = fake(200, { data: { securityEvents: [] }, meta: { requestId: 'r', cursor: null } }) + await expect(listSecurityEvents(last.transport, 'tok')).resolves.toEqual({ ok: true, value: { events: [], nextCursor: null } }) + expect(last.calls[0]!.path).toBe('/v1/auth/security-events') + }) + + it('reports an api-edge error with its code', async () => { + const f = fake(429, { error: { code: 'rate_limited', message: 'slow down' } }) + await expect(updateProfile(f.transport, 'tok', { displayName: 'A' })).resolves.toMatchObject({ ok: false, status: 429, code: 'rate_limited' }) + expect(f.calls[0]).toMatchObject({ path: '/v1/auth/profile', method: 'PATCH', body: { displayName: 'A' } }) + }) + + it('reads and writes email preferences for the person in one organization', async () => { + const g = fake(200, { data: { preferences: [] } }) + await getPreferences(g.transport, 'tok', 'org 1') + expect(g.calls[0]!.path).toBe('/v1/notifications/preferences?orgId=org%201') + const p = fake(200, { data: { preference: { orgId: 'org_1' } } }) + await updatePreferences(p.transport, 'tok', { orgId: 'org_1', userId: 'usr_1', categories: { billing: false } }) + expect(p.calls[0]).toMatchObject({ + path: '/v1/notifications/preferences', + method: 'PUT', + body: { orgId: 'org_1', subjectKind: 'user', subjectId: 'usr_1', channel: 'email', categories: { billing: false } }, + }) + }) + + it('picks the organization asked for only among the person’s own, else their first', () => { + const orgs = [org('a'), org('b')] + expect(pickOrganization(orgs, 'b')?.id).toBe('b') + expect(pickOrganization(orgs, 'someone-elses')?.id).toBe('a') + expect(pickOrganization(orgs, undefined)?.id).toBe('a') + expect(pickOrganization([], 'a')).toBeNull() + }) +}) diff --git a/tests/cms/src/lumen-forms.test.ts b/tests/cms/src/lumen-forms.test.ts new file mode 100644 index 0000000..c7395a4 --- /dev/null +++ b/tests/cms/src/lumen-forms.test.ts @@ -0,0 +1,120 @@ +import type { LumenTransport } from '@cms/lib/lumen/client' +import { LUMEN_SESSION_COOKIE } from '@cms/lib/lumen/cookies' +import { backTo, categoriesFromForm, type FormDeps, type FormUser, notificationsForm, profileForm } from '@cms/lib/lumen/forms' +import { statusMessage } from '@cms/lib/lumen/status' + +// The account pages' form handlers (lumen-payload-console design §4). + +const ORIGIN = 'https://lumen-payload-cms-stage.nexo-7be.workers.dev' +const editor: FormUser = { id: 7, role: 'editor', lumenUserId: 'usr_ed', collection: 'users' } + +function setup(user: FormUser | null = editor, answer: { status: number; body: unknown } = { status: 200, body: { data: { user: { id: 'usr_ed', email: 'ed@example.com', displayName: 'Ed' } } } }) { + const calls: { path: string; method: string; auth: string | null; body: unknown }[] = [] + const names: unknown[] = [] + const transport: LumenTransport = async (path, init) => { + calls.push({ path, method: init.method ?? 'GET', auth: new Headers(init.headers).get('authorization'), body: init.body ? JSON.parse(String(init.body)) : undefined }) + return new Response(JSON.stringify(answer.body), { status: answer.status }) + } + const deps: FormDeps = { + transport: async () => transport, + authenticate: async () => user, + syncName: async (id, name) => { + names.push([id, name]) + }, + } + return { deps, calls, names } +} + +function post(path: string, fields: Record, headers: Record = {}) { + return new Request(`${ORIGIN}${path}`, { + method: 'POST', + headers: { origin: ORIGIN, cookie: `${LUMEN_SESSION_COOKIE}=tok`, 'content-type': 'application/x-www-form-urlencoded', ...headers }, + body: new URLSearchParams(fields).toString(), + }) +} + +describe('account forms', () => { + it('refuse a post from another origin, a sibling Worker included, and call nothing', async () => { + const s = setup() + const res = await profileForm(post('/lumen/profile', { displayName: 'X' }, { origin: 'https://lumen-payload-web-console-next-stage.nexo-7be.workers.dev' }), s.deps) + expect(res.status).toBe(403) + expect(s.calls).toHaveLength(0) + }) + + it('send a signed-out visitor to the sign-in, and a pending account to the pending page', async () => { + const out = await profileForm(post('/lumen/profile', {}, { cookie: '' }), setup().deps) + expect([out.status, out.headers.get('location')]).toEqual([303, '/admin/login?redirect=%2Fadmin%2Faccount']) + const pending = await profileForm(post('/lumen/profile', {}), setup({ id: 8, role: null, lumenUserId: 'usr_p' }).deps) + expect(pending.headers.get('location')).toBe('/admin/unauthorized') + }) + + it('save the display name at Lumen with the session, copy it onto the users row, and say so', async () => { + const s = setup() + const res = await profileForm(post('/lumen/profile', { displayName: ' Ed ' }), s.deps) + expect([res.status, res.headers.get('location')]).toEqual([303, '/admin/account?saved=1']) + expect(s.calls).toEqual([{ path: '/v1/auth/profile', method: 'PATCH', auth: 'Bearer tok', body: { displayName: 'Ed' } }]) + expect(s.names).toEqual([[7, 'Ed']]) + }) + + it('clear the name when the field is empty, and refuse one that is too long without calling Lumen', async () => { + const s = setup() + await profileForm(post('/lumen/profile', { displayName: ' ' }), s.deps) + expect(s.calls[0]!.body).toEqual({ displayName: null }) + const long = setup() + const res = await profileForm(post('/lumen/profile', { displayName: 'x'.repeat(81) }), long.deps) + expect(res.headers.get('location')).toBe('/admin/account?error=too_long') + expect(long.calls).toHaveLength(0) + }) + + it('report what Lumen said when it refuses, and leave the users row alone', async () => { + const s = setup(editor, { status: 422, body: { error: { code: 'validation_failed', message: 'no' } } }) + const res = await profileForm(post('/lumen/profile', { displayName: 'Ed' }), s.deps) + expect(res.headers.get('location')).toBe('/admin/account?error=validation_failed') + expect(s.names).toHaveLength(0) + }) + + it('save every email category for the organization as the person, ticked or not', async () => { + const s = setup(editor, { status: 200, body: { data: { preference: {} } } }) + const res = await notificationsForm(post('/lumen/notifications', { orgId: 'org_1', billing: 'on', security: 'on' }), s.deps) + expect(res.headers.get('location')).toBe('/admin/organization/notifications?org=org_1&saved=1') + expect(s.calls[0]).toEqual({ + path: '/v1/notifications/preferences', + method: 'PUT', + auth: 'Bearer tok', + body: { + orgId: 'org_1', + subjectKind: 'user', + subjectId: 'usr_ed', + channel: 'email', + categories: { invitation: false, billing: true, security: true, support: false, product: false }, + }, + }) + }) + + it('refuse a notifications form without an organization', async () => { + const s = setup() + const res = await notificationsForm(post('/lumen/notifications', { billing: 'on' }), s.deps) + expect(res.headers.get('location')).toBe('/admin/organization/notifications?error=bad_request') + expect(s.calls).toHaveLength(0) + }) + + it('read checkboxes as browsers send them: present and "on", or absent', () => { + const form = new FormData() + form.set('product', 'on') + form.set('billing', 'yes') + expect(categoriesFromForm(form)).toEqual({ invitation: false, billing: false, security: false, support: false, product: true }) + }) +}) + +describe('status lines', () => { + it('turn codes into sentences, and never echo markup', () => { + expect(statusMessage({ saved: '1' })).toEqual({ kind: 'saved', text: 'Saved.' }) + expect(statusMessage({ error: 'too_long' })?.text).toMatch(/too long/) + expect(statusMessage({ error: '' })?.text).toBe('Lumen answered with an error (scriptxscript).') + expect(statusMessage({})).toBeNull() + for (const key of ['constructor', 'toString', '__proto__', 'hasOwnProperty']) { + expect(typeof statusMessage({ error: key })?.text).toBe('string') + } + expect(backTo('/admin/account', { error: 'a b' })).toBe('/admin/account?error=a+b') + }) +}) diff --git a/tests/cms/src/lumen-model-preferences.test.ts b/tests/cms/src/lumen-model-preferences.test.ts new file mode 100644 index 0000000..b366811 --- /dev/null +++ b/tests/cms/src/lumen-model-preferences.test.ts @@ -0,0 +1,48 @@ +import { + PREFERENCE_CATEGORIES, + effectiveCategories, + buildUpdatedCategories, +} from "@cms/lib/lumen/models/preferences"; +import type { NotificationPreference } from "@saas/contracts/notifications"; + +const row = (categories: NotificationPreference["categories"]): NotificationPreference => ({ + subjectKind: "user", + subjectId: "usr_1", + orgId: "org_1", + channel: "email", + categories, + updatedAt: "2026-06-11T00:00:00Z", +}); + +describe("effectiveCategories", () => { + it("defaults every category to deliver when no row exists", () => { + const state = effectiveCategories(undefined); + for (const { key } of PREFERENCE_CATEGORIES) expect(state[key]).toBe(true); + }); + + it("treats null/missing entries as deliver and only false as suppressed", () => { + const state = effectiveCategories([row({ billing: false, product: null, support: true })]); + expect(state.billing).toBe(false); + expect(state.product).toBe(true); + expect(state.support).toBe(true); + expect(state.invitation).toBe(true); + }); + + it("ignores non-email channel rows", () => { + const other = { ...row({ billing: false }), channel: "sms" as never }; + const state = effectiveCategories([other]); + expect(state.billing).toBe(true); + }); +}); + +describe("buildUpdatedCategories", () => { + it("flips only the requested category and keeps the rest explicit", () => { + const current = effectiveCategories([row({ billing: false })]); + const next = buildUpdatedCategories(current, "product", false); + expect(next.product).toBe(false); + expect(next.billing).toBe(false); + expect(next.invitation).toBe(true); + expect(next.security).toBe(true); + expect(next.support).toBe(true); + }); +}); diff --git a/tests/cms/src/lumen-model-profile.test.ts b/tests/cms/src/lumen-model-profile.test.ts new file mode 100644 index 0000000..a3cca2a --- /dev/null +++ b/tests/cms/src/lumen-model-profile.test.ts @@ -0,0 +1,53 @@ +import { + validateDisplayName, + toDisplayNameValue, + buildProfilePatch, + initials, + DISPLAY_NAME_MAX, +} from "@cms/lib/lumen/models/profile"; + +describe("validateDisplayName", () => { + it("allows empty (clears the name)", () => { + expect(validateDisplayName("").ok).toBe(true); + expect(validateDisplayName(" ").ok).toBe(true); + }); + it("rejects over the bound, accepts at the bound", () => { + expect(validateDisplayName("a".repeat(DISPLAY_NAME_MAX)).ok).toBe(true); + expect(validateDisplayName("a".repeat(DISPLAY_NAME_MAX + 1)).ok).toBe(false); + }); +}); + +describe("toDisplayNameValue", () => { + it("trims and maps empty → null", () => { + expect(toDisplayNameValue(" Ada ")).toBe("Ada"); + expect(toDisplayNameValue(" ")).toBeNull(); + }); +}); + +describe("buildProfilePatch", () => { + it("returns null when unchanged (incl. whitespace-only edits)", () => { + expect(buildProfilePatch("Ada", "Ada")).toBeNull(); + expect(buildProfilePatch("Ada", " Ada ")).toBeNull(); + expect(buildProfilePatch(null, "")).toBeNull(); + expect(buildProfilePatch(null, " ")).toBeNull(); + }); + it("emits the new value when changed", () => { + expect(buildProfilePatch("Ada", "Grace")).toEqual({ displayName: "Grace" }); + }); + it("emits null when clearing a previously-set name", () => { + expect(buildProfilePatch("Ada", "")).toEqual({ displayName: null }); + }); +}); + +describe("initials", () => { + it("uses the display name when present", () => { + expect(initials("Ada Lovelace", "ada@x.io")).toBe("AL"); + }); + it("falls back to email local-part segments", () => { + expect(initials(null, "ada.lovelace@x.io")).toBe("AL"); + expect(initials("", "ada@x.io")).toBe("AD"); + }); + it("handles a single token", () => { + expect(initials("Madonna", "m@x.io")).toBe("MA"); + }); +}); diff --git a/tests/cms/src/lumen-model-security-events.test.ts b/tests/cms/src/lumen-model-security-events.test.ts new file mode 100644 index 0000000..a714a8a --- /dev/null +++ b/tests/cms/src/lumen-model-security-events.test.ts @@ -0,0 +1,148 @@ +import { + securityOutcomeBadge, + formatSecurityTimestamp, + toSecurityRow, + appendSecurityPage, + hasMoreSecurityEvents, + EMPTY_SECURITY_EVENTS, + type SecurityEventsState, +} from "@cms/lib/lumen/models/security-events"; +import type { PublicSecurityEvent } from "@saas/contracts/security-events"; + +function event( + over: Partial = {}, +): PublicSecurityEvent { + return { + id: "sec_1", + eventType: "session.created", + outcome: "success", + occurredAt: "2026-01-16T10:00:00.000Z", + requestId: "req_1", + correlationId: null, + ip: "203.0.113.7", + userAgent: "Mozilla/5.0", + metadata: {}, + ...over, + }; +} + +describe("securityOutcomeBadge", () => { + it("maps each known outcome to its variant + label", () => { + expect(securityOutcomeBadge("success")).toEqual({ + variant: "success", + label: "Success", + }); + expect(securityOutcomeBadge("failure")).toEqual({ + variant: "destructive", + label: "Failure", + }); + }); + + it("falls back to a neutral outline badge for an unknown outcome", () => { + const badge = securityOutcomeBadge("teleported" as never); + expect(badge.variant).toBe("outline"); + expect(badge.label).toBe("teleported"); + }); +}); + +describe("formatSecurityTimestamp", () => { + it("returns the fallback for null / undefined / empty", () => { + expect(formatSecurityTimestamp(null)).toBe("—"); + expect(formatSecurityTimestamp(undefined)).toBe("—"); + expect(formatSecurityTimestamp("")).toBe("—"); + expect(formatSecurityTimestamp(null, "never")).toBe("never"); + }); + + it("returns the fallback for an unparseable timestamp", () => { + expect(formatSecurityTimestamp("not-a-date")).toBe("—"); + }); + + it("formats a valid ISO timestamp to a non-fallback string", () => { + const out = formatSecurityTimestamp("2026-01-16T10:00:00.000Z"); + expect(out).not.toBe("—"); + expect(out.length).toBeGreaterThan(0); + }); +}); + +describe("toSecurityRow", () => { + it("shapes a successful event", () => { + const row = toSecurityRow(event()); + expect(row.id).toBe("sec_1"); + expect(row.eventType).toBe("session.created"); + expect(row.outcome).toBe("success"); + expect(row.badge.variant).toBe("success"); + expect(row.ip).toBe("203.0.113.7"); + expect(row.userAgent).toBe("Mozilla/5.0"); + expect(row.occurredAtLabel).not.toBe("—"); + }); + + it("renders an em-dash for a null ip / user-agent", () => { + const row = toSecurityRow(event({ ip: null, userAgent: null })); + expect(row.ip).toBe("—"); + expect(row.userAgent).toBe("—"); + }); + + it("surfaces a failure outcome with the destructive badge", () => { + const row = toSecurityRow( + event({ eventType: "login.challenge.failed", outcome: "failure" }), + ); + expect(row.badge.variant).toBe("destructive"); + expect(row.badge.label).toBe("Failure"); + }); +}); + +describe("appendSecurityPage", () => { + it("replaces the list on reset and records the cursor", () => { + const next = appendSecurityPage( + EMPTY_SECURITY_EVENTS, + { securityEvents: [event({ id: "a" })], nextCursor: "CUR1" }, + true, + ); + expect(next.events.map((e) => e.id)).toEqual(["a"]); + expect(next.cursor).toBe("CUR1"); + }); + + it("concatenates a subsequent page and advances the cursor", () => { + const first: SecurityEventsState = { + events: [event({ id: "a" })], + cursor: "CUR1", + }; + const next = appendSecurityPage(first, { + securityEvents: [event({ id: "b" }), event({ id: "c" })], + nextCursor: null, + }); + expect(next.events.map((e) => e.id)).toEqual(["a", "b", "c"]); + expect(next.cursor).toBeNull(); + }); + + it("is idempotent on id — a boundary event repeated across pages is not duplicated", () => { + const first: SecurityEventsState = { + events: [event({ id: "a" }), event({ id: "b" })], + cursor: "CUR1", + }; + const next = appendSecurityPage(first, { + securityEvents: [event({ id: "b" }), event({ id: "c" })], + nextCursor: "CUR2", + }); + expect(next.events.map((e) => e.id)).toEqual(["a", "b", "c"]); + expect(next.cursor).toBe("CUR2"); + }); + + it("passes the opaque cursor back verbatim without mutation", () => { + const opaque = "eyJjcm...2In0="; + const next = appendSecurityPage( + EMPTY_SECURITY_EVENTS, + { securityEvents: [], nextCursor: opaque }, + true, + ); + expect(next.cursor).toBe(opaque); + }); +}); + +describe("hasMoreSecurityEvents", () => { + it("is true only while a continuation cursor remains", () => { + expect(hasMoreSecurityEvents({ events: [], cursor: "CUR1" })).toBe(true); + expect(hasMoreSecurityEvents({ events: [], cursor: null })).toBe(false); + expect(hasMoreSecurityEvents(EMPTY_SECURITY_EVENTS)).toBe(false); + }); +}); diff --git a/tests/cms/src/lumen-session.test.ts b/tests/cms/src/lumen-session.test.ts index 535dba1..7073e30 100644 --- a/tests/cms/src/lumen-session.test.ts +++ b/tests/cms/src/lumen-session.test.ts @@ -1,5 +1,5 @@ import type { LumenTransport } from '@cms/lib/lumen/client' -import { clearSessionCache, forgetSession, resolveSession, SESSION_CACHE_MS } from '@cms/lib/lumen/session' +import { clearSessionCache, forgetSession, resolveSession, RETRY_AFTER_MS, SESSION_CACHE_MS, STALE_MAX_MS } from '@cms/lib/lumen/session' // Asking api-edge whether a token is a live session, and remembering the // answer for 30 seconds (design §2). @@ -53,6 +53,44 @@ describe('resolveSession', () => { expect(t.calls).toHaveLength(3) }) + it('asks once for concurrent requests with the same token', async () => { + let release: () => void = () => {} + const gate = new Promise((r) => (release = r)) + const t = transport([async () => (await gate, ok())]) + const all = Promise.all([resolveSession(t.fn, 'tok', 0), resolveSession(t.fn, 'tok', 0), resolveSession(t.fn, 'tok', 0)]) + release() + const sessions = await all + expect(sessions.every((s) => s?.user.id === user.id)).toBe(true) + expect(t.calls).toHaveLength(1) + }) + + it('keeps a confirmed session through a rate limit or an outage, briefly, without re-asking each time', async () => { + const t = transport([ok, () => status(429), () => status(503), () => status(429)]) + await expect(resolveSession(t.fn, 'tok', 0)).resolves.not.toBeNull() + const later = SESSION_CACHE_MS + 1 + await expect(resolveSession(t.fn, 'tok', later)).resolves.not.toBeNull() // 429: the confirmed session stands + await expect(resolveSession(t.fn, 'tok', later + 1)).resolves.not.toBeNull() // backing off: not asked + expect(t.calls).toHaveLength(2) + await expect(resolveSession(t.fn, 'tok', later + RETRY_AFTER_MS + 1)).resolves.not.toBeNull() // 503: still stands + expect(t.calls).toHaveLength(3) + // Past the stale window, failure means signed out. + await expect(resolveSession(t.fn, 'tok', STALE_MAX_MS + 1)).resolves.toBeNull() + }) + + it('never keeps a session api-edge refused, or one that has expired', async () => { + const t = transport([ok, () => status(401), () => status(429)]) + await resolveSession(t.fn, 'tok', 0) + await expect(resolveSession(t.fn, 'tok', SESSION_CACHE_MS + 1)).resolves.toBeNull() + await expect(resolveSession(t.fn, 'tok', 2 * SESSION_CACHE_MS + 2)).resolves.toBeNull() + const expired = transport([ + () => new Response(JSON.stringify({ data: { session: { id: 's', expiresAt: '1970-01-01T00:00:40Z' }, user } }), { status: 200 }), + () => status(503), + ]) + clearSessionCache() + await resolveSession(expired.fn, 'old', 0) + await expect(resolveSession(expired.fn, 'old', 41_000)).resolves.toBeNull() + }) + it('keeps tokens apart, and forgets one on sign-out', async () => { const t = transport([ok, () => status(401), () => status(401)]) await expect(resolveSession(t.fn, 'a', 0)).resolves.not.toBeNull() diff --git a/tests/identity-worker/src/security-events.test.ts b/tests/identity-worker/src/security-events.test.ts index 3030955..2a4c882 100644 --- a/tests/identity-worker/src/security-events.test.ts +++ b/tests/identity-worker/src/security-events.test.ts @@ -13,6 +13,7 @@ if (typeof globalThis.crypto.randomUUID !== "function") { import { handleSecurityEvents } from "../../../apps/identity-worker/src/handlers/security-events"; import { createAuthService } from "../../../apps/identity-worker/src/services/auth"; +import { parseUserPublicId } from "../../../apps/identity-worker/src/ids"; interface JsonResp { data: { securityEvents: PublicSecurityEvent[] }; @@ -25,7 +26,10 @@ interface JsonResp { } // Helpers to create an authenticated session and get a bearer token -async function setupAuthenticatedUser(repo: ReturnType) { +async function setupAuthenticatedUser( + repo: ReturnType, + { keepSignInEvents = false }: { keepSignInEvents?: boolean } = {}, +) { // Use a recent timestamp so the session (30-day TTL) is valid for the handler's `new Date()` const recentPast = new Date(Date.now() - 60_000); // 1 minute ago const auth = createAuthService({ repo, now: () => recentPast }); @@ -35,7 +39,14 @@ async function setupAuthenticatedUser(repo: ReturnType { expect(json.meta.cursor).toBeNull(); }); + it("returns the events sign-in itself recorded (public id in the session, UUID in the table)", async () => { + const repo = createFakeRepository(); + const { token } = await setupAuthenticatedUser(repo, { keepSignInEvents: true }); + const seen: string[] = []; + const query = repo.querySecurityEventsByUser.bind(repo); + repo.querySecurityEventsByUser = async (params) => { + seen.push(params.userId); + return query(params); + }; + + const response = await handleSecurityEvents(makeRequest(token), makeEnv(), "req_signin", { repo }); + expect(response.status).toBe(200); + const json = (await response.json()) as JsonResp; + expect(json.data.securityEvents.length).toBeGreaterThan(0); + expect(seen[0]).toMatch(/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/); + }); + it("returns security events for authenticated user", async () => { const repo = createFakeRepository(); const { token, userId } = await setupAuthenticatedUser(repo);