Skip to content

feat(preview): verify SahajCloud's live-preview token before opening a session - #208

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

The consumer half of the new live-preview credential. SahajCloud signs a short-lived Ed25519 token (sydevs/SahajCloud#787, #788); this verifies it with a public key committed into the bundle, and opens a preview session on any route — so the CMS panel points at the real page an editor is editing, not at a second renderer kept approximately equal to it.

It also fixes a defect that is live on main today: no live edit renders in the atlas at all, because preview wrote to cache keys the drawers do not read.

Verification is the point, not decoration

src/config/preview.ts validated nothing. It read secret off the URL and trusted it, gated only by the pathname being /preview:

if (pathname !== PREVIEW_PATH) return null
…
secret: params.get('secret'),

Widening that gate to every route without verifying would turn any atlas URL into a denial of service. An active session inerts every <a>, snaps navigation back, pins all queries to staleTime: Infinity, and adds draft=true plus the credential header to every request — including POST /events/:id/register. And public/_redirects serves the SPA shell for any path, so sahajatlas.com/anything?live-preview=x would qualify. Share that link and the recipient gets a site where nothing is clickable, with no error shown.

A forged token now opens no session. readLivePreviewParams returns active: false in every branch — it reports what the URL claims, which is unauthenticated — and only activateLivePreview, having checked the signature, may flip the flag.

The two-step, and why the gap fails closed

Verifying a signature is asynchronous. Capturing cannot be: main.tsx runs before React mounts, and BrowserRouter snapshots window.location on mount, so the token must leave the URL by then.

  • captureLivePreview() — synchronous. Stashes the token, scrubs the address bar, opens nothing.
  • activateLivePreview() — async. Verifies, then flips active. A refusal wipes the session rather than merely leaving active false: an unproven token is not a credential, and leaving one in memory is how it eventually reaches a header.

applyRequestContext gates on active, never on the token being present, so nothing can leave the browser in between. main.tsx additionally holds the render until activation settles, so no component can mount, read active: false, and never hear otherwise.

The key is public and committed, which is why signing was chosen

This bundle ships to anyone, so it can hold no secret — a symmetric key here would be the signing key, and anyone could mint. A verification key cannot mint, so publishing it costs nothing. That asymmetry is the whole reason the CMS signs rather than sharing a secret.

The token carries { exp } and nothing else. An audience claim was tried and dropped in SahajCloud#788: it was checked against the token rather than against the key presenting it, so it only narrowed which surface a leaked token unlocked drafts on, never what it could reach.

Hand-written verifier, deliberately

jose's jwtVerify measured 5.75 KiB gzipped against 8–11 KiB of spare budget in a bundle that ships as a public widget. WeMeditateWeb uses jose — it verifies on the server, where the bytes are free. Here it is ~40 lines pinning alg === 'EdDSA' before touching the signature.

Neither repo imports from the other, so the format is written twice and token.test.ts mints with the same construction the CMS minter uses. Checked end to end with the real production keypair: a token minted by SahajCloud's own module verifies here against the committed key.

The transport is Payload's own hook, not ours

28e2855e dropped @payloadcms/live-preview-react in July, for a real reason: the library's default relation round-trip sends credentials: 'include' for an admin cookie that a cross-origin widget has none of. But requestHandler is an explicit override point, so overriding it was always enough — re-implementing the transport was not. The dependency is back, pinned exactly at 3.88.0 (1.6 KiB gzipped, zero dependencies, peer range ^16.8 || ^17 || ^18 || ^19).

Deleted, and what replaced each:

Gone Now
useLivePreviewMessages — the origin check, the payload-live-preview tag check, the ready handshake useLivePreview
api.populatePreviewDoc (config/api/fetch.ts) a requestHandler routed through interceptFetch
lib/live-preview/messages.ts (editedDocumentId) namesPreviewedDoc, asserting the endpoint

The request still goes through interceptFetch, so the API key, the preview token header and draft=true attach in the one place every other SahajCloud request gets them — applyRequestContext still gates on livePreview.active, which is only ever true after the signature held.

Why the hook needs no document identity, and what stands in until it has one

useLivePreview cannot be told which document the page shows, and it holds its merge cache at module scope. Both are safe here only because there is never more than one subscriber: LivePreviewController returns EventLivePreview or RegionLivePreview, resolveLivePreviewTarget derives the document from the route, and allowedLivePreviewPaths permits only sub-paths of that same document (/register, /share). The target cannot change mid-session.

That leaves the panel's own broadcast, which names whatever the editor has open. mergeData composes endpoint as <the message's collectionSlug>/<our initialData.id> — the collection half is theirs, the id half is ours — so namesPreviewedDoc asserts the whole string and refuses anything else. This is editedDocumentId's job, relocated into code the override made us write anyway.

A region route carries a slug, and the endpoint is POST /regions/:id, so the region arm reads its id off the drawer's own cache entry (enabled: false, no request of its own). That is the same entry writeRegionEdit overlays, so there is no window where a populate succeeds with nowhere to write the result.

Two things the library omits, and the seed that answers both

mergeData is requestHandler(…).then((res) => res.json()). No catch, no status check.

  • A rejection takes the subscription's callback with it, silently, and escapes as an unhandled rejection from a session where nothing is really wrong.
  • An {errors:[…]} body becomes the document the library caches — and since it has no id, every later edit is addressed at regions/undefined. One 403 would end live preview for the rest of the session.

So every refusal answers with the seed, { id }, which fails the zod parse the cache writes already sit behind. The last good document stays on screen, and the next message still populates under the right id.

⚠ The zod parse and the React Query writes are unchanged and load-bearing. mergeData returns the server's JSON verbatim, so EventDocSchema / RegionNodeSchema are what stop a refusal body being written in as a document.

The live defect: preview wrote to keys nothing reads

Preview wrote ['event', id] and ['region', slug]; the views read ['event', id, locale] (config/api/index.ts) and ['region', slug, locale] (RegionView). So no live edit has ever rendered, independent of everything else here.

regionQuery(slug, locale) now exists beside the other factories, and the three inline copies of those keys moved onto them. Both writes failed against the old bare keys before passing.

⚠ The region populate must run at depth 0, and that is still asserted rather than assumed: RegionNodeSchema types parent as z.number().nullish(), so a populated parent fails the parse. region.test.ts pins the rejection. The per-collection depth moved with the code it describes — depth is now a prop handed to useLivePreview, so LivePreviewController.transport.test.tsx asserts it on the request that actually leaves the browser.

Shape, matching the other consumer

config/preview.ts → config/live-preview/, split four ways — and the split is the import graph seam, not tidiness:

Module In the embed graph?
protocol.ts — names and types yes (~120 bytes of strings)
session.ts — the singleton, nothing else yes
token.ts — the verifier and the key no
boot.ts — capture, scrub, activate no
components/live-preview/ + @payloadcms/live-preview-react no — lazy, behind App's dynamic import

Even the pure URL reader lives in boot.ts: a widget that never boots a preview has no use for it, and a module in a shared chunk is carried whole. Verified in the built output — Ed25519 appears in main-*.js alone, and payload-live-preview / X-Payload-HTTP-Method-Override appear only in assets/LivePreviewController-*.js, which the walked static closure of embed.js does not contain.

⚠ Nothing structural was enforcing that last row, so Widget.standalone.test.ts now does. Its graph walk resolves no package specifier, by design, and pnpm size cannot see 1.6 KiB disappear inside 10 KiB of spare budget — the gate would stay green while every host paid, on every page view, for a hook only a CMS editor can trigger. A closed importer list, in the manner of config/responsive.test.ts, is what makes the seam reviewable.

preview→livePreview, secret→token, usePreviewLinkGuard→useLivePreviewLinkGuard, PreviewController→LivePreviewController, lib/preview/→lib/live-preview/. PREVIEW_SECRET_HEADER→LIVE_PREVIEW_HEADER, wire name unchanged — SahajCloud's CORS allowlist and the Cloudflare Cache Rule match the literal.

The rest

  • Scrub deletes only the token. The old replaceState(null, '', '/preview') dropped the whole query string and the hash — invisible while the target was always /preview, and fatal once the path names the document. A side effect: the CMS's ?locale= now reaches the widget for the first time.
  • LivePreviewController is route-keyed. Identity comes from the path, never from a ?collection=&id= pair — that would be a second, unauthenticated claim about the URL. PreviewFallback, the boot fetches and the initial hop are gone — Payload never offers preview for an unsaved document (handleLivePreview guards operation !== 'create'), so the fallback was unreachable.
  • /preview survives for event-submissions only. A new-event proposal has no Event id, so the widget cannot fetch it back. The route, the params and the dispatch seam are kept; see the caveat below.
  • decideSlot is bypassed under preview (FULL_SLOT). A panel narrower than 360×420 rendered CompactEmbedView — a single card — and the previewed document never drew.
  • captureLivePreview is standalone-only, and now asserted. Widget.standalone.test.ts walks the real import graph (static and dynamic) and refuses the widget any path to boot.ts/token.ts, plus a closed list asserting main.tsx is boot.ts's only importer. From inside <sahaj-atlas> the address bar belongs to the host page, and scrubbing it would be this widget vandalising somebody else's URL. Nothing structural stopped that once the gate was no longer "the pathname is /preview".

Test results

  • pnpm lint, pnpm typecheck — clean
  • pnpm test:run — 1519 passed (119 files)
  • pnpm build — CSS scoping and no-sourcemap assertions pass
Graph Size Budget
standalone 295.9 KiB 308 KiB ✅ 12.1 KiB spare
loader 2.6 KiB 3.5 KiB ✅ 0.9 KiB spare
embed 297.8 KiB 308 KiB ✅ 10.2 KiB spare

Measured uncredentialed, which is what CI reads. ⚠ These are 1.6 KiB below the numbers this description carried before the library came back, and none of that is the library. The earlier figures were read off a stale node_modules; against a worktree at the previous commit installed identically, embed and loader are unchanged to the tenth of a KiB and standalone is 0.1 KiB smaller.

Every new assertion was watched failing against the old behaviour first — the endpoint check against a predicate that always accepts, the region depth against depth: 1, the two failure specs against the handler with no try/ok, and the importer list against an added import in App.tsx.

⚠ Note on the failure specs: the obvious version of each was vacuous. The write-side zod parse keeps a refusal body off the screen whether or not the handler checks the status, so what the spec pins is that the next edit still renders, which is what the library's module-scope merge cache actually breaks.

What is not verified, and the merge order

⚠ No browser pass. Everything above is structural. The loop this PR exists for — panel → postMessage → populate → drawer re-render — only exists with a CMS admin on the other end, and no local gate can see it. Open one region and one event in the real panel before merging.

⚠ event-submissions renders nothing yet. The atlas has never had that arm. The route and the dispatch seam are kept, but no renderer for previewEvent was invented: a proposal has no webPath and its target loads at depth 0, so the shape is undefined on this side. SahajCloud#723 owns it. Today /preview gives a reviewer the ordinary atlas with the guards on.

⚠ Ed25519 in WebCrypto needs Safari 17+. Older browsers reject the import, the catch returns false, and preview silently does not open. Acceptable for an admin panel, worth knowing.

Merge order: SahajCloud#787 → WeMeditateWeb#99 → this → SahajCloud#788. #788 repoints Events, Regions and EventSubmissions at real atlas paths; until this lands, the widget opens no session on them.

🤖 Generated with Claude Code

…a session

The consumer half of the new credential. SahajCloud signs a short-lived
Ed25519 token; this verifies it with a PUBLIC key committed into the bundle.

Additive: nothing imports it yet, so behaviour is unchanged and the module
tree-shakes out — all three size budgets still pass with spare.

**Verification is the point, not decoration.** The existing session
(`config/preview.ts`) validates nothing: it reads `secret` off the URL and
trusts it, gated only by the pathname being `/preview`. Widening that gate to
every route without verifying would turn any atlas URL into a denial of
service — `preview.active` inerts every link, snaps navigation back, pins all
queries to `staleTime: Infinity` and adds `draft=true` to every request,
including `POST /events/:id/register`. `public/_redirects` serves the SPA shell
for any path, so `sahajatlas.com/anything?live-preview=x` would qualify. Share
that link and the recipient gets a site where nothing is clickable, with no
error. A forged token now opens no session at all.

**The key is public and committed, which is why signing was chosen.** This
bundle ships to anyone, so it can hold no secret — a symmetric key here would
BE the signing key. A verification key cannot mint, so publishing it costs
nothing.

**The token names an API-client role**, not a site, and this checks it. The
claim first named `sy-atlas`, which only a consumer checked while the CMS
accepted either, so one leaked token unlocked drafts on both surfaces.

Malformed input is refused without throwing — load-bearing, because this runs
at boot before React mounts, and a throw would take the whole widget down on a
host page over a stray query parameter.

`live-preview.test.ts` mints with the SAME construction the CMS 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 against the committed key.

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 sahajatlas-design with  Cloudflare Pages  Cloudflare Pages

Latest commit: 2f3e148
Status: ✅  Deploy successful!
Preview URL: https://de98cc97.sahajatlas-design.pages.dev
Branch Preview URL: https://claude-feat-live-preview.sahajatlas-design.pages.dev

View logs

@cloudflare-workers-and-pages

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

Copy link
Copy Markdown

Deploying sahajatlas with  Cloudflare Pages  Cloudflare Pages

Latest commit: 2f3e148
Status: ✅  Deploy successful!
Preview URL: https://6a369221.sahajatlas.pages.dev
Branch Preview URL: https://claude-feat-live-preview.sahajatlas.pages.dev

View logs

Ardnived and others added 8 commits September 15, 2026 17:43
…e claim

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

**Still hand-written, and now for a measured reason.** `jose`'s `jwtVerify`
costs ~5.75 KiB gzipped in a browser build; this widget ships to host pages
with 8-11 KiB spare against a hard budget, for one verify on a rarely-taken
path. WeMeditateWeb adopted `jose` because its verification is server-side and
free. What is written here is now a reading of a standard, not an invention.

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

⚠ The header is pinned to `EdDSA` before the signature is touched. It is
attacker-controlled, so it must not choose the algorithm the verify uses —
there is a case for that.

Verified against a token minted by SahajCloud's own module under the
production key, using the key committed in this file rather than an injected
one. Budgets unchanged: standalone 297.1, loader 2.9, embed 299.7 KiB.

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.
No live edit renders in the atlas today, and nothing anywhere says so.

`setQueryData` under a key nothing subscribes to succeeds: it creates the
entry, returns nothing, and reports no miss. So when the drawer query keys
gained a locale suffix, the live-preview controller kept seeding and
overlaying `['event', id]` and `['region', slug]` — dead entries no view
had ever read — and every keystroke in the admin went nowhere in silence.

- `regionQuery(slug, locale)` joins `eventQuery` in `config/api`, and the
  three inline copies of those two keys (RegionView, OnlineView,
  `useEventFromPath`) now build them from the factories, so a writer and a
  reader cannot drift apart again.
- The controller's two cache writes become `writeEventEdit` /
  `writeRegionEdit`, so the node lane can drive them against a real
  QueryClient rather than infer the key from a component.
- The region populate drops to depth 0. `RegionNodeSchema` types `parent`
  as an id, because it is the wholesale-tree shape; at depth 1 the CMS
  returns it populated, the safeParse fails, and the overlay skips — the
  same silent no-op, one layer down. Events keep depth 1, which is where
  their region and images come from.

`region.test.ts` pins the populated-parent rejection that forces depth 0,
and `fetch.test.ts` pins the depth each collection is sent at.

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
Two repos verify the same credential minted by the same CMS, and spelled it
two different ways. This takes SahajAtlasWeb's half onto WeMeditateWeb's
vocabulary (`lib/live-preview/`: protocol, session, navigation) so a reader
moving between them recognises what they are looking at.

`config/preview.ts` becomes `config/live-preview/`, split four ways, and the
split is load-bearing rather than tidiness:

- `protocol.ts` — parameter and header names, the session shape. No state.
- `session.ts` — the singleton and the pure reader. The request interceptor
  and `App` read it, so it is in the EMBEDDED widget's graph too.
- `token.ts` — the signature check.
- `boot.ts` — the boot-time capture, standalone only.

The last two must never reach `Widget.tsx`: `boot.ts` writes the address
bar, which from inside `<sahaj-atlas>` belongs to the host page.

Renames: `preview` → `livePreview`, `PREVIEW_SECRET_HEADER` →
`LIVE_PREVIEW_HEADER` (the wire name stays, since SahajCloud's CORS
allowlist and Cloudflare Cache Rule match the literal), `session.secret` →
`session.token`, `usePreviewLinkGuard` → `useLivePreviewLinkGuard`,
`allowedPreviewPaths` → `allowedLivePreviewPaths`, `PreviewController` →
`LivePreviewController`.

Behaviour is unchanged.

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
SahajCloud now points every `livePreview.url` at the document's own page, so
the atlas has to preview at a path rather than at `/preview`. The pathname
was also the only thing standing in for a security check, and widening the
gate without replacing it would have been a denial of service: `active`
inerts every `<a>`, snaps navigation back, pins all queries to
`staleTime: Infinity`, and adds `draft=true` plus a credential header to
every request — `POST /events/:id/register` included. `public/_redirects`
serves the SPA shell for every path, so `sahajatlas.com/anything?live-preview=x`
would have qualified, and the recipient of that link would get a page where
nothing is clickable and nothing says why.

**The gate is now the Ed25519 signature**, checked against the committed
public key that landed in the first commit of this branch.

- **Capture and activation are separate, because one cannot wait and the
  other cannot be skipped.** `captureLivePreview` is synchronous — stash the
  token, scrub the URL, open nothing — and must be, since `BrowserRouter`
  snapshots `window.location` on mount. `activateLivePreview` verifies and
  only then flips `active`. The gap fails closed at the interceptor, which
  reads `active` and never the token's presence; `main.tsx` additionally
  holds the render until activation settles, so no component exists to make
  a request in between.
- **The scrub deletes only the token.** It used to `replaceState` to
  `/preview`, taking the whole query string and the hash with it. Harmless
  while the target was always `/preview`; on a document's own page it would
  discard the route being previewed.
- **`LivePreviewController` is keyed on the route.** The path names the
  document and the drawer has already fetched it, so the boot fetch and the
  initial hop are gone. An incoming edit is matched by `collectionSlug` plus
  the id or slug the route carries — `editedDocumentId`, pure and specced,
  because Payload's transport is a broadcast and a missed check writes one
  document's unsaved edits onto another's page. `PreviewFallback` is deleted:
  `handleLivePreview` guards `operation !== 'create'`, so it was unreachable.
  `getRegionNodeById` existed only for the boot fetch and goes with it.
- **`/preview` survives for `event-submissions` alone** — a proposal has no
  page and cannot be fetched back — so `'preview'` stays in `RESERVED_SLUGS`,
  and `resolveLivePreviewTarget` reads it as naming no document.
- **A preview session skips `decideSlot`.** The panel is framed and can be
  dragged under 360×420, which answers `compact` — a reviewer would get a
  one-button card where their document should be, linking off to another
  site. There is nowhere bigger to offer an editor inside their own admin.

`Widget.standalone.test.ts` walks the real import graph, static and dynamic,
and refuses the widget any path to `boot.ts` or `token.ts`. It was safe by
accident before — capture only fired on `/preview` — and nothing structural
replaced that. Embedded, the address bar `boot.ts` rewrites is the host's.

Size: standalone 297.5, loader 2.9, embed 299.4 KiB against 308/3.5/308.
The embed graph is 0.3 KiB SMALLER than before: all it carries is the
session singleton and four string constants.

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
Sweeps the prose that still described `SAHAJCLOUD_PREVIEW_SECRET`: the
interceptor's docblock, the data-layer rule, the architecture note, and the
`@payloadcms/live-preview-react` chunk comment for a dependency that is no
longer in the tree.

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
The list also claimed seven jsdom specs against sixteen in the lane, so it
now reads as the set of precedents it actually is, with the grep that
answers the census question.

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

Copy link
Copy Markdown
Contributor Author

Browser pass — the gate verified against a real Chromium

The PR body said this was unverified outside jsdom. It no longer is, for the security property. Headless Chromium, the real production build of this branch served through a local mirror of public/_redirects, and tokens minted with the real production signing key (~/sahajcloud-live-preview-key.txt, now merged as #787/#788).

First, the keypair itself: the public half derived from the production private key is byte-identical to the VERIFY_KEY committed in src/config/live-preview/token.ts. So this build verifies against the key the CMS actually signs with.

Scenario CMS requests draft=true preview header
no token 5 0 0
forged (valid shape, corrupted signature) 5 0 0
expired (valid signature, past exp) 5 0 0
valid 5 5 5

13 of 14 assertions passed:

  • A forged token and an expired token each open no session. No request carries draft=true, none carries the credential. This is the denial-of-service the PR exists to close, and it is closed.
  • A valid token opens the session on an ordinary route (/gb/london) — every CMS request carries both draft=true and the header.
  • The scrub removes the token and nothing else: loading /gb/london?live-preview=…&locale=fr&map=0#anchor leaves http://localhost:4173/gb/london?locale=fr&map=0#anchor in the address bar. The forged token is scrubbed too, so a rejected credential does not linger in history either.

The one that did not pass is my harness, not the code

I asserted the decideSlot bypass by looking for the compact card in a 320×400 viewport. The check is inconclusive: with the CMS stubbed at 403 the app renders the same error card at every viewport — 37 nodes in all three runs, including 1280×900 — so it distinguishes nothing. It needs real CMS data to mean anything. FULL_SLOT remains covered by the unit lane.

Still not verified, and it needs a human

The postMessage loop — panel → unsaved edit → populate → drawer re-render. It only exists with a real Payload admin on the other end, and the local API client key returns 403 against production (the documented local-vs-production role gap), so I could not drive it. Open one region and one event in the real panel before merging.

🤖 Verified with Claude Code

@Ardnived
Ardnived marked this pull request as ready for review September 16, 2026 05:03
@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

`28e2855e` dropped `@payloadcms/live-preview-react` in July because the
library's default relation round-trip is credentialed — `credentials:
'include'` for an admin cookie a cross-origin widget has none of. But
`requestHandler` is an explicit override point, so overriding it was
always enough, and re-implementing the transport was not.

Gone: the origin check, the `payload-live-preview` tag check and the
ready handshake (`useLivePreviewMessages`), `populatePreviewDoc` in
`config/api/fetch.ts`, and `lib/live-preview/messages.ts` with it.
`useLivePreview` does the first three; the fourth becomes a
`requestHandler` routed through `interceptFetch`, so the API key, the
preview token header and `draft=true` still attach in the one place
every other SahajCloud request gets them.

`useLivePreview` cannot be told which document the page shows, and holds
its merge cache at module scope. Both are safe only because there is
never more than one subscriber: the controller returns `EventLivePreview`
**or** `RegionLivePreview`, and `resolveLivePreviewTarget` plus
`allowedLivePreviewPaths` confine navigation to sub-paths of that same
document. `namesPreviewedDoc` is what each arm filters on meanwhile —
`mergeData` composes the endpoint from the panel's `collectionSlug`
joined to our own `initialData.id`, so the collection half is whatever
the editor happens to have open. That is `editedDocumentId`'s job,
relocated into code we have to write anyway.

Two things the library omits, and the seed that answers both. `mergeData`
is `requestHandler(…).then((res) => res.json())` — no catch, no status
check. A rejection takes the subscription's callback with it, and an
`{errors:[…]}` body becomes the document it caches and addresses the NEXT
populate from, so one 403 would end the session. Every refusal therefore
answers with `{ id }`, which fails the zod parse the cache writes sit
behind, leaving the last good document on screen.

The region arm reads its id off the drawer's own cache entry, since a
region route carries a slug and the endpoint is `POST /regions/:id`. It
is the same entry `writeRegionEdit` overlays, so a populate can never
succeed with nowhere to write it. Depth stays 1 for events and 0 for
regions — a populated `parent` fails `RegionNodeSchema`, which is now
asserted where depth actually lives, as a prop handed to the hook.

The library is 1.6 KiB gzipped and must stay out of the embed's eager
graph. `Widget.standalone.test.ts` gains a closed importer list for it:
the graph walk there resolves no package specifier, and `pnpm size`
cannot see 1.6 KiB inside 10 KiB of spare budget. Measured on the same
node_modules as HEAD, `embed` and `loader` are unchanged and `standalone`
is 0.1 KiB smaller; the live-preview code sits in its own lazy chunk,
reached only through `App`'s dynamic import.

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
Ardnived and others added 2 commits September 16, 2026 11:04
`session.ts` held one object literal built from `LIVE_PREVIEW_INACTIVE`, a type and a
constant that both already lived in `protocol.ts`. Since `protocol.ts` is in the embedded
widget's import graph either way, merging costs the embed nothing and removes a module.

The seam the folder exists for is unchanged: state and names on one side, reachable from
both graphs, and every behaviour — verification, capture, the `history.replaceState` scrub —
on the other, in `token.ts` and `boot.ts`, which `Widget.standalone.test.ts` still keeps
out of `Widget.tsx`'s graph. That test now names one shared module instead of two.

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
The docblocks claimed the scrub takes the token "out of the address bar". Preview renders
inside the CMS admin's iframe, where the browser shows the admin's URL and this page's own
URL is never displayed to anyone — so there is no address bar for it to leave. What it does
is keep the token out of `location.href`, which any in-page script reads freely, analytics
and error reporters included.

Also records what bounds the risk, which was written down nowhere: a leaked token grants
nothing on its own, because SahajCloud's `createAccessConfig` runs `hasPermission` first and
only lifts the published-only clause for a request already authenticated as a `clients`
user. The exposure is a leaked token combined with an API key — which is worth stating here
in particular, since this widget ships a browser-usable one.

The embed-side claim stays, in `location` terms rather than address-bar ones: on a host page
that URL really is the host's, and really is displayed.

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
sydevs-bot pushed a commit that referenced this pull request Oct 5, 2026
The pin was habit, not intent: 4a333b5 (#208) re-adopted the library and typed an
exact version with no reason recorded anywhere in the repo.

It now tracks the version that actually constrains it. SahajCloud pins `payload`
to exactly 3.90.2, and this library merges a message that CMS mints, so trailing
it by two minors of one upstream monorepo had nothing behind it.

Both dists are byte-identical between 3.88.0 and 3.90.2 — `@payloadcms/live-preview-react`
and its only dependency `@payloadcms/live-preview` both diff empty — so this is
version identity and no behaviour. The lockfile gains no transitive.

The pin stays exact, and `docs/rules/data-layer.md` now says why: a caret would let
a fresh resolve carry the merge semantics ahead of the CMS that produces them.

Co-Authored-By: Claude Opus 5 <[email protected]>
Claude-Session: https://claude.ai/code/session_01ACFLPqetwEAjT37C9D5pWD
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