diff --git a/.claude/audits/2026-11-02-avatar-e2e-sandbox-only.md b/.claude/audits/2026-11-02-avatar-e2e-sandbox-only.md index 5a0d5c60..ad982280 100644 --- a/.claude/audits/2026-11-02-avatar-e2e-sandbox-only.md +++ b/.claude/audits/2026-11-02-avatar-e2e-sandbox-only.md @@ -32,7 +32,7 @@ stay in the session scratchpad (`…/scratchpad/proofs/`), not in the repository |---|---|---| | 1 | runner deleted, no line invokes it (the two "removed" mentions excluded) | `DEV_RUNNER_GONE` | | 2 | alias, `bash -n`, dispatcher line | `ALIAS_OK` | -| 3 | suite `cmp`-identical to V1-2; db-sandbox.sh blocks 47-52, 58-61, 255, 270-332, 342-359 verbatim; no `cmd_verify_e2e` / `cmd_sheet_assets_e2e` | `BLOCKS_IDENTICAL` | +| 3 | suite identical to V1-2 once the `noRedirectFetch` lines are dropped (owner-gated, see below); db-sandbox.sh blocks 47-52, 58-61, 255, 270-332, 342-359 verbatim; no `cmd_verify_e2e` / `cmd_sheet_assets_e2e` | `BLOCKS_IDENTICAL` | | 4 | no `supabase status`, `54321`, `supabase_kong`, `supabase_db_faunosteo`, `supabase_network_faunosteo` in the runner or the suite | `NO_DEV_IDS` | | 8 | `corepack pnpm -s typecheck && lint` in `$W` (after `pnpm wasm:build`, the git-ignored `packages/core-wasm/pkg` being absent in a fresh worktree) | `STATIC_GREEN` | @@ -105,16 +105,34 @@ environment supplies. Nothing else is contacted. nothing in the runner or the suite reads it. `NET` is a plain bridge (it can route to the host): the proofs above show nothing uses that route. -## Residual LOW (owner brief §3; no code change here, to fix on V1-2 first then port) +## Redirects refused (owner condition at the checkpoint, 2026-11-02) -- The suite's supabase-js clients use Node's global fetch: default `redirect: follow`; a proxy - would be honoured only with `NODE_USE_ENV_PROXY=1` (unset here, unset by every proof). No - endpoint of the gateway or its upstreams redirects today; a redirect to a foreign host would - appear in strace as a connect outside 127.0.0.1:57800 (none). Security gate nuance: on a - cross-origin redirect undici drops `Authorization` but keeps supabase-js's `apikey` header, so - a redirecting sandbox upstream would carry the sandbox anon or service key to the target; that - key opens nothing on DEV (different JWT secret). Hardening when ported from V1-2: a custom - fetch with `redirect: 'error'` in the suite's two client factories. +The former residual LOW is closed on this branch: `tests/e2e/noRedirectFetch.ts` wraps the +global fetch with `redirect: 'error'` (set after the caller's init, so nothing restores +`follow`); the suite's `anonClient()` and `serviceClient()` pass it through `global.fetch`, +which supabase-js hands to its auth, REST and Storage calls (raw to auth-js, through +`fetchWithAuth` for REST and Storage; neither layer sets `redirect`, retries reuse the wrapper). No production client changes (`packages/supabase/src`, `apps/app/src` +untouched since 6287e5b). Security gate nuance that motivated it: on a cross-origin redirect +undici drops `Authorization` but keeps supabase-js's `apikey` header. +- Regression test `packages/supabase/tests/no-redirect-fetch.test.ts` (in `pnpm --filter + @faunosteo/supabase test:run`, 12 files / 131 tests green): two `node:http` servers, the + origin answers every request with 302 towards the target; REST, auth and Storage calls all + error, the target receives nothing, every origin request carries `apikey: test-key`; the + control (plain fetch, default `follow`) reaches the target at `/landed`. Negative control by + the executor: with `follow` in the wrapper, 3 of the 4 cases fail. +- Live proof j (strace, same harness as a-i): a Python 302 listener on 127.0.0.1:57800 + (`Location: http://127.0.0.1:57801/landed`) and a recording target on 57801. Control: + `curl -L` lands on 57801 (1 hit). The suite with forged `iss: db-sandbox` keys: 1 connect to + 127.0.0.1:57800, 0 to 57801, 0 hit on the target, `createUser: fetch failed`, 5 tests skipped, + rc 1 (fails closed). +- Positive run 2, fresh sandbox from the branch, under strace, proxies unset: **5/5**, 4 + connects all to 127.0.0.1:57800, 0 key in the output, gateway and worker removed, final `down`. + DEV `StartedAt` digest identical to the pre-flight. + +## Residual LOW (owner brief §3; kept as is, V1-2 first then port) + +- A proxy would be honoured by Node's fetch only with `NODE_USE_ENV_PROXY=1` (unset here, + unset by every proof). - `worker_env` is read by the EXIT trap before `start_worker` assigns it (an inherited value would be `rm -f`'d on an early `die`). - Every docker call follows `DOCKER_HOST` / the current context (both local here). diff --git a/.claude/tasks/contracts/2026-11-02-avatar-e2e-sandbox-only-0240.md b/.claude/tasks/contracts/2026-11-02-avatar-e2e-sandbox-only-0240.md index a37abc2f..4f15065f 100644 --- a/.claude/tasks/contracts/2026-11-02-avatar-e2e-sandbox-only-0240.md +++ b/.claude/tasks/contracts/2026-11-02-avatar-e2e-sandbox-only-0240.md @@ -43,6 +43,7 @@ Skill invocation: « develop: neutraliser `pnpm e2e:avatar` (scripts/avatar-e2e. ## CLARIFICATIONS Q: port `cmd_sheet_assets_e2e` too (same gateway), so `pnpm e2e:sheet-assets` works on develop? / A: no, avatar only [gated 2026-11-02] Q (challengers): the port cannot make the later V1-2 → develop merge conflict-free in db-sandbox.sh / A: accepted, expectations and rule written in the plan ("take V1-2's file whole") [gated 2026-11-02] +Q (owner, checkpoint 2026-11-02): close the redirect LOW before the merge / A: the suite's two client factories pass `global: { fetch: noRedirectFetch }` (`redirect: 'error'`, tests/e2e/noRedirectFetch.ts), a regression test with a real 302 in `pnpm --filter @faunosteo/supabase test:run`, live proof j; the suite file therefore differs from V1-2 by those lines only (V1-2 gets the same change at integration) [gated 2026-11-02] Q (executor): the plan's CLAUDE.md:490 and SUPABASE.md §6 wording names `scripts/avatar-e2e.sh` as removed, criterion 1 said "nothing names it" / A: criterion 1 narrowed to "nothing invokes it", lines containing `removed` or `the DEV script` (the SUPABASE.md note wraps before `removed`) excluded from the oracle (same wording as V1-2) [gated 2026-11-02, internal] Q (challengers): proof f (port taken) contains one loopback connect by construction / A: criterion for f = the only AF_INET connect is 127.0.0.1:57800; flagged to the owner [gated 2026-11-02] @@ -55,8 +56,8 @@ Q (challengers): proof f (port taken) contains one loopback connect by construct CHECK: W=/tmp/claude-1000/-home-bchanot-Documents-faunosteo/573c6c77-7294-4d96-a518-83afaafef8d1/scratchpad/bugfix-avatar; grep -qF '"e2e:avatar": "bash scripts/db-sandbox.sh avatar-e2e"' "$W/package.json" && bash -n "$W/scripts/db-sandbox.sh" && grep -qF 'avatar-e2e) shift; cmd_avatar_e2e "$@" ;;' "$W/scripts/db-sandbox.sh" && echo ALIAS_OK EXPECT: ALIAS_OK EVIDENCE: MET exit=0 marker-found :: ALIAS_OK -3. The ported blocks are the V1-2 bytes: the suite file is identical to V1-2's; db-sandbox.sh contains V1-2 a15c35c lines 47-52 (variables), 58-61 (REPO check), 255 (down), 270-332 (gateway and worker helpers) and 342-359 (`cmd_avatar_e2e`) verbatim, and does NOT contain `cmd_verify_e2e` nor `cmd_sheet_assets_e2e`. - CHECK: W=/tmp/claude-1000/-home-bchanot-Documents-faunosteo/573c6c77-7294-4d96-a518-83afaafef8d1/scratchpad/bugfix-avatar; V=/tmp/claude-1000/-home-bchanot-Documents-faunosteo/e641af9a-743e-46d0-9804-99667836040e/scratchpad/v1-2; cmp -s "$W/packages/supabase/tests/e2e/avatar-flow.e2e.ts" "$V/packages/supabase/tests/e2e/avatar-flow.e2e.ts" && python3 -I -c 'import sys; dev=open(sys.argv[1],encoding="utf-8").read(); ref=open(sys.argv[2],encoding="utf-8").read().split("\n"); bad=[f"{a}-{b}" for a,b in [(47,52),(58,61),(255,255),(270,332),(342,359)] if "\n".join(ref[a-1:b]) not in dev]; bad+=[n for n in ("cmd_verify_e2e","cmd_sheet_assets_e2e") if n in dev]; sys.exit("not verbatim / forbidden: "+" ".join(bad)) if bad else print("BLOCKS_IDENTICAL")' "$W/scripts/db-sandbox.sh" "$V/scripts/db-sandbox.sh" +3. The ported blocks are the V1-2 bytes: the suite file is identical to V1-2's once the lines naming `noRedirectFetch` are dropped (the import and the two `global: { fetch: noRedirectFetch }` options, owner-gated); db-sandbox.sh contains V1-2 a15c35c lines 47-52 (variables), 58-61 (REPO check), 255 (down), 270-332 (gateway and worker helpers) and 342-359 (`cmd_avatar_e2e`) verbatim, and does NOT contain `cmd_verify_e2e` nor `cmd_sheet_assets_e2e`. + CHECK: W=/tmp/claude-1000/-home-bchanot-Documents-faunosteo/573c6c77-7294-4d96-a518-83afaafef8d1/scratchpad/bugfix-avatar; V=/tmp/claude-1000/-home-bchanot-Documents-faunosteo/e641af9a-743e-46d0-9804-99667836040e/scratchpad/v1-2; python3 -I -c 'import sys; a=[l for l in open(sys.argv[1],encoding="utf-8") if "noRedirectFetch" not in l]; b=open(sys.argv[2],encoding="utf-8").readlines(); sys.exit("suite differs beyond noRedirectFetch lines") if a!=b else None' "$W/packages/supabase/tests/e2e/avatar-flow.e2e.ts" "$V/packages/supabase/tests/e2e/avatar-flow.e2e.ts" && python3 -I -c 'import sys; dev=open(sys.argv[1],encoding="utf-8").read(); ref=open(sys.argv[2],encoding="utf-8").read().split("\n"); bad=[f"{a}-{b}" for a,b in [(47,52),(58,61),(255,255),(270,332),(342,359)] if "\n".join(ref[a-1:b]) not in dev]; bad+=[n for n in ("cmd_verify_e2e","cmd_sheet_assets_e2e") if n in dev]; sys.exit("not verbatim / forbidden: "+" ".join(bad)) if bad else print("BLOCKS_IDENTICAL")' "$W/scripts/db-sandbox.sh" "$V/scripts/db-sandbox.sh" EXPECT: BLOCKS_IDENTICAL EVIDENCE: MET exit=0 marker-found :: BLOCKS_IDENTICAL 4. No DEV identifier remains in the runner or the suite (no `supabase status`, no 54321, no DEV container or network name). @@ -73,7 +74,11 @@ Q (challengers): proof f (port taken) contains one loopback connect by construct CHECK: W=/tmp/claude-1000/-home-bchanot-Documents-faunosteo/573c6c77-7294-4d96-a518-83afaafef8d1/scratchpad/bugfix-avatar; cd "$W" && corepack pnpm -s typecheck >/dev/null 2>&1 && corepack pnpm -s lint >/dev/null 2>&1 && echo STATIC_GREEN EXPECT: STATIC_GREEN EVIDENCE: MET exit=0 marker-found :: STATIC_GREEN -9. The guard's limits are written where a reader meets them (brief §3), without touching the byte-copied code: the SUPABASE.md §5.1 row for `pnpm db:sandbox avatar-e2e` and the audit log state that the issuer check routes to the sandbox and is not a signature check, and name what the isolation rests on (fixed gateway URL in the worker's 600 env file, `max_redirects(0)` and `proxy(None)` in `crates/worker/src/http.rs`, sandbox-signed keys, upstreams by container name) and the residual LOW (supabase-js default `redirect: follow`, no redirecting endpoint today). Judged by the verifier. +9. The guard's limits are written where a reader meets them (brief §3), without touching the byte-copied code: the SUPABASE.md §5.1 row for `pnpm db:sandbox avatar-e2e` and the audit log state that the issuer check routes to the sandbox and is not a signature check, and name what the isolation rests on (fixed gateway URL in the worker's 600 env file, `max_redirects(0)` and `proxy(None)` in `crates/worker/src/http.rs`, sandbox-signed keys, upstreams by container name) and the redirect refusal of criterion 10 (the former residual LOW). Judged by the verifier. +10. The suite's supabase-js clients refuse HTTP redirects: `tests/e2e/noRedirectFetch.ts` exports `noRedirectFetch` (`fetch(input, { ...init, redirect: 'error' })`, `redirect` set last), both client factories of the suite pass `global: { fetch: noRedirectFetch }`, no production client (`packages/supabase/src`, `apps/app/src`) changes, and the regression test `tests/no-redirect-fetch.test.ts` proves with two local `node:http` servers that a 302 from the first towards the second is not followed by auth, REST and Storage calls (the second server receives no request, the `apikey` header reaches only the first) while a control fetch with the default `follow` does reach the second. Live proof j (orchestrator): the suite with forged `iss: db-sandbox` keys against a 302 listener on 127.0.0.1:57800 pointing at 127.0.0.1:57801 opens no connect to 57801 (strace), logged in the audit file. + CHECK: W=/tmp/claude-1000/-home-bchanot-Documents-faunosteo/573c6c77-7294-4d96-a518-83afaafef8d1/scratchpad/bugfix-avatar; grep -qF "redirect: 'error'" "$W/packages/supabase/tests/e2e/noRedirectFetch.ts" && [ "$(grep -c 'global: { fetch: noRedirectFetch }' "$W/packages/supabase/tests/e2e/avatar-flow.e2e.ts")" = 2 ] && git -C "$W" diff --quiet 6287e5b -- packages/supabase/src apps/app/src && cd "$W/packages/supabase" && node_modules/.bin/vitest run tests/no-redirect-fetch.test.ts >/dev/null 2>&1 && echo NO_REDIRECT_OK + EXPECT: NO_REDIRECT_OK + EVIDENCE: MET exit=0 marker-found :: NO_REDIRECT_OK ## FILE SCOPE -scripts/db-sandbox.sh, scripts/avatar-e2e.sh (deleted), package.json, packages/supabase/tests/e2e/avatar-flow.e2e.ts, packages/supabase/vitest.e2e.config.ts, scripts/dev-env.sh, CLAUDE.md, README.md, docs/development/{STORAGE,SUPABASE,WORKSPACE,TEST_STRATEGY,ENVIRONMENTS,IDENTITY}.md, .claude/audits/2026-11-02-avatar-e2e-sandbox-only.md (new), .claude/tasks/{plans,contracts}/2026-11-02-avatar-e2e-sandbox-only-*.md +packages/supabase/tests/e2e/noRedirectFetch.ts (new), packages/supabase/tests/no-redirect-fetch.test.ts (new), scripts/db-sandbox.sh, scripts/avatar-e2e.sh (deleted), package.json, packages/supabase/tests/e2e/avatar-flow.e2e.ts, packages/supabase/vitest.e2e.config.ts, scripts/dev-env.sh, CLAUDE.md, README.md, docs/development/{STORAGE,SUPABASE,WORKSPACE,TEST_STRATEGY,ENVIRONMENTS,IDENTITY}.md, .claude/audits/2026-11-02-avatar-e2e-sandbox-only.md (new), .claude/tasks/{plans,contracts}/2026-11-02-avatar-e2e-sandbox-only-*.md diff --git a/.claude/tasks/plans/2026-11-02-avatar-e2e-sandbox-only-0215.md b/.claude/tasks/plans/2026-11-02-avatar-e2e-sandbox-only-0215.md index b1ee3faf..640d00a3 100644 --- a/.claude/tasks/plans/2026-11-02-avatar-e2e-sandbox-only-0215.md +++ b/.claude/tasks/plans/2026-11-02-avatar-e2e-sandbox-only-0215.md @@ -100,6 +100,8 @@ NOT ported (V1-2 only, with the reason): `SB_SEED_PW` / `seed_passwords` / `SAND - NOT touched (still true after the fix): `docs/development/RUST.md:178`, `BROWSER_TESTS.md:103`, `SUPABASE.md:38`, `CHANGELOG.md` (neither 6287e5b nor the V1-2 commits added a line). +7. (owner, checkpoint 2026-11-02) `packages/supabase/tests/e2e/noRedirectFetch.ts`: `export const noRedirectFetch: typeof fetch = (input, init) => fetch(input, { ...init, redirect: 'error' })`; the suite's `anonClient()` and `serviceClient()` add `global: { fetch: noRedirectFetch }` (supabase-js hands `global.fetch` raw to auth-js and through `fetchWithAuth` to REST and Storage; no layer sets `redirect`, our wrapper sets it last); regression test `tests/no-redirect-fetch.test.ts` (two `node:http` servers, 302 from A to B, auth + REST + Storage calls fail, B sees nothing, `apikey` only at A, control plain fetch reaches B); live proof j under strace. The suite now differs from V1-2 by those lines: V1-2 takes the same change at integration (merge rule amended). + ## Merge expectations (V1-2 → develop, later) Develop's `db-sandbox.sh` is the merge-base text (9135d73); the port changes base regions V1-2 changes @@ -107,7 +109,7 @@ differently. Expected conflicts: the usage header, the function block (V1-2 has `cmd_sheet_assets_e2e` around `cmd_avatar_e2e`), the dispatcher, the usage `sed` range. Rule: take V1-2's file whole; check with an empty `git diff -- scripts/db-sandbox.sh` after the merge. The suite, `package.json`, `dev-env.sh`, the vitest comment and the ported variable / `down` / `REPO` lines merge -cleanly. Doc lines reworded for develop conflict with V1-2's: keep V1-2's text (same rule as the +cleanly, except the suite: V1-2 adopts the `noRedirectFetch` lines (owner decision 2026-11-02). Doc lines reworded for develop conflict with V1-2's: keep V1-2's text (same rule as the sheet-assets lines in TODO). ## Proof (log committed as `.claude/audits/2026-11-02-avatar-e2e-sandbox-only.md` on this branch) diff --git a/docs/development/SUPABASE.md b/docs/development/SUPABASE.md index 1029f7c2..173c9f62 100644 --- a/docs/development/SUPABASE.md +++ b/docs/development/SUPABASE.md @@ -805,7 +805,7 @@ Docker. | `pnpm db:sandbox types [--check]` | `supabase gen types --db-url ... --schema public` through Prettier, written or diffed with the committed file | | `pnpm db:sandbox test` | `packages/supabase/tests/sandbox/*.sandbox.ts`: real GoTrue and PostgREST sessions, concurrent SQL sessions | | `pnpm db:sandbox e2e-shell` (= `pnpm e2e:shell`) | the authenticated `/app` shell in Chromium (`apps/app/e2e/shell`, `docs/development/BROWSER_TESTS.md`): a loopback dev server whose Supabase calls are replayed on the sandbox, fictitious accounts per test | -| `pnpm db:sandbox avatar-e2e` (= `pnpm e2e:avatar`) | the avatar flow on the sandbox alone: an nginx gateway (`nginx:1.31-alpine`; `/auth/v1/`, `/rest/v1/`, `/storage/v1/` to the sandbox containers, `return 404` elsewhere) published on `127.0.0.1:57800` only; the real worker `faunosteo_worker:dev run` (avatars and sweep, 5 s sweep, no quarantine grace, 512 MiB, read-only, no capability, `nonroot`) on the sandbox network, its service key in a 600 env file removed once started; then `packages/supabase/tests/e2e/avatar-flow.e2e.ts` through that port. The suite accepts only `http://127.0.0.1:57800`, the container `faunosteo_dbsandbox_db` and keys whose JWT payload carries `iss: db-sandbox`, else it throws before any request. The issuer check only routes the run to the sandbox: it is not a signature check and not an authentication. The isolation rests on the fixed gateway URL in the worker's env file, the worker's `max_redirects(0)` and `proxy(None)` (`crates/worker/src/http.rs`), sandbox-signed keys and upstreams reached by container name on the sandbox network. Residual: the suite's supabase-js clients keep fetch's default `redirect: follow` (no endpoint of the gateway or its upstreams redirects today) | +| `pnpm db:sandbox avatar-e2e` (= `pnpm e2e:avatar`) | the avatar flow on the sandbox alone: an nginx gateway (`nginx:1.31-alpine`; `/auth/v1/`, `/rest/v1/`, `/storage/v1/` to the sandbox containers, `return 404` elsewhere) published on `127.0.0.1:57800` only; the real worker `faunosteo_worker:dev run` (avatars and sweep, 5 s sweep, no quarantine grace, 512 MiB, read-only, no capability, `nonroot`) on the sandbox network, its service key in a 600 env file removed once started; then `packages/supabase/tests/e2e/avatar-flow.e2e.ts` through that port. The suite accepts only `http://127.0.0.1:57800`, the container `faunosteo_dbsandbox_db` and keys whose JWT payload carries `iss: db-sandbox`, else it throws before any request. The issuer check only routes the run to the sandbox: it is not a signature check and not an authentication. The isolation rests on the fixed gateway URL in the worker's env file, the worker's `max_redirects(0)` and `proxy(None)` (`crates/worker/src/http.rs`), sandbox-signed keys and upstreams reached by container name on the sandbox network. The suite's supabase-js clients refuse every HTTP redirect (`global.fetch` = `tests/e2e/noRedirectFetch.ts`, `redirect: 'error'`; regression test `tests/no-redirect-fetch.test.ts`) | | `pnpm db:sandbox sql` / `down` | psql as postgres on stdin / remove the stack | Every CLI call passes `--db-url` with `sslmode=disable` (the sandbox has no diff --git a/packages/supabase/tests/e2e/avatar-flow.e2e.ts b/packages/supabase/tests/e2e/avatar-flow.e2e.ts index 054a4c36..4feadd1a 100644 --- a/packages/supabase/tests/e2e/avatar-flow.e2e.ts +++ b/packages/supabase/tests/e2e/avatar-flow.e2e.ts @@ -15,6 +15,7 @@ import { createHash, randomBytes } from 'node:crypto' import { execFileSync } from 'node:child_process' import { deflateSync } from 'node:zlib' import { createClient, type SupabaseClient } from '@supabase/supabase-js' +import { noRedirectFetch } from './noRedirectFetch' import { beginAvatarUpload, confirmAssetUpload, @@ -52,6 +53,7 @@ type Client = SupabaseClient function anonClient(): Client { return createClient(SANDBOX_URL, ANON ?? '', { auth: { persistSession: false, autoRefreshToken: false }, + global: { fetch: noRedirectFetch }, }) } @@ -65,6 +67,7 @@ async function signedIn(email: string): Promise { function serviceClient(): Client { return createClient(SANDBOX_URL, SERVICE ?? '', { auth: { persistSession: false, autoRefreshToken: false }, + global: { fetch: noRedirectFetch }, }) } diff --git a/packages/supabase/tests/e2e/noRedirectFetch.ts b/packages/supabase/tests/e2e/noRedirectFetch.ts new file mode 100644 index 00000000..05b0fb14 --- /dev/null +++ b/packages/supabase/tests/e2e/noRedirectFetch.ts @@ -0,0 +1,8 @@ +/** + * The suite's fetch: a 3xx answer is an error, never a request to another + * origin (owner decision 2026-11-02). supabase-js hands `global.fetch` to its + * auth, REST and Storage calls and spreads the caller's init before ours runs, + * so `redirect` set here is final: nothing restores `follow`. + */ +export const noRedirectFetch: typeof fetch = (input, init) => + fetch(input, { ...init, redirect: 'error' }) diff --git a/packages/supabase/tests/no-redirect-fetch.test.ts b/packages/supabase/tests/no-redirect-fetch.test.ts new file mode 100644 index 00000000..a317832f --- /dev/null +++ b/packages/supabase/tests/no-redirect-fetch.test.ts @@ -0,0 +1,95 @@ +import { createServer, type IncomingMessage, type Server } from 'node:http' +import type { AddressInfo } from 'node:net' +import { afterAll, beforeAll, beforeEach, describe, expect, it } from 'vitest' +import { createClient } from '@supabase/supabase-js' +import type { Database } from '../src' +import { noRedirectFetch } from './e2e/noRedirectFetch' + +type Seen = { url?: string; apikey?: string | string[] } + +const targetSeen: Seen[] = [] +const originSeen: Seen[] = [] +let target: Server +let origin: Server +let originUrl = '' + +function listen( + seen: Seen[], + answer: (res: import('node:http').ServerResponse) => void, +): Promise { + const server = createServer((req: IncomingMessage, res) => { + seen.push({ url: req.url, apikey: req.headers.apikey }) + answer(res) + }) + return new Promise((resolve) => { + server.listen(0, '127.0.0.1', () => resolve(server)) + }) +} + +const portOf = (server: Server) => (server.address() as AddressInfo).port + +function client() { + return createClient(originUrl, 'test-key', { + auth: { persistSession: false, autoRefreshToken: false }, + global: { fetch: noRedirectFetch }, + }) +} + +function expectNotFollowed() { + expect(targetSeen).toHaveLength(0) + // supabase-js may retry a failed GET: count the origin hits, not their number + expect(originSeen.length).toBeGreaterThan(0) + expect(originSeen.every((r) => r.apikey === 'test-key')).toBe(true) +} + +beforeAll(async () => { + target = await listen(targetSeen, (res) => { + res.writeHead(200, { 'content-type': 'application/json' }).end('{}') + }) + origin = await listen(originSeen, (res) => { + const landing = `http://127.0.0.1:${portOf(target)}/landed` + res.writeHead(302, { location: landing }).end() + }) + originUrl = `http://127.0.0.1:${portOf(origin)}` +}) + +afterAll(async () => { + await Promise.all( + [target, origin].map((s) => new Promise((done) => s.close(done))), + ) +}) + +beforeEach(() => { + targetSeen.length = 0 + originSeen.length = 0 +}) + +describe('noRedirectFetch', () => { + it('does not follow a redirect on a REST call', async () => { + const { error } = await client().from('assets').select('id') + expect(error).not.toBeNull() + expectNotFollowed() + }) + + it('does not follow a redirect on an auth call', async () => { + const { error } = await client().auth.signInWithPassword({ + email: 'a@b.c', + password: 'x', + }) + expect(error).not.toBeNull() + expectNotFollowed() + }) + + it('does not follow a redirect on a storage call', async () => { + const { error } = await client().storage.from('avatars').download('k') + expect(error).not.toBeNull() + expectNotFollowed() + }) + + it('control: the default fetch follows the same redirect', async () => { + const res = await fetch(`${originUrl}/control`) + expect(res.status).toBe(200) + expect(targetSeen).toHaveLength(1) + expect(targetSeen[0].url).toBe('/landed') + }) +})