-
Notifications
You must be signed in to change notification settings - Fork 463
Expand file tree
/
Copy pathauth-client.ts
More file actions
6289 lines (5697 loc) · 209 KB
/
Copy pathauth-client.ts
File metadata and controls
6289 lines (5697 loc) · 209 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import { NextResponse, type NextRequest } from "next/server.js";
import { RequestCookies, ResponseCookies } from "@edge-runtime/cookies";
import * as jose from "jose";
import * as oauth from "oauth4webapi";
import * as client from "openid-client";
import packageJson from "../../package.json" with { type: "json" };
import {
AccessTokenError,
AccessTokenErrorCode,
AccessTokenForConnectionError,
AccessTokenForConnectionErrorCode,
AuthorizationCodeGrantError,
AuthorizationCodeGrantRequestError,
AuthorizationError,
BackchannelAuthenticationError,
BackchannelAuthenticationNotSupportedError,
BackchannelLogoutError,
ConnectAccountError,
ConnectAccountErrorCodes,
CustomTokenExchangeError,
CustomTokenExchangeErrorCode,
DiscoveryError,
DPoPError,
DPoPErrorCode,
InvalidConfigurationError,
InvalidStateError,
MfaChallengeError,
MfaEnrollmentError,
MfaGetAuthenticatorsError,
MfaNoAvailableFactorsError,
MfaRequiredError,
MfaVerifyError,
MissingStateError,
MtlsError,
MtlsErrorCode,
MyAccountApiError,
OAuth2Error,
PasskeyChallengeError,
PasskeyEnrollmentChallengeError,
PasskeyEnrollmentVerifyError,
PasskeyGetTokenError,
PasskeyRegisterError,
PasswordlessDbChallengeError,
PasswordlessDbGetTokenError,
PasswordlessStartError,
PasswordlessVerifyError,
SdkError
} from "../errors/index.js";
import {
IssuerValidationError,
SessionDomainMismatchError
} from "../errors/mcd.js";
import {
CompleteConnectAccountRequest,
CompleteConnectAccountResponse,
ConnectAccountOptions,
ConnectAccountRequest,
ConnectAccountResponse
} from "../types/connected-accounts.js";
import { DpopKeyPair, DpopOptions } from "../types/dpop.js";
import {
AccessTokenForConnectionOptions,
AccessTokenSet,
ActClaim,
AuthenticatorApiResponse,
AuthorizationParameters,
BackchannelAuthenticationOptions,
BackchannelAuthenticationResponse,
ChallengeApiResponse,
ConnectionTokenSet,
CustomTokenExchangeOptions,
CustomTokenExchangeResponse,
EnrollmentApiResponse,
EnrollOobOptions,
EnrollOtpOptions,
GetAccessTokenOptions,
GRANT_TYPE_CUSTOM_TOKEN_EXCHANGE,
GRANT_TYPE_PASSKEY,
GRANT_TYPE_PASSWORDLESS_OTP,
LogoutStrategy,
LogoutToken,
PasskeyChallengeOptions,
PasskeyChallengeResponse,
PasskeyEnrollmentChallengeOptions,
PasskeyEnrollmentChallengeResponse,
PasskeyEnrollmentVerifyOptions,
PasskeyEnrollmentVerifyResponse,
PasskeyGetTokenOptions,
PasskeyRegisterOptions,
PasskeyRegisterResponse,
PasswordlessDbChallenge,
PasswordlessDbChallengeEmailOptions,
PasswordlessDbChallengePhoneOptions,
PasswordlessDbGetTokenOptions,
PasswordlessStartOptions,
PasswordlessVerifyOptions,
PasswordlessVerifyTokenResponse,
ProxyOptions,
RESPONSE_TYPES,
SessionData,
StartInteractiveLoginOptions,
SUBJECT_TOKEN_TYPES,
TokenSet,
User,
VerifyMfaOptions
} from "../types/index.js";
import type { SessionCheckResult } from "../types/mcd.js";
import type { MfaTokenEndpointResponse } from "../types/mfa.js";
import { resolveAppBaseUrl } from "../utils/app-base-url.js";
import {
mergeAuthorizationParamsIntoSearchParams,
parseNonNegativeIntegerParam
} from "../utils/authorization-params-helpers.js";
import {
DEFAULT_MFA_CONTEXT_TTL_SECONDS,
DEFAULT_SCOPES
} from "../utils/constants.js";
import { withDPoPNonceRetry } from "../utils/dpopRetry.js";
import { createSizeLimitedFetch } from "../utils/fetchUtils.js";
import { createAuthCompletePostMessageResponse } from "../utils/html-helpers.js";
import { buildEnrollOptions } from "../utils/mfa-server-utils.js";
import {
buildVerifyParams,
getVerifyGrantType,
transformVerifyBodyToOptions
} from "../utils/mfa-transform-utils.js";
import {
decryptMfaToken,
encryptMfaToken,
extractMfaErrorDetails,
handleMfaError,
isMfaRequiredError
} from "../utils/mfa-utils.js";
import {
extractMfaToken,
parseJsonBody,
validateArrayFieldAndThrow,
validateStringFieldAndThrow,
validateVerificationCredentialAndThrow
} from "../utils/mfa-validation-utils.js";
import { normalizeDomain, normalizeIssuer } from "../utils/normalize.js";
import { extractOAuthErrorDetails } from "../utils/oauth-error-utils.js";
import { createRouteUrl, removeTrailingSlash } from "../utils/pathUtils.js";
import {
buildForwardedRequestHeaders,
buildForwardedResponseHeaders,
transformTargetUrl
} from "../utils/proxy.js";
import {
ensureDefaultScope,
getScopeForAudience
} from "../utils/scope-helpers.js";
import { getSessionChangesAfterGetAccessToken } from "../utils/session-changes-helpers.js";
import {
buildSessionFromCallback,
isSessionCeilingInPast,
isSessionCeilingReached,
mergePopupTokenIntoSession
} from "../utils/session-helpers.js";
import {
compareScopes,
findAccessTokenSet,
isBeforeOrEqual,
mergeScopes,
normalizeExpiresAt,
normalizeTokenType,
tokenSetFromAccessTokenSet
} from "../utils/token-set-helpers.js";
import { isUrl, toSafeRedirect } from "../utils/url-helpers.js";
import type { AuthClientProvider } from "./auth-client-provider.js";
import {
addCacheControlHeadersForSession,
type ReadonlyRequestCookies
} from "./cookies.js";
import { DiscoveryCache } from "./discovery-cache.js";
import {
AccessTokenFactory,
Fetcher,
FetcherConfig,
FetcherHooks,
FetcherMinimalConfig
} from "./fetcher.js";
import { AbstractSessionStore } from "./session/abstract-session-store.js";
import { TransactionState, TransactionStore } from "./transaction-store.js";
import { filterDefaultIdTokenClaims } from "./user.js";
export type BeforeSessionSavedHook = (
session: SessionData,
idToken: string | null
) => Promise<SessionData>;
export type OnCallbackContext = {
/**
* The type of response expected from the authorization server.
* One of {@link RESPONSE_TYPES}
*/
responseType?: RESPONSE_TYPES;
/**
* The resolved base URL for the current request, used to build safe redirects.
*/
appBaseUrl?: string;
/**
* The URL or path the user should be redirected to after completing the transaction.
*/
returnTo?: string;
/**
* The connected account information when the responseType is {@link RESPONSE_TYPES.CONNECT_CODE}
*/
connectedAccount?: CompleteConnectAccountResponse;
/**
* The return strategy for this callback flow.
* - 'redirect' (default): Standard OAuth redirect flow
* - 'postMessage': Popup flow returning via window.postMessage
* Hook authors can use this to detect popup flows and adapt behavior.
*/
challengeMode?: "redirect" | "popup";
};
export type OnCallbackHook = (
error: SdkError | null,
ctx: OnCallbackContext,
session: SessionData | null
) => Promise<NextResponse>;
// params passed to the /authorize endpoint that cannot be overwritten
const INTERNAL_AUTHORIZE_PARAMS = [
"client_id",
"redirect_uri",
"response_type",
"code_challenge",
"code_challenge_method",
"state",
"nonce"
];
/**
* A constant representing the grant type for federated connection access token exchange.
*
* This grant type is used in OAuth token exchange scenarios where a federated connection
* access token is required. It is specific to Auth0's implementation and follows the
* "urn:auth0:params:oauth:grant-type:token-exchange:federated-connection-access-token" format.
*/
const GRANT_TYPE_FEDERATED_CONNECTION_ACCESS_TOKEN =
"urn:auth0:params:oauth:grant-type:token-exchange:federated-connection-access-token";
/**
* A constant representing the token type for federated connection access tokens.
* This is used to specify the type of token being requested from Auth0.
*
* @constant
* @type {string}
*/
const REQUESTED_TOKEN_TYPE_FEDERATED_CONNECTION_ACCESS_TOKEN =
"http://auth0.com/oauth/token-type/federated-connection-access-token";
export interface Routes {
login: string;
logout: string;
callback: string;
profile: string;
accessToken: string;
backChannelLogout: string;
connectAccount: string;
mfaAuthenticators: string;
mfaChallenge: string;
mfaVerify: string;
mfaAssociate: string;
passwordlessStart: string;
passwordlessVerify: string;
passwordlessDbOtpChallenge: string;
passwordlessDbGetToken: string;
passkeyRegister: string;
passkeyChallenge: string;
passkeyGetToken: string;
passkeyEnrollmentChallenge: string;
passkeyEnrollmentVerify: string;
}
export type RoutesOptions = Partial<Routes>;
/**
* @private
*/
export interface AuthClientOptions {
transactionStore: TransactionStore;
sessionStore: AbstractSessionStore;
domain: string;
/**
* Issuer URL override. When provided, this is used instead of constructing
* the issuer from the domain hostname. Required for providers like Okta that
* use path-based authorization server URLs (e.g. https://myorg.okta.com/oauth2/default/).
*/
issuer?: string;
clientId: string;
clientSecret?: string;
clientAssertionSigningKey?: string | jose.CryptoKey;
clientAssertionSigningAlg?: string;
authorizationParameters?: AuthorizationParameters;
pushedAuthorizationRequests?: boolean;
secret: string;
/**
* Normalized appBaseUrl. When omitted, the SDK infers the base URL from the request.
* If you construct AuthClient directly, normalize the value first.
*/
appBaseUrl?: string | string[];
signInReturnToPath?: string;
logoutStrategy?: LogoutStrategy;
includeIdTokenHintInOIDCLogoutUrl?: boolean;
beforeSessionSaved?: BeforeSessionSavedHook;
onCallback?: OnCallbackHook;
routes: Routes;
// custom fetch implementation to allow for dependency injection
fetch?: typeof fetch;
discoveryCache?: DiscoveryCache;
provider?: AuthClientProvider;
allowInsecureRequests?: boolean;
httpTimeout?: number;
enableTelemetry?: boolean;
enableAccessTokenEndpoint?: boolean;
noContentProfileResponseWhenUnauthenticated?: boolean;
enableConnectAccountEndpoint?: boolean;
tokenRefreshBuffer?: number;
useDPoP?: boolean;
dpopKeyPair?: DpopKeyPair;
dpopOptions?: DpopOptions;
/**
* Enable mTLS (Mutual TLS) client authentication (RFC 8705).
*
* When `true`, the SDK uses `oauth.TlsClientAuth()` for client authentication
* and routes all token requests to the mTLS endpoint aliases advertised in
* the Auth0 discovery document (`mtls_endpoint_aliases`).
*
* Requires the `fetch` option to be set with a TLS-aware implementation
* (e.g. Node.js `undici` with a client certificate). The standard `fetch`
* global has no client certificate API.
*
* @default false
*/
useMtls?: boolean;
/**
* MFA token TTL in seconds (for token encryption expiration).
* Default: 300 (5 minutes, matching Auth0's mfa_token expiration)
*/
mfaTokenTtl?: number;
/**
* Content Security Policy nonce for inline scripts.
* Required when CSP is enabled and popup flows use postMessage return strategy.
* The nonce is injected into the <script> tag of the postMessage HTML response.
*/
cspNonce?: string;
/**
* @future This option is reserved for future implementation.
* Currently not used - placeholder for upcoming nonce persistence feature.
*/
// dpopHandleStorage?: DPoPHandleStorageInterface; // Commented out until implementation
}
/**
* @private
*/
export class AuthClient {
private transactionStore: TransactionStore;
private sessionStore: AbstractSessionStore;
private clientMetadata: oauth.Client;
private clientSecret?: string;
private clientAssertionSigningKey?: string | jose.CryptoKey;
private clientAssertionSigningAlg: string;
readonly domain: string;
private readonly _issuer: string;
private authorizationParameters: AuthorizationParameters;
private pushedAuthorizationRequests: boolean;
// Normalized appBaseUrl for this client instance.
private appBaseUrl?: string | string[];
private signInReturnToPath: string;
private logoutStrategy: LogoutStrategy;
private includeIdTokenHintInOIDCLogoutUrl: boolean;
private beforeSessionSaved?: BeforeSessionSavedHook;
private onCallback: OnCallbackHook;
private routes: Routes;
private fetch: typeof fetch;
private discoveryCache: DiscoveryCache;
public provider?: AuthClientProvider;
private allowInsecureRequests: boolean;
private httpTimeout: number;
private httpOptions: () => { signal: AbortSignal; headers: Headers };
private authorizationServerMetadata?: oauth.AuthorizationServer;
private readonly enableAccessTokenEndpoint: boolean;
private readonly noContentProfileResponseWhenUnauthenticated: boolean;
private readonly enableConnectAccountEndpoint: boolean;
private readonly tokenRefreshBuffer: number;
private dpopOptions?: DpopOptions;
private dpopKeyPair?: DpopKeyPair;
private readonly useDPoP: boolean;
private dpopValidated = false;
private readonly useMtls: boolean;
private readonly mfaTokenTtl: number;
private readonly cspNonce?: string;
private proxyDpopHandles: { [audience: string]: oauth.DPoPHandle } = {};
/**
* Maximum allowed response body size (1 MB). Responses exceeding this limit
* are aborted to prevent memory exhaustion from malicious or oversized
* OIDC discovery documents, JWKS responses, or token endpoint payloads.
* @internal
*/
static readonly MAX_RESPONSE_BODY_SIZE = 1024 * 1024;
constructor(options: AuthClientOptions) {
// dependencies
this.fetch = createSizeLimitedFetch(
options.fetch || fetch,
AuthClient.MAX_RESPONSE_BODY_SIZE
);
this.discoveryCache = options.discoveryCache || new DiscoveryCache();
this.provider = options.provider;
this.allowInsecureRequests = options.allowInsecureRequests ?? false;
this.httpTimeout = options.httpTimeout ?? 5000;
this.httpOptions = () => {
const headers = new Headers();
const enableTelemetry = options.enableTelemetry ?? true;
if (enableTelemetry) {
const name = "nextjs-auth0";
const version = packageJson.version;
headers.set("User-Agent", `${name}/${version}`);
headers.set(
"Auth0-Client",
encodeBase64(
JSON.stringify({
name,
version
})
)
);
}
return {
signal: AbortSignal.timeout(this.httpTimeout),
headers
};
};
if (this.allowInsecureRequests && process.env.NODE_ENV === "production") {
console.warn(
"allowInsecureRequests is enabled in a production environment. This is not recommended."
);
}
// stores
this.transactionStore = options.transactionStore;
this.sessionStore = options.sessionStore;
// authorization server
this.domain = options.domain;
this._issuer = options.issuer ?? `https://${options.domain}/`;
this.clientMetadata = { client_id: options.clientId };
// Apply DPoP timing validation options to client metadata if provided
if (options.dpopOptions) {
if (typeof options.dpopOptions.clockSkew === "number") {
this.clientMetadata[oauth.clockSkew] = options.dpopOptions.clockSkew;
}
if (typeof options.dpopOptions.clockTolerance === "number") {
this.clientMetadata[oauth.clockTolerance] =
options.dpopOptions.clockTolerance;
}
}
// Store dpopOptions for use in retry logic
this.dpopOptions = options.dpopOptions;
this.clientSecret = options.clientSecret;
this.authorizationParameters = options.authorizationParameters || {
scope: DEFAULT_SCOPES
};
this.pushedAuthorizationRequests =
options.pushedAuthorizationRequests ?? false;
this.clientAssertionSigningKey = options.clientAssertionSigningKey;
this.clientAssertionSigningAlg =
options.clientAssertionSigningAlg || "RS256";
this.authorizationParameters.scope = ensureDefaultScope(
this.authorizationParameters
);
const scope = getScopeForAudience(
this.authorizationParameters.scope,
this.authorizationParameters.audience
)
?.split(" ")
.map((s) => s.trim());
if (!scope || !scope.includes("openid")) {
throw new Error(
"The 'openid' scope must be included in the set of scopes. See https://auth0.com/docs"
);
}
// application
if (Array.isArray(options.appBaseUrl)) {
if (options.appBaseUrl.length === 0) {
throw new InvalidConfigurationError(
"APP_BASE_URL array configuration cannot be empty."
);
}
const invalidUrls = options.appBaseUrl.filter(
(url) => isUrl(url) === false
);
if (invalidUrls.length > 0) {
throw new InvalidConfigurationError(
`APP_BASE_URL array contains invalid URLs: ${invalidUrls.join(", ")}`
);
}
}
this.appBaseUrl = options.appBaseUrl;
this.signInReturnToPath = options.signInReturnToPath || "/";
// validate logout strategy
const validStrategies = ["auto", "oidc", "v2"] as const;
let logoutStrategy = options.logoutStrategy || "auto";
if (!validStrategies.includes(logoutStrategy)) {
console.error(
`Invalid logoutStrategy: ${logoutStrategy}. Must be one of: ${validStrategies.join(", ")}. Defaulting to "auto"`
);
logoutStrategy = "auto";
}
this.logoutStrategy = logoutStrategy;
this.includeIdTokenHintInOIDCLogoutUrl =
options.includeIdTokenHintInOIDCLogoutUrl ?? true;
// hooks
this.beforeSessionSaved = options.beforeSessionSaved;
this.onCallback = options.onCallback || this.defaultOnCallback;
// routes
this.routes = options.routes;
this.enableAccessTokenEndpoint = options.enableAccessTokenEndpoint ?? true;
this.noContentProfileResponseWhenUnauthenticated =
options.noContentProfileResponseWhenUnauthenticated ?? false;
this.enableConnectAccountEndpoint =
options.enableConnectAccountEndpoint ?? false;
this.tokenRefreshBuffer = options.tokenRefreshBuffer ?? 0;
this.useDPoP = options.useDPoP ?? false;
this.useMtls = options.useMtls ?? false;
if (this.useMtls && this.useDPoP) {
throw new MtlsError(
MtlsErrorCode.MTLS_INCOMPATIBLE_CLIENT_AUTH,
"useMtls and useDPoP cannot be used together. " +
"When both are present, the server always issues a DPoP-bound token (cnf.jkt) " +
"and the certificate is ignored for token binding."
);
}
if (this.useMtls && !options.fetch) {
throw new MtlsError(
MtlsErrorCode.MTLS_REQUIRES_CUSTOM_FETCH,
"useMtls requires the customFetch option (Auth0Client) or the fetch option (AuthClient) " +
"to be set with a TLS-aware implementation (e.g. Node.js undici with a client certificate). " +
"The standard fetch global has no client certificate API. " +
"See https://github.com/auth0/nextjs-auth0/blob/main/EXAMPLES.md#mtls for setup instructions."
);
}
if (
this.useMtls &&
(options.clientSecret || options.clientAssertionSigningKey)
) {
throw new MtlsError(
MtlsErrorCode.MTLS_INCOMPATIBLE_CLIENT_AUTH,
"useMtls cannot be combined with clientSecret or clientAssertionSigningKey. " +
"mTLS replaces secret-based client authentication entirely."
);
}
if (this.useMtls) {
this.clientMetadata.use_mtls_endpoint_aliases = true;
}
// MFA token TTL for token encryption
this.mfaTokenTtl = options.mfaTokenTtl ?? DEFAULT_MFA_CONTEXT_TTL_SECONDS;
// CSP nonce for popup postMessage inline scripts
this.cspNonce = options.cspNonce;
// Store keypair if provided, but validate lazily to avoid crypto bundling
this.dpopKeyPair = options.dpopKeyPair;
}
/**
* Lazy validation of DPoP configuration.
* Validates both provided keypairs and environment variables.
* Only imports dpopUtils (with crypto) when actually needed.
*/
private async ensureDpopValidated(): Promise<void> {
if (this.dpopValidated || !this.useDPoP) {
return;
}
// Dynamic import only when needed - prevents crypto from being bundled
const dpopModule = await import("../utils/dpopUtils.js");
const dpopConfig = await dpopModule.validateDpopConfiguration({
useDPoP: this.useDPoP,
dpopKeyPair: this.dpopKeyPair, // Pass existing keypair for validation
dpopOptions: this.dpopOptions
});
if (dpopConfig.dpopKeyPair) {
this.dpopKeyPair = dpopConfig.dpopKeyPair;
}
if (dpopConfig.dpopOptions) {
this.dpopOptions = dpopConfig.dpopOptions;
// Update clientMetadata with resolved values from environment variables
// This ensures clockSkew/clockTolerance from env vars are applied to OAuth operations
if (typeof this.dpopOptions.clockSkew === "number") {
this.clientMetadata[oauth.clockSkew] = this.dpopOptions.clockSkew;
}
if (typeof this.dpopOptions.clockTolerance === "number") {
this.clientMetadata[oauth.clockTolerance] =
this.dpopOptions.clockTolerance;
}
}
this.dpopValidated = true;
}
async handler(req: NextRequest): Promise<NextResponse> {
let { pathname } = req.nextUrl;
// Next.js does NOT automatically strip basePath from pathname in middleware.
// We must manually strip it to match against our route configurations.
// Example: With basePath='/app', a request to '/app/auth/login' will have
// pathname='/app/auth/login', but routes are configured as '/auth/login'.
const basePath = req.nextUrl.basePath;
if (basePath && pathname.startsWith(basePath)) {
pathname = pathname.slice(basePath.length) || "/";
}
const sanitizedPathname = removeTrailingSlash(pathname);
const method = req.method;
if (method === "GET" && sanitizedPathname === this.routes.login) {
return this.handleLogin(req);
} else if (method === "GET" && sanitizedPathname === this.routes.logout) {
return this.handleLogout(req);
} else if (method === "GET" && sanitizedPathname === this.routes.callback) {
return this.handleCallback(req);
} else if (method === "GET" && sanitizedPathname === this.routes.profile) {
return this.handleProfile(req);
} else if (
method === "GET" &&
sanitizedPathname === this.routes.accessToken &&
this.enableAccessTokenEndpoint
) {
return this.handleAccessToken(req);
} else if (
method === "POST" &&
sanitizedPathname === this.routes.backChannelLogout
) {
return this.handleBackChannelLogout(req);
} else if (
method === "GET" &&
sanitizedPathname === this.routes.connectAccount &&
this.enableConnectAccountEndpoint
) {
return this.handleConnectAccount(req);
} else if (
method === "GET" &&
sanitizedPathname === this.routes.mfaAuthenticators
) {
return this.handleGetAuthenticators(req);
} else if (
method === "POST" &&
sanitizedPathname === this.routes.mfaChallenge
) {
return this.handleChallenge(req);
} else if (
method === "POST" &&
sanitizedPathname === this.routes.mfaAssociate
) {
return this.handleAssociate(req);
} else if (
method === "POST" &&
sanitizedPathname === this.routes.mfaVerify
) {
return this.handleVerify(req);
} else if (
method === "POST" &&
sanitizedPathname === this.routes.passwordlessStart
) {
return this.handlePasswordlessStart(req);
} else if (
method === "POST" &&
sanitizedPathname === this.routes.passwordlessVerify
) {
return this.handlePasswordlessVerify(req);
} else if (
method === "POST" &&
sanitizedPathname === this.routes.passwordlessDbOtpChallenge
) {
return this.handlePasswordlessDbOtpChallenge(req);
} else if (
method === "POST" &&
sanitizedPathname === this.routes.passwordlessDbGetToken
) {
return this.handlePasswordlessDbGetToken(req);
} else if (
method === "POST" &&
sanitizedPathname === this.routes.passkeyRegister
) {
return this.handlePasskeyRegister(req);
} else if (
method === "POST" &&
sanitizedPathname === this.routes.passkeyChallenge
) {
return this.handlePasskeyChallenge(req);
} else if (
method === "POST" &&
sanitizedPathname === this.routes.passkeyGetToken
) {
return this.handlePasskeyGetToken(req);
} else if (
method === "POST" &&
sanitizedPathname === this.routes.passkeyEnrollmentChallenge
) {
return this.handlePasskeyEnrollmentChallenge(req);
} else if (
method === "POST" &&
sanitizedPathname === this.routes.passkeyEnrollmentVerify
) {
return this.handlePasskeyEnrollmentVerify(req);
} else if (sanitizedPathname.startsWith("/me/")) {
return this.handleMyAccount(req);
} else if (sanitizedPathname.startsWith("/my-org/")) {
return this.handleMyOrg(req);
} else {
// no auth handler found, simply touch the sessions if rolling sessions are enabled.
// TODO: we should try to avoid reading from the DB (for stateful sessions) on every
// request if possible.
const res = NextResponse.next();
if (
this.sessionStore.isRolling &&
(await this.sessionStore.shouldRollSession(req))
) {
const { error, session } = await this.getSessionWithDomainCheck(
req.cookies
);
if (error instanceof SessionDomainMismatchError) {
console.warn(`[nextjs-auth0] ${error.message}`);
}
if (!error && session) {
// we pass the existing session (containing an `createdAt` timestamp) to the set method
// which will update the cookie's `maxAge` property based on the `createdAt` time
await this.sessionStore.set(req.cookies, res.cookies, {
...session
});
addCacheControlHeadersForSession(res);
}
}
return res;
}
}
async startInteractiveLogin(
options: StartInteractiveLoginOptions = {},
req?: NextRequest
): Promise<NextResponse> {
await this.ensureDpopValidated();
const appBaseUrl = resolveAppBaseUrl(this.appBaseUrl, req);
const redirectUri = createRouteUrl(
this.routes.callback,
appBaseUrl
).toString(); // must be registered with the authorization server
let returnTo = this.signInReturnToPath;
// Validate returnTo parameter
if (options.returnTo) {
const safeBaseUrl = new URL(
(this.authorizationParameters.redirect_uri as string | undefined) ||
appBaseUrl
);
const sanitizedReturnTo = toSafeRedirect(options.returnTo, safeBaseUrl);
if (sanitizedReturnTo) {
returnTo =
sanitizedReturnTo.pathname +
sanitizedReturnTo.search +
sanitizedReturnTo.hash;
}
}
// Generate PKCE challenges
const codeChallengeMethod = "S256";
const codeVerifier = oauth.generateRandomCodeVerifier();
const codeChallenge = await oauth.calculatePKCECodeChallenge(codeVerifier);
const state = oauth.generateRandomState();
const nonce = oauth.generateRandomNonce();
// Construct base authorization parameters
// If provided on both sides, this does not merge the scope property,
// instead, the scope from the right side (options) fully overrides the left side.
const authorizationParams = mergeAuthorizationParamsIntoSearchParams(
this.authorizationParameters,
options.authorizationParameters,
INTERNAL_AUTHORIZE_PARAMS
);
authorizationParams.set("client_id", this.clientMetadata.client_id);
authorizationParams.set("redirect_uri", redirectUri);
authorizationParams.set("response_type", RESPONSE_TYPES.CODE);
authorizationParams.set("code_challenge", codeChallenge);
authorizationParams.set("code_challenge_method", codeChallengeMethod);
authorizationParams.set("state", state);
authorizationParams.set("nonce", nonce);
// Add dpop_jkt parameter if DPoP is enabled
if (this.dpopKeyPair) {
try {
const publicKeyJwk = await jose.exportJWK(this.dpopKeyPair.publicKey);
const dpopJkt = await jose.calculateJwkThumbprint(publicKeyJwk);
authorizationParams.set("dpop_jkt", dpopJkt);
} catch (error) {
throw new DPoPError(
DPoPErrorCode.DPOP_JKT_CALCULATION_FAILED,
"DPoP is enabled but failed to calculate key thumbprint (dpop_jkt). " +
"This is required for secure DPoP binding. Please check your key configuration.",
error instanceof Error ? error : undefined
);
}
}
// Resolve challengeMode: controls whether handleCallback returns a redirect
// (standard) or postMessage HTML (popup flows). Only stored in TransactionState
// when non-default to minimize encrypted cookie size.
const challengeMode = options.challengeMode || "redirect";
// Runtime guard — TypeScript enforces at compile time, but JS callers
// or incorrect casts could pass invalid values.
if (challengeMode !== "redirect" && challengeMode !== "popup") {
throw new InvalidConfigurationError(
`Invalid challengeMode: ${challengeMode}. Expected 'redirect' or 'popup'.`
);
}
// Enforce openid scope in resolver mode
if (this.provider?.isResolverMode) {
// Merge scopes from baseConfig defaults and explicit options
const explicitScope = options.authorizationParameters?.scope;
const defaultScope = this.authorizationParameters.scope || "";
// Combine scopes: base config defaults + explicit options
const scopeString = [defaultScope, explicitScope]
.filter(Boolean)
.join(" ");
const scopeSet = new Set(scopeString.split(/\s+/).filter(Boolean));
// Enforce openid scope in resolver mode
if (!scopeSet.has("openid")) {
throw new InvalidConfigurationError(
'The "openid" scope is required in resolver mode (DomainResolver). ' +
'Add "openid" to your SDK configuration or login options.'
);
}
}
// Prepare transaction state
// Read max_age from the already-merged authorizationParams (not the static SDK config)
// so that per-request values (e.g. max_age=0 for step-up auth) are preserved for
// auth_time validation at callback. Falls back to SDK-level config when absent.
const requestedMaxAgeStr = authorizationParams.get("max_age");
let resolvedMaxAge: number | undefined =
this.authorizationParameters.max_age;
if (requestedMaxAgeStr !== null) {
const parsed = parseNonNegativeIntegerParam(
"max_age",
requestedMaxAgeStr
);
if (parsed === null) {
throw new InvalidConfigurationError(
`Invalid max_age parameter: "${requestedMaxAgeStr}". Must be a non-negative integer.`
);
}
resolvedMaxAge = parsed;
}
const transactionState: TransactionState = {
nonce,
maxAge: resolvedMaxAge,
codeVerifier,
responseType: RESPONSE_TYPES.CODE,
state,
returnTo,
scope: authorizationParams.get("scope") || undefined,
audience: authorizationParams.get("audience") || undefined,
challengeMode: challengeMode !== "redirect" ? challengeMode : undefined,
// Store origin domain and issuer for callback delegation in resolver mode
originDomain: this.provider?.isResolverMode ? this.domain : undefined,
originIssuer: this.provider?.isResolverMode ? this.issuer : undefined
};
// Generate authorization URL with PAR handling
const [error, authorizationUrl] =
await this.authorizationUrl(authorizationParams);
if (error) {
return new NextResponse(
"An error occurred while trying to initiate the login request.",
{
status: 500
}
);
}
// Set response and save transaction
const res = NextResponse.redirect(authorizationUrl.toString());
// Save transaction state
await this.transactionStore.save(res.cookies, transactionState);
return res;
}
async handleLogin(req: NextRequest): Promise<NextResponse> {
const searchParams = Object.fromEntries(req.nextUrl.searchParams.entries());
// Extract challengeMode from URL query params.
// URL param takes precedence over programmatic StartInteractiveLoginOptions.challengeMode.
// Must be deleted before forwarding remaining params to Auth0 /authorize.
const queryChallengeMode = searchParams.challengeMode;
delete searchParams.challengeMode;
// Validate challengeMode value
if (
queryChallengeMode &&
queryChallengeMode !== "popup" &&
queryChallengeMode !== "redirect"
) {
return new NextResponse(
`Invalid challengeMode query param: ${queryChallengeMode}. Expected 'redirect', 'popup', or omit.`,
{ status: 400 }
);
}
// Validate max_age query param value
if (
searchParams.max_age !== undefined &&
parseNonNegativeIntegerParam("max_age", searchParams.max_age) === null
) {
return new NextResponse(
`Invalid max_age query param: "${searchParams.max_age}". Must be a non-negative integer.`,
{ status: 400 }
);
}
// do not pass returnTo as part of authorizationParameters
// returnTo should only be used in txn state
const { returnTo, ...authorizationParameters } = searchParams;
const options: StartInteractiveLoginOptions = {
authorizationParameters,
returnTo: returnTo,
challengeMode: queryChallengeMode as "redirect" | "popup" | undefined
};
return this.startInteractiveLogin(options, req);
}
async handleLogout(req: NextRequest): Promise<NextResponse> {
const {
error: sessionError,
session,
exists: sessionExists
} = await this.getSessionWithDomainCheck(req.cookies);
// Propagate domain mismatch error but don't delete session on domain mismatch
const hasDomainMismatch = sessionError && sessionExists;
const [discoveryError, authorizationServerMetadata] =
await this.discoverAuthorizationServerMetadata();
if (discoveryError) {