@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
@@ -0,0 +1,147 @@
1
+ // Tests covering the AbortError handling added to initWorkerAsync.
2
+ // See https://github.com/AxaFrance/oidc-client/issues/1675
3
+ import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
4
+
5
+ import { initWorkerAsync, registrationCache } from './initWorker';
6
+ import { OidcConfiguration } from './types';
7
+
8
+ const SERVICE_WORKER_RELATIVE_URL = '/OidcServiceWorker.js';
9
+
10
+ const buildConfiguration = (overrides: Partial<OidcConfiguration> = {}): OidcConfiguration => {
11
+ return {
12
+ client_id: 'test-client',
13
+ redirect_uri: 'http://localhost/callback',
14
+ scope: 'openid',
15
+ authority: 'http://authority',
16
+ service_worker_relative_url: SERVICE_WORKER_RELATIVE_URL,
17
+ service_worker_activate: () => true,
18
+ ...overrides,
19
+ } as OidcConfiguration;
20
+ };
21
+
22
+ const createAbortError = (): DOMException => {
23
+ // DOMException is available in the test environment (jsdom / happy-dom).
24
+ return new DOMException('The operation was aborted.', 'AbortError');
25
+ };
26
+
27
+ describe('initWorkerAsync AbortError handling', () => {
28
+ let originalNavigator: PropertyDescriptor | undefined;
29
+ let originalWindow: PropertyDescriptor | undefined;
30
+ let warnSpy: ReturnType<typeof vi.spyOn>;
31
+
32
+ beforeEach(() => {
33
+ registrationCache.clear();
34
+ originalNavigator = Object.getOwnPropertyDescriptor(globalThis, 'navigator');
35
+ originalWindow = Object.getOwnPropertyDescriptor(globalThis, 'window');
36
+ Object.defineProperty(globalThis, 'window', {
37
+ configurable: true,
38
+ value: {},
39
+ });
40
+ Object.defineProperty(globalThis, 'navigator', {
41
+ configurable: true,
42
+ value: {
43
+ serviceWorker: {
44
+ register: vi.fn(),
45
+ ready: Promise.resolve({} as ServiceWorkerRegistration),
46
+ controller: null,
47
+ addEventListener: vi.fn(),
48
+ removeEventListener: vi.fn(),
49
+ },
50
+ },
51
+ });
52
+ warnSpy = vi.spyOn(console, 'warn').mockImplementation(() => {});
53
+ });
54
+
55
+ afterEach(() => {
56
+ registrationCache.clear();
57
+ if (originalNavigator) {
58
+ Object.defineProperty(globalThis, 'navigator', originalNavigator);
59
+ } else {
60
+ delete (globalThis as { navigator?: unknown }).navigator;
61
+ }
62
+ if (originalWindow) {
63
+ Object.defineProperty(globalThis, 'window', originalWindow);
64
+ } else {
65
+ delete (globalThis as { window?: unknown }).window;
66
+ }
67
+ vi.restoreAllMocks();
68
+ });
69
+
70
+ it('returns null when a custom service_worker_register rejects with an AbortError', async () => {
71
+ const abortError = createAbortError();
72
+ const service_worker_register = vi.fn(() => Promise.reject(abortError));
73
+
74
+ const result = await initWorkerAsync(
75
+ buildConfiguration({ service_worker_register }),
76
+ 'default',
77
+ );
78
+
79
+ expect(result).toBeNull();
80
+ expect(service_worker_register).toHaveBeenCalledOnce();
81
+ expect(registrationCache.has(SERVICE_WORKER_RELATIVE_URL)).toBe(false);
82
+ expect(warnSpy).toHaveBeenCalled();
83
+ });
84
+
85
+ it('returns null when navigator.serviceWorker.register rejects with an AbortError', async () => {
86
+ const abortError = createAbortError();
87
+ (navigator.serviceWorker.register as unknown as ReturnType<typeof vi.fn>).mockImplementation(
88
+ () => Promise.reject(abortError),
89
+ );
90
+
91
+ const result = await initWorkerAsync(buildConfiguration(), 'default');
92
+
93
+ expect(result).toBeNull();
94
+ // The cache entry for the SW URL should have been cleared so a later retry is possible.
95
+ expect(Array.from(registrationCache.keys())).toHaveLength(0);
96
+ expect(warnSpy).toHaveBeenCalled();
97
+ });
98
+
99
+ it('also treats plain { name: "AbortError" } rejections as aborts', async () => {
100
+ const plainAbort = { name: 'AbortError', message: 'aborted' };
101
+ const service_worker_register = vi.fn(() => Promise.reject(plainAbort));
102
+
103
+ const result = await initWorkerAsync(
104
+ buildConfiguration({ service_worker_register }),
105
+ 'default',
106
+ );
107
+
108
+ expect(result).toBeNull();
109
+ expect(registrationCache.has(SERVICE_WORKER_RELATIVE_URL)).toBe(false);
110
+ });
111
+
112
+ it('allows a subsequent call to retry registration after an AbortError', async () => {
113
+ const abortError = createAbortError();
114
+ const service_worker_register = vi
115
+ .fn()
116
+ .mockImplementationOnce(() => Promise.reject(abortError))
117
+ // Returning a never-resolving promise on the retry is fine for the assertion below:
118
+ // we only need to confirm that the function was called a second time after the
119
+ // failed cache entry was cleared.
120
+ .mockImplementationOnce(() => new Promise<ServiceWorkerRegistration>(() => {}));
121
+
122
+ const configuration = buildConfiguration({ service_worker_register });
123
+
124
+ const firstResult = await initWorkerAsync(configuration, 'default');
125
+ expect(firstResult).toBeNull();
126
+ expect(service_worker_register).toHaveBeenCalledTimes(1);
127
+
128
+ // Kick off the second call (don't await – the mocked promise never resolves).
129
+ void initWorkerAsync(configuration, 'default');
130
+ // Allow the microtask queue to drain so the registration call is observed.
131
+ await Promise.resolve();
132
+
133
+ expect(service_worker_register).toHaveBeenCalledTimes(2);
134
+ });
135
+
136
+ it('propagates non-AbortError rejections to the caller', async () => {
137
+ const genericError = new Error('boom');
138
+ const service_worker_register = vi.fn(() => Promise.reject(genericError));
139
+
140
+ await expect(
141
+ initWorkerAsync(buildConfiguration({ service_worker_register }), 'default'),
142
+ ).rejects.toBe(genericError);
143
+
144
+ // Non-AbortError rejections keep the cache entry in place (existing behavior).
145
+ expect(registrationCache.has(SERVICE_WORKER_RELATIVE_URL)).toBe(true);
146
+ });
147
+ });
@@ -0,0 +1,33 @@
1
+ import { describe, expect, it, vi } from 'vitest';
2
+
3
+ import {
4
+ defaultDemonstratingProofOfPossessionConfiguration,
5
+ generateJwkAsync,
6
+ generateJwtDemonstratingProofOfPossessionAsync,
7
+ } from './jwt';
8
+
9
+ const decodePayload = (jwt: string) => {
10
+ const payload = jwt.split('.')[1].replace(/-/g, '+').replace(/_/g, '/');
11
+ return JSON.parse(atob(payload));
12
+ };
13
+
14
+ describe('generateJwtDemonstratingProofOfPossessionAsync', () => {
15
+ it('uses a cryptographically secure UUID for the DPoP jti', async () => {
16
+ const uuid = '123e4567-e89b-42d3-a456-426614174000';
17
+ const randomUUID = vi.fn(() => uuid);
18
+ const webCrypto = {
19
+ subtle: globalThis.crypto.subtle,
20
+ randomUUID,
21
+ };
22
+ const jwk = await generateJwkAsync(globalThis)(
23
+ defaultDemonstratingProofOfPossessionConfiguration.generateKeyAlgorithm,
24
+ );
25
+
26
+ const jwt = await generateJwtDemonstratingProofOfPossessionAsync({ crypto: webCrypto })(
27
+ defaultDemonstratingProofOfPossessionConfiguration,
28
+ )(jwk, 'GET', 'https://api.example.com/resource');
29
+
30
+ expect(randomUUID).toHaveBeenCalledOnce();
31
+ expect(decodePayload(jwt).jti).toBe(btoa(uuid));
32
+ });
33
+ });
package/src/jwt.ts CHANGED
@@ -209,7 +209,7 @@ export const generateJwtDemonstratingProofOfPossessionAsync =
209
209
  async (jwk, method = 'POST', url: string, extrasClaims = {}) => {
210
210
  const claims = {
211
211
  // https://www.rfc-editor.org/rfc/rfc9449.html#name-concept
212
- jti: btoa(guid()),
212
+ jti: btoa(w.crypto.randomUUID()),
213
213
  htm: method,
214
214
  htu: url,
215
215
  iat: Math.round(Date.now() / 1000),
@@ -230,49 +230,3 @@ export const generateJwtDemonstratingProofOfPossessionAsync =
230
230
  // console.info('JWT:', jwt);
231
231
  return jwt;
232
232
  };
233
-
234
- const guid = () => {
235
- // RFC4122: The version 4 UUID is meant for generating UUIDs from truly-random or
236
- // pseudo-random numbers.
237
- // The algorithm is as follows:
238
- // Set the two most significant bits (bits 6 and 7) of the
239
- // clock_seq_hi_and_reserved to zero and one, respectively.
240
- // Set the four most significant bits (bits 12 through 15) of the
241
- // time_hi_and_version field to the 4-bit version number from
242
- // Section 4.1.3. Version4
243
- // Set all the other bits to randomly (or pseudo-randomly) chosen
244
- // values.
245
- // UUID = time-low "-" time-mid "-"time-high-and-version "-"clock-seq-reserved and low(2hexOctet)"-" node
246
- // time-low = 4hexOctet
247
- // time-mid = 2hexOctet
248
- // time-high-and-version = 2hexOctet
249
- // clock-seq-and-reserved = hexOctet:
250
- // clock-seq-low = hexOctet
251
- // node = 6hexOctet
252
- // Format: xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx
253
- // y could be 1000, 1001, 1010, 1011 since most significant two bits needs to be 10
254
- // y values are 8, 9, A, B
255
- const guidHolder = 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx';
256
- const hex = '0123456789abcdef';
257
- let r = 0;
258
- let guidResponse = '';
259
- for (let i = 0; i < 36; i++) {
260
- if (guidHolder[i] !== '-' && guidHolder[i] !== '4') {
261
- // each x and y needs to be random
262
- r = (Math.random() * 16) | 0;
263
- }
264
-
265
- if (guidHolder[i] === 'x') {
266
- guidResponse += hex[r];
267
- } else if (guidHolder[i] === 'y') {
268
- // clock-seq-and-reserved first hex is filtered and remaining hex values are random
269
- r &= 0x3; // bit and with 0011 to set pos 2 to zero ?0??
270
- r |= 0x8; // set pos 3 to 1 as 1???
271
- guidResponse += hex[r];
272
- } else {
273
- guidResponse += guidHolder[i];
274
- }
275
- }
276
-
277
- return guidResponse;
278
- };
package/src/login.spec.ts CHANGED
@@ -5,6 +5,7 @@ import { beforeEach, describe, expect, it, vi } from 'vitest';
5
5
 
6
6
  import { ILOidcLocation } from './location';
7
7
  import { loginCallbackAsync } from './login';
8
+ import { OidcError, OidcErrorCode } from './oidcError';
8
9
  import { OidcStateError, OidcStateErrorCode } from './oidcStateError';
9
10
 
10
11
  const makeStorage = (): Storage => {
@@ -149,3 +150,36 @@ describe('loginCallbackAsync — state/nonce guards (issue #1678)', () => {
149
150
  expect(caught).not.toBeInstanceOf(TypeError);
150
151
  });
151
152
  });
