-
-
Notifications
You must be signed in to change notification settings - Fork 392
/
client.js
1531 lines (1310 loc) · 41.1 KB
/
client.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
/* eslint-disable max-classes-per-file */
const { inspect } = require('util');
const stdhttp = require('http');
const crypto = require('crypto');
const { strict: assert } = require('assert');
const querystring = require('querystring');
const url = require('url');
const { ParseError } = require('got');
const jose = require('jose');
const base64url = require('base64url');
const defaultsDeep = require('lodash/defaultsDeep');
const defaults = require('lodash/defaults');
const merge = require('lodash/merge');
const isPlainObject = require('lodash/isPlainObject');
const tokenHash = require('oidc-token-hash');
const { assertSigningAlgValuesSupport, assertIssuerConfiguration } = require('./helpers/assert');
const pick = require('./helpers/pick');
const processResponse = require('./helpers/process_response');
const TokenSet = require('./token_set');
const { OPError, RPError } = require('./errors');
const now = require('./helpers/unix_timestamp');
const { random } = require('./helpers/generators');
const request = require('./helpers/request');
const {
CALLBACK_PROPERTIES, CLIENT_DEFAULTS, JWT_CONTENT, CLOCK_TOLERANCE,
} = require('./helpers/consts');
const issuerRegistry = require('./issuer_registry');
const instance = require('./helpers/weak_cache');
const { authenticatedPost, resolveResponseType, resolveRedirectUri } = require('./helpers/client');
const DeviceFlowHandle = require('./device_flow_handle');
function pickCb(input) {
return pick(input, ...CALLBACK_PROPERTIES);
}
function authorizationHeaderValue(token, tokenType = 'Bearer') {
return `${tokenType} ${token}`;
}
function cleanUpClaims(claims) {
if (Object.keys(claims._claim_names).length === 0) {
delete claims._claim_names;
}
if (Object.keys(claims._claim_sources).length === 0) {
delete claims._claim_sources;
}
}
function assignClaim(target, source, sourceName, throwOnMissing = true) {
return ([claim, inSource]) => {
if (inSource === sourceName) {
if (throwOnMissing && source[claim] === undefined) {
throw new RPError(`expected claim "${claim}" in "${sourceName}"`);
} else if (source[claim] !== undefined) {
target[claim] = source[claim];
}
delete target._claim_names[claim];
}
};
}
function verifyPresence(payload, jwt, prop) {
if (payload[prop] === undefined) {
throw new RPError({
message: `missing required JWT property ${prop}`,
jwt,
});
}
}
function authorizationParams(params) {
const authParams = {
client_id: this.client_id,
scope: 'openid',
response_type: resolveResponseType.call(this),
redirect_uri: resolveRedirectUri.call(this),
...params,
};
Object.entries(authParams).forEach(([key, value]) => {
if (value === null || value === undefined) {
delete authParams[key];
} else if (key === 'claims' && typeof value === 'object') {
authParams[key] = JSON.stringify(value);
} else if (key === 'resource' && Array.isArray(value)) {
authParams[key] = value;
} else if (typeof value !== 'string') {
authParams[key] = String(value);
}
});
return authParams;
}
async function claimJWT(label, jwt) {
try {
const { header, payload } = jose.JWT.decode(jwt, { complete: true });
const { iss } = payload;
if (header.alg === 'none') {
return payload;
}
let key;
if (!iss || iss === this.issuer.issuer) {
key = await this.issuer.queryKeyStore(header);
} else if (issuerRegistry.has(iss)) {
key = await issuerRegistry.get(iss).queryKeyStore(header);
} else {
const discovered = await this.issuer.constructor.discover(iss);
key = await discovered.queryKeyStore(header);
}
return jose.JWT.verify(jwt, key);
} catch (err) {
if (err instanceof RPError || err instanceof OPError || err.name === 'AggregateError') {
throw err;
} else {
throw new RPError({
printf: ['failed to validate the %s JWT (%s: %s)', label, err.name, err.message],
jwt,
});
}
}
}
function getKeystore(jwks) {
const keystore = jose.JWKS.asKeyStore(jwks);
if (keystore.all().some((key) => key.type !== 'private')) {
throw new TypeError('jwks must only contain private keys');
}
return keystore;
}
// if an OP doesnt support client_secret_basic but supports client_secret_post, use it instead
// this is in place to take care of most common pitfalls when first using discovered Issuers without
// the support for default values defined by Discovery 1.0
function checkBasicSupport(client, metadata, properties) {
try {
const supported = client.issuer.token_endpoint_auth_methods_supported;
if (!supported.includes(properties.token_endpoint_auth_method)) {
if (supported.includes('client_secret_post')) {
properties.token_endpoint_auth_method = 'client_secret_post';
}
}
} catch (err) {}
}
function handleCommonMistakes(client, metadata, properties) {
if (!metadata.token_endpoint_auth_method) { // if no explicit value was provided
checkBasicSupport(client, metadata, properties);
}
// :fp: c'mon people... RTFM
if (metadata.redirect_uri) {
if (metadata.redirect_uris) {
throw new TypeError('provide a redirect_uri or redirect_uris, not both');
}
properties.redirect_uris = [metadata.redirect_uri];
delete properties.redirect_uri;
}
if (metadata.response_type) {
if (metadata.response_types) {
throw new TypeError('provide a response_type or response_types, not both');
}
properties.response_types = [metadata.response_type];
delete properties.response_type;
}
}
function getDefaultsForEndpoint(endpoint, issuer, properties) {
if (!issuer[`${endpoint}_endpoint`]) return;
const tokenEndpointAuthMethod = properties.token_endpoint_auth_method;
const tokenEndpointAuthSigningAlg = properties.token_endpoint_auth_signing_alg;
const eam = `${endpoint}_endpoint_auth_method`;
const easa = `${endpoint}_endpoint_auth_signing_alg`;
if (properties[eam] === undefined && properties[easa] === undefined) {
if (tokenEndpointAuthMethod !== undefined) {
properties[eam] = tokenEndpointAuthMethod;
}
if (tokenEndpointAuthSigningAlg !== undefined) {
properties[easa] = tokenEndpointAuthSigningAlg;
}
}
}
class BaseClient {}
module.exports = (issuer, aadIssValidation = false) => class Client extends BaseClient {
/**
* @name constructor
* @api public
*/
constructor(metadata = {}, jwks) {
super();
if (typeof metadata.client_id !== 'string' || !metadata.client_id) {
throw new TypeError('client_id is required');
}
const properties = { ...CLIENT_DEFAULTS, ...metadata };
handleCommonMistakes(this, metadata, properties);
assertSigningAlgValuesSupport('token', this.issuer, properties);
['introspection', 'revocation'].forEach((endpoint) => {
getDefaultsForEndpoint(endpoint, this.issuer, properties);
assertSigningAlgValuesSupport(endpoint, this.issuer, properties);
});
Object.entries(properties).forEach(([key, value]) => {
instance(this).get('metadata').set(key, value);
if (!this[key]) {
Object.defineProperty(this, key, {
get() { return instance(this).get('metadata').get(key); },
enumerable: true,
});
}
});
if (jwks !== undefined) {
const keystore = getKeystore.call(this, jwks);
instance(this).set('keystore', keystore);
}
this[CLOCK_TOLERANCE] = 0;
}
/**
* @name authorizationUrl
* @api public
*/
authorizationUrl(params = {}) {
if (!isPlainObject(params)) {
throw new TypeError('params must be a plain object');
}
assertIssuerConfiguration(this.issuer, 'authorization_endpoint');
const target = url.parse(this.issuer.authorization_endpoint, true);
target.search = null;
target.query = {
...target.query,
...authorizationParams.call(this, params),
};
return url.format(target);
}
/**
* @name authorizationPost
* @api public
*/
authorizationPost(params = {}) {
if (!isPlainObject(params)) {
throw new TypeError('params must be a plain object');
}
const inputs = authorizationParams.call(this, params);
const formInputs = Object.keys(inputs)
.map((name) => `<input type="hidden" name="${name}" value="${inputs[name]}"/>`).join('\n');
return `<!DOCTYPE html>
<head>
<title>Requesting Authorization</title>
</head>
<body onload="javascript:document.forms[0].submit()">
<form method="post" action="${this.issuer.authorization_endpoint}">
${formInputs}
</form>
</body>
</html>`;
}
/**
* @name endSessionUrl
* @api public
*/
endSessionUrl(params = {}) {
assertIssuerConfiguration(this.issuer, 'end_session_endpoint');
const {
0: postLogout,
length,
} = this.post_logout_redirect_uris || [];
const {
post_logout_redirect_uri = length === 1 ? postLogout : undefined,
} = params;
let hint = params.id_token_hint;
if (hint instanceof TokenSet) {
if (!hint.id_token) {
throw new TypeError('id_token not present in TokenSet');
}
hint = hint.id_token;
}
const target = url.parse(this.issuer.end_session_endpoint, true);
target.search = null;
target.query = {
...params,
...target.query,
...{
post_logout_redirect_uri,
id_token_hint: hint,
},
};
Object.entries(target.query).forEach(([key, value]) => {
if (value === null || value === undefined) {
delete target.query[key];
}
});
return url.format(target);
}
/**
* @name callbackParams
* @api public
*/
callbackParams(input) { // eslint-disable-line class-methods-use-this
const isIncomingMessage = input instanceof stdhttp.IncomingMessage
|| (input && input.method && input.url);
const isString = typeof input === 'string';
if (!isString && !isIncomingMessage) {
throw new TypeError('#callbackParams only accepts string urls, http.IncomingMessage or a lookalike');
}
if (isIncomingMessage) {
switch (input.method) {
case 'GET':
return pickCb(url.parse(input.url, true).query);
case 'POST':
if (input.body === undefined) {
throw new TypeError('incoming message body missing, include a body parser prior to this method call');
}
switch (typeof input.body) {
case 'object':
case 'string':
if (Buffer.isBuffer(input.body)) {
return pickCb(querystring.parse(input.body.toString('utf-8')));
}
if (typeof input.body === 'string') {
return pickCb(querystring.parse(input.body));
}
return pickCb(input.body);
default:
throw new TypeError('invalid IncomingMessage body object');
}
default:
throw new TypeError('invalid IncomingMessage method');
}
} else {
return pickCb(url.parse(input, true).query);
}
}
/**
* @name callback
* @api public
*/
async callback(
redirectUri,
parameters,
checks = {},
{ exchangeBody, clientAssertionPayload } = {},
) {
let params = pickCb(parameters);
if (checks.jarm && !('response' in parameters)) {
throw new RPError({
message: 'expected a JARM response',
checks,
params,
});
} else if ('response' in parameters) {
const decrypted = await this.decryptJARM(params.response);
params = await this.validateJARM(decrypted);
}
if (this.default_max_age && !checks.max_age) {
checks.max_age = this.default_max_age;
}
if (params.state && !checks.state) {
throw new TypeError('checks.state argument is missing');
}
if (!params.state && checks.state) {
throw new RPError({
message: 'state missing from the response',
checks,
params,
});
}
if (checks.state !== params.state) {
throw new RPError({
printf: ['state mismatch, expected %s, got: %s', checks.state, params.state],
checks,
params,
});
}
if (params.error) {
throw new OPError(params);
}
const RESPONSE_TYPE_REQUIRED_PARAMS = {
code: ['code'],
id_token: ['id_token'],
token: ['access_token', 'token_type'],
};
if (checks.response_type) {
for (const type of checks.response_type.split(' ')) { // eslint-disable-line no-restricted-syntax
if (type === 'none') {
if (params.code || params.id_token || params.access_token) {
throw new RPError({
message: 'unexpected params encountered for "none" response',
checks,
params,
});
}
} else {
for (const param of RESPONSE_TYPE_REQUIRED_PARAMS[type]) { // eslint-disable-line no-restricted-syntax, max-len
if (!params[param]) {
throw new RPError({
message: `${param} missing from response`,
checks,
params,
});
}
}
}
}
}
if (params.id_token) {
const tokenset = new TokenSet(params);
await this.decryptIdToken(tokenset);
await this.validateIdToken(tokenset, checks.nonce, 'authorization', checks.max_age, checks.state);
if (!params.code) {
return tokenset;
}
}
if (params.code) {
const tokenset = await this.grant({
...exchangeBody,
grant_type: 'authorization_code',
code: params.code,
redirect_uri: redirectUri,
code_verifier: checks.code_verifier,
}, { clientAssertionPayload });
await this.decryptIdToken(tokenset);
await this.validateIdToken(tokenset, checks.nonce, 'token', checks.max_age);
if (params.session_state) {
tokenset.session_state = params.session_state;
}
return tokenset;
}
return new TokenSet(params);
}
/**
* @name oauthCallback
* @api public
*/
async oauthCallback(
redirectUri,
parameters,
checks = {},
{ exchangeBody, clientAssertionPayload } = {},
) {
let params = pickCb(parameters);
if (checks.jarm && !('response' in parameters)) {
throw new RPError({
message: 'expected a JARM response',
checks,
params,
});
} else if ('response' in parameters) {
const decrypted = await this.decryptJARM(params.response);
params = await this.validateJARM(decrypted);
}
if (params.state && !checks.state) {
throw new TypeError('checks.state argument is missing');
}
if (!params.state && checks.state) {
throw new RPError({
message: 'state missing from the response',
checks,
params,
});
}
if (checks.state !== params.state) {
throw new RPError({
printf: ['state mismatch, expected %s, got: %s', checks.state, params.state],
checks,
params,
});
}
if (params.error) {
throw new OPError(params);
}
const RESPONSE_TYPE_REQUIRED_PARAMS = {
code: ['code'],
token: ['access_token', 'token_type'],
};
if (checks.response_type) {
for (const type of checks.response_type.split(' ')) { // eslint-disable-line no-restricted-syntax
if (type === 'none') {
if (params.code || params.id_token || params.access_token) {
throw new RPError({
message: 'unexpected params encountered for "none" response',
checks,
params,
});
}
}
if (RESPONSE_TYPE_REQUIRED_PARAMS[type]) {
for (const param of RESPONSE_TYPE_REQUIRED_PARAMS[type]) { // eslint-disable-line no-restricted-syntax, max-len
if (!params[param]) {
throw new RPError({
message: `${param} missing from response`,
checks,
params,
});
}
}
}
}
}
if (params.code) {
return this.grant({
...exchangeBody,
grant_type: 'authorization_code',
code: params.code,
redirect_uri: redirectUri,
code_verifier: checks.code_verifier,
}, { clientAssertionPayload });
}
return new TokenSet(params);
}
/**
* @name decryptIdToken
* @api private
*/
async decryptIdToken(token) {
if (!this.id_token_encrypted_response_alg) {
return token;
}
let idToken = token;
if (idToken instanceof TokenSet) {
if (!idToken.id_token) {
throw new TypeError('id_token not present in TokenSet');
}
idToken = idToken.id_token;
}
const expectedAlg = this.id_token_encrypted_response_alg;
const expectedEnc = this.id_token_encrypted_response_enc;
const result = await this.decryptJWE(idToken, expectedAlg, expectedEnc);
if (token instanceof TokenSet) {
token.id_token = result;
return token;
}
return result;
}
async validateJWTUserinfo(body) {
const expectedAlg = this.userinfo_signed_response_alg;
return this.validateJWT(body, expectedAlg, []);
}
/**
* @name decryptJARM
* @api private
*/
async decryptJARM(response) {
if (!this.authorization_encrypted_response_alg && !this.authorization_encrypted_response_enc) {
return response;
}
const expectedAlg = this.authorization_encrypted_response_alg;
const expectedEnc = this.authorization_encrypted_response_enc;
return this.decryptJWE(response, expectedAlg, expectedEnc);
}
/**
* @name validateJARM
* @api private
*/
async validateJARM(response) {
const expectedAlg = this.authorization_signed_response_alg;
const { payload } = await this.validateJWT(response, expectedAlg, ['iss', 'exp', 'aud']);
return pickCb(payload);
}
/**
* @name decryptJWTUserinfo
* @api private
*/
async decryptJWTUserinfo(body) {
if (!this.userinfo_encrypted_response_alg) {
return body;
}
const expectedAlg = this.userinfo_encrypted_response_alg;
const expectedEnc = this.userinfo_encrypted_response_enc;
return this.decryptJWE(body, expectedAlg, expectedEnc);
}
/**
* @name decryptJWE
* @api private
*/
async decryptJWE(jwe, expectedAlg, expectedEnc) {
const header = JSON.parse(base64url.decode(jwe.split('.')[0]));
if (header.alg !== expectedAlg) {
throw new RPError({
printf: ['unexpected JWE alg received, expected %s, got: %s', expectedAlg, header.alg],
jwt: jwe,
});
}
if (header.enc !== expectedEnc) {
throw new RPError({
printf: ['unexpected JWE enc received, expected %s, got: %s', expectedEnc, header.enc],
jwt: jwe,
});
}
let keyOrStore;
if (expectedAlg.match(/^(?:RSA|ECDH)/)) {
keyOrStore = instance(this).get('keystore');
} else {
keyOrStore = await this.joseSecret(expectedAlg === 'dir' ? expectedEnc : expectedAlg);
}
const payload = jose.JWE.decrypt(jwe, keyOrStore);
return payload.toString('utf8');
}
/**
* @name validateIdToken
* @api private
*/
async validateIdToken(tokenSet, nonce, returnedBy, maxAge, state) {
let idToken = tokenSet;
const expectedAlg = this.id_token_signed_response_alg;
const isTokenSet = idToken instanceof TokenSet;
if (isTokenSet) {
if (!idToken.id_token) {
throw new TypeError('id_token not present in TokenSet');
}
idToken = idToken.id_token;
}
idToken = String(idToken);
const timestamp = now();
const { protected: header, payload, key } = await this.validateJWT(idToken, expectedAlg);
if (maxAge || (maxAge !== null && this.require_auth_time)) {
if (!payload.auth_time) {
throw new RPError({
message: 'missing required JWT property auth_time',
jwt: idToken,
});
}
if (!Number.isInteger(payload.auth_time)) {
throw new RPError({
message: 'JWT auth_time claim must be a JSON number integer',
jwt: idToken,
});
}
}
if (maxAge && (payload.auth_time + maxAge < timestamp - this[CLOCK_TOLERANCE])) {
throw new RPError({
printf: ['too much time has elapsed since the last End-User authentication, max_age %i, auth_time: %i, now %i', maxAge, payload.auth_time, timestamp - this[CLOCK_TOLERANCE]],
jwt: idToken,
});
}
if (nonce !== null && (payload.nonce || nonce !== undefined) && payload.nonce !== nonce) {
throw new RPError({
printf: ['nonce mismatch, expected %s, got: %s', nonce, payload.nonce],
jwt: idToken,
});
}
if (returnedBy === 'authorization') {
if (!payload.at_hash && tokenSet.access_token) {
throw new RPError({
message: 'missing required property at_hash',
jwt: idToken,
});
}
if (!payload.c_hash && tokenSet.code) {
throw new RPError({
message: 'missing required property c_hash',
jwt: idToken,
});
}
const fapi = this.constructor.name === 'FAPIClient';
if (fapi) {
if (payload.iat < timestamp - 3600) {
throw new RPError({
printf: ['JWT issued too far in the past, now %i, iat %i', timestamp, payload.iat],
jwt: idToken,
});
}
if (!payload.s_hash && (tokenSet.state || state)) {
throw new RPError({
message: 'missing required property s_hash',
jwt: idToken,
});
}
}
if (payload.s_hash) {
if (!state) {
throw new TypeError('cannot verify s_hash, "checks.state" property not provided');
}
try {
tokenHash.validate({ claim: 's_hash', source: 'state' }, payload.s_hash, state, header.alg, key && key.crv);
} catch (err) {
throw new RPError({ message: err.message, jwt: idToken });
}
}
}
if (tokenSet.access_token && payload.at_hash !== undefined) {
try {
tokenHash.validate({ claim: 'at_hash', source: 'access_token' }, payload.at_hash, tokenSet.access_token, header.alg, key && key.crv);
} catch (err) {
throw new RPError({ message: err.message, jwt: idToken });
}
}
if (tokenSet.code && payload.c_hash !== undefined) {
try {
tokenHash.validate({ claim: 'c_hash', source: 'code' }, payload.c_hash, tokenSet.code, header.alg, key && key.crv);
} catch (err) {
throw new RPError({ message: err.message, jwt: idToken });
}
}
return tokenSet;
}
/**
* @name validateJWT
* @api private
*/
async validateJWT(jwt, expectedAlg, required = ['iss', 'sub', 'aud', 'exp', 'iat']) {
const isSelfIssued = this.issuer.issuer === 'https://self-issued.me';
const timestamp = now();
let header;
let payload;
try {
({ header, payload } = jose.JWT.decode(jwt, { complete: true }));
} catch (err) {
throw new RPError({
printf: ['failed to decode JWT (%s: %s)', err.name, err.message],
jwt,
});
}
if (header.alg !== expectedAlg) {
throw new RPError({
printf: ['unexpected JWT alg received, expected %s, got: %s', expectedAlg, header.alg],
jwt,
});
}
if (isSelfIssued) {
required = [...required, 'sub_jwk']; // eslint-disable-line no-param-reassign
}
required.forEach(verifyPresence.bind(undefined, payload, jwt));
if (payload.iss !== undefined) {
let expectedIss = this.issuer.issuer;
if (aadIssValidation) {
expectedIss = this.issuer.issuer.replace('{tenantid}', payload.tid);
}
if (payload.iss !== expectedIss) {
throw new RPError({
printf: ['unexpected iss value, expected %s, got: %s', expectedIss, payload.iss],
jwt,
});
}
}
if (payload.iat !== undefined) {
if (!Number.isInteger(payload.iat)) {
throw new RPError({
message: 'JWT iat claim must be a JSON number integer',
jwt,
});
}
}
if (payload.nbf !== undefined) {
if (!Number.isInteger(payload.nbf)) {
throw new RPError({
message: 'JWT nbf claim must be a JSON number integer',
jwt,
});
}
if (payload.nbf > timestamp + this[CLOCK_TOLERANCE]) {
throw new RPError({
printf: ['JWT not active yet, now %i, nbf %i', timestamp + this[CLOCK_TOLERANCE], payload.nbf],
jwt,
});
}
}
if (payload.exp !== undefined) {
if (!Number.isInteger(payload.exp)) {
throw new RPError({
message: 'JWT exp claim must be a JSON number integer',
jwt,
});
}
if (timestamp - this[CLOCK_TOLERANCE] >= payload.exp) {
throw new RPError({
printf: ['JWT expired, now %i, exp %i', timestamp - this[CLOCK_TOLERANCE], payload.exp],
jwt,
});
}
}
if (payload.aud !== undefined) {
if (Array.isArray(payload.aud)) {
if (payload.aud.length > 1 && !payload.azp) {
throw new RPError({
message: 'missing required JWT property azp',
jwt,
});
}
if (!payload.aud.includes(this.client_id)) {
throw new RPError({
printf: ['aud is missing the client_id, expected %s to be included in %j', this.client_id, payload.aud],
jwt,
});
}
} else if (payload.aud !== this.client_id) {
throw new RPError({
printf: ['aud mismatch, expected %s, got: %s', this.client_id, payload.aud],
jwt,
});
}
}
if (payload.azp !== undefined && payload.azp !== this.client_id) {
throw new RPError({
printf: ['azp must be the client_id, expected %s, got: %s', this.client_id, payload.azp],
jwt,
});
}
let key;
if (isSelfIssued) {
try {
assert(isPlainObject(payload.sub_jwk));
key = jose.JWK.asKey(payload.sub_jwk);
assert.equal(key.type, 'public');
} catch (err) {
throw new RPError({
message: 'failed to use sub_jwk claim as an asymmetric JSON Web Key',
jwt,
});
}
if (key.thumbprint !== payload.sub) {
throw new RPError({
message: 'failed to match the subject with sub_jwk',
jwt,
});
}
} else if (header.alg.startsWith('HS')) {
key = await this.joseSecret();
} else if (header.alg !== 'none') {
key = await this.issuer.queryKeyStore(header);
}
if (!key && header.alg === 'none') {
return { protected: header, payload };
}
try {
return jose.JWS.verify(jwt, key, { complete: true });
} catch (err) {
throw new RPError({
message: 'failed to validate JWT signature',
jwt,
});
}
}
/**
* @name refresh
* @api public
*/
async refresh(refreshToken, { exchangeBody, clientAssertionPayload } = {}) {
let token = refreshToken;
if (token instanceof TokenSet) {
if (!token.refresh_token) {
throw new TypeError('refresh_token not present in TokenSet');
}
token = token.refresh_token;
}
const tokenset = await this.grant({
...exchangeBody,
grant_type: 'refresh_token',
refresh_token: String(token),
}, { clientAssertionPayload });
if (tokenset.id_token) {
await this.decryptIdToken(tokenset);
await this.validateIdToken(tokenset, null, 'token', null);
}
return tokenset;
}
async resource(resourceUrl, accessToken, options) {
let token = accessToken;
const opts = merge({
verb: 'GET',
via: 'header',
}, options);
if (token instanceof TokenSet) {
if (!token.access_token) {
throw new TypeError('access_token not present in TokenSet');
}
opts.tokenType = opts.tokenType || token.token_type;
token = token.access_token;
}
const verb = String(opts.verb).toUpperCase();
let requestOpts;
switch (opts.via) {
case 'query':
if (verb !== 'GET') {