@axa-fr/oidc-client 7.29.4 → 7.29.6

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.
@@ -1,4 +1,4 @@
1
- import { describe, expect, it } from 'vitest';
1
+ import { afterEach, describe, expect, it, vi } from 'vitest';
2
2
 
3
3
  import { sleepAsync } from './initWorker';
4
4
  import {
@@ -13,6 +13,64 @@ import { synchroniseTokensStatus } from './renewTokens';
13
13
  import { StringMap, TokenAutomaticRenewMode } from './types';
14
14
 
15
15
  describe('ParseTokens test Suite', () => {
16
+ describe.each(['accessToken', 'idToken'])('%s payload extraction', tokenProperty => {
17
+ const payload = { sub: 'unit-test', name: 'Test user' };
18
+ const encodedPayload = btoa(JSON.stringify(payload));
19
+
20
+ afterEach(() => {
21
+ vi.restoreAllMocks();
22
+ });
23
+
24
+ it.each([`header.${encodedPayload}.signature`, `.${encodedPayload}.`])(
25
+ 'extracts the payload from a three-part token: %s',
26
+ token => {
27
+ const tokens = setTokens(
28
+ { [tokenProperty]: token, issuedAt: 1000, expiresIn: 60 },
29
+ null,
30
+ TokenRenewMode.access_token_invalid,
31
+ );
32
+
33
+ expect(tokens[`${tokenProperty}Payload`]).toEqual(payload);
34
+ expect(tokens[tokenProperty]).toBe(token);
35
+ },
36
+ );
37
+
38
+ it.each([
39
+ undefined,
40
+ null,
41
+ '',
42
+ 'opaque-token',
43
+ `header.${encodedPayload}`,
44
+ `header.${encodedPayload}.signature.extra`,
45
+ `header.${encodedPayload}.signature.`,
46
+ ])('returns a null payload for a token without exactly three parts: %s', token => {
47
+ const warn = vi.spyOn(console, 'warn').mockImplementation(() => undefined);
48
+ const tokens = setTokens(
49
+ { [tokenProperty]: token, issuedAt: 1000, expiresIn: 60 },
50
+ null,
51
+ TokenRenewMode.access_token_invalid,
52
+ );
53
+
54
+ expect(tokens[`${tokenProperty}Payload`]).toBeNull();
55
+ expect(warn).not.toHaveBeenCalled();
56
+ });
57
+
58
+ it.each(['header..signature', 'header.!.signature', 'header.bm90IGpzb24=.signature'])(
59
+ 'warns and returns a null payload when decoding fails: %s',
60
+ token => {
61
+ const warn = vi.spyOn(console, 'warn').mockImplementation(() => undefined);
62
+ const tokens = setTokens(
63
+ { [tokenProperty]: token, issuedAt: 1000, expiresIn: 60 },
64
+ null,
65
+ TokenRenewMode.access_token_invalid,
66
+ );
67
+
68
+ expect(tokens[`${tokenProperty}Payload`]).toBeNull();
69
+ expect(warn).toHaveBeenCalledExactlyOnceWith(expect.any(Error));
70
+ },
71
+ );
72
+ });
73
+
16
74
  const currentTimeUnixSecond = new Date().getTime() / 1000;
17
75
  describe.each([
18
76
  [currentTimeUnixSecond + 120, currentTimeUnixSecond - 10, true],
@@ -16,21 +16,14 @@ const extractTokenPayload = (token: string) => {
16
16
  if (!token) {
17
17
  return null;
18
18
  }
19
- if (countLetter(token, '.') === 2) {
20
- return parseJwt(token.split('.')[1]);
21
- } else {
22
- return null;
23
- }
19
+ const parts = token.split('.');
20
+ return parts.length === 3 ? parseJwt(parts[1]) : null;
24
21
  } catch (e) {
25
22
  console.warn(e);
26
23
  }
27
24
  return null;
28
25
  };
29
26
 
30
- const countLetter = (str: string, find) => {
31
- return str.split(find).length - 1;
32
- };
33
-
34
27
  export type Tokens = {
35
28
  refreshToken: string;
36
29
  idTokenPayload: any;
@@ -0,0 +1,139 @@
1
+ import { afterEach, describe, expect, it, vi } from 'vitest';
2
+
3
+ import { TokenRenewMode } from './parseTokens';
4
+ import {
5
+ performFirstTokenRequestAsync,
6
+ performPushedAuthorizationRequestAsync,
7
+ performRevocationRequestAsync,
8
+ performTokenRequestAsync,
9
+ } from './requests';
10
+ import type { Fetch, StringMap } from './types';
11
+
12
+ describe('OAuth request form encoding', () => {
13
+ afterEach(() => {
14
+ vi.unstubAllGlobals();
15
+ });
16
+
17
+ it.each(['revocation', 'token', 'first token', 'PAR'])(
18
+ 'preserves encoding and parameters for %s requests',
19
+ async requestType => {
20
+ const fetch = vi
21
+ .fn<Fetch>()
22
+ .mockResolvedValue(
23
+ new Response(
24
+ JSON.stringify(
25
+ requestType === 'PAR'
26
+ ? { request_uri: 'urn:request:example', expires_in: 60 }
27
+ : { access_token: 'opaque', issued_at: 1000, expires_in: 60 },
28
+ ),
29
+ { status: requestType === 'PAR' ? 201 : 200 },
30
+ ),
31
+ );
32
+ const parameters = {
33
+ 'custom key': 'a+b &c=値',
34
+ scope: 'openid profile',
35
+ empty: '',
36
+ };
37
+ const endpoint = 'https://issuer.example.com/endpoint';
38
+ const expectedParameters: StringMap = { ...parameters };
39
+
40
+ if (requestType === 'revocation') {
41
+ await performRevocationRequestAsync(fetch)(
42
+ endpoint,
43
+ 'opaque',
44
+ 'access_token',
45
+ 'client',
46
+ parameters,
47
+ );
48
+ Object.assign(expectedParameters, {
49
+ token: 'opaque',
50
+ token_type_hint: 'access_token',
51
+ client_id: 'client',
52
+ });
53
+ } else if (requestType === 'token') {
54
+ await performTokenRequestAsync(fetch)(
55
+ endpoint,
56
+ { grant_type: 'refresh_token' },
57
+ parameters,
58
+ null,
59
+ {},
60
+ TokenRenewMode.access_token_invalid,
61
+ );
62
+ expectedParameters.grant_type = 'refresh_token';
63
+ } else if (requestType === 'first token') {
64
+ vi.stubGlobal('fetch', fetch);
65
+ const storage = {
66
+ getCodeVerifierAsync: vi.fn().mockResolvedValue('test-verifier'),
67
+ setCodeVerifierAsync: vi.fn(),
68
+ setStateAsync: vi.fn(),
69
+ };
70
+ await performFirstTokenRequestAsync(storage)(
71
+ endpoint,
72
+ parameters,
73
+ {},
74
+ TokenRenewMode.access_token_invalid,
75
+ );
76
+ expectedParameters.code_verifier = 'test-verifier';
77
+ expect(storage.setCodeVerifierAsync).toHaveBeenCalledWith(null);
78
+ expect(storage.setStateAsync).toHaveBeenCalledWith(null);
79
+ } else {
80
+ await performPushedAuthorizationRequestAsync(fetch)(endpoint, parameters);
81
+ }
82
+
83
+ expect(fetch).toHaveBeenCalledOnce();
84
+ const [url, request] = fetch.mock.calls[0];
85
+ expect(url).toBe(endpoint);
86
+ expect(request.method).toBe('POST');
87
+ expect(request.headers).toEqual({
88
+ 'Content-Type': 'application/x-www-form-urlencoded;charset=UTF-8',
89
+ });
90
+ expect(request.body).toContain('custom%20key=a%2Bb%20%26c%3D%E5%80%A4');
91
+ expect(request.body).toContain('scope=openid%20profile');
92
+ expect(Object.fromEntries(new URLSearchParams(request.body as string))).toEqual(
93
+ expectedParameters,
94
+ );
95
+ expect(parameters).toEqual({
96
+ 'custom key': 'a+b &c=値',
97
+ scope: 'openid profile',
98
+ empty: '',
99
+ });
100
+ },
101
+ );
102
+
103
+ it('does not let revocation extras override existing parameters', async () => {
104
+ const fetch = vi.fn<Fetch>().mockResolvedValue(new Response(null, { status: 200 }));
105
+
106
+ await performRevocationRequestAsync(fetch)(
107
+ 'https://issuer.example.com/revoke',
108
+ 'original',
109
+ 'access_token',
110
+ 'client',
111
+ { token: 'replacement', client_id: 'other', token_type_hint: 'refresh_token' },
112
+ );
113
+
114
+ expect(fetch.mock.calls[0][1].body).toBe(
115
+ 'token=original&token_type_hint=access_token&client_id=client',
116
+ );
117
+ });
118
+
119
+ it('preserves enumerable inherited parameters in token requests', async () => {
120
+ const fetch = vi.fn<Fetch>().mockResolvedValue(new Response('{}', { status: 400 }));
121
+ const details: StringMap = Object.assign(Object.create({ inherited: 'value' }), {
122
+ grant_type: 'refresh_token',
123
+ });
124
+
125
+ await performTokenRequestAsync(fetch)(
126
+ 'https://issuer.example.com/token',
127
+ details,
128
+ { grant_type: 'ignored', extra: 'added' },
129
+ null,
130
+ {},
131
+ TokenRenewMode.access_token_invalid,
132
+ );
133
+
134
+ expect(fetch.mock.calls[0][1].body).toBe(
135
+ 'grant_type=refresh_token&extra=added&inherited=value',
136
+ );
137
+ expect(details.extra).toBe('added');
138
+ });
139
+ });
package/src/requests.ts CHANGED
@@ -69,6 +69,14 @@ export const TOKEN_TYPE = {
69
69
  access_token: 'access_token',
70
70
  };
71
71
 
72
+ const encodeFormBody = (details: StringMap): string => {
73
+ const formBody: string[] = [];
74
+ for (const property in details) {
75
+ formBody.push(`${encodeURIComponent(property)}=${encodeURIComponent(details[property])}`);
76
+ }
77
+ return formBody.join('&');
78
+ };
79
+
72
80
  export const performRevocationRequestAsync =
73
81
  fetch =>
74
82
  async (
@@ -90,13 +98,7 @@ export const performRevocationRequestAsync =
90
98
  }
91
99
  }
92
100
 
93
- const formBody = [];
94
- for (const property in details) {
95
- const encodedKey = encodeURIComponent(property);
96
- const encodedValue = encodeURIComponent(details[property]);
97
- formBody.push(`${encodedKey}=${encodedValue}`);
98
- }
99
- const formBodyString = formBody.join('&');
101
+ const formBodyString = encodeFormBody(details);
100
102
 
101
103
  const response = await internalFetch(fetch)(
102
104
  url,
@@ -161,12 +163,7 @@ export const performPushedAuthorizationRequestAsync =
161
163
  );
162
164
  }
163
165
 
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
- }
166
+ const formBodyString = encodeFormBody(details);
170
167
 
171
168
  let response: Response;
172
169
  try {
@@ -177,7 +174,7 @@ export const performPushedAuthorizationRequestAsync =
177
174
  headers: {
178
175
  'Content-Type': 'application/x-www-form-urlencoded;charset=UTF-8',
179
176
  },
180
- body: formBody.join('&'),
177
+ body: formBodyString,
181
178
  },
182
179
  timeoutMs,
183
180
  );
@@ -244,13 +241,7 @@ export const performTokenRequestAsync =
244
241
  }