153
+
154
+ describe('loginCallbackAsync — OAuth errors', () => {
155
+ it.each([
156
+ ['login_required', OidcErrorCode.LOGIN_REQUIRED],
157
+ ['consent_required', OidcErrorCode.CONSENT_REQUIRED],
158
+ ['interaction_required', OidcErrorCode.INTERACTION_REQUIRED],
159
+ ['access_denied', OidcErrorCode.OAUTH_ERROR],
160
+ ] as const)('throws a typed %s callback error', async (oauthError, code) => {
161
+ const storage = makeStorage();
162
+ const description = 'Authentication is required';
163
+ const href = `http://localhost:4200/authentication/callback?error=${oauthError}&error_description=${encodeURIComponent(description)}`;
164
+ const { oidc, publishedEvents } = buildOidc({ href, storage });
165
+
166
+ let caught: unknown;
167
+ try {
168
+ await loginCallbackAsync(oidc)();
169
+ } catch (error) {
170
+ caught = error;
171
+ }
172
+
173
+ expect(caught).toBeInstanceOf(OidcError);
174
+ expect(caught).toMatchObject({
175
+ code,
176
+ phase: 'callback',
177
+ oauthError,
178
+ oauthErrorDescription: description,
179
+ message: `Error from OIDC server: ${oauthError} - ${description}`,
180
+ });
181
+ expect(publishedEvents.find(event => event.name === 'loginCallbackAsync_error')?.data).toBe(
182
+ caught,
183
+ );
184
+ });
185
+ });
package/src/login.ts CHANGED
@@ -5,11 +5,24 @@ import { initWorkerAsync } from './initWorker.js';
5
5
  import { generateJwkAsync, generateJwtDemonstratingProofOfPossessionAsync } from './jwt';
