-
Notifications
You must be signed in to change notification settings - Fork 159
Expand file tree
/
Copy pathcontext.js
More file actions
1059 lines (948 loc) · 34.7 KB
/
Copy pathcontext.js
File metadata and controls
1059 lines (948 loc) · 34.7 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
const url = require('url');
const urlJoin = require('url-join');
const {
jwtVerify,
createRemoteJWKSet,
customFetch: joseCustomFetch,
decodeJwt,
} = require('jose');
const TokenSet = require('./tokenset');
const clone = require('clone');
const { strict: assert } = require('assert');
const createError = require('http-errors');
const debug = require('./debug')('context');
const { once } = require('./once');
const {
get: getClient,
buildEndSessionUrl,
buildRequestObject,
decryptAccessToken,
client: oidcClient,
} = require('./client');
const { encodeState, decodeState } = require('../lib/hooks/getLoginState');
const onLogin = require('./hooks/backchannelLogout/onLogIn');
const onLogoutToken = require('./hooks/backchannelLogout/onLogoutToken');
const {
cancelSilentLogin,
resumeSilentLogin,
} = require('../middleware/attemptSilentLogin');
const weakRef = require('./weakCache');
const {
regenerateSessionStoreId,
replaceSession,
} = require('../lib/appSession');
const { SessionExpiredError } = require('./errors');
const { epoch } = require('./utils/epoch');
const {
extractSessionExpiry,
isSessionExpiryReached,
isSessionExpiryInPast,
} = require('./utils/sessionExpiry');
// Caches one RemoteJWKSet instance per auth() configuration for backchannel logout token verification.
const jwksClientCache = new Map();
/**
* Returns a RemoteJWKSet for verifying backchannel logout tokens.
*
* Creates the instance on first call and caches it against the config reference so
* subsequent backchannel logout requests reuse the same instance. This means the
* internal JWKS key cache built up over time is preserved across requests, avoiding
* a redundant fetch to the IdP's JWKS endpoint on every logout.
*/
async function getRemoteJWKSet(config) {
if (jwksClientCache.has(config)) {
return jwksClientCache.get(config);
}
const { serverMetadata } = await getClient(config);
if (!serverMetadata.jwks_uri) {
throw new Error('No JWKS URI available for token verification');
}
const pkg = require('../package.json');
const headers = new Headers();
headers.set(
'User-Agent',
config.httpUserAgent || `${pkg.name}/${pkg.version}`,
);
if (config.enableTelemetry) {
headers.set(
'Auth0-Client',
Buffer.from(
JSON.stringify({ name: pkg.name, version: pkg.version }),
).toString('base64'),
);
}
const fetchFn = config.customFetch || fetch;
const JWKS = createRemoteJWKSet(new URL(serverMetadata.jwks_uri), {
timeoutDuration: config.httpTimeout,
headers,
[joseCustomFetch]: (url, options) =>
fetchFn(url, {
...options,
signal: AbortSignal.timeout(config.httpTimeout),
}),
});
jwksClientCache.set(config, JWKS);
return JWKS;
}
const TOKEN_EXCHANGE_GRANT_TYPE =
'urn:ietf:params:oauth:grant-type:token-exchange';
const ACCESS_TOKEN_EXCHANGE_IDENTIFIER =
'urn:ietf:params:oauth:token-type:access_token';
/**
* Parameters that cannot be supplied via the `extra` option.
*
* 1. SDK-controlled — always set by the SDK; allowing overrides would break
* OAuth protocol integrity or client authentication.
*
* 2. First-class params — have dedicated, named fields in the options object.
* Accepting them again via `extra` would create ambiguity about precedence
* and hide intent (e.g. actor_token/actor_token_type must be paired and
* validated together; organization affects tenant context and must be explicit).
*
* Anything not listed here (e.g. `connection`, `resource`, `login_hint`) can be
* passed freely via `extra`.
*/
const PARAM_DENYLIST = Object.freeze(
new Set([
// SDK-controlled
'grant_type',
'client_id',
'client_secret',
'client_assertion',
'client_assertion_type',
// First-class params
'subject_token',
'subject_token_type',
'actor_token',
'actor_token_type',
'requested_token_type',
'organization',
'audience',
'aud',
'scope',
]),
);
function validateTokenExchangeExtras(extra) {
if (!extra) return {};
const result = {};
for (const [k, v] of Object.entries(extra)) {
if (PARAM_DENYLIST.has(k)) {
debug('customTokenExchange: extra param "%s" ignored (in denylist)', k);
} else {
result[k] = v;
}
}
return result;
}
/**
* Fails fast on common subject_token mistakes before hitting the network.
*/
function validateSubjectToken(token) {
if (typeof token !== 'string' || token.trim().length === 0) {
throw createError(400, 'subject_token is required for token exchange');
}
if (token !== token.trim()) {
throw createError(
400,
'subject_token must not include leading or trailing whitespace',
);
}
if (/^bearer\s+/i.test(token)) {
throw createError(
400,
"subject_token must not include the 'Bearer ' prefix",
);
}
}
/**
* Extracts the `act` claim for delegation flows.
* Prefers the id_token claims (via the helper openid-client attaches to every
* TokenEndpointResponse), then falls back to decoding the access_token JWT
* directly for M2M flows where no id_token is returned.
* Returns undefined silently when the access token is opaque or neither
* source carries the claim.
*/
function extractActClaim(exchanged) {
const idTokenClaims = exchanged.claims(); // undefined when no id_token
if (idTokenClaims && idTokenClaims.act) {
return idTokenClaims.act;
}
if (exchanged.access_token) {
try {
const decoded = decodeJwt(exchanged.access_token);
if (decoded.act) return decoded.act;
} catch {
// opaque access token — act claim not available
}
}
return undefined;
}
function isExpired() {
return tokenSet.call(this).expired();
}
/**
* Normalizes token_type to 'Bearer' for consistency with v4 behavior.
* openid-client v6 returns lowercase 'bearer', but we normalize to 'Bearer'
* to maintain backward compatibility in sessions and afterCallback.
*/
function normalizeTokenType(tokenType) {
return tokenType?.toLowerCase() === 'bearer' ? 'Bearer' : tokenType;
}
async function refresh({ tokenEndpointParams } = {}) {
let { config, req } = weakRef(this);
const session = req[config.session.name];
// Pre-check: do not call /oauth/token if the IdP session ceiling has passed.
// The authorization server has already revoked the session server-side at this point, so a
// refresh attempt would fail with invalid_grant anyway. Surfacing a clean
// SessionExpiredError is better than a confusing token-endpoint error.
if (isSessionExpiryReached(session?.sessionExpiresAt)) {
throw new SessionExpiredError();
}
const { configuration } = await getClient(config);
const oldTokenSet = tokenSet.call(this);
let parameters;
if (config.tokenEndpointParams || tokenEndpointParams) {
parameters = { ...config.tokenEndpointParams, ...tokenEndpointParams };
}
const newTokenSet = await oidcClient.refreshTokenGrant(
configuration,
oldTokenSet.refresh_token,
parameters,
);
// Decrypt the refreshed access token when JWE decryption is configured, so the
// stored token and req.oidc.accessToken remain plaintext JWTs after a refresh —
// consistent with the callback. Without this, encrypted tokens would revert to
// ciphertext on the first refresh.
let refreshedAccessToken = newTokenSet.access_token;
if (config.accessTokenDecryptionKey && refreshedAccessToken) {
try {
refreshedAccessToken = await decryptAccessToken(
refreshedAccessToken,
config.accessTokenDecryptionKey,
config.accessTokenDecryptionAlg,
);
} catch (error) {
throw createError(
500,
`Failed to decrypt the refreshed access token: ${error.message}. ` +
'Check that accessTokenDecryptionKey matches the key configured on the ' +
'authorization server, and that accessTokenDecryptionAlg (if set) matches ' +
'the JWE "alg".',
);
}
}
// Update the session, preserving sessionExpiresAt — the refresh-token grant
// does not return a session_expiry claim, so we must not overwrite the ceiling
// that was set at login.
Object.assign(session, {
access_token: refreshedAccessToken,
// If no new ID token assume the current ID token is valid.
id_token: newTokenSet.id_token || oldTokenSet.id_token,
// If no new refresh token assume the current refresh token is valid.
refresh_token: newTokenSet.refresh_token || oldTokenSet.refresh_token,
token_type: normalizeTokenType(newTokenSet.token_type),
expires_at: newTokenSet.expires_in
? epoch() + newTokenSet.expires_in
: undefined,
// Preserve the IdP session ceiling across refreshes — do not re-derive
// from the refresh response (it won't contain session_expiry).
...(session.sessionExpiresAt !== undefined && {
sessionExpiresAt: session.sessionExpiresAt,
}),
});
// Delete the old token set
const cachedTokenSet = weakRef(session);
delete cachedTokenSet.value;
return this.accessToken;
}
function tokenSet() {
const contextCache = weakRef(this);
const session = contextCache.req[contextCache.config.session.name];
if (!session || !('id_token' in session)) {
return undefined;
}
const cachedTokenSet = weakRef(session);
if (!('value' in cachedTokenSet)) {
const { id_token, access_token, refresh_token, token_type, expires_at } =
session;
cachedTokenSet.value = new TokenSet({
id_token,
access_token,
refresh_token,
token_type,
expires_at,
});
}
return cachedTokenSet.value;
}
class RequestContext {
constructor(config, req, res, next) {
Object.assign(weakRef(this), { config, req, res, next });
}
isAuthenticated() {
return !!this.idTokenClaims;
}
get idToken() {
try {
return tokenSet.call(this).id_token;
} catch {
return undefined;
}
}
get refreshToken() {
try {
return tokenSet.call(this).refresh_token;
} catch {
return undefined;
}
}
get accessToken() {
try {
const { access_token, token_type, expires_in } = tokenSet.call(this);
if (!access_token || !token_type || typeof expires_in !== 'number') {
return undefined;
}
return {
access_token,
token_type,
expires_in,
isExpired: isExpired.bind(this),
refresh: refresh.bind(this),
};
} catch {
return undefined;
}
}
get idTokenClaims() {
try {
const {
config: { session },
req,
} = weakRef(this);
// The ID Token from Auth0's Refresh Grant doesn't contain a "sid"
// so we should check the backup sid we stored at login.
const { sid } = req[session.name];
return { sid, ...clone(tokenSet.call(this).claims()) };
} catch {
return undefined;
}
}
get user() {
try {
const {
config: { identityClaimFilter },
} = weakRef(this);
const { idTokenClaims } = this;
const user = clone(idTokenClaims);
identityClaimFilter.forEach((claim) => {
delete user[claim];
});
return user;
} catch {
return undefined;
}
}
async fetchUserInfo() {
const { config } = weakRef(this);
const { configuration } = await getClient(config);
const ts = tokenSet.call(this);
if (!ts || !ts.access_token) {
throw new Error(
`Access token is required to fetch user info but none was found in the session.\n`,
);
}
const claims = ts.claims();
const sub = claims?.sub;
return oidcClient.fetchUserInfo(configuration, ts.access_token, sub);
}
async customTokenExchange(options = {}) {
const { config } = weakRef(this);
const { audience: defaultAudience, scope: defaultScope } =
config.authorizationParams;
const {
subject_token = this.accessToken && this.accessToken.access_token,
subject_token_type = ACCESS_TOKEN_EXCHANGE_IDENTIFIER,
actor_token,
actor_token_type,
requested_token_type,
organization,
audience = defaultAudience,
scope = defaultScope,
extra,
} = options;
validateSubjectToken(subject_token);
if (organization !== undefined && !organization.trim()) {
throw createError(400, 'organization must not be blank');
}
if (actor_token !== undefined && actor_token_type === undefined) {
throw createError(
400,
'actor_token_type is required when actor_token is provided',
);
}
debug('customTokenExchange() audience=%s scope=%s', audience, scope);
const { configuration } = await getClient(config);
const parameters = {
subject_token,
subject_token_type,
...(actor_token !== undefined && { actor_token }),
...(actor_token_type !== undefined && { actor_token_type }),
...(requested_token_type !== undefined && { requested_token_type }),
...(organization !== undefined && { organization }),
...(audience !== undefined && { audience }),
...(scope !== undefined && { scope }),
...validateTokenExchangeExtras(extra),
};
try {
const exchanged = await oidcClient.genericGrantRequest(
configuration,
TOKEN_EXCHANGE_GRANT_TYPE,
parameters,
);
const result = Object.assign({}, exchanged);
if (actor_token !== undefined) {
const act = extractActClaim(exchanged);
if (act !== undefined) {
result.act = act;
}
}
return result;
} catch (error) {
debug(
'customTokenExchange() failed: %s - %s',
error.error,
error.error_description,
);
const status = error.error === 'mfa_required' ? 401 : 400;
throw createError(status, error.message, {
error: error.error,
error_description: error.error_description,
});
}
}
}
class ResponseContext {
constructor(config, req, res, next, transient) {
Object.assign(weakRef(this), { config, req, res, next, transient });
}
get errorOnRequiredAuth() {
return weakRef(this).config.errorOnRequiredAuth;
}
getRedirectUri() {
const { config } = weakRef(this);
if (config.routes.callback) {
return urlJoin(config.baseURL, config.routes.callback);
}
}
silentLogin(options = {}) {
return this.login({
...options,
silent: true,
authorizationParams: { ...options.authorizationParams, prompt: 'none' },
});
}
async login(options = {}) {
let { config, req, res, next, transient } = weakRef(this);
next = once(next);
try {
const { configuration, serverMetadata } = await getClient(config);
// Set default returnTo value, allow passed-in options to override or use originalUrl on GET
let returnTo = config.baseURL;
if (options.returnTo) {
returnTo = options.returnTo;
debug('req.oidc.login() called with returnTo: %s', returnTo);
} else if (req.method === 'GET' && req.originalUrl) {
// Collapse any leading slashes to a single slash to prevent Open Redirects
returnTo = req.originalUrl.replace(/^\/+/, '/');
debug('req.oidc.login() without returnTo, using: %s', returnTo);
}
options = {
authorizationParams: {},
returnTo,
...options,
};
// Ensure a redirect_uri, merge in configuration options, then passed-in options.
options.authorizationParams = {
redirect_uri: this.getRedirectUri(),
...config.authorizationParams,
...options.authorizationParams,
};
const stateValue = await config.getLoginState(req, options);
if (typeof stateValue !== 'object') {
next(new Error('Custom state value must be an object.'));
}
if (options.silent) {
stateValue.attemptingSilentLogin = true;
}
const validResponseTypes = ['id_token', 'code id_token', 'code'];
assert(
validResponseTypes.includes(options.authorizationParams.response_type),
`response_type should be one of ${validResponseTypes.join(', ')}`,
);
assert(
/\bopenid\b/.test(options.authorizationParams.scope),
'scope should contain "openid"',
);
const authVerification = {
nonce: transient.generateNonce(),
state: encodeState(stateValue),
...(options.authorizationParams.max_age
? {
max_age: options.authorizationParams.max_age,
}
: undefined),
};
let authParams = {
...options.authorizationParams,
...authVerification,
};
const usePKCE =
options.authorizationParams.response_type.includes('code');
if (usePKCE) {
debug(
'response_type includes code, the authorization request will use PKCE',
);
authVerification.code_verifier = transient.generateCodeVerifier();
authParams.code_challenge_method = 'S256';
authParams.code_challenge = await transient.calculateCodeChallenge(
authVerification.code_verifier,
);
}
await transient.store(config.transactionCookie.name, req, res, {
sameSite:
options.authorizationParams.response_mode === 'form_post'
? 'None'
: config.transactionCookie.sameSite,
value: JSON.stringify(authVerification),
});
if (config.requestObjectSigningKey) {
// The request object's `aud` must exactly match the issuer identifier as
// advertised in discovery (which may include a trailing slash), not the
// configured issuerBaseURL.
const requestJwt = await buildRequestObject(
authParams,
config,
serverMetadata.issuer,
);
authParams = {
client_id: config.clientID,
request: requestJwt,
};
}
let authorizationUrl;
if (config.pushedAuthorizationRequests) {
authorizationUrl = await oidcClient.buildAuthorizationUrlWithPAR(
configuration,
authParams,
);
} else {
authorizationUrl = oidcClient.buildAuthorizationUrl(
configuration,
authParams,
);
}
debug('redirecting to %s', authorizationUrl.toString());
res.redirect(authorizationUrl.toString());
} catch (err) {
next(err);
}
}
async logout(params = {}) {
let { config, req, res, next } = weakRef(this);
next = once(next);
let returnURL = params.returnTo || config.routes.postLogoutRedirect;
debug('req.oidc.logout() with return url: %s', returnURL);
try {
const clientResult = await getClient(config);
/**
* Generates the logout URL.
*
* Depending on the configuration, this function will either perform a local only logout
* or a federated logout by redirecting to the appropriate URL.
*
* @param {string} idTokenHint - The ID token hint to be used for the logout request.
* @returns {string} The URL to redirect the user to for logout.
*/
const getLogoutUrl = (idTokenHint) => {
// if idpLogout is not configured, perform a local only logout
if (!config.idpLogout) {
debug('performing a local only logout, redirecting to %s', returnURL);
return returnURL;
}
// if idpLogout is configured, perform a federated logout
return buildEndSessionUrl(config, clientResult, {
...config.logoutParams,
...(idTokenHint && { id_token_hint: idTokenHint }),
post_logout_redirect_uri: returnURL,
...params.logoutParams,
});
};
if (url.parse(returnURL).host === null) {
returnURL = urlJoin(config.baseURL, returnURL);
}
cancelSilentLogin(req, res);
if (!req.oidc.isAuthenticated()) {
debug('end-user already logged out, redirecting to %s', returnURL);
// perform idp logout with no token hint
return res.redirect(getLogoutUrl(undefined));
}
const { idToken: id_token_hint } = req.oidc;
req[config.session.name] = undefined;
returnURL = getLogoutUrl(id_token_hint);
} catch (err) {
return next(err);
}
debug('logging out of identity provider, redirecting to %s', returnURL);
res.redirect(returnURL);
}
async callback(options = {}) {
let { config, req, res, transient, next } = weakRef(this);
next = once(next);
try {
const { configuration } = await getClient(config);
let tokenResponse;
let claims;
try {
const authVerification = await transient.getOnce(
config.transactionCookie.name,
req,
res,
);
if (!authVerification) {
if (req.oidc.isAuthenticated()) {
// User already has a valid session — this is a stale/replayed callback
// (e.g., browser back button navigated back to a consumed /callback URL).
debug(
'stale callback detected, user already authenticated, redirecting to baseURL',
);
return res.redirect(config.baseURL);
} else {
/*
* The transaction cookie is missing for an unauthenticated user. Possible causes:
* 1. A request was made directly to the callback URL without going through the
* login route first — no cookie was ever set.
* 2. The browser dropped the SameSite=None cookie during the IdP redirect
* (common in Safari/ITP, privacy mode, or browsers that reject SameSite=None
* without a Secure flag on non-HTTPS origins).
* 3. legacySameSiteCookie is false and the browser does not support SameSite=None,
* so neither the primary nor the fallback cookie was sent back.
* 4. Multiple apps share the same transactionCookie.name and cookie path on the
* same domain — a second app's login flow overwrote this app's cookie before
* the callback fired. Set a unique transactionCookie.name and session.cookie.path
* per app to isolate them.
*/
throw new Error(
`"${config.transactionCookie.name}" cookie not found. ` +
`Ensure the login flow is initiated through the SDK's login route before ` +
`the callback is processed. If using SameSite=None cookies, verify the ` +
`origin is served over HTTPS and the Secure flag is set. For multi-app ` +
`deployments on the same domain, configure a unique transactionCookie.name ` +
`and session.cookie.path per application.`,
);
}
}
const checks = JSON.parse(authVerification);
req.openidState = decodeState(checks.state);
const responseType = config.authorizationParams.response_type;
// Build a Request object for openid-client v6
const protocol = req.protocol;
// Use req.hostname (respects X-Forwarded-Host when trust proxy is enabled)
const hostname = req.hostname;
// Determine port from X-Forwarded-Port or Host header
// req.hostname respects trust proxy for host, but strips port
// So we need to check X-Forwarded-Port for reverse proxy scenarios
let port;
const xForwardedPort = req.get('x-forwarded-port');
const xForwardedHost = req.get('x-forwarded-host');
// Use regex to extract port, handles IPv6 addresses
if (xForwardedPort) {
// Explicit X-Forwarded-Port header from reverse proxy
port = xForwardedPort;
} else if (xForwardedHost) {
// Port included in X-Forwarded-Host header
port = /:(\d+)$/.exec(xForwardedHost)?.[1];
} else {
const hostHeader = req.get('host');
if (hostHeader) {
port = /:(\d+)$/.exec(hostHeader)?.[1];
}
}
// Don't include standard ports in URL
const standardPorts = { http: '80', https: '443' };
const needsPort = port && port !== standardPorts[protocol];
// Build host with port if needed
const host = needsPort ? `${hostname}:${port}` : hostname;
const currentUrl = new URL(
`${protocol}://${host}${req.originalUrl ?? req.url}`,
);
/*
* Use options.redirectUri if explicitly provided, otherwise fall back to
* the configured callback URL (baseURL + routes.callback).
* Only use the raw currentUrl if neither is available.
* This restores the pre-v6 behavior where redirect_uri was always passed
* explicitly to the token endpoint rather than inferred from the request URL,
* ensuring apps with proxy path rewriting or dynamic redirect URIs work correctly.
*/
const configuredRedirectUri =
options.redirectUri || this.getRedirectUri();
let callbackUrl;
if (configuredRedirectUri) {
/*
* Use the configured URI as origin+path, but take the query string from
* the actual request — it carries code, state and other callback params
* for GET flows. For POST flows the params come from the body, so the
* query string is effectively empty.
*/
callbackUrl = new URL(configuredRedirectUri);
callbackUrl.search = currentUrl.search;
} else {
callbackUrl = currentUrl;
}
let request = callbackUrl;
if (req.method === 'POST') {
// Build headers using headersDistinct for proper multi-value header support
const headers = Object.entries(req.headersDistinct).reduce(
(acc, [key, values]) => {
for (const value of values) {
acc.append(key, value);
}
return acc;
},
new Headers(),
);
if (req.body && typeof req.body === 'object') {
// Body already parsed - serialize back to URLSearchParams
request = new Request(callbackUrl.href, {
method: 'POST',
headers,
body: new URLSearchParams(req.body).toString(),
});
} else {
// Body not parsed - pass the stream as duplex
request = new Request(callbackUrl.href, {
method: 'POST',
headers,
body: req,
duplex: 'half',
});
}
}
if (responseType === 'id_token') {
// Implicit flow - use implicitAuthentication
claims = await oidcClient.implicitAuthentication(
configuration,
request,
checks.nonce,
{
expectedState: checks.state,
maxAge: checks.max_age,
},
);
// For implicit flow, we only get id_token claims, no access_token
tokenResponse = {
id_token: req.body?.id_token,
claims: () => claims,
};
} else {
// code or code id_token - use authorizationCodeGrant
tokenResponse = await oidcClient.authorizationCodeGrant(
configuration,
request,
{
expectedNonce: checks.nonce,
expectedState: checks.state,
pkceCodeVerifier: checks.code_verifier,
maxAge: checks.max_age,
},
{
...(config && config.tokenEndpointParams),
...options.tokenEndpointParams,
},
);
claims = tokenResponse.claims();
}
} catch (error) {
// Handle v6 error types
const errorData = {
error: error.error || error.code || 'unknown_error',
error_description:
error.error_description || error.message || 'An error occurred',
};
throw createError(400, error.message, errorData);
}
// Build session from token response
let session = {
id_token: tokenResponse.id_token,
access_token: tokenResponse.access_token,
refresh_token: tokenResponse.refresh_token,
token_type: normalizeTokenType(tokenResponse.token_type),
expires_at: tokenResponse.expires_in
? epoch() + tokenResponse.expires_in
: undefined,
};
if (config.accessTokenDecryptionKey && session.access_token) {
try {
session.access_token = await decryptAccessToken(
session.access_token,
config.accessTokenDecryptionKey,
config.accessTokenDecryptionAlg,
);
} catch (error) {
// Surface a clear, actionable error instead of a raw crypto stack trace.
// The most common causes are a key that does not match the tenant's
// encryption key, or an accessTokenDecryptionAlg that does not match the
// alg the token was encrypted with.
throw createError(
500,
`Failed to decrypt the access token: ${error.message}. ` +
'Check that accessTokenDecryptionKey matches the key configured on the ' +
'authorization server, and that accessTokenDecryptionAlg (if set) matches ' +
'the JWE "alg".',
);
}
}
// Must store the `sid` separately as the ID Token gets overridden by
// ID Token from the Refresh Grant which may not contain a sid (In Auth0 currently).
session.sid = claims?.sid;
// Persist the session_expiry claim from the ID token as sessionExpiresAt.
// This is the IdP-asserted ceiling on the RP session lifetime (IPSIE SL1).
// Only set when the claim is present — absence means the connection does not
// have id_token_session_expiry_supported enabled, and existing behavior applies.
const sessionExpiresAt = extractSessionExpiry(claims);
if (sessionExpiresAt) {
// Lockout guard: reject a session whose ceiling was already in the past when the IdP
// issued the token. We compare against claims.iat so a token that arrives late does
// not get incorrectly rejected.
if (isSessionExpiryInPast(sessionExpiresAt, claims.iat)) {
throw createError(
400,
'The session_expiry claim is in the past at login time.',
{ error: 'invalid_session_expiry' },
);
}
session.sessionExpiresAt = sessionExpiresAt;
}
// Check if user was previously authenticated BEFORE we modify the session
const wasAuthenticated = req.oidc.isAuthenticated();
const previousSub = wasAuthenticated ? req.oidc.user.sub : null;
if (config.afterCallback) {
// Temporarily set the session so that req.oidc methods can access token data.
// Note: This is a behavioral change from previous versions where req.oidc
// inside afterCallback reflected the old session state. Now it reflects
// the new tokens from the current authentication.
const originalSession = req[config.session.name]
? { ...req[config.session.name] }
: {};
Object.assign(req[config.session.name], session);
try {
session = await config.afterCallback(
req,
res,
session,
req.openidState,
);
} finally {
// Restore original session state (will be properly set below)
Object.keys(req[config.session.name]).forEach(
(key) => delete req[config.session.name][key],
);
Object.assign(req[config.session.name], originalSession);
}
}
if (wasAuthenticated) {
if (previousSub === claims?.sub) {
// If it's the same user logging in again, just update the existing session.
Object.assign(req[config.session.name], session);
} else {
// If it's a different user, replace the session to remove any custom user
// properties on the session
replaceSession(req, session, config);
// And regenerate the session id so the previous user wont know the new user's session id
await regenerateSessionStoreId(req, config);
}
} else {
// If a new user is replacing an anonymous session, update the existing session to keep
// any anonymous session state (eg. checkout basket)
Object.assign(req[config.session.name], session);
// But update the session store id so a previous anonymous user wont know the new user's session id
await regenerateSessionStoreId(req, config);
}
resumeSilentLogin(req, res);
if (
req.oidc.isAuthenticated() &&
config.backchannelLogout &&
config.backchannelLogout.onLogin !== false
) {
await (config.backchannelLogout.onLogin || onLogin)(req, config);
}
} catch (err) {
if (!req.openidState || !req.openidState.attemptingSilentLogin) {
return next(err);
}
}
res.redirect(req.openidState.returnTo || config.baseURL);
}
async backchannelLogout() {
let { config, req, res } = weakRef(this);
res.setHeader('cache-control', 'no-store');
const logoutToken = req.body?.logout_token;
if (!logoutToken) {
res.status(400).json({
error: 'invalid_request',
error_description: 'Missing logout_token',
});
return;
}
const onToken =