@cbrl/supabase 0.0.0-stage → 0.1.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 +21 -0
- package/README.md +224 -2
- package/dist/client.d.mts +7 -0
- package/dist/client.mjs +13 -0
- package/dist/config-Dkh2tZlv.mjs +22 -0
- package/dist/index.d.mts +45 -0
- package/dist/index.mjs +42 -0
- package/dist/local.d.mts +49 -0
- package/dist/local.mjs +89 -0
- package/dist/proxy.d.mts +23 -0
- package/dist/proxy.mjs +53 -0
- package/dist/react.d.mts +24 -0
- package/dist/react.mjs +46 -0
- package/dist/routes.d.mts +43 -0
- package/dist/routes.mjs +67 -0
- package/dist/safe-next-DOPsO5Ar.mjs +18 -0
- package/dist/server.d.mts +12 -0
- package/dist/server.mjs +30 -0
- package/package.json +76 -3
package/LICENSE
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026 Kayron Cabral
|
|
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
CHANGED
|
@@ -1,3 +1,225 @@
|
|
|
1
|
-
#
|
|
1
|
+
# @cbrl/supabase
|
|
2
2
|
|
|
3
|
-
|
|
3
|
+
Supabase Auth wiring for Next.js 16 (App Router, `proxy.ts`), so each app keeps
|
|
4
|
+
only its specifics (redirect paths, user upsert, logging):
|
|
5
|
+
|
|
6
|
+
- Public config read as literal `process.env.NEXT_PUBLIC_*`, so Next.js inlines it.
|
|
7
|
+
- Browser and cookie-bound server clients that return `null` when Supabase is
|
|
8
|
+
not configured, letting the app render a signed-out UI instead of crashing.
|
|
9
|
+
- Session refresh for `proxy.ts` per the `@supabase/ssr` cookie contract, bounded
|
|
10
|
+
by a timeout so an outage never blocks a request.
|
|
11
|
+
- Route Handler factories for the OAuth (PKCE) callback and an E2E-only password
|
|
12
|
+
sign-in, both with same-origin `next` sanitisation.
|
|
13
|
+
- A Google sign-in hook and helpers that read the local stack for scripts and
|
|
14
|
+
Playwright.
|
|
15
|
+
|
|
16
|
+
```sh
|
|
17
|
+
pnpm add @cbrl/supabase @supabase/ssr @supabase/supabase-js
|
|
18
|
+
```
|
|
19
|
+
|
|
20
|
+
Peers: `next` ^16, `react` ^19, `@supabase/ssr` ^0.12, `@supabase/supabase-js` ^2.119.
|
|
21
|
+
|
|
22
|
+
| Entry | Runs in | Exports |
|
|
23
|
+
| ----------------------- | ---------------------------------- | ----------------------------------------------------------------------------------------------------------------------- |
|
|
24
|
+
| `@cbrl/supabase` | anywhere | `supabasePublicConfig()`, `isSupabaseConfigured()`, `sessionUserFromAuthUser(user)`, `sessionUserFromClaims(claims)` |
|
|
25
|
+
| `@cbrl/supabase/client` | browser | `getSupabaseBrowserClient()` |
|
|
26
|
+
| `@cbrl/supabase/server` | server (`server-only`) | `createSupabaseServerClient()` |
|
|
27
|
+
| `@cbrl/supabase/proxy` | `proxy.ts` | `updateSession(request, options?)`, `SESSION_REFRESH_TIMEOUT_MS` |
|
|
28
|
+
| `@cbrl/supabase/routes` | Route Handlers (`server-only`) | `authCallbackRoute(options)`, `testSignInRoute(options?)` |
|
|
29
|
+
| `@cbrl/supabase/react` | Client Components (`'use client'`) | `useGoogleSignIn(options)` |
|
|
30
|
+
| `@cbrl/supabase/local` | Node scripts, Playwright config | `findSupabaseAppDir(cwd?, options?)`, `readLocalSupabase(options?)`, `withRole(dbUrl, user, password)`, `writeEnvLocal` |
|
|
31
|
+
|
|
32
|
+
Environment: `NEXT_PUBLIC_SUPABASE_URL` and `NEXT_PUBLIC_SUPABASE_PUBLISHABLE_KEY`.
|
|
33
|
+
|
|
34
|
+
## Root: config and session user
|
|
35
|
+
|
|
36
|
+
```ts
|
|
37
|
+
import { isSupabaseConfigured, sessionUserFromClaims, type SessionUser } from '@cbrl/supabase'
|
|
38
|
+
```
|
|
39
|
+
|
|
40
|
+
`SessionUser` is `{ id, email, name, avatarUrl, emailVerified, appMetadata }`:
|
|
41
|
+
`name` is `full_name` or `name`, `avatarUrl` is `avatar_url` or `picture` from the
|
|
42
|
+
identity metadata, `emailVerified` is `true` only when the provider reported
|
|
43
|
+
`email_verified: true`. Map it further in the app when needed:
|
|
44
|
+
|
|
45
|
+
```ts
|
|
46
|
+
// app: lib/auth/session.ts
|
|
47
|
+
import 'server-only'
|
|
48
|
+
import { sessionUserFromClaims } from '@cbrl/supabase'
|
|
49
|
+
import { createSupabaseServerClient } from '@cbrl/supabase/server'
|
|
50
|
+
import { isAuthSessionMissingError } from '@supabase/supabase-js'
|
|
51
|
+
import { cache } from 'react'
|
|
52
|
+
|
|
53
|
+
export const getSessionUser = cache(async () => {
|
|
54
|
+
const supabase = await createSupabaseServerClient()
|
|
55
|
+
if (!supabase) return null
|
|
56
|
+
const { data, error } = await supabase.auth.getClaims()
|
|
57
|
+
if (error && !isAuthSessionMissingError(error)) throw error
|
|
58
|
+
if (!data?.claims) return null
|
|
59
|
+
const user = sessionUserFromClaims(data.claims)
|
|
60
|
+
const legacyUid = user.appMetadata.legacy_uid
|
|
61
|
+
return { ...user, uid: typeof legacyUid === 'string' ? legacyUid : user.id }
|
|
62
|
+
})
|
|
63
|
+
```
|
|
64
|
+
|
|
65
|
+
## `/client` and `/server`
|
|
66
|
+
|
|
67
|
+
```ts
|
|
68
|
+
'use client'
|
|
69
|
+
import { getSupabaseBrowserClient } from '@cbrl/supabase/client'
|
|
70
|
+
|
|
71
|
+
const supabase = getSupabaseBrowserClient() // singleton; null when unconfigured
|
|
72
|
+
```
|
|
73
|
+
|
|
74
|
+
```ts
|
|
75
|
+
import { createSupabaseServerClient } from '@cbrl/supabase/server'
|
|
76
|
+
|
|
77
|
+
const supabase = await createSupabaseServerClient() // one per request; null when unconfigured
|
|
78
|
+
```
|
|
79
|
+
|
|
80
|
+
Cookie writes from Server Components are dropped (Next.js forbids them); the
|
|
81
|
+
proxy refresh already wrote the fresh token on the way in.
|
|
82
|
+
|
|
83
|
+
## `/proxy`
|
|
84
|
+
|
|
85
|
+
```ts
|
|
86
|
+
// src/proxy.ts
|
|
87
|
+
import { updateSession } from '@cbrl/supabase/proxy'
|
|
88
|
+
import type { NextRequest } from 'next/server'
|
|
89
|
+
|
|
90
|
+
export async function proxy(request: NextRequest) {
|
|
91
|
+
const requestHeaders = new Headers(request.headers)
|
|
92
|
+
requestHeaders.set('x-pathname', request.nextUrl.pathname + request.nextUrl.search)
|
|
93
|
+
return updateSession(request, {
|
|
94
|
+
requestHeaders,
|
|
95
|
+
onError: (error) => console.warn('session refresh failed', error),
|
|
96
|
+
})
|
|
97
|
+
}
|
|
98
|
+
|
|
99
|
+
export const config = {
|
|
100
|
+
matcher: [
|
|
101
|
+
'/((?!_next/static|_next/image|favicon.ico|.*\\.(?:svg|png|jpg|jpeg|gif|webp|avif|ico)$).*)',
|
|
102
|
+
],
|
|
103
|
+
}
|
|
104
|
+
```
|
|
105
|
+
|
|
106
|
+
| Option | Default | Effect |
|
|
107
|
+
| ---------------- | -------- | --------------------------------------------------------------------------------------- |
|
|
108
|
+
| `requestHeaders` | incoming | Headers forwarded to the app; refreshed `cookie` is written into them before forwarding |
|
|
109
|
+
| `onError` | none | Called when `getClaims()` throws or times out; the request still goes through |
|
|
110
|
+
| `timeoutMs` | `4000` | Upper bound for the refresh |
|
|
111
|
+
|
|
112
|
+
## `/routes`
|
|
113
|
+
|
|
114
|
+
```ts
|
|
115
|
+
// src/app/auth/callback/route.ts
|
|
116
|
+
import { sessionUserFromAuthUser } from '@cbrl/supabase'
|
|
117
|
+
import { authCallbackRoute } from '@cbrl/supabase/routes'
|
|
118
|
+
import { upsertUser } from '@/lib/auth/upsert-user'
|
|
119
|
+
|
|
120
|
+
export const GET = authCallbackRoute({
|
|
121
|
+
defaultNext: '/dashboard',
|
|
122
|
+
failurePath: '/login?error=auth',
|
|
123
|
+
onSession: (user) => upsertUser(sessionUserFromAuthUser(user)),
|
|
124
|
+
onError: (error) => console.warn('code exchange failed', error.code ?? error.name),
|
|
125
|
+
})
|
|
126
|
+
```
|
|
127
|
+
|
|
128
|
+
`next` is honoured only when it resolves to a same-origin path; otherwise the
|
|
129
|
+
user lands on `defaultNext`. A missing code, missing config or failed exchange
|
|
130
|
+
redirects to `failurePath`. A throw in `onSession` propagates.
|
|
131
|
+
|
|
132
|
+
```ts
|
|
133
|
+
// src/app/api/e2e-signin/route.ts
|
|
134
|
+
import { testSignInRoute } from '@cbrl/supabase/routes'
|
|
135
|
+
|
|
136
|
+
export const POST = testSignInRoute()
|
|
137
|
+
```
|
|
138
|
+
|
|
139
|
+
The test sign-in responds 404 unless `ENABLE_TEST_AUTH=true`, and always 404 when
|
|
140
|
+
`VERCEL_ENV=production`. It takes `{ email, password }` (400 otherwise), returns
|
|
141
|
+
503 without config, 401 on bad credentials and `{ userId, ...extra }` on success,
|
|
142
|
+
where `extra` is what the optional `onSignIn(user, supabase)` returns. Enable
|
|
143
|
+
password sign-in only in the local `supabase/config.toml`.
|
|
144
|
+
|
|
145
|
+
## `/react`
|
|
146
|
+
|
|
147
|
+
```tsx
|
|
148
|
+
'use client'
|
|
149
|
+
import { Button } from '@cbrl/design'
|
|
150
|
+
import { useGoogleSignIn } from '@cbrl/supabase/react'
|
|
151
|
+
import { toast } from 'sonner'
|
|
152
|
+
|
|
153
|
+
export function GoogleButton({ next }: { next: string }) {
|
|
154
|
+
const { signIn, pending } = useGoogleSignIn({
|
|
155
|
+
next,
|
|
156
|
+
onError: () => toast.error('Could not sign in. Try again.'),
|
|
157
|
+
})
|
|
158
|
+
return (
|
|
159
|
+
<Button onClick={() => void signIn()} disabled={pending}>
|
|
160
|
+
Continue with Google
|
|
161
|
+
</Button>
|
|
162
|
+
)
|
|
163
|
+
}
|
|
164
|
+
```
|
|
165
|
+
|
|
166
|
+
Redirects to Google (`prompt=select_account`) and back through
|
|
167
|
+
`/auth/callback?next=…` (`callbackPath` overrides it). Repeated clicks while
|
|
168
|
+
pending are ignored; `pending` stays `true` on success because the page navigates
|
|
169
|
+
away. An off-site `next` becomes `/`.
|
|
170
|
+
|
|
171
|
+
## `/local`
|
|
172
|
+
|
|
173
|
+
For Node scripts and Playwright only (uses `node:child_process` and `node:fs`).
|
|
174
|
+
`readLocalSupabase()` runs `pnpm exec supabase status -o json` in the directory
|
|
175
|
+
holding `supabase/config.toml`, found by walking up from `cwd` (and probing
|
|
176
|
+
`apps/web` at each level, configurable with `subdirs`).
|
|
177
|
+
|
|
178
|
+
```ts
|
|
179
|
+
// scripts/local-env.ts
|
|
180
|
+
import {
|
|
181
|
+
findSupabaseAppDir,
|
|
182
|
+
readLocalSupabase,
|
|
183
|
+
withRole,
|
|
184
|
+
writeEnvLocal,
|
|
185
|
+
} from '@cbrl/supabase/local'
|
|
186
|
+
|
|
187
|
+
const local = readLocalSupabase()
|
|
188
|
+
const target = writeEnvLocal(
|
|
189
|
+
{
|
|
190
|
+
NEXT_PUBLIC_SUPABASE_URL: local.apiUrl,
|
|
191
|
+
NEXT_PUBLIC_SUPABASE_PUBLISHABLE_KEY: local.publishableKey,
|
|
192
|
+
SUPABASE_SECRET_KEY: local.secretKey,
|
|
193
|
+
DATABASE_URL: withRole(local.dbUrl, 'app_runtime', 'local_only_password'),
|
|
194
|
+
},
|
|
195
|
+
{ appDir: findSupabaseAppDir() },
|
|
196
|
+
)
|
|
197
|
+
console.log(`Local Supabase values written to ${target}`)
|
|
198
|
+
```
|
|
199
|
+
|
|
200
|
+
`writeEnvLocal` creates `.env.local` from `.env.example` when missing (or starts
|
|
201
|
+
empty), replaces every line for the given keys, appends the rest and sets mode
|
|
202
|
+
`0o600`.
|
|
203
|
+
|
|
204
|
+
```ts
|
|
205
|
+
// playwright.config.ts
|
|
206
|
+
import { defineConfig } from '@playwright/test'
|
|
207
|
+
import { readLocalSupabase } from '@cbrl/supabase/local'
|
|
208
|
+
|
|
209
|
+
const local = readLocalSupabase()
|
|
210
|
+
const supabaseEnv = {
|
|
211
|
+
NEXT_PUBLIC_SUPABASE_URL: local.apiUrl,
|
|
212
|
+
NEXT_PUBLIC_SUPABASE_PUBLISHABLE_KEY: local.publishableKey,
|
|
213
|
+
SUPABASE_SECRET_KEY: local.secretKey,
|
|
214
|
+
DATABASE_URL: local.dbUrl,
|
|
215
|
+
}
|
|
216
|
+
Object.assign(process.env, supabaseEnv)
|
|
217
|
+
|
|
218
|
+
export default defineConfig({
|
|
219
|
+
webServer: {
|
|
220
|
+
command: 'pnpm run build && pnpm run start -p 3000',
|
|
221
|
+
url: 'http://localhost:3000',
|
|
222
|
+
env: { ...supabaseEnv, ENABLE_TEST_AUTH: 'true' },
|
|
223
|
+
},
|
|
224
|
+
})
|
|
225
|
+
```
|
|
@@ -0,0 +1,7 @@
|
|
|
1
|
+
import { SupabaseClient } from "@supabase/supabase-js";
|
|
2
|
+
/**
|
|
3
|
+
* Browser Supabase client (Auth, Storage, …). `createBrowserClient` keeps a
|
|
4
|
+
* singleton, so calling this per render is cheap. `null` when Supabase is not
|
|
5
|
+
* configured.
|
|
6
|
+
*/
|
|
7
|
+
export declare function getSupabaseBrowserClient(): SupabaseClient | null;
|
package/dist/client.mjs
ADDED
|
@@ -0,0 +1,13 @@
|
|
|
1
|
+
import { n as supabasePublicConfig } from "./config-Dkh2tZlv.mjs";
|
|
2
|
+
import { createBrowserClient } from "@supabase/ssr";
|
|
3
|
+
// src/client.ts
|
|
4
|
+
/**
|
|
5
|
+
* Browser Supabase client (Auth, Storage, …). `createBrowserClient` keeps a
|
|
6
|
+
* singleton, so calling this per render is cheap. `null` when Supabase is not
|
|
7
|
+
* configured.
|
|
8
|
+
*/
|
|
9
|
+
function getSupabaseBrowserClient() {
|
|
10
|
+
const config = supabasePublicConfig();
|
|
11
|
+
return config ? createBrowserClient(config.url, config.key) : null;
|
|
12
|
+
}
|
|
13
|
+
export { getSupabaseBrowserClient };
|
|
@@ -0,0 +1,22 @@
|
|
|
1
|
+
// src/config.ts
|
|
2
|
+
/**
|
|
3
|
+
* Public Supabase config read from `NEXT_PUBLIC_SUPABASE_URL` and
|
|
4
|
+
* `NEXT_PUBLIC_SUPABASE_PUBLISHABLE_KEY`, or `null` when either is missing so
|
|
5
|
+
* callers can render a signed-out / degraded UI instead of crashing.
|
|
6
|
+
*
|
|
7
|
+
* Both variables are read as literal `process.env.NEXT_PUBLIC_*` member
|
|
8
|
+
* expressions, which lets Next.js inline them into the browser bundle.
|
|
9
|
+
*/
|
|
10
|
+
function supabasePublicConfig() {
|
|
11
|
+
const url = process.env.NEXT_PUBLIC_SUPABASE_URL;
|
|
12
|
+
const key = process.env.NEXT_PUBLIC_SUPABASE_PUBLISHABLE_KEY;
|
|
13
|
+
return url && key ? {
|
|
14
|
+
url,
|
|
15
|
+
key
|
|
16
|
+
} : null;
|
|
17
|
+
}
|
|
18
|
+
/** Whether both public Supabase variables are set. */
|
|
19
|
+
function isSupabaseConfigured() {
|
|
20
|
+
return supabasePublicConfig() !== null;
|
|
21
|
+
}
|
|
22
|
+
export { supabasePublicConfig as n, isSupabaseConfigured as t };
|
package/dist/index.d.mts
ADDED
|
@@ -0,0 +1,45 @@
|
|
|
1
|
+
import { JwtPayload, User } from "@supabase/supabase-js";
|
|
2
|
+
/** Project URL and publishable key of the Supabase project the app talks to. */
|
|
3
|
+
type SupabasePublicConfig = {
|
|
4
|
+
url: string;
|
|
5
|
+
key: string;
|
|
6
|
+
};
|
|
7
|
+
/**
|
|
8
|
+
* Public Supabase config read from `NEXT_PUBLIC_SUPABASE_URL` and
|
|
9
|
+
* `NEXT_PUBLIC_SUPABASE_PUBLISHABLE_KEY`, or `null` when either is missing so
|
|
10
|
+
* callers can render a signed-out / degraded UI instead of crashing.
|
|
11
|
+
*
|
|
12
|
+
* Both variables are read as literal `process.env.NEXT_PUBLIC_*` member
|
|
13
|
+
* expressions, which lets Next.js inline them into the browser bundle.
|
|
14
|
+
*/
|
|
15
|
+
export declare function supabasePublicConfig(): SupabasePublicConfig | null;
|
|
16
|
+
/** Whether both public Supabase variables are set. */
|
|
17
|
+
export declare function isSupabaseConfigured(): boolean;
|
|
18
|
+
/** The signed-in user, normalised from a Supabase user or verified JWT claims. */
|
|
19
|
+
type SessionUser = {
|
|
20
|
+
/** Supabase Auth user id (`auth.users.id`, the JWT `sub`). */
|
|
21
|
+
id: string;
|
|
22
|
+
email: string | null;
|
|
23
|
+
/** `full_name`, falling back to `name`, from the identity metadata. */
|
|
24
|
+
name: string | null;
|
|
25
|
+
/** `avatar_url`, falling back to `picture`, from the identity metadata. */
|
|
26
|
+
avatarUrl: string | null;
|
|
27
|
+
/** `true` only when the identity provider reported `email_verified: true`. */
|
|
28
|
+
emailVerified: boolean;
|
|
29
|
+
/** Server-controlled `app_metadata`, for app-specific claims. */
|
|
30
|
+
appMetadata: Record<string, unknown>;
|
|
31
|
+
};
|
|
32
|
+
/** The fields of a Supabase `User` that {@link sessionUserFromAuthUser} reads. */
|
|
33
|
+
type AuthUserFields = Pick<User, 'id' | 'email' | 'app_metadata' | 'user_metadata'>;
|
|
34
|
+
/**
|
|
35
|
+
* Maps a Supabase `User` (from `exchangeCodeForSession`, `signInWithPassword`,
|
|
36
|
+
* `onAuthStateChange`, …) to a {@link SessionUser}.
|
|
37
|
+
*/
|
|
38
|
+
export declare function sessionUserFromAuthUser(user: AuthUserFields): SessionUser;
|
|
39
|
+
/**
|
|
40
|
+
* Maps verified JWT claims (`supabase.auth.getClaims()`) to a
|
|
41
|
+
* {@link SessionUser}, so server code can read the user without a network
|
|
42
|
+
* round trip to the Auth server.
|
|
43
|
+
*/
|
|
44
|
+
export declare function sessionUserFromClaims(claims: JwtPayload): SessionUser;
|
|
45
|
+
export type { AuthUserFields, SessionUser, SupabasePublicConfig };
|
package/dist/index.mjs
ADDED
|
@@ -0,0 +1,42 @@
|
|
|
1
|
+
import { n as supabasePublicConfig, t as isSupabaseConfigured } from "./config-Dkh2tZlv.mjs";
|
|
2
|
+
// src/session-user.ts
|
|
3
|
+
function isRecord(value) {
|
|
4
|
+
return typeof value === "object" && value !== null && !Array.isArray(value);
|
|
5
|
+
}
|
|
6
|
+
function asMetadata(value) {
|
|
7
|
+
return isRecord(value) ? value : {};
|
|
8
|
+
}
|
|
9
|
+
function text(metadata, ...keys) {
|
|
10
|
+
for (const key of keys) {
|
|
11
|
+
const value = metadata[key];
|
|
12
|
+
if (typeof value === "string" && value.length > 0) return value;
|
|
13
|
+
}
|
|
14
|
+
return null;
|
|
15
|
+
}
|
|
16
|
+
function build(id, email, appMetadata, userMetadata) {
|
|
17
|
+
const identity = asMetadata(userMetadata);
|
|
18
|
+
return {
|
|
19
|
+
id,
|
|
20
|
+
email: typeof email === "string" && email.length > 0 ? email : null,
|
|
21
|
+
name: text(identity, "full_name", "name"),
|
|
22
|
+
avatarUrl: text(identity, "avatar_url", "picture"),
|
|
23
|
+
emailVerified: identity.email_verified === true,
|
|
24
|
+
appMetadata: asMetadata(appMetadata)
|
|
25
|
+
};
|
|
26
|
+
}
|
|
27
|
+
/**
|
|
28
|
+
* Maps a Supabase `User` (from `exchangeCodeForSession`, `signInWithPassword`,
|
|
29
|
+
* `onAuthStateChange`, …) to a {@link SessionUser}.
|
|
30
|
+
*/
|
|
31
|
+
function sessionUserFromAuthUser(user) {
|
|
32
|
+
return build(user.id, user.email, user.app_metadata, user.user_metadata);
|
|
33
|
+
}
|
|
34
|
+
/**
|
|
35
|
+
* Maps verified JWT claims (`supabase.auth.getClaims()`) to a
|
|
36
|
+
* {@link SessionUser}, so server code can read the user without a network
|
|
37
|
+
* round trip to the Auth server.
|
|
38
|
+
*/
|
|
39
|
+
function sessionUserFromClaims(claims) {
|
|
40
|
+
return build(claims.sub, claims.email, claims.app_metadata, claims.user_metadata);
|
|
41
|
+
}
|
|
42
|
+
export { isSupabaseConfigured, sessionUserFromAuthUser, sessionUserFromClaims, supabasePublicConfig };
|
package/dist/local.d.mts
ADDED
|
@@ -0,0 +1,49 @@
|
|
|
1
|
+
/** URLs and keys of the local Supabase stack, from `supabase status`. */
|
|
2
|
+
export type LocalSupabase = {
|
|
3
|
+
apiUrl: string;
|
|
4
|
+
publishableKey: string;
|
|
5
|
+
secretKey: string;
|
|
6
|
+
/** Postgres URL as the `postgres` owner role. */
|
|
7
|
+
dbUrl: string;
|
|
8
|
+
};
|
|
9
|
+
/** Options for {@link findSupabaseAppDir}. */
|
|
10
|
+
export type FindSupabaseAppDirOptions = {
|
|
11
|
+
/**
|
|
12
|
+
* Subdirectories also probed at each level, so the search works from a
|
|
13
|
+
* monorepo root. Defaults to `['apps/web']`.
|
|
14
|
+
*/
|
|
15
|
+
subdirs?: readonly string[];
|
|
16
|
+
};
|
|
17
|
+
/**
|
|
18
|
+
* The directory holding `supabase/config.toml`, found by walking up from `cwd`
|
|
19
|
+
* (and probing `subdirs` at each level). Throws when none is found.
|
|
20
|
+
*/
|
|
21
|
+
export declare function findSupabaseAppDir(cwd?: string, options?: FindSupabaseAppDirOptions): string;
|
|
22
|
+
/** Options for {@link readLocalSupabase}. */
|
|
23
|
+
export type ReadLocalSupabaseOptions = {
|
|
24
|
+
/** Where to start looking for the app directory. Defaults to `process.cwd()`. */
|
|
25
|
+
cwd?: string;
|
|
26
|
+
};
|
|
27
|
+
/**
|
|
28
|
+
* URL, keys and database URL of the LOCAL Supabase stack, read from
|
|
29
|
+
* `pnpm exec supabase status -o json` in the app directory so nothing is
|
|
30
|
+
* hard-coded. For Node scripts and Playwright configs only.
|
|
31
|
+
*/
|
|
32
|
+
export declare function readLocalSupabase(options?: ReadLocalSupabaseOptions): LocalSupabase;
|
|
33
|
+
/** `dbUrl` with its credentials swapped for `user` / `password` (e.g. a non-owner runtime role). */
|
|
34
|
+
export declare function withRole(dbUrl: string, user: string, password: string): string;
|
|
35
|
+
/** Options for {@link writeEnvLocal}. */
|
|
36
|
+
export type WriteEnvLocalOptions = {
|
|
37
|
+
/** Directory holding the env files. */
|
|
38
|
+
appDir: string;
|
|
39
|
+
/** Target file name. Defaults to `.env.local`. */
|
|
40
|
+
file?: string;
|
|
41
|
+
/** Template copied when the target does not exist yet. Defaults to `.env.example`. */
|
|
42
|
+
template?: string;
|
|
43
|
+
};
|
|
44
|
+
/**
|
|
45
|
+
* Upserts `KEY=value` lines into `.env.local` (created from `.env.example` when
|
|
46
|
+
* missing), leaving every other line untouched, and restricts the file to its
|
|
47
|
+
* owner (mode `0o600`). Returns the path written.
|
|
48
|
+
*/
|
|
49
|
+
export declare function writeEnvLocal(values: Readonly<Record<string, string>>, options: WriteEnvLocalOptions): string;
|
package/dist/local.mjs
ADDED
|
@@ -0,0 +1,89 @@
|
|
|
1
|
+
import { execFileSync } from "node:child_process";
|
|
2
|
+
import { chmodSync, existsSync, readFileSync, writeFileSync } from "node:fs";
|
|
3
|
+
import path from "node:path";
|
|
4
|
+
// src/local.ts
|
|
5
|
+
const ENV_KEY = /^\s*([A-Za-z_][A-Za-z0-9_]*)\s*=/;
|
|
6
|
+
const CONFIG_FILE = path.join("supabase", "config.toml");
|
|
7
|
+
/**
|
|
8
|
+
* The directory holding `supabase/config.toml`, found by walking up from `cwd`
|
|
9
|
+
* (and probing `subdirs` at each level). Throws when none is found.
|
|
10
|
+
*/
|
|
11
|
+
function findSupabaseAppDir(cwd = process.cwd(), options = {}) {
|
|
12
|
+
const { subdirs = ["apps/web"] } = options;
|
|
13
|
+
for (let dir = path.resolve(cwd);; dir = path.dirname(dir)) {
|
|
14
|
+
for (const candidate of [dir, ...subdirs.map((subdir) => path.join(dir, subdir))]) if (existsSync(path.join(candidate, CONFIG_FILE))) return candidate;
|
|
15
|
+
if (path.dirname(dir) === dir) throw new Error(`${CONFIG_FILE} not found above ${cwd}`);
|
|
16
|
+
}
|
|
17
|
+
}
|
|
18
|
+
function field(status, key) {
|
|
19
|
+
const value = status[key];
|
|
20
|
+
if (typeof value !== "string" || value.length === 0) throw new Error(`supabase status: missing ${key}. Is the local stack running?`);
|
|
21
|
+
return value;
|
|
22
|
+
}
|
|
23
|
+
/**
|
|
24
|
+
* URL, keys and database URL of the LOCAL Supabase stack, read from
|
|
25
|
+
* `pnpm exec supabase status -o json` in the app directory so nothing is
|
|
26
|
+
* hard-coded. For Node scripts and Playwright configs only.
|
|
27
|
+
*/
|
|
28
|
+
function readLocalSupabase(options = {}) {
|
|
29
|
+
const raw = execFileSync("pnpm", [
|
|
30
|
+
"exec",
|
|
31
|
+
"supabase",
|
|
32
|
+
"status",
|
|
33
|
+
"-o",
|
|
34
|
+
"json",
|
|
35
|
+
"--workdir",
|
|
36
|
+
"."
|
|
37
|
+
], {
|
|
38
|
+
cwd: findSupabaseAppDir(options.cwd),
|
|
39
|
+
encoding: "utf8",
|
|
40
|
+
stdio: [
|
|
41
|
+
"ignore",
|
|
42
|
+
"pipe",
|
|
43
|
+
"ignore"
|
|
44
|
+
]
|
|
45
|
+
});
|
|
46
|
+
const status = JSON.parse(raw);
|
|
47
|
+
if (typeof status !== "object" || status === null) throw new Error("supabase status: unexpected output");
|
|
48
|
+
const record = Object.fromEntries(Object.entries(status));
|
|
49
|
+
return {
|
|
50
|
+
apiUrl: field(record, "API_URL"),
|
|
51
|
+
publishableKey: field(record, "PUBLISHABLE_KEY"),
|
|
52
|
+
secretKey: field(record, "SECRET_KEY"),
|
|
53
|
+
dbUrl: field(record, "DB_URL")
|
|
54
|
+
};
|
|
55
|
+
}
|
|
56
|
+
/** `dbUrl` with its credentials swapped for `user` / `password` (e.g. a non-owner runtime role). */
|
|
57
|
+
function withRole(dbUrl, user, password) {
|
|
58
|
+
const url = new URL(dbUrl);
|
|
59
|
+
url.username = encodeURIComponent(user);
|
|
60
|
+
url.password = encodeURIComponent(password);
|
|
61
|
+
return url.toString();
|
|
62
|
+
}
|
|
63
|
+
/**
|
|
64
|
+
* Upserts `KEY=value` lines into `.env.local` (created from `.env.example` when
|
|
65
|
+
* missing), leaving every other line untouched, and restricts the file to its
|
|
66
|
+
* owner (mode `0o600`). Returns the path written.
|
|
67
|
+
*/
|
|
68
|
+
function writeEnvLocal(values, options) {
|
|
69
|
+
const { appDir, file = ".env.local", template = ".env.example" } = options;
|
|
70
|
+
const target = path.join(appDir, file);
|
|
71
|
+
const templatePath = path.join(appDir, template);
|
|
72
|
+
const source = existsSync(target) ? target : templatePath;
|
|
73
|
+
const content = existsSync(source) ? readFileSync(source, "utf8") : "";
|
|
74
|
+
const updates = new Map(Object.entries(values));
|
|
75
|
+
const seen = /* @__PURE__ */ new Set();
|
|
76
|
+
const lines = content.split("\n").map((line) => {
|
|
77
|
+
const key = ENV_KEY.exec(line)?.[1];
|
|
78
|
+
const value = key === void 0 ? void 0 : updates.get(key);
|
|
79
|
+
if (key === void 0 || value === void 0) return line;
|
|
80
|
+
seen.add(key);
|
|
81
|
+
return `${key}=${value}`;
|
|
82
|
+
});
|
|
83
|
+
if (lines.at(-1) === "") lines.pop();
|
|
84
|
+
for (const [key, value] of updates) if (!seen.has(key)) lines.push(`${key}=${value}`);
|
|
85
|
+
writeFileSync(target, `${lines.join("\n")}\n`, { mode: 384 });
|
|
86
|
+
chmodSync(target, 384);
|
|
87
|
+
return target;
|
|
88
|
+
}
|
|
89
|
+
export { findSupabaseAppDir, readLocalSupabase, withRole, writeEnvLocal };
|
package/dist/proxy.d.mts
ADDED
|
@@ -0,0 +1,23 @@
|
|
|
1
|
+
import { NextRequest, NextResponse } from "next/server";
|
|
2
|
+
/** Default upper bound for the session refresh before the request goes through anyway. */
|
|
3
|
+
export declare const SESSION_REFRESH_TIMEOUT_MS = 4000;
|
|
4
|
+
/** Options for {@link updateSession}. */
|
|
5
|
+
export type UpdateSessionOptions = {
|
|
6
|
+
/**
|
|
7
|
+
* Headers to forward to the app instead of the incoming ones, e.g. a copy of
|
|
8
|
+
* `request.headers` with extra entries. Refreshed auth cookies are written
|
|
9
|
+
* into it before forwarding.
|
|
10
|
+
*/
|
|
11
|
+
requestHeaders?: Headers;
|
|
12
|
+
/** Called when the refresh throws or times out; the request still goes through. */
|
|
13
|
+
onError?: (error: unknown) => void;
|
|
14
|
+
/** Refresh timeout in milliseconds. Defaults to {@link SESSION_REFRESH_TIMEOUT_MS}. */
|
|
15
|
+
timeoutMs?: number;
|
|
16
|
+
};
|
|
17
|
+
/**
|
|
18
|
+
* Refreshes the Supabase session cookie in `proxy.ts`, so Server Components see
|
|
19
|
+
* a valid token. Follows the `@supabase/ssr` contract: refreshed cookies go to
|
|
20
|
+
* both the forwarded request and the response, along with the cache headers the
|
|
21
|
+
* library asks for. A Supabase outage only skips the refresh.
|
|
22
|
+
*/
|
|
23
|
+
export declare function updateSession(request: NextRequest, options?: UpdateSessionOptions): Promise<NextResponse>;
|
package/dist/proxy.mjs
ADDED
|
@@ -0,0 +1,53 @@
|
|
|
1
|
+
import { n as supabasePublicConfig } from "./config-Dkh2tZlv.mjs";
|
|
2
|
+
import { createServerClient } from "@supabase/ssr";
|
|
3
|
+
import { NextResponse } from "next/server";
|
|
4
|
+
// src/proxy.ts
|
|
5
|
+
/** Default upper bound for the session refresh before the request goes through anyway. */
|
|
6
|
+
const SESSION_REFRESH_TIMEOUT_MS = 4e3;
|
|
7
|
+
async function withTimeout(promise, timeoutMs) {
|
|
8
|
+
let timer;
|
|
9
|
+
const timeout = new Promise((_, reject) => {
|
|
10
|
+
timer = setTimeout(() => {
|
|
11
|
+
reject(/* @__PURE__ */ new Error(`session refresh timed out after ${timeoutMs}ms`));
|
|
12
|
+
}, timeoutMs);
|
|
13
|
+
});
|
|
14
|
+
try {
|
|
15
|
+
return await Promise.race([promise, timeout]);
|
|
16
|
+
} finally {
|
|
17
|
+
clearTimeout(timer);
|
|
18
|
+
}
|
|
19
|
+
}
|
|
20
|
+
/**
|
|
21
|
+
* Refreshes the Supabase session cookie in `proxy.ts`, so Server Components see
|
|
22
|
+
* a valid token. Follows the `@supabase/ssr` contract: refreshed cookies go to
|
|
23
|
+
* both the forwarded request and the response, along with the cache headers the
|
|
24
|
+
* library asks for. A Supabase outage only skips the refresh.
|
|
25
|
+
*/
|
|
26
|
+
async function updateSession(request, options = {}) {
|
|
27
|
+
const { requestHeaders, onError, timeoutMs = SESSION_REFRESH_TIMEOUT_MS } = options;
|
|
28
|
+
function forward() {
|
|
29
|
+
if (!requestHeaders) return NextResponse.next({ request });
|
|
30
|
+
const cookie = request.headers.get("cookie");
|
|
31
|
+
if (cookie !== null) requestHeaders.set("cookie", cookie);
|
|
32
|
+
return NextResponse.next({ request: { headers: requestHeaders } });
|
|
33
|
+
}
|
|
34
|
+
let response = forward();
|
|
35
|
+
const config = supabasePublicConfig();
|
|
36
|
+
if (!config) return response;
|
|
37
|
+
const supabase = createServerClient(config.url, config.key, { cookies: {
|
|
38
|
+
getAll: () => request.cookies.getAll(),
|
|
39
|
+
setAll(cookiesToSet, headers) {
|
|
40
|
+
for (const { name, value } of cookiesToSet) request.cookies.set(name, value);
|
|
41
|
+
response = forward();
|
|
42
|
+
for (const { name, value, options: cookieOptions } of cookiesToSet) response.cookies.set(name, value, cookieOptions);
|
|
43
|
+
for (const [key, value] of Object.entries(headers)) response.headers.set(key, value);
|
|
44
|
+
}
|
|
45
|
+
} });
|
|
46
|
+
try {
|
|
47
|
+
await withTimeout(supabase.auth.getClaims(), timeoutMs);
|
|
48
|
+
} catch (error) {
|
|
49
|
+
onError?.(error);
|
|
50
|
+
}
|
|
51
|
+
return response;
|
|
52
|
+
}
|
|
53
|
+
export { SESSION_REFRESH_TIMEOUT_MS, updateSession };
|
package/dist/react.d.mts
ADDED
|
@@ -0,0 +1,24 @@
|
|
|
1
|
+
/** Options for {@link useGoogleSignIn}. */
|
|
2
|
+
export type UseGoogleSignInOptions = {
|
|
3
|
+
/** Same-origin path to land on after sign-in; anything else falls back to `/`. */
|
|
4
|
+
next: string;
|
|
5
|
+
/** Path of the OAuth callback route. Defaults to `/auth/callback`. */
|
|
6
|
+
callbackPath?: string;
|
|
7
|
+
/**
|
|
8
|
+
* Called when sign-in cannot start: Supabase is not configured, or
|
|
9
|
+
* `signInWithOAuth` returned an error.
|
|
10
|
+
*/
|
|
11
|
+
onError?: (error: Error) => void;
|
|
12
|
+
};
|
|
13
|
+
/** State returned by {@link useGoogleSignIn}. */
|
|
14
|
+
export type GoogleSignIn = {
|
|
15
|
+
/** Starts the redirect to Google. Repeated calls while pending are ignored. */
|
|
16
|
+
signIn: () => Promise<void>;
|
|
17
|
+
/** `true` from the first call until an error (on success the page navigates away). */
|
|
18
|
+
pending: boolean;
|
|
19
|
+
};
|
|
20
|
+
/**
|
|
21
|
+
* Google sign-in through Supabase Auth (OAuth + PKCE). Redirects the page to
|
|
22
|
+
* Google with `prompt=select_account`, back through `callbackPath?next=…`.
|
|
23
|
+
*/
|
|
24
|
+
export declare function useGoogleSignIn(options: UseGoogleSignInOptions): GoogleSignIn;
|
package/dist/react.mjs
ADDED
|
@@ -0,0 +1,46 @@
|
|
|
1
|
+
"use client";
|
|
2
|
+
import { getSupabaseBrowserClient } from "./client.mjs";
|
|
3
|
+
import { t as safeNextPath } from "./safe-next-DOPsO5Ar.mjs";
|
|
4
|
+
import { useCallback, useRef, useState } from "react";
|
|
5
|
+
// src/react.ts
|
|
6
|
+
/**
|
|
7
|
+
* Google sign-in through Supabase Auth (OAuth + PKCE). Redirects the page to
|
|
8
|
+
* Google with `prompt=select_account`, back through `callbackPath?next=…`.
|
|
9
|
+
*/
|
|
10
|
+
function useGoogleSignIn(options) {
|
|
11
|
+
const { next, callbackPath = "/auth/callback", onError } = options;
|
|
12
|
+
const [pending, setPending] = useState(false);
|
|
13
|
+
const started = useRef(false);
|
|
14
|
+
return {
|
|
15
|
+
signIn: useCallback(async () => {
|
|
16
|
+
if (started.current) return;
|
|
17
|
+
const supabase = getSupabaseBrowserClient();
|
|
18
|
+
if (!supabase) {
|
|
19
|
+
onError?.(/* @__PURE__ */ new Error("Supabase is not configured"));
|
|
20
|
+
return;
|
|
21
|
+
}
|
|
22
|
+
started.current = true;
|
|
23
|
+
setPending(true);
|
|
24
|
+
const callback = new URL(callbackPath, window.location.origin);
|
|
25
|
+
callback.searchParams.set("next", safeNextPath(next, "/"));
|
|
26
|
+
const { error } = await supabase.auth.signInWithOAuth({
|
|
27
|
+
provider: "google",
|
|
28
|
+
options: {
|
|
29
|
+
redirectTo: callback.toString(),
|
|
30
|
+
queryParams: { prompt: "select_account" }
|
|
31
|
+
}
|
|
32
|
+
});
|
|
33
|
+
if (error) {
|
|
34
|
+
started.current = false;
|
|
35
|
+
setPending(false);
|
|
36
|
+
onError?.(error);
|
|
37
|
+
}
|
|
38
|
+
}, [
|
|
39
|
+
next,
|
|
40
|
+
callbackPath,
|
|
41
|
+
onError
|
|
42
|
+
]),
|
|
43
|
+
pending
|
|
44
|
+
};
|
|
45
|
+
}
|
|
46
|
+
export { useGoogleSignIn };
|
|
@@ -0,0 +1,43 @@
|
|
|
1
|
+
import { NextRequest, NextResponse } from "next/server";
|
|
2
|
+
import { AuthError, SupabaseClient, User } from "@supabase/supabase-js";
|
|
3
|
+
/** A Next.js Route Handler. */
|
|
4
|
+
export type RouteHandler = (request: NextRequest) => Promise<NextResponse>;
|
|
5
|
+
/** Options for {@link authCallbackRoute}. */
|
|
6
|
+
export type AuthCallbackRouteOptions = {
|
|
7
|
+
/** Where to land when `next` is missing or not a same-origin path. */
|
|
8
|
+
defaultNext: string;
|
|
9
|
+
/** Where to land when there is no code, Supabase is not configured or the exchange fails. */
|
|
10
|
+
failurePath: string;
|
|
11
|
+
/**
|
|
12
|
+
* Runs after a successful exchange, before redirecting (e.g. upsert the app's
|
|
13
|
+
* user row). A throw propagates to the route.
|
|
14
|
+
*/
|
|
15
|
+
onSession?: (user: User, supabase: SupabaseClient) => Promise<void> | void;
|
|
16
|
+
/** Called when the code exchange fails. */
|
|
17
|
+
onError?: (error: AuthError) => void;
|
|
18
|
+
};
|
|
19
|
+
/**
|
|
20
|
+
* `GET` handler for the OAuth (PKCE) return leg, mounted at
|
|
21
|
+
* `app/auth/callback/route.ts`: exchanges `?code` for a session cookie and
|
|
22
|
+
* redirects to `?next` (same-origin only) or `defaultNext`.
|
|
23
|
+
*/
|
|
24
|
+
export declare function authCallbackRoute(options: AuthCallbackRouteOptions): RouteHandler;
|
|
25
|
+
/** Options for {@link testSignInRoute}. */
|
|
26
|
+
export type TestSignInRouteOptions = {
|
|
27
|
+
/**
|
|
28
|
+
* Runs after a successful sign-in (e.g. upsert the app's user row). Fields it
|
|
29
|
+
* returns are merged into the JSON response next to `userId`.
|
|
30
|
+
*/
|
|
31
|
+
onSignIn?: (user: User, supabase: SupabaseClient) => Promise<Record<string, unknown> | undefined> | Record<string, unknown> | undefined;
|
|
32
|
+
};
|
|
33
|
+
/**
|
|
34
|
+
* `POST` handler for E2E sign-in with email + password against a local
|
|
35
|
+
* Supabase stack; the server client writes the real session cookies, which a
|
|
36
|
+
* Playwright fixture can save as `storageState`.
|
|
37
|
+
*
|
|
38
|
+
* Responds 404 unless `ENABLE_TEST_AUTH=true`, and always 404 when
|
|
39
|
+
* `VERCEL_ENV=production`. Body: `{ email, password }` (400 otherwise).
|
|
40
|
+
* Responds 503 when Supabase is not configured, 401 on bad credentials and
|
|
41
|
+
* `{ userId, ...extra }` on success.
|
|
42
|
+
*/
|
|
43
|
+
export declare function testSignInRoute(options?: TestSignInRouteOptions): RouteHandler;
|
package/dist/routes.mjs
ADDED
|
@@ -0,0 +1,67 @@
|
|
|
1
|
+
import { t as safeNextPath } from "./safe-next-DOPsO5Ar.mjs";
|
|
2
|
+
import { createSupabaseServerClient } from "./server.mjs";
|
|
3
|
+
import { NextResponse } from "next/server";
|
|
4
|
+
// src/routes.ts
|
|
5
|
+
/**
|
|
6
|
+
* `GET` handler for the OAuth (PKCE) return leg, mounted at
|
|
7
|
+
* `app/auth/callback/route.ts`: exchanges `?code` for a session cookie and
|
|
8
|
+
* redirects to `?next` (same-origin only) or `defaultNext`.
|
|
9
|
+
*/
|
|
10
|
+
function authCallbackRoute(options) {
|
|
11
|
+
const { defaultNext, failurePath, onSession, onError } = options;
|
|
12
|
+
return async function GET(request) {
|
|
13
|
+
const { searchParams, origin } = request.nextUrl;
|
|
14
|
+
const code = searchParams.get("code");
|
|
15
|
+
const next = safeNextPath(searchParams.get("next"), defaultNext);
|
|
16
|
+
const supabase = code ? await createSupabaseServerClient() : null;
|
|
17
|
+
if (supabase && code) {
|
|
18
|
+
const { data, error } = await supabase.auth.exchangeCodeForSession(code);
|
|
19
|
+
if (!error) {
|
|
20
|
+
await onSession?.(data.user, supabase);
|
|
21
|
+
return NextResponse.redirect(new URL(next, origin));
|
|
22
|
+
}
|
|
23
|
+
onError?.(error);
|
|
24
|
+
}
|
|
25
|
+
return NextResponse.redirect(new URL(failurePath, origin));
|
|
26
|
+
};
|
|
27
|
+
}
|
|
28
|
+
function credentials(body) {
|
|
29
|
+
if (typeof body !== "object" || body === null) return null;
|
|
30
|
+
if (!("email" in body) || !("password" in body)) return null;
|
|
31
|
+
const { email, password } = body;
|
|
32
|
+
return typeof email === "string" && typeof password === "string" ? {
|
|
33
|
+
email,
|
|
34
|
+
password
|
|
35
|
+
} : null;
|
|
36
|
+
}
|
|
37
|
+
function testAuthEnabled() {
|
|
38
|
+
return process.env.ENABLE_TEST_AUTH === "true" && process.env.VERCEL_ENV !== "production";
|
|
39
|
+
}
|
|
40
|
+
/**
|
|
41
|
+
* `POST` handler for E2E sign-in with email + password against a local
|
|
42
|
+
* Supabase stack; the server client writes the real session cookies, which a
|
|
43
|
+
* Playwright fixture can save as `storageState`.
|
|
44
|
+
*
|
|
45
|
+
* Responds 404 unless `ENABLE_TEST_AUTH=true`, and always 404 when
|
|
46
|
+
* `VERCEL_ENV=production`. Body: `{ email, password }` (400 otherwise).
|
|
47
|
+
* Responds 503 when Supabase is not configured, 401 on bad credentials and
|
|
48
|
+
* `{ userId, ...extra }` on success.
|
|
49
|
+
*/
|
|
50
|
+
function testSignInRoute(options = {}) {
|
|
51
|
+
const { onSignIn } = options;
|
|
52
|
+
return async function POST(request) {
|
|
53
|
+
if (!testAuthEnabled()) return new NextResponse(null, { status: 404 });
|
|
54
|
+
const body = credentials(await request.json().catch(() => null));
|
|
55
|
+
if (!body) return NextResponse.json({ error: "email and password are required" }, { status: 400 });
|
|
56
|
+
const supabase = await createSupabaseServerClient();
|
|
57
|
+
if (!supabase) return NextResponse.json({ error: "supabase not configured" }, { status: 503 });
|
|
58
|
+
const { data, error } = await supabase.auth.signInWithPassword(body);
|
|
59
|
+
if (error) return NextResponse.json({ error: error.message }, { status: 401 });
|
|
60
|
+
const extra = await onSignIn?.(data.user, supabase);
|
|
61
|
+
return NextResponse.json({
|
|
62
|
+
...extra,
|
|
63
|
+
userId: data.user.id
|
|
64
|
+
});
|
|
65
|
+
};
|
|
66
|
+
}
|
|
67
|
+
export { authCallbackRoute, testSignInRoute };
|
|
@@ -0,0 +1,18 @@
|
|
|
1
|
+
// src/safe-next.ts
|
|
2
|
+
const PROBE_ORIGIN = "http://same-origin.invalid";
|
|
3
|
+
/**
|
|
4
|
+
* Same-origin path (with query and hash) from an untrusted `next` value, or
|
|
5
|
+
* `fallback`. Resolving against a probe origin rejects absolute,
|
|
6
|
+
* protocol-relative and backslash/whitespace tricks the URL parser would turn
|
|
7
|
+
* into another host.
|
|
8
|
+
*/
|
|
9
|
+
function safeNextPath(raw, fallback) {
|
|
10
|
+
if (!raw?.startsWith("/") || raw.startsWith("//") || raw.startsWith("/\\")) return fallback;
|
|
11
|
+
try {
|
|
12
|
+
const url = new URL(raw, PROBE_ORIGIN);
|
|
13
|
+
return url.origin === PROBE_ORIGIN ? `${url.pathname}${url.search}${url.hash}` : fallback;
|
|
14
|
+
} catch {
|
|
15
|
+
return fallback;
|
|
16
|
+
}
|
|
17
|
+
}
|
|
18
|
+
export { safeNextPath as t };
|
|
@@ -0,0 +1,12 @@
|
|
|
1
|
+
import "server-only";
|
|
2
|
+
import { SupabaseClient } from "@supabase/supabase-js";
|
|
3
|
+
/**
|
|
4
|
+
* Server Supabase client bound to the request cookies, for Server Components,
|
|
5
|
+
* Server Actions and Route Handlers. Create one per request. `null` when
|
|
6
|
+
* Supabase is not configured.
|
|
7
|
+
*
|
|
8
|
+
* Cookie writes from a Server Component are dropped (Next.js forbids them
|
|
9
|
+
* there); the proxy's {@link https://supabase.com/docs/guides/auth/server-side/nextjs | session refresh}
|
|
10
|
+
* already wrote the fresh token on the way in.
|
|
11
|
+
*/
|
|
12
|
+
export declare function createSupabaseServerClient(): Promise<SupabaseClient | null>;
|
package/dist/server.mjs
ADDED
|
@@ -0,0 +1,30 @@
|
|
|
1
|
+
import { n as supabasePublicConfig } from "./config-Dkh2tZlv.mjs";
|
|
2
|
+
import { createServerClient } from "@supabase/ssr";
|
|
3
|
+
import "server-only";
|
|
4
|
+
import { cookies } from "next/headers";
|
|
5
|
+
// src/server.ts
|
|
6
|
+
/**
|
|
7
|
+
* Server Supabase client bound to the request cookies, for Server Components,
|
|
8
|
+
* Server Actions and Route Handlers. Create one per request. `null` when
|
|
9
|
+
* Supabase is not configured.
|
|
10
|
+
*
|
|
11
|
+
* Cookie writes from a Server Component are dropped (Next.js forbids them
|
|
12
|
+
* there); the proxy's {@link https://supabase.com/docs/guides/auth/server-side/nextjs | session refresh}
|
|
13
|
+
* already wrote the fresh token on the way in.
|
|
14
|
+
*/
|
|
15
|
+
async function createSupabaseServerClient() {
|
|
16
|
+
const config = supabasePublicConfig();
|
|
17
|
+
if (!config) return null;
|
|
18
|
+
const cookieStore = await cookies();
|
|
19
|
+
return createServerClient(config.url, config.key, { cookies: {
|
|
20
|
+
getAll: () => cookieStore.getAll(),
|
|
21
|
+
setAll(cookiesToSet) {
|
|
22
|
+
try {
|
|
23
|
+
for (const { name, value, options } of cookiesToSet) cookieStore.set(name, value, options);
|
|
24
|
+
} catch {
|
|
25
|
+
return;
|
|
26
|
+
}
|
|
27
|
+
}
|
|
28
|
+
} });
|
|
29
|
+
}
|
|
30
|
+
export { createSupabaseServerClient };
|
package/package.json
CHANGED
|
@@ -1,6 +1,79 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@cbrl/supabase",
|
|
3
|
-
"version": "0.
|
|
4
|
-
"
|
|
5
|
-
"
|
|
3
|
+
"version": "0.1.0",
|
|
4
|
+
"description": "Supabase Auth wiring for Next.js 16: public config, browser/server clients, proxy session refresh, OAuth callback and test sign-in routes, a Google sign-in hook and local-stack helpers.",
|
|
5
|
+
"license": "MIT",
|
|
6
|
+
"author": "Kayron Cabral",
|
|
7
|
+
"homepage": "https://github.com/kaycabral/toolkit/tree/main/packages/supabase#readme",
|
|
8
|
+
"bugs": {
|
|
9
|
+
"url": "https://github.com/kaycabral/toolkit/issues"
|
|
10
|
+
},
|
|
11
|
+
"repository": {
|
|
12
|
+
"type": "git",
|
|
13
|
+
"url": "git+https://github.com/kaycabral/toolkit.git",
|
|
14
|
+
"directory": "packages/supabase"
|
|
15
|
+
},
|
|
16
|
+
"keywords": [
|
|
17
|
+
"supabase",
|
|
18
|
+
"auth",
|
|
19
|
+
"nextjs",
|
|
20
|
+
"ssr",
|
|
21
|
+
"oauth"
|
|
22
|
+
],
|
|
23
|
+
"type": "module",
|
|
24
|
+
"sideEffects": false,
|
|
25
|
+
"exports": {
|
|
26
|
+
".": "./dist/index.mjs",
|
|
27
|
+
"./client": "./dist/client.mjs",
|
|
28
|
+
"./local": "./dist/local.mjs",
|
|
29
|
+
"./proxy": "./dist/proxy.mjs",
|
|
30
|
+
"./react": "./dist/react.mjs",
|
|
31
|
+
"./routes": "./dist/routes.mjs",
|
|
32
|
+
"./server": "./dist/server.mjs",
|
|
33
|
+
"./package.json": "./package.json"
|
|
34
|
+
},
|
|
35
|
+
"files": [
|
|
36
|
+
"dist"
|
|
37
|
+
],
|
|
38
|
+
"dependencies": {
|
|
39
|
+
"server-only": "^0.0.1"
|
|
40
|
+
},
|
|
41
|
+
"peerDependencies": {
|
|
42
|
+
"@supabase/ssr": "^0.12.0",
|
|
43
|
+
"@supabase/supabase-js": "^2.119.0",
|
|
44
|
+
"next": "^16.0.0",
|
|
45
|
+
"react": "^19.0.0"
|
|
46
|
+
},
|
|
47
|
+
"devDependencies": {
|
|
48
|
+
"@arethetypeswrong/cli": "^0.18.5",
|
|
49
|
+
"@supabase/ssr": "^0.12.7",
|
|
50
|
+
"@supabase/supabase-js": "^2.119.1",
|
|
51
|
+
"@testing-library/react": "^16.3.2",
|
|
52
|
+
"@types/node": "^25.6.2",
|
|
53
|
+
"@types/react": "^19.2.14",
|
|
54
|
+
"@types/react-dom": "^19.2.3",
|
|
55
|
+
"@vitest/coverage-v8": "^4.1.6",
|
|
56
|
+
"eslint": "^9.39.4",
|
|
57
|
+
"jsdom": "^29.1.1",
|
|
58
|
+
"next": "^16.4.6",
|
|
59
|
+
"publint": "^0.3.25",
|
|
60
|
+
"react": "^19.2.6",
|
|
61
|
+
"react-dom": "^19.2.6",
|
|
62
|
+
"tsdown": "^0.23.7",
|
|
63
|
+
"typescript": "^5.9.3",
|
|
64
|
+
"vitest": "^4.1.6",
|
|
65
|
+
"@cbrl/eslint-config": "0.2.0",
|
|
66
|
+
"@cbrl/tsconfig": "0.1.0",
|
|
67
|
+
"@cbrl/testing": "0.2.0"
|
|
68
|
+
},
|
|
69
|
+
"publishConfig": {
|
|
70
|
+
"access": "public"
|
|
71
|
+
},
|
|
72
|
+
"scripts": {
|
|
73
|
+
"build": "tsdown",
|
|
74
|
+
"typecheck": "tsc --noEmit",
|
|
75
|
+
"test": "vitest run --coverage",
|
|
76
|
+
"check:package": "node scripts/check-client-directive.mjs && node ../../scripts/check-package.mjs --types",
|
|
77
|
+
"lint": "eslint ."
|
|
78
|
+
}
|
|
6
79
|
}
|