Skip to content

perf(api): cache, usage and purge coverage for /api/globals reads - #777

Merged
Ardnived merged 17 commits into
mainfrom
claude/perf-710-globals-cache
Sep 15, 2026
Merged

Ardnived merged 17 commits into
mainfrom
claude/perf-710-globals-cache

Conversation

@sydevs-bot

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

Copy link
Copy Markdown
Contributor

Summary

  • GET /api/globals/<slug> is now edge-cacheable for the six client-read globals, tagged and purged on write.
  • A client read of a global is now metered, origin-enforced and select-gated, like a collection read.
  • Tag purge is not Enterprise-only. Four places said it was, which made the purge credentials look optional.
  • Round 2: one cache. The consumer-revalidation half is gone, and the global gates no longer reach their surface through a cast.
  • Round 3: one list. Every cacheable slug and its TTL now live in CACHE_TTLS, collections and globals alike.

Changes

  • src/plugins/cache/policy.ts — CACHE_TTLS.collections + CACHE_TTLS.globals, both sets derived from it, plus a second matcher shape for ['api','globals',slug]
  • src/plugins/cache/index.ts — afterChange purge on CACHEABLE_GLOBALS (no delete half; globals have none)
  • src/plugins/usage/hooks.ts — ClientReadGate, the shared gate shape, plus onlyOnCallerAuthority
  • src/plugins/usage/usagePlugin.ts — the four gates declared once, registered on collections and globals

The caching system today, as asked on cache/index.ts

There are two caches between an editor's save and a visitor's screen. Only one of them is ours.

# Cache Lives TTL Invalidated by
1 Cloudflare edge, in front of Railway the sydevelopers.com zone 600s (s-maxage) a Cache-Tag purge on every write — cachePlugin, this repo
2 WeMeditateWeb's KV, a read-through layer over its own CMS reads that Worker 24h nothing. Its TTL expires, and that is all

Cache 2 is why this PR carried a second set and an outbound call: a tag purge cannot reach another
Worker's KV, so a wm-web-config edit could keep serving for a day. That is now answered by
removing our half rather than by wiring it up
, because cache 2 should not exist.

A Worker's fetch() to a hostname on a different Cloudflare zone
reads through that zone's cache.
So once the Cache Rule below covers /api/globals/, WeMeditateWeb's subrequests hit cache 1 — the
one this repo purges on write. Its own KV copy then buys a longer TTL and nothing else, at the cost
of being the only cache in the system with no invalidation path. The same argument covers the
collection reads it caches (pages, meditations, lectures, songs): those ten slugs are already in
cache 1.

Dropping it is a change in sydevs/WeMeditateWeb, filed as
WeMeditateWeb#98
, blocked by #710. The
accepted limitation, stated plainly: a miss then costs a Railway round trip every 600s per colo,
instead of once a day globally.

Review round 3 (Ardnived)

Thread Outcome
policy.ts:74 — list the cacheable slugs in CACHE_TTLS? And should everything be cached? Adopted (3304b64) for the restructure. The second question is answered and left open — see below.
policy.ts:161 — is this comment necessary? Adopted (526c818). No. The two match shapes are two bullets now.
purge.ts:17 — belongs in the docs, not in code Adopted (4dc02e6). DEPLOYMENT.md § Edge Cache already carried it in more detail.
revalidateConsumers.ts:7 — file the WeMeditateWeb ticket Done. WeMeditateWeb#98.

What 3304b64 restructures

CACHE_TTLS was a collection slug → TTL map, and CACHEABLE_GLOBALS a bare Set beside it. So a
global had nowhere to carry a TTL and matchCacheableRead hard-coded DEFAULT_SMAXAGE for one.

CACHE_TTLS now has a collections half and a globals half, each a slug → TTL map, and
CACHEABLE_SLUGS and CACHEABLE_GLOBALS are both Object.keys of their half. One place lists a
cacheable read; nothing can drift from it. ttlForGlobal mirrors ttlForSlug and feeds the matcher.

The two halves stay separate rather than becoming one flat map, for two reasons: they are two URL
shapes (/api/<slug> against /api/globals/<slug>), and only a collection slug may be tagged by a
custom endpoint — CacheableSlug keys off collections alone, so publicReadCacheHeaders still
cannot tag a global.

