@axa-fr/oidc-client 7.27.18 → 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 (91) 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 +918 -545
  14. package/dist/index.umd.cjs +2 -2
  15. package/dist/initWorker.d.ts +1 -0
  16. package/dist/initWorker.d.ts.map +1 -1
  17. package/dist/initWorkerAbortError.spec.d.ts +2 -0
  18. package/dist/initWorkerAbortError.spec.d.ts.map +1 -0
  19. package/dist/jwt.spec.d.ts +2 -0
  20. package/dist/jwt.spec.d.ts.map +1 -0
  21. package/dist/login.d.ts +3 -3
  22. package/dist/login.d.ts.map +1 -1
  23. package/dist/logout.d.ts.map +1 -1
  24. package/dist/oidc.d.ts +12 -2
  25. package/dist/oidc.d.ts.map +1 -1
  26. package/dist/oidcClient.d.ts +5 -1
  27. package/dist/oidcClient.d.ts.map +1 -1
  28. package/dist/oidcError.d.ts +57 -0
  29. package/dist/oidcError.d.ts.map +1 -0
  30. package/dist/oidcError.spec.d.ts +2 -0
  31. package/dist/oidcError.spec.d.ts.map +1 -0
  32. package/dist/oidcStateError.d.ts +7 -4
  33. package/dist/oidcStateError.d.ts.map +1 -1
  34. package/dist/par.spec.d.ts +2 -0
  35. package/dist/par.spec.d.ts.map +1 -0
  36. package/dist/parseTokens.d.ts +1 -1
  37. package/dist/parseTokens.d.ts.map +1 -1
  38. package/dist/pushedAuthorizationRequestError.d.ts +20 -0
  39. package/dist/pushedAuthorizationRequestError.d.ts.map +1 -0
  40. package/dist/pushedAuthorizationRequestError.spec.d.ts +2 -0
  41. package/dist/pushedAuthorizationRequestError.spec.d.ts.map +1 -0
  42. package/dist/renewTokens.d.ts +11 -0
  43. package/dist/renewTokens.d.ts.map +1 -1
  44. package/dist/renewTokensError.spec.d.ts +2 -0
  45. package/dist/renewTokensError.spec.d.ts.map +1 -0
  46. package/dist/requests.d.ts +21 -14
  47. package/dist/requests.d.ts.map +1 -1
  48. package/dist/silentLogin.d.ts +6 -4
  49. package/dist/silentLogin.d.ts.map +1 -1
  50. package/dist/silentLogin.spec.d.ts +2 -0
  51. package/dist/silentLogin.spec.d.ts.map +1 -0
  52. package/dist/types.d.ts +5 -0
  53. package/dist/types.d.ts.map +1 -1
  54. package/dist/user.d.ts.map +1 -1
  55. package/dist/version.d.ts +1 -1
  56. package/dist/version.d.ts.map +1 -1
  57. package/package.json +2 -3
  58. package/src/crypto.spec.ts +40 -0
  59. package/src/crypto.ts +9 -10
  60. package/src/events.ts +3 -0
  61. package/src/fetch.spec.ts +105 -0
  62. package/src/fetch.ts +39 -3
  63. package/src/index.ts +14 -1
  64. package/src/initWorker.ts +37 -17
  65. package/src/initWorkerAbortError.spec.ts +147 -0
  66. package/src/jwt.spec.ts +33 -0
  67. package/src/jwt.ts +1 -47
  68. package/src/login.spec.ts +34 -0
  69. package/src/login.ts +119 -14
  70. package/src/logout.spec.ts +58 -0
  71. package/src/logout.ts +46 -7
  72. package/src/oidc.ts +78 -16
  73. package/src/oidcClient.ts +8 -1
  74. package/src/oidcError.spec.ts +105 -0
  75. package/src/oidcError.ts +197 -0
  76. package/src/oidcStateError.spec.ts +18 -0
  77. package/src/oidcStateError.ts +29 -8
  78. package/src/par.spec.ts +232 -0
  79. package/src/parseTokens.spec.ts +2 -1
  80. package/src/parseTokens.ts +1 -1
  81. package/src/pushedAuthorizationRequestError.spec.ts +43 -0
  82. package/src/pushedAuthorizationRequestError.ts +50 -0
  83. package/src/renewTokens.ts +167 -29
  84. package/src/renewTokensError.spec.ts +116 -0
  85. package/src/requests.spec.ts +293 -4
  86. package/src/requests.ts +174 -8
  87. package/src/silentLogin.spec.ts +158 -0
  88. package/src/silentLogin.ts +36 -9
  89. package/src/types.ts +6 -0
  90. package/src/user.ts +71 -31
  91. package/src/version.ts +1 -1
