Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
22 changes: 12 additions & 10 deletions ai/context/operations.md
Original file line number Diff line number Diff line change
Expand Up @@ -121,7 +121,7 @@ orun integrations list --org <ws> --json && orun cloud check --org <ws>
| check integrations | `orun integrations list --org <ws> --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
Expand Down Expand Up @@ -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
Expand All @@ -182,18 +184,18 @@ orun secrets set CMS_SETUP_TOKEN --org <ws> --env stage # a token of 16+ chara
# then visit https://lumen-payload-cms-stage.<subdomain>.workers.dev/setup?token=<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.<subdomain>.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
```

Expand Down Expand Up @@ -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 |
Expand Down
12 changes: 12 additions & 0 deletions apps/api-edge/src/app-config.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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`;
}
13 changes: 11 additions & 2 deletions apps/api-edge/src/cors.ts
Original file line number Diff line number Diff line change
@@ -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
Expand All @@ -16,6 +16,14 @@ const WORKERS_ORIGINS: Record<string, string> = {
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<string, string> = {
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+)?$/;

Expand Down Expand Up @@ -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;
}

Expand Down
6 changes: 6 additions & 0 deletions apps/cms/cloudflare-env.d.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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
}
9 changes: 9 additions & 0 deletions apps/cms/component.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
34 changes: 28 additions & 6 deletions apps/cms/docs/architecture.md
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,10 @@ browser ──► lumen-payload-cms-<env> (Worker)
/api/graphql GraphQL ├─ payload ─► HYPERDRIVE_CMS ─► Supabase Postgres, schema cms
/health liveness + db ┘ │ (cache disabled)
/api/media/file/* uploaded files └──────► R2_MEDIA ─► <prefix>lumen-payload-cms-media-<env>
/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
Expand All @@ -25,6 +28,9 @@ browser ──► lumen-payload-cms-<env> (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-<env>` (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
Expand All @@ -49,9 +55,25 @@ browser ──► lumen-payload-cms-<env> (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
Expand All @@ -63,7 +85,7 @@ browser ──► lumen-payload-cms-<env> (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.
19 changes: 13 additions & 6 deletions apps/cms/docs/overview.md
Original file line number Diff line number Diff line change
Expand Up @@ -10,8 +10,11 @@ at `/api/<collection>` 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.
Expand All @@ -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

Expand Down
53 changes: 40 additions & 13 deletions apps/cms/docs/runbook.md
Original file line number Diff line number Diff line change
Expand Up @@ -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:
Expand All @@ -21,9 +38,11 @@ setup. Once per environment:
- directly: `pnpm exec wrangler secret put CMS_SETUP_TOKEN --name lumen-payload-cms-<env>`
(it prompts for the value).
3. Visit `https://lumen-payload-cms-<env>.nexo-7be.workers.dev/setup?token=<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.

Expand All @@ -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
Expand All @@ -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 <token>" -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=<token>" -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
```
Expand Down Expand Up @@ -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:<pw>@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:<port>` 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.

Expand Down
Loading
Loading