diff --git a/README.md b/README.md index 8d7ece9..25f0ae5 100644 --- a/README.md +++ b/README.md @@ -263,12 +263,12 @@ withSupabase( `env` overrides environment variable resolution. Defaults to reading `SUPABASE_URL`, `SUPABASE_PUBLISHABLE_KEYS`, `SUPABASE_SECRET_KEYS`, and `SUPABASE_JWKS` from the runtime environment. -`middleware` composes additional entries onto the context — they run after the Supabase context is established and contribute their own typed keys. The first-party entries live on the `@supabase/server/middleware/*` subpaths; see [Postgres](#postgres-rls-scoped-queries). +Called with config only, `withSupabase(config)` returns an entry for `pipeline` from `@supabase/middleware`. Entries placed after it in the array receive the Supabase context and contribute their own typed keys; entries placed before it run ahead of the auth gate. The first-party entries live on the `@supabase/server/middleware/*` subpaths; see [Postgres](#postgres-rls-scoped-queries). -> **Alpha.** The `middleware` option and the `@supabase/server/middleware/*` -> subpaths track `@supabase/middleware` 0.x — entry shapes, context keys, and -> config options may change between 0.x releases. Everything else in -> `@supabase/server` is stable. +> **Alpha.** Composing `withSupabase` as a `pipeline` entry and the +> `@supabase/server/middleware/*` subpaths track `@supabase/middleware` 0.x — +> entry shapes and context keys may change between 0.x releases. The +> `withSupabase(config, handler)` form is stable. ## Framework Adapters @@ -447,20 +447,21 @@ export default { ## Postgres (RLS-scoped queries) -> **Alpha.** The `middleware` option and the `@supabase/server/middleware/*` -> subpaths track `@supabase/middleware` 0.x — entry shapes, context keys, and -> config options may change between 0.x releases. Everything else in -> `@supabase/server` is stable. +> **Alpha.** Composing `withSupabase` as a `pipeline` entry and the +> `@supabase/server/middleware/*` subpaths track `@supabase/middleware` 0.x — +> entry shapes and context keys may change between 0.x releases. The +> `withSupabase(config, handler)` form is stable. When PostgREST isn't the right tool — joins, CTEs, window functions — `withPostgresClient` puts a direct Postgres connection on `ctx.postgres`, scoped to the caller by RLS: ```ts +import { pipeline } from '@supabase/middleware' import { withSupabase } from '@supabase/server' import { withPostgresClient } from '@supabase/server/middleware/postgres' export default { - fetch: withSupabase( - { auth: 'user', middleware: [withPostgresClient()] }, + fetch: pipeline( + [withSupabase({ auth: 'user' }), withPostgresClient()], async (_req, ctx) => { // No WHERE clause — RLS scopes the rows to the caller. const notes = await ctx.postgres.query`select id, body from notes` @@ -477,10 +478,7 @@ When a handler legitimately needs to cross user boundaries, `withPostgresAdminCl ```ts import { withPostgresAdminClient } from '@supabase/server/middleware/postgres-admin' -withSupabase( - { auth: 'secret', middleware: [withPostgresAdminClient()] }, - handler, -) +pipeline([withSupabase({ auth: 'secret' }), withPostgresAdminClient()], handler) ``` The pair mirrors `ctx.supabase` / `ctx.supabaseAdmin`, and they share one connection pool. Keeping them as two middleware is deliberate: bypassing RLS stays visible at the composition site, so you can grep for every handler that can do it. diff --git a/docs/api-reference.md b/docs/api-reference.md index 7750e41..9881fd3 100644 --- a/docs/api-reference.md +++ b/docs/api-reference.md @@ -21,27 +21,37 @@ Wraps a fetch handler with auth, CORS, and client creation. Returns a `(req: Req - Verifies credentials per `config.auth` - Returns JSON error response on auth failure - Adds CORS headers to all responses +- Buffers the request body at the entry point, so composed middleware and the handler can each read it +- Reading the raw `req.body` stream bypasses the buffer, so a handler that forwards the request with `fetch()` after another layer has read the body rebuilds it from `await req.arrayBuffer()`. -A `middleware` array selects a second overload, which accumulates each entry's -contribution onto the handler's `ctx`: +```ts +function withSupabase( + config: WithSupabaseConfig, +): Entry> +``` + +Called with config only, `withSupabase` is an entry for `pipeline` from `@supabase/middleware`. Position decides what runs before and after the auth gate. A config carrying a `middleware` key is refused when the stack is built; entries compose through `pipeline` or nesting: ```ts -function withSupabase< - Database = unknown, - const Entries extends readonly Entry[] = readonly Entry[], ->( - config: WithSupabaseConfig & { middleware: Entries }, - handler: ( - req: Request, - ctx: SupabaseContext & MiddlewareCtx, - ) => Promise, -): (req: Request) => Promise +import { pipeline } from '@supabase/middleware' +import { withOAuthProtectedResource, withSupabase } from '@supabase/server' +import { withPostgresClient } from '@supabase/server/middleware/postgres' + +pipeline( + [ + withOAuthProtectedResource(), + withSupabase({ auth: 'user' }), + withPostgresClient(), + ], + handler, +) ``` -> **Alpha.** The `middleware` option and the `@supabase/server/middleware/*` -> subpaths track `@supabase/middleware` 0.x — entry shapes, context keys, and -> config options may change between 0.x releases. Everything else in -> `@supabase/server` is stable. +Entries before `withSupabase` see every request, including unauthenticated ones, and observe its `401` responses on the way out. Entries after it receive the full `SupabaseContext` and may declare prerequisites on its keys; an entry contributing one of those keys is a compile-time conflict. Nesting works the same way: `withOAuthProtectedResource(withSupabase(config, handler))` places the OAuth middleware ahead of the gate, `withSupabase(config, withPostgresClient(handler))` places Postgres behind it. Placing `withOAuthProtectedResource` directly after `withSupabase` with an auth mode that requires credentials is refused when the stack is built; a pre-auth middleware separated from `withSupabase` by another entry is not detected and must be ordered by hand. + +> **Alpha.** The entry form and the `@supabase/server/middleware/*` subpaths +> track `@supabase/middleware` 0.x — entry shapes and context keys may change +> between 0.x releases. Everything else in `@supabase/server` is stable. ### createSupabaseContext @@ -189,10 +199,10 @@ Defaults to `auth: 'user'` when config is omitted. ## @supabase/server/middleware/claims -> **Alpha.** The `middleware` option and the `@supabase/server/middleware/*` -> subpaths track `@supabase/middleware` 0.x — entry shapes, context keys, and -> config options may change between 0.x releases. Everything else in -> `@supabase/server` is stable. +> **Alpha.** Composing `withSupabase` as a `pipeline` entry and the +> `@supabase/server/middleware/*` subpaths track `@supabase/middleware` 0.x — +> entry shapes and context keys may change between 0.x releases. The +> `withSupabase(config, handler)` form is stable. ### withClaims @@ -232,10 +242,10 @@ Defaults to `SUPABASE_JWKS` (inline JSON) or `SUPABASE_JWKS_URL` (https endpoint ## @supabase/server/middleware/required-claims -> **Alpha.** The `middleware` option and the `@supabase/server/middleware/*` -> subpaths track `@supabase/middleware` 0.x — entry shapes, context keys, and -> config options may change between 0.x releases. Everything else in -> `@supabase/server` is stable. +> **Alpha.** Composing `withSupabase` as a `pipeline` entry and the +> `@supabase/server/middleware/*` subpaths track `@supabase/middleware` 0.x — +> entry shapes and context keys may change between 0.x releases. The +> `withSupabase(config, handler)` form is stable. ### withRequiredClaims @@ -273,7 +283,7 @@ pipeline([withRequiredClaims(), withPostgresClient()], async (req, ctx) => { The gate's 401 and 500 short-circuits carry no CORS headers, and a bare pipeline answers no `OPTIONS` preflight. For browser callers, compose `withCors` (`@supabase/middleware/cors`) ahead of the gate: it answers preflight before the gate runs and stamps `Access-Control-*` headers on the gate's short-circuit responses. -Inside `withSupabase` the context already carries verified `jwtClaims`, so composing the gate through the `middleware` option is a compile-time conflict. Use `withSupabase({ auth: 'user' })` to gate that path. +After `withSupabase` in a `pipeline` the context already carries verified `jwtClaims`, so placing the gate there is a compile-time conflict. Use `withSupabase({ auth: 'user' })` to gate that path. The gate contributes `jwtClaims` and nothing else. A handler that needs the full `SupabaseContext` behind an auth gate (for example `ctx.userClaims` or `ctx.authMode`, which no composable entry contributes) uses `withSupabase({ auth: 'user' })` directly. A host that takes an entries array can wrap it as the sole entry. `cors: 'disabled'` leaves CORS handling to the host: @@ -296,10 +306,10 @@ Defaults to `SUPABASE_JWKS` (inline JSON) or `SUPABASE_JWKS_URL` (https endpoint ## @supabase/server/middleware/postgres -> **Alpha.** The `middleware` option and the `@supabase/server/middleware/*` -> subpaths track `@supabase/middleware` 0.x — entry shapes, context keys, and -> config options may change between 0.x releases. Everything else in -> `@supabase/server` is stable. +> **Alpha.** Composing `withSupabase` as a `pipeline` entry and the +> `@supabase/server/middleware/*` subpaths track `@supabase/middleware` 0.x — +> entry shapes and context keys may change between 0.x releases. The +> `withSupabase(config, handler)` form is stable. ### withPostgresClient @@ -397,10 +407,10 @@ The minimal claims shape `withPostgresClient` requires upstream at `ctx.jwtClaim ## @supabase/server/middleware/postgres-admin -> **Alpha.** The `middleware` option and the `@supabase/server/middleware/*` -> subpaths track `@supabase/middleware` 0.x — entry shapes, context keys, and -> config options may change between 0.x releases. Everything else in -> `@supabase/server` is stable. +> **Alpha.** Composing `withSupabase` as a `pipeline` entry and the +> `@supabase/server/middleware/*` subpaths track `@supabase/middleware` 0.x — +> entry shapes and context keys may change between 0.x releases. The +> `withSupabase(config, handler)` form is stable. ### withPostgresAdminClient diff --git a/docs/postgres.md b/docs/postgres.md index 54226a9..706abc2 100644 --- a/docs/postgres.md +++ b/docs/postgres.md @@ -1,9 +1,9 @@ # Postgres (`ctx.postgres`) -> **Alpha.** The `middleware` option and the `@supabase/server/middleware/*` -> subpaths track `@supabase/middleware` 0.x — entry shapes, context keys, and -> config options may change between 0.x releases. Everything else in -> `@supabase/server` is stable. +> **Alpha.** Composing `withSupabase` as a `pipeline` entry and the +> `@supabase/server/middleware/*` subpaths track `@supabase/middleware` 0.x — +> entry shapes and context keys may change between 0.x releases. The +> `withSupabase(config, handler)` form is stable. Two middleware give you a direct Postgres connection, mirroring the `ctx.supabase` / `ctx.supabaseAdmin` pair: @@ -17,12 +17,13 @@ Reach for the scoped one by default. The admin one is a deliberate opt-out, cove `withPostgresClient` puts a direct Postgres connection on `ctx.postgres`, scoped to the calling user by RLS. It is the safe version of "authenticate, then query as the user": you write plain SQL, and Postgres — not your application code — decides which rows the caller may see. ```ts +import { pipeline } from '@supabase/middleware' import { withSupabase } from '@supabase/server' import { withPostgresClient } from '@supabase/server/middleware/postgres' export default { - fetch: withSupabase( - { auth: 'user', middleware: [withPostgresClient()] }, + fetch: pipeline( + [withSupabase({ auth: 'user' }), withPostgresClient()], async (_req, ctx) => { // No WHERE clause — RLS scopes the rows to the caller. const notes = await ctx.postgres.query`select id, body from notes` @@ -136,10 +137,10 @@ Reach for those helpers rather than reading settings by hand. In particular, the `withPostgresClient` needs the caller's verified claims at `ctx.jwtClaims`. That prerequisite is enforced at compile time, so there are exactly two ways to satisfy it. -**Inside `withSupabase`** — the context already carries `jwtClaims`, so compose it directly: +**After `withSupabase`** — the context already carries `jwtClaims`, so place it next in the array: ```ts -withSupabase({ auth: 'user', middleware: [withPostgresClient()] }, handler) +pipeline([withSupabase({ auth: 'user' }), withPostgresClient()], handler) ``` **Standalone** — in a Supabase-agnostic `pipeline`, pair it with [`withClaims`](../src/middleware/claims/index.ts), which verifies the Bearer token against the project JWKS: @@ -180,12 +181,13 @@ Without the grant the query fails with `permission denied` (SQLSTATE `42501`) _b When a handler legitimately needs to cross user boundaries — an admin dashboard, a cron aggregate, a background job — compose `withPostgresAdminClient` instead. It contributes `ctx.postgresAdmin`, which runs queries as-is under the connection-string role: no claim injection, no role switch, no wrapping transaction. ```ts +import { pipeline } from '@supabase/middleware' import { withSupabase } from '@supabase/server' import { withPostgresAdminClient } from '@supabase/server/middleware/postgres-admin' export default { - fetch: withSupabase( - { auth: 'secret', middleware: [withPostgresAdminClient()] }, + fetch: pipeline( + [withSupabase({ auth: 'secret' }), withPostgresAdminClient()], async (_req, ctx) => { const rows = await ctx.postgresAdmin .query`select user_id, count(*) from notes group by user_id` @@ -200,7 +202,14 @@ Unlike the scoped half it declares **no upstream prerequisite** — it never rea Compose both when a handler needs each in turn. They share one pool, and `ctx.postgres` stays RLS-scoped regardless: ```ts -middleware: [withPostgresClient(), withPostgresAdminClient()] +pipeline( + [ + withSupabase({ auth: 'user' }), + withPostgresClient(), + withPostgresAdminClient(), + ], + handler, +) ``` Two things worth being deliberate about: diff --git a/e2e/README.md b/e2e/README.md index 444f5f4..fb3f242 100644 --- a/e2e/README.md +++ b/e2e/README.md @@ -41,7 +41,7 @@ Run a single adapter with `pnpm test:e2e h3`. client is not scoped to the caller) - `apps/core/app.ts` — same surface on the core `withSupabase(config, handler)` fetch wrapper (no adapter) — what an Edge Function deploys, running on Node. - Plus `GET /my-notes-pg` (user, `middleware: [withPostgresClient()]` — a real `pg` + Plus `GET /my-notes-pg` (user, `pipeline([withSupabase({ auth: 'user' }), withPostgresClient()], …)` — a real `pg` connection, same unfiltered query, rows scoped by RLS alone). Only the core and edge apps carry this route: `pg` needs raw TCP, which is precisely the runtime claim under test. diff --git a/e2e/apps/core/app.ts b/e2e/apps/core/app.ts index b5f1a39..7d509f4 100644 --- a/e2e/apps/core/app.ts +++ b/e2e/apps/core/app.ts @@ -7,6 +7,7 @@ // The core wrapper has no router, so routes are dispatched on pathname and // each auth mode gets its own wrapped handler. import { withSupabase } from '../../../dist/index.mjs' +import { pipeline } from '@supabase/middleware' import { withPostgresClient } from '../../../dist/middleware/postgres/index.mjs' import { withPostgresAdminClient } from '../../../dist/middleware/postgres-admin/index.mjs' import type { NoteRow } from '../notes.ts' @@ -53,11 +54,12 @@ const userHandler = withSupabase({ auth: 'user' }, async (req, ctx) => { // It carries no interpolation, so there is nothing to parameterize. const PG_QUERY = 'select id, user_id, body from notes order by created_at' -const postgresHandler = withSupabase( - { - auth: 'user', - middleware: [withPostgresClient(), withPostgresAdminClient()], - }, +const postgresHandler = pipeline( + [ + withSupabase({ auth: 'user' }), + withPostgresClient(), + withPostgresAdminClient(), + ], async (req, ctx) => { const { pathname } = new URL(req.url) if (pathname === '/all-notes-pg') { diff --git a/e2e/supabase/functions/server-e2e/deno.json b/e2e/supabase/functions/server-e2e/deno.json index 6107944..eca9bde 100644 --- a/e2e/supabase/functions/server-e2e/deno.json +++ b/e2e/supabase/functions/server-e2e/deno.json @@ -5,7 +5,7 @@ "@supabase/server/middleware/postgres-admin": "../_vendor/package/dist/middleware/postgres-admin/index.mjs", "@supabase/supabase-js": "npm:@supabase/supabase-js@2", "@supabase/supabase-js/cors": "npm:@supabase/supabase-js@2/cors", - "@supabase/middleware": "npm:@supabase/middleware@0.3.1", + "@supabase/middleware": "npm:@supabase/middleware@0.5.0", "jose": "npm:jose@6", "pg": "npm:pg@8" } diff --git a/e2e/supabase/functions/server-e2e/index.ts b/e2e/supabase/functions/server-e2e/index.ts index 78f4238..67d51b3 100644 --- a/e2e/supabase/functions/server-e2e/index.ts +++ b/e2e/supabase/functions/server-e2e/index.ts @@ -7,6 +7,7 @@ import { withSupabase } from '@supabase/server' import { withPostgresClient } from '@supabase/server/middleware/postgres' import { withPostgresAdminClient } from '@supabase/server/middleware/postgres-admin' +import { pipeline } from '@supabase/middleware' const COLUMNS = 'id, user_id, body' @@ -96,14 +97,12 @@ const PG_QUERY = `select ${COLUMNS} from notes order by created_at` // Both halves composed together, running the identical query: /my-notes-pg is // RLS-scoped, /all-notes-pg bypasses RLS. Same security boundary as the core // app, but on the real Deno runtime. -const postgresHandler = withSupabase( - { - auth: 'user', - middleware: [ - withPostgresClient(pgConfig), - withPostgresAdminClient(pgConfig), - ], - }, +const postgresHandler = pipeline( + [ + withSupabase({ auth: 'user' }), + withPostgresClient(pgConfig), + withPostgresAdminClient(pgConfig), + ], async (req, ctx) => { if (route(req) === '/all-notes-pg') { return Response.json(await ctx.postgresAdmin.queryRaw(PG_QUERY)) diff --git a/jsr.json b/jsr.json index 1fc3856..cbc5ccd 100644 --- a/jsr.json +++ b/jsr.json @@ -18,14 +18,7 @@ "./oauth-protected-resource": "./src/oauth-protected-resource/index.ts" }, "publish": { - "include": [ - "src/**/*.ts", - "README.md", - "LICENSE" - ], - "exclude": [ - "src/**/*.test.ts", - "src/**/*.spec.ts" - ] + "include": ["src/**/*.ts", "README.md", "LICENSE"], + "exclude": ["src/**/*.test.ts", "src/**/*.spec.ts"] } } diff --git a/package.json b/package.json index f97a8aa..8b8b785 100644 --- a/package.json +++ b/package.json @@ -256,7 +256,7 @@ "vitest": "^4.1.0" }, "dependencies": { - "@supabase/middleware": "^0.4.0", + "@supabase/middleware": "^0.5.0", "jose": "^6.2.0" } } diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml index ae6704b..3a3853d 100644 --- a/pnpm-lock.yaml +++ b/pnpm-lock.yaml @@ -12,8 +12,8 @@ importers: .: dependencies: '@supabase/middleware': - specifier: ^0.4.0 - version: 0.4.0(typescript@5.9.3) + specifier: ^0.5.0 + version: 0.5.0(typescript@5.9.3) jose: specifier: ^6.2.0 version: 6.2.0 @@ -833,8 +833,8 @@ packages: resolution: {integrity: sha512-N3hzlq2xr6IYkkgj0tC4j0U3LWVshr5U/DAvmD5Bu8bW1ne2XOwxOx3ps6Y3NbptBAlzDrezmeJevlZR4AqsLA==} engines: {node: '>=22.0.0'} - '@supabase/middleware@0.4.0': - resolution: {integrity: sha512-iGDAzSQVKRzaKkcbap4G9C20NWc6MYXNht2Mgg7dkY1E8H3Y4bsR7UlWiaL1sbMkgVO/qS0GnrEEXPnzzBXd0A==} + '@supabase/middleware@0.5.0': + resolution: {integrity: sha512-OjukUo+5p14zxTuylf2zVg1hZCHWKLO6VrZhtVeQQw09yrVo3GAduvFJPiFDhTAz/Du1ZfEzAR+s6aRAWD5wzQ==} engines: {node: '>=22'} peerDependencies: typescript: '>=5.4' @@ -3483,7 +3483,7 @@ snapshots: dependencies: tslib: 2.8.1 - '@supabase/middleware@0.4.0(typescript@5.9.3)': + '@supabase/middleware@0.5.0(typescript@5.9.3)': dependencies: std-env: 4.2.0 optionalDependencies: diff --git a/src/core/parts/boundary.test.ts b/src/core/parts/boundary.test.ts new file mode 100644 index 0000000..163831d --- /dev/null +++ b/src/core/parts/boundary.test.ts @@ -0,0 +1,54 @@ +import { describe, expect, it } from 'vitest' + +import { EnvError, ErrorCodeHeader } from '../../errors.js' +import { withConstructionBoundary } from './boundary.js' +import { markConstructionFailure } from './construction-failure.js' + +const branded = (hint?: string) => async () => { + throw markConstructionFailure( + new EnvError('missing key', 'MISSING_DEFAULT_PUBLISHABLE_KEY', { hint }), + ) +} + +describe('withConstructionBoundary', () => { + it('maps a branded construction failure to a 500 JSON response', async () => { + const res = await withConstructionBoundary( + { auth: 'none' }, + branded(), + )(new Request('http://localhost')) + expect(res.status).toBe(500) + expect(res.headers.get(ErrorCodeHeader)).toBe( + 'MISSING_DEFAULT_PUBLISHABLE_KEY', + ) + expect((await res.json()).code).toBe('MISSING_DEFAULT_PUBLISHABLE_KEY') + }) + + it('lets an unbranded EnvError propagate', async () => { + const throwing = async () => { + throw new EnvError('handler-level env failure') + } + await expect( + withConstructionBoundary( + { auth: 'none' }, + throwing, + )(new Request('http://localhost')), + ).rejects.toThrow('handler-level env failure') + }) + + it('passes a normal response through unchanged', async () => { + const res = await withConstructionBoundary( + { auth: 'none' }, + async () => new Response('ok', { status: 201 }), + )(new Request('http://localhost')) + expect(res.status).toBe(201) + expect(await res.text()).toBe('ok') + }) + + it('honors errors: { detailed: false }', async () => { + const res = await withConstructionBoundary( + { auth: 'none', errors: { detailed: false } }, + branded('set it'), + )(new Request('http://localhost')) + expect((await res.json()).hint).toBeUndefined() + }) +}) diff --git a/src/core/parts/boundary.ts b/src/core/parts/boundary.ts new file mode 100644 index 0000000..0f36639 --- /dev/null +++ b/src/core/parts/boundary.ts @@ -0,0 +1,42 @@ +import { defineMiddleware } from '@supabase/middleware' +import type { Middleware } from '@supabase/middleware' + +import type { WithSupabaseConfig } from '../../types.js' +import { + constructionFailureResponse, + isConstructionFailure, +} from './construction-failure.js' + +/** + * Turns a client-construction failure thrown below it into the JSON error + * response `withSupabase` returns for a missing URL or key. + * + * Every other throw propagates unchanged, including an `EnvError` raised by + * the handler or by the first `ctx.supabaseAdmin` access: those happen after + * the context is established and belong to the caller. + */ +export const withConstructionBoundary: Middleware< + 'supabaseBoundary', + WithSupabaseConfig, + Record, + true +> = defineMiddleware< + 'supabaseBoundary', + WithSupabaseConfig, + Record, + true +>({ + key: 'supabaseBoundary', + run: (config) => + async function* () { + try { + const response: Response = yield { supabaseBoundary: true } + return response + } catch (error) { + if (isConstructionFailure(error)) { + return constructionFailureResponse(error, config.errors) + } + throw error + } + }, +}) diff --git a/src/core/parts/construction-failure.test.ts b/src/core/parts/construction-failure.test.ts new file mode 100644 index 0000000..cea3513 --- /dev/null +++ b/src/core/parts/construction-failure.test.ts @@ -0,0 +1,80 @@ +import { describe, expect, it } from 'vitest' + +import { + CreateSupabaseClientError, + EnvError, + ErrorCodeHeader, + Errors, +} from '../../errors.js' +import { + constructionFailureResponse, + isConstructionFailure, + markConstructionFailure, +} from './construction-failure.js' + +describe('construction failure brand', () => { + it('marks and recognizes an EnvError', () => { + const error = markConstructionFailure( + new EnvError('missing key', 'MISSING_DEFAULT_PUBLISHABLE_KEY'), + ) + expect(isConstructionFailure(error)).toBe(true) + }) + + it('does not recognize an unmarked error of the same class', () => { + expect( + isConstructionFailure(new EnvError('handler-level env failure')), + ).toBe(false) + expect(isConstructionFailure(new Error('x'))).toBe(false) + }) + + it('leaves the error shape and JSON payload untouched', () => { + const plain = new EnvError('missing key', 'MISSING_DEFAULT_PUBLISHABLE_KEY') + const marked = markConstructionFailure( + new EnvError('missing key', 'MISSING_DEFAULT_PUBLISHABLE_KEY'), + ) + expect(Object.getOwnPropertyNames(marked)).toEqual( + Object.getOwnPropertyNames(plain), + ) + expect(JSON.stringify(marked)).toBe(JSON.stringify(plain)) + }) + + it('renders an EnvError as a 500 that keeps its code and hint', async () => { + const error = markConstructionFailure( + new EnvError('missing key', 'MISSING_DEFAULT_PUBLISHABLE_KEY', { + hint: 'set it', + }), + ) + const res = constructionFailureResponse(error) + expect(res.status).toBe(500) + expect(res.headers.get(ErrorCodeHeader)).toBe( + 'MISSING_DEFAULT_PUBLISHABLE_KEY', + ) + const body = await res.json() + expect(body.code).toBe('MISSING_DEFAULT_PUBLISHABLE_KEY') + expect(body.hint).toBe('set it') + }) + + it('renders a CreateSupabaseClientError with its own status', async () => { + const error = markConstructionFailure( + Errors[CreateSupabaseClientError]({ cause: new Error('boom') }), + ) + const res = constructionFailureResponse(error) + expect(res.status).toBe(error.status) + expect((await res.json()).code).toBe(CreateSupabaseClientError) + }) + + it('honors errors: { detailed: false }', async () => { + const error = markConstructionFailure( + new EnvError('missing key', 'MISSING_DEFAULT_PUBLISHABLE_KEY', { + hint: 'set it', + }), + ) + const body = await constructionFailureResponse(error, { + detailed: false, + }).json() + expect(body).toEqual({ + code: 'MISSING_DEFAULT_PUBLISHABLE_KEY', + message: expect.any(String), + }) + }) +}) diff --git a/src/core/parts/construction-failure.ts b/src/core/parts/construction-failure.ts new file mode 100644 index 0000000..7be04ee --- /dev/null +++ b/src/core/parts/construction-failure.ts @@ -0,0 +1,40 @@ +import { errorResponse } from '../../error-response.js' +import { AuthError, EnvError } from '../../errors.js' +import type { ErrorResponseConfig } from '../../types.js' + +const constructionFailure = Symbol.for('@supabase/server:constructionFailure') + +/** + * Marks an error thrown while a Supabase client is constructed for the + * request. `withSupabase`'s boundary maps only marked errors to a JSON + * response; any other throw escaping a part or the handler propagates. + * + * The mark is a non-enumerable symbol property, so the error's class, own + * properties and `toJSON` payload are unchanged. + */ +export function markConstructionFailure(error: E): E { + Object.defineProperty(error, constructionFailure, { value: true }) + return error +} + +/** True for an `EnvError` or `AuthError` carrying the construction mark. */ +export function isConstructionFailure( + error: unknown, +): error is EnvError | AuthError { + return ( + (error instanceof EnvError || error instanceof AuthError) && + constructionFailure in error + ) +} + +/** + * The JSON response for a construction failure: the error's own code, status, + * hint, details and docs, rendered exactly as `errorResponse` renders any + * other {@link SupabaseServerError}. + */ +export function constructionFailureResponse( + error: EnvError | AuthError, + errors?: ErrorResponseConfig, +): Response { + return errorResponse(error, { errors }) +} diff --git a/src/core/parts/cors.test.ts b/src/core/parts/cors.test.ts new file mode 100644 index 0000000..be7fd10 --- /dev/null +++ b/src/core/parts/cors.test.ts @@ -0,0 +1,105 @@ +import { describe, expect, it } from 'vitest' + +import { ErrorCodeHeader } from '../../errors.js' +import { withSupabaseCors } from './cors.js' + +const ok = async () => Response.json({ ok: true }) +const failing = async () => + Response.json( + { code: 'X' }, + { status: 401, headers: { [ErrorCodeHeader]: 'X' } }, + ) + +describe('withSupabaseCors', () => { + it('answers OPTIONS with 204 and the default headers', async () => { + const res = await withSupabaseCors( + { auth: 'none' }, + ok, + )(new Request('http://localhost', { method: 'OPTIONS' })) + expect(res.status).toBe(204) + expect(res.headers.get('Access-Control-Allow-Origin')).toBe('*') + }) + + it('stamps CORS headers on a success response and exposes nothing extra', async () => { + const res = await withSupabaseCors( + { auth: 'none' }, + ok, + )(new Request('http://localhost')) + expect(res.headers.get('Access-Control-Allow-Origin')).toBe('*') + expect(res.headers.get('Access-Control-Expose-Headers')).toBeNull() + }) + + it('exposes the error-code header on a response that carries it', async () => { + const res = await withSupabaseCors( + { auth: 'none' }, + failing, + )(new Request('http://localhost')) + expect(res.status).toBe(401) + expect(res.headers.get('Access-Control-Allow-Origin')).toBe('*') + expect(res.headers.get('Access-Control-Expose-Headers')).toBe( + ErrorCodeHeader, + ) + }) + + it('appends to a configured Access-Control-Expose-Headers value', async () => { + const res = await withSupabaseCors( + { + auth: 'none', + cors: { + headers: { + 'Access-Control-Allow-Origin': '*', + 'Access-Control-Expose-Headers': 'x-request-id', + }, + }, + }, + failing, + )(new Request('http://localhost')) + expect(res.headers.get('Access-Control-Expose-Headers')).toBe( + `x-request-id, ${ErrorCodeHeader}`, + ) + }) + + it('does not list the error-code header twice when the config already exposes it', async () => { + const res = await withSupabaseCors( + { + auth: 'none', + cors: { + headers: { + 'Access-Control-Allow-Origin': '*', + 'Access-Control-Expose-Headers': `x-request-id, ${ErrorCodeHeader.toUpperCase()}`, + }, + }, + }, + failing, + )(new Request('http://localhost')) + expect(res.headers.get('Access-Control-Expose-Headers')).toBe( + `x-request-id, ${ErrorCodeHeader.toUpperCase()}`, + ) + }) + + it("lets OPTIONS through and stamps nothing when cors is 'disabled'", async () => { + const config = { auth: 'none', cors: 'disabled' } as const + const preflight = await withSupabaseCors( + config, + ok, + )(new Request('http://localhost', { method: 'OPTIONS' })) + expect(preflight.status).toBe(200) + + const res = await withSupabaseCors( + config, + failing, + )(new Request('http://localhost')) + expect(res.headers.get('Access-Control-Allow-Origin')).toBeNull() + expect(res.headers.get('Access-Control-Expose-Headers')).toBeNull() + expect(res.headers.get(ErrorCodeHeader)).toBe('X') + }) + + it('propagates a thrown error untouched', async () => { + const boom = async () => { + throw new Error('handler failure') + } + await expect( + withSupabaseCors({ auth: 'none' }, boom)(new Request('http://localhost')), + ).rejects.toThrow('handler failure') + }) +}) diff --git a/src/core/parts/cors.ts b/src/core/parts/cors.ts new file mode 100644 index 0000000..ae22dd3 --- /dev/null +++ b/src/core/parts/cors.ts @@ -0,0 +1,69 @@ +import { defineMiddleware } from '@supabase/middleware' +import type { Middleware } from '@supabase/middleware' + +import { addCorsHeaders, buildCorsHeaders, isCorsDisabled } from '../../cors.js' +import { ErrorCodeHeader } from '../../errors.js' +import type { WithSupabaseConfig } from '../../types.js' + +/** + * CORS for `withSupabase`, on both sides of the request. + * + * Request side: every `OPTIONS` request is answered with `204` and the + * configured headers. Response side: the configured headers are stamped on + * every response, and a response that carries `x-supabase-server-error` gets + * that name appended to `Access-Control-Expose-Headers`, because a + * cross-origin caller cannot read a non-safelisted header otherwise. + * `cors: 'disabled'` turns all of this off and lets `OPTIONS` reach the + * handler. + * + * Outermost part of the composite, so the gate's short-circuits and the + * boundary's error responses pass through here on their way out. + */ +export const withSupabaseCors: Middleware< + 'supabaseCors', + WithSupabaseConfig, + Record, + Record | null +> = defineMiddleware< + 'supabaseCors', + WithSupabaseConfig, + Record, + Record | null +>({ + key: 'supabaseCors', + run: (config) => { + const disabled = isCorsDisabled(config.cors) + const headers = disabled ? null : buildCorsHeaders(config.cors) + return async function* (req) { + if (disabled) { + const passthrough: Response = yield { supabaseCors: null } + return passthrough + } + + if (req.method === 'OPTIONS') { + return new Response(null, { + status: 204, + headers: headers ?? undefined, + }) + } + + const response: Response = yield { + supabaseCors: headers, + } + const stamped = addCorsHeaders(response, config.cors) + if (stamped.headers.has(ErrorCodeHeader)) { + const exposed = stamped.headers.get('Access-Control-Expose-Headers') + const listed = exposed + ? exposed.split(',').map((name) => name.trim().toLowerCase()) + : [] + if (!listed.includes(ErrorCodeHeader.toLowerCase())) { + stamped.headers.set( + 'Access-Control-Expose-Headers', + exposed ? `${exposed}, ${ErrorCodeHeader}` : ErrorCodeHeader, + ) + } + } + return stamped + } + }, +}) diff --git a/src/core/parts/gate.test.ts b/src/core/parts/gate.test.ts new file mode 100644 index 0000000..98a4144 --- /dev/null +++ b/src/core/parts/gate.test.ts @@ -0,0 +1,82 @@ +import { describe, expect, it } from 'vitest' +import { pipeline } from '@supabase/middleware' + +import { ErrorCodeHeader, MissingCredentialsError } from '../../errors.js' +import { withAuthGate } from './gate.js' +import { + withAuthKeyName, + withAuthMode, + withJwtClaims, + withUserClaims, +} from './projections.js' + +const baseEnv = { + url: 'https://test.supabase.co', + publishableKeys: { default: 'sb_publishable_xyz' }, + secretKeys: { default: 'sb_secret_xyz' }, + jwks: null, +} + +describe('withAuthGate', () => { + it('short-circuits with the JSON error when credentials are missing', async () => { + const res = await withAuthGate( + { auth: 'user', env: baseEnv }, + async () => new Response('unreachable'), + )(new Request('http://localhost')) + expect(res.status).toBe(401) + expect(res.headers.get(ErrorCodeHeader)).toBe(MissingCredentialsError) + expect((await res.json()).code).toBe(MissingCredentialsError) + expect(res.headers.get('Access-Control-Allow-Origin')).toBeNull() + }) + + it("contributes the verified identity under auth: 'none'", async () => { + const res = await withAuthGate( + { auth: 'none', env: baseEnv }, + async (_req, ctx) => Response.json(ctx.supabaseAuth), + )(new Request('http://localhost')) + expect(await res.json()).toEqual({ + userClaims: null, + jwtClaims: null, + authMode: 'none', + }) + }) + + it('honors errors: { detailed: false } on the short-circuit', async () => { + const res = await withAuthGate( + { auth: 'user', env: baseEnv, errors: { detailed: false } }, + async () => new Response('unreachable'), + )(new Request('http://localhost')) + expect(await res.json()).toEqual({ + code: MissingCredentialsError, + message: expect.any(String), + }) + }) +}) + +describe('projections', () => { + it('republish each field of the gate result as its own key', async () => { + const handler = pipeline( + [ + withAuthGate({ auth: 'none', env: baseEnv }), + withUserClaims(), + withJwtClaims(), + withAuthMode(), + withAuthKeyName(), + ], + async (_req, ctx) => + Response.json({ + keys: Object.keys(ctx).sort(), + authMode: ctx.authMode, + }), + ) + const body = await (await handler(new Request('http://localhost'))).json() + expect(body.authMode).toBe('none') + expect(body.keys).toEqual([ + 'authKeyName', + 'authMode', + 'jwtClaims', + 'supabaseAuth', + 'userClaims', + ]) + }) +}) diff --git a/src/core/parts/gate.ts b/src/core/parts/gate.ts new file mode 100644 index 0000000..7d2e115 --- /dev/null +++ b/src/core/parts/gate.ts @@ -0,0 +1,52 @@ +import { defineMiddleware } from '@supabase/middleware' +import type { Middleware } from '@supabase/middleware' + +import { errorResponse } from '../../error-response.js' +import type { SupabaseContext, WithSupabaseConfig } from '../../types.js' +import { verifyAuth } from '../verify-auth.js' + +/** + * The verified identity for one request, as a single value. The projections + * in `./projections.ts` republish each field as its own `ctx` key; this + * bundle itself stays internal to the composite. + */ +export type AuthGateContribution = Pick< + SupabaseContext, + 'userClaims' | 'jwtClaims' | 'authMode' +> & { authKeyName: string | undefined } + +/** + * The auth gate. Verifies the request's credentials against `config.auth` + * (or the deprecated `config.allow`) and short-circuits with the JSON error + * response when they fail. CORS headers are the CORS part's job, so the + * short-circuit carries only the error body and the error-code header. + */ +export const withAuthGate: Middleware< + 'supabaseAuth', + WithSupabaseConfig, + Record, + AuthGateContribution +> = defineMiddleware< + 'supabaseAuth', + WithSupabaseConfig, + Record, + AuthGateContribution +>({ + key: 'supabaseAuth', + run: (config) => async (req) => { + const { data, error } = await verifyAuth(req, { + auth: config.auth, + allow: config.allow, + env: config.env, + }) + if (error) return errorResponse(error, { errors: config.errors }) + return { + supabaseAuth: { + userClaims: data.userClaims, + jwtClaims: data.jwtClaims, + authMode: data.authMode, + authKeyName: data.keyName ?? undefined, + }, + } + }, +}) diff --git a/src/core/parts/projections.ts b/src/core/parts/projections.ts new file mode 100644 index 0000000..72495e1 --- /dev/null +++ b/src/core/parts/projections.ts @@ -0,0 +1,53 @@ +import { defineMiddleware } from '@supabase/middleware' +import type { Middleware } from '@supabase/middleware' + +import type { AuthMode, JWTClaims, UserClaims } from '../../types.js' +import type { AuthGateContribution } from './gate.js' + +type NeedsAuth = { supabaseAuth: AuthGateContribution } + +/** `ctx.userClaims`, read off the gate result. */ +export const withUserClaims: Middleware< + 'userClaims', + void, + NeedsAuth, + UserClaims | null +> = defineMiddleware<'userClaims', void, NeedsAuth, UserClaims | null>({ + key: 'userClaims', + run: () => async (_req, ctx) => ({ userClaims: ctx.supabaseAuth.userClaims }), +}) + +/** `ctx.jwtClaims`, read off the gate result. */ +export const withJwtClaims: Middleware< + 'jwtClaims', + void, + NeedsAuth, + JWTClaims | null +> = defineMiddleware<'jwtClaims', void, NeedsAuth, JWTClaims | null>({ + key: 'jwtClaims', + run: () => async (_req, ctx) => ({ jwtClaims: ctx.supabaseAuth.jwtClaims }), +}) + +/** `ctx.authMode`, read off the gate result. */ +export const withAuthMode: Middleware<'authMode', void, NeedsAuth, AuthMode> = + defineMiddleware<'authMode', void, NeedsAuth, AuthMode>({ + key: 'authMode', + run: () => async (_req, ctx) => ({ authMode: ctx.supabaseAuth.authMode }), + }) + +/** + * `ctx.authKeyName`, read off the gate result. `undefined` for `user` and + * `none` modes, which match no named key; the client parts read it to mirror + * the key a `publishable` or `secret` request matched. + */ +export const withAuthKeyName: Middleware< + 'authKeyName', + void, + NeedsAuth, + string | undefined +> = defineMiddleware<'authKeyName', void, NeedsAuth, string | undefined>({ + key: 'authKeyName', + run: () => async (_req, ctx) => ({ + authKeyName: ctx.supabaseAuth.authKeyName, + }), +}) diff --git a/src/core/pre-auth.ts b/src/core/pre-auth.ts new file mode 100644 index 0000000..7c5f0ec --- /dev/null +++ b/src/core/pre-auth.ts @@ -0,0 +1,32 @@ +const preAuthTag = Symbol.for('@supabase/server:preAuth') + +/** + * Marks every handler a middleware produces as belonging to a pre-auth + * middleware, one that must run before any auth gate. `withSupabase` reads + * the mark off its downstream handler at composition time and refuses a + * stack that would run the middleware behind its gate. + * + * Both call forms are covered: the handler form marks the produced handler, + * the entry form marks the handler the entry produces when a `pipeline` + * folds it. + */ +export function tagPreAuth(middleware: T, name: string): T { + const base = middleware as unknown as (...args: unknown[]) => unknown + const mark = (fn: F): F => { + Object.defineProperty(fn, preAuthTag, { value: name }) + return fn + } + const tagged = (...args: unknown[]) => { + const out = base(...args) + if (typeof args[args.length - 1] === 'function') return mark(out) + return (handler: unknown) => mark((out as (h: unknown) => unknown)(handler)) + } + return tagged as unknown as T +} + +/** The pre-auth middleware name a handler carries, or `undefined`. */ +export function preAuthName(handler: unknown): string | undefined { + return typeof handler === 'function' && preAuthTag in handler + ? (handler as unknown as Record)[preAuthTag] + : undefined +} diff --git a/src/error-response.ts b/src/error-response.ts index b7fd87b..b123094 100644 --- a/src/error-response.ts +++ b/src/error-response.ts @@ -15,22 +15,20 @@ import type { ErrorResponseConfig } from './types.js' * same body, same `x-supabase-server-error` header, same status. * * @param error - The error to render. - * @param options - Extra headers (CORS, typically) and body verbosity. + * @param options - Body verbosity. * * @internal */ export function errorResponse( error: SupabaseServerError, options?: { - /** Merged in ahead of the code header — CORS headers, typically. */ - headers?: Record /** Body verbosity. @see {@link ErrorResponseConfig} */ errors?: ErrorResponseConfig }, ): Response { return Response.json(buildErrorBody(error, options?.errors), { status: error.status, - headers: { ...options?.headers, [ErrorCodeHeader]: error.code }, + headers: { [ErrorCodeHeader]: error.code }, }) } diff --git a/src/middleware/admin-client/index.ts b/src/middleware/admin-client/index.ts index f19277b..f092e6c 100644 --- a/src/middleware/admin-client/index.ts +++ b/src/middleware/admin-client/index.ts @@ -92,10 +92,8 @@ const base = defineMiddleware< */ export function withSupabaseAdminClient( config?: WithSupabaseAdminClientConfig, -): Entry<'supabaseAdmin', Record, SupabaseClient> { - return base(config) as unknown as Entry< - 'supabaseAdmin', - Record, - SupabaseClient - > +): Entry<{ supabaseAdmin: SupabaseClient }> { + return base(config) as unknown as Entry<{ + supabaseAdmin: SupabaseClient + }> } diff --git a/src/middleware/client/brand.test.ts b/src/middleware/client/brand.test.ts new file mode 100644 index 0000000..1f497ab --- /dev/null +++ b/src/middleware/client/brand.test.ts @@ -0,0 +1,27 @@ +import { describe, expect, it } from 'vitest' +import { pipeline } from '@supabase/middleware' + +import { isConstructionFailure } from '../../core/parts/construction-failure.js' +import { withSupabaseClient } from './index.js' + +describe('withSupabaseClient construction failures', () => { + it('brands the error thrown when the default publishable key is missing', async () => { + const handler = pipeline( + [ + withSupabaseClient({ + env: { + url: 'https://test.supabase.co', + publishableKeys: {}, + secretKeys: {}, + jwks: null, + }, + }), + ], + async () => new Response('unreachable'), + ) + + await expect(handler(new Request('http://localhost'))).rejects.toSatisfy( + isConstructionFailure, + ) + }) +}) diff --git a/src/middleware/client/index.ts b/src/middleware/client/index.ts index 50c1ecb..0da83c7 100644 --- a/src/middleware/client/index.ts +++ b/src/middleware/client/index.ts @@ -6,6 +6,7 @@ import { createContextClient } from '../../core/create-context-client.js' import { extractCredentials } from '../../core/extract-credentials.js' import { readUpstreamAuth } from '../../core/read-upstream-auth.js' import { CreateSupabaseClientError, EnvError, Errors } from '../../errors.js' +import { markConstructionFailure } from '../../core/parts/construction-failure.js' import type { CreateContextClientOptions } from '../../types.js' /** @@ -54,9 +55,11 @@ const base = defineMiddleware< supabaseOptions: config?.supabaseOptions, }) } catch (e) { - throw e instanceof EnvError - ? e - : Errors[CreateSupabaseClientError]({ cause: e }) + throw markConstructionFailure( + e instanceof EnvError + ? e + : Errors[CreateSupabaseClientError]({ cause: e }), + ) } return { supabase } }, @@ -96,10 +99,8 @@ const base = defineMiddleware< */ export function withSupabaseClient( config?: WithSupabaseClientConfig, -): Entry<'supabase', Record, SupabaseClient> { - return base(config) as unknown as Entry< - 'supabase', - Record, - SupabaseClient - > +): Entry<{ supabase: SupabaseClient }> { + return base(config) as unknown as Entry<{ + supabase: SupabaseClient + }> } diff --git a/src/middleware/postgres-admin/index.ts b/src/middleware/postgres-admin/index.ts index 08525cd..d6b0277 100644 --- a/src/middleware/postgres-admin/index.ts +++ b/src/middleware/postgres-admin/index.ts @@ -43,25 +43,18 @@ export interface WithPostgresAdminClientConfig { * `auth: 'secret'` and `auth: 'none'`: * * ```ts + * import { pipeline } from '@supabase/middleware' * import { withSupabase } from '@supabase/server' * import { withPostgresAdminClient } from '@supabase/server/middleware/postgres-admin' * - * export default { - * fetch: withSupabase( - * { auth: 'secret', middleware: [withPostgresAdminClient()] }, - * async (_req, ctx) => { - * const rows = await ctx.postgresAdmin.query`select user_id, count(*) from notes group by user_id` - * return Response.json(rows) - * }, - * ), - * } + * pipeline([withSupabase({ auth: 'secret' }), withPostgresAdminClient()], handler) * ``` * * Compose both halves when a handler needs each in turn — they share one pool, * and `ctx.postgres` stays RLS-scoped regardless: * * ```ts - * middleware: [withPostgresClient(), withPostgresAdminClient()] + * pipeline([withSupabase({ auth: 'user' }), withPostgresClient(), withPostgresAdminClient()], handler) * ``` * * > **Authorization is yours now.** RLS is not consulted, so any per-user diff --git a/src/middleware/postgres/index.ts b/src/middleware/postgres/index.ts index be8b50f..3535b88 100644 --- a/src/middleware/postgres/index.ts +++ b/src/middleware/postgres/index.ts @@ -119,11 +119,12 @@ export interface WithPostgresClientConfig { * > claim, and RLS still applies to them. They are not supported here yet, so * > such a token is refused rather than downgraded. * - * Reads the caller's claims from `ctx.jwtClaims`, which `withSupabase` already - * populates (JWKS-verified) — so inside `withSupabase` you compose it directly: + * Reads the caller's claims from `ctx.jwtClaims`, which `withSupabase` + * populates (JWKS-verified) — so after `withSupabase` in a pipeline it composes + * directly: * * ```ts - * withSupabase({ auth: 'user', middleware: [withPostgresClient()] }, handler) + * pipeline([withSupabase({ auth: 'user' }), withPostgresClient()], handler) * ``` * * Standalone (no `withSupabase`), pair it with `withClaims` so `ctx.jwtClaims` diff --git a/src/middleware/required-claims/index.test.ts b/src/middleware/required-claims/index.test.ts index 492c747..5ad8e75 100644 --- a/src/middleware/required-claims/index.test.ts +++ b/src/middleware/required-claims/index.test.ts @@ -317,12 +317,12 @@ describe('withRequiredClaims composition (type-level)', () => { void _bad }) - it('gating inside withSupabase is a compile-time conflict', () => { - // withSupabase already verifies credentials and seeds jwtClaims before - // the middleware array runs, so the gate is redundant there. - // @ts-expect-error — Conflict<'jwtClaims'>: key already on the context - const _bad = withSupabase( - { auth: 'none', env: baseEnv, middleware: [withRequiredClaims()] }, + it('gating after withSupabase in a pipeline is a compile-time conflict', () => { + // withSupabase verifies credentials and contributes jwtClaims itself, so a + // gate placed after it collides on the key. + const _bad = pipeline( + [withSupabase({ auth: 'none', env: baseEnv }), withRequiredClaims()], + // @ts-expect-error — Conflict<'jwtClaims'>: key already on the context async () => Response.json({ ok: true }), ) void _bad diff --git a/src/middleware/required-claims/index.ts b/src/middleware/required-claims/index.ts index 5013cd3..0e8f98f 100644 --- a/src/middleware/required-claims/index.ts +++ b/src/middleware/required-claims/index.ts @@ -71,10 +71,10 @@ export interface WithRequiredClaimsConfig { * the gate runs and stamps `Access-Control-*` headers on the short-circuit * responses. * - * Inside `withSupabase` the context already carries verified `jwtClaims`, so - * this gate is unnecessary there and composing it through the `middleware` - * option is a compile-time conflict. Use `withSupabase({ auth: 'user' })` to - * gate that path. + * After `withSupabase` in a pipeline the context already carries verified + * `jwtClaims`, so this gate is unnecessary there and placing it after + * `withSupabase` is a compile-time conflict. Use `withSupabase({ auth: 'user' })` + * to gate that path. * * @example Gated standalone pipeline * ```ts diff --git a/src/oauth-protected-resource/with-oauth-protected-resource.ts b/src/oauth-protected-resource/with-oauth-protected-resource.ts index 495bb01..e0aa03d 100644 --- a/src/oauth-protected-resource/with-oauth-protected-resource.ts +++ b/src/oauth-protected-resource/with-oauth-protected-resource.ts @@ -1,6 +1,7 @@ import { defineMiddleware } from '@supabase/middleware' import type { Middleware } from '@supabase/middleware' +import { tagPreAuth } from '../core/pre-auth.js' import { resourceMetadataResponse } from './responses.js' import { getAuthUrl, getResourceMetadataUrl, getResourceUrl } from './url.js' import type { UrlOption } from './url.js' @@ -78,7 +79,10 @@ export interface OAuthProtectedResourceConfig { * Contributes `ctx.oauthProtectedResource` (the resolved metadata URL) to the * downstream context. Nested under `withSupabase`, the key is typed on the * handler's `ctx` when the outermost call is anchored with - * `satisfies FetchHandler` — see `withSupabase`'s type note. + * `satisfies FetchHandler` — see `withSupabase`'s type note. Placed directly + * after `withSupabase` with an auth mode that requires credentials, the + * composition is refused when the stack is built, since the gate would + * answer discovery and preflight before this middleware runs. * * The OAuth Protected Resource surface is alpha — the config shape, the * contributed context key, and the metadata route may change in a minor @@ -133,77 +137,87 @@ export const withOAuthProtectedResource: Middleware< OAuthProtectedResourceConfig | undefined, Record, OAuthProtectedResourceContribution -> = defineMiddleware< - 'oauthProtectedResource', - OAuthProtectedResourceConfig | undefined, - Record, - OAuthProtectedResourceContribution ->({ - key: 'oauthProtectedResource', - run: (config) => - async function* (req) { - const url = new URL(req.url) - // The metadata document lives at `{resource}/oauth-protected-resource`. - // Matching on the suffix keeps this working wherever the endpoint is - // mounted, without assuming the Edge Functions path convention. - const isMetadataRoute = url.pathname.endsWith('/oauth-protected-resource') +> = tagPreAuth( + defineMiddleware< + 'oauthProtectedResource', + OAuthProtectedResourceConfig | undefined, + Record, + OAuthProtectedResourceContribution + >({ + key: 'oauthProtectedResource', + run: (config) => + async function* (req) { + const url = new URL(req.url) + // The metadata document lives at `{resource}/oauth-protected-resource`. + // Matching on the suffix keeps this working wherever the endpoint is + // mounted, without assuming the Edge Functions path convention. + const isMetadataRoute = url.pathname.endsWith( + '/oauth-protected-resource', + ) - // RFC 9728 — OAuth Protected Resource Metadata - if (isMetadataRoute && req.method === 'GET') { - return resourceMetadataResponse(req, { - resource: getResourceUrl(req, config?.resourceServer), - authorizationServers: [getAuthUrl(req, config?.authorizationServer)], - }) - } + // RFC 9728 — OAuth Protected Resource Metadata + if (isMetadataRoute && req.method === 'GET') { + return resourceMetadataResponse(req, { + resource: getResourceUrl(req, config?.resourceServer), + authorizationServers: [ + getAuthUrl(req, config?.authorizationServer), + ], + }) + } - // CORS preflight for the metadata route — browser-based clients fetch the - // discovery document cross-origin. - if (isMetadataRoute && req.method === 'OPTIONS') { - return new Response(null, { - status: 204, - headers: { - 'Access-Control-Allow-Origin': '*', - 'Access-Control-Allow-Methods': 'GET, OPTIONS', - 'Access-Control-Allow-Headers': - 'content-type, mcp-protocol-version', - }, - }) - } + // CORS preflight for the metadata route — browser-based clients fetch the + // discovery document cross-origin. + if (isMetadataRoute && req.method === 'OPTIONS') { + return new Response(null, { + status: 204, + headers: { + 'Access-Control-Allow-Origin': '*', + 'Access-Control-Allow-Methods': 'GET, OPTIONS', + 'Access-Control-Allow-Headers': + 'content-type, mcp-protocol-version', + }, + }) + } - const resourceMetadataUrl = getResourceMetadataUrl( - req, - config?.resourceServer, - ) - const response = yield { - oauthProtectedResource: { resourceMetadataUrl }, - } + const resourceMetadataUrl = getResourceMetadataUrl( + req, + config?.resourceServer, + ) + const response = yield { + oauthProtectedResource: { resourceMetadataUrl }, + } - // Enrich a 401 with WWW-Authenticate so clients can discover the auth - // server — unless the handler already set one (its value wins, e.g. an - // RFC 6750 error or a custom resource_metadata override). - if ( - response.status === 401 && - !response.headers.has('WWW-Authenticate') - ) { - const challenge = `Bearer resource_metadata="${resourceMetadataUrl}"` - try { - response.headers.set('WWW-Authenticate', challenge) - return response - } catch { - // Headers on a fetch()-proxied response carry the immutable guard, - // so enrichment falls back to a copy. A copy cannot carry `.url` or - // `.redirected` and cannot reuse a consumed body stream, which is - // why in-place mutation is the primary path. - const headers = new Headers(response.headers) - headers.set('WWW-Authenticate', challenge) - return new Response(response.bodyUsed ? null : response.body, { - status: response.status, - statusText: response.statusText, - headers, - }) + // Enrich a 401 with WWW-Authenticate so clients can discover the auth + // server — unless the handler already set one (its value wins, e.g. an + // RFC 6750 error or a custom resource_metadata override). + if ( + response.status === 401 && + !response.headers.has('WWW-Authenticate') + ) { + const challenge = `Bearer resource_metadata="${resourceMetadataUrl}"` + try { + response.headers.set('WWW-Authenticate', challenge) + return response + } catch { + // Headers on a fetch()-proxied response carry the immutable guard, + // so enrichment falls back to a copy. A copy cannot carry `.url` or + // `.redirected` and cannot reuse a consumed body stream, which is + // why in-place mutation is the primary path. + const headers = new Headers(response.headers) + headers.set('WWW-Authenticate', challenge) + return new Response( + response.bodyUsed || response.body?.locked ? null : response.body, + { + status: response.status, + statusText: response.statusText, + headers, + }, + ) + } } - } - return response - }, -}) + return response + }, + }), + 'withOAuthProtectedResource', +) diff --git a/src/types.ts b/src/types.ts index 0499c66..fc3f054 100644 --- a/src/types.ts +++ b/src/types.ts @@ -449,8 +449,9 @@ export interface SupabaseContext { * from the entries' `In` — a declared prerequisite is mandatory, and this one * is not. * - * Seeding both keys takes a wrapper that writes the context directly, as - * `withSupabase` does; a `defineMiddleware` entry contributes exactly one key. + * Inside `withSupabase`, two projection parts contribute these keys, one + * each, ahead of the client parts; a `defineMiddleware` entry contributes + * exactly one key. * * @internal */ diff --git a/src/with-supabase.test.ts b/src/with-supabase.test.ts index 1f95c3e..93ba5a6 100644 --- a/src/with-supabase.test.ts +++ b/src/with-supabase.test.ts @@ -1,6 +1,6 @@ import { beforeEach, describe, expect, expectTypeOf, it, vi } from 'vitest' -import { defineMiddleware, getEnv } from '@supabase/middleware' -import type { Entry, FetchHandler } from '@supabase/middleware' +import { defineMiddleware, getEnv, pipeline } from '@supabase/middleware' +import type { FetchHandler } from '@supabase/middleware' import { _resetAllowDeprecationWarned } from './core/utils/deprecation.js' import { createSupabaseContext } from './create-supabase-context.js' @@ -11,7 +11,7 @@ import { MissingCredentialsError, MissingDefaultSecretKeyError, } from './errors.js' -import type { WithSupabaseConfig } from './types.js' +import type { JWTClaims, SupabaseContext, WithSupabaseConfig } from './types.js' import { withClaims } from './middleware/claims/index.js' import { withPostgresClient } from './middleware/postgres/index.js' import { withOAuthProtectedResource } from './oauth-protected-resource/with-oauth-protected-resource.js' @@ -306,200 +306,31 @@ describe('withSupabase', () => { }) }) - describe('middleware', () => { - it('composes middleware after the Supabase context is established', async () => { - const withFlag = defineMiddleware< - 'flag', - void, - Record, - boolean - >({ - key: 'flag', - run: () => async () => ({ flag: true }), - }) - - const handler = withSupabase( - { auth: 'none', env: baseEnv, middleware: [withFlag()] }, - async (_req, ctx) => - Response.json({ authMode: ctx.authMode, flag: ctx.flag }), - ) - - const res = await handler(new Request('http://localhost')) - const body = await res.json() - expect(body.authMode).toBe('none') - expect(body.flag).toBe(true) - }) - - it('middleware receives the Supabase context at runtime', async () => { - let capturedHasSupabase = false - - const withCapture = defineMiddleware< - 'captured', - void, - Record, - boolean - >({ - key: 'captured', - run: () => async (_req, ctx) => { - capturedHasSupabase = !!(ctx as { supabase?: unknown }).supabase - return { captured: capturedHasSupabase } - }, - }) - - const handler = withSupabase( - { auth: 'none', env: baseEnv, middleware: [withCapture()] }, - async (_, ctx) => Response.json({ captured: ctx.captured }), - ) - - const res = await handler(new Request('http://localhost')) - const body = await res.json() - expect(body.captured).toBe(capturedHasSupabase) - expect(capturedHasSupabase).toBe(true) - }) - - it('middleware can short-circuit before the handler', async () => { - const withBlock = defineMiddleware< - 'blocked', - void, - Record, - true - >({ - key: 'blocked', - run: () => async () => new Response('blocked', { status: 403 }), - }) - - const innerHandler = vi.fn(async () => Response.json({ ok: true })) - - const handler = withSupabase( - { auth: 'none', env: baseEnv, middleware: [withBlock()] }, - innerHandler, - ) - - const res = await handler(new Request('http://localhost')) - expect(res.status).toBe(403) - expect(innerHandler).not.toHaveBeenCalled() + it("forwards the host's second fetch argument to getEnv as platform env", async () => { + const withReadEnv = defineMiddleware< + 'bindingValue', + void, + Record, + string | undefined + >({ + key: 'bindingValue', + run: () => async () => ({ + bindingValue: getEnv('WITH_SUPABASE_TEST_BINDING'), + }), }) - it('middleware run in array order (first = outermost, runs first on request)', async () => { - const order: string[] = [] - - const withA = defineMiddleware<'a', void, Record, true>({ - key: 'a', - run: () => async () => { - order.push('a') - return { a: true as const } - }, - }) - const withB = defineMiddleware<'b', void, Record, true>({ - key: 'b', - run: () => async () => { - order.push('b') - return { b: true as const } - }, - }) - - const handler = withSupabase( - { auth: 'none', env: baseEnv, middleware: [withA(), withB()] }, - async (_req, ctx) => Response.json({ a: ctx.a, b: ctx.b }), - ) - - const res = await handler(new Request('http://localhost')) - const body = await res.json() - expect(order).toEqual(['a', 'b']) - expect(body).toEqual({ a: true, b: true }) - }) - - it('middleware run in array order with shared ctx dependency', async () => { - const withFirst = defineMiddleware< - 'a', - void, - Record, - string - >({ - key: 'a', - run: () => async () => ({ a: 'http://localhost' as const }), - }) - const withSecond = defineMiddleware<'b', void, { a: string }, URL>({ - key: 'b', - run: () => async (_req, ctx) => { - const url = URL.parse(ctx.a) - url!.pathname = '/supabase' - - return { b: url! } - }, - }) - - const handler = withSupabase( - { auth: 'none', env: baseEnv, middleware: [withFirst(), withSecond()] }, - async (_req, ctx) => Response.json({ a: ctx.a, b: ctx.b }), - ) - - const res = await handler(new Request('http://localhost')) - const body = await res.json() - expect(body).toEqual({ - a: 'http://localhost', - b: 'http://localhost/supabase', - }) - - // Reverse order is a compile-time ordering error; at runtime the - // broken dependency chain throws all the same. - // @ts-expect-error — prereq 'a' is not yet on the context - const handlerReverse = withSupabase( - { auth: 'none', env: baseEnv, middleware: [withSecond(), withFirst()] }, - async (_req: Request, ctx: { a: string; b: URL }) => - Response.json({ a: ctx.a, b: ctx.b }), - ) - - expect(handlerReverse(new Request('http://localhost'))).rejects.toThrow( - "Cannot set properties of null (setting 'pathname')", - ) - }) - - it("forwards the host's second fetch argument to getEnv as platform env", async () => { - const withReadEnv = defineMiddleware< - 'bindingValue', - void, - Record, - string | undefined - >({ - key: 'bindingValue', - run: () => async () => ({ - bindingValue: getEnv('WITH_SUPABASE_TEST_BINDING'), - }), - }) - - const handler = withSupabase( - { auth: 'none', env: baseEnv, middleware: [withReadEnv()] }, - async (_req, ctx) => Response.json({ bindingValue: ctx.bindingValue }), - ) - - // Simulate a Workers-style invocation: fetch(request, env). - const res = await handler(new Request('http://localhost'), { - WITH_SUPABASE_TEST_BINDING: 'from-platform', - }) - const body = await res.json() - expect(body).toEqual({ bindingValue: 'from-platform' }) - }) - - it('CORS headers still apply when middleware are present', async () => { - const withNoop = defineMiddleware< - 'noop', - void, - Record, - true - >({ - key: 'noop', - run: () => async () => ({ noop: true as const }), - }) - - const handler = withSupabase( - { auth: 'none', env: baseEnv, middleware: [withNoop()] }, - async () => Response.json({ ok: true }), - ) + const handler = withSupabase( + { auth: 'none', env: baseEnv }, + withReadEnv(async (_req, ctx) => + Response.json({ bindingValue: ctx.bindingValue }), + ), + ) - const res = await handler(new Request('http://localhost')) - expect(res.headers.get('Access-Control-Allow-Origin')).toBe('*') + // Workers-style invocation: fetch(request, env). + const res = await handler(new Request('http://localhost'), { + WITH_SUPABASE_TEST_BINDING: 'from-platform', }) + expect(await res.json()).toEqual({ bindingValue: 'from-platform' }) }) describe('nested under an upstream middleware', () => { @@ -633,31 +464,12 @@ describe('withSupabase', () => { }) describe('type guarantees (tsc-verified)', () => { - const withProvider = defineMiddleware< - 'prov', - void, - Record, - { v: number } - >({ - key: 'prov', - run: () => async () => ({ prov: { v: 1 } }), - }) - - const withNeedsProv = defineMiddleware< - 'dep', - void, - { prov: { v: number } }, - { ok: true } - >({ - key: 'dep', - run: () => async () => ({ dep: { ok: true as const } }), - }) - - it('an entry may declare a prerequisite on a Supabase-provided key', () => { - // withPostgresClient declares In: { jwtClaims }; the SupabaseContext - // seed satisfies it, so composing it here compiles. - const _handler = withSupabase( - { auth: 'none', env: baseEnv, middleware: [withPostgresClient()] }, + it('as a pipeline entry, supplies jwtClaims to withPostgresClient', () => { + const _handler = pipeline( + [ + withSupabase({ auth: 'user', env: baseEnv }), + withPostgresClient({ connectionString: 'postgres://x' }), + ], async (_req, ctx) => { expectTypeOf(ctx.postgres).not.toBeAny() expectTypeOf(ctx.supabase).not.toBeAny() @@ -667,113 +479,353 @@ describe('type guarantees (tsc-verified)', () => { void _handler }) - it('an entry keyed on a Supabase-provided key fails to compile', () => { - // withClaims contributes 'jwtClaims', which withSupabase already seeds. - // Gating inside the array is redundant; the collision is a type error. - // (Same property the SDK-1614 gate relies on.) - // @ts-expect-error — Conflict<'jwtClaims'>: key already on the context - const _bad = withSupabase( - { auth: 'none', env: baseEnv, middleware: [withClaims()] }, + it('an entry keyed on a Supabase-provided key fails to compile after withSupabase', () => { + const _handler = pipeline( + [withSupabase({ auth: 'none', env: baseEnv }), withClaims()], + // @ts-expect-error — Conflict<'jwtClaims'>: withSupabase already contributes it async () => Response.json({ ok: true }), ) - void _bad + void _handler }) - it('sibling ordering: provider before dependent compiles', () => { - const _ok = withSupabase( - { - auth: 'none', - env: baseEnv, - middleware: [withProvider(), withNeedsProv()], - }, - async (_req, ctx) => { - expectTypeOf(ctx.dep).toEqualTypeOf<{ ok: true }>() - expectTypeOf(ctx.prov).toEqualTypeOf<{ v: number }>() + it('nested: Base flows in from an outer middleware', () => { + const _composed = withOAuthProtectedResource( + withSupabase({ auth: 'none', env: baseEnv }, async (_req, ctx) => { + expectTypeOf( + ctx.oauthProtectedResource.resourceMetadataUrl, + ).toEqualTypeOf() + expectTypeOf(ctx.supabase).not.toBeAny() return Response.json({ ok: true }) - }, - ) - void _ok + }), + ) satisfies FetchHandler + void _composed }) - it('sibling ordering: dependent before provider fails to compile', () => { - // @ts-expect-error — prereq 'prov' is not yet on the context - const _bad = withSupabase( - { - auth: 'none', - env: baseEnv, - middleware: [withNeedsProv(), withProvider()], - }, - async () => Response.json({ ok: true }), + it('accepts a pre-annotated handler, as the ui-library mcp-server block does', () => { + async function handleMcp( + _request: Request, + ctx: SupabaseContext, + ): Promise { + return Response.json({ id: ctx.userClaims?.id ?? null }) + } + const _composed = withOAuthProtectedResource( + withSupabase( + { + auth: 'user', + env: baseEnv, + cors: { headers: { 'Access-Control-Allow-Origin': '*' } }, + }, + handleMcp, + ), ) - void _bad + void _composed }) - it('a prerequisite nothing supplies fails to compile', () => { - // @ts-expect-error — prereq 'prov' is not on the context - const _bad = withSupabase( - { auth: 'none', env: baseEnv, middleware: [withNeedsProv()] }, - async () => Response.json({ ok: true }), + it('explicit Database types the client', () => { + const _handler = withSupabase<{ fixture: true }>( + { auth: 'none', env: baseEnv }, + async (_req, ctx) => { + expectTypeOf(ctx.supabase).not.toBeAny() + return Response.json({ ok: true }) + }, ) - void _bad + void _handler }) - it('nested: Base flows in beside a middleware array', () => { - // The `satisfies FetchHandler` anchor is what pushes the upstream - // contribution into `Base`; the validation conditional on the handler - // parameter must not resolve the call before that happens. - const _composed = withOAuthProtectedResource( - withSupabase( - { auth: 'none', env: baseEnv, middleware: [withProvider()] }, + it('nested: a middleware with a prerequisite composes as the handler', () => { + const _handler = withSupabase( + { auth: 'user', env: baseEnv }, + withPostgresClient( + { connectionString: 'postgres://x' }, async (_req, ctx) => { - expectTypeOf( - ctx.oauthProtectedResource.resourceMetadataUrl, - ).toEqualTypeOf() - expectTypeOf(ctx.prov).toEqualTypeOf<{ v: number }>() + expectTypeOf(ctx.postgres).not.toBeAny() expectTypeOf(ctx.supabase).not.toBeAny() return Response.json({ ok: true }) }, ), - ) satisfies FetchHandler - void _composed + ) + void _handler }) +}) - it('a widened entry poisons validation for later typed entries', () => { - // A hand-wrapped entry types as Entry. Its - // string key folds an index signature into the accumulated context, so - // every later typed key reports a false conflict. Pinned here so the - // failure mode is documented rather than discovered in consumer code. - const widened = ((h) => h) as Entry +describe('withSupabase as a pipeline entry', () => { + const oauthCfg = { + resourceServer: 'http://localhost/functions/v1/mcp', + authorizationServer: 'https://test.supabase.co/auth/v1', + } + const mcp = () => + pipeline( + [ + withOAuthProtectedResource(oauthCfg), + withSupabase({ auth: 'user', env: baseEnv }), + ], + async () => new Response('handler ran'), + ) - // @ts-expect-error — false Conflict<'prov'> caused by the widened entry - const _bad = withSupabase( - { auth: 'none', env: baseEnv, middleware: [widened, withProvider()] }, + it('returns an entry when called with config only', () => { + expect(typeof withSupabase({ auth: 'none', env: baseEnv })).toBe('function') + }) + + it('serves OAuth discovery ahead of the auth gate', async () => { + const res = await mcp()( + new Request('http://localhost/functions/v1/mcp/oauth-protected-resource'), + ) + expect(res.status).toBe(200) + expect((await res.json()).authorization_servers).toEqual([ + 'https://test.supabase.co/auth/v1', + ]) + }) + + it('enriches the gate 401 with WWW-Authenticate', async () => { + const res = await mcp()( + new Request('http://localhost/functions/v1/mcp', { method: 'POST' }), + ) + expect(res.status).toBe(401) + expect(res.headers.get('WWW-Authenticate')).toBe( + 'Bearer resource_metadata="http://localhost/functions/v1/mcp/oauth-protected-resource"', + ) + }) + + it('lets the OAuth middleware answer the metadata preflight', async () => { + const res = await mcp()( + new Request( + 'http://localhost/functions/v1/mcp/oauth-protected-resource', + { + method: 'OPTIONS', + }, + ), + ) + expect(res.status).toBe(204) + expect(res.headers.get('Access-Control-Allow-Headers')).toContain( + 'mcp-protocol-version', + ) + }) + + it('supplies jwtClaims to an entry placed after it', async () => { + const withCaller = defineMiddleware< + 'caller', + void, + { jwtClaims: JWTClaims | null }, + string + >({ + key: 'caller', + run: () => async (_req, ctx) => ({ + caller: ctx.jwtClaims?.sub ?? 'anon', + }), + }) + const handler = pipeline( + [withSupabase({ auth: 'none', env: baseEnv }), withCaller()], + async (_req, ctx) => + Response.json({ caller: ctx.caller, authMode: ctx.authMode }), + ) + expect( + await (await handler(new Request('http://localhost'))).json(), + ).toEqual({ + caller: 'anon', + authMode: 'none', + }) + }) + + it('stamps CORS headers and exposes the error code on the gate 401', async () => { + const handler = pipeline( + [withSupabase({ auth: 'user', env: baseEnv })], + async () => new Response('handler ran'), + ) + const res = await handler(new Request('http://localhost')) + expect(res.status).toBe(401) + expect(res.headers.get('Access-Control-Allow-Origin')).toBe('*') + expect(res.headers.get('Access-Control-Expose-Headers')).toBe( + ErrorCodeHeader, + ) + }) + + it('answers OPTIONS with 204 before the gate', async () => { + const handler = pipeline( + [withSupabase({ auth: 'user', env: baseEnv })], + async () => new Response('handler ran'), + ) + const res = await handler( + new Request('http://localhost', { method: 'OPTIONS' }), + ) + expect(res.status).toBe(204) + expect(res.headers.get('Access-Control-Allow-Origin')).toBe('*') + }) + + it('stamps CORS headers on a success response when an entry follows it', async () => { + const withNoop = defineMiddleware<'noop', void, Record, true>( + { + key: 'noop', + run: () => async () => ({ noop: true as const }), + }, + ) + const handler = pipeline( + [withSupabase({ auth: 'none', env: baseEnv }), withNoop()], async () => Response.json({ ok: true }), ) - void _bad + const res = await handler(new Request('http://localhost')) + expect(res.status).toBe(200) + expect(res.headers.get('Access-Control-Allow-Origin')).toBe('*') + }) +}) - // Placed last, a widened entry has nothing after it to poison. - const _last = withSupabase( - { auth: 'none', env: baseEnv, middleware: [withProvider(), widened] }, +describe('withSupabase context shape', () => { + it('exposes exactly the documented keys and no internal plumbing', async () => { + const handler = withSupabase( + { auth: 'none', env: baseEnv }, async (_req, ctx) => { - expectTypeOf(ctx.prov).toEqualTypeOf<{ v: number }>() - return Response.json({ ok: true }) + // @ts-expect-error — internal to the composite + void ctx.supabaseAuth + // @ts-expect-error — internal to the composite + void ctx.supabaseCors + return Response.json({ keys: Object.keys(ctx).sort() }) }, ) - void _last + const body = await (await handler(new Request('http://localhost'))).json() + expect(body.keys).toEqual([ + 'authKeyName', + 'authMode', + 'jwtClaims', + 'supabase', + 'supabaseAdmin', + 'userClaims', + ]) }) - it('explicit Database defaults Entries; array accepted, unvalidated', () => { - const _handler = withSupabase<{ fixture: true }>( - { auth: 'none', env: baseEnv, middleware: [withProvider()] }, + it('buffers the request at the entry so a nested middleware and the handler can both read the body', async () => { + const withPeek = defineMiddleware< + 'peek', + void, + Record, + string + >({ + key: 'peek', + run: () => async (req) => ({ peek: await req.text() }), + }) + const handler = withSupabase( + { auth: 'none', env: baseEnv }, + withPeek(async (req, ctx) => + Response.json({ peek: ctx.peek, again: await req.text() }), + ), + ) + const res = await handler( + new Request('http://localhost', { method: 'POST', body: 'hello' }), + ) + expect(await res.json()).toEqual({ peek: 'hello', again: 'hello' }) + }) +}) + +describe('withSupabase key mirroring', () => { + it('the client is built with the named key the request matched', async () => { + const handler = withSupabase( + { + auth: 'publishable:web', + env: { + ...baseEnv, + publishableKeys: { + default: 'sb_publishable_xyz', + web: 'sb_publishable_web', + }, + }, + }, async (_req, ctx) => { - expectTypeOf(ctx.supabase).not.toBeAny() - // Entries defaulted to readonly AnyEntry[]: no tuple inference, so - // contributions are not accumulated onto ctx. - // @ts-expect-error — 'prov' is not on ctx without tuple inference - void ctx.prov + expect(ctx.authKeyName).toBe('web') + expect( + (ctx.supabase as unknown as { supabaseKey: string }).supabaseKey, + ).toBe('sb_publishable_web') return Response.json({ ok: true }) }, ) - void _handler + + const req = new Request('http://localhost', { + headers: { apikey: 'sb_publishable_web' }, + }) + const res = await handler(req) + expect(res.status).toBe(200) + }) +}) + +describe('pre-auth middleware placement', () => { + const oauthCfg = { + resourceServer: 'http://localhost/functions/v1/mcp', + authorizationServer: 'https://test.supabase.co/auth/v1', + } + const ok = async () => new Response('ok') + + it('refuses a pipeline that places withOAuthProtectedResource after a credentialed gate', () => { + expect(() => + pipeline( + [ + withSupabase({ auth: 'user', env: baseEnv }), + withOAuthProtectedResource(oauthCfg), + ], + ok, + ), + ).toThrow(/withOAuthProtectedResource is placed after withSupabase/) + }) + + it('refuses the nested form as well', () => { + expect(() => + withSupabase( + { auth: 'user', env: baseEnv }, + withOAuthProtectedResource(oauthCfg, ok), + ), + ).toThrow(/placed after withSupabase/) + }) + + it("accepts the placement when the gate admits anonymous requests (auth: 'none')", async () => { + const handler = pipeline( + [ + withSupabase({ auth: 'none', env: baseEnv }), + withOAuthProtectedResource(oauthCfg), + ], + ok, + ) + const res = await handler( + new Request('http://localhost/functions/v1/mcp/oauth-protected-resource'), + ) + expect(res.status).toBe(200) + }) + + it("accepts the placement when 'none' is one of several modes", () => { + expect(() => + pipeline( + [ + withSupabase({ auth: ['user', 'none'], env: baseEnv }), + withOAuthProtectedResource(oauthCfg), + ], + ok, + ), + ).not.toThrow() + }) + + it('accepts the correct order and the wrap form', () => { + expect(() => + pipeline( + [ + withOAuthProtectedResource(oauthCfg), + withSupabase({ auth: 'user', env: baseEnv }), + ], + ok, + ), + ).not.toThrow() + expect(() => + withOAuthProtectedResource( + oauthCfg, + withSupabase({ auth: 'user', env: baseEnv }, ok), + ), + ).not.toThrow() + }) +}) + +describe('withSupabase config without a middleware option', () => { + it('refuses a config carrying a middleware key, even when built outside the call', () => { + const config = { + auth: 'none', + env: baseEnv, + middleware: [], + } as unknown as WithSupabaseConfig + expect(() => withSupabase(config, async () => new Response('ok'))).toThrow( + /has no `middleware` option/, + ) }) }) diff --git a/src/with-supabase.ts b/src/with-supabase.ts index 5a5afab..349d8a5 100644 --- a/src/with-supabase.ts +++ b/src/with-supabase.ts @@ -1,40 +1,99 @@ -import { addCorsHeaders, buildCorsHeaders, isCorsDisabled } from './cors.js' -import { verifyAuth } from './core/verify-auth.js' -import { errorResponse } from './error-response.js' +import { defineComposite } from '@supabase/middleware' +import type { BaseContext, Entry } from '@supabase/middleware' + +import { preAuthName } from './core/pre-auth.js' +import { withConstructionBoundary } from './core/parts/boundary.js' +import { withSupabaseCors } from './core/parts/cors.js' +import { withAuthGate } from './core/parts/gate.js' import { - AuthError, - CreateSupabaseClientError, - EnvError, - ErrorCodeHeader, -} from './errors.js' + withAuthKeyName, + withAuthMode, + withJwtClaims, + withUserClaims, +} from './core/parts/projections.js' import { withSupabaseAdminClient } from './middleware/admin-client/index.js' import { withSupabaseClient } from './middleware/client/index.js' -import type { - SupabaseContext, - UpstreamAuth, - WithSupabaseConfig, -} from './types.js' -import { isContext, seedContext } from '@supabase/middleware' -import type { BaseContext, Entry, ValidateEntries } from '@supabase/middleware' +import type { SupabaseContext, WithSupabaseConfig } from './types.js' -type AnyEntry = Entry // eslint-disable-next-line @typescript-eslint/no-explicit-any type AnyHandler = (req: Request, ctx: any) => Promise /** - * Accumulate the ctx contributions of a middleware tuple — same logic as - * `pipeline`'s internal `Accumulate`, seeded from `object` (the engine reserves - * no ctx keys; see implementation note below). + * The parts `withSupabase` is made of, outermost first. Each contributes one + * key; the composite derives its contributions from them and keeps + * `supabaseCors`, `supabaseBoundary` and `supabaseAuth` internal, so the + * handler sees exactly {@link SupabaseContext}. + * + * Order is load-bearing: the CORS part must see every response on the way + * out, the boundary must sit above the client parts whose construction + * errors it maps, the gate must run before the projections that read its + * result, and the projections must run before the client parts, which read + * the flat `authMode` / `authKeyName` keys to mirror the matched credential. */ -type MiddlewareCtx = - Entries extends readonly [ - Entry, - ...infer Rest, - ] - ? Rest extends readonly AnyEntry[] - ? { [P in Key]: Contribution } & MiddlewareCtx - : { [P in Key]: Contribution } - : object +const composite = defineComposite({ + build: (config: WithSupabaseConfig) => + [ + withSupabaseCors(config), + withConstructionBoundary(config), + withAuthGate(config), + withUserClaims(), + withJwtClaims(), + withAuthMode(), + withAuthKeyName(), + withSupabaseClient({ + env: config.env, + supabaseOptions: config.supabaseOptions, + }), + withSupabaseAdminClient({ + env: config.env, + supabaseOptions: config.supabaseOptions, + }), + ] as const, + internal: ['supabaseCors', 'supabaseBoundary', 'supabaseAuth'], +}) + +/** + * The config-only overload declares `Entry>`; this + * holds only while every public key the parts contribute is in + * `SupabaseContext` and no public key is listed under `internal`. + */ +type EntryIsSound = + ReturnType extends Entry ? true : false +const entryIsSound: EntryIsSound = true +void entryIsSound + +/** Whether every configured auth mode requires credentials, so an unauthenticated request never passes the gate. */ +function requiresCredentials(config: WithSupabaseConfig): boolean { + const modes = config.auth ?? config.allow ?? 'user' + const list = Array.isArray(modes) ? modes : [modes] + return !list.includes('none') +} + +/** + * A pre-auth middleware behind a credentialed gate never sees the requests + * it exists to answer. Refusing the stack at composition time is the only + * place that failure is observable: at request time the gate has already + * answered. + */ +function rejectPreAuthBehindGate( + config: WithSupabaseConfig, + handler: unknown, +): void { + const name = preAuthName(handler) + if (name === undefined || !requiresCredentials(config)) return + throw new Error( + `${name} is placed after withSupabase, whose auth gate answers unauthenticated requests before it runs, so OAuth discovery and preflight cannot be served. Place it first: pipeline([${name}(config), withSupabase(config)], handler) or ${name}(config, withSupabase(config, handler)).`, + ) +} + +/** `withSupabase` composes through `pipeline` or nesting; a `middleware` key on the config has no effect and is refused so it cannot be mistaken for one. */ +function rejectMiddlewareOption(config: WithSupabaseConfig): void { + if ('middleware' in config) { + throw new Error( + 'withSupabase has no `middleware` option. Compose entries with pipeline([withSupabase(config), ...entries], handler) from @supabase/middleware, or nest them: withSupabase(config, entry(handler)).', + ) + } +} /** * Wraps a request handler with Supabase auth, client creation, and CORS handling. @@ -50,7 +109,8 @@ type MiddlewareCtx = * runtime supplies one, it is captured as the platform env behind * `@supabase/middleware`'s `getEnv` for any composed middleware. Nested under * another middleware, it is that middleware's accumulated context instead, - * which is reused rather than reseeded. + * which is reused rather than reseeded. At the entry point the request body + * is buffered, so a nested middleware and the handler can both read it. * * **Type note.** `Base` carries an upstream middleware's contributions into the * handler's `ctx`: with `satisfies FetchHandler` on the outermost call, @@ -70,7 +130,6 @@ type MiddlewareCtx = * ```ts * import { withSupabase } from '@supabase/server' * - * // Without middleware — existing API, unchanged. * export default { * fetch: withSupabase({ auth: 'user' }, async (req, ctx) => { * const { data } = await ctx.supabase.rpc('get_my_profile') @@ -83,13 +142,7 @@ export function withSupabase< Database = unknown, Base extends BaseContext = BaseContext, >( - config: WithSupabaseConfig & { - /** - * Absent in this overload. Supplying a `middleware` array selects the - * composable-middleware variant, which is alpha. - */ - middleware?: never - }, + config: WithSupabaseConfig, // `NoInfer` blocks inference from the handler argument, leaving the // contextual return type as the single source of `Base` — the same split the // engine's `Middleware` interface documents. Without it, an annotated handler @@ -98,217 +151,54 @@ export function withSupabase< req: Request, ctx: NoInfer & SupabaseContext, ) => Promise, - // `ctx?: Base` mirrors the engine's `Produced` shape for an `In`-less - // middleware: at the top level `Base` is the empty upstream (any platform - // argument still typechecks), and nested it is what lets the upstream - // middleware's contribution flow inward. ): (req: Request, ctx?: Base) => Promise /** - * **Alpha.** Variant that accepts a `middleware` array — each - * `withFoo(config)` call returns an `Entry` from `@supabase/middleware`. - * Middleware run **after** the Supabase context is established; they receive - * `ctx.supabase`, `ctx.userClaims`, etc. already present and contribute their - * own typed keys on top. (This is the server leg of a Plugin: the package's - * middleware goes here; its client namespace goes in `createClient`'s - * `plugins` array.) + * **Alpha.** Config-only call: returns an entry for a `pipeline` array, so + * `withSupabase` composes by position with any other middleware. Entries + * placed before it run ahead of the auth gate and may answer unauthenticated + * requests; entries placed after it receive the full {@link SupabaseContext} + * and may declare prerequisites on its keys. * - * The composable middleware surface tracks `@supabase/middleware` 0.x — entry - * shapes, context keys, and config options may change between 0.x releases. - * The no-`middleware` overload above is stable. + * The composable surface tracks `@supabase/middleware` 0.x — entry shapes and + * context keys may change between 0.x releases. The handler-form overload is + * stable. * - * @example + * @alpha + * @category Middleware + * + * @example OAuth discovery ahead of the gate, Postgres behind it * ```ts - * import { withSupabase } from '@supabase/server' - * import { withGuestbook } from '@supabase/plugin-guestbook/server' - * import { withRateLimit } from '@supabase/plugin-rate-limit/server' + * import { pipeline } from '@supabase/middleware' + * import { withOAuthProtectedResource, withSupabase } from '@supabase/server' + * import { withPostgresClient } from '@supabase/server/middleware/postgres' * * export default { - * fetch: withSupabase( - * { auth: 'user', middleware: [withRateLimit({ rpm: 100 }), withGuestbook()] }, - * async (req, ctx) => { - * ctx.supabase // from @supabase/server - * ctx.rateLimit // from withRateLimit - * ctx.guestbook // from withGuestbook - * return Response.json(await ctx.guestbook.list()) + * fetch: pipeline( + * [withOAuthProtectedResource(), withSupabase({ auth: 'user' }), withPostgresClient()], + * async (_req, ctx) => { + * const rows = await ctx.postgres.query`select id, body from notes` + * return Response.json(rows) * }, * ), * } * ``` - * - * **Type note.** `MiddlewareCtx` accumulates the key contributions of - * the middleware array onto the handler's `ctx`. `ValidateEntries` checks the - * array against the same context the entries see at runtime: the upstream - * `Base` plus {@link SupabaseContext}. An entry may declare `In` prerequisites - * on Supabase-provided keys (`supabase`, `jwtClaims`, and the rest). An entry - * whose key collides with a Supabase-provided key, or with an earlier sibling, - * fails to compile. The failure sentinel occupies the handler parameter, never - * `entries`, so `const Entries` tuple inference stays intact, as in the - * engine's `pipeline`. - * - * @alpha */ -export function withSupabase< - Database = unknown, - const Entries extends readonly AnyEntry[] = readonly AnyEntry[], - Base extends BaseContext = BaseContext, ->( - config: WithSupabaseConfig & { - /** - * **Alpha.** Entries to run after the Supabase context is established. - * Each receives `ctx.supabase`, `ctx.jwtClaims`, and the rest already - * present, and contributes its own typed keys on top. - * - * The composable middleware surface tracks `@supabase/middleware` 0.x — - * entry shapes, context keys, and config options may change between 0.x - * releases. - * - * @alpha - */ - middleware: Entries - }, - // Validation sits on the handler parameter (never on `entries`) so it does - // not disrupt `const Entries` tuple inference; the seed is the context the - // entries actually see at runtime. - handler: [ - ValidateEntries>, - ] extends [true] - ? ( - req: Request, - ctx: NoInfer & SupabaseContext & MiddlewareCtx, - ) => Promise - : ValidateEntries>, -): (req: Request, ctx?: Base) => Promise - export function withSupabase( - config: WithSupabaseConfig & { middleware?: readonly AnyEntry[] }, - handler: AnyHandler, -): (req: Request, platformArg?: unknown) => Promise { - // withSupabase runs on the engine: the context clients are the same public - // middleware anyone can compose (`./middleware/client`, - // `./middleware/admin-client`), folded around the user's middleware and - // handler — the same fold as pipeline's reduceRight, but without calling - // pipeline() so we supply the seeded ctx ourselves. - const clientEntries: readonly AnyEntry[] = [ - withSupabaseClient({ - env: config.env, - supabaseOptions: config.supabaseOptions, - }) as AnyEntry, - withSupabaseAdminClient({ - env: config.env, - supabaseOptions: config.supabaseOptions, - }) as AnyEntry, - ] - // The user's middleware and handler fold once at wrap time. - const userComposed = (config.middleware ?? []).reduceRight( - (h, entry) => entry(h), - handler, - ) - - return async (req: Request, platformArg?: unknown) => { - // Cross-origin browser code cannot read a non-safelisted response header - // unless it is named in Access-Control-Expose-Headers, so the error code - // header would be invisible in exactly the case it is most useful. - const errorHeaders = () => { - if (isCorsDisabled(config.cors)) return {} - const headers = buildCorsHeaders(config.cors) - const exposeKey = - Object.keys(headers).find( - (name) => name.toLowerCase() === 'access-control-expose-headers', - ) ?? 'Access-Control-Expose-Headers' - const exposed = headers[exposeKey] - return { - ...headers, - [exposeKey]: exposed - ? `${exposed}, ${ErrorCodeHeader}` - : ErrorCodeHeader, - } - } - - if (!isCorsDisabled(config.cors) && req.method === 'OPTIONS') { - return new Response(null, { - status: 204, - headers: buildCorsHeaders(config.cors), - }) - } - - const { data: auth, error } = await verifyAuth(req, { - auth: config.auth, - allow: config.allow, - env: config.env, - }) - if (error) { - return errorResponse(error, { - headers: errorHeaders(), - errors: config.errors, - }) - } - - // Track whether the request has moved past the client entries: only - // client-phase construction failures (the `supabase` entry) map to JSON - // error responses. User middleware and handler throws propagate - // unchanged — including the EnvError a lazily constructed - // `supabaseAdmin` throws at its first property access. - let inClientPhase = true - const markUserPhase: AnyHandler = (r, ctx) => { - inClientPhase = false - return userComposed(r, ctx) - } - const composed = clientEntries.reduceRight( - (h, entry) => entry(h), - markUserPhase, - ) - - let response: Response - try { - // As the entry point, `platformArg` is the host env — seed a context from - // it (captured behind getEnv). Nested under another middleware, it's an - // already-seeded context: reuse it, or reseeding would clobber the platform - // env and drop upstream ctx keys. - const baseContext = isContext(platformArg) - ? platformArg - : seedContext(platformArg) - // The client entries read these two keys back off the context; - // `satisfies` holds the seed to that shape without widening it. - const upstreamAuth = { - authMode: auth.authMode, - authKeyName: auth.keyName ?? undefined, - } satisfies UpstreamAuth - response = await composed(req, { - ...baseContext, - userClaims: auth.userClaims, - jwtClaims: auth.jwtClaims, - ...upstreamAuth, - }) - } catch (e) { - // Client-phase construction failures map to JSON error responses: - // EnvError (missing URL / keys) and the client middleware's - // CreateSupabaseClientError take the same shape as the JSON errors - // createSupabaseContext produces. - const mapped = !inClientPhase - ? null - : e instanceof EnvError - ? // Keep the EnvError's code, hint, and details — it already names - // the exact variable at fault. - new AuthError(e.message, e.code, 500, { - hint: e.hint, - details: e.details, - docs: e.docs, - cause: e, - }) - : e instanceof AuthError && e.code === CreateSupabaseClientError - ? e - : null - if (!mapped) throw e - return errorResponse(mapped, { - headers: errorHeaders(), - errors: config.errors, - }) - } + config: WithSupabaseConfig, +): Entry> - if (!isCorsDisabled(config.cors)) { - return addCorsHeaders(response, config.cors) +export function withSupabase( + config: WithSupabaseConfig, + handler?: AnyHandler, +): unknown { + rejectMiddlewareOption(config) + if (handler === undefined) { + return (next: AnyHandler) => { + rejectPreAuthBehindGate(config, next) + return composite(config, next) } - return response } + rejectPreAuthBehindGate(config, handler) + return composite(config, handler) }