@jskit-ai/auth-provider-supabase-core 0.2.4 → 0.2.6

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.
@@ -0,0 +1,494 @@
1
+ import { AUTH_TEXTS, createAuthError } from "@jskit-ai/auth-core/server/authTexts";
2
+ import { hostOnlyCookieName } from "@jskit-ai/auth-core/server/utils";
3
+ import { isTransientSupabaseError, mapAuthError, mapRecoveryError } from "./authErrorMappers.js";
4
+ import { safeRequestCookies, cookieOptions, cookieClearOptions } from "./authCookies.js";
5
+ import { loadJose, classifyJwtVerifyError } from "./authJwt.js";
6
+ import { authenticateDevAuthRequest, isDevAuthToken } from "./devAuthBootstrap.js";
7
+ import { requireAuthenticatedProfile } from "./authenticatedProfile.js";
8
+
9
+ const ACCESS_TOKEN_COOKIE_NAME = "sb_access_token";
10
+ const REFRESH_TOKEN_COOKIE_NAME = "sb_refresh_token";
11
+ const RECOVERY_ACCESS_TOKEN_COOKIE_NAME = "sb_recovery_access_token";
12
+ const RECOVERY_REFRESH_TOKEN_COOKIE_NAME = "sb_recovery_refresh_token";
13
+ const PERSISTENT_SESSION_COOKIE_MAX_AGE_SECONDS = 60 * 60 * 24 * 400;
14
+
15
+ /**
16
+ * A request's Supabase session: its cookies, verifying its access token,
17
+ * refreshing it, and signing it or the account's other sessions out.
18
+ * @param {object} dependencies
19
+ * @param {import("../types.js").SupabaseConfig} dependencies.config
20
+ * @param {import("../types.js").SupabaseClients} dependencies.clients
21
+ * @param {import("../types.js").SupabaseProfileMirror} dependencies.profileMirror
22
+ * @param {import("../types.js").SupabaseProfiles} dependencies.profiles
23
+ */
24
+ function createSupabaseSessions({ config, clients, profileMirror, profiles }) {
25
+ const { isProduction, jwtAudience, supabaseUrl } = config;
26
+ // Production cookies are Secure, so they are also host-only __Host- cookies.
27
+ const ACCESS_TOKEN_COOKIE = hostOnlyCookieName(ACCESS_TOKEN_COOKIE_NAME, isProduction);
28
+ const REFRESH_TOKEN_COOKIE = hostOnlyCookieName(REFRESH_TOKEN_COOKIE_NAME, isProduction);
29
+ const RECOVERY_ACCESS_TOKEN_COOKIE = hostOnlyCookieName(RECOVERY_ACCESS_TOKEN_COOKIE_NAME, isProduction);
30
+ const RECOVERY_REFRESH_TOKEN_COOKIE = hostOnlyCookieName(RECOVERY_REFRESH_TOKEN_COOKIE_NAME, isProduction);
31
+ const issuerUrl = supabaseUrl ? new URL("/auth/v1", supabaseUrl).toString().replace(/\/$/, "") : "";
32
+ const jwksUrl = issuerUrl ? `${issuerUrl}/.well-known/jwks.json` : "";
33
+
34
+ let jwksResolver = null;
35
+
36
+ async function getJwksResolver() {
37
+ if (jwksResolver) {
38
+ return jwksResolver;
39
+ }
40
+
41
+ const jose = await loadJose();
42
+ jwksResolver = jose.createRemoteJWKSet(new URL(jwksUrl));
43
+ return jwksResolver;
44
+ }
45
+
46
+ async function verifyAccessToken(accessToken) {
47
+ const jose = await loadJose();
48
+ const jwks = await getJwksResolver();
49
+
50
+ try {
51
+ const { payload } = await jose.jwtVerify(accessToken, jwks, {
52
+ issuer: issuerUrl,
53
+ audience: jwtAudience,
54
+ clockTolerance: 5
55
+ });
56
+
57
+ return {
58
+ status: "valid",
59
+ payload
60
+ };
61
+ } catch (error) {
62
+ return {
63
+ status: classifyJwtVerifyError(error)
64
+ };
65
+ }
66
+ }
67
+
68
+ async function verifyAccessTokenViaSupabase(accessToken, profileOptions = {}) {
69
+ const supabase = clients.createSupabaseClient();
70
+
71
+ try {
72
+ const response = await supabase.auth.getUser(accessToken);
73
+ if (response.error) {
74
+ if (isTransientSupabaseError(response.error)) {
75
+ return { status: "transient" };
76
+ }
77
+
78
+ return { status: "invalid" };
79
+ }
80
+
81
+ if (!response.data?.user) {
82
+ return { status: "invalid" };
83
+ }
84
+
85
+ const profile = await profileMirror.syncProfileFromSupabaseUser(response.data.user, response.data.user.email, profileOptions);
86
+ return {
87
+ status: "valid",
88
+ profile
89
+ };
90
+ } catch (error) {
91
+ if (isTransientSupabaseError(error)) {
92
+ return { status: "transient" };
93
+ }
94
+
95
+ return { status: "invalid" };
96
+ }
97
+ }
98
+
99
+ async function setSessionFromRequestCookies(request, options = {}) {
100
+ const cookies = safeRequestCookies(request);
101
+ const accessToken = String(cookies[ACCESS_TOKEN_COOKIE] || "").trim();
102
+ const refreshToken = String(cookies[REFRESH_TOKEN_COOKIE] || "").trim();
103
+
104
+ return setSupabaseSessionFromTokens({ accessToken, refreshToken }, options);
105
+ }
106
+
107
+ async function setRecoverySessionFromRequestCookies(request, options = {}) {
108
+ const cookies = safeRequestCookies(request);
109
+ const accessToken = String(cookies[RECOVERY_ACCESS_TOKEN_COOKIE] || "").trim();
110
+ const refreshToken = String(cookies[RECOVERY_REFRESH_TOKEN_COOKIE] || "").trim();
111
+
112
+ return setSupabaseSessionFromTokens({ accessToken, refreshToken }, options);
113
+ }
114
+
115
+ async function setSupabaseSessionFromTokens({ accessToken, refreshToken }, options = {}) {
116
+ const normalizedAccessToken = String(accessToken || "").trim();
117
+ const normalizedRefreshToken = String(refreshToken || "").trim();
118
+
119
+ if (!normalizedAccessToken || !normalizedRefreshToken) {
120
+ throw createAuthError(AUTH_TEXTS.sessionRequired);
121
+ }
122
+
123
+ const supabase = options.supabaseClient || clients.createSupabaseClient();
124
+ let sessionResponse;
125
+ try {
126
+ sessionResponse = await supabase.auth.setSession({
127
+ access_token: normalizedAccessToken,
128
+ refresh_token: normalizedRefreshToken
129
+ });
130
+ } catch (error) {
131
+ throw mapRecoveryError(error);
132
+ }
133
+
134
+ const session = sessionResponse.data?.session || null;
135
+ const user = sessionResponse.data?.user || null;
136
+
137
+ if (sessionResponse.error || !session || !user) {
138
+ throw mapRecoveryError(sessionResponse.error);
139
+ }
140
+
141
+ return {
142
+ ...sessionResponse,
143
+ data: {
144
+ ...sessionResponse.data,
145
+ session,
146
+ user
147
+ }
148
+ };
149
+ }
150
+
151
+ async function resolveCurrentSupabaseUser(request, options = {}) {
152
+ const supabase = options.supabaseClient || clients.createSupabaseClient();
153
+ const cookies = safeRequestCookies(request);
154
+ const accessToken = String(cookies[ACCESS_TOKEN_COOKIE] || "").trim();
155
+ let user = null;
156
+ let session = null;
157
+
158
+ async function getUserByAccessToken(token) {
159
+ if (!token) {
160
+ return null;
161
+ }
162
+
163
+ try {
164
+ const userResponse = await supabase.auth.getUser(token);
165
+ if (!userResponse.error && userResponse.data?.user) {
166
+ return userResponse.data.user;
167
+ }
168
+
169
+ if (userResponse.error && isTransientSupabaseError(userResponse.error)) {
170
+ throw mapAuthError(userResponse.error, 503);
171
+ }
172
+ } catch (error) {
173
+ if (isTransientSupabaseError(error)) {
174
+ throw mapAuthError(error, 503);
175
+ }
176
+ }
177
+
178
+ return null;
179
+ }
180
+
181
+ if (accessToken) {
182
+ user = await getUserByAccessToken(accessToken);
183
+ }
184
+
185
+ if (!user) {
186
+ const sessionResponse = await setSessionFromRequestCookies(request, {
187
+ supabaseClient: supabase
188
+ });
189
+ user = sessionResponse.data.user || null;
190
+ session = sessionResponse.data.session || null;
191
+ }
192
+
193
+ const currentAccessToken = String(session?.access_token || accessToken || "").trim();
194
+ const explicitUser = await getUserByAccessToken(currentAccessToken);
195
+ if (explicitUser) {
196
+ user = explicitUser;
197
+ }
198
+
199
+ if (!user) {
200
+ throw createAuthError(AUTH_TEXTS.sessionRequired);
201
+ }
202
+
203
+ return {
204
+ session,
205
+ user
206
+ };
207
+ }
208
+
209
+ function resolveRequestSessionTokens(request) {
210
+ const cookies = safeRequestCookies(request);
211
+ return {
212
+ accessToken: String(cookies[ACCESS_TOKEN_COOKIE] || ""),
213
+ refreshToken: String(cookies[REFRESH_TOKEN_COOKIE] || "")
214
+ };
215
+ }
216
+
217
+ async function authenticateDevAuthRequestFromCookies(request, tokens = resolveRequestSessionTokens(request)) {
218
+ const devAuthResult = await authenticateDevAuthRequest(
219
+ {
220
+ request,
221
+ accessToken: tokens.accessToken,
222
+ refreshToken: tokens.refreshToken
223
+ },
224
+ {
225
+ config: config.devAuth,
226
+ userProfilesRepository: profiles.userProfilesRepository
227
+ }
228
+ );
229
+
230
+ if (!devAuthResult || devAuthResult.authenticated !== true) {
231
+ return devAuthResult;
232
+ }
233
+
234
+ return profileMirror.withActor({
235
+ ...devAuthResult,
236
+ profile: requireAuthenticatedProfile(devAuthResult.profile, {
237
+ context: "dev auth profile"
238
+ })
239
+ });
240
+ }
241
+
242
+ function writeSessionCookies(reply, session) {
243
+ const accessToken = String(session?.access_token || "");
244
+ const refreshToken = String(session?.refresh_token || "");
245
+ if (!accessToken || !refreshToken) {
246
+ return;
247
+ }
248
+
249
+ const sessionAccessMaxAge = Number.isFinite(Number(session?.expires_in)) ? Number(session.expires_in) : 3600;
250
+ const purpose = String(session?.purpose || "normal").trim();
251
+ const accessCookieName = purpose === "recovery" ? RECOVERY_ACCESS_TOKEN_COOKIE : ACCESS_TOKEN_COOKIE;
252
+ const refreshCookieName = purpose === "recovery" ? RECOVERY_REFRESH_TOKEN_COOKIE : REFRESH_TOKEN_COOKIE;
253
+ const cookieMaxAge = purpose === "recovery"
254
+ ? Math.floor(sessionAccessMaxAge)
255
+ : Math.max(Math.floor(sessionAccessMaxAge), PERSISTENT_SESSION_COOKIE_MAX_AGE_SECONDS);
256
+
257
+ reply.setCookie(accessCookieName, accessToken, cookieOptions(isProduction, cookieMaxAge));
258
+ reply.setCookie(refreshCookieName, refreshToken, cookieOptions(isProduction, cookieMaxAge));
259
+ }
260
+
261
+ function clearSessionCookies(reply) {
262
+ for (const clearOptions of cookieClearOptions(isProduction)) {
263
+ // A __Host- cookie only exists at Path=/.
264
+ if (clearOptions.path === "/" || !isProduction) {
265
+ reply.clearCookie(ACCESS_TOKEN_COOKIE, clearOptions);
266
+ reply.clearCookie(REFRESH_TOKEN_COOKIE, clearOptions);
267
+ reply.clearCookie(RECOVERY_ACCESS_TOKEN_COOKIE, clearOptions);
268
+ reply.clearCookie(RECOVERY_REFRESH_TOKEN_COOKIE, clearOptions);
269
+ }
270
+ }
271
+ }
272
+
273
+ async function logout(request) {
274
+ const cookies = safeRequestCookies(request);
275
+ const accessToken = String(cookies[ACCESS_TOKEN_COOKIE] || "").trim();
276
+ const refreshToken = String(cookies[REFRESH_TOKEN_COOKIE] || "").trim();
277
+
278
+ if (!accessToken && !refreshToken) {
279
+ return {
280
+ ok: true,
281
+ clearSession: true
282
+ };
283
+ }
284
+
285
+ if (isDevAuthToken(accessToken) || isDevAuthToken(refreshToken)) {
286
+ return {
287
+ ok: true,
288
+ clearSession: true
289
+ };
290
+ }
291
+
292
+ clients.ensureConfigured();
293
+ const supabase = clients.createSupabaseClient();
294
+ await setSessionFromRequestCookies(request, {
295
+ supabaseClient: supabase
296
+ });
297
+
298
+ const response = await supabase.auth.signOut({
299
+ scope: "local"
300
+ });
301
+
302
+ if (response.error) {
303
+ throw mapAuthError(response.error, Number(response.error?.status || 400));
304
+ }
305
+
306
+ return {
307
+ ok: true,
308
+ clearSession: true
309
+ };
310
+ }
311
+
312
+ async function authenticateRequest(request, { syncProfile = true, refreshSession = true } = {}) {
313
+ const { accessToken, refreshToken } = resolveRequestSessionTokens(request);
314
+ // Without sync, a login whose app profile does not exist yet is not signed in.
315
+ const signedIn = (profile, session = null) => (profile
316
+ ? profileMirror.withActor({ authenticated: true, profile, clearSession: false, session, transientFailure: false })
317
+ : { authenticated: false, clearSession: false, session: null, transientFailure: false });
318
+
319
+ const devAuthResult = await authenticateDevAuthRequestFromCookies(request, { accessToken, refreshToken });
320
+ if (devAuthResult) {
321
+ return devAuthResult;
322
+ }
323
+
324
+ if (!accessToken && !refreshToken) {
325
+ return {
326
+ authenticated: false,
327
+ clearSession: false,
328
+ session: null,
329
+ transientFailure: false
330
+ };
331
+ }
332
+
333
+ clients.ensureConfigured();
334
+
335
+ if (accessToken) {
336
+ const verification = await verifyAccessToken(accessToken);
337
+
338
+ if (verification.status === "valid") {
339
+ return signedIn(await profileMirror.syncProfileFromJwtClaims(verification.payload, { syncProfile }));
340
+ }
341
+
342
+ if (verification.status === "transient") {
343
+ return {
344
+ authenticated: false,
345
+ clearSession: false,
346
+ session: null,
347
+ transientFailure: true
348
+ };
349
+ }
350
+
351
+ if (verification.status === "invalid") {
352
+ const supabaseVerification = await verifyAccessTokenViaSupabase(accessToken, { syncProfile });
353
+ if (supabaseVerification.status === "valid") {
354
+ return signedIn(supabaseVerification.profile);
355
+ }
356
+
357
+ if (supabaseVerification.status === "transient") {
358
+ return {
359
+ authenticated: false,
360
+ clearSession: false,
361
+ session: null,
362
+ transientFailure: true
363
+ };
364
+ }
365
+ }
366
+ }
367
+
368
+ if (!refreshToken) {
369
+ return {
370
+ authenticated: false,
371
+ clearSession: true,
372
+ session: null,
373
+ transientFailure: false
374
+ };
375
+ }
376
+
377
+ // A caller that cannot store a refreshed session, such as a realtime socket,
378
+ // must not spend the single-use refresh token; it is told to refresh first.
379
+ if (!refreshSession) {
380
+ return {
381
+ authenticated: false,
382
+ refreshRequired: true,
383
+ clearSession: false,
384
+ session: null,
385
+ transientFailure: false
386
+ };
387
+ }
388
+
389
+ const supabase = clients.createSupabaseClient();
390
+ let refreshResponse;
391
+ try {
392
+ refreshResponse = await supabase.auth.refreshSession({ refresh_token: refreshToken });
393
+ /* c8 ignore next 17 -- defensive: refreshSession usually resolves with { error } for auth/transport issues. */
394
+ } catch (error) {
395
+ if (isTransientSupabaseError(error)) {
396
+ return {
397
+ authenticated: false,
398
+ clearSession: false,
399
+ session: null,
400
+ transientFailure: true
401
+ };
402
+ }
403
+
404
+ return {
405
+ authenticated: false,
406
+ clearSession: true,
407
+ session: null,
408
+ transientFailure: false
409
+ };
410
+ }
411
+
412
+ if (refreshResponse.error) {
413
+ if (isTransientSupabaseError(refreshResponse.error)) {
414
+ return {
415
+ authenticated: false,
416
+ clearSession: false,
417
+ session: null,
418
+ transientFailure: true
419
+ };
420
+ }
421
+
422
+ return {
423
+ authenticated: false,
424
+ clearSession: true,
425
+ session: null,
426
+ transientFailure: false
427
+ };
428
+ }
429
+
430
+ if (!refreshResponse.data?.session || !refreshResponse.data?.user) {
431
+ return {
432
+ authenticated: false,
433
+ clearSession: true,
434
+ session: null,
435
+ transientFailure: false
436
+ };
437
+ }
438
+
439
+ const profile = await profileMirror.syncProfileFromSupabaseUser(refreshResponse.data.user, refreshResponse.data.user.email, { syncProfile });
440
+ return signedIn(profile, refreshResponse.data.session);
441
+ }
442
+
443
+ async function signOutOtherSessions(request) {
444
+ clients.ensureConfigured();
445
+ const supabase = clients.createSupabaseClient();
446
+ await setSessionFromRequestCookies(request, {
447
+ supabaseClient: supabase
448
+ });
449
+ const response = await supabase.auth.signOut({
450
+ scope: "others"
451
+ });
452
+
453
+ if (response.error) {
454
+ throw mapAuthError(response.error, Number(response.error?.status || 400));
455
+ }
456
+
457
+ return {
458
+ ok: true
459
+ };
460
+ }
461
+
462
+ function hasAccessTokenCookie(request) {
463
+ const cookies = safeRequestCookies(request);
464
+ return Boolean(cookies[ACCESS_TOKEN_COOKIE] || cookies[RECOVERY_ACCESS_TOKEN_COOKIE]);
465
+ }
466
+
467
+ function hasSessionCookie(request) {
468
+ const cookies = safeRequestCookies(request);
469
+ return Boolean(
470
+ cookies[ACCESS_TOKEN_COOKIE] ||
471
+ cookies[REFRESH_TOKEN_COOKIE] ||
472
+ cookies[RECOVERY_ACCESS_TOKEN_COOKIE] ||
473
+ cookies[RECOVERY_REFRESH_TOKEN_COOKIE]
474
+ );
475
+ }
476
+
477
+ return Object.freeze({
478
+ // readable-check: allow setter-seam - not a slot: sets the Supabase client's session from the request's cookies
479
+ setSessionFromRequestCookies,
480
+ // readable-check: allow setter-seam - not a slot: sets the Supabase client's recovery session from the request's cookies
481
+ setRecoverySessionFromRequestCookies,
482
+ resolveCurrentSupabaseUser,
483
+ authenticateDevAuthRequestFromCookies,
484
+ authenticateRequest,
485
+ hasAccessTokenCookie,
486
+ hasSessionCookie,
487
+ writeSessionCookies,
488
+ clearSessionCookies,
489
+ logout,
490
+ signOutOtherSessions
491
+ });
492
+ }
493
+
494
+ export { createSupabaseSessions };
@@ -0,0 +1,28 @@
1
+ import { createClient } from "@supabase/supabase-js";
2
+ import { buildSupabaseServerClientOptions } from "./supabaseClientOptions.js";
3
+
4
+ /**
5
+ * New Supabase clients for the app's project. Each operation makes its own,
6
+ * since a client holds the session it signs in with.
7
+ * @param {import("../types.js").SupabaseConfig} config
8
+ */
9
+ function createSupabaseClients(config) {
10
+ /** Refuses the operation when the app names no Supabase project. */
11
+ function ensureConfigured() {
12
+ if (!config.configured) {
13
+ throw new Error("Auth provider is not configured.");
14
+ }
15
+ }
16
+
17
+ function createSupabaseClient() {
18
+ ensureConfigured();
19
+ return createClient(config.supabaseUrl, config.supabasePublishableKey, buildSupabaseServerClientOptions());
20
+ }
21
+
22
+ return Object.freeze({
23
+ ensureConfigured,
24
+ createSupabaseClient
25
+ });
26
+ }
27
+
28
+ export { createSupabaseClients };
@@ -2,84 +2,10 @@ import {
2
2
  attachDeferredAuthService,
3
3
  createDeferredAuthService
4
4
  } from "@jskit-ai/auth-core/server/deferredAuthService";