6
6
  import { ILOidcLocation } from './location';
7
7
  import Oidc from './oidc';
8
+ import {
9
+ createNetworkError,
10
+ createOAuthError,
11
+ isNetworkErrorCause,
12
+ isOidcError,
13
+ isRetryableHttpStatus,
14
+ OidcError,
15
+ OidcErrorCode,
16
+ } from './oidcError.js';
8
17
  import { OidcStateError, OidcStateErrorCode } from './oidcStateError.js';
9
18
  import { isTokensOidcValid } from './parseTokens.js';
19
+ import {
20
+ PushedAuthorizationRequestError,
21
+ PushedAuthorizationRequestErrorCode,
22
+ } from './pushedAuthorizationRequestError.js';
10
23
  import { performAuthorizationRequestAsync, performFirstTokenRequestAsync } from './requests.js';
11
24
  import { getParseQueryStringFromLocation } from './route-utils.js';
12
- import { OidcConfiguration, StringMap } from './types.js';
25
+ import { Fetch, OidcConfiguration, StringMap } from './types.js';
13
26
 
14
27
  export type InitAsyncFunction = (authority: string, authorityConfiguration: any) => Promise<any>;
15
28
 
@@ -20,6 +33,7 @@ export const defaultLoginAsync =
20
33
  publishEvent: (string, any) => void,