245
242
  }
246
243
 
247
- const formBody = [];
248
- for (const property in details) {
249
- const encodedKey = encodeURIComponent(property);
250
- const encodedValue = encodeURIComponent(details[property]);
251
- formBody.push(`${encodedKey}=${encodedValue}`);
252
- }
253
- const formBodyString = formBody.join('&');
244
+ const formBodyString = encodeFormBody(details);
254
245
 
255
246
  const response = await internalFetch(fetch)(
256
247
  url,
@@ -354,13 +345,7 @@ export const performFirstTokenRequestAsync =
354
345
  ): Promise<PerformTokenRequestResponse> => {
355
346
  formBodyExtras = formBodyExtras ? { ...formBodyExtras } : {};
356
347
  formBodyExtras.code_verifier = await storage.getCodeVerifierAsync();
357
- const formBody = [];
358
- for (const property in formBodyExtras) {
359
- const encodedKey = encodeURIComponent(property);
360
- const encodedValue = encodeURIComponent(formBodyExtras[property]);
361
- formBody.push(`${encodedKey}=${encodedValue}`);
362
- }
363
- const formBodyString = formBody.join('&');
348
+ const formBodyString = encodeFormBody(formBodyExtras);
364
349
  const response = await internalFetch(fetch)(
365
350
  url,
366
351
  {
@@ -1,6 +1,6 @@
1
1
  import { describe, expect, it } from 'vitest';
2
2
 
3
- import { getPath } from './route-utils';
3
+ import { getLocation, getParseQueryStringFromLocation, getPath } from './route-utils';
4
4
 
5
5
  describe('Route test Suite', () => {
6
6
  it.each([
@@ -17,6 +17,61 @@ describe('Route test Suite', () => {
17
17
  expect(path).toBe(expected);
18
18
  });
19
19
 
20
+ describe('URL parsing', () => {
21
+ it('preserves the original URL and separates its components', () => {
22
+ const href = 'https://example.com:8443/path/?state=abc#section';
23
+
24
+ expect(getLocation(href)).toEqual({
25
+ href,
26
+ protocol: 'https:',
27
+ host: 'example.com:8443',
28
+ hostname: 'example.com',
29
+ port: '8443',
30
+ path: '/path/',
31
+ search: 'state=abc',
32
+ hash: '#section',
33
+ });
34
+ });
35
+
36
+ it.each([
37
+ ['https://example.com/path?outer=value#route?inner=value', 'inner=value', '#route'],
38
+ ['https://example.com/path?outer=value#route?a?b', 'outer=value', '#route?a?b'],
39
+ ['https://example.com/path', '', ''],
40
+ ])('preserves query and fragment precedence for %s', (href, search, hash) => {
41
+ expect(getLocation(href)).toMatchObject({ search, hash });
42
+ });
43
+
44
+ it.each([
45
+ ['https://example.com/path/#_=_', '/path'],
46
+ ['https://example.com/path//#', '/path/'],
47
+ ['https://example.com/path/#/route/', '/path#/route/'],
48
+ ])(
49
+ 'normalizes only the existing trailing slash and sentinel fragments for %s',
50
+ (href, path) => {
51
+ expect(getPath(href)).toBe(path);
52
+ },
53
+ );
54
+
55
+ it.each([
56
+ ['?name=Jane%20Doe&scope=openid%2Bprofile', { name: 'Jane Doe', scope: 'openid+profile' }],
57
+ ['?scope=openid+profile', { scope: 'openid+profile' }],
58
+ ['?key=first&key=last', { key: 'last' }],
59
+ ['?empty=&flag', { empty: '', flag: 'undefined' }],
60
+ ['?value=a=b', { value: 'a' }],
61
+ ['', { '': 'undefined' }],
62
+ ['?outer=value#route?inner=value', { inner: 'value' }],
63
+ ['?%E5%90%8D=%E5%80%A4', { 名: '値' }],
64
+ ])('preserves query decoding behavior for %s', (suffix, expected) => {
65
+ expect(getParseQueryStringFromLocation(`https://example.com/${suffix}`)).toEqual(expected);
66
+ });
67
+
68
+ it.each(['?key=%', '?%ZZ=value'])('preserves malformed escape errors for %s', suffix => {
69
+ expect(() => getParseQueryStringFromLocation(`https://example.com/${suffix}`)).toThrow(
70
+ URIError,
71
+ );
72
+ });
73
+ });
74
+
20
75
  it('wrong uri format', () => {
21
76
  expect(() => getPath('urimybad/toto.com')).toThrowError();
22
77
  });
@@ -22,18 +22,16 @@ export const getLocation = (href: string) => {
22
22
  search = search.slice(1);
23
23
  }
24
24
 
25
- return (
26
- match && {
27
- href,
28
- protocol: match[1],
29
- host: match[2],
30
- hostname: match[3],
31
- port: match[4],
32
- path: match[5],
33
- search,
34
- hash,
35
- }
36
- );
25
+ return {
26
+ href,
27
+ protocol: match[1],
28
+ host: match[2],
29
+ hostname: match[3],
30
+ port: match[4],
31
+ path: match[5],
32
+ search,
33
+ hash,
34
+ };
37
35
  };
38
36
 
39
37
  export const getPath = (href: string) => {
@@ -65,17 +63,9 @@ export const getParseQueryStringFromLocation = (href: string) => {
65
63
 
66
64
  const parseQueryString = (queryString: string) => {
67
65
  const params: any = {};
68
- let temp;
69
- let i;
70
- let l;
71
-
72
- // Split into key/value pairs
73
- const queries = queryString.split('&');
74
-
75
- // Convert the array of strings into an object
76
- for (i = 0, l = queries.length; i < l; i++) {
77
- temp = queries[i].split('=');
78
- params[decodeURIComponent(temp[0])] = decodeURIComponent(temp[1]);
66
+ for (const query of queryString.split('&')) {
67
+ const [key, value] = query.split('=');
68
+ params[decodeURIComponent(key)] = decodeURIComponent(value);
79
69
  }
80
70
 
81
71
  return params;
package/src/version.ts CHANGED
@@ -1 +1 @@
1
- export default '7.29.4';
1
+ export default '7.29.6';