diff --git a/ai/context/operations.md b/ai/context/operations.md index 45b2ab9..7cc900e 100644 --- a/ai/context/operations.md +++ b/ai/context/operations.md @@ -121,7 +121,7 @@ orun integrations list --org --json && orun cloud check --org | check integrations | `orun integrations list --org --json` | | custom domain | see [Setting the domain later](#setting-the-domain-later): replace the domain string, create the zone, restore `infra/terraform/cloudflare-domain`'s commented-out `subscribe` block (it ships parked, `subscribe.environments: []`, mid-way to provider v5), merge, then run the `08-docs` phase | | headless/CI credentials | `ORUN_TOKEN` (workspace-scoped) + `GITHUB_TOKEN` | -| open the CMS admin | [Open the admin](#open-the-admin-once-per-environment): the owner sets `CMS_SETUP_TOKEN`, then visits `/setup?token=…` once | +| open the CMS admin | [Open the admin](#open-the-admin-once-per-environment): the owner sets `CMS_SETUP_TOKEN`, visits `/setup?token=…` once and signs in with Lumen | The ops phases (docs refresh and the original deployment sequence) all live in ONE versioned artifact: `repo-blueprint.yaml` in the baseline this @@ -171,8 +171,10 @@ it through `api-edge`, and no worker calls it. ### Open the admin (once per environment) -The admin ships **closed**: the first account can only be created through a -setup token the owner chooses. The full steps are in +The admin signs people in with their **Lumen account** (emailed code, GitHub +or Google); it has no passwords of its own. A new account waits, *pending*, +until an admin gives it a role in *Users*. The **first admin** needs a setup +token the owner chooses. The full steps are in [`apps/cms/docs/runbook.md`](../../apps/cms/docs/runbook.md); in short: ```bash @@ -182,18 +184,18 @@ orun secrets set CMS_SETUP_TOKEN --org --env stage # a token of 16+ chara # then visit https://lumen-payload-cms-stage..workers.dev/setup?token= ``` -The visit sets a 15-minute cookie and opens `/admin/create-first-user`. That -account is an admin; admins create every other account. Once it exists, -Payload refuses first-user creation on its own, and the token can be deleted. +The visit sets a 15-minute cookie and opens the Lumen sign-in. While no admin +exists, whoever signs in with that cookie becomes the admin; afterwards admins +make everyone else an `editor` or `admin`, and the token can be deleted. ### Verify it ```bash B=https://lumen-payload-cms-stage..workers.dev curl -fsS $B/health # {"status":"ok","db":"ok"} -curl -s -o /dev/null -w '%{http_code}\n' $B/admin # 200 -curl -s -o /dev/null -w '%{http_code}\n' -X POST $B/api/users/first-register \ - -H content-type:application/json -d '{"email":"x@example.com","password":"x"}' # 403 until setup is opened +curl -s -o /dev/null -w '%{http_code}\n' $B/admin # 200, the Lumen sign-in +curl -s -o /dev/null -w '%{http_code}\n' -X POST $B/api/users/login \ + -H content-type:application/json -d '{"email":"x@example.com","password":"x"}' # 403: no CMS passwords curl -fsS "$B/api/media?limit=1" # the media collection answers ``` @@ -231,7 +233,7 @@ anyone's real domain). Nothing that uses the domain was removed; it waits: | `intent.yaml` | `BASE_DOMAIN` (every environment) and `CONSOLE_CUSTOM_DOMAIN` (`stage.lumen-payload.example.com`, `prod.lumen-payload.example.com`) — the parameters of the parked `infra/terraform/cloudflare-domain` | | `infra/terraform/cloudflare-domain` | `baseDomain` in its `component.yaml`, the Terraform variable's default, its README | | `apps/api-edge/wrangler.template.jsonc` | `CONSOLE_CUSTOM_DOMAIN`, the console origin CORS allows besides the workers.dev one | -| `apps/identity-worker/wrangler.template.jsonc` | `OAUTH_ALLOWED_CONSOLE_ORIGINS`, which lists the workers.dev console too, so sign-in works without a domain | +| `apps/identity-worker/wrangler.template.jsonc` | `OAUTH_ALLOWED_CONSOLE_ORIGINS`, which lists the workers.dev console and CMS too, so sign-in works without a domain | | `apps/notifications-worker/wrangler.template.jsonc` | `EMAIL_FROM_ADDRESS`, `no-reply@mail.lumen-payload.example.com` | | `apps/billing-worker/wrangler.template.jsonc` | `POLAR_SUCCESS_URL`, the fallback return after checkout | | `tests/api-edge` | the CORS fixtures, which follow the edge's config | diff --git a/apps/api-edge/src/app-config.ts b/apps/api-edge/src/app-config.ts index 70bbdc5..d20c4e6 100644 --- a/apps/api-edge/src/app-config.ts +++ b/apps/api-edge/src/app-config.ts @@ -15,3 +15,15 @@ export const CONSOLE_WORKER_PREFIX = "lumen-payload-web-console-next"; export function consoleWorkersDevOrigin(environment: string): string { return `https://${CONSOLE_WORKER_PREFIX}-${environment}.${WORKERS_DEV_SUBDOMAIN}.workers.dev`; } + +/** + * Worker name prefix of the Payload CMS (apps/cms), which is becoming the + * console (specs/epics/lumen-payload-console): its sign-in page calls the + * auth routes from the browser. + */ +export const CMS_WORKER_PREFIX = "lumen-payload-cms"; + +/** workers.dev origin of the CMS for a given environment name. */ +export function cmsWorkersDevOrigin(environment: string): string { + return `https://${CMS_WORKER_PREFIX}-${environment}.${WORKERS_DEV_SUBDOMAIN}.workers.dev`; +} diff --git a/apps/api-edge/src/cors.ts b/apps/api-edge/src/cors.ts index 00f915f..7db9c0f 100644 --- a/apps/api-edge/src/cors.ts +++ b/apps/api-edge/src/cors.ts @@ -1,5 +1,5 @@ import type { Env } from "./env"; -import { consoleWorkersDevOrigin } from "./app-config"; +import { cmsWorkersDevOrigin, consoleWorkersDevOrigin } from "./app-config"; // Deploy hostnames for `apps/web-console-next` (Next.js + opennextjs/cloudflare) // under the cloudflare-workers-assets-turbo composition. Per-env naming via @@ -16,6 +16,14 @@ const WORKERS_ORIGINS: Record = { prod: consoleWorkersDevOrigin("prod"), }; +// The Payload CMS signs people in from the browser (lumen-payload-console +// design §1), so its origin may call api-edge too — each environment its own. +const CMS_ORIGINS: Record = { + dev: cmsWorkersDevOrigin("dev"), + stage: cmsWorkersDevOrigin("stage"), + prod: cmsWorkersDevOrigin("prod"), +}; + const LOCALHOST_RE = /^https?:\/\/localhost(:\d+)?$/; const VITE_DEV_RE = /^https?:\/\/127\.0\.0\.1(:\d+)?$/; @@ -46,11 +54,12 @@ export function isAllowedOrigin(origin: string | null, env: Env): boolean { if (environment === "stage" || environment === "prod") { if (customDomain && origin === `https://${customDomain}`) return true; if (origin === WORKERS_ORIGINS[environment]) return true; + if (origin === CMS_ORIGINS[environment]) return true; return false; } if (customDomain && origin === `https://${customDomain}`) return true; - for (const workerOrigin of Object.values(WORKERS_ORIGINS)) { + for (const workerOrigin of [...Object.values(WORKERS_ORIGINS), ...Object.values(CMS_ORIGINS)]) { if (origin === workerOrigin) return true; } diff --git a/apps/cms/cloudflare-env.d.ts b/apps/cms/cloudflare-env.d.ts index a64173e..e35ef78 100644 --- a/apps/cms/cloudflare-env.d.ts +++ b/apps/cms/cloudflare-env.d.ts @@ -6,6 +6,12 @@ interface CloudflareEnv { /** The media bucket (stage and prod only; infra/terraform/cloudflare-r2-cms). */ R2_MEDIA?: R2Bucket ENVIRONMENT: string + /** api-edge, over a service binding: the CMS server's way to Lumen (stage and prod). */ + LUMEN_API?: Fetcher + /** api-edge's public URL, which the browser calls to sign in. */ + LUMEN_API_PUBLIC_URL?: string + /** api-edge's URL for a local run without the binding. */ + LUMEN_API_URL?: string PAYLOAD_SECRET?: string CMS_SETUP_TOKEN?: string } diff --git a/apps/cms/component.yaml b/apps/cms/component.yaml index 35e0fcb..39b4044 100644 --- a/apps/cms/component.yaml +++ b/apps/cms/component.yaml @@ -45,6 +45,15 @@ spec: - mode: advisory when: triggerRef: github-pull-request + # Lumen sign-in (lumen-payload-console PX1): the CMS checks sessions with + # api-edge over its LUMEN_API service binding, and the sign-in page calls + # api-edge from the browser, which needs api-edge's CORS for this origin. + - component: api-edge + mode: enforced + modeRules: + - mode: advisory + when: + triggerRef: github-pull-request # Runtime secrets, pushed to the Worker by secrets-live after each deploy. # PAYLOAD_SECRET generated by cloudflare-hyperdrive-cms; nobody types it. # CMS_SETUP_TOKEN the owner's, and only if they want to open first-user diff --git a/apps/cms/docs/architecture.md b/apps/cms/docs/architecture.md index 4871034..1bc6e37 100644 --- a/apps/cms/docs/architecture.md +++ b/apps/cms/docs/architecture.md @@ -13,7 +13,10 @@ browser ──► lumen-payload-cms- (Worker) /api/graphql GraphQL ├─ payload ─► HYPERDRIVE_CMS ─► Supabase Postgres, schema cms /health liveness + db ┘ │ (cache disabled) /api/media/file/* uploaded files └──────► R2_MEDIA ─► lumen-payload-cms-media- - /setup opens first-user setup (owner only) + /setup opens first-admin setup (owner only) + /auth/lumen/* the Lumen session in, out, and the OAuth return + │ + lumen strategy ──┴──► LUMEN_API (service binding) ─► api-edge ─► identity ``` ## Bindings and secrets @@ -25,6 +28,9 @@ browser ──► lumen-payload-cms- (Worker) | `ASSETS` | static assets | `.open-next/assets` | | `ENVIRONMENT` | var | `dev` / `stage` / `prod` | | `PAYLOAD_SECRET` | secret | `CMS_PAYLOAD_SECRET`, generated by terraform; pushed by `secrets-live` | +| `LUMEN_API` | service | `lumen-payload-api-edge-` (stage, prod); who a session belongs to, and sign-out | +| `LUMEN_API_PUBLIC_URL` | var | api-edge's public URL, where the sign-in page sends the browser | +| `LUMEN_API_URL` | var, local only | api-edge over HTTPS when there is no `LUMEN_API` binding (`wrangler dev`) | | `CMS_SETUP_TOKEN` | secret, optional | the owner's (runbook); absent = setup closed | ## Decisions that shape the code @@ -49,9 +55,25 @@ browser ──► lumen-payload-cms- (Worker) it is off and Payload's local disk stands in; with no prefix configured the table is the same either way. Uploads over 10 MiB are refused (413), not stored truncated: `abortOnLimit` is on. -- **Closed by default** (`src/lib/setup-gate.ts`, `src/collections/Users.ts`, - `src/app/setup/route.ts`). Creating the first account needs the owner's - setup token; afterwards Payload refuses `first-register` itself. +- **Lumen is the only sign-in** (`src/lib/lumen/`, `src/collections/Users.ts`; + specs/epics/lumen-payload-console design §2–§3). Payload's local strategy is + off (`disableLocalStrategy: { enableFields: true }`, so the columns stay), so + 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, + 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 + 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. - **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 @@ -63,7 +85,7 @@ browser ──► lumen-payload-cms- (Worker) ## Out of scope here -Single sign-on with Lumen identity, serving content through `api-edge`, -per-tenant content, and image derivatives: resizing, cropping and focal +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 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 2bd066e..aa30d87 100644 --- a/apps/cms/docs/overview.md +++ b/apps/cms/docs/overview.md @@ -10,8 +10,11 @@ at `/api/` and GraphQL at `/api/graphql`, over Postgres schema ## What it holds -- **users**: staff accounts (`admin`, `editor`). The first account is created - through the setup gate and is an admin; admins create the rest. +- **users**: staff accounts, one per Lumen account that signed in + (`lumenUserId`). Sign-in is Lumen's (emailed code, GitHub, Google); there are + no CMS passwords. A new account has no role until an admin makes it an + `editor` or `admin`; the first admin signs in through the owner's setup + token. - **pages** and **posts**: drafts, versions (25 per document), a Lexical rich-text body and a unique slug. Posts have an excerpt and a category. - **categories**: name and slug. @@ -29,10 +32,14 @@ Staff upload media; only admins delete it. - **cloudflare-hyperdrive-cms**: its database path (cache disabled) and its generated Payload secret. - **cloudflare-r2-cms**: its media bucket. -- **db-migrate**: applies schema `cms` (migrations `200_cms_payload_core` and - `205_cms_media`) before the CMS deploys. - -Nothing in the fleet calls the CMS, and the CMS calls nothing in the fleet. +- **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 + sign-in page call the auth routes, and identity-worker's OAuth return + allowlist includes the CMS. + +Nothing in the fleet calls the CMS. ## Verified by diff --git a/apps/cms/docs/runbook.md b/apps/cms/docs/runbook.md index ff03838..4ddec93 100644 --- a/apps/cms/docs/runbook.md +++ b/apps/cms/docs/runbook.md @@ -9,10 +9,27 @@ wiring, runs `wrangler deploy`, pushes the runtime secrets, and smoke-checks `/health` and `/admin` (retried for about 4.5 minutes). Pull requests build, typecheck and dry-run the deploy; nothing deploys from a pull request. -## Open the admin (first account) +## Sign in -The CMS ships closed: nobody can create the first account until the owner opens -setup. Once per environment: +The admin has no passwords of its own. `/admin` shows a Lumen sign-in: an +emailed code, or GitHub or Google where the identity plane has them +configured. The sign-in runs against `api-edge` from the browser; the Lumen +session it returns goes to `/auth/lumen/session`, which puts it in an +HttpOnly `lumen_session` cookie on the CMS host and never shows it to page +scripts. Each request, the `lumen` auth strategy (`src/lib/lumen/`) asks +`api-edge` who the cookie belongs to (cached 30 s) and maps the Lumen user to +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. + +## Open the admin (first admin) + +Nobody becomes an admin by signing in, except through setup, which the owner +opens. Once per environment: 1. Choose a token of at least 16 characters, and keep it to yourself. 2. Give it to the Worker, either way: @@ -21,9 +38,11 @@ setup. Once per environment: - directly: `pnpm exec wrangler secret put CMS_SETUP_TOKEN --name lumen-payload-cms-` (it prompts for the value). 3. Visit `https://lumen-payload-cms-.nexo-7be.workers.dev/setup?token=`. - It sets a 15-minute cookie and sends you to `/admin/create-first-user`. -4. Create the account. It becomes an admin. From then on, admins create every - other account in `/admin`, and setup is irrelevant. + It sets a 15-minute cookie and sends you to the sign-in page. +4. Sign in with your Lumen account. While no admin exists, the account that + signs in with that cookie becomes the admin (a pending account is promoted). + From then on, admins give everyone else their role in *Users*, and setup + changes nothing. You can delete `CMS_SETUP_TOKEN` afterwards; nothing needs it. @@ -32,7 +51,9 @@ You can delete `CMS_SETUP_TOKEN` afterwards; nothing needs it. ```bash B=https://lumen-payload-cms-stage.nexo-7be.workers.dev curl -fsS $B/health # {"status":"ok","db":"ok"} -curl -s -o /dev/null -w '%{http_code}\n' $B/admin # 200 +curl -s -o /dev/null -w '%{http_code}\n' $B/admin # 200, the Lumen sign-in +curl -s -o /dev/null -w '%{http_code}\n' -X POST $B/api/users/login \ + -H content-type:application/json -d '{"email":"x@example.com","password":"x"}' # 403: no passwords curl -s -o /dev/null -w '%{http_code}\n' -X POST $B/api/users/first-register \ -H content-type:application/json -d '{"email":"x@example.com","password":"x"}' # 403 curl -fsS "$B/api/pages?limit=5" # published pages only @@ -51,8 +72,8 @@ a suffix (`photo-1.jpg`). Only admins delete media; deleting removes the object from the bucket too. ```bash -# as staff (a session token from /api/users/login): -curl -H "Authorization: JWT " -F "file=@photo.jpg;type=image/jpeg" \ +# as staff: the lumen_session cookie of a signed-in browser (a Lumen session token) +curl -H "Cookie: lumen_session=" -F "file=@photo.jpg;type=image/jpeg" \ -F '_payload={"alt":"What the photo shows"}' "$B/api/media" curl -fsS -o /dev/null -w '%{http_code}\n' "$B/api/media/file/photo.jpg" # 200 ``` @@ -82,17 +103,23 @@ curl -fsS -o /dev/null -w '%{http_code}\n' "$B/api/media/file/photo.jpg" # 200 ```bash # Postgres 16 on 127.0.0.1:54329 with a database `cms`, then: export DATABASE_URL=postgres://postgres:@127.0.0.1:54329/cms -for m in 200_cms_payload_core 205_cms_media; do psql "$DATABASE_URL" -f ../../packages/db/src/migrations/$m/up.sql; done +for m in 200_cms_payload_core 205_cms_media 206_cms_lumen_identity; do psql "$DATABASE_URL" -f ../../packages/db/src/migrations/$m/up.sql; done pnpm dev # Node, http://localhost:3002; uploads go to a local folder # The real runtime (workerd), after `pnpm build`: node ../../tooling/wire/render.mjs --template wrangler.template.jsonc --out wrangler.jsonc --map wiring.fixture.json -printf 'PAYLOAD_SECRET=%s\nCMS_SETUP_TOKEN=%s\n' "$(openssl rand -hex 24)" "$(openssl rand -hex 16)" > .dev.vars +# no api-edge runs locally: drop env.stage.services from wrangler.jsonc, and +# point the CMS at stage's api-edge instead +printf 'PAYLOAD_SECRET=%s\nCMS_SETUP_TOKEN=%s\nLUMEN_API_URL=%s\n' "$(openssl rand -hex 24)" "$(openssl rand -hex 16)" \ + https://lumen-payload-api-edge-stage.nexo-7be.workers.dev > .dev.vars CLOUDFLARE_HYPERDRIVE_LOCAL_CONNECTION_STRING_HYPERDRIVE_CMS="$DATABASE_URL" \ - pnpm exec wrangler dev --config wrangler.jsonc --env stage --port 8799 + pnpm exec wrangler dev --config wrangler.jsonc --env stage --port 8799 --ip 127.0.0.1 ``` -`wrangler dev` needs a password in the local connection string. It serves +`wrangler dev` needs a password in the local connection string. Without the +`LUMEN_API` service binding the CMS reaches `api-edge` over `LUMEN_API_URL`. +Stage's `api-edge` accepts `http://127.0.0.1:` and shows the emailed +code on the sign-in page, so a local sign-in needs no inbox. It serves `R2_MEDIA` from a local bucket under `.wrangler/state`, so uploads exercise the real R2 adapter. diff --git a/apps/cms/payload-migrations/20261028_121234_cms_lumen_identity.json b/apps/cms/payload-migrations/20261028_121234_cms_lumen_identity.json new file mode 100644 index 0000000..e396b24 --- /dev/null +++ b/apps/cms/payload-migrations/20261028_121234_cms_lumen_identity.json @@ -0,0 +1,2026 @@ +{ + "version": "7", + "dialect": "postgresql", + "tables": { + "cms.users_sessions": { + "name": "users_sessions", + "schema": "cms", + "columns": { + "_order": { + "name": "_order", + "type": "integer", + "primaryKey": false, + "notNull": true + }, + "_parent_id": { + "name": "_parent_id", + "type": "uuid", + "primaryKey": false, + "notNull": true + }, + "id": { + "name": "id", + "type": "varchar", + "primaryKey": true, + "notNull": true + }, + "created_at": { + "name": "created_at", + "type": "timestamp(3) with time zone", + "primaryKey": false, + "notNull": false + }, + "expires_at": { + "name": "expires_at", + "type": "timestamp(3) with time zone", + "primaryKey": false, + "notNull": true + } + }, + "indexes": { + "users_sessions_order_idx": { + "name": "users_sessions_order_idx", + "columns": [ + { + "expression": "_order", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + }, + "users_sessions_parent_id_idx": { + "name": "users_sessions_parent_id_idx", + "columns": [ + { + "expression": "_parent_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + } + }, + "foreignKeys": { + "users_sessions_parent_id_fk": { + "name": "users_sessions_parent_id_fk", + "tableFrom": "users_sessions", + "tableTo": "users", + "schemaTo": "cms", + "columnsFrom": [ + "_parent_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "cascade", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "cms.users": { + "name": "users", + "schema": "cms", + "columns": { + "id": { + "name": "id", + "type": "uuid", + "primaryKey": true, + "notNull": true, + "default": "gen_random_uuid()" + }, + "name": { + "name": "name", + "type": "varchar", + "primaryKey": false, + "notNull": false + }, + "role": { + "name": "role", + "type": "enum_users_role", + "typeSchema": "cms", + "primaryKey": false, + "notNull": false + }, + "lumen_user_id": { + "name": "lumen_user_id", + "type": "varchar", + "primaryKey": false, + "notNull": false + }, + "updated_at": { + "name": "updated_at", + "type": "timestamp(3) with time zone", + "primaryKey": false, + "notNull": true, + "default": "now()" + }, + "created_at": { + "name": "created_at", + "type": "timestamp(3) with time zone", + "primaryKey": false, + "notNull": true, + "default": "now()" + }, + "email": { + "name": "email", + "type": "varchar", + "primaryKey": false, + "notNull": true + }, + "reset_password_token": { + "name": "reset_password_token", + "type": "varchar", + "primaryKey": false, + "notNull": false + }, + "reset_password_expiration": { + "name": "reset_password_expiration", + "type": "timestamp(3) with time zone", + "primaryKey": false, + "notNull": false + }, + "salt": { + "name": "salt", + "type": "varchar", + "primaryKey": false, + "notNull": false + }, + "hash": { + "name": "hash", + "type": "varchar", + "primaryKey": false, + "notNull": false + }, + "login_attempts": { + "name": "login_attempts", + "type": "numeric", + "primaryKey": false, + "notNull": false, + "default": 0 + }, + "lock_until": { + "name": "lock_until", + "type": "timestamp(3) with time zone", + "primaryKey": false, + "notNull": false + } + }, + "indexes": { + "users_lumen_user_id_idx": { + "name": "users_lumen_user_id_idx", + "columns": [ + { + "expression": "lumen_user_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": true, + "concurrently": false, + "method": "btree", + "with": {} + }, + "users_updated_at_idx": { + "name": "users_updated_at_idx", + "columns": [ + { + "expression": "updated_at", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + }, + "users_created_at_idx": { + "name": "users_created_at_idx", + "columns": [ + { + "expression": "created_at", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + }, + "users_email_idx": { + "name": "users_email_idx", + "columns": [ + { + "expression": "email", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": true, + "concurrently": false, + "method": "btree", + "with": {} + } + }, + "foreignKeys": {}, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "cms.pages": { + "name": "pages", + "schema": "cms", + "columns": { + "id": { + "name": "id", + "type": "uuid", + "primaryKey": true, + "notNull": true, + "default": "gen_random_uuid()" + }, + "title": { + "name": "title", + "type": "varchar", + "primaryKey": false, + "notNull": false + }, + "slug": { + "name": "slug", + "type": "varchar", + "primaryKey": false, + "notNull": false + }, + "content": { + "name": "content", + "type": "jsonb", + "primaryKey": false, + "notNull": false + }, + "published_at": { + "name": "published_at", + "type": "timestamp(3) with time zone", + "primaryKey": false, + "notNull": false + }, + "updated_at": { + "name": "updated_at", + "type": "timestamp(3) with time zone", + "primaryKey": false, + "notNull": true, + "default": "now()" + }, + "created_at": { + "name": "created_at", + "type": "timestamp(3) with time zone", + "primaryKey": false, + "notNull": true, + "default": "now()" + }, + "_status": { + "name": "_status", + "type": "enum_pages_status", + "typeSchema": "cms", + "primaryKey": false, + "notNull": false, + "default": "'draft'" + } + }, + "indexes": { + "pages_slug_idx": { + "name": "pages_slug_idx", + "columns": [ + { + "expression": "slug", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": true, + "concurrently": false, + "method": "btree", + "with": {} + }, + "pages_updated_at_idx": { + "name": "pages_updated_at_idx", + "columns": [ + { + "expression": "updated_at", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + }, + "pages_created_at_idx": { + "name": "pages_created_at_idx", + "columns": [ + { + "expression": "created_at", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + }, + "pages__status_idx": { + "name": "pages__status_idx", + "columns": [ + { + "expression": "_status", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + } + }, + "foreignKeys": {}, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "cms._pages_v": { + "name": "_pages_v", + "schema": "cms", + "columns": { + "id": { + "name": "id", + "type": "uuid", + "primaryKey": true, + "notNull": true, + "default": "gen_random_uuid()" + }, + "parent_id": { + "name": "parent_id", + "type": "uuid", + "primaryKey": false, + "notNull": false + }, + "version_title": { + "name": "version_title", + "type": "varchar", + "primaryKey": false, + "notNull": false + }, + "version_slug": { + "name": "version_slug", + "type": "varchar", + "primaryKey": false, + "notNull": false + }, + "version_content": { + "name": "version_content", + "type": "jsonb", + "primaryKey": false, + "notNull": false + }, + "version_published_at": { + "name": "version_published_at", + "type": "timestamp(3) with time zone", + "primaryKey": false, + "notNull": false + }, + "version_updated_at": { + "name": "version_updated_at", + "type": "timestamp(3) with time zone", + "primaryKey": false, + "notNull": false + }, + "version_created_at": { + "name": "version_created_at", + "type": "timestamp(3) with time zone", + "primaryKey": false, + "notNull": false + }, + "version__status": { + "name": "version__status", + "type": "enum__pages_v_version_status", + "typeSchema": "cms", + "primaryKey": false, + "notNull": false, + "default": "'draft'" + }, + "created_at": { + "name": "created_at", + "type": "timestamp(3) with time zone", + "primaryKey": false, + "notNull": true, + "default": "now()" + }, + "updated_at": { + "name": "updated_at", + "type": "timestamp(3) with time zone", + "primaryKey": false, + "notNull": true, + "default": "now()" + }, + "latest": { + "name": "latest", + "type": "boolean", + "primaryKey": false, + "notNull": false + } + }, + "indexes": { + "_pages_v_parent_idx": { + "name": "_pages_v_parent_idx", + "columns": [ + { + "expression": "parent_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + }, + "_pages_v_version_version_slug_idx": { + "name": "_pages_v_version_version_slug_idx", + "columns": [ + { + "expression": "version_slug", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + }, + "_pages_v_version_version_updated_at_idx": { + "name": "_pages_v_version_version_updated_at_idx", + "columns": [ + { + "expression": "version_updated_at", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + }, + "_pages_v_version_version_created_at_idx": { + "name": "_pages_v_version_version_created_at_idx", + "columns": [ + { + "expression": "version_created_at", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + }, + "_pages_v_version_version__status_idx": { + "name": "_pages_v_version_version__status_idx", + "columns": [ + { + "expression": "version__status", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + }, + "_pages_v_created_at_idx": { + "name": "_pages_v_created_at_idx", + "columns": [ + { + "expression": "created_at", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + }, + "_pages_v_updated_at_idx": { + "name": "_pages_v_updated_at_idx", + "columns": [ + { + "expression": "updated_at", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + }, + "_pages_v_latest_idx": { + "name": "_pages_v_latest_idx", + "columns": [ + { + "expression": "latest", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + } + }, + "foreignKeys": { + "_pages_v_parent_id_pages_id_fk": { + "name": "_pages_v_parent_id_pages_id_fk", + "tableFrom": "_pages_v", + "tableTo": "pages", + "schemaTo": "cms", + "columnsFrom": [ + "parent_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "set null", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "cms.posts": { + "name": "posts", + "schema": "cms", + "columns": { + "id": { + "name": "id", + "type": "uuid", + "primaryKey": true, + "notNull": true, + "default": "gen_random_uuid()" + }, + "title": { + "name": "title", + "type": "varchar", + "primaryKey": false, + "notNull": false + }, + "slug": { + "name": "slug", + "type": "varchar", + "primaryKey": false, + "notNull": false + }, + "excerpt": { + "name": "excerpt", + "type": "varchar", + "primaryKey": false, + "notNull": false + }, + "content": { + "name": "content", + "type": "jsonb", + "primaryKey": false, + "notNull": false + }, + "category_id": { + "name": "category_id", + "type": "uuid", + "primaryKey": false, + "notNull": false + }, + "published_at": { + "name": "published_at", + "type": "timestamp(3) with time zone", + "primaryKey": false, + "notNull": false + }, + "updated_at": { + "name": "updated_at", + "type": "timestamp(3) with time zone", + "primaryKey": false, + "notNull": true, + "default": "now()" + }, + "created_at": { + "name": "created_at", + "type": "timestamp(3) with time zone", + "primaryKey": false, + "notNull": true, + "default": "now()" + }, + "_status": { + "name": "_status", + "type": "enum_posts_status", + "typeSchema": "cms", + "primaryKey": false, + "notNull": false, + "default": "'draft'" + } + }, + "indexes": { + "posts_slug_idx": { + "name": "posts_slug_idx", + "columns": [ + { + "expression": "slug", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": true, + "concurrently": false, + "method": "btree", + "with": {} + }, + "posts_category_idx": { + "name": "posts_category_idx", + "columns": [ + { + "expression": "category_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + }, + "posts_updated_at_idx": { + "name": "posts_updated_at_idx", + "columns": [ + { + "expression": "updated_at", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + }, + "posts_created_at_idx": { + "name": "posts_created_at_idx", + "columns": [ + { + "expression": "created_at", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + }, + "posts__status_idx": { + "name": "posts__status_idx", + "columns": [ + { + "expression": "_status", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + } + }, + "foreignKeys": { + "posts_category_id_categories_id_fk": { + "name": "posts_category_id_categories_id_fk", + "tableFrom": "posts", + "tableTo": "categories", + "schemaTo": "cms", + "columnsFrom": [ + "category_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "set null", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "cms._posts_v": { + "name": "_posts_v", + "schema": "cms", + "columns": { + "id": { + "name": "id", + "type": "uuid", + "primaryKey": true, + "notNull": true, + "default": "gen_random_uuid()" + }, + "parent_id": { + "name": "parent_id", + "type": "uuid", + "primaryKey": false, + "notNull": false + }, + "version_title": { + "name": "version_title", + "type": "varchar", + "primaryKey": false, + "notNull": false + }, + "version_slug": { + "name": "version_slug", + "type": "varchar", + "primaryKey": false, + "notNull": false + }, + "version_excerpt": { + "name": "version_excerpt", + "type": "varchar", + "primaryKey": false, + "notNull": false + }, + "version_content": { + "name": "version_content", + "type": "jsonb", + "primaryKey": false, + "notNull": false + }, + "version_category_id": { + "name": "version_category_id", + "type": "uuid", + "primaryKey": false, + "notNull": false + }, + "version_published_at": { + "name": "version_published_at", + "type": "timestamp(3) with time zone", + "primaryKey": false, + "notNull": false + }, + "version_updated_at": { + "name": "version_updated_at", + "type": "timestamp(3) with time zone", + "primaryKey": false, + "notNull": false + }, + "version_created_at": { + "name": "version_created_at", + "type": "timestamp(3) with time zone", + "primaryKey": false, + "notNull": false + }, + "version__status": { + "name": "version__status", + "type": "enum__posts_v_version_status", + "typeSchema": "cms", + "primaryKey": false, + "notNull": false, + "default": "'draft'" + }, + "created_at": { + "name": "created_at", + "type": "timestamp(3) with time zone", + "primaryKey": false, + "notNull": true, + "default": "now()" + }, + "updated_at": { + "name": "updated_at", + "type": "timestamp(3) with time zone", + "primaryKey": false, + "notNull": true, + "default": "now()" + }, + "latest": { + "name": "latest", + "type": "boolean", + "primaryKey": false, + "notNull": false + } + }, + "indexes": { + "_posts_v_parent_idx": { + "name": "_posts_v_parent_idx", + "columns": [ + { + "expression": "parent_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + }, + "_posts_v_version_version_slug_idx": { + "name": "_posts_v_version_version_slug_idx", + "columns": [ + { + "expression": "version_slug", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + }, + "_posts_v_version_version_category_idx": { + "name": "_posts_v_version_version_category_idx", + "columns": [ + { + "expression": "version_category_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + }, + "_posts_v_version_version_updated_at_idx": { + "name": "_posts_v_version_version_updated_at_idx", + "columns": [ + { + "expression": "version_updated_at", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + }, + "_posts_v_version_version_created_at_idx": { + "name": "_posts_v_version_version_created_at_idx", + "columns": [ + { + "expression": "version_created_at", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + }, + "_posts_v_version_version__status_idx": { + "name": "_posts_v_version_version__status_idx", + "columns": [ + { + "expression": "version__status", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + }, + "_posts_v_created_at_idx": { + "name": "_posts_v_created_at_idx", + "columns": [ + { + "expression": "created_at", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + }, + "_posts_v_updated_at_idx": { + "name": "_posts_v_updated_at_idx", + "columns": [ + { + "expression": "updated_at", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + }, + "_posts_v_latest_idx": { + "name": "_posts_v_latest_idx", + "columns": [ + { + "expression": "latest", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + } + }, + "foreignKeys": { + "_posts_v_parent_id_posts_id_fk": { + "name": "_posts_v_parent_id_posts_id_fk", + "tableFrom": "_posts_v", + "tableTo": "posts", + "schemaTo": "cms", + "columnsFrom": [ + "parent_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "set null", + "onUpdate": "no action" + }, + "_posts_v_version_category_id_categories_id_fk": { + "name": "_posts_v_version_category_id_categories_id_fk", + "tableFrom": "_posts_v", + "tableTo": "categories", + "schemaTo": "cms", + "columnsFrom": [ + "version_category_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "set null", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "cms.categories": { + "name": "categories", + "schema": "cms", + "columns": { + "id": { + "name": "id", + "type": "uuid", + "primaryKey": true, + "notNull": true, + "default": "gen_random_uuid()" + }, + "name": { + "name": "name", + "type": "varchar", + "primaryKey": false, + "notNull": true + }, + "slug": { + "name": "slug", + "type": "varchar", + "primaryKey": false, + "notNull": true + }, + "updated_at": { + "name": "updated_at", + "type": "timestamp(3) with time zone", + "primaryKey": false, + "notNull": true, + "default": "now()" + }, + "created_at": { + "name": "created_at", + "type": "timestamp(3) with time zone", + "primaryKey": false, + "notNull": true, + "default": "now()" + } + }, + "indexes": { + "categories_slug_idx": { + "name": "categories_slug_idx", + "columns": [ + { + "expression": "slug", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": true, + "concurrently": false, + "method": "btree", + "with": {} + }, + "categories_updated_at_idx": { + "name": "categories_updated_at_idx", + "columns": [ + { + "expression": "updated_at", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + }, + "categories_created_at_idx": { + "name": "categories_created_at_idx", + "columns": [ + { + "expression": "created_at", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + } + }, + "foreignKeys": {}, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "cms.media": { + "name": "media", + "schema": "cms", + "columns": { + "id": { + "name": "id", + "type": "uuid", + "primaryKey": true, + "notNull": true, + "default": "gen_random_uuid()" + }, + "alt": { + "name": "alt", + "type": "varchar", + "primaryKey": false, + "notNull": true + }, + "updated_at": { + "name": "updated_at", + "type": "timestamp(3) with time zone", + "primaryKey": false, + "notNull": true, + "default": "now()" + }, + "created_at": { + "name": "created_at", + "type": "timestamp(3) with time zone", + "primaryKey": false, + "notNull": true, + "default": "now()" + }, + "url": { + "name": "url", + "type": "varchar", + "primaryKey": false, + "notNull": false + }, + "thumbnail_u_r_l": { + "name": "thumbnail_u_r_l", + "type": "varchar", + "primaryKey": false, + "notNull": false + }, + "filename": { + "name": "filename", + "type": "varchar", + "primaryKey": false, + "notNull": false + }, + "mime_type": { + "name": "mime_type", + "type": "varchar", + "primaryKey": false, + "notNull": false + }, + "filesize": { + "name": "filesize", + "type": "numeric", + "primaryKey": false, + "notNull": false + }, + "width": { + "name": "width", + "type": "numeric", + "primaryKey": false, + "notNull": false + }, + "height": { + "name": "height", + "type": "numeric", + "primaryKey": false, + "notNull": false + } + }, + "indexes": { + "media_updated_at_idx": { + "name": "media_updated_at_idx", + "columns": [ + { + "expression": "updated_at", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + }, + "media_created_at_idx": { + "name": "media_created_at_idx", + "columns": [ + { + "expression": "created_at", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + }, + "media_filename_idx": { + "name": "media_filename_idx", + "columns": [ + { + "expression": "filename", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": true, + "concurrently": false, + "method": "btree", + "with": {} + } + }, + "foreignKeys": {}, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "cms.payload_kv": { + "name": "payload_kv", + "schema": "cms", + "columns": { + "id": { + "name": "id", + "type": "uuid", + "primaryKey": true, + "notNull": true, + "default": "gen_random_uuid()" + }, + "key": { + "name": "key", + "type": "varchar", + "primaryKey": false, + "notNull": true + }, + "data": { + "name": "data", + "type": "jsonb", + "primaryKey": false, + "notNull": true + } + }, + "indexes": { + "payload_kv_key_idx": { + "name": "payload_kv_key_idx", + "columns": [ + { + "expression": "key", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": true, + "concurrently": false, + "method": "btree", + "with": {} + } + }, + "foreignKeys": {}, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "cms.payload_locked_documents": { + "name": "payload_locked_documents", + "schema": "cms", + "columns": { + "id": { + "name": "id", + "type": "uuid", + "primaryKey": true, + "notNull": true, + "default": "gen_random_uuid()" + }, + "global_slug": { + "name": "global_slug", + "type": "varchar", + "primaryKey": false, + "notNull": false + }, + "updated_at": { + "name": "updated_at", + "type": "timestamp(3) with time zone", + "primaryKey": false, + "notNull": true, + "default": "now()" + }, + "created_at": { + "name": "created_at", + "type": "timestamp(3) with time zone", + "primaryKey": false, + "notNull": true, + "default": "now()" + } + }, + "indexes": { + "payload_locked_documents_global_slug_idx": { + "name": "payload_locked_documents_global_slug_idx", + "columns": [ + { + "expression": "global_slug", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + }, + "payload_locked_documents_updated_at_idx": { + "name": "payload_locked_documents_updated_at_idx", + "columns": [ + { + "expression": "updated_at", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + }, + "payload_locked_documents_created_at_idx": { + "name": "payload_locked_documents_created_at_idx", + "columns": [ + { + "expression": "created_at", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + } + }, + "foreignKeys": {}, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "cms.payload_locked_documents_rels": { + "name": "payload_locked_documents_rels", + "schema": "cms", + "columns": { + "id": { + "name": "id", + "type": "serial", + "primaryKey": true, + "notNull": true + }, + "order": { + "name": "order", + "type": "integer", + "primaryKey": false, + "notNull": false + }, + "parent_id": { + "name": "parent_id", + "type": "uuid", + "primaryKey": false, + "notNull": true + }, + "path": { + "name": "path", + "type": "varchar", + "primaryKey": false, + "notNull": true + }, + "users_id": { + "name": "users_id", + "type": "uuid", + "primaryKey": false, + "notNull": false + }, + "pages_id": { + "name": "pages_id", + "type": "uuid", + "primaryKey": false, + "notNull": false + }, + "posts_id": { + "name": "posts_id", + "type": "uuid", + "primaryKey": false, + "notNull": false + }, + "categories_id": { + "name": "categories_id", + "type": "uuid", + "primaryKey": false, + "notNull": false + }, + "media_id": { + "name": "media_id", + "type": "uuid", + "primaryKey": false, + "notNull": false + } + }, + "indexes": { + "payload_locked_documents_rels_order_idx": { + "name": "payload_locked_documents_rels_order_idx", + "columns": [ + { + "expression": "order", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + }, + "payload_locked_documents_rels_parent_idx": { + "name": "payload_locked_documents_rels_parent_idx", + "columns": [ + { + "expression": "parent_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + }, + "payload_locked_documents_rels_path_idx": { + "name": "payload_locked_documents_rels_path_idx", + "columns": [ + { + "expression": "path", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + }, + "payload_locked_documents_rels_users_id_idx": { + "name": "payload_locked_documents_rels_users_id_idx", + "columns": [ + { + "expression": "users_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + }, + "payload_locked_documents_rels_pages_id_idx": { + "name": "payload_locked_documents_rels_pages_id_idx", + "columns": [ + { + "expression": "pages_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + }, + "payload_locked_documents_rels_posts_id_idx": { + "name": "payload_locked_documents_rels_posts_id_idx", + "columns": [ + { + "expression": "posts_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + }, + "payload_locked_documents_rels_categories_id_idx": { + "name": "payload_locked_documents_rels_categories_id_idx", + "columns": [ + { + "expression": "categories_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + }, + "payload_locked_documents_rels_media_id_idx": { + "name": "payload_locked_documents_rels_media_id_idx", + "columns": [ + { + "expression": "media_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + } + }, + "foreignKeys": { + "payload_locked_documents_rels_parent_fk": { + "name": "payload_locked_documents_rels_parent_fk", + "tableFrom": "payload_locked_documents_rels", + "tableTo": "payload_locked_documents", + "schemaTo": "cms", + "columnsFrom": [ + "parent_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "cascade", + "onUpdate": "no action" + }, + "payload_locked_documents_rels_users_fk": { + "name": "payload_locked_documents_rels_users_fk", + "tableFrom": "payload_locked_documents_rels", + "tableTo": "users", + "schemaTo": "cms", + "columnsFrom": [ + "users_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "cascade", + "onUpdate": "no action" + }, + "payload_locked_documents_rels_pages_fk": { + "name": "payload_locked_documents_rels_pages_fk", + "tableFrom": "payload_locked_documents_rels", + "tableTo": "pages", + "schemaTo": "cms", + "columnsFrom": [ + "pages_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "cascade", + "onUpdate": "no action" + }, + "payload_locked_documents_rels_posts_fk": { + "name": "payload_locked_documents_rels_posts_fk", + "tableFrom": "payload_locked_documents_rels", + "tableTo": "posts", + "schemaTo": "cms", + "columnsFrom": [ + "posts_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "cascade", + "onUpdate": "no action" + }, + "payload_locked_documents_rels_categories_fk": { + "name": "payload_locked_documents_rels_categories_fk", + "tableFrom": "payload_locked_documents_rels", + "tableTo": "categories", + "schemaTo": "cms", + "columnsFrom": [ + "categories_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "cascade", + "onUpdate": "no action" + }, + "payload_locked_documents_rels_media_fk": { + "name": "payload_locked_documents_rels_media_fk", + "tableFrom": "payload_locked_documents_rels", + "tableTo": "media", + "schemaTo": "cms", + "columnsFrom": [ + "media_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "cascade", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "cms.payload_preferences": { + "name": "payload_preferences", + "schema": "cms", + "columns": { + "id": { + "name": "id", + "type": "uuid", + "primaryKey": true, + "notNull": true, + "default": "gen_random_uuid()" + }, + "key": { + "name": "key", + "type": "varchar", + "primaryKey": false, + "notNull": false + }, + "value": { + "name": "value", + "type": "jsonb", + "primaryKey": false, + "notNull": false + }, + "updated_at": { + "name": "updated_at", + "type": "timestamp(3) with time zone", + "primaryKey": false, + "notNull": true, + "default": "now()" + }, + "created_at": { + "name": "created_at", + "type": "timestamp(3) with time zone", + "primaryKey": false, + "notNull": true, + "default": "now()" + } + }, + "indexes": { + "payload_preferences_key_idx": { + "name": "payload_preferences_key_idx", + "columns": [ + { + "expression": "key", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + }, + "payload_preferences_updated_at_idx": { + "name": "payload_preferences_updated_at_idx", + "columns": [ + { + "expression": "updated_at", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + }, + "payload_preferences_created_at_idx": { + "name": "payload_preferences_created_at_idx", + "columns": [ + { + "expression": "created_at", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + } + }, + "foreignKeys": {}, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "cms.payload_preferences_rels": { + "name": "payload_preferences_rels", + "schema": "cms", + "columns": { + "id": { + "name": "id", + "type": "serial", + "primaryKey": true, + "notNull": true + }, + "order": { + "name": "order", + "type": "integer", + "primaryKey": false, + "notNull": false + }, + "parent_id": { + "name": "parent_id", + "type": "uuid", + "primaryKey": false, + "notNull": true + }, + "path": { + "name": "path", + "type": "varchar", + "primaryKey": false, + "notNull": true + }, + "users_id": { + "name": "users_id", + "type": "uuid", + "primaryKey": false, + "notNull": false + } + }, + "indexes": { + "payload_preferences_rels_order_idx": { + "name": "payload_preferences_rels_order_idx", + "columns": [ + { + "expression": "order", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + }, + "payload_preferences_rels_parent_idx": { + "name": "payload_preferences_rels_parent_idx", + "columns": [ + { + "expression": "parent_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + }, + "payload_preferences_rels_path_idx": { + "name": "payload_preferences_rels_path_idx", + "columns": [ + { + "expression": "path", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + }, + "payload_preferences_rels_users_id_idx": { + "name": "payload_preferences_rels_users_id_idx", + "columns": [ + { + "expression": "users_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + } + }, + "foreignKeys": { + "payload_preferences_rels_parent_fk": { + "name": "payload_preferences_rels_parent_fk", + "tableFrom": "payload_preferences_rels", + "tableTo": "payload_preferences", + "schemaTo": "cms", + "columnsFrom": [ + "parent_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "cascade", + "onUpdate": "no action" + }, + "payload_preferences_rels_users_fk": { + "name": "payload_preferences_rels_users_fk", + "tableFrom": "payload_preferences_rels", + "tableTo": "users", + "schemaTo": "cms", + "columnsFrom": [ + "users_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "cascade", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "cms.payload_migrations": { + "name": "payload_migrations", + "schema": "cms", + "columns": { + "id": { + "name": "id", + "type": "uuid", + "primaryKey": true, + "notNull": true, + "default": "gen_random_uuid()" + }, + "name": { + "name": "name", + "type": "varchar", + "primaryKey": false, + "notNull": false + }, + "batch": { + "name": "batch", + "type": "numeric", + "primaryKey": false, + "notNull": false + }, + "updated_at": { + "name": "updated_at", + "type": "timestamp(3) with time zone", + "primaryKey": false, + "notNull": true, + "default": "now()" + }, + "created_at": { + "name": "created_at", + "type": "timestamp(3) with time zone", + "primaryKey": false, + "notNull": true, + "default": "now()" + } + }, + "indexes": { + "payload_migrations_updated_at_idx": { + "name": "payload_migrations_updated_at_idx", + "columns": [ + { + "expression": "updated_at", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + }, + "payload_migrations_created_at_idx": { + "name": "payload_migrations_created_at_idx", + "columns": [ + { + "expression": "created_at", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + } + }, + "foreignKeys": {}, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + } + }, + "enums": { + "cms.enum_users_role": { + "name": "enum_users_role", + "schema": "cms", + "values": [ + "admin", + "editor" + ] + }, + "cms.enum_pages_status": { + "name": "enum_pages_status", + "schema": "cms", + "values": [ + "draft", + "published" + ] + }, + "cms.enum__pages_v_version_status": { + "name": "enum__pages_v_version_status", + "schema": "cms", + "values": [ + "draft", + "published" + ] + }, + "cms.enum_posts_status": { + "name": "enum_posts_status", + "schema": "cms", + "values": [ + "draft", + "published" + ] + }, + "cms.enum__posts_v_version_status": { + "name": "enum__posts_v_version_status", + "schema": "cms", + "values": [ + "draft", + "published" + ] + } + }, + "schemas": { + "cms": "cms" + }, + "sequences": {}, + "roles": {}, + "policies": {}, + "views": {}, + "_meta": { + "schemas": {}, + "tables": {}, + "columns": {} + }, + "id": "3bb091e0-8a69-44dd-866d-d05cf0ba7754", + "prevId": "00000000-0000-0000-0000-000000000000" +} \ No newline at end of file diff --git a/apps/cms/payload-migrations/20261028_121234_cms_lumen_identity.ts b/apps/cms/payload-migrations/20261028_121234_cms_lumen_identity.ts new file mode 100644 index 0000000..f38fe37 --- /dev/null +++ b/apps/cms/payload-migrations/20261028_121234_cms_lumen_identity.ts @@ -0,0 +1,17 @@ +import { MigrateUpArgs, MigrateDownArgs, sql } from '@payloadcms/db-postgres' + +export async function up({ db, payload, req }: MigrateUpArgs): Promise { + await db.execute(sql` + ALTER TABLE "cms"."users" ALTER COLUMN "role" DROP DEFAULT; + ALTER TABLE "cms"."users" ALTER COLUMN "role" DROP NOT NULL; + ALTER TABLE "cms"."users" ADD COLUMN "lumen_user_id" varchar; + CREATE UNIQUE INDEX "users_lumen_user_id_idx" ON "cms"."users" USING btree ("lumen_user_id");`) +} + +export async function down({ db, payload, req }: MigrateDownArgs): Promise { + await db.execute(sql` + DROP INDEX "cms"."users_lumen_user_id_idx"; + ALTER TABLE "cms"."users" ALTER COLUMN "role" SET DEFAULT 'editor'; + ALTER TABLE "cms"."users" ALTER COLUMN "role" SET NOT NULL; + ALTER TABLE "cms"."users" DROP COLUMN "lumen_user_id";`) +} diff --git a/apps/cms/payload-migrations/index.ts b/apps/cms/payload-migrations/index.ts index a04c98d..d154b27 100644 --- a/apps/cms/payload-migrations/index.ts +++ b/apps/cms/payload-migrations/index.ts @@ -1,5 +1,6 @@ import * as migration_20261027_203229_cms_payload_core from './20261027_203229_cms_payload_core'; import * as migration_20261028_061257_cms_media from './20261028_061257_cms_media'; +import * as migration_20261028_121234_cms_lumen_identity from './20261028_121234_cms_lumen_identity'; export const migrations = [ { @@ -10,6 +11,11 @@ export const migrations = [ { up: migration_20261028_061257_cms_media.up, down: migration_20261028_061257_cms_media.down, - name: '20261028_061257_cms_media' + name: '20261028_061257_cms_media', + }, + { + up: migration_20261028_121234_cms_lumen_identity.up, + down: migration_20261028_121234_cms_lumen_identity.down, + name: '20261028_121234_cms_lumen_identity' }, ]; diff --git a/apps/cms/scripts/payload-migration-to-sql.mjs b/apps/cms/scripts/payload-migration-to-sql.mjs index d3e6045..68b6d2b 100755 --- a/apps/cms/scripts/payload-migration-to-sql.mjs +++ b/apps/cms/scripts/payload-migration-to-sql.mjs @@ -8,9 +8,10 @@ // // Idempotent because the runner sends a migration as one query to the Supabase // Management API with no transaction of its own: a partial apply must converge -// on retry. Statements it cannot make idempotent (drops, renames, type -// changes) are kept as written and reported on stderr, and the exit code is 2 -// so they cannot slip through unread. +// on retry. Column default and nullability changes are idempotent as they +// are. Statements it cannot make idempotent (drops, renames, type changes) are +// kept as written and reported on stderr, and the exit code is 2 so they +// cannot slip through unread. import { readFileSync } from 'node:fs' import { basename } from 'node:path' @@ -45,6 +46,8 @@ const out = statements.map((stmt) => { if (/^ALTER TABLE \S+ ADD CONSTRAINT /.test(stmt)) return guarded(stmt) if (/^ALTER TABLE \S+ ADD COLUMN "/.test(stmt)) return stmt.replace(/ ADD COLUMN "/, ' ADD COLUMN IF NOT EXISTS "') + ';' if (/^ALTER TYPE \S+ ADD VALUE '/.test(stmt)) return stmt.replace(/ ADD VALUE '/, " ADD VALUE IF NOT EXISTS '") + ';' + // Re-running these leaves the column as the first run did: already idempotent. + if (/^ALTER TABLE \S+ ALTER COLUMN "[^"]+" (DROP DEFAULT|DROP NOT NULL|SET NOT NULL|SET DEFAULT [^;]+)$/.test(stmt)) return stmt + ';' unsafe.push(stmt.split('\n')[0]) return stmt + ';' }) diff --git a/apps/cms/src/app/(payload)/admin/importMap.js b/apps/cms/src/app/(payload)/admin/importMap.js index 2c0fde6..fd7d088 100644 --- a/apps/cms/src/app/(payload)/admin/importMap.js +++ b/apps/cms/src/app/(payload)/admin/importMap.js @@ -22,6 +22,9 @@ import { UnderlineFeatureClient as UnderlineFeatureClient_e70f5e05f09f93e00b997e import { BoldFeatureClient as BoldFeatureClient_e70f5e05f09f93e00b997edb1ef0c864 } from '@payloadcms/richtext-lexical/client' import { ItalicFeatureClient as ItalicFeatureClient_e70f5e05f09f93e00b997edb1ef0c864 } from '@payloadcms/richtext-lexical/client' 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 { CollectionCards as CollectionCards_f9c02e79a4aed9a3924487c0cd4cafb1 } from '@payloadcms/next/rsc' /** @type import('payload').ImportMap */ @@ -50,5 +53,8 @@ export const importMap = { "@payloadcms/richtext-lexical/client#BoldFeatureClient": BoldFeatureClient_e70f5e05f09f93e00b997edb1ef0c864, "@payloadcms/richtext-lexical/client#ItalicFeatureClient": ItalicFeatureClient_e70f5e05f09f93e00b997edb1ef0c864, "@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, "@payloadcms/next/rsc#CollectionCards": CollectionCards_f9c02e79a4aed9a3924487c0cd4cafb1 } diff --git a/apps/cms/src/app/(site)/auth/lumen/callback/OAuthCallback.tsx b/apps/cms/src/app/(site)/auth/lumen/callback/OAuthCallback.tsx new file mode 100644 index 0000000..b5e06e9 --- /dev/null +++ b/apps/cms/src/app/(site)/auth/lumen/callback/OAuthCallback.tsx @@ -0,0 +1,57 @@ +'use client' + +import { useEffect, useRef, useState } from 'react' + +// The codes identity-worker's OAuth callback sends back (#error=…). +const MESSAGES: Record = { + access_denied: 'The sign-in was cancelled.', + missing_code: 'The provider did not finish the sign-in. Try again.', + provider_unavailable: 'That sign-in provider is not available right now.', + exchange_failed: 'The provider did not accept the sign-in. Try again.', + identity_failed: 'The provider did not say who you are. Try again.', + oauth_failed: 'The sign-in failed. Try again.', + email_required: 'Your account with that provider has no email address.', + email_unverified: 'Your account with that provider has no verified email address.', + server_error: 'Something went wrong on our side. Try again.', + missing: 'The sign-in did not return a session.', +} + +// Reads the token from the fragment, removes it from the address bar and the +// history, and hands it to /auth/lumen/session in a same-origin form post. +export function OAuthCallback({ redirect }: { redirect: string }) { + const form = useRef(null) + const tokenInput = useRef(null) + const [error, setError] = useState(null) + + useEffect(() => { + const fragment = new URLSearchParams(window.location.hash.slice(1)) + window.history.replaceState(null, '', window.location.pathname + window.location.search) + const token = fragment.get('token') + if (token && form.current && tokenInput.current) { + tokenInput.current.value = token + form.current.submit() + return + } + const code = fragment.get('error') ?? 'missing' + setError(MESSAGES[code] ?? `The sign-in failed (${code}).`) + }, []) + + return ( +
+
+ + +
+ {error ? ( + <> +

{error}

+

+ Back to sign-in +

+ + ) : ( +

Signing you in…

+ )} +
+ ) +} diff --git a/apps/cms/src/app/(site)/auth/lumen/callback/page.tsx b/apps/cms/src/app/(site)/auth/lumen/callback/page.tsx new file mode 100644 index 0000000..5538f4c --- /dev/null +++ b/apps/cms/src/app/(site)/auth/lumen/callback/page.tsx @@ -0,0 +1,10 @@ +import { OAuthCallback } from './OAuthCallback' + +export const dynamic = 'force-dynamic' + +// Where identity-worker sends a GitHub or Google sign-in back to, with the +// token in the URL fragment (#token=…), which never reaches a server. +export default async function Page({ searchParams }: { searchParams: Promise> }) { + const { redirect } = await searchParams + return +} diff --git a/apps/cms/src/app/(site)/auth/lumen/logout/route.ts b/apps/cms/src/app/(site)/auth/lumen/logout/route.ts new file mode 100644 index 0000000..79ab057 --- /dev/null +++ b/apps/cms/src/app/(site)/auth/lumen/logout/route.ts @@ -0,0 +1,20 @@ +import { isSameOrigin } from '@/lib/lumen/cookies' +import { endSession } from '@/lib/lumen/logout' +import { lumenTransport } from '@/lib/lumen/transport' + +export const dynamic = 'force-dynamic' + +// Sign out (design §1): revoke the Lumen session at api-edge, not just forget +// it, and remove the cookie. Same-origin posts only, so another site cannot +// sign a visitor out. +export async function POST(request: Request): Promise { + const self = new URL(request.url) + if (!isSameOrigin(request.headers, request.url)) { + return new Response('Sign-out must come from this site.\n', { status: 403, headers: { 'cache-control': 'no-store', 'content-type': 'text/plain' } }) + } + const { setCookie } = await endSession(await lumenTransport(), request.headers, self.protocol === 'https:') + return new Response(null, { + status: 303, + headers: { 'cache-control': 'no-store', location: '/admin/login?signedOut=1', 'set-cookie': setCookie }, + }) +} diff --git a/apps/cms/src/app/(site)/auth/lumen/session/route.ts b/apps/cms/src/app/(site)/auth/lumen/session/route.ts new file mode 100644 index 0000000..79c35aa --- /dev/null +++ b/apps/cms/src/app/(site)/auth/lumen/session/route.ts @@ -0,0 +1,45 @@ +import { isSameOrigin, safeAdminRedirect, sessionCookie } from '@/lib/lumen/cookies' +import { resolveSession } from '@/lib/lumen/session' +import { lumenTransport } from '@/lib/lumen/transport' + +export const dynamic = 'force-dynamic' + +const noStore = { 'cache-control': 'no-store' } + +async function fields(request: Request): Promise<{ token: string | null; redirect: string | null }> { + const type = request.headers.get('content-type') ?? '' + if (type.includes('application/json')) { + const body = (await request.json().catch(() => ({}))) as { token?: unknown; redirect?: unknown } + return { + token: typeof body.token === 'string' ? body.token : null, + redirect: typeof body.redirect === 'string' ? body.redirect : null, + } + } + const form = await request.formData().catch((): FormData | null => null) + const token = form?.get('token') + const redirect = form?.get('redirect') + return { token: typeof token === 'string' ? token : null, redirect: typeof redirect === 'string' ? redirect : null } +} + +// The one place a Lumen token enters the CMS (design §1): the sign-in page +// posts it here once, the CMS checks it with api-edge, and keeps it in an +// httpOnly cookie from then on. Same-origin posts only. +export async function POST(request: Request): Promise { + const self = new URL(request.url) + if (!isSameOrigin(request.headers, request.url)) { + return new Response('Sign-in must come from this site.\n', { status: 403, headers: { ...noStore, 'content-type': 'text/plain' } }) + } + const { token, redirect } = await fields(request) + const back = (error: string) => new Response(null, { status: 303, headers: { ...noStore, location: `/admin/login?error=${error}` } }) + if (!token) return back('missing') + const session = await resolveSession(await lumenTransport(), token) + if (!session) return back('invalid') + return new Response(null, { + status: 303, + headers: { + ...noStore, + location: safeAdminRedirect(redirect), + 'set-cookie': sessionCookie(token, session.expiresAt, self.protocol === 'https:'), + }, + }) +} diff --git a/apps/cms/src/app/setup/route.ts b/apps/cms/src/app/setup/route.ts index 95b55c6..3404445 100644 --- a/apps/cms/src/app/setup/route.ts +++ b/apps/cms/src/app/setup/route.ts @@ -2,10 +2,11 @@ import { MIN_SETUP_TOKEN_LENGTH, SETUP_CLOSED_MESSAGE, SETUP_COOKIE, setupIsOpen export const dynamic = 'force-dynamic' -// The owner's door into first-user setup (design §4): /setup?token=. A match sets a short-lived HttpOnly cookie -// that the first-user gate on `users` accepts, and sends them to Payload's -// create-first-user form with the token gone from the address bar. +// The owner's door to the first admin (lumen-payload-cms design §4, +// lumen-payload-console design §3): /setup?token=. A match sets a short-lived HttpOnly cookie and sends them to the +// Lumen sign-in with the token gone from the address bar. Whoever signs in +// with that cookie while no admin exists becomes the admin. export function GET(request: Request): Response { const url = new URL(request.url) const token = url.searchParams.get('token') @@ -27,6 +28,6 @@ export function GET(request: Request): Response { .join('; ') return new Response(null, { status: 303, - headers: { location: '/admin/create-first-user', 'set-cookie': cookie, 'cache-control': 'no-store' }, + headers: { location: '/admin/login', 'set-cookie': cookie, 'cache-control': 'no-store' }, }) } diff --git a/apps/cms/src/collections/Users.ts b/apps/cms/src/collections/Users.ts index ddeb98c..3ebb143 100644 --- a/apps/cms/src/collections/Users.ts +++ b/apps/cms/src/collections/Users.ts @@ -1,58 +1,62 @@ -import { APIError, type CollectionBeforeChangeHook, type CollectionBeforeOperationHook, type CollectionConfig } from 'payload' +import type { CollectionAfterLogoutHook, CollectionConfig } from 'payload' -import { adminOrSelf, isAdmin, isAdminField, isStaff } from '../lib/access' -import { presentedSetupToken, SETUP_CLOSED_MESSAGE, setupIsOpen } from '../lib/setup-gate' +import { adminOrSelf, isAdmin, isAdminField, isStaff, selfOrAdmin } from '../lib/access' +import { lumenStrategy } from '../lib/lumen/strategy' -const noUsersYet = async (req: Parameters[0]['req']): Promise => { - const { totalDocs } = await req.payload.count({ collection: 'users', overrideAccess: true, req }) - return totalDocs === 0 -} - -// Creating the first account — the only create an anonymous request can reach, -// through /api/users/first-register — needs the owner's setup token. Every -// later account is created by an admin, which the create rule enforces. -const firstUserGate: CollectionBeforeOperationHook = async ({ operation, req }) => { - if (operation !== 'create' || req.user) return - if (!(await noUsersYet(req))) return - if (!setupIsOpen(process.env.CMS_SETUP_TOKEN, presentedSetupToken(req.headers))) { - throw new APIError(SETUP_CLOSED_MESSAGE, 403, undefined, true) - } -} - -// Whoever creates the first account is its admin. -const firstUserIsAdmin: CollectionBeforeChangeHook = async ({ data, operation, req }) => { - if (operation === 'create' && (await noUsersYet(req))) return { ...data, role: 'admin' } - return data +// Sign-out from Payload's own endpoint (/api/users/logout, which the admin +// calls on inactivity) ends the Lumen session too, so the cookie cannot sign +// the person straight back in. +const endLumenSession: CollectionAfterLogoutHook = async ({ req }) => { + const [{ lumenTransport }, { endSession }] = await Promise.all([import('../lib/lumen/transport'), import('../lib/lumen/logout')]) + const secure = new URL(req.url ?? 'https://cms.invalid').protocol === 'https:' + const { setCookie } = await endSession(await lumenTransport(), req.headers, secure) + req.responseHeaders ??= new Headers() + req.responseHeaders.append('set-cookie', setCookie) } +// Staff accounts (lumen-payload-console design §3). People sign in with their +// Lumen account; there are no Payload passwords. A row is created on first +// sign-in and linked by lumenUserId. No role means pending: signed in but not +// let into the admin. An admin can also add a row by email beforehand, with a +// role, as an invitation: it is linked when that email signs in. export const Users: CollectionConfig = { slug: 'users', - auth: true, - admin: { useAsTitle: 'email', defaultColumns: ['email', 'name', 'role'] }, + auth: { + // enableFields keeps the auth columns (email, sessions, ...) so the + // schema stays as migration 200 made it; only the password flows go. + disableLocalStrategy: { enableFields: true }, + strategies: [lumenStrategy], + }, + admin: { useAsTitle: 'email', defaultColumns: ['email', 'name', 'role', 'lumenUserId'] }, access: { admin: isStaff, - read: adminOrSelf, + read: selfOrAdmin, create: isAdmin, update: adminOrSelf, delete: isAdmin, }, - hooks: { - beforeOperation: [firstUserGate], - beforeChange: [firstUserIsAdmin], - }, + hooks: { afterLogout: [endLumenSession] }, fields: [ { name: 'name', type: 'text' }, { name: 'role', type: 'select', - required: true, - defaultValue: 'editor', saveToJWT: true, options: [ { label: 'Admin', value: 'admin' }, { label: 'Editor', value: 'editor' }, ], + admin: { description: 'Empty means pending: signed in with Lumen, but not let into the admin yet.' }, access: { create: isAdminField, update: isAdminField }, }, + { + name: 'lumenUserId', + label: 'Lumen user', + type: 'text', + unique: true, + index: true, + admin: { readOnly: true, position: 'sidebar', description: 'Set on first Lumen sign-in.' }, + access: { create: () => false, update: () => false }, + }, ], } diff --git a/apps/cms/src/components/admin/LumenLogin.tsx b/apps/cms/src/components/admin/LumenLogin.tsx new file mode 100644 index 0000000..0cfce17 --- /dev/null +++ b/apps/cms/src/components/admin/LumenLogin.tsx @@ -0,0 +1,24 @@ +import type { AdminViewServerProps } from 'payload' +import { redirect } from 'next/navigation' + +import { safeAdminRedirect } from '../../lib/lumen/cookies' +import { lumenPublicApiUrl } from '../../lib/lumen/transport' +import { LumenSignIn } from './LumenSignIn' + +const first = (value: string | string[] | undefined): string | null => (typeof value === 'string' ? value : null) + +// The admin's login view, replaced (design §1): Payload's local strategy is +// off, so its own view would render no form. +export async function LumenLogin({ initPageResult, searchParams }: AdminViewServerProps) { + const target = safeAdminRedirect(first(searchParams?.redirect)) + if (initPageResult.req.user) redirect(target) + return ( + + ) +} diff --git a/apps/cms/src/components/admin/LumenSignIn.tsx b/apps/cms/src/components/admin/LumenSignIn.tsx new file mode 100644 index 0000000..2a94c3a --- /dev/null +++ b/apps/cms/src/components/admin/LumenSignIn.tsx @@ -0,0 +1,180 @@ +'use client' + +import { Button } from '@payloadcms/ui' +import { useEffect, useRef, useState, type FormEvent } from 'react' + +type Provider = { id: string; displayName: string } +type Envelope = { data?: T; error?: { code?: string; message?: string } } + +const ERRORS: Record = { + missing: 'The sign-in did not return a session. Try again.', + invalid: 'That session is not valid any more. Sign in again.', +} + +async function call(url: string, body?: unknown): Promise<{ ok: boolean; data?: T; message?: string }> { + try { + const response = await fetch(url, { + method: body === undefined ? 'GET' : 'POST', + headers: body === undefined ? { accept: 'application/json' } : { accept: 'application/json', 'content-type': 'application/json' }, + body: body === undefined ? undefined : JSON.stringify(body), + }) + const json = (await response.json().catch(() => ({}))) as Envelope + if (response.ok) return { ok: true, data: json.data } + return { ok: false, message: json.error?.message ?? `The request failed (${response.status}).` } + } catch { + return { ok: false, message: 'Lumen could not be reached. Check your connection and try again.' } + } +} + +// Sign in with a Lumen account (design §1). The browser talks to api-edge +// directly, as the Lumen console did: api-edge rate-limits sign-in per client +// IP. The token that comes back is posted once to /auth/lumen/session, which +// keeps it in an httpOnly cookie; this page does not store it. +export function LumenSignIn({ + apiUrl, + redirect, + error, + signedOut, + productName, +}: { + apiUrl: string + redirect: string + error?: string | null + signedOut?: boolean + productName: string +}) { + const [providers, setProviders] = useState([]) + const [step, setStep] = useState<'email' | 'code'>('email') + const [email, setEmail] = useState('') + const [code, setCode] = useState('') + const [challengeId, setChallengeId] = useState(null) + const [emailHint, setEmailHint] = useState(null) + const [debugCode, setDebugCode] = useState(null) + const [busy, setBusy] = useState(false) + const [message, setMessage] = useState(error ? (ERRORS[error] ?? 'The sign-in failed. Try again.') : null) + const sessionForm = useRef(null) + const tokenInput = useRef(null) + + useEffect(() => { + if (!apiUrl) return + void call<{ providers: Provider[] }>(`${apiUrl}/v1/auth/oauth/providers`).then((r) => { + if (r.ok && r.data?.providers) setProviders(r.data.providers) + }) + }, [apiUrl]) + + const start = async (event: FormEvent) => { + event.preventDefault() + setBusy(true) + setMessage(null) + const r = await call<{ challengeId: string; delivery: { emailHint: string; code?: string } }>(`${apiUrl}/v1/auth/login/start`, { email }) + setBusy(false) + if (!r.ok || !r.data) return setMessage(r.message ?? 'The code could not be sent.') + setChallengeId(r.data.challengeId) + setEmailHint(r.data.delivery.emailHint) + setDebugCode(r.data.delivery.code ?? null) + setStep('code') + } + + const complete = async (event: FormEvent) => { + event.preventDefault() + if (!challengeId) return + setBusy(true) + setMessage(null) + const r = await call<{ token: string }>(`${apiUrl}/v1/auth/login/complete`, { challengeId, code: code.trim() }) + if (!r.ok || !r.data?.token || !sessionForm.current || !tokenInput.current) { + setBusy(false) + return setMessage(r.message ?? 'That code did not work.') + } + tokenInput.current.value = r.data.token + sessionForm.current.submit() + } + + const oauthUrl = (provider: string) => { + const back = `${window.location.origin}/auth/lumen/callback?redirect=${encodeURIComponent(redirect)}` + return `${apiUrl}/v1/auth/oauth/${encodeURIComponent(provider)}/start?return_to=${encodeURIComponent(back)}` + } + + const input = { + width: '100%', + padding: '0.6rem 0.75rem', + fontSize: '1rem', + border: '1px solid var(--theme-elevation-150)', + borderRadius: 'var(--style-radius-s, 4px)', + background: 'var(--theme-input-bg, var(--theme-elevation-0))', + color: 'var(--theme-text)', + } as const + + return ( +
+

