@supabase/server 0.1.0-alpha.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Supabase
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md ADDED
@@ -0,0 +1,305 @@
1
+ # @supabase/server
2
+
3
+ [![License](https://img.shields.io/npm/l/nx.svg?style=flat-square)](./LICENSE)
4
+ [![Package](https://img.shields.io/npm/v/@supabase/server)](https://www.npmjs.com/package/@supabase/server)
5
+ [![pkg.pr.new](https://pkg.pr.new/badge/supabase/server)](https://pkg.pr.new/~/supabase/server)
6
+
7
+ Server-side utilities for Supabase. Handles auth, client creation, and context injection so you write business logic, not boilerplate.
8
+
9
+ ```ts
10
+ import { withSupabase } from '@supabase/server'
11
+
12
+ export default {
13
+ fetch: withSupabase({ allow: 'user' }, async (_req, ctx) => {
14
+ const { data } = await ctx.supabase.from('todos').select()
15
+ return Response.json(data)
16
+ }),
17
+ }
18
+ ```
19
+
20
+ One import. One line of config. Auth is validated, clients are scoped, CORS is handled. Your handler only runs on successful auth.
21
+
22
+ ## Installation
23
+
24
+ ```bash
25
+ # Deno
26
+ import { withSupabase } from "npm:@supabase/server";
27
+
28
+ # npm
29
+ pnpm add @supabase/server
30
+ ```
31
+
32
+ ## Quick Start
33
+
34
+ ### Authenticated endpoint
35
+
36
+ ```ts
37
+ export default {
38
+ fetch: withSupabase({ allow: 'user' }, async (_req, ctx) => {
39
+ // ctx.supabase — RLS-scoped to the authenticated user
40
+ // ctx.supabaseAdmin — bypasses RLS (service role)
41
+ // ctx.userClaims — user identity from JWT (id, email, role)
42
+ // ctx.claims — JWT claims
43
+ // ctx.authType — which auth mode matched
44
+
45
+ const { data } = await ctx.supabase.from('todos').select()
46
+ return Response.json(data)
47
+ }),
48
+ }
49
+ ```
50
+
51
+ ### Public endpoint (no auth)
52
+
53
+ ```ts
54
+ export default {
55
+ fetch: withSupabase({ allow: 'always' }, async (_req, _ctx) => {
56
+ return Response.json({ status: 'ok' })
57
+ }),
58
+ }
59
+ ```
60
+
61
+ ### API key protected
62
+
63
+ ```ts
64
+ export default {
65
+ fetch: withSupabase({ allow: 'secret' }, async (_req, ctx) => {
66
+ const { data } = await ctx.supabaseAdmin.from('config').select()
67
+ return Response.json(data)
68
+ }),
69
+ }
70
+ ```
71
+
72
+ ### Dual auth (user or service)
73
+
74
+ ```ts
75
+ export default {
76
+ fetch: withSupabase({ allow: ['user', 'secret'] }, async (req, ctx) => {
77
+ const userId = ctx.userClaims?.id ?? (await req.json()).user_id
78
+ const { data } = await ctx.supabaseAdmin
79
+ .from('reports')
80
+ .select()
81
+ .eq('user_id', userId)
82
+ return Response.json(data)
83
+ }),
84
+ }
85
+ ```
86
+
87
+ ## Auth Modes
88
+
89
+ | Mode | Credential | Use case |
90
+ | ------------------ | --------------------- | --------------------------------------------------- |
91
+ | `"user"` (default) | Valid JWT | Authenticated user endpoints |
92
+ | `"public"` | Valid publishable key | Client-facing, key-validated endpoints |
93
+ | `"secret"` | Valid secret key | Server-to-server, internal calls |
94
+ | `"always"` | None | Open endpoints, wrappers that handle their own auth |
95
+
96
+ Array syntax (`allow: ["user", "secret"]`) accepts multiple auth methods — first match wins.
97
+
98
+ Named key validation: `allow: "public:web_app"` validates against a specific named key in `SUPABASE_PUBLISHABLE_KEYS`.
99
+
100
+ ## Context
101
+
102
+ Every handler receives a `SupabaseContext`:
103
+
104
+ ```ts
105
+ interface SupabaseContext {
106
+ supabase: SupabaseClient // RLS-scoped (user or anon depending on auth)
107
+ supabaseAdmin: SupabaseClient // Bypasses RLS
108
+ userClaims: UserClaims | null // JWT-derived identity (for full User, call supabase.auth.getUser())
109
+ claims: JWTClaims | null // Present when auth is JWT
110
+ authType: Allow // Which auth mode matched
111
+ }
112
+ ```
113
+
114
+ `supabase` is always the safe client — it respects RLS. When `authType` is `"user"`, it's scoped to that user's permissions. Otherwise, it's initialized as anonymous.
115
+
116
+ `supabaseAdmin` always bypasses RLS. Use it for operations that need full database access.
117
+
118
+ ## Config
119
+
120
+ ```ts
121
+ withSupabase(
122
+ {
123
+ allow: 'user', // who can call this function
124
+ cors: false, // disable CORS (default: supabase-js CORS headers)
125
+ env: { url: '...' }, // env overrides (optional)
126
+ },
127
+ handler,
128
+ )
129
+ ```
130
+
131
+ `cors` defaults to the standard [supabase-js CORS headers](https://supabase.com/docs/guides/functions/cors). Pass a `Record<string, string>` to set custom headers, or `false` to disable CORS handling (e.g. when using a framework that handles CORS separately).
132
+
133
+ ```ts
134
+ withSupabase(
135
+ {
136
+ allow: 'user',
137
+ cors: {
138
+ 'Access-Control-Allow-Origin': 'https://myapp.com',
139
+ 'Access-Control-Allow-Headers': 'authorization, content-type',
140
+ },
141
+ },
142
+ handler,
143
+ )
144
+ ```
145
+
146
+ `env` overrides environment variable resolution. Defaults to reading `SUPABASE_URL`, `SUPABASE_PUBLISHABLE_KEYS`, `SUPABASE_SECRET_KEYS`, and `SUPABASE_JWKS` from the runtime environment.
147
+
148
+ ## Framework Adapters
149
+
150
+ ### Hono
151
+
152
+ ```ts
153
+ import { Hono } from 'hono'
154
+ import { withSupabase } from '@supabase/server/adapters/hono'
155
+
156
+ const app = new Hono()
157
+
158
+ app.get('/todos', withSupabase({ allow: 'user' }), async (c) => {
159
+ const { supabase: sb } = c.var.supabaseContext
160
+ const { data } = await sb.from('todos').select()
161
+ return c.json(data)
162
+ })
163
+
164
+ app.get('/health', (c) => c.json({ status: 'ok' }))
165
+
166
+ export default { fetch: app.fetch }
167
+ ```
168
+
169
+ The adapter does not handle CORS — use `hono/cors` for that. Per-route auth works naturally by applying the middleware to specific routes.
170
+
171
+ ## Primitives
172
+
173
+ For when you need more control than `withSupabase` provides — multiple routes with different auth, custom response headers, or building your own wrapper.
174
+
175
+ All primitives are available from `@supabase/server/core`.
176
+
177
+ ```ts
178
+ import {
179
+ verifyAuth,
180
+ createContextClient,
181
+ createAdminClient,
182
+ } from '@supabase/server/core'
183
+ ```
184
+
185
+ ### verifyAuth
186
+
187
+ Extracts credentials from a Request and validates against the allow config.
188
+
189
+ ```ts
190
+ const { data: auth, error } = await verifyAuth(req, { allow: 'user' })
191
+ if (error) {
192
+ return Response.json({ error: error.message }, { status: error.status })
193
+ }
194
+ ```
195
+
196
+ ### verifyCredentials
197
+
198
+ Low-level — works with raw credentials instead of a Request. Used by SSR adapters and custom auth flows.
199
+
200
+ ```ts
201
+ const credentials = { token: myToken, apikey: null }
202
+ const { data: auth, error } = await verifyCredentials(credentials, {
203
+ allow: 'user',
204
+ })
205
+ ```
206
+
207
+ ### createContextClient / createAdminClient
208
+
209
+ ```ts
210
+ const supabase = createContextClient(auth.token) // user-scoped, RLS applies
211
+ const supabase = createContextClient() // anonymous, RLS as anon
212
+ const supabaseAdmin = createAdminClient() // bypasses RLS
213
+ ```
214
+
215
+ ### createSupabaseContext
216
+
217
+ Full context assembly from a Request — `verifyAuth` + client creation in one call.
218
+
219
+ ```ts
220
+ const { data: ctx, error } = await createSupabaseContext(req, { allow: 'user' })
221
+ ```
222
+
223
+ ### resolveEnv
224
+
225
+ Resolves environment variables with optional overrides.
226
+
227
+ ```ts
228
+ const { data: env, error } = resolveEnv({
229
+ url: process.env.NEXT_PUBLIC_SUPABASE_URL,
230
+ })
231
+ ```
232
+
233
+ ### Example: custom multi-route handler
234
+
235
+ ```ts
236
+ import { verifyAuth, createContextClient } from '@supabase/server/core'
237
+
238
+ export default {
239
+ fetch: async (req) => {
240
+ const url = new URL(req.url)
241
+
242
+ if (url.pathname === '/health') {
243
+ return Response.json({ status: 'ok' })
244
+ }
245
+
246
+ if (url.pathname === '/todos') {
247
+ const { data: auth, error } = await verifyAuth(req, { allow: 'user' })
248
+ if (error)
249
+ return Response.json({ error: error.message }, { status: error.status })
250
+
251
+ const supabase = createContextClient(auth.token)
252
+ const { data } = await supabase.from('todos').select()
253
+ return Response.json(data)
254
+ }
255
+
256
+ return new Response('Not found', { status: 404 })
257
+ },
258
+ }
259
+ ```
260
+
261
+ ## Environment Variables
262
+
263
+ Automatically available in Supabase Edge Functions:
264
+
265
+ | Variable | Format | Description |
266
+ | --------------------------- | ------------------------------------------------------------- | ------------------------------------- |
267
+ | `SUPABASE_URL` | `https://<ref>.supabase.co` | Your project URL |
268
+ | `SUPABASE_PUBLISHABLE_KEYS` | `{"default":"sb_publishable_...","web":"sb_publishable_..."}` | Publishable API keys (named) |
269
+ | `SUPABASE_SECRET_KEYS` | `{"default":"sb_secret_...","web":"sb_secret_..."}` | Secret API keys (named) |
270
+ | `SUPABASE_JWKS` | `{"keys":[...]}` or `[...]` | JSON Web Key Set for JWT verification |
271
+
272
+ Also supported (for local dev, self-hosted, or other runtimes):
273
+
274
+ | Variable | Format | Description |
275
+ | -------------------------- | -------------------- | ---------------------- |
276
+ | `SUPABASE_PUBLISHABLE_KEY` | `sb_publishable_...` | Single publishable key |
277
+ | `SUPABASE_SECRET_KEY` | `sb_secret_...` | Single secret key |
278
+
279
+ When both singular and plural forms are set, plural takes priority.
280
+
281
+ For other environments, pass overrides via the `env` config option or `resolveEnv()`.
282
+
283
+ ## Exports
284
+
285
+ | Export | What's in it |
286
+ | -------------------------------- | ----------------------------------------------------------------------------------------------------------------- |
287
+ | `@supabase/server` | `withSupabase`, `createSupabaseContext` |
288
+ | `@supabase/server/core` | `verifyAuth`, `verifyCredentials`, `extractCredentials`, `createContextClient`, `createAdminClient`, `resolveEnv` |
289
+ | `@supabase/server/wrappers` | `verifyWebhookSignature` |
290
+ | `@supabase/server/adapters/hono` | `withSupabase` (Hono middleware) |
291
+
292
+ ## Development
293
+
294
+ ```bash
295
+ pnpm install
296
+ pnpm dev
297
+ ```
298
+
299
+ ## Contributing
300
+
301
+ See [CONTRIBUTING.md](CONTRIBUTING.md) for development workflow, commit conventions, and release process.
302
+
303
+ ## License
304
+
305
+ MIT
@@ -0,0 +1,24 @@
1
+ Object.defineProperty(exports, Symbol.toStringTag, { value: 'Module' });
2
+ const require_create_supabase_context = require('../../create-supabase-context-DNWor6i_.cjs');
3
+ let hono_http_exception = require("hono/http-exception");
4
+ let hono_factory = require("hono/factory");
5
+
6
+ //#region src/adapters/hono/middleware.ts
7
+ function withSupabase(config) {
8
+ return (0, hono_factory.createMiddleware)(async (c, next) => {
9
+ if (c.var.supabaseContext) {
10
+ await next();
11
+ return;
12
+ }
13
+ const { data: ctx, error } = await require_create_supabase_context.createSupabaseContext(c.req.raw, config);
14
+ if (error) throw new hono_http_exception.HTTPException(error.status, {
15
+ message: error.message,
16
+ cause: error
17
+ });
18
+ c.set("supabaseContext", ctx);
19
+ await next();
20
+ });
21
+ }
22
+
23
+ //#endregion
24
+ exports.withSupabase = withSupabase;
@@ -0,0 +1,11 @@
1
+ import { l as WithSupabaseConfig, o as SupabaseContext } from "../../types-DNh3Z1O1.cjs";
2
+ import * as hono_types0 from "hono/types";
3
+
4
+ //#region src/adapters/hono/middleware.d.ts
5
+ declare function withSupabase(config?: Omit<WithSupabaseConfig, 'cors'>): hono_types0.MiddlewareHandler<{
6
+ Variables: {
7
+ supabaseContext: SupabaseContext;
8
+ };
9
+ }, string, {}, Response>;
10
+ //#endregion
11
+ export { withSupabase };
@@ -0,0 +1,11 @@
1
+ import { l as WithSupabaseConfig, o as SupabaseContext } from "../../types-BLM5-qA8.mjs";
2
+ import * as hono_types0 from "hono/types";
3
+
4
+ //#region src/adapters/hono/middleware.d.ts
5
+ declare function withSupabase(config?: Omit<WithSupabaseConfig, 'cors'>): hono_types0.MiddlewareHandler<{
6
+ Variables: {
7
+ supabaseContext: SupabaseContext;
8
+ };
9
+ }, string, {}, Response>;
10
+ //#endregion
11
+ export { withSupabase };
@@ -0,0 +1,23 @@
1
+ import { t as createSupabaseContext } from "../../create-supabase-context-BrSIe29v.mjs";
2
+ import { HTTPException } from "hono/http-exception";
3
+ import { createMiddleware } from "hono/factory";
4
+
5
+ //#region src/adapters/hono/middleware.ts
6
+ function withSupabase(config) {
7
+ return createMiddleware(async (c, next) => {
8
+ if (c.var.supabaseContext) {
9
+ await next();
10
+ return;
11
+ }
12
+ const { data: ctx, error } = await createSupabaseContext(c.req.raw, config);
13
+ if (error) throw new HTTPException(error.status, {
14
+ message: error.message,
15
+ cause: error
16
+ });
17
+ c.set("supabaseContext", ctx);
18
+ await next();
19
+ });
20
+ }
21
+
22
+ //#endregion
23
+ export { withSupabase };
@@ -0,0 +1,9 @@
1
+ Object.defineProperty(exports, Symbol.toStringTag, { value: 'Module' });
2
+ const require_verify_auth = require('../verify-auth-6a1UPrFz.cjs');
3
+
4
+ exports.createAdminClient = require_verify_auth.createAdminClient;
5
+ exports.createContextClient = require_verify_auth.createContextClient;
6
+ exports.extractCredentials = require_verify_auth.extractCredentials;
7
+ exports.resolveEnv = require_verify_auth.resolveEnv;
8
+ exports.verifyAuth = require_verify_auth.verifyAuth;
9
+ exports.verifyCredentials = require_verify_auth.verifyCredentials;
@@ -0,0 +1,3 @@
1
+ import "../types-DNh3Z1O1.cjs";
2
+ import { a as extractCredentials, i as verifyCredentials, n as createContextClient, o as resolveEnv, r as verifyAuth, t as createAdminClient } from "../create-admin-client-BZ_3qcxI.cjs";
3
+ export { createAdminClient, createContextClient, extractCredentials, resolveEnv, verifyAuth, verifyCredentials };
@@ -0,0 +1,3 @@
1
+ import "../types-BLM5-qA8.mjs";
2
+ import { a as extractCredentials, i as verifyCredentials, n as createContextClient, o as resolveEnv, r as verifyAuth, t as createAdminClient } from "../create-admin-client-CSX-Q_Fv.mjs";
3
+ export { createAdminClient, createContextClient, extractCredentials, resolveEnv, verifyAuth, verifyCredentials };
@@ -0,0 +1,3 @@
1
+ import { a as createAdminClient, i as createContextClient, n as verifyCredentials, o as resolveEnv, r as extractCredentials, t as verifyAuth } from "../verify-auth-DxUT0XoT.mjs";
2
+
3
+ export { createAdminClient, createContextClient, extractCredentials, resolveEnv, verifyAuth, verifyCredentials };
@@ -0,0 +1,60 @@
1
+ import { i as Credentials, n as AllowWithKey, r as AuthResult, s as SupabaseEnv } from "./types-DNh3Z1O1.cjs";
2
+ import { SupabaseClient } from "@supabase/supabase-js";
3
+
4
+ //#region src/errors.d.ts
5
+ declare class EnvError extends Error {
6
+ readonly status = 500;
7
+ readonly code: string;
8
+ constructor(message: string, code?: string);
9
+ }
10
+ declare class AuthError extends Error {
11
+ readonly status: number;
12
+ readonly code: string;
13
+ constructor(message: string, code?: string, status?: number);
14
+ }
15
+ //#endregion
16
+ //#region src/core/resolve-env.d.ts
17
+ declare function resolveEnv(overrides?: Partial<SupabaseEnv>): {
18
+ data: SupabaseEnv;
19
+ error: null;
20
+ } | {
21
+ data: null;
22
+ error: EnvError;
23
+ };
24
+ //#endregion
25
+ //#region src/core/extract-credentials.d.ts
26
+ declare function extractCredentials(request: Request): Credentials;
27
+ //#endregion
28
+ //#region src/core/verify-credentials.d.ts
29
+ interface VerifyCredentialsOptions {
30
+ allow: AllowWithKey | AllowWithKey[];
31
+ env?: Partial<SupabaseEnv>;
32
+ }
33
+ declare function verifyCredentials(credentials: Credentials, options: VerifyCredentialsOptions): Promise<{
34
+ data: AuthResult;
35
+ error: null;
36
+ } | {
37
+ data: null;
38
+ error: AuthError;
39
+ }>;
40
+ //#endregion
41
+ //#region src/core/verify-auth.d.ts
42
+ interface VerifyAuthOptions {
43
+ allow: AllowWithKey | AllowWithKey[];
44
+ env?: Partial<SupabaseEnv>;
45
+ }
46
+ declare function verifyAuth(request: Request, options: VerifyAuthOptions): Promise<{
47
+ data: AuthResult;
48
+ error: null;
49
+ } | {
50
+ data: null;
51
+ error: AuthError;
52
+ }>;
53
+ //#endregion
54
+ //#region src/core/create-context-client.d.ts
55
+ declare function createContextClient(token?: string | null, env?: Partial<SupabaseEnv>, keyName?: string | null): SupabaseClient;
56
+ //#endregion
57
+ //#region src/core/create-admin-client.d.ts
58
+ declare function createAdminClient(env?: Partial<SupabaseEnv>, keyName?: string | null): SupabaseClient;
59
+ //#endregion
60
+ export { extractCredentials as a, EnvError as c, verifyCredentials as i, createContextClient as n, resolveEnv as o, verifyAuth as r, AuthError as s, createAdminClient as t };
@@ -0,0 +1,60 @@
1
+ import { i as Credentials, n as AllowWithKey, r as AuthResult, s as SupabaseEnv } from "./types-BLM5-qA8.mjs";
2
+ import { SupabaseClient } from "@supabase/supabase-js";
3
+
4
+ //#region src/errors.d.ts
5
+ declare class EnvError extends Error {
6
+ readonly status = 500;
7
+ readonly code: string;
8
+ constructor(message: string, code?: string);
9
+ }
10
+ declare class AuthError extends Error {
11
+ readonly status: number;
12
+ readonly code: string;
13
+ constructor(message: string, code?: string, status?: number);
14
+ }
15
+ //#endregion
16
+ //#region src/core/resolve-env.d.ts
17
+ declare function resolveEnv(overrides?: Partial<SupabaseEnv>): {
18
+ data: SupabaseEnv;
19
+ error: null;
20
+ } | {
21
+ data: null;
22
+ error: EnvError;
23
+ };
24
+ //#endregion
25
+ //#region src/core/extract-credentials.d.ts
26
+ declare function extractCredentials(request: Request): Credentials;
27
+ //#endregion
28
+ //#region src/core/verify-credentials.d.ts
29
+ interface VerifyCredentialsOptions {
30
+ allow: AllowWithKey | AllowWithKey[];
31
+ env?: Partial<SupabaseEnv>;
32
+ }
33
+ declare function verifyCredentials(credentials: Credentials, options: VerifyCredentialsOptions): Promise<{
34
+ data: AuthResult;
35
+ error: null;
36
+ } | {
37
+ data: null;
38
+ error: AuthError;
39
+ }>;
40
+ //#endregion
41
+ //#region src/core/verify-auth.d.ts
42
+ interface VerifyAuthOptions {
43
+ allow: AllowWithKey | AllowWithKey[];
44
+ env?: Partial<SupabaseEnv>;
45
+ }
46
+ declare function verifyAuth(request: Request, options: VerifyAuthOptions): Promise<{
47
+ data: AuthResult;
48
+ error: null;
49
+ } | {
50
+ data: null;
51
+ error: AuthError;
52
+ }>;
53
+ //#endregion
54
+ //#region src/core/create-context-client.d.ts
55
+ declare function createContextClient(token?: string | null, env?: Partial<SupabaseEnv>, keyName?: string | null): SupabaseClient;
56
+ //#endregion
57
+ //#region src/core/create-admin-client.d.ts
58
+ declare function createAdminClient(env?: Partial<SupabaseEnv>, keyName?: string | null): SupabaseClient;
59
+ //#endregion
60
+ export { extractCredentials as a, EnvError as c, verifyCredentials as i, createContextClient as n, resolveEnv as o, verifyAuth as r, AuthError as s, createAdminClient as t };
@@ -0,0 +1,35 @@
1
+ import { a as createAdminClient, c as EnvError, i as createContextClient, s as AuthError, t as verifyAuth } from "./verify-auth-DxUT0XoT.mjs";
2
+
3
+ //#region src/create-supabase-context.ts
4
+ async function createSupabaseContext(request, options) {
5
+ const { data: auth, error } = await verifyAuth(request, {
6
+ allow: options?.allow ?? "user",
7
+ env: options?.env
8
+ });
9
+ if (error) return {
10
+ data: null,
11
+ error
12
+ };
13
+ try {
14
+ const supabase = createContextClient(auth.token, options?.env, auth.keyName);
15
+ const adminKeyName = auth.authType === "secret" ? auth.keyName : void 0;
16
+ return {
17
+ data: {
18
+ supabase,
19
+ supabaseAdmin: createAdminClient(options?.env, adminKeyName),
20
+ userClaims: auth.userClaims,
21
+ claims: auth.claims,
22
+ authType: auth.authType
23
+ },
24
+ error: null
25
+ };
26
+ } catch (e) {
27
+ return {
28
+ data: null,
29
+ error: e instanceof EnvError ? new AuthError(e.message, e.code, 500) : new AuthError("Failed to create Supabase client", "CLIENT_ERROR", 500)
30
+ };
31
+ }
32
+ }
33
+
34
+ //#endregion
35
+ export { createSupabaseContext as t };
@@ -0,0 +1,40 @@
1
+ const require_verify_auth = require('./verify-auth-6a1UPrFz.cjs');
2
+
3
+ //#region src/create-supabase-context.ts
4
+ async function createSupabaseContext(request, options) {
5
+ const { data: auth, error } = await require_verify_auth.verifyAuth(request, {
6
+ allow: options?.allow ?? "user",
7
+ env: options?.env
8
+ });
9
+ if (error) return {
10
+ data: null,
11
+ error
12
+ };
13
+ try {
14
+ const supabase = require_verify_auth.createContextClient(auth.token, options?.env, auth.keyName);
15
+ const adminKeyName = auth.authType === "secret" ? auth.keyName : void 0;
16
+ return {
17
+ data: {
18
+ supabase,
19
+ supabaseAdmin: require_verify_auth.createAdminClient(options?.env, adminKeyName),
20
+ userClaims: auth.userClaims,
21
+ claims: auth.claims,
22
+ authType: auth.authType
23
+ },
24
+ error: null
25
+ };
26
+ } catch (e) {
27
+ return {
28
+ data: null,
29
+ error: e instanceof require_verify_auth.EnvError ? new require_verify_auth.AuthError(e.message, e.code, 500) : new require_verify_auth.AuthError("Failed to create Supabase client", "CLIENT_ERROR", 500)
30
+ };
31
+ }
32
+ }
33
+
34
+ //#endregion
35
+ Object.defineProperty(exports, 'createSupabaseContext', {
36
+ enumerable: true,
37
+ get: function () {
38
+ return createSupabaseContext;
39
+ }
40
+ });
package/dist/index.cjs ADDED
@@ -0,0 +1,52 @@
1
+ Object.defineProperty(exports, Symbol.toStringTag, { value: 'Module' });
2
+ const require_verify_auth = require('./verify-auth-6a1UPrFz.cjs');
3
+ const require_create_supabase_context = require('./create-supabase-context-DNWor6i_.cjs');
4
+ let _supabase_supabase_js_cors = require("@supabase/supabase-js/cors");
5
+
6
+ //#region src/cors.ts
7
+ function buildCorsHeaders(config) {
8
+ if (config === false) return {};
9
+ if (typeof config === "object") return config;
10
+ return _supabase_supabase_js_cors.corsHeaders;
11
+ }
12
+ function addCorsHeaders(response, config) {
13
+ if (config === false) return response;
14
+ const corsHeaders = buildCorsHeaders(config);
15
+ const newResponse = new Response(response.body, response);
16
+ for (const [key, value] of Object.entries(corsHeaders)) newResponse.headers.set(key, value);
17
+ return newResponse;
18
+ }
19
+
20
+ //#endregion
21
+ //#region src/with-supabase.ts
22
+ function withSupabase(config, handler) {
23
+ return async (req) => {
24
+ if (config.cors !== false && req.method === "OPTIONS") return new Response(null, {
25
+ status: 204,
26
+ headers: buildCorsHeaders(config.cors)
27
+ });
28
+ const { data: ctx, error } = await require_create_supabase_context.createSupabaseContext(req, config);
29
+ if (error) return Response.json({
30
+ error: error.message,
31
+ code: error.code
32
+ }, {
33
+ status: error.status,
34
+ headers: config.cors !== false ? buildCorsHeaders(config.cors) : {}
35
+ });
36
+ const response = await handler(req, ctx);
37
+ if (config.cors !== false) return addCorsHeaders(response, config.cors);
38
+ return response;
39
+ };
40
+ }
41
+
42
+ //#endregion
43
+ exports.AuthError = require_verify_auth.AuthError;
44
+ exports.EnvError = require_verify_auth.EnvError;
45
+ exports.createAdminClient = require_verify_auth.createAdminClient;
46
+ exports.createContextClient = require_verify_auth.createContextClient;
47
+ exports.createSupabaseContext = require_create_supabase_context.createSupabaseContext;
48
+ exports.extractCredentials = require_verify_auth.extractCredentials;
49
+ exports.resolveEnv = require_verify_auth.resolveEnv;
50
+ exports.verifyAuth = require_verify_auth.verifyAuth;
51
+ exports.verifyCredentials = require_verify_auth.verifyCredentials;
52
+ exports.withSupabase = withSupabase;