Skip to content

feat(preview)!: render drafts on any route, and delete the preview routes - #99

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

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

Conversation

@Ardnived

@Ardnived Ardnived commented Sep 15, 2026 •

Copy link
Copy Markdown
Contributor

Summary

Preview is no longer a place. Any page renders drafts when the URL carries a valid token from SahajCloud, so pages/preview/(full) and pages/preview/embed are gone — and with them a second renderer that had to be kept approximately equal to the real one, and never quite was.

Pairs with sydevs/SahajCloud#787 and #788, which mint the token and repoint every panel.

The credential

SahajCloud signs a short-lived Ed25519 token; this verifies it with a public key committed in .env.production. The key cannot mint, so publishing it costs nothing — and it is what lets this site check a token without holding a shared secret that would have to be rotated in lockstep with the CMS. Unset, live preview is unavailable and every request renders published content.

Verification is the whole gate. A forged or expired token opens no session, so an invalid value renders the published page with a 200, indistinguishable from an ordinary request.

The token reaches the fetchers; only the verdict reaches the browser. loadLivePreview returns a session carrying the credential; toClientState strips it before passToClient serialises anything into the page. There is a test for that, because passToClient is exactly the kind of thing a later change widens without noticing.

Threading — where the 404s were

getDocumentById rejects a draft outright unless asked for one, so every draft meditation and lecture preview would have hit the error page. getPageBySlug did the same and now reads draft: true — under which Payload matches the draft version's slug, so a renamed draft is reachable at the URL SahajCloud's own composer builds for the panel. The two agreeing is why the panel and the site share one composer.

getWebTranslations set the header but never asked for the draft, which is the whole of SahajCloud#776: a translator previewing their own edit saw published copy.

Scope decides what reads drafts. No scope means this route's own document; wm-web-translations means the strings, leaving the page published — so a translator sees their copy on the real article rather than inside someone's half-finished draft.

A translator can preview an unpublished locale. availableLocales is gated on translations being published, so the 404 fired before rendering a single string, for exactly the person who needs it most. The gate exists to stop the public meeting a half-translated site.

Live editing

The stream is Payload's useLivePreview. An earlier revision of this PR re-implemented it, because the hook takes no collection, id or predicate and so cannot be told which document a page shows. That over-corrected. Three mechanisms already leave exactly one subscriber, for the document the URL names:

  1. the wrapper mounts only for an unscoped session — the CMS emits scope=wm-web-config / scope=wm-web-translations for a global, so a globals preview mounts no document subscriber at all
  2. there are exactly two call sites, on routes that cannot both render
  3. the link guard inerts every anchor but #hash, so the iframe cannot navigate and initialData is fixed for the session

So lib/live-preview/messages.ts and merge.ts are gone, and the listener, the payload-live-preview tag, the origin check, the ready() handshake and the teardown all come from the SDK. What is left is lib/live-preview/document.tsx: a wrapper mounted only under an open session (a React hook cannot be conditional, and mounting it unconditionally would attach a listener and fire ready() on every ordinary page view), and a requestHandler.

Populating relationships — the one thing that was genuinely forced

mergeData's default handler POSTs to the CMS with credentials: 'include' against an API answering Access-Control-Allow-Origin: * with no Allow-Credentials. Browsers refuse that pairing, which is why relationship population has never worked here. The CMS's wildcard is load-bearing for the atlas widget on third-party hosts, so it is the request that moves, not the CORS header — requestHandler is an explicit override point.

POST /api/live-preview/populate runs the round trip same-origin. The browser cannot call the CMS itself in any case: the API key that unlocks a draft read is a server-only secret, and an unauthenticated read is a 403.

⚠ The Ed25519 token is re-verified there, before anything else happens. The key is attached on our side, so without that check this is an open proxy handing any caller the CMS's unpublished content. No token, a forged token and an expired token each get a bare 403 with no body and no CMS call — there are tests for all three. The endpoint is matched against the collections the site already reads, which rules out a traversal, an unrelated collection and every global at once.

The forwarded read repeats the shape the server render used. SahajCloud requires select from an API client and populate at depth > 1, and prunes its answer to select — all three verified against production — so a proxy reading a different shape would hand the template a document missing the fields it renders. It goes in the body, not the query string: under the method override the body wins.

