@jskit-ai/auth-provider-supabase-core 0.2.5 → 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.
@@ -1,12 +1,9 @@
1
1
  import { AppError } from "@jskit-ai/kernel/server/runtime/errors";
2
2
  import { normalizeRecordId } from "@jskit-ai/kernel/shared/support/normalize";
3
- import {
4
- assertDevAuthPolicy,
5
- ensureDevAuthRuntimeAvailable,
6
- resolveDevAuthPolicy
7
- } from "@jskit-ai/auth-core/server/devAuth";
3
+ import { ensureDevAuthRuntimeAvailable, resolveDevAuthPolicyFromEnv } from "@jskit-ai/auth-core/server/devAuth";
8
4
  import { normalizeEmail } from "@jskit-ai/auth-core/server/utils";
9
5
  import { AUTH_TEXTS, authFieldError } from "@jskit-ai/auth-core/server/authTexts";
6
+ import { validationError } from "./authErrorMappers.js";
10
7
  import { loadJose, isExpiredJwtError } from "./authJwt.js";
11
8
 
12
9
  const DEV_AUTH_TOKEN_PREFIX = "jskit-dev.";
@@ -31,43 +28,21 @@ function stripDevAuthTokenPrefix(token) {
31
28
  return String(token || "").trim().slice(DEV_AUTH_TOKEN_PREFIX.length);
32
29
  }
33
30
 