package/src/oidc.ts CHANGED
@@ -1,6 +1,6 @@
1
1
  import { startCheckSessionAsync as defaultStartCheckSessionAsync } from './checkSession.js';
2
2
  import { CheckSessionIFrame } from './checkSessionIFrame.js';
3
- import { base64urlOfHashOfASCIIEncodingAsync } from './crypto';
3
+ import { base64urlOfHashOfASCIIEncodingAsync, generateRandom } from './crypto';
4
4
  import { eventNames } from './events.js';
5
5
  import { initSession } from './initSession.js';
6
6
  import { getTabId, initWorkerAsync } from './initWorker.js';
@@ -13,8 +13,19 @@ import { tryKeepSessionAsync } from './keepSession';
13
13
  import { ILOidcLocation, OidcLocation } from './location';
14
14
  import { defaultLoginAsync, loginCallbackAsync } from './login.js';
15
15
  import { clearSessionAsync, destroyAsync, logoutAsync } from './logout.js';
16
+ import {
17
+ createOAuthError,
18
+ isOidcError,
19
+ OidcError,
20
+ OidcErrorCode,
21
+ serializeOidcError,
22
+ } from './oidcError.js';
16
23
  import { TokenRenewMode, Tokens } from './parseTokens.js';
17
- import { autoRenewTokens, renewTokensAndStartTimerAsync } from './renewTokens.js';
24
+ import {
25
+ autoRenewTokens,
26
+ renewTokensAndStartTimerResultAsync,
27
+ RenewTokensResult,
28
+ } from './renewTokens.js';
18
29
  import { fetchFromIssuer } from './requests.js';
19
30
  import { getParseQueryStringFromLocation } from './route-utils.js';
20
31
  import defaultSilentLoginAsync from './silentLogin.js';