Sign in to {productName}

+

Use your Lumen account. There is no separate CMS password.

+ {signedOut && !message &&

You are signed out.

} + {message && ( +

+ {message} +

+ )} + +
+ + +
+ + {step === 'email' ? ( +
+ + setEmail(e.target.value)} + style={input} + /> + +
+ ) : ( +
+

+ We sent a code to {emailHint ?? email}. +

+ {debugCode && ( +

+ Stage delivers the code here: {debugCode} +

+ )} + + setCode(e.target.value)} + style={input} + /> + + +
+ )} + + {providers.length > 0 && step === 'email' && ( +
+

Or continue with

+ {providers.map((p) => ( + + ))} +
+ )} +
+ ) +} diff --git a/apps/cms/src/components/admin/LumenSignOut.tsx b/apps/cms/src/components/admin/LumenSignOut.tsx new file mode 100644 index 0000000..9f8cfc6 --- /dev/null +++ b/apps/cms/src/components/admin/LumenSignOut.tsx @@ -0,0 +1,20 @@ +'use client' + +import { useEffect, useRef } from 'react' + +// The admin's logout view, replaced: the nav's log-out link lands here, and +// this posts to /auth/lumen/logout, which revokes the Lumen session. +export function LumenSignOut() { + const form = useRef(null) + useEffect(() => { + form.current?.submit() + }, []) + return ( +
+

