Skip to content

feat(fields): declarative live-preview targets, repointed by the open tab - #773

Merged
Ardnived merged 11 commits into
mainfrom
claude/feat-708-preview-targets
Sep 15, 2026
Merged

Ardnived merged 11 commits into
mainfrom
claude/feat-708-preview-targets

Conversation

@sydevs-bot

@sydevs-bot sydevs-bot commented Sep 12, 2026 •

Copy link
Copy Markdown
Contributor

Summary

  • A tab can declare where Live Preview points, as data — so a translator edits each string on the screen it appears on.
  • The four hand-rolled live-preview call sites in the Meditations frame editor now go through that one mechanism.
  • The frame-editor playhead no longer accepts a postMessage from any origin. It timestamps inserted frames.

Changes

  • src/fields/previewTargetField.ts — a zero-height ui field carrying { path?, params?, autoOpen? } in admin.custom. admin.livePreview.url runs on the server and never sees the open tab; a field inside a tab mounts exactly while that tab is open.
  • src/components/admin/PreviewTarget/ — the component that applies it, and composeTargetUrl, which rewrites the server-resolved URL rather than composing one. The declaration ships to the browser, so it holds no origin and no credential: the origin is inherited, and a target that would land on another origin is refused.
  • src/fields/translationsField.ts + both translationsSchema.json — preview beside screenshot, injected as the tab's first field.
  • Both translations globals gain a livePreview.url. Each reads locale and never data, each points at a page that renders with no document, and neither sends a preview secret.
  • src/components/admin/FrameEditor/ — autoOpen replaces useLivePreviewAuto, iframeRef replaces the iframe querySelector, and each playhead subscription names the origin it will hear from.
  • src/lib/utilities/url.ts — one function, originOf. Parsing is URL.parse, the built-in that returns null rather than throwing.

Preview

Test results

  • Lean gate: ✓ pnpm lint, pnpm typecheck, pnpm typecheck:tests, pnpm test:unit (1952 unit tests), re-run after the review round
  • Targeted specs: 60 passed — translations-globals, translations-field
  • Build: N/A (Railway builds the preview)

Manual verification

  1. /admin → Sahaj Atlas → Translations: open Live Preview, then switch tabs. Search, Filters and Calendar repoint the iframe; every other tab shows the widget's own base view, and leaving a targeted tab puts it back without closing the panel.
  2. /admin → WeMeditate Web → Translations, in a non-English locale: the Map tab must land on /<locale>/map, not /map.
  3. /admin → Meditations → a meditation → Frames: the panel opens itself, a frame thumbnail seeks the preview, and the playhead still tracks while audio plays.
  4. /admin → WeMeditate App → Translations: unchanged, no panel.

Notes for reviewer

Fewer targets than the ticket lists, and here is the line I drew. A target is declared only where the view is reachable as a path. The atlas event, online, registration and share views each resolve against an entity (resolveStack in SahajAtlasWeb reads online as <region>/online, share as <event>/share), and wm-web's article, meditation and lecture tabs are document-shaped. Both need a published exemplar to point at — the ticket's own unanswered open question. Adding each later is a one-line schema edit.

A repointed panel shows PUBLISHED copy, and that is the honest state of it. Neither consumer can boot a preview session from a view path: SahajAtlasWeb's readPreviewParams returns null off /preview, and WeMeditateWeb reads secret only under pages/preview/. sydevs/SahajAtlasWeb#198 and sydevs/WeMeditateWeb#80 are the routes that would change that. Until one lands, a translator sees the real screen with its published strings, which is still the point of the ticket.

Two paths differ from the ticket, both to keep the repo's own layout rules: the field factory is src/fields/previewTargetField.ts (field factories live there), and composeTargetUrl sits beside its only consumer, since a single-consumer module under src/lib/ fails lib-boundary.spec.ts.

wm-web-config keeps its data-dependent URL. It declares no target and has no tabs to switch between, so the rule does not bind, and moving it would have cost a working home-page preview for nothing.

No breakpoint in the declaration. Nothing declares one yet; the shape has room.

No migration. A ui field creates no column, and preview never reaches the emitted JSON Schema (pinned in translations-field.int.spec.ts).

Detail

