Repository navigation
Expand file tree
/
Copy pathoauth.ts
More file actions
1423 lines (1223 loc) · 42.4 KB
/
Copy pathoauth.ts
File metadata and controls
1423 lines (1223 loc) · 42.4 KB
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
/*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
import { decodeBase64 } from './buffer.js';
const WELL_KNOWN_ROUTE = '/.well-known';
export const AUTH_PROTECTED_RESOURCE_METADATA_DISCOVERY_PATH = `${WELL_KNOWN_ROUTE}/oauth-protected-resource`;
export const AUTH_SERVER_METADATA_DISCOVERY_PATH = `${WELL_KNOWN_ROUTE}/oauth-authorization-server`;
export const OPENID_CONNECT_DISCOVERY_PATH = `${WELL_KNOWN_ROUTE}/openid-configuration`;
export const AUTH_SCOPE_SEPARATOR = ' ';
/**
* RFC 8693 grant type for OAuth token exchange.
*/
export const GRANT_TYPE_TOKEN_EXCHANGE = 'urn:ietf:params:oauth:grant-type:token-exchange';
/**
* RFC 8693 token type for an OAuth 2.0 access token used as the `subject_token`
* during a token exchange.
*/
export const TOKEN_TYPE_ACCESS_TOKEN = 'urn:ietf:params:oauth:token-type:access_token';
/**
* Token type for an OpenID Connect ID Token. Used as the `subject_token_type` in
* the IdP-side token exchange that mints an ID-JAG.
*/
export const TOKEN_TYPE_ID_TOKEN = 'urn:ietf:params:oauth:token-type:id_token';
/**
* Token type for an Identity Assertion Authorization Grant (ID-JAG) used in
* Cross App Access (XAA) flows.
*/
export const TOKEN_TYPE_ID_JAG = 'urn:ietf:params:oauth:token-type:id-jag';
/**
* RFC 7523 grant type used to exchange a JWT assertion (e.g. an ID-JAG) for an
* access token at the resource's authorization server.
*/
export const GRANT_TYPE_JWT_BEARER = 'urn:ietf:params:oauth:grant-type:jwt-bearer';
/**
* Build the request body for the IdP-side token exchange that mints an ID-JAG
* for the requested audience. See draft-ietf-oauth-identity-assertion-authz-grant.
*
* @param clientId the requesting app's client_id at the IdP.
* @param clientSecret the requesting app's client_secret at the IdP, if applicable.
* Omit (or pass `undefined`) for public clients (`token_endpoint_auth_method=none`).
* @param idToken the OpenID Connect `id_token` previously issued by the IdP to
* the requesting app. Per the spec the subject token MUST be an ID Token
* (not an access token).
* @param audience the *authorization server* URL of the resource (the issuer
* that will redeem the ID-JAG). Required.
* @param resource the resource indicator (RFC 8707) — the URL of the actual
* protected resource (e.g. the MCP server URL). Optional but typically required
* in practice.
* @param scopes scopes the requesting app wants granted at the resource.
*/
export function buildIdJagExchangeBody(clientId: string, clientSecret: string | undefined, idToken: string, audience: string, resource: string | undefined, scopes: readonly string[]): URLSearchParams {
const body = new URLSearchParams();
body.append('client_id', clientId);
if (clientSecret) {
body.append('client_secret', clientSecret);
}
body.append('grant_type', GRANT_TYPE_TOKEN_EXCHANGE);
body.append('subject_token', idToken);
body.append('subject_token_type', TOKEN_TYPE_ID_TOKEN);
body.append('requested_token_type', TOKEN_TYPE_ID_JAG);
body.append('audience', audience);
if (resource) {
body.append('resource', resource);
}
if (scopes.length) {
body.append('scope', scopes.join(AUTH_SCOPE_SEPARATOR));
}
return body;
}
/**
* Build the request body sent to a resource server's authorization server to
* redeem an ID-JAG for a resource-scoped access token (RFC 7523 JWT-bearer grant).
*/
export function buildResourceRedemptionBody(clientId: string, clientSecret: string | undefined, idJag: string, resource: string | undefined, scopes: readonly string[]): URLSearchParams {
const body = new URLSearchParams();
body.append('client_id', clientId);
if (clientSecret) {
body.append('client_secret', clientSecret);
}
body.append('grant_type', GRANT_TYPE_JWT_BEARER);
body.append('assertion', idJag);
if (resource) {
body.append('resource', resource);
}
if (scopes.length) {
body.append('scope', scopes.join(AUTH_SCOPE_SEPARATOR));
}
return body;
}
//#region types
/**
* Base OAuth 2.0 error codes as specified in RFC 6749.
*/
export const enum AuthorizationErrorType {
InvalidRequest = 'invalid_request',
InvalidClient = 'invalid_client',
InvalidGrant = 'invalid_grant',
UnauthorizedClient = 'unauthorized_client',
UnsupportedGrantType = 'unsupported_grant_type',
InvalidScope = 'invalid_scope'
}
/**
* Device authorization grant specific error codes as specified in RFC 8628 section 3.5.
*/
export const enum AuthorizationDeviceCodeErrorType {
/**
* The authorization request is still pending as the end user hasn't completed the user interaction steps.
*/
AuthorizationPending = 'authorization_pending',
/**
* A variant of "authorization_pending", polling should continue but interval must be increased by 5 seconds.
*/
SlowDown = 'slow_down',
/**
* The authorization request was denied.
*/
AccessDenied = 'access_denied',
/**
* The "device_code" has expired and the device authorization session has concluded.
*/
ExpiredToken = 'expired_token'
}
/**
* Dynamic client registration specific error codes as specified in RFC 7591.
*/
export const enum AuthorizationRegistrationErrorType {
/**
* The value of one or more redirection URIs is invalid.
*/
InvalidRedirectUri = 'invalid_redirect_uri',
/**
* The value of one of the client metadata fields is invalid and the server has rejected this request.
*/
InvalidClientMetadata = 'invalid_client_metadata',
/**
* The software statement presented is invalid.
*/
InvalidSoftwareStatement = 'invalid_software_statement',
/**
* The software statement presented is not approved for use by this authorization server.
*/
UnapprovedSoftwareStatement = 'unapproved_software_statement'
}
/**
* Metadata about a protected resource.
*/
export interface IAuthorizationProtectedResourceMetadata {
/**
* REQUIRED. The protected resource's resource identifier URL that uses https scheme and has no fragment components.
*/
resource: string;
/**
* OPTIONAL. Human-readable name of the protected resource intended for display to the end user.
*/
resource_name?: string;
/**
* OPTIONAL. JSON array containing a list of OAuth authorization server identifiers.
*/
authorization_servers?: string[];
/**
* OPTIONAL. URL of the protected resource's JWK Set document.
*/
jwks_uri?: string;
/**
* RECOMMENDED. JSON array containing a list of the OAuth 2.0 scope values used in authorization requests.
*/
scopes_supported?: string[];
/**
* OPTIONAL. JSON array containing a list of the OAuth 2.0 Bearer Token presentation methods supported.
*/
bearer_methods_supported?: string[];
/**
* OPTIONAL. JSON array containing a list of the JWS signing algorithms supported.
*/
resource_signing_alg_values_supported?: string[];
/**
* OPTIONAL. JSON array containing a list of the JWE encryption algorithms supported.
*/
resource_encryption_alg_values_supported?: string[];
/**
* OPTIONAL. JSON array containing a list of the JWE encryption algorithms supported.
*/
resource_encryption_enc_values_supported?: string[];
/**
* OPTIONAL. URL of a page containing human-readable documentation.
*/
resource_documentation?: string;
/**
* OPTIONAL. URL that provides the resource's requirements on how clients can use the data.
*/
resource_policy_uri?: string;
/**
* OPTIONAL. URL that provides the resource's terms of service.
*/
resource_tos_uri?: string;
}
/**
* Metadata about an OAuth 2.0 Authorization Server.
*/
export interface IAuthorizationServerMetadata {
/**
* REQUIRED. The authorization server's issuer identifier URL that uses https scheme and has no query or fragment components.
*/
issuer: string;
/**
* URL of the authorization server's authorization endpoint.
* This is REQUIRED unless no grant types are supported that use the authorization endpoint.
*/
authorization_endpoint?: string;
/**
* URL of the authorization server's token endpoint.
* This is REQUIRED unless only the implicit grant type is supported.
*/
token_endpoint?: string;
/**
* OPTIONAL. URL of the authorization server's device code endpoint.
*/
device_authorization_endpoint?: string;
/**
* OPTIONAL. URL of the authorization server's JWK Set document containing signing keys.
*/
jwks_uri?: string;
/**
* OPTIONAL. URL of the authorization server's OAuth 2.0 Dynamic Client Registration endpoint.
*/
registration_endpoint?: string;
/**
* RECOMMENDED. JSON array containing a list of the OAuth 2.0 scope values supported.
*/
scopes_supported?: string[];
/**
* REQUIRED. JSON array containing a list of the OAuth 2.0 response_type values supported.
*/
response_types_supported: string[];
/**
* OPTIONAL. JSON array containing a list of the OAuth 2.0 response_mode values supported.
* Default is ["query", "fragment"].
*/
response_modes_supported?: string[];
/**
* OPTIONAL. JSON array containing a list of OAuth 2.0 grant type values supported.
* Default is ["authorization_code", "implicit"].
*/
grant_types_supported?: string[];
/**
* OPTIONAL. JSON array containing a list of client authentication methods supported by the token endpoint.
* Default is "client_secret_basic".
*/
token_endpoint_auth_methods_supported?: string[];
/**
* OPTIONAL. JSON array containing a list of JWS signing algorithms supported by the token endpoint.
*/
token_endpoint_auth_signing_alg_values_supported?: string[];
/**
* OPTIONAL. URL of a page containing human-readable documentation for developers.
*/
service_documentation?: string;
/**
* OPTIONAL. Languages and scripts supported for the user interface, as a JSON array of BCP 47 language tags.
*/
ui_locales_supported?: string[];
/**
* OPTIONAL. URL that the authorization server provides to read about the authorization server's requirements.
*/
op_policy_uri?: string;
/**
* OPTIONAL. URL that the authorization server provides to read about the authorization server's terms of service.
*/
op_tos_uri?: string;
/**
* OPTIONAL. URL of the authorization server's OAuth 2.0 revocation endpoint.
*/
revocation_endpoint?: string;
/**
* OPTIONAL. JSON array containing a list of client authentication methods supported by the revocation endpoint.
*/
revocation_endpoint_auth_methods_supported?: string[];
/**
* OPTIONAL. JSON array containing a list of JWS signing algorithms supported by the revocation endpoint.
*/
revocation_endpoint_auth_signing_alg_values_supported?: string[];
/**
* OPTIONAL. URL of the authorization server's OAuth 2.0 introspection endpoint.
*/
introspection_endpoint?: string;
/**
* OPTIONAL. JSON array containing a list of client authentication methods supported by the introspection endpoint.
*/
introspection_endpoint_auth_methods_supported?: string[];
/**
* OPTIONAL. JSON array containing a list of JWS signing algorithms supported by the introspection endpoint.
*/
introspection_endpoint_auth_signing_alg_values_supported?: string[];
/**
* OPTIONAL. JSON array containing a list of PKCE code challenge methods supported.
*/
code_challenge_methods_supported?: string[];
/**
* OPTIONAL. Boolean flag indicating whether the authorization server supports the
* client_id_metadata document.
* ref https://datatracker.ietf.org/doc/html/draft-parecki-oauth-client-id-metadata-document-03
*/
client_id_metadata_document_supported?: boolean;
}
/**
* Request for the dynamic client registration endpoint.
* @see https://datatracker.ietf.org/doc/html/rfc7591#section-2
*/
export interface IAuthorizationDynamicClientRegistrationRequest {
/**
* OPTIONAL. Array of redirection URI strings for use in redirect-based flows
* such as the authorization code and implicit flows.
*/
redirect_uris?: string[];
/**
* OPTIONAL. String indicator of the requested authentication method for the token endpoint.
* Values: "none", "client_secret_post", "client_secret_basic".
* Default is "client_secret_basic".
*/
token_endpoint_auth_method?: string;
/**
* OPTIONAL. Array of OAuth 2.0 grant type strings that the client can use at the token endpoint.
* Default is ["authorization_code"].
*/
grant_types?: string[];
/**
* OPTIONAL. Array of the OAuth 2.0 response type strings that the client can use at the authorization endpoint.
* Default is ["code"].
*/
response_types?: string[];
/**
* OPTIONAL. Human-readable string name of the client to be presented to the end-user during authorization.
*/
client_name?: string;
/**
* OPTIONAL. URL string of a web page providing information about the client.
*/
client_uri?: string;
/**
* OPTIONAL. URL string that references a logo for the client.
*/
logo_uri?: string;
/**
* OPTIONAL. String containing a space-separated list of scope values that the client can use when requesting access tokens.
*/
scope?: string;
/**
* OPTIONAL. Array of strings representing ways to contact people responsible for this client, typically email addresses.
*/
contacts?: string[];
/**
* OPTIONAL. URL string that points to a human-readable terms of service document for the client.
*/
tos_uri?: string;
/**
* OPTIONAL. URL string that points to a human-readable privacy policy document.
*/
policy_uri?: string;
/**
* OPTIONAL. URL string referencing the client's JSON Web Key (JWK) Set document.
*/
jwks_uri?: string;
/**
* OPTIONAL. Client's JSON Web Key Set document value.
*/
jwks?: object;
/**
* OPTIONAL. A unique identifier string assigned by the client developer or software publisher.
*/
software_id?: string;
/**
* OPTIONAL. A version identifier string for the client software.
*/
software_version?: string;
/**
* OPTIONAL. A software statement containing client metadata values about the client software as claims.
*/
software_statement?: string;
/**
* OPTIONAL. Application type. Usually "native" for OAuth clients.
* https://openid.net/specs/openid-connect-registration-1_0.html
*/
application_type?: 'native' | 'web' | string;
/**
* OPTIONAL. Additional metadata fields as defined by extensions.
*/
[key: string]: unknown;
}
/**
* Response from the dynamic client registration endpoint.
*/
export interface IAuthorizationDynamicClientRegistrationResponse {
/**
* REQUIRED. The client identifier issued by the authorization server.
*/
client_id: string;
/**
* OPTIONAL. The client secret issued by the authorization server.
* Not returned for public clients.
*/
client_secret?: string;
/**
* OPTIONAL. Time at which the client secret will expire in seconds since the Unix Epoch.
*/
client_secret_expires_at?: number;
/**
* OPTIONAL. Client name as provided during registration.
*/
client_name?: string;
/**
* OPTIONAL. Client URI as provided during registration.
*/
client_uri?: string;
/**
* OPTIONAL. Array of redirection URIs as provided during registration.
*/
redirect_uris?: string[];
/**
* OPTIONAL. Array of grant types allowed for the client.
*/
grant_types?: string[];
/**
* OPTIONAL. Array of response types allowed for the client.
*/
response_types?: string[];
/**
* OPTIONAL. Type of authentication method used by the client.
*/
token_endpoint_auth_method?: string;
}
/**
* Response from the authorization endpoint.
* Typically returned as query parameters in a redirect.
*/
export interface IAuthorizationAuthorizeResponse {
/**
* REQUIRED. The authorization code generated by the authorization server.
*/
code: string;
/**
* REQUIRED. The state value that was sent in the authorization request.
* Used to prevent CSRF attacks.
*/
state: string;
}
/**
* Error response from the authorization endpoint.
*/
export interface IAuthorizationAuthorizeErrorResponse {
/**
* REQUIRED. Error code as specified in OAuth 2.0.
*/
error: string;
/**
* OPTIONAL. Human-readable description of the error.
*/
error_description?: string;
/**
* OPTIONAL. URI to a human-readable web page with more information about the error.
*/
error_uri?: string;
/**
* REQUIRED. The state value that was sent in the authorization request.
*/
state: string;
}
/**
* Response from the token endpoint.
*/
export interface IAuthorizationTokenResponse {
/**
* REQUIRED. The access token issued by the authorization server.
*/
access_token: string;
/**
* REQUIRED. The type of the token issued. Usually "Bearer".
*/
token_type: string;
/**
* RECOMMENDED. The lifetime in seconds of the access token.
*/
expires_in?: number;
/**
* OPTIONAL. The refresh token, which can be used to obtain new access tokens.
*/
refresh_token?: string;
/**
* OPTIONAL. The scope of the access token as a space-delimited list of strings.
*/
scope?: string;
/**
* OPTIONAL. ID Token value associated with the authenticated session for OpenID Connect flows.
*/
id_token?: string;
}
/**
* Error response from the token endpoint.
*/
export interface IAuthorizationTokenErrorResponse {
/**
* REQUIRED. Error code as specified in OAuth 2.0.
*/
error: string;
/**
* OPTIONAL. Human-readable description of the error.
*/
error_description?: string;
/**
* OPTIONAL. URI to a human-readable web page with more information about the error.
*/
error_uri?: string;
}
/**
* Response from the device authorization endpoint as per RFC 8628 section 3.2.
*/
export interface IAuthorizationDeviceResponse {
/**
* REQUIRED. The device verification code.
*/
device_code: string;
/**
* REQUIRED. The end-user verification code.
*/
user_code: string;
/**
* REQUIRED. The end-user verification URI on the authorization server.
*/
verification_uri: string;
/**
* OPTIONAL. A verification URI that includes the user_code, designed for non-textual transmission.
*/
verification_uri_complete?: string;
/**
* REQUIRED. The lifetime in seconds of the device_code and user_code.
*/
expires_in: number;
/**
* OPTIONAL. The minimum amount of time in seconds that the client should wait between polling requests.
* If no value is provided, clients must use 5 as the default.
*/
interval?: number;
}
/**
* Error response from the token endpoint when using device authorization grant.
* As defined in RFC 8628 section 3.5.
*/
export interface IAuthorizationErrorResponse {
/**
* REQUIRED. Error code as specified in OAuth 2.0 or in RFC 8628 section 3.5.
*/
error: AuthorizationErrorType | string;
/**
* OPTIONAL. Human-readable description of the error.
*/
error_description?: string;
/**
* OPTIONAL. URI to a human-readable web page with more information about the error.
*/
error_uri?: string;
}
/**
* Error response from the token endpoint when using device authorization grant.
* As defined in RFC 8628 section 3.5.
*/
export interface IAuthorizationDeviceTokenErrorResponse extends IAuthorizationErrorResponse {
/**
* REQUIRED. Error code as specified in OAuth 2.0 or in RFC 8628 section 3.5.
*/
error: AuthorizationErrorType | AuthorizationDeviceCodeErrorType | string;
}
export interface IAuthorizationRegistrationErrorResponse {
/**
* REQUIRED. Error code as specified in OAuth 2.0 or Dynamic Client Registration.
*/
error: AuthorizationRegistrationErrorType | string;
/**
* OPTIONAL. Human-readable description of the error.
*/
error_description?: string;
}
export interface IAuthorizationJWTClaims {
/**
* REQUIRED. JWT ID. Unique identifier for the token.
*/
jti: string;
/**
* REQUIRED. Subject. Principal about which the token asserts information.
*/
sub: string;
/**
* REQUIRED. Issuer. Entity that issued the token.
*/
iss: string;
/**
* OPTIONAL. Audience. Recipients that the token is intended for.
*/
aud?: string | string[];
/**
* OPTIONAL. Expiration time. Time after which the token is invalid (seconds since Unix epoch).
*/
exp?: number;
/**
* OPTIONAL. Not before time. Time before which the token is not valid (seconds since Unix epoch).
*/
nbf?: number;
/**
* OPTIONAL. Issued at time when the token was issued (seconds since Unix epoch).
*/
iat?: number;
/**
* OPTIONAL. Authorized party. The party to which the token was issued.
*/
azp?: string;
/**
* OPTIONAL. Scope values for which the token is valid.
*/
scope?: string;
/**
* OPTIONAL. Full name of the user.
*/
name?: string;
/**
* OPTIONAL. Given or first name of the user.
*/
given_name?: string;
/**
* OPTIONAL. Family name or last name of the user.
*/
family_name?: string;
/**
* OPTIONAL. Middle name of the user.
*/
middle_name?: string;
/**
* OPTIONAL. Preferred username or email the user wishes to be referred to.
*/
preferred_username?: string;
/**
* OPTIONAL. Email address of the user.
*/
email?: string;
/**
* OPTIONAL. True if the user's email has been verified.
*/
email_verified?: boolean;
/**
* OPTIONAL. User's profile picture URL.
*/
picture?: string;
/**
* OPTIONAL. Authentication time. Time when the user authentication occurred.
*/
auth_time?: number;
/**
* OPTIONAL. Authentication context class reference.
*/
acr?: string;
/**
* OPTIONAL. Authentication methods references.
*/
amr?: string[];
/**
* OPTIONAL. Session ID. String identifier for a session.
*/
sid?: string;
/**
* OPTIONAL. Address component.
*/
address?: {
formatted?: string;
street_address?: string;
locality?: string;
region?: string;
postal_code?: string;
country?: string;
};
/**
* OPTIONAL. Groups that the user belongs to.
*/
groups?: string[];
/**
* OPTIONAL. Roles assigned to the user.
*/
roles?: string[];
/** Entra ID tenant id; absent on non-Entra tokens. Distinguishes work/school from personal accounts. */
tid?: string;
/**
* OPTIONAL. Handles optional claims that are not explicitly defined in the standard.
*/
[key: string]: unknown;
}
//#endregion
//#region is functions
export function isAuthorizationProtectedResourceMetadata(obj: unknown): obj is IAuthorizationProtectedResourceMetadata {
if (typeof obj !== 'object' || obj === null) {
return false;
}
const metadata = obj as IAuthorizationProtectedResourceMetadata;
if (!metadata.resource) {
return false;
}
if (metadata.scopes_supported !== undefined && !Array.isArray(metadata.scopes_supported)) {
return false;
}
return true;
}
const urisToCheck: Array<keyof IAuthorizationServerMetadata> = [
'issuer',
'authorization_endpoint',
'token_endpoint',
'registration_endpoint',
'jwks_uri'
];
export function isAuthorizationServerMetadata(obj: unknown): obj is IAuthorizationServerMetadata {
if (typeof obj !== 'object' || obj === null) {
return false;
}
const metadata = obj as IAuthorizationServerMetadata;
if (!metadata.issuer) {
throw new Error('Authorization server metadata must have an issuer');
}
for (const uri of urisToCheck) {
if (!metadata[uri]) {
continue;
}
if (typeof metadata[uri] !== 'string') {
throw new Error(`Authorization server metadata '${uri}' must be a string`);
}
if (!metadata[uri].startsWith('https://') && !metadata[uri].startsWith('http://')) {
throw new Error(`Authorization server metadata '${uri}' must start with http:// or https://`);
}
}
return true;
}
export function isAuthorizationDynamicClientRegistrationResponse(obj: unknown): obj is IAuthorizationDynamicClientRegistrationResponse {
if (typeof obj !== 'object' || obj === null) {
return false;
}
const response = obj as IAuthorizationDynamicClientRegistrationResponse;
return response.client_id !== undefined;
}
export function isAuthorizationAuthorizeResponse(obj: unknown): obj is IAuthorizationAuthorizeResponse {
if (typeof obj !== 'object' || obj === null) {
return false;
}
const response = obj as IAuthorizationAuthorizeResponse;
return response.code !== undefined && response.state !== undefined;
}
export function isAuthorizationTokenResponse(obj: unknown): obj is IAuthorizationTokenResponse {
if (typeof obj !== 'object' || obj === null) {
return false;
}
const response = obj as IAuthorizationTokenResponse;
return response.access_token !== undefined && response.token_type !== undefined;
}
export function isAuthorizationDeviceResponse(obj: unknown): obj is IAuthorizationDeviceResponse {
if (typeof obj !== 'object' || obj === null) {
return false;
}
const response = obj as IAuthorizationDeviceResponse;
return response.device_code !== undefined && response.user_code !== undefined && response.verification_uri !== undefined && response.expires_in !== undefined;
}
export function isAuthorizationErrorResponse(obj: unknown): obj is IAuthorizationErrorResponse {
if (typeof obj !== 'object' || obj === null) {
return false;
}
const response = obj as IAuthorizationErrorResponse;
return response.error !== undefined;
}
export function isAuthorizationRegistrationErrorResponse(obj: unknown): obj is IAuthorizationRegistrationErrorResponse {
if (typeof obj !== 'object' || obj === null) {
return false;
}
const response = obj as IAuthorizationRegistrationErrorResponse;
return response.error !== undefined;
}
//#endregion
export function getDefaultMetadataForUrl(authorizationServer: URL): IAuthorizationServerMetadata {
return {
issuer: authorizationServer.toString(),
authorization_endpoint: new URL('/authorize', authorizationServer).toString(),
token_endpoint: new URL('/token', authorizationServer).toString(),
registration_endpoint: new URL('/register', authorizationServer).toString(),
// Default values for Dynamic OpenID Providers
// https://openid.net/specs/openid-connect-discovery-1_0.html
response_types_supported: ['code', 'id_token', 'id_token token'],
};
}
/**
* The grant types that we support
*/
const grantTypesSupported = ['authorization_code', 'refresh_token', 'urn:ietf:params:oauth:grant-type:device_code'];
/**
* Default port for the authorization flow. We try to use this port so that
* the redirect URI does not change when running on localhost. This is useful
* for servers that only allow exact matches on the redirect URI. The spec
* says that the port should not matter, but some servers do not follow
* the spec and require an exact match.
*/
export const DEFAULT_AUTH_FLOW_PORT = 33418;
export async function fetchDynamicRegistration(serverMetadata: IAuthorizationServerMetadata, clientName: string, scopes?: string[]): Promise<IAuthorizationDynamicClientRegistrationResponse> {
if (!serverMetadata.registration_endpoint) {
throw new Error('Server does not support dynamic registration');
}
const requestBody: IAuthorizationDynamicClientRegistrationRequest = {
client_name: clientName,
client_uri: 'https://code.visualstudio.com',
grant_types: serverMetadata.grant_types_supported
? serverMetadata.grant_types_supported.filter(gt => grantTypesSupported.includes(gt))
: grantTypesSupported,
response_types: ['code'],
redirect_uris: [
'https://insiders.vscode.dev/redirect',
'https://vscode.dev/redirect',
'http://127.0.0.1/',
// Added these for any server that might do
// only exact match on the redirect URI even
// though the spec says it should not care
// about the port.
`http://127.0.0.1:${DEFAULT_AUTH_FLOW_PORT}/`
],
scope: scopes?.join(AUTH_SCOPE_SEPARATOR),
token_endpoint_auth_method: 'none',
application_type: 'native'
};
const response = await fetch(serverMetadata.registration_endpoint, {
method: 'POST',
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify(requestBody)
});
if (!response.ok) {
const result = await response.text();
let errorDetails: string = result;
try {
const errorResponse = JSON.parse(result);
if (isAuthorizationRegistrationErrorResponse(errorResponse)) {
errorDetails = `${errorResponse.error}${errorResponse.error_description ? `: ${errorResponse.error_description}` : ''}`;
}
} catch {
// JSON parsing failed, use raw text
}
throw new Error(`Registration to ${serverMetadata.registration_endpoint} failed: ${errorDetails}`);
}
const registration = await response.json();
if (isAuthorizationDynamicClientRegistrationResponse(registration)) {
return registration;