5
- import { normalizeEmail } from "@jskit-ai/auth-core/server/utils";
6
5
  import { defineProvider } from "@jskit-ai/kernel/shared/capabilities";
7
- import { resolveAllowedOriginsFromSurfaceDefinitions } from "@jskit-ai/kernel/shared/support/returnToPath";
8
- import { createService } from "../lib/service.js";
9
-
10
- const PROFILE_MODES = Object.freeze(["provider", "users"]);
11
-
12
- function normalizeRecord(value) {
13
- return value && typeof value === "object" && !Array.isArray(value) ? value : {};
14
- }
15
-
16
- function splitCsv(value) {
17
- return String(value || "").split(",").map((entry) => entry.trim()).filter(Boolean);
18
- }
19
-
20
- function oauthConfig(config) {
21
- const oauth = normalizeRecord(normalizeRecord(config.auth).oauth);
22
- return {
23
- providers: Array.isArray(oauth.providers)
24
- ? oauth.providers.map((entry) => String(entry || "").trim()).filter(Boolean)
25
- : splitCsv(oauth.providers),
26
- defaultProvider: String(oauth.defaultProvider || "").trim(),
27
- queryParams: normalizeRecord(oauth.queryParams)
28
- };
29
- }
30
-
31
- function providerConfig(env, config) {
32
- const configuredOauth = oauthConfig(config);
33
- const envProviders = splitCsv(env.AUTH_OAUTH_PROVIDERS);
34
- return {
35
- id: "supabase",
36
- supabaseUrl: String(env.AUTH_SUPABASE_URL || env.SUPABASE_URL || "").trim(),
37
- supabasePublishableKey: String(
38
- env.AUTH_SUPABASE_PUBLISHABLE_KEY || env.SUPABASE_PUBLISHABLE_KEY || ""
39
- ).trim(),
40
- jwtAudience: String(env.AUTH_JWT_AUDIENCE || "authenticated").trim(),
41
- oauthProviders: envProviders.length > 0 ? envProviders : configuredOauth.providers,
42
- oauthDefaultProvider: String(env.AUTH_OAUTH_DEFAULT_PROVIDER || "").trim() || configuredOauth.defaultProvider,
43
- oauthProviderQueryParams: configuredOauth.queryParams
44
- };
45
- }
46
-
47
- function profileMode(config) {
48
- const mode = String(normalizeRecord(config.auth).profileMode || "provider").trim().toLowerCase();
49
- if (!PROFILE_MODES.includes(mode)) {
50
- throw new Error(`Unsupported config.auth.profileMode "${mode}". Supported values: ${PROFILE_MODES.join(", ")}.`);
51
- }
52
- return mode;
53
- }
54
-
55
- function createProviderProfileProjector() {
56
- return Object.freeze({
57
- async findByIdentity() { return null; },
58
- async syncIdentityProfile(profileLike) {
59
- const profile = normalizeRecord(profileLike);
60
- const authProviderUserSid = String(profile.authProviderUserSid || "").trim();
61
- const email = normalizeEmail(profile.email || "");
62
- if (!authProviderUserSid || !email) {
63
- throw new TypeError("Provider identity profile requires authProviderUserSid and email.");
64
- }
65
- return {
66
- id: authProviderUserSid,
67
- authProvider: String(profile.authProvider || "supabase").trim() || "supabase",
68
- authProviderUserSid,
69
- email,
70
- displayName: String(profile.displayName || email.split("@")[0] || "User").trim(),
71
- profileSource: "auth-provider"
72
- };
73
- }
74
- });
75
- }
76
-
77
- function assertSelectedProvider(env) {
78
- const selected = String(env.AUTH_PROVIDER || "").trim().toLowerCase();
79
- if (selected && selected !== "supabase") {
80
- throw new Error(`AUTH_PROVIDER is "${selected}", but the installed auth provider is Supabase.`);
81
- }
82
- }
6
+ import { assertSelectedProvider, resolveSupabaseConfig } from "../lib/config.js";
7
+ import { PROVIDER_MODE_PROFILES, createUsersModeProfiles } from "../lib/profileModes.js";
8
+ import { createSupabaseAuthService } from "../lib/service.js";
83
9
 
