forked from panva/oauth4webapi
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathindex.js
2051 lines (2051 loc) · 75.8 KB
/
index.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
let USER_AGENT;
if (typeof navigator === 'undefined' || !navigator.userAgent?.startsWith?.('Mozilla/5.0 ')) {
const NAME = 'oauth4webapi';
const VERSION = 'v2.17.0';
USER_AGENT = `${NAME}/${VERSION}`;
}
function looseInstanceOf(input, expected) {
if (input == null) {
return false;
}
try {
return (input instanceof expected ||
Object.getPrototypeOf(input)[Symbol.toStringTag] === expected.prototype[Symbol.toStringTag]);
}
catch {
return false;
}
}
export const clockSkew = Symbol();
export const clockTolerance = Symbol();
export const customFetch = Symbol();
export const modifyAssertion = Symbol();
export const jweDecrypt = Symbol();
export const jwksCache = Symbol();
export const useMtlsAlias = Symbol();
const encoder = new TextEncoder();
const decoder = new TextDecoder();
function buf(input) {
if (typeof input === 'string') {
return encoder.encode(input);
}
return decoder.decode(input);
}
const CHUNK_SIZE = 0x8000;
function encodeBase64Url(input) {
if (input instanceof ArrayBuffer) {
input = new Uint8Array(input);
}
const arr = [];
for (let i = 0; i < input.byteLength; i += CHUNK_SIZE) {
arr.push(String.fromCharCode.apply(null, input.subarray(i, i + CHUNK_SIZE)));
}
return btoa(arr.join('')).replace(/=/g, '').replace(/\+/g, '-').replace(/\//g, '_');
}
function decodeBase64Url(input) {
try {
const binary = atob(input.replace(/-/g, '+').replace(/_/g, '/').replace(/\s/g, ''));
const bytes = new Uint8Array(binary.length);
for (let i = 0; i < binary.length; i++) {
bytes[i] = binary.charCodeAt(i);
}
return bytes;
}
catch (cause) {
throw new OPE('The input to be decoded is not correctly encoded.', { cause });
}
}
function b64u(input) {
if (typeof input === 'string') {
return decodeBase64Url(input);
}
return encodeBase64Url(input);
}
class LRU {
constructor(maxSize) {
this.cache = new Map();
this._cache = new Map();
this.maxSize = maxSize;
}
get(key) {
let v = this.cache.get(key);
if (v) {
return v;
}
if ((v = this._cache.get(key))) {
this.update(key, v);
return v;
}
return undefined;
}
has(key) {
return this.cache.has(key) || this._cache.has(key);
}
set(key, value) {
if (this.cache.has(key)) {
this.cache.set(key, value);
}
else {
this.update(key, value);
}
return this;
}
delete(key) {
if (this.cache.has(key)) {
return this.cache.delete(key);
}
if (this._cache.has(key)) {
return this._cache.delete(key);
}
return false;
}
update(key, value) {
this.cache.set(key, value);
if (this.cache.size >= this.maxSize) {
this._cache = this.cache;
this.cache = new Map();
}
}
}
export class UnsupportedOperationError extends Error {
constructor(message) {
super(message ?? 'operation not supported');
this.name = this.constructor.name;
Error.captureStackTrace?.(this, this.constructor);
}
}
export class OperationProcessingError extends Error {
constructor(message, options) {
super(message, options);
this.name = this.constructor.name;
Error.captureStackTrace?.(this, this.constructor);
}
}
const OPE = OperationProcessingError;
const dpopNonces = new LRU(100);
function isCryptoKey(key) {
return key instanceof CryptoKey;
}
function isPrivateKey(key) {
return isCryptoKey(key) && key.type === 'private';
}
function isPublicKey(key) {
return isCryptoKey(key) && key.type === 'public';
}
const SUPPORTED_JWS_ALGS = [
'PS256',
'ES256',
'RS256',
'PS384',
'ES384',
'RS384',
'PS512',
'ES512',
'RS512',
'EdDSA',
];
function processDpopNonce(response) {
try {
const nonce = response.headers.get('dpop-nonce');
if (nonce) {
dpopNonces.set(new URL(response.url).origin, nonce);
}
}
catch { }
return response;
}
function normalizeTyp(value) {
return value.toLowerCase().replace(/^application\//, '');
}
function isJsonObject(input) {
if (input === null || typeof input !== 'object' || Array.isArray(input)) {
return false;
}
return true;
}
function prepareHeaders(input) {
if (looseInstanceOf(input, Headers)) {
input = Object.fromEntries(input.entries());
}
const headers = new Headers(input);
if (USER_AGENT && !headers.has('user-agent')) {
headers.set('user-agent', USER_AGENT);
}
if (headers.has('authorization')) {
throw new TypeError('"options.headers" must not include the "authorization" header name');
}
if (headers.has('dpop')) {
throw new TypeError('"options.headers" must not include the "dpop" header name');
}
return headers;
}
function signal(value) {
if (typeof value === 'function') {
value = value();
}
if (!(value instanceof AbortSignal)) {
throw new TypeError('"options.signal" must return or be an instance of AbortSignal');
}
return value;
}
export async function discoveryRequest(issuerIdentifier, options) {
if (!(issuerIdentifier instanceof URL)) {
throw new TypeError('"issuerIdentifier" must be an instance of URL');
}
if (issuerIdentifier.protocol !== 'https:' && issuerIdentifier.protocol !== 'http:') {
throw new TypeError('"issuer.protocol" must be "https:" or "http:"');
}
const url = new URL(issuerIdentifier.href);
switch (options?.algorithm) {
case undefined:
case 'oidc':
url.pathname = `${url.pathname}/.well-known/openid-configuration`.replace('//', '/');
break;
case 'oauth2':
if (url.pathname === '/') {
url.pathname = '.well-known/oauth-authorization-server';
}
else {
url.pathname = `.well-known/oauth-authorization-server/${url.pathname}`.replace('//', '/');
}
break;
default:
throw new TypeError('"options.algorithm" must be "oidc" (default), or "oauth2"');
}
const headers = prepareHeaders(options?.headers);
headers.set('accept', 'application/json');
return (options?.[customFetch] || fetch)(url.href, {
headers: Object.fromEntries(headers.entries()),
method: 'GET',
redirect: 'manual',
signal: options?.signal ? signal(options.signal) : null,
}).then(processDpopNonce);
}
function validateString(input) {
return typeof input === 'string' && input.length !== 0;
}
export async function processDiscoveryResponse(expectedIssuerIdentifier, response) {
if (!(expectedIssuerIdentifier instanceof URL)) {
throw new TypeError('"expectedIssuer" must be an instance of URL');
}
if (!looseInstanceOf(response, Response)) {
throw new TypeError('"response" must be an instance of Response');
}
if (response.status !== 200) {
throw new OPE('"response" is not a conform Authorization Server Metadata response');
}
assertReadableResponse(response);
let json;
try {
json = await response.json();
}
catch (cause) {
throw new OPE('failed to parse "response" body as JSON', { cause });
}
if (!isJsonObject(json)) {
throw new OPE('"response" body must be a top level object');
}
if (!validateString(json.issuer)) {
throw new OPE('"response" body "issuer" property must be a non-empty string');
}
if (new URL(json.issuer).href !== expectedIssuerIdentifier.href) {
throw new OPE('"response" body "issuer" does not match "expectedIssuer"');
}
return json;
}
function randomBytes() {
return b64u(crypto.getRandomValues(new Uint8Array(32)));
}
export function generateRandomCodeVerifier() {
return randomBytes();
}
export function generateRandomState() {
return randomBytes();
}
export function generateRandomNonce() {
return randomBytes();
}
export async function calculatePKCECodeChallenge(codeVerifier) {
if (!validateString(codeVerifier)) {
throw new TypeError('"codeVerifier" must be a non-empty string');
}
return b64u(await crypto.subtle.digest('SHA-256', buf(codeVerifier)));
}
function getKeyAndKid(input) {
if (input instanceof CryptoKey) {
return { key: input };
}
if (!(input?.key instanceof CryptoKey)) {
return {};
}
if (input.kid !== undefined && !validateString(input.kid)) {
throw new TypeError('"kid" must be a non-empty string');
}
return {
key: input.key,
kid: input.kid,
modifyAssertion: input[modifyAssertion],
};
}
function formUrlEncode(token) {
return encodeURIComponent(token).replace(/%20/g, '+');
}
function clientSecretBasic(clientId, clientSecret) {
const username = formUrlEncode(clientId);
const password = formUrlEncode(clientSecret);
const credentials = btoa(`${username}:${password}`);
return `Basic ${credentials}`;
}
function psAlg(key) {
switch (key.algorithm.hash.name) {
case 'SHA-256':
return 'PS256';
case 'SHA-384':
return 'PS384';
case 'SHA-512':
return 'PS512';
default:
throw new UnsupportedOperationError('unsupported RsaHashedKeyAlgorithm hash name');
}
}
function rsAlg(key) {
switch (key.algorithm.hash.name) {
case 'SHA-256':
return 'RS256';
case 'SHA-384':
return 'RS384';
case 'SHA-512':
return 'RS512';
default:
throw new UnsupportedOperationError('unsupported RsaHashedKeyAlgorithm hash name');
}
}
function esAlg(key) {
switch (key.algorithm.namedCurve) {
case 'P-256':
return 'ES256';
case 'P-384':
return 'ES384';
case 'P-521':
return 'ES512';
default:
throw new UnsupportedOperationError('unsupported EcKeyAlgorithm namedCurve');
}
}
function keyToJws(key) {
switch (key.algorithm.name) {
case 'RSA-PSS':
return psAlg(key);
case 'RSASSA-PKCS1-v1_5':
return rsAlg(key);
case 'ECDSA':
return esAlg(key);
case 'Ed25519':
case 'Ed448':
return 'EdDSA';
default:
throw new UnsupportedOperationError('unsupported CryptoKey algorithm name');
}
}
function getClockSkew(client) {
const skew = client?.[clockSkew];
return typeof skew === 'number' && Number.isFinite(skew) ? skew : 0;
}
function getClockTolerance(client) {
const tolerance = client?.[clockTolerance];
return typeof tolerance === 'number' && Number.isFinite(tolerance) && Math.sign(tolerance) !== -1
? tolerance
: 30;
}
function epochTime() {
return Math.floor(Date.now() / 1000);
}
function clientAssertion(as, client) {
const now = epochTime() + getClockSkew(client);
return {
jti: randomBytes(),
aud: [as.issuer, as.token_endpoint],
exp: now + 60,
iat: now,
nbf: now,
iss: client.client_id,
sub: client.client_id,
};
}
async function privateKeyJwt(as, client, key, kid, modifyAssertion) {
const header = { alg: keyToJws(key), kid };
const payload = clientAssertion(as, client);
modifyAssertion?.(header, payload);
return jwt(header, payload, key);
}
function assertAs(as) {
if (typeof as !== 'object' || as === null) {
throw new TypeError('"as" must be an object');
}
if (!validateString(as.issuer)) {
throw new TypeError('"as.issuer" property must be a non-empty string');
}
return true;
}
function assertClient(client) {
if (typeof client !== 'object' || client === null) {
throw new TypeError('"client" must be an object');
}
if (!validateString(client.client_id)) {
throw new TypeError('"client.client_id" property must be a non-empty string');
}
return true;
}
function assertClientSecret(clientSecret) {
if (!validateString(clientSecret)) {
throw new TypeError('"client.client_secret" property must be a non-empty string');
}
return clientSecret;
}
function assertNoClientPrivateKey(clientAuthMethod, clientPrivateKey) {
if (clientPrivateKey !== undefined) {
throw new TypeError(`"options.clientPrivateKey" property must not be provided when ${clientAuthMethod} client authentication method is used.`);
}
}
function assertNoClientSecret(clientAuthMethod, clientSecret) {
if (clientSecret !== undefined) {
throw new TypeError(`"client.client_secret" property must not be provided when ${clientAuthMethod} client authentication method is used.`);
}
}
async function clientAuthentication(as, client, body, headers, clientPrivateKey) {
body.delete('client_secret');
body.delete('client_assertion_type');
body.delete('client_assertion');
switch (client.token_endpoint_auth_method) {
case undefined:
case 'client_secret_basic': {
assertNoClientPrivateKey('client_secret_basic', clientPrivateKey);
headers.set('authorization', clientSecretBasic(client.client_id, assertClientSecret(client.client_secret)));
break;
}
case 'client_secret_post': {
assertNoClientPrivateKey('client_secret_post', clientPrivateKey);
body.set('client_id', client.client_id);
body.set('client_secret', assertClientSecret(client.client_secret));
break;
}
case 'private_key_jwt': {
assertNoClientSecret('private_key_jwt', client.client_secret);
if (clientPrivateKey === undefined) {
throw new TypeError('"options.clientPrivateKey" must be provided when "client.token_endpoint_auth_method" is "private_key_jwt"');
}
const { key, kid, modifyAssertion } = getKeyAndKid(clientPrivateKey);
if (!isPrivateKey(key)) {
throw new TypeError('"options.clientPrivateKey.key" must be a private CryptoKey');
}
body.set('client_id', client.client_id);
body.set('client_assertion_type', 'urn:ietf:params:oauth:client-assertion-type:jwt-bearer');
body.set('client_assertion', await privateKeyJwt(as, client, key, kid, modifyAssertion));
break;
}
case 'tls_client_auth':
case 'self_signed_tls_client_auth':
case 'none': {
assertNoClientSecret(client.token_endpoint_auth_method, client.client_secret);
assertNoClientPrivateKey(client.token_endpoint_auth_method, clientPrivateKey);
body.set('client_id', client.client_id);
break;
}
default:
throw new UnsupportedOperationError('unsupported client token_endpoint_auth_method');
}
}
async function jwt(header, payload, key) {
if (!key.usages.includes('sign')) {
throw new TypeError('CryptoKey instances used for signing assertions must include "sign" in their "usages"');
}
const input = `${b64u(buf(JSON.stringify(header)))}.${b64u(buf(JSON.stringify(payload)))}`;
const signature = b64u(await crypto.subtle.sign(keyToSubtle(key), key, buf(input)));
return `${input}.${signature}`;
}
export async function issueRequestObject(as, client, parameters, privateKey) {
assertAs(as);
assertClient(client);
parameters = new URLSearchParams(parameters);
const { key, kid, modifyAssertion } = getKeyAndKid(privateKey);
if (!isPrivateKey(key)) {
throw new TypeError('"privateKey.key" must be a private CryptoKey');
}
parameters.set('client_id', client.client_id);
const now = epochTime() + getClockSkew(client);
const claims = {
...Object.fromEntries(parameters.entries()),
jti: randomBytes(),
aud: as.issuer,
exp: now + 60,
iat: now,
nbf: now,
iss: client.client_id,
};
let resource;
if (parameters.has('resource') &&
(resource = parameters.getAll('resource')) &&
resource.length > 1) {
claims.resource = resource;
}
{
let value = parameters.get('max_age');
if (value !== null) {
claims.max_age = parseInt(value, 10);
if (!Number.isFinite(claims.max_age)) {
throw new OPE('"max_age" parameter must be a number');
}
}
}
{
let value = parameters.get('claims');
if (value !== null) {
try {
claims.claims = JSON.parse(value);
}
catch (cause) {
throw new OPE('failed to parse the "claims" parameter as JSON', { cause });
}
if (!isJsonObject(claims.claims)) {
throw new OPE('"claims" parameter must be a JSON with a top level object');
}
}
}
{
let value = parameters.get('authorization_details');
if (value !== null) {
try {
claims.authorization_details = JSON.parse(value);
}
catch (cause) {
throw new OPE('failed to parse the "authorization_details" parameter as JSON', { cause });
}
if (!Array.isArray(claims.authorization_details)) {
throw new OPE('"authorization_details" parameter must be a JSON with a top level array');
}
}
}
const header = {
alg: keyToJws(key),
typ: 'oauth-authz-req+jwt',
kid,
};
modifyAssertion?.(header, claims);
return jwt(header, claims, key);
}
async function dpopProofJwt(headers, options, url, htm, clockSkew, accessToken) {
const { privateKey, publicKey, nonce = dpopNonces.get(url.origin) } = options;
if (!isPrivateKey(privateKey)) {
throw new TypeError('"DPoP.privateKey" must be a private CryptoKey');
}
if (!isPublicKey(publicKey)) {
throw new TypeError('"DPoP.publicKey" must be a public CryptoKey');
}
if (nonce !== undefined && !validateString(nonce)) {
throw new TypeError('"DPoP.nonce" must be a non-empty string or undefined');
}
if (!publicKey.extractable) {
throw new TypeError('"DPoP.publicKey.extractable" must be true');
}
const now = epochTime() + clockSkew;
const header = {
alg: keyToJws(privateKey),
typ: 'dpop+jwt',
jwk: await publicJwk(publicKey),
};
const payload = {
iat: now,
jti: randomBytes(),
htm,
nonce,
htu: `${url.origin}${url.pathname}`,
ath: accessToken ? b64u(await crypto.subtle.digest('SHA-256', buf(accessToken))) : undefined,
};
options[modifyAssertion]?.(header, payload);
headers.set('dpop', await jwt(header, payload, privateKey));
}
let jwkCache;
async function getSetPublicJwkCache(key) {
const { kty, e, n, x, y, crv } = await crypto.subtle.exportKey('jwk', key);
const jwk = { kty, e, n, x, y, crv };
jwkCache.set(key, jwk);
return jwk;
}
async function publicJwk(key) {
jwkCache || (jwkCache = new WeakMap());
return jwkCache.get(key) || getSetPublicJwkCache(key);
}
function validateEndpoint(value, endpoint, useMtlsAlias) {
if (typeof value !== 'string') {
if (useMtlsAlias) {
throw new TypeError(`"as.mtls_endpoint_aliases.${endpoint}" must be a string`);
}
throw new TypeError(`"as.${endpoint}" must be a string`);
}
return new URL(value);
}
function resolveEndpoint(as, endpoint, useMtlsAlias = false) {
if (useMtlsAlias && as.mtls_endpoint_aliases && endpoint in as.mtls_endpoint_aliases) {
return validateEndpoint(as.mtls_endpoint_aliases[endpoint], endpoint, useMtlsAlias);
}
return validateEndpoint(as[endpoint], endpoint, useMtlsAlias);
}
function alias(client, options) {
if (client.use_mtls_endpoint_aliases || options?.[useMtlsAlias]) {
return true;
}
return false;
}
export async function pushedAuthorizationRequest(as, client, parameters, options) {
assertAs(as);
assertClient(client);
const url = resolveEndpoint(as, 'pushed_authorization_request_endpoint', alias(client, options));
const body = new URLSearchParams(parameters);
body.set('client_id', client.client_id);
const headers = prepareHeaders(options?.headers);
headers.set('accept', 'application/json');
if (options?.DPoP !== undefined) {
await dpopProofJwt(headers, options.DPoP, url, 'POST', getClockSkew(client));
}
return authenticatedRequest(as, client, 'POST', url, body, headers, options);
}
export function isOAuth2Error(input) {
const value = input;
if (typeof value !== 'object' || Array.isArray(value) || value === null) {
return false;
}
return value.error !== undefined;
}
function unquote(value) {
if (value.length >= 2 && value[0] === '"' && value[value.length - 1] === '"') {
return value.slice(1, -1);
}
return value;
}
const SPLIT_REGEXP = /((?:,|, )?[0-9a-zA-Z!#$%&'*+-.^_`|~]+=)/;
const SCHEMES_REGEXP = /(?:^|, ?)([0-9a-zA-Z!#$%&'*+\-.^_`|~]+)(?=$|[ ,])/g;
function wwwAuth(scheme, params) {
const arr = params.split(SPLIT_REGEXP).slice(1);
if (!arr.length) {
return { scheme: scheme.toLowerCase(), parameters: {} };
}
arr[arr.length - 1] = arr[arr.length - 1].replace(/,$/, '');
const parameters = {};
for (let i = 1; i < arr.length; i += 2) {
const idx = i;
if (arr[idx][0] === '"') {
while (arr[idx].slice(-1) !== '"' && ++i < arr.length) {
arr[idx] += arr[i];
}
}
const key = arr[idx - 1].replace(/^(?:, ?)|=$/g, '').toLowerCase();
parameters[key] = unquote(arr[idx]);
}
return {
scheme: scheme.toLowerCase(),
parameters,
};
}
export function parseWwwAuthenticateChallenges(response) {
if (!looseInstanceOf(response, Response)) {
throw new TypeError('"response" must be an instance of Response');
}
const header = response.headers.get('www-authenticate');
if (header === null) {
return undefined;
}
const result = [];
for (const { 1: scheme, index } of header.matchAll(SCHEMES_REGEXP)) {
result.push([scheme, index]);
}
if (!result.length) {
return undefined;
}
const challenges = result.map(([scheme, indexOf], i, others) => {
const next = others[i + 1];
let parameters;
if (next) {
parameters = header.slice(indexOf, next[1]);
}
else {
parameters = header.slice(indexOf);
}
return wwwAuth(scheme, parameters);
});
return challenges;
}
export async function processPushedAuthorizationResponse(as, client, response) {
assertAs(as);
assertClient(client);
if (!looseInstanceOf(response, Response)) {
throw new TypeError('"response" must be an instance of Response');
}
if (response.status !== 201) {
let err;
if ((err = await handleOAuthBodyError(response))) {
return err;
}
throw new OPE('"response" is not a conform Pushed Authorization Request Endpoint response');
}
assertReadableResponse(response);
let json;
try {
json = await response.json();
}
catch (cause) {
throw new OPE('failed to parse "response" body as JSON', { cause });
}
if (!isJsonObject(json)) {
throw new OPE('"response" body must be a top level object');
}
if (!validateString(json.request_uri)) {
throw new OPE('"response" body "request_uri" property must be a non-empty string');
}
if (typeof json.expires_in !== 'number' || json.expires_in <= 0) {
throw new OPE('"response" body "expires_in" property must be a positive number');
}
return json;
}
export async function protectedResourceRequest(accessToken, method, url, headers, body, options) {
if (!validateString(accessToken)) {
throw new TypeError('"accessToken" must be a non-empty string');
}
if (!(url instanceof URL)) {
throw new TypeError('"url" must be an instance of URL');
}
headers = prepareHeaders(headers);
if (options?.DPoP === undefined) {
headers.set('authorization', `Bearer ${accessToken}`);
}
else {
await dpopProofJwt(headers, options.DPoP, url, method.toUpperCase(), getClockSkew({ [clockSkew]: options?.[clockSkew] }), accessToken);
headers.set('authorization', `DPoP ${accessToken}`);
}
return (options?.[customFetch] || fetch)(url.href, {
body,
headers: Object.fromEntries(headers.entries()),
method,
redirect: 'manual',
signal: options?.signal ? signal(options.signal) : null,
}).then(processDpopNonce);
}
export async function userInfoRequest(as, client, accessToken, options) {
assertAs(as);
assertClient(client);
const url = resolveEndpoint(as, 'userinfo_endpoint', alias(client, options));
const headers = prepareHeaders(options?.headers);
if (client.userinfo_signed_response_alg) {
headers.set('accept', 'application/jwt');
}
else {
headers.set('accept', 'application/json');
headers.append('accept', 'application/jwt');
}
return protectedResourceRequest(accessToken, 'GET', url, headers, null, {
...options,
[clockSkew]: getClockSkew(client),
});
}
let jwksMap;
function setJwksCache(as, jwks, uat, cache) {
jwksMap || (jwksMap = new WeakMap());
jwksMap.set(as, {
jwks,
uat,
get age() {
return epochTime() - this.uat;
},
});
if (cache) {
Object.assign(cache, { jwks: structuredClone(jwks), uat });
}
}
function isFreshJwksCache(input) {
if (typeof input !== 'object' || input === null) {
return false;
}
if (!('uat' in input) || typeof input.uat !== 'number' || epochTime() - input.uat >= 300) {
return false;
}
if (!('jwks' in input) ||
!isJsonObject(input.jwks) ||
!Array.isArray(input.jwks.keys) ||
!Array.prototype.every.call(input.jwks.keys, isJsonObject)) {
return false;
}
return true;
}
function clearJwksCache(as, cache) {
jwksMap?.delete(as);
delete cache?.jwks;
delete cache?.uat;
}
async function getPublicSigKeyFromIssuerJwksUri(as, options, header) {
const { alg, kid } = header;
checkSupportedJwsAlg(alg);
if (!jwksMap?.has(as) && isFreshJwksCache(options?.[jwksCache])) {
setJwksCache(as, options?.[jwksCache].jwks, options?.[jwksCache].uat);
}
let jwks;
let age;
if (jwksMap?.has(as)) {
;
({ jwks, age } = jwksMap.get(as));
if (age >= 300) {
clearJwksCache(as, options?.[jwksCache]);
return getPublicSigKeyFromIssuerJwksUri(as, options, header);
}
}
else {
jwks = await jwksRequest(as, options).then(processJwksResponse);
age = 0;
setJwksCache(as, jwks, epochTime(), options?.[jwksCache]);
}
let kty;
switch (alg.slice(0, 2)) {
case 'RS':
case 'PS':
kty = 'RSA';
break;
case 'ES':
kty = 'EC';
break;
case 'Ed':
kty = 'OKP';
break;
default:
throw new UnsupportedOperationError();
}
const candidates = jwks.keys.filter((jwk) => {
if (jwk.kty !== kty) {
return false;
}
if (kid !== undefined && kid !== jwk.kid) {
return false;
}
if (jwk.alg !== undefined && alg !== jwk.alg) {
return false;
}
if (jwk.use !== undefined && jwk.use !== 'sig') {
return false;
}
if (jwk.key_ops?.includes('verify') === false) {
return false;
}
switch (true) {
case alg === 'ES256' && jwk.crv !== 'P-256':
case alg === 'ES384' && jwk.crv !== 'P-384':
case alg === 'ES512' && jwk.crv !== 'P-521':
case alg === 'EdDSA' && !(jwk.crv === 'Ed25519' || jwk.crv === 'Ed448'):
return false;
}
return true;
});
const { 0: jwk, length } = candidates;
if (!length) {
if (age >= 60) {
clearJwksCache(as, options?.[jwksCache]);
return getPublicSigKeyFromIssuerJwksUri(as, options, header);
}
throw new OPE('error when selecting a JWT verification key, no applicable keys found');
}
if (length !== 1) {
throw new OPE('error when selecting a JWT verification key, multiple applicable keys found, a "kid" JWT Header Parameter is required');
}
const key = await importJwk(alg, jwk);
if (key.type !== 'public') {
throw new OPE('jwks_uri must only contain public keys');
}
return key;
}
export const skipSubjectCheck = Symbol();
function getContentType(response) {
return response.headers.get('content-type')?.split(';')[0];
}
export async function processUserInfoResponse(as, client, expectedSubject, response) {
assertAs(as);
assertClient(client);
if (!looseInstanceOf(response, Response)) {
throw new TypeError('"response" must be an instance of Response');
}
if (response.status !== 200) {
throw new OPE('"response" is not a conform UserInfo Endpoint response');
}
let json;
if (getContentType(response) === 'application/jwt') {
assertReadableResponse(response);
const { claims, jwt } = await validateJwt(await response.text(), checkSigningAlgorithm.bind(undefined, client.userinfo_signed_response_alg, as.userinfo_signing_alg_values_supported), noSignatureCheck, getClockSkew(client), getClockTolerance(client), client[jweDecrypt])
.then(validateOptionalAudience.bind(undefined, client.client_id))
.then(validateOptionalIssuer.bind(undefined, as.issuer));
jwtResponseBodies.set(response, jwt);
json = claims;
}
else {
if (client.userinfo_signed_response_alg) {
throw new OPE('JWT UserInfo Response expected');
}
assertReadableResponse(response);
try {
json = await response.json();
}
catch (cause) {
throw new OPE('failed to parse "response" body as JSON', { cause });
}
}
if (!isJsonObject(json)) {
throw new OPE('"response" body must be a top level object');
}
if (!validateString(json.sub)) {
throw new OPE('"response" body "sub" property must be a non-empty string');
}
switch (expectedSubject) {
case skipSubjectCheck:
break;
default:
if (!validateString(expectedSubject)) {
throw new OPE('"expectedSubject" must be a non-empty string');
}
if (json.sub !== expectedSubject) {
throw new OPE('unexpected "response" body "sub" value');
}
}
return json;
}
async function authenticatedRequest(as, client, method, url, body, headers, options) {
await clientAuthentication(as, client, body, headers, options?.clientPrivateKey);
headers.set('content-type', 'application/x-www-form-urlencoded;charset=UTF-8');
return (options?.[customFetch] || fetch)(url.href, {
body,
headers: Object.fromEntries(headers.entries()),
method,
redirect: 'manual',
signal: options?.signal ? signal(options.signal) : null,
}).then(processDpopNonce);
}
async function tokenEndpointRequest(as, client, grantType, parameters, options) {
const url = resolveEndpoint(as, 'token_endpoint', alias(client, options));
parameters.set('grant_type', grantType);
const headers = prepareHeaders(options?.headers);
headers.set('accept', 'application/json');
if (options?.DPoP !== undefined) {
await dpopProofJwt(headers, options.DPoP, url, 'POST', getClockSkew(client));
}
return authenticatedRequest(as, client, 'POST', url, parameters, headers, options);
}
export async function refreshTokenGrantRequest(as, client, refreshToken, options) {
assertAs(as);
assertClient(client);
if (!validateString(refreshToken)) {
throw new TypeError('"refreshToken" must be a non-empty string');
}
const parameters = new URLSearchParams(options?.additionalParameters);
parameters.set('refresh_token', refreshToken);
return tokenEndpointRequest(as, client, 'refresh_token', parameters, options);
}
const idTokenClaims = new WeakMap();
const jwtResponseBodies = new WeakMap();
export function getValidatedIdTokenClaims(ref) {
if (!ref.id_token) {
return undefined;
}
const claims = idTokenClaims.get(ref);
if (!claims) {
throw new TypeError('"ref" was already garbage collected or did not resolve from the proper sources');
}
return claims[0];
}
export async function validateIdTokenSignature(as, ref, options) {
assertAs(as);
if (!idTokenClaims.has(ref)) {
throw new OPE('"ref" does not contain an ID Token to verify the signature of');
}
const { 0: protectedHeader, 1: payload, 2: encodedSignature, } = idTokenClaims.get(ref)[1].split('.');
const header = JSON.parse(buf(b64u(protectedHeader)));
if (header.alg.startsWith('HS')) {
throw new UnsupportedOperationError();
}
let key;
key = await getPublicSigKeyFromIssuerJwksUri(as, options, header);
await validateJwsSignature(protectedHeader, payload, key, b64u(encodedSignature));
}
async function validateJwtResponseSignature(as, ref, options) {
assertAs(as);
if (!jwtResponseBodies.has(ref)) {
throw new OPE('"ref" does not contain a processed JWT Response to verify the signature of');
}
const { 0: protectedHeader, 1: payload, 2: encodedSignature, } = jwtResponseBodies.get(ref).split('.');
const header = JSON.parse(buf(b64u(protectedHeader)));
if (header.alg.startsWith('HS')) {
throw new UnsupportedOperationError();
}
let key;
key = await getPublicSigKeyFromIssuerJwksUri(as, options, header);
await validateJwsSignature(protectedHeader, payload, key, b64u(encodedSignature));
}
export function validateJwtUserInfoSignature(as, ref, options) {
return validateJwtResponseSignature(as, ref, options);
}
export function validateJwtIntrospectionSignature(as, ref, options) {
return validateJwtResponseSignature(as, ref, options);
}
async function processGenericAccessTokenResponse(as, client, response, ignoreIdToken = false, ignoreRefreshToken = false) {
assertAs(as);
assertClient(client);
if (!looseInstanceOf(response, Response)) {
throw new TypeError('"response" must be an instance of Response');
}
if (response.status !== 200) {
let err;
if ((err = await handleOAuthBodyError(response))) {
return err;