What the new spec proves, and what it does not. All six globals sit at DEFAULT_SMAXAGE today,
so asserting the matcher's TTL does not distinguish the map from a constant by value. It is the
guard for the first per-global override: patching one entry to 42 and reverting the matcher to
DEFAULT_SMAXAGE reds it, and reds nothing else.

Caching everything, and whether it can disturb the CMS

Four things keep the CMS out of the cache today, and none of them is the allowlist:

  1. The Cache Rule matches only a GET carrying a non-empty Authorization header. The admin panel
    authenticates by cookie, so no admin read can match it (DEPLOYMENT.md:86-97).
  2. createAccessConfig constrains clients reads to _status: published, so anything cacheable is
    published-only. Drafts are unreachable, not merely uncached.
  3. A live-preview read carries x-sahajcloud-preview-secret, excluded by the rule and served
    private, no-store by the app as well.
  4. Vary: Authorization with vary.authorization = passthrough keys a separate variant per API key.

So the allowlist is not what protects the CMS. What it protects against is a new collection
holding per-caller or personal data being cached before anyone reviews it — users, clients and
managers are excluded today by being absent, not by a rule. Opt-out would invert that default.
My recommendation is to keep opt-in; widening it is a change worth its own ticket rather than a
line in this one. Say the word either way.

Preview

https://sahajcloud-sahajcloud-pr-777.up.railway.app — rebuilding on this push.

Contract impact

This changes what an existing API client sees on a global read, intentionally (question 1 in the ticket):

  • It counts against the daily quota, once per top-level read.
  • It must send select, or 400; and populate at effective depth > 1.
  • It is origin-enforced: a non-empty allowedDomains now applies, else 403.

All three readers we can see already send select — WeMeditateWeb/server/cms-client.ts,
SahajAtlasWeb/src/config/api/fetch.ts. WeMeditateApp is outside this loop's repository access
and must be checked by hand
, per the ticket's remaining open question, and per the still-open
thread on usagePlugin.ts:86.

Test results

  • Lean gate: ✓ lint, typecheck (src + tests), 1974 unit tests
  • Targeted spec: tests/int/globals-client-reads.int.spec.ts — 11 passed (9 local-API, 2 REST)
  • origin/main merged in (28f0ed4), gate re-run green after it
  • Build: N/A (Railway builds the preview)

The two REST cases are what carry the refactor: they drive handleEndpoints with a real client key
and supply no overrideAccess, so they are the only place the gates are observed reaching a live
request through the new wiring.

Manual verification

Everything below needs credentials or a dashboard this session cannot reach.

  1. Add one starts_with "/api/globals/" term to the existing Cache Rule's path group — "Client read edge cache (Vary: Authorization)". Nothing caches without it, and the argument for dropping WeMeditateWeb's KV rests on it. Never a second rule: it would not carry the Authorization-present condition and would reopen the cached-403 bypass (DEPLOYMENT.md:86-97).
  2. Confirm CLOUDFLARE_ZONE_ID and CLOUDFLARE_CACHE_PURGE_TOKEN are set on the Railway production service, and that the token's scope includes cache purge. Unset, every purge in this PR — and the ten collections' existing purges — is a silent no-op.
  3. Against the preview, with a client key: curl -sI -H "Authorization: clients API-Key <key>" "$URL/api/globals/sy-atlas-config?select[availableLocales]=true" shows the three headers.
  4. Against production after step 1: the same request twice shows MISS then HIT; an admin edit then a third request shows MISS again. That is the end-to-end proof tag purge works on our plan.
  5. The same request without Authorization still returns 403 and cf-cache-status: DYNAMIC.

Review round 2 (Ardnived)

Thread Outcome
revalidateConsumers.ts:7 — drop the KV layer, rely on the edge? Adopted (a45b20b). Our half is deleted; the consumer half is now WeMeditateWeb#98.
cache/index.ts:70 — unify the two sets Adopted (a45b20b). CACHEABLE_GLOBALS is now the only set.
env/server.ts:159 — connect to KV directly instead? Answered, then moot (a45b20b). Both env vars are gone.
usage/hooks.ts:89 — rework rather than add this Reworked (589a0ec), one question open. The cast is gone; the overrideAccess exemption remains, and whether it stays is your call.
What rounds 1 and 2 changed, and the open questions they left

What a45b20b removes, and why nothing regresses