84
10
  const AuthSupabaseProvider = defineProvider({
85
11
  id: "auth.supabase",
@@ -94,34 +20,29 @@ const AuthSupabaseProvider = defineProvider({
94
20
  provides: {
95
21
  authService: "auth.service"
96
22
  },
23
+ /**
24
+ * @param {object} dependencies
25
+ * @param {import("@jskit-ai/kernel/server/types").RuntimeEnv} dependencies.env
26
+ */
97
27
  setup({ env }) {
98
28
  assertSelectedProvider(env);
99
29
  return { authService: createDeferredAuthService() };
100
30
  },
31
+ /**
32
+ * @param {object} dependencies
33
+ * @param {import("@jskit-ai/kernel/server/types").RuntimeConfig} dependencies.config
34
+ * @param {import("@jskit-ai/kernel/server/types").RuntimeEnv} dependencies.env
35
+ * @param {import("@jskit-ai/auth-core/server/types").AuthExtensions} dependencies.extensions
36
+ * @param {import("@jskit-ai/users-core/server/types").UsersIdentity | null} dependencies.identity The users' records, when users-core is installed.
37
+ */
101
38
  boot({ config, env, extensions, identity }, { outputs }) {
102
- assertSelectedProvider(env);
103
- const mode = profileMode(config);
104
- if (mode === "users" && !identity) {
39
+ const supabaseConfig = resolveSupabaseConfig({ config, env });
40
+ if (supabaseConfig.profileMode === "users" && !identity) {
105
41
  throw new Error('Supabase auth profileMode "users" requires the users.identity capability.');
106
42
  }
107
- const projector = mode === "users" ? identity.profileProjector : createProviderProfileProjector();
108
- const appPublicUrl = String(env.APP_PUBLIC_URL || "").trim();
109
- const baseService = createService({
110
- authProvider: providerConfig(env, config),
111
- appPublicUrl,
112
- authAllowedReturnToOrigins: resolveAllowedOriginsFromSurfaceDefinitions(config.surfaceDefinitions || {}, {
113
- seedOrigins: [appPublicUrl]
114
- }),
115
- nodeEnv: String(env.NODE_ENV || "development").trim() || "development",
116
- userSettingsRepository: mode === "users" ? identity.repositories.userSettings : null,
117
- userProfilesRepository: mode === "users" ? identity.repositories.userProfiles : null,
118
- userProfileSyncService: projector,
119
- profileProjectionEnabled: mode === "users",
120
- devAuthBypassEnabled: env.AUTH_DEV_BYPASS_ENABLED,
121
- devAuthBypassSecret: String(env.AUTH_DEV_BYPASS_SECRET || "").trim(),
122
- devAuthAccessTtlSeconds: env.AUTH_DEV_ACCESS_TTL_SECONDS,
123
- devAuthRefreshTtlSeconds: env.AUTH_DEV_REFRESH_TTL_SECONDS
124
- });
43
+ const profiles = supabaseConfig.profileMode === "users" ? createUsersModeProfiles(identity) : PROVIDER_MODE_PROFILES;
44
+ const baseService = createSupabaseAuthService({ config: supabaseConfig, profiles });
45
+ // readable-check: allow setter-seam - deferred until boot: auth.service is built after every setup has registered its auth extensions, and those setups already receive it
125
46
  attachDeferredAuthService(outputs.authService, extensions.decorateService(baseService));
126
47
  }
127
48
  });
@@ -0,0 +1,21 @@
1
+ // Supabase auth's own types, named once for the modules that share them.
2
+
3
+ /** @typedef {ReturnType<typeof import("./lib/config.js").resolveSupabaseConfig>} SupabaseConfig Supabase auth's settings, read once from the app's config and Env. */
4
+ /** @typedef {ReturnType<typeof import("./lib/supabaseClients.js").createSupabaseClients>} SupabaseClients New Supabase clients for the app's project. */
5
+ /** @typedef {ReturnType<typeof import("./lib/profileMirror.js").createSupabaseProfileMirror>} SupabaseProfileMirror The app profile and actor of each Supabase user. */
6
+ /** @typedef {ReturnType<typeof import("./lib/sessions.js").createSupabaseSessions>} SupabaseSessions A request's Supabase session. */
7
+ /** @typedef {ReturnType<typeof import("./lib/securityStatus.js").createSupabaseSecurityStatus>} SupabaseSecurityStatus The sign-in methods of the signed-in account. */
8
+
9
+ /** @typedef {Pick<import("@jskit-ai/users-core/server/types").UserProfilesRepository, "findById" | "findByEmail">} SupabaseUserProfiles The app users dev auth signs in as. */
10
+ /** @typedef {Pick<import("@jskit-ai/users-core/server/types").UserSettingsRepository, "ensureForUserId" | "updatePasswordSignInEnabled" | "updatePasswordSetupRequired">} SupabaseUserSettings Whether each user may sign in with a password. */
11
+
12
+ /**
13
+ * Where each Supabase user's app profile lives, by config.auth.profileMode.
14
+ * @typedef {object} SupabaseProfiles
15
+ * @property {import("@jskit-ai/auth-core/server/types").AuthProfileProjector} projector
16
+ * Makes or finds the app profile of a Supabase user.
17
+ * @property {SupabaseUserProfiles} userProfilesRepository
18
+ * @property {SupabaseUserSettings} userSettingsRepository
19
+ */
20
+
21
+ export {};