21
34
  initAsync: InitAsyncFunction,
22
35
  oidcLocation: ILOidcLocation,
36
+ getFetch: () => Fetch = () => window.fetch,
23
37
  ) =>
24
38
  (
25
39
  callbackPath: string = undefined,
@@ -88,13 +102,41 @@ export const defaultLoginAsync =
88
102
  response_type: 'code',
89
103
  ...extraFinal,
90
104
  };
105
+
106
+ const parMode = configuration.par ?? 'disabled';
107
+ const pushedAuthorizationRequestEndpoint =
108
+ oidcServerConfiguration.pushedAuthorizationRequestEndpoint;
109
+ const serverRequiresPar = oidcServerConfiguration.requirePushedAuthorizationRequests;
110
+ if (
111
+ !pushedAuthorizationRequestEndpoint &&
112
+ (parMode === 'required' || (parMode === 'auto' && serverRequiresPar))
113
+ ) {
114
+ throw new PushedAuthorizationRequestError(
115
+ PushedAuthorizationRequestErrorCode.ENDPOINT_UNAVAILABLE,
116
+ 'Pushed Authorization Requests are required, but the authorization server metadata does not provide a pushed_authorization_request_endpoint.',
117
+ );
118
+ }
119
+
120
+ const pushedAuthorizationRequest =
121
+ parMode !== 'disabled' && pushedAuthorizationRequestEndpoint
122
+ ? {
123
+ endpoint: pushedAuthorizationRequestEndpoint,
124
+ fetch: getFetch(),
125
+ timeoutMs: configuration.par_request_timeout,
126
+ }
127
+ : undefined;
128
+
91
129
  await performAuthorizationRequestAsync(storage, oidcLocation)(
92
130
  oidcServerConfiguration.authorizationEndpoint,
93
131
  extraInternal,
132
+ pushedAuthorizationRequest,
94
133
  );