revalidateConsumers.ts, CONSUMER_CACHED_GLOBALS, WEMEDITATE_REVALIDATE_URL,
WEMEDITATE_REVALIDATE_SECRET, and the union wiring. The integration was inert without both env
vars and WeMeditateWeb never shipped the endpoint, so removing it restores today's behaviour rather
than changing it. What it removes is coupling: a second hard-coded list of another repo's cached
slugs, an outbound call from the CMS to a consumer, and a shared secret to rotate.

What 589a0ec reworks

asGlobalBeforeOperationHook was one line of substance — hook as unknown as GlobalBeforeOperationHook — wrapped in forty lines explaining why the cast was safe. A double
cast asserts an agreement instead of checking it
: if payload changed either signature, that file
would keep compiling and start misbehaving.

The rework names the subset the gates actually read — args, operation, overrideAccess, req,
all present on both of payload's argument types — as ClientReadGate. A gate typed that way is
directly assignable to CollectionBeforeOperationHook and to GlobalBeforeOperationHook, so
tsc now checks both registration sites that the cast used to silence. The four gate bodies are
unchanged apart from reading args through readOperationArgs, since payload declares it optional
on the global signature.

Open question 1 — the overrideAccess exemption

What survives 589a0ec is onlyOnCallerAuthority — a global read runs the gates only when
overrideAccess === false, i.e. when it is the caller's own read and not one of ours. A collection
read gets this from the numeric currentDepth payload attaches to population; a global read has no
such signal, and this repo makes several internal findGlobal calls that forward the caller's
req.

If that exemption is the part that reads wrong, the alternatives are both worse, and I would rather
you pick than guess:

Open question 2 — WeMeditateApp

The select gate reaches WeMeditateApp, which reads wm-app-config and wm-app-translations and
which no one in this loop can see. Confirm its reads send select before merge, or drop those two
slugs from the gate until it is confirmed.

Review round 1 (adversarial review)

Thread Outcome
usage/hooks.ts:141 — the gates rest on a default nothing exercises Adopted (60f73ef). Two cases drive handleEndpoints and supply no overrideAccess.
cache/index.ts:71 — revalidation gated on edge-cacheability Superseded by a45b20b. There is one set now, so the union it added is gone with it.
purge.ts:12 — comments narrate the removed belief Adopted (3874a80), and finished in 4dc02e6 — the note now lives only in DEPLOYMENT.md.
usagePlugin.ts:86 — the select gate reaches WeMeditateApp unchecked Open — your call. See open question 2.
revalidateConsumers.ts:59 — an integration with no scheduled consumer Resolved by removal (a45b20b).

Detail

The cache miss was structural, not a missing slug. matchCacheableRead accepted ['api', slug] and ['api', slug, <numeric id>]. A global read is three segments with a non-numeric third, so it returned null and the middleware exited before setting any header. Adding globals to CACHEABLE_SLUGS would have matched nothing — segments[1] is the literal string globals.

wm-app-status is excluded from caching on purpose. It is an operator readiness report read in the admin over cookie auth, with computed fields. It stays DYNAMIC, the fail-safe direction. It is still gated, which costs nothing: a client cannot read it anyway.

The §3 warning is settled, by behaviour not by types. A global read reports operation: 'read' — payload's global HookOperationType is 'countVersions' | 'read' | 'restoreVersion' | 'update', and findOneOperation passes 'read'. The integration spec asserts it through the select gate, which can only refuse the read if it saw that literal.

Why overrideAccess is a sound discriminator. Payload's REST handler for a global passes a closed list of nine args and overrideAccess is not among them, so it defaults to false (findOne.js:11, and line 24 hands the defaulted value to the hook). The local API defaults it to true. It is unsettable over REST, so it cannot be forged by a caller. That default is pinned by behaviour, not by reading payload's source: the REST default for overrideAccess drives handleEndpoints with the client's API key and supplies nothing, so a bump that changes it reds the spec instead of silently disarming the gates.

It also fails safe in the right direction: a new internal findGlobal is exempt automatically, and a new REST-reachable path is gated automatically.

Every assertion was watched failing at its own site, twice over for the matcher: removing the globals branch reds the "matches" cases, while an over-broad branch with no slug allowlist and no exact-segment guard reds the "returns null" ones. One defect cannot red both.

The max-age note from the ticket stands and is out of scope: buildCacheHeaders emits max-age equal to s-maxage, so a browser holds its own copy for 600s and no purge reaches it. Tolerable at this TTL, and changing it would affect the ten cacheable collections too.

