diff --git a/README.md b/README.md index 64ca3b5..3309e14 100644 --- a/README.md +++ b/README.md @@ -542,7 +542,7 @@ No. `@supabase/ssr` handles cookie-based session management for frameworks like | Export | What's in it | | --------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------- | -| `@supabase/server` | `withSupabase`, `createSupabaseContext` | +| `@supabase/server` | `withSupabase`, `createWithSupabase`, `createSupabaseContext` | | `@supabase/server/core` | `verifyAuth`, `verifyCredentials`, `extractCredentials`, `createContextClient`, `createAdminClient`, `resolveEnv` | | `@supabase/server/adapters/hono` | `withSupabase` (Hono middleware) | | `@supabase/server/adapters/h3` | `withSupabase` (H3 / Nuxt middleware) | diff --git a/docs/api-reference.md b/docs/api-reference.md index 8bea0b3..e87c8f2 100644 --- a/docs/api-reference.md +++ b/docs/api-reference.md @@ -24,6 +24,8 @@ Wraps a fetch handler with auth, CORS, and client creation. Returns a `(req: Req - 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()`. +Passing `Database` explicitly (`withSupabase(...)`) is deprecated in both forms. Choose it once with [`createWithSupabase`](#createwithsupabase) instead. + ```ts function withSupabase( config: WithSupabaseConfig, @@ -49,6 +51,34 @@ pipeline( 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. +### createWithSupabase + +```ts +function createWithSupabase(): Composite< + SupabaseContext, + WithSupabaseConfig, + Record +> +``` + +Returns a `withSupabase` whose `ctx.supabase` and `ctx.supabaseAdmin` are `SupabaseClient`. Call it once at module scope and use the result in both forms, `withSupabase(config, handler)` and `withSupabase(config)` as a `pipeline` entry. It is built from the same parts as `withSupabase` and behaves the same at runtime. + +```ts +import { createWithSupabase } from '@supabase/server' +import type { Database } from './database.types.ts' + +const withSupabase = createWithSupabase() + +export default { + fetch: withSupabase({ auth: 'user' }, async (_req, ctx) => { + const { data } = await ctx.supabase.from('todos').select('id, title') + return Response.json(data) + }), +} +``` + +The return type is `Composite` from `@supabase/middleware`, so the engine's composite checks apply: a middleware placed below it that contributes one of its keys fails to compile, in a `pipeline` and in a nested stack anchored with `satisfies FetchHandler`. + ### createSupabaseContext ```ts diff --git a/docs/mcp.md b/docs/mcp.md index 837d567..d09acce 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -4,14 +4,19 @@ An MCP server your app exposes to its users is an HTTP endpoint that MCP clients ```ts import { pipeline } from '@supabase/middleware' -import { withOAuthProtectedResource, withSupabase } from '@supabase/server' +import { + createWithSupabase, + withOAuthProtectedResource, +} from '@supabase/server' import { createMcpHandler, McpServer } from '@modelcontextprotocol/server' import { z } from 'zod/v4' import type { Database } from './database.types' +const withSupabase = createWithSupabase() + export default { fetch: pipeline( - [withOAuthProtectedResource(), withSupabase({ auth: 'user' })], + [withOAuthProtectedResource(), withSupabase({ auth: 'user' })], async (req, { supabase }) => { const handler = createMcpHandler( () => { @@ -44,7 +49,7 @@ export default { } ``` -Pass the `Database` generic (from `supabase gen types typescript`) when tools write. Without it the client is `SupabaseClient` and `insert({ title })` fails type-checking with the argument resolved to `never[]`; reads compile either way. +Choose `Database` (from `supabase gen types typescript`) with `createWithSupabase` when tools write. Without it the client is `SupabaseClient` and `insert({ title })` fails type-checking with the argument resolved to `never[]`; reads compile either way. ## The two entries diff --git a/docs/typescript-generics.md b/docs/typescript-generics.md index 8919791..c579dbe 100644 --- a/docs/typescript-generics.md +++ b/docs/typescript-generics.md @@ -18,13 +18,17 @@ This produces a `Database` type that describes your schema. ## Using with withSupabase +Choose `Database` once with `createWithSupabase`, at module scope, and use the result wherever you'd use `withSupabase`: + ```ts -import { withSupabase } from '@supabase/server' +import { createWithSupabase } from '@supabase/server' import type { Database } from './database.types.ts' +const withSupabase = createWithSupabase() + export default { - fetch: withSupabase({ auth: 'user' }, async (_req, ctx) => { - // ctx.supabase is SupabaseClient + fetch: withSupabase({ auth: 'user' }, async (_req, ctx) => { + // ctx.supabase and ctx.supabaseAdmin are SupabaseClient // Fully typed: column names, return type, etc. const { data } = await ctx.supabase .from('todos') @@ -35,6 +39,28 @@ export default { } ``` +The result composes the same way `withSupabase` does: nested around a handler or another middleware, or as a `pipeline` entry, where the entries after it see the typed clients. + +```ts +import { pipeline } from '@supabase/middleware' +import { withPostgresClient } from '@supabase/server/middleware/postgres' + +export default { + fetch: pipeline( + [withSupabase({ auth: 'user' }), withPostgresClient()], + async (_req, ctx) => { + // ctx.supabase is SupabaseClient; ctx.postgres is RLS-scoped too + const { data } = await ctx.supabase.from('todos').select('id, title') + return Response.json(data) + }, + ), +} +``` + +`createWithSupabase` returns a `Composite` from `@supabase/middleware`, so the engine checks it like any composite. A middleware below it that contributes one of its keys fails to compile: `withClaims()` contributes `jwtClaims`, which it already provides. In a nested stack, the check needs `satisfies FetchHandler` on the outermost call. + +Passing `Database` to `withSupabase` itself (`withSupabase(config, handler)`) is deprecated. It also fixes `withSupabase`'s second type parameter to its default, so keys from a middleware wrapped around it are missing from `ctx`. + ## Using with createSupabaseContext ```ts @@ -147,11 +173,13 @@ app.listen(3000) If your tables are in a schema other than `public`, pass it via `supabaseOptions`: ```ts -import { withSupabase } from '@supabase/server' +import { createWithSupabase } from '@supabase/server' import type { Database } from './database.types.ts' +const withSupabase = createWithSupabase() + export default { - fetch: withSupabase( + fetch: withSupabase( { auth: 'user', supabaseOptions: { db: { schema: 'api' } }, @@ -173,7 +201,7 @@ export default { - Auth settings (`persistSession`, `autoRefreshToken`, `detectSessionInUrl`) are force-set to server-safe values ```ts -withSupabase( +withSupabase( { auth: 'user', supabaseOptions: { diff --git a/src/index.ts b/src/index.ts index 0af4547..b71e561 100644 --- a/src/index.ts +++ b/src/index.ts @@ -84,7 +84,7 @@ * @packageDocumentation */ -export { withSupabase } from './with-supabase.js' +export { createWithSupabase, withSupabase } from './with-supabase.js' export { createSupabaseContext } from './create-supabase-context.js' export { withOAuthProtectedResource } from './oauth-protected-resource/with-oauth-protected-resource.js' diff --git a/src/with-supabase.test.ts b/src/with-supabase.test.ts index 02a2f3b..8fccb1d 100644 --- a/src/with-supabase.test.ts +++ b/src/with-supabase.test.ts @@ -1,6 +1,7 @@ import { beforeEach, describe, expect, expectTypeOf, it, vi } from 'vitest' import { defineMiddleware, getEnv, pipeline } from '@supabase/middleware' import type { FetchHandler } from '@supabase/middleware' +import type { SupabaseClient } from '@supabase/supabase-js' import { exportJWK, generateKeyPair, SignJWT } from 'jose' import { _resetAllowDeprecationWarned } from './core/utils/deprecation.js' @@ -16,7 +17,7 @@ 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' -import { withSupabase } from './with-supabase.js' +import { createWithSupabase, withSupabase } from './with-supabase.js' const baseEnv = { url: 'https://test.supabase.co', @@ -25,6 +26,21 @@ const baseEnv = { jwks: null, } +type Database = { + public: { + Tables: { + notes: { + Row: { id: number; body: string } + Insert: { id?: number; body: string } + Update: { id?: number; body?: string } + Relationships: [] + } + } + Views: Record + Functions: Record + } +} + describe('withSupabase', () => { it('handles OPTIONS preflight with CORS', async () => { const handler = withSupabase({ auth: 'none', env: baseEnv }, async () => @@ -570,6 +586,104 @@ describe('type guarantees (tsc-verified)', () => { }) }) +describe('createWithSupabase type guarantees (tsc-verified)', () => { + const withTypedSupabase = createWithSupabase() + const config = { auth: 'user', env: baseEnv } as const + + it('types ctx.supabase and ctx.supabaseAdmin for the chosen Database', () => { + const _handler = withTypedSupabase(config, async (_req, ctx) => { + expectTypeOf(ctx.supabase).toEqualTypeOf>() + expectTypeOf(ctx.supabaseAdmin).toEqualTypeOf>() + await ctx.supabase.from('notes').insert({ body: 'typed' }) + // @ts-expect-error — no such table in Database + await ctx.supabaseAdmin.from('missing').select() + return Response.json({ ok: true }) + }) satisfies FetchHandler + void _handler + }) + + it('as a pipeline entry, passes its keys and the chosen Database on', () => { + const _handler = pipeline( + [withTypedSupabase(config), withPostgresClient()], + async (_req, ctx) => { + expectTypeOf(ctx.postgres).not.toBeAny() + expectTypeOf(ctx.supabase).toEqualTypeOf>() + expectTypeOf(ctx.supabaseAdmin).toEqualTypeOf< + SupabaseClient + >() + return Response.json({ ok: true }) + }, + ) + void _handler + }) + + it('nested: a middleware with a prerequisite composes as the handler', () => { + const _handler = withTypedSupabase( + config, + withPostgresClient(async (_req, ctx) => { + expectTypeOf(ctx.postgres).not.toBeAny() + expectTypeOf(ctx.supabase).toEqualTypeOf>() + expectTypeOf(ctx.supabaseAdmin).toEqualTypeOf< + SupabaseClient + >() + return Response.json({ ok: true }) + }), + ) satisfies FetchHandler + void _handler + }) + + it('nested: Base flows in from an outer middleware alongside Database', () => { + const _composed = withOAuthProtectedResource( + withTypedSupabase(config, async (_req, ctx) => { + expectTypeOf( + ctx.oauthProtectedResource.resourceMetadataUrl, + ).toEqualTypeOf() + expectTypeOf(ctx.supabase).toEqualTypeOf>() + return Response.json({ ok: true }) + }), + ) satisfies FetchHandler + void _composed + }) + + it('accepts a handler annotated with SupabaseContext', () => { + async function handle( + _req: Request, + ctx: SupabaseContext, + ): Promise { + return Response.json({ id: ctx.userClaims?.id ?? null }) + } + const _handler = withTypedSupabase(config, handle) satisfies FetchHandler + void _handler + }) + + it('as a pipeline entry, a later entry contributing one of its keys fails to compile', () => { + const _handler = pipeline( + [withTypedSupabase(config), withClaims()], + // @ts-expect-error — middleware-conflict: it already contributes jwtClaims + async () => Response.json({ ok: true }), + ) + void _handler + }) + + it('nested: a middleware contributing one of its keys fails to compile', () => { + const _handler = withTypedSupabase( + config, + // @ts-expect-error — middleware-conflict: it already contributes jwtClaims + withClaims(async () => Response.json({ ok: true })), + ) satisfies FetchHandler + void _handler + }) + + it('nested: a second withSupabase inside it fails to compile', () => { + const _handler = withTypedSupabase( + config, + // @ts-expect-error — middleware-conflict: its keys are already on the context + withTypedSupabase(config, async () => Response.json({ ok: true })), + ) satisfies FetchHandler + void _handler + }) +}) + describe('withSupabase as a pipeline entry', () => { const oauthCfg = { resourceServer: 'http://localhost/functions/v1/mcp', @@ -852,6 +966,73 @@ describe('withSupabase config without a middleware option', () => { }) }) +describe('createWithSupabase at runtime', () => { + const withTypedSupabase = createWithSupabase() + const oauthCfg = { + resourceServer: 'http://localhost/functions/v1/mcp', + authorizationServer: 'https://test.supabase.co/auth/v1', + } + const ok = async () => new Response('ok') + + it('exposes the same context keys as withSupabase', async () => { + const handler = withTypedSupabase( + { auth: 'none', env: baseEnv }, + async (_req, ctx) => Response.json({ keys: Object.keys(ctx).sort() }), + ) + const body = await (await handler(new Request('http://localhost'))).json() + expect(body.keys).toEqual([ + 'authKeyName', + 'authMode', + 'jwtClaims', + 'supabase', + 'supabaseAdmin', + 'userClaims', + ]) + }) + + it('answers a request without credentials with the gate 401', async () => { + const handler = pipeline( + [withTypedSupabase({ auth: 'user', env: baseEnv })], + ok, + ) + const res = await handler(new Request('http://localhost')) + expect(res.status).toBe(401) + expect(res.headers.get('Access-Control-Allow-Origin')).toBe('*') + }) + + it('refuses withOAuthProtectedResource behind its credentialed gate, in both forms', () => { + expect(() => + pipeline( + [ + withTypedSupabase({ auth: 'user', env: baseEnv }), + withOAuthProtectedResource(oauthCfg), + ], + ok, + ), + ).toThrow(/withOAuthProtectedResource is placed after withSupabase/) + expect(() => + withTypedSupabase( + { auth: 'user', env: baseEnv }, + withOAuthProtectedResource(oauthCfg, ok), + ), + ).toThrow(/placed after withSupabase/) + }) + + it('refuses a config carrying a middleware key', () => { + const config = { + auth: 'none', + env: baseEnv, + middleware: [], + } as unknown as WithSupabaseConfig + expect(() => withTypedSupabase(config, ok)).toThrow( + /has no `middleware` option/, + ) + expect(() => withTypedSupabase(config)).toThrow( + /has no `middleware` option/, + ) + }) +}) + describe('withSupabase audience and issuer validation', () => { it('validates audience and issuer when configured', async () => { const { privateKey, publicKey } = await generateKeyPair('RS256') diff --git a/src/with-supabase.ts b/src/with-supabase.ts index 06c347e..5ee4de2 100644 --- a/src/with-supabase.ts +++ b/src/with-supabase.ts @@ -1,5 +1,10 @@ import { defineComposite } from '@supabase/middleware' -import type { BaseContext, Entry } from '@supabase/middleware' +import type { + BaseContext, + Composite, + Contributions, + Entry, +} from '@supabase/middleware' import { preAuthName } from './core/pre-auth.js' import { withConstructionBoundary } from './core/parts/boundary.js' @@ -24,10 +29,10 @@ import type { type AnyHandler = (req: Request, ctx: any) => Promise /** - * 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}. + * The parts `withSupabase` is made of, outermost first, with both clients + * typed for `Database`. 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 @@ -35,37 +40,45 @@ type AnyHandler = (req: Request, ctx: any) => Promise * result, and the projections must run before the client parts, which read * the flat `authMode` / `authKeyName` keys to mirror the matched credential. */ -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'], -}) +function supabaseComposite() { + return 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`. + * `createWithSupabase`'s return statement checks that every key its declared + * type names is one the parts contribute, with the same type. This checks the + * reverse: a public key the parts contribute but the declaration leaves out + * would escape the collision checks. */ -type EntryIsSound = - ReturnType extends Entry ? true : false -const entryIsSound: EntryIsSound = true -void entryIsSound +type Contributed = Contributions< + [ReturnType>] +> +const everyKeyDeclared: [ + Exclude, +] extends [never] + ? true + : false = true +void everyKeyDeclared /** Whether every configured auth mode requires credentials, so an unauthenticated request never passes the gate. */ function requiresCredentials(config: WithSupabaseConfig): boolean { @@ -105,6 +118,75 @@ function rejectMiddlewareOption(config: WithSupabaseConfig): void { } } +/** + * Runs the two construction-time checks before the composite builds: on the + * config at the call, and on the downstream handler once it is known, which + * for a `pipeline` entry is when the array folds. The composite's type passes + * through unchanged. + */ +function withChecks(composite: C): C { + const build = composite as unknown as ( + config: WithSupabaseConfig, + handler: AnyHandler, + ) => AnyHandler + const checked = (config: WithSupabaseConfig, handler?: AnyHandler) => { + rejectMiddlewareOption(config) + if (handler === undefined) { + return (next: AnyHandler) => { + rejectPreAuthBehindGate(config, next) + return build(config, next) + } + } + rejectPreAuthBehindGate(config, handler) + return build(config, handler) + } + return checked as unknown as C +} + +/** + * Creates a {@link withSupabase} whose clients are typed for your `Database`, + * like `createClient()` in `@supabase/supabase-js`. Call it once at + * module scope, then use the result wherever you use `withSupabase`: nested + * around a handler or another middleware, or as a `pipeline` entry. + * + * The result is a `Composite` from `@supabase/middleware`, built from the same + * parts as `withSupabase` and with the same runtime behavior. Being the + * engine's own type, it gets the engine's checks: a middleware that + * contributes one of its keys again below it fails to compile, in a `pipeline` + * and in a nested stack anchored with `satisfies FetchHandler`. + * + * @typeParam Database - Your generated database types, from + * `supabase gen types typescript`. `ctx.supabase` and `ctx.supabaseAdmin` are + * typed `SupabaseClient`. + * + * @category Middleware + * + * @example + * ```ts + * import { createWithSupabase } from '@supabase/server' + * + * // `Database` is the type `supabase gen types typescript` generates. + * const withSupabase = createWithSupabase() + * + * export default { + * fetch: withSupabase({ auth: 'user' }, async (_req, ctx) => { + * // ctx.supabase is SupabaseClient + * const { data } = await ctx.supabase.from('todos').select('id, title') + * return Response.json(data) + * }), + * } + * ``` + */ +export function createWithSupabase(): Composite< + SupabaseContext, + WithSupabaseConfig, + Record +> { + return withChecks(supabaseComposite()) +} + +const untypedWithSupabase = createWithSupabase() + /** * Wraps a request handler with Supabase auth, client creation, and CORS handling. * @@ -129,10 +211,12 @@ function rejectMiddlewareOption(config: WithSupabaseConfig): void { * the engine already asks of nested stacks (it also gates collision detection * there): `Base` flows from the contextual return type, and without the anchor * the outer call resolves before it can push, so `Base` stays the empty - * upstream and upstream keys are absent from `ctx`. Supplying `Database` explicitly - * (`withSupabase(...)`) also defaults every later type parameter, `Base` - * included; in that case annotate both (`withSupabase(...)`) - * or read the upstream key through a cast. + * upstream and upstream keys are absent from `ctx`. + * + * @typeParam Database - Deprecated: choose it once with + * {@link createWithSupabase} instead. Supplied here (`withSupabase(...)`), + * it also defaults every later type parameter, `Base` included, so upstream + * keys are absent from `ctx`. * * @category Middleware * @@ -170,6 +254,9 @@ export function withSupabase< * requests; entries placed after it receive the full {@link SupabaseContext} * and may declare prerequisites on its keys. * + * @typeParam Database - Deprecated: choose it once with + * {@link createWithSupabase} instead. + * * @category Middleware * * @example OAuth discovery ahead of the gate, Postgres behind it @@ -197,13 +284,7 @@ export function withSupabase( config: WithSupabaseConfig, handler?: AnyHandler, ): unknown { - rejectMiddlewareOption(config) - if (handler === undefined) { - return (next: AnyHandler) => { - rejectPreAuthBehindGate(config, next) - return composite(config, next) - } - } - rejectPreAuthBehindGate(config, handler) - return composite(config, handler) + return handler === undefined + ? untypedWithSupabase(config) + : untypedWithSupabase(config, handler) }