@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
@@ -1,7 +1,296 @@
1
- import { describe, expect, it } from 'vitest';
1
+ import { afterAll, beforeAll, describe, expect, it, vi } from 'vitest';
2
2
 
3
- describe('Requests test Suite', () => {
4
- it('performAuthorizationRequestAsync', async () => {
5
- expect(true).toBe(true);
3
+ import { ILOidcLocation } from './location';
4
+ import {
5
+ PushedAuthorizationRequestError,
6
+ PushedAuthorizationRequestErrorCode,
7
+ } from './pushedAuthorizationRequestError';
8
+ import {
9
+ performAuthorizationRequestAsync,
10
+ performPushedAuthorizationRequestAsync,
11
+ performTokenRequestAsync,
12
+ } from './requests';
13
+ import { Fetch } from './types';
14
+
15
+ class FakeLocation implements ILOidcLocation {
16
+ openedUrl: string = null;
17
+
18
+ open(url: string): void {
19
+ this.openedUrl = url;
20
+ }
21
+
22
+ reload(): void {}
23
+
24
+ getCurrentHref(): string {
25
+ return '';
26
+ }
27
+
28
+ getPath(): string {
29
+ return '/';
30
+ }
31
+
32
+ getOrigin(): string {
33
+ return 'https://client.example.com';
34
+ }
35
+ }
36
+
37
+ const createResponse = (status: number, data: unknown): Response =>
38
+ ({
39
+ status,
40
+ json: vi.fn(async () => data),
41
+ }) as unknown as Response;
42
+
43
+ const asFetch = (mock: ReturnType<typeof vi.fn>): Fetch => mock as unknown as Fetch;
44
+
45
+ describe('Pushed Authorization Requests', () => {
46
+ it('posts the authorization parameters as form data and accepts a RFC 9126 response', async () => {
47
+ const fetchMock = vi.fn(async (_url: string, _request: RequestInit) =>
48
+ createResponse(201, {
49
+ request_uri: 'urn:ietf:params:oauth:request_uri:abc',
50
+ expires_in: 90,
51
+ }),
52
+ );
53
+
54
+ const result = await performPushedAuthorizationRequestAsync(asFetch(fetchMock))(
55
+ 'https://issuer.example.com/par',
56
+ {
57
+ client_id: 'client',
58
+ redirect_uri: 'https://client.example.com/callback',
59
+ scope: 'openid profile',
60
+ state: 'state-value',
61
+ },
62
+ );
63
+
64
+ expect(result).toEqual({
65
+ request_uri: 'urn:ietf:params:oauth:request_uri:abc',
66
+ expires_in: 90,
67
+ });
68
+ expect(fetchMock).toHaveBeenCalledOnce();
69
+ const [url, request] = fetchMock.mock.calls[0];
70
+ expect(url).toBe('https://issuer.example.com/par');
71
+ expect(request.method).toBe('POST');
72
+ expect(request.headers).toEqual({
73
+ 'Content-Type': 'application/x-www-form-urlencoded;charset=UTF-8',
74
+ });
75
+ expect(Object.fromEntries(new URLSearchParams(request.body as string))).toEqual({
76
+ client_id: 'client',
77
+ redirect_uri: 'https://client.example.com/callback',
78
+ scope: 'openid profile',
79
+ state: 'state-value',
80
+ });
81
+ });
82
+
83
+ it('surfaces OAuth error details returned by the PAR endpoint', async () => {
84
+ const fetchMock = vi.fn(async () =>
85
+ createResponse(400, {
86
+ error: 'invalid_request',
87
+ error_description: 'redirect_uri is invalid',
88
+ }),
89
+ );
90
+
91
+ await expect(
92
+ performPushedAuthorizationRequestAsync(asFetch(fetchMock))('https://issuer.example.com/par', {
93
+ client_id: 'client',
94
+ }),
95
+ ).rejects.toMatchObject({
96
+ name: 'PushedAuthorizationRequestError',
97
+ code: PushedAuthorizationRequestErrorCode.REQUEST_FAILED,
98
+ status: 400,
99
+ oauthError: 'invalid_request',
100
+ oauthErrorDescription: 'redirect_uri is invalid',
101
+ });
102
+ });
103
+
104
+ it.each([
105
+ [{ expires_in: 90 }, 'missing request_uri'],
106
+ [{ request_uri: 'urn:request:abc' }, 'missing expires_in'],
107
+ [{ request_uri: '', expires_in: 90 }, 'empty request_uri'],
108
+ [{ request_uri: 'urn:request:abc', expires_in: 0 }, 'invalid expires_in'],
109
+ ])('rejects an invalid successful response (%s: %s)', async (data: any, _description) => {
110
+ const fetchMock = vi.fn(async () => createResponse(201, data));
111
+
112
+ await expect(
113
+ performPushedAuthorizationRequestAsync(asFetch(fetchMock))('https://issuer.example.com/par', {
114
+ client_id: 'client',
115
+ }),
116
+ ).rejects.toMatchObject({
117
+ code: PushedAuthorizationRequestErrorCode.INVALID_RESPONSE,
118
+ status: 201,
119
+ });
120
+ });
121
+
122
+ it('rejects request_uri in the pushed parameters before sending a request', async () => {
123
+ const fetchMock = vi.fn();
124
+
125
+ await expect(
126
+ performPushedAuthorizationRequestAsync(asFetch(fetchMock))('https://issuer.example.com/par', {
127
+ client_id: 'client',
128
+ request_uri: 'urn:request:not-allowed',
129
+ }),
130
+ ).rejects.toBeInstanceOf(PushedAuthorizationRequestError);
131
+ expect(fetchMock).not.toHaveBeenCalled();
132
+ });
133
+ });
134
+
135
+ describe('performAuthorizationRequestAsync', () => {
136
+ const originalWindow = Object.getOwnPropertyDescriptor(globalThis, 'window');
137
+
138
+ beforeAll(() => {
139
+ Object.defineProperty(globalThis, 'window', {
140
+ configurable: true,
141
+ value: { crypto: globalThis.crypto },
142
+ });
143
+ });
144
+
145
+ afterAll(() => {
146
+ if (originalWindow) {
147
+ Object.defineProperty(globalThis, 'window', originalWindow);
148
+ } else {
149
+ delete (globalThis as { window?: unknown }).window;
150
+ }
151
+ });
152
+
153
+ it('keeps the existing front-channel authorization request when PAR is not selected', async () => {
154
+ const storage = {
155
+ setCodeVerifierAsync: vi.fn(async () => undefined),
156
+ setStateAsync: vi.fn(async () => undefined),
157
+ };
158
+ const location = new FakeLocation();
159
+
160
+ await performAuthorizationRequestAsync(storage, location)(
161
+ 'https://issuer.example.com/authorize',
162
+ {
163
+ client_id: 'client',
164
+ redirect_uri: 'https://client.example.com/callback',
165
+ response_type: 'code',
166
+ scope: 'openid',
167
+ state: 'state-value',
168
+ },
169
+ );
170
+
171
+ const url = new URL(location.openedUrl);
172
+ expect(url.origin + url.pathname).toBe('https://issuer.example.com/authorize');
173
+ expect(Object.fromEntries(url.searchParams)).toMatchObject({
174
+ client_id: 'client',
175
+ redirect_uri: 'https://client.example.com/callback',
176
+ response_type: 'code',
177
+ scope: 'openid',
178
+ state: 'state-value',
179
+ code_challenge_method: 'S256',
180
+ });
181
+ expect(url.searchParams.get('code_challenge')).toBeTruthy();
182
+ expect(storage.setCodeVerifierAsync).toHaveBeenCalledWith(expect.any(String));
183
+ expect(storage.setStateAsync).toHaveBeenCalledWith('state-value');
184
+ });
185
+
186
+ it('pushes the complete PKCE request and redirects with only client_id and request_uri', async () => {
187
+ const storage = {
188
+ setCodeVerifierAsync: vi.fn(async () => undefined),
189
+ setStateAsync: vi.fn(async () => undefined),
190
+ };
191
+ const location = new FakeLocation();
192
+ const fetchMock = vi.fn(async (_url: string, _request: RequestInit) =>
193
+ createResponse(201, {
194
+ request_uri: 'urn:ietf:params:oauth:request_uri:abc/123',
195
+ expires_in: 60,
196
+ }),
197
+ );
198
+
199
+ await performAuthorizationRequestAsync(storage, location)(
200
+ 'https://issuer.example.com/authorize',
201
+ {
202
+ client_id: 'client',
203
+ redirect_uri: 'https://client.example.com/callback',
204
+ response_type: 'code',
205
+ scope: 'openid profile',
206
+ state: 'state-value',
207
+ nonce: 'nonce-value',
208
+ },
209
+ {
210
+ endpoint: 'https://issuer.example.com/par',
211
+ fetch: asFetch(fetchMock),
212
+ timeoutMs: 5000,
213
+ },
214
+ );
215
+
216
+ const [, request] = fetchMock.mock.calls[0];
217
+ const pushedParameters = Object.fromEntries(new URLSearchParams(request.body as string));
218
+ expect(pushedParameters).toMatchObject({
219
+ client_id: 'client',
220
+ redirect_uri: 'https://client.example.com/callback',
221
+ response_type: 'code',
222
+ scope: 'openid profile',
223
+ state: 'state-value',
224
+ nonce: 'nonce-value',
225
+ code_challenge_method: 'S256',
226
+ });
227
+ expect(pushedParameters.code_challenge).toBeTruthy();
228
+
229
+ const redirect = new URL(location.openedUrl);
230
+ expect(Object.fromEntries(redirect.searchParams)).toEqual({
231
+ client_id: 'client',
232
+ request_uri: 'urn:ietf:params:oauth:request_uri:abc/123',
233
+ });
234
+ });
235
+ });
236
+
237
+ describe('token endpoint error details', () => {
238
+ it('preserves OAuth details, HTTP status and the DPoP nonce on a non-2xx response', async () => {
239
+ const fetchMock = vi.fn(async () => {
240
+ return new Response(
241
+ JSON.stringify({
242
+ error: 'use_dpop_nonce',
243
+ error_description: 'A fresh proof is required',
244
+ }),
245
+ {
246
+ status: 400,
247
+ headers: {
248
+ 'Content-Type': 'application/json',
249
+ 'DPoP-Nonce': 'server-nonce',
250
+ },
251
+ },
252
+ );
253
+ });
254
+
255
+ const response = await performTokenRequestAsync(asFetch(fetchMock))(
256
+ 'https://issuer.example.com/token',
257
+ { grant_type: 'refresh_token' },
258
+ {},
259
+ null,
260
+ { DPoP: 'proof' },
261
+ 'access_token_or_id_token_invalid',
262
+ );
263
+
264
+ expect(response).toMatchObject({
265
+ success: false,
266
+ status: 400,
267
+ oauthError: 'use_dpop_nonce',
268
+ oauthErrorDescription: 'A fresh proof is required',
269
+ demonstratingProofOfPossessionNonce: 'server-nonce',
270
+ });
271
+ });
272
+
273
+ it.each([408, 429, 500])('preserves retryable HTTP status %s for the caller', async status => {
274
+ const fetchMock = vi.fn(async () => {
275
+ return new Response(JSON.stringify({ error: 'temporarily_unavailable' }), {
276
+ status,
277
+ headers: { 'Content-Type': 'application/json' },
278
+ });
279
+ });
280
+
281
+ const response = await performTokenRequestAsync(asFetch(fetchMock))(
282
+ 'https://issuer.example.com/token',
283
+ { grant_type: 'refresh_token' },
284
+ {},
285
+ null,
286
+ {},
287
+ 'access_token_or_id_token_invalid',
288
+ );
289
+
290
+ expect(response).toMatchObject({
291
+ success: false,
292
+ status,
293
+ oauthError: 'temporarily_unavailable',
294
+ });
6
295
  });
7
296
  });
package/src/requests.ts CHANGED
@@ -3,6 +3,10 @@ import { deriveChallengeAsync, generateRandom } from './crypto.js';
3
3
  import { ILOidcLocation } from './location';
4
4
  import { OidcAuthorizationServiceConfiguration } from './oidc.js';
5
5
  import { parseOriginalTokens } from './parseTokens.js';
6
+ import {
7
+ PushedAuthorizationRequestError,
8
+ PushedAuthorizationRequestErrorCode,
9
+ } from './pushedAuthorizationRequestError.js';
6
10
  import { Fetch, StringMap } from './types.js';
7
11
 
8
12
  const oneHourSecond = 60 * 60;
@@ -39,8 +43,12 @@ const internalFetch =
39
43
  let response;
40
44
  try {
41
45
  const controller = new AbortController();
42
- setTimeout(() => controller.abort(), timeoutMs);
43
- response = await fetch(url, { ...headers, signal: controller.signal });
46
+ const timeoutId = setTimeout(() => controller.abort(), timeoutMs);
47
+ try {
48
+ response = await fetch(url, { ...headers, signal: controller.signal });
49
+ } finally {
50
+ clearTimeout(timeoutId);
51
+ }
44
52
  } catch (e: any) {
45
53
  if (e.name === 'AbortError' || e.message === 'Network request failed') {
46
54
  if (numberRetry <= 1) {
@@ -102,10 +110,18 @@ export const performRevocationRequestAsync =
102
110
  timeoutMs,
103
111
  );
104
112
  if (response.status !== 200) {
105
- return { success: false };
113
+ const data = await getResponseJsonAsync(response);
114
+ return {
115
+ success: false,
116
+ status: response.status,
117
+ oauthError: typeof data?.error === 'string' ? data.error : undefined,
118
+ oauthErrorDescription:
119
+ typeof data?.error_description === 'string' ? data.error_description : undefined,
120
+ };
106
121
  }
107
122
  return {
108
123
  success: true,
124
+ status: response.status,
109
125
  };
110
126
  };
111
127
 
@@ -114,8 +130,103 @@ type PerformTokenRequestResponse = {
114
130
  status?: number;
115
131
  data?: any;
116
132
  demonstratingProofOfPossessionNonce?: string;
133
+ oauthError?: string;
134
+ oauthErrorDescription?: string;
135
+ };
136
+
137
+ export type PushedAuthorizationRequestResponse = {
138
+ request_uri: string;
139
+ expires_in: number;
117
140
  };
118
141
 
142
+ const getResponseJsonAsync = async (response: Response): Promise<any> => {
143
+ try {
144
+ return await response.json();
145
+ } catch {
146
+ return null;
147
+ }
148
+ };
149
+
150
+ export const performPushedAuthorizationRequestAsync =
151
+ (fetch: Fetch) =>
152
+ async (
153
+ url: string,
154
+ details: StringMap,
155
+ timeoutMs = 10000,
156
+ ): Promise<PushedAuthorizationRequestResponse> => {
157
+ if (details.request_uri !== undefined) {
158
+ throw new PushedAuthorizationRequestError(
159
+ PushedAuthorizationRequestErrorCode.REQUEST_FAILED,
160
+ 'The request_uri parameter must not be included in a pushed authorization request.',
161
+ );
162
+ }
163
+
164
+ const formBody = [];
165
+ for (const property in details) {
166
+ const encodedKey = encodeURIComponent(property);
167
+ const encodedValue = encodeURIComponent(details[property]);
168
+ formBody.push(`${encodedKey}=${encodedValue}`);
169
+ }
170
+
171
+ let response: Response;
172
+ try {
173
+ response = await internalFetch(fetch)(
174
+ url,
175
+ {
176
+ method: 'POST',
177
+ headers: {
178
+ 'Content-Type': 'application/x-www-form-urlencoded;charset=UTF-8',
179
+ },
180
+ body: formBody.join('&'),
181
+ },
182
+ timeoutMs,
183
+ );
184
+ } catch (cause) {
185
+ throw new PushedAuthorizationRequestError(
186
+ PushedAuthorizationRequestErrorCode.REQUEST_FAILED,
187
+ 'The pushed authorization request could not be sent.',
188
+ { cause },
189
+ );
190
+ }
191
+
192
+ const data = await getResponseJsonAsync(response);
193
+ if (response.status !== 201) {
194
+ const oauthError = typeof data?.error === 'string' ? data.error : undefined;
195
+ const oauthErrorDescription =
196
+ typeof data?.error_description === 'string' ? data.error_description : undefined;
197
+ const serverError = [oauthError, oauthErrorDescription].filter(Boolean).join(': ');
198
+ throw new PushedAuthorizationRequestError(
199
+ PushedAuthorizationRequestErrorCode.REQUEST_FAILED,
200
+ `The pushed authorization request failed with HTTP status ${response.status}${
201
+ serverError ? ` (${serverError})` : ''
202
+ }.`,
203
+ {
204
+ status: response.status,
205
+ oauthError,
206
+ oauthErrorDescription,
207
+ },
208
+ );
209
+ }
210
+
211
+ if (
212
+ typeof data?.request_uri !== 'string' ||
213
+ data.request_uri.length === 0 ||
214
+ !Number.isInteger(data?.expires_in) ||
215
+ data.expires_in <= 0
216
+ ) {
217
+ throw new PushedAuthorizationRequestError(
218
+ PushedAuthorizationRequestErrorCode.INVALID_RESPONSE,
219
+ 'The pushed authorization response must contain a non-empty request_uri and a positive integer expires_in.',
220
+ { status: response.status },
221
+ );
222
+ }
223
+
224
+ return {
225
+ request_uri: data.request_uri,
226
+ expires_in: data.expires_in,
227
+ };
228
+ };
229
+
119
230
  export const performTokenRequestAsync =
120
231
  (fetch: Fetch) =>
121
232
  async (
@@ -154,10 +265,19 @@ export const performTokenRequestAsync =
154
265
  timeoutMs,
155
266
  );
156
267
  if (response.status !== 200) {
268
+ const data = await getResponseJsonAsync(response);
157
269
  return {
158
270
  success: false,
159
271
  status: response.status,
160
- demonstratingProofOfPossessionNonce: null,
272
+ data,
273
+ oauthError: typeof data?.error === 'string' ? data.error : undefined,
274
+ oauthErrorDescription:
275
+ typeof data?.error_description === 'string' ? data.error_description : undefined,
276
+ demonstratingProofOfPossessionNonce: response.headers?.has(
277
+ demonstratingProofOfPossessionNonceResponseHeader,
278
+ )
279
+ ? response.headers.get(demonstratingProofOfPossessionNonceResponseHeader)
280
+ : null,
161
281
  };
162
282
  }
163
283
  const tokens = await response.json();
@@ -177,7 +297,16 @@ export const performTokenRequestAsync =
177
297
  };
178
298
 
179
299
  export const performAuthorizationRequestAsync =
180
- (storage: any, oidcLocation: ILOidcLocation) => async (url, extras: StringMap) => {
300
+ (storage: any, oidcLocation: ILOidcLocation) =>
301
+ async (
302
+ url,
303
+ extras: StringMap,
304
+ pushedAuthorizationRequest?: {
305
+ endpoint: string;
306
+ fetch: Fetch;
307
+ timeoutMs?: number;
308
+ },
309
+ ) => {
181
310
  extras = extras ? { ...extras } : {};
182
311
  const codeVerifier = generateRandom(128);
183
312
  const codeChallenge = await deriveChallengeAsync(codeVerifier);
@@ -185,6 +314,19 @@ export const performAuthorizationRequestAsync =
185
314
  await storage.setStateAsync(extras.state);
186
315
  extras.code_challenge = codeChallenge;
187
316
  extras.code_challenge_method = 'S256';
317
+
318
+ if (pushedAuthorizationRequest) {
319
+ const response = await performPushedAuthorizationRequestAsync(
320
+ pushedAuthorizationRequest.fetch,
321
+ )(pushedAuthorizationRequest.endpoint, extras, pushedAuthorizationRequest.timeoutMs);
322
+ oidcLocation.open(
323
+ `${url}?client_id=${encodeURIComponent(extras.client_id)}&request_uri=${encodeURIComponent(
324
+ response.request_uri,
325
+ )}`,
326
+ );
327
+ return;
328
+ }
329
+
188
330
  let queryString = '';
189
331
  if (extras) {
190
332
  for (const [key, value] of Object.entries(extras)) {
@@ -202,7 +344,14 @@ export const performAuthorizationRequestAsync =
202
344
  const demonstratingProofOfPossessionNonceResponseHeader = 'DPoP-Nonce';
203
345
  export const performFirstTokenRequestAsync =
204
346
  (storage: any) =>
205
- async (url, formBodyExtras, headersExtras, tokenRenewMode: string, timeoutMs = 10000) => {
347
+ async (
348
+ url,
349
+ formBodyExtras,
350
+ headersExtras,
351
+ tokenRenewMode: string,
352
+ timeoutMs = 10000,
353
+ shouldPreserveLoginStateForDpopRetry = false,
354
+ ): Promise<PerformTokenRequestResponse> => {
206
355
  formBodyExtras = formBodyExtras ? { ...formBodyExtras } : {};
207
356
  formBodyExtras.code_verifier = await storage.getCodeVerifierAsync();
208
357
  const formBody = [];
@@ -224,10 +373,27 @@ export const performFirstTokenRequestAsync =
224
373
  },
225
374
  timeoutMs,
226
375
  );
227
- await Promise.all([storage.setCodeVerifierAsync(null), storage.setStateAsync(null)]);
228
376
  if (response.status !== 200) {
229
- return { success: false, status: response.status };
377
+ const data = await getResponseJsonAsync(response);
378
+ const oauthError = typeof data?.error === 'string' ? data.error : undefined;
379
+ if (!(shouldPreserveLoginStateForDpopRetry && oauthError === 'use_dpop_nonce')) {
380
+ await Promise.all([storage.setCodeVerifierAsync(null), storage.setStateAsync(null)]);
381
+ }
382
+ return {
383
+ success: false,
384
+ status: response.status,
385
+ data,
386
+ oauthError,
387
+ oauthErrorDescription:
388
+ typeof data?.error_description === 'string' ? data.error_description : undefined,
389
+ demonstratingProofOfPossessionNonce: response.headers?.has(
390
+ demonstratingProofOfPossessionNonceResponseHeader,
391
+ )
392
+ ? response.headers.get(demonstratingProofOfPossessionNonceResponseHeader)
393
+ : null,
394
+ };
230
395
  }
396
+ await Promise.all([storage.setCodeVerifierAsync(null), storage.setStateAsync(null)]);
231
397
  let demonstratingProofOfPossessionNonce: string = null;
232
398
  if (response.headers.has(demonstratingProofOfPossessionNonceResponseHeader)) {
233
399
  demonstratingProofOfPossessionNonce = response.headers.get(