Signing you out…

+ +
+ ) +} diff --git a/apps/cms/src/components/admin/PendingAccess.tsx b/apps/cms/src/components/admin/PendingAccess.tsx new file mode 100644 index 0000000..c3780b3 --- /dev/null +++ b/apps/cms/src/components/admin/PendingAccess.tsx @@ -0,0 +1,25 @@ +import type { AdminViewServerProps } from 'payload' + +// The admin's "unauthorized" view, replaced (design §3): who is signed in, +// and why they cannot go further yet. +export async function PendingAccess({ initPageResult }: AdminViewServerProps) { + const user = initPageResult.req.user as { email?: string } | null + return ( +
+

Waiting for access

+ {user?.email ? ( +

+ You are signed in as {user.email}, but nobody has given this account a role in the CMS yet. Ask + an admin to open Users and make you an editor or an admin. +

+ ) : ( +

You do not have access to this page.

+ )} +
+ +
+
+ ) +} diff --git a/apps/cms/src/lib/access.ts b/apps/cms/src/lib/access.ts index 744508d..f65cc21 100644 --- a/apps/cms/src/lib/access.ts +++ b/apps/cms/src/lib/access.ts @@ -1,10 +1,10 @@ import type { Access, FieldAccess, PayloadRequest } from 'payload' type Role = 'admin' | 'editor' -type StaffUser = { collection?: string; role?: Role } | null | undefined +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 + user && (user.collection === undefined || user.collection === 'users') ? (user.role ?? undefined) : undefined export const anyone: Access = () => true // Boolean-only (not Access): Payload's `access.admin` must answer yes or no. @@ -16,6 +16,14 @@ export const isAdminField: FieldAccess = ({ req: { user } }) => roleOf(user as S export const publishedOrStaff: Access = ({ req: { user } }) => roleOf(user as StaffUser) ? true : { _status: { equals: 'published' } } +/** Anyone signed in reads their own account (a pending one too); admins read all. */ +export const selfOrAdmin: Access = ({ req: { user } }) => { + const u = user as (StaffUser & { id?: string }) | null + if (roleOf(u) === 'admin') return true + if (u?.id && (u.collection === undefined || u.collection === 'users')) return { id: { equals: u.id } } + return false +} + /** Admins manage every account; an editor reads and edits their own. */ export const adminOrSelf: Access = ({ req: { user } }) => { const u = user as (StaffUser & { id?: string }) | null diff --git a/apps/cms/src/lib/lumen/accounts.ts b/apps/cms/src/lib/lumen/accounts.ts new file mode 100644 index 0000000..25e558b --- /dev/null +++ b/apps/cms/src/lib/lumen/accounts.ts @@ -0,0 +1,49 @@ +import type { LumenUser } from './client' + +// The Payload account of a signed-in Lumen user (design §3). Lumen says who +// someone is; the CMS keeps only what the content plane needs: the link +// (lumenUserId), a display name and a role. No role means pending: signed in, +// but not let into the admin until an admin gives them one. + +export type Role = 'admin' | 'editor' +export type Account = { id: string; email: string; name?: string | null; role?: Role | null; lumenUserId?: string | null } + +export type AccountStore = { + findByLumenId(lumenUserId: string): Promise + /** A row made before Lumen sign-in (or by an admin, as an invitation) with this email and no link yet. */ + findUnlinkedByEmail(email: string): Promise + adminExists(): Promise + create(data: Omit): Promise + update(id: string, data: Partial>): Promise +} + +/** + * Find, link or create the account, in that order. `setupOpen` is true when + * the request carries the owner's setup token: while no admin exists, it makes + * the person signing in the first admin. Without it nobody becomes admin by + * signing in. + */ +export async function accountFor(store: AccountStore, user: LumenUser, setupOpen: boolean): Promise { + let account = await store.findByLumenId(user.id) + if (!account) { + const unlinked = await store.findUnlinkedByEmail(user.email) + if (unlinked) account = await store.update(unlinked.id, { lumenUserId: user.id }) + } + if (!account) { + const role: Role | null = setupOpen && !(await store.adminExists()) ? 'admin' : null + try { + account = await store.create({ email: user.email, name: user.displayName ?? null, lumenUserId: user.id, role }) + } catch (error) { + // Two first requests of one person can race to create the row; the + // unique link lets one win, and the other reads it back. + const raced = await store.findByLumenId(user.id) + if (!raced) throw error + account = raced + } + return account + } + if (!account.role && setupOpen && !(await store.adminExists())) { + account = await store.update(account.id, { role: 'admin' }) + } + return account +} diff --git a/apps/cms/src/lib/lumen/client.ts b/apps/cms/src/lib/lumen/client.ts new file mode 100644 index 0000000..1b7a6bb --- /dev/null +++ b/apps/cms/src/lib/lumen/client.ts @@ -0,0 +1,45 @@ +// Calls to Lumen's public API (api-edge), made by the CMS server. The +// transport is injected: on Workers it is the LUMEN_API service binding +// (lib/lumen/transport.ts), in tests a fake. Every response is api-edge's +// envelope: { data } on success, { error: { code, message } } on failure. + +export type LumenTransport = (path: string, init: RequestInit) => Promise + +export type LumenResult = + | { ok: true; status: number; data: T } + | { ok: false; status: number; code: string; message: string } + +export type LumenUser = { id: string; email: string; displayName: string | null; lastOrgSlug?: string | null } +export type LumenSessionResponse = { session: { id: string; expiresAt: string; createdAt?: string }; user: LumenUser } + +export async function lumenCall( + transport: LumenTransport, + path: string, + options: { token?: string | null; method?: string; body?: unknown } = {}, +): Promise> { + const headers = new Headers({ accept: 'application/json' }) + if (options.token) headers.set('authorization', `Bearer ${options.token}`) + const init: RequestInit = { method: options.method ?? 'GET', headers } + if (options.body !== undefined) { + headers.set('content-type', 'application/json') + init.body = JSON.stringify(options.body) + } + let response: Response + try { + response = await transport(path, init) + } catch (error) { + return { ok: false, status: 0, code: 'unreachable', message: error instanceof Error ? error.message : String(error) } + } + let parsed: unknown = null + try { + parsed = response.status === 204 ? null : await response.json() + } catch { + 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 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/cookies.ts b/apps/cms/src/lib/lumen/cookies.ts new file mode 100644 index 0000000..ec64db7 --- /dev/null +++ b/apps/cms/src/lib/lumen/cookies.ts @@ -0,0 +1,111 @@ +// The Lumen session on the CMS host (lumen-payload-console design §1, §6): +// the bearer token api-edge issued, in one httpOnly cookie that only this +// host receives. Pure helpers, no Payload or Workers imports: tests/cms +// exercises them directly. + +export const LUMEN_SESSION_COOKIE = 'lumen_session' + +/** The longest a session cookie lives, whatever the token says (Lumen's own limit is 30 days). */ +export const MAX_SESSION_SECONDS = 30 * 24 * 60 * 60 + +/** A cookie's value from a Cookie header, or null. */ +export function readCookie(headers: Headers, name: string): string | null { + const cookie = headers.get('cookie') ?? '' + for (const part of cookie.split(';')) { + const eq = part.indexOf('=') + if (eq === -1) continue + if (part.slice(0, eq).trim() !== name) continue + try { + const value = decodeURIComponent(part.slice(eq + 1).trim()) + return value.length > 0 ? value : null + } catch { + return null + } + } + return null +} + +/** The Set-Cookie that stores a session until it expires (at most MAX_SESSION_SECONDS). */ +export function sessionCookie(token: string, expiresAt: string | null | undefined, secure: boolean, now = Date.now()): string { + const expiry = expiresAt ? Date.parse(expiresAt) : NaN + const seconds = Number.isFinite(expiry) ? Math.floor((expiry - now) / 1000) : MAX_SESSION_SECONDS + const maxAge = Math.max(0, Math.min(seconds, MAX_SESSION_SECONDS)) + return [ + `${LUMEN_SESSION_COOKIE}=${encodeURIComponent(token)}`, + 'Path=/', + `Max-Age=${maxAge}`, + 'HttpOnly', + 'SameSite=Lax', + secure ? 'Secure' : '', + ] + .filter(Boolean) + .join('; ') +} + +/** The Set-Cookie that removes the session. */ +export function clearedSessionCookie(secure: boolean): string { + return [`${LUMEN_SESSION_COOKIE}=`, 'Path=/', 'Max-Age=0', 'HttpOnly', 'SameSite=Lax', secure ? 'Secure' : ''] + .filter(Boolean) + .join('; ') +} + +/** + * Where to go after signing in: a path inside the admin, or the admin itself. + * Never another host, a protocol-relative URL or a path outside /admin. + */ +export function safeAdminRedirect(raw: string | null | undefined): string { + if (!raw || !raw.startsWith('/admin')) return '/admin' + if (raw.startsWith('//') || raw.includes('\\') || /[\u0000-\u001f]/.test(raw)) return '/admin' + const next = raw.slice('/admin'.length) + if (next !== '' && !next.startsWith('/') && !next.startsWith('?') && !next.startsWith('#')) return '/admin' + return raw +} + +/** + * A request another site's page made in the background (fetch, form, image) + * rather than a person following a link. The session cookie is SameSite=Lax, + * so browsers already withhold it from most of these; this refuses the rest. + * Requests without Fetch Metadata (curl, old browsers) are not refused. + */ +export function isCrossSiteNonNavigation(headers: Headers): boolean { + return headers.get('sec-fetch-site') === 'cross-site' && headers.get('sec-fetch-mode') !== 'navigate' +} + +/** + * A request that names another origin as its sender. Browsers send Origin on + * every POST, PUT, PATCH and DELETE (a form or fetch) and on cross-origin + * fetches, so this is what stops another page, including a sibling Worker on + * the same workers.dev site (SameSite does not separate those), from writing + * through Payload's API with the session cookie. It does for the Lumen cookie + * what Payload's `csrf` allowlist does for Payload's own cookie, which is off + * here. Only the Host header names this CMS here: an auth strategy gets no + * URL, and a page elsewhere cannot set Host. Following a link sends no + * Origin, so links into the admin from anywhere still sign people in. + */ +export function isForeignOrigin(headers: Headers): boolean { + const presented = headers.get('origin') + if (presented === null) return false + const host = headers.get('host') + if (!host || presented === 'null') return true + try { + return new URL(presented).host !== host.toLowerCase() + } catch { + return true + } +} + +/** + * True only when the browser says the request comes from this CMS. "This + * CMS" is the request URL's origin, or the same scheme with the Host header + * (a local `wrangler dev` rewrites the URL's host to localhost). A page on + * another site makes the browser send that site's Origin; it cannot change + * Host. + */ +export function isSameOrigin(headers: Headers, requestUrl: string): boolean { + const presented = headers.get('origin') + if (!presented) return false + const url = new URL(requestUrl) + if (presented === url.origin) return true + const host = headers.get('host') + return host !== null && presented === `${url.protocol}//${host}` +} diff --git a/apps/cms/src/lib/lumen/logout.ts b/apps/cms/src/lib/lumen/logout.ts new file mode 100644 index 0000000..5065c49 --- /dev/null +++ b/apps/cms/src/lib/lumen/logout.ts @@ -0,0 +1,23 @@ +import { lumenCall, type LumenTransport } from './client' +import { clearedSessionCookie, LUMEN_SESSION_COOKIE, readCookie } from './cookies' +import { forgetSession } from './session' + +/** + * End a Lumen session: revoke it at api-edge (POST /v1/auth/logout), forget it + * here, and return the Set-Cookie that removes it from the browser. A failed + * revoke still clears the cookie: the person asked to leave. + */ +export async function endSession( + transport: LumenTransport, + headers: Headers, + secure: boolean, +): Promise<{ revoked: boolean; setCookie: string }> { + const token = readCookie(headers, LUMEN_SESSION_COOKIE) + let revoked = false + if (token) { + const result = await lumenCall(transport, '/v1/auth/logout', { token, method: 'POST' }) + revoked = result.ok || result.status === 401 + await forgetSession(token) + } + return { revoked, setCookie: clearedSessionCookie(secure) } +} diff --git a/apps/cms/src/lib/lumen/payload-store.ts b/apps/cms/src/lib/lumen/payload-store.ts new file mode 100644 index 0000000..1b464a3 --- /dev/null +++ b/apps/cms/src/lib/lumen/payload-store.ts @@ -0,0 +1,31 @@ +import type { Payload } from 'payload' + +import type { Account, AccountStore } from './accounts' + +// AccountStore over Payload's Local API. Access rules are bypassed on +// purpose: this runs while the request is still being authenticated, so there +// is no user yet to check them against. accountFor decides what is allowed. +export function payloadAccountStore(payload: Payload): AccountStore { + const one = async (where: Record): Promise => { + const { docs } = await payload.find({ collection: 'users', where: where as never, limit: 1, depth: 0, overrideAccess: true }) + return (docs[0] as unknown as Account | undefined) ?? null + } + return { + findByLumenId: (lumenUserId) => one({ lumenUserId: { equals: lumenUserId } }), + findUnlinkedByEmail: (email) => + one({ and: [{ email: { equals: email.toLowerCase() } }, { lumenUserId: { exists: false } }] }), + adminExists: async () => { + const { totalDocs } = await payload.count({ collection: 'users', where: { role: { equals: 'admin' } }, overrideAccess: true }) + return totalDocs > 0 + }, + create: async (data) => + (await payload.create({ + collection: 'users', + data: { ...data, email: data.email.toLowerCase() } as never, + depth: 0, + overrideAccess: true, + })) as unknown as Account, + update: async (id, data) => + (await payload.update({ collection: 'users', id, data: data as never, depth: 0, overrideAccess: true })) as unknown as Account, + } +} diff --git a/apps/cms/src/lib/lumen/session.ts b/apps/cms/src/lib/lumen/session.ts new file mode 100644 index 0000000..57c7c27 --- /dev/null +++ b/apps/cms/src/lib/lumen/session.ts @@ -0,0 +1,57 @@ +import { lumenCall, type LumenSessionResponse, type LumenTransport, type LumenUser } from './client' + +// Whether a Lumen session is live, asked of api-edge (GET /v1/auth/session) +// 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. + +export type LumenSession = { user: LumenUser; expiresAt: string } + +export const SESSION_CACHE_MS = 30_000 +const MAX_ENTRIES = 1000 + +type Entry = { at: number; value: LumenSession | null } +const cache = 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('') +} + +/** + * 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. + */ +export async function resolveSession( + transport: LumenTransport, + token: string, + now: number = Date.now(), +): Promise { + const key = await tokenKey(token) + const hit = cache.get(key) + if (hit && now - hit.at < SESSION_CACHE_MS) return hit.value + + 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 { + return null + } + if (cache.size >= MAX_ENTRIES) cache.delete(cache.keys().next().value as string) + cache.set(key, { at: now, value }) + return value +} + +/** Drop a token from the cache (sign-out), so the next request asks api-edge again. */ +export async function forgetSession(token: string): Promise { + cache.delete(await tokenKey(token)) +} + +/** For tests. */ +export function clearSessionCache(): void { + cache.clear() +} diff --git a/apps/cms/src/lib/lumen/strategy.ts b/apps/cms/src/lib/lumen/strategy.ts new file mode 100644 index 0000000..443dee0 --- /dev/null +++ b/apps/cms/src/lib/lumen/strategy.ts @@ -0,0 +1,52 @@ +import type { AuthStrategy, AuthStrategyFunction, Payload } from 'payload' + +import { presentedSetupToken, setupIsOpen } from '../setup-gate' +import { accountFor, type AccountStore } from './accounts' +import type { LumenTransport } from './client' +import { isCrossSiteNonNavigation, isForeignOrigin, LUMEN_SESSION_COOKIE, readCookie } from './cookies' +import { resolveSession } from './session' + +// The only way into the admin (design §2): a live Lumen session in the +// lumen_session cookie, resolved through api-edge, mapped to a `users` row. +// The token itself is never put on the user: Payload hands req.user to the +// browser. + +export type StrategyDeps = { + transport: () => Promise + store: (payload: Payload) => AccountStore + setupToken: () => string | undefined +} + +export function lumenAuthenticate(deps: StrategyDeps): AuthStrategyFunction { + return async ({ headers, payload }) => { + if (isCrossSiteNonNavigation(headers) || isForeignOrigin(headers)) return { user: null } + const token = readCookie(headers, LUMEN_SESSION_COOKIE) + if (!token) return { user: null } + const session = await resolveSession(await deps.transport(), token) + if (!session) return { user: null } + const setupOpen = setupIsOpen(deps.setupToken(), presentedSetupToken(headers)) + const account = await accountFor(deps.store(payload), session.user, setupOpen) + return { user: { ...account, collection: 'users', _strategy: 'lumen' } as never } + } +} + +// The runtime pieces load on first use, so importing the users collection +// (tests do) does not load the Workers adapter. +export const lumenStrategy: AuthStrategy = { + name: 'lumen', + authenticate: lumenAuthenticate({ + transport: async () => (await import('./transport')).lumenTransport(), + store: (payload) => { + let store: AccountStore | undefined + const lazy = async () => (store ??= (await import('./payload-store')).payloadAccountStore(payload)) + return { + findByLumenId: async (id) => (await lazy()).findByLumenId(id), + findUnlinkedByEmail: async (email) => (await lazy()).findUnlinkedByEmail(email), + adminExists: async () => (await lazy()).adminExists(), + create: async (data) => (await lazy()).create(data), + update: async (id, data) => (await lazy()).update(id, data), + } + }, + setupToken: () => process.env.CMS_SETUP_TOKEN, + }), +} diff --git a/apps/cms/src/lib/lumen/transport.ts b/apps/cms/src/lib/lumen/transport.ts new file mode 100644 index 0000000..a081327 --- /dev/null +++ b/apps/cms/src/lib/lumen/transport.ts @@ -0,0 +1,28 @@ +import { getCloudflareContext } from '@opennextjs/cloudflare' + +import { isWorkersRuntime } from '../runtime' +import type { LumenTransport } from './client' + +// How the CMS server reaches api-edge. On Workers, the LUMEN_API service +// binding: the call stays inside Cloudflare and api-edge authenticates it by +// its bearer token like any other client. Off Workers (local `next dev`, a +// local `wrangler dev` without the binding), LUMEN_API_URL. +export async function lumenTransport(): Promise { + if (isWorkersRuntime()) { + const { env } = await getCloudflareContext({ async: true }) + const binding = (env as { LUMEN_API?: { fetch(url: string, init?: RequestInit): Promise } }).LUMEN_API + if (binding) return (path, init) => binding.fetch(`https://lumen-api${path}`, init) + } + const base = process.env.LUMEN_API_URL + if (!base) { + return async () => { + throw new Error('The CMS has no way to reach Lumen: the LUMEN_API binding (or LUMEN_API_URL) is missing.') + } + } + return (path, init) => fetch(`${base.replace(/\/+$/, '')}${path}`, init) +} + +/** The api-edge URL the browser calls for sign-in (a Worker var; not a secret). */ +export function lumenPublicApiUrl(): string { + return (process.env.LUMEN_API_PUBLIC_URL ?? process.env.LUMEN_API_URL ?? '').replace(/\/+$/, '') +} diff --git a/apps/cms/src/lib/setup-gate.ts b/apps/cms/src/lib/setup-gate.ts index 697b13f..986ab51 100644 --- a/apps/cms/src/lib/setup-gate.ts +++ b/apps/cms/src/lib/setup-gate.ts @@ -1,8 +1,8 @@ -// The first-user gate (design §4). A fresh Payload install hands -// /admin/create-first-user to whoever arrives first; on a public workers.dev -// hostname that is an account takeover window. So creating the FIRST user -// requires a token equal to the Worker secret CMS_SETUP_TOKEN, which only the -// owner can set. Without that secret, setup is closed. +// The first-admin gate (lumen-payload-cms design §4, lumen-payload-console +// design §3). Anyone with a Lumen account can sign in, and on stage anyone can +// get one, so becoming the FIRST admin requires a token equal to the Worker +// secret CMS_SETUP_TOKEN, which only the owner can set. Without that secret, +// setup is closed and every new account stays pending. // // Pure functions, no Payload imports: tests/cms exercises them directly. diff --git a/apps/cms/src/payload-types.ts b/apps/cms/src/payload-types.ts index 9b9499b..6bef20a 100644 --- a/apps/cms/src/payload-types.ts +++ b/apps/cms/src/payload-types.ts @@ -130,7 +130,14 @@ export interface UserAuthOperations { export interface User { id: string; name?: string | null; - role: 'admin' | 'editor'; + /** + * Empty means pending: signed in with Lumen, but not let into the admin yet. + */ + role?: ('admin' | 'editor') | null; + /** + * Set on first Lumen sign-in. + */ + lumenUserId?: string | null; updatedAt: string; createdAt: string; email: string; @@ -341,6 +348,7 @@ export interface PayloadMigration { export interface UsersSelect { name?: T; role?: T; + lumenUserId?: T; updatedAt?: T; createdAt?: T; email?: T; diff --git a/apps/cms/src/payload.config.ts b/apps/cms/src/payload.config.ts index c994cd7..6029bfa 100644 --- a/apps/cms/src/payload.config.ts +++ b/apps/cms/src/payload.config.ts @@ -43,6 +43,15 @@ export default buildConfig({ user: Users.slug, importMap: { baseDir: path.resolve(dirname) }, meta: { titleSuffix: ' — CMS' }, + // Lumen sign-in replaces Payload's password views (lumen-payload-console + // design §1, §3): Payload's local strategy is off on `users`. + components: { + views: { + login: { Component: '/components/admin/LumenLogin#LumenLogin' }, + unauthorized: { Component: '/components/admin/PendingAccess#PendingAccess' }, + logout: { Component: '/components/admin/LumenSignOut#LumenSignOut' }, + }, + }, }, collections: [Users, Pages, Posts, Categories, Media], editor: lexicalEditor(), diff --git a/apps/cms/wrangler.template.jsonc b/apps/cms/wrangler.template.jsonc index 0791026..189f8c3 100644 --- a/apps/cms/wrangler.template.jsonc +++ b/apps/cms/wrangler.template.jsonc @@ -15,25 +15,40 @@ "vars": { "ENVIRONMENT": "local" }, "env": { "dev": { - "vars": { "ENVIRONMENT": "dev" } + "vars": { + "ENVIRONMENT": "dev", + "LUMEN_API_PUBLIC_URL": "https://lumen-payload-api-edge-dev.nexo-7be.workers.dev" + } }, "stage": { - "vars": { "ENVIRONMENT": "stage" }, + "vars": { + "ENVIRONMENT": "stage", + "LUMEN_API_PUBLIC_URL": "https://lumen-payload-api-edge-stage.nexo-7be.workers.dev" + }, "hyperdrive": [ { "binding": "HYPERDRIVE_CMS", "id": "@@wiring(cloudflare-hyperdrive-cms/stage:hyperdrive_id)@@" } ], "r2_buckets": [ { "binding": "R2_MEDIA", "bucket_name": "@@wiring(cloudflare-r2-cms/stage:bucket_name)@@" } - ] + ], + // Lumen sign-in (lumen-payload-console design §2): sessions are checked + // with api-edge over this binding, never over the public internet. + "services": [{ "binding": "LUMEN_API", "service": "lumen-payload-api-edge-stage" }] }, "prod": { - "vars": { "ENVIRONMENT": "prod" }, + "vars": { + "ENVIRONMENT": "prod", + "LUMEN_API_PUBLIC_URL": "https://lumen-payload-api-edge-prod.nexo-7be.workers.dev" + }, "hyperdrive": [ { "binding": "HYPERDRIVE_CMS", "id": "@@wiring(cloudflare-hyperdrive-cms/prod:hyperdrive_id)@@" } ], "r2_buckets": [ { "binding": "R2_MEDIA", "bucket_name": "@@wiring(cloudflare-r2-cms/prod:bucket_name)@@" } - ] + ], + // Lumen sign-in (lumen-payload-console design §2): sessions are checked + // with api-edge over this binding, never over the public internet. + "services": [{ "binding": "LUMEN_API", "service": "lumen-payload-api-edge-prod" }] } } } diff --git a/apps/identity-worker/wrangler.template.jsonc b/apps/identity-worker/wrangler.template.jsonc index 0da6241..4def0de 100644 --- a/apps/identity-worker/wrangler.template.jsonc +++ b/apps/identity-worker/wrangler.template.jsonc @@ -37,7 +37,7 @@ "GITHUB_OAUTH_CLIENT_ID": "", "GOOGLE_OAUTH_CLIENT_ID": "", "OAUTH_REDIRECT_BASE_URL": "", - "OAUTH_ALLOWED_CONSOLE_ORIGINS": "https://lumen-payload-web-console-next-dev.nexo-7be.workers.dev", + "OAUTH_ALLOWED_CONSOLE_ORIGINS": "https://lumen-payload-web-console-next-dev.nexo-7be.workers.dev,https://lumen-payload-cms-dev.nexo-7be.workers.dev", "SOLO_MODE": "true" } }, @@ -51,7 +51,7 @@ "GITHUB_OAUTH_CLIENT_ID": "Ov23liKBsjAqJJsmBavV", "GOOGLE_OAUTH_CLIENT_ID": "441163126775-7fabhvpbl9tsga921rklpdlde7mduq34.apps.googleusercontent.com", "OAUTH_REDIRECT_BASE_URL": "https://lumen-payload-api-edge-stage.nexo-7be.workers.dev", - "OAUTH_ALLOWED_CONSOLE_ORIGINS": "https://stage.lumen-payload.example.com,https://lumen-payload-web-console-next-stage.nexo-7be.workers.dev", + "OAUTH_ALLOWED_CONSOLE_ORIGINS": "https://stage.lumen-payload.example.com,https://lumen-payload-web-console-next-stage.nexo-7be.workers.dev,https://lumen-payload-cms-stage.nexo-7be.workers.dev", "SOLO_MODE": "true" }, "hyperdrive": [ @@ -85,7 +85,7 @@ "GITHUB_OAUTH_CLIENT_ID": "Ov23lilp2aoyeBDVU8Vc", "GOOGLE_OAUTH_CLIENT_ID": "441163126775-7fabhvpbl9tsga921rklpdlde7mduq34.apps.googleusercontent.com", "OAUTH_REDIRECT_BASE_URL": "https://lumen-payload-api-edge-prod.nexo-7be.workers.dev", - "OAUTH_ALLOWED_CONSOLE_ORIGINS": "https://prod.lumen-payload.example.com,https://lumen-payload-web-console-next-prod.nexo-7be.workers.dev", + "OAUTH_ALLOWED_CONSOLE_ORIGINS": "https://prod.lumen-payload.example.com,https://lumen-payload-web-console-next-prod.nexo-7be.workers.dev,https://lumen-payload-cms-prod.nexo-7be.workers.dev", "SOLO_MODE": "true" }, "hyperdrive": [ diff --git a/packages/db/src/manifest.ts b/packages/db/src/manifest.ts index 2a488a7..b825f9f 100644 --- a/packages/db/src/manifest.ts +++ b/packages/db/src/manifest.ts @@ -201,5 +201,14 @@ export const manifest: MigrationManifest = { description: "Payload CMS media (lumen-payload-cms PC4) — the media upload collection's table (files live in the cloudflare-r2-cms bucket) and its column on Payload's document-lock relations; generated from apps/cms/payload-migrations by scripts/payload-migration-to-sql.mjs", }, + { + id: "206_cms_lumen_identity", + context: "cms", + path: "206_cms_lumen_identity/up.sql", + checksum: + "81bc9ddcf261928a81ded38c77698cef729506581962d0fa731681fab4f9d279", + description: + "CMS staff sign in with Lumen (lumen-payload-console PX1) — users gain lumen_user_id (unique, the link to identity.users) and role becomes optional with no default (no role means pending); generated from apps/cms/payload-migrations", + }, ], }; diff --git a/packages/db/src/migrations/206_cms_lumen_identity/up.sql b/packages/db/src/migrations/206_cms_lumen_identity/up.sql new file mode 100644 index 0000000..ba79444 --- /dev/null +++ b/packages/db/src/migrations/206_cms_lumen_identity/up.sql @@ -0,0 +1,9 @@ +-- Generated from apps/cms/payload-migrations/20261028_121234_cms_lumen_identity.ts +-- by apps/cms/scripts/payload-migration-to-sql.mjs. Do not edit by hand: +-- change the collection, run `payload migrate:create`, and convert again. + +CREATE SCHEMA IF NOT EXISTS cms; +ALTER TABLE "cms"."users" ALTER COLUMN "role" DROP DEFAULT; +ALTER TABLE "cms"."users" ALTER COLUMN "role" DROP NOT NULL; +ALTER TABLE "cms"."users" ADD COLUMN IF NOT EXISTS "lumen_user_id" varchar; +CREATE UNIQUE INDEX IF NOT EXISTS "users_lumen_user_id_idx" ON "cms"."users" USING btree ("lumen_user_id"); diff --git a/specs/epics/lumen-payload-console/IMPLEMENTATION-STATUS.md b/specs/epics/lumen-payload-console/IMPLEMENTATION-STATUS.md index b3a9b86..247608e 100644 --- a/specs/epics/lumen-payload-console/IMPLEMENTATION-STATUS.md +++ b/specs/epics/lumen-payload-console/IMPLEMENTATION-STATUS.md @@ -5,8 +5,8 @@ the code departed from `design.md`. | Milestone | State | PR | |---|---|---| -| PX0 — the spec | In review | — | -| PX1 — Lumen sign-in | Not started | — | +| PX0 — the spec | Merged | sourceplane/lumen-payload#21 | +| PX1 — Lumen sign-in | In review | — | | PX2 — your account and organization | Not started | — | | PX3 — billing and plan | Not started | — | | PX4 — the front door | Not started | — | @@ -14,4 +14,17 @@ the code departed from `design.md`. ## Departures from the design -None yet. +- **PX1, CSRF.** Design §6 sets Payload's `csrf` allowlist to the CMS origin. + That allowlist only guards Payload's own `payload-token` cookie, whose + strategy is off once `disableLocalStrategy` is set, so setting it would + guard nothing. The `lumen` strategy does the same job for the Lumen cookie + itself: a request whose `Origin` names another host gets no user + (`isForeignOrigin`, `src/lib/lumen/cookies.ts`), which also separates + sibling Workers on the same workers.dev site. +- **PX1, the same-origin check behind `wrangler dev`.** Local `wrangler dev` + rewrites the request URL's host to `localhost`, so `/auth/lumen/session` + also accepts an `Origin` equal to the request's scheme with its `Host` + header. A page elsewhere cannot set `Host`. +- **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. diff --git a/tasks/PX-2.TaskContract.yaml b/tasks/PX-2.TaskContract.yaml new file mode 100644 index 0000000..39800f8 --- /dev/null +++ b/tasks/PX-2.TaskContract.yaml @@ -0,0 +1,28 @@ +apiVersion: orun.io/v1 +kind: TaskContract +metadata: + name: PX-2 + title: "PX1: Lumen sign-in for the Payload admin" +spec: + goal: "The Payload admin signs people in with their Lumen account and nothing else: the lumen auth strategy over api-edge, an httpOnly session cookie, pending accounts until an admin grants a role, the first admin through the owner's setup token, and sign-out that revokes the Lumen session." + affects: + - "apps/cms/**" + - "tests/cms/**" + - "packages/db/src/manifest.ts" + - "packages/db/src/migrations/206_cms_lumen_identity/**" + - "tests/db/src/cms-migration.test.ts" + - "apps/api-edge/src/app-config.ts" + - "apps/api-edge/src/cors.ts" + - "tests/api-edge/src/cors.test.ts" + - "apps/identity-worker/wrangler.template.jsonc" + - "tests/identity-worker/src/oauth-allowlist.test.ts" + - "ai/context/operations.md" + - "specs/epics/lumen-payload-console/IMPLEMENTATION-STATUS.md" + - "tasks/PX-2.TaskContract.yaml" + doneWhen: + - "on stage, an email-code sign-in reaches the pending page" + - "on stage, with setup open, a sign-in reaches the admin as admin" + - "on stage, a second account is pending until an admin promotes it" + - "after sign-out the old token answers 401 at GET /v1/auth/session" + - "prod's /admin shows the Lumen sign-in page" + gates: [] diff --git a/tests/api-edge/src/cors.test.ts b/tests/api-edge/src/cors.test.ts index 2ab8d5c..338e6d5 100644 --- a/tests/api-edge/src/cors.test.ts +++ b/tests/api-edge/src/cors.test.ts @@ -1,5 +1,5 @@ import { handlePreflight, applyCorsHeaders, isAllowedOrigin } from "@api-edge/cors"; -import { consoleWorkersDevOrigin } from "@api-edge/app-config"; +import { cmsWorkersDevOrigin, consoleWorkersDevOrigin } from "@api-edge/app-config"; import type { Env } from "@api-edge/env"; const stageEnv: Env = { ENVIRONMENT: "stage", CONSOLE_CUSTOM_DOMAIN: "stage.lumen-payload.example.com" }; @@ -311,3 +311,38 @@ describe("api-edge cors", () => { }); }); }); + +// lumen-payload-console PX1: the Payload CMS signs people in from the +// browser, so each environment's CMS origin is allowed in that environment +// only, and its literal stays the CMS Worker's own name. +describe("api-edge cors — the CMS origin", () => { + const cms = (env: string) => cmsWorkersDevOrigin(env); + + it("is the CMS Worker's workers.dev origin", () => { + expect(cms("stage")).toBe("https://lumen-payload-cms-stage.nexo-7be.workers.dev"); + }); + + it("is allowed in its own environment", () => { + expect(isAllowedOrigin(cms("stage"), stageEnv)).toBe(true); + expect(isAllowedOrigin(cms("prod"), prodEnv)).toBe(true); + }); + + it("is refused in the other environment", () => { + expect(isAllowedOrigin(cms("prod"), stageEnv)).toBe(false); + expect(isAllowedOrigin(cms("stage"), prodEnv)).toBe(false); + }); + + it("does not widen to look-alikes", () => { + expect(isAllowedOrigin("https://lumen-payload-cms-stage.nexo-7be.workers.dev.evil.example", stageEnv)).toBe(false); + expect(isAllowedOrigin("https://evil-lumen-payload-cms-stage.nexo-7be.workers.dev", stageEnv)).toBe(false); + expect(isAllowedOrigin("http://lumen-payload-cms-stage.nexo-7be.workers.dev", stageEnv)).toBe(false); + }); + + it("answers the browser's preflight with CORS headers", () => { + const res = handlePreflight( + new Request("https://api/v1/auth/login/start", { method: "OPTIONS", headers: { origin: cms("stage") } }), + stageEnv, + ); + expect(res!.headers.get("access-control-allow-origin")).toBe(cms("stage")); + }); +}); diff --git a/tests/cms/docs/overview.md b/tests/cms/docs/overview.md index 7701892..0b3c1df 100644 --- a/tests/cms/docs/overview.md +++ b/tests/cms/docs/overview.md @@ -12,11 +12,15 @@ this component changed. A red suite blocks the merge. | Suite | The promise | |---|---| | `setup-gate` | First-user setup is closed unless the owner set a long-enough `CMS_SETUP_TOKEN` and the request presents exactly it. | -| `users-gate` | `/api/users/first-register` is refused with 403 until then; the first account becomes an admin; the gate never touches later accounts or other operations. | +| `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-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). | | `wrangler-config` | The rendered config deploys the OpenNext build, binds `HYPERDRIVE_CMS` per environment from wiring, and commits no ids or secrets. | -| `migration-sync` | `packages/db` migration 200 is byte for byte the converter's output for Payload's migration. | +| `migration-sync` | Each converted `packages/db` migration (200, 205, 206) is byte for byte the converter's output for its Payload migration. | | `runtime` | The Worker reads its binding; `next build` and the CLIs read `DATABASE_URL`. | | `slug` | Slugs are derived, normalised and capped. | diff --git a/tests/cms/docs/runbook.md b/tests/cms/docs/runbook.md index 2255b05..b48ced8 100644 --- a/tests/cms/docs/runbook.md +++ b/tests/cms/docs/runbook.md @@ -16,5 +16,5 @@ pnpm --filter @saas/cms-tests typecheck `CONVERTED` in `src/migration-sync.test.ts`. - **wrangler-config**: the template lost a binding, gained a committed id, or changed `main`/`assets` away from the OpenNext outputs. -- **access / users-gate**: a collection's rules changed. If that was deliberate, +- **access / users / lumen-***: a collection's rules or the sign-in changed. If that was deliberate, update the test together with `apps/cms/docs/architecture.md`. diff --git a/tests/cms/src/access.test.ts b/tests/cms/src/access.test.ts index d98c003..887dc65 100644 --- a/tests/cms/src/access.test.ts +++ b/tests/cms/src/access.test.ts @@ -2,7 +2,7 @@ import { Categories } from '@cms/collections/Categories' import { Pages } from '@cms/collections/Pages' import { Posts } from '@cms/collections/Posts' import { Users } from '@cms/collections/Users' -import { adminOrSelf, anyone, isAdmin, isStaff, publishedOrStaff } from '@cms/lib/access' +import { adminOrSelf, anyone, isAdmin, isStaff, publishedOrStaff, selfOrAdmin } from '@cms/lib/access' // The rules the CMS promises (design §3, Routes): published pages, posts and // categories are public; everything else needs a staff session; only admins @@ -74,17 +74,19 @@ describe('collection contract', () => { expect(access(Categories).delete).toBe(isAdmin) }) - it('users: staff-only admin panel, admin-managed accounts, editor by default', () => { + it('users: staff-only admin panel, admin-managed accounts, pending by default', () => { expect(Users.auth).toBeTruthy() expect(access(Users).admin).toBe(isStaff) expect(access(Users).create).toBe(isAdmin) expect(access(Users).delete).toBe(isAdmin) - expect(access(Users).read).toBe(adminOrSelf) + // Anyone signed in reads their own account (a pending one too). + expect(access(Users).read).toBe(selfOrAdmin) expect(access(Users).update).toBe(adminOrSelf) const role = Users.fields.find((f) => 'name' in f && f.name === 'role') as Record & { access: { create: unknown; update: unknown } } - expect(role.defaultValue).toBe('editor') + // No default: a new Lumen sign-in has no role, which means pending. + expect(role.defaultValue).toBeUndefined() expect(role.saveToJWT).toBe(true) // Only an admin may set or change a role: an editor cannot promote themself. expect(call(role.access.update, editor)).toBe(false) diff --git a/tests/cms/src/lumen-accounts.test.ts b/tests/cms/src/lumen-accounts.test.ts new file mode 100644 index 0000000..d1ded67 --- /dev/null +++ b/tests/cms/src/lumen-accounts.test.ts @@ -0,0 +1,85 @@ +import { accountFor, type Account, type AccountStore } from '@cms/lib/lumen/accounts' + +// Who a signed-in Lumen user is in the CMS (design §3): found by the link, +// linked by email once, or created. No role means pending; the first admin +// needs the owner's setup token. + +function store(rows: Account[] = []) { + let next = rows.length + const s: AccountStore & { rows: Account[] } = { + rows, + findByLumenId: async (id) => rows.find((r) => r.lumenUserId === id) ?? null, + findUnlinkedByEmail: async (email) => rows.find((r) => r.email === email.toLowerCase() && !r.lumenUserId) ?? null, + adminExists: async () => rows.some((r) => r.role === 'admin'), + create: async (data) => { + if (rows.some((r) => r.lumenUserId && r.lumenUserId === data.lumenUserId)) throw new Error('unique') + const row = { id: `u${++next}`, ...data, email: data.email.toLowerCase() } + rows.push(row) + return row + }, + update: async (id, data) => { + const row = rows.find((r) => r.id === id)! + Object.assign(row, data) + return row + }, + } + return s +} + +const lumen = { id: 'usr_ed', email: 'Ed@Example.com', displayName: 'Ed' } + +describe('accountFor', () => { + it('returns the linked account', async () => { + const s = store([{ id: 'u1', email: 'ed@example.com', role: 'editor', lumenUserId: 'usr_ed' }]) + await expect(accountFor(s, lumen, false)).resolves.toMatchObject({ id: 'u1', role: 'editor' }) + expect(s.rows).toHaveLength(1) + }) + + it('links an unlinked account with the same email once, keeping its role (an invitation)', async () => { + const s = store([{ id: 'u1', email: 'ed@example.com', role: 'editor', lumenUserId: null }]) + await expect(accountFor(s, lumen, false)).resolves.toMatchObject({ id: 'u1', role: 'editor', lumenUserId: 'usr_ed' }) + }) + + it('never re-links an account linked to someone else', async () => { + const s = store([{ id: 'u1', email: 'ed@example.com', role: 'admin', lumenUserId: 'usr_other' }]) + let created = 0 + s.create = async () => { + created++ + throw new Error('email taken') + } + await expect(accountFor(s, lumen, true)).rejects.toThrow('email taken') + expect(created).toBe(1) + expect(s.rows[0]).toMatchObject({ lumenUserId: 'usr_other', role: 'admin' }) + }) + + it('creates a pending account (no role) for anyone new', async () => { + const s = store() + await expect(accountFor(s, lumen, false)).resolves.toMatchObject({ email: 'ed@example.com', name: 'Ed', role: null, lumenUserId: 'usr_ed' }) + }) + + it('makes the first admin only with the setup token and only while no admin exists', async () => { + const s = store() + await expect(accountFor(s, lumen, true)).resolves.toMatchObject({ role: 'admin' }) + await expect(accountFor(s, { id: 'usr_2', email: 'two@example.com', displayName: null }, true)).resolves.toMatchObject({ role: null }) + }) + + it('promotes a pending account through setup while there is no admin, and only then', async () => { + const s = store([{ id: 'u1', email: 'ed@example.com', role: null, lumenUserId: 'usr_ed' }]) + await expect(accountFor(s, lumen, false)).resolves.toMatchObject({ role: null }) + await expect(accountFor(s, lumen, true)).resolves.toMatchObject({ role: 'admin' }) + const t = store([ + { id: 'u1', email: 'boss@example.com', role: 'admin', lumenUserId: 'usr_boss' }, + { id: 'u2', email: 'ed@example.com', role: null, lumenUserId: 'usr_ed' }, + ]) + await expect(accountFor(t, lumen, true)).resolves.toMatchObject({ role: null }) + }) + + it('reads the row back when two first requests race to create it', async () => { + const s = store() + s.create = async (data) => { + s.rows.push({ id: 'u9', ...data, email: data.email.toLowerCase() }) + throw new Error('unique violation') + } + await expect(accountFor(s, lumen, false)).resolves.toMatchObject({ id: 'u9' }) + }) +}) diff --git a/tests/cms/src/lumen-cookies.test.ts b/tests/cms/src/lumen-cookies.test.ts new file mode 100644 index 0000000..043a43d --- /dev/null +++ b/tests/cms/src/lumen-cookies.test.ts @@ -0,0 +1,100 @@ +import { + clearedSessionCookie, + isCrossSiteNonNavigation, + isForeignOrigin, + isSameOrigin, + LUMEN_SESSION_COOKIE, + MAX_SESSION_SECONDS, + readCookie, + safeAdminRedirect, + sessionCookie, +} from '@cms/lib/lumen/cookies' + +// The Lumen session cookie and the checks around it (lumen-payload-console +// design §1, §6). + +describe('readCookie', () => { + it('reads the named cookie and nothing else', () => { + const headers = new Headers({ cookie: `a=1; ${LUMEN_SESSION_COOKIE}=sps_ses_x.y; ${LUMEN_SESSION_COOKIE}x=no` }) + expect(readCookie(headers, LUMEN_SESSION_COOKIE)).toBe('sps_ses_x.y') + expect(readCookie(new Headers(), LUMEN_SESSION_COOKIE)).toBeNull() + expect(readCookie(new Headers({ cookie: `${LUMEN_SESSION_COOKIE}=` }), LUMEN_SESSION_COOKIE)).toBeNull() + expect(readCookie(new Headers({ cookie: `${LUMEN_SESSION_COOKIE}=%E0%A4%A` }), LUMEN_SESSION_COOKIE)).toBeNull() + }) +}) + +describe('sessionCookie', () => { + const now = Date.parse('2026-10-28T12:00:00Z') + + it('is httpOnly, Lax, Path=/ and Secure on https, and lives until the session expires', () => { + const cookie = sessionCookie('tok', '2026-10-29T12:00:00Z', true, now) + expect(cookie).toContain(`${LUMEN_SESSION_COOKIE}=tok`) + expect(cookie).toContain('HttpOnly') + expect(cookie).toContain('SameSite=Lax') + expect(cookie).toContain('Path=/') + expect(cookie).toContain('Secure') + expect(cookie).toContain('Max-Age=86400') + expect(cookie).not.toMatch(/Domain=/i) + }) + + it('never outlives 30 days, never goes negative, and drops Secure on http', () => { + expect(sessionCookie('t', '2027-12-01T00:00:00Z', true, now)).toContain(`Max-Age=${MAX_SESSION_SECONDS}`) + expect(sessionCookie('t', '2026-10-01T00:00:00Z', true, now)).toContain('Max-Age=0') + expect(sessionCookie('t', null, false, now)).toContain(`Max-Age=${MAX_SESSION_SECONDS}`) + expect(sessionCookie('t', null, false, now)).not.toContain('Secure') + }) + + it('clears with Max-Age=0', () => { + expect(clearedSessionCookie(true)).toMatch(new RegExp(`^${LUMEN_SESSION_COOKIE}=; Path=/; Max-Age=0; HttpOnly; SameSite=Lax; Secure$`)) + }) +}) + +describe('safeAdminRedirect', () => { + it.each([ + ['/admin', '/admin'], + ['/admin/collections/pages', '/admin/collections/pages'], + ['/admin?x=1', '/admin?x=1'], + ])('keeps %s', (raw, expected) => expect(safeAdminRedirect(raw)).toBe(expected)) + + it.each([null, '', 'https://evil.example/admin', '//evil.example/admin', '/administrator', '/api/users', '/admin\\@evil', '/admin\n'])( + 'sends %p to /admin', + (raw) => expect(safeAdminRedirect(raw as string | null)).toBe('/admin'), + ) +}) + +describe('request origin checks', () => { + it('refuses background requests from another site, not links followed from one', () => { + expect(isCrossSiteNonNavigation(new Headers({ 'sec-fetch-site': 'cross-site', 'sec-fetch-mode': 'cors' }))).toBe(true) + expect(isCrossSiteNonNavigation(new Headers({ 'sec-fetch-site': 'cross-site', 'sec-fetch-mode': 'no-cors' }))).toBe(true) + expect(isCrossSiteNonNavigation(new Headers({ 'sec-fetch-site': 'cross-site', 'sec-fetch-mode': 'navigate' }))).toBe(false) + expect(isCrossSiteNonNavigation(new Headers({ 'sec-fetch-site': 'same-origin', 'sec-fetch-mode': 'cors' }))).toBe(false) + expect(isCrossSiteNonNavigation(new Headers())).toBe(false) + }) + + it('a request naming another origin is foreign, a sibling Worker on the same site included', () => { + const host = 'lumen-payload-cms-stage.nexo-7be.workers.dev' + expect(isForeignOrigin(new Headers({ host, origin: `https://${host}` }))).toBe(false) + expect(isForeignOrigin(new Headers({ host }))).toBe(false) + expect(isForeignOrigin(new Headers({ host, origin: 'https://lumen-payload-web-console-next-stage.nexo-7be.workers.dev' }))).toBe(true) + expect(isForeignOrigin(new Headers({ host, origin: 'https://evil.example' }))).toBe(true) + expect(isForeignOrigin(new Headers({ host, origin: 'null' }))).toBe(true) + expect(isForeignOrigin(new Headers({ host, origin: 'not a url' }))).toBe(true) + expect(isForeignOrigin(new Headers({ origin: `https://${host}` }))).toBe(true) + expect(isForeignOrigin(new Headers({ host: '127.0.0.1:8799', origin: 'http://127.0.0.1:8799' }))).toBe(false) + }) + + it('same origin means exactly this origin', () => { + const origin = 'https://lumen-payload-cms-stage.nexo-7be.workers.dev' + const url = `${origin}/auth/lumen/session` + expect(isSameOrigin(new Headers({ origin }), url)).toBe(true) + expect(isSameOrigin(new Headers({ origin: 'https://lumen-payload-web-console-next-stage.nexo-7be.workers.dev' }), url)).toBe(false) + expect(isSameOrigin(new Headers(), url)).toBe(false) + }) + + it('also accepts the Host the browser used when the URL was rewritten (local wrangler dev)', () => { + const url = 'http://localhost:8799/auth/lumen/session' + expect(isSameOrigin(new Headers({ origin: 'http://127.0.0.1:8799', host: '127.0.0.1:8799' }), url)).toBe(true) + expect(isSameOrigin(new Headers({ origin: 'https://evil.example', host: '127.0.0.1:8799' }), url)).toBe(false) + expect(isSameOrigin(new Headers({ origin: 'https://127.0.0.1:8799', host: '127.0.0.1:8799' }), url)).toBe(false) + }) +}) diff --git a/tests/cms/src/lumen-session.test.ts b/tests/cms/src/lumen-session.test.ts new file mode 100644 index 0000000..535dba1 --- /dev/null +++ b/tests/cms/src/lumen-session.test.ts @@ -0,0 +1,64 @@ +import type { LumenTransport } from '@cms/lib/lumen/client' +import { clearSessionCache, forgetSession, resolveSession, SESSION_CACHE_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). + +const user = { id: 'usr_0123', email: 'ed@example.com', displayName: 'Ed' } +const ok = () => + new Response(JSON.stringify({ data: { session: { id: 'ses_1', expiresAt: '2026-11-27T00:00:00Z' }, user } }), { status: 200 }) +const status = (code: number) => new Response(JSON.stringify({ error: { code: 'x', message: 'x' } }), { status: code }) + +function transport(responses: Array<() => Response | Promise>) { + const calls: Array<{ path: string; auth: string | null }> = [] + const fn: LumenTransport = async (path, init) => { + calls.push({ path, auth: new Headers(init.headers).get('authorization') }) + const next = responses.shift() + if (!next) throw new Error('no more responses') + return next() + } + return { fn, calls } +} + +beforeEach(() => clearSessionCache()) + +describe('resolveSession', () => { + it('asks api-edge with the bearer token and returns who it is', async () => { + const t = transport([ok]) + await expect(resolveSession(t.fn, 'tok', 0)).resolves.toEqual({ user, expiresAt: '2026-11-27T00:00:00Z' }) + expect(t.calls).toEqual([{ path: '/v1/auth/session', auth: 'Bearer tok' }]) + }) + + it('remembers the answer for 30 seconds, then asks again', async () => { + const t = transport([ok, () => status(401)]) + await resolveSession(t.fn, 'tok', 0) + await expect(resolveSession(t.fn, 'tok', SESSION_CACHE_MS - 1)).resolves.not.toBeNull() + expect(t.calls).toHaveLength(1) + await expect(resolveSession(t.fn, 'tok', SESSION_CACHE_MS)).resolves.toBeNull() + expect(t.calls).toHaveLength(2) + }) + + it('remembers a refusal too', async () => { + const t = transport([() => status(401)]) + await expect(resolveSession(t.fn, 'bad', 0)).resolves.toBeNull() + await expect(resolveSession(t.fn, 'bad', 1000)).resolves.toBeNull() + expect(t.calls).toHaveLength(1) + }) + + it('fails closed and does not remember when api-edge is down', async () => { + const t = transport([() => status(503), () => Promise.reject(new Error('reset')), ok]) + await expect(resolveSession(t.fn, 'tok', 0)).resolves.toBeNull() + await expect(resolveSession(t.fn, 'tok', 1)).resolves.toBeNull() + await expect(resolveSession(t.fn, 'tok', 2)).resolves.not.toBeNull() + expect(t.calls).toHaveLength(3) + }) + + 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() + await expect(resolveSession(t.fn, 'b', 0)).resolves.toBeNull() + await forgetSession('a') + await expect(resolveSession(t.fn, 'a', 1)).resolves.toBeNull() + expect(t.calls).toHaveLength(3) + }) +}) diff --git a/tests/cms/src/lumen-strategy.test.ts b/tests/cms/src/lumen-strategy.test.ts new file mode 100644 index 0000000..028c2e3 --- /dev/null +++ b/tests/cms/src/lumen-strategy.test.ts @@ -0,0 +1,112 @@ +import type { Account, AccountStore } from '@cms/lib/lumen/accounts' +import type { LumenTransport } from '@cms/lib/lumen/client' +import { LUMEN_SESSION_COOKIE } from '@cms/lib/lumen/cookies' +import { endSession } from '@cms/lib/lumen/logout' +import { clearSessionCache } from '@cms/lib/lumen/session' +import { lumenAuthenticate } from '@cms/lib/lumen/strategy' +import { SETUP_COOKIE } from '@cms/lib/setup-gate' + +// The only way into the admin (design §2): a live Lumen session in the +// lumen_session cookie, mapped to a users row. + +const SETUP = 'owner-setup-token-0123456789' +const user = { id: 'usr_ed', email: 'ed@example.com', displayName: 'Ed' } + +function deps(answer: number = 200) { + const calls: string[] = [] + const transport: LumenTransport = async (path, init) => { + calls.push(`${init.method ?? 'GET'} ${path} ${new Headers(init.headers).get('authorization')}`) + if (answer !== 200) return new Response(JSON.stringify({ error: { code: 'unauthenticated' } }), { status: answer }) + return new Response(JSON.stringify({ data: { session: { id: 's', expiresAt: '2026-12-01T00:00:00Z' }, user } })) + } + const rows: Account[] = [] + const store: AccountStore = { + findByLumenId: async (id) => rows.find((r) => r.lumenUserId === id) ?? null, + findUnlinkedByEmail: async () => null, + adminExists: async () => rows.some((r) => r.role === 'admin'), + create: async (data) => { + const row = { id: `u${rows.length + 1}`, ...data } + rows.push(row) + return row + }, + update: async (id, data) => Object.assign(rows.find((r) => r.id === id)!, data), + } + const authenticate = lumenAuthenticate({ transport: async () => transport, store: () => store, setupToken: () => SETUP }) + const run = (headers: Record) => authenticate({ headers: new Headers(headers), payload: {} as never }) + return { run, calls, rows, transport } +} + +beforeEach(() => clearSessionCache()) + +describe('lumen auth strategy', () => { + it('signs nobody in without the cookie, and asks api-edge nothing', async () => { + const d = deps() + await expect(d.run({})).resolves.toEqual({ user: null }) + expect(d.calls).toHaveLength(0) + }) + + it('signs in a live session as its users row, marked as this strategy', async () => { + const d = deps() + const { user: signedIn } = (await d.run({ cookie: `${LUMEN_SESSION_COOKIE}=tok` })) as { user: Record } + expect(signedIn).toMatchObject({ id: 'u1', email: 'ed@example.com', lumenUserId: 'usr_ed', collection: 'users', _strategy: 'lumen', role: null }) + expect(d.calls).toEqual(['GET /v1/auth/session Bearer tok']) + }) + + it('never puts the Lumen token on the user (Payload sends req.user to the browser)', async () => { + const d = deps() + const result = await d.run({ cookie: `${LUMEN_SESSION_COOKIE}=sps_ses_secret.value` }) + expect(JSON.stringify(result)).not.toContain('sps_ses_secret') + }) + + it('signs nobody in for a dead session', async () => { + const d = deps(401) + await expect(d.run({ cookie: `${LUMEN_SESSION_COOKIE}=tok` })).resolves.toEqual({ user: null }) + expect(d.rows).toHaveLength(0) + }) + + it('ignores background requests from another site', async () => { + const d = deps() + await expect( + d.run({ cookie: `${LUMEN_SESSION_COOKIE}=tok`, 'sec-fetch-site': 'cross-site', 'sec-fetch-mode': 'cors' }), + ).resolves.toEqual({ user: null }) + expect(d.calls).toHaveLength(0) + }) + + it('ignores writes another origin sends with the cookie, a sibling Worker on the same site included', async () => { + const d = deps() + const host = 'lumen-payload-cms-stage.nexo-7be.workers.dev' + const cookie = `${LUMEN_SESSION_COOKIE}=tok` + await expect( + d.run({ cookie, host, origin: 'https://lumen-payload-web-console-next-stage.nexo-7be.workers.dev', 'sec-fetch-site': 'same-site', 'sec-fetch-mode': 'navigate' }), + ).resolves.toEqual({ user: null }) + expect(d.calls).toHaveLength(0) + const own = (await d.run({ cookie, host, origin: `https://${host}`, 'sec-fetch-site': 'same-origin' })) as { user: unknown } + expect(own.user).not.toBeNull() + }) + + it('makes the first admin only with the setup cookie', async () => { + const d = deps() + const first = (await d.run({ cookie: `${LUMEN_SESSION_COOKIE}=tok; ${SETUP_COOKIE}=${SETUP}x` })) as unknown as { user: { role: unknown } } + expect(first.user.role).toBeNull() + clearSessionCache() + const again = (await d.run({ cookie: `${LUMEN_SESSION_COOKIE}=tok; ${SETUP_COOKIE}=${SETUP}` })) as unknown as { user: { role: unknown } } + expect(again.user.role).toBe('admin') + }) +}) + +describe('endSession (sign-out)', () => { + it('revokes the session at api-edge and clears the cookie', async () => { + const d = deps() + const result = await endSession(d.transport, new Headers({ cookie: `${LUMEN_SESSION_COOKIE}=tok` }), true) + expect(d.calls).toEqual(['POST /v1/auth/logout Bearer tok']) + expect(result.revoked).toBe(true) + expect(result.setCookie).toContain('Max-Age=0') + }) + + it('still clears the cookie when there is no session', async () => { + const d = deps() + const result = await endSession(d.transport, new Headers(), false) + expect(d.calls).toHaveLength(0) + expect(result.setCookie).toContain(`${LUMEN_SESSION_COOKIE}=;`) + }) +}) diff --git a/tests/cms/src/migration-sync.test.ts b/tests/cms/src/migration-sync.test.ts index 2ed2fd5..7558ad6 100644 --- a/tests/cms/src/migration-sync.test.ts +++ b/tests/cms/src/migration-sync.test.ts @@ -16,6 +16,7 @@ const converter = join(root, 'apps/cms/scripts/payload-migration-to-sql.mjs') const CONVERTED: Record = { '20261027_203229_cms_payload_core.ts': '200_cms_payload_core', '20261028_061257_cms_media.ts': '205_cms_media', + '20261028_121234_cms_lumen_identity.ts': '206_cms_lumen_identity', } describe('Payload migrations ↔ db-migrate', () => { diff --git a/tests/cms/src/users-gate.test.ts b/tests/cms/src/users-gate.test.ts deleted file mode 100644 index 8b4f722..0000000 --- a/tests/cms/src/users-gate.test.ts +++ /dev/null @@ -1,77 +0,0 @@ -import { APIError } from './stubs/payload' - -import { Users } from '@cms/collections/Users' -import { SETUP_COOKIE, SETUP_HEADER } from '@cms/lib/setup-gate' - -// Jest maps 'payload' to ./stubs/payload, so this is the class Users.ts throws. - -type Hook = (args: Record) => Promise -const gate = Users.hooks!.beforeOperation![0] as unknown as Hook -const firstIsAdmin = Users.hooks!.beforeChange![0] as unknown as Hook - -const TOKEN = 'owner-setup-token-0123456789' - -function req({ users, user = null, headers = {} }: { users: number; user?: unknown; headers?: Record }) { - return { - user, - headers: new Headers(headers), - payload: { count: async () => ({ totalDocs: users }) }, - } -} - -describe('first-user gate (Users.beforeOperation)', () => { - const saved = process.env.CMS_SETUP_TOKEN - afterEach(() => { - if (saved === undefined) delete process.env.CMS_SETUP_TOKEN - else process.env.CMS_SETUP_TOKEN = saved - }) - - it('refuses the first account with 403 when setup was never opened', async () => { - delete process.env.CMS_SETUP_TOKEN - const err = await gate({ operation: 'create', req: req({ users: 0, headers: { [SETUP_HEADER]: TOKEN } }) }).catch((e) => e) - expect(err).toBeInstanceOf(APIError) - expect((err as APIError).status).toBe(403) - expect((err as APIError).isPublic).toBe(true) - }) - - it('refuses the first account without the token, or with the wrong one', async () => { - process.env.CMS_SETUP_TOKEN = TOKEN - await expect(gate({ operation: 'create', req: req({ users: 0 }) })).rejects.toBeInstanceOf(APIError) - await expect( - gate({ operation: 'create', req: req({ users: 0, headers: { cookie: `${SETUP_COOKIE}=${TOKEN}x` } }) }), - ).rejects.toBeInstanceOf(APIError) - }) - - it('allows the first account with the setup cookie or header', async () => { - process.env.CMS_SETUP_TOKEN = TOKEN - await expect(gate({ operation: 'create', req: req({ users: 0, headers: { cookie: `${SETUP_COOKIE}=${TOKEN}` } }) })).resolves.toBeUndefined() - await expect(gate({ operation: 'create', req: req({ users: 0, headers: { [SETUP_HEADER]: TOKEN } }) })).resolves.toBeUndefined() - }) - - it('stays out of the way once an account exists (Payload refuses first-register itself)', async () => { - delete process.env.CMS_SETUP_TOKEN - await expect(gate({ operation: 'create', req: req({ users: 1 }) })).resolves.toBeUndefined() - }) - - it('never gates signed-in staff or other operations', async () => { - delete process.env.CMS_SETUP_TOKEN - await expect(gate({ operation: 'create', req: req({ users: 0, user: { role: 'admin' } }) })).resolves.toBeUndefined() - for (const operation of ['read', 'update', 'delete', 'login', 'forgotPassword']) { - await expect(gate({ operation, req: req({ users: 0 }) })).resolves.toBeUndefined() - } - }) -}) - -describe('first user is admin (Users.beforeChange)', () => { - it('makes the first account an admin whatever role it asked for', async () => { - const data = await firstIsAdmin({ data: { email: 'o@example.com', role: 'editor' }, operation: 'create', req: req({ users: 0 }) }) - expect(data).toMatchObject({ role: 'admin' }) - }) - - it('leaves later accounts as created', async () => { - const data = await firstIsAdmin({ data: { email: 'e@example.com', role: 'editor' }, operation: 'create', req: req({ users: 3 }) }) - expect(data).toMatchObject({ role: 'editor' }) - const updated = await firstIsAdmin({ data: { role: 'editor' }, operation: 'update', req: req({ users: 0 }) }) - expect(updated).toMatchObject({ role: 'editor' }) - }) -}) diff --git a/tests/cms/src/users.test.ts b/tests/cms/src/users.test.ts new file mode 100644 index 0000000..4f63727 --- /dev/null +++ b/tests/cms/src/users.test.ts @@ -0,0 +1,55 @@ +import { Users } from '@cms/collections/Users' + +// Staff accounts sign in with Lumen only (design §1, §3). + +type AnyAccess = (args: { req: { user: unknown } }) => unknown +const call = (fn: unknown, user: unknown) => (fn as AnyAccess)({ req: { user } }) +const field = (name: string) => Users.fields.find((f) => 'name' in f && f.name === name) as Record + +const admin = { id: 'a', collection: 'users', role: 'admin' } +const editor = { id: 'e', collection: 'users', role: 'editor' } +const pending = { id: 'p', collection: 'users', role: null } + +describe('users', () => { + it('has no Payload passwords: the local strategy is off, its columns stay, and Lumen is the strategy', () => { + const auth = Users.auth as { disableLocalStrategy: unknown; strategies: Array<{ name: string }> } + expect(auth.disableLocalStrategy).toEqual({ enableFields: true }) + expect(auth.strategies.map((s) => s.name)).toEqual(['lumen']) + }) + + it('has no first-register hooks left: the setup rule lives in account provisioning', () => { + expect(Users.hooks?.beforeOperation).toBeUndefined() + expect(Users.hooks?.beforeChange).toBeUndefined() + expect(Users.hooks?.afterLogout).toHaveLength(1) + }) + + it('a role is optional with no default: no role means pending', () => { + expect(field('role').required).toBeUndefined() + expect(field('role').defaultValue).toBeUndefined() + expect((field('role').options as Array<{ value: string }>).map((o) => o.value)).toEqual(['admin', 'editor']) + }) + + it('links to Lumen by a unique, read-only lumenUserId that no request can set', () => { + const link = field('lumenUserId') + expect(link).toMatchObject({ type: 'text', unique: true, index: true }) + const access = link.access as { create: () => boolean; update: () => boolean } + expect(access.create()).toBe(false) + expect(access.update()).toBe(false) + }) + + it('lets admins and editors into the admin, never a pending account', () => { + expect(call(Users.access!.admin, admin)).toBe(true) + expect(call(Users.access!.admin, editor)).toBe(true) + expect(call(Users.access!.admin, pending)).toBe(false) + expect(call(Users.access!.admin, null)).toBe(false) + }) + + it('a pending account reads only itself; only admins create, delete or read everyone', () => { + expect(call(Users.access!.read, pending)).toEqual({ id: { equals: 'p' } }) + expect(call(Users.access!.read, admin)).toBe(true) + expect(call(Users.access!.update, pending)).toBe(false) + expect(call(Users.access!.create, editor)).toBe(false) + expect(call(Users.access!.delete, editor)).toBe(false) + expect(call(Users.access!.create, admin)).toBe(true) + }) +}) diff --git a/tests/cms/src/wrangler-config.test.ts b/tests/cms/src/wrangler-config.test.ts index da6a966..a93d4e5 100644 --- a/tests/cms/src/wrangler-config.test.ts +++ b/tests/cms/src/wrangler-config.test.ts @@ -38,6 +38,7 @@ type Env = { vars?: Record hyperdrive?: Array<{ binding: string; id: string }> r2_buckets?: Array<{ binding: string; bucket_name: string }> + services?: Array<{ binding: string; service: string }> } let rendered: Env & { name: string @@ -91,7 +92,14 @@ describe('wrangler config', () => { ['prod', '00000000000000000000000000000013'], ])('%s binds HYPERDRIVE_CMS to its own config', (env, id) => { expect(rendered.env[env]!.hyperdrive).toEqual([{ binding: 'HYPERDRIVE_CMS', id }]) - expect(rendered.env[env]!.vars).toEqual({ ENVIRONMENT: env }) + expect(rendered.env[env]!.vars).toEqual({ + ENVIRONMENT: env, + LUMEN_API_PUBLIC_URL: `https://lumen-payload-api-edge-${env}.nexo-7be.workers.dev`, + }) + }) + + it.each(['stage', 'prod'])('%s reaches api-edge over the LUMEN_API service binding (Lumen sign-in)', (env) => { + expect(rendered.env[env]!.services).toEqual([{ binding: 'LUMEN_API', service: `lumen-payload-api-edge-${env}` }]) }) it.each([ @@ -101,9 +109,10 @@ describe('wrangler config', () => { expect(rendered.env[env]!.r2_buckets).toEqual([{ binding: 'R2_MEDIA', bucket_name: bucket }]) }) - it('dev binds no database and no bucket: it never deploys', () => { + it('dev binds no database, no bucket and no api-edge: it never deploys', () => { expect(rendered.env.dev!.hyperdrive).toBeUndefined() expect(rendered.env.dev!.r2_buckets).toBeUndefined() + expect(rendered.env.dev!.services).toBeUndefined() }) it('carries no secrets: PAYLOAD_SECRET and CMS_SETUP_TOKEN are Worker secrets', () => { diff --git a/tests/db/src/cms-migration.test.ts b/tests/db/src/cms-migration.test.ts index 5060f3c..d744706 100644 --- a/tests/db/src/cms-migration.test.ts +++ b/tests/db/src/cms-migration.test.ts @@ -146,3 +146,40 @@ describe("CMS media migration (205_cms_media)", () => { expect(media).not.toMatch(/\b(public|identity|membership|billing|events|projects)\./); }); }); + +describe("CMS Lumen identity migration (206_cms_lumen_identity)", () => { + const sql = readFileSync( + resolve(MIGRATIONS_ROOT, "206_cms_lumen_identity/up.sql"), + "utf-8", + ); + const ids = manifest.migrations.map((m) => m.id); + + it("is registered under the cms context, after the CMS core and media", () => { + expect(ids.indexOf("206_cms_lumen_identity")).toBeGreaterThan(ids.indexOf("205_cms_media")); + expect(manifest.migrations.find((m) => m.id === "206_cms_lumen_identity")!.context).toBe("cms"); + }); + + it("links users to Lumen by a unique lumen_user_id", () => { + expect(sql).toContain('ALTER TABLE "cms"."users" ADD COLUMN IF NOT EXISTS "lumen_user_id" varchar;'); + expect(sql).toContain('CREATE UNIQUE INDEX IF NOT EXISTS "users_lumen_user_id_idx" ON "cms"."users" USING btree ("lumen_user_id");'); + }); + + it("makes the role optional with no default (no role means pending), without a new enum value", () => { + expect(sql).toContain('ALTER TABLE "cms"."users" ALTER COLUMN "role" DROP DEFAULT;'); + expect(sql).toContain('ALTER TABLE "cms"."users" ALTER COLUMN "role" DROP NOT NULL;'); + expect(sql).not.toMatch(/ADD VALUE/); + }); + + it("is idempotent statement by statement, and stays in schema cms", () => { + for (const stmt of statements(sql)) { + const ok = + stmt.startsWith("CREATE SCHEMA IF NOT EXISTS ") || + /^CREATE (UNIQUE )?INDEX IF NOT EXISTS /.test(stmt) || + /^ALTER TABLE "cms"\."\w+" ADD COLUMN IF NOT EXISTS /.test(stmt) || + /^ALTER TABLE "cms"\."\w+" ALTER COLUMN "\w+" (DROP DEFAULT|DROP NOT NULL)$/.test(stmt.replace(/;$/, "")); + if (!ok) throw new Error(`not idempotent: ${stmt.split("\n")[0]}`); + } + expect(sql).not.toMatch(/\b(DROP TABLE|DROP COLUMN|GRANT|RENAME)\b/i); + expect(sql).not.toMatch(/\b(public|identity|membership|billing|events|projects)\./); + }); +}); diff --git a/tests/identity-worker/src/oauth-allowlist.test.ts b/tests/identity-worker/src/oauth-allowlist.test.ts new file mode 100644 index 0000000..a57a91c --- /dev/null +++ b/tests/identity-worker/src/oauth-allowlist.test.ts @@ -0,0 +1,41 @@ +import fs from "node:fs"; +import path from "node:path"; +import { fileURLToPath } from "node:url"; + +import { isAllowedReturnTo } from "../../../apps/identity-worker/src/oauth/config"; + +// GitHub and Google sign-in return to the Payload CMS as well as the console +// (lumen-payload-console design §1): each environment allows its own CMS +// origin, and only its own. + +const templatePath = path.resolve( + path.dirname(fileURLToPath(import.meta.url)), + "../../../apps/identity-worker/wrangler.template.jsonc", +); + +function parseJsonc(text: string): Record { + const withoutComments = text + .split("\n") + .filter((line) => !line.trim().startsWith("//")) + .join("\n"); + return JSON.parse(withoutComments.replace(/,(\s*[}\]])/g, "$1")) as Record; +} + +const config = parseJsonc(fs.readFileSync(templatePath, "utf-8")) as { + env: Record; +}; +const cms = (env: string) => `https://lumen-payload-cms-${env}.nexo-7be.workers.dev`; + +describe("OAuth return allowlist", () => { + it.each(["dev", "stage", "prod"])("%s lets sign-in return to its own CMS", (env) => { + const vars = config.env[env]!.vars; + const allowed = vars.OAUTH_ALLOWED_CONSOLE_ORIGINS.split(","); + expect(allowed).toContain(cms(env)); + expect(isAllowedReturnTo(`${cms(env)}/auth/lumen/callback?redirect=%2Fadmin`, vars as never)).toBe(true); + }); + + it("does not let stage sign-in return to prod's CMS, or the reverse", () => { + expect(config.env.stage!.vars.OAUTH_ALLOWED_CONSOLE_ORIGINS).not.toContain(cms("prod")); + expect(config.env.prod!.vars.OAUTH_ALLOWED_CONSOLE_ORIGINS).not.toContain(cms("stage")); + }); +});