@axa-fr/oidc-client 7.27.19 → 7.29.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (85) hide show
  1. package/README.md +122 -4
  2. package/dist/crypto.d.ts.map +1 -1
  3. package/dist/crypto.spec.d.ts +2 -0
  4. package/dist/crypto.spec.d.ts.map +1 -0
  5. package/dist/events.d.ts +3 -0
  6. package/dist/events.d.ts.map +1 -1
  7. package/dist/fetch.d.ts +2 -1
  8. package/dist/fetch.d.ts.map +1 -1
  9. package/dist/fetch.spec.d.ts +2 -0
  10. package/dist/fetch.spec.d.ts.map +1 -0
  11. package/dist/index.d.ts +4 -1
  12. package/dist/index.d.ts.map +1 -1
  13. package/dist/index.js +922 -556
  14. package/dist/index.umd.cjs +2 -2
  15. package/dist/jwt.spec.d.ts +2 -0
  16. package/dist/jwt.spec.d.ts.map +1 -0
  17. package/dist/login.d.ts +3 -3
  18. package/dist/login.d.ts.map +1 -1
  19. package/dist/logout.d.ts.map +1 -1
  20. package/dist/oidc.d.ts +12 -2
  21. package/dist/oidc.d.ts.map +1 -1
  22. package/dist/oidcClient.d.ts +5 -1
  23. package/dist/oidcClient.d.ts.map +1 -1
  24. package/dist/oidcError.d.ts +57 -0
  25. package/dist/oidcError.d.ts.map +1 -0
  26. package/dist/oidcError.spec.d.ts +2 -0
  27. package/dist/oidcError.spec.d.ts.map +1 -0
  28. package/dist/oidcStateError.d.ts +7 -4
  29. package/dist/oidcStateError.d.ts.map +1 -1
  30. package/dist/par.spec.d.ts +2 -0
  31. package/dist/par.spec.d.ts.map +1 -0
  32. package/dist/parseTokens.d.ts +1 -1
  33. package/dist/parseTokens.d.ts.map +1 -1
  34. package/dist/pushedAuthorizationRequestError.d.ts +20 -0
  35. package/dist/pushedAuthorizationRequestError.d.ts.map +1 -0
  36. package/dist/pushedAuthorizationRequestError.spec.d.ts +2 -0
  37. package/dist/pushedAuthorizationRequestError.spec.d.ts.map +1 -0
  38. package/dist/renewTokens.d.ts +11 -0
  39. package/dist/renewTokens.d.ts.map +1 -1
  40. package/dist/renewTokensError.spec.d.ts +2 -0
  41. package/dist/renewTokensError.spec.d.ts.map +1 -0
  42. package/dist/requests.d.ts +21 -14
  43. package/dist/requests.d.ts.map +1 -1
  44. package/dist/silentLogin.d.ts +6 -4
  45. package/dist/silentLogin.d.ts.map +1 -1
  46. package/dist/silentLogin.spec.d.ts +2 -0
  47. package/dist/silentLogin.spec.d.ts.map +1 -0
  48. package/dist/types.d.ts +5 -0
  49. package/dist/types.d.ts.map +1 -1
  50. package/dist/user.d.ts.map +1 -1
  51. package/dist/version.d.ts +1 -1
  52. package/dist/version.d.ts.map +1 -1
  53. package/package.json +2 -3
  54. package/src/crypto.spec.ts +40 -0
  55. package/src/crypto.ts +9 -10
  56. package/src/events.ts +3 -0
  57. package/src/fetch.spec.ts +105 -0
  58. package/src/fetch.ts +39 -3
  59. package/src/index.ts +14 -1
  60. package/src/jwt.spec.ts +33 -0
  61. package/src/jwt.ts +1 -47
  62. package/src/login.spec.ts +34 -0
  63. package/src/login.ts +119 -14
  64. package/src/logout.spec.ts +58 -0
  65. package/src/logout.ts +46 -7
  66. package/src/oidc.ts +78 -16
  67. package/src/oidcClient.ts +8 -1
  68. package/src/oidcError.spec.ts +105 -0
  69. package/src/oidcError.ts +197 -0
  70. package/src/oidcStateError.spec.ts +18 -0
  71. package/src/oidcStateError.ts +29 -8
  72. package/src/par.spec.ts +232 -0
  73. package/src/parseTokens.spec.ts +2 -1
  74. package/src/parseTokens.ts +1 -1
  75. package/src/pushedAuthorizationRequestError.spec.ts +43 -0
  76. package/src/pushedAuthorizationRequestError.ts +50 -0
  77. package/src/renewTokens.ts +167 -29
  78. package/src/renewTokensError.spec.ts +116 -0
  79. package/src/requests.spec.ts +293 -4
  80. package/src/requests.ts +174 -8
  81. package/src/silentLogin.spec.ts +158 -0
  82. package/src/silentLogin.ts +36 -9
  83. package/src/types.ts +6 -0
  84. package/src/user.ts +71 -31
  85. package/src/version.ts +1 -1