What @Ardnived's review changed. One of four adopted, three answered in thread:

  • parseUrl was a built-in with a different name — adopted in 1373bf4. URL.parse returns null instead of throwing, is standard from Node 22, and TypeScript 5.7 types it under this repo's DOM lib. originOf stays, because an opaque origin stringifies to the literal 'null' and no built-in knows that matters here.
  • The ui field's name — Payload's UIField declares name: string, not optional. It also has to be unique: a ui field takes a form-state slot at its path, and an unnamed tab does not extend that path, so Meditations' two would share one entry under a constant.
  • The playhead's per-subscription origin — the origin is env-derived, but livePreview.url runs on the server and WEMEDITATE_WEB_URL has no NEXT_PUBLIC_ prefix, so the browser cannot read it without a new client variable. The iframe's src is where the send side already takes targetOrigin. Per subscription and not module-global, because a module-global is never cleared.
  • A central URL helper — composeTargetUrl writes no parser; it is URL plus URLSearchParams, and url.ts is that central home. The duplication is real one layer out: six livePreview.url call sites hand-build ${base}/…?collection=…&id=…&secret=…. Asked in thread whether to file a ticket for a shared previewUrl() builder — outside feat(fields): declarative live-preview targets, repointed by the open tab #708.

What the critic round changed. Both findings held, and both were about the global's own URL rather than the mechanism:

  • The Atlas base URL landed on an overlay. It pointed at ${SAHAJATLAS_URL}/preview, described as the route that renders the base view. It is a document boot route: with no collection and id, the widget renders PreviewFallback — "Save this document to preview it." — inside a click-swallowing fixed inset-0 div. That is what eight untargeted tabs showed, and what every targeted tab restored to. It now points at the widget's root, and the spec refuses a document-less preview route on either global (864f540).
  • The composed URL carried the preview secret to paths nothing reads it on. No path either global's tabs compose reads a secret, and the one route that does read one is also the only one that scrubs it from the address bar (capturePreview — "the secret lives only in memory"). So the credential sat in the panel's URL for a whole editing session, with WeMeditateWeb's Sentry session replay recording the page. Both URLs now send only locale (467a9d9). composeTargetUrl stays generic: a rule stripping one named parameter on a path change would encode a consumer's routing inside a pure composer, for globals it cannot see. The invariant lives where the URL is written, checked by translations-globals.int.spec.ts.

Both new assertions were watched failing against the defect they describe, and locale is now pinned across a repoint — with secret gone it is the only parameter either URL sends, so nothing else would notice the carry-forward disappearing.

What the earlier review pass changed. Four cleanup lenses and a security review ran over the branch. Three findings held, and the first was a live defect:

  • The restore target was wrong across a tab switch. React mounts the incoming tab's field with the URL from the render it mounted in — still the outgoing tab's composed URL, because the outgoing restore has not re-rendered the provider yet. Each instance captured that as "the default", so leaving a targeted tab sent the panel to the previous tab's view. tests/unit/preview-target-component.spec.ts drives the real component over a stand-in provider and fails on the old capture; no single-mount test could see it.
  • The playhead's allowed origin was module-global and never cleared, so the document-lifetime listener kept accepting from whichever origin the last-mounted component published. Each subscription now carries its own origin.
  • The opaque-origin rule was written twice. src/lib/utilities/url.ts states it once.

