Repository navigation
feat(auth): gate and seed previews behind Cloudflare Access - #1082
Conversation
A small Cloudflare Worker now sits in front of every Railway preview and is
reached at `pr-<n>.cloud-preview.sydevelopers.com`, a Workers Custom Domain
created on the PR's first push and swept a day after it closes. Cloudflare
Access runs ahead of the Worker for a Custom Domain, so a sydevs login is the
only way in.
`src/middleware.ts` widens from the cache choke point to a host plus
shared-secret-header gate. The Worker's own `fetch` to Railway carries the
Railway host too, so the header is the only proof the hop happened — it is not
an identity, which Access already settled. `/api/health` is exempt by path:
Railway's healthcheck arrives as `Host: healthcheck.railway.app` and never
traverses Cloudflare, so a host-only gate would make every preview undeployable
and the only symptom would be three failed deploys.
The matcher widens past `/api`, or `/admin` on the raw Railway host would stay
open. That widens the body Next buffers pre-auth, so `next.config.mjs`'s cap
comment now says what the matcher covers.
Never-cache needs both halves, because Workers run ahead of the cache: the
response carries `private, no-store` and the subrequest to Railway carries
`cf: { cacheTtl: -1 }`.
`getServerUrl()` returns the preview's own fixed address rather than
production's, so a sign-in link composed on a preview opens that preview — and
`ownOrigins()` gains the same address, or a reviewer's save would 403 on CSRF
while page loads kept working. Fixing either alone reproduces that 403.
`/api/health` reports the commit it is serving, which is the only field that
can: `version` is identical on every commit.
Refs #1081
Co-Authored-By: Claude Opus 5 <[email protected]>
Claude-Session: https://claude.ai/code/session_01Mg9rjX5KDEbK7EeiEzbPvZ
…s them `previewAutoSignIn` widens from one address to a boolean, so `issueMagicLink` mints a session for any account of the collection rather than comparing the caller's address against a configured one. That is what makes a manager's view checkable: #1073's promise, that an event's own manager sees their registrants and another manager is turned away, needed two accounts nobody could sign in to. `/admin/login` on a preview now lists every account with its kind, its per-locale role labels and the records it manages, read through `summarizeGrants()` with a `localeIsolatedReq`-wrapped request, one copy per row. A row submits the page's own Server Action, so the cookie and the redirect have one implementation — and nothing here builds a response carrying a `user`, whose `roles` would arrive flat and default-locale. The picker is an anonymous enumeration surface, which is the one thing `request-magic-link` refuses to be on production. `previewSignInHere()` is the only gate on it, and the same predicate turns `previewAutoSignIn` on, so the list and the sign-in it offers cannot disagree. `PREVIEW_ADMIN_EMAIL` is retired across eleven sites. The gate loses its address arm and returns a boolean; the account keeps a committed constant address, because what made the old one a credential was that nothing else decided who could ask. The smoke lane holds the `github-ci` Access service token instead, attached by `playwright.config.ts`, and a new unit spec pins its two hand-copied constants against the real ones. All three specs built on the variable are rewritten rather than deleted. Production's uniform answer is asserted through `issueMagicLink` with the option off, rather than a second environment: naming the suite `production` would also switch the mail adapter and the storage isolation over. `DEPLOYMENT.md` no longer claims the zone's cache rule is evaluated on the inbound request — through the Worker it governs the subrequest to Railway. Refs #1081 Co-Authored-By: Claude Opus 5 <[email protected]> Claude-Session: https://claude.ai/code/session_01Mg9rjX5KDEbK7EeiEzbPvZ
…when it fails A Railway PR preview forks service configuration and variables, never volume data, so it boots with one row anywhere. `seeds/preview-fixture/` is the content CI now puts in: three regions in a country → city → venue tree, two accepted managers, two published classes on real weekly schedules, six registrants, eight registrations and five contact messages across all five statuses. The seed step lives inside the existing `Lint, Test & Smoke` job and fails it when a preview was discovered and the fill did not succeed — a change can no longer admit "Data: not seeded" in a line of its own description (#1073). A PR with no preview at all still only warns. ⚠ Never a job of its own: a new job is a new check name no ruleset requires, `merge-gate.mjs` reads SKIPPED as OK, and #903 forbids renaming a required check — a split would leave this unenforced at the gate. A registration cannot be created `pending`. A created-`pending` row queues screening, a screening pass leaves it `pending`, and delivery then writes `accepted` because `registration`'s `deliveredStatus` is `accepted`. Both guards read the status at create, so the fixture authors every row with a terminal status and reaches `pending` by a second update pass; `COLLECTION_METADATA` states a `countWhere` floor for the survivor rather than trusting the count. `/api/health` reports the commit it serves and discovery now waits for it to equal the PR head SHA. `version` is identical on every commit and Railway's status proves only that the deploy started, so a PR pushed to twice in quick succession was filled and tested as the push before. `commit: unknown` is terminal rather than waited out — no amount of waiting identifies the build. `scripts/preview-domain.ts` registers the fixed address on every push and sweeps a closed PR's a day later; its decision half is pure, so the rules that matter are tested. An open PR keeps its address however old, and one whose PR GitHub did not report is left alone: never having looked is not evidence of absence. The seed CLI carries the Access service token and, against a preview, asks it to sign the provisioned admin in — so CI needs no `ADMIN_TOKEN`. That works on a preview and nowhere else, because production answers the same call with no token. Refs #1081 Co-Authored-By: Claude Opus 5 <[email protected]> Claude-Session: https://claude.ai/code/session_01Mg9rjX5KDEbK7EeiEzbPvZ
A twelfth site the ticket's table missed, and the one that still documented the address as a credential to keep unguessable. Replaced by the two variables a preview now does need, both a person's: the shared secret the Worker sends and `src/middleware.ts` requires, and the `github-ci` Access service token CI's seed and smoke steps carry. Two comments stopped naming the variable as well, so the retirement is greppable rather than nearly so. What the name carried — that it was a secret held in Railway, GitHub and the loop's settings at once, and so could not be withdrawn from one of them alone — is said in words instead. Refs #1081 Co-Authored-By: Claude Opus 5 <[email protected]> Claude-Session: https://claude.ai/code/session_01Mg9rjX5KDEbK7EeiEzbPvZ
…nt name Six findings from the branch review, three of them bypasses. Each was reproduced before the fix and each now fails a spec against the defect. **The gate checked that the header existed, not what it said.** The header's name is in this public repository and a preview's Railway host is published in an anonymously readable commit status — so `curl -H 'x-sahajcloud-preview-proxy: anything'` was served, and the very next request got an admin session, because this branch also makes the admin's address a committed constant and signs any manager in. The value is now compared, and a preview with no secret refuses everything but its health route rather than serving the admin panel to anyone. **The gate and the sign-in bypass keyed on different inputs.** The gate read a `-pr-<n>` Railway host; `managersSignInDirectly` read "any Railway name but production". A `staging` deployment — reached on a host no Worker answers for and no Access app covers — therefore published every manager's address, roles and managed records, with one-click admin sign-in beside them. Both now read `railwayEnvironmentName()` through one `pr-<n>` allowlist, so they cover one set by construction. `getServerUrl()` reads the same answer, so a deployment cannot compose links for an address nothing serves it at. That also retires the host test. It fails **open** on every shape it does not recognise — an absent `Host`, a `:port` suffix, a `railway.app` domain without `up.` — and `Host` is a header the caller writes. **The Worker proxied to any attacker-named origin.** `new URL(path, base)` treats a path beginning `//` as scheme-relative, so `//evil.example/x` replaced the authority: the shared secret, the caller's cookies and their Access assertion went to that host, and its body came back under the preview's origin. The parts are assigned instead. **The seed step would have gone red on every PR.** `getCountTargets` counts `user-submissions` under its `countWhere`, so the floor had to be the rows that filter matches — one `pending` registration — not the fixture's 13. Stated as 13 it could never pass. A new case runs the real verification, which the row-count cases could not catch. **Cloudflare's attach-domain operation is a PUT.** A POST answers 405, which would have failed the address step before any preview was reachable. Being an upsert also makes "every push runs this" free, so the error-swallowing goes — and a real hostname conflict now fails loudly instead of letting CI seed and smoke an address the Worker does not serve. The step then waits for the address to answer, because a fresh Custom Domain provisions its certificate asynchronously and everything after it assumes reachable. Also from the review: the health exemption is exact and read-only rather than a prefix on every method; the fixture refuses to run against production, warns rather than errors on a dry run's unresolved parents, and guards the `pending` pass on an id; the picker lists only accounts a click can actually sign in; `cfFetch` treats a 200 carrying `success: false` as a failure and keeps the status on a non-JSON body; discovery tells "never answered" from "kept serving an earlier commit"; and the sweep refuses an unrecognised argument and takes `--force`. Quality, same pass: one hostname parser rather than three (two of which checked no suffix, so the Worker and the sweep could disagree about which addresses are ours), one Access-header builder, one `responsibilityLabel`, and the smoke helper imports the admin address rather than mirroring it behind a spec. Refs #1081 Co-Authored-By: Claude Opus 5 <[email protected]> Claude-Session: https://claude.ai/code/session_01Mg9rjX5KDEbK7EeiEzbPvZ
|
🚅 Deployed to the SahajCloud-pr-1082 environment in sahajcloud
1 service not affected by this PR
|
sydevs-bot
left a comment
There was a problem hiding this comment.
1 question for the reviewer, one per thread.
🤖 Written by the sydevs autonomous loop — see what this is
Generated by Claude Code
|
🤖 no session running recent dispatchesWritten by the sydevs dispatcher. Sessions never edit this comment. |
|
CI is red on absent configuration, not on this change. Nothing pushed.
Two of the four values This is step 0 in the description — a person's, and no edit here can supply either value. Making the step skip when they are absent would disable the gate on every PR, which #1073 exists to prevent. So I left the tree alone. Everything ahead of it passed: lint, format:check, typecheck, typecheck:tests, 101 test files, 1821 cases, and Railway preview discovery at Set both values, then push to re-run. 🤖 Written by the sydevs autonomous loop — see what this is Generated by Claude Code |
Five conflicts, all in Markdown, all the unit lane's file and test counts: both sides added specs, so neither side's number described the merged tree. Re-measured it instead — 245 files, 3174 tests — and wrote that to PERF.md and its three consumers. scripts/AGENTS.md also conflicted on the script table. Kept both sides: main's rewritten `preview-reminder-digest-emails.ts` row (#1070), this branch's rewritten `get-railway-preview-url.ts` row and its two new `preview-domain*` rows. `src/plugins/login/magicLinks.ts` auto-merged and was checked by hand: main moved mail composition to `generateEmail`, this branch widened the auto-sign-in condition, and the merged file carries both. Co-Authored-By: Claude Opus 5 <[email protected]> Claude-Session: https://claude.ai/code/session_01Mg9rjW7RBxjZHMg885wFa3
The Format step's 15 s was measured on 2026-10-20 at `89f6569`, where the lane held 239 files. This branch's count sweep bumped that figure with the rest, which claimed the measurement came off a tree it never ran on. A row naming a commit and a date records conditions. Only the `Files / tests` row follows the tree, and the pinning spec reads only that one, so nothing caught this. Co-Authored-By: Claude Opus 5 <[email protected]> Claude-Session: https://claude.ai/code/session_01Mg9rjW7RBxjZHMg885wFa3
|
Merged
One file auto-merged where it could have gone wrong. Also pushed a joined fix: the count sweep had bumped a figure recorded on 2026-10-20 at ⚠ The body's Test results line still reads 243 files / 3122 cases. Left for whoever refreshes it. 🤖 Written by the sydevs autonomous loop — see what this is Generated by Claude Code |
sydevs-bot
left a comment
There was a problem hiding this comment.
🧐 Adversarial review
This matches #1081 closely. The ticket prescribes the Worker, the gate, the picker, the fixture and part F's three corrections, and I found nothing here that the ticket or a named review line did not ask for — #1078 settled the wildcard-route and split-PR questions, correctly. Both findings are one rule living in two places; neither is a reason to hold the PR. What is left is step 0 and the four .claude/workflow.json edits, both a person's and both named in the body.
Findings
should-fix—responsibilityLabelhas one caller, and the picker it was extracted for still spells its rule inline. SeePreviewPicker.tsx:144.consider—next.config.mjs:19holds a third copy of the environment-name regex and the domain suffix, pinned by a spec rather than removed bynext.config.ts.
What was checked
Read whole: lib/preview/proxy.ts, preview-proxy/index.ts, middleware.ts, PreviewPicker.tsx, SignIn/actions.ts, SignIn/index.tsx, previewAdmin/index.ts, serverUrl.ts, scripts/lib/cloudflare.ts, preview-domain-plan.ts, plus the next.config.mjs, magicLinks.ts and grantSummary.ts diffs.
Ladder: preview-domain-plan.ts's pure/CLI split follows railway-preview-status.ts, which this repo already tests the same way — not a finding. The hand-styled picker row names what Payload's Card cannot do.
Live, on the Railway host: GET /admin answers 302 to pr-1082.cloud-preview.sydevelopers.com/admin, and /api/health returns commit: 138c01f8… — this head — with environment: SahajCloud-pr-1082. Criteria B and E hold on the real deploy, and PREVIEW_PROXY_SECRET is set.
Preview links: unreachable, as the body says. .claude/workflow.json on main still points at the Railway host and sets no Access token. Nothing raised on it.
🤖 Written by the sydevs autonomous loop — see what this is
Generated by Claude Code
The helper was extracted so the invitation email's list and this picker
could not name a kind of managed document two ways, and the picker still
spelled the singular/plural rule inline — leaving the helper one caller,
whose copy is the only one under test.
Its docstring counted three surfaces. The third, `inviteHeading`, was
never going to call it: a subject counts the items ("1 region", "4
events") lowercase rather than labelling a row, so the docstring now says
two and names what the subject does instead.
Co-Authored-By: Claude Opus 5 <[email protected]>
Claude-Session: https://claude.ai/code/session_01Mg9rjWDYYKfEQHNPL8LdcZ
…rom src The config held a third copy of `PREVIEW_ENVIRONMENT_NAME` and `PREVIEW_DOMAIN_SUFFIX`, and a second copy of `deploymentEnvironment()`'s chain, each because a `.mjs` config cannot import TypeScript. Next 15+ reads `next.config.ts`, and this repo is on next@^16: the file is renamed and now imports both, by the relative reach `preview-proxy/index.ts` already makes. Two specs pinned those copies in agreement; the agreement blocks go with them. Verified through Next's own `loadConfig`, which is what `next build` calls: it transpiles the config with swc, registers a require hook for the imported `.ts`, and honours tsconfig `paths`. The composed origin is `pr-1082.cloud-preview.sydevelopers.com` on `SahajCloud-pr-1082`, absent on `SahajCloud-staging` and off-Railway. Breaking `PREVIEW_DOMAIN_SUFFIX` moves the config's answer with it and reds the spec. The rename also puts the config under `pnpm typecheck`, which a `.mjs` file was not: `allowJs` without `checkJs` never read its JSDoc `@type`. That surfaced `images.remotePatterns`, whose conditional spread widened the scheme to `string`. Co-Authored-By: Claude Opus 5 <[email protected]> Claude-Session: https://claude.ai/code/session_01Mg9rjWDYYKfEQHNPL8LdcZ
`src/lib/preview/proxy.ts` counted six consumers and its purity paragraph named three reaches; the Next config is a seventh, and reaches it from a file swc transpiles before Next has started. `docs/architecture.md` now says why that config is TypeScript, and the unit lane is recounted at 260 / 3501 in `tests/PERF.md` plus its two consumers, with this run's measurement as PERF.md's forty-fifth row. Co-Authored-By: Claude Opus 5 <[email protected]> Claude-Session: https://claude.ai/code/session_01Mg9rjWDYYKfEQHNPL8LdcZ
|
Two critic threads, both adopted and resolved. Pushed
⚠ The rename also put the config under Gate green: lint, format, both typechecks, 3501 unit cases, plus 🤖 Written by the sydevs autonomous loop — see what this is Generated by Claude Code |
Five conflicts, all Markdown, and four of them one fact: both sides recounted the unit lane. The merged tree is measured rather than added up — 261 files and 3510 tests, which `perf-figures-pinned.spec.ts` pins to what is on disk. `tests/PERF.md` takes this run as its forty-sixth row; `AGENTS.md`, `docs/rules/testing-reqs.md` and `tests/AGENTS.md` quote the same pair. The fifth is `scripts/AGENTS.md`'s table, where each side added rows: `lib/cloudflare.ts`, `preview-domain.ts` and `preview-domain-plan.ts` from this branch, `audit-challenge-parents.ts` and `challenge-mounts.ts` from #1106, each kept at its own placement. One shared row differs in substance — `get-railway-preview-url.ts`, which this branch rewrote to wait for the head commit rather than for `/api/health` — and that is this branch's, untouched on `main`. Co-Authored-By: Claude Opus 5 <[email protected]> Claude-Session: https://claude.ai/code/session_01Mg9rjZTnsrufohceG18CSK
…udit `main` does not typecheck. #1106 added `audit-challenge-parents.ts` and `challenge-mounts.ts` reading `Client.name`; #1108 split that field into a required internal `label` and an optional public `title`. Each was green against its own base, and #1106 merged second, so `tsc` fails on `main` itself at three sites — not at any conflict between the two branches. Merging `main` brought the break here, which is why it is fixed here. `label` is the field the split kept for operator-facing output: required, never shown to the public, and what manager-facing mail already uses. `title` is optional and would print nothing for most services. Co-Authored-By: Claude Opus 5 <[email protected]> Claude-Session: https://claude.ai/code/session_01Mg9rjZTnsrufohceG18CSK
|
Merged Four were one fact: both sides recounted the unit lane. I measured the merged tree rather than adding the two bumps together — 261 files, 3510 tests, which
⚠ Gate green: lint, format, both typechecks, 3510 unit tests. Plus 🤖 Written by the sydevs autonomous loop — see what this is Generated by Claude Code |
Five Markdown conflicts and one semantic conflict no marker showed. Four of the five are the same fact twice: both sides recounted the unit lane from 255 / 3457. Measured on the merged tree rather than added up — 262 files and 3530 tests. `tests/PERF.md` takes this run as its forty-seventh row; `AGENTS.md`, `docs/rules/testing-reqs.md` and `tests/AGENTS.md` quote the same pair. The fifth is `docs/architecture.md`'s Sentry paragraph. #1102 rewrote it from "the `environment` tag" to "the `environment` FIELD", adding why no capture sets a tag beside it; this branch had only renamed `next.config.mjs` to `next.config.ts` in it, twice. Resolved as main's prose carrying this branch's two renames. **The semantic conflict is `tests/unit/submission-deliverers.spec.ts`, which git merged clean and which then failed.** #1102 added a mock factory for `@/lib/env/deploymentEnvironment` declaring `deploymentEnvironment` alone — complete against `main`, where that module exports nothing else a deliverer reaches. On this branch `getServerUrl()` reads `railwayEnvironmentName()` from the same module, and a factory replaces the module whole, so the review link's `adminDocUrl()` threw vitest's missing-export error inside `deliverProposal`'s try, which reported it as a retryable delivery failure and sent no email. The factory now declares both exports, the second off-Railway to match the `'test'` name beside it. Neither side is wrong, and neither could have seen it: the mock is complete on `main` and the import is correct here. Co-Authored-By: Claude Opus 5 <[email protected]> Claude-Session: https://claude.ai/code/session_01Mg9rjXTetkJdxYxxUHBYFi
|
Merged Four conflicts were the same fact twice — both sides recounted the unit lane from 255 / 3457. Measured, not added up: 262 files, 3530 tests, green gate. The fifth is
Neither side is wrong: the mock is complete on 🤖 Written by the sydevs autonomous loop — see what this is Generated by Claude Code |
Payload's auth provider reads the user once, when the admin mounts. The picker's Server Action redirect()ed into the panel by a soft navigation, so the provider still held no user: logout skipped POST /logout and landed on the sign-in page, whose live session cookie sent it straight back in. A row now signs in through request-magic-link, which a preview answers with the session cookie, and then loads its destination with a full page load. Co-Authored-By: Claude Opus 5.5 <[email protected]>
`main` landed #1103, which added one unit spec and nine cases; this branch adds six specs. Both sides rewrote the same four doc figures, so every hunk conflicted on a number neither side owns alone. Each count is now the merged tree's, measured rather than added up: 263 files and 3540 cases, from the lean gate run on this merge. The arithmetic sum was 3539, and `perf-figures-pinned` is what caught the difference. `scripts/AGENTS.md` conflicted on the whole script table because both sides added rows. Kept this branch's table, which carries `lib/cloudflare.ts`, `preview-domain.ts`, `preview-domain-plan.ts` and the rewritten `get-railway-preview-url.ts` row, and folded in main's one change: the repeat-signup wording (#1099) on the notification-email script's row. Co-Authored-By: Claude Opus 5 <[email protected]> Claude-Session: https://claude.ai/code/session_01Mg9rjXy4x5sxqYdj6kAevL
|
Merged Four were the unit-lane counts:
Lean gate green on the merge: lint, format, both typechecks, 263 files / 3540 cases in 56.6 s. That run is a new row in 🤖 Written by the sydevs autonomous loop — see what this is Generated by Claude Code |
`Register the preview's fixed address` failed on this PR's own head:
CloudflareError: Cloudflare PUT /accounts/***/storage/kv/namespaces/
9c43446be07544ae933284c8967b5d20/values/pr-1082: HTTP 401 — 10000:
Authentication error
The step read `secrets.CLOUDFLARE_API_KEY`, which is the name of the
environment variable the scripts and Railway use, not the name of the
GitHub secret holding the account's API token. #1111 moved the nightly
cleanup off that repo-level secret and onto the org-level
`CLOUDFLARE_API_TOKEN` for the same reason; both steps added here were
written before it and kept the old name.
The sweep step shadowed the job's Cloudflare pair with its own copy, so
merging #1111 left one file handing `scripts/preview-domain.ts` two
different credentials depending on which step invoked it. The copy is
deleted rather than corrected — it is the drift that the job-level
values exist to prevent.
This fixes which token is sent. Whether that token carries Workers KV
Storage:Edit, Workers Scripts:Edit, Zone:Read and the zone's Workers
Routes:Edit is still step 0's, and the check stays red until it does.
Co-Authored-By: Claude Opus 5 <[email protected]>
Claude-Session: https://claude.ai/code/session_01Mg9rjWoSjeryJXkLhfAYYL
|
Pushed The red check sent the wrong secret. Merging #1111 also split one file. The sweep step shadowed the job's Cloudflare pair with a copy of its own, so What remains is still step 0's. This fixes which token is sent, not what it may do. If the org token lacks Workers KV Storage:Edit, Workers Scripts:Edit, Zone:Read or the zone's Workers Routes:Edit, the KV write answers the same Gate green: lint, format, both typechecks, 263 files / 3540 cases. 🤖 Written by the sydevs autonomous loop — see what this is Generated by Claude Code |
All four conflicts were one fact: the unit lane's file and test counts. Neither side was right on the merged tree. `main` added one spec (+7 cases) in #1105; this branch added six (+53). Taking either side wholesale would have reddened `perf-figures-pinned`, which counts the specs on disk. Resolved by measuring the merged tree instead: 264 files, 3547 cases, confirmed by the lane itself rather than by adding the two deltas. PERF.md keeps its forty-eighth row at the 263 / 3540 that session measured — a recorded measurement is not the current tree — and gains a forty-ninth for this one. Co-Authored-By: Claude Opus 5 <[email protected]> Claude-Session: https://claude.ai/code/session_01Mg9rjYZKEqwyKgc9kgfJ79
|
Merged Neither side was right on the merged tree —
Lean gate green: lint, format, typecheck, typecheck:tests, 264 files / 3547 cases in 46.2 s. No semantic conflict to settle: 🤖 Written by the sydevs autonomous loop — see what this is Generated by Claude Code |
CI now reads the org secret CLOUDFLARE_API_TOKEN for the address step and the nightly sweep. Record that, and that re-scoping the shared token must keep the preview address's permissions. Co-Authored-By: Claude Opus 5.5 <[email protected]>
…sign-in fails - The gate reads the PR number straight from previewNumberFromEnvironmentName rather than testing the name and parsing it again behind an unreachable branch; isPreviewEnvironmentName is now defined by that same parse. - The sweep plan drops a membership check its own lookup already makes. - A picker row that cannot sign in shows a Payload Banner instead of doing nothing, which is what made the logout loop hard to read. - Comments and a spec name that still described the picker posting the page's Server Action now describe the endpoint it uses. Co-Authored-By: Claude Opus 5.5 <[email protected]>
Summary
pr-<n>.cloud-preview.sydevelopers.com, behind a GitHub login, filled with made-up data by CI, and signs a reviewer in as any manager it holds..env.examplestill documented the retired variable as a credential to keep unguessable — a twelfth site the ticket's table missed.scripts/preview-domain.ts's own token list, the one its failure message sends a reader to, still named three scopes afterefe6252added the zone's Workers Routes:Edit to the other two sites —fc5bab7.Change outline
The main change is where a request to a preview goes, and what decides it. Three layers are new, and each one refuses something the other two cannot.
Flow — reaching a preview
⚠ Three things in that flow are not interchangeable, and each failed once. Access decides who; the shared-secret header only says the hop happened, and its value is compared — its name is in this public repository, so a presence test was opened by anyone who read the source. Whether this is a preview comes from Railway's environment name, never the request's
Host: a host test fails open on every shape it does not recognise, andHostis a header the caller writes. And never-cache needs both halves, because a Worker runs ahead of the cache — the zone's cache-phase rule governs the subrequest to Railway, not the inbound request.⚠ The
302is passed explicitly, becauseNextResponse.redirectdefaults to 307 and #1081's criterion B, itscurl -istep and the paragraph above them all name 302. Nothing here wants 307's method guarantee: the branch serves GET and HEAD only.Behaviour — who a preview signs in
issueMagicLink({ config, email }) src/plugins/login/magicLinks.ts find the account by email - config.previewAutoSignIn && account.email === config.previewAutoSignIn + config.previewAutoSignIn # a boolean: this environment, not one address hasAcceptedFlag && !account._verified → return nothing # unchanged: a token nobody can spend return { token: createSession(…) } …throttle, invitation, mailed link — all unchanged managersLoginHere() src/plugins/previewAdmin/index.ts - previewAutoSignIn: previewAdminEmail() # three conditions, one an env var + previewAutoSignIn: previewSignInHere() # `SahajCloud-pr-<n>` or bare `pr-<n>`, + # and not production — the same + # allowlist the gate readsContract — what a preview now reports and answers on
GET /api/health src/app/(payload)/api/health/route.ts { status, timestamp, uptime, environment, version } + { …, commit: RAILWAY_GIT_COMMIT_SHA ?? 'unknown' } # the only field that says WHICH build getServerUrl() src/lib/utilities/serverUrl.ts - SAHAJCLOUD_URL ?? localhost:PORT # a preview inherits production's + previewServerUrl() ?? SAHAJCLOUD_URL ?? localhost:PORT # the preview's own fixed address, + # from the same environment name ownOrigins() → Payload `csrf` - [getServerUrl(), RAILWAY_PUBLIC_DOMAIN] + [the fixed address, RAILWAY_PUBLIC_DOMAIN] # what a reviewer's browser actually sendsFiles — three new homes, and why each is separate
Preview
⚠ Nothing in this PR can be verified by re-running it. The Worker, the Access app and the shared secret are all in force on the preview this PR builds, so a failure here cannot be reproduced against
mainand a fix cannot be proven by a re-run. That is also why step 0 below deploys the Worker by hand, once, before this merges.Links go in once the preview answers at its fixed address. Until step 0 is done by a person, this PR has no reachable preview and the seed step will red the check — see Notes for reviewer.
<fixed>/admin/login<fixed>/admin/collections/events/1/registrations<fixed>/admin/collections/user-submissions?where[type][equals]=contactData: not seeded yet— the fill runs in CI against the fixed address, which needs step 0 first.Test results
test:unit(260 files, 3501 cases)tests/int/preview-auto-signin.int.spec.ts(11),seeds/tests/preview-fixture-import.test.ts(10)preview-gate(9),preview-proxy(7),preview-domain-plan(6),scripts-cloudflare-client(5),e2e-preview-constants(2), plus 5 added torailway-preview-status, 6 toserver-urland 2 toseed-data-filesEight mutation checks, each run and reverted. Restoring
headers.has()redspreview-gate; restoring "any Railway name but production" redspreview-admin-gate; restoringnew URL(path, base)redspreview-proxy; restoring the 13-row floor reds the fixture suite; and removing the/api/healthexemption orcf: { cacheTtl: -1 }reds their own cases. From the review pass:&&for||in the shared Cloudflare client, and dropping the status offCloudflareError, each red two cases ofscripts-cloudflare-client; and lettingNextResponse.redirecttake its own default status redspreview-gate. From the third pass: breakingPREVIEW_DOMAIN_SUFFIXmoves the Next config's composed origin with it and redsnext-config-server-actions.Manual verification
Every item is a once-only observation on this PR's own preview, with
CF-Access-Client-Id/CF-Access-Client-Secretwhere a credential is needed.curl -s https://<railway-host>/api/healthreturns 200 withcommitequal to this PR's head SHA. Acommitofunknownmeans Railway does not injectRAILWAY_GIT_COMMIT_SHAand the discovery change must change before merge.curl -H 'x-sahajcloud-preview-proxy: wrong' https://<railway-host>/adminis refused, and the same request carrying the real secret is served. ⚠ If this one is wrong, nothing else in this PR means much — it is the gate.curl -i https://<railway-host>/adminanswers 302 tohttps://pr-<n>.cloud-preview.sydevelopers.com/admin; the same POST to/api/managers/request-magic-linkis refused.sydevsmember gets in. Open a second PR's fixed address minutes later: the login appears again. That is expected.curl -i https://pr-<n>.cloud-preview.sydevelopers.com/api/healthwith no token returns the Access login, not 200.curl -sI <fixed>/adminwith the service token showscache-control: private, no-storeand nocf-cache-status: HIT./admin/loginlists the admin and both fixture managers with their roles and managed records. Sign in as each of the three back to back: all get in, none is rate-limited. ⚠ The zone's auth rate limit is 10 requests/60 s per IP and is evaluated ahead of the Worker — if this fails, that rule needs a host term (step 0).ownOrigins()change is missing.cloud.sydevelopers.com./admin/collections/user-submissions, search for your own surname and forgmail.com: both return nothing./admin/collections/eventslists both either way —eventsread is project-wide, and only writes are subtree-scoped.pnpm tsx scripts/preview-domain.ts sweepwith no--applyagainst a PR closed last week and the longest-running open PR: it names the closed one and leaves the open one.https://cloud.sydevelopers.com, save a record, and confirmcf-cache-statuson a client API read is unchanged from before.Notes for reviewer
This is child 1 of 2, and it merges first. sydevs/claude-workflow#241 gives the loop its way through the gate and is blocked by this. It consumes the fixed address shape, the sign-in route and the red check from here, and provides nothing back.
Step 0 is a person's, in Cloudflare, before this merges, and nothing in this PR can do it: the Zero Trust org; the GitHub IdP restricted to org
sydevs; one worker-level Access app; two Service Auth policies, one per named token (claude-loop,github-ci) — one policy on "any service token" would make switching one off a deletion; the AUD tag; therequest_cf_overrides_cache_rulescompatibility flag; and one hand deploy of the Worker. Confirm the zone's rate-limit and WAF rules carry a host term. The cache rule no longer needs one, since previews are uncacheable by construction.⚠ Step 0 also includes widening
CLOUDFLARE_API_KEY, and that is what the red check is.Register the preview's fixed addressanswers401 10000: Authentication erroron the KV write forpr-1082. The token needs Workers KV Storage:Edit, Workers Scripts:Edit, Zone:Read and the zone's Workers Routes:Edit. Nothing in the repository supplies it, and no re-run clears the check.Four
.claude/workflow.jsonedits are also a person's, and are deliberately not done here. That file is a Protected Path: an unattended run cannot write it and waits out its lease having written nothing (#874). The edits:previewUrl.pattern→https://pr-{pr}.cloud-preview.sydevelopers.com,previewUrl.seed→pnpm seed preview-fixture, the newpreviewUrl.auth→{ "signInPath": "/api/managers/request-magic-link", "account": "[email protected]", "accountsPage": "/admin/login" }, andsecurityReview.triggerPatternextended to cover^preview-proxy/.Residue the sweep cannot clear. Deleting a Workers Custom Domain does not remove the Advanced Certificate it generated. Those go by hand. The sweep is load-bearing rather than hygiene: a zone holds 100 Custom Domains.
Three variables a person sets, none read through
serverEnv:PREVIEW_PROXY_SECRET(a Railway preview variable and a GitHub secret), andCF_ACCESS_CLIENT_ID/CF_ACCESS_CLIENT_SECRET(GitHub secrets, thegithub-citoken).PREVIEW_ADMIN_EMAILalso leaves Railway, GitHub's secrets and the loop's cloud environment.What this PR deliberately does not do, each named rather than quietly skipped:
middleware→proxyis not renamed.next@^16.4.3deprecatesmiddleware, andproxydefaults to the Node runtime — which would also invalidate this file's header comment about server-only code that must not enter the Edge bundle, a separate claim to re-reason. Its own ticket. The header now reads correctly under either runtime.wranglerstays a thing a person runs rather than a lockfile entry.How a manager's smaller reach is shown, answered 2026-11-07 (Ardnived, option B). #1081 asked that the event manager see fewer Events than the admin. No fixture can make that true —
eventsread is project-wide and only writes are subtree-scoped — so the criterion is now editability: the event manager saves the class naming them and is refused the sibling. The criterion is rewritten on the ticket, and verification item 12 is that observation.One judgement worth checking. The fixture carries a
formsrow and sixusersrows the ticket's table did not list. The five contact messages cannot exist without a form, and a registration with no registrant leaves the Registrations page — the page this goal exists for — showing blanks. Both are declared inEXPECTED_COUNTSandCOLLECTION_METADATA.The review pass found six defects, three of them bypasses, and they are in their own commit (
fix(preview): compare the proxy secret…) so the shape of the fix is readable on its own. Worth knowing while reviewing:curlwas served — and the next request got an admin session.stagingenvironment would have published every manager's account with one-click admin sign-in, behind nothing.new URL(path, base)let a//evil.example/xpath replace the authority, sending the shared secret and the caller's Access assertion there.pendingregistrations, of which there is one.PUT; thePOSTwould have 405'd before any preview was reachable.The critic's second pass raised four more, all built (2026-11-10). The one that changed a behaviour outside this PR's own area:
requireEnvplus an envelope-checking fetch existed three times underscripts/, and onlypreview-domain.ts's copy knew Cloudflare answers some failures200withsuccess: false— sosetup-stream-webhook.tsread a refusedGETas "nothing registered" and would overwrite the live, account-scoped Stream webhook without--force. Onescripts/lib/cloudflare.tsnow owns that rule, and the branch-level security sweep then caught a regression in my own extraction: an unparseable200read as an empty envelope re-armed the same overwrite, so it throws (39d9c39). ⚠r2AccessKeyId's two-scope token-verify fallback needs a refusal as a value, not a throw, and catchesCloudflareErroritself. The other three: the seed CLI reported a gate 403 as missingADMIN_TOKENadvice and now leads with the route, status and answer; the gate's redirect status; and the picker's duplicate'inactive'literal.The critic's third pass raised two, both built (2026-11-11). The picker labelled a managed kind inline while
responsibilityLabelsat one caller short (50be7f8);inviteHeadingwas never the third caller its docstring counted, because a subject counts items lowercase. Andnext.config.mjsheld a third copy of the environment-name pattern and the domain suffix, so it is nownext.config.tsand imports them (e6ba3f5) — which also deletes a second copy ofdeploymentEnvironment()'s chain, whose comment named the same.mjsreason. Next transpiles a TypeScript config with swc and resolves its imports, confirmed through its ownloadConfig. ⚠ The rename also puts the config underpnpm typecheck, which a.mjsfile was not —allowJswithoutcheckJsnever read its JSDoc@type— and that foundimages.remotePatterns' conditional spread widening its scheme tostring. One deliberate behaviour change rides along:onRailwaynow readsrailwayEnvironmentName(), so an emptyRAILWAY_ENVIRONMENT_NAMEbeside a set legacy variable reads as off-Railway. That is build-log verbosity only, and it is the??deploymentEnvironment()already used to decide production from preview.Dismissed findings, with reasons. Each was raised, checked and not acted on:
DEPLOYMENT.md, so a future re-test corrects the paragraph rather than re-deriving it.implement-ticketdoes not split a ticket.has:-gated two-entry middleware matcher would restore production's matched surface and with it the pre-auth body-buffer ceiling. It re-spells the preview test inside the matcher, where it can drift from the gate and fail open — strictly worse than the memory bound, which the old/api/:path*matcher already carried for every nonexistent/api/…path./api/guard inmatchCacheableReadsaves a regex and two allocations per non-API request. It changes the answer for a non-normalised//api/…path, in the function whose own history records a verified cache access-control bypass. Not worth it.cacheTtlon the Worker's KV read would cut a central round trip per colo per minute, at the price of a 502 window whenever a Railway host is re-discovered. Measured nowhere; the reviewer's call.Detail
Why the Railway host is read, never built. Railway appends a random suffix to some generated domains, so a constructed host turns #661's loud failure into a 502.
scripts/get-railway-preview-url.tsreads it out of Railway's commit-status description, and the KV value comes from there and nowhere else —scripts/preview-domain.tsalso refuses a--hostthat is not a Railway host, because the Worker sends the shared secret and the caller's Access session to whatever KV names.Why
commitand notversion.npm_package_versionis identical on every commit, and Railway's commit status proves only that it started that deploy. So a PR pushed to twice in quick succession was filled and tested as the push before.commit: unknownis terminal rather than waited out: it means Railway stopped injecting the SHA, and no amount of waiting identifies the build. Discovery also tells "never answered" from "kept serving an earlier commit", because the two send a reader to different places.Why a
pendingregistration takes two passes. A created-pendingrow queues screening; a screening pass leaves itpending, and delivery then writesaccepted, becauseregistration'sdeliveredStatusisaccepted. Both guards read the status at create, so the fixture authors every row with a terminal status — which skips screening — and reachespendingby an update, which queues nothing.COLLECTION_METADATAstates acountWherefloor for the survivor, and a new case runs the real verification against it.Why production's uniform answer is asserted through
issueMagicLinkrather than a second integration environment: naming a suite's environmentproductionwould also switch the mail adapter and the storage isolation over, which is a different suite's business. The uniform answer is entirelypreviewAutoSignInbeing off, so the case drives that directly, andpreview-auto-signin.spec.tspins that production resolves to off.Why the fixture's events carry a real weekly schedule rather than
inactive: true, which the repo's own test fixtures default to: an event with no schedule shows nothing on the map, the calendar or the listing — the pages most changes here are about.The seed step is inside
Lint, Test & Smoke, never a job of its own. A new job is a new check name no ruleset requires,merge-gate.mjsreads SKIPPED as OK, and #903 forbids renaming a required check — so a split would leave this goal's own red-check criterion unenforced at the gate.Why the seed CLI's refusal is untested.
seeds/run.tscallsmain()at module scope, so the unit lane cannot import it, and extracting one message template intoseeds/lib/to pin it buys a module whose only consumer is that CLI. Every other diagnostic in the file is uncovered for the same reason.Documentation swept:
AGENTS.md(the Admin Access table, Project Structure),DEPLOYMENT.md(a new preview-topology section, the rejected wildcard, and the corrected cache-rule premise at the old:124),docs/environment.md,docs/architecture.md(why the config is TypeScript),scripts/AGENTS.md(thescripts/lib/convention and the shared client's row),seeds/AGENTS.md,tests/COVERAGE.md,.env.example, andtests/PERF.mdplus its consumers for the new unit-lane counts.Closes #1081
Generated by Claude Code