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
5 changes: 5 additions & 0 deletions ai/context/operations.md
Original file line number Diff line number Diff line change
Expand Up @@ -164,6 +164,11 @@ it through `api-edge`, and no worker calls it.
served at `/api/media/file/<filename>`. SVG is refused. The bucket component
runs with `CLOUDFLARE_R2_TOKEN` (project rung, from the Cloudflare
connection's `r2-data` template, rotated by the platform every 30 days).
- **Sign-in and account:** the admin signs in with a Lumen account (no CMS
passwords; a new account is pending until an admin gives it a role, and
admins invite people by creating a user with their email). Its *Account*
nav group holds the Lumen account pages: Profile, Security activity,
Organization and Notifications.
- **Secrets:** `CMS_PAYLOAD_SECRET` is generated and published by
`cloudflare-hyperdrive-cms` (nobody chooses or sees it) and pushed to the
Worker as `PAYLOAD_SECRET`. `CMS_SETUP_TOKEN` exists only if the owner sets
Expand Down
16 changes: 15 additions & 1 deletion apps/api-edge/src/auth-facade.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@ import type { Env } from "./env";
import { errorResponse } from "./http";
import { replayOrExecute } from "./idempotency";
import { cacheApiStore, bearerToken } from "./actor-cache";
import type { RouteFamily } from "./rate-limit";

const LOGOUT_PATH = "/v1/auth/logout";

Expand Down Expand Up @@ -44,6 +45,19 @@ const FORWARDED_HEADERS = [
"cookie",
];

/** Routes a signed-in person uses for their own account: rate-limited as `account`, not `auth`. */
const ACCOUNT_ROUTES = new Set(["/v1/auth/session", "/v1/auth/profile", "/v1/auth/security-events"]);

/**
* The rate-limit family of an auth route: `account` for a bearer reading its
* own session, profile or security events (or saving its profile), `auth`
* for everything else — sign-in, OAuth, logout and anonymous calls.
*/
export function authRouteFamily(request: Request, pathname: string): RouteFamily {
if (!ACCOUNT_ROUTES.has(pathname)) return "auth";
return bearerToken(request.headers.get("authorization")) ? "account" : "auth";
}

export function isAuthRoute(pathname: string): boolean {
return pathname in AUTH_ROUTES || pathname in AUTH_MULTI_METHOD_ROUTES || isOAuthRoute(pathname);
}
Expand Down Expand Up @@ -72,7 +86,7 @@ export async function handleAuthRoute(
return errorResponse("unsupported", "Method not allowed", 405, requestId);
}

return replayOrExecute(request, requestId, env, "auth", async () => {
return replayOrExecute(request, requestId, env, authRouteFamily(request, pathname), async () => {
if (!env.IDENTITY_WORKER) {
return errorResponse(
"internal_error",
Expand Down
11 changes: 11 additions & 0 deletions apps/api-edge/src/rate-limit.ts
Original file line number Diff line number Diff line change
Expand Up @@ -49,6 +49,7 @@ import type { Env } from "./env.js";

export type RouteFamily =
| "auth"
| "account"
| "org"
| "project"
| "config"
Expand Down Expand Up @@ -76,6 +77,12 @@ interface FamilyConfig {
* blunting abuse. Tunable; no per-tenant overrides yet (B5 territory).
*
* - `auth`: tighter — login/logout flows are the brute-force target.
* - `account`: a signed-in person reading their own session, profile and
* security events (and saving their profile). The bucket is keyed on the
* bearer itself, so the tight `auth` cap never slowed token guessing —
* every guess gets a fresh bucket — and it only throttled a real session;
* the Payload admin re-checks its session and reads the profile on page
* loads (lumen-payload-console PX2).
* - everything else (writes/reads): 60/300 per minute identity/org.
* - `audit` is read-only and trusted further; raised to 120/600.
*/
Expand All @@ -84,6 +91,10 @@ const LIMITS: Record<RouteFamily, FamilyConfig> = {
identity: { limit: 10, windowSec: 60 },
org: { limit: 60, windowSec: 60 },
},
account: {
identity: { limit: 60, windowSec: 60 },
org: { limit: 300, windowSec: 60 },
},
org: {
identity: { limit: 60, windowSec: 60 },
org: { limit: 300, windowSec: 60 },
Expand Down
27 changes: 22 additions & 5 deletions apps/cms/docs/architecture.md
Original file line number Diff line number Diff line change
Expand Up @@ -15,8 +15,11 @@ browser ──► lumen-payload-cms-<env> (Worker)
/api/media/file/* uploaded files └──────► R2_MEDIA ─► <prefix>lumen-payload-cms-media-<env>
/setup opens first-admin setup (owner only)
/auth/lumen/* the Lumen session in, out, and the OAuth return
/admin/account… the Lumen account pages (custom admin views)
/lumen/* their forms
│
lumen strategy ──┴──► LUMEN_API (service binding) ─► api-edge ─► identity
lumen strategy, account pages ──► LUMEN_API (service binding) ─► api-edge ─► identity,
membership, notifications
```

## Bindings and secrets
Expand Down Expand Up @@ -61,19 +64,34 @@ browser ──► lumen-payload-cms-<env> (Worker)
there are no CMS passwords, and `login`, `first-register` and password reset
answer 403. The `lumen` strategy reads the `lumen_session` cookie, asks
api-edge `GET /v1/auth/session` over the service binding (answers cached
30 s per token, keyed by its hash; failures are not cached), and finds,
30 s per token, keyed by its hash; concurrent requests share one lookup;
when api-edge cannot answer, a session it confirmed in the last 5 minutes
still stands until it expires, and an unconfirmed one fails closed), and finds,
links (by email) or creates the `users` row by `lumenUserId`. The token stays
in the HttpOnly cookie: it is never on `req.user`, so the admin's browser
code never sees it. A request that names another origin gets no user, so
no other page can write through the API with the cookie, not even a sibling
Worker on the same workers.dev site, which SameSite does not separate. This
stands in for Payload's `csrf` allowlist, which applies only to Payload's
own cookie and is off with it. `/auth/lumen/session` takes a token only from
own cookie and is off with it. Every response also carries
`frame-ancestors 'self'` (and `X-Frame-Options: SAMEORIGIN`), so no other
page can frame the admin and click through it. `/auth/lumen/session` takes a token only from
a same-origin form post.
- **Roles stay Payload's.** A new row has no role: pending, which the admin's
`unauthorized` view tells them. The first admin needs the owner's setup token
(`src/lib/setup-gate.ts`, `src/app/setup/route.ts`): while no admin exists,
the account that signs in with it becomes admin. Admins grant the rest.
- **The account pages are admin views over api-edge** (`src/components/admin/account/`,
`src/lib/lumen/account-api.ts`, `src/lib/lumen/forms.ts`; design §4).
Payload's `account` view is replaced, so Payload still keeps pending
accounts out of it; the other three are custom views, which Payload does not
guard, so each checks for a staff role itself and brings Payload's default
template. They read per request, uncached, with the person's own token, and
render on the server: the browser never calls api-edge for them. Forms post
to `/lumen/*` route handlers that accept only a same-origin post from staff
and answer `303` back to the page. The console's framework-free models
(`src/lib/lumen/models/`) are copied, not shared: the console is retired in
PX4.
- **Pinned versions.** Payload 3.89.0 hashes passwords with 25,000 PBKDF2
iterations; 3.90.0 hard-codes 600,000, which workerd rejects. Next 16.3.3,
React 19.2.6, OpenNext 1.20.1 and wrangler 4.116 are the combination Payload's
Expand All @@ -85,7 +103,6 @@ browser ──► lumen-payload-cms-<env> (Worker)

## Out of scope here

Lumen's account pages in the admin (PX2, PX3), the console URL opening the
admin (PX4), serving content through `api-edge`, per-tenant content, and image derivatives: resizing, cropping and focal
Billing and plan in the admin (PX3), the console URL opening the admin (PX4), serving content through `api-edge`, per-tenant content, and image derivatives: resizing, cropping and focal
points need `sharp`, which does not run on Workers, so files are stored and
served as uploaded.
7 changes: 6 additions & 1 deletion apps/cms/docs/overview.md
Original file line number Diff line number Diff line change
Expand Up @@ -27,6 +27,10 @@ Published pages, posts and categories, and all media, are readable by anyone
through the API. Drafts, accounts and everything else need a staff session.
Staff upload media; only admins delete it.

The admin also has the person's **Lumen account pages** (Profile, Security
activity, Organization, Notifications), read from and saved to Lumen through
`api-edge`; nothing of them is stored in the CMS but the display name.

## Depends on

- **cloudflare-hyperdrive-cms**: its database path (cache disabled) and its
Expand All @@ -35,7 +39,8 @@ Staff upload media; only admins delete it.
- **db-migrate**: applies schema `cms` (migrations `200_cms_payload_core`,
`205_cms_media` and `206_cms_lumen_identity`) before the CMS deploys.
- **api-edge**: the CMS asks it, over a service binding, whose Lumen session a
request carries, and ends the session on sign-out. Its CORS lets the CMS's
request carries, ends the session on sign-out, and reads and changes the
account pages' data with the person's session. Its CORS lets the CMS's
sign-in page call the auth routes, and identity-worker's OAuth return
allowlist includes the CMS.

Expand Down
27 changes: 25 additions & 2 deletions apps/cms/docs/runbook.md
Original file line number Diff line number Diff line change
Expand Up @@ -23,8 +23,27 @@ a `users` row by `lumenUserId`, creating the row the first time.
A new row has **no role**, which means *pending*: the person is signed in but
sees "Waiting for access" until an admin opens *Users* and makes them an
`editor` or `admin`. A row an admin created beforehand with the same email
(an invitation) is linked on that person's first sign-in and keeps its role.
Signing out (the admin's log-out button) revokes the Lumen session too.
(an invitation) is linked on that person's first sign-in and keeps its role:
to invite someone, open *Users → Create new*, enter their email and pick a
role. Signing out (the admin's log-out button) revokes the Lumen session too.

## Your account

The admin's nav has an **Account** group: the same Lumen account pages the
console had, for admins and editors (a pending account sees none of them).
Each page reads Lumen through `api-edge` with the person's own session when it
loads; forms post to `/lumen/*` on the CMS, which calls `api-edge` and comes
back to the page with *Saved.* or what went wrong.

| Page | Path | Shows | Changes |
|---|---|---|---|
| Profile | `/admin/account` (Payload's account page, replaced) | email, CMS role, Lumen user id | display name (copied onto the `users` row) |
| Security activity | `/admin/account/security` | sign-ins, codes and sessions, newest first, 50 a page | — |
| Organization | `/admin/organization` | the Lumen organization (Solo: the personal one) | — (renaming is not in the API) |
| Notifications | `/admin/organization/notifications` | email categories for that organization | which categories Lumen emails |

A page that cannot reach Lumen says so (for example *The CMS could not reach
Lumen*) instead of failing: check `api-edge` and the `LUMEN_API` binding.

## Open the admin (first admin)

Expand Down Expand Up @@ -147,6 +166,10 @@ real R2 adapter.
environment and published `WIRING_CLOUDFLARE_R2_CMS`, then redeploy the CMS.
- **An upload answers 413.** It is over 10 MiB (`MEDIA_MAX_BYTES` in
`src/collections/Media.ts`).
- **An account page says "Lumen answered with an error (internal_error)".**
api-edge or the worker behind it failed; its logs carry the request id.
Security activity answered 503 for everyone until identity-worker queried
events by the user's UUID rather than its public `usr_` id (PX2).
- **Deploy: "exceeds the size limit" or CPU errors (1102).** The account is on
Workers Free. The CMS needs Workers Paid.
- **Requests hang for 10 s, then 500.** A regression to a shared pool: the
Expand Down
14 changes: 14 additions & 0 deletions apps/cms/next.config.ts
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,20 @@ const nextConfig: NextConfig = {
output: 'standalone',
outputFileTracingRoot: path.join(dirname, '../..'),
serverExternalPackages: ['jose', 'pg', 'pg-cloudflare'],
// Nobody frames the CMS (lumen-payload-console design §6): sibling Workers
// on the same workers.dev site get the Lax session cookie, so a framed
// admin page could be clicked through from one of them.
async headers() {
return [
{
source: '/:path*',
headers: [
{ key: 'Content-Security-Policy', value: "frame-ancestors 'self'" },
{ key: 'X-Frame-Options', value: 'SAMEORIGIN' },
],
},
]
},
webpack: (webpackConfig) => {
webpackConfig.resolve.extensionAlias = {
'.cjs': ['.cts', '.cjs'],
Expand Down
1 change: 1 addition & 0 deletions apps/cms/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -29,6 +29,7 @@
},
"devDependencies": {
"@cloudflare/workers-types": "^4.20250508.0",
"@saas/contracts": "workspace:*",
"@types/node": "22.19.9",
"@types/pg": "8.20.0",
"@types/react": "19.2.14",
Expand Down
10 changes: 10 additions & 0 deletions apps/cms/src/app/(payload)/admin/importMap.js

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

9 changes: 9 additions & 0 deletions apps/cms/src/app/(site)/lumen/notifications/route.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
import { formDeps } from '@/lib/lumen/form-deps'
import { notificationsForm } from '@/lib/lumen/forms'

export const dynamic = 'force-dynamic'

// The Notifications page's form (lumen-payload-console design §4).
export function POST(request: Request): Promise<Response> {
return notificationsForm(request, formDeps)
}
9 changes: 9 additions & 0 deletions apps/cms/src/app/(site)/lumen/profile/route.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
import { formDeps } from '@/lib/lumen/form-deps'
import { profileForm } from '@/lib/lumen/forms'

export const dynamic = 'force-dynamic'

// The Profile page's form (lumen-payload-console design §4).
export function POST(request: Request): Promise<Response> {
return profileForm(request, formDeps)
}
39 changes: 39 additions & 0 deletions apps/cms/src/components/admin/account/AccountNav.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,39 @@
'use client'

import { Link, NavGroup } from '@payloadcms/ui'
import { usePathname } from 'next/navigation'

// The Account group in the admin's nav (design §4), styled as Payload's own
// links. The nav only renders for people who can use the admin.
const LINKS = [
{ href: '/admin/account', label: 'Profile' },
{ href: '/admin/account/security', label: 'Security activity' },
{ href: '/admin/organization', label: 'Organization' },
{ href: '/admin/organization/notifications', label: 'Notifications' },
]

export function AccountNav() {
const pathname = usePathname()
return (
<NavGroup label="Account">
{LINKS.map(({ href, label }) => {
const active = pathname === href
const inner = (
<>
{active ? <div className="nav__link-indicator" /> : null}
<span className="nav__link-label">{label}</span>
</>
)
return active ? (
<div key={href} className="nav__link" id={`nav-lumen-${label.toLowerCase().replace(/\s+/g, '-')}`}>
{inner}
</div>
) : (
<Link key={href} className="nav__link" href={href} prefetch={false} id={`nav-lumen-${label.toLowerCase().replace(/\s+/g, '-')}`}>
{inner}
</Link>
)
})}
</NavGroup>
)
}
Loading
Loading