95
134
  } catch (exception) {
96
- publishEvent(eventNames.loginAsync_error, exception);
97
- throw exception;
135
+ const error = isNetworkErrorCause(exception)
136
+ ? createNetworkError(exception, 'login')
137
+ : exception;
138
+ publishEvent(eventNames.loginAsync_error, error);
139
+ throw error;
98
140
  }
99
141
  };
100
142
  return loginLocalAsync();
@@ -146,8 +188,11 @@ export const loginCallbackAsync =
146
188
  }
147
189
 
148
190
  if (queryParams.error || queryParams.error_description) {
149
- throw new Error(
191
+ throw createOAuthError(
192
+ queryParams.error,
193
+ queryParams.error_description,
150
194
  `Error from OIDC server: ${queryParams.error} - ${queryParams.error_description}`,
195
+ isSilentSignin ? 'refresh' : 'callback',
151
196
  );
152
197
  }
153
198
 
@@ -165,12 +210,14 @@ export const loginCallbackAsync =
165
210
  throw new OidcStateError(
166
211
  OidcStateErrorCode.STATE_MISSING,
167
212
  'OIDC state is missing from storage. The login state may have been cleared between the authorization redirect and the callback (e.g., private browsing, storage cleared, or browser eviction).',
213
+ isSilentSignin ? 'refresh' : 'callback',
168
214
  );
169
215
  }
170
216
  if (queryParams.state !== state) {
171
217
  throw new OidcStateError(
172
218
  OidcStateErrorCode.STATE_MISMATCH,
173
219
  `OIDC state does not match the stored one (expected: ${state}, received: ${queryParams.state}).`,
220
+ isSilentSignin ? 'refresh' : 'callback',
174
221
  );
175
222
  }
176
223
  }
@@ -178,6 +225,7 @@ export const loginCallbackAsync =
178
225
  throw new OidcStateError(
179
226
  OidcStateErrorCode.NONCE_MISSING,
180
227
  'OIDC nonce is missing from storage. The login state may have been cleared between the authorization redirect and the callback (e.g., private browsing, storage cleared, or browser eviction).',
228
+ isSilentSignin ? 'refresh' : 'callback',
181
229
  );
182
230
  }
183
231
 
@@ -205,11 +253,12 @@ export const loginCallbackAsync =
205
253
 
206
254
  const url = oidcServerConfiguration.tokenEndpoint;
207
255
  const headersExtras = {};
256
+ let demonstratingProofOfPossessionJwk;
208
257
  if (configuration.demonstrating_proof_of_possession) {
209
258
  if (serviceWorker) {
210
259
  headersExtras['DPoP'] = `DPOP_SECURED_BY_OIDC_SERVICE_WORKER_${oidc.configurationName}`;
211
260
  } else {
212
- const jwk = await generateJwkAsync(window)(
261
+ demonstratingProofOfPossessionJwk = await generateJwkAsync(window)(
213
262
  configuration.demonstrating_proof_of_possession_configuration.generateKeyAlgorithm,
214
263
  );
215
264
  const session = initSession(
@@ -217,23 +266,65 @@ export const loginCallbackAsync =
217
266
  configuration.storage,
218
267
  configuration.login_state_storage ?? configuration.storage,
219
268
  );
220
- await session.setDemonstratingProofOfPossessionJwkAsync(jwk);
269
+ await session.setDemonstratingProofOfPossessionJwkAsync(
270
+ demonstratingProofOfPossessionJwk,
271
+ );
221
272
  headersExtras['DPoP'] = await generateJwtDemonstratingProofOfPossessionAsync(window)(
222
273
  configuration.demonstrating_proof_of_possession_configuration,
223
- )(jwk, 'POST', url);
274
+ )(demonstratingProofOfPossessionJwk, 'POST', url);
224
275
  }
225
276
  }