@@ -35,6 +46,8 @@ export const getFetchDefault = () => {
35
46
  export interface OidcAuthorizationServiceConfigurationJson {
36
47
  check_session_iframe?: string;
37
48
  issuer: string;
49
+ pushed_authorization_request_endpoint?: string;
50
+ require_pushed_authorization_requests?: boolean;
38
51
  }
39
52
 
40
53
  export class OidcAuthorizationServiceConfiguration {
@@ -45,6 +58,8 @@ export class OidcAuthorizationServiceConfiguration {
45
58
  private revocationEndpoint: string;
46
59
  private userInfoEndpoint: string;
47
60
  private endSessionEndpoint: string;
61
+ private pushedAuthorizationRequestEndpoint: string;
62
+ private requirePushedAuthorizationRequests: boolean;
48
63
 
49
64
  constructor(request: any) {
50
65
  this.authorizationEndpoint = request.authorization_endpoint;
@@ -54,6 +69,9 @@ export class OidcAuthorizationServiceConfiguration {
54
69
  this.checkSessionIframe = request.check_session_iframe;
55
70
  this.issuer = request.issuer;
56
71
  this.endSessionEndpoint = request.end_session_endpoint;
72
+ this.pushedAuthorizationRequestEndpoint = request.pushed_authorization_request_endpoint;
73
+ this.requirePushedAuthorizationRequests =
74
+ request.require_pushed_authorization_requests ?? false;
57
75
  }
58
76
  }
59
77
 
@@ -85,10 +103,6 @@ const loginCallbackWithAutoTokensRenewAsync = async (oidc): Promise<LoginCallbac
85
103
  return { callbackPath };
86
104
  };
87
105
 
88
- const getRandomInt = max => {
89
- return Math.floor(Math.random() * max);
90
- };
91
-
92
106
  export class Oidc {
93
107
  public configuration: OidcConfiguration;
94
108
  public userInfo: null;
@@ -148,6 +162,8 @@ export class Oidc {
148
162
  configuration.demonstrating_proof_of_possession_configuration ??
149
163
  defaultDemonstratingProofOfPossessionConfiguration,
150
164
  preload_user_info: configuration.preload_user_info ?? false,
165
+ par: configuration.par ?? 'disabled',
166
+ par_request_timeout: configuration.par_request_timeout ?? 10000,
151
167
  };
152
168
 
153
169
  this.getFetch = getFetch ?? getFetchDefault;
@@ -165,11 +181,12 @@ export class Oidc {
165
181
  this.destroyAsync.bind(this);
166
182
  this.logoutAsync.bind(this);
167
183
  this.renewTokensAsync.bind(this);
184
+ this.renewTokensOrThrowAsync.bind(this);
168
185
  this.initAsync(this.configuration.authority, this.configuration.authority_configuration);
169
186
  }
170
187
 
171
188
  subscribeEvents(func): string {
172
- const id = getRandomInt(9999999999999).toString();
189
+ const id = generateRandom(16);
173
190
  this.events.push({ id, func });
174
191
  return id;
175
192
  }
@@ -243,13 +260,26 @@ Please checkout that you are using OIDC hook inside a <OidcProvider configuratio
243
260
  const location = this.location;
244
261
  const queryParams = getParseQueryStringFromLocation(location.getCurrentHref());
245
262
  if (queryParams.error) {
263
+ const error = createOAuthError(
264
+ queryParams.error,
265
+ queryParams.error_description,
266
+ `Error from OIDC server: ${queryParams.error} - ${queryParams.error_description}`,
267
+ 'refresh',
268
+ );
246
269
  window.parent.postMessage(
247
- `${this.configurationName}_oidc_error:${JSON.stringify({ error: queryParams.error })}`,
270
+ `${this.configurationName}_oidc_error:${JSON.stringify({
271
+ error: queryParams.error,
272
+ error_description: queryParams.error_description,
273
+ oidcError: serializeOidcError(error),
274
+ })}`,
248
275
  location.getOrigin(),
249
276
  );
250
277
  } else {
251
278
  window.parent.postMessage(
252
- `${this.configurationName}_oidc_exception:${JSON.stringify({ error: exception == null ? '' : exception.toString() })}`,
279
+ `${this.configurationName}_oidc_exception:${JSON.stringify({
280
+ error: exception == null ? '' : exception.toString(),
281
+ oidcError: isOidcError(exception) ? serializeOidcError(exception) : undefined,
282
+ })}`,
253
283
  location.getOrigin(),
254
284
  );
255
285
  }
@@ -281,6 +311,10 @@ Please checkout that you are using OIDC hook inside a <OidcProvider configuratio
281
311
  userinfo_endpoint: authorityConfiguration.userinfo_endpoint,
282
312
  check_session_iframe: authorityConfiguration.check_session_iframe,
283
313
  issuer: authorityConfiguration.issuer,
314
+ pushed_authorization_request_endpoint:
315
+ authorityConfiguration.pushed_authorization_request_endpoint,
316
+ require_pushed_authorization_requests:
317
+ authorityConfiguration.require_pushed_authorization_requests,
284
318
  });
285
319
  }
286
320
 
@@ -360,6 +394,7 @@ Please checkout that you are using OIDC hook inside a <OidcProvider configuratio
360
394
  this.publishEvent.bind(this),
361
395
  this.initAsync.bind(this),
362
396
  this.location,
397
+ this.getFetch,
363
398
  )(callbackPath, extras, isSilentSignin, scope);
364
399
  }
365
400
  return this.loginPromise.finally(() => {
@@ -464,23 +499,50 @@ Please checkout that you are using OIDC hook inside a <OidcProvider configuratio
464
499
  });
465
500
  }
466
501
 
467
- renewTokensPromise: Promise<any> = null;
502
+ renewTokensPromise: Promise<RenewTokensResult> = null;
468
503
 