@@ -0,0 +1,50 @@
1
+ import {
2
+ isRetryableHttpStatus,
3
+ OidcError,
4
+ OidcErrorCode as BaseOidcErrorCode,
5
+ } from './oidcError.js';
6
+
7
+ export const PushedAuthorizationRequestErrorCode = {
8
+ ENDPOINT_UNAVAILABLE: 'ENDPOINT_UNAVAILABLE',
9
+ REQUEST_FAILED: 'REQUEST_FAILED',
10
+ INVALID_RESPONSE: 'INVALID_RESPONSE',
11
+ } as const;
12
+
13
+ // eslint-disable-next-line @typescript-eslint/no-redeclare
14
+ export type PushedAuthorizationRequestErrorCode =
15
+ (typeof PushedAuthorizationRequestErrorCode)[keyof typeof PushedAuthorizationRequestErrorCode];
16
+
17
+ type PushedAuthorizationRequestErrorOptions = {
18
+ status?: number;
19
+ oauthError?: string;
20
+ oauthErrorDescription?: string;
21
+ cause?: unknown;
22
+ };
23
+
24
+ export class PushedAuthorizationRequestError extends OidcError {
25
+ declare readonly code: PushedAuthorizationRequestErrorCode;
26
+
27
+ constructor(
28
+ code: PushedAuthorizationRequestErrorCode,
29
+ message: string,
30
+ options: PushedAuthorizationRequestErrorOptions = {},
31
+ ) {
32
+ super(code as BaseOidcErrorCode, message, {
33
+ phase: 'login',
34
+ retryable: options.cause !== undefined || isRetryableHttpStatus(options.status),
35
+ status: options.status,
36
+ oauthError: options.oauthError,
37
+ oauthErrorDescription: options.oauthErrorDescription,
38
+ cause: options.cause,
39
+ });
40
+ this.name = 'PushedAuthorizationRequestError';
41
+
42
+ Object.setPrototypeOf(this, PushedAuthorizationRequestError.prototype);
43
+ }
44
+ }
45
+
46
+ export const isPushedAuthorizationRequestError = (
47
+ value: unknown,
48
+ ): value is PushedAuthorizationRequestError => {
49
+ return value instanceof PushedAuthorizationRequestError;
50
+ };
@@ -2,12 +2,49 @@ import { eventNames } from './events';
2
2
  import { initSession } from './initSession.js';
3
3
  import { initWorkerAsync, sleepAsync } from './initWorker.js';
4
4
  import Oidc from './oidc.js';
5
+ import {
6
+ createNetworkError,
7
+ isNetworkErrorCause,
8
+ isOidcError,
9
+ isRetryableHttpStatus,
10
+ OidcError,
11
+ OidcErrorCode,
12
+ } from './oidcError.js';
13
+ import { OidcStateError, OidcStateErrorCode } from './oidcStateError.js';
5
14
  import { computeTimeLeft, isTokensOidcValid, setTokens, Tokens } from './parseTokens.js';
6
15
  import { performTokenRequestAsync } from './requests';
7
16
  import { _silentLoginAsync } from './silentLogin';
8
17
  import timer from './timer.js';
9
18
  import { OidcConfiguration, StringMap, TokenAutomaticRenewMode } from './types.js';
10
19
 