Dismissed, with reasons. Extracting a shared previewUrl() builder across the ?secret=… templates in the repo — real, and outside this ticket; the one new invariant it would protect (the We Meditate URL's trailing slash) is asserted through the composition in translations-globals.int.spec.ts instead. And autoOpen on the Meditations tabs being ceremony over the deleted 3-line hook — it is the unification the ticket asked for, and it is what makes the frame tabs declare their preview behaviour the same way every other tab does.

Security review: no findings. It read the origin gate, the composer, the access-plugin project and role config, and the six existing livePreview.url call sites. It ran before the secret came out of both new URLs, which only narrows what they reach.

Closes #708

🤖 Written by the sydevs autonomous loop — see what this is

🤖 Generated with Claude Code

https://claude.ai/code/session_01BXJEVP2EB3k8oWDX2AzxgM

`admin.livePreview.url` runs on the server and receives no client UI
state, so the open tab can never reach it. This adds the one seam that
can: a zero-height `ui` field that mounts exactly while its tab is open,
carrying a `PreviewTarget` in `admin.custom`, plus the component that
applies it through `useLivePreviewContext().setURL`.

Three constraints shaped it:

- `admin.custom` and not top-level `custom` — Payload strips the latter
  from the client field config.
- It is serialized, so the declaration is data. The earlier sketch of a
  `resolve` callback cannot cross.
- It ships to the browser, so it carries neither an origin nor the
  preview secret. `composeTargetUrl` rewrites the server-resolved
  default instead, keeping its origin and query, and refuses any target
  that would move the preview off that origin.

Co-Authored-By: Claude Opus 5 <[email protected]>
Claude-Session: https://claude.ai/code/session_01LoHq9vRZQ9tBptoMqoAhou
`buildTranslationTabs` injects a preview target as a tab's first field
whenever its schema group declares one, so a translator sees the strings
on the screen they appear on.

Both translations globals gain a live-preview URL, and both read
`locale` and never `data`: Payload re-resolves a server URL whenever it
changes and overwrites the panel, so a data-dependent one would clobber
the repoint on every save. The We Meditate URL ends in a slash because a
relative target resolves against it — without it, `map` would leave the
locale prefix behind.

Targets are declared only where the view is a path. The event-, region-
and document-shaped tabs (atlas `event`, `online`, `registration`,
`share`; wm-web `article`, `meditation`, `lecture`) each need a published
exemplar to point at, which is the ticket's own open question, and
`compact`, `emails` and `errors` have no page by design. A tab with no
target inherits the global's default URL, which is the base view.

Co-Authored-By: Claude Opus 5 <[email protected]>
Claude-Session: https://claude.ai/code/session_01LoHq9vRZQ9tBptoMqoAhou
`handleMessage` checked `event.data.type` and never `event.origin`, so
any page able to reach the admin window could set the playhead that
timestamps a newly inserted frame. The send side already derived its
`targetOrigin` from the iframe; the receive side now gates on the same
origin, published from the live-preview `iframeRef`, and fails closed
with no origin published.

The other three hand-rolled live-preview call sites go with it, since
they are the same seam:

- `useLivePreviewAuto` is replaced by `autoOpen` on the Frames and Add
  New tabs, and the hook and both call lines are gone.
- `useSeekToTime` posts through the context's `iframeRef` instead of
  `document.querySelector('iframe[src*="/preview/embed"]')`, which was
  standing in for that ref and matched a URL shape only the We Meditate
  preview uses. No `querySelector` for an iframe remains in `src/`.

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

Three findings from the review pass, one of them a live defect.

**The restore target was wrong across a tab switch.** React mounts the
incoming tab's field with the URL from the render it mounted in — still
the outgoing tab's composed URL, because the outgoing restore has not
re-rendered the provider yet. Each instance captured that as "the
default", so leaving a targeted tab sent the panel to the previous tab's
view instead of the global's own URL. What we last composed is now
remembered for the panel rather than per instance, which is what tells a
URL we set apart from one Payload resolved. An instance also restores
only if it actually repointed, so an `autoOpen`-only field never
touches the URL.

`tests/unit/preview-target-component.spec.ts` drives the real component
over a stand-in provider and fails on the old capture. No single-mount
test could see this.

**The playhead's allowed origin was module-global and never cleared**, so
the document-lifetime listener kept accepting from whichever origin the
last-mounted component published. Each subscription now names the origin
it will hear from, which ties the permission to a mounted component. A
cache update arriving while nothing is subscribed is dropped — a window
of one React commit, and the playhead is only meaningful while the
editor is mounted.

**The opaque-origin rule was written twice**, once per new module.
`src/lib/utilities/url.ts` states it once: an opaque origin stringifies
to `'null'`, so two unrelated ones compare equal, and every caller here
is comparing origins to decide whether to trust something.

Also: the declared-targets unit spec no longer restates each global's
live-preview URL — the int spec composes against the real one, including
the trailing slash the We Meditate locale prefix depends on.

Co-Authored-By: Claude Opus 5 <[email protected]>
Claude-Session: https://claude.ai/code/session_01LoHq9vRZQ9tBptoMqoAhou
…s its keep

`docs/rules/admin-ui.md` carried two statements this branch made false —
that `FrameEditor` arms preview with a mount effect, and that the
playhead listener takes any message — plus the four rules the mechanism
turns on. `src/globals/AGENTS.md` gains `preview` beside `screenshot` as
a schema extension, and in the list of keywords that must never reach the
emitted JSON Schema. `src/AGENTS.md` names the new `utilities/url`.

`tests/AGENTS.md` says when a spec may boot jsdom and mount a component,
because the answer is "rarely": extract the pure part first, and keep the
DOM for what only exists between mounts. `tests/COVERAGE.md` records both
new subjects.

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

railway-app Bot commented Sep 12, 2026 •

Copy link
Copy Markdown

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

Service Status Web Updated
SahajCloud ✅ Success (View Logs) Web Sep 12, 2026 at 7:53 pm UTC
1 service not affected by this PR
  • mailpit

@railway-app
railway-app Bot temporarily deployed to sahajcloud / SahajCloud-pr-773 September 12, 2026 17:49 Destroyed
@sydevs-bot sydevs-bot added the bot:working Lock: a cloud session is running on this item. Removed when it ends. label Sep 12, 2026
@sydevs-bot

sydevs-bot commented Sep 12, 2026 •

Copy link
Copy Markdown
Contributor Author

🤖 no session running

recent dispatches
  • 21:11Z address-review · attempt 1 · session · done
  • 21:11Z address-review · attempt 1 · session
  • 19:43Z address-review · attempt 1 · session · done
  • 19:43Z address-review · attempt 1 · session
  • 18:58Z resolve-conflicts · attempt 1 · session · done

Written by the sydevs dispatcher. Sessions never edit this comment.

@sydevs-bot sydevs-bot left a comment

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🧐 Adversarial review

Right shape, and smaller than the ticket. One ui field of data, one component and one pure composer replace four hand-rolled call sites, and take useLivePreviewAuto, the iframe querySelector and the open postMessage with them.

Four of ~21 targets ship. Declaring only where a view is a path is the right line; the rest need a published exemplar.

Both consumers read. /search, /filters and /calendar match resolveStack; relative map keeps its locale prefix. One defect below.

Findings

  • should-fix — the atlas default URL lands on the widget's "Save this document to preview it." overlay.
  • consider — the composed URL carries the preview secret to paths no consumer reads.

What was checked

Ticket #708, the diff, new specs. SahajAtlasWeb main: config/preview.ts, PreviewController.tsx, shape/path.ts. WeMeditateWeb: pages/preview/*/+data.ts, sentry.browser.config.ts. Ran composeTargetUrl on both real base URLs — //host, absolute, backslash and javascript: refused, /fr/map resolves.

🤖 Written by the sydevs autonomous loop — see what this is


Generated by Claude Code

@sydevs-bot sydevs-bot added bot:working Lock: a cloud session is running on this item. Removed when it ends. and removed bot:working Lock: a cloud session is running on this item. Removed when it ends. labels Sep 12, 2026
`sy-atlas-translations` pointed Live Preview at `${SAHAJATLAS_URL}/preview`,
described as the route that renders the base view. It is not: `/preview` is a
document boot route, and with no `collection` and `id` the widget renders
`PreviewFallback` — "Save this document to preview it." — inside a
`fixed inset-0` div that swallows every click
(SahajAtlasWeb `components/preview/PreviewController.tsx`).

That URL is what the eight untargeted tabs show and what every targeted tab
restores to, so the panel was unusable everywhere a tab declared no target.

Point it at the widget's root instead, which renders the base view. `locale`
still rides along: the widget detects it from the query string first
(`i18nDetectionOptions.order`, `LOCALE_PARAM`). Nothing is lost by leaving
`/preview` — `readPreviewParams` returns null off that path, so no target a
tab composes opened a draft session either. sydevs/SahajAtlasWeb#198 is the
route that would.

The spec now refuses a document-less preview route on either targeted global.
It fails against the old URL and passes for `wm-web-translations`, which
already pointed at a rendered page.

Co-Authored-By: Claude Opus 5 <[email protected]>
Claude-Session: https://claude.ai/code/session_019uDkqfGhci6MBQfWjgq2BR
Both new translations preview URLs carried `SAHAJCLOUD_PREVIEW_SECRET`, and no
path either global's tabs can compose reads one:

- SahajAtlasWeb's `readPreviewParams` returns null off `/preview`, so `/`,
  `/search`, `/filters` and `/calendar` all ignore it.
- WeMeditateWeb reads `secret` only under `pages/preview/`, where it is
  required and a miss is a 403. A published page never looks.

The route that does read one also removes it from the address bar at boot —
`capturePreview`, "the secret lives only in memory, never in the bundle or
storage". Off that route nothing scrubs it either, so the credential sat in
the panel's URL for a whole editing session, with WeMeditateWeb's Sentry
session replay recording the page. Now neither URL sends it, and the spec
refuses both a `secret` parameter and the value appearing anywhere in the URL.

`composeTargetUrl` is left generic: it carries the default's query forward
without reading it. A rule that stripped one named parameter on a path change
would encode a consumer's routing in a pure composer, for globals it cannot
see. The invariant belongs where the URL is written, which is where it now is.

`locale` is what the query carries now, so a new case pins it across a
repoint — otherwise the carry-forward could go unnoticed.

Co-Authored-By: Claude Opus 5 <[email protected]>
Claude-Session: https://claude.ai/code/session_019uDkqfGhci6MBQfWjgq2BR
Both halves of the review are one rule, so the rule reads as one: the
`/preview` boot route is the only route that reads a preview secret, and the
only one that needs a document. A global pointed there with neither gets the
save-first overlay and a parked credential.

Also corrects the composer's contract, which said it keeps the default's
`secret` — it keeps the default's query, and no default sends a secret now.

Co-Authored-By: Claude Opus 5 <[email protected]>
Claude-Session: https://claude.ai/code/session_019uDkqfGhci6MBQfWjgq2BR
@railway-app
railway-app Bot temporarily deployed to sahajcloud / SahajCloud-pr-773 September 12, 2026 18:24 Destroyed
@sydevs-bot

Copy link
Copy Markdown
Contributor Author

Both critic findings adopted. Pushed 0fd10e3.

  • Atlas preview landed on a save-first overlay — 864f540. The base URL is the widget's root now. /preview with no document renders a click-swallowing "Save this document to preview it."
  • The composed URL carried the preview secret — 467a9d9. Neither translations URL sends secret: only a /preview route reads one, and it is the only one that scrubs it. composeTargetUrl stays generic, so the invariant sits where the URL is written.

Both threads resolved. Nothing rebutted, nothing asked.

docs/rules/admin-ui.md carries both halves as one rule (f6fe459). main merged in, lean gate green after it, translations-globals + translations-field 60 passed.

🤖 Written by the sydevs autonomous loop — see what this is


Generated by Claude Code

@sydevs-bot sydevs-bot removed the bot:working Lock: a cloud session is running on this item. Removed when it ends. label Sep 12, 2026
@sydevs-bot
sydevs-bot marked this pull request as ready for review September 12, 2026 18:32
@sydevs-bot
sydevs-bot requested a review from Ardnived September 12, 2026 18:32
@sydevs-bot sydevs-bot added awaiting bot:working Lock: a cloud session is running on this item. Removed when it ends. and removed awaiting labels Sep 12, 2026
`main` #772 replaced the hand-written client-entry list in
`tests/unit/client-bundle-safety.spec.ts` with a derived set —
`clientEntries()` over every `'use client'` file. This branch had added
`components/admin/PreviewTarget/PreviewTarget.tsx` to that list.

Took the derived set. `PreviewTarget.tsx` carries a leading `'use client'`
directive, so it is an entry automatically, and the spec's own
`misses no file TypeScript reads as a client entry` case proves that rather
than assuming it. The per-entry comment went with the list: the rule it
recorded — `@/fields/previewTargetField` is types and a plain object literal
so the declaration can cross to the browser — is already stated in that
module's own header.

Nothing else conflicted. The branch's new code imports no `@/plugins/access`
barrel, the new `SERVER_ONLY` row #772 added.

Gate after the merge: lint, typecheck, typecheck:tests, 1952 unit tests, plus
`translations-globals` and `translations-field` (60 tests) — all green.

Co-Authored-By: Claude Opus 5 <[email protected]>
Claude-Session: https://claude.ai/code/session_0158CavRbZEnPZhmp4fnCwa5
@railway-app
railway-app Bot temporarily deployed to sahajcloud / SahajCloud-pr-773 September 12, 2026 19:02 Destroyed
@sydevs-bot sydevs-bot removed the bot:working Lock: a cloud session is running on this item. Removed when it ends. label Sep 12, 2026
Comment thread src/fields/previewTargetField.ts Resolved
Comment thread src/lib/utilities/url.ts Resolved
interface Subscription {
cb: Subscriber
/** The live-preview iframe's origin, as of this subscription. */
origin: string

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Is it really necessary to store this? The live preview should always be at the same domain - which is derived from an ENV var. We've made a lot of edits to this file as a result, but they don't seem strictly needed

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

It is env-derived, but the browser cannot read it: livePreview.url runs on the server, and WEMEDITATE_WEB_URL has no NEXT_PUBLIC_ prefix (Meditations.ts:153). Using it means publishing a new client variable.

The iframe's src is where the send side already takes targetOrigin. Per subscription, not module-global: a module-global is never cleared, so it keeps accepting whichever origin last mounted.

🤖 Written by the sydevs autonomous loop — see what this is


Generated by Claude Code

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

We can switch WEMEDITATE_WEB_URL across the project to be a public variable (ie. NEXT_PUBLIC_WEMEDITATE_WEB_URL) - if that let's us reduce the amount of code

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

It costs code, not saves it — your call.

The rename is 45 references in 29 files, plus Railway and the runbook. It deletes ~12 lines here.

It cannot land gradually. The browser sees only a literal process.env.NEXT_PUBLIC_* inlined at build (#760). Rename Railway late and the playhead reads 0, so frames insert at 0:00. Rename code first and boot fails: the var is required.

Say the word and I'll do it.

🤖 Written by the sydevs autonomous loop — see what this is


Generated by Claude Code

@sydevs-bot sydevs-bot added bot:working Lock: a cloud session is running on this item. Removed when it ends. and removed awaiting labels Sep 12, 2026
`parseUrl` was a try/catch wrapper returning null on a bad URL. That is
exactly `URL.parse`, standard since Node 22 and in every browser the admin
supports, and typed by TypeScript 5.7 under this repo's DOM lib.

`originOf` stays: an opaque origin stringifies to the literal 'null', so two
unrelated ones compare equal, and every caller compares origins to decide
whether to trust something. That rule is ours, and has no built-in.

Co-Authored-By: Claude Opus 5 <[email protected]>
Claude-Session: https://claude.ai/code/session_01BXJEVP2EB3k8oWDX2AzxgM
@railway-app
railway-app Bot temporarily deployed to sahajcloud / SahajCloud-pr-773 September 12, 2026 19:50 Destroyed
@sydevs-bot

Copy link
Copy Markdown
Contributor Author

One of four adopted. Pushed 1373bf4.

Lean gate green. translations-globals + translations-field: 60 passed.

🤖 Written by the sydevs autonomous loop — see what this is


Generated by Claude Code

@sydevs-bot sydevs-bot added awaiting bot:working Lock: a cloud session is running on this item. Removed when it ends. and removed bot:working Lock: a cloud session is running on this item. Removed when it ends. awaiting labels Sep 12, 2026
@Ardnived

Copy link
Copy Markdown
Contributor

@sydevs-bot Answer: does this ticket require follow-up tickets in the other projects to support live previewing translations (as opposed to page content). If so, file those tickets now before we merge.

@sydevs-bot

Copy link
Copy Markdown
Contributor Author

Yes — two, one per consumer. Filed.

Neither can render an unsaved translation, so every repointed panel shows published copy:

Both must merge before the SahajCloud half, or the secret rides the panel's URL with no reader — the exposure 467a9d9 removed. That half is #776, blocked by both.

⚠ The body above cites sydevs/SahajAtlasWeb#198 and sydevs/WeMeditateWeb#80 as the routes that would unlock drafts. Both closed without it. #206 and #96 supersede them.

Also answered the NEXT_PUBLIC_WEMEDITATE_WEB_URL thread: 45 references in 29 files to delete ~12. Your call.

No code changed. Nothing pushed.

🤖 Written by the sydevs autonomous loop — see what this is


Generated by Claude Code

@sydevs-bot sydevs-bot added awaiting and removed bot:working Lock: a cloud session is running on this item. Removed when it ends. labels Sep 13, 2026
@sydevs-bot sydevs-bot moved this from Revising to Approved in SYDevelopers Technical Roadmap Sep 14, 2026
@Ardnived
Ardnived merged commit ce60b12 into main Sep 15, 2026
70 of 78 checks passed
@Ardnived
Ardnived deleted the claude/feat-708-preview-targets branch September 15, 2026 00:59
@sydevs-bot sydevs-bot moved this from Approved to Done in SYDevelopers Technical Roadmap Sep 15, 2026
Ardnived added a commit that referenced this pull request Sep 15, 2026
…ared 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]>
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]>

This branch was successfully deployed

No deployments
sahajcloud / SahajCloud-pr-773 — 1373bf4c Deployed Sep 12, 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.

feat(fields): declarative live-preview targets, repointed by the open tab

3 participants