226
277
 
227
- const tokenResponse = await performFirstTokenRequestAsync(storage)(
278
+ let tokenResponse = await performFirstTokenRequestAsync(storage)(
228
279
  url,
229
280
  { ...data, ...extras },
230
281
  headersExtras,
231
282
  oidc.configuration.token_renew_mode,
232
283
  tokenRequestTimeout,
284
+ configuration.demonstrating_proof_of_possession,
233
285
  );
234
286
 
287
+ if (
288
+ !tokenResponse.success &&
289
+ tokenResponse.oauthError === 'use_dpop_nonce' &&
290
+ tokenResponse.demonstratingProofOfPossessionNonce &&
291
+ configuration.demonstrating_proof_of_possession
292
+ ) {
293
+ await storage.setDemonstratingProofOfPossessionNonce(
294
+ tokenResponse.demonstratingProofOfPossessionNonce,
295
+ );
296
+ if (!serviceWorker) {
297
+ headersExtras['DPoP'] = await generateJwtDemonstratingProofOfPossessionAsync(window)(
298
+ configuration.demonstrating_proof_of_possession_configuration,
299
+ )(demonstratingProofOfPossessionJwk, 'POST', url, {
300
+ nonce: tokenResponse.demonstratingProofOfPossessionNonce,
301
+ });
302
+ }
303
+ tokenResponse = await performFirstTokenRequestAsync(storage)(
304
+ url,
305
+ { ...data, ...extras },
306
+ headersExtras,
307
+ oidc.configuration.token_renew_mode,
308
+ tokenRequestTimeout,
309
+ );
310
+ } else if (!tokenResponse.success && configuration.demonstrating_proof_of_possession) {
311
+ await Promise.all([storage.setCodeVerifierAsync(null), storage.setStateAsync(null)]);
312
+ }
313
+
235
314
  if (!tokenResponse.success) {
236
- throw new Error('Token request failed');
315
+ const code =
316
+ tokenResponse.oauthError === 'use_dpop_nonce'
317
+ ? OidcErrorCode.DPOP_NONCE_REQUIRED
318
+ : OidcErrorCode.TOKEN_REQUEST_FAILED;
319
+ throw new OidcError(code, 'Token request failed', {
320
+ phase: isSilentSignin ? 'refresh' : 'callback',
321
+ retryable:
322
+ code === OidcErrorCode.DPOP_NONCE_REQUIRED ||
323
+ isRetryableHttpStatus(tokenResponse.status),
324
+ status: tokenResponse.status,
325
+ oauthError: tokenResponse.oauthError,
326
+ oauthErrorDescription: tokenResponse.oauthErrorDescription,
327
+ });
237
328
  }
238
329
 
239
330
  let loginParams;
@@ -243,7 +334,10 @@ export const loginCallbackAsync =
243
334
 
244
335
  // @ts-ignore
245
336
  if (tokenResponse.data.state !== extras.state) {
246
- throw new Error('state is not valid');
337
+ throw new OidcError(OidcErrorCode.INVALID_STATE, 'state is not valid', {
338
+ phase: isSilentSignin ? 'refresh' : 'callback',
339
+ retryable: false,
340
+ });
247
341
  }
248
342
  const { isValid, reason } = isTokensOidcValid(
249
343
  formattedTokens,
@@ -251,7 +345,14 @@ export const loginCallbackAsync =
251
345
  oidcServerConfiguration,
252
346
  );
253
347
  if (!isValid) {
254
- throw new Error(`Tokens are not OpenID valid, reason: ${reason}`);
348
+ const message = `Tokens are not OpenID valid, reason: ${reason}`;
349
+ if (reason.startsWith('Nonce does not match')) {
350
+ throw new OidcError(OidcErrorCode.INVALID_NONCE, message, {
351
+ phase: isSilentSignin ? 'refresh' : 'callback',
352
+ retryable: false,
353
+ });
354
+ }
355
+ throw new Error(message);
255
356
  }
256
357
 
257
358
  if (serviceWorker) {
@@ -307,8 +408,12 @@ export const loginCallbackAsync =
307
408
  extras: loginParams.extras,
308
409
  };
309
410
  } catch (exception) {
310
- console.error(exception);
311
- oidc.publishEvent(eventNames.loginCallbackAsync_error, exception);
312
- throw exception;
411
+ const error =
412
+ !isOidcError(exception) && isNetworkErrorCause(exception)
413
+ ? createNetworkError(exception, isSilentSignin ? 'refresh' : 'callback')
414
+ : exception;
415
+ console.error(error);
416
+ oidc.publishEvent(eventNames.loginCallbackAsync_error, error);
417
+ throw error;
313
418
  }