Two things the SDK leaves to the caller are handled in the handler, because mergeData has neither a try/catch nor a status check:

  • the document filter. endpoint is the only identifying value a handler is given, and its first segment is the message's own slug. A message about another collection is refused — this is the filter the deleted code carried, restored at zero structural cost in code the CORS problem makes us write anyway.
  • failure. A rejection would kill the callback silently and a non-2xx JSON error body would be merged in and rendered as the document. Every failure answers with the last good document instead, which is what stays on screen.

The newly-created-relationship limitation is fixed. A relation pointed at a document that does not exist yet used to arrive as a bare id and stay unpopulated until save and reload. The CMS populates the unsaved document and answers with the real objects — verified against production.

The token reaches the browser the only way it can: caught from the URL as the scrub erases it from location.href, held in module state. It is still absent from passToClient, and the proxy trusts nothing it is given.

The meditation frame protocol moves to the public /meditations/:id/embed. ⚠ Its inbound origin check now fails closed — it compared against a '*' fallback when PUBLIC__SAHAJCLOUD_URL was unset, so an unset variable let any page drive the playhead that timestamps frames.

Three leaks closed

The token rides in a query string, because an iframe navigation carries no header. It is not the address bar that is at risk — a preview is an iframe inside the CMS admin, so the browser shows cloud.sydevelopers.com/admin/… and the preview page's URL is never displayed. What reads it is location.href, from inside the page:

  • Plausible posts location.href with every pageview, and Referrer-Policy governs what the browser sends, not what a script reads. ⚠ The scrub cannot win this race and never could: measured on the deployed preview, the <script defer> is the FIRST script in the document and runs the moment parsing ends, while Vike's client entry is <script type="module" async> at the end of <body> whose body dynamically import()s a hashed chunk. So pages/+Head.tsx omits the tag entirely under a preview — which is also right on its own terms, since an editor in the admin's iframe is not a visitor.
  • Sentry initialises against an already-clean URL, because sentryBrowserConfig calls the scrub as its own first statement. That is a structural guarantee, not a call order in another module — it replaces two calls written above their own imports in pages/+client.ts, working by ESM hoisting, that any import-sorting rule would have undone with nothing turning red. sentry.browser.config.test.ts records location.href at the moment Sentry.init runs, so moving that statement turns it red. With it guaranteed, beforeSend and beforeBreadcrumb can never see a token, and both are deleted; the pure stripLivePreviewToken stays, since the scrub is built on it.
  • responses carry no-store, noindex and no-referrer, set after next() so api-routes' own Cache-Control cannot overwrite them, and registered before the routes because Hono never reaches middleware added after a handler that returns

What a leaked token is worth, which bounds all of the above: nothing on its own. SahajCloud's createAccessConfig runs hasPermission first and lifts its published-only clause only for a request already authenticated as a clients user. The exposure is a leaked token combined with an API key — not hypothetical, since the atlas ships a browser-usable one. That, plus a 45–90 minute verify-only lifetime, is the size of the risk.

scrubAddressBar is renamed scrubTokenFromLocation: the old name was the most-repeated copy of the address-bar claim.

No canonical under preview. ContentHead returns null: previewing a draft would otherwise claim a canonical for a URL that 404s publicly, and advertise unpublished locales in the hreflang cluster.

No banner. The panel sits in the CMS admin, whose chrome already says Live Preview, and a fixed bar would overlap the site header and eat the top of a 375×667 meditation embed. The repo carried an unrendered PreviewBanner for a year and nobody missed it.

Test results

  • pnpm lint — 0 errors; my files add no warnings
  • pnpm typecheck, pnpm build — clean
  • pnpm test:run — 642 passed (69 files)

Each new assertion was watched failing first: dropping the endpoint check, the session gate, or the token verification each turns the matching specs red and nothing else.

Verified end to end with the real production keypair: a token minted by SahajCloud's own module verifies here, and fails under a different key.

Not in this PR

Removing the KV cache. SahajCloud#710 made globals edge-cacheable, which unblocks it, and it is the one item from the plan left undone. It is independent of preview now — the bypassCache threading is already in place — so it is better measured on its own than bundled with a behaviour change this size.

