Repository navigation
feat(supabase): add canonical CORS headers export for edge functions - #2071
Conversation
📝 WalkthroughWalkthroughAdds a canonical CORS module and export, new Deno edge functions and comprehensive CORS tests, local Supabase setup/cleanup scripts, switches preview CI to use pkg.pr.new preview artifacts via a reusable integration-tests workflow, and removes Verdaccio/local-registry plumbing. Changes
Sequence Diagram(s)sequenceDiagram
autonumber
participant Preview as "preview-release"
participant Updater as "scripts/update-pkg-pr-urls.sh"
participant Reusable as "integration-tests (reusable)"
participant Supabase as "Local Supabase (test:supabase:setup)"
participant Runners as "Test runners (Deno/Node/Browser/Platforms)"
Preview->>Preview: compute commit_hash
Preview->>Updater: run update-pkg-pr-urls.sh(commit_hash)
Updater-->>Preview: manifests updated (replace {COMMIT_HASH})
Preview->>Reusable: invoke integration-tests (with commit_hash)
Reusable->>Supabase: run test:supabase:setup (start services & functions)
Reusable->>Runners: execute tests against pkg.pr.new artifacts
Runners-->>Reusable: return results
Reusable->>Supabase: run test:supabase:stop
Reusable-->>Preview: publish test outcome
Estimated code review effort🎯 4 (Complex) | ⏱️ ~45 minutes Possibly related PRs
Suggested reviewers
🚥 Pre-merge checks | ✅ 3✅ Passed checks (3 passed)
✏️ Tip: You can configure your own custom pre-merge checks in the settings. ✨ Finishing touches
🧪 Generate unit tests (beta)
Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out. Comment |
@supabase/auth-js
@supabase/functions-js
@supabase/postgrest-js
@supabase/realtime-js
@supabase/storage-js
@supabase/supabase-js
commit: |
1cd791f to
009de37
Compare
There was a problem hiding this comment.
Actionable comments posted: 5
🤖 Fix all issues with AI agents
In `@packages/core/supabase-js/src/cors.ts`:
- Around line 81-88: The code currently allows origin?: string | string[] and
joins arrays into a comma list (invalid for Access-Control-Allow-Origin); update
createCorsHeaders to accept only a single origin string (or throw/error if an
array is provided) and update the JSDoc for origin to document that callers must
supply a single origin (e.g., by using
validateOrigin(request.headers.get('Origin')) before calling createCorsHeaders).
If you instead want dynamic allowlist behavior, implement logic that reads the
incoming Origin header, validates it against an allowlist (use or add a
validateOrigin function), then echo back only that single origin in
Access-Control-Allow-Origin and add Vary: Origin; do not join arrays into a
comma-separated header value. Ensure references to createCorsHeaders,
validateOrigin, and the origin?: string | string[] type are updated accordingly.
In `@packages/core/supabase-js/supabase/functions/cors-http-methods/index.ts`:
- Around line 6-48: The handler currently returns a body for 204/OPTIONS and for
HEAD requests which breaks HTTP semantics; change the OPTIONS branch (where new
Response('ok', { status: 204, headers: corsHeaders })) to return a null/empty
body (e.g., new Response(null, ...)) and ensure the final response logic that
builds JSON (the Response(JSON.stringify(responseData), ...)) returns an
empty/null body when req.method === 'HEAD' (keep headers intact) so HEAD and 204
responses have no body while other methods continue returning the JSON payload.
In `@packages/core/supabase-js/test/deno/cors-http-methods.test.ts`:
- Around line 11-21: The test's POST isn't CORS-simple because it uses
'application/json'; update the fetch in the simpleMethods loop (variable
simpleMethods and the fetch call using functionUrl) to use a simple content
type—e.g., set headers['Content-Type'] = 'text/plain' and send a plain string
body for POST (or remove the Content-Type/header and body entirely) so the POST
is CORS-simple and the test matches real CORS semantics.
In `@packages/core/supabase-js/test/deno/cors-validation.test.ts`:
- Around line 1-2: Remove the unused import "node:buffer" at the top of the test
file: delete the line import 'node:buffer' since the file only uses Deno.test,
fetch and std assertions (assertEquals, assertExists) and that import is not
referenced anywhere.
In `@packages/core/supabase-js/test/module-resolution-cors.test.mjs`:
- Around line 49-53: The test currently uses includes() on the comma-separated
string corsHeaders['Access-Control-Allow-Headers'] (allowedHeaders), which can
yield false positives by matching substrings; change the check to split
allowedHeaders on commas, trim each token and normalize case (e.g., toLowerCase)
into an array, then for each header in requiredHeaders compare exact tokens
(also normalized) and throw the Error if a required header is not present;
update the loop that iterates requiredHeaders to use this tokenized list for
exact matching.
🧹 Nitpick comments (3)
packages/core/supabase-js/test/deno/package.json (1)
7-10: Avoid repeating setup-deps intest:cors-all.
Right nowtest:cors-allrunssetup-depsthree times via the sub-scripts. Consider running it once and then invoking the tests directly.♻️ Suggested adjustment
- "test:cors-all": "npm run test:cors-validation && npm run test:cors-http-methods && npm run test:cors-errors", + "test:cors-all": "npm run setup-deps && node run-deno-test.js cors-validation.test.ts && node run-deno-test.js cors-http-methods.test.ts && node run-deno-test.js cors-errors.test.ts",packages/core/supabase-js/test/types/cors.test-d.ts (1)
8-8: UnusedexpectErrorimport.The
expectErrorfunction is imported but never used in the test file. Consider removing it or adding test cases that verify type errors are correctly raised (e.g., passing invalid option types tocreateCorsHeaders).♻️ Suggested fix
-import { expectType, expectAssignable, expectNotAssignable, expectError } from 'tsd' +import { expectType, expectAssignable, expectNotAssignable } from 'tsd'Alternatively, add type error tests:
// Test: createCorsHeaders rejects invalid options expectError(createCorsHeaders({ origin: 123 })) expectError(createCorsHeaders({ credentials: 'yes' }))packages/core/supabase-js/test/deno/cors-validation.test.ts (1)
39-84: Consider extracting header/method validation helpers.The header and method validation loops are duplicated patterns. Consider extracting a helper function to reduce verbosity:
function assertContainsAll(actual: string, required: string[], label: string) { const normalizedActual = actual.toLowerCase() for (const item of required) { if (!normalizedActual.includes(item.toLowerCase())) { throw new Error(`Required ${label} "${item}" not found in: ${actual}`) } } }This is optional as the current code is readable and explicit.
4a81788 to
d9119d8
Compare
There was a problem hiding this comment.
Actionable comments posted: 1
🤖 Fix all issues with AI agents
In `@packages/core/supabase-js/test/deno/cors-validation.test.ts`:
- Around line 17-28: The test name "OPTIONS preflight - should return 204
status" and the assertion in the t.step callback are inconsistent: update the
assertion that checks the response status to expect 204 (change the
assertEquals(response.status, 200) to assertEquals(response.status, 204)) so the
t.step block that performs the fetch (using functionUrl and the response
variable) matches the test name and the similar preflight check later in the
file.
🧹 Nitpick comments (2)
packages/core/supabase-js/src/cors.ts (1)
157-166: Consider clarifying the dynamic validation example.The example shows
origin: validatedOrigin || '*'as a fallback, butvalidateOrigin()returns a boolean, not the origin string. The pattern should use the request origin directly after validation:const requestOrigin = req.headers.get('Origin') if (!validateOrigin(requestOrigin, allowedOrigins)) { return new Response('Forbidden', { status: 403 }) } const corsHeaders = createCorsHeaders({ origin: requestOrigin || '*' // requestOrigin, not validatedOrigin })The actual example in
validateOrigin's JSDoc (lines 232-256) shows this correctly.packages/core/supabase-js/test/deno/cors-validation.test.ts (1)
60-65: Use exact token matching for header validation.The current implementation uses
allowedHeadersLower.includes(header.toLowerCase())which performs substring matching on the comma-separated string. This could cause false positives (e.g.,'accept'matching inside'accept-profile').For consistency with the fix applied to
module-resolution-cors.test.mjs, use split + trim for exact token matching:♻️ Suggested fix
- const allowedHeadersLower = allowedHeaders.toLowerCase() - requiredHeaders.forEach((header) => { - if (!allowedHeadersLower.includes(header.toLowerCase())) { - throw new Error(`Required header "${header}" not found in: ${allowedHeaders}`) - } - }) + const allowedHeaderTokens = allowedHeaders.split(',').map((h) => h.trim().toLowerCase()) + requiredHeaders.forEach((header) => { + if (!allowedHeaderTokens.includes(header.toLowerCase())) { + throw new Error(`Required header "${header}" not found in: ${allowedHeaders}`) + } + })
f7bb6fb to
cadfcb4
Compare
There was a problem hiding this comment.
Actionable comments posted: 1
🤖 Fix all issues with AI agents
In `@packages/core/supabase-js/test/unit/cors.test.ts`:
- Around line 66-72: The test expects createCorsHeaders to throw when origin is
an array but the implementation lacks this check; update createCorsHeaders to
validate the origin parameter (in packages/core/supabase-js/src/cors.ts) by
detecting if origin is an Array and throwing Error('Access-Control-Allow-Origin
does not support multiple origins'), or alternatively remove/adjust the test to
match current behavior—preferably add the array check inside createCorsHeaders
so functions like createCorsHeaders(...) and any callers consistently reject
array origins with the exact message the test asserts.
🧹 Nitpick comments (2)
packages/core/supabase-js/test/types/cors.test-d.ts (1)
44-45: Type test may mislead about runtime behavior.This tests that
createCorsHeaders({ credentials: true })compiles, but at runtime this will throw becausecredentials: truewith the defaultorigin: '*'is invalid. While type tests focus on compile-time validity, consider adding a comment clarifying this is a type-only check and the call would throw at runtime.💡 Suggested clarification
// Test: createCorsHeaders with credentials +// Note: This tests type validity only; at runtime, credentials: true without +// an explicit origin would throw (default origin is '*') expectType<CorsHeaders>(createCorsHeaders({ credentials: true }))packages/core/supabase-js/test/unit/cors.test.ts (1)
16-30: Consider exact token matching for header validation.Similar to the ESM test fix, using
toContainon the comma-separated header string could theoretically produce false positives (e.g.,acceptmatching insideaccept-profile). While the current header names don't overlap in practice, consider using exact token matching for consistency with the module resolution tests.💡 Suggested approach
it('should include all Supabase custom headers', () => { const allowedHeaders = corsHeaders['Access-Control-Allow-Headers'] const headerTokens = allowedHeaders.split(',').map((h) => h.trim().toLowerCase()) const requiredHeaders = [ 'authorization', 'x-client-info', 'apikey', 'content-type', 'x-supabase-api-version', 'accept-profile', 'content-profile', 'prefer', 'accept', 'x-region', ] for (const header of requiredHeaders) { expect(headerTokens).toContain(header) } })
There was a problem hiding this comment.
Actionable comments posted: 1
🤖 Fix all issues with AI agents
In `@packages/core/supabase-js/package.json`:
- Around line 68-71: The package supabase-js's package.json is missing tsd in
devDependencies while the "test:types" npm script invokes tsd; add "tsd"
(matching the workspace version or a compatible semver) to the devDependencies
section of packages/core/supabase-js/package.json so the "test:types" script can
run reliably in all environments, ensuring the script name "test:types" and the
devDependencies entry for "tsd" are present and versioned appropriately.
ae3a7c1 to
5306823
Compare
There was a problem hiding this comment.
Actionable comments posted: 2
🤖 Fix all issues with AI agents
In `@packages/core/supabase-js/src/cors.ts`:
- Around line 151-156: Remove the two module-level console.log statements in
cors.ts that reference corsHeaders['Access-Control-Allow-Origin'] and the
timestamp (they run on import and pollute consumer output); either delete those
console.log calls entirely or replace them with a gated debug logger (e.g., only
emit when a DEBUG env/flag is set or via an exported logger) so normal imports
do not print to stdout. Ensure references to corsHeaders remain untouched except
for removing the debug prints.
In `@packages/core/supabase-js/test/module-resolution-cors.test.cjs`:
- Around line 49-54: The test currently uses includes() on the raw string
corsHeaders['Access-Control-Allow-Headers'] (bound to allowedHeaders), which can
yield false positives; instead parse allowedHeaders into an array by splitting
on commas, trim each entry and normalize case, then check each requiredHeaders
entry against the array using exact equality (e.g., create a Set of
trimmed/lowercased allowed header names and verify every header from
requiredHeaders is present in that Set) so comparisons are exact rather than
substring-based.
bc27648 to
4f30f87
Compare
There was a problem hiding this comment.
Actionable comments posted: 3
🤖 Fix all issues with AI agents
In @.github/workflows/ci-supabase-js.yml:
- Around line 210-228: The workflow uses backgrounded test commands (npx nx
test:deno:all, npx nx test:integration, npx nx test:integration:browser, and the
second group npx nx test:next, npx nx test:expo, npx nx test:bun) and then calls
wait without tracking PIDs which can swallow failures; update the script to
capture each background job's PID (use $! after each npx command), store them
(e.g., in an array or distinct variables), then call wait on each PID and check
each wait's exit status, exiting the step with a non-zero code if any waited PID
fails so that any failing test causes the job to fail; apply this
PID-capture-and-check pattern for both the core integration group
(functions/commands: npx nx test:deno:all, npx nx test:integration, npx nx
test:integration:browser) and the platform-specific group (npx nx test:next, npx
nx test:expo, npx nx test:bun).
In `@packages/core/supabase-js/scripts/cleanup-supabase.sh`:
- Around line 8-16: The cleanup block that stops functions currently removes
/tmp/supabase-functions.pid but leaves /tmp/supabase-functions.log behind;
update the logic in the same block that handles FUNCTIONS_PID (the PID-file
check/kill/remove sequence) to also remove the corresponding log file
(/tmp/supabase-functions.log) after the PID file is deleted, ensuring you check
for the log file's existence before attempting to delete it so there are no
errors when the log is already absent.
In `@packages/core/supabase-js/scripts/setup-supabase.sh`:
- Around line 29-34: The script currently exports SUPABASE_ANON_KEY and
SUPABASE_SERVICE_ROLE_KEY via shell export which won’t persist across GitHub
Actions steps; instead run the status commands into temporary variables,
validate they are non-empty and not "null" (fail early if they are), and then
persist them to GITHUB_ENV by appending lines like SUPABASE_ANON_KEY=... and
SUPABASE_SERVICE_ROLE_KEY=... to the file referenced by $GITHUB_ENV; locate the
assignments to SUPABASE_ANON_KEY and SUPABASE_SERVICE_ROLE_KEY in the script and
replace the direct export with a two-step assign-and-validate plus echo >>
$GITHUB_ENV approach so downstream steps see the values.
🧹 Nitpick comments (1)
packages/core/supabase-js/scripts/setup-supabase.sh (1)
9-15: Add a process health check after starting background functions.The
supabase functions serveprocess may exit immediately (port already in use, missing dependencies, etc.), but the script continues running and only fails later during the curl test at line 38 with an unclear error. Add a check usingkill -0right after the sleep to verify the process is still running and exit with a clear diagnostic message if not.🔍 Suggested safeguard
npx supabase functions serve > /tmp/supabase-functions.log 2>&1 & FUNCTIONS_PID=$! echo $FUNCTIONS_PID > /tmp/supabase-functions.pid echo "Functions PID: $FUNCTIONS_PID" sleep 3 +if ! kill -0 "$FUNCTIONS_PID" 2>/dev/null; then + echo "❌ Functions process exited. See /tmp/supabase-functions.log" + exit 1 +fi
d1db940 to
0cbc5bf
Compare
There was a problem hiding this comment.
Actionable comments posted: 1
🤖 Fix all issues with AI agents
In `@scripts/update-pkg-pr-urls.sh`:
- Around line 31-47: The script currently only warns when no {COMMIT_HASH}
placeholders are found and still exits 0; change it to fail the script (exit
non‑zero) when no placeholders exist or when no replacements were made.
Specifically, before running sed, use grep on "$file" to check for the literal
"{COMMIT_HASH}" (or count matches) and if none are found print an error and exit
1; after running the sed replacement check that grep for "$COMMIT_HASH" returns
at least one match (or compare counts before/after) and if zero, print an error
and exit 1; update the echo lines around the checks to reflect failure instead
of success. Ensure you reference and use the COMMIT_HASH and "$file" variables
and preserve macOS/Linux sed branches.
🧹 Nitpick comments (1)
scripts/update-pkg-pr-urls.sh (1)
1-3: Considerset -euo pipefailfor stricter error detection.
It helps catch unset vars and pipeline failures in a file‑mutating script.Proposed change
-#!/bin/bash -set -e +#!/bin/bash +set -euo pipefail
9646512 to
9218b23
Compare
There was a problem hiding this comment.
Actionable comments posted: 1
🤖 Fix all issues with AI agents
In @.github/workflows/preview-release.yml:
- Around line 61-70: The step "Get commit hash" writes to $GITHUB_OUTPUT without
quoting which can cause word-splitting (SC2086); update the echo that appends
"sha=$COMMIT_SHA" to quote the variable and the output file by changing the
append command to use quoted expansions (refer to COMMIT_SHA and GITHUB_OUTPUT
in this step) so the line becomes an echo that redirects to "$GITHUB_OUTPUT"
with the value quoted.
🧹 Nitpick comments (1)
.github/workflows/integration-tests.yml (1)
92-109: Quote$GITHUB_WORKSPACEto satisfy shellcheck.The
$GITHUB_WORKSPACEvariable should be quoted to prevent potential word splitting. Static analysis (SC2086) flagged these occurrences.🛠️ Proposed fix
cd packages/core/supabase-js/test/integration/next npm install --legacy-peer-deps - cd $GITHUB_WORKSPACE + cd "$GITHUB_WORKSPACE" cd packages/core/supabase-js/test/integration/expo npm install --legacy-peer-deps - cd $GITHUB_WORKSPACE + cd "$GITHUB_WORKSPACE" cd packages/core/supabase-js/test/integration/bun bun install - cd $GITHUB_WORKSPACE + cd "$GITHUB_WORKSPACE"
There was a problem hiding this comment.
Actionable comments posted: 2
🤖 Fix all issues with AI agents
In `@packages/core/supabase-js/project.json`:
- Around line 40-79: The Deno test targets that hit a local Supabase instance
(e.g., test:deno:integration and test:deno:edge-functions) must start Supabase
before running; update each target's dependsOn from ["test:deno:setup"] to
["test:supabase:setup", "test:deno:setup"] so the test:supabase:setup task runs
first, and apply the same change to any other Deno targets that perform real
DB/function calls (e.g., add test:supabase:setup to test:deno:cors-validation,
test:deno:cors-http-methods, test:deno:cors-errors if they require the running
instance).
- Around line 33-39: The "test:deno:setup" Nx target currently runs "npm install
&& deno install" which fails because test/deno is not in the workspace and its
local dependencies cannot be resolved; update the target (named
"test:deno:setup" with executor "nx:run-commands") to remove the "npm install"
step so the command is just "deno install" to match how run-deno-test.js runs
Deno and relies on deno.json import maps.
There was a problem hiding this comment.
Actionable comments posted: 1
🤖 Fix all issues with AI agents
In @.github/workflows/integration-tests.yml:
- Around line 77-90: The CI step that verifies edge functions uses a plain curl
invocation (RESPONSE/HTTP_CODE) which can hang; update the "Verify edge
functions" block to use curl timeouts (e.g., --connect-timeout and --max-time)
and wrap the POST probe in a bounded retry loop that attempts the curl up to N
times with a short sleep between tries, breaking on 200 and failing after max
attempts; ensure you still populate RESPONSE/HTTP_CODE, print the final status
and dump /tmp/supabase-functions.log on failure so diagnostics remain available.
🧹 Nitpick comments (2)
.github/workflows/integration-tests.yml (1)
5-15: Add least‑privilege workflow permissions.Default
GITHUB_TOKENpermissions are broader than needed here. Restricting tocontents: readreduces blast radius without affecting this workflow.🔒 Proposed change
on: workflow_call: inputs: commit_hash: description: 'Git commit hash for pkg.pr.new URLs' required: true type: string + +permissions: + contents: readpackages/core/supabase-js/project.json (1)
40-79: Consider addinginputsto Deno test targets for Nx affected/caching consistency.♻️ Suggested update (apply to each Deno test target)
"test:deno:integration": { "executor": "nx:run-commands", + "inputs": ["testing", "^production"], "options": { "command": "node run-deno-test.js integration.test.ts", "cwd": "{projectRoot}/test/deno" }, "dependsOn": ["test:deno:setup"] },
There was a problem hiding this comment.
Actionable comments posted: 2
🤖 Fix all issues with AI agents
In @.github/workflows/integration-tests.yml:
- Around line 35-36: The workflow step "Update pkg.pr.new URLs with commit hash"
passes the commit hash unquoted to the script; wrap the input in quotes when
invoking ./scripts/update-pkg-pr-urls.sh to ensure shell safety (quote ${{
inputs.commit_hash }}), i.e., change the run invocation so the argument is
passed as a single quoted string to update-pkg-pr-urls.sh to prevent
word-splitting or unexpected characters from breaking the call.
- Around line 96-113: In the "Prepare platform test dependencies" step, the
unquoted variable $GITHUB_WORKSPACE is used in cd commands (e.g., after npm/bun
installs); update those cd commands to quote the variable so the shell receives
it as a single argument (i.e., use "$GITHUB_WORKSPACE") to prevent
word-splitting and satisfy shellcheck SC2086 while keeping the existing install
flow for packages/core/supabase-js/test/integration/next, expo, and bun.
There was a problem hiding this comment.
Actionable comments posted: 2
🤖 Fix all issues with AI agents
In `@packages/core/supabase-js/test/deno/cors-validation.test.ts`:
- Around line 54-90: The test currently checks headers/methods using substring
matches (allowedHeadersLower.includes and allowedMethodsUpper.includes) which
allows false positives (e.g., "accept" inside "accept-profile"); change
validation to split the header/method strings into exact token sets and check
membership: parse response.headers.get('Access-Control-Allow-Headers') and
'Access-Control-Allow-Methods' by splitting on commas, trimming, normalizing
case, build Sets, then assert every item in requiredHeaders and requiredMethods
is present in those Sets (refer to variables requiredHeaders,
allowedHeadersLower, requiredMethods, allowedMethodsUpper and the OPTIONS
preflight test block).
- Around line 10-15: Update the in-file test-run instructions in the
cors-validation comment block to tell developers to run the test from the repo
root using Nx instead of running `npm run test:cors-validation` from test/deno;
replace the line that says "Run `npm run test:cors-validation` from test/deno"
with guidance to run "nx run <project>:test:cors-validation" (or the appropriate
Nx target for the packages/core/supabase-js project) from the repository root so
the cors-validation tests are executed via Nx.
1a5ea55 to
6bf22e0
Compare
There was a problem hiding this comment.
Actionable comments posted: 1
🤖 Fix all issues with AI agents
In @.github/workflows/integration-tests.yml:
- Around line 62-70: In the "Install browser dependencies" step, quote the
environment variable usage to avoid word-splitting by replacing mkdir -p
$PUPPETEER_CACHE_DIR with mkdir -p "$PUPPETEER_CACHE_DIR" (reference
PUPPETEER_CACHE_DIR and the Install browser dependencies step) so the workflow
is robust to paths containing spaces and satisfies shellcheck SC2086.
🧹 Nitpick comments (1)
packages/core/supabase-js/scripts/setup-supabase.sh (1)
48-57: Consider exiting with error if all retry attempts fail.The retry loop prints a warning when all 3 attempts fail but still exits successfully. This could mask edge function startup failures, leading to harder-to-diagnose test failures downstream.
♻️ Proposed change to fail on exhausted retries
if [ "$HTTP_CODE" = "200" ]; then echo " ✅ Edge functions responding" break elif [ $i -lt 3 ]; then echo " ⏳ Attempt $i/3 failed (status $HTTP_CODE), retrying..." sleep 3 else - echo " ⚠️ Edge functions may still be initializing (status $HTTP_CODE)" + echo " ❌ Edge functions failed to respond after 3 attempts (status $HTTP_CODE)" + echo " Check /tmp/supabase-functions.log for details" + exit 1 fi done
eb683c0 to
ad86d83
Compare
There was a problem hiding this comment.
Actionable comments posted: 1
🤖 Fix all issues with AI agents
In `@packages/core/supabase-js/supabase/functions/cors-errors/index.ts`:
- Around line 52-57: The catch block that returns a 500 Response currently
accesses error.message (in the catch handling that constructs the Response with
corsHeaders), which assumes the thrown value is an Error; change it to safely
extract the message by checking the caught value (e.g., use instanceof Error or
typeof) and fall back to String(error) or a default message before serializing
to JSON so non-Error throwables won't cause a runtime crash; update the Response
creation in that catch to use the safe message extraction.
🧹 Nitpick comments (5)
packages/core/storage-js/tsdown.config.ts (1)
31-46: LGTM! Robust handling of parallel build race conditions.The error handling correctly addresses the scenario where parallel builds might rename the file concurrently. The ENOENT check ensures the build doesn't fail if the file was already renamed.
One minor observation: the
access()check is technically redundant sincerename()would throw ENOENT anyway if the file doesn't exist, but it does make the intent clearer.Consider using
unknowninstead ofanyfor the caught error to align with stricter TypeScript practices:♻️ Optional type safety improvement
- } catch (err: any) { + } catch (err: unknown) { // Ignore ENOENT errors (file already renamed by parallel build) - if (err?.code !== 'ENOENT') { + if (err instanceof Error && (err as NodeJS.ErrnoException).code !== 'ENOENT') { throw err } }packages/core/supabase-js/test/deno/edge-functions-integration.test.ts (1)
110-117: Nitpick: Redundant assertion inside conditional.The
assertEquals(error, null)on line 112 is tautological since you're already inside theif (!error)branch. Consider removing it.♻️ Suggested cleanup
results.forEach(({ data, error }) => { if (!error) { - assertEquals(error, null) assertExists(data) assertEquals(typeof data.message, 'string') assertEquals(typeof data.timestamp, 'string') } })packages/core/supabase-js/supabase/functions/cors-http-methods/index.ts (1)
37-56: Dynamic property assignment may cause TypeScript errors.The
responseDataobject is implicitly typed at declaration, butreceivedBodyis added conditionally later. This could cause TypeScript strict mode errors. Consider declaring the property upfront with an optional type.♻️ Suggested fix
// Handle all HTTP methods - const responseData = { + const responseData: { + success: boolean + method: string + methodType: string + timestamp: string + corsNote: string + corsHeaders: string[] + receivedBody?: unknown + } = { success: true, method: req.method, methodType, timestamp, corsNote: isSimpleMethod ? 'Simple methods work with basic CORS' : 'Non-simple methods require Access-Control-Allow-Methods header', corsHeaders: Object.keys(corsHeaders), }packages/core/supabase-js/scripts/setup-supabase.sh (1)
34-35: Split declaration and assignment to detect command failures.The
export VAR="$(cmd)"pattern masks the return code of the command substitution. Ifnpx supabase statusorjqfails,set -ewon't catch it becauseexportalways succeeds. This could leave keys empty without any error.🛠️ Suggested fix
echo "🔑 Exporting authentication keys..." -export SUPABASE_ANON_KEY="$(npx supabase status --output json | jq -r '.ANON_KEY')" -export SUPABASE_SERVICE_ROLE_KEY="$(npx supabase status --output json | jq -r '.SERVICE_ROLE_KEY')" +SUPABASE_ANON_KEY="$(npx supabase status --output json | jq -r '.ANON_KEY')" +SUPABASE_SERVICE_ROLE_KEY="$(npx supabase status --output json | jq -r '.SERVICE_ROLE_KEY')" +export SUPABASE_ANON_KEY SUPABASE_SERVICE_ROLE_KEY echo " Keys exported".github/workflows/integration-tests.yml (1)
67-72: Quote$GITHUB_ENVto prevent word splitting.Static analysis (SC2086) flags the unquoted
$GITHUB_ENVon lines 70-71. While unlikely to contain spaces in CI, quoting follows shell best practices.🛠️ Suggested fix
- name: Export auth keys run: | cd packages/core/supabase-js - echo SUPABASE_ANON_KEY="$(npx supabase status --output json | jq -r '.ANON_KEY')" >> $GITHUB_ENV - echo SUPABASE_SERVICE_ROLE_KEY="$(npx supabase status --output json | jq -r '.SERVICE_ROLE_KEY')" >> $GITHUB_ENV + echo "SUPABASE_ANON_KEY=$(npx supabase status --output json | jq -r '.ANON_KEY')" >> "$GITHUB_ENV" + echo "SUPABASE_SERVICE_ROLE_KEY=$(npx supabase status --output json | jq -r '.SERVICE_ROLE_KEY')" >> "$GITHUB_ENV" echo "✅ Keys exported"
There was a problem hiding this comment.
Actionable comments posted: 2
🤖 Fix all issues with AI agents
In `@packages/core/supabase-js/test/deno/cors-validation.test.ts`:
- Around line 54-60: The test comment claiming "All 10 current Supabase headers
must be allowed" is inconsistent with the actual requiredHeaders array; update
the comment or the array to match: either change the comment to state that the
test checks a minimal subset (e.g., "Check required Supabase headers") or add
the remaining Supabase header names to the requiredHeaders array in
cors-validation.test.ts so the assertion truly covers all 10 headers (modify the
requiredHeaders variable to include the missing header strings).
- Around line 112-152: The test currently only makes an OPTIONS call
(preflightResponse) and a POST but never asserts that
Access-Control-Allow-Headers actually permits the new header; update the test to
inspect preflightResponse.headers.get('access-control-allow-headers') (or
equivalent) and assert it includes 'x-supabase-new-feature' (or '*' if the
function intentionally allows all headers), or if the intended policy is
wildcard, change the test comment to state that Access-Control-Allow-Headers: *
is expected; use the existing preflightResponse variable and keep
assertPreflightStatus checks but add an assertion on the allow-headers value to
validate CORS behavior.
68eeb23 to
0b4b409
Compare
0b4b409 to
9649669
Compare
v2.95.0 of the supabase-js sdk has been released, which contains supabase/supabase-js#2071 <!-- This is an auto-generated comment: release notes by coderabbit.ai --> ## Summary by CodeRabbit * **Documentation** * Updated guides and examples to recommend using CORS headers from the Supabase JS SDK (v2.95.0+) instead of manually defining headers. * Examples now show the SDK-based approach and include a clear fallback path for older SDK versions that require hardcoded headers. * Added notes that SDK header updates will be reflected automatically in edge functions. <!-- end of auto-generated comment: release notes by coderabbit.ai -->
v2.95.0 of the supabase-js sdk has been released, which contains supabase/supabase-js#2071 <!-- This is an auto-generated comment: release notes by coderabbit.ai --> ## Summary by CodeRabbit * **Documentation** * Updated guides and examples to recommend using CORS headers from the Supabase JS SDK (v2.95.0+) instead of manually defining headers. * Examples now show the SDK-based approach and include a clear fallback path for older SDK versions that require hardcoded headers. * Added notes that SDK header updates will be reflected automatically in edge functions. <!-- end of auto-generated comment: release notes by coderabbit.ai -->
Tests: Change how integration tests are ran
pkg.pr.newfor integration testsFeature: helper to return CORS headers
Exports canonical CORS configuration from
@supabase/supabase-js/corsto prevent CORS errors in Edge Functions when new headers are added to the SDK.What's New
corsHeaders- Default CORS config with all Supabase headersProblem Solved
Previously, Edge Functions used hardcoded CORS headers from docs. When
supabase-jsv2.93.0added new headers, all Edge Functions broke with CORS errors, requiring an emergency revert tov2.93.2.Solution
Edge Functions now import CORS headers directly from the SDK, ensuring automatic synchronization. When new headers are added, Edge Functions get them automatically on SDK update.
Before:
After:
Migration Strategy
Summary by CodeRabbit
New Features
Tests
Documentation
Chores / CI