-
Notifications
You must be signed in to change notification settings - Fork 463
Expand file tree
/
Copy pathclient.ts
More file actions
1890 lines (1730 loc) · 67.6 KB
/
Copy pathclient.ts
File metadata and controls
1890 lines (1730 loc) · 67.6 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 type { IncomingMessage, ServerResponse } from "http";
import type { ParsedUrlQuery } from "querystring";
import { cookies, headers as getHeaders } from "next/headers.js";
import { NextRequest, NextResponse } from "next/server.js";
import { NextApiHandler, NextApiRequest, NextApiResponse } from "next/types.js";
import {
AccessTokenError,
AccessTokenErrorCode,
AccessTokenForConnectionError,
AccessTokenForConnectionErrorCode,
ConnectAccountError,
ConnectAccountErrorCodes,
InvalidConfigurationError,
MfaRequiredError
} from "../errors/index.js";
import { DpopKeyPair, DpopOptions } from "../types/dpop.js";
import {
AccessTokenForConnectionOptions,
AuthorizationParameters,
BackchannelAuthenticationOptions,
ConnectAccountOptions,
CustomTokenExchangeOptions,
CustomTokenExchangeResponse,
GetAccessTokenOptions,
LogoutStrategy,
SessionData,
SessionDataStore,
StartInteractiveLoginOptions,
User
} from "../types/index.js";
import type { DiscoveryCacheOptions, DomainResolver } from "../types/mcd.js";
import {
DEFAULT_MFA_CONTEXT_TTL_SECONDS,
DEFAULT_SCOPES
} from "../utils/constants.js";
import { isRequest } from "../utils/request.js";
import { getSessionChangesAfterGetAccessToken } from "../utils/session-changes-helpers.js";
import { AuthClientProvider } from "./auth-client-provider.js";
import {
AuthClient,
BeforeSessionSavedHook,
OnCallbackHook,
Routes,
RoutesOptions
} from "./auth-client.js";
import { RequestCookies, ResponseCookies } from "./cookies.js";
import { DiscoveryCache } from "./discovery-cache.js";
import { AccessTokenFactory, CustomFetchImpl, Fetcher } from "./fetcher.js";
import * as withApiAuthRequired from "./helpers/with-api-auth-required.js";
import {
appRouteHandlerFactory,
AppRouterPageRoute,
AppRouterPageRouteOpts,
PageRoute,
pageRouteHandlerFactory,
WithPageAuthRequiredAppRouterOptions,
WithPageAuthRequiredPageRouterOptions
} from "./helpers/with-page-auth-required.js";
import { ServerMfaClient } from "./mfa/server-mfa-client.js";
import {
toHeadersFromIncomingMessage,
toNextRequest,
toNextResponse,
toUrlFromPagesRouter
} from "./next-compat.js";
import { ServerPasskeyClient } from "./passkey/server-passkey-client.js";
import { ServerPasswordlessClient } from "./passwordless/server-passwordless-client.js";
import {
AbstractSessionStore,
SessionConfiguration,
SessionCookieOptions
} from "./session/abstract-session-store.js";
import { StatefulSessionStore } from "./session/stateful-session-store.js";
import { StatelessSessionStore } from "./session/stateless-session-store.js";
import {
TransactionCookieOptions,
TransactionStore
} from "./transaction-store.js";
export interface Auth0ClientOptions {
// authorization server configuration
/**
* The Auth0 domain for the tenant.
*
* - `string`: Static domain (e.g., `"example.us.auth0.com"`). Existing behavior preserved.
* - `DomainResolver`: Async function resolving domain per-request from headers.
* Enables Multiple Custom Domains (MCD) for B2C multi-brand, B2B SaaS, or domain migration.
*
* Falls back to `AUTH0_DOMAIN` environment variable if not provided.
*
* @see {@link DomainResolver} for resolver signature and examples.
* @see [MCD Examples](https://github.com/auth0/nextjs-auth0/blob/main/EXAMPLES.md#multiple-custom-domains-mcd)
*/
domain?: string | DomainResolver;
/**
* The Auth0 client ID.
*
* If it's not specified, it will be loaded from the `AUTH0_CLIENT_ID` environment variable.
*/
clientId?: string;
/**
* The Auth0 client secret.
*
* If it's not specified, it will be loaded from the `AUTH0_CLIENT_SECRET` environment variable.
*/
clientSecret?: string;
/**
* Additional parameters to send to the `/authorize` endpoint.
*/
authorizationParameters?: AuthorizationParameters;
/**
* If enabled, the SDK will use the Pushed Authorization Requests (PAR) protocol when communicating with the authorization server.
*/
pushedAuthorizationRequests?: boolean;
/**
* Private key for use with `private_key_jwt` clients.
* This should be a string that is the contents of a PEM file or a CryptoKey.
*/
clientAssertionSigningKey?: string | CryptoKey;
/**
* The algorithm used to sign the client assertion JWT.
* Uses one of `token_endpoint_auth_signing_alg_values_supported` if not specified.
* If the Authorization Server discovery document does not list `token_endpoint_auth_signing_alg_values_supported`
* this property will be required.
*/
clientAssertionSigningAlg?: string;
// application configuration
/**
* The URL of your application (e.g.: `http://localhost:3000`).
*
* Can be a single URL string, or an array of allowed base URLs. When an array is
* provided, the SDK validates the incoming request origin against the list and uses
* the matching entry (allow-list mode). This is useful for multi-domain or preview
* deployments where you want to restrict which origins are accepted.
*
* If it's not specified, it will be loaded from the `APP_BASE_URL` environment variable.
* Multiple origins can be provided as a comma-separated string (e.g. `https://app.example.com,https://myapp.vercel.app`).
* If neither is provided, the SDK will infer it from the request host at runtime.
*/
appBaseUrl?: string | string[];
/**
* A 32-byte, hex-encoded secret used for encrypting cookies.
*
* If it's not specified, it will be loaded from the `AUTH0_SECRET` environment variable.
*/
secret?: string;
/**
* The path to redirect the user to after successfully authenticating. Defaults to `/`.
*/
signInReturnToPath?: string;
// session configuration
/**
* Configure the session timeouts and whether to use rolling sessions or not.
*
* See [Session configuration](https://github.com/auth0/nextjs-auth0/blob/main/EXAMPLES.md#session-configuration) for additional details.
*/
session?: SessionConfiguration;
// transaction cookie configuration
/**
* Configure the transaction cookie used to store the state of the authentication transaction.
*/
transactionCookie?: TransactionCookieOptions;
// logout configuration
/**
* Configure the logout strategy to use.
*
* - `'auto'` (default): Attempts OIDC RP-Initiated Logout first, falls back to `/v2/logout` if not supported
* - `'oidc'`: Always uses OIDC RP-Initiated Logout (requires RP-Initiated Logout to be enabled)
* - `'v2'`: Always uses the Auth0 `/v2/logout` endpoint (supports wildcards in allowed logout URLs)
*/
logoutStrategy?: LogoutStrategy;
/**
* Configure whether to include id_token_hint in OIDC logout URLs.
*
* **Recommended (default)**: Set to `true` to include `id_token_hint` parameter.
* Auth0 recommends using `id_token_hint` for secure logout as per the
* OIDC specification.
*
* **Alternative approach**: Set to `false` if your application cannot securely
* store ID tokens. When disabled, only `logout_hint` (session ID), `client_id`,
* and `post_logout_redirect_uri` are sent.
*
*
* @see https://auth0.com/docs/authenticate/login/logout/log-users-out-of-auth0#oidc-logout-endpoint-parameters
* @default true (recommended and backwards compatible)
*/
includeIdTokenHintInOIDCLogoutUrl?: boolean;
// hooks
/**
* A method to manipulate the session before persisting it.
*
* See [beforeSessionSaved](https://github.com/auth0/nextjs-auth0/blob/main/EXAMPLES.md#beforesessionsaved) for additional details
*/
beforeSessionSaved?: BeforeSessionSavedHook;
/**
* A method to handle errors or manage redirects after attempting to authenticate.
*
* See [onCallback](https://github.com/auth0/nextjs-auth0/blob/main/EXAMPLES.md#oncallback) for additional details
*/
onCallback?: OnCallbackHook;
// provide a session store to persist sessions in your own data store
/**
* A custom session store implementation used to persist sessions to a data store.
*
* See [Database sessions](https://github.com/auth0/nextjs-auth0/blob/main/EXAMPLES.md#database-sessions) for additional details.
*/
sessionStore?: SessionDataStore;
/**
* Configure the paths for the authentication routes.
*
* See [Custom routes](https://github.com/auth0/nextjs-auth0/blob/main/EXAMPLES.md#custom-routes) for additional details.
*/
routes?: RoutesOptions;
/**
* Allow insecure requests to be made to the authorization server. This can be useful when testing
* with a mock OIDC provider that does not support TLS, locally.
* This option can only be used when NODE_ENV is not set to `production`.
*/
allowInsecureRequests?: boolean;
/**
* Integer value for the HTTP timeout in milliseconds for authentication requests.
* Defaults to `5000` ms.
*/
httpTimeout?: number;
/**
* Boolean value to opt-out of sending the library name and version to your authorization server
* via the `Auth0-Client` header. Defaults to `true`.
*/
enableTelemetry?: boolean;
/**
* Boolean value to enable the `/auth/access-token` endpoint for use in the client app.
*
* Defaults to `true`.
*
* NOTE: Set this to `false` if your client does not need to directly interact with resource servers (Token Mediating Backend). This will be false for most apps.
*
* A security best practice is to disable this to avoid exposing access tokens to the client app.
*
* See: https://datatracker.ietf.org/doc/html/draft-ietf-oauth-browser-based-apps#name-token-mediating-backend
*/
enableAccessTokenEndpoint?: boolean;
/**
* Number of seconds to refresh access tokens early when calling `getAccessToken`.
* This is a server-side buffer applied to token expiration checks. For example,
* with a buffer of 60 seconds, tokens expiring within the next minute will be
* refreshed proactively when a refresh token is available.
*
* Defaults to `0` (no early refresh).
*/
tokenRefreshBuffer?: number;
/**
* If true, the profile endpoint will return a 204 No Content response when the user is not authenticated
* instead of returning a 401 Unauthorized response.
*
* Defaults to `false`.
*/
noContentProfileResponseWhenUnauthenticated?: boolean;
enableParallelTransactions?: boolean;
/**
* If true, the `/auth/connect` endpoint will be mounted to enable users to connect additional accounts.
*/
enableConnectAccountEndpoint?: boolean;
// DPoP Configuration
/**
* Enable DPoP (Demonstrating Proof-of-Possession) for enhanced OAuth 2.0 security.
*
* When enabled, the SDK will:
* - Generate DPoP proofs for token requests and protected resource requests
* - Bind access tokens cryptographically to the client's key pair
* - Prevent token theft and replay attacks
* - Handle DPoP nonce errors with automatic retry logic
*
* DPoP requires an ES256 key pair that can be provided via `dpopKeyPair` option
* or loaded from environment variables `AUTH0_DPOP_PUBLIC_KEY` and `AUTH0_DPOP_PRIVATE_KEY`.
*
* @default false
*
* @example Enable DPoP with generated keys
* ```typescript
* import { generateKeyPair } from "oauth4webapi";
*
* const dpopKeyPair = await generateKeyPair("ES256");
*
* const auth0 = new Auth0Client({
* useDPoP: true,
* dpopKeyPair
* });
* ```
*
* @example Enable DPoP with environment variables
* ```typescript
* // .env.local
* // AUTH0_DPOP_PUBLIC_KEY="-----BEGIN PUBLIC KEY-----..."
* // AUTH0_DPOP_PRIVATE_KEY="-----BEGIN PRIVATE KEY-----..."
*
* const auth0 = new Auth0Client({
* useDPoP: true
* // Keys loaded automatically from environment
* });
* ```
*
* @see {@link https://datatracker.ietf.org/doc/html/rfc9449 | RFC 9449: OAuth 2.0 Demonstrating Proof-of-Possession at the Application Layer (DPoP)}
*/
useDPoP?: boolean;
/**
* ES256 key pair for DPoP proof generation.
*
* If not provided when `useDPoP` is true, the SDK will attempt to load keys from
* environment variables `AUTH0_DPOP_PUBLIC_KEY` and `AUTH0_DPOP_PRIVATE_KEY`.
* Keys must be in PEM format and use the P-256 elliptic curve.
*
* @example Provide key pair directly
* ```typescript
* import { generateKeyPair } from "oauth4webapi";
*
* const keyPair = await generateKeyPair("ES256");
*
* const auth0 = new Auth0Client({
* useDPoP: true,
* dpopKeyPair: keyPair
* });
* ```
*
* @example Load from files
* ```typescript
* import { importSPKI, importPKCS8 } from "jose";
* import { readFileSync } from "fs";
*
* const publicKeyPem = readFileSync("dpop-public.pem", "utf8");
* const privateKeyPem = readFileSync("dpop-private.pem", "utf8");
*
* const auth0 = new Auth0Client({
* useDPoP: true,
* dpopKeyPair: {
* publicKey: await importSPKI(publicKeyPem, "ES256"),
* privateKey: await importPKCS8(privateKeyPem, "ES256")
* }
* });
* ```
*
* @see {@link DpopKeyPair} for the key pair interface
* @see {@link generateDpopKeyPair} for generating new key pairs
*/
dpopKeyPair?: DpopKeyPair;
/**
* Configuration options for DPoP timing validation and retry behavior.
*
* These options control how the SDK validates DPoP proof timing and handles
* nonce errors. Proper configuration is important for both security and reliability.
*
* @example Basic configuration
* ```typescript
* const auth0 = new Auth0Client({
* useDPoP: true,
* dpopOptions: {
* clockTolerance: 60, // Allow 60 seconds clock difference
* clockSkew: 0, // No clock adjustment needed
* retry: {
* delay: 200, // 200ms delay before retry
* jitter: true // Add randomness to prevent thundering herd
* }
* }
* });
* ```
*
* @example Environment variable configuration
* ```bash
* # .env.local
* AUTH0_DPOP_CLOCK_SKEW=0
* AUTH0_DPOP_CLOCK_TOLERANCE=30
* AUTH0_RETRY_DELAY=100
* AUTH0_RETRY_JITTER=true
* ```
*
* @see {@link DpopOptions} for detailed option descriptions
*/
dpopOptions?: DpopOptions;
// mTLS Configuration
/**
* Enable mTLS (Mutual TLS, RFC 8705) client authentication.
*
* When `true`, the SDK authenticates with Auth0 using a client TLS certificate
* instead of a client secret or private-key JWT. Access tokens issued by Auth0
* will be certificate-bound (`cnf.x5t#S256` claim), providing strong proof-of-possession
* protection against token theft.
*
* Using mTLS requires:
* 1. A TLS-aware `customFetch` implementation that attaches your client certificate
* (e.g. Node.js `undici` configured with `connect: { key, cert }`).
* 2. The mTLS feature to be enabled on your Auth0 tenant.
*
* You do **not** need to provide `clientSecret` or `clientAssertionSigningKey`
* when `useMtls` is `true` — the certificate is the sole client credential.
*
* Can also be enabled by setting the `AUTH0_MTLS=true` environment variable.
*
* @default false
*
* @example
* ```typescript
* import { Agent, fetch as undiciFetch } from "undici";
* import { readFileSync } from "fs";
*
* const tlsAgent = new Agent({
* connect: {
* key: readFileSync("client.key"),
* cert: readFileSync("client.crt")
* }
* });
*
* export const auth0 = new Auth0Client({
* useMtls: true,
* customFetch: (url, init) =>
* undiciFetch(url, { ...init, dispatcher: tlsAgent })
* });
* ```
*
* @see {@link https://datatracker.ietf.org/doc/html/rfc8705 | RFC 8705: OAuth 2.0 Mutual-TLS Client Authentication}
*/
useMtls?: boolean;
/**
* A custom `fetch` implementation used for all outbound requests to Auth0.
*
* Required when `useMtls` is `true` — provide a TLS-aware implementation that
* attaches your client certificate to every request (e.g. `undici` with
* `connect: { key, cert }`).
*
* Can also be used independently (without mTLS) to proxy requests, add custom
* headers, or inject test doubles in unit tests.
*
* @example
* ```typescript
* import { Agent, fetch as undiciFetch } from "undici";
*
* const tlsAgent = new Agent({ connect: { cert, key } });
*
* export const auth0 = new Auth0Client({
* useMtls: true,
* customFetch: (url, init) =>
* undiciFetch(url, { ...init, dispatcher: tlsAgent })
* });
* ```
*/
customFetch?: typeof fetch;
/**
* MFA context TTL in seconds. Controls how long encrypted mfa_token remains valid.
* Default: 300 (5 minutes, matching Auth0's mfa_token expiration)
*
* Can also be set via AUTH0_MFA_TOKEN_TTL environment variable.
*
* @example
* ```typescript
* const auth0 = new Auth0Client({
* mfaTokenTtl: 600 // 10 minutes
* });
* ```
*/
mfaTokenTtl?: number;
/**
* Content Security Policy nonce for inline scripts in popup flows.
*
* Required when your application uses CSP and the popup-based step-up
* authentication flow (challengeMode: 'popup'). The nonce is
* injected into the inline `<script>` tag of the postMessage HTML response.
*
* @example
* ```typescript
* const auth0 = new Auth0Client({
* cspNonce: crypto.randomUUID()
* });
* ```
*/
cspNonce?: string;
/**
* Configuration for the OIDC discovery metadata cache.
* Controls TTL and maximum cached issuers for MCD resolver mode.
* Also applies in static mode (single cached entry).
*
* @see {@link DiscoveryCacheOptions}
* @see [MCD Examples](https://github.com/auth0/nextjs-auth0/blob/main/EXAMPLES.md#multiple-custom-domains-mcd)
*/
discoveryCache?: DiscoveryCacheOptions;
}
export type PagesRouterRequest = IncomingMessage | NextApiRequest;
export type PagesRouterResponse =
ServerResponse<IncomingMessage> | NextApiResponse;
export class Auth0Client {
private transactionStore: TransactionStore;
private sessionStore: AbstractSessionStore;
private provider: AuthClientProvider;
private routes: Routes;
private _mfa?: ServerMfaClient;
private _passwordless?: ServerPasswordlessClient;
private _passkey?: ServerPasskeyClient;
#options: Auth0ClientOptions;
constructor(options: Auth0ClientOptions = {}) {
this.#options = options;
// Extract and validate required options
const {
domain,
clientId,
clientSecret,
appBaseUrl,
secret,
clientAssertionSigningKey
} = this.validateAndExtractRequiredOptions(options);
const clientAssertionSigningAlg =
options.clientAssertionSigningAlg ||
process.env.AUTH0_CLIENT_ASSERTION_SIGNING_ALG;
// Early warning if DPoP is enabled but no keypair (doesn't require crypto)
if (options.useDPoP && !options.dpopKeyPair) {
const privateKeyEnv = process.env.AUTH0_DPOP_PRIVATE_KEY;
const publicKeyEnv = process.env.AUTH0_DPOP_PUBLIC_KEY;
const hasBothKeys = Boolean(privateKeyEnv && publicKeyEnv);
if (!hasBothKeys) {
console.warn(
"WARNING: useDPoP is set to true but dpopKeyPair is not provided. " +
"DPoP will not be used and protected requests will use bearer authentication instead. " +
"To enable DPoP, provide a dpopKeyPair in the Auth0Client options or set " +
"AUTH0_DPOP_PUBLIC_KEY and AUTH0_DPOP_PRIVATE_KEY environment variables."
);
}
// Note: If both env vars ARE present, validation happens lazily on first DPoP operation
// This prevents crypto module from being bundled when useDPoP=false
}
// Resolve MFA token TTL from options or environment variable
const mfaTokenTtl = this.resolveMfaTokenTtl(
options.mfaTokenTtl,
process.env.AUTH0_MFA_TOKEN_TTL
);
const tokenRefreshBufferOption = options.tokenRefreshBuffer;
if (tokenRefreshBufferOption != null) {
if (
typeof tokenRefreshBufferOption !== "number" ||
!Number.isFinite(tokenRefreshBufferOption) ||
tokenRefreshBufferOption < 0
) {
throw new TypeError(
"tokenRefreshBuffer must be a non-negative number of seconds."
);
}
}
const tokenRefreshBuffer = tokenRefreshBufferOption ?? 0;
// Auto-detect base path for cookie configuration
const basePath = process.env.NEXT_PUBLIC_BASE_PATH;
// Session cookie secure can be configured via options or AUTH0_COOKIE_SECURE.
const envCookieSecure = process.env.AUTH0_COOKIE_SECURE;
const sessionSecureExplicit =
options.session?.cookie?.secure ??
(envCookieSecure !== undefined ? envCookieSecure === "true" : undefined);
const sessionCookieOptions: SessionCookieOptions = {
name: options.session?.cookie?.name ?? "__session",
secure: sessionSecureExplicit ?? false,
sameSite:
options.session?.cookie?.sameSite ??
(process.env.AUTH0_COOKIE_SAME_SITE as "lax" | "strict" | "none") ??
"lax",
path:
options.session?.cookie?.path ??
process.env.AUTH0_COOKIE_PATH ??
basePath ??
"/",
transient:
options.session?.cookie?.transient ??
process.env.AUTH0_COOKIE_TRANSIENT === "true",
domain: options.session?.cookie?.domain ?? process.env.AUTH0_COOKIE_DOMAIN
};
// Transaction cookies only support secure via options (no env var).
const transactionSecureExplicit = options.transactionCookie?.secure;
const transactionCookieOptions: TransactionCookieOptions = {
prefix: options.transactionCookie?.prefix ?? "__txn_",
secure: transactionSecureExplicit ?? false,
sameSite: options.transactionCookie?.sameSite ?? "lax",
path: options.transactionCookie?.path ?? basePath ?? "/",
maxAge: options.transactionCookie?.maxAge ?? 3600,
domain:
options.transactionCookie?.domain ?? process.env.AUTH0_COOKIE_DOMAIN
};
if (appBaseUrl) {
const usesHttps = Array.isArray(appBaseUrl)
? appBaseUrl.every((url) => new URL(url).protocol === "https:")
: new URL(appBaseUrl).protocol === "https:";
// Only enforce secure cookies when the configured base URL(s) are all https.
if (usesHttps) {
sessionCookieOptions.secure = true;
transactionCookieOptions.secure = true;
}
} else if (process.env.NODE_ENV === "production") {
// No appBaseUrl is configured, so the SDK relies on the request host at runtime.
// In production we require secure cookies for this dynamic mode (and fail fast if
// a cookie is explicitly marked insecure) to avoid shipping non-secure defaults.
if (sessionSecureExplicit === false) {
throw new InvalidConfigurationError(
"Session cookies must be marked secure in production when appBaseUrl is not configured. Set AUTH0_COOKIE_SECURE=true or session.cookie.secure=true."
);
}
if (transactionSecureExplicit === false) {
throw new InvalidConfigurationError(
"Transaction cookies must be marked secure in production when appBaseUrl is not configured. Set transactionCookie.secure=true."
);
}
sessionCookieOptions.secure = true;
transactionCookieOptions.secure = true;
} else if (
process.env.NODE_ENV === "development" &&
(sessionSecureExplicit === false || transactionSecureExplicit === false)
) {
// Warn during development when dynamic base URL resolution is combined with
// explicitly insecure cookies, since production will reject this configuration.
console.warn(
"'appBaseUrl' is not configured and cookies are explicitly marked insecure. This is allowed in development, but will throw in production. Configure appBaseUrl or set secure=true for session/transaction cookies."
);
}
this.routes = {
login: process.env.NEXT_PUBLIC_LOGIN_ROUTE || "/auth/login",
logout: "/auth/logout",
callback: "/auth/callback",
backChannelLogout: "/auth/backchannel-logout",
profile: process.env.NEXT_PUBLIC_PROFILE_ROUTE || "/auth/profile",
accessToken:
process.env.NEXT_PUBLIC_ACCESS_TOKEN_ROUTE || "/auth/access-token",
connectAccount: "/auth/connect",
mfaAuthenticators:
process.env.NEXT_PUBLIC_MFA_AUTHENTICATORS_ROUTE ||
"/auth/mfa/authenticators",
mfaChallenge:
process.env.NEXT_PUBLIC_MFA_CHALLENGE_ROUTE || "/auth/mfa/challenge",
mfaVerify: process.env.NEXT_PUBLIC_MFA_VERIFY_ROUTE || "/auth/mfa/verify",
mfaAssociate:
process.env.NEXT_PUBLIC_MFA_ASSOCIATE_ROUTE || "/auth/mfa/associate",
// deleteAuthenticator uses mfaAuthenticators route with DELETE method
passwordlessStart:
process.env.NEXT_PUBLIC_PASSWORDLESS_START_ROUTE ||
"/auth/passwordless/start",
passwordlessVerify:
process.env.NEXT_PUBLIC_PASSWORDLESS_VERIFY_ROUTE ||
"/auth/passwordless/verify",
passwordlessDbOtpChallenge:
process.env.NEXT_PUBLIC_PASSWORDLESS_DB_OTP_CHALLENGE_ROUTE ||
"/auth/passwordless/otp/challenge",
passwordlessDbGetToken:
process.env.NEXT_PUBLIC_PASSWORDLESS_DB_GET_TOKEN_ROUTE ||
"/auth/passwordless/otp/token",
passkeyRegister:
process.env.NEXT_PUBLIC_PASSKEY_REGISTER_ROUTE ||
"/auth/passkey/register",
passkeyChallenge:
process.env.NEXT_PUBLIC_PASSKEY_CHALLENGE_ROUTE ||
"/auth/passkey/challenge",
passkeyGetToken:
process.env.NEXT_PUBLIC_PASSKEY_GET_TOKEN_ROUTE ||
"/auth/passkey/get-token",
passkeyEnrollmentChallenge:
process.env.NEXT_PUBLIC_PASSKEY_ENROLLMENT_CHALLENGE_ROUTE ||
"/auth/passkey/enrollment-challenge",
passkeyEnrollmentVerify:
process.env.NEXT_PUBLIC_PASSKEY_ENROLLMENT_VERIFY_ROUTE ||
"/auth/passkey/enrollment-verify",
...options.routes
};
this.transactionStore = new TransactionStore({
secret,
cookieOptions: transactionCookieOptions,
enableParallelTransactions: options.enableParallelTransactions ?? true
});
this.sessionStore = options.sessionStore
? new StatefulSessionStore({
...options.session,
secret,
store: options.sessionStore,
cookieOptions: sessionCookieOptions
})
: new StatelessSessionStore({
...options.session,
secret,
cookieOptions: sessionCookieOptions
});
// Create discovery cache for the provider
const discoveryCache = new DiscoveryCache(options.discoveryCache);
// When AUTH0_DOMAIN is not available at module evaluation time (e.g. during a
// Next.js standalone build that injects env vars only at runtime), `domain` will
// be undefined. Passing undefined to AuthClientProvider causes it to throw
// immediately in the constructor, which breaks the build.
//
// Work around this by converting a missing domain into a DomainResolver that
// reads AUTH0_DOMAIN lazily on the first request. If the env var is still absent
// at request time, the resolver will throw with a clear error message.
//
// If domain is already a string or a DomainResolver function, it is used as-is.
const domainForProvider: string | DomainResolver =
domain ||
(() => {
const runtimeDomain = process.env.AUTH0_DOMAIN;
if (!runtimeDomain) {
throw new InvalidConfigurationError(
"Missing: domain: Set AUTH0_DOMAIN env var or pass domain in options."
);
}
return runtimeDomain;
});
// Create provider that manages AuthClient instances
// Note: We defer the provider reference in the factory to avoid circular reference during construction.
// The factory captures 'this' by reference, and will read this.provider when called later (not during construction).
this.provider = new AuthClientProvider({
domain: domainForProvider,
allowInsecureRequests: options.allowInsecureRequests,
createAuthClient: (domainForClient, issuerForClient) => {
return new AuthClient({
transactionStore: this.transactionStore,
sessionStore: this.sessionStore,
domain: domainForClient,
issuer: issuerForClient,
clientId,
clientSecret,
clientAssertionSigningKey,
clientAssertionSigningAlg,
authorizationParameters: options.authorizationParameters,
pushedAuthorizationRequests: options.pushedAuthorizationRequests,
appBaseUrl,
secret,
signInReturnToPath: options.signInReturnToPath,
logoutStrategy: options.logoutStrategy,
includeIdTokenHintInOIDCLogoutUrl:
options.includeIdTokenHintInOIDCLogoutUrl,
beforeSessionSaved: options.beforeSessionSaved,
onCallback: options.onCallback,
routes: this.routes,
allowInsecureRequests: options.allowInsecureRequests,
httpTimeout: options.httpTimeout,
enableTelemetry: options.enableTelemetry,
enableAccessTokenEndpoint: options.enableAccessTokenEndpoint,
noContentProfileResponseWhenUnauthenticated:
options.noContentProfileResponseWhenUnauthenticated,
enableConnectAccountEndpoint: options.enableConnectAccountEndpoint,
tokenRefreshBuffer,
useDPoP: options.useDPoP || false,
dpopKeyPair: options.dpopKeyPair,
dpopOptions: options.dpopOptions,
useMtls: options.useMtls ?? process.env.AUTH0_MTLS === "true",
fetch: options.customFetch,
mfaTokenTtl,
cspNonce: options.cspNonce,
discoveryCache,
provider: this.provider
});
}
});
// Update provider references in any already-created AuthClients (static mode)
// This is needed because the factory in static mode is called during AuthClientProvider construction,
// before this.provider is fully assigned. The closure captures 'this', so by this point it will be valid.
const staticClient = this.provider.getAuthClientForStaticMode();
if (staticClient) {
staticClient.provider = this.provider;
}
}
/**
* middleware mounts the SDK routes to run as a middleware function.
*/
async middleware(req: Request | NextRequest): Promise<NextResponse> {
const nextReq = toNextRequest(req);
const authClient = await this.provider.forRequest(
nextReq.headers,
nextReq.nextUrl
);
return authClient.handler.bind(authClient)(nextReq);
}
/**
* getSession returns the session data for the current request.
*
* This method can be used in Server Components, Server Actions, and Route Handlers in the **App Router**.
*/
async getSession(): Promise<SessionData | null>;
/**
* getSession returns the session data for the current request.
*
* This method can be used in middleware and `getServerSideProps`, API routes in the **Pages Router**.
*/
async getSession(
req: PagesRouterRequest | NextRequest
): Promise<SessionData | null>;
/**
* getSession returns the session data for the current request.
*/
async getSession(
req?: Request | PagesRouterRequest | NextRequest
): Promise<SessionData | null> {
const { authClient, normalizedReq } = await this.resolveRequestContext(req);
// extract cookies
let reqCookies:
RequestCookies | import("./cookies.js").ReadonlyRequestCookies;
if (normalizedReq) {
reqCookies =
normalizedReq instanceof NextRequest
? normalizedReq.cookies
: this.createRequestCookies(normalizedReq);
} else {
reqCookies = await cookies();
}
const { error, session } =
await authClient.getSessionWithDomainCheck(reqCookies);
if (error) throw error;
return session;
}
/**
* Fetches session using an already-resolved AuthClient, avoiding double resolver invocation.
* @internal
*/
private async getSessionFromAuthClient(
authClient: AuthClient,
req?: PagesRouterRequest | NextRequest
): Promise<SessionData | null> {
let reqCookies:
RequestCookies | import("./cookies.js").ReadonlyRequestCookies;
if (req) {
reqCookies =
req instanceof NextRequest
? req.cookies
: this.createRequestCookies(req);
} else {
reqCookies = await cookies();
}
const { error, session } =
await authClient.getSessionWithDomainCheck(reqCookies);
if (error) throw error;
return session;
}
/**
* getAccessToken returns the access token.
*
* This method can be used in Server Components, Server Actions, and Route Handlers in the **App Router**.
*
* NOTE: Server Components cannot set cookies. Calling `getAccessToken()` in a Server Component will cause the access token to be refreshed, if it is expired, and the updated token set will not to be persisted.
* It is recommended to call `getAccessToken(req, res)` in the middleware if you need to retrieve the access token in a Server Component to ensure the updated token set is persisted.
*/
/**
* @param options Optional configuration for getting the access token.
* @param options.refresh Force a refresh of the access token.
*/
async getAccessToken(options?: GetAccessTokenOptions): Promise<{
token: string;
expiresAt: number;
scope?: string;
token_type?: string;
audience?: string;
}>;
/**
* getAccessToken returns the access token.
*
* This method can be used in middleware and `getServerSideProps`, API routes in the **Pages Router**.
*
* @param req The request object.
* @param res The response object.
* @param options Optional configuration for getting the access token.
* @param options.refresh Force a refresh of the access token.
*/
async getAccessToken(
req: PagesRouterRequest | NextRequest,
res: PagesRouterResponse | NextResponse,
options?: GetAccessTokenOptions
): Promise<{
token: string;
expiresAt: number;
scope?: string;
token_type?: string;
audience?: string;
}>;
/**
* getAccessToken returns the access token.
*
* Please note: If you are passing audience, ensure that the used audiences and scopes are
* part of the Application's Refresh Token Policies in Auth0 when configuring Multi-Resource Refresh Tokens (MRRT).
* {@link https://auth0.com/docs/secure/tokens/refresh-tokens/multi-resource-refresh-token|See Auth0 Documentation on Multi-resource Refresh Tokens}
*
* NOTE: Server Components cannot set cookies. Calling `getAccessToken()` in a Server Component will cause the access token to be refreshed, if it is expired, and the updated token set will not to be persisted.
* It is recommended to call `getAccessToken(req, res)` in the middleware if you need to retrieve the access token in a Server Component to ensure the updated token set is persisted.
*/
async getAccessToken(
arg1?: PagesRouterRequest | NextRequest | GetAccessTokenOptions,
arg2?: PagesRouterResponse | NextResponse,
arg3?: GetAccessTokenOptions
): Promise<{
token: string;
expiresAt: number;
scope?: string;
token_type?: string;
audience?: string;
}> {
const defaultOptions: GetAccessTokenOptions = {
refresh: false
};
let req: PagesRouterRequest | NextRequest | undefined = undefined;
let res: PagesRouterResponse | NextResponse | undefined = undefined;
let options: GetAccessTokenOptions = {};
// Determine which overload was called based on arguments
if (
arg1 &&
(arg1 instanceof Request || typeof (arg1 as any).headers === "object")
) {
// Case: getAccessToken(req, res, options?)
req = arg1 as PagesRouterRequest | NextRequest;
res = arg2; // arg2 must be Response if arg1 is Request
// Merge provided options (arg3) with defaults
options = { ...defaultOptions, ...(arg3 ?? {}) };
if (!res) {
throw new TypeError(
"getAccessToken(req, res): The 'res' argument is missing. Both 'req' and 'res' must be provided together for Pages Router or middleware usage."
);
}
} else {
// Case: getAccessToken(options?) or getAccessToken()
// arg1 (if present) must be options, arg2 and arg3 must be undefined.
if (arg2 !== undefined || arg3 !== undefined) {
throw new TypeError(
"getAccessToken: Invalid arguments. Valid signatures are getAccessToken(), getAccessToken(options), or getAccessToken(req, res, options)."
);
}
// Merge provided options (arg1) with defaults
options = {
...defaultOptions,
...((arg1 as GetAccessTokenOptions) ?? {})
};
}
return this.executeGetAccessToken(req, res, options);
}
/**
* Core implementation of getAccessToken that performs the actual token retrieval.
* This is separated to enable request coalescing via the cache.
*/
private async executeGetAccessToken(
req: PagesRouterRequest | NextRequest | undefined,
res: PagesRouterResponse | NextResponse | undefined,