Skip to content

feat(preview)!: live-preview tokens, minted and accepted - #787

Merged
Ardnived merged 12 commits into
mainfrom
claude/feat-live-preview-tokens
Sep 16, 2026
Merged

Ardnived merged 12 commits into
mainfrom
claude/feat-live-preview-tokens

Conversation

@Ardnived

@Ardnived Ardnived commented Sep 15, 2026 •

Copy link
Copy Markdown
Contributor

Summary

The preview credential becomes a short-lived Ed25519 token that this service mints and verifies. x-sahajcloud-preview-secret now carries that token instead of SAHAJCLOUD_PREVIEW_SECRET copied verbatim.

Scope grew on request: this was "the minter, inert". It now also changes what the draft gate accepts, because a token that nothing accepts unlocks nothing. The URL repoint and the retirement of the env var are in #788, which stacks on this.

Why not keep the shared secret

  • It leaked permanently. The value also rode in the panel's URL, where browser history, Referer, Sentry session replay and a Plausible script that posts location.href all read it. Neither Referrer-Policy nor a Sentry beforeSend stops that last one.
  • A public bundle cannot verify it. SahajAtlasWeb ships as a <sahaj-atlas> widget. Giving it the secret so it can check a token is giving everyone the ability to mint one.

So the CMS signs and the consumers verify. Ed25519, asymmetric: the private key never leaves this service, the public key is committed in each consumer, nothing is duplicated, rotation touches one platform.

The key is a JWK, not PKCS8

A PKCS8 private key cannot yield its own public half through Web Crypto, and this service needs both — it mints for the panel and verifies again when a consumer forwards one back. A JWK carries x beside d, so one variable gives both and they cannot drift. Two variables eventually would, silently, in a way indistinguishable from a forged token.

The verdict is resolved once, ahead of the readers

Verifying a signature is async. Three of the four readers are sync — validateClientQueryParamsHook, assertClientOriginAllowed, publicReadCacheHeaders — and making them async would ripple through a security path for no gain.

resolveLivePreviewHook runs first in the beforeOperation chain and stamps the answer on req.context. Verified against payload 3.86 that this is safe: collections/operations/find.js awaits buildBeforeOperation before executeAccess, and globals/operations/findOne.js does the same.

⚠ An unstamped request reads as no preview. Failing closed is the only safe default for a flag whose job is to unlock drafts.

What the token binds

{ aud, exp } — which site, when it dies. Not the path. Path binding breaks on WeMeditateWeb's /en/* redirect, on the atlas's in-app navigation, and on a slug renamed mid-edit, each a silent preview failure.

Test results

  • pnpm lint, pnpm typecheck, pnpm typecheck:tests — green
  • pnpm test:unit — 2041 passed
  • Integration: globals-client-reads, role-based-access, client-query-validation, client-origin-enforcement, pages-localize-status — green

globals-client-reads gains both halves of the gate: a valid token returns the draft, a forged one does not. Without the positive case, a change that simply refused every draft read would pass every other assertion while breaking live preview outright.

The specs that exercised the bypass now mint a real token and run the resolver, so they prove the composition rather than a header string.

⚠ Action needed

Live preview does not work from this PR alone — the builders still put secret= on a URL nothing reads. #788 repoints them. Preview points only at unreleased consumers, so nothing in use regresses.

Before merging #788, someone needs to run pnpm generate:preview-keypair and set the private half as LIVE_PREVIEW_SIGNING_KEY on Railway. Unset, the CMS runs normally and simply does not offer live preview.

🤖 Generated with Claude Code

Ardnived and others added 2 commits September 14, 2026 18:24
…777 made them cacheable

`createAccessConfig` constrains a client read of a draft-enabled entity to
`{ _status: { equals: 'published' } }` unless the request carries a valid preview
secret. That clause asked `collectionHasDrafts`, which resolved the slug through
`req.payload.collections[...]` — a map a global is not in. So it answered `false`
for every global, the clause never fired on one, and an ordinary client API key
plus `?draft=true` read unpublished copy out of all three translations globals
with no preview secret at all.

#777 raised the stakes. `/api/globals/<slug>` is now edge-cacheable, and
`matchCacheableRead` keys on the pathname while the middleware gates `no-store`
on the preview-secret *header*. So the same uncredentialed draft read came back
`public, max-age=600, s-maxage=600` and could sit at the Cloudflare edge for ten
minutes, replayed by `Vary: Authorization` to every request sharing that API key
— which, for WeMeditateWeb, is every visitor.

Two independent fixes, because the two layers answer different questions:

- `entityHasDrafts` checks `req.payload.config.globals` as well as collections,
  so the published-only clause fires on a global. This is the access fix.
- `isDraftRead` marks any read carrying a truthy `?draft=` as unstorable, whether
  or not a preview secret rides with it. A caller may be legitimately authorised
  for drafts and the response still must not enter a shared cache. Applied on
  both cache surfaces — the REST middleware and the in-handler decorator.

`draft=false`, `draft=0` and `draft=` stay cacheable: WeMeditateWeb passes
`draft: isPreview` unconditionally, so treating the parameter's presence as a
draft read would make the whole site uncacheable. An unrecognised value fails
closed.

Both halves were watched failing first — the integration cases returned the
unpublished string, and the cache cases returned `public, max-age=600`.

DEPLOYMENT.md records the recommended Cache Rule hardening: the rule already
excludes the preview-secret header, and should exclude `draft=true` too, so the
bypass does not rest on an origin header alone.

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
Groundwork for the cross-repo live-preview unification. Adds the credential
and nothing that consumes it yet, so this changes no behaviour.

`SAHAJCLOUD_PREVIEW_SECRET` on a preview URL has two problems that only get
worse as preview widens from one route to every route:

- **It leaks permanently.** A URL is read by browser history, `Referer`,
  Sentry's session replay, and — on WeMeditateWeb — an analytics script that
  posts `location.href`. A long-lived symmetric secret in that position stays
  valid forever.
