-
-
Notifications
You must be signed in to change notification settings - Fork 54
/
index.ts
3559 lines (3150 loc) · 113 KB
/
index.ts
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: string
// @ts-ignore
if (typeof navigator === 'undefined' || !navigator.userAgent?.startsWith?.('Mozilla/5.0 ')) {
const NAME = 'oauth4webapi'
const VERSION = 'v2.3.0'
USER_AGENT = `${NAME}/${VERSION}`
}
type JsonObject = { [Key in string]?: JsonValue }
type JsonArray = JsonValue[]
type JsonPrimitive = string | number | boolean | null
type JsonValue = JsonPrimitive | JsonObject | JsonArray
/**
* Interface to pass an asymmetric private key and, optionally, its associated JWK Key ID to be
* added as a `kid` JOSE Header Parameter.
*/
export interface PrivateKey {
/**
* An asymmetric private CryptoKey.
*
* Its algorithm must be compatible with a supported {@link JWSAlgorithm JWS `alg` Algorithm}.
*/
key: CryptoKey
/**
* JWK Key ID to add to JOSE headers when this key is used. When not provided no `kid` (JWK Key
* ID) will be added to the JOSE Header.
*/
kid?: string
}
/**
* Supported Client Authentication Methods.
*
* - **`client_secret_basic`** (default) uses the HTTP `Basic` authentication scheme to send
* {@link Client.client_id `client_id`} and {@link Client.client_secret `client_secret`} in an
* `Authorization` HTTP Header.
* - **`client_secret_post`** uses the HTTP request body to send {@link Client.client_id `client_id`}
* and {@link Client.client_secret `client_secret`} as `application/x-www-form-urlencoded` body
* parameters.
* - **`private_key_jwt`** uses the HTTP request body to send {@link Client.client_id `client_id`},
* `client_assertion_type`, and `client_assertion` as `application/x-www-form-urlencoded` body
* parameters. The `client_assertion` is signed using a private key supplied as an
* {@link AuthenticatedRequestOptions.clientPrivateKey options parameter}.
* - **`none`** (public client) uses the HTTP request body to send only
* {@link Client.client_id `client_id`} as `application/x-www-form-urlencoded` body parameter.
*
* @see [RFC 6749 - The OAuth 2.0 Authorization Framework](https://www.rfc-editor.org/rfc/rfc6749.html#section-2.3)
* @see [OpenID Connect Core 1.0](https://openid.net/specs/openid-connect-core-1_0.html#ClientAuthentication)
* @see [OAuth Token Endpoint Authentication Methods](https://www.iana.org/assignments/oauth-parameters/oauth-parameters.xhtml#token-endpoint-auth-method)
*/
export type ClientAuthenticationMethod =
| 'client_secret_basic'
| 'client_secret_post'
| 'private_key_jwt'
| 'none'
/**
* Supported JWS `alg` Algorithm identifiers.
*
* @example CryptoKey algorithm for the `PS256`, `PS384`, or `PS512` JWS Algorithm Identifiers
*
* ```ts
* interface RSAPSSAlgorithm extends RsaHashedKeyAlgorithm {
* name: 'RSA-PSS'
* hash: { name: 'SHA-256' | 'SHA-384' | 'SHA-512' }
* }
*
* interface PS256 extends RSAPSSAlgorithm {
* hash: { name: 'SHA-256' }
* }
*
* interface PS384 extends RSAPSSAlgorithm {
* hash: { name: 'SHA-384' }
* }
*
* interface PS512 extends RSAPSSAlgorithm {
* hash: { name: 'SHA-512' }
* }
* ```
*
* @example CryptoKey algorithm for the `ES256`, `ES384`, or `ES512` JWS Algorithm Identifiers
*
* ```ts
* interface ECDSAAlgorithm extends EcKeyAlgorithm {
* name: 'ECDSA'
* namedCurve: 'P-256' | 'P-384' | 'P-521'
* }
*
* interface ES256 extends ECDSAAlgorithm {
* namedCurve: 'P-256'
* }
*
* interface ES384 extends ECDSAAlgorithm {
* namedCurve: 'P-384'
* }
*
* interface ES512 extends ECDSAAlgorithm {
* namedCurve: 'P-521'
* }
* ```
*
* @example CryptoKey algorithm for the `RS256`, `RS384`, or `RS512` JWS Algorithm Identifiers
*
* ```ts
* interface ECDSAAlgorithm extends RsaHashedKeyAlgorithm {
* name: 'RSASSA-PKCS1-v1_5'
* hash: { name: 'SHA-256' | 'SHA-384' | 'SHA-512' }
* }
*
* interface RS256 extends ECDSAAlgorithm {
* hash: { name: 'SHA-256' }
* }
*
* interface RS384 extends ECDSAAlgorithm {
* hash: { name: 'SHA-384' }
* }
*
* interface RS512 extends ECDSAAlgorithm {
* hash: { name: 'SHA-512' }
* }
* ```
*
* @example CryptoKey algorithm for the `EdDSA` JWS Algorithm Identifier (Experimental)
*
* Runtime support for this algorithm is very limited, it depends on the [Secure Curves in the Web
* Cryptography API](https://wicg.github.io/webcrypto-secure-curves/) proposal which is yet to be
* widely adopted. If the proposal changes this implementation will follow up with a minor release.
*
* ```ts
* interface EdDSA extends KeyAlgorithm {
* name: 'Ed25519' | 'Ed448'
* }
* ```
*/
export type JWSAlgorithm =
// widely used
| 'PS256'
| 'ES256'
| 'RS256'
| 'EdDSA'
// less used
| 'ES384'
| 'PS384'
| 'RS384'
| 'ES512'
| 'PS512'
| 'RS512'
interface JWK {
readonly kty?: string
readonly kid?: string
readonly alg?: string
readonly use?: string
readonly key_ops?: string[]
readonly e?: string
readonly n?: string
readonly crv?: string
readonly x?: string
readonly y?: string
readonly [parameter: string]: JsonValue | undefined
}
/** @ignore during Documentation generation but part of the public API */
export const clockSkew = Symbol()
/** @ignore during Documentation generation but part of the public API */
export const clockTolerance = Symbol()
/**
* Authorization Server Metadata
*
* @see [IANA OAuth Authorization Server Metadata registry](https://www.iana.org/assignments/oauth-parameters/oauth-parameters.xhtml#authorization-server-metadata)
*/
export interface AuthorizationServer {
/** Authorization server's Issuer Identifier URL. */
readonly issuer: string
/** URL of the authorization server's authorization endpoint. */
readonly authorization_endpoint?: string
/** URL of the authorization server's token endpoint. */
readonly token_endpoint?: string
/** URL of the authorization server's JWK Set document. */
readonly jwks_uri?: string
/** URL of the authorization server's Dynamic Client Registration Endpoint. */
readonly registration_endpoint?: string
/** JSON array containing a list of the `scope` values that this authorization server supports. */
readonly scopes_supported?: string[]
/**
* JSON array containing a list of the `response_type` values that this authorization server
* supports.
*/
readonly response_types_supported?: string[]
/**
* JSON array containing a list of the `response_mode` values that this authorization server
* supports.
*/
readonly response_modes_supported?: string[]
/**
* JSON array containing a list of the `grant_type` values that this authorization server
* supports.
*/
readonly grant_types_supported?: string[]
/** JSON array containing a list of client authentication methods supported by this token endpoint. */
readonly token_endpoint_auth_methods_supported?: string[]
/**
* JSON array containing a list of the JWS signing algorithms supported by the token endpoint for
* the signature on the JWT used to authenticate the client at the token endpoint.
*/
readonly token_endpoint_auth_signing_alg_values_supported?: string[]
/**
* URL of a page containing human-readable information that developers might want or need to know
* when using the authorization server.
*/
readonly service_documentation?: string
/**
* Languages and scripts supported for the user interface, represented as a JSON array of language
* tag values from RFC 5646.
*/
readonly ui_locales_supported?: string[]
/**
* URL that the authorization server provides to the person registering the client to read about
* the authorization server's requirements on how the client can use the data provided by the
* authorization server.
*/
readonly op_policy_uri?: string
/**
* URL that the authorization server provides to the person registering the client to read about
* the authorization server's terms of service.
*/
readonly op_tos_uri?: string
/** URL of the authorization server's revocation endpoint. */
readonly revocation_endpoint?: string
/**
* JSON array containing a list of client authentication methods supported by this revocation
* endpoint.
*/
readonly revocation_endpoint_auth_methods_supported?: string[]
/**
* JSON array containing a list of the JWS signing algorithms supported by the revocation endpoint
* for the signature on the JWT used to authenticate the client at the revocation endpoint.
*/
readonly revocation_endpoint_auth_signing_alg_values_supported?: string[]
/** URL of the authorization server's introspection endpoint. */
readonly introspection_endpoint?: string
/**
* JSON array containing a list of client authentication methods supported by this introspection
* endpoint.
*/
readonly introspection_endpoint_auth_methods_supported?: string[]
/**
* JSON array containing a list of the JWS signing algorithms supported by the introspection
* endpoint for the signature on the JWT used to authenticate the client at the introspection
* endpoint.
*/
readonly introspection_endpoint_auth_signing_alg_values_supported?: string[]
/** PKCE code challenge methods supported by this authorization server. */
readonly code_challenge_methods_supported?: string[]
/** Signed JWT containing metadata values about the authorization server as claims. */
readonly signed_metadata?: string
/** URL of the authorization server's device authorization endpoint. */
readonly device_authorization_endpoint?: string
/** Indicates authorization server support for mutual-TLS client certificate-bound access tokens. */
readonly tls_client_certificate_bound_access_tokens?: boolean
/**
* JSON object containing alternative authorization server endpoints, which a client intending to
* do mutual TLS will use in preference to the conventional endpoints.
*/
readonly mtls_endpoint_aliases?: MTLSEndpointAliases
/** URL of the authorization server's UserInfo Endpoint. */
readonly userinfo_endpoint?: string
/**
* JSON array containing a list of the Authentication Context Class References that this
* authorization server supports.
*/
readonly acr_values_supported?: string[]
/**
* JSON array containing a list of the Subject Identifier types that this authorization server
* supports.
*/
readonly subject_types_supported?: string[]
/**
* JSON array containing a list of the JWS `alg` values supported by the authorization server for
* the ID Token.
*/
readonly id_token_signing_alg_values_supported?: string[]
/**
* JSON array containing a list of the JWE `alg` values supported by the authorization server for
* the ID Token.
*/
readonly id_token_encryption_alg_values_supported?: string[]
/**
* JSON array containing a list of the JWE `enc` values supported by the authorization server for
* the ID Token.
*/
readonly id_token_encryption_enc_values_supported?: string[]
/** JSON array containing a list of the JWS `alg` values supported by the UserInfo Endpoint. */
readonly userinfo_signing_alg_values_supported?: string[]
/** JSON array containing a list of the JWE `alg` values supported by the UserInfo Endpoint. */
readonly userinfo_encryption_alg_values_supported?: string[]
/** JSON array containing a list of the JWE `enc` values supported by the UserInfo Endpoint. */
readonly userinfo_encryption_enc_values_supported?: string[]
/**
* JSON array containing a list of the JWS `alg` values supported by the authorization server for
* Request Objects.
*/
readonly request_object_signing_alg_values_supported?: string[]
/**
* JSON array containing a list of the JWE `alg` values supported by the authorization server for
* Request Objects.
*/
readonly request_object_encryption_alg_values_supported?: string[]
/**
* JSON array containing a list of the JWE `enc` values supported by the authorization server for
* Request Objects.
*/
readonly request_object_encryption_enc_values_supported?: string[]
/**
* JSON array containing a list of the `display` parameter values that the authorization server
* supports.
*/
readonly display_values_supported?: string[]
/** JSON array containing a list of the Claim Types that the authorization server supports. */
readonly claim_types_supported?: string[]
/**
* JSON array containing a list of the Claim Names of the Claims that the authorization server MAY
* be able to supply values for.
*/
readonly claims_supported?: string[]
/**
* Languages and scripts supported for values in Claims being returned, represented as a JSON
* array of RFC 5646 language tag values.
*/
readonly claims_locales_supported?: string[]
/**
* Boolean value specifying whether the authorization server supports use of the `claims`
* parameter.
*/
readonly claims_parameter_supported?: boolean
/**
* Boolean value specifying whether the authorization server supports use of the `request`
* parameter.
*/
readonly request_parameter_supported?: boolean
/**
* Boolean value specifying whether the authorization server supports use of the `request_uri`
* parameter.
*/
readonly request_uri_parameter_supported?: boolean
/**
* Boolean value specifying whether the authorization server requires any `request_uri` values
* used to be pre-registered.
*/
readonly require_request_uri_registration?: boolean
/**
* Indicates where authorization request needs to be protected as Request Object and provided
* through either `request` or `request_uri` parameter.
*/
readonly require_signed_request_object?: boolean
/** URL of the authorization server's pushed authorization request endpoint. */
readonly pushed_authorization_request_endpoint?: string
/** Indicates whether the authorization server accepts authorization requests only via PAR. */
readonly require_pushed_authorization_requests?: boolean
/**
* JSON array containing a list of algorithms supported by the authorization server for
* introspection response signing.
*/
readonly introspection_signing_alg_values_supported?: string[]
/**
* JSON array containing a list of algorithms supported by the authorization server for
* introspection response content key encryption (`alg` value).
*/
readonly introspection_encryption_alg_values_supported?: string[]
/**
* JSON array containing a list of algorithms supported by the authorization server for
* introspection response content encryption (`enc` value).
*/
readonly introspection_encryption_enc_values_supported?: string[]
/**
* Boolean value indicating whether the authorization server provides the `iss` parameter in the
* authorization response.
*/
readonly authorization_response_iss_parameter_supported?: boolean
/**
* JSON array containing a list of algorithms supported by the authorization server for
* introspection response signing.
*/
readonly authorization_signing_alg_values_supported?: string[]
/**
* JSON array containing a list of algorithms supported by the authorization server for
* introspection response encryption (`alg` value).
*/
readonly authorization_encryption_alg_values_supported?: string[]
/**
* JSON array containing a list of algorithms supported by the authorization server for
* introspection response encryption (`enc` value).
*/
readonly authorization_encryption_enc_values_supported?: string[]
/** CIBA Backchannel Authentication Endpoint. */
readonly backchannel_authentication_endpoint?: string
/**
* JSON array containing a list of the JWS signing algorithms supported for validation of signed
* CIBA authentication requests.
*/
readonly backchannel_authentication_request_signing_alg_values_supported?: string[]
/** Supported CIBA authentication result delivery modes. */
readonly backchannel_token_delivery_modes_supported?: string[]
/** Indicates whether the authorization server supports the use of the CIBA `user_code` parameter. */
readonly backchannel_user_code_parameter_supported?: boolean
/**
* URL of an authorization server iframe that supports cross-origin communications for session
* state information with the RP Client, using the HTML5 postMessage API.
*/
readonly check_session_iframe?: string
/** JSON array containing a list of the JWS algorithms supported for DPoP proof JWTs. */
readonly dpop_signing_alg_values_supported?: string[]
/**
* URL at the authorization server to which an RP can perform a redirect to request that the
* End-User be logged out at the authorization server.
*/
readonly end_session_endpoint?: string
/**
* Boolean value specifying whether the authorization server can pass `iss` (issuer) and `sid`
* (session ID) query parameters to identify the RP session with the authorization server when the
* `frontchannel_logout_uri` is used.
*/
readonly frontchannel_logout_session_supported?: boolean
/** Boolean value specifying whether the authorization server supports HTTP-based logout. */
readonly frontchannel_logout_supported?: boolean
/**
* Boolean value specifying whether the authorization server can pass a `sid` (session ID) Claim
* in the Logout Token to identify the RP session with the OP.
*/
readonly backchannel_logout_session_supported?: boolean
/** Boolean value specifying whether the authorization server supports back-channel logout. */
readonly backchannel_logout_supported?: boolean
readonly [metadata: string]: JsonValue | undefined
}
export interface MTLSEndpointAliases
extends Pick<
AuthorizationServer,
| 'token_endpoint'
| 'revocation_endpoint'
| 'introspection_endpoint'
| 'device_authorization_endpoint'
| 'userinfo_endpoint'
| 'pushed_authorization_request_endpoint'
> {
readonly [metadata: string]: JsonValue | undefined
}
/**
* Recognized Client Metadata that have an effect on the exposed functionality.
*
* @see [IANA OAuth Client Registration Metadata registry](https://www.iana.org/assignments/oauth-parameters/oauth-parameters.xhtml#client-metadata)
*/
export interface Client {
/** Client identifier. */
client_id: string
/** Client secret. */
client_secret?: string
/**
* Client {@link ClientAuthenticationMethod authentication method} for the client's authenticated
* requests. Default is `client_secret_basic`.
*/
token_endpoint_auth_method?: ClientAuthenticationMethod
/**
* JWS `alg` algorithm required for signing the ID Token issued to this Client. When not
* configured the default is to allow only algorithms listed in
* {@link AuthorizationServer.id_token_signing_alg_values_supported `as.id_token_signing_alg_values_supported`}
* and fall back to `RS256` when the authorization server metadata is not set.
*/
id_token_signed_response_alg?: string
/**
* JWS `alg` algorithm required for signing authorization responses. When not configured the
* default is to allow only {@link JWSAlgorithm supported algorithms} listed in
* {@link AuthorizationServer.authorization_signing_alg_values_supported `as.authorization_signing_alg_values_supported`}
* and fall back to `RS256` when the authorization server metadata is not set.
*/
authorization_signed_response_alg?: JWSAlgorithm
/**
* Boolean value specifying whether the {@link IDToken.auth_time `auth_time`} Claim in the ID Token
* is REQUIRED. Default is `false`.
*/
require_auth_time?: boolean
/**
* JWS `alg` algorithm REQUIRED for signing UserInfo Responses. When not configured the default is
* to allow only algorithms listed in
* {@link AuthorizationServer.userinfo_signing_alg_values_supported `as.userinfo_signing_alg_values_supported`}
* and fall back to `RS256` when the authorization server metadata is not set.
*/
userinfo_signed_response_alg?: string
/**
* JWS `alg` algorithm REQUIRED for signed introspection responses. When not configured the
* default is to allow only algorithms listed in
* {@link AuthorizationServer.introspection_signing_alg_values_supported `as.introspection_signing_alg_values_supported`}
* and fall back to `RS256` when the authorization server metadata is not set.
*/
introspection_signed_response_alg?: string
/** Default Maximum Authentication Age. */
default_max_age?: number
/**
* Use to adjust the client's assumed current time. Positive and negative finite values
* representing seconds are allowed. Default is `0` (Date.now() + 0 seconds is used).
*
* @ignore during Documentation generation but part of the public API
*
* @example Client's local clock is mistakenly 1 hour in the past
*
* ```ts
* const client: oauth.Client = {
* client_id: 'abc4ba37-4ab8-49b5-99d4-9441ba35d428',
* // ... other metadata
* [oauth.clockSkew]: +(60 * 60),
* }
* ```
*
* @example Client's local clock is mistakenly 1 hour in the future
*
* ```ts
* const client: oauth.Client = {
* client_id: 'abc4ba37-4ab8-49b5-99d4-9441ba35d428',
* // ... other metadata
* [oauth.clockSkew]: -(60 * 60),
* }
* ```
*/
[clockSkew]?: number
/**
* Use to set allowed client's clock tolerance when checking DateTime JWT Claims. Only positive
* finite values representing seconds are allowed. Default is `30` (30 seconds).
*
* @ignore during Documentation generation but part of the public API
*
* @example Tolerate 30 seconds clock skew when validating JWT claims like `exp` or `nbf`.
*
* ```ts
* const client: oauth.Client = {
* client_id: 'abc4ba37-4ab8-49b5-99d4-9441ba35d428',
* // ... other metadata
* [oauth.clockTolerance]: 30,
* }
* ```
*/
[clockTolerance]?: number
[metadata: string]: JsonValue | undefined
}
const encoder = new TextEncoder()
const decoder = new TextDecoder()
function buf(input: string): Uint8Array
function buf(input: Uint8Array): string
function buf(input: string | Uint8Array) {
if (typeof input === 'string') {
return encoder.encode(input)
}
return decoder.decode(input)
}
const CHUNK_SIZE = 0x8000
function encodeBase64Url(input: Uint8Array | ArrayBuffer) {
if (input instanceof ArrayBuffer) {
input = new Uint8Array(input)
}
const arr = []
for (let i = 0; i < input.byteLength; i += CHUNK_SIZE) {
// @ts-expect-error
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: string) {
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 {
throw new TypeError('The input to be decoded is not correctly encoded.')
}
}
function b64u(input: string): Uint8Array
function b64u(input: Uint8Array | ArrayBuffer): string
function b64u(input: string | Uint8Array | ArrayBuffer) {
if (typeof input === 'string') {
return decodeBase64Url(input)
}
return encodeBase64Url(input)
}
/** Simple LRU */
class LRU<T1, T2> {
cache = new Map<T1, T2>()
_cache = new Map<T1, T2>()
maxSize: number
constructor(maxSize: number) {
this.maxSize = maxSize
}
get(key: T1) {
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: T1) {
return this.cache.has(key) || this._cache.has(key)
}
set(key: T1, value: T2) {
if (this.cache.has(key)) {
this.cache.set(key, value)
} else {
this.update(key, value)
}
return this
}
delete(key: T1) {
if (this.cache.has(key)) {
return this.cache.delete(key)
}
if (this._cache.has(key)) {
return this._cache.delete(key)
}
return false
}
update(key: T1, value: T2) {
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?: string) {
super(message ?? 'operation not supported')
this.name = this.constructor.name
// @ts-ignore
Error.captureStackTrace?.(this, this.constructor)
}
}
export class OperationProcessingError extends Error {
constructor(message: string) {
super(message)
this.name = this.constructor.name
// @ts-ignore
Error.captureStackTrace?.(this, this.constructor)
}
}
const OPE = OperationProcessingError
const dpopNonces: LRU<string, string> = new LRU(100)
function isCryptoKey(key: unknown): key is CryptoKey {
return key instanceof CryptoKey
}
function isPrivateKey(key: unknown): key is CryptoKey {
return isCryptoKey(key) && key.type === 'private'
}
function isPublicKey(key: unknown): key is CryptoKey {
return isCryptoKey(key) && key.type === 'public'
}
const SUPPORTED_JWS_ALGS: JWSAlgorithm[] = [
'PS256',
'ES256',
'RS256',
'PS384',
'ES384',
'RS384',
'PS512',
'ES512',
'RS512',
'EdDSA',
]
export interface HttpRequestOptions {
/**
* An AbortSignal instance, or a factory returning one, to abort the HTTP Request(s) triggered by
* this function's invocation.
*
* @example A 5000ms timeout AbortSignal for every request
*
* ```js
* const signal = () => AbortSignal.timeout(5_000) // Note: AbortSignal.timeout may not yet be available in all runtimes.
* ```
*/
signal?: (() => AbortSignal) | AbortSignal
/**
* A Headers instance to additionally send with the HTTP Request(s) triggered by this function's
* invocation.
*/
headers?: Headers
}
export interface DiscoveryRequestOptions extends HttpRequestOptions {
/** The issuer transformation algorithm to use. */
algorithm?: 'oidc' | 'oauth2'
}
function processDpopNonce(response: Response) {
const url = new URL(response.url)
if (response.headers.has('dpop-nonce')) {
dpopNonces.set(url.origin, response.headers.get('dpop-nonce')!)
}
return response
}
function normalizeTyp(value: string) {
return value.toLowerCase().replace(/^application\//, '')
}
function isJsonObject<T = JsonObject>(input: unknown): input is T {
if (input === null || typeof input !== 'object' || Array.isArray(input)) {
return false
}
return true
}
function prepareHeaders(input: unknown): Headers {
if (input !== undefined && !(input instanceof Headers)) {
throw new TypeError('"options.headers" must be an instance of Headers')
}
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: Exclude<HttpRequestOptions['signal'], undefined>): AbortSignal {
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
}
/**
* Performs an authorization server metadata discovery using one of two
* {@link DiscoveryRequestOptions.algorithm transformation algorithms} applied to the
* `issuerIdentifier` argument.
*
* - `oidc` (default) as defined by OpenID Connect Discovery 1.0.
* - `oauth2` as defined by RFC 8414.
*
* @param issuerIdentifier Issuer Identifier to resolve the well-known discovery URI for.
*
* @see [RFC 8414 - OAuth 2.0 Authorization Server Metadata](https://www.rfc-editor.org/rfc/rfc8414.html#section-3)
* @see [OpenID Connect Discovery 1.0](https://openid.net/specs/openid-connect-discovery-1_0.html#ProviderConfig)
*/
export async function discoveryRequest(
issuerIdentifier: URL,
options?: DiscoveryRequestOptions,
): Promise<Response> {
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: // Fall through
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 fetch(url.href, {
headers,
method: 'GET',
redirect: 'manual',
signal: options?.signal ? signal(options.signal) : null,
}).then(processDpopNonce)
}
function validateString(input: unknown): input is string {
return typeof input === 'string' && input.length !== 0
}
/**
* Validates Response instance to be one coming from the authorization server's well-known discovery
* endpoint.
*
* @param expectedIssuerIdentifier Expected Issuer Identifier value.
* @param response Resolved value from {@link discoveryRequest}.
*
* @returns Resolves with the discovered Authorization Server Metadata.
*
* @see [RFC 8414 - OAuth 2.0 Authorization Server Metadata](https://www.rfc-editor.org/rfc/rfc8414.html#section-3)
* @see [OpenID Connect Discovery 1.0](https://openid.net/specs/openid-connect-discovery-1_0.html#ProviderConfig)
*/
export async function processDiscoveryResponse(
expectedIssuerIdentifier: URL,
response: Response,
): Promise<AuthorizationServer> {
if (!(expectedIssuerIdentifier instanceof URL)) {
throw new TypeError('"expectedIssuer" must be an instance of URL')
}
if (!(response instanceof 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: JsonValue
try {
json = await response.json()
} catch {
throw new OPE('failed to parse "response" body as JSON')
}
if (!isJsonObject<AuthorizationServer>(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
}
/** Generates 32 random bytes and encodes them using base64url. */
function randomBytes() {
return b64u(crypto.getRandomValues(new Uint8Array(32)))
}
/**
* Generate random `code_verifier` value.
*
* @see [RFC 7636 - Proof Key for Code Exchange by OAuth Public Clients (PKCE)](https://www.rfc-editor.org/rfc/rfc7636.html#section-4)
*/
export function generateRandomCodeVerifier() {
return randomBytes()
}
/**
* Generate random `state` value.
*
* @see [RFC 6749 - The OAuth 2.0 Authorization Framework](https://www.rfc-editor.org/rfc/rfc6749.html#section-4.1.1)
*/
export function generateRandomState() {
return randomBytes()
}
/**
* Generate random `nonce` value.
*
* @see [OpenID Connect Core 1.0](https://openid.net/specs/openid-connect-core-1_0.html#IDToken)
*/
export function generateRandomNonce() {
return randomBytes()
}
/**
* Calculates the PKCE `code_verifier` value to send with an authorization request using the S256
* PKCE Code Challenge Method transformation.
*
* @param codeVerifier `code_verifier` value generated e.g. from {@link generateRandomCodeVerifier}.
*
* @see [RFC 7636 - Proof Key for Code Exchange by OAuth Public Clients (PKCE)](https://www.rfc-editor.org/rfc/rfc7636.html#section-4)
*/
export async function calculatePKCECodeChallenge(codeVerifier: string) {
if (!validateString(codeVerifier)) {
throw new TypeError('"codeVerifier" must be a non-empty string')
}
return b64u(await crypto.subtle.digest({ name: 'SHA-256' }, buf(codeVerifier)))
}
interface NormalizedKeyInput {
key?: CryptoKey
kid?: string
}
function getKeyAndKid(input: CryptoKey | PrivateKey | undefined): NormalizedKeyInput {
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 }
}
export interface DPoPOptions extends CryptoKeyPair {
/**
* Private CryptoKey instance to sign the DPoP Proof JWT with.
*
* Its algorithm must be compatible with a supported {@link JWSAlgorithm JWS `alg` Algorithm}.
*/
privateKey: CryptoKey
/** The public key corresponding to {@link DPoPOptions.privateKey}. */
publicKey: CryptoKey
/**
* Server-Provided Nonce to use in the request. This option serves as an override in case the
* self-correcting mechanism does not work with a particular server. Previously received nonces
* will be used automatically.
*/
nonce?: string
}
export interface DPoPRequestOptions {
/** DPoP-related options. */
DPoP?: DPoPOptions
}
export interface AuthenticatedRequestOptions {
/**
* Private key to use for `private_key_jwt`
* {@link ClientAuthenticationMethod client authentication}. Its algorithm must be compatible with
* a supported {@link JWSAlgorithm JWS `alg` Algorithm}.
*/
clientPrivateKey?: CryptoKey | PrivateKey
}
export interface PushedAuthorizationRequestOptions
extends HttpRequestOptions,
AuthenticatedRequestOptions,
DPoPRequestOptions {}
/**
* The client identifier is encoded using the `application/x-www-form-urlencoded` encoding algorithm
* per Appendix B, and the encoded value is used as the username; the client password is encoded
* using the same algorithm and used as the password.