Security review run despite securityReview.triggerPattern not matching these paths, since the diff touches an authorization gate. No HIGH or MEDIUM findings. Rounds 2 and 3 only remove surface: an outbound integration, two env vars, a type cast, and two narrative comments. Note the change can only tighten access on globals, which carried no gates at all before.

Closes #710

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

🤖 Generated with Claude Code

https://claude.ai/code/session_0189pNQL3TV9qFhF5qderCBQ

`matchCacheableRead` accepted only `['api', slug]` and
`['api', slug, <numeric id>]`, so `/api/globals/<slug>` — three segments
with a non-numeric third — returned null and the middleware exited before
setting any header. Adding `globals` to `CACHEABLE_SLUGS` would have done
nothing, since `segments[1]` is the literal string `globals`. The miss was
structural, so this adds a second shape rather than a slug.

`CACHEABLE_GLOBALS` holds the six client-read globals at `DEFAULT_SMAXAGE`.
`wm-app-status` is excluded on purpose: it is an operator readiness report
read over cookie auth, with computed fields, so it stays DYNAMIC.
`/api/globals/<slug>/versions` keeps returning null — a versions read
carries drafts.

Also corrects two comments that asserted tag purge needs Cloudflare
Enterprise. It has been available on every plan since April 2025, and that
stale belief is why purge-on-write was treated as optional polish: unset
credentials make every purge in this plugin a silent no-op.

Refs #710

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

`cachePlugin` mapped `config.collections` only, so a global's write purged
nothing. Globals have no delete, so this is an `afterChange` half only —
which also covers `publishSpecificLocale`, the write that matters most
here: a client read is published-only and merged with English, so
publishing one locale changes what every client sees.

The edge cache is the one invalidation point every consumer shares, but
WeMeditateWeb keeps a second copy — a read-through KV layer at 24h for
`web-config:*` and `web-translations:*`, which no tag purge can reach. So a
write to a `wm-web-*` global also POSTs the slug to that site's own
invalidation endpoint. The consumer owns its keys and its locale set;
hard-coding its key format here was the alternative, and a silent mismatch
in it would look exactly like a working purge.

Both calls are best-effort and non-throwing, and inert without their env
vars — so this is a no-op until WEMEDITATE_REVALIDATE_URL and
WEMEDITATE_REVALIDATE_SECRET are set and WeMeditateWeb ships the route.

Refs #710

Co-Authored-By: Claude Opus 5 <[email protected]>
Claude-Session: https://claude.ai/code/session_01KgJEcyvxgZ8Z8xj3biVtKs
`usagePlugin` mapped `config.collections` only, so `GET /api/globals/*` was
unmetered, outside origin enforcement, and exempt from the `select` gate —
while every atlas widget boot on every host page and every WeMeditateWeb
request reads its config and its translations from a global.

The four hooks read only `args`, `operation` and `req`, never the config
argument, so one adapter re-types them rather than duplicating the bodies.
Two copies would let origin enforcement or the select gate drift between a
collection read and a global read, which is the divergence this closes. The
order is now declared once and shared, for the same reason.

A global read reports `operation: 'read'`, confirmed against payload's
global `HookOperationType` and `findOneOperation`, so the two gates keyed on
that literal fire rather than metering nothing.

The adapter carries one exemption. A collection hook skips an internal read
through the numeric `currentDepth` payload attaches to relationship
population; a global read has no such signal, and this codebase makes
several internal global reads that forward the caller's req. Left ungated,
`clientEnglishFallback`'s own English re-read would be refused 400 for
passing no `select` — silently disabling the fallback for every client read
of a translations global — and `loadAppConfigOnce` and the atlas endpoints
would each be metered twice. `overrideAccess` separates the two exactly:
payload's REST handler for a global never passes it, and the local API
defaults it to true, so it cannot be set by a caller over REST.

Refs #710

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

Each assertion was watched failing against a defect reintroduced at its own
site, then restored — twice over, because the matcher's two failure
directions need opposite defects: removing the globals branch reds the
"matches" assertions, and an over-broad branch with no slug allowlist and no
exact-segment guard reds the "returns null" ones.

The integration spec settles the one claim #710 could not settle from the
checkout: a global read reports `operation: 'read'`, asserted through
behaviour rather than by reading payload's types, since the select gate can
only refuse the read if it saw that literal.