- **A public bundle cannot verify it.** Giving SahajAtlasWeb the secret so it
  can check a token is giving everyone the ability to mint one.

So the CMS signs and the consumers verify. Ed25519, asymmetric: the private
key never leaves this service, the public key is committed in each consumer,
nothing is duplicated, and rotation touches one platform.

The token binds `{ aud, exp }` — which site, and when it dies. Deliberately
NOT the path: path binding breaks on WeMeditateWeb's `/en/*` redirect, on the
atlas's in-app navigation, and on a slug renamed mid-edit, each a silent
preview failure. With a 45-minute life, replay across pages of the same site
buys nothing that previewing the page directly would not.

`LIVE_PREVIEW_SIGNING_KEY` is optional. Unset, minting returns `null` and
callers fall back to an unavailable page — a fresh checkout, or a preview
deploy that never had the variable, should run without live preview rather
than fail to boot.

`verifyLivePreviewToken` lives beside the minter so the two halves of the
format cannot drift, and so this repo's specs prove a minted token verifies.
Each consumer carries its own copy of the check, since neither imports from
here; `tests/unit/live-preview-token.spec.ts` is the reference. It refuses a
wrong audience, an expired token, edited claims and a foreign signature, and
never reports which.

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
@railway-app

railway-app Bot commented Sep 15, 2026 •

Copy link
Copy Markdown

🚅 Deployed to the SahajCloud-pr-787 environment in sahajcloud

Service Status Web Updated
SahajCloud ✅ Success (View Logs) Web Sep 16, 2026 at 1:52 am UTC
1 service not affected by this PR
  • mailpit

Ardnived and others added 2 commits September 14, 2026 19:47
…ared secret

Folds the credential swap into the token work. `x-sahajcloud-preview-secret`
now carries a short-lived Ed25519 token this service issued, verified here,
rather than `SAHAJCLOUD_PREVIEW_SECRET` copied verbatim.

**The header name is unchanged on purpose.** The Cloudflare Cache Rule matches
on it and the CORS allowlist names it, and neither cares what the value means.
Only what counts as valid changed — so no infrastructure moves with this.

**Why.** The old value also rode in the panel's URL, where browser history,
`Referer`, Sentry session replay and an analytics script that posts
`location.href` all read it — a long-lived symmetric secret, permanently
exposed. And a public bundle like the atlas widget could never be given it to
verify with, because holding it means being able to mint it.

**The key is a JWK now, not PKCS8.** A PKCS8 private key cannot yield its own
public half through Web Crypto, and this service needs both: it mints tokens
for the panel and verifies them again when a consumer forwards one back. A JWK
carries `x` beside `d`, so one variable gives both and they cannot drift — two
variables eventually would, silently, in a way indistinguishable from a forged
token.

**The verdict is resolved once, ahead of the readers.** Verifying a signature
is async; three of the four readers are sync (`validateClientQueryParamsHook`,
`assertClientOriginAllowed`, `publicReadCacheHeaders`), and making them async
would ripple through a security path for no gain. `resolveLivePreviewHook` runs
first in the `beforeOperation` chain and stamps the answer on `req.context`.
That is safe because Payload awaits every `beforeOperation` before it resolves
access — verified in `collections/operations/find.js` and
`globals/operations/findOne.js`, both on 3.86.

An unstamped request reads as no preview. Failing closed is the only safe
default for a flag whose job is to unlock drafts.

The specs that exercised the bypass now mint a real token and run the resolver,
so they prove the composition rather than a header string. `globals-client-reads`
gains the other half of the gate: a valid token *does* return the draft, and a
forged one does not — without that, a change that refused every draft read
would pass every other case while breaking live preview outright.

