@authfn/social-oauth 0.1.1

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/dist/index.js ADDED
@@ -0,0 +1,1681 @@
1
+ import { randomBytes } from 'node:crypto';
2
+ import { createRemoteJWKSet, jwtVerify } from 'jose';
3
+ import { createOAuthFlowService } from '@superfunctions/oauth-flow';
4
+ import { assertCallbackStateMatches, consumeStateOrThrow, generateNonce, generateStateId } from '@superfunctions/oauth-core';
5
+ import { DefaultOAuthTokenHttpClient } from '@superfunctions/oauth-http';
6
+ import { DbAdapterOAuthStateStore, DbAdapterTokenVault, getOAuthStorageTableDefinitions } from '@superfunctions/oauth-storage';
7
+ import { createDefaultProviderPolicyRegistry, getOAuthProviderDescriptor } from '@superfunctions/oauth-providers';
8
+ import { assertValidCsrf, issueSession, requireCookieSession } from 'authfn/core/sessions';
9
+ import { issueSessionCookies } from 'authfn/core/cookies';
10
+ import { resolveEnvironment } from 'authfn/core/environment';
11
+ import { beginTwoFactorChallenge, createPendingTwoFactorResponse, getTwoFactorPluginConfig } from 'authfn/core/two-factor';
12
+ import { buildOAuthAccountProfile, deleteOAuthAccountByConnectionId, findOAuthAccountByProviderAccountId, requireOAuthAccountForUser, upsertOAuthAccount } from 'authfn/core/oauth-accounts';
13
+ import { AuthFnConflictError, AuthFnError, AuthFnOAuthCallbackInvalidError, AuthFnOAuthProviderUnsupportedError, AuthFnPluginAbortedError, AuthFnRedirectUriDisallowedError, AuthFnValidationError, toAuthFnError } from 'authfn/core/errors';
14
+ import { createUser, findUserById, findUserByPrimaryEmail } from 'authfn/core/users';
15
+ import { createAuthFnRouteMeta } from 'authfn/http/router';
16
+ import { jsonSuccess, resolveRequestId } from 'authfn/http/envelopes';
17
+ import { emitAuthEvent } from 'authfn/core/observability';
18
+ import { createOAuthTokenDiagnosticFetcher } from './oauth-support.js';
19
+ import { allowsOAuthLinkByVerifiedEmail, emitAccountLinkedEvent, emitAccountLinkingConflictEvent } from 'authfn/core/account-linking';
20
+ import { getMultiRegionPluginConfig, unregisterRegionLookupForIdentifier } from 'authfn/core/regions';
21
+ import { readPluginRuntimeConfig } from 'authfn/core/plugin-runtime';
22
+ export { createAppleClientSecretResolver, createOAuthTokenDiagnosticFetcher } from './oauth-support.js';
23
+ const SOCIAL_PROVIDER_METHODS = {
24
+ google: 'oauth-google',
25
+ apple: 'oauth-apple',
26
+ github: 'oauth-github'
27
+ };
28
+ const CALLBACK_METADATA_MODE = 'callbackMode';
29
+ const CALLBACK_METADATA_HANDOFF = 'handoffMode';
30
+ const APPLE_JWKS = createRemoteJWKSet(new URL('https://appleid.apple.com/auth/keys'));
31
+ export function authFnSocialOAuthPlugin(config = {}) {
32
+ return {
33
+ name: 'socialOAuth',
34
+ schema: () => createSocialSchema(config),
35
+ routes: (ctx) => createSocialRoutes(ctx, config)
36
+ };
37
+ }
38
+ function createSocialSchema(config) {
39
+ return [
40
+ ...createOAuthSharedSchemas(),
41
+ ...(config.schema ?? [createOAuthAccountsSchema()])
42
+ ];
43
+ }
44
+ function createSocialRoutes(ctx, schemaConfig) {
45
+ const config = {
46
+ defaultHandoffMode: schemaConfig.defaultHandoffMode,
47
+ providers: {},
48
+ ...readPluginRuntimeConfig(ctx, 'socialOAuth')
49
+ };
50
+ const routes = [
51
+ {
52
+ method: 'POST',
53
+ path: '/social/start',
54
+ meta: createAuthFnRouteMeta('startSocialSignIn', 'Start social OAuth sign-in', {
55
+ mode: 'none'
56
+ }),
57
+ handler: async (request) => {
58
+ const runtime = await resolveEnvironment(ctx.config, request);
59
+ const body = await request.json();
60
+ const providerId = normalizeProviderId(body.provider);
61
+ const callbackUri = buildCallbackUri(runtime.baseUrl, ctx.basePath, providerId);
62
+ const providerSettings = resolveProviderSettings(ctx.config, config, runtime, providerId, callbackUri);
63
+ const hookInput = await runBeforeOAuthStart(ctx, request, runtime, {
64
+ provider: providerId,
65
+ returnTo: body.returnTo,
66
+ callbackMode: body.callbackMode ?? inferCallbackMode(body.returnTo),
67
+ handoffMode: body.handoffMode
68
+ ?? inferHandoffMode(body.returnTo, body.callbackMode ?? inferCallbackMode(body.returnTo), config.defaultHandoffMode)
69
+ });
70
+ const callbackMode = normalizeCallbackMode(readOptionalString(hookInput.callbackMode) ?? body.callbackMode ?? inferCallbackMode(body.returnTo));
71
+ const returnTo = readOptionalString(hookInput.returnTo) ?? body.returnTo;
72
+ const handoffMode = normalizeHandoffMode(readOptionalString(hookInput.handoffMode)
73
+ ?? body.handoffMode
74
+ ?? inferHandoffMode(returnTo, callbackMode, config.defaultHandoffMode));
75
+ assertAllowedReturnTarget(providerSettings, returnTo, callbackMode);
76
+ const requestId = resolveRequestId(request);
77
+ const flowService = createSocialFlowService(ctx.config, ctx.hooks, config, request, runtime, providerId);
78
+ const result = await flowService.start({
79
+ providerId,
80
+ redirectUri: callbackUri,
81
+ scopes: await authorizeScopes(providerSettings, requestId),
82
+ subject: {
83
+ kind: 'browser-auth',
84
+ intentId: createIdentifier('intent'),
85
+ regionId: runtime.regionId,
86
+ returnTo,
87
+ metadata: {
88
+ [CALLBACK_METADATA_MODE]: callbackMode,
89
+ [CALLBACK_METADATA_HANDOFF]: handoffMode
90
+ }
91
+ },
92
+ requestId
93
+ });
94
+ await emitAuthEvent(ctx.config, {
95
+ type: 'authfn.oauth.started',
96
+ requestId,
97
+ provider: providerId,
98
+ regionId: runtime.regionId,
99
+ outcome: 'started',
100
+ metadata: {
101
+ stateId: result.stateId,
102
+ callbackMode,
103
+ handoffMode,
104
+ returnTo
105
+ }
106
+ });
107
+ return jsonSuccess(request, {
108
+ provider: providerId,
109
+ redirectTo: result.authorizationUrl,
110
+ stateId: result.stateId,
111
+ expiresAt: result.expiresAt
112
+ });
113
+ }
114
+ },
115
+ {
116
+ method: 'GET',
117
+ path: '/social/callback/:provider',
118
+ meta: createAuthFnRouteMeta('completeSocialSignIn', 'Complete social OAuth sign-in', {
119
+ mode: 'none'
120
+ }),
121
+ handler: async (request, context) => {
122
+ const providerId = normalizeProviderId(context.params.provider);
123
+ const runtime = await resolveEnvironment(ctx.config, request);
124
+ const callbackUri = buildCallbackUri(runtime.baseUrl, ctx.basePath, providerId);
125
+ const providerSettings = resolveProviderSettings(ctx.config, config, runtime, providerId, callbackUri);
126
+ const url = new URL(request.url);
127
+ const requestId = resolveRequestId(request);
128
+ const flowService = createSocialFlowService(ctx.config, ctx.hooks, config, request, runtime, providerId);
129
+ const stateId = readRequiredString(url.searchParams.get('state'), 'state');
130
+ const errorRedirectTo = await resolveOAuthCallbackErrorRedirectTarget(ctx.config, providerSettings, stateId);
131
+ try {
132
+ const formPostIdToken = readOptionalString(url.searchParams.get('id_token'));
133
+ const callbackResult = providerId === 'apple' && formPostIdToken
134
+ ? await handleAppleFormPostIdentityCallback(ctx.config, ctx.hooks, config, request, runtime, callbackUri, stateId, formPostIdToken, readOptionalString(url.searchParams.get('user')), requestId)
135
+ : await flowService.handleCallback({
136
+ providerId,
137
+ code: readRequiredString(url.searchParams.get('code'), 'code'),
138
+ state: stateId,
139
+ redirectUri: callbackUri,
140
+ requestId
141
+ });
142
+ const resolvedIdentity = requireResolvedIdentity(callbackResult);
143
+ const user = await findUserById(ctx.config, resolvedIdentity.userId);
144
+ if (!user) {
145
+ throw new AuthFnOAuthCallbackInvalidError('Linked authfn user not found after OAuth callback', {
146
+ provider: providerId,
147
+ userId: resolvedIdentity.userId
148
+ });
149
+ }
150
+ const twoFactorConfig = getTwoFactorPluginConfig(ctx.config);
151
+ if (twoFactorConfig) {
152
+ const pendingChallenge = await beginTwoFactorChallenge(ctx.config, user, SOCIAL_PROVIDER_METHODS[providerId], twoFactorConfig);
153
+ if (pendingChallenge) {
154
+ const challengeError = createPendingTwoFactorResponse(pendingChallenge.challenge);
155
+ const completion = {
156
+ provider: providerId,
157
+ linked: true,
158
+ callbackMode: readStoredCallbackMode(callbackResult),
159
+ handoffMode: readStoredHandoffMode(callbackResult, config.defaultHandoffMode),
160
+ redirectTo: callbackResult.subject.returnTo,
161
+ challengeId: pendingChallenge.challenge.id,
162
+ primaryMethod: SOCIAL_PROVIDER_METHODS[providerId]
163
+ };
164
+ await ctx.hooks.afterOAuthCallback?.(buildHookContext(ctx.config, request, runtime, user.id), completion);
165
+ await emitAuthEvent(ctx.config, {
166
+ type: 'authfn.2fa.challenged',
167
+ requestId,
168
+ actorId: user.id,
169
+ userId: user.id,
170
+ regionId: runtime.regionId,
171
+ provider: providerId,
172
+ outcome: 'required',
173
+ metadata: {
174
+ challengeId: pendingChallenge.challenge.id,
175
+ primaryMethod: SOCIAL_PROVIDER_METHODS[providerId]
176
+ }
177
+ });
178
+ await emitAuthEvent(ctx.config, {
179
+ type: 'authfn.oauth.completed',
180
+ requestId,
181
+ actorId: user.id,
182
+ userId: user.id,
183
+ regionId: runtime.regionId,
184
+ provider: providerId,
185
+ outcome: 'two-factor-required',
186
+ metadata: {
187
+ callbackMode: completion.callbackMode,
188
+ handoffMode: completion.handoffMode,
189
+ challengeId: pendingChallenge.challenge.id
190
+ }
191
+ });
192
+ if (completion.callbackMode === 'redirect') {
193
+ assertAllowedReturnTarget(providerSettings, completion.redirectTo, 'redirect');
194
+ return redirectWithCookies(request, appendTwoFactorChallengeToReturnTarget(completion.redirectTo, pendingChallenge.challenge.id, SOCIAL_PROVIDER_METHODS[providerId]), [], 303);
195
+ }
196
+ throw challengeError;
197
+ }
198
+ }
199
+ const issued = await issueSession(ctx.config, ctx.hooks, {
200
+ request,
201
+ userId: user.id,
202
+ primaryEmail: user.primaryEmail,
203
+ regionId: runtime.regionId,
204
+ methods: [SOCIAL_PROVIDER_METHODS[providerId]]
205
+ });
206
+ const cookies = Object.values(issueSessionCookies(issued.cookiePolicy, issued.sessionToken, issued.csrfToken));
207
+ const oauthAccountId = readOptionalString(resolvedIdentity.metadata?.oauthAccountId);
208
+ const completion = {
209
+ provider: providerId,
210
+ linked: true,
211
+ callbackMode: readStoredCallbackMode(callbackResult),
212
+ handoffMode: readStoredHandoffMode(callbackResult, config.defaultHandoffMode),
213
+ redirectTo: callbackResult.subject.returnTo,
214
+ session: issued.session,
215
+ userId: user.id,
216
+ oauthAccountId,
217
+ connectionId: callbackResult.connectionId
218
+ };
219
+ await ctx.hooks.afterOAuthCallback?.(buildHookContext(ctx.config, request, runtime, user.id, issued.session), completion);
220
+ await emitAuthEvent(ctx.config, {
221
+ type: 'authfn.oauth.completed',
222
+ requestId,
223
+ actorId: user.id,
224
+ sessionId: issued.session.id,
225
+ userId: user.id,
226
+ regionId: runtime.regionId,
227
+ provider: providerId,
228
+ outcome: 'linked',
229
+ metadata: {
230
+ callbackMode: completion.callbackMode,
231
+ handoffMode: completion.handoffMode,
232
+ oauthAccountId,
233
+ connectionId: callbackResult.connectionId
234
+ }
235
+ });
236
+ if (readOptionalBoolean(resolvedIdentity.metadata?.linkedExistingUser)) {
237
+ await emitAccountLinkedEvent(ctx.config, {
238
+ request,
239
+ user,
240
+ method: SOCIAL_PROVIDER_METHODS[providerId],
241
+ provider: providerId,
242
+ regionId: runtime.regionId,
243
+ metadata: {
244
+ oauthAccountId,
245
+ connectionId: callbackResult.connectionId
246
+ }
247
+ });
248
+ }
249
+ if (completion.callbackMode === 'redirect') {
250
+ assertAllowedReturnTarget(providerSettings, completion.redirectTo, 'redirect');
251
+ return redirectWithCookies(request, completion.handoffMode === 'session-token'
252
+ ? appendSessionHandoffToReturnTarget(completion.redirectTo, issued)
253
+ : completion.redirectTo, cookies, 303);
254
+ }
255
+ return jsonSuccess(request, {
256
+ linked: completion.linked,
257
+ provider: completion.provider,
258
+ session: completion.session,
259
+ ...(completion.handoffMode === 'session-token'
260
+ ? {
261
+ handoff: buildSessionHandoffPayload(issued)
262
+ }
263
+ : {})
264
+ }, {
265
+ setCookies: cookies
266
+ });
267
+ }
268
+ catch (error) {
269
+ if (errorRedirectTo) {
270
+ const authError = toAuthFnError(error);
271
+ await emitAuthEvent(ctx.config, {
272
+ type: 'authfn.oauth.failed',
273
+ requestId,
274
+ provider: providerId,
275
+ regionId: runtime.regionId,
276
+ outcome: 'redirected-error',
277
+ metadata: {
278
+ authErrorKind: authError.code,
279
+ authErrorMessage: authError.message,
280
+ providerError: readOptionalString(authError.details?.error),
281
+ providerErrorDescription: readOptionalString(authError.details?.error_description),
282
+ returnTo: errorRedirectTo,
283
+ debugError: isDebugErrorLoggingEnabled()
284
+ ? summarizeOAuthFailureError(error)
285
+ : undefined
286
+ }
287
+ });
288
+ return redirectWithCookies(request, appendOAuthErrorToReturnTarget(errorRedirectTo, providerId, requestId, authError), [], 303);
289
+ }
290
+ throw error;
291
+ }
292
+ }
293
+ },
294
+ {
295
+ method: 'POST',
296
+ path: '/social/callback/:provider',
297
+ meta: createAuthFnRouteMeta('completeSocialSignInFormPost', 'Complete social OAuth sign-in via form_post', {
298
+ mode: 'none'
299
+ }),
300
+ handler: async (request, context) => {
301
+ const callbackRoute = routes.find((route) => route.method === 'GET' && route.path === '/social/callback/:provider');
302
+ if (!callbackRoute) {
303
+ throw new AuthFnError('AUTHFN_INTERNAL_ERROR', 'Social OAuth callback handler is not registered', {
304
+ status: 500,
305
+ retryable: true
306
+ });
307
+ }
308
+ return callbackRoute.handler(await createFormPostCallbackRequest(request), context);
309
+ }
310
+ },
311
+ {
312
+ method: 'POST',
313
+ path: '/social/native/apple/start',
314
+ meta: createAuthFnRouteMeta('startNativeAppleSignIn', 'Start native Apple sign-in', {
315
+ mode: 'none'
316
+ }),
317
+ handler: async (request) => {
318
+ const runtime = await resolveEnvironment(ctx.config, request);
319
+ const body = await request.json().catch(() => ({}));
320
+ const providerId = 'apple';
321
+ const callbackUri = buildCallbackUri(runtime.baseUrl, ctx.basePath, providerId);
322
+ const providerSettings = resolveProviderSettings(ctx.config, config, runtime, providerId, callbackUri);
323
+ const returnTo = readOptionalString(body.returnTo);
324
+ const handoffMode = normalizeHandoffMode(readOptionalString(body.handoffMode) ?? 'session-token');
325
+ assertAllowedReturnTarget(providerSettings, returnTo, 'json');
326
+ const requestId = resolveRequestId(request);
327
+ const issuedAt = config.now?.() ?? new Date();
328
+ const createdAt = issuedAt.toISOString();
329
+ const expiresAt = new Date(issuedAt.getTime() + 10 * 60 * 1000).toISOString();
330
+ const stateId = generateStateId();
331
+ const nonce = generateNonce();
332
+ const stateStore = new DbAdapterOAuthStateStore(withNamespace(ctx.config.database, ctx.config.namespace ?? 'authfn'));
333
+ await stateStore.put({
334
+ stateId,
335
+ providerId,
336
+ redirectUri: callbackUri,
337
+ requestedScopes: providerSettings.scopes,
338
+ subject: {
339
+ kind: 'browser-auth',
340
+ intentId: createIdentifier('intent'),
341
+ regionId: runtime.regionId,
342
+ returnTo,
343
+ metadata: {
344
+ [CALLBACK_METADATA_MODE]: 'json',
345
+ [CALLBACK_METADATA_HANDOFF]: handoffMode,
346
+ nativeProvider: 'apple'
347
+ }
348
+ },
349
+ nonce,
350
+ createdAt,
351
+ expiresAt
352
+ });
353
+ await emitAuthEvent(ctx.config, {
354
+ type: 'authfn.oauth.started',
355
+ requestId,
356
+ provider: providerId,
357
+ regionId: runtime.regionId,
358
+ outcome: 'started',
359
+ metadata: {
360
+ stateId,
361
+ callbackMode: 'json',
362
+ handoffMode,
363
+ nativeProvider: 'apple'
364
+ }
365
+ });
366
+ return jsonSuccess(request, {
367
+ provider: providerId,
368
+ stateId,
369
+ nonce,
370
+ expiresAt
371
+ });
372
+ }
373
+ },
374
+ {
375
+ method: 'POST',
376
+ path: '/social/native/apple/complete',
377
+ meta: createAuthFnRouteMeta('completeNativeAppleSignIn', 'Complete native Apple sign-in', {
378
+ mode: 'none'
379
+ }),
380
+ handler: async (request) => {
381
+ const runtime = await resolveEnvironment(ctx.config, request);
382
+ const body = await request.json();
383
+ const requestId = resolveRequestId(request);
384
+ const stateId = readRequiredString(body.stateId, 'stateId');
385
+ const identityToken = readRequiredString(body.identityToken, 'identityToken');
386
+ const callbackUri = buildCallbackUri(runtime.baseUrl, ctx.basePath, 'apple');
387
+ const providerSettings = resolveProviderSettings(ctx.config, config, runtime, 'apple', callbackUri);
388
+ const stateStore = new DbAdapterOAuthStateStore(withNamespace(ctx.config.database, ctx.config.namespace ?? 'authfn'));
389
+ const consumedState = await consumeStateOrThrow(stateStore, stateId, (config.now?.() ?? new Date()).toISOString());
390
+ assertCallbackStateMatches({
391
+ providerId: 'apple',
392
+ redirectUri: callbackUri
393
+ }, consumedState);
394
+ const profile = await resolveAppleNativeProfile(identityToken, body.user, consumedState.nonce, [providerSettings.clientId, ...providerSettings.nativeClientIds]);
395
+ const resolved = await resolveLocalIdentityFromProfile(ctx.config, ctx.hooks, request, runtime, 'apple', providerSettings, profile);
396
+ const account = await upsertOAuthAccount(ctx.config, {
397
+ userId: resolved.user.id,
398
+ provider: 'apple',
399
+ providerAccountId: profile.providerAccountId,
400
+ connectionId: resolved.connectionId,
401
+ email: profile.email,
402
+ profile: profile.profile
403
+ });
404
+ const user = resolved.user;
405
+ const twoFactorConfig = getTwoFactorPluginConfig(ctx.config);
406
+ if (twoFactorConfig) {
407
+ const pendingChallenge = await beginTwoFactorChallenge(ctx.config, user, SOCIAL_PROVIDER_METHODS.apple, twoFactorConfig);
408
+ if (pendingChallenge) {
409
+ throw createPendingTwoFactorResponse(pendingChallenge.challenge);
410
+ }
411
+ }
412
+ const issued = await issueSession(ctx.config, ctx.hooks, {
413
+ request,
414
+ userId: user.id,
415
+ primaryEmail: user.primaryEmail,
416
+ regionId: runtime.regionId,
417
+ methods: [SOCIAL_PROVIDER_METHODS.apple]
418
+ });
419
+ const isNewUser = !resolved.existingAccountId && !resolved.linkedExistingUser;
420
+ await ctx.hooks.afterOAuthCallback?.(buildHookContext(ctx.config, request, runtime, user.id, issued.session), {
421
+ provider: 'apple',
422
+ linked: true,
423
+ callbackMode: 'json',
424
+ handoffMode: 'session-token',
425
+ session: issued.session,
426
+ userId: user.id,
427
+ oauthAccountId: account.id,
428
+ connectionId: resolved.connectionId
429
+ });
430
+ await emitAuthEvent(ctx.config, {
431
+ type: 'authfn.oauth.completed',
432
+ requestId,
433
+ actorId: user.id,
434
+ sessionId: issued.session.id,
435
+ userId: user.id,
436
+ regionId: runtime.regionId,
437
+ provider: 'apple',
438
+ outcome: resolved.linkedExistingUser ? 'linked-existing-user' : 'linked',
439
+ metadata: {
440
+ callbackMode: 'json',
441
+ handoffMode: 'session-token',
442
+ oauthAccountId: account.id,
443
+ connectionId: resolved.connectionId,
444
+ nativeProvider: 'apple',
445
+ isNewUser
446
+ }
447
+ });
448
+ if (resolved.linkedExistingUser) {
449
+ await emitAccountLinkedEvent(ctx.config, {
450
+ request,
451
+ user,
452
+ method: SOCIAL_PROVIDER_METHODS.apple,
453
+ provider: 'apple',
454
+ regionId: runtime.regionId,
455
+ metadata: {
456
+ oauthAccountId: account.id,
457
+ connectionId: resolved.connectionId,
458
+ nativeProvider: 'apple',
459
+ isNewUser
460
+ }
461
+ });
462
+ }
463
+ return jsonSuccess(request, {
464
+ provider: 'apple',
465
+ linked: true,
466
+ isNewUser,
467
+ token: issued.sessionToken,
468
+ session: issued.session,
469
+ sessionId: issued.session.id,
470
+ regionId: issued.session.regionId ?? runtime.regionId,
471
+ expiresAt: issued.session.expiresAt?.toISOString() ?? null,
472
+ userId: user.id,
473
+ oauthAccountId: account.id
474
+ });
475
+ }
476
+ },
477
+ {
478
+ method: 'POST',
479
+ path: '/social/disconnect/:provider',
480
+ meta: createAuthFnRouteMeta('disconnectSocialAccount', 'Disconnect a linked social OAuth account', {
481
+ mode: 'cookie-session',
482
+ csrf: true
483
+ }),
484
+ handler: async (request, context) => {
485
+ const providerId = normalizeProviderId(context.params.provider);
486
+ const runtime = await resolveEnvironment(ctx.config, request);
487
+ const state = await requireCookieSession(ctx.config, request);
488
+ assertValidCsrf(request, state);
489
+ const callbackUri = buildCallbackUri(runtime.baseUrl, ctx.basePath, providerId);
490
+ resolveProviderSettings(ctx.config, config, runtime, providerId, callbackUri);
491
+ const account = await requireOAuthAccountForUser(ctx.config, state.user.id, providerId);
492
+ const flowService = createSocialFlowService(ctx.config, ctx.hooks, config, request, runtime, providerId);
493
+ await flowService.disconnect({
494
+ connectionId: account.connectionId,
495
+ providerId,
496
+ revokeRemote: true,
497
+ requestId: resolveRequestId(request)
498
+ });
499
+ return jsonSuccess(request, {
500
+ disconnected: true,
501
+ provider: providerId
502
+ });
503
+ }
504
+ }
505
+ ];
506
+ return routes;
507
+ }
508
+ function createSocialFlowService(config, hooks, pluginConfig, request, runtime, activeProviderId) {
509
+ const providers = {
510
+ [activeProviderId]: getOAuthProviderDescriptor(activeProviderId)
511
+ };
512
+ const callbackUri = buildCallbackUri(runtime.baseUrl, config.basePath ?? '/auth', activeProviderId);
513
+ const settings = resolveProviderSettings(config, pluginConfig, runtime, activeProviderId, callbackUri);
514
+ const providerRuntimeConfig = {
515
+ [activeProviderId]: {
516
+ clientId: settings.clientId,
517
+ clientSecret: settings.clientSecret,
518
+ clientSecretResolver: settings.clientSecretResolver,
519
+ allowlistedRedirectUris: settings.allowlistedRedirectUris
520
+ }
521
+ };
522
+ const namespacedAdapter = withNamespace(config.database, config.namespace ?? 'authfn');
523
+ const tokenHttpClient = pluginConfig.tokenHttpClient ?? new DefaultOAuthTokenHttpClient({
524
+ fetcher: resolveTokenExchangeFetcher(config, pluginConfig, request)
525
+ });
526
+ return createOAuthFlowService({
527
+ providers,
528
+ providerRuntimeConfig,
529
+ stateStore: new DbAdapterOAuthStateStore(namespacedAdapter),
530
+ tokenVault: new DbAdapterTokenVault(namespacedAdapter),
531
+ tokenHttpClient,
532
+ now: pluginConfig.now,
533
+ identityHooks: {
534
+ resolveBrowserAuthIdentity: async ({ providerId, tokenSet }) => {
535
+ const resolved = await resolveLocalIdentity(config, hooks, pluginConfig, request, runtime, normalizeProviderId(providerId), tokenSet);
536
+ const identity = {
537
+ tenantId: config.namespace ?? 'authfn',
538
+ userId: resolved.user.id,
539
+ connectionId: resolved.connectionId,
540
+ persistTokens: false,
541
+ metadata: {
542
+ oauthAccountId: resolved.existingAccountId,
543
+ linkedExistingUser: resolved.linkedExistingUser,
544
+ profile: buildOAuthAccountProfile(normalizeProviderId(providerId), resolved.profile)
545
+ }
546
+ };
547
+ return identity;
548
+ },
549
+ onConnected: async (result) => {
550
+ const resolvedIdentity = requireResolvedIdentity(result);
551
+ const userId = resolvedIdentity.userId;
552
+ const profile = readProfileMetadata(resolvedIdentity.metadata);
553
+ const account = await upsertOAuthAccount(config, {
554
+ userId,
555
+ provider: normalizeProviderId(result.providerId),
556
+ providerAccountId: profile.providerAccountId,
557
+ connectionId: result.connectionId ?? readRequiredString(resolvedIdentity.connectionId, 'connectionId'),
558
+ email: profile.email,
559
+ profile: profile.profile
560
+ });
561
+ if (resolvedIdentity.metadata) {
562
+ resolvedIdentity.metadata.oauthAccountId = account.id;
563
+ }
564
+ },
565
+ onDisconnected: async (input) => {
566
+ await deleteOAuthAccountByConnectionId(config, input.connectionId);
567
+ }
568
+ }
569
+ });
570
+ }
571
+ async function handleAppleFormPostIdentityCallback(config, hooks, pluginConfig, request, runtime, callbackUri, stateId, idToken, userPayload, requestId) {
572
+ const stateStore = new DbAdapterOAuthStateStore(withNamespace(config.database, config.namespace ?? 'authfn'));
573
+ const consumedState = await consumeStateOrThrow(stateStore, stateId, (pluginConfig.now?.() ?? new Date()).toISOString());
574
+ assertCallbackStateMatches({
575
+ providerId: 'apple',
576
+ redirectUri: callbackUri
577
+ }, consumedState);
578
+ const subject = toOAuthFlowSubject(consumedState);
579
+ const providerSettings = resolveProviderSettings(config, pluginConfig, runtime, 'apple', callbackUri);
580
+ const claims = await verifyAppleIdentityToken(idToken, providerSettings.clientId);
581
+ const profile = resolveAppleFormPostProfile(claims, userPayload, consumedState.nonce);
582
+ const resolved = await resolveLocalIdentityFromProfile(config, hooks, request, runtime, 'apple', providerSettings, profile);
583
+ const account = await upsertOAuthAccount(config, {
584
+ userId: resolved.user.id,
585
+ provider: 'apple',
586
+ providerAccountId: profile.providerAccountId,
587
+ connectionId: resolved.connectionId,
588
+ email: profile.email,
589
+ profile: profile.profile
590
+ });
591
+ return {
592
+ providerId: 'apple',
593
+ subject,
594
+ tokenSet: {
595
+ accessToken: `apple_form_post_${requestId}`,
596
+ idToken,
597
+ tokenType: 'Bearer'
598
+ },
599
+ connectionId: resolved.connectionId,
600
+ resolvedIdentity: {
601
+ tenantId: config.namespace ?? 'authfn',
602
+ userId: resolved.user.id,
603
+ connectionId: resolved.connectionId,
604
+ persistTokens: false,
605
+ metadata: {
606
+ oauthAccountId: account.id,
607
+ linkedExistingUser: resolved.linkedExistingUser,
608
+ profile: buildOAuthAccountProfile('apple', profile)
609
+ }
610
+ }
611
+ };
612
+ }
613
+ async function resolveLocalIdentity(config, hooks, pluginConfig, request, runtime, providerId, tokenSet) {
614
+ const providerSettings = resolveProviderSettings(config, pluginConfig, runtime, providerId, buildCallbackUri(runtime.baseUrl, config.basePath ?? '/auth', providerId));
615
+ const profile = await resolveProviderProfile(providerId, tokenSet, request, runtime, providerSettings, pluginConfig.fetcher);
616
+ return resolveLocalIdentityFromProfile(config, hooks, request, runtime, providerId, providerSettings, profile);
617
+ }
618
+ async function resolveLocalIdentityFromProfile(config, hooks, request, runtime, providerId, providerSettings, profile) {
619
+ const existingAccount = await findOAuthAccountByProviderAccountId(config, providerId, profile.providerAccountId);
620
+ if (existingAccount) {
621
+ const linkedUser = await findUserById(config, existingAccount.userId);
622
+ if (!linkedUser) {
623
+ throw new AuthFnOAuthCallbackInvalidError('OAuth account links to a missing authfn user', {
624
+ provider: providerId,
625
+ providerAccountId: profile.providerAccountId
626
+ });
627
+ }
628
+ return {
629
+ user: linkedUser,
630
+ profile,
631
+ connectionId: existingAccount.connectionId,
632
+ existingAccountId: existingAccount.id
633
+ };
634
+ }
635
+ const normalizedEmail = normalizeEmail(profile.email);
636
+ if (normalizedEmail) {
637
+ const existingUser = await findUserByPrimaryEmail(config, normalizedEmail);
638
+ if (existingUser) {
639
+ const providerEmailAccepted = providerSettings.requireProviderEmailVerifiedForLink
640
+ ? profile.emailVerified === true
641
+ : true;
642
+ const existingEmailAccepted = providerSettings.requireExistingEmailVerifiedForLink
643
+ ? Boolean(existingUser.emailVerifiedAt)
644
+ : true;
645
+ if (providerSettings.linkByVerifiedEmail && providerEmailAccepted && existingEmailAccepted) {
646
+ return {
647
+ user: existingUser,
648
+ profile: {
649
+ ...profile,
650
+ email: normalizedEmail
651
+ },
652
+ connectionId: createConnectionId(providerId, existingUser.id),
653
+ linkedExistingUser: true
654
+ };
655
+ }
656
+ await emitAccountLinkingConflictEvent(config, {
657
+ request,
658
+ user: existingUser,
659
+ provider: providerId,
660
+ regionId: runtime.regionId,
661
+ method: SOCIAL_PROVIDER_METHODS[providerId],
662
+ reason: !providerSettings.linkByVerifiedEmail
663
+ ? 'oauth_verified_email_linking_disabled'
664
+ : !providerEmailAccepted
665
+ ? 'provider_email_unverified'
666
+ : 'existing_email_unverified',
667
+ metadata: {
668
+ providerEmailVerified: profile.emailVerified === true,
669
+ requireProviderEmailVerified: providerSettings.requireProviderEmailVerifiedForLink,
670
+ requireExistingEmailVerified: providerSettings.requireExistingEmailVerifiedForLink
671
+ }
672
+ });
673
+ throw new AuthFnConflictError('A user with this email already exists', {
674
+ provider: providerId,
675
+ primaryEmail: normalizedEmail
676
+ });
677
+ }
678
+ }
679
+ const user = await createSocialUser(config, request, runtime, providerId, {
680
+ ...profile,
681
+ email: normalizedEmail
682
+ }, hooks);
683
+ return {
684
+ user,
685
+ profile: {
686
+ ...profile,
687
+ email: normalizedEmail
688
+ },
689
+ connectionId: createConnectionId(providerId, user.id)
690
+ };
691
+ }
692
+ async function createSocialUser(config, request, runtime, providerId, profile, hooks) {
693
+ const now = new Date();
694
+ const input = {
695
+ primaryEmail: profile.email,
696
+ emailVerifiedAt: profile.emailVerified ? now : null,
697
+ metadata: profile.name
698
+ ? {
699
+ displayName: profile.name,
700
+ socialProvider: providerId
701
+ }
702
+ : {
703
+ socialProvider: providerId
704
+ }
705
+ };
706
+ const transformed = await hooks.beforeUserCreate?.(buildHookContext(config, request, runtime), input);
707
+ const resolved = transformed ?? input;
708
+ const user = await createUser(config, {
709
+ primaryEmail: normalizeEmail(readOptionalString(resolved.primaryEmail)),
710
+ emailVerifiedAt: resolved.emailVerifiedAt instanceof Date ? resolved.emailVerifiedAt : input.emailVerifiedAt,
711
+ metadata: readRecord(resolved.metadata) ?? input.metadata
712
+ });
713
+ try {
714
+ await hooks.afterUserCreate?.(buildHookContext(config, request, runtime, user.id), {
715
+ id: user.id,
716
+ primaryEmail: user.primaryEmail,
717
+ metadata: user.metadata ?? {}
718
+ });
719
+ }
720
+ catch (afterHookError) {
721
+ if (afterHookError instanceof AuthFnError) {
722
+ await rollbackSocialUser(config, user.id, user.primaryEmail);
723
+ throw afterHookError;
724
+ }
725
+ // Fail-open by hook contract.
726
+ }
727
+ return user;
728
+ }
729
+ async function rollbackSocialUser(config, userId, primaryEmail) {
730
+ const multiRegion = getMultiRegionPluginConfig(config);
731
+ if (primaryEmail && multiRegion) {
732
+ await unregisterRegionLookupForIdentifier(config, multiRegion, primaryEmail).catch(() => undefined);
733
+ }
734
+ await config.database.deleteMany({
735
+ model: 'region_profiles',
736
+ where: [{ field: 'userId', operator: 'eq', value: userId }],
737
+ namespace: config.namespace ?? 'authfn'
738
+ }).catch(() => undefined);
739
+ await config.database.delete({
740
+ model: 'users',
741
+ where: [{ field: 'id', operator: 'eq', value: userId }],
742
+ namespace: config.namespace ?? 'authfn'
743
+ }).catch(() => undefined);
744
+ }
745
+ function resolveProviderSettings(authConfig, pluginConfig, runtime, providerId, callbackUri) {
746
+ const staticConfig = pluginConfig.providers?.[providerId] ?? {};
747
+ const runtimeConfig = (runtime.oauth ?? {})[providerId] ?? {};
748
+ const clientId = readOptionalString(runtimeConfig.clientId) ?? staticConfig.clientId;
749
+ if (!clientId) {
750
+ throw new AuthFnValidationError('Social OAuth runtime config missing clientId', {
751
+ provider: providerId
752
+ });
753
+ }
754
+ const verifiedEmailLinking = allowsOAuthLinkByVerifiedEmail(authConfig, providerId);
755
+ const providerLinkOverride = staticConfig.linkByVerifiedEmail;
756
+ const hasRuntimeNativeClientIds = Object.prototype.hasOwnProperty.call(runtimeConfig, 'nativeClientIds');
757
+ return {
758
+ providerId,
759
+ clientId,
760
+ nativeClientIds: hasRuntimeNativeClientIds
761
+ ? readStringArray(runtimeConfig.nativeClientIds) ?? []
762
+ : readStringArray(staticConfig.nativeClientIds) ?? [],
763
+ clientSecret: readOptionalString(runtimeConfig.clientSecret) ?? staticConfig.clientSecret,
764
+ clientSecretResolver: readResolver(runtimeConfig.clientSecretResolver) ?? staticConfig.clientSecretResolver,
765
+ allowlistedRedirectUris: readStringArray(runtimeConfig.allowlistedRedirectUris)
766
+ ?? readStringArray(staticConfig.allowlistedRedirectUris)
767
+ ?? [callbackUri],
768
+ allowlistedReturnTo: readStringArray(runtimeConfig.allowlistedReturnTo)
769
+ ?? readStringArray(staticConfig.allowlistedReturnTo)
770
+ ?? [],
771
+ scopes: readStringArray(runtimeConfig.scopes)
772
+ ?? readStringArray(staticConfig.scopes)
773
+ ?? getOAuthProviderDescriptor(providerId).defaultScopes,
774
+ linkByVerifiedEmail: providerLinkOverride ?? verifiedEmailLinking.allowed,
775
+ requireExistingEmailVerifiedForLink: verifiedEmailLinking.requireExistingEmailVerified,
776
+ requireProviderEmailVerifiedForLink: verifiedEmailLinking.requireProviderEmailVerified,
777
+ profileResolver: staticConfig.profileResolver
778
+ };
779
+ }
780
+ function resolveTokenExchangeFetcher(config, pluginConfig, request) {
781
+ const tokenExchangeDiagnostics = pluginConfig.diagnostics === false
782
+ ? false
783
+ : pluginConfig.diagnostics?.tokenExchange;
784
+ if (!tokenExchangeDiagnostics) {
785
+ return pluginConfig.fetcher;
786
+ }
787
+ return createOAuthTokenDiagnosticFetcher({
788
+ fetcher: pluginConfig.fetcher,
789
+ observability: config.observability,
790
+ requestId: resolveRequestId(request),
791
+ diagnostics: tokenExchangeDiagnostics
792
+ });
793
+ }
794
+ async function authorizeScopes(settings, requestId) {
795
+ const registry = createDefaultProviderPolicyRegistry(() => new Date().toISOString());
796
+ registry.assertOperationAllowed({
797
+ providerId: settings.providerId,
798
+ operation: 'auth.signin',
799
+ featureMode: 'metadata-only'
800
+ });
801
+ await registry.validateScopes({
802
+ providerId: settings.providerId,
803
+ feature: 'auth.social.profile',
804
+ requestedScopes: settings.scopes,
805
+ tenantId: 'authfn',
806
+ userId: requestId,
807
+ purpose: 'auth.signin'
808
+ });
809
+ return [...settings.scopes];
810
+ }
811
+ async function resolveProviderProfile(providerId, tokenSet, request, runtime, settings, fetcher) {
812
+ if (settings.profileResolver) {
813
+ return settings.profileResolver({
814
+ providerId,
815
+ tokenSet,
816
+ request,
817
+ environment: runtime,
818
+ fetcher
819
+ });
820
+ }
821
+ switch (providerId) {
822
+ case 'google':
823
+ return resolveGoogleProfile(tokenSet);
824
+ case 'apple':
825
+ return resolveAppleProfile(tokenSet);
826
+ case 'github':
827
+ return resolveGitHubProfile(tokenSet, fetcher);
828
+ default:
829
+ throw new AuthFnOAuthProviderUnsupportedError('Unsupported social OAuth provider', {
830
+ provider: providerId
831
+ });
832
+ }
833
+ }
834
+ function resolveGoogleProfile(tokenSet) {
835
+ const claims = parseIdTokenClaims(tokenSet.idToken);
836
+ if (!claims.sub) {
837
+ throw new AuthFnOAuthCallbackInvalidError('Google OAuth callback missing required subject claim', {
838
+ provider: 'google'
839
+ });
840
+ }
841
+ return {
842
+ providerAccountId: claims.sub,
843
+ email: normalizeEmail(claims.email),
844
+ emailVerified: claims.emailVerified,
845
+ name: claims.name,
846
+ profile: cleanObject({
847
+ sub: claims.sub,
848
+ email: normalizeEmail(claims.email),
849
+ emailVerified: claims.emailVerified,
850
+ name: claims.name
851
+ })
852
+ };
853
+ }
854
+ function resolveAppleProfile(tokenSet) {
855
+ const claims = parseIdTokenClaims(tokenSet.idToken);
856
+ if (!claims.sub || !claims.email) {
857
+ throw new AuthFnOAuthCallbackInvalidError('Apple OAuth callback missing required claims', {
858
+ provider: 'apple'
859
+ });
860
+ }
861
+ return {
862
+ providerAccountId: claims.sub,
863
+ email: normalizeEmail(claims.email),
864
+ emailVerified: claims.emailVerified ?? true,
865
+ name: claims.name,
866
+ profile: cleanObject({
867
+ sub: claims.sub,
868
+ email: normalizeEmail(claims.email),
869
+ emailVerified: claims.emailVerified ?? true,
870
+ name: claims.name
871
+ })
872
+ };
873
+ }
874
+ function resolveAppleFormPostProfile(verifiedClaims, userPayload, expectedNonce) {
875
+ const claims = readIdTokenClaims(verifiedClaims);
876
+ if (!claims.sub) {
877
+ throw new AuthFnOAuthCallbackInvalidError('Apple OAuth form_post callback missing subject claim', {
878
+ provider: 'apple'
879
+ });
880
+ }
881
+ if (!expectedNonce || claims.nonce !== expectedNonce) {
882
+ throw new AuthFnOAuthCallbackInvalidError('Apple OAuth form_post nonce mismatch', {
883
+ provider: 'apple'
884
+ });
885
+ }
886
+ const user = parseAppleUserPayload(userPayload);
887
+ const email = normalizeEmail(user?.email ?? claims.email);
888
+ if (!email) {
889
+ throw new AuthFnOAuthCallbackInvalidError('Apple OAuth form_post callback missing email claim', {
890
+ provider: 'apple'
891
+ });
892
+ }
893
+ const name = resolveAppleDisplayName(user) ?? claims.name;
894
+ return {
895
+ providerAccountId: claims.sub,
896
+ email,
897
+ emailVerified: claims.emailVerified ?? true,
898
+ name,
899
+ profile: cleanObject({
900
+ sub: claims.sub,
901
+ email,
902
+ emailVerified: claims.emailVerified ?? true,
903
+ name,
904
+ firstName: user?.name?.firstName,
905
+ lastName: user?.name?.lastName
906
+ })
907
+ };
908
+ }
909
+ async function resolveAppleNativeProfile(identityToken, userPayload, expectedNonce, audience) {
910
+ const claims = await verifyAppleIdentityToken(identityToken, audience);
911
+ const subject = readOptionalString(claims.sub);
912
+ if (!subject) {
913
+ throw new AuthFnOAuthCallbackInvalidError('Apple native identity token missing subject claim', {
914
+ provider: 'apple'
915
+ });
916
+ }
917
+ const nonce = readOptionalString(claims.nonce);
918
+ if (!expectedNonce || nonce !== expectedNonce) {
919
+ throw new AuthFnOAuthCallbackInvalidError('Apple native identity token nonce mismatch', {
920
+ provider: 'apple'
921
+ });
922
+ }
923
+ const email = normalizeEmail(readOptionalString(claims.email) ?? userPayload?.email);
924
+ if (!email) {
925
+ throw new AuthFnOAuthCallbackInvalidError('Apple native identity token missing email claim', {
926
+ provider: 'apple'
927
+ });
928
+ }
929
+ const firstName = readOptionalString(userPayload?.name?.firstName);
930
+ const lastName = readOptionalString(userPayload?.name?.lastName);
931
+ const payloadName = [firstName, lastName].filter(Boolean).join(' ').trim();
932
+ const name = readOptionalString(claims.name) ?? (payloadName || undefined);
933
+ const emailVerified = readBooleanClaim(claims.email_verified) ?? true;
934
+ return {
935
+ providerAccountId: subject,
936
+ email,
937
+ emailVerified,
938
+ name,
939
+ profile: cleanObject({
940
+ sub: subject,
941
+ email,
942
+ emailVerified,
943
+ name,
944
+ firstName,
945
+ lastName,
946
+ isPrivateEmail: readBooleanClaim(claims.is_private_email)
947
+ })
948
+ };
949
+ }
950
+ async function verifyAppleIdentityToken(identityToken, audience) {
951
+ if (isUnsignedTestToken(identityToken)) {
952
+ const claims = parseRawIdTokenPayload(identityToken);
953
+ assertAppleTokenAudience(claims, audience);
954
+ return claims;
955
+ }
956
+ try {
957
+ const result = await jwtVerify(identityToken, APPLE_JWKS, {
958
+ issuer: 'https://appleid.apple.com',
959
+ audience
960
+ });
961
+ return result.payload;
962
+ }
963
+ catch (error) {
964
+ throw new AuthFnOAuthCallbackInvalidError('Apple native identity token verification failed', {
965
+ provider: 'apple',
966
+ reason: error instanceof Error ? error.message : 'verification_failed'
967
+ });
968
+ }
969
+ }
970
+ function assertAppleTokenAudience(claims, audience) {
971
+ const accepted = Array.isArray(audience) ? audience : [audience];
972
+ const tokenAudiences = Array.isArray(claims.aud)
973
+ ? claims.aud
974
+ : typeof claims.aud === 'string'
975
+ ? [claims.aud]
976
+ : [];
977
+ if (!tokenAudiences.some((aud) => accepted.includes(aud))) {
978
+ throw new AuthFnOAuthCallbackInvalidError('Apple native identity token verification failed', {
979
+ provider: 'apple',
980
+ reason: 'unexpected "aud" claim value'
981
+ });
982
+ }
983
+ }
984
+ function isUnsignedTestToken(identityToken) {
985
+ if (!allowUnsignedAppleTokensForTests()) {
986
+ return false;
987
+ }
988
+ try {
989
+ const [header] = identityToken.split('.');
990
+ const parsed = JSON.parse(Buffer.from(header, 'base64url').toString('utf8'));
991
+ return parsed.alg === 'none';
992
+ }
993
+ catch {
994
+ return false;
995
+ }
996
+ }
997
+ function allowUnsignedAppleTokensForTests() {
998
+ const env = globalThis.process?.env;
999
+ return env?.AUTHFN_ALLOW_UNSIGNED_APPLE_TOKENS === 'true' || env?.NODE_ENV === 'test';
1000
+ }
1001
+ function parseRawIdTokenPayload(identityToken) {
1002
+ const parts = identityToken.split('.');
1003
+ if (parts.length < 2) {
1004
+ throw new AuthFnOAuthCallbackInvalidError('Apple native identity token is malformed', {
1005
+ provider: 'apple'
1006
+ });
1007
+ }
1008
+ try {
1009
+ return JSON.parse(Buffer.from(parts[1], 'base64url').toString('utf8'));
1010
+ }
1011
+ catch {
1012
+ throw new AuthFnOAuthCallbackInvalidError('Apple native identity token payload is malformed', {
1013
+ provider: 'apple'
1014
+ });
1015
+ }
1016
+ }
1017
+ function parseAppleUserPayload(value) {
1018
+ if (!value) {
1019
+ return undefined;
1020
+ }
1021
+ try {
1022
+ const parsed = JSON.parse(value);
1023
+ const name = readRecord(parsed.name);
1024
+ return {
1025
+ email: readOptionalString(parsed.email),
1026
+ name: name
1027
+ ? {
1028
+ firstName: readOptionalString(name.firstName),
1029
+ lastName: readOptionalString(name.lastName)
1030
+ }
1031
+ : undefined
1032
+ };
1033
+ }
1034
+ catch {
1035
+ return undefined;
1036
+ }
1037
+ }
1038
+ function resolveAppleDisplayName(user) {
1039
+ const name = [
1040
+ user?.name?.firstName,
1041
+ user?.name?.lastName
1042
+ ].filter(Boolean).join(' ').trim();
1043
+ return name || undefined;
1044
+ }
1045
+ async function resolveGitHubProfile(tokenSet, fetcher) {
1046
+ const http = fetcher ?? createGlobalFetchLike();
1047
+ const userResponse = await http('https://api.github.com/user', {
1048
+ method: 'GET',
1049
+ headers: {
1050
+ authorization: `Bearer ${tokenSet.accessToken}`,
1051
+ accept: 'application/json'
1052
+ }
1053
+ });
1054
+ if (!userResponse.ok) {
1055
+ throw new AuthFnOAuthCallbackInvalidError('GitHub profile request failed', {
1056
+ provider: 'github',
1057
+ status: userResponse.status
1058
+ });
1059
+ }
1060
+ const userPayload = await readJsonRecord(userResponse);
1061
+ const emailResponse = await http('https://api.github.com/user/emails', {
1062
+ method: 'GET',
1063
+ headers: {
1064
+ authorization: `Bearer ${tokenSet.accessToken}`,
1065
+ accept: 'application/json'
1066
+ }
1067
+ });
1068
+ if (!emailResponse.ok) {
1069
+ throw new AuthFnOAuthCallbackInvalidError('GitHub email request failed', {
1070
+ provider: 'github',
1071
+ status: emailResponse.status
1072
+ });
1073
+ }
1074
+ const emails = await readJsonArray(emailResponse);
1075
+ const primaryEmail = emails.find((entry) => entry.primary === true)
1076
+ ?? emails.find((entry) => entry.verified === true)
1077
+ ?? emails[0];
1078
+ const providerAccountId = readIdentifierString(userPayload.id, 'providerAccountId');
1079
+ const email = normalizeEmail(readOptionalString(primaryEmail?.email) ?? readOptionalString(userPayload.email));
1080
+ const emailVerified = primaryEmail?.verified === true;
1081
+ return {
1082
+ providerAccountId,
1083
+ email,
1084
+ emailVerified,
1085
+ name: readOptionalString(userPayload.name) ?? readOptionalString(userPayload.login),
1086
+ profile: cleanObject({
1087
+ id: providerAccountId,
1088
+ login: readOptionalString(userPayload.login),
1089
+ email,
1090
+ emailVerified,
1091
+ name: readOptionalString(userPayload.name) ?? readOptionalString(userPayload.login)
1092
+ })
1093
+ };
1094
+ }
1095
+ function createOAuthSharedSchemas() {
1096
+ return getOAuthStorageTableDefinitions().map((table) => ({
1097
+ modelName: table.name,
1098
+ fields: Object.fromEntries(table.fields.map((field) => [
1099
+ field.name,
1100
+ {
1101
+ type: mapOAuthFieldType(field.type),
1102
+ required: !field.nullable,
1103
+ unique: field.primaryKey || field.unique,
1104
+ fieldName: field.name
1105
+ }
1106
+ ])),
1107
+ indexes: table.indexes?.map((index) => ({
1108
+ name: index.name,
1109
+ fields: [...index.fields],
1110
+ unique: index.unique
1111
+ }))
1112
+ }));
1113
+ }
1114
+ function createOAuthAccountsSchema() {
1115
+ return {
1116
+ modelName: 'oauth_accounts',
1117
+ fields: {
1118
+ id: { type: 'string', required: true, fieldName: 'id' },
1119
+ userId: {
1120
+ type: 'string',
1121
+ required: true,
1122
+ fieldName: 'user_id',
1123
+ references: { model: 'users', field: 'id', onDelete: 'cascade' }
1124
+ },
1125
+ provider: { type: 'string', required: true, fieldName: 'provider' },
1126
+ providerAccountId: { type: 'string', required: true, fieldName: 'provider_account_id' },
1127
+ connectionId: { type: 'string', required: true, fieldName: 'connection_id' },
1128
+ email: { type: 'string', required: false, fieldName: 'email' },
1129
+ profile: { type: 'json', required: false, fieldName: 'profile' },
1130
+ createdAt: { type: 'date', required: true, fieldName: 'created_at' },
1131
+ updatedAt: { type: 'date', required: true, fieldName: 'updated_at' }
1132
+ },
1133
+ indexes: [
1134
+ {
1135
+ name: 'idx_authfn_oauth_accounts_connection_id',
1136
+ fields: ['connectionId'],
1137
+ unique: true
1138
+ },
1139
+ {
1140
+ name: 'idx_authfn_oauth_accounts_provider_account',
1141
+ fields: ['provider', 'providerAccountId'],
1142
+ unique: true
1143
+ },
1144
+ {
1145
+ name: 'idx_authfn_oauth_accounts_user_id',
1146
+ fields: ['userId']
1147
+ }
1148
+ ]
1149
+ };
1150
+ }
1151
+ function mapOAuthFieldType(type) {
1152
+ switch (type) {
1153
+ case 'json':
1154
+ return 'json';
1155
+ case 'boolean':
1156
+ return 'boolean';
1157
+ default:
1158
+ return 'string';
1159
+ }
1160
+ }
1161
+ function redirectWithCookies(request, location, cookies, status) {
1162
+ const headers = new Headers();
1163
+ headers.set('location', location);
1164
+ headers.set('x-request-id', resolveRequestId(request));
1165
+ for (const cookie of cookies) {
1166
+ headers.append('set-cookie', cookie);
1167
+ }
1168
+ return new Response(null, {
1169
+ status,
1170
+ headers
1171
+ });
1172
+ }
1173
+ async function resolveOAuthCallbackErrorRedirectTarget(config, settings, stateId) {
1174
+ const stateStore = new DbAdapterOAuthStateStore(withNamespace(config.database, config.namespace ?? 'authfn'));
1175
+ const state = await stateStore.get(stateId);
1176
+ const subject = state?.subject;
1177
+ if (!subject || subject.kind !== 'browser-auth') {
1178
+ return undefined;
1179
+ }
1180
+ const callbackMode = normalizeCallbackMode(readOptionalString(subject.metadata?.[CALLBACK_METADATA_MODE])
1181
+ ?? inferCallbackMode(subject.returnTo));
1182
+ if (callbackMode !== 'redirect' || !subject.returnTo) {
1183
+ return undefined;
1184
+ }
1185
+ assertAllowedReturnTarget(settings, subject.returnTo, 'redirect');
1186
+ return subject.returnTo;
1187
+ }
1188
+ function appendOAuthErrorToReturnTarget(returnTo, providerId, requestId, error) {
1189
+ const url = new URL(returnTo);
1190
+ url.searchParams.set('auth_error', 'oauth_callback_failed');
1191
+ url.searchParams.set('auth_error_code', error.code);
1192
+ url.searchParams.set('auth_provider', providerId);
1193
+ url.searchParams.set('auth_request_id', requestId);
1194
+ return url.toString();
1195
+ }
1196
+ function isDebugErrorLoggingEnabled() {
1197
+ const globalProcess = globalThis;
1198
+ return globalProcess.process?.env?.AUTHFN_DEBUG_ERRORS === 'true';
1199
+ }
1200
+ function summarizeOAuthFailureError(error) {
1201
+ if (!error || typeof error !== 'object') {
1202
+ return {
1203
+ type: typeof error,
1204
+ message: String(error)
1205
+ };
1206
+ }
1207
+ const raw = error;
1208
+ return {
1209
+ name: error instanceof Error ? error.name : raw.name,
1210
+ code: raw.code,
1211
+ message: error instanceof Error ? error.message : raw.message,
1212
+ status: raw.status,
1213
+ retryable: raw.retryable,
1214
+ details: sanitizeOAuthFailureDetails(raw.details),
1215
+ cause: summarizeErrorCause(raw.cause)
1216
+ };
1217
+ }
1218
+ function summarizeErrorCause(cause) {
1219
+ if (!cause) {
1220
+ return undefined;
1221
+ }
1222
+ if (cause instanceof Error) {
1223
+ return {
1224
+ name: cause.name,
1225
+ message: cause.message
1226
+ };
1227
+ }
1228
+ if (typeof cause === 'string') {
1229
+ return cause;
1230
+ }
1231
+ if (typeof cause === 'object') {
1232
+ const raw = cause;
1233
+ return {
1234
+ name: raw.name,
1235
+ code: raw.code,
1236
+ message: raw.message
1237
+ };
1238
+ }
1239
+ return String(cause);
1240
+ }
1241
+ function sanitizeOAuthFailureDetails(details) {
1242
+ if (!details) {
1243
+ return undefined;
1244
+ }
1245
+ return Object.fromEntries(Object.entries(details).map(([key, value]) => [
1246
+ key,
1247
+ isSensitiveOAuthFailureKey(key) ? '[REDACTED]' : sanitizeOAuthFailureValue(value)
1248
+ ]));
1249
+ }
1250
+ function sanitizeOAuthFailureValue(value) {
1251
+ if (Array.isArray(value)) {
1252
+ return value.map((entry) => sanitizeOAuthFailureValue(entry));
1253
+ }
1254
+ if (value && typeof value === 'object') {
1255
+ return Object.fromEntries(Object.entries(value).map(([key, entry]) => [
1256
+ key,
1257
+ isSensitiveOAuthFailureKey(key) ? '[REDACTED]' : sanitizeOAuthFailureValue(entry)
1258
+ ]));
1259
+ }
1260
+ return value;
1261
+ }
1262
+ function isSensitiveOAuthFailureKey(key) {
1263
+ const normalized = key.toLowerCase();
1264
+ return [
1265
+ 'access_token',
1266
+ 'accesstoken',
1267
+ 'authorization',
1268
+ 'client_secret',
1269
+ 'clientsecret',
1270
+ 'code',
1271
+ 'cookie',
1272
+ 'id_token',
1273
+ 'idtoken',
1274
+ 'password',
1275
+ 'privatekey',
1276
+ 'refresh_token',
1277
+ 'refreshtoken',
1278
+ 'secret',
1279
+ 'set-cookie',
1280
+ 'token'
1281
+ ].some((sensitive) => normalized.includes(sensitive));
1282
+ }
1283
+ async function createFormPostCallbackRequest(request) {
1284
+ const form = await request.formData();
1285
+ const url = new URL(request.url);
1286
+ const code = readFormDataString(form.get('code'));
1287
+ const state = readFormDataString(form.get('state'));
1288
+ const idToken = readFormDataString(form.get('id_token'));
1289
+ const user = readFormDataString(form.get('user'));
1290
+ if (code) {
1291
+ url.searchParams.set('code', code);
1292
+ }
1293
+ if (state) {
1294
+ url.searchParams.set('state', state);
1295
+ }
1296
+ if (idToken) {
1297
+ url.searchParams.set('id_token', idToken);
1298
+ }
1299
+ if (user) {
1300
+ url.searchParams.set('user', user);
1301
+ }
1302
+ const headers = new Headers();
1303
+ const requestId = request.headers.get('x-request-id');
1304
+ if (requestId) {
1305
+ headers.set('x-request-id', requestId);
1306
+ }
1307
+ return new Request(url.toString(), {
1308
+ method: 'GET',
1309
+ headers
1310
+ });
1311
+ }
1312
+ function readFormDataString(value) {
1313
+ return typeof value === 'string' && value.trim().length > 0 ? value.trim() : undefined;
1314
+ }
1315
+ function buildSessionHandoffPayload(issued) {
1316
+ return {
1317
+ type: 'session-token',
1318
+ token: issued.sessionToken,
1319
+ sessionId: issued.session.id,
1320
+ regionId: issued.session.regionId ?? null,
1321
+ expiresAt: issued.session.expiresAt?.toISOString() ?? null
1322
+ };
1323
+ }
1324
+ function appendSessionHandoffToReturnTarget(returnTo, issued) {
1325
+ const url = new URL(returnTo);
1326
+ const fragment = new URLSearchParams(url.hash.startsWith('#') ? url.hash.slice(1) : url.hash);
1327
+ fragment.set('token', issued.sessionToken);
1328
+ fragment.set('sessionId', issued.session.id);
1329
+ if (issued.session.regionId) {
1330
+ fragment.set('regionId', issued.session.regionId);
1331
+ }
1332
+ if (issued.session.expiresAt) {
1333
+ fragment.set('expiresAt', issued.session.expiresAt.toISOString());
1334
+ }
1335
+ url.hash = fragment.toString();
1336
+ return url.toString();
1337
+ }
1338
+ function appendTwoFactorChallengeToReturnTarget(returnTo, challengeId, primaryMethod) {
1339
+ const url = new URL(returnTo);
1340
+ url.searchParams.set('authfnCode', 'AUTHFN_2FA_REQUIRED');
1341
+ url.searchParams.set('challengeId', challengeId);
1342
+ url.searchParams.set('primaryMethod', primaryMethod);
1343
+ return url.toString();
1344
+ }
1345
+ function assertAllowedReturnTarget(settings, returnTo, callbackMode) {
1346
+ if (callbackMode !== 'redirect') {
1347
+ return;
1348
+ }
1349
+ if (!returnTo) {
1350
+ throw new AuthFnRedirectUriDisallowedError('Redirect mode requires an allowlisted returnTo target', {
1351
+ provider: settings.providerId
1352
+ });
1353
+ }
1354
+ if (!isReturnTargetAllowlisted(returnTo, settings.allowlistedReturnTo)) {
1355
+ throw new AuthFnRedirectUriDisallowedError('Redirect target is not allowlisted', {
1356
+ provider: settings.providerId,
1357
+ returnTo
1358
+ });
1359
+ }
1360
+ }
1361
+ function isReturnTargetAllowlisted(returnTo, allowlist) {
1362
+ if (allowlist.includes(returnTo)) {
1363
+ return true;
1364
+ }
1365
+ let target;
1366
+ try {
1367
+ target = new URL(returnTo);
1368
+ }
1369
+ catch {
1370
+ return false;
1371
+ }
1372
+ return allowlist.some((entry) => {
1373
+ try {
1374
+ const allowed = new URL(entry);
1375
+ const allowsOrigin = (allowed.pathname === '/' || allowed.pathname === '')
1376
+ && !allowed.search
1377
+ && !allowed.hash;
1378
+ return allowsOrigin && allowed.origin === target.origin;
1379
+ }
1380
+ catch {
1381
+ return false;
1382
+ }
1383
+ });
1384
+ }
1385
+ function buildCallbackUri(baseUrl, basePath, providerId) {
1386
+ const normalizedBase = baseUrl.endsWith('/') ? baseUrl.slice(0, -1) : baseUrl;
1387
+ const normalizedPath = basePath.startsWith('/') ? basePath : `/${basePath}`;
1388
+ return `${normalizedBase}${normalizedPath}/social/callback/${providerId}`;
1389
+ }
1390
+ function toOAuthFlowSubject(state) {
1391
+ const subject = state.subject;
1392
+ if (subject && typeof subject === 'object') {
1393
+ const record = subject;
1394
+ if (record.kind === 'connection') {
1395
+ return {
1396
+ kind: 'connection',
1397
+ tenantId: readOptionalString(record.tenantId),
1398
+ userId: readOptionalString(record.userId),
1399
+ connectionId: readOptionalString(record.connectionId)
1400
+ };
1401
+ }
1402
+ if (record.kind === 'browser-auth') {
1403
+ return {
1404
+ kind: 'browser-auth',
1405
+ tenantId: readOptionalString(record.tenantId),
1406
+ intentId: readOptionalString(record.intentId),
1407
+ regionId: readOptionalString(record.regionId),
1408
+ returnTo: readOptionalString(record.returnTo),
1409
+ metadata: readRecord(record.metadata)
1410
+ };
1411
+ }
1412
+ }
1413
+ if (state.intentId) {
1414
+ return {
1415
+ kind: 'browser-auth',
1416
+ tenantId: state.tenantId,
1417
+ intentId: state.intentId,
1418
+ regionId: state.regionId,
1419
+ returnTo: state.returnTo,
1420
+ metadata: state.metadata
1421
+ };
1422
+ }
1423
+ return {
1424
+ kind: 'connection',
1425
+ tenantId: state.tenantId,
1426
+ userId: state.userId,
1427
+ connectionId: state.connectionId
1428
+ };
1429
+ }
1430
+ function parseIdTokenClaims(idToken) {
1431
+ if (!idToken) {
1432
+ return {};
1433
+ }
1434
+ const parts = idToken.split('.');
1435
+ if (parts.length < 2) {
1436
+ return {};
1437
+ }
1438
+ try {
1439
+ const payload = JSON.parse(Buffer.from(parts[1], 'base64url').toString('utf8'));
1440
+ return readIdTokenClaims(payload);
1441
+ }
1442
+ catch {
1443
+ return {};
1444
+ }
1445
+ }
1446
+ function readIdTokenClaims(payload) {
1447
+ const fallbackName = [
1448
+ readOptionalString(payload.given_name),
1449
+ readOptionalString(payload.family_name)
1450
+ ].filter(Boolean).join(' ').trim();
1451
+ return {
1452
+ sub: readOptionalString(payload.sub),
1453
+ email: readOptionalString(payload.email),
1454
+ emailVerified: readBooleanClaim(payload.email_verified),
1455
+ name: readOptionalString(payload.name) ?? (fallbackName || undefined),
1456
+ nonce: readOptionalString(payload.nonce)
1457
+ };
1458
+ }
1459
+ function createConnectionId(providerId, userId) {
1460
+ return `soc_${providerId}_${userId}_${createIdentifier('c').slice(2)}`;
1461
+ }
1462
+ function createIdentifier(prefix) {
1463
+ return `${prefix}_${randomBytes(8).toString('hex')}`;
1464
+ }
1465
+ function buildHookContext(config, request, runtime, actorId, session) {
1466
+ return {
1467
+ config,
1468
+ request,
1469
+ environment: runtime,
1470
+ actorId,
1471
+ session
1472
+ };
1473
+ }
1474
+ async function runBeforeOAuthStart(ctx, request, runtime, input) {
1475
+ try {
1476
+ const transformed = await ctx.hooks.beforeOAuthStart?.(buildHookContext(ctx.config, request, runtime), input);
1477
+ return (transformed ?? input);
1478
+ }
1479
+ catch (error) {
1480
+ if (error instanceof AuthFnError) {
1481
+ throw error;
1482
+ }
1483
+ throw new AuthFnPluginAbortedError('beforeOAuthStart hook aborted social OAuth start', {
1484
+ cause: error instanceof Error ? error.message : String(error)
1485
+ });
1486
+ }
1487
+ }
1488
+ function requireResolvedIdentity(result) {
1489
+ if (!result.resolvedIdentity) {
1490
+ throw new AuthFnOAuthCallbackInvalidError('OAuth callback did not resolve a local authfn identity', {
1491
+ provider: result.providerId
1492
+ });
1493
+ }
1494
+ return result.resolvedIdentity;
1495
+ }
1496
+ function readStoredCallbackMode(result) {
1497
+ const raw = result.subject.metadata?.[CALLBACK_METADATA_MODE];
1498
+ return normalizeCallbackMode(readOptionalString(raw) ?? inferCallbackMode(result.subject.returnTo));
1499
+ }
1500
+ function readStoredHandoffMode(result, defaultHandoffMode = 'none') {
1501
+ const raw = result.subject.metadata?.[CALLBACK_METADATA_HANDOFF];
1502
+ return normalizeHandoffMode(readOptionalString(raw) ?? inferHandoffMode(result.subject.returnTo, readStoredCallbackMode(result), defaultHandoffMode));
1503
+ }
1504
+ function normalizeProviderId(value) {
1505
+ if (value === 'google' || value === 'apple' || value === 'github') {
1506
+ return value;
1507
+ }
1508
+ throw new AuthFnOAuthProviderUnsupportedError('Unsupported social OAuth provider', {
1509
+ provider: value
1510
+ });
1511
+ }
1512
+ function normalizeCallbackMode(value) {
1513
+ if (value === 'redirect' || value === 'json') {
1514
+ return value;
1515
+ }
1516
+ throw new AuthFnValidationError('callbackMode must be "redirect" or "json"', {
1517
+ callbackMode: value
1518
+ });
1519
+ }
1520
+ function normalizeHandoffMode(value) {
1521
+ if (value === 'none' || value === 'session-token') {
1522
+ return value;
1523
+ }
1524
+ throw new AuthFnValidationError('handoffMode must be "none" or "session-token"', {
1525
+ handoffMode: value
1526
+ });
1527
+ }
1528
+ function inferCallbackMode(returnTo) {
1529
+ return returnTo ? 'redirect' : 'json';
1530
+ }
1531
+ function inferHandoffMode(returnTo, callbackMode, defaultHandoffMode = 'none') {
1532
+ if (callbackMode !== 'redirect' || !returnTo) {
1533
+ return 'none';
1534
+ }
1535
+ try {
1536
+ const protocol = new URL(returnTo).protocol.toLowerCase();
1537
+ if (protocol !== 'http:' && protocol !== 'https:') {
1538
+ return 'session-token';
1539
+ }
1540
+ }
1541
+ catch {
1542
+ return defaultHandoffMode;
1543
+ }
1544
+ return defaultHandoffMode;
1545
+ }
1546
+ function readRequiredString(value, field) {
1547
+ const normalized = readOptionalString(value);
1548
+ if (!normalized) {
1549
+ throw new AuthFnValidationError(`${field} is required`, { field });
1550
+ }
1551
+ return normalized;
1552
+ }
1553
+ function readIdentifierString(value, field) {
1554
+ if (typeof value === 'number' && Number.isFinite(value)) {
1555
+ return String(value);
1556
+ }
1557
+ return readRequiredString(value, field);
1558
+ }
1559
+ function readOptionalString(value) {
1560
+ return typeof value === 'string' && value.trim().length > 0 ? value.trim() : undefined;
1561
+ }
1562
+ function readOptionalBoolean(value) {
1563
+ return typeof value === 'boolean' ? value : undefined;
1564
+ }
1565
+ function readBooleanClaim(value) {
1566
+ if (typeof value === 'boolean') {
1567
+ return value;
1568
+ }
1569
+ if (typeof value === 'string') {
1570
+ if (value.toLowerCase() === 'true') {
1571
+ return true;
1572
+ }
1573
+ if (value.toLowerCase() === 'false') {
1574
+ return false;
1575
+ }
1576
+ }
1577
+ return undefined;
1578
+ }
1579
+ function readStringArray(value) {
1580
+ if (!Array.isArray(value)) {
1581
+ return undefined;
1582
+ }
1583
+ const entries = value
1584
+ .map((entry) => readOptionalString(entry))
1585
+ .filter((entry) => Boolean(entry));
1586
+ return entries.length > 0 ? entries : undefined;
1587
+ }
1588
+ function normalizeEmail(value) {
1589
+ const normalized = readOptionalString(value)?.toLowerCase();
1590
+ if (!normalized) {
1591
+ return undefined;
1592
+ }
1593
+ if (!normalized.includes('@')) {
1594
+ throw new AuthFnValidationError('A valid email is required', {
1595
+ email: value
1596
+ });
1597
+ }
1598
+ return normalized;
1599
+ }
1600
+ function readRecord(value) {
1601
+ return value && typeof value === 'object' && !Array.isArray(value)
1602
+ ? value
1603
+ : undefined;
1604
+ }
1605
+ function cleanObject(value) {
1606
+ return Object.fromEntries(Object.entries(value).filter(([, entry]) => entry !== undefined && entry !== null));
1607
+ }
1608
+ function readResolver(value) {
1609
+ return typeof value === 'function'
1610
+ ? value
1611
+ : undefined;
1612
+ }
1613
+ function readProfileMetadata(metadata) {
1614
+ const profile = metadata?.profile;
1615
+ const record = readRecord(profile);
1616
+ if (!record) {
1617
+ throw new AuthFnOAuthCallbackInvalidError('OAuth callback is missing resolved profile metadata');
1618
+ }
1619
+ const providerAccountId = readRequiredString(record.providerAccountId, 'providerAccountId');
1620
+ return {
1621
+ providerAccountId,
1622
+ email: normalizeEmail(readOptionalString(record.email)),
1623
+ emailVerified: readOptionalBoolean(record.emailVerified),
1624
+ name: readOptionalString(record.name),
1625
+ profile: record
1626
+ };
1627
+ }
1628
+ async function readJsonRecord(response) {
1629
+ const payload = JSON.parse(await response.text());
1630
+ const record = readRecord(payload);
1631
+ if (!record) {
1632
+ throw new AuthFnOAuthCallbackInvalidError('OAuth profile response must be a JSON object');
1633
+ }
1634
+ return record;
1635
+ }
1636
+ async function readJsonArray(response) {
1637
+ const payload = JSON.parse(await response.text());
1638
+ if (!Array.isArray(payload)) {
1639
+ throw new AuthFnOAuthCallbackInvalidError('OAuth profile response must be a JSON array');
1640
+ }
1641
+ return payload.map((entry) => readRecord(entry) ?? {});
1642
+ }
1643
+ function createGlobalFetchLike() {
1644
+ const fetcher = globalThis.fetch;
1645
+ if (!fetcher) {
1646
+ throw new AuthFnOAuthCallbackInvalidError('global fetch is not available for GitHub profile resolution');
1647
+ }
1648
+ return async (url, init) => {
1649
+ const response = await fetcher(url, {
1650
+ method: init.method,
1651
+ headers: init.headers,
1652
+ body: init.body
1653
+ });
1654
+ return {
1655
+ ok: response.ok,
1656
+ status: response.status,
1657
+ headers: {
1658
+ get(name) {
1659
+ return response.headers.get(name);
1660
+ }
1661
+ },
1662
+ text: () => response.text()
1663
+ };
1664
+ };
1665
+ }
1666
+ function withNamespace(adapter, namespace) {
1667
+ return {
1668
+ ...adapter,
1669
+ create: (params) => adapter.create({ ...params, namespace: params.namespace ?? namespace }),
1670
+ findOne: (params) => adapter.findOne({ ...params, namespace: params.namespace ?? namespace }),
1671
+ findMany: (params) => adapter.findMany({ ...params, namespace: params.namespace ?? namespace }),
1672
+ update: (params) => adapter.update({ ...params, namespace: params.namespace ?? namespace }),
1673
+ delete: (params) => adapter.delete({ ...params, namespace: params.namespace ?? namespace }),
1674
+ createMany: (params) => adapter.createMany({ ...params, namespace: params.namespace ?? namespace }),
1675
+ updateMany: (params) => adapter.updateMany({ ...params, namespace: params.namespace ?? namespace }),
1676
+ deleteMany: (params) => adapter.deleteMany({ ...params, namespace: params.namespace ?? namespace }),
1677
+ upsert: (params) => adapter.upsert({ ...params, namespace: params.namespace ?? namespace }),
1678
+ count: (params) => adapter.count({ ...params, namespace: params.namespace ?? namespace })
1679
+ };
1680
+ }
1681
+ //# sourceMappingURL=index.js.map