⚠ It reads with `overrideAccess: false`, which is not the convenience it is
in the collection specs. The adapter uses that flag as its internal-read
exemption, so a spec omitting it would get payload's local-API default of
true and every gate would correctly skip — four vacuous assertions. A final
case asserts the other half: an internal read, which arrives true, is
neither metered nor refused.

Refs #710

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

Four places asserted that Cache-Tag purge needs Cloudflare Enterprise —
policy.ts, purge.ts twice, and DEPLOYMENT.md. It has been available on every
plan since April 2025. The correction matters beyond wording: under the old
belief the purge credentials read as optional polish for a plan we do not
have, so purge-on-write was plausibly dead in production for as long as the
plan was not Enterprise. DEPLOYMENT.md now says to confirm both variables are
set, and .env.example documents them rather than leaving them unlisted.

Adds the `starts_with "/api/globals/"` Cache Rule term to DEPLOYMENT.md, with
the standing warning about why it belongs in the existing rule's path group
and never in a second rule.

docs/rules/api-clients.md carries the client-facing contract change — a
global read is now metered, origin-enforced and select-gated — and the
adapter's overrideAccess exemption, including the note that a spec must pass
`overrideAccess: false` or it asserts nothing.

Refs #710

Co-Authored-By: Claude Opus 5 <[email protected]>
Claude-Session: https://claude.ai/code/session_01KgJEcyvxgZ8Z8xj3biVtKs
Four findings, all in tests:

- The int spec's operation-literal case was byte-identical to the select-gate
  case beside it, so it could never fail independently. Its claim now rides
  the select-gate assertion, which is what actually carries it.
- cache-policy's two globals loops overlapped: given the spelled-out list and
  the size check, the second could not fail. One set-equality assertion now
  pins both drift directions.
- The purge spec's second slug was a whole extra `it` for one data point, and
  `CONSUMER_CACHED_GLOBALS` was exported but imported nowhere. The spec now
  loops the exported set, which removes the duplicate list and gives the
  export its consumer.

Each consolidated assertion was re-watched failing — a slug dropped from
`CACHEABLE_GLOBALS` and from `CONSUMER_CACHED_GLOBALS` reds three of them.

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

railway-app Bot commented Sep 13, 2026 •

Copy link
Copy Markdown

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

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

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

sydevs-bot commented Sep 13, 2026 •

Copy link
Copy Markdown
Contributor Author

🤖 no session running

recent dispatches
  • 23:46Z address-review · attempt 1 · session · done
  • 23:46Z address-review · attempt 1 · session
  • 04:26Z address-review · attempt 1 · session · done
  • 04:26Z address-review · attempt 1 · session
  • 22:01Z address-review · 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

The diff matches #710's shape and size. Two things sit outside it: a consumer integration with no consumer, and #710's WeMeditateApp question, which shipping answers by default. The cache half is pinned tightly; the usage half rests on an assumption no test reaches.

Findings

  • blocker — usage/hooks.ts:141: every gate hinges on overrideAccess === false; each spec supplies that flag itself.
  • should-fix — usagePlugin.ts:86: the select gate reaches WeMeditateApp unchecked.
  • should-fix — revalidateConsumers.ts:59: an integration with no scheduled consumer.
  • consider — cache/index.ts:71: revalidation gated on edge-cacheability.
  • consider — purge.ts:12: comments narrate the removed belief.

Checked. All five cache files, four gates in usage/hooks.ts, usagePlugin.ts, both specs. Both reachable consumers send select (WeMeditateWeb/server/cms-client.ts:514,623, SahajAtlasWeb/config/api/fetch.ts:731,752); WeMeditateApp is not. No node_modules here, so payload's default is unverified.

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


Generated by Claude Code