314
419
  };
@@ -5,6 +5,7 @@ import { describe, expect, it, vi } from 'vitest';
5
5
  import { eventNames } from './events';
6
6
  import { ILOidcLocation } from './location';
7
7
  import { clearSessionAsync, logoutAsync } from './logout';
8
+ import { OidcErrorCode } from './oidcError';
8
9
 
9
10
  describe('Logout test suite', () => {
10
11
  const expectedFinalUrl =
@@ -296,6 +297,63 @@ describe('Logout test suite', () => {
296
297
  expect(oidc.isLoggingOut).toBe(false);
297
298
  });
298
299
 
300
+ it('keeps revocation best-effort and publishes a typed logout error', async () => {
301
+ const events: Array<{ name: string; data: any }> = [];
302
+ const oidc: any = {
303
+ configuration: {
304
+ authority: 'http://api',
305
+ client_id: 'client',
306
+ logout_tokens_to_invalidate: ['access_token'],
307
+ },
308
+ tokens: {
309
+ accessToken: 'access-token',
310
+ idToken: 'id-token',
311
+ idTokenPayload: { sub: 'subject' },
312
+ },
313
+ isLoggingOut: false,
314
+ initAsync: vi.fn(async () => ({
315
+ revocationEndpoint: 'http://api/revoke',
316
+ })),
317
+ destroyAsync: vi.fn(async () => {
318
+ oidc.tokens = null;
319
+ }),
320
+ logoutSameTabAsync: vi.fn(),
321
+ publishEvent: (name: string, data: unknown) => events.push({ name, data }),
322
+ };
323
+ const location: ILOidcLocation = {
324
+ getCurrentHref: () => '',
325
+ getOrigin: () => 'http://client',
326
+ getPath: () => '/',
327
+ open: vi.fn(),
328
+ reload: vi.fn(),
329
+ };
330
+ const fetchMock = vi.fn(async () => {
331
+ return new Response(JSON.stringify({ error: 'temporarily_unavailable' }), {
332
+ status: 503,
333
+ headers: { 'Content-Type': 'application/json' },
334
+ });
335
+ });
336
+
337
+ await logoutAsync(
338
+ oidc,
339
+ { default: oidc },
340
+ fetchMock,
341
+ console,
342
+ location,
343
+ )(null, {
344
+ 'no_reload:oidc': 'true',
345
+ });
346
+
347
+ expect(events.find(event => event.name === eventNames.logoutAsync_error)?.data).toMatchObject({
348
+ code: OidcErrorCode.REQUEST_FAILED,
349
+ phase: 'logout',
350
+ retryable: true,
351
+ status: 503,
352
+ oauthError: 'temporarily_unavailable',
353
+ });
354
+ expect(oidc.isLoggingOut).toBe(false);
355
+ });
356
+
299
357
  describe('clearSessionAsync', () => {
300
358
  it('clears the local session and emits logout_from_same_tab without contacting the IdP', async () => {
301
359
  const events: { name: string; data: unknown }[] = [];
package/src/logout.ts CHANGED
@@ -2,6 +2,14 @@ import { eventNames } from './events';
2
2
  import { initSession } from './initSession.js';
3
3
  import { initWorkerAsync } from './initWorker.js';
4
4
  import { ILOidcLocation } from './location';
5
+ import {
6
+ createNetworkError,
7
+ isNetworkErrorCause,
8
+ isOidcError,
9
+ isRetryableHttpStatus,
10
+ OidcError,
11
+ OidcErrorCode,
12
+ } from './oidcError.js';
5
13
  import { performRevocationRequestAsync, TOKEN_TYPE } from './requests.js';
6
14
  import timer from './timer.js';
7
15
  import { StringMap } from './types.js';
@@ -115,10 +123,17 @@ export const logoutAsync =
115
123
  (oidc, oidcDatabase, fetch, console, oicLocation: ILOidcLocation) =>
116
124
  async (callbackPathOrUrl: string | null | undefined = undefined, extras: StringMap = null) => {
117
125
  const configuration = oidc.configuration;
118
- const oidcServerConfiguration = await oidc.initAsync(
119
- configuration.authority,
120
- configuration.authority_configuration,
121
- );
126
+ let oidcServerConfiguration;
127
+ try {
128
+ oidcServerConfiguration = await oidc.initAsync(
129
+ configuration.authority,
130
+ configuration.authority_configuration,
131
+ );
132
+ } catch (cause) {
133
+ const error = isNetworkErrorCause(cause) ? createNetworkError(cause, 'logout') : cause;
134
+ oidc.publishEvent(eventNames.logoutAsync_error, error);
135
+ throw error;
136
+ }
122
137
  if (callbackPathOrUrl && typeof callbackPathOrUrl !== 'string') {
123
138
  callbackPathOrUrl = undefined;
124
139
  console.warn('callbackPathOrUrl path is not a string');
@@ -187,14 +202,33 @@ export const logoutAsync =
187
202
  // Revocation must be awaited *before* navigation, so a cancelled
188
203
  // navigation can never leave valid tokens behind both in storage
189
204
  // and on the authorization server.
190
- await Promise.all(promises);
205
+ const results = await Promise.all(promises);
206
+ for (const result of results) {
207
+ if (!result.success) {
208
+ oidc.publishEvent(
209
+ eventNames.logoutAsync_error,
210
+ new OidcError(OidcErrorCode.REQUEST_FAILED, 'Token revocation request failed', {
211
+ phase: 'logout',
212
+ retryable: isRetryableHttpStatus(result.status),
213
+ status: result.status,
214
+ oauthError: result.oauthError,
215
+ oauthErrorDescription: result.oauthErrorDescription,
216
+ }),
217
+ );
218
+ }
219
+ }
191
220
  }
192
221
  }
193
222
  } catch (exception) {
223
+ const error =
224
+ !isOidcError(exception) && isNetworkErrorCause(exception)
225
+ ? createNetworkError(exception, 'logout')
226
+ : exception;
227
+ oidc.publishEvent(eventNames.logoutAsync_error, error);
194
228
  console.warn(
195
229
  'logoutAsync: error when revoking tokens, if the error persist, you ay configure property logout_tokens_to_invalidate from configuration to avoid this error',
196
230
  );
197
- console.warn(exception);
231
+ console.warn(error);
198
232
  }
199
233
 
200
234
  const oidcExtras = extractExtras(extras, ':oidc');
@@ -236,6 +270,11 @@ export const logoutAsync =
236
270
  // If anything went wrong, reset the flag so the app is not stuck in a
237
271
  // "logging out forever" state.
238
272
  oidc.isLoggingOut = false;
239
- throw exception;
273
+ const error =
274
+ !isOidcError(exception) && isNetworkErrorCause(exception)
275
+ ? createNetworkError(exception, 'logout')
276
+ : exception;
277
+ oidc.publishEvent(eventNames.logoutAsync_error, error);
278
+ throw error;
240
279
  }
241
280
  };