@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.
- package/locales/en.json +3 -19
- package/package.json +3 -3
- package/patterns/supabase-auth/example/package.json +1 -1
- package/src/server/lib/accountFlows.js +66 -86
- package/src/server/lib/authProfileNames.js +9 -12
- package/src/server/lib/authenticatedProfile.js +1 -2
- package/src/server/lib/config.js +90 -0
- package/src/server/lib/devAuthBootstrap.js +34 -57
- package/src/server/lib/flowGuards.js +1 -27
- package/src/server/lib/index.js +1 -1
- package/src/server/lib/oauthFlows.js +65 -68
- package/src/server/lib/{passwordSecurityFlows.js → passwordFlows.js} +68 -112
- package/src/server/lib/profileMirror.js +204 -0
- package/src/server/lib/profileModes.js +80 -0
- package/src/server/lib/securityStatus.js +109 -0
- package/src/server/lib/service.js +87 -1092
- package/src/server/lib/sessions.js +494 -0
- package/src/server/lib/supabaseClients.js +28 -0
- package/src/server/providers/AuthSupabaseProvider.js +19 -98
- package/src/server/types.js +21 -0
- package/test/auth.provider.supabase.test.js +155 -144
- package/test/codedTexts.test.js +3 -5
- package/test/devAuthBootstrap.test.js +37 -34
- package/test/index.test.js +3 -3
- package/src/server/lib/standaloneProfileSyncService.js +0 -97
- package/src/server/lib/test-utils.js +0 -44
|
@@ -1,1141 +1,136 @@
|
|
|
1
|
-
import { createClient } from "@supabase/supabase-js";
|
|
2
|
-
import { AppError } from "@jskit-ai/kernel/server/runtime/errors";
|
|
3
|
-
import { AUTH_TEXTS, createAuthError } from "@jskit-ai/auth-core/server/authTexts";
|
|
4
1
|
import { normalizeAuthCapabilities } from "@jskit-ai/auth-core/shared/authCapabilities";
|
|
5
2
|
import { ensureDevAuthExchangeAvailable } from "@jskit-ai/auth-core/server/devAuth";
|
|
6
|
-
import {
|
|
7
|
-
import {
|
|
8
|
-
AUTH_METHOD_PASSWORD_ID,
|
|
9
|
-
AUTH_METHOD_PASSWORD_PROVIDER,
|
|
10
|
-
buildOAuthMethodId
|
|
11
|
-
} from "@jskit-ai/auth-core/shared/authMethods";
|
|
12
|
-
import { hostOnlyCookieName, normalizeEmail } from "@jskit-ai/auth-core/server/utils";
|
|
13
|
-
import {
|
|
14
|
-
isTransientAuthMessage,
|
|
15
|
-
isTransientSupabaseError,
|
|
16
|
-
mapAuthError,
|
|
17
|
-
validationError,
|
|
18
|
-
isUserNotFoundLikeAuthError,
|
|
19
|
-
mapRecoveryError,
|
|
20
|
-
mapPasswordUpdateError,
|
|
21
|
-
mapOtpVerifyError,
|
|
22
|
-
mapProfileUpdateError,
|
|
23
|
-
mapCurrentPasswordError
|
|
24
|
-
} from "./authErrorMappers.js";
|
|
25
|
-
import { displayNameFromEmail, resolveDisplayName, resolveDisplayNameFromClaims } from "./authProfileNames.js";
|
|
26
|
-
import {
|
|
27
|
-
normalizeOAuthProviderInput as normalizeOAuthProviderInputFromCatalog,
|
|
28
|
-
mapOAuthCallbackError
|
|
29
|
-
} from "./authInputParsers.js";
|
|
30
|
-
import {
|
|
31
|
-
parseHttpUrl,
|
|
32
|
-
buildPasswordResetRedirectUrl,
|
|
33
|
-
buildOtpLoginRedirectUrl,
|
|
34
|
-
normalizeOAuthIntent,
|
|
35
|
-
normalizeReturnToPath,
|
|
36
|
-
buildOAuthRedirectUrl,
|
|
37
|
-
buildOAuthLoginRedirectUrl,
|
|
38
|
-
buildOAuthLinkRedirectUrl
|
|
39
|
-
} from "./authRedirectUrls.js";
|
|
40
|
-
import {
|
|
41
|
-
normalizeIdentityProviderId,
|
|
42
|
-
collectProviderIdsFromSupabaseUser,
|
|
43
|
-
buildAuthMethodsStatusFromProviderIds,
|
|
44
|
-
buildAuthMethodsStatusFromSupabaseUser,
|
|
45
|
-
buildSecurityStatusFromAuthMethodsStatus,
|
|
46
|
-
findAuthMethodById,
|
|
47
|
-
findLinkedIdentityByProvider
|
|
48
|
-
} from "./authMethodStatus.js";
|
|
49
|
-
import { safeRequestCookies, cookieOptions, cookieClearOptions } from "./authCookies.js";
|
|
50
|
-
import { loadJose, isExpiredJwtError, classifyJwtVerifyError } from "./authJwt.js";
|
|
51
|
-
import { buildDisabledPasswordSecret } from "./authSecrets.js";
|
|
52
|
-
import { createAccountFlows } from "./accountFlows.js";
|
|
53
|
-
import { createOauthFlows } from "./oauthFlows.js";
|
|
54
|
-
import { createPasswordSecurityFlows } from "./passwordSecurityFlows.js";
|
|
55
|
-
import { buildSupabaseServerClientOptions } from "./supabaseClientOptions.js";
|
|
56
|
-
import { USER_PROFILE_EMAIL_CONFLICT_CODE } from "./standaloneProfileSyncService.js";
|
|
57
|
-
import {
|
|
58
|
-
assertDevAuthBootstrapConfig,
|
|
59
|
-
authenticateDevAuthRequest,
|
|
60
|
-
createDevAuthSession,
|
|
61
|
-
isDevAuthToken,
|
|
62
|
-
resolveDevAuthConfig,
|
|
63
|
-
resolveDevAuthProfile
|
|
64
|
-
} from "./devAuthBootstrap.js";
|
|
3
|
+
import { createSupabaseAccountFlows } from "./accountFlows.js";
|
|
65
4
|
import { requireAuthenticatedProfile } from "./authenticatedProfile.js";
|
|
66
|
-
import {
|
|
67
|
-
|
|
68
|
-
|
|
69
|
-
|
|
70
|
-
} from "./
|
|
71
|
-
|
|
72
|
-
|
|
73
|
-
|
|
74
|
-
const
|
|
75
|
-
|
|
76
|
-
|
|
77
|
-
|
|
78
|
-
|
|
79
|
-
|
|
80
|
-
|
|
81
|
-
|
|
82
|
-
|
|
83
|
-
|
|
84
|
-
|
|
85
|
-
|
|
86
|
-
|
|
87
|
-
|
|
88
|
-
|
|
89
|
-
const fallbackNormalized = String(fallback || "")
|
|
90
|
-
.trim()
|
|
91
|
-
.toLowerCase();
|
|
92
|
-
if (AUTH_PROVIDER_ID_PATTERN.test(fallbackNormalized)) {
|
|
93
|
-
return fallbackNormalized;
|
|
94
|
-
}
|
|
95
|
-
|
|
96
|
-
return DEFAULT_AUTH_PROVIDER_ID;
|
|
97
|
-
}
|
|
98
|
-
|
|
99
|
-
function normalizeProviderUserId(value) {
|
|
100
|
-
return String(value || "").trim();
|
|
101
|
-
}
|
|
102
|
-
|
|
103
|
-
function createService(options) {
|
|
104
|
-
const authProvider = options.authProvider && typeof options.authProvider === "object" ? options.authProvider : null;
|
|
105
|
-
if (!authProvider) {
|
|
106
|
-
throw new Error("authProvider is required.");
|
|
107
|
-
}
|
|
108
|
-
|
|
109
|
-
const authProviderId = normalizeAuthProviderId(authProvider.id);
|
|
110
|
-
if (authProviderId !== DEFAULT_AUTH_PROVIDER_ID) {
|
|
111
|
-
throw new Error(`Unsupported auth provider "${authProviderId}".`);
|
|
112
|
-
}
|
|
113
|
-
|
|
114
|
-
const supabaseUrl = String(authProvider.supabaseUrl || "").trim();
|
|
115
|
-
const supabasePublishableKey = String(authProvider.supabasePublishableKey || "").trim();
|
|
116
|
-
const supabaseConfigured = Boolean(supabaseUrl && supabasePublishableKey);
|
|
117
|
-
const userSettingsRepository = options.userSettingsRepository || null;
|
|
118
|
-
const passwordMethodToggleSupported =
|
|
119
|
-
typeof userSettingsRepository?.ensureForUserId === "function" &&
|
|
120
|
-
typeof userSettingsRepository?.updatePasswordSignInEnabled === "function";
|
|
121
|
-
const userProfilesRepository = options.userProfilesRepository || null;
|
|
122
|
-
const userProfileSyncService = options.userProfileSyncService;
|
|
123
|
-
const profileProjectionEnabled = options.profileProjectionEnabled === true;
|
|
124
|
-
if (
|
|
125
|
-
!userProfileSyncService ||
|
|
126
|
-
typeof userProfileSyncService.syncIdentityProfile !== "function" ||
|
|
127
|
-
typeof userProfileSyncService.findByIdentity !== "function"
|
|
128
|
-
) {
|
|
129
|
-
throw new Error("userProfileSyncService with syncIdentityProfile() and findByIdentity() is required.");
|
|
130
|
-
}
|
|
131
|
-
const isProduction = options.nodeEnv === "production";
|
|
132
|
-
// Production cookies are Secure, so they are also host-only __Host- cookies.
|
|
133
|
-
const ACCESS_TOKEN_COOKIE = hostOnlyCookieName(ACCESS_TOKEN_COOKIE_NAME, isProduction);
|
|
134
|
-
const REFRESH_TOKEN_COOKIE = hostOnlyCookieName(REFRESH_TOKEN_COOKIE_NAME, isProduction);
|
|
135
|
-
const RECOVERY_ACCESS_TOKEN_COOKIE = hostOnlyCookieName(RECOVERY_ACCESS_TOKEN_COOKIE_NAME, isProduction);
|
|
136
|
-
const RECOVERY_REFRESH_TOKEN_COOKIE = hostOnlyCookieName(RECOVERY_REFRESH_TOKEN_COOKIE_NAME, isProduction);
|
|
137
|
-
const jwtAudience = String(authProvider.jwtAudience || DEFAULT_AUDIENCE).trim();
|
|
138
|
-
const devAuthConfig = resolveDevAuthConfig({
|
|
139
|
-
enabled: options.devAuthBypassEnabled,
|
|
140
|
-
secret: options.devAuthBypassSecret,
|
|
141
|
-
nodeEnv: options.nodeEnv,
|
|
142
|
-
jwtAudience,
|
|
143
|
-
accessTtlSeconds: options.devAuthAccessTtlSeconds,
|
|
144
|
-
refreshTtlSeconds: options.devAuthRefreshTtlSeconds
|
|
145
|
-
});
|
|
146
|
-
assertDevAuthBootstrapConfig(devAuthConfig, {
|
|
147
|
-
userProfilesRepository
|
|
148
|
-
});
|
|
149
|
-
const settingsProfileAuthInfo = Object.freeze({
|
|
150
|
-
emailManagedBy: normalizeAuthProviderId(authProvider.emailManagedBy || authProviderId, { fallback: authProviderId }),
|
|
151
|
-
emailChangeFlow: normalizeAuthProviderId(authProvider.emailChangeFlow || authProviderId, { fallback: authProviderId })
|
|
152
|
-
});
|
|
153
|
-
const passwordResetRedirectUrl = buildPasswordResetRedirectUrl({
|
|
154
|
-
appPublicUrl: options.appPublicUrl
|
|
155
|
-
});
|
|
156
|
-
const otpLoginRedirectUrl = buildOtpLoginRedirectUrl({
|
|
157
|
-
appPublicUrl: options.appPublicUrl
|
|
158
|
-
});
|
|
159
|
-
const appPublicUrl = String(options.appPublicUrl || "");
|
|
160
|
-
const authAllowedReturnToOrigins = Array.isArray(options.authAllowedReturnToOrigins)
|
|
161
|
-
? options.authAllowedReturnToOrigins
|
|
162
|
-
: [];
|
|
163
|
-
const authOAuthCatalog = resolveSupabaseOAuthProviderCatalog({
|
|
164
|
-
oauthProviderCatalog: authProvider.oauthProviderCatalog || options.authOAuthProviderCatalog,
|
|
165
|
-
oauthProviders: authProvider.oauthProviders ?? options.authOAuthProviders,
|
|
166
|
-
oauthDefaultProvider: authProvider.oauthDefaultProvider ?? options.authOAuthDefaultProvider,
|
|
167
|
-
oauthProviderLabels: authProvider.oauthProviderLabels || options.authOAuthProviderLabels,
|
|
168
|
-
oauthProviderQueryParams: authProvider.oauthProviderQueryParams || options.authOAuthProviderQueryParams
|
|
169
|
-
});
|
|
170
|
-
const authOAuthProviders = authOAuthCatalog.providers;
|
|
171
|
-
const authOAuthProviderIds = authOAuthCatalog.providerIds;
|
|
172
|
-
const authOAuthDefaultProvider = authOAuthCatalog.defaultProvider;
|
|
173
|
-
const authOAuthCatalogResponse = Object.freeze(buildOAuthProviderCatalogResponse(authOAuthCatalog));
|
|
5
|
+
import { createDevAuthSession, resolveDevAuthProfile } from "./devAuthBootstrap.js";
|
|
6
|
+
import { createSupabaseOAuthFlows } from "./oauthFlows.js";
|
|
7
|
+
import { createSupabasePasswordFlows } from "./passwordFlows.js";
|
|
8
|
+
import { SUPABASE_PROVIDER_ID, createSupabaseProfileMirror } from "./profileMirror.js";
|
|
9
|
+
import { createSupabaseSecurityStatus } from "./securityStatus.js";
|
|
10
|
+
import { createSupabaseSessions } from "./sessions.js";
|
|
11
|
+
import { createSupabaseClients } from "./supabaseClients.js";
|
|
12
|
+
|
|
13
|
+
const SETTINGS_PROFILE_AUTH_INFO = Object.freeze({
|
|
14
|
+
emailManagedBy: SUPABASE_PROVIDER_ID,
|
|
15
|
+
emailChangeFlow: SUPABASE_PROVIDER_ID
|
|
16
|
+
});
|
|
17
|
+
|
|
18
|
+
/**
|
|
19
|
+
* The `auth.service` for Supabase Auth.
|
|
20
|
+
* @param {object} dependencies
|
|
21
|
+
* @param {import("../types.js").SupabaseConfig} dependencies.config
|
|
22
|
+
* @param {import("../types.js").SupabaseProfiles} dependencies.profiles
|
|
23
|
+
*/
|
|
24
|
+
function createSupabaseAuthService({ config, profiles }) {
|
|
25
|
+
const { configured } = config;
|
|
26
|
+
const oauthOffered = configured && config.oauth.providers.length > 0;
|
|
174
27
|
const capabilities = normalizeAuthCapabilities({
|
|
175
28
|
provider: {
|
|
176
|
-
id:
|
|
29
|
+
id: SUPABASE_PROVIDER_ID,
|
|
177
30
|
label: "Supabase"
|
|
178
31
|
},
|
|
179
32
|
features: {
|
|
180
33
|
password: {
|
|
181
|
-
login:
|
|
182
|
-
register:
|
|
183
|
-
change:
|
|
184
|
-
methodToggle:
|
|
34
|
+
login: configured,
|
|
35
|
+
register: configured,
|
|
36
|
+
change: configured,
|
|
37
|
+
methodToggle: configured && config.profileMode === "users"
|
|
185
38
|
},
|
|
186
39
|
passwordRecovery: {
|
|
187
|
-
request:
|
|
188
|
-
complete:
|
|
189
|
-
delivery:
|
|
40
|
+
request: configured,
|
|
41
|
+
complete: configured,
|
|
42
|
+
delivery: configured ? "email" : "disabled"
|
|
190
43
|
},
|
|
191
44
|
otp: {
|
|
192
|
-
login:
|
|
45
|
+
login: configured
|
|
193
46
|
},
|
|
194
47
|
oauthLogin: {
|
|
195
|
-
enabled:
|
|
196
|
-
providers:
|
|
197
|
-
defaultProvider:
|
|
48
|
+
enabled: oauthOffered,
|
|
49
|
+
providers: config.oauthCatalog.providers,
|
|
50
|
+
defaultProvider: config.oauthCatalog.defaultProvider
|
|
198
51
|
},
|
|
199
|
-
emailConfirmation:
|
|
200
|
-
profileUpdate:
|
|
52
|
+
emailConfirmation: configured,
|
|
53
|
+
profileUpdate: configured,
|
|
201
54
|
providerLinking: {
|
|
202
|
-
start:
|
|
203
|
-
unlink:
|
|
55
|
+
start: oauthOffered,
|
|
56
|
+
unlink: oauthOffered
|
|
204
57
|
},
|
|
205
|
-
securityStatus:
|
|
206
|
-
signOutOtherSessions:
|
|
207
|
-
appProfileProjection:
|
|
208
|
-
devLoginAs:
|
|
58
|
+
securityStatus: configured || config.devAuth.enabled === true,
|
|
59
|
+
signOutOtherSessions: configured,
|
|
60
|
+
appProfileProjection: config.profileMode === "users",
|
|
61
|
+
devLoginAs: config.devAuth.enabled === true
|
|
209
62
|
}
|
|
210
63
|
});
|
|
211
|
-
const securityStatusActions = Object.freeze({
|
|
212
|
-
changePassword: true,
|
|
213
|
-
setPasswordEnabled: capabilities.features.password.methodToggle,
|
|
214
|
-
linkProvider: capabilities.features.providerLinking.start,
|
|
215
|
-
unlinkProvider: capabilities.features.providerLinking.unlink,
|
|
216
|
-
signOutOtherSessions: capabilities.features.signOutOtherSessions
|
|
217
|
-
});
|
|
218
|
-
|
|
219
|
-
function buildProviderSecurityStatus(authMethodsStatus) {
|
|
220
|
-
return buildSecurityStatusFromAuthMethodsStatus(authMethodsStatus, {
|
|
221
|
-
actions: securityStatusActions
|
|
222
|
-
});
|
|
223
|
-
}
|
|
224
|
-
|
|
225
|
-
function normalizeOAuthProviderInput(value) {
|
|
226
|
-
return normalizeOAuthProviderInputFromCatalog(value, {
|
|
227
|
-
providerIds: authOAuthProviderIds,
|
|
228
|
-
defaultProvider: authOAuthDefaultProvider
|
|
229
|
-
});
|
|
230
|
-
}
|
|
231
|
-
|
|
232
|
-
function buildOAuthLoginRedirectUrlWithCatalog(payload) {
|
|
233
|
-
return buildOAuthLoginRedirectUrl({
|
|
234
|
-
...payload,
|
|
235
|
-
providerIds: authOAuthProviderIds
|
|
236
|
-
});
|
|
237
|
-
}
|
|
238
|
-
|
|
239
|
-
function buildOAuthLinkRedirectUrlWithCatalog(payload) {
|
|
240
|
-
return buildOAuthLinkRedirectUrl({
|
|
241
|
-
...payload,
|
|
242
|
-
providerIds: authOAuthProviderIds
|
|
243
|
-
});
|
|
244
|
-
}
|
|
245
|
-
|
|
246
|
-
function resolveOAuthProviderQueryParamsForProvider(providerId) {
|
|
247
|
-
return resolveOAuthProviderQueryParams(providerId, {
|
|
248
|
-
providerQueryParamsById: authOAuthCatalog.providerQueryParamsById
|
|
249
|
-
});
|
|
250
|
-
}
|
|
251
|
-
|
|
252
|
-
function normalizeAuthReturnToTarget(value, { fallback = "/" } = {}) {
|
|
253
|
-
return normalizeReturnToPath(value, {
|
|
254
|
-
fallback,
|
|
255
|
-
allowedOrigins: authAllowedReturnToOrigins
|
|
256
|
-
});
|
|
257
|
-
}
|
|
258
|
-
|
|
259
|
-
const issuerUrl = supabaseUrl ? new URL("/auth/v1", supabaseUrl).toString().replace(/\/$/, "") : "";
|
|
260
|
-
const jwksUrl = issuerUrl ? `${issuerUrl}/.well-known/jwks.json` : "";
|
|
261
|
-
|
|
262
|
-
let jwksResolver = null;
|
|
263
|
-
|
|
264
|
-
function ensureConfigured() {
|
|
265
|
-
if (!supabaseUrl || !supabasePublishableKey) {
|
|
266
|
-
throw new AppError(500, "Auth provider is not configured.", { code: "auth.supabase.config.missing" });
|
|
267
|
-
}
|
|
268
|
-
}
|
|
269
|
-
|
|
270
|
-
function createSupabaseClient() {
|
|
271
|
-
ensureConfigured();
|
|
272
|
-
return createClient(supabaseUrl, supabasePublishableKey, buildSupabaseServerClientOptions());
|
|
273
|
-
}
|
|
274
|
-
|
|
275
|
-
function getSupabaseClient() {
|
|
276
|
-
return createSupabaseClient();
|
|
277
|
-
}
|
|
278
|
-
|
|
279
|
-
function createStatelessSupabaseClient() {
|
|
280
|
-
return createSupabaseClient();
|
|
281
|
-
}
|
|
282
|
-
|
|
283
|
-
async function getJwksResolver() {
|
|
284
|
-
if (jwksResolver) {
|
|
285
|
-
return jwksResolver;
|
|
286
|
-
}
|
|
287
|
-
|
|
288
|
-
const jose = await loadJose();
|
|
289
|
-
jwksResolver = jose.createRemoteJWKSet(new URL(jwksUrl));
|
|
290
|
-
return jwksResolver;
|
|
291
|
-
}
|
|
292
|
-
|
|
293
|
-
async function verifyAccessToken(accessToken) {
|
|
294
|
-
const jose = await loadJose();
|
|
295
|
-
const jwks = await getJwksResolver();
|
|
296
|
-
|
|
297
|
-
try {
|
|
298
|
-
const { payload } = await jose.jwtVerify(accessToken, jwks, {
|
|
299
|
-
issuer: issuerUrl,
|
|
300
|
-
audience: jwtAudience,
|
|
301
|
-
clockTolerance: 5
|
|
302
|
-
});
|
|
303
|
-
|
|
304
|
-
return {
|
|
305
|
-
status: "valid",
|
|
306
|
-
payload
|
|
307
|
-
};
|
|
308
|
-
} catch (error) {
|
|
309
|
-
return {
|
|
310
|
-
status: classifyJwtVerifyError(error)
|
|
311
|
-
};
|
|
312
|
-
}
|
|
313
|
-
}
|
|
314
|
-
|
|
315
|
-
async function verifyAccessTokenViaSupabase(accessToken, profileOptions = {}) {
|
|
316
|
-
const supabase = getSupabaseClient();
|
|
317
|
-
|
|
318
|
-
try {
|
|
319
|
-
const response = await supabase.auth.getUser(accessToken);
|
|
320
|
-
if (response.error) {
|
|
321
|
-
if (isTransientSupabaseError(response.error)) {
|
|
322
|
-
return { status: "transient" };
|
|
323
|
-
}
|
|
324
|
-
|
|
325
|
-
return { status: "invalid" };
|
|
326
|
-
}
|
|
327
|
-
|
|
328
|
-
if (!response.data?.user) {
|
|
329
|
-
return { status: "invalid" };
|
|
330
|
-
}
|
|
331
|
-
|
|
332
|
-
const profile = await syncProfileFromSupabaseUser(response.data.user, response.data.user.email, profileOptions);
|
|
333
|
-
return {
|
|
334
|
-
status: "valid",
|
|
335
|
-
profile
|
|
336
|
-
};
|
|
337
|
-
} catch (error) {
|
|
338
|
-
if (isTransientSupabaseError(error)) {
|
|
339
|
-
return { status: "transient" };
|
|
340
|
-
}
|
|
341
|
-
|
|
342
|
-
return { status: "invalid" };
|
|
343
|
-
}
|
|
344
|
-
}
|
|
345
|
-
|
|
346
|
-
async function setSessionFromRequestCookies(request, options = {}) {
|
|
347
|
-
const cookies = safeRequestCookies(request);
|
|
348
|
-
const accessToken = String(cookies[ACCESS_TOKEN_COOKIE] || "").trim();
|
|
349
|
-
const refreshToken = String(cookies[REFRESH_TOKEN_COOKIE] || "").trim();
|
|
350
|
-
|
|
351
|
-
return setSupabaseSessionFromTokens({ accessToken, refreshToken }, options);
|
|
352
|
-
}
|
|
353
|
-
|
|
354
|
-
async function setRecoverySessionFromRequestCookies(request, options = {}) {
|
|
355
|
-
const cookies = safeRequestCookies(request);
|
|
356
|
-
const accessToken = String(cookies[RECOVERY_ACCESS_TOKEN_COOKIE] || "").trim();
|
|
357
|
-
const refreshToken = String(cookies[RECOVERY_REFRESH_TOKEN_COOKIE] || "").trim();
|
|
358
|
-
|
|
359
|
-
return setSupabaseSessionFromTokens({ accessToken, refreshToken }, options);
|
|
360
|
-
}
|
|
361
|
-
|
|
362
|
-
async function setSupabaseSessionFromTokens({ accessToken, refreshToken }, options = {}) {
|
|
363
|
-
const normalizedAccessToken = String(accessToken || "").trim();
|
|
364
|
-
const normalizedRefreshToken = String(refreshToken || "").trim();
|
|
365
|
-
|
|
366
|
-
if (!normalizedAccessToken || !normalizedRefreshToken) {
|
|
367
|
-
throw createAuthError(AUTH_TEXTS.sessionRequired);
|
|
368
|
-
}
|
|
369
|
-
|
|
370
|
-
const supabase = options.supabaseClient || getSupabaseClient();
|
|
371
|
-
let sessionResponse;
|
|
372
|
-
try {
|
|
373
|
-
sessionResponse = await supabase.auth.setSession({
|
|
374
|
-
access_token: normalizedAccessToken,
|
|
375
|
-
refresh_token: normalizedRefreshToken
|
|
376
|
-
});
|
|
377
|
-
} catch (error) {
|
|
378
|
-
throw mapRecoveryError(error);
|
|
379
|
-
}
|
|
380
|
-
|
|
381
|
-
const session = sessionResponse.data?.session || null;
|
|
382
|
-
const user = sessionResponse.data?.user || null;
|
|
383
|
-
|
|
384
|
-
if (sessionResponse.error || !session || !user) {
|
|
385
|
-
throw mapRecoveryError(sessionResponse.error);
|
|
386
|
-
}
|
|
387
|
-
|
|
388
|
-
return {
|
|
389
|
-
...sessionResponse,
|
|
390
|
-
data: {
|
|
391
|
-
...sessionResponse.data,
|
|
392
|
-
session,
|
|
393
|
-
user
|
|
394
|
-
}
|
|
395
|
-
};
|
|
396
|
-
}
|
|
397
|
-
|
|
398
|
-
async function resolveCurrentSupabaseUser(request, options = {}) {
|
|
399
|
-
const supabase = options.supabaseClient || getSupabaseClient();
|
|
400
|
-
const cookies = safeRequestCookies(request);
|
|
401
|
-
const accessToken = String(cookies[ACCESS_TOKEN_COOKIE] || "").trim();
|
|
402
|
-
let user = null;
|
|
403
|
-
let session = null;
|
|
404
|
-
|
|
405
|
-
async function getUserByAccessToken(token) {
|
|
406
|
-
if (!token) {
|
|
407
|
-
return null;
|
|
408
|
-
}
|
|
409
|
-
|
|
410
|
-
try {
|
|
411
|
-
const userResponse = await supabase.auth.getUser(token);
|
|
412
|
-
if (!userResponse.error && userResponse.data?.user) {
|
|
413
|
-
return userResponse.data.user;
|
|
414
|
-
}
|
|
415
|
-
|
|
416
|
-
if (userResponse.error && isTransientSupabaseError(userResponse.error)) {
|
|
417
|
-
throw mapAuthError(userResponse.error, 503);
|
|
418
|
-
}
|
|
419
|
-
} catch (error) {
|
|
420
|
-
if (isTransientSupabaseError(error)) {
|
|
421
|
-
throw mapAuthError(error, 503);
|
|
422
|
-
}
|
|
423
|
-
}
|
|
424
|
-
|
|
425
|
-
return null;
|
|
426
|
-
}
|
|
427
|
-
|
|
428
|
-
if (accessToken) {
|
|
429
|
-
user = await getUserByAccessToken(accessToken);
|
|
430
|
-
}
|
|
431
|
-
|
|
432
|
-
if (!user) {
|
|
433
|
-
const sessionResponse = await setSessionFromRequestCookies(request, {
|
|
434
|
-
supabaseClient: supabase
|
|
435
|
-
});
|
|
436
|
-
user = sessionResponse.data.user || null;
|
|
437
|
-
session = sessionResponse.data.session || null;
|
|
438
|
-
}
|
|
439
|
-
|
|
440
|
-
const currentAccessToken = String(session?.access_token || accessToken || "").trim();
|
|
441
|
-
const explicitUser = await getUserByAccessToken(currentAccessToken);
|
|
442
|
-
if (explicitUser) {
|
|
443
|
-
user = explicitUser;
|
|
444
|
-
}
|
|
445
|
-
|
|
446
|
-
if (!user) {
|
|
447
|
-
throw createAuthError(AUTH_TEXTS.sessionRequired);
|
|
448
|
-
}
|
|
449
|
-
|
|
450
|
-
return {
|
|
451
|
-
session,
|
|
452
|
-
user
|
|
453
|
-
};
|
|
454
|
-
}
|
|
455
|
-
|
|
456
|
-
function resolveRequestSessionTokens(request) {
|
|
457
|
-
const cookies = safeRequestCookies(request);
|
|
458
|
-
return {
|
|
459
|
-
accessToken: String(cookies[ACCESS_TOKEN_COOKIE] || ""),
|
|
460
|
-
refreshToken: String(cookies[REFRESH_TOKEN_COOKIE] || "")
|
|
461
|
-
};
|
|
462
|
-
}
|
|
463
|
-
|
|
464
|
-
async function authenticateDevAuthRequestFromCookies(request, tokens = resolveRequestSessionTokens(request)) {
|
|
465
|
-
const devAuthResult = await authenticateDevAuthRequest(
|
|
466
|
-
{
|
|
467
|
-
request,
|
|
468
|
-
accessToken: tokens.accessToken,
|
|
469
|
-
refreshToken: tokens.refreshToken
|
|
470
|
-
},
|
|
471
|
-
{
|
|
472
|
-
config: devAuthConfig,
|
|
473
|
-
userProfilesRepository
|
|
474
|
-
}
|
|
475
|
-
);
|
|
476
|
-
|
|
477
|
-
if (!devAuthResult || devAuthResult.authenticated !== true) {
|
|
478
|
-
return devAuthResult;
|
|
479
|
-
}
|
|
480
|
-
|
|
481
|
-
return withActor({
|
|
482
|
-
...devAuthResult,
|
|
483
|
-
profile: requireAuthenticatedProfile(devAuthResult.profile, {
|
|
484
|
-
context: "dev auth profile"
|
|
485
|
-
})
|
|
486
|
-
});
|
|
487
|
-
}
|
|
488
|
-
|
|
489
|
-
function writeSessionCookies(reply, session) {
|
|
490
|
-
const accessToken = String(session?.access_token || "");
|
|
491
|
-
const refreshToken = String(session?.refresh_token || "");
|
|
492
|
-
if (!accessToken || !refreshToken) {
|
|
493
|
-
return;
|
|
494
|
-
}
|
|
495
|
-
|
|
496
|
-
const sessionAccessMaxAge = Number.isFinite(Number(session?.expires_in)) ? Number(session.expires_in) : 3600;
|
|
497
|
-
const purpose = String(session?.purpose || "normal").trim();
|
|
498
|
-
const accessCookieName = purpose === "recovery" ? RECOVERY_ACCESS_TOKEN_COOKIE : ACCESS_TOKEN_COOKIE;
|
|
499
|
-
const refreshCookieName = purpose === "recovery" ? RECOVERY_REFRESH_TOKEN_COOKIE : REFRESH_TOKEN_COOKIE;
|
|
500
|
-
const cookieMaxAge = purpose === "recovery"
|
|
501
|
-
? Math.floor(sessionAccessMaxAge)
|
|
502
|
-
: Math.max(Math.floor(sessionAccessMaxAge), PERSISTENT_SESSION_COOKIE_MAX_AGE_SECONDS);
|
|
503
|
-
|
|
504
|
-
reply.setCookie(accessCookieName, accessToken, cookieOptions(isProduction, cookieMaxAge));
|
|
505
|
-
reply.setCookie(refreshCookieName, refreshToken, cookieOptions(isProduction, cookieMaxAge));
|
|
506
|
-
}
|
|
507
|
-
|
|
508
|
-
function clearSessionCookies(reply) {
|
|
509
|
-
for (const clearOptions of cookieClearOptions(isProduction)) {
|
|
510
|
-
// A __Host- cookie only exists at Path=/.
|
|
511
|
-
if (clearOptions.path === "/" || !isProduction) {
|
|
512
|
-
reply.clearCookie(ACCESS_TOKEN_COOKIE, clearOptions);
|
|
513
|
-
reply.clearCookie(REFRESH_TOKEN_COOKIE, clearOptions);
|
|
514
|
-
reply.clearCookie(RECOVERY_ACCESS_TOKEN_COOKIE, clearOptions);
|
|
515
|
-
reply.clearCookie(RECOVERY_REFRESH_TOKEN_COOKIE, clearOptions);
|
|
516
|
-
}
|
|
517
|
-
}
|
|
518
|
-
}
|
|
519
|
-
|
|
520
|
-
async function logout(request) {
|
|
521
|
-
const cookies = safeRequestCookies(request);
|
|
522
|
-
const accessToken = String(cookies[ACCESS_TOKEN_COOKIE] || "").trim();
|
|
523
|
-
const refreshToken = String(cookies[REFRESH_TOKEN_COOKIE] || "").trim();
|
|
524
|
-
|
|
525
|
-
if (!accessToken && !refreshToken) {
|
|
526
|
-
return {
|
|
527
|
-
ok: true,
|
|
528
|
-
clearSession: true
|
|
529
|
-
};
|
|
530
|
-
}
|
|
531
|
-
|
|
532
|
-
if (isDevAuthToken(accessToken) || isDevAuthToken(refreshToken)) {
|
|
533
|
-
return {
|
|
534
|
-
ok: true,
|
|
535
|
-
clearSession: true
|
|
536
|
-
};
|
|
537
|
-
}
|
|
538
64
|
|
|
539
|
-
|
|
540
|
-
|
|
541
|
-
|
|
542
|
-
|
|
543
|
-
|
|
544
|
-
|
|
545
|
-
|
|
546
|
-
scope: "local"
|
|
547
|
-
});
|
|
548
|
-
|
|
549
|
-
if (response.error) {
|
|
550
|
-
throw mapAuthError(response.error, Number(response.error?.status || 400));
|
|
551
|
-
}
|
|
552
|
-
|
|
553
|
-
return {
|
|
554
|
-
ok: true,
|
|
555
|
-
clearSession: true
|
|
556
|
-
};
|
|
557
|
-
}
|
|
558
|
-
|
|
559
|
-
function requireSynchronizedProfile(profile) {
|
|
560
|
-
try {
|
|
561
|
-
return requireAuthenticatedProfile(profile, {
|
|
562
|
-
context: "authentication profile"
|
|
563
|
-
});
|
|
564
|
-
} catch (error) {
|
|
565
|
-
if (error instanceof AppError) {
|
|
566
|
-
throw new AppError(500, "Authentication profile synchronization failed. Please retry.", {
|
|
567
|
-
code: "auth.supabase.profile.syncFailed"
|
|
568
|
-
});
|
|
569
|
-
}
|
|
570
|
-
throw error;
|
|
571
|
-
}
|
|
572
|
-
}
|
|
573
|
-
|
|
574
|
-
function buildNormalizedIdentityKey(identityLike) {
|
|
575
|
-
const source = identityLike && typeof identityLike === "object" ? identityLike : {};
|
|
576
|
-
const authProvider = normalizeAuthProviderId(source.authProvider || authProviderId, {
|
|
577
|
-
fallback: authProviderId
|
|
578
|
-
});
|
|
579
|
-
const authProviderUserSid = normalizeProviderUserId(source.authProviderUserSid);
|
|
580
|
-
|
|
581
|
-
if (!authProviderUserSid) {
|
|
582
|
-
throw new TypeError("Profile identity is missing required fields.");
|
|
583
|
-
}
|
|
584
|
-
|
|
585
|
-
return {
|
|
586
|
-
authProvider,
|
|
587
|
-
authProviderUserSid
|
|
588
|
-
};
|
|
589
|
-
}
|
|
65
|
+
const clients = createSupabaseClients(config);
|
|
66
|
+
const profileMirror = createSupabaseProfileMirror({ config, profiles });
|
|
67
|
+
const sessions = createSupabaseSessions({ config, clients, profileMirror, profiles });
|
|
68
|
+
const securityStatus = createSupabaseSecurityStatus({ config, capabilities, sessions, profileMirror, profiles });
|
|
69
|
+
const accountFlows = createSupabaseAccountFlows({ config, clients, sessions, profileMirror, securityStatus });
|
|
70
|
+
const oauthFlows = createSupabaseOAuthFlows({ config, clients, sessions, profileMirror, securityStatus });
|
|
71
|
+
const passwordFlows = createSupabasePasswordFlows({ config, clients, sessions, profileMirror, securityStatus, profiles });
|
|
590
72
|
|
|
591
|
-
function
|
|
592
|
-
|
|
593
|
-
const identity = buildNormalizedIdentityKey(source);
|
|
594
|
-
const email = normalizeEmail(source.email || "");
|
|
595
|
-
const displayName = String(source.displayName || "").trim();
|
|
596
|
-
|
|
597
|
-
if (!email || !displayName) {
|
|
598
|
-
throw new TypeError("Profile identity is missing required fields.");
|
|
599
|
-
}
|
|
600
|
-
|
|
601
|
-
return {
|
|
602
|
-
authProvider: identity.authProvider,
|
|
603
|
-
authProviderUserSid: identity.authProviderUserSid,
|
|
604
|
-
email,
|
|
605
|
-
displayName
|
|
606
|
-
};
|
|
607
|
-
}
|
|
608
|
-
|
|
609
|
-
async function findProfileByIdentity(identityProfile, options = {}) {
|
|
610
|
-
const normalized = buildNormalizedIdentityKey(identityProfile);
|
|
611
|
-
return userProfileSyncService.findByIdentity(
|
|
612
|
-
{
|
|
613
|
-
authProvider: normalized.authProvider,
|
|
614
|
-
authProviderUserSid: normalized.authProviderUserSid
|
|
615
|
-
},
|
|
616
|
-
options
|
|
617
|
-
);
|
|
73
|
+
function getCapabilities() {
|
|
74
|
+
return capabilities;
|
|
618
75
|
}
|
|
619
76
|
|
|
620
77
|
function getSettingsProfileAuthInfo() {
|
|
621
|
-
return {
|
|
622
|
-
emailManagedBy: settingsProfileAuthInfo.emailManagedBy,
|
|
623
|
-
emailChangeFlow: settingsProfileAuthInfo.emailChangeFlow
|
|
624
|
-
};
|
|
625
|
-
}
|
|
626
|
-
|
|
627
|
-
// With syncProfile: false the caller asks only who is signed in, so the
|
|
628
|
-
// existing profile is read instead of synchronized.
|
|
629
|
-
async function syncProfileMirror(nextProfile, { syncProfile = true } = {}) {
|
|
630
|
-
if (!syncProfile) {
|
|
631
|
-
return findProfileByIdentity(nextProfile);
|
|
632
|
-
}
|
|
633
|
-
try {
|
|
634
|
-
const normalized = buildNormalizedIdentityProfile(nextProfile);
|
|
635
|
-
const synchronizedProfile = await userProfileSyncService.syncIdentityProfile(normalized);
|
|
636
|
-
return requireSynchronizedProfile(synchronizedProfile);
|
|
637
|
-
} catch (error) {
|
|
638
|
-
if (String(error?.code || "") === USER_PROFILE_EMAIL_CONFLICT_CODE) {
|
|
639
|
-
throw new AppError(
|
|
640
|
-
409,
|
|
641
|
-
"This email is already registered with another sign-in method. Sign in with that method, then link this provider in Settings > Security.",
|
|
642
|
-
{ code: "auth.supabase.profile.emailConflict" }
|
|
643
|
-
);
|
|
644
|
-
}
|
|
645
|
-
|
|
646
|
-
throw error;
|
|
647
|
-
}
|
|
648
|
-
}
|
|
649
|
-
|
|
650
|
-
async function syncProfileFromSupabaseUser(supabaseUser, fallbackEmail, profileOptions = {}) {
|
|
651
|
-
const supabaseUserId = normalizeProviderUserId(supabaseUser?.id);
|
|
652
|
-
const email = normalizeEmail(supabaseUser?.email || fallbackEmail);
|
|
653
|
-
|
|
654
|
-
if (!supabaseUserId || !email) {
|
|
655
|
-
throw new AppError(500, "Auth provider user payload is missing required fields.", { code: "auth.supabase.profile.payloadIncomplete" });
|
|
656
|
-
}
|
|
657
|
-
|
|
658
|
-
return syncProfileMirror({
|
|
659
|
-
authProvider: authProviderId,
|
|
660
|
-
authProviderUserSid: supabaseUserId,
|
|
661
|
-
email,
|
|
662
|
-
displayName: resolveDisplayName(supabaseUser, email)
|
|
663
|
-
}, profileOptions);
|
|
664
|
-
}
|
|
665
|
-
|
|
666
|
-
function buildActorFromProfile(profile) {
|
|
667
|
-
return normalizeAuthActor(
|
|
668
|
-
{
|
|
669
|
-
provider: profile?.authProvider || authProviderId,
|
|
670
|
-
providerUserId: profile?.authProviderUserSid || profile?.id,
|
|
671
|
-
email: profile?.email,
|
|
672
|
-
displayName: profile?.displayName,
|
|
673
|
-
appUserId: profileProjectionEnabled ? profile?.id : null,
|
|
674
|
-
profileSource: profile?.profileSource || (profileProjectionEnabled ? "users" : "auth-provider")
|
|
675
|
-
},
|
|
676
|
-
{
|
|
677
|
-
provider: authProviderId,
|
|
678
|
-
profileSource: profileProjectionEnabled ? "users" : "auth-provider"
|
|
679
|
-
}
|
|
680
|
-
);
|
|
681
|
-
}
|
|
682
|
-
|
|
683
|
-
function withActor(result) {
|
|
684
|
-
if (!result || typeof result !== "object") {
|
|
685
|
-
return result;
|
|
686
|
-
}
|
|
687
|
-
if (result.authenticated !== true && !result.profile) {
|
|
688
|
-
return result;
|
|
689
|
-
}
|
|
690
|
-
const actor = buildActorFromProfile(result.profile);
|
|
691
|
-
if (!actor) {
|
|
692
|
-
return result;
|
|
693
|
-
}
|
|
694
|
-
const { profile: _profile, ...authResult } = result;
|
|
695
|
-
return normalizeAuthResult({
|
|
696
|
-
...authResult,
|
|
697
|
-
actor
|
|
698
|
-
});
|
|
699
|
-
}
|
|
700
|
-
|
|
701
|
-
function withActorResult(operation) {
|
|
702
|
-
return async (...args) => withActor(await operation(...args));
|
|
703
|
-
}
|
|
704
|
-
|
|
705
|
-
async function syncProfileFromJwtClaims(claims, { syncProfile = true } = {}) {
|
|
706
|
-
const supabaseUserId = normalizeProviderUserId(claims?.sub);
|
|
707
|
-
if (!supabaseUserId) {
|
|
708
|
-
throw new AppError(401, "Token is missing subject claim.", { code: "auth.supabase.token.subjectMissing" });
|
|
709
|
-
}
|
|
710
|
-
|
|
711
|
-
const existing = await findProfileByIdentity({
|
|
712
|
-
authProvider: authProviderId,
|
|
713
|
-
authProviderUserSid: supabaseUserId
|
|
714
|
-
});
|
|
715
|
-
if (!syncProfile) {
|
|
716
|
-
return existing;
|
|
717
|
-
}
|
|
718
|
-
const emailFromToken = normalizeEmail(claims?.email || "");
|
|
719
|
-
|
|
720
|
-
if (!emailFromToken) {
|
|
721
|
-
if (existing) {
|
|
722
|
-
return existing;
|
|
723
|
-
}
|
|
724
|
-
throw new AppError(401, "Token is missing email claim.", { code: "auth.supabase.token.emailMissing" });
|
|
725
|
-
}
|
|
726
|
-
|
|
727
|
-
return syncProfileMirror({
|
|
728
|
-
authProvider: authProviderId,
|
|
729
|
-
authProviderUserSid: supabaseUserId,
|
|
730
|
-
email: emailFromToken,
|
|
731
|
-
displayName: resolveDisplayNameFromClaims(claims, emailFromToken)
|
|
732
|
-
});
|
|
733
|
-
}
|
|
734
|
-
|
|
735
|
-
async function resolvePasswordSignInPolicyForUserId(userId) {
|
|
736
|
-
if (!userSettingsRepository || typeof userSettingsRepository.ensureForUserId !== "function") {
|
|
737
|
-
return {
|
|
738
|
-
passwordSignInEnabled: true,
|
|
739
|
-
passwordSetupRequired: false
|
|
740
|
-
};
|
|
741
|
-
}
|
|
742
|
-
|
|
743
|
-
const settings = await userSettingsRepository.ensureForUserId(userId);
|
|
744
|
-
return {
|
|
745
|
-
passwordSignInEnabled: settings?.passwordSignInEnabled !== false,
|
|
746
|
-
passwordSetupRequired: settings?.passwordSetupRequired === true
|
|
747
|
-
};
|
|
748
|
-
}
|
|
749
|
-
|
|
750
|
-
async function setPasswordSignInEnabledForUserId(userId, enabled, options = {}) {
|
|
751
|
-
if (!userSettingsRepository || typeof userSettingsRepository.updatePasswordSignInEnabled !== "function") {
|
|
752
|
-
throw new AppError(500, "Password sign-in settings repository is not configured.", {
|
|
753
|
-
code: "auth.supabase.config.passwordSettingsMissing"
|
|
754
|
-
});
|
|
755
|
-
}
|
|
756
|
-
|
|
757
|
-
const updated = await userSettingsRepository.updatePasswordSignInEnabled(userId, enabled, options);
|
|
758
|
-
return {
|
|
759
|
-
passwordSignInEnabled: updated.passwordSignInEnabled !== false,
|
|
760
|
-
passwordSetupRequired: updated.passwordSetupRequired === true
|
|
761
|
-
};
|
|
762
|
-
}
|
|
763
|
-
|
|
764
|
-
async function setPasswordSetupRequiredForUserId(userId, required) {
|
|
765
|
-
if (!userSettingsRepository || typeof userSettingsRepository.updatePasswordSetupRequired !== "function") {
|
|
766
|
-
return;
|
|
767
|
-
}
|
|
768
|
-
|
|
769
|
-
await userSettingsRepository.updatePasswordSetupRequired(userId, required);
|
|
770
|
-
}
|
|
771
|
-
|
|
772
|
-
async function resolveCurrentAuthContext(request, options = {}) {
|
|
773
|
-
const current = await resolveCurrentSupabaseUser(request, options);
|
|
774
|
-
const profile = await syncProfileFromSupabaseUser(current.user, current.user?.email || "");
|
|
775
|
-
const passwordSignInPolicy = await resolvePasswordSignInPolicyForUserId(profile.id);
|
|
776
|
-
const authMethodsStatus = buildAuthMethodsStatusFromSupabaseUser(current.user, {
|
|
777
|
-
...passwordSignInPolicy,
|
|
778
|
-
oauthProviders: authOAuthProviders
|
|
779
|
-
});
|
|
780
|
-
|
|
781
|
-
return {
|
|
782
|
-
...current,
|
|
783
|
-
profile,
|
|
784
|
-
passwordSignInEnabled: passwordSignInPolicy.passwordSignInEnabled,
|
|
785
|
-
passwordSetupRequired: passwordSignInPolicy.passwordSetupRequired,
|
|
786
|
-
authMethodsStatus
|
|
787
|
-
};
|
|
788
|
-
}
|
|
789
|
-
|
|
790
|
-
async function resolveDevAuthSecurityStatus(request) {
|
|
791
|
-
const devAuthResult = await authenticateDevAuthRequestFromCookies(request);
|
|
792
|
-
if (!devAuthResult) {
|
|
793
|
-
return null;
|
|
794
|
-
}
|
|
795
|
-
|
|
796
|
-
if (devAuthResult.authenticated !== true) {
|
|
797
|
-
throw createAuthError(AUTH_TEXTS.sessionRequired);
|
|
798
|
-
}
|
|
799
|
-
|
|
800
|
-
const passwordSignInPolicy = await resolvePasswordSignInPolicyForUserId(devAuthResult.actor.id);
|
|
801
|
-
const authMethodsStatus = buildAuthMethodsStatusFromProviderIds([AUTH_METHOD_PASSWORD_PROVIDER], {
|
|
802
|
-
...passwordSignInPolicy,
|
|
803
|
-
oauthProviders: authOAuthProviders
|
|
804
|
-
});
|
|
805
|
-
|
|
806
|
-
return buildProviderSecurityStatus(authMethodsStatus);
|
|
807
|
-
}
|
|
808
|
-
|
|
809
|
-
const { register, resendRegisterConfirmation, login, requestOtpLogin, verifyOtpLogin, updateDisplayName } = createAccountFlows({
|
|
810
|
-
ensureConfigured,
|
|
811
|
-
validationError,
|
|
812
|
-
getSupabaseClient,
|
|
813
|
-
displayNameFromEmail,
|
|
814
|
-
mapAuthError,
|
|
815
|
-
syncProfileFromSupabaseUser,
|
|
816
|
-
resolvePasswordSignInPolicyForUserId,
|
|
817
|
-
otpLoginRedirectUrl,
|
|
818
|
-
buildOtpLoginRedirectUrl,
|
|
819
|
-
appPublicUrl,
|
|
820
|
-
isTransientSupabaseError,
|
|
821
|
-
isUserNotFoundLikeAuthError,
|
|
822
|
-
mapOtpVerifyError,
|
|
823
|
-
setSessionFromRequestCookies,
|
|
824
|
-
mapProfileUpdateError,
|
|
825
|
-
normalizeReturnToPath: normalizeAuthReturnToTarget
|
|
826
|
-
});
|
|
827
|
-
|
|
828
|
-
const { oauthStart, startProviderLink, oauthComplete, unlinkProvider } = createOauthFlows({
|
|
829
|
-
ensureConfigured,
|
|
830
|
-
normalizeOAuthProviderInput,
|
|
831
|
-
normalizeReturnToPath: normalizeAuthReturnToTarget,
|
|
832
|
-
buildOAuthLoginRedirectUrl: buildOAuthLoginRedirectUrlWithCatalog,
|
|
833
|
-
appPublicUrl,
|
|
834
|
-
authOAuthDefaultProvider,
|
|
835
|
-
resolveOAuthProviderQueryParams: resolveOAuthProviderQueryParamsForProvider,
|
|
836
|
-
getSupabaseClient,
|
|
837
|
-
mapAuthError,
|
|
838
|
-
setSessionFromRequestCookies,
|
|
839
|
-
buildOAuthLinkRedirectUrl: buildOAuthLinkRedirectUrlWithCatalog,
|
|
840
|
-
validationError,
|
|
841
|
-
mapOAuthCallbackError,
|
|
842
|
-
mapRecoveryError,
|
|
843
|
-
syncProfileFromSupabaseUser,
|
|
844
|
-
resolveCurrentAuthContext,
|
|
845
|
-
buildOAuthMethodId,
|
|
846
|
-
findAuthMethodById,
|
|
847
|
-
findLinkedIdentityByProvider,
|
|
848
|
-
buildSecurityStatusFromAuthMethodsStatus: buildProviderSecurityStatus
|
|
849
|
-
});
|
|
850
|
-
|
|
851
|
-
const {
|
|
852
|
-
requestPasswordReset,
|
|
853
|
-
completePasswordRecovery,
|
|
854
|
-
resetPassword,
|
|
855
|
-
changePassword,
|
|
856
|
-
setPasswordSignInEnabled,
|
|
857
|
-
signOutOtherSessions,
|
|
858
|
-
getSecurityStatus
|
|
859
|
-
} = createPasswordSecurityFlows({
|
|
860
|
-
ensureConfigured,
|
|
861
|
-
validationError,
|
|
862
|
-
getSupabaseClient,
|
|
863
|
-
passwordResetRedirectUrl,
|
|
864
|
-
mapAuthError,
|
|
865
|
-
mapRecoveryError,
|
|
866
|
-
syncProfileFromSupabaseUser,
|
|
867
|
-
setSessionFromRequestCookies,
|
|
868
|
-
setRecoverySessionFromRequestCookies,
|
|
869
|
-
resolvePasswordSignInPolicyForUserId,
|
|
870
|
-
mapPasswordUpdateError,
|
|
871
|
-
setPasswordSetupRequiredForUserId,
|
|
872
|
-
normalizeEmail,
|
|
873
|
-
createStatelessSupabaseClient,
|
|
874
|
-
mapCurrentPasswordError,
|
|
875
|
-
resolveCurrentAuthContext,
|
|
876
|
-
findAuthMethodById,
|
|
877
|
-
authMethodPasswordId: AUTH_METHOD_PASSWORD_ID,
|
|
878
|
-
buildDisabledPasswordSecret,
|
|
879
|
-
setPasswordSignInEnabledForUserId,
|
|
880
|
-
buildAuthMethodsStatusFromSupabaseUser: (user, statusOptions = {}) =>
|
|
881
|
-
buildAuthMethodsStatusFromSupabaseUser(user, {
|
|
882
|
-
...statusOptions,
|
|
883
|
-
oauthProviders: authOAuthProviders
|
|
884
|
-
}),
|
|
885
|
-
buildSecurityStatusFromAuthMethodsStatus: buildProviderSecurityStatus,
|
|
886
|
-
authMethodPasswordProvider: AUTH_METHOD_PASSWORD_PROVIDER,
|
|
887
|
-
buildAuthMethodsStatusFromProviderIds: (providerIds, statusOptions = {}) =>
|
|
888
|
-
buildAuthMethodsStatusFromProviderIds(providerIds, {
|
|
889
|
-
...statusOptions,
|
|
890
|
-
oauthProviders: authOAuthProviders
|
|
891
|
-
}),
|
|
892
|
-
resolveDevAuthSecurityStatus
|
|
893
|
-
});
|
|
894
|
-
|
|
895
|
-
async function authenticateRequest(request, { syncProfile = true, refreshSession = true } = {}) {
|
|
896
|
-
const { accessToken, refreshToken } = resolveRequestSessionTokens(request);
|
|
897
|
-
// Without sync, a login whose app profile does not exist yet is not signed in.
|
|
898
|
-
const signedIn = (profile, session = null) => (profile
|
|
899
|
-
? withActor({ authenticated: true, profile, clearSession: false, session, transientFailure: false })
|
|
900
|
-
: { authenticated: false, clearSession: false, session: null, transientFailure: false });
|
|
901
|
-
|
|
902
|
-
const devAuthResult = await authenticateDevAuthRequestFromCookies(request, { accessToken, refreshToken });
|
|
903
|
-
if (devAuthResult) {
|
|
904
|
-
return devAuthResult;
|
|
905
|
-
}
|
|
906
|
-
|
|
907
|
-
if (!accessToken && !refreshToken) {
|
|
908
|
-
return {
|
|
909
|
-
authenticated: false,
|
|
910
|
-
clearSession: false,
|
|
911
|
-
session: null,
|
|
912
|
-
transientFailure: false
|
|
913
|
-
};
|
|
914
|
-
}
|
|
915
|
-
|
|
916
|
-
ensureConfigured();
|
|
917
|
-
|
|
918
|
-
if (accessToken) {
|
|
919
|
-
const verification = await verifyAccessToken(accessToken);
|
|
920
|
-
|
|
921
|
-
if (verification.status === "valid") {
|
|
922
|
-
return signedIn(await syncProfileFromJwtClaims(verification.payload, { syncProfile }));
|
|
923
|
-
}
|
|
924
|
-
|
|
925
|
-
if (verification.status === "transient") {
|
|
926
|
-
return {
|
|
927
|
-
authenticated: false,
|
|
928
|
-
clearSession: false,
|
|
929
|
-
session: null,
|
|
930
|
-
transientFailure: true
|
|
931
|
-
};
|
|
932
|
-
}
|
|
933
|
-
|
|
934
|
-
if (verification.status === "invalid") {
|
|
935
|
-
const supabaseVerification = await verifyAccessTokenViaSupabase(accessToken, { syncProfile });
|
|
936
|
-
if (supabaseVerification.status === "valid") {
|
|
937
|
-
return signedIn(supabaseVerification.profile);
|
|
938
|
-
}
|
|
939
|
-
|
|
940
|
-
if (supabaseVerification.status === "transient") {
|
|
941
|
-
return {
|
|
942
|
-
authenticated: false,
|
|
943
|
-
clearSession: false,
|
|
944
|
-
session: null,
|
|
945
|
-
transientFailure: true
|
|
946
|
-
};
|
|
947
|
-
}
|
|
948
|
-
}
|
|
949
|
-
}
|
|
950
|
-
|
|
951
|
-
if (!refreshToken) {
|
|
952
|
-
return {
|
|
953
|
-
authenticated: false,
|
|
954
|
-
clearSession: true,
|
|
955
|
-
session: null,
|
|
956
|
-
transientFailure: false
|
|
957
|
-
};
|
|
958
|
-
}
|
|
959
|
-
|
|
960
|
-
// A caller that cannot store a refreshed session, such as a realtime socket,
|
|
961
|
-
// must not spend the single-use refresh token; it is told to refresh first.
|
|
962
|
-
if (!refreshSession) {
|
|
963
|
-
return {
|
|
964
|
-
authenticated: false,
|
|
965
|
-
refreshRequired: true,
|
|
966
|
-
clearSession: false,
|
|
967
|
-
session: null,
|
|
968
|
-
transientFailure: false
|
|
969
|
-
};
|
|
970
|
-
}
|
|
971
|
-
|
|
972
|
-
const supabase = getSupabaseClient();
|
|
973
|
-
let refreshResponse;
|
|
974
|
-
try {
|
|
975
|
-
refreshResponse = await supabase.auth.refreshSession({ refresh_token: refreshToken });
|
|
976
|
-
/* c8 ignore next 17 -- defensive: refreshSession usually resolves with { error } for auth/transport issues. */
|
|
977
|
-
} catch (error) {
|
|
978
|
-
if (isTransientSupabaseError(error)) {
|
|
979
|
-
return {
|
|
980
|
-
authenticated: false,
|
|
981
|
-
clearSession: false,
|
|
982
|
-
session: null,
|
|
983
|
-
transientFailure: true
|
|
984
|
-
};
|
|
985
|
-
}
|
|
986
|
-
|
|
987
|
-
return {
|
|
988
|
-
authenticated: false,
|
|
989
|
-
clearSession: true,
|
|
990
|
-
session: null,
|
|
991
|
-
transientFailure: false
|
|
992
|
-
};
|
|
993
|
-
}
|
|
994
|
-
|
|
995
|
-
if (refreshResponse.error) {
|
|
996
|
-
if (isTransientSupabaseError(refreshResponse.error)) {
|
|
997
|
-
return {
|
|
998
|
-
authenticated: false,
|
|
999
|
-
clearSession: false,
|
|
1000
|
-
session: null,
|
|
1001
|
-
transientFailure: true
|
|
1002
|
-
};
|
|
1003
|
-
}
|
|
1004
|
-
|
|
1005
|
-
return {
|
|
1006
|
-
authenticated: false,
|
|
1007
|
-
clearSession: true,
|
|
1008
|
-
session: null,
|
|
1009
|
-
transientFailure: false
|
|
1010
|
-
};
|
|
1011
|
-
}
|
|
1012
|
-
|
|
1013
|
-
if (!refreshResponse.data?.session || !refreshResponse.data?.user) {
|
|
1014
|
-
return {
|
|
1015
|
-
authenticated: false,
|
|
1016
|
-
clearSession: true,
|
|
1017
|
-
session: null,
|
|
1018
|
-
transientFailure: false
|
|
1019
|
-
};
|
|
1020
|
-
}
|
|
1021
|
-
|
|
1022
|
-
const profile = await syncProfileFromSupabaseUser(refreshResponse.data.user, refreshResponse.data.user.email, { syncProfile });
|
|
1023
|
-
return signedIn(profile, refreshResponse.data.session);
|
|
1024
|
-
}
|
|
1025
|
-
|
|
1026
|
-
function hasAccessTokenCookie(request) {
|
|
1027
|
-
const cookies = safeRequestCookies(request);
|
|
1028
|
-
return Boolean(cookies[ACCESS_TOKEN_COOKIE] || cookies[RECOVERY_ACCESS_TOKEN_COOKIE]);
|
|
1029
|
-
}
|
|
1030
|
-
|
|
1031
|
-
function hasSessionCookie(request) {
|
|
1032
|
-
const cookies = safeRequestCookies(request);
|
|
1033
|
-
return Boolean(
|
|
1034
|
-
cookies[ACCESS_TOKEN_COOKIE] ||
|
|
1035
|
-
cookies[REFRESH_TOKEN_COOKIE] ||
|
|
1036
|
-
cookies[RECOVERY_ACCESS_TOKEN_COOKIE] ||
|
|
1037
|
-
cookies[RECOVERY_REFRESH_TOKEN_COOKIE]
|
|
1038
|
-
);
|
|
78
|
+
return { ...SETTINGS_PROFILE_AUTH_INFO };
|
|
1039
79
|
}
|
|
1040
80
|
|
|
1041
81
|
function getOAuthProviderCatalog() {
|
|
1042
|
-
return
|
|
1043
|
-
}
|
|
1044
|
-
|
|
1045
|
-
function getCapabilities() {
|
|
1046
|
-
return capabilities;
|
|
82
|
+
return config.oauthCatalog;
|
|
1047
83
|
}
|
|
1048
84
|
|
|
1049
85
|
function isDevAuthBootstrapEnabled() {
|
|
1050
|
-
return
|
|
86
|
+
return config.devAuth.enabled === true;
|
|
1051
87
|
}
|
|
1052
88
|
|
|
1053
|
-
async function devLoginAs(
|
|
1054
|
-
ensureDevAuthExchangeAvailable(
|
|
89
|
+
async function devLoginAs(input, request) {
|
|
90
|
+
ensureDevAuthExchangeAvailable(config.devAuth, request);
|
|
1055
91
|
const rawProfile = await resolveDevAuthProfile(input, {
|
|
1056
|
-
userProfilesRepository
|
|
1057
|
-
validationError
|
|
92
|
+
userProfilesRepository: profiles.userProfilesRepository
|
|
1058
93
|
});
|
|
1059
94
|
const profile = requireAuthenticatedProfile(rawProfile, {
|
|
1060
95
|
context: "dev auth profile"
|
|
1061
96
|
});
|
|
1062
|
-
return withActor({
|
|
97
|
+
return profileMirror.withActor({
|
|
1063
98
|
profile,
|
|
1064
|
-
session: await createDevAuthSession(profile,
|
|
99
|
+
session: await createDevAuthSession(profile, config.devAuth)
|
|
1065
100
|
});
|
|
1066
101
|
}
|
|
1067
102
|
|
|
1068
|
-
return {
|
|
103
|
+
return Object.freeze({
|
|
1069
104
|
getCapabilities,
|
|
1070
|
-
register: withActorResult(register),
|
|
1071
|
-
resendRegisterConfirmation,
|
|
1072
|
-
login: withActorResult(login),
|
|
1073
|
-
requestOtpLogin,
|
|
1074
|
-
verifyOtpLogin: withActorResult(verifyOtpLogin),
|
|
1075
|
-
oauthStart,
|
|
1076
|
-
oauthComplete: withActorResult(oauthComplete),
|
|
1077
|
-
startProviderLink,
|
|
1078
|
-
requestPasswordReset,
|
|
1079
|
-
completePasswordRecovery: withActorResult(completePasswordRecovery),
|
|
1080
|
-
resetPassword,
|
|
1081
|
-
updateDisplayName: withActorResult(updateDisplayName),
|
|
1082
|
-
changePassword: withActorResult(changePassword),
|
|
1083
|
-
setPasswordSignInEnabled
|
|
1084
|
-
|
|
1085
|
-
|
|
1086
|
-
|
|
1087
|
-
|
|
105
|
+
register: profileMirror.withActorResult(accountFlows.register),
|
|
106
|
+
resendRegisterConfirmation: accountFlows.resendRegisterConfirmation,
|
|
107
|
+
login: profileMirror.withActorResult(accountFlows.login),
|
|
108
|
+
requestOtpLogin: accountFlows.requestOtpLogin,
|
|
109
|
+
verifyOtpLogin: profileMirror.withActorResult(accountFlows.verifyOtpLogin),
|
|
110
|
+
oauthStart: oauthFlows.oauthStart,
|
|
111
|
+
oauthComplete: profileMirror.withActorResult(oauthFlows.oauthComplete),
|
|
112
|
+
startProviderLink: oauthFlows.startProviderLink,
|
|
113
|
+
requestPasswordReset: passwordFlows.requestPasswordReset,
|
|
114
|
+
completePasswordRecovery: profileMirror.withActorResult(passwordFlows.completePasswordRecovery),
|
|
115
|
+
resetPassword: passwordFlows.resetPassword,
|
|
116
|
+
updateDisplayName: profileMirror.withActorResult(accountFlows.updateDisplayName),
|
|
117
|
+
changePassword: profileMirror.withActorResult(passwordFlows.changePassword),
|
|
118
|
+
// readable-check: allow setter-seam - not a slot: setPasswordSignInEnabled is an auth.service operation
|
|
119
|
+
setPasswordSignInEnabled: passwordFlows.setPasswordSignInEnabled,
|
|
120
|
+
unlinkProvider: oauthFlows.unlinkProvider,
|
|
121
|
+
signOutOtherSessions: sessions.signOutOtherSessions,
|
|
122
|
+
logout: sessions.logout,
|
|
123
|
+
getSecurityStatus: securityStatus.getSecurityStatus,
|
|
1088
124
|
getSettingsProfileAuthInfo,
|
|
1089
125
|
getOAuthProviderCatalog,
|
|
1090
126
|
isDevAuthBootstrapEnabled,
|
|
1091
127
|
devLoginAs,
|
|
1092
|
-
authenticateRequest,
|
|
1093
|
-
hasAccessTokenCookie,
|
|
1094
|
-
hasSessionCookie,
|
|
1095
|
-
writeSessionCookies,
|
|
1096
|
-
clearSessionCookies
|
|
1097
|
-
};
|
|
128
|
+
authenticateRequest: sessions.authenticateRequest,
|
|
129
|
+
hasAccessTokenCookie: sessions.hasAccessTokenCookie,
|
|
130
|
+
hasSessionCookie: sessions.hasSessionCookie,
|
|
131
|
+
writeSessionCookies: sessions.writeSessionCookies,
|
|
132
|
+
clearSessionCookies: sessions.clearSessionCookies
|
|
133
|
+
});
|
|
1098
134
|
}
|
|
1099
135
|
|
|
1100
|
-
|
|
1101
|
-
displayNameFromEmail,
|
|
1102
|
-
resolveDisplayName,
|
|
1103
|
-
resolveDisplayNameFromClaims,
|
|
1104
|
-
isTransientAuthMessage,
|
|
1105
|
-
isTransientSupabaseError,
|
|
1106
|
-
mapAuthError,
|
|
1107
|
-
validationError,
|
|
1108
|
-
isUserNotFoundLikeAuthError,
|
|
1109
|
-
mapRecoveryError,
|
|
1110
|
-
mapPasswordUpdateError,
|
|
1111
|
-
mapOtpVerifyError,
|
|
1112
|
-
mapProfileUpdateError,
|
|
1113
|
-
mapCurrentPasswordError,
|
|
1114
|
-
parseHttpUrl,
|
|
1115
|
-
buildPasswordResetRedirectUrl,
|
|
1116
|
-
buildOtpLoginRedirectUrl,
|
|
1117
|
-
normalizeOAuthIntent,
|
|
1118
|
-
normalizeReturnToPath,
|
|
1119
|
-
buildOAuthRedirectUrl,
|
|
1120
|
-
buildOAuthLoginRedirectUrl,
|
|
1121
|
-
buildOAuthLinkRedirectUrl,
|
|
1122
|
-
normalizeOAuthProviderInput: normalizeOAuthProviderInputFromCatalog,
|
|
1123
|
-
mapOAuthCallbackError,
|
|
1124
|
-
resolveSupabaseOAuthProviderCatalog,
|
|
1125
|
-
resolveOAuthProviderQueryParams,
|
|
1126
|
-
buildOAuthProviderCatalogResponse,
|
|
1127
|
-
normalizeIdentityProviderId,
|
|
1128
|
-
collectProviderIdsFromSupabaseUser,
|
|
1129
|
-
buildAuthMethodsStatusFromProviderIds,
|
|
1130
|
-
buildAuthMethodsStatusFromSupabaseUser,
|
|
1131
|
-
buildSecurityStatusFromAuthMethodsStatus,
|
|
1132
|
-
findAuthMethodById,
|
|
1133
|
-
findLinkedIdentityByProvider,
|
|
1134
|
-
safeRequestCookies,
|
|
1135
|
-
cookieOptions,
|
|
1136
|
-
cookieClearOptions,
|
|
1137
|
-
isExpiredJwtError,
|
|
1138
|
-
classifyJwtVerifyError
|
|
1139
|
-
};
|
|
1140
|
-
|
|
1141
|
-
export { createService, __testables };
|
|
136
|
+
export { createSupabaseAuthService };
|