You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
{{ message }}
Repository navigation
fix: pass withSupabase error responses through middleware seam - #139
Middleware entries in withSupabase's middleware array never observed the responses withSupabase builds itself. This PR routes those responses through the array's response phase, with guards.
Scope
Behavior with a response-seam middleware in the array
Status
WWW-Authenticate (and any decoration) on auth-generated 401s
✅ Fixed
Decoration of client-construction error responses
✅ Fixed
Silent failure on misplaced pre-auth middleware
✅ Fixed (runtime warning)
Serving OAuth discovery from inside the array
❌ Out of scope (needs pre-auth placement)
Middleware's own OPTIONS/preflight handling from inside the array
❌ Out of scope (needs pre-auth placement)
The wrap form — withOAuthProtectedResource(cfg, withSupabase(cfg, handler)) or pipeline([withOAuthProtectedResource(cfg)], withSupabase(cfg, handler)) — remains the supported placement for the full OAuth flow. A placement support table is added to docs/api-reference.md.
Problem
Auth failures and client-construction failures returned directly, so an entry like withOAuthProtectedResource could not attach WWW-Authenticate to a 401. MCP clients got a bare 401 with no pointer to the authorization server, and nothing failed loudly.
Fix
The middleware chain folds once at wrap time around a dual-purpose terminal: normally it calls the user handler; when the context carries a withSupabase-built error response under a private symbol key, it returns that response so entries run their response phase against it. Folding once means entry state (rate-limit counters, caches) is shared between the success and error paths, so a rate limiter genuinely throttles repeated bad-auth traffic.
Guards bound the semantics:
Same-status rule: an entry can decorate an error response but cannot swap it for a different-status one, so a request-phase short-circuit cannot bypass the auth gate.
Header restoration: a same-status replacement gets the original error response's headers (CORS, the exposed error-code header) re-applied where the entry set no value of its own; body-derived headers stay the replacement's.
Body restoration: an entry that drains the body (logging) gets it rebuilt from a fresh copy; header decorations survive.
Crash fallback: an entry that throws on this path is logged via console.error and the plain error response is returned.
On auth failure the context carries userClaims: null and jwtClaims: null, with no auth mode or clients; on client-construction failure the verified claims and auth mode are present and only the clients are absent. The OPTIONS/CORS short-circuit is unchanged, and nothing changes when middleware is absent or empty.
withOAuthProtectedResource warns once per process when it detects (via a private context marker, not key names) that it sits inside a withSupabase array.
Tests
Fourteen new unit tests cover the routing on both error paths, the same-status and crash guards, entry-state persistence across error-path requests, header and body restoration, the context shape on each path, the in-array 401 enrichment, discovery staying wrap-form, and the placement warning (including no false positive from an unrelated userClaims key).
Validation
Tested end-to-end against a real MCP Edge Function in supabase-community/edge-function-mcp-sandbox#11: 401 enrichment works, authenticated MCP calls unaffected, discovery/preflight behave as documented, warning fires.
This PR routed withSupabase's own error responses through the middleware array (option D in the design doc). It fixed the missing WWW-Authenticate header on auth 401s, but it could not fix OAuth discovery or the metadata preflight: those need middleware to run before the auth gate, and the array is a post-auth-only slot.
Decision (2026-09-04): retire the middleware array on withSupabase and make withSupabase a pipeline entry, built with defineComposite (supabase/middleware#36). Placement is then decided by array position, so all three symptoms are fixed by where the middleware sits:
Thanks to @raulb for the end-to-end validation in supabase-community/edge-function-mcp-sandbox#11, which confirmed the symptom table. The withOAuthProtectedResource placement reference from this PR's docs returns in the follow-up, showing the wrap and pipeline forms.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
Middleware entries in
withSupabase'smiddlewarearray never observed the responseswithSupabasebuilds itself. This PR routes those responses through the array's response phase, with guards.Scope
WWW-Authenticate(and any decoration) on auth-generated401sOPTIONS/preflight handling from inside the arrayThe wrap form —
withOAuthProtectedResource(cfg, withSupabase(cfg, handler))orpipeline([withOAuthProtectedResource(cfg)], withSupabase(cfg, handler))— remains the supported placement for the full OAuth flow. A placement support table is added todocs/api-reference.md.Problem
Auth failures and client-construction failures returned directly, so an entry like
withOAuthProtectedResourcecould not attachWWW-Authenticateto a 401. MCP clients got a bare 401 with no pointer to the authorization server, and nothing failed loudly.Fix
The middleware chain folds once at wrap time around a dual-purpose terminal: normally it calls the user handler; when the context carries a
withSupabase-built error response under a private symbol key, it returns that response so entries run their response phase against it. Folding once means entry state (rate-limit counters, caches) is shared between the success and error paths, so a rate limiter genuinely throttles repeated bad-auth traffic.Guards bound the semantics:
console.errorand the plain error response is returned.On auth failure the context carries
userClaims: nullandjwtClaims: null, with no auth mode or clients; on client-construction failure the verified claims and auth mode are present and only the clients are absent. The OPTIONS/CORS short-circuit is unchanged, and nothing changes whenmiddlewareis absent or empty.withOAuthProtectedResourcewarns once per process when it detects (via a private context marker, not key names) that it sits inside awithSupabasearray.Tests
Fourteen new unit tests cover the routing on both error paths, the same-status and crash guards, entry-state persistence across error-path requests, header and body restoration, the context shape on each path, the in-array 401 enrichment, discovery staying wrap-form, and the placement warning (including no false positive from an unrelated
userClaimskey).Validation
Tested end-to-end against a real MCP Edge Function in supabase-community/edge-function-mcp-sandbox#11: 401 enrichment works, authenticated MCP calls unaffected, discovery/preflight behave as documented, warning fires.
🤖 Generated with Claude Code