`.env` carries a development signing key, the same posture as the dev secrets
beside it (#570 tracks that generally). Production sets its own on Railway.

⚠ Live preview stays broken until the URL repoint lands: the builders still put
`secret=` on a URL nothing reads. Preview points only at unreleased consumers,
so nothing in use regresses.

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
@railway-app
railway-app Bot temporarily deployed to sahajcloud / SahajCloud-pr-787 September 15, 2026 03:06 Destroyed
… unlock

`pages-localize-status` still set the retired shared secret on the header, so
the live-preview draft-unlock case asserted the published path instead — CI
caught it where the targeted local run did not, because the fix had landed on
the stacked branch rather than this one.

The signing key moves into `vitest.config.mts`, which overrides `.env` and is
the only place both lanes read. Fixed rather than generated per run: a rotating
key would make a signature failure look like flake.

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
@railway-app
railway-app Bot temporarily deployed to sahajcloud / SahajCloud-pr-787 September 15, 2026 03:21 Destroyed
@Ardnived Ardnived changed the title feat(preview): sign live-preview URLs with a short-lived Ed25519 token feat(preview)!: live-preview tokens, minted and accepted Sep 15, 2026
`RESOLVE_LIVE_PREVIEW` was a rename of `resolveLivePreviewHook` that existed
only to hold a docblock. The rationale belongs at the two registration sites,
where the ordering it explains is actually visible.

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
@railway-app
railway-app Bot temporarily deployed to sahajcloud / SahajCloud-pr-787 September 15, 2026 15:13 Destroyed
… not a site

`LivePreviewAudience` checked almost nothing. It named `wm-web` or
`sy-atlas`, and only the CONSUMER checked it — against a constant it
hardcoded — while this service, which is what actually unlocks drafts,
accepted either. So a token leaked from one surface could be replayed
straight at the API with the other key and unlock its drafts too.

The claim is now the API-client role, and `resolveLivePreviewHook` matches
it against `req.user.roles` on the authenticated key. That is a boundary,
because it is checked against something the request PROVES rather than
something a consumer asserts about itself.

`LivePreviewRole` derives from the generated `Client['roles']`, so a role
added or renamed upstream is a compile error here rather than a token
nobody can redeem — and there is one role vocabulary instead of a parallel
one shadowing it.

What it buys is modest and worth stating: the client key already scopes
WHICH collections are readable, so this does not widen or narrow that. It
stops one leaked token from removing the published-only filter on both
surfaces instead of one.

`globals-client-reads` gains the case that justifies the change — a valid,
unexpired, correctly signed token presented by a key that does not hold the
role it names, serving published content. Watched failing against a build
with the role check removed.

`createClientAuthenticatedRequest` grew a `roles` parameter: its stub
client had none, so every preview case through it would have been refused.

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
@railway-app
railway-app Bot temporarily deployed to sahajcloud / SahajCloud-pr-787 September 15, 2026 15:29 Destroyed
…oy script

Four defects an adversarial review found, all of which would have shipped.

**1. Every save reloaded the preview iframe.** Ed25519 is deterministic, so
claims are a token's only variation — and `exp = now + TTL` differs between
any two mints a second apart. Payload compares the live-preview URL by value
and reassigns the iframe's `src` when it changes, and the URL re-resolves on
every save. With `pages` autosaving every 60s that is a full reload each
minute: scroll lost, `appIsReady` reset, the postMessage stream stalled until
the consumer re-announces `ready` — the opposite of live.

The expiry is bucketed now, so consecutive mints inside a window are
byte-identical and the URL is stable. A token lives between one and two TTLs,
and the spec pins both ends so bucketing cannot quietly become a long-lived
credential.

**2. `publicReadCacheHeaders` failed OPEN on five endpoints.** It asked for the
validated verdict, which `resolveLivePreviewHook` stamps on `req.context` —
but every one of those endpoints reads through `asTrustedReq`, which clones
the context so `SKIP_VALIDATION` cannot leak back. The stamp landed on the
clone, so a preview read computed `preview: false` and a draft-bearing
response was stamped `public, s-maxage=…` with `Vary: Authorization`, where
the edge could replay it to anyone sharing the API key.

It reads header presence now, like the Edge middleware already does. Weaker
than validity and deliberately so: presence cannot miss, and the cost of a
bogus header is a colder cache rather than a leaked draft. The access layer
still decides what is returned.

**3. `setup-railway.sh` aborted.** It still demanded
`SAHAJCLOUD_PREVIEW_SECRET`, which no longer exists in the schema, and never
set `LIVE_PREVIEW_SIGNING_KEY` — the one variable the cutover actually needs.
`RAILWAY_RUNBOOK.md` was updated; the script that does the work was not.

**4. The key format was documented wrong everywhere an operator looks.** Three
places said PKCS8 while the code exports and imports a JWK, and the retired
secret's description was left orphaned above the new variable in
`.env.example`, reading as its documentation.

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
@railway-app
railway-app Bot temporarily deployed to sahajcloud / SahajCloud-pr-787 September 15, 2026 15:41 Destroyed
…d flag

A review flagged that `usagePlugin({ enabled: !isE2ETest })` would unregister
`resolveLivePreviewHook` under E2E, leaving every verdict false and live
preview silently serving published content.

The coupling is real. The defect is not: a repo-wide search finds `E2E_TEST`
only at its own definition in payload.config.ts — no workflow, script,
playwright config or spec sets it, and the smoke lane runs against a deployed
Railway preview that does not either. So `isE2ETest` is always false.

Recorded at the registration site rather than restructured, because a reader
of `usagePlugin({ enabled })` would otherwise never guess it gates draft
access. If E2E ever does set the variable, the resolver needs its own
registration rather than a home inside a metering plugin.

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
@railway-app
railway-app Bot temporarily deployed to sahajcloud / SahajCloud-pr-787 September 15, 2026 17:35 Destroyed
…iew-tokens

# Conflicts:
#	docs/rules/access.md
#	src/plugins/cache/cacheHeaders.ts
#	tests/int/globals-client-reads.int.spec.ts
@railway-app
railway-app Bot temporarily deployed to sahajcloud / SahajCloud-pr-787 September 15, 2026 17:41 Destroyed
Comment thread src/lib/livePreview/token.ts Resolved
Comment thread src/lib/livePreview/token.ts Resolved
Comment thread src/lib/livePreview/token.ts Resolved
Comment thread src/lib/utilities/previewSecret.ts Resolved
Comment thread src/lib/utilities/previewSecret.ts Resolved
Comment thread src/lib/utilities/previewSecret.ts Resolved
Comment thread src/plugins/cache/cacheHeaders.ts Resolved
The token module hand-rolled Ed25519 framing — base64url helpers, manual JWK
surgery for the public half, its own two-part wire format and claim parsing —
in a repo that already reached the opposite conclusion for HMAC tokens in
`lib/utilities/signedToken.ts`. `jose` is a pinned dependency there and Payload
signs its own auth JWTs with it, so this is a standard EdDSA JWS now: the
algorithm is pinned on verify, `exp` is the library's check against an
injectable clock, and `alg: none` is refused rather than hand-checked.

The role claim goes with it. The client API key on the request already decides
which collections are readable, so matching a role only narrowed which surface
a leaked token unlocked drafts on, never what it could reach.

`resolveLivePreviewHook` runs on every metered collection and global operation,
so it is no longer `async`: with no header it returns before allocating a
promise or touching `req.context`. An unstamped request already read as "no
preview", so the skipped path needs no verdict. `hasValidPreviewSecret` becomes
`isLivePreviewRequest` — it checks no secret, and never did.

BREAKING CHANGE: the wire format is a three-part compact JWS, and the token no
longer carries a role. Both consumers must verify `header.payload` under
`alg: EdDSA` instead of a bare payload, and drop their own role check.

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
@railway-app
railway-app Bot temporarily deployed to sahajcloud / SahajCloud-pr-787 September 16, 2026 00:19 Destroyed
Ardnived added a commit that referenced this pull request Sep 16, 2026
… composers directly

Follows #787 through the repoint.

**The role claim is gone**, per the review: the client API key already scopes
which collections are readable, so the claim only narrowed which SURFACE a
leaked token could unlock drafts on, never what it could reach. Removed from
`livePreviewUrl` and from all nine `livePreview.url` call sites.

**`buildPath: buildEventWebPath`**, not a lambda that forwards the same two
arguments. Both occurrences — Events and Regions — take the composer directly.
Pages keeps its lambda: it branches on `platform` before composing, so there is
a real function there rather than a wrapper.

One spec pinned the two-part wire format and now pins a compact JWS. The others
needed no change, which is the useful signal: they assert the URL shape and the
presence of a credential, not its internals.

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
Picks up the corrected .github/workflows/workflow-state.yml. This branch was
cut before the legacy job was removed, so its copy still names the deleted
state-machine.yml and GitHub rejects the whole file on every
pull_request_review event.
@railway-app
railway-app Bot temporarily deployed to sahajcloud / SahajCloud-pr-787 September 16, 2026 01:49 Destroyed
@Ardnived
Ardnived merged commit 39a0529 into main Sep 16, 2026
5 checks passed
@Ardnived
Ardnived deleted the claude/feat-live-preview-tokens branch September 16, 2026 04:52
@sydevs-bot sydevs-bot moved this from Revising to Done in SYDevelopers Technical Roadmap Sep 16, 2026
Ardnived added a commit that referenced this pull request Sep 16, 2026
…ecret is gone (#788)

* fix(access)!: a client key reads draft globals with ?draft=true, and #777 made them cacheable

`createAccessConfig` constrains a client read of a draft-enabled entity to
`{ _status: { equals: 'published' } }` unless the request carries a valid preview
secret. That clause asked `collectionHasDrafts`, which resolved the slug through
`req.payload.collections[...]` — a map a global is not in. So it answered `false`
for every global, the clause never fired on one, and an ordinary client API key
plus `?draft=true` read unpublished copy out of all three translations globals
with no preview secret at all.

#777 raised the stakes. `/api/globals/<slug>` is now edge-cacheable, and
`matchCacheableRead` keys on the pathname while the middleware gates `no-store`
on the preview-secret *header*. So the same uncredentialed draft read came back
`public, max-age=600, s-maxage=600` and could sit at the Cloudflare edge for ten
minutes, replayed by `Vary: Authorization` to every request sharing that API key
— which, for WeMeditateWeb, is every visitor.

Two independent fixes, because the two layers answer different questions:

- `entityHasDrafts` checks `req.payload.config.globals` as well as collections,
  so the published-only clause fires on a global. This is the access fix.
- `isDraftRead` marks any read carrying a truthy `?draft=` as unstorable, whether
  or not a preview secret rides with it. A caller may be legitimately authorised
  for drafts and the response still must not enter a shared cache. Applied on
  both cache surfaces — the REST middleware and the in-handler decorator.

`draft=false`, `draft=0` and `draft=` stay cacheable: WeMeditateWeb passes
`draft: isPreview` unconditionally, so treating the parameter's presence as a
draft read would make the whole site uncacheable. An unrecognised value fails
closed.

Both halves were watched failing first — the integration cases returned the
unpublished string, and the cache cases returned `public, max-age=600`.

DEPLOYMENT.md records the recommended Cache Rule hardening: the rule already
excludes the preview-secret header, and should exclude `draft=true` too, so the
bypass does not rest on an origin header alone.

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>

* fix(pages)!: webUrl put a tag segment in a path no site serves

`Pages.buildPath` emitted `[locale, tag, slug]`, so a page tagged `wisdom`
published `webUrl: https://…/wisdom/my-article`. Nothing serves that path.

- **WeMeditateWeb** routes a page at exactly one segment. Its builder is
  `ROUTE_BUILDERS.pages = '/' + slug`, its matcher is `^/([^/]+)/?$`, and its
  own spec pins that a nested path does not match. Its sitemap publishes the
  same one-segment shape.
- **The legacy Rails site** does not serve it either. Checked against
  production on 2026-09-15: `/wisdom` is a 404, articles live at
  `/articles/<slug>`, and `wisdom` appears only as `/inspiration/wisdom`, a
  category index.

So a tagged page published a canonical that 404s, while an untagged page
worked — which is why it survived: the failure is invisible unless the page
happens to carry a tag. `tags` is optional, so both shapes are common.

The path is now `[locale, slug]`. The two specs that pinned the tag segment
asserted the defect, so they invert here; both were watched failing first.

`livePreview.url` in the same file moves to `serverEnv`, so an unset base
fails at boot instead of interpolating `undefined`. The `web:` base stays on
raw `process.env` deliberately — it runs per read, and that late bind is what
lets a spec stub it with `vi.stubEnv`; it already guards to `null` rather than
producing a broken URL.

Found while planning the cross-repo live-preview unification: the same
`buildPath` is what the live-preview panel URL will be composed from, so the
panel would have landed on those same 404s.

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>

* feat(preview): sign live-preview URLs with a short-lived Ed25519 token

Groundwork for the cross-repo live-preview unification. Adds the credential
and nothing that consumes it yet, so this changes no behaviour.

`SAHAJCLOUD_PREVIEW_SECRET` on a preview URL has two problems that only get
worse as preview widens from one route to every route:

- **It leaks permanently.** A URL is read by browser history, `Referer`,
  Sentry's session replay, and — on WeMeditateWeb — an analytics script that
  posts `location.href`. A long-lived symmetric secret in that position stays
  valid forever.
- **A public bundle cannot verify it.** Giving SahajAtlasWeb the secret so it
  can check a token is giving everyone the ability to mint one.

So the CMS signs and the consumers verify. Ed25519, asymmetric: the private
key never leaves this service, the public key is committed in each consumer,
nothing is duplicated, and rotation touches one platform.

The token binds `{ aud, exp }` — which site, and when it dies. Deliberately
NOT the path: path binding breaks on WeMeditateWeb's `/en/*` redirect, on the
atlas's in-app navigation, and on a slug renamed mid-edit, each a silent
preview failure. With a 45-minute life, replay across pages of the same site
buys nothing that previewing the page directly would not.

`LIVE_PREVIEW_SIGNING_KEY` is optional. Unset, minting returns `null` and
callers fall back to an unavailable page — a fresh checkout, or a preview
deploy that never had the variable, should run without live preview rather
than fail to boot.

`verifyLivePreviewToken` lives beside the minter so the two halves of the
format cannot drift, and so this repo's specs prove a minted token verifies.
Each consumer carries its own copy of the check, since neither imports from
here; `tests/unit/live-preview-token.spec.ts` is the reference. It refuses a
wrong audience, an expired token, edited claims and a foreign signature, and
never reports which.

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>

* feat(preview): one path composer per collection, and a page for a document with no URL

More groundwork for the live-preview unification. Still no change to any
`livePreview.url`, so the panel behaves exactly as it does today.

**One composer, two callers.** `webPath` and the live-preview URL are the same
path, and were written separately. They disagreed: a tag segment was published
that no site serves. `buildPageWebPath` and `buildEventWebPath` are now the one
answer each, colocated with their collection and consumed by both
`publicUrlFields` and — once the repoint lands — `admin.livePreview.url`.

The locale is a parameter rather than read from `req`. `publicUrlFields` passes
`req.locale`; `livePreview.url` receives its own `locale.code`. They are not
reliably the same value, and a composer that reached for `req.locale` itself
would silently render English in the panel.

`buildEventWebPath` keeps the `relationId` from `@/plugins/access/documentManagers`
that Events.ts already used, not the one in `@/lib/utilities`. The two are not
equivalent — only the first resolves a string id — so importing the tidier
path would have quietly changed which events resolve a URL.

**A page instead of `null`.** Returning `null` from `livePreview.url` does more
than blank the panel: `setLivePreviewURL` calls `setIsLivePreviewing(false)`,
and an effect then persists `editViewType: 'default'` as that editor's
preference, so live preview is off next time they open any document of that
collection. On a first render a falsy URL hides the toggle entirely, with no
explanation. `pages` autosaves every 60s and the URL re-resolves on each save,
so an editor clearing the slug to retype it can lose the panel and their
preference mid-edit.

`/live-preview-unavailable` explains the specific problem instead. Hosted here
because the CSP `frame-src` already allows `'self'`, and because a consumer
site should not carry a route whose only job is to explain a CMS-side problem.

Verified against payload 3.86 while writing this: `url()` is never called for
an unsaved document (`handleLivePreview` guards `operation !== 'create'`), a
`null` return leaves the URL undefined, and a *throwing* `url()` is swallowed
into a logger call — so a composer must never throw, only return null.

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>

* feat(preview)!: the draft gate accepts a live-preview token, not a shared secret

Folds the credential swap into the token work. `x-sahajcloud-preview-secret`
now carries a short-lived Ed25519 token this service issued, verified here,
rather than `SAHAJCLOUD_PREVIEW_SECRET` copied verbatim.

**The header name is unchanged on purpose.** The Cloudflare Cache Rule matches
on it and the CORS allowlist names it, and neither cares what the value means.
Only what counts as valid changed — so no infrastructure moves with this.

**Why.** The old value also rode in the panel's URL, where browser history,
`Referer`, Sentry session replay and an analytics script that posts
`location.href` all read it — a long-lived symmetric secret, permanently
exposed. And a public bundle like the atlas widget could never be given it to
verify with, because holding it means being able to mint it.

**The key is a JWK now, not PKCS8.** A PKCS8 private key cannot yield its own
public half through Web Crypto, and this service needs both: it mints tokens
for the panel and verifies them again when a consumer forwards one back. A JWK
carries `x` beside `d`, so one variable gives both and they cannot drift — two
variables eventually would, silently, in a way indistinguishable from a forged
token.

**The verdict is resolved once, ahead of the readers.** Verifying a signature
is async; three of the four readers are sync (`validateClientQueryParamsHook`,
`assertClientOriginAllowed`, `publicReadCacheHeaders`), and making them async
would ripple through a security path for no gain. `resolveLivePreviewHook` runs
first in the `beforeOperation` chain and stamps the answer on `req.context`.
That is safe because Payload awaits every `beforeOperation` before it resolves
access — verified in `collections/operations/find.js` and
`globals/operations/findOne.js`, both on 3.86.

An unstamped request reads as no preview. Failing closed is the only safe
default for a flag whose job is to unlock drafts.

The specs that exercised the bypass now mint a real token and run the resolver,
so they prove the composition rather than a header string. `globals-client-reads`
gains the other half of the gate: a valid token *does* return the draft, and a
forged one does not — without that, a change that refused every draft read
would pass every other case while breaking live preview outright.

`.env` carries a development signing key, the same posture as the dev secrets
beside it (#570 tracks that generally). Production sets its own on Railway.

⚠ Live preview stays broken until the URL repoint lands: the builders still put
`secret=` on a URL nothing reads. Preview points only at unreleased consumers,
so nothing in use regresses.

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>

* feat(preview)!: point every panel at the real page, and retire the shared secret

Completes the hard cutover. `SAHAJCLOUD_PREVIEW_SECRET` is gone; every
`livePreview.url` now points at the page the document will be published at,
with a short-lived token on it.

| Collection | Was | Now |
| --- | --- | --- |
| Pages | `/{locale}/preview?collection&id&secret` | its own slug path |
| Meditations | `/{locale}/preview/embed?…` | `meditations/{id}/embed` |
| Lectures | *(no panel at all)* | `lectures/{id}` |
| Events | `/preview?collection&id&secret&locale` | its region path + id |
| Regions | same | its own map path |
| wm-web-config | `/preview?collection=pages&id={homePage}` | the site root |
| Both translations globals | a view, with no credential | the same view, with one |
| EventSubmissions | `/preview?collection&id&secret` | `/preview`, with a token |

Each path comes from the composer its own `webPath` publishes, so the panel
and the published URL cannot disagree.

**EventSubmissions keeps its route, and is the only one that does.** A proposal
has no page: `event-submissions` is create-only for API clients and a
new-event proposal has no Event id, so the widget cannot fetch it back — the
render-ready shape rides postMessage in `previewEvent`. Retiring that needs the
mechanism replaced, which #723's `user-submissions` unification owns.

**Lectures gained a panel it never had**, while WeMeditateWeb has carried a
`LecturePreview` component the whole time, reachable by nothing.

**`wm-web-config` stopped previewing a document.** It resolved `homePage` and
previewed that page by id — a data-dependent URL, which #708 established
re-resolves on save and clobbers a repointed panel. The root renders the home
page anyway.

Both translations globals carry the credential again. #773 had to strip it:
`/preview` was the only route that read *and* scrubbed one, so a secret sent
anywhere else sat in the panel's URL all session. Every route reads and scrubs
a token now, and it expires on its own. That is what #776 was filed for.

⚠ **The trailing slash on a locale path is load-bearing.** A tab's relative
target (`map`) resolves against the base: under `/fr/` it becomes `/fr/map`,
under `/fr` it hoists to `/map` and the edited locale is lost silently.

Three specs asserted the retired shape and now assert the new one, including
that `secret` and `collection` are absent so a revert is loud.
`atlas-collections` was rewritten rather than retargeted: it used to call
`url()` with a bare `{ data: { id: 42 } }`, and composing a path reads the
region tree, so it needs a real `req` and real rows. A spec that kept the old
call would resolve no path and silently assert the "unavailable" page.

The test signing key moved to `vitest.config.mts`, which overrides `.env` and
so is the only place both lanes read.

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>

* test(preview): mint a real token in the specs that exercise the draft unlock

`pages-localize-status` still set the retired shared secret on the header, so
the live-preview draft-unlock case asserted the published path instead — CI
caught it where the targeted local run did not, because the fix had landed on
the stacked branch rather than this one.

The signing key moves into `vitest.config.mts`, which overrides `.env` and is
the only place both lanes read. Fixed rather than generated per run: a rotating
key would make a signature failure look like flake.

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>

* refactor(preview): register the resolver directly, not through an alias

`RESOLVE_LIVE_PREVIEW` was a rename of `resolveLivePreviewHook` that existed
only to hold a docblock. The rationale belongs at the two registration sites,
where the ordering it explains is actually visible.

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>

* refactor(preview)!: a token names the client role that may redeem it, not a site

`LivePreviewAudience` checked almost nothing. It named `wm-web` or
`sy-atlas`, and only the CONSUMER checked it — against a constant it
hardcoded — while this service, which is what actually unlocks drafts,
accepted either. So a token leaked from one surface could be replayed
straight at the API with the other key and unlock its drafts too.

The claim is now the API-client role, and `resolveLivePreviewHook` matches
it against `req.user.roles` on the authenticated key. That is a boundary,
because it is checked against something the request PROVES rather than
something a consumer asserts about itself.

`LivePreviewRole` derives from the generated `Client['roles']`, so a role
added or renamed upstream is a compile error here rather than a token
nobody can redeem — and there is one role vocabulary instead of a parallel
one shadowing it.

What it buys is modest and worth stating: the client key already scopes
WHICH collections are readable, so this does not widen or narrow that. It
stops one leaked token from removing the published-only filter on both
surfaces instead of one.

`globals-client-reads` gains the case that justifies the change — a valid,
unexpired, correctly signed token presented by a key that does not hold the
role it names, serving published content. Watched failing against a build
with the role check removed.

`createClientAuthenticatedRequest` grew a `roles` parameter: its stub
client had none, so every preview case through it would have been refused.

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>

* fix(preview): stable tokens, header-presence cache gate, and the deploy script

Four defects an adversarial review found, all of which would have shipped.

**1. Every save reloaded the preview iframe.** Ed25519 is deterministic, so
claims are a token's only variation — and `exp = now + TTL` differs between
any two mints a second apart. Payload compares the live-preview URL by value
and reassigns the iframe's `src` when it changes, and the URL re-resolves on
every save. With `pages` autosaving every 60s that is a full reload each
minute: scroll lost, `appIsReady` reset, the postMessage stream stalled until
the consumer re-announces `ready` — the opposite of live.

The expiry is bucketed now, so consecutive mints inside a window are
byte-identical and the URL is stable. A token lives between one and two TTLs,
and the spec pins both ends so bucketing cannot quietly become a long-lived
credential.

**2. `publicReadCacheHeaders` failed OPEN on five endpoints.** It asked for the
validated verdict, which `resolveLivePreviewHook` stamps on `req.context` —
but every one of those endpoints reads through `asTrustedReq`, which clones
the context so `SKIP_VALIDATION` cannot leak back. The stamp landed on the
clone, so a preview read computed `preview: false` and a draft-bearing
response was stamped `public, s-maxage=…` with `Vary: Authorization`, where
the edge could replay it to anyone sharing the API key.

It reads header presence now, like the Edge middleware already does. Weaker
than validity and deliberately so: presence cannot miss, and the cost of a
bogus header is a colder cache rather than a leaked draft. The access layer
still decides what is returned.

**3. `setup-railway.sh` aborted.** It still demanded
`SAHAJCLOUD_PREVIEW_SECRET`, which no longer exists in the schema, and never
set `LIVE_PREVIEW_SIGNING_KEY` — the one variable the cutover actually needs.
`RAILWAY_RUNBOOK.md` was updated; the script that does the work was not.

**4. The key format was documented wrong everywhere an operator looks.** Three
places said PKCS8 while the code exports and imports a JWK, and the retired
secret's description was left orphaned above the new variable in
`.env.example`, reading as its documentation.

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>

* refactor(preview): call sites name the client role, following #787

* fix(preview): locale in the path, the config scope, and a same-origin fallback

Adversarial-review findings specific to the repoint.

**The locale never reached WeMeditate Web.** Meditations and Lectures put it
in `?locale=`, and that site derives its locale from the path and reads no
such parameter (`pages/+onBeforeRoute.ts`). A translator editing Czech saw
English, silently. Meditations was a regression — its old URL had the locale
in the path, and switching from `data.locale` to the `locale` argument moved
the value into a parameter nothing reads, so no locale arrived at all.

`wmWebLocalePath` puts it back in the path and omits it for English, which
301s to the bare path. The atlas keeps `?locale=` and is correct to: it reads
the parameter through i18next's `lookupQuerystring`.

**`wm-web-config` sent no scope**, so the consumer fell back to "the route's
own primary document" and read drafts for the home page rather than the config
global. It is a declared scope in WeMeditateWeb's closed set with no emitter.

**`/live-preview-unavailable` is root-relative now.** Built from
`SAHAJCLOUD_URL`, it was cross-origin on a Railway PR preview — those inherit
the shared production value — so the CSP refused the iframe. And a preview
environment has no signing key, so EVERY panel resolves there: the page that
exists to prevent a blank panel would have produced one on every PR. Payload
resolves a relative URL against the admin window, which is 'self' by
construction. Its `reason` lookup also guards the prototype chain, it is
noindex, and its no-key copy no longer names an internal variable to an
unauthenticated reader.

**New: `wm-web-live-preview.int.spec.ts`.** Nothing pinned these four URLs at
all — the atlas collections and the translations globals were covered, so the
repoint looked well tested while the two defects above sat in the gap. Watched
failing against the old shape.

`page-web-path`'s "never emits a tag segment" asserted `not.toContain('/')` on
an English path, which the function cannot fail: it takes no tag, and a
non-default locale legitimately contains a slash. It counts segments now.

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>

* fix(config): SAHAJATLAS_URL pointed at the legacy service, where /preview 404s

`setup-railway.sh` set `SAHAJATLAS_URL=https://atlas.sydevelopers.com`, and
production carries that value — visible in the admin's own CSP `frame-src`
header, which `next.config.mjs` bakes from it.

That host is the LEGACY atlas. The replacement is `sahajatlas.com`. Checked
both directly on 2026-09-15:

    atlas.sydevelopers.com/preview  → 404
    sahajatlas.com/preview          → 200

So Events, Regions and EventSubmissions live preview has been pointing at a
service that never served the route it asks for. Atlas live preview does not
work in production today, and has not.

Worth stating plainly because it inverts a concern raised in review: repointing
those three at real paths cannot regress a working feature, because there is no
working feature to regress. It also means the fix is a Railway variable, not
code — this commit corrects the provisioning script and the docs, and whoever
deploys still has to change the value on the service.

One variable, four consumers: the preview target, the CSP `frame-src`, the
`csrf` allowlist, and the admin's own `AtlasMapView` iframe. All four want the
replacement.

Same shape as #783, where `WEMEDITATE_WEB_URL` was found pointing at a
workers.dev host inside published canonical URLs.

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>

* docs(preview): record that the resolver rides on usagePlugin's enabled flag

A review flagged that `usagePlugin({ enabled: !isE2ETest })` would unregister
`resolveLivePreviewHook` under E2E, leaving every verdict false and live
preview silently serving published content.

The coupling is real. The defect is not: a repo-wide search finds `E2E_TEST`
only at its own definition in payload.config.ts — no workflow, script,
playwright config or spec sets it, and the smoke lane runs against a deployed
Railway preview that does not either. So `isE2ETest` is always false.

Recorded at the registration site rather than restructured, because a reader
of `usagePlugin({ enabled })` would otherwise never guess it gates draft
access. If E2E ever does set the variable, the resolver needs its own
registration rather than a home inside a metering plugin.

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>

* refactor(preview)!: jose signs the token, and it carries only an expiry

The token module hand-rolled Ed25519 framing — base64url helpers, manual JWK
surgery for the public half, its own two-part wire format and claim parsing —
in a repo that already reached the opposite conclusion for HMAC tokens in
`lib/utilities/signedToken.ts`. `jose` is a pinned dependency there and Payload
signs its own auth JWTs with it, so this is a standard EdDSA JWS now: the
algorithm is pinned on verify, `exp` is the library's check against an
injectable clock, and `alg: none` is refused rather than hand-checked.

The role claim goes with it. The client API key on the request already decides
which collections are readable, so matching a role only narrowed which surface
a leaked token unlocked drafts on, never what it could reach.

`resolveLivePreviewHook` runs on every metered collection and global operation,
so it is no longer `async`: with no header it returns before allocating a
promise or touching `req.context`. An unstamped request already read as "no
preview", so the skipped path needs no verdict. `hasValidPreviewSecret` becomes
`isLivePreviewRequest` — it checks no secret, and never did.

BREAKING CHANGE: the wire format is a three-part compact JWS, and the token no
longer carries a role. Both consumers must verify `header.payload` under
`alg: EdDSA` instead of a bare payload, and drop their own role check.

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>

* refactor(preview): drop the role from every URL builder, and pass the composers directly

Follows #787 through the repoint.

**The role claim is gone**, per the review: the client API key already scopes
which collections are readable, so the claim only narrowed which SURFACE a
leaked token could unlock drafts on, never what it could reach. Removed from
`livePreviewUrl` and from all nine `livePreview.url` call sites.

**`buildPath: buildEventWebPath`**, not a lambda that forwards the same two
arguments. Both occurrences — Events and Regions — take the composer directly.
Pages keeps its lambda: it branches on `platform` before composing, so there is
a real function there rather than a wrapper.

One spec pinned the two-part wire format and now pins a compact JWS. The others
needed no change, which is the useful signal: they assert the URL shape and the
presence of a credential, not its internals.

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>

---------

Co-authored-by: Claude Opus 5 (1M context) <[email protected]>
sydevs-bot pushed a commit that referenced this pull request Sep 16, 2026
`LIVE_PREVIEW_SIGNING_KEY` is declared twice in the server env schema, so
`tsc` refuses the file with TS1117 and every check after lint stops. The
duplicate is on `main`: #787 and #788 each added the same block, and a
squash merge of the second produced no conflict with the first. CI runs
only on pull requests here, so nothing typechecked `main` after the second
landed — this PR's merge ref is where the error first appears.

Both copies are byte-identical, docblock included, so the fix is to keep
one. Merging `main` in is what brings the defect into reach: the branch's
own copy of the file still carried the `SAHAJCLOUD_PREVIEW_SECRET` the two
preview PRs replaced.

`main` stays broken until this merges or another PR carries the same
removal.

Co-Authored-By: Claude Opus 5 <[email protected]>
Claude-Session: https://claude.ai/code/session_01KLoFETxwioFUddzP4kssBE
sydevs-bot pushed a commit that referenced this pull request Sep 18, 2026
The header retold #787 in six lines that the ticket, the PR body and the
commit already carry. What a reader cannot re-derive is the concatenation
rule and the tracked-files scope, so those stay and the story goes.

The #787/#810 breadcrumb stays too — docs/rules/code-comments.md keeps
those whatever else is cut.

Refs #810

Co-authored-by: Claude Opus 5 <[email protected]>
github-merge-queue Bot pushed a commit that referenced this pull request Sep 18, 2026
)

* fix(docs): resolve the conflict block in the access rule

`docs/rules/access.md` carried a raw, unresolved conflict block from #787.
Markdown is the one place a marker is silent: the same lines in a `.ts` file
are a syntax error both `pnpm lint` and `pnpm typecheck` reject, and in
`.json`, `.mts` or `.yml` they break a parser. Here they rendered as ordinary
text, and no lint covers `docs/`, so the block survived four merges. #801 and
#803 each edited prose inside it without seeing it.

The file is a `docs/rules/` rule, so it loads into every agent session that
reads `src/plugins/access/` — both halves at once, contradicting each other.

Neither half was wholly current, so the resolution is a mix.

The client-grant paragraph takes the `origin/main` text: both
`wemeditate-web` and `sahaj-atlas` may create `user-submissions`, create only.
`config/roles.ts:95,122` grants exactly that and nothing else. The `HEAD` text
named `wemeditate-web` alone and cited form submissions, a collection #801
deleted.

The warning paragraph takes the `HEAD` text, which differs from its twin only
in the final clause. "with no live-preview credential at all" is correct;
"with no preview secret" names the shared secret #788 deleted. A legitimate
draft read now carries a minted Ed25519 token, and `previewSecret.ts` says so
in the file: the header name outlived the value it used to carry.

Refs #810

Co-authored-by: Claude Opus 5 <[email protected]>

* test(docs): fail when a conflict marker lands anywhere tracked

Nothing in the repo grepped for conflict markers, which is why the block in
`docs/rules/access.md` survived four merges. A unit spec closes that, and runs
in both places that matter: `pnpm test:unit` is the lean gate's fast lane, and
`pnpm test` runs it in CI.

It is a unit spec rather than a line in `.claude/skills/pr-prep/check.sh`
deliberately. `.claude/` is a Claude Code Protected Path, so an unattended run
cannot write there — the write is prompted rather than refused, and the session
stalls until its lease expires.

The scan shells to `git grep`, for scope and for cost. Tracked files are what
can land on `main`, and git scans them in ~40ms where reading 76MB of tracked
bytes into JS would cost more than the rest of the lane.

Two traps are handled in the spec. The patterns are built by concatenation, so
the file cannot match itself. And a second test greps a scratch block through
the same pattern and the same command, because a pattern typo, a `git grep`
that cannot see the tree, and an exit code read the wrong way all produce the
same green as a clean tree does.

Proven by reintroducing a marker in a tracked file and watching the lane go
red.

Refs #810

Co-authored-by: Claude Opus 5 <[email protected]>

* refactor(tests): simplify the conflict-marker guard per /simplify pass

The three marker tokens are now named constants the pattern and the fixture
both build from, so the second test visibly shares the definition it is there
to prove. `grep` closed over the one pattern it was ever called with, its
two-valued argv fragment became a `noIndex` flag, and the `maxBuffer` knob went
— nothing it guarded was reachable.

The temp directory the non-vacuity test writes is now removed in
`onTestFinished`. Every lane run had been leaving one behind.

Cut the docstring roughly in half. One claim in it was also false: reading the
tracked tree into JS measures ~130ms against a 27s lane, not "more than the
rest of the unit lane". A checkable number that is wrong by two orders of
magnitude costs more than it buys, so the comparison is gone rather than
restated.

Refs #810

Co-authored-by: Claude Opus 5 <[email protected]>

* fix(tests): close two ways the conflict guard could go quiet

Both found by an adversarial review pass and reproduced before fixing.

`-I` skipped whatever git calls binary, and that includes a plain text file
marked `-diff` in `.gitattributes`. A scratch repo with `*.lock -diff` and a
real conflict block in `deps.lock` exited 1 with no output, so the guard went
green with the block committed. Without `-I` the same tree reports
`Binary file deps.lock matches`, which is a non-empty row and fails the
assertion. A guard should name a media file loudly rather than miss a real
block quietly, and the tree has no binary match today.

The fixture also proved only the pattern, not the scan. `--no-index` bypasses
index enumeration, the pathspec and `.gitattributes` — every structural way the
tracked scan can come back empty — so a sparse checkout, or the `-diff` case
above, left both tests green. It is now a real repository with the file really
tracked, which exercises the same path the tree test takes and lets the
`noIndex` branch go.

`grep.column` is pinned off. A contributor who sets it globally got
`sample.md:1:1:…` and failed the exact-array assertion on a clean tree.

A spawn that never ran reported "exited null". It now says git may not be on
PATH.

Refs #810

Co-authored-by: Claude Opus 5 <[email protected]>

* fix(tests): cut the guard docstring narration

The header retold #787 in six lines that the ticket, the PR body and the
commit already carry. What a reader cannot re-derive is the concatenation
rule and the tracked-files scope, so those stay and the story goes.

The #787/#810 breadcrumb stays too — docs/rules/code-comments.md keeps
those whatever else is cut.

Refs #810

Co-authored-by: Claude Opus 5 <[email protected]>

---------

Co-authored-by: Claude <[email protected]>

This branch was successfully deployed

No deployments
sahajcloud / SahajCloud-pr-787 — 197a1b1b Deployed Sep 16, 2026 by railway-app[bot]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

Development

Successfully merging this pull request may close these issues.

1 participant