20
+ export type RenewTokensResult = {
21
+ tokens: Tokens | null;
22
+ status: string | null;
23
+ error?: OidcError;
24
+ };
25
+
26
+ const createRefreshTokenError = (
27
+ message: string,
28
+ response?: {
29
+ status?: number;
30
+ oauthError?: string;
31
+ oauthErrorDescription?: string;
32
+ },
33
+ ): OidcError => {
34
+ const code =
35
+ response?.oauthError === 'use_dpop_nonce'
36
+ ? OidcErrorCode.DPOP_NONCE_REQUIRED
37
+ : OidcErrorCode.TOKEN_REQUEST_FAILED;
38
+ return new OidcError(code, message, {
39
+ phase: 'refresh',
40
+ retryable:
41
+ code === OidcErrorCode.DPOP_NONCE_REQUIRED || isRetryableHttpStatus(response?.status),
42
+ status: response?.status,
43
+ oauthError: response?.oauthError,
44
+ oauthErrorDescription: response?.oauthErrorDescription,
45
+ });
46
+ };
47
+
11
48
  async function syncTokens(
12
49
  oidc: Oidc,
13
50
  forceRefresh: boolean,
@@ -17,7 +54,7 @@ async function syncTokens(
17
54
  const updateTokens = tokens => {
18
55
  oidc.tokens = tokens;
19
56
  };
20
- const { tokens, status } = await synchroniseTokensAsync(oidc)(
57
+ const result = await synchroniseTokensAsync(oidc)(
21
58
  updateTokens,
22
59
  0,
23
60
  0,
@@ -25,6 +62,7 @@ async function syncTokens(
25
62
  extras,
26
63
  scope,
27
64
  );
65
+ const { tokens, status } = result;
28
66
 
29
67
  const serviceWorker = await initWorkerAsync(oidc.configuration, oidc.configurationName);
30
68
  if (!serviceWorker) {
@@ -38,12 +76,12 @@ async function syncTokens(
38
76
 
39
77
  if (!oidc.tokens) {
40
78
  await oidc.destroyAsync(status);
41
- return null;
79
+ return { ...result, tokens: null } as RenewTokensResult;
42
80
  }
43
- return tokens;
81
+ return { ...result, tokens } as RenewTokensResult;
44
82
  }
45
83
 
46
- export async function renewTokensAndStartTimerAsync(
84
+ export async function renewTokensAndStartTimerResultAsync(
47
85
  oidc,
48
86
  forceRefresh = false,
49
87
  extras: StringMap = null,
@@ -52,14 +90,14 @@ export async function renewTokensAndStartTimerAsync(
52
90
  const configuration = oidc.configuration;
53
91
  const lockResourcesName = `${configuration.client_id}_${oidc.configurationName}_${configuration.authority}`;
54
92
 
55
- let tokens: null;
93
+ let result: RenewTokensResult;
56
94
  const serviceWorker = await initWorkerAsync(oidc.configuration, oidc.configurationName);
57
95
  if ((configuration?.storage === window?.sessionStorage && !serviceWorker) || !navigator.locks) {
58
- tokens = await syncTokens(oidc, forceRefresh, extras, scope);
96
+ result = await syncTokens(oidc, forceRefresh, extras, scope);
59
97
  } else {
60
- let status: any = 'retry';
61
- while (status === 'retry') {
62
- status = await navigator.locks.request(
98
+ let lockResult: any = 'retry';
99
+ while (lockResult === 'retry') {
100
+ lockResult = await navigator.locks.request(
63
101
  lockResourcesName,
64
102
  { ifAvailable: true },
65
103
  async lock => {
@@ -73,11 +111,11 @@ export async function renewTokensAndStartTimerAsync(
73
111
  },
74
112
  );
75
113
  }
76
- tokens = status;
114
+ result = lockResult;
77
115
  }
78
116
 
79
- if (!tokens) {
80
- return null;
117
+ if (!result.tokens) {
118
+ return result;
81
119
  }
82
120
 
83
121
  if (oidc.timeoutId) {
@@ -85,7 +123,17 @@ export async function renewTokensAndStartTimerAsync(
85
123
  oidc.timeoutId = autoRenewTokens(oidc, oidc.tokens.expiresAt, extras, scope);
86
124
  }
87
125
 
88
- return oidc.tokens;
126
+ return { ...result, tokens: oidc.tokens };
127
+ }
128
+
129
+ export async function renewTokensAndStartTimerAsync(
130
+ oidc,
131
+ forceRefresh = false,
132
+ extras: StringMap = null,
133
+ scope: string = null,
134
+ ) {
135
+ const result = await renewTokensAndStartTimerResultAsync(oidc, forceRefresh, extras, scope);
136
+ return result.tokens;
89
137
  }
90
138
 
91
139
  export const autoRenewTokens = (
@@ -227,6 +275,7 @@ const synchroniseTokensAsync =
227
275
  forceRefresh = false,
228
276
  extras: StringMap = null,
229
277
  scope: string = null,
278
+ lastError: OidcError = null,
230
279
  ) => {
231
280
  if (!navigator.onLine && document.hidden) {
232
281
  return { tokens: oidc.tokens, status: 'GIVE_UP' };
@@ -248,8 +297,12 @@ const synchroniseTokensAsync =
248
297
 
249
298
  if (tryNumber >= maxTries || backgroundTry >= maxBackgroundTries) {
250
299
  updateTokens(null);
251
- oidc.publishEvent(eventNames.refreshTokensAsync_error, { message: 'refresh token' });
252
- return { tokens: null, status: 'SESSION_LOST' };
300
+ const error = lastError ?? createRefreshTokenError('refresh token');
301
+ oidc.publishEvent(eventNames.refreshTokensAsync_error, {
302
+ message: 'refresh token',
303
+ error,
304
+ });
305
+ return { tokens: null, status: 'SESSION_LOST', error };
253
306
  }
254
307
 
255
308
  if (!extras) {
@@ -262,6 +315,7 @@ const synchroniseTokensAsync =
262
315
  oidc.configurationName,
263
316
  oidc.configuration,
264
317
  oidc.publishEvent.bind(oidc),
318
+ 'refresh',
265
319
  )(extras, state, scope);
266
320
  };
267
321
  const localSilentLoginAsync = async () => {
@@ -302,27 +356,42 @@ const synchroniseTokensAsync =
302
356
  const silent_token_response = await silentLoginAsync(silentLoginInput);
303
357
  if (!silent_token_response) {
304
358
  updateTokens(null);
359
+ const error = createRefreshTokenError('refresh token silent not active');
305
360
  oidc.publishEvent(eventNames.refreshTokensAsync_error, {
306
361
  message: 'refresh token silent not active',
362
+ error,
307
363
  });
308
- return { tokens: null, status: 'SESSION_LOST' };
364
+ return { tokens: null, status: 'SESSION_LOST', error };
309
365
  }
310
366
  if (silent_token_response.error) {
311
367
  updateTokens(null);
368
+ const error =
369
+ silent_token_response.oidcError ??
370
+ new OidcError(OidcErrorCode.OAUTH_ERROR, 'refresh token silent', {
371
+ phase: 'refresh',
372
+ retryable: false,
373
+ oauthError: silent_token_response.error,
374
+ });
312
375
  oidc.publishEvent(eventNames.refreshTokensAsync_error, {
313
376
  message: 'refresh token silent',
377
+ error,
314
378
  });
315
- return { tokens: null, status: 'SESSION_LOST' };
379
+ return { tokens: null, status: 'SESSION_LOST', error };
316
380
  }
317
381
 
318
382
  updateTokens(silent_token_response.tokens);
319
383
  oidc.publishEvent(Oidc.eventNames.token_renewed, {});
320
384
  return { tokens: silent_token_response.tokens, status: 'LOGGED' };
321
385
  } catch (exceptionSilent: any) {
322
- console.error(exceptionSilent);
386
+ const error =
387
+ isOidcError(exceptionSilent) || !isNetworkErrorCause(exceptionSilent)
388
+ ? exceptionSilent
389
+ : createNetworkError(exceptionSilent, 'refresh');
390
+ console.error(error);
323
391
  oidc.publishEvent(eventNames.refreshTokensAsync_silent_error, {
324
392
  message: 'exceptionSilent',
325
- exception: exceptionSilent.message,
393
+ exception: error.message,
394
+ error: isOidcError(error) ? error : undefined,
326
395
  });
327
396
  return await synchroniseTokensAsync(oidc)(
328
397
  updateTokens,
@@ -331,6 +400,7 @@ const synchroniseTokensAsync =
331
400
  forceRefresh,
332
401
  extras,
333
402
  scope,
403
+ isOidcError(error) ? error : lastError,
334
404
  );
335
405
  }
336
406
  };
@@ -346,10 +416,14 @@ const synchroniseTokensAsync =
346
416
  switch (status) {
347
417
  case synchroniseTokensStatus.SESSION_LOST:
348
418
  updateTokens(null);
349
- oidc.publishEvent(eventNames.refreshTokensAsync_error, {
350
- message: 'refresh token session lost',
351
- });
352
- return { tokens: null, status: 'SESSION_LOST' };
419
+ {
420
+ const error = lastError ?? createRefreshTokenError('refresh token session lost');
421
+ oidc.publishEvent(eventNames.refreshTokensAsync_error, {
422
+ message: 'refresh token session lost',
423
+ error,
424
+ });
425
+ return { tokens: null, status: 'SESSION_LOST', error };
426
+ }
353
427
  case synchroniseTokensStatus.NOT_CONNECTED:
354
428
  updateTokens(null);
355
429
  return { tokens: null, status: null };
@@ -435,7 +509,7 @@ const synchroniseTokensAsync =
435
509
  'POST',
436
510
  );
437
511
  }
438
- const tokenResponse = await performTokenRequestAsync(oidc.getFetch())(
512
+ let tokenResponse = await performTokenRequestAsync(oidc.getFetch())(
439
513
  url,
440
514
  details,
441
515
  finalExtras,
@@ -445,6 +519,43 @@ const synchroniseTokensAsync =
445
519
  timeoutMs,
446
520
  );
447
521
 
522
+ if (
523
+ !tokenResponse.success &&
524
+ tokenResponse.oauthError === 'use_dpop_nonce' &&
525
+ tokenResponse.demonstratingProofOfPossessionNonce &&
526
+ configuration.demonstrating_proof_of_possession
527
+ ) {
528
+ const serviceWorker = await initWorkerAsync(configuration, oidc.configurationName);
529
+ if (serviceWorker) {
530
+ await serviceWorker.setDemonstratingProofOfPossessionNonce(
531
+ tokenResponse.demonstratingProofOfPossessionNonce,
532
+ );
533
+ } else {
534
+ const session = initSession(
535
+ oidc.configurationName,
536
+ configuration.storage,
537
+ configuration.login_state_storage ?? configuration.storage,
538
+ );
539
+ await session.setDemonstratingProofOfPossessionNonce(
540
+ tokenResponse.demonstratingProofOfPossessionNonce,
541
+ );
542
+ }
543
+ headersExtras['DPoP'] = await oidc.generateDemonstrationOfProofOfPossessionAsync(
544
+ tokens.accessToken,
545
+ url,
546
+ 'POST',
547
+ );
548
+ tokenResponse = await performTokenRequestAsync(oidc.getFetch())(
549
+ url,
550
+ details,
551
+ finalExtras,
552
+ tokens,
553
+ headersExtras,
554
+ configuration.token_renew_mode,
555
+ timeoutMs,
556
+ );
557
+ }
558
+
448
559
  if (tokenResponse.success) {
449
560
  // Guard against a missing/corrupted nonce reaching id_token validation.
450
561
  // Without this guard, accessing `nonce.nonce` would throw a TypeError
@@ -454,10 +565,16 @@ const synchroniseTokensAsync =
454
565
  // See https://github.com/AxaFrance/oidc-client/issues/1678
455
566
  if (!nonce || !nonce.nonce) {
456
567
  updateTokens(null);
568
+ const error = new OidcStateError(
569
+ OidcStateErrorCode.NONCE_MISSING,
570
+ 'refresh token: nonce missing from storage',
571
+ 'refresh',
572
+ );
457
573
  oidc.publishEvent(eventNames.refreshTokensAsync_error, {
458
574
  message: 'refresh token: nonce missing from storage',
575
+ error,
459
576
  });
460
- return { tokens: null, status: 'SESSION_LOST' };
577
+ return { tokens: null, status: 'SESSION_LOST', error };
461
578
  }
462
579
  const { isValid, reason } = isTokensOidcValid(
463
580
  tokenResponse.data,
@@ -466,10 +583,21 @@ const synchroniseTokensAsync =
466
583
  );
467
584
  if (!isValid) {
468
585
  updateTokens(null);
586
+ const error = new OidcError(
587
+ reason.startsWith('Nonce does not match')
588
+ ? OidcErrorCode.INVALID_NONCE
589
+ : OidcErrorCode.TOKEN_REQUEST_FAILED,
590
+ `refresh token return not valid tokens, reason: ${reason}`,
591
+ {
592
+ phase: 'refresh',
593
+ retryable: false,
594
+ },
595
+ );
469
596
  oidc.publishEvent(eventNames.refreshTokensAsync_error, {
470
597
  message: `refresh token return not valid tokens, reason: ${reason}`,
598
+ error,
471
599
  });
472
- return { tokens: null, status: 'SESSION_LOST' };
600
+ return { tokens: null, status: 'SESSION_LOST', error };
473
601
  }
474
602
  updateTokens(tokenResponse.data);
475
603
  if (tokenResponse.demonstratingProofOfPossessionNonce) {
@@ -495,17 +623,20 @@ const synchroniseTokensAsync =
495
623
  oidc.publishEvent(Oidc.eventNames.token_renewed, { reason: 'REFRESH_TOKEN' });
496
624
  return { tokens: tokenResponse.data, status: 'LOGGED_IN' };
497
625
  } else {
626
+ const error = createRefreshTokenError('Token request failed', tokenResponse);
498
627
  oidc.publishEvent(eventNames.refreshTokensAsync_silent_error, {
499
628
  message: 'bad request',
500
629
  tokenResponse,
630
+ error,
501
631
  });
502
632
 
503
633
  if (tokenResponse.status >= 400 && tokenResponse.status < 500) {
504
634
  updateTokens(null);
505
635
  oidc.publishEvent(eventNames.refreshTokensAsync_error, {
506
636
  message: `session lost: ${tokenResponse.status}`,
637
+ error,
507
638
  });
508
- return { tokens: null, status: 'SESSION_LOST' };
639
+ return { tokens: null, status: 'SESSION_LOST', error };
509
640
  }
510
641
 
511
642
  return await synchroniseTokensAsync(oidc)(
@@ -515,6 +646,7 @@ const synchroniseTokensAsync =
515
646
  forceRefresh,
516
647
  extras,
517
648
  scope,
649
+ error,
518
650
  );
519
651
  }
520
652
  };
@@ -522,11 +654,16 @@ const synchroniseTokensAsync =
522
654
  }
523
655
  }
524
656
  } catch (exception: any) {
525
- console.error(exception);
657
+ const error =
658
+ isOidcError(exception) || !isNetworkErrorCause(exception)
659
+ ? exception
660
+ : createNetworkError(exception, 'refresh');
661
+ console.error(error);
526
662
 
527
663
  oidc.publishEvent(eventNames.refreshTokensAsync_silent_error, {
528
664
  message: 'exception',
529
- exception: exception.message,
665
+ exception: error.message,
666
+ error: isOidcError(error) ? error : undefined,
530
667
  });
531
668
  // we need to break the loop or errors, as direct call of synchroniseTokensAsync
532
669
  // inside of synchroniseTokensAsync will cause an infinite loop and kill the browser stack
@@ -540,6 +677,7 @@ const synchroniseTokensAsync =
540
677
  forceRefresh,
541
678
  extras,
542
679
  scope,
680
+ isOidcError(error) ? error : lastError,
543
681
  )
544
682
  .then(resolve)
545
683
  .catch(reject);
@@ -0,0 +1,116 @@
1
+ import { afterEach, describe, expect, it, vi } from 'vitest';
2
+
3
+ import * as initSessionModule from './initSession';
4
+ import * as initWorkerModule from './initWorker';
5
+ import Oidc from './oidc';
6
+ import { OidcError, OidcErrorCode } from './oidcError';
7
+ import { OidcStateError, OidcStateErrorCode } from './oidcStateError';
8
+ import { Tokens } from './parseTokens';
9
+ import { renewTokensAndStartTimerResultAsync } from './renewTokens';
10
+ import * as requestsModule from './requests';
11
+
12
+ afterEach(() => {
13
+ vi.restoreAllMocks();
14
+ vi.unstubAllGlobals();
15
+ });
16
+
17
+ describe('strict token renewal', () => {
18
+ it('keeps renewTokensAsync non-throwing while the strict method throws the shared error', async () => {
19
+ const error = new OidcError(OidcErrorCode.TOKEN_REQUEST_FAILED, 'Token request failed', {
20
+ phase: 'refresh',
21
+ retryable: false,
22
+ status: 400,
23
+ oauthError: 'invalid_grant',
24
+ });
25
+ const oidc = Object.create(Oidc.prototype) as Oidc;
26
+ const sharedResult = Promise.resolve({
27
+ tokens: null,
28
+ status: 'SESSION_LOST',
29
+ error,
30
+ });
31
+ oidc.renewTokensPromise = sharedResult;
32
+
33
+ const nonThrowing = oidc.renewTokensAsync();
34
+ const strict = oidc.renewTokensOrThrowAsync();
35
+
36
+ await expect(nonThrowing).resolves.toBeNull();
37
+ await expect(strict).rejects.toBe(error);
38
+ });
39
+
40
+ it('returns renewed tokens from the strict method', async () => {
41
+ const tokens = {
42
+ accessToken: 'access-token',
43
+ expiresAt: Date.now() / 1000 + 3600,
44
+ } as Tokens;
45
+ const oidc = Object.create(Oidc.prototype) as Oidc;
46
+ oidc.renewTokensPromise = Promise.resolve({
47
+ tokens,
48
+ status: 'LOGGED_IN',
49
+ });
50
+
51
+ await expect(oidc.renewTokensOrThrowAsync()).resolves.toBe(tokens);
52
+ });
53
+
54
+ it('returns SESSION_LOST with OidcStateError(NONCE_MISSING) when refresh succeeds but nonce storage is missing', async () => {
55
+ vi.stubGlobal('navigator', { locks: undefined, onLine: true });
56
+ vi.stubGlobal('document', { hidden: false });
57
+ vi.stubGlobal('window', { sessionStorage: {} });
58
+ vi.spyOn(initWorkerModule, 'initWorkerAsync').mockResolvedValue(null);
59
+ vi.spyOn(initSessionModule, 'initSession').mockReturnValue({
60
+ getNonceAsync: vi.fn().mockResolvedValue({ nonce: undefined }),
61
+ initAsync: vi.fn().mockResolvedValue({
62
+ status: null,
63
+ tokens: {
64
+ accessToken: 'access-token',
65
+ expiresAt: 0,
66
+ issuedAt: 1,
67
+ refreshToken: 'refresh-token',
68
+ },
69
+ }),
70
+ setTokens: vi.fn(),
71
+ } as never);
72
+ vi.spyOn(requestsModule, 'performTokenRequestAsync').mockReturnValue(
73
+ vi.fn().mockResolvedValue({
74
+ data: { accessToken: 'renewed-token' },
75
+ status: 200,
76
+ success: true,
77
+ }) as never,
78
+ );
79
+
80
+ const oidc = Object.create(Oidc.prototype) as Oidc;
81
+ oidc.configurationName = 'default';
82
+ oidc.configuration = {
83
+ authority: 'https://issuer.example.com',
84
+ client_id: 'client',
85
+ redirect_uri: 'https://client.example.com/callback',
86
+ refresh_time_before_tokens_expiration_in_second: 0,
87
+ scope: 'openid',
88
+ storage: {},
89
+ token_renew_mode: 'access_token_or_id_token_invalid',
90
+ } as never;
91
+ oidc.destroyAsync = vi.fn();
92
+ oidc.getFetch = vi.fn();
93
+ oidc.initAsync = vi.fn().mockResolvedValue({
94
+ tokenEndpoint: 'https://issuer.example.com/token',
95
+ });
96
+ oidc.publishEvent = vi.fn();
97
+ oidc.tokens = {
98
+ accessToken: 'access-token',
99
+ expiresAt: 0,
100
+ issuedAt: 1,
101
+ refreshToken: 'refresh-token',
102
+ } as Tokens;
103
+
104
+ const result = await renewTokensAndStartTimerResultAsync(oidc);
105
+
106
+ expect(result.status).toBe('SESSION_LOST');
107
+ expect(result.tokens).toBeNull();
108
+ expect(result.error).toBeInstanceOf(OidcStateError);
109
+ expect(result.error).toMatchObject({
110
+ code: OidcStateErrorCode.NONCE_MISSING,
111
+ phase: 'refresh',
112
+ retryable: false,
113
+ });
114
+ expect(oidc.tokens).toBeNull();
115
+ });
116
+ });