Your favorite shift management application!
fix(ci): gate preview teardown on the label and surface Cloudflare challenges (#220)
panteL64f91a7726b2
diff --git a/.github/workflows/pr-preview.yml b/.github/workflows/pr-preview.ymlindex c3f349f..a2398b9 100644--- a/.github/workflows/pr-preview.yml+++ b/.github/workflows/pr-preview.yml@@ -60,7 +60,6 @@ jobs:KOMODO_SERVER_ID: ${{ vars.KOMODO_SERVER_ID }}PREVIEW_DOMAIN: ${{ vars.PREVIEW_DOMAIN }}PREVIEW_CADDY_NETWORK: ${{ vars.PREVIEW_CADDY_NETWORK }}- PREVIEW_ADMIN_EMAIL: ${{ vars.PREVIEW_ADMIN_EMAIL }}KOMODO_API_KEY: ${{ secrets.KOMODO_API_KEY }}KOMODO_API_SECRET: ${{ secrets.KOMODO_API_SECRET }}PREVIEW_BETTER_AUTH_SECRET: ${{ secrets.PREVIEW_BETTER_AUTH_SECRET }}@@ -70,7 +69,7 @@ jobs:run: |missing=""for name in KOMODO_URL KOMODO_SERVER_ID PREVIEW_DOMAIN PREVIEW_CADDY_NETWORK \- PREVIEW_ADMIN_EMAIL KOMODO_API_KEY KOMODO_API_SECRET \+ KOMODO_API_KEY KOMODO_API_SECRET \PREVIEW_BETTER_AUTH_SECRET PREVIEW_BASIC_AUTH_HASH \PREVIEW_BASIC_AUTH_PASSWORD PREVIEW_ADMIN_PASSWORD; doeval "value=\${$name}"@@ -142,22 +141,40 @@ jobs:PREVIEW_IMAGE: ghcr.io/pantelx/bettershift:pr-${{ github.event.number }}PREVIEW_BASIC_AUTH_HASH: ${{ secrets.PREVIEW_BASIC_AUTH_HASH }}PREVIEW_BETTER_AUTH_SECRET: ${{ secrets.PREVIEW_BETTER_AUTH_SECRET }}+ PREVIEW_CF_BYPASS_TOKEN: ${{ secrets.PREVIEW_CF_BYPASS_TOKEN }}run: node scripts/preview-stack.mjs deploy- name: Wait for the instanceenv:URL: https://pr-${{ github.event.number }}.${{ vars.PREVIEW_DOMAIN }}BASIC_PASSWORD: ${{ secrets.PREVIEW_BASIC_AUTH_PASSWORD }}+ CF_BYPASS: ${{ secrets.PREVIEW_CF_BYPASS_TOKEN }}run: |# Has to cover a registry pull, the migration, the Next.js boot and Caddy's first ACME issuance.deadline=$(( $(date +%s) + 300 ))+ # Three in a row, not one: right after a redeploy the proxy may still+ # hold the old container as an upstream and answer at random.+ ok=0while [ "$(date +%s)" -lt "$deadline" ]; do- if curl -sf -u "preview:$BASIC_PASSWORD" "$URL/api/health" >/dev/null; then- echo "Instanz ist erreichbar."- exit 0+ if curl -sf -u "preview:$BASIC_PASSWORD" -H "X-Preview-CI-Bypass: $CF_BYPASS" \+ "$URL/api/health" >/dev/null; then+ ok=$(( ok + 1 ))+ if [ "$ok" -ge 3 ]; then+ echo "Instanz ist erreichbar."+ exit 0+ fi+ else+ ok=0fisleep 5done+ # A Cloudflare challenge looks exactly like a dead instance to curl -f.+ body=$(curl -s -u "preview:$BASIC_PASSWORD" -H "X-Preview-CI-Bypass: $CF_BYPASS" "$URL/api/health" || true)+ case "$body" in+ *"Just a moment"*|*"challenges.cloudflare.com"*)+ echo "::error::Cloudflare is challenging $URL instead of passing the request through. The X-Preview-CI-Bypass header needs a matching WAF skip rule (see docs/PR_PREVIEWS.md)."+ exit 1 ;;+ esacecho "::error::$URL/api/health is not answering. The stack is left standing for debugging."exit 1@@ -165,8 +182,10 @@ jobs:env:PREVIEW_URL: https://pr-${{ github.event.number }}.${{ vars.PREVIEW_DOMAIN }}PREVIEW_BASIC_AUTH_PASSWORD: ${{ secrets.PREVIEW_BASIC_AUTH_PASSWORD }}- PREVIEW_ADMIN_EMAIL: ${{ vars.PREVIEW_ADMIN_EMAIL }}+ PREVIEW_ADMIN_EMAIL: admin@${{ vars.PREVIEW_DOMAIN }}+ PREVIEW_MEMBER_EMAIL: member@${{ vars.PREVIEW_DOMAIN }}PREVIEW_ADMIN_PASSWORD: ${{ secrets.PREVIEW_ADMIN_PASSWORD }}+ PREVIEW_CF_BYPASS_TOKEN: ${{ secrets.PREVIEW_CF_BYPASS_TOKEN }}run: node scripts/seed-preview.mjs- name: Comment on the PR@@ -174,7 +193,8 @@ jobs:GH_TOKEN: ${{ github.token }}PR: ${{ github.event.number }}URL: https://pr-${{ github.event.number }}.${{ vars.PREVIEW_DOMAIN }}- ADMIN_EMAIL: ${{ vars.PREVIEW_ADMIN_EMAIL }}+ ADMIN_EMAIL: admin@${{ vars.PREVIEW_DOMAIN }}+ MEMBER_EMAIL: member@${{ vars.PREVIEW_DOMAIN }}ADMIN_PASSWORD: ${{ secrets.PREVIEW_ADMIN_PASSWORD }}SHA: ${{ github.event.pull_request.head.sha }}STALE_IMAGE: ${{ steps.image.outputs.stale }}@@ -191,7 +211,10 @@ jobs:**$URL**- Sign in with \`$ADMIN_EMAIL\` / \`$ADMIN_PASSWORD\`+ | Account | E-mail | Password |+ | --- | --- | --- |+ | Admin (superadmin, owns both calendars) | \`$ADMIN_EMAIL\` | \`$ADMIN_PASSWORD\` |+ | Member (Contribute bundle on "Dienstplan Team A") | \`$MEMBER_EMAIL\` | \`$ADMIN_PASSWORD\` |The instance sits behind basic auth (user \`preview\`). Every further push resetsit and seeds the demo data again.@@ -211,11 +234,14 @@ jobs:name: Tear the preview down# vars.KOMODO_URL as the switch: secrets are not readable in a job-level `if`,# repository variables are. With no configuration there is nothing to tear down.+ # On `closed` the label is still on the payload, so it gates the run: without it+ # this PR never had a preview and there is no stack to destroy.if: >-vars.KOMODO_URL != '' &&(github.event_name == 'workflow_dispatch' ||(github.event.pull_request.head.repo.full_name == github.repository &&- (github.event.action == 'closed' ||+ ((github.event.action == 'closed' &&+ contains(github.event.pull_request.labels.*.name, 'preview')) ||(github.event.action == 'unlabeled' && github.event.label.name == 'preview'))))runs-on: ubuntu-latesttimeout-minutes: 10@@ -232,6 +258,7 @@ jobs:KOMODO_API_KEY: ${{ secrets.KOMODO_API_KEY }}KOMODO_API_SECRET: ${{ secrets.KOMODO_API_SECRET }}PR_NUMBER: ${{ github.event.number || inputs.pr_number }}+ PREVIEW_CF_BYPASS_TOKEN: ${{ secrets.PREVIEW_CF_BYPASS_TOKEN }}run: node scripts/preview-stack.mjs destroy- name: Update the commentdiff --git a/docs/PR_PREVIEWS.md b/docs/PR_PREVIEWS.mdindex 9e9e75a..0bcbd67 100644--- a/docs/PR_PREVIEWS.md+++ b/docs/PR_PREVIEWS.md@@ -8,10 +8,11 @@ This guide explains the automated preview environments BetterShift spins up for2. [Prerequisites on the Server](#prerequisites-on-the-server)3. [Secrets](#secrets)4. [Variables](#variables)-5. [How the Pieces Fit Together](#how-the-pieces-fit-together)-6. [What's Different in a Preview](#whats-different-in-a-preview)-7. [Manual Cleanup](#manual-cleanup)-8. [Security Note](#security-note)+5. [Cloudflare in Front](#cloudflare-in-front)+6. [How the Pieces Fit Together](#how-the-pieces-fit-together)+7. [What's Different in a Preview](#whats-different-in-a-preview)+8. [Manual Cleanup](#manual-cleanup)+9. [Security Note](#security-note)---@@ -19,7 +20,7 @@ This guide explains the automated preview environments BetterShift spins up forAdding the `preview` label to a pull request from this repository gets it a running, seeded BetterShift instance at `https://pr-<number>.<PREVIEW_DOMAIN>`. Usually that takes a few minutes; in the worst case it takes considerably longer, because the deploy job first waits for the PR's image to finish building — that wait alone is allowed to run for up to 25 minutes. Every further push to the PR (a `synchronize` event) redeploys it from scratch: the old container and its data are destroyed first, so the instance always reflects the latest commit and starts from a clean, freshly seeded database.-Closing the PR, or removing the `preview` label again, tears the instance down completely — container and data, nothing left behind. Reopening a closed PR that still carries the `preview` label deploys it again, the same way a `synchronize` push does: fresh container, freshly reseeded database.+Closing a PR that carries the `preview` label, or removing the label again, tears the instance down completely — container and data, nothing left behind. Closing a PR that never had the label does nothing: the `teardown` job checks for the label on the `closed` event and skips itself otherwise, so it doesn't go looking for a stack that was never created. Reopening a closed PR that still carries the `preview` label deploys it again, the same way a `synchronize` push does: fresh container, freshly reseeded database.A pull request from a fork never gets a preview: `.github/workflows/pr-preview.yml` checks `head.repo.full_name` against the target repository and, for a fork PR that gets labeled `preview`, only writes an explanatory `::notice::` into the job log instead of deploying anything. It is a log line rather than a PR comment on purpose: a `pull_request` event from a fork gets a read-only `GITHUB_TOKEN` no matter what the workflow's `permissions:` block says, so posting a comment would simply fail with a 403. Whoever added the label has write access and can read the job. Fork PRs don't get repository secrets or a pushed image, so there would be nothing to deploy against anyway.@@ -83,6 +84,9 @@ Repository secrets the `deploy` job in `.github/workflows/pr-preview.yml` requir| `PREVIEW_BASIC_AUTH_HASH` | bcrypt hash of the Basic Auth password || `PREVIEW_BASIC_AUTH_PASSWORD` | the same password, in plain text || `PREVIEW_ADMIN_PASSWORD` | password for the seed admin account |+| `PREVIEW_CF_BYPASS_TOKEN` | optional — shared value for the `X-Preview-CI-Bypass` header, see [Cloudflare in Front](#cloudflare-in-front) |++The Komodo user behind `KOMODO_API_KEY` needs permissions on two resource types, not one. On **Stacks**, level `Write` — that covers creating, updating and deleting them as well as the `Execute` that deploy and destroy need. On the **Server** named by `KOMODO_SERVER_ID`, level `Read` plus the specific permission `Attach`: Komodo checks separately whether a user may hang a new stack onto a given server, and without it `/write/CreateStack` fails with `Cannot attach Stack to this Server` even though every stack permission is in place. In TOML form that second part reads `all.Server = { level = "Read", specific = ["Attach"] }`.Generate the hash with:@@ -94,13 +98,15 @@ Store its output in `PREVIEW_BASIC_AUTH_HASH` exactly as printed — plain, unes`PREVIEW_BASIC_AUTH_PASSWORD` has to hold the plain-text password, not just the hash, because both the workflow's health check (a plain `curl` request) and `scripts/seed-preview.mjs` need to authenticate through Basic Auth themselves before they can reach the app at all.+Both seeded accounts get their address from `PREVIEW_DOMAIN`: `admin@<PREVIEW_DOMAIN>` and `member@<PREVIEW_DOMAIN>`. They are identifiers, nothing more — BetterShift sends no mail at all, so neither address has to be a real mailbox. There is no repository variable for either one; the workflow builds them, and `scripts/seed-preview.mjs` takes `PREVIEW_ADMIN_EMAIL` and `PREVIEW_MEMBER_EMAIL` for a run by hand against some other instance.+`PREVIEW_ADMIN_PASSWORD` has two constraints. It must be **at least 8 characters** long — better-auth enforces that minimum on `/api/auth/sign-up/email`, and a shorter one makes `scripts/seed-preview.mjs` fail with an opaque `400` that says nothing about the length. And it must be a **throwaway used nowhere else**: the deploy job writes it into the sticky PR comment in plain text, on a public repository, so anyone can read it. The member account the seed script creates (`[email protected]`) is registered with the same password.The Basic Auth username is fixed to `preview` — it's hardcoded into the compose label key (`caddy.basic_auth.preview`) and into the workflow's health-check `curl` call, and it's the default `scripts/seed-preview.mjs` falls back to (`PREVIEW_BASIC_AUTH_USER`, which this workflow never sets). There is no repository variable for it.## Variables-Repository variables the `deploy` job reads. Same place, one tab over: **Settings → Secrets and variables → Actions → Variables**. `KOMODO_URL` doubles as the feature's on/off switch — while it is unset, the `teardown` job skips itself, so closing a PR on a repository that has no preview server configured doesn't produce a red job.+Repository variables the `deploy` job reads. Same place, one tab over: **Settings → Secrets and variables → Actions → Variables**. `KOMODO_URL` doubles as the feature's on/off switch — while it is unset, the `teardown` job skips itself, so closing a PR on a repository that has no preview server configured doesn't produce a red job. The same job also skips a `closed` event on a PR that doesn't carry the `preview` label.| Variable | Example || --- | --- |@@ -108,7 +114,33 @@ Repository variables the `deploy` job reads. Same place, one tab over: **Setting| `KOMODO_SERVER_ID` | ID of the server the previews are deployed to || `PREVIEW_DOMAIN` | `preview.example.com` || `PREVIEW_CADDY_NETWORK` | name of the Docker network Caddy is attached to (see [Prerequisites](#prerequisites-on-the-server)) |-| `PREVIEW_ADMIN_EMAIL` | `[email protected]` |++## Cloudflare in Front++If the Komodo instance or the preview domain sits behind Cloudflare, the runner's requests look like bot traffic: they arrive from Azure datacenter ranges, and Cloudflare answers them with a challenge page (`Just a moment…`) under status `403`, which no script can solve. The symptom is a deploy or teardown failing with `/read/GetStack -> 403` followed by a page of markup. The same request from a residential connection goes straight through, so this only ever shows up in CI.++On this repository's own preview host the cause was Bot Fight Mode, and the fix was the zone toggle below — the header rule never came into play there. Don't assume that for another setup, though.++**First find out which feature fired.** In the Cloudflare dashboard, open **Security → Events** for that hostname and look at the *Service* column of the blocked request. The fix differs:++| Service | Fix |+| --- | --- |+| `Security Level`, `Browser Integrity Check`, `Custom rules`, `Managed rules` | the skip rule below |+| `Bot Fight Mode` | turn it off for this zone under **Security → Bots** — a skip rule has no effect on it |++Bot Fight Mode cannot be exempted: it doesn't run on the Ruleset Engine, so *Skip*, *Bypass* and *Allow* never reach it, and allowlisting the runners by IP is not an option either — GitHub Actions runs on thousands of rotating Azure ranges. Switching it off for a zone that only serves throwaway previews is the trade-off here; Komodo still requires its API key and secret, and every preview instance still sits behind Basic Auth.++For everything else, a WAF custom rule lets CI through, keyed on a header only CI knows. Zone-level custom rules are included in the Free plan (5 per zone) — this is not the account-level WAF, which is an Enterprise feature and is not needed:++1. Generate a random value (`openssl rand -hex 32`) and store it as the repository secret `PREVIEW_CF_BYPASS_TOKEN`. The workflow passes it as `X-Preview-CI-Bypass` on every request it makes — to Komodo, to the health check and from the seed script.+2. In Cloudflare, per zone, under **Security → WAF → Custom rules**, add a rule for the Komodo hostname and one for `*.<PREVIEW_DOMAIN>` matching `http.request.headers["x-preview-ci-bypass"][0] eq "<the same value>"`, with the action **Skip** and all remaining security products ticked.+3. Put that rule above any challenge rule — Cloudflare evaluates custom rules in order.++Leaving `PREVIEW_CF_BYPASS_TOKEN` unset is fine for a host that isn't behind Cloudflare, or where the fix was a toggle rather than a rule: the scripts then send no extra header. Either way, a challenge that comes back anyway is now named as such by both scripts and the health check, instead of being reported as a bare `403` with a page of HTML attached.++The header is a shared secret, not authentication — anyone who learns it can skip the WAF for those hostnames. Komodo's own API key and the Basic Auth in front of every preview instance still apply behind it.++Two details of the generated compose file are worth knowing before the first deploy. The site label is written as `caddy: http://pr-<n>.<PREVIEW_DOMAIN>` — the explicit scheme keeps Caddy from starting automatic HTTPS for a name that resolves to Cloudflare rather than to the server, which behind a TLS-terminating proxy ends in a redirect loop or a certificate order that can never complete.## How the Pieces Fit Together@@ -141,7 +173,7 @@ PR gets the label "preview"naming the head commit — or, on the fallback path above,saying that the image comes from an earlier commit-PR is closed / the "preview" label is removed+PR carrying the label is closed / the "preview" label is removed/ the workflow is started by hand (Run workflow, with a PR number)│▼@@ -176,12 +208,12 @@ KOMODO_URL=… KOMODO_API_KEY=… KOMODO_API_SECRET=… PR_NUMBER=<n> \node scripts/preview-stack.mjs destroy```-This is safe to run even if the stack is already gone — `scripts/preview-stack.mjs` checks for it first and does nothing if it can't find it.+This is safe to run even if the stack is already gone — `scripts/preview-stack.mjs` checks for it first and does nothing if it can't find it. If Komodo is behind Cloudflare, add `PREVIEW_CF_BYPASS_TOKEN=…` to that line as well (see [Cloudflare in Front](#cloudflare-in-front)).Note that a health check that times out during deploy deliberately leaves the stack running instead of tearing it down: the whole point is to keep the container's logs inspectable in Komodo while you figure out what went wrong. The same is true if the seed step fails. In both cases nothing removes the stack automatically — use the command above once you're done investigating.## Security Note-This repository is public, and a PR comment is world-readable. The sticky comment the `deploy` job posts therefore includes the seed admin's login (email and password) so anyone can look at the preview, but never the Basic Auth password — that one stays a repository secret and is never written into a comment.+This repository is public, and a PR comment is world-readable. The sticky comment the `deploy` job posts therefore includes the login of both seeded accounts — the admin and the member — so anyone can look at the preview from either side, but never the Basic Auth password — that one stays a repository secret and is never written into a comment.Preview instances only ever contain data `scripts/seed-preview.mjs` generates itself: fictional names, fictional calendars, fictional shifts. Nothing from a real deployment is ever copied into a preview.diff --git a/scripts/preview-stack.mjs b/scripts/preview-stack.mjsindex b5ea0e8..832d442 100644--- a/scripts/preview-stack.mjs+++ b/scripts/preview-stack.mjs@@ -49,10 +49,26 @@ function redact(text) {return masked.length > 2000 ? `${masked.slice(0, 2000)}… [truncated]` : masked;}+/**+ * Cloudflare answers a challenge with an HTML page, not JSON — without this the+ * failure reads as an unexplained 403 with a page of markup glued to it.+ */+function isCloudflareChallenge(text) {+ return /Just a moment|cf-browser-verification|challenges\.cloudflare\.com/i.test(text || "");+}++// Sent on every request so a Cloudflare WAF rule can skip its security checks+// for CI (see docs/PR_PREVIEWS.md). Unset means no Cloudflare in front.+function bypassHeader() {+ const token = process.env.PREVIEW_CF_BYPASS_TOKEN;+ return token ? { "x-preview-ci-bypass": token } : {};+}+async function komodo(path, body) {const res = await fetch(`${process.env.KOMODO_URL.replace(/\/$/, "")}${path}`, {method: "POST",headers: {+ ...bypassHeader(),"content-type": "application/json","x-api-key": process.env.KOMODO_API_KEY,"x-api-secret": process.env.KOMODO_API_SECRET,@@ -61,6 +77,16 @@ async function komodo(path, body) {});const text = await res.text();if (!res.ok) {+ if (isCloudflareChallenge(text)) {+ const error = new Error(+ `${path} -> ${res.status}: Cloudflare served a challenge instead of passing the request to Komodo. ` ++ "Add a WAF rule that skips the security checks for the X-Preview-CI-Bypass header and store its " ++ "value in the PREVIEW_CF_BYPASS_TOKEN secret (see docs/PR_PREVIEWS.md)."+ );+ error.status = res.status;+ error.bodyText = text;+ throw error;+ }const error = new Error(`${path} -> ${res.status}: ${redact(text)}`);error.status = res.status;error.bodyText = text;@@ -108,7 +134,7 @@ function composeFile({ image, host, network, tz, locale }) {` image: ${image}`," pull_policy: always"," restart: unless-stopped",- " networks: [caddy]",+ ` networks: [${network}]`," environment:",' AUTH_ENABLED: "true"',' ALLOW_USER_REGISTRATION: "true"',@@ -123,14 +149,15 @@ function composeFile({ image, host, network, tz, locale }) {// it is confirmed off for the preview domain.' CSP_STRICT_DYNAMIC_BYPASS: "true"'," labels:",- ` caddy: ${host}`,+ // http:// on purpose: Cloudflare terminates TLS, so Caddy must not try to+ // get its own certificate for a name that never resolves to it directly.+ ` caddy: http://${host}`,' caddy.reverse_proxy: "{{upstreams 3000}}"',' caddy.basic_auth.preview: "${BASIC_AUTH_HASH}"',"","networks:",- " caddy:",+ ` ${network}:`," external: true",- ` name: ${network}`,"",].join("\n");}@@ -171,7 +198,10 @@ async function findStack(name) {try {return await komodo("/read/GetStack", { stack: name });} catch (error) {- if (error.status === 404 || /not found|does not exist/i.test(error.bodyText || "")) {+ if (isCloudflareChallenge(error.bodyText)) throw error;+ // Komodo answers an unknown stack with 500 and "Did not find any Stack+ // matching <name>", so the status alone says nothing — match the wording too.+ if (error.status === 404 || /not found|does not exist|did not find/i.test(error.bodyText || "")) {return null;}throw error;diff --git a/scripts/seed-preview.mjs b/scripts/seed-preview.mjsindex 67f5ea6..554d7bb 100644--- a/scripts/seed-preview.mjs+++ b/scripts/seed-preview.mjs@@ -19,7 +19,7 @@ function requireEnv(name) {const BASE = requireEnv("PREVIEW_URL").replace(/\/$/, "");const ADMIN_EMAIL = requireEnv("PREVIEW_ADMIN_EMAIL");const ADMIN_PASSWORD = requireEnv("PREVIEW_ADMIN_PASSWORD");-const MEMBER_EMAIL = process.env.PREVIEW_MEMBER_EMAIL || "[email protected]";+const MEMBER_EMAIL = process.env.PREVIEW_MEMBER_EMAIL || `member@${new URL(BASE).hostname}`;const BASIC_USER = process.env.PREVIEW_BASIC_AUTH_USER || "preview";const BASIC_PASSWORD = process.env.PREVIEW_BASIC_AUTH_PASSWORD || "";@@ -28,13 +28,47 @@ const BASIC_HEADER = BASIC_PASSWORD? { authorization: "Basic " + Buffer.from(`${BASIC_USER}:${BASIC_PASSWORD}`).toString("base64") }: {};+// Lets a Cloudflare WAF rule skip its security checks for CI requests+// (see docs/PR_PREVIEWS.md). Unset means no Cloudflare in front.+const BYPASS_HEADER = process.env.PREVIEW_CF_BYPASS_TOKEN+ ? { "x-preview-ci-bypass": process.env.PREVIEW_CF_BYPASS_TOKEN }+ : {};+let cookie = "";-async function api(path, { method = "GET", body } = {}) {- const res = await fetch(`${BASE}${path}`, {+const sleep = (ms) => new Promise((resolve) => setTimeout(resolve, ms));++/**+ * Right after a redeploy the proxy can still hold the old container as an+ * upstream, so single requests come back as a gateway error while others+ * succeed. Retrying is worth the small risk of creating a row twice: every+ * push wipes the database anyway, but a failed seed fails the whole deploy.+ */+const TRANSIENT = new Set([502, 503, 504]);++async function request(path, { method, body }) {+ for (let attempt = 1; ; attempt += 1) {+ let res;+ try {+ res = await send(path, { method, body });+ } catch (error) {+ if (attempt >= 5) throw error;+ console.warn(`${method} ${path} failed (${error.message}) — retry ${attempt}/4.`);+ await sleep(2000);+ continue;+ }+ if (!TRANSIENT.has(res.status) || attempt >= 5) return res;+ console.warn(`${method} ${path} -> ${res.status} from the proxy — retry ${attempt}/4.`);+ await sleep(2000);+ }+}++async function send(path, { method = "GET", body } = {}) {+ return fetch(`${BASE}${path}`, {method,headers: {...BASIC_HEADER,+ ...BYPASS_HEADER,"content-type": "application/json",// Node's fetch sends `sec-fetch-mode: cors` (unlike a browser it never adds// Origin itself), which trips better-auth's CSRF check unless we set it.@@ -43,6 +77,10 @@ async function api(path, { method = "GET", body } = {}) {},body: body === undefined ? undefined : JSON.stringify(body),});+}++async function api(path, { method = "GET", body } = {}) {+ const res = await request(path, { method, body });const setCookies = res.headers.getSetCookie();if (setCookies.length > 0) {@@ -51,6 +89,12 @@ async function api(path, { method = "GET", body } = {}) {const text = await res.text();if (!res.ok) {+ if (/Just a moment|challenges\.cloudflare\.com/i.test(text)) {+ throw new Error(+ `${method} ${path} -> ${res.status}: Cloudflare served a challenge instead of the app. ` ++ "The X-Preview-CI-Bypass header needs a matching WAF skip rule (see docs/PR_PREVIEWS.md)."+ );+ }const error = new Error(`${method} ${path} -> ${res.status}: ${text}`);error.status = res.status;error.bodyText = text;