469
- async renewTokensAsync(extras: StringMap = null, scope: string = null) {
504
+ private async renewTokensResultAsync(
505
+ extras: StringMap = null,
506
+ scope: string = null,
507
+ ): Promise<RenewTokensResult | null> {
470
508
  if (this.renewTokensPromise !== null) {
471
509
  return this.renewTokensPromise;
472
510
  }
473
511
  if (!this.timeoutId) {
474
- return;
512
+ return null;
475
513
  }
476
514
  timer.clearTimeout(this.timeoutId);
477
- // @ts-ignore
478
- this.renewTokensPromise = renewTokensAndStartTimerAsync(this, true, extras, scope);
479
- return this.renewTokensPromise.finally(() => {
480
- this.renewTokensPromise = null;
515
+ const promise = renewTokensAndStartTimerResultAsync(this, true, extras, scope);
516
+ this.renewTokensPromise = promise;
517
+ return promise.finally(() => {
518
+ if (this.renewTokensPromise === promise) {
519
+ this.renewTokensPromise = null;
520
+ }
481
521
  });
482
522
  }
483
523
 
524
+ async renewTokensAsync(
525
+ extras: StringMap = null,
526
+ scope: string = null,
527
+ ): Promise<Tokens | null | undefined> {
528
+ const result = await this.renewTokensResultAsync(extras, scope);
529
+ return result?.tokens;
530
+ }
531
+
532
+ async renewTokensOrThrowAsync(extras: StringMap = null, scope: string = null): Promise<Tokens> {
533
+ const result = await this.renewTokensResultAsync(extras, scope);
534
+ if (result?.error) {
535
+ throw result.error;
536
+ }
537
+ if (!result?.tokens) {
538
+ throw new OidcError(OidcErrorCode.TOKEN_REQUEST_FAILED, 'Token renewal failed', {
539
+ phase: 'refresh',
540
+ retryable: false,
541
+ });
542
+ }
543
+ return result.tokens;
544
+ }
545
+
484
546
  async destroyAsync(status) {
485
547
  return await destroyAsync(this)(status);
486
548
  }
package/src/oidcClient.ts CHANGED
@@ -114,10 +114,17 @@ export class OidcClient {
114
114
  return this._oidc.silentLoginCallbackAsync();
115
115
  }
116
116
 
117
- renewTokensAsync(extras: StringMap = null, scope: string = null): Promise<void> {
117
+ renewTokensAsync(
118
+ extras: StringMap = null,
119
+ scope: string = null,
120
+ ): Promise<Tokens | null | undefined> {
118
121
  return this._oidc.renewTokensAsync(extras, scope);
119
122
  }
120
123
 
124
+ renewTokensOrThrowAsync(extras: StringMap = null, scope: string = null): Promise<Tokens> {
125
+ return this._oidc.renewTokensOrThrowAsync(extras, scope);
126
+ }
127
+
121
128
  loginCallbackAsync(): Promise<LoginCallback> {
122
129
  return this._oidc.loginCallbackWithAutoTokensRenewAsync();
123
130
  }
@@ -0,0 +1,105 @@
1
+ import { describe, expect, it } from 'vitest';
2
+
3
+ import {
4
+ createNetworkError,
5
+ createOAuthError,
6
+ deserializeOidcError,
7
+ isOidcError,
8
+ OidcError,
9
+ OidcErrorCode,
10
+ serializeOidcError,
11
+ } from './oidcError';
12
+
13
+ describe('OidcError', () => {
14
+ it('preserves all public fields and the Error prototype chain', () => {
15
+ const cause = new TypeError('fetch failed');
16
+ const error = new OidcError(OidcErrorCode.TOKEN_REQUEST_FAILED, 'Token request failed', {
17
+ phase: 'refresh',
18
+ retryable: true,
19
+ status: 503,
20
+ oauthError: 'temporarily_unavailable',
21
+ oauthErrorDescription: 'Try again later',
22
+ cause,
23
+ });
24
+
25
+ expect(error).toBeInstanceOf(Error);
26
+ expect(error).toBeInstanceOf(OidcError);
27
+ expect(error.name).toBe('OidcError');
28
+ expect(error.message).toBe('Token request failed');
29
+ expect(error).toMatchObject({
30
+ code: OidcErrorCode.TOKEN_REQUEST_FAILED,
31
+ phase: 'refresh',
32
+ retryable: true,
33
+ status: 503,
34
+ oauthError: 'temporarily_unavailable',
35
+ oauthErrorDescription: 'Try again later',
36
+ cause,
37
+ });
38
+ expect(isOidcError(error)).toBe(true);
39
+ expect(isOidcError(new Error('other'))).toBe(false);
40
+ });
41
+
42
+ it.each([
43
+ ['login_required', OidcErrorCode.LOGIN_REQUIRED, false],
44
+ ['consent_required', OidcErrorCode.CONSENT_REQUIRED, false],
45
+ ['interaction_required', OidcErrorCode.INTERACTION_REQUIRED, false],
46
+ ['server_error', OidcErrorCode.OAUTH_ERROR, true],
47
+ ['temporarily_unavailable', OidcErrorCode.OAUTH_ERROR, true],
48
+ ['access_denied', OidcErrorCode.OAUTH_ERROR, false],
49
+ ] as const)('maps OAuth error %s to %s', (oauthError, code, retryable) => {
50
+ const error = createOAuthError(
51
+ oauthError,
52
+ 'description',
53
+ `Error from OIDC server: ${oauthError} - description`,
54
+ 'callback',
55
+ );
56
+
57
+ expect(error).toMatchObject({
58
+ code,
59
+ phase: 'callback',
60
+ retryable,
61
+ oauthError,
62
+ oauthErrorDescription: 'description',
63
+ });
64
+ });
65
+
66
+ it('wraps a network failure without changing its message', () => {
67
+ const cause = new Error('Failed to fetch');
68
+ const error = createNetworkError(cause, 'userinfo');
69
+
70
+ expect(error).toMatchObject({
71
+ code: OidcErrorCode.NETWORK_ERROR,
72
+ message: 'Failed to fetch',
73
+ phase: 'userinfo',
74
+ retryable: true,
75
+ cause,
76
+ });
77
+ });
78
+
79
+ it('serializes and reconstructs an OidcError without stack or cause', () => {
80
+ const original = new OidcError(OidcErrorCode.LOGIN_REQUIRED, 'login required', {
81
+ phase: 'refresh',
82
+ retryable: false,
83
+ oauthError: 'login_required',
84
+ oauthErrorDescription: 'Sign in again',
85
+ cause: new Error('not cloneable'),
86
+ });
87
+
88
+ const serialized = serializeOidcError(original);
89
+ expect(serialized).not.toHaveProperty('stack');
90
+ expect(serialized).not.toHaveProperty('cause');
91
+
92
+ const reconstructed = deserializeOidcError(serialized);
93
+ expect(reconstructed).toBeInstanceOf(OidcError);
94
+ expect(reconstructed).toMatchObject({
95
+ name: 'OidcError',
96
+ message: 'login required',
97
+ code: OidcErrorCode.LOGIN_REQUIRED,
98
+ phase: 'refresh',
99
+ retryable: false,
100
+ oauthError: 'login_required',
101
+ oauthErrorDescription: 'Sign in again',
102
+ });
103
+ expect(reconstructed?.cause).toBeUndefined();
104
+ });
105
+ });
@@ -0,0 +1,197 @@
1
+ export const OidcErrorCode = {
2
+ LOGIN_REQUIRED: 'LOGIN_REQUIRED',
3
+ CONSENT_REQUIRED: 'CONSENT_REQUIRED',
4
+ INTERACTION_REQUIRED: 'INTERACTION_REQUIRED',
5
+ OAUTH_ERROR: 'OAUTH_ERROR',
6
+ TOKEN_REQUEST_FAILED: 'TOKEN_REQUEST_FAILED',
7
+ SILENT_LOGIN_TIMEOUT: 'SILENT_LOGIN_TIMEOUT',
8
+ INVALID_STATE: 'INVALID_STATE',
9
+ INVALID_NONCE: 'INVALID_NONCE',
10
+ DPOP_NONCE_REQUIRED: 'DPOP_NONCE_REQUIRED',
11
+ NETWORK_ERROR: 'NETWORK_ERROR',
12
+ // Backwards-compatible codes exposed by the existing specialised errors.
13
+ STATE_MISSING: 'STATE_MISSING',
14
+ STATE_MISMATCH: 'STATE_MISMATCH',
15
+ NONCE_MISSING: 'NONCE_MISSING',
16
+ ENDPOINT_UNAVAILABLE: 'ENDPOINT_UNAVAILABLE',
17
+ REQUEST_FAILED: 'REQUEST_FAILED',
18
+ INVALID_RESPONSE: 'INVALID_RESPONSE',
19
+ } as const;
20
+
21
+ // eslint-disable-next-line @typescript-eslint/no-redeclare
22
+ export type OidcErrorCode = (typeof OidcErrorCode)[keyof typeof OidcErrorCode];
23
+
24
+ export type OidcErrorPhase =
25
+ 'login' | 'callback' | 'refresh' | 'logout' | 'userinfo' | 'api_request';
26
+
27
+ export type OidcErrorOptions = {
28
+ phase: OidcErrorPhase;
29
+ retryable: boolean;
30
+ oauthError?: string;
31
+ oauthErrorDescription?: string;
32
+ status?: number;
33
+ cause?: unknown;
34
+ };
35
+
36
+ export type SerializedOidcError = {
37
+ name: string;
38
+ message: string;
39
+ code: OidcErrorCode;
40
+ phase: OidcErrorPhase;
41
+ retryable: boolean;
42
+ oauthError?: string;
43
+ oauthErrorDescription?: string;
44
+ status?: number;
45
+ };
46
+
47
+ const oidcErrorCodes = new Set<string>(Object.values(OidcErrorCode));
48
+ const oidcErrorPhases = new Set<OidcErrorPhase>([
49
+ 'login',
50
+ 'callback',
51
+ 'refresh',
52
+ 'logout',
53
+ 'userinfo',
54
+ 'api_request',
55
+ ]);
56
+
57
+ export class OidcError extends Error {
58
+ readonly code: OidcErrorCode;
59
+ readonly phase: OidcErrorPhase;
60
+ readonly oauthError?: string;
61
+ readonly oauthErrorDescription?: string;
62
+ readonly retryable: boolean;
63
+ readonly status?: number;
64
+ readonly cause?: unknown;
65
+
66
+ constructor(code: OidcErrorCode, message: string, options: OidcErrorOptions) {
67
+ super(message);
68
+ this.name = 'OidcError';
69
+ this.code = code;
70
+ this.phase = options.phase;
71
+ this.oauthError = options.oauthError;
72
+ this.oauthErrorDescription = options.oauthErrorDescription;
73
+ this.retryable = options.retryable;
74
+ this.status = options.status;
75
+ this.cause = options.cause;
76
+
77
+ Object.setPrototypeOf(this, new.target.prototype);
78
+ }
79
+ }
80
+
81
+ export const isOidcError = (value: unknown): value is OidcError => value instanceof OidcError;
82
+
83
+ export const isRetryableHttpStatus = (status?: number): boolean =>
84
+ status === 408 || status === 429 || (status !== undefined && status >= 500);
85
+
86
+ export const oidcErrorCodeFromOAuthError = (oauthError?: string): OidcErrorCode => {
87
+ switch (oauthError) {
88
+ case 'login_required':
89
+ return OidcErrorCode.LOGIN_REQUIRED;
90
+ case 'consent_required':
91
+ return OidcErrorCode.CONSENT_REQUIRED;
92
+ case 'interaction_required':
93
+ return OidcErrorCode.INTERACTION_REQUIRED;
94
+ case 'use_dpop_nonce':
95
+ return OidcErrorCode.DPOP_NONCE_REQUIRED;
96
+ default:
97
+ return OidcErrorCode.OAUTH_ERROR;
98
+ }
99
+ };
100
+
101
+ export const createOAuthError = (
102
+ oauthError: string | undefined,
103
+ oauthErrorDescription: string | undefined,
104
+ message: string,
105
+ phase: OidcErrorPhase,
106
+ status?: number,
107
+ ): OidcError => {
108
+ const code = oidcErrorCodeFromOAuthError(oauthError);
109
+ const requiresInteraction =
110
+ code === OidcErrorCode.LOGIN_REQUIRED ||
111
+ code === OidcErrorCode.CONSENT_REQUIRED ||
112
+ code === OidcErrorCode.INTERACTION_REQUIRED;
113
+ const retryable =
114
+ !requiresInteraction &&
115
+ (code === OidcErrorCode.DPOP_NONCE_REQUIRED ||
116
+ oauthError === 'server_error' ||
117
+ oauthError === 'temporarily_unavailable' ||
118
+ isRetryableHttpStatus(status));
119
+ return new OidcError(code, message, {
120
+ phase,
121
+ retryable,
122
+ oauthError,
123
+ oauthErrorDescription,
124
+ status,
125
+ });
126
+ };
127
+
128
+ export const createNetworkError = (
129
+ cause: unknown,
130
+ phase: OidcErrorPhase,
131
+ fallbackMessage = 'Network request failed',
132
+ ): OidcError => {
133
+ const message =
134
+ cause instanceof Error && typeof cause.message === 'string' && cause.message
135
+ ? cause.message
136
+ : fallbackMessage;
137
+ return new OidcError(OidcErrorCode.NETWORK_ERROR, message, {
138
+ phase,
139
+ retryable: true,
140
+ cause,
141
+ });
142
+ };
143
+
144
+ export const isNetworkErrorCause = (value: unknown): boolean => {
145
+ if (!(value instanceof Error)) {
146
+ return false;
147
+ }
148
+ return (
149
+ value.name === 'AbortError' ||
150
+ value.name === 'NetworkError' ||
151
+ value.message === 'Network request failed' ||
152
+ value.message === 'Failed to fetch' ||
153
+ value.message === 'fetch failed'
154
+ );
155
+ };
156
+
157
+ export const serializeOidcError = (error: OidcError): SerializedOidcError => ({
158
+ name: error.name,
159
+ message: error.message,
160
+ code: error.code,
161
+ phase: error.phase,
162
+ retryable: error.retryable,
163
+ oauthError: error.oauthError,
164
+ oauthErrorDescription: error.oauthErrorDescription,
165
+ status: error.status,
166
+ });
167
+
168
+ export const deserializeOidcError = (value: unknown): OidcError | null => {
169
+ if (!value || typeof value !== 'object') {
170
+ return null;
171
+ }
172
+ const serialized = value as Partial<SerializedOidcError>;
173
+ if (
174
+ typeof serialized.message !== 'string' ||
175
+ typeof serialized.code !== 'string' ||
176
+ !oidcErrorCodes.has(serialized.code) ||
177
+ typeof serialized.phase !== 'string' ||
178
+ !oidcErrorPhases.has(serialized.phase as OidcErrorPhase) ||
179
+ typeof serialized.retryable !== 'boolean'
180
+ ) {
181
+ return null;
182
+ }
183
+ const error = new OidcError(serialized.code as OidcErrorCode, serialized.message, {
184
+ phase: serialized.phase as OidcErrorPhase,
185
+ retryable: serialized.retryable,
186
+ oauthError: typeof serialized.oauthError === 'string' ? serialized.oauthError : undefined,
187
+ oauthErrorDescription:
188
+ typeof serialized.oauthErrorDescription === 'string'
189
+ ? serialized.oauthErrorDescription
190
+ : undefined,
191
+ status: typeof serialized.status === 'number' ? serialized.status : undefined,
192
+ });
193
+ if (typeof serialized.name === 'string' && serialized.name) {
194
+ error.name = serialized.name;
195
+ }
196
+ return error;
197
+ };
@@ -1,5 +1,6 @@
1
1
  import { describe, expect, it } from 'vitest';
2
2
 
3
+ import { deserializeOidcError, OidcError, serializeOidcError } from './oidcError';
3
4
  import { isOidcStateError, OidcStateError, OidcStateErrorCode } from './oidcStateError';
4
5
 
5
6
  describe('OidcStateError', () => {
@@ -12,6 +13,7 @@ describe('OidcStateError', () => {
12
13
  it('is an Error subclass with name "OidcStateError"', () => {
13
14
  const err = new OidcStateError(OidcStateErrorCode.STATE_MISSING, 'missing');
14
15
  expect(err).toBeInstanceOf(Error);
16
+ expect(err).toBeInstanceOf(OidcError);
15
17
  expect(err).toBeInstanceOf(OidcStateError);
16
18
  expect(err.name).toBe('OidcStateError');
17
19
  });
@@ -20,6 +22,8 @@ describe('OidcStateError', () => {
20
22
  const err = new OidcStateError(OidcStateErrorCode.STATE_MISMATCH, 'mismatch happened');
21
23
  expect(err.code).toBe('STATE_MISMATCH');
22
24
  expect(err.message).toBe('mismatch happened');
25
+ expect(err.phase).toBe('callback');
26
+ expect(err.retryable).toBe(false);
23
27
  });
24
28
 
25
29
  it('is detectable via isOidcStateError', () => {
@@ -30,4 +34,18 @@ describe('OidcStateError', () => {
30
34
  expect(isOidcStateError(undefined)).toBe(false);
31
35
  expect(isOidcStateError({ code: 'STATE_MISSING' })).toBe(false);
32
36
  });
37
+
38
+ it('stays detectable after serialization and deserialization', () => {
39
+ const err = new OidcStateError(OidcStateErrorCode.NONCE_MISSING, 'nonce missing', 'refresh');
40
+ const reconstructed = deserializeOidcError(serializeOidcError(err));
41
+
42
+ expect(reconstructed).toBeInstanceOf(OidcError);
43
+ expect(reconstructed).not.toBeInstanceOf(OidcStateError);
44
+ expect(isOidcStateError(reconstructed)).toBe(true);
45
+ expect(reconstructed).toMatchObject({
46
+ code: OidcStateErrorCode.NONCE_MISSING,
47
+ phase: 'refresh',
48
+ name: 'OidcStateError',
49
+ });
50
+ });
33
51
  });
@@ -1,3 +1,10 @@
1
+ import {
2
+ isOidcError,
3
+ OidcError,
4
+ OidcErrorCode as BaseOidcErrorCode,
5
+ OidcErrorPhase,
6
+ } from './oidcError.js';
7
+
1
8
  /**
2
9
  * Stable, machine-readable codes for OIDC state / nonce failures occurring
3
10
  * between the authorization redirect and the callback handling.
@@ -21,20 +28,32 @@ export const OidcStateErrorCode = {
21
28
  // eslint-disable-next-line @typescript-eslint/no-redeclare
22
29
  export type OidcStateErrorCode = (typeof OidcStateErrorCode)[keyof typeof OidcStateErrorCode];
23
30
 
31
+ const oidcStateErrorCodes = new Set<string>(Object.values(OidcStateErrorCode));
32
+
33
+ export const isOidcStateErrorCode = (value: unknown): value is OidcStateErrorCode =>
34
+ typeof value === 'string' && oidcStateErrorCodes.has(value);
35
+
24
36
  /**
25
37
  * Typed error thrown when the OIDC login state or nonce is missing,
26
38
  * corrupted, or does not match the value returned by the authorization server.
27
39
  *
28
- * Consumers can use `instanceof OidcStateError` and inspect `code` instead of
29
- * relying on the (unstable) error message text.
40
+ * Consumers should prefer {@link isOidcStateError} and inspect `code` instead
41
+ * of relying on the (unstable) error message text, especially when errors may
42
+ * cross a postMessage boundary during silent renew.
30
43
  */
31
- export class OidcStateError extends Error {
32
- readonly code: OidcStateErrorCode;
44
+ export class OidcStateError extends OidcError {
45
+ declare readonly code: OidcStateErrorCode;
33
46
 
34
- constructor(code: OidcStateErrorCode, message: string) {
35
- super(message);
47
+ constructor(
48
+ code: OidcStateErrorCode,
49
+ message: string,
50
+ phase: Extract<OidcErrorPhase, 'callback' | 'refresh'> = 'callback',
51
+ ) {
52
+ super(code as BaseOidcErrorCode, message, {
53
+ phase,
54
+ retryable: false,
55
+ });
36
56
  this.name = 'OidcStateError';
37
- this.code = code;
38
57
 
39
58
  // Keep prototype chain intact when transpiled to ES5.
40
59
  Object.setPrototypeOf(this, OidcStateError.prototype);
@@ -46,5 +65,7 @@ export class OidcStateError extends Error {
46
65
  * specifically to state/nonce failures.
47
66
  */
48
67
  export const isOidcStateError = (value: unknown): value is OidcStateError => {
49
- return value instanceof OidcStateError;
68
+ return (
69
+ value instanceof OidcStateError || (isOidcError(value) && isOidcStateErrorCode(value.code))
70
+ );
50
71
  };