Two placeholder configs — found, deliberately not guessed.

  • pages/+Head.tsx still says data-domain="yourdomain.com", with its original TODO. Plausible's servers receive the URL either way, so this is a live third-party channel rather than an inert placeholder — which is why the preview omission above matters even while the domain is wrong.
  • sentry.browser.config.ts still says tracePropagationTargets: [/^\//, /^https:\/\/yourserver\.io\/api/].

Neither has an unambiguous value in the repo to take. There is no site-URL config or env var at all — every origin is derived from the request (pageContext.urlParsed.origin, and isIndexableHost in server/sitemap.ts), by design. wemeditate.com appears only in test fixtures and one .env.example comment. And the live wemeditate.com is still the old Rails site, running Fathom (cdn.usefathom.com) and GTM, not Plausible — so the repo holds no evidence that a Plausible site is even registered, let alone under what domain. Someone with the Plausible account has to say.

Dependency

@payloadcms/[email protected], pinned exactly rather than caretted — it is a hook whose effect body this code depends on the shape of. @payloadcms/live-preview stays: it is that package's own dependency, and the CollectionPopulationRequestHandler type comes from it.

⚠ Before merge

SahajCloud#787 and #788 must merge first, and LIVE_PREVIEW_SIGNING_KEY must be set on the Railway service. Until then this site simply never sees a valid token, and every request renders published content.

🤖 Generated with Claude Code

Ardnived and others added 2 commits September 14, 2026 19:34
…ugh pageContext

Adds the consumer half of SahajCloud's Ed25519 token: a verifier, the
per-request memo, and the verdict on pageContext + passToClient.

No fetcher reads it yet, so behaviour is unchanged.

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

The consumer half of the credential. SahajCloud signs a short-lived Ed25519
token and puts it on the panel's URL; this verifies it with a PUBLIC key and
puts the verdict — never the token — on `pageContext`.

The key is committed in `.env.production` on purpose. A verification key
cannot mint, so publishing it costs nothing, and it is what lets this site
check a token without holding a shared secret that would have to be kept in
step with the CMS. Unset, live preview is unavailable and every request
renders published content.

The token names the API-CLIENT ROLE that may redeem it, not a site. The claim
first named `wm-web`, which only a consumer checked — against a constant it
hardcoded — while the CMS accepted either, so one leaked token unlocked drafts
on both surfaces. A role is matched against the roles on the authenticated key,
which the caller has to prove.

Verification is the whole gate: a forged or expired token opens no session, so
an invalid value renders the published page with a 200, indistinguishable from
an ordinary request. Nothing tells a caller whether they guessed right.

The verdict is memoised per `pageContext`, the way `site-context.ts` memoises
its global reads. Several `data()` functions and `onBeforeRender` all ask, and
they must agree — a second call that disagreed would render a draft body inside
published chrome. Not `+onBeforeRoute`, where `locale` is derived: that hook is
synchronous and runs on the client during client-side routing.

`server/live-preview.test.ts` mints with the SAME construction SahajCloud's
minter uses, so the format is pinned on both sides of a boundary neither repo
imports across. Checked end to end with the real production keypair: a token
minted by SahajCloud's own module verifies here, and fails under another key.

No fetcher reads the verdict yet, so behaviour is unchanged.

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
@cloudflare-workers-and-pages

cloudflare-workers-and-pages Bot commented Sep 15, 2026 •

Copy link
Copy Markdown

Deploying wemeditate-design with  Cloudflare Pages  Cloudflare Pages

Latest commit: d1a7a8e
Status: ✅  Deploy successful!
Preview URL: https://49cafa7b.wm-design.pages.dev
Branch Preview URL: https://claude-feat-live-preview.wm-design.pages.dev

View logs

@cloudflare-workers-and-pages

cloudflare-workers-and-pages Bot commented Sep 15, 2026 •

Copy link
Copy Markdown

Deploying with  Cloudflare Workers  Cloudflare Workers

The latest updates on your project. Learn more about integrating Git with Workers.

Status Name Latest Commit Preview URL Updated (UTC)
✅ Deployment successful!
View logs
wemeditate-web d1a7a8e Commit Preview URL

Branch Preview URL
Sep 16 2026, 06:10 PM

Ardnived and others added 2 commits September 15, 2026 14:00
…utes

Preview is no longer a place. Any page renders drafts when the URL carries a
valid token, so `pages/preview/(full)` and `pages/preview/embed` are gone —
with them a second renderer that had to be kept approximately equal to the real
one, and never quite was.

**The token reaches the fetchers; only the verdict reaches the browser.**
`loadLivePreview` returns a session carrying the credential, and `toClientState`
strips it before `passToClient` serialises anything into the page. A test pins
that, because `passToClient` is exactly the kind of thing a later change widens
without noticing.

**Threading, which is where the 404s were.** `getDocumentById` rejects a draft
outright unless asked for one, so every draft meditation and lecture preview
would have hit the error page. `getPageBySlug` did the same and now reads
`draft: true` — under which Payload matches the DRAFT version's slug, so a
renamed draft is reachable at the URL SahajCloud's own composer builds for the
panel. `getWebTranslations` set the header but never ASKED for the draft, which
is the whole of SahajCloud#776: a translator previewing their own edit saw
published copy.

**Scope decides what reads drafts.** No scope means this route's own document.
`wm-web-translations` means the strings, leaving the page published — so a
translator sees their copy on the real article, not inside someone's draft.

**A translator can preview an unpublished locale.** `availableLocales` is gated
on translations being published, so the 404 fired before rendering a single
string — for exactly the person who needs it. The gate exists to stop the
PUBLIC meeting a half-translated site.

**Three leaks closed.** The token rides in a query string, because an iframe
navigation carries no header:

- the address bar is scrubbed at client entry, BEFORE Plausible's deferred
  script reads `location.href` and posts it somewhere no response header
  reaches
- Sentry gets `beforeSend` and `beforeBreadcrumb` — two hooks, because the
  navigation trail is a separate field from the event URL
- responses carry `no-store`, `noindex` and `no-referrer`, set AFTER `next()`
  so `api-routes`' own `Cache-Control` cannot overwrite them, and registered
  BEFORE the routes because Hono never reaches middleware added after a
  handler that returns

**No canonical under preview.** `ContentHead` returns null: previewing a draft
would otherwise claim a canonical for a URL that 404s publicly, and advertise
unpublished locales in the hreflang cluster.

**No banner.** The panel sits in the CMS admin, whose chrome already says Live
Preview, and a fixed bar would overlap the site header and eat the top of a
375×667 meditation embed. The repo carried an unrendered `PreviewBanner` for a
year and nobody missed it.

`mergePreviewData` and the link guard move to `lib/`; the guard now takes the
session rather than inferring it from where it was mounted, and attaches no
listener off-preview. `collectionSchema` went with the routes that used it.

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

Restores live editing on the real routes, and closes two defects the deleted
code carried.

**A filtered listener, not `useLivePreview`.** The library hook takes no
`collection`, no `id` and no predicate, so it cannot reject a message meant for
another document — `wm-web-config` previews the site root and its messages
carry `globalSlug`, which the hook would merge into the page and render as the
config. Its merge cache is also a module-level `let` shared by every
subscription, so one wrong-shaped merge poisons the base for all later ones.

Its default transport made this moot anyway: a cross-origin POST with
`credentials: 'include'`, against an API that answers
`Access-Control-Allow-Origin: *`. Every browser refuses a credentialed request
against a wildcard origin, so relationship re-population has never worked here.
`mergePreviewData` does that job locally, keeping the server-fetched object
whenever a message collapses a populated relation to the same bare id.

**The frame protocol moves to `/meditations/:id/embed`** — a real, public,
chrome-less route, rather than `/preview/embed`, a second renderer that had to
be kept equal to it. The channel is unchanged: inbound `SEEK_TO_TIME` when an
editor clicks a frame thumbnail, outbound `PLAYBACK_TIME_UPDATE` as the
timestamp a newly inserted frame is written at.

⚠ **The inbound check now fails closed.** It compared against a `'*'` fallback
when `PUBLIC__SAHAJCLOUD_URL` was unset, so an unset variable let any page
drive the playhead that timestamps frames. Its sibling on the same file already
failed closed; only this one was open.

Both channels attach nothing at all off-preview, so the ordinary embed pays
none of it.

Accepted cost, worth stating: a relation pointed at a NEWLY created document
arrives as a bare id and stays unpopulated until save and reload. That is what
the broken round trip was for.

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
@Ardnived
Ardnived marked this pull request as ready for review September 15, 2026 21:05
@sydevs-bot

Copy link
Copy Markdown
Contributor

I could not request a reviewer here, so this is the step left for you.

  • request a reviewer — GitHub said: Review cannot be requested from pull request author. - https://docs.github.com/rest/pulls/review-requests#request-reviewers-for-a-pull-request

🤖 sydevs dispatcher

@Ardnived Ardnived changed the title feat(preview): verify SahajCloud's live-preview token, and carry the verdict feat(preview)!: render drafts on any route, and delete the preview routes Sep 15, 2026
Comment thread hooks/useLivePreviewMessages.ts Resolved
Comment thread lib/live-preview/merge.ts Resolved
Comment thread lib/live-preview/merge.ts Resolved
Comment thread lib/live-preview/token-url.ts Resolved
Comment thread lib/live-preview/token-url.ts Resolved
Comment thread pages/[slug]/+data.ts Resolved
Comment thread pages/meditations/[id]/embed/+Page.tsx Resolved
… Payload

Addresses the review on #99.

**Where it lives.** `lib/live-preview/` is now the browser half — the
unsaved-edit stream, the link guard, the address-bar scrub, the sparse-merge
and the meditation frame channel — and `server/live-preview.ts` stays the
server half, because it reads the token. The two meet at
`lib/live-preview/protocol.ts`: the parameter names, the scope set and the
verdict shape, which both import. The `live-preview` parameter used to be
spelled in both files with a comment asking the two to stay in step.

**`components/organisms/LivePreview` is gone.** It rendered `null` and
attached a listener. That is behaviour, not UI, and atomic design has no shelf
for it. `LayoutRoot` calls `useLivePreviewLinkGuard()` directly, the way it
already works for the route announcer.

**Payload's SDK now owns Payload's protocol.** `isLivePreviewEvent`, `ready`
and `unsubscribe` come from `@payloadcms/live-preview`, so the origin check,
the `payload-live-preview` type tag, the `opener ?? parent` handshake and the
teardown are no longer ours to keep in step. What stays ours is the one thing
the SDK structurally cannot express: rejecting a message meant for another
document. `useLivePreview` and `subscribe` take no `collection`, no `id` and
no predicate, and `wm-web-config` previews the site root with
`globalSlug: 'wm-web-config'` — the site config would be merged into the page.
Its population round trip cannot run here either: `mergeData` has no local
path, and its default handler POSTs cross-origin with `credentials: 'include'`
against a CMS answering `Access-Control-Allow-Origin: *`, which browsers
refuse. `@payloadcms/live-preview-react` was an unused dependency and is
replaced by the SDK it wrapped.

**One name for "is this read previewing?".** `previewArgs(session, scope)`
replaces the `preview.active && preview.scope === null` pair spelled out in
three `data()` functions and the translations read; `useDocumentPreviewActive()`
replaces the same condition spelled in two page components. No React provider:
vike-react already publishes `pageContext` through one, and the `data()`
functions run before any component and carry the token a provider must never
see.

**The embed page's frame channel is a helper.** `useFrameEditorChannel` holds
the inbound `SEEK_TO_TIME` listener and the outbound `PLAYBACK_TIME_UPDATE`
sender, with `readSeekTimestamp` as a pure, tested function — including the
case that must fail CLOSED when `PUBLIC__SAHAJCLOUD_URL` is unset.

**`scrubLivePreviewUrl` is `stripLivePreviewToken`.** A URL in, a URL out.
`scrubAddressBar` takes nothing and returns nothing, and is called once from
the client entry. The two are no longer near-homographs.

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
Ardnived and others added 7 commits September 15, 2026 17:36
… standard JWS

SahajCloud's review moved minting onto `jose`, so the token is now a standard
EdDSA compact JWS carrying only `exp` — three parts, signed over
`header.payload`. This verifier destructured two parts and checked a `role`
claim that no longer exists, so it refused every token the CMS now issues.

`jwtVerify` replaces the hand-written split, key import, signature check,
claim parse and expiry comparison. `algorithms: ['EdDSA']` is the part worth
naming: the header is attacker-controlled, so it must not be allowed to
nominate its own algorithm. There is a case for that.

The role check goes with it. 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 — not worth the code
on either side of the boundary.

The public key and the header name are unchanged, so nothing needs rotating.

`jose` is a new dependency here, and it is server-side only: `dist/client`
carries no `jwtVerify` and no verify key, checked after building. It is what
the CMS already uses, so the two halves of this format now share one
implementation rather than two hand-written ones drifting apart.

The spec mints with the same construction the CMS does, and gains the
algorithm-confusion case. Verified against a token minted by SahajCloud's own
module under the production key — accepted, and refused under another key.

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.
Payload's `mergeData` populates a live-preview document by POSTing it back
to the CMS. Its default handler cannot run here: it sends
`credentials: 'include'` while SahajCloud answers
`Access-Control-Allow-Origin: *` with no `Allow-Credentials`, which browsers
refuse, and the API key that unlocks a draft read is a server-only secret
(an unauthenticated read is a 403 — verified against production).

So the round trip moves to the server, behind `POST
/api/live-preview/populate`. The Ed25519 token is re-verified there before
anything else happens: the key is attached on our side, so without that
check this is an open proxy handing any caller unpublished content. A
refusal is a bare 403 with no body.

The read shape is the render's own (`documentReadArgs`). SahajCloud requires
`select` from an API client and `populate` at depth > 1, and prunes its
answer to `select` — all verified against production — so a proxy reading a
different shape would hand the template a document missing fields. It goes
in the body, not the query string: under the method override the body wins.

The token reaches the browser the only way it can, by being caught from the
URL as the address-bar scrub erases it. It is still absent from
`passToClient`, and the proxy trusts nothing it is given.

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
`useLivePreviewMessages` re-implemented `useLivePreview` because the hook
cannot be told which document a page shows. That over-corrected: three
mechanisms already leave exactly one subscriber for the document the URL
names — an unscoped session (the CMS emits `scope=` for a global), two call
sites on routes that cannot both render, and the link guard, which fixes
`initialData` for the session.

So the transport, the handshake, the origin check and the teardown come from
the SDK now, and `lib/live-preview/messages.ts` and `merge.ts` are gone. What
is left is the ~10 lines the hook has no way to be told: a wrapper mounted
only under an open session (a hook cannot be conditional, and mounting it
unconditionally would fire `ready()` on every page view), and a
`requestHandler` that asserts the endpoint's collection is this page's — the
document filter the deleted code carried, in code the CORS problem makes us
write anyway.

`mergeData` has no try/catch and no status check, so the handler carries
both: a failed populate answers with the last good document, rather than
rendering `{errors:[…]}` or killing the callback silently.

The newly-created-relationship limitation the old merge documented and
accepted is fixed — the CMS populates the unsaved document (verified against
production).

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

The scrub's ordering was two calls written ABOVE their own imports in
`pages/+client.ts`, working only by ESM hoisting, with a comment as the
sole enforcement. Any import-sorting rule reorders that silently and the
protection disappears with no test failing.

Each reader now states its own precondition, so there is no cross-module
order left to preserve:

- `sentryBrowserConfig` calls `scrubAddressBar()` as its first statement,
  outside the PROD check. Sentry cannot initialise against a URL that
  still carries a token. `sentry.browser.config.test.ts` records
  `location.href` at the moment `Sentry.init` runs, so moving that call
  below the init turns it red.
- `pages/+Head.tsx` omits the analytics script entirely under an active
  preview.

⚠ **That second one is a real leak, not a tidy-up.** The claim that the
client entry evaluates before Plausible's deferred script does not hold.
Measured on the deployed preview: the Plausible `<script defer>` is the
FIRST script in the document and runs the moment parsing ends, while
Vike's client entry is `<script type="module" async>` at the end of
`<body>` whose body is a dynamic `import()` of a hashed chunk — it cannot
evaluate until that chunk is fetched. Plausible read and posted
`location.href`, token included, every time. No call ordering inside the
entry could have fixed that; only not emitting the tag does.

Not emitting it is also right on its own terms: an editor inside the CMS
admin's preview iframe is not a visitor, and a draft URL is not a
pageview anyone wants counted.

`pages/+client.ts` keeps its own `scrubAddressBar()` call — idempotent,
and the one thing left if Sentry is ever removed — and `client.test.ts`
pins it with `sentryBrowserConfig` mocked out.

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
`beforeSend` and `beforeBreadcrumb` each ran `stripLivePreviewToken` over
every URL Sentry was about to send. With the scrub guaranteed to run
first — the previous commit makes it `sentryBrowserConfig`'s own first
statement — Sentry initialises against an already-clean `location.href`
and neither hook can ever see a token. They cost a function call on every
event and every breadcrumb to find nothing.

The pure `stripLivePreviewToken` stays: `scrubAddressBar` is built on it.

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
The docblocks claimed the scrub protects "the address bar, and so
`document.referrer` of anything the page opens". A preview runs in an
iframe inside the CMS admin: the browser shows
`cloud.sydevelopers.com/admin/…` and the preview page's own URL is never
displayed. There is no address bar to protect.

What the scrub actually does is keep the token out of `location.href`,
where in-page third-party JavaScript reads it — Plausible posts it with
every pageview, and no `Referrer-Policy` reaches that, because
`Referrer-Policy` governs what the browser sends rather than what a
script chooses to read. `window.history.replaceState` is not there to
change what an editor sees; it is the only way to move `location.href`
without navigating.

`scrubAddressBar` is renamed `scrubTokenFromLocation`, since the name was
the most-repeated copy of the wrong claim. Same correction in
`protocol.ts`, `navigation.ts`, `server/live-preview.ts` and the specs.

Also records the fact that bounds the risk, which nobody had written
down: a leaked token grants nothing on its own. SahajCloud's
`createAccessConfig` runs `hasPermission` first and lifts the
published-only clause only for a request already authenticated as a
`clients` user. The exposure is a leaked token combined with an API key —
which matters because the atlas ships a browser-usable one. The 45–90
minute window is the CMS's bucketed 45-minute TTL, which a token outlives
by between one and two TTLs.

`server/live-preview.ts` also stopped naming a Sentry `beforeSend` that
no longer exists.

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
@Ardnived
Ardnived enabled auto-merge September 16, 2026 18:20
@Ardnived
Ardnived disabled auto-merge September 16, 2026 18:24
@Ardnived
Ardnived merged commit 0a4736f into main Sep 16, 2026
8 checks passed
@Ardnived
Ardnived deleted the claude/feat-live-preview branch September 16, 2026 18:24
@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 Nov 2, 2026
* test: drop leftovers from the KV cache removal and an unused smoke helper

- `kv: undefined` in two sahajcloud-context mocks: the context lost its
  kv field in #107, so the mocks described a shape that no longer exists.
- Three retry tests titled "…since the KV layer used to supply that":
  the KV layer is gone, so the titles now state only the behaviour.
- `headTags()` in the smoke preview helper: exported in #28 and never
  called.

The audit found no migration-era test files left; #87, #99 and #107
already removed them with their code.

Co-Authored-By: Claude Opus 5.5 <[email protected]>

* fix(server): drop the stale KV binding claim

`getSahajCloudContext()` returns `{ apiKey, baseURL }`, and
`SahajCloudEnv.Bindings` carries no KV namespace — the binding went with
`server/kv-cache.ts` in #98. The docblock still promised a reader that the
helper resolves one, which is the same leftover this PR deletes from the
file's own test mock. Wording now matches `sitemap-routes.ts`.

Co-Authored-By: Claude Opus 5 <[email protected]>
Claude-Session: https://claude.ai/code/session_01Mg9rjXde9tn99Z82seiuKd

* fix(components): call the related fetch edge-cached

Nothing in this Worker holds persistent state (server/CACHING.md). The
related endpoints are cached by the Cloudflare zone in front of SahajCloud,
which sets `s-maxage` and `Cache-Tag` through `publicReadCacheHeaders`. The
KV namespace these docblocks named went away in #98, so "KV-cached" pointed
a reader at a cache they could neither inspect nor purge.

Co-Authored-By: Claude Opus 5 <[email protected]>
Claude-Session: https://claude.ai/code/session_01Mg9rjXde9tn99Z82seiuKd

---------

Co-authored-by: Claude Opus 5.5 <[email protected]>
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.

2 participants