34
- function resolveDevAuthConfig({
35
- enabled = false,
36
- secret = "",
37
- nodeEnv = "development",
38
- jwtAudience = "authenticated",
39
- accessTtlSeconds = DEFAULT_DEV_AUTH_ACCESS_TTL_SECONDS,
40
- refreshTtlSeconds = DEFAULT_DEV_AUTH_REFRESH_TTL_SECONDS
41
- } = {}) {
42
- const policy = resolveDevAuthPolicy({
43
- enabled,
44
- nodeEnv,
45
- secret
46
- });
31
+ /**
32
+ * Dev auth's policy (AUTH_DEV_BYPASS_ENABLED and AUTH_DEV_BYPASS_SECRET), and
33
+ * the audience and lifetimes of the tokens it signs.
34
+ * @param {import("@jskit-ai/kernel/server/types").RuntimeEnv} env
35
+ * @param {string} jwtAudience
36
+ */
37
+ function resolveDevAuthConfig(env, jwtAudience) {
47
38
  return Object.freeze({
48
- ...policy,
49
- jwtAudience: String(jwtAudience || "authenticated").trim() || "authenticated",
50
- accessTtlSeconds: normalizePositiveInteger(accessTtlSeconds, DEFAULT_DEV_AUTH_ACCESS_TTL_SECONDS),
51
- refreshTtlSeconds: normalizePositiveInteger(refreshTtlSeconds, DEFAULT_DEV_AUTH_REFRESH_TTL_SECONDS)
39
+ ...resolveDevAuthPolicyFromEnv(env),
40
+ jwtAudience,
41
+ accessTtlSeconds: normalizePositiveInteger(env.AUTH_DEV_ACCESS_TTL_SECONDS, DEFAULT_DEV_AUTH_ACCESS_TTL_SECONDS),
42
+ refreshTtlSeconds: normalizePositiveInteger(env.AUTH_DEV_REFRESH_TTL_SECONDS, DEFAULT_DEV_AUTH_REFRESH_TTL_SECONDS)
52
43
  });
53
44
  }
54
45
 
55
- function assertDevAuthBootstrapConfig(config, { userProfilesRepository = null } = {}) {
56
- assertDevAuthPolicy(config);
57
- if (!config?.enabled) {
58
- return;
59
- }
60
- if (
61
- !userProfilesRepository ||
62
- typeof userProfilesRepository.findById !== "function" ||
63
- typeof userProfilesRepository.findByEmail !== "function"
64
- ) {
65
- throw new Error(
66
- "Dev auth bootstrap requires internal.repository.user-profiles with findById() and findByEmail() when AUTH_DEV_BYPASS_ENABLED=true."
67
- );
68
- }
69
- }
70
-
71
46
  function buildProfileFromTokenClaims(payload) {
72
47
  const id = normalizeRecordId(payload?.sub, { fallback: null });
73
48
  const email = normalizeEmail(payload?.email || "");
@@ -96,9 +71,13 @@ function buildProfileFromTokenClaims(payload) {
96
71
  };
97
72
  }
98
73
 
99
- async function resolveProfileFromTokenClaims(payload, { userProfilesRepository = null } = {}) {
74
+ /**
75
+ * @param {any} payload
76
+ * @param {{ userProfilesRepository: import("../types.js").SupabaseUserProfiles }} dependencies
77
+ */
78
+ async function resolveProfileFromTokenClaims(payload, { userProfilesRepository }) {
100
79
  const userId = normalizeRecordId(payload?.sub, { fallback: null });
101
- if (userId && userProfilesRepository && typeof userProfilesRepository.findById === "function") {
80
+ if (userId) {
102
81
  const latest = await userProfilesRepository.findById(userId);
103
82
  if (latest?.id) {
104
83
  return latest;
@@ -190,15 +169,14 @@ async function createDevAuthSession(profile, config) {
190
169
  };
191
170
  }
192
171
 
193
- async function resolveDevAuthProfile(input = {}, { userProfilesRepository = null, validationError } = {}) {
194
- if (!userProfilesRepository || typeof userProfilesRepository.findById !== "function") {
195
- throw new AppError(500, "Dev auth bootstrap requires internal.repository.user-profiles.findById().", {
196
- code: "auth.supabase.dev.findByIdMissing"
197
- });
198
- }
199
-
200
- const normalizedUserId = normalizeRecordId(input?.userId, { fallback: null });
201
- const normalizedEmail = normalizeEmail(input?.email || "");
172
+ /**
173
+ * The app user a dev login names by id or email.
174
+ * @param {{ userId?: unknown, email?: unknown }} input
175
+ * @param {{ userProfilesRepository: import("../types.js").SupabaseUserProfiles }} dependencies
176
+ */
177
+ async function resolveDevAuthProfile(input, { userProfilesRepository }) {
178
+ const normalizedUserId = normalizeRecordId(input.userId, { fallback: null });
179
+ const normalizedEmail = normalizeEmail(input.email || "");
202
180
  if (!normalizedUserId && !normalizedEmail) {
203
181
  throw validationError({
204
182
  userId: authFieldError(AUTH_TEXTS.devUserRequired),
@@ -217,12 +195,6 @@ async function resolveDevAuthProfile(input = {}, { userProfilesRepository = null
217
195
  }
218
196
 
219
197
  if (normalizedEmail) {
220
- if (typeof userProfilesRepository.findByEmail !== "function") {
221
- throw new AppError(500, "Dev auth bootstrap requires internal.repository.user-profiles.findByEmail() for email lookup.", {
222
- code: "auth.supabase.dev.findByEmailMissing"
223
- });
224
- }
225
-
226
198
  const byEmail = await userProfilesRepository.findByEmail(normalizedEmail);
227
199
  if (byEmail?.id) {
228
200
  return byEmail;
@@ -233,9 +205,15 @@ async function resolveDevAuthProfile(input = {}, { userProfilesRepository = null
233
205
  throw validationError(fieldErrors);
234
206
  }
235
207
 
208
+ /**
209
+ * @param {{ request: object, accessToken?: string, refreshToken?: string }} tokens
210
+ * @param {object} dependencies
211
+ * @param {import("../types.js").SupabaseConfig["devAuth"]} dependencies.config
212
+ * @param {import("../types.js").SupabaseUserProfiles} dependencies.userProfilesRepository
213
+ */
236
214
  async function authenticateDevAuthRequest(
237
215
  { request, accessToken = "", refreshToken = "" },
238
- { config, userProfilesRepository = null } = {}
216
+ { config, userProfilesRepository }
239
217
  ) {
240
218
  const hasDevAccessToken = isDevAuthToken(accessToken);
241
219
  const hasDevRefreshToken = isDevAuthToken(refreshToken);
@@ -311,7 +289,6 @@ async function authenticateDevAuthRequest(
311
289
  }
312
290
 
313
291
  export {
314
- assertDevAuthBootstrapConfig,
315
292
  authenticateDevAuthRequest,
316
293
  createDevAuthSession,
317
294
  isDevAuthToken,
@@ -1,22 +1,4 @@
1
- function requireNoFieldErrors(parsed, validationError) {
2
- if (typeof validationError !== "function") {
3
- throw new TypeError("requireNoFieldErrors requires validationError.");
4
- }
5
-
6
- const fieldErrors =
7
- parsed && typeof parsed === "object" && parsed.fieldErrors && typeof parsed.fieldErrors === "object"
8
- ? parsed.fieldErrors
9
- : {};
10
- if (Object.keys(fieldErrors).length > 0) {
11
- throw validationError(fieldErrors);
12
- }
13
- }
14
-
15
1
  function requireAuthUserSession(response, mapError, status = 401) {
16
- if (typeof mapError !== "function") {
17
- throw new TypeError("requireAuthUserSession requires mapError.");
18
- }
19
-
20
2
  if (response?.error || !response?.data?.user || !response?.data?.session) {
21
3
  throw mapError(response?.error, status);
22
4
  }
@@ -28,10 +10,6 @@ function requireAuthUserSession(response, mapError, status = 401) {
28
10
  }
29
11
 
30
12
  function requireAuthUser(response, mapError, status = 400) {
31
- if (typeof mapError !== "function") {
32
- throw new TypeError("requireAuthUser requires mapError.");
33
- }
34
-
35
13
  if (response?.error || !response?.data?.user) {
36
14
  throw mapError(response?.error, status);
37
15
  }
@@ -42,10 +20,6 @@ function requireAuthUser(response, mapError, status = 400) {
42
20
  }
43
21
 
44
22
  function requireAuthSession(response, mapError, status = 401) {
45
- if (typeof mapError !== "function") {
46
- throw new TypeError("requireAuthSession requires mapError.");
47
- }
48
-
49
23
  if (response?.error || !response?.data?.session) {
50
24
  throw mapError(response?.error, status);
51
25
  }
@@ -55,4 +29,4 @@ function requireAuthSession(response, mapError, status = 401) {
55
29
  };
56
30
  }
57
31
 
58
- export { requireNoFieldErrors, requireAuthUserSession, requireAuthUser, requireAuthSession };
32
+ export { requireAuthUserSession, requireAuthUser, requireAuthSession };
@@ -1 +1 @@
1
- export { createService, __testables } from "./service.js";
1
+ export { createSupabaseAuthService } from "./service.js";
@@ -1,35 +1,42 @@
1
1
  import { AppError } from "@jskit-ai/kernel/server/runtime/errors";
2
2
  import { authLoginOAuthStartParamsValidator, authLoginOAuthStartQueryValidator } from "@jskit-ai/auth-core/shared/commands/authLoginOAuthStartCommand";
3
3
  import { authLoginOAuthCompleteBodyValidator } from "@jskit-ai/auth-core/shared/commands/authLoginOAuthCompleteCommand";
4
+ import { buildOAuthMethodId } from "@jskit-ai/auth-core/shared/authMethods";
5
+ import { mapAuthError, mapRecoveryError, validationError } from "./authErrorMappers.js";
6
+ import { normalizeReturnToPath } from "@jskit-ai/auth-core/server/utils";
7
+ import { mapOAuthCallbackError, normalizeOAuthProviderInput } from "./authInputParsers.js";
8
+ import { buildOAuthLinkRedirectUrl, buildOAuthLoginRedirectUrl } from "./authRedirectUrls.js";
9
+ import { resolveOAuthProviderQueryParams } from "./oauthProviderCatalog.js";
10
+ import { findAuthMethodById, findLinkedIdentityByProvider } from "./authMethodStatus.js";
11
+
12
+ /**
13
+ * Signing in with, linking and unlinking an OAuth provider through Supabase.
14
+ * @param {object} dependencies
15
+ * @param {import("../types.js").SupabaseConfig} dependencies.config
16
+ * @param {import("../types.js").SupabaseClients} dependencies.clients
17
+ * @param {import("../types.js").SupabaseSessions} dependencies.sessions
18
+ * @param {import("../types.js").SupabaseProfileMirror} dependencies.profileMirror
19
+ * @param {import("../types.js").SupabaseSecurityStatus} dependencies.securityStatus
20
+ */
21
+ function createSupabaseOAuthFlows({ config, clients, sessions, profileMirror, securityStatus }) {
22
+ /** A provider the app offers, else its default one. */
23
+ function configuredProvider(value) {
24
+ return normalizeOAuthProviderInput(value, {
25
+ providerIds: config.oauth.providerIds,
26
+ defaultProvider: config.oauth.defaultProvider
27
+ });
28
+ }
4
29
 
5
- function createOauthFlows(deps) {
6
- const {
7
- ensureConfigured,
8
- normalizeOAuthProviderInput,
9
- normalizeReturnToPath,
10
- buildOAuthLoginRedirectUrl,
11
- appPublicUrl,
12
- authOAuthDefaultProvider,
13
- resolveOAuthProviderQueryParams = () => null,
14
- getSupabaseClient,
15
- mapAuthError,
16
- setSessionFromRequestCookies,
17
- buildOAuthLinkRedirectUrl,
18
- validationError,
19
- mapOAuthCallbackError,
20
- mapRecoveryError,
21
- syncProfileFromSupabaseUser,
22
- resolveCurrentAuthContext,
23
- buildOAuthMethodId,
24
- findAuthMethodById,
25
- findLinkedIdentityByProvider,
26
- buildSecurityStatusFromAuthMethodsStatus
27
- } = deps;
30
+ function allowedReturnTo(value) {
31
+ return normalizeReturnToPath(value, { fallback: "/", allowedOrigins: config.allowedReturnToOrigins });
32
+ }
28
33
 
29
34
  async function requestOAuthRedirectUrl(supabase, provider, redirectTo, requestFlow) {
30
35
  let response;
31
36
  try {
32
- const queryParams = resolveOAuthProviderQueryParams(provider);
37
+ const queryParams = resolveOAuthProviderQueryParams(provider, {
38
+ providerQueryParamsById: config.oauth.providerQueryParamsById
39
+ });
33
40
  response = await requestFlow({
34
41
  provider,
35
42
  options: {
@@ -48,11 +55,11 @@ function createOauthFlows(deps) {
48
55
  return String(response.data.url);
49
56
  }
50
57
 
51
- async function oauthStart(payload = {}) {
52
- ensureConfigured();
58
+ async function oauthStart(payload) {
59
+ clients.ensureConfigured();
53
60
 
54
61
  const paramsResult = authLoginOAuthStartParamsValidator.schema.patch({
55
- provider: payload.provider || authOAuthDefaultProvider
62
+ provider: payload.provider || config.oauth.defaultProvider
56
63
  });
57
64
  if (Object.keys(paramsResult.errors).length > 0) {
58
65
  throw validationError(paramsResult.errors);
@@ -65,14 +72,15 @@ function createOauthFlows(deps) {
65
72
  throw validationError(queryResult.errors);
66
73
  }
67
74
 
68
- const provider = normalizeOAuthProviderInput(paramsResult.validatedObject.provider);
69
- const returnTo = normalizeReturnToPath(queryResult.validatedObject.returnTo, { fallback: "/" });
75
+ const provider = configuredProvider(paramsResult.validatedObject.provider);
76
+ const returnTo = allowedReturnTo(queryResult.validatedObject.returnTo);
70
77
  const redirectTo = buildOAuthLoginRedirectUrl({
71
- appPublicUrl,
78
+ appPublicUrl: config.appPublicUrl,
79
+ providerIds: config.oauth.providerIds,
72
80
  provider,
73
81
  returnTo
74
82
  });
75
- const supabase = getSupabaseClient();
83
+ const supabase = clients.createSupabaseClient();
76
84
  const url = await requestOAuthRedirectUrl(supabase, provider, redirectTo, (input) =>
77
85
  supabase.auth.signInWithOAuth(input)
78
86
  );
@@ -84,11 +92,11 @@ function createOauthFlows(deps) {
84
92
  };
85
93
  }
86
94
 
87
- async function startProviderLink(request, payload = {}) {
88
- ensureConfigured();
95
+ async function startProviderLink(request, payload) {
96
+ clients.ensureConfigured();
89
97
 
90
98
  const paramsResult = authLoginOAuthStartParamsValidator.schema.patch({
91
- provider: payload.provider || authOAuthDefaultProvider
99
+ provider: payload.provider || config.oauth.defaultProvider
92
100
  });
93
101
  if (Object.keys(paramsResult.errors).length > 0) {
94
102
  throw validationError(paramsResult.errors);
@@ -101,21 +109,16 @@ function createOauthFlows(deps) {
101
109
  throw validationError(queryResult.errors);
102
110
  }
103
111
 
104
- const provider = normalizeOAuthProviderInput(paramsResult.validatedObject.provider);
105
- const returnTo = normalizeReturnToPath(queryResult.validatedObject.returnTo, { fallback: "/" });
106
- const supabase = getSupabaseClient();
107
- await setSessionFromRequestCookies(request, {
112
+ const provider = configuredProvider(paramsResult.validatedObject.provider);
113
+ const returnTo = allowedReturnTo(queryResult.validatedObject.returnTo);
114
+ const supabase = clients.createSupabaseClient();
115
+ await sessions.setSessionFromRequestCookies(request, {
108
116
  supabaseClient: supabase
109
117
  });
110
118
 
111
- if (typeof supabase.auth.linkIdentity !== "function") {
112
- throw new AppError(500, "Supabase client does not support identity linking in this environment.", {
113
- code: "auth.supabase.link.unsupported"
114
- });
115
- }
116
-
117
119
  const redirectTo = buildOAuthLinkRedirectUrl({
118
- appPublicUrl,
120
+ appPublicUrl: config.appPublicUrl,
121
+ providerIds: config.oauth.providerIds,
119
122
  provider,
120
123
  returnTo
121
124
  });
@@ -130,8 +133,8 @@ function createOauthFlows(deps) {
130
133
  };
131
134
  }
132
135
 
133
- async function oauthComplete(payload = {}) {
134
- ensureConfigured();
136
+ async function oauthComplete(payload) {
137
+ clients.ensureConfigured();
135
138
 
136
139
  const result = authLoginOAuthCompleteBodyValidator.schema.patch(payload);
137
140
  if (Object.keys(result.errors).length > 0) {
@@ -142,7 +145,6 @@ function createOauthFlows(deps) {
142
145
  const accessToken = String(parsed.accessToken || "").trim();
143
146
  const refreshToken = String(parsed.refreshToken || "").trim();
144
147
  const errorCode = String(parsed.error || parsed.error_code || "").trim();
145
- const errorDescription = String(parsed.errorDescription || parsed.error_description || "").trim();
146
148
  const hasSessionPair = Boolean(accessToken && refreshToken);
147
149
  const fieldErrors = {};
148
150
 
@@ -174,14 +176,14 @@ function createOauthFlows(deps) {
174
176
 
175
177
  const provider =
176
178
  !hasSessionPair || code || errorCode
177
- ? normalizeOAuthProviderInput(parsed.provider || authOAuthDefaultProvider)
179
+ ? configuredProvider(parsed.provider || config.oauth.defaultProvider)
178
180
  : null;
179
181
 
180
182
  if (errorCode) {
181
- throw mapOAuthCallbackError(errorCode, errorDescription);
183
+ throw mapOAuthCallbackError(errorCode);
182
184
  }
183
185
 
184
- const supabase = getSupabaseClient();
186
+ const supabase = clients.createSupabaseClient();
185
187
  let response;
186
188
  try {
187
189
  if (hasSessionPair) {
@@ -200,7 +202,7 @@ function createOauthFlows(deps) {
200
202
  throw mapRecoveryError(response.error);
201
203
  }
202
204
 
203
- const profile = await syncProfileFromSupabaseUser(response.data.user, response.data.user.email);
205
+ const profile = await profileMirror.syncProfileFromSupabaseUser(response.data.user, response.data.user.email);
204
206
 
205
207
  return {
206
208
  provider,
@@ -209,21 +211,16 @@ function createOauthFlows(deps) {
209
211
  };
210
212
  }
211
213
 
212
- async function unlinkProvider(request, payload = {}) {
213
- ensureConfigured();
214
+ async function unlinkProvider(request, payload) {
215
+ clients.ensureConfigured();
214
216
 
215
- const provider = normalizeOAuthProviderInput(payload.provider);
216
- const supabase = getSupabaseClient();
217
- if (typeof supabase.auth.unlinkIdentity !== "function") {
218
- throw new AppError(500, "Supabase client does not support identity unlinking in this environment.", {
219
- code: "auth.supabase.unlink.unsupported"
220
- });
221
- }
217
+ const provider = configuredProvider(payload.provider);
218
+ const supabase = clients.createSupabaseClient();
222
219
 
223
- await setSessionFromRequestCookies(request, {
220
+ await sessions.setSessionFromRequestCookies(request, {
224
221
  supabaseClient: supabase
225
222
  });
226
- const current = await resolveCurrentAuthContext(request, {
223
+ const current = await securityStatus.currentAuthContext(request, {
227
224
  supabaseClient: supabase
228
225
  });
229
226
  const methodId = buildOAuthMethodId(provider);
@@ -256,20 +253,20 @@ function createOauthFlows(deps) {
256
253
  throw mapAuthError(response.error, Number(response.error?.status || 400));
257
254
  }
258
255
 
259
- const refreshed = await resolveCurrentAuthContext(request, {
256
+ const refreshed = await securityStatus.currentAuthContext(request, {
260
257
  supabaseClient: supabase
261
258
  });
262
259
  return {
263
- securityStatus: buildSecurityStatusFromAuthMethodsStatus(refreshed.authMethodsStatus)
260
+ securityStatus: securityStatus.buildSecurityStatus(refreshed.authMethodsStatus)
264
261
  };
265
262
  }
266
263
 
267
- return {
264
+ return Object.freeze({
268
265
  oauthStart,
269
266
  startProviderLink,
270
267
  oauthComplete,
271
268
  unlinkProvider
272
- };
269
+ });
273
270
  }
274
271
 
275
- export { createOauthFlows };
272
+ export { createSupabaseOAuthFlows };