Comment thread src/plugins/usage/hooks.ts Resolved
// and every atlas widget boot and WeMeditateWeb request reads one.
// `exclusions` names collections only, and no global is a Payload system
// collection, so every global is wrapped.
globals: config.globals?.map((global) => ({

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.

This is where the select gate goes live for WeMeditateApp, which reads wm-app-config and wm-app-translations and which no one in this loop can see. #710's open question was whether to gate globals from day one or after checking that app. The PR body still lists that check as outstanding, so shipping answers the question by default, and the failure mode is a 400 at app boot.

Confirm before merge, or leave the two wm-app-* globals out until it is?

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


Generated by Claude 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.

Asking, not guessing — this is the reviewer's call.

Shipping as-is answers #710's open question by default, and the failure mode is a 400 at WeMeditateApp boot. No one in this loop can read that app to check.

Two options: confirm its wm-app-* reads send select before merge, or drop those two slugs from the gate now and add them once confirmed. Say which and I will make it so.

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


Generated by Claude Code

Comment thread src/plugins/cache/index.ts Resolved
Comment thread src/plugins/cache/purge.ts Resolved
@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 13, 2026
Every case in the spec supplied `overrideAccess: false` itself, so the
suite proved the adapter and said nothing about what payload hands it on
a real request. A default of `undefined` — today or after a bump — makes
`asGlobalBeforeOperationHook` return early, all four gates no-op, and
#710 ships inert with every assertion still green.

Two cases now drive `handleEndpoints`, payload's own REST entry point,
authenticated with the client's API key and supplying nothing: a read
with no `select` must be 400, and the same read with one must be 200.

Watched failing at its own site: patching `findOne.js`'s
`overrideAccess = false` default to `undefined` reds the no-select case
and leaves all nine local-API cases green — which is precisely the blind
spot, demonstrated.

Co-Authored-By: Claude Opus 5 <[email protected]>
Claude-Session: https://claude.ai/code/session_01B17W6T1CMHWFk1VhvTUJj9
The globals write hook attached on `CACHEABLE_GLOBALS` alone, so
WeMeditateWeb's KV revalidation rode on whether *we* cache the read at
the edge. The two properties are unrelated: dropping `wm-web-config` to
DYNAMIC later would silently stop the consumer's purge as well.

Attach on the union of `CACHEABLE_GLOBALS` and
`CONSUMER_CACHED_GLOBALS`, and let each invalidation answer to its own
set inside the hook.

The guard is written against the sets, not a literal list. Today the
consumer set is a subset, so the union equals `CACHEABLE_GLOBALS` and
the assertion cannot tell them apart — it reds only on the drift it
exists for, confirmed by dropping `wm-web-config` from
`CACHEABLE_GLOBALS` against the old wiring.

Co-Authored-By: Claude Opus 5 <[email protected]>
Claude-Session: https://claude.ai/code/session_01B17W6T1CMHWFk1VhvTUJj9
Three comments narrated the belief they had just removed — "and this
file used to say it was", "whatever older comments in this repo used to
say", and DEPLOYMENT.md's paragraph on what the old belief implied. The
rule reads fine without it: tag purge works on every plan, so these
credentials are the invalidation path. The issue number carries the
story.

Co-Authored-By: Claude Opus 5 <[email protected]>
Claude-Session: https://claude.ai/code/session_01B17W6T1CMHWFk1VhvTUJj9
Both were claims the code now makes and the guides did not: that a spec
supplying `overrideAccess` proves only the adapter, and that a
consumer's own cache is a set independent of edge-cacheability.

Co-Authored-By: Claude Opus 5 <[email protected]>
Claude-Session: https://claude.ai/code/session_01B17W6T1CMHWFk1VhvTUJj9
@railway-app
railway-app Bot temporarily deployed to sahajcloud / SahajCloud-pr-777 September 13, 2026 22:11 Destroyed
@sydevs-bot

Copy link
Copy Markdown
Contributor Author

Review round 1 addressed — pushed 18d5a81. Three adopted, two need your call.

Adopted

Open — two decisions I will not guess

  • WeMeditateApp: confirm its wm-app-* reads send select, or drop those slugs from the gate.
  • The consumer half: approve the WeMeditateWeb ticket and I will file it.

Lean gate green.

🤖 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 13, 2026
@sydevs-bot
sydevs-bot marked this pull request as ready for review September 13, 2026 22:20
@sydevs-bot
sydevs-bot requested a review from Ardnived September 13, 2026 22:20
Comment thread src/lib/env/server.ts Resolved
Comment thread src/plugins/cache/index.ts Resolved
Comment on lines +89 to +144
// ============================================================================
// GLOBAL ADAPTER
// ============================================================================

/**
* Re-types a collection `beforeOperation` hook as a global one, so the same
* four gates run on a global read (#710), and adds the one operation-shaped
* exemption a global needs.
*
* The two signatures differ in exactly one property: a collection hook gets
* `collection: SanitizedCollectionConfig`, a global hook gets
* `global: SanitizedGlobalConfig`. Every hook in this file reads only `args`,
* `operation` and `req` — never the config argument — so each is already
* structurally a valid global hook. (`args` is optional on the global
* signature and required on the collection one; payload always passes it.)
*
* Two things make it safe to share a body rather than write a second one:
*
* - **`operation` is the same literal.** A global read reports
* `operation: 'read'`, like a collection's (payload's global
* `HookOperationType` is `'countVersions' | 'read' | 'restoreVersion' |
* 'update'`, and `findOneOperation` passes `'read'`). The two gates that
* return early unless `operation === 'read'` therefore fire, rather than
* silently metering nothing.
* - **One definition, two surfaces.** Duplicating the bodies would let origin
* enforcement or the `select` gate drift between a collection read and a
* global read, which is exactly the divergence #710 exists to close.
*
* ## ⚠ The `overrideAccess` exemption, and why a global needs its own
*
* A collection hook skips an internal read through the numeric `currentDepth`
* payload attaches to relationship population. **A global read has no such
* signal** — `findGlobal` never sets `currentDepth` — and this codebase makes
* plenty of internal global reads that forward the caller's `req`:
* `clientEnglishFallback` re-reads its own global in English,
* `loadAppConfigOnce` reads `wm-app-config` while serving a page, and the
* atlas endpoints read `sy-atlas-config` for locales and canonical ownership.
* Without an exemption, each would be metered a second time, and the ones that
* pass no `select` would be refused 400 — silently disabling the English
* fallback for every client read of a translations global.
*
* `overrideAccess` separates the two exactly. Payload's REST handler for a
* global never passes it, so a client's own read arrives `false`; the local
* API defaults it to `true`, so every `payload.findGlobal()` in our server
* code arrives `true`. It is unsettable over REST, which is what makes it
* sound for the origin gate as well as the meter: an internal read runs on our
* authority, inside a top-level request the gates already cleared.
*/
export function asGlobalBeforeOperationHook(
hook: CollectionBeforeOperationHook,
): GlobalBeforeOperationHook {
return (args) => {
if (args.overrideAccess !== false) return
return (hook as unknown as GlobalBeforeOperationHook)(args)
}
}

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.

This does not feel like a good change. Consider in depth how we could rework / refactor our code instead to avoid adding this

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.

Reworked in 589a0ec. The as unknown as cast is gone. The four gates are typed ClientReadGate — the argument subset both of payload's hook signatures satisfy — so tsc checks each registration instead of an assertion standing in for it. Bodies unchanged, 11/11 int cases pass.

What survives is the overrideAccess exemption. If that is what you object to, the PR body has the two alternatives. Your pick.

🤖 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 14, 2026
@railway-app
railway-app Bot temporarily deployed to sahajcloud / SahajCloud-pr-777 September 14, 2026 04:38 Destroyed
@sydevs-bot

Copy link
Copy Markdown
Contributor Author

Round 2 addressed — pushed 28f0ed4. Your three cache threads had one answer, so they got one change.

Adopted

  • Drop the KV layer, and unify the two sets → a45b20b. revalidateConsumers.ts, CONSUMER_CACHED_GLOBALS and both env vars are deleted. One set, one cache, one invalidation point. Nothing regresses — it was inert without the env vars.
  • Rework the adapter → 589a0ec. The as unknown as cast is gone; tsc now checks what it asserted.

Open — two decisions I will not guess

  • The overrideAccess exemption that survives the refactor. Alternatives are in the PR body.
  • WeMeditateApp: confirm its wm-app-* reads send select, or drop those two slugs.

The PR body explains the caching system, as you asked. Two caches; only the edge one can be invalidated. Dropping WeMeditateWeb's KV is a ticket there — approve and I file it.

🤖 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. awaiting labels Sep 14, 2026
Comment thread src/plugins/cache/policy.ts Outdated
Comment on lines +74 to +97
/**
* Cacheable **global** slugs — the client-read configuration and translation
* globals, every one of which a widget or site fetches on boot (#710). They all
* use {@link DEFAULT_SMAXAGE}; there is no per-global override, because these
* are edited at the same low frequency and nothing has asked for a second rate.
* Like {@link CACHEABLE_SLUGS}, this is also the set whose writes purge.
*
* The `Cache-Tag` is the global's own slug, exactly as it is for a collection.
* The two namespaces cannot collide — every global here is `wm-*` or `sy-*`,
* and no collection slug takes either prefix.
*
* ⚠ **`wm-app-status` is deliberately absent.** It is an operator readiness
* report, read in the admin over cookie auth, and it carries computed fields.
* It stays `DYNAMIC`, which is the fail-safe direction. Add a global here only
* when a client genuinely reads it and its contents are published-only.
*/
export const CACHEABLE_GLOBALS: ReadonlySet<string> = new Set([
'wm-web-config',
'wm-web-translations',
'wm-app-config',
'wm-app-translations',
'sy-atlas-config',
'sy-atlas-translations',
])

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.

Would it make more sense to restructure so that the list of cachable slugs are listed in CACHE_TTLS?

Or would it even make sense to ensure that all collections and globals are cached via the API? How can we ensure that this caching doesn't interfere with the proper functioning of the CMS?

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.

Restructured in 3304b64 — CACHE_TTLS now has a collections and a globals half, both slug → TTL maps, with both sets derived from it.

Caching everything: the CMS is already clear. The Cache Rule requires Authorization, so admin cookie reads never match, client access is published-only, preview gets no-store. The bar is per-key data. Opt-in keeps users, clients and managers out; opt-out caches the next such collection unnoticed. Widening is a ticket.

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


Generated by Claude Code

Comment thread src/plugins/cache/policy.ts Resolved
Comment thread src/plugins/cache/purge.ts Resolved
@sydevs-bot sydevs-bot added the bot:working Lock: a cloud session is running on this item. Removed when it ends. label Sep 14, 2026
DEPLOYMENT.md § Edge Cache already states the plan support, the token
scope, and what an unset pair costs, in more detail than the comment did.
The docblock now points there instead of restating it, so the fact has one
home to keep current.

Co-Authored-By: Claude Opus 5 <[email protected]>
Claude-Session: https://claude.ai/code/session_0189pNQL3TV9qFhF5qderCBQ
The matchCacheableRead docblock argued why a global read is a second path
shape rather than a slug addition. That reasoning is history, not a rule a
reader needs: the two shapes are now listed as two bullets.

Co-Authored-By: Claude Opus 5 <[email protected]>
Claude-Session: https://claude.ai/code/session_0189pNQL3TV9qFhF5qderCBQ
CACHEABLE_GLOBALS was a bare Set beside a TTL map, so globals had no place
to carry a TTL and the matcher hard-coded DEFAULT_SMAXAGE for them.

CACHE_TTLS now has a `collections` and a `globals` half, each a slug -> TTL
map. Both sets derive from it, so a cacheable read is listed in exactly one
place with its TTL, and the sets cannot drift from it. The halves stay
separate because they are two URL shapes, and only a collection slug may be
tagged by a custom endpoint -- CacheableSlug keys off `collections` alone.

ttlForGlobal mirrors ttlForSlug and feeds matchCacheableRead. All six
globals sit at DEFAULT_SMAXAGE today, so the new spec does not distinguish
the map from a constant by value; it is the guard for the first per-global
override, and reds when one is added and the matcher ignores it.

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

Copy link
Copy Markdown
Contributor Author

Round 3 — pushed 3304b64. Three adopted, one question back, ticket filed.

Adopted

Filed

Open — your call

  • Cache everything, or keep the allowlist? The body gives four reasons the CMS is safe from caching already. The allowlist guards a future personal-data collection, not the admin. I would keep opt-in.
  • From round 2: the overrideAccess exemption, and WeMeditateApp's reads.

Lean gate green: lint, typecheck, 1974 tests.

🤖 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 14, 2026
@sydevs-bot sydevs-bot moved this from Revising to Approved in SYDevelopers Technical Roadmap Sep 15, 2026
@Ardnived
Ardnived merged commit 26bee73 into main Sep 15, 2026
46 of 50 checks passed
@Ardnived
Ardnived deleted the claude/perf-710-globals-cache branch September 15, 2026 01:10
@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
…777 made them cacheable (#785)

`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]>
Ardnived added a commit that referenced this pull request Sep 16, 2026
* 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]>

* 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)!: 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]>

* 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]>

* 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]>

---------

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-777 — 3304b641 Deployed Sep 14, 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.

perf(api): cache, usage and purge coverage for /api/globals reads

3 participants