@axa-fr/oidc-client 7.27.19 → 7.29.2

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
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
  };
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
  }