deno.land / x / oauth4webapi@v1.2.2 / src / index.ts

View Documentation
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
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325
3326
3327
3328
3329
3330
3331
3332
3333
3334
3335
3336
3337
3338
3339
3340
3341
3342
3343
3344
3345
3346
3347
3348
3349
3350
3351
3352
3353
3354
3355
3356
3357
3358
3359
3360
3361
3362
3363
3364
3365
3366
3367
3368
3369
3370
3371
3372
3373
3374
3375
3376
3377
3378
3379
3380
3381
3382
3383
3384
3385
3386
3387
3388
3389
3390
3391
3392
3393
3394
3395
3396
3397
3398
3399
3400
3401
3402
3403
3404
3405
3406
3407
3408
3409
3410
3411
3412
3413
3414
3415
3416
3417
3418
3419
3420
3421
3422
3423
3424
3425
3426
3427
3428
3429
3430
3431
3432
3433
3434
3435
3436
3437
3438
3439
3440
3441
3442
3443
3444
3445
3446
3447
3448
3449
3450
3451
3452
3453
3454
3455
3456
3457
3458
3459
3460
3461
3462
3463
3464
3465
3466
3467
3468
3469
3470
3471
3472
3473
3474
3475
3476
3477
3478
3479
3480
3481
3482
3483
3484
3485
3486
3487
3488
3489
3490
3491
3492
3493
3494
3495
3496
3497
3498
3499
3500
3501
let USER_AGENT: string// @ts-ignoreif (typeof navigator === 'undefined' || !navigator.userAgent?.startsWith?.('Mozilla/5.0 ')) { const NAME = 'oauth4webapi' const VERSION = 'v1.2.2' USER_AGENT = `${NAME}/${VERSION}`}
/** @ignore */export type JsonObject = { [Key in string]?: JsonValue }/** @ignore */export type JsonArray = JsonValue[]/** @ignore */export type JsonPrimitive = string | number | boolean | null/** @ignore */export 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` JWS Algorithm Identifier * * ```ts * interface Ps256Algorithm extends RsaHashedKeyAlgorithm { * name: 'RSA-PSS' * hash: { name: 'SHA-256' } * } * ``` * * @example CryptoKey algorithm for the `ES256` JWS Algorithm Identifier * * ```ts * interface Es256Algorithm extends EcKeyAlgorithm { * name: 'ECDSA' * namedCurve: 'P-256' * } * ``` * * @example CryptoKey algorithm for the `RS256` JWS Algorithm Identifier * * ```ts * interface Rs256Algorithm extends RsaHashedKeyAlgorithm { * name: 'RSASSA-PKCS1-v1_5' * hash: { name: 'SHA-256' } * } * ``` * * @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 EdDSAAlgorithm extends KeyAlgorithm { * name: 'Ed25519' * } * ``` */export type JWSAlgorithm = 'PS256' | 'ES256' | 'RS256' | 'EdDSA'
/** * JSON Web Key * * @ignore */export interface JWK { /** Key Type */ readonly kty?: string /** Key ID */ readonly kid?: string /** Algorithm */ readonly alg?: string /** Public Key Use */ readonly use?: string /** Key Operations */ readonly key_ops?: string[] /** (RSA) Exponent */ readonly e?: string /** (RSA) Modulus */ readonly n?: string /** * (EC) Curve * * (OKP) The subtype of key pair */ readonly crv?: string /** * (EC) X Coordinate * * (OKP) The public key */ readonly x?: string /** (EC) Y Coordinate */ readonly y?: string readonly [parameter: string]: JsonValue | undefined}
/** * 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 {@link JWSAlgorithm supported 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?: JWSAlgorithm /** * 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 {@link JWSAlgorithm supported 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?: JWSAlgorithm /** * JWS `alg` algorithm REQUIRED for signed introspection responses. When not configured the * default is to allow only {@link JWSAlgorithm supported 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?: JWSAlgorithm /** Default Maximum Authentication Age. */ default_max_age?: number [metadata: string]: JsonValue | undefined}
const encoder = new TextEncoder()const decoder = new TextDecoder()
function buf(input: string): Uint8Arrayfunction buf(input: Uint8Array): stringfunction buf(input: string | Uint8Array) { if (typeof input === 'string') { return encoder.encode(input) } return decoder.decode(input)}
const CHUNK_SIZE = 0x8000function 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): Uint8Arrayfunction b64u(input: Uint8Array | ArrayBuffer): stringfunction 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', '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 preserveBodyStream(response: Response) { assertReadableResponse(response) return response.clone()}
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') } let json: JsonValue try { json = await preserveBodyStream(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. */function formUrlEncode(token: string) { return encodeURIComponent(token).replace(/%20/g, '+')}
/** * Formats client_id and client_secret as an HTTP Basic Authentication header as per the OAuth 2.0 * specified in RFC6749. */function clientSecretBasic(clientId: string, clientSecret: string) { const username = formUrlEncode(clientId) const password = formUrlEncode(clientSecret) const credentials = btoa(`${username}:${password}`) return `Basic ${credentials}`}
/** Determines an RSASSA-PSS algorithm identifier from CryptoKey instance properties. */function psAlg(key: CryptoKey): JWSAlgorithm { switch ((<RsaHashedKeyAlgorithm>key.algorithm).hash.name) { case 'SHA-256': return 'PS256' default: throw new UnsupportedOperationError('unsupported RsaHashedKeyAlgorithm hash name') }}
/** Determines an RSASSA-PKCS1-v1_5 algorithm identifier from CryptoKey instance properties. */function rsAlg(key: CryptoKey): JWSAlgorithm { switch ((<RsaHashedKeyAlgorithm>key.algorithm).hash.name) { case 'SHA-256': return 'RS256' default: throw new UnsupportedOperationError('unsupported RsaHashedKeyAlgorithm hash name') }}
/** Determines an ECDSA algorithm identifier from CryptoKey instance properties. */function esAlg(key: CryptoKey): JWSAlgorithm { switch ((<EcKeyAlgorithm>key.algorithm).namedCurve) { case 'P-256': return 'ES256' default: throw new UnsupportedOperationError('unsupported EcKeyAlgorithm namedCurve') }}
/** Determines a supported JWS `alg` identifier from CryptoKey instance properties. */function determineJWSAlgorithm(key: CryptoKey) { switch (key.algorithm.name) { case 'RSA-PSS': return psAlg(key) case 'RSASSA-PKCS1-v1_5': return rsAlg(key) case 'ECDSA': return esAlg(key) case 'Ed25519': return 'EdDSA' default: throw new UnsupportedOperationError('unsupported CryptoKey algorithm name') }}
/** Returns the current unix timestamp in seconds. */function epochTime() { return Math.floor(Date.now() / 1000)}
function clientAssertion(as: AuthorizationServer, client: Client) { const now = epochTime() return { jti: randomBytes(), aud: [as.issuer, as.token_endpoint], exp: now + 60, iat: now, nbf: now, iss: client.client_id, sub: client.client_id, }}
/** Generates a unique client assertion to be used in `private_key_jwt` authenticated requests. */async function privateKeyJwt( as: AuthorizationServer, client: Client, key: CryptoKey, kid?: string,) { return jwt( { alg: determineJWSAlgorithm(key), kid, }, clientAssertion(as, client), key, )}
function assertAs(as: AuthorizationServer): as is AuthorizationServer { if (typeof as !== 'object' || as === null) { throw new TypeError('"as" must be an object') } if (!validateString(as.issuer)) { throw new TypeError('"as.issuer" property must be a non-empty string') } return true}
function assertClient(client: Client): client is Client { if (typeof client !== 'object' || client === null) { throw new TypeError('"client" must be an object') } if (!validateString(client.client_id)) { throw new TypeError('"client.client_id" property must be a non-empty string') } return true}
function assertClientSecret(clientSecret: unknown) { if (!validateString(clientSecret)) { throw new TypeError('"client.client_secret" property must be a non-empty string') } return clientSecret}
function assertNoClientPrivateKey(clientAuthMethod: string, clientPrivateKey: unknown) { if (clientPrivateKey !== undefined) { throw new TypeError( `"options.clientPrivateKey" property must not be provided when ${clientAuthMethod} client authentication method is used.`, ) }}
function assertNoClientSecret(clientAuthMethod: string, clientSecret: unknown) { if (clientSecret !== undefined) { throw new TypeError( `"client.client_secret" property must not be provided when ${clientAuthMethod} client authentication method is used.`, ) }}
/** * Applies supported client authentication to an URLSearchParams instance representing the request * body and/or a Headers instance to be sent with an authenticated request. */async function clientAuthentication( as: AuthorizationServer, client: Client, body: URLSearchParams, headers: Headers, clientPrivateKey?: CryptoKey | PrivateKey,) { body.delete('client_secret') body.delete('client_assertion_type') body.delete('client_assertion') switch (client.token_endpoint_auth_method) { case undefined: // Fall through case 'client_secret_basic': { assertNoClientPrivateKey('client_secret_basic', clientPrivateKey) headers.set( 'authorization', clientSecretBasic(client.client_id, assertClientSecret(client.client_secret)), ) break } case 'client_secret_post': { assertNoClientPrivateKey('client_secret_post', clientPrivateKey) body.set('client_id', client.client_id) body.set('client_secret', assertClientSecret(client.client_secret)) break } case 'private_key_jwt': { assertNoClientSecret('private_key_jwt', client.client_secret) if (clientPrivateKey === undefined) { throw new TypeError( '"options.clientPrivateKey" must be provided when "client.token_endpoint_auth_method" is "private_key_jwt"', ) } const { key, kid } = getKeyAndKid(clientPrivateKey) if (!isPrivateKey(key)) { throw new TypeError('"options.clientPrivateKey.key" must be a private CryptoKey') } body.set('client_id', client.client_id) body.set('client_assertion_type', 'urn:ietf:params:oauth:client-assertion-type:jwt-bearer') body.set('client_assertion', await privateKeyJwt(as, client, key, kid)) break } case 'none': { assertNoClientSecret('none', client.client_secret) assertNoClientPrivateKey('none', clientPrivateKey) body.set('client_id', client.client_id) break } default: throw new UnsupportedOperationError('unsupported client token_endpoint_auth_method') }}
/** Minimal JWT sign() implementation. */async function jwt( header: CompactJWSHeaderParameters, claimsSet: Record<string, unknown>, key: CryptoKey,) { if (!key.usages.includes('sign')) { throw new TypeError( 'CryptoKey instances used for signing assertions must include "sign" in their "usages"', ) } const input = `${b64u(buf(JSON.stringify(header)))}.${b64u(buf(JSON.stringify(claimsSet)))}` const signature = b64u(await crypto.subtle.sign(subtleAlgorithm(key), key, buf(input))) return `${input}.${signature}`}
/** * Generates a signed JWT-Secured Authorization Request (JAR). * * @param as Authorization Server Metadata. * @param client Client Metadata. * @param privateKey Private key to sign the Request Object with. * * @see [RFC 9101 - The OAuth 2.0 Authorization Framework: JWT-Secured Authorization Request (JAR)](https://www.rfc-editor.org/rfc/rfc9101.html#name-request-object-2) */export async function issueRequestObject( as: AuthorizationServer, client: Client, parameters: URLSearchParams, privateKey: CryptoKey | PrivateKey,) { assertAs(as) assertClient(client) if (!(parameters instanceof URLSearchParams)) { throw new TypeError('"parameters" must be an instance of URLSearchParams') } parameters = new URLSearchParams(parameters) const { key, kid } = getKeyAndKid(privateKey) if (!isPrivateKey(key)) { throw new TypeError('"privateKey.key" must be a private CryptoKey') } parameters.set('client_id', client.client_id) const now = epochTime() const claims: Record<string, unknown> = { ...Object.fromEntries(parameters.entries()), jti: randomBytes(), aud: as.issuer, exp: now + 60, iat: now, nbf: now, iss: client.client_id, } let resource: string[] if ( parameters.has('resource') && (resource = parameters.getAll('resource')) && resource.length > 1 ) { claims.resource = resource } return jwt( { alg: determineJWSAlgorithm(key), typ: 'oauth-authz-req+jwt', kid, }, claims, key, )}
/** Generates a unique DPoP Proof JWT */async function dpopProofJwt( headers: Headers, options: DPoPOptions, url: URL, htm: string, accessToken?: string,) { const { privateKey, publicKey, nonce = dpopNonces.get(url.origin) } = options if (!isPrivateKey(privateKey)) { throw new TypeError('"DPoP.privateKey" must be a private CryptoKey') } if (!isPublicKey(publicKey)) { throw new TypeError('"DPoP.publicKey" must be a public CryptoKey') } if (nonce !== undefined && !validateString(nonce)) { throw new TypeError('"DPoP.nonce" must be a non-empty string or undefined') } if (!publicKey.extractable) { throw new TypeError('"DPoP.publicKey.extractable" must be true') } const now = epochTime() const proof = await jwt( { alg: determineJWSAlgorithm(privateKey), typ: 'dpop+jwt', jwk: await publicJwk(publicKey), }, { iat: now, jti: randomBytes(), htm, nonce, htu: `${url.origin}${url.pathname}`, ath: accessToken ? b64u(await crypto.subtle.digest({ name: 'SHA-256' }, buf(accessToken))) : undefined, }, privateKey, ) headers.set('dpop', proof)}
/** Exports an asymmetric crypto key as bare JWK */async function publicJwk(key: CryptoKey) { const { kty, e, n, x, y, crv } = await crypto.subtle.exportKey('jwk', key) return { kty, crv, e, n, x, y }}
/** * Performs a Pushed Authorization Request at the * {@link AuthorizationServer.pushed_authorization_request_endpoint `as.pushed_authorization_request_endpoint`}. * * @param as Authorization Server Metadata. * @param client Client Metadata. * @param parameters Authorization Request parameters. * * @see [RFC 9126 - OAuth 2.0 Pushed Authorization Requests](https://www.rfc-editor.org/rfc/rfc9126.html#name-pushed-authorization-reques) * @see [draft-ietf-oauth-dpop-10 - OAuth 2.0 Demonstrating Proof-of-Possession at the Application Layer (DPoP)](https://www.ietf.org/archive/id/draft-ietf-oauth-dpop-10.html#name-dpop-with-pushed-authorizat) */export async function pushedAuthorizationRequest( as: AuthorizationServer, client: Client, parameters: URLSearchParams, options?: PushedAuthorizationRequestOptions,): Promise<Response> { assertAs(as) assertClient(client) if (!(parameters instanceof URLSearchParams)) { throw new TypeError('"parameters" must be an instance of URLSearchParams') } if (typeof as.pushed_authorization_request_endpoint !== 'string') { throw new TypeError('"as.pushed_authorization_request_endpoint" must be a string') } const url = new URL(as.pushed_authorization_request_endpoint) const body = new URLSearchParams(parameters) body.set('client_id', client.client_id) const headers = prepareHeaders(options?.headers) headers.set('accept', 'application/json') if (options?.DPoP !== undefined) { await dpopProofJwt(headers, options.DPoP, url, 'POST') if (!body.has('dpop_jkt')) { body.set('dpop_jkt', await calculateJwkThumbprint(options.DPoP.publicKey)) } } return authenticatedRequest(as, client, 'POST', url, body, headers, options)}
export interface PushedAuthorizationResponse { readonly request_uri: string readonly expires_in: number readonly [parameter: string]: JsonValue | undefined}
export interface OAuth2Error { readonly error: string readonly error_description?: string readonly error_uri?: string readonly algs?: string readonly scope?: string readonly [parameter: string]: JsonValue | undefined}
/** A helper function used to determine if a response processing function returned an OAuth2Error. */export function isOAuth2Error(input?: ReturnTypes): input is OAuth2Error { const value = <unknown>input if (typeof value !== 'object' || Array.isArray(value) || value === null) { return false } // @ts-expect-error return value.error !== undefined}
export interface WWWAuthenticateChallenge { /** NOTE: because the value is case insensitive it is always returned lowercased */ readonly scheme: string readonly parameters: { readonly realm?: string readonly error?: string readonly error_description?: string readonly error_uri?: string readonly algs?: string readonly scope?: string /** NOTE: because the parameter names are case insensitive they are always returned lowercased */ readonly [parameter: string]: string | undefined }}
function unquote(value: string) { if (value.length >= 2 && value[0] === '"' && value[value.length - 1] === '"') { return value.slice(1, -1) } return value}
const SPLIT_REGEXP = /((?:,|, )?[0-9a-zA-Z!#$%&'*+-.^_`|~]+=)/const SCHEMES_REGEXP = /(?:^|, ?)([0-9a-zA-Z!#$%&'*+\-.^_`|~]+)(?=$|[ ,])/g
function wwwAuth(scheme: string, params: string): WWWAuthenticateChallenge { const arr = params.split(SPLIT_REGEXP).slice(1) if (!arr.length) { return { scheme: scheme.toLowerCase(), parameters: {} } } arr[arr.length - 1] = arr[arr.length - 1].replace(/,$/, '') const parameters: WWWAuthenticateChallenge['parameters'] = {} for (let i = 1; i < arr.length; i += 2) { const idx = i if (arr[idx][0] === '"') { while (arr[idx].slice(-1) !== '"' && ++i < arr.length) { arr[idx] += arr[i] } } const key = arr[idx - 1].replace(/^(?:, ?)|=$/g, '').toLowerCase() // @ts-expect-error parameters[key] = unquote(arr[idx]) } return { scheme: scheme.toLowerCase(), parameters, }}
/** * Parses the `WWW-Authenticate` HTTP Header from a Response instance. * * @returns Array of {@link WWWAuthenticateChallenge} objects. Their order from the response is * preserved. `undefined` when there wasn't a `WWW-Authenticate` HTTP Header returned. */export function parseWwwAuthenticateChallenges( response: Response,): WWWAuthenticateChallenge[] | undefined { if (!(response instanceof Response)) { throw new TypeError('"response" must be an instance of Response') } if (!response.headers.has('www-authenticate')) { return undefined } const header = response.headers.get('www-authenticate')! const result: [string, number][] = [] for (const { 1: scheme, index } of header.matchAll(SCHEMES_REGEXP)) { result.push([scheme, index!]) } if (!result.length) { return undefined } const challenges = result.map(([scheme, indexOf], i, others) => { const next = others[i + 1] let parameters: string if (next) { parameters = header.slice(indexOf, next[1]) } else { parameters = header.slice(indexOf) } return wwwAuth(scheme, parameters) }) return challenges}
/** * Validates Response instance to be one coming from the * {@link AuthorizationServer.pushed_authorization_request_endpoint `as.pushed_authorization_request_endpoint`}. * * @param as Authorization Server Metadata. * @param client Client Metadata. * @param response Resolved value from {@link pushedAuthorizationRequest}. * * @returns Resolves with an object representing the parsed successful response, or an object * representing an OAuth 2.0 protocol style error. Use {@link isOAuth2Error} to determine if an * OAuth 2.0 error was returned. * @see [RFC 9126 - OAuth 2.0 Pushed Authorization Requests](https://www.rfc-editor.org/rfc/rfc9126.html#name-pushed-authorization-reques) */export async function processPushedAuthorizationResponse( as: AuthorizationServer, client: Client, response: Response,): Promise<PushedAuthorizationResponse | OAuth2Error> { assertAs(as) assertClient(client) if (!(response instanceof Response)) { throw new TypeError('"response" must be an instance of Response') } if (response.status !== 201) { let err: OAuth2Error | undefined if ((err = await handleOAuthBodyError(response))) { return err } throw new OPE('"response" is not a conform Pushed Authorization Request Endpoint response') } let json: JsonValue try { json = await preserveBodyStream(response).json() } catch { throw new OPE('failed to parse "response" body as JSON') } if (!isJsonObject<PushedAuthorizationResponse>(json)) { throw new OPE('"response" body must be a top level object') } if (!validateString(json.request_uri)) { throw new OPE('"response" body "request_uri" property must be a non-empty string') } if (typeof json.expires_in !== 'number' || json.expires_in <= 0) { throw new OPE('"response" body "expires_in" property must be a positive number') } return json}
export interface ProtectedResourceRequestOptions extends Omit<HttpRequestOptions, 'headers'>, DPoPRequestOptions {}/** * Performs a protected resource request at an arbitrary URL. * * Authorization Header is used to transmit the Access Token value. * * @param accessToken The Access Token for the request. * @param method The HTTP method for the request. * @param url Target URL for the request. * @param headers Headers for the request. * @param body Request body compatible with the Fetch API and the request's method. * * @see [RFC 6750 - The OAuth 2.0 Authorization Framework: Bearer Token Usage](https://www.rfc-editor.org/rfc/rfc6750.html#section-2.1) * @see [draft-ietf-oauth-dpop-10 - OAuth 2.0 Demonstrating Proof-of-Possession at the Application Layer (DPoP)](https://www.ietf.org/archive/id/draft-ietf-oauth-dpop-10.html#name-protected-resource-access) */export async function protectedResourceRequest( accessToken: string, method: 'GET' | 'POST' | 'PUT' | 'DELETE' | 'PATCH' | string, url: URL, headers: Headers, body: RequestInit['body'], options?: ProtectedResourceRequestOptions,): Promise<Response> { if (!validateString(accessToken)) { throw new TypeError('"accessToken" must be a non-empty string') } if (!(url instanceof URL)) { throw new TypeError('"url" must be an instance of URL') } headers = prepareHeaders(headers) if (options?.DPoP === undefined) { headers.set('authorization', `Bearer ${accessToken}`) } else { await dpopProofJwt(headers, options.DPoP, url, 'GET', accessToken) headers.set('authorization', `DPoP ${accessToken}`) } return fetch(url.href, { body, headers, method, redirect: 'manual', signal: options?.signal ? signal(options.signal) : null, }).then(processDpopNonce)}
export interface UserInfoRequestOptions extends HttpRequestOptions, DPoPRequestOptions {}
/** * Performs a UserInfo Request at the * {@link AuthorizationServer.userinfo_endpoint `as.userinfo_endpoint`}. * * Authorization Header is used to transmit the Access Token value. * * @param as Authorization Server Metadata. * @param client Client Metadata. * @param accessToken Access Token value. * * @see [OpenID Connect Core 1.0](https://openid.net/specs/openid-connect-core-1_0.html#UserInfo) * @see [draft-ietf-oauth-dpop-10 - OAuth 2.0 Demonstrating Proof-of-Possession at the Application Layer (DPoP)](https://www.ietf.org/archive/id/draft-ietf-oauth-dpop-10.html#name-protected-resource-access) */export async function userInfoRequest( as: AuthorizationServer, client: Client, accessToken: string, options?: UserInfoRequestOptions,): Promise<Response> { assertAs(as) assertClient(client) if (typeof as.userinfo_endpoint !== 'string') { throw new TypeError('"as.userinfo_endpoint" must be a string') } const url = new URL(as.userinfo_endpoint) const headers = prepareHeaders(options?.headers) if (client.userinfo_signed_response_alg) { headers.set('accept', 'application/jwt') } else { headers.set('accept', 'application/json') headers.append('accept', 'application/jwt') } return protectedResourceRequest(accessToken, 'GET', url, headers, null, options)}
export interface UserInfoResponse { readonly sub: string readonly name?: string readonly given_name?: string readonly family_name?: string readonly middle_name?: string readonly nickname?: string readonly preferred_username?: string readonly profile?: string readonly picture?: string readonly website?: string readonly email?: string readonly email_verified?: boolean readonly gender?: string readonly birthdate?: string readonly zoneinfo?: string readonly locale?: string readonly phone_number?: string readonly updated_at?: number readonly address?: { readonly formatted?: string readonly street_address?: string readonly locality?: string readonly region?: string readonly postal_code?: string readonly country?: string } readonly [claim: string]: JsonValue | undefined}
const jwksCache = new LRU<string, { jwks: JsonWebKeySet; iat: number; age: number }>(20)const cryptoKeyCaches: Record<string, WeakMap<JWK, CryptoKey>> = {}
async function getPublicSigKeyFromIssuerJwksUri( as: AuthorizationServer, options: HttpRequestOptions | undefined, header: CompactJWSHeaderParameters,): Promise<CryptoKey> { const { alg, kid } = header checkSupportedJwsAlg(alg) let jwks: JsonWebKeySet let age: number if (jwksCache.has(as.jwks_uri!)) { ;({ jwks, age } = jwksCache.get(as.jwks_uri!)!) if (age >= 300) { // force a re-fetch every 5 minutes jwksCache.delete(as.jwks_uri!) return getPublicSigKeyFromIssuerJwksUri(as, options, header) } } else { jwks = await jwksRequest(as, options).then(processJwksResponse) age = 0 jwksCache.set(as.jwks_uri!, { jwks, iat: epochTime(), get age() { return epochTime() - this.iat }, }) } let kty: string switch (alg.slice(0, 2)) { case 'RS': // Fall through case 'PS': kty = 'RSA' break case 'ES': kty = 'EC' break case 'Ed': kty = 'OKP' break default: throw new UnsupportedOperationError() } const candidates = jwks.keys.filter((jwk) => { // filter keys based on the mapping of signature algorithms to Key Type if (jwk.kty !== kty) { return false } // filter keys based on the JWK Key ID in the header if (kid !== undefined && kid !== jwk.kid) { return false } // filter keys based on the key's declared Algorithm if (jwk.alg !== undefined && alg !== jwk.alg) { return false } // filter keys based on the key's declared Public Key Use if (jwk.use !== undefined && jwk.use !== 'sig') { return false } // filter keys based on the key's declared Key Operations if (jwk.key_ops?.includes('verify') === false) { return false } // filter keys based on alg-specific key requirements switch (true) { case alg === 'ES256' && jwk.crv !== 'P-256': // Fall through case alg === 'EdDSA' && jwk.crv !== 'Ed25519': return false } return true }) const { 0: jwk, length } = candidates if (!length) { if (age >= 60) { // allow re-fetch if cache is at least 1 minute old jwksCache.delete(as.jwks_uri!) return getPublicSigKeyFromIssuerJwksUri(as, options, header) } throw new OPE('error when selecting a JWT verification key, no applicable keys found') } else if (length !== 1) { throw new OPE( 'error when selecting a JWT verification key, multiple applicable keys found, a "kid" JWT Header Parameter is required', ) } cryptoKeyCaches[alg] ||= new WeakMap() let key = cryptoKeyCaches[alg].get(jwk) if (!key) { key = await importJwk({ ...jwk, alg }) if (key.type !== 'public') { throw new OPE('jwks_uri must only contain public keys') } cryptoKeyCaches[alg].set(jwk, key) } return key}
/** * DANGER ZONE * * Use this as a value to {@link processUserInfoResponse} `expectedSubject` parameter to skip the * `sub` claim value check. * * @see [OpenID Connect Core 1.0](https://openid.net/specs/openid-connect-core-1_0.html#UserInfoResponse) */export const skipSubjectCheck = Symbol()
function getContentType(response: Response) { return response.headers.get('content-type')?.split(';')[0]}
/** * Validates Response instance to be one coming from the * {@link AuthorizationServer.userinfo_endpoint `as.userinfo_endpoint`}. * * @param as Authorization Server Metadata. * @param client Client Metadata. * @param expectedSubject Expected `sub` claim value. In response to OpenID Connect authentication * requests, the expected subject is the one from the ID Token claims retrieved from * {@link getValidatedIdTokenClaims}. * @param response Resolved value from {@link userInfoRequest}. * * @returns Resolves with an object representing the parsed successful response, or an object * representing an OAuth 2.0 protocol style error. Use {@link isOAuth2Error} to determine if an * OAuth 2.0 error was returned. * @see [OpenID Connect Core 1.0](https://openid.net/specs/openid-connect-core-1_0.html#UserInfo) */export async function processUserInfoResponse( as: AuthorizationServer, client: Client, expectedSubject: string | typeof skipSubjectCheck, response: Response, options?: HttpRequestOptions,): Promise<UserInfoResponse> { assertAs(as) assertClient(client) 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 UserInfo Endpoint response') } let json: JsonValue if (getContentType(response) === 'application/jwt') { if (typeof as.jwks_uri !== 'string') { throw new TypeError('"as.jwks_uri" must be a string') } const { claims } = await validateJwt( await preserveBodyStream(response).text(), checkSigningAlgorithm.bind( undefined, client.userinfo_signed_response_alg, as.userinfo_signing_alg_values_supported, ), getPublicSigKeyFromIssuerJwksUri.bind(undefined, as, options), ) .then(validateOptionalAudience.bind(undefined, client.client_id)) .then(validateOptionalIssuer.bind(undefined, as.issuer)) json = <JsonValue>claims } else { if (client.userinfo_signed_response_alg) { throw new OPE('JWT UserInfo Response expected') } try { json = await preserveBodyStream(response).json() } catch { throw new OPE('failed to parse "response" body as JSON') } } if (!isJsonObject<UserInfoResponse>(json)) { throw new OPE('"response" body must be a top level object') } if (!validateString(json.sub)) { throw new OPE('"response" body "sub" property must be a non-empty string') } switch (expectedSubject) { case skipSubjectCheck: break default: if (!validateString(expectedSubject)) { throw new OPE('"expectedSubject" must be a non-empty string') } if (json.sub !== expectedSubject) { throw new OPE('unexpected "response" body "sub" value') } } return json}
function padded(buf: Uint8Array, length: number) { const out = new Uint8Array(length) out.set(buf) return out}
function timingSafeEqual(a: Uint8Array, b: Uint8Array) { const len = Math.max(a.byteLength, b.byteLength) a = padded(a, len) b = padded(b, len) let out = 0 let i = -1 while (++i < len) { out |= a[i] ^ b[i] } return out === 0}
async function idTokenHash(alg: JWSAlgorithm, data: string) { let algorithm: Algorithm switch (alg) { case 'RS256': // Fall through case 'PS256': // Fall through case 'ES256': algorithm = { name: 'SHA-256' } break case 'EdDSA': algorithm = { name: 'SHA-512' } break default: throw new UnsupportedOperationError() } const digest = await crypto.subtle.digest(algorithm, buf(data)) return b64u(digest.slice(0, digest.byteLength / 2))}
async function idTokenHashMatches(alg: JWSAlgorithm, data: string, actual: string) { const expected = await idTokenHash(alg, data) return timingSafeEqual(buf(actual), buf(expected))}
async function authenticatedRequest( as: AuthorizationServer, client: Client, method: string, url: URL, body: URLSearchParams, headers: Headers, options?: Omit<HttpRequestOptions, 'headers'> & AuthenticatedRequestOptions,) { await clientAuthentication(as, client, body, headers, options?.clientPrivateKey) return fetch(url.href, { body, headers, method, redirect: 'manual', signal: options?.signal ? signal(options.signal) : null, }).then(processDpopNonce)}
export interface TokenEndpointRequestOptions extends HttpRequestOptions, AuthenticatedRequestOptions, DPoPRequestOptions { /** Any additional parameters to send. This cannot override existing parameter values. */ additionalParameters?: URLSearchParams}
async function tokenEndpointRequest( as: AuthorizationServer, client: Client, grantType: string, parameters: URLSearchParams, options?: Omit<TokenEndpointRequestOptions, 'additionalParameters'>,): Promise<Response> { if (typeof as.token_endpoint !== 'string') { throw new TypeError('"as.token_endpoint" must be a string') } const url = new URL(as.token_endpoint) parameters.set('grant_type', grantType) const headers = prepareHeaders(options?.headers) headers.set('accept', 'application/json') if (options?.DPoP !== undefined) { await dpopProofJwt(headers, options.DPoP, url, 'POST') } return authenticatedRequest(as, client, 'POST', url, parameters, headers, options)}
/** * Performs a Refresh Token Grant request at the * {@link AuthorizationServer.token_endpoint `as.token_endpoint`}. * * @param as Authorization Server Metadata. * @param client Client Metadata. * @param refreshToken Refresh Token value. * * @see [RFC 6749 - The OAuth 2.0 Authorization Framework](https://www.rfc-editor.org/rfc/rfc6749.html#section-6) * @see [OpenID Connect Core 1.0](https://openid.net/specs/openid-connect-core-1_0.html#RefreshTokens) * @see [draft-ietf-oauth-dpop-10 - OAuth 2.0 Demonstrating Proof-of-Possession at the Application Layer (DPoP)](https://www.ietf.org/archive/id/draft-ietf-oauth-dpop-10.html#name-dpop-access-token-request) */export async function refreshTokenGrantRequest( as: AuthorizationServer, client: Client, refreshToken: string, options?: TokenEndpointRequestOptions,): Promise<Response> { assertAs(as) assertClient(client) if (!validateString(refreshToken)) { throw new TypeError('"refreshToken" must be a non-empty string') } const parameters = new URLSearchParams(options?.additionalParameters) parameters.set('refresh_token', refreshToken) return tokenEndpointRequest(as, client, 'refresh_token', parameters, options)}
const idTokenClaims = new WeakMap<TokenEndpointResponse, IDToken>()
/** * Returns ID Token claims validated during {@link processAuthorizationCodeOpenIDResponse}. * * @param ref Value previously resolved from {@link processAuthorizationCodeOpenIDResponse}. * * @returns JWT Claims Set from an ID Token. */export function getValidatedIdTokenClaims(ref: OpenIDTokenEndpointResponse): IDToken
/** * Returns ID Token claims validated during {@link processRefreshTokenResponse} or * {@link processDeviceCodeResponse}. * * @param ref Value previously resolved from {@link processRefreshTokenResponse} or * {@link processDeviceCodeResponse}. * * @returns JWT Claims Set from an ID Token, or undefined if there is no ID Token in `ref`. */export function getValidatedIdTokenClaims(ref: TokenEndpointResponse): IDToken | undefinedexport function getValidatedIdTokenClaims( ref: OpenIDTokenEndpointResponse | TokenEndpointResponse,): IDToken | undefined { if (!idTokenClaims.has(ref)) { throw new TypeError( '"ref" was already garbage collected or did not resolve from the proper sources', ) } return idTokenClaims.get(ref)}
async function processGenericAccessTokenResponse( as: AuthorizationServer, client: Client, response: Response, options?: HttpRequestOptions, ignoreIdToken = false, ignoreRefreshToken = false,): Promise<TokenEndpointResponse | OAuth2Error> { assertAs(as) assertClient(client) if (!(response instanceof Response)) { throw new TypeError('"response" must be an instance of Response') } if (response.status !== 200) { let err: OAuth2Error | undefined if ((err = await handleOAuthBodyError(response))) { return err } throw new OPE('"response" is not a conform Token Endpoint response') } let json: JsonValue try { json = await preserveBodyStream(response).json() } catch { throw new OPE('failed to parse "response" body as JSON') } if (!isJsonObject<TokenEndpointResponse>(json)) { throw new OPE('"response" body must be a top level object') } if (!validateString(json.access_token)) { throw new OPE('"response" body "access_token" property must be a non-empty string') } if (!validateString(json.token_type)) { throw new OPE('"response" body "token_type" property must be a non-empty string') } // @ts-expect-error json.token_type = json.token_type.toLowerCase() if (json.token_type !== 'dpop' && json.token_type !== 'bearer') { throw new UnsupportedOperationError('unsupported `token_type` value') } if ( json.expires_in !== undefined && (typeof json.expires_in !== 'number' || json.expires_in <= 0) ) { throw new OPE('"response" body "expires_in" property must be a positive number') } if ( !ignoreRefreshToken && json.refresh_token !== undefined && !validateString(json.refresh_token) ) { throw new OPE('"response" body "refresh_token" property must be a non-empty string') } if (json.scope !== undefined && typeof json.scope !== 'string') { throw new OPE('"response" body "scope" property must be a string') } if (!ignoreIdToken) { if (json.id_token !== undefined && !validateString(json.id_token)) { throw new OPE('"response" body "id_token" property must be a non-empty string') } if (json.id_token) { if (typeof as.jwks_uri !== 'string') { throw new TypeError('"as.jwks_uri" must be a string') } const { header, claims } = await validateJwt( json.id_token, checkSigningAlgorithm.bind( undefined, client.id_token_signed_response_alg, as.id_token_signing_alg_values_supported, ), getPublicSigKeyFromIssuerJwksUri.bind(undefined, as, options), ) .then(validatePresence.bind(undefined, ['aud', 'exp', 'iat', 'iss', 'sub'])) .then(validateIssuer.bind(undefined, as.issuer)) .then(validateAudience.bind(undefined, client.client_id)) if (Array.isArray(claims.aud) && claims.aud.length !== 1 && claims.azp !== client.client_id) { throw new OPE('unexpected ID Token "azp" (authorized party) claim value') } if (client.require_auth_time && typeof claims.auth_time !== 'number') { throw new OPE('unexpected ID Token "auth_time" (authentication time) claim value') } if (claims.at_hash !== undefined) { if ( typeof claims.at_hash !== 'string' || !(await idTokenHashMatches(header.alg, json.access_token, claims.at_hash)) ) { throw new OPE('unexpected ID Token "at_hash" (access token hash) claim value') } } idTokenClaims.set(json, <IDToken>claims) } } return json}
/** * Validates Refresh Token Grant Response instance to be one coming from the * {@link AuthorizationServer.token_endpoint `as.token_endpoint`}. * * @param as Authorization Server Metadata. * @param client Client Metadata. * @param response Resolved value from {@link refreshTokenGrantRequest}. * * @returns Resolves with an object representing the parsed successful response, or an object * representing an OAuth 2.0 protocol style error. Use {@link isOAuth2Error} to determine if an * OAuth 2.0 error was returned. * @see [RFC 6749 - The OAuth 2.0 Authorization Framework](https://www.rfc-editor.org/rfc/rfc6749.html#section-6) * @see [OpenID Connect Core 1.0](https://openid.net/specs/openid-connect-core-1_0.html#RefreshTokens) */export async function processRefreshTokenResponse( as: AuthorizationServer, client: Client, response: Response, options?: HttpRequestOptions,): Promise<TokenEndpointResponse | OAuth2Error> { return processGenericAccessTokenResponse(as, client, response, options)}
function validateOptionalAudience(expected: string, result: ParsedJWT) { if (result.claims.aud !== undefined) { return validateAudience(expected, result) } return result}
function validateAudience(expected: string, result: ParsedJWT) { if (Array.isArray(result.claims.aud)) { if (!result.claims.aud.includes(expected)) { throw new OPE('unexpected JWT "aud" (audience) claim value') } } else if (result.claims.aud !== expected) { throw new OPE('unexpected JWT "aud" (audience) claim value') } return result}
function validateOptionalIssuer(expected: string, result: ParsedJWT) { if (result.claims.iss !== undefined) { return validateIssuer(expected, result) } return result}
function validateIssuer(expected: string, result: ParsedJWT) { if (result.claims.iss !== expected) { throw new OPE('unexpected JWT "iss" (issuer) claim value') } return result}
/** * Performs an Authorization Code grant request at the * {@link AuthorizationServer.token_endpoint `as.token_endpoint`}. * * @param as Authorization Server Metadata. * @param client Client Metadata. * @param callbackParameters Parameters obtained from the callback to redirect_uri, this is returned * from {@link validateAuthResponse}, or {@link validateJwtAuthResponse}. * @param redirectUri `redirect_uri` value used in the authorization request. * @param codeVerifier PKCE `code_verifier` to send to the token endpoint. * * @see [RFC 6749 - The OAuth 2.0 Authorization Framework](https://www.rfc-editor.org/rfc/rfc6749.html#section-4.1) * @see [OpenID Connect Core 1.0](https://openid.net/specs/openid-connect-core-1_0.html#CodeFlowAuth) * @see [RFC 7636 - Proof Key for Code Exchange by OAuth Public Clients (PKCE)](https://www.rfc-editor.org/rfc/rfc7636.html#section-4) * @see [draft-ietf-oauth-dpop-10 - OAuth 2.0 Demonstrating Proof-of-Possession at the Application Layer (DPoP)](https://www.ietf.org/archive/id/draft-ietf-oauth-dpop-10.html#name-dpop-access-token-request) */export async function authorizationCodeGrantRequest( as: AuthorizationServer, client: Client, callbackParameters: CallbackParameters, redirectUri: string, codeVerifier: string, options?: TokenEndpointRequestOptions,): Promise<Response> { assertAs(as) assertClient(client) if (!(callbackParameters instanceof CallbackParameters)) { throw new TypeError( '"callbackParameters" must be an instance of CallbackParameters obtained from "validateAuthResponse()", or "validateJwtAuthResponse()', ) } if (!validateString(redirectUri)) { throw new TypeError('"redirectUri" must be a non-empty string') } if (!validateString(codeVerifier)) { throw new TypeError('"codeVerifier" must be a non-empty string') } const code = getURLSearchParameter(callbackParameters, 'code') if (!code) { throw new OPE('no authorization code in "callbackParameters"') } const parameters = new URLSearchParams(options?.additionalParameters) parameters.set('redirect_uri', redirectUri) parameters.set('code_verifier', codeVerifier) parameters.set('code', code) return tokenEndpointRequest(as, client, 'authorization_code', parameters, options)}
interface JWTPayload { readonly iss?: string readonly sub?: string readonly aud?: string | string[] readonly jti?: string readonly nbf?: number readonly exp?: number readonly iat?: number readonly [claim: string]: JsonValue | undefined}
export interface IDToken extends JWTPayload { readonly iss: string readonly sub: string readonly aud: string | string[] readonly iat: number readonly exp: number readonly nonce?: string readonly auth_time?: number readonly azp?: string}
interface CompactJWSHeaderParameters { alg: JWSAlgorithm kid?: string typ?: string crit?: string[] jwk?: JWK}
interface ParsedJWT { header: CompactJWSHeaderParameters claims: JWTPayload}
const claimNames = { aud: 'audience', exp: 'expiration time', iat: 'issued at', iss: 'issuer', sub: 'subject',}
function validatePresence(required: (keyof typeof claimNames)[], result: ParsedJWT) { for (const claim of required) { if (result.claims[claim] === undefined) { throw new OPE(`JWT "${claim}" (${claimNames[claim]}) claim missing`) } } return result}
export interface TokenEndpointResponse { readonly access_token: string readonly expires_in?: number readonly id_token?: string readonly refresh_token?: string readonly scope?: string /** NOTE: because the value is case insensitive it is always returned lowercased */ readonly token_type: string readonly [parameter: string]: JsonValue | undefined}
export interface OpenIDTokenEndpointResponse { readonly access_token: string readonly expires_in?: number readonly id_token: string readonly refresh_token?: string readonly scope?: string /** NOTE: because the value is case insensitive it is always returned lowercased */ readonly token_type: string readonly [parameter: string]: JsonValue | undefined}
export interface OAuth2TokenEndpointResponse { readonly access_token: string readonly expires_in?: number readonly id_token?: undefined readonly refresh_token?: string readonly scope?: string /** NOTE: because the value is case insensitive it is always returned lowercased */ readonly token_type: string readonly [parameter: string]: JsonValue | undefined}
export interface ClientCredentialsGrantResponse { readonly access_token: string readonly expires_in?: number readonly scope?: string /** NOTE: because the value is case insensitive it is always returned lowercased */ readonly token_type: string readonly [parameter: string]: JsonValue | undefined}
/** * Use this as a value to {@link processAuthorizationCodeOpenIDResponse} `expectedNonce` parameter to * indicate no `nonce` ID Token claim value is expected, i.e. no `nonce` parameter value was sent * with the authorization request. */export const expectNoNonce = Symbol()
/** * Use this as a value to {@link processAuthorizationCodeOpenIDResponse} `maxAge` parameter to * indicate no `auth_time` ID Token claim value check should be performed. */export const skipAuthTimeCheck = Symbol()
/** * (OpenID Connect only) Validates Authorization Code Grant Response instance to be one coming from * the {@link AuthorizationServer.token_endpoint `as.token_endpoint`}. * * @param as Authorization Server Metadata. * @param client Client Metadata. * @param response Resolved value from {@link authorizationCodeGrantRequest}. * @param expectedNonce Expected ID Token `nonce` claim value. Default is {@link expectNoNonce}. * @param maxAge ID Token {@link IDToken.auth_time `auth_time`} claim value will be checked to be * present and conform to the `maxAge` value. Use of this option is required if you sent a * `max_age` parameter in an authorization request. Default is * {@link Client.default_max_age `client.default_max_age`} and falls back to * {@link skipAuthTimeCheck}. * * @returns Resolves with an object representing the parsed successful response, or an object * representing an OAuth 2.0 protocol style error. Use {@link isOAuth2Error} to determine if an * OAuth 2.0 error was returned. * @see [RFC 6749 - The OAuth 2.0 Authorization Framework](https://www.rfc-editor.org/rfc/rfc6749.html#section-4.1) * @see [OpenID Connect Core 1.0](https://openid.net/specs/openid-connect-core-1_0.html#CodeFlowAuth) */export async function processAuthorizationCodeOpenIDResponse( as: AuthorizationServer, client: Client, response: Response, expectedNonce?: string | typeof expectNoNonce, maxAge?: number | typeof skipAuthTimeCheck, options?: HttpRequestOptions,): Promise<OpenIDTokenEndpointResponse | OAuth2Error> { const result = await processGenericAccessTokenResponse(as, client, response, options) if (isOAuth2Error(result)) { return result } if (!validateString(result.id_token)) { throw new OPE('"response" body "id_token" property must be a non-empty string') } maxAge ??= client.default_max_age ?? skipAuthTimeCheck const claims = getValidatedIdTokenClaims(result)! if ( (client.require_auth_time || maxAge !== skipAuthTimeCheck) && claims.auth_time === undefined ) { throw new OPE('ID Token "auth_time" (authentication time) claim missing') } if (maxAge !== skipAuthTimeCheck) { if (typeof maxAge !== 'number' || maxAge < 0) { throw new TypeError('"options.max_age" must be a non-negative number') } const now = epochTime() const tolerance = 30 if (claims.auth_time! + maxAge < now - tolerance) { throw new OPE('too much time has elapsed since the last End-User authentication') } } switch (expectedNonce) { case undefined: case expectNoNonce: if (claims.nonce !== undefined) { throw new OPE('unexpected ID Token "nonce" claim value') } break default: if (!validateString(expectedNonce)) { throw new TypeError('"expectedNonce" must be a non-empty string') } if (claims.nonce === undefined) { throw new OPE('ID Token "nonce" claim missing') } if (claims.nonce !== expectedNonce) { throw new OPE('unexpected ID Token "nonce" claim value') } } return <OpenIDTokenEndpointResponse>result}
/** * (OAuth 2.0 without OpenID Connect only) Validates Authorization Code Grant Response instance to * be one coming from the {@link AuthorizationServer.token_endpoint `as.token_endpoint`}. * * @param as Authorization Server Metadata. * @param client Client Metadata. * @param response Resolved value from {@link authorizationCodeGrantRequest}. * * @returns Resolves with an object representing the parsed successful response, or an object * representing an OAuth 2.0 protocol style error. Use {@link isOAuth2Error} to determine if an * OAuth 2.0 error was returned. * @see [RFC 6749 - The OAuth 2.0 Authorization Framework](https://www.rfc-editor.org/rfc/rfc6749.html#section-4.1) */export async function processAuthorizationCodeOAuth2Response( as: AuthorizationServer, client: Client, response: Response,): Promise<OAuth2TokenEndpointResponse | OAuth2Error> { const result = await processGenericAccessTokenResponse(as, client, response, undefined, true) if (isOAuth2Error(result)) { return result } if (result.id_token !== undefined) { if (typeof result.id_token === 'string' && result.id_token.length) { throw new OPE( 'Unexpected ID Token returned, use processAuthorizationCodeOpenIDResponse() for OpenID Connect callback processing', ) } // @ts-expect-error delete result.id_token } return <OAuth2TokenEndpointResponse>result}
function checkJwtType(expected: string, result: ParsedJWT) { if (typeof result.header.typ !== 'string' || normalizeTyp(result.header.typ) !== expected) { throw new OPE('unexpected JWT "typ" header parameter value') } return result}
export interface ClientCredentialsGrantRequestOptions extends HttpRequestOptions, AuthenticatedRequestOptions, DPoPRequestOptions {}/** * Performs a Client Credentials Grant request at the * {@link AuthorizationServer.token_endpoint `as.token_endpoint`}. * * @param as Authorization Server Metadata. * @param client Client Metadata. * * @see [RFC 6749 - The OAuth 2.0 Authorization Framework](https://www.rfc-editor.org/rfc/rfc6749.html#section-4.4) * @see [draft-ietf-oauth-dpop-10 - OAuth 2.0 Demonstrating Proof-of-Possession at the Application Layer (DPoP)](https://www.ietf.org/archive/id/draft-ietf-oauth-dpop-10.html#name-dpop-access-token-request) */export async function clientCredentialsGrantRequest( as: AuthorizationServer, client: Client, parameters: URLSearchParams, options?: ClientCredentialsGrantRequestOptions,): Promise<Response> { assertAs(as) assertClient(client) return tokenEndpointRequest( as, client, 'client_credentials', new URLSearchParams(parameters), options, )}
/** * Validates Client Credentials Grant Response instance to be one coming from the * {@link AuthorizationServer.token_endpoint `as.token_endpoint`}. * * @param as Authorization Server Metadata. * @param client Client Metadata. * @param response Resolved value from {@link clientCredentialsGrantRequest}. * * @returns Resolves with an object representing the parsed successful response, or an object * representing an OAuth 2.0 protocol style error. Use {@link isOAuth2Error} to determine if an * OAuth 2.0 error was returned. * @see [RFC 6749 - The OAuth 2.0 Authorization Framework](https://www.rfc-editor.org/rfc/rfc6749.html#section-4.4) */export async function processClientCredentialsResponse( as: AuthorizationServer, client: Client, response: Response,): Promise<ClientCredentialsGrantResponse | OAuth2Error> { const result = await processGenericAccessTokenResponse( as, client, response, undefined, true, true, ) if (isOAuth2Error(result)) { return result } return <ClientCredentialsGrantResponse>result}
export interface RevocationRequestOptions extends HttpRequestOptions, AuthenticatedRequestOptions { /** Any additional parameters to send. This cannot override existing parameter values. */ additionalParameters?: URLSearchParams}
/** * Performs a Revocation Request at the * {@link AuthorizationServer.revocation_endpoint `as.revocation_endpoint`}. * * @param as Authorization Server Metadata. * @param client Client Metadata. * @param token Token to revoke. You can provide the `token_type_hint` parameter via * {@link RevocationRequestOptions.additionalParameters options}. * @see [RFC 7009 - OAuth 2.0 Token Revocation](https://www.rfc-editor.org/rfc/rfc7009.html#section-2) */export async function revocationRequest( as: AuthorizationServer, client: Client, token: string, options?: RevocationRequestOptions,): Promise<Response> { assertAs(as) assertClient(client) if (!validateString(token)) { throw new TypeError('"token" must be a non-empty string') } if (typeof as.revocation_endpoint !== 'string') { throw new TypeError('"as.revocation_endpoint" must be a string') } const url = new URL(as.revocation_endpoint) const body = new URLSearchParams(options?.additionalParameters) body.set('token', token) const headers = prepareHeaders(options?.headers) headers.delete('accept') return authenticatedRequest(as, client, 'POST', url, body, headers, options)}
/** * Validates Response instance to be one coming from the * {@link AuthorizationServer.revocation_endpoint `as.revocation_endpoint`}. * * @param response Resolved value from {@link revocationRequest}. * * @returns Resolves with `undefined` when the request was successful, or an object representing an * OAuth 2.0 protocol style error. * @see [RFC 7009 - OAuth 2.0 Token Revocation](https://www.rfc-editor.org/rfc/rfc7009.html#section-2) */export async function processRevocationResponse( response: Response,): Promise<undefined | OAuth2Error> { if (!(response instanceof Response)) { throw new TypeError('"response" must be an instance of Response') } if (response.status !== 200) { let err: OAuth2Error | undefined if ((err = await handleOAuthBodyError(response))) { return err } throw new OPE('"response" is not a conform Revocation Endpoint response') } return undefined}
export interface IntrospectionRequestOptions extends HttpRequestOptions, AuthenticatedRequestOptions { /** Any additional parameters to send. This cannot override existing parameter values. */ additionalParameters?: URLSearchParams /** * Request a JWT Response from the * {@link AuthorizationServer.introspection_endpoint `as.introspection_endpoint`}. Default is * * - True when * {@link Client.introspection_signed_response_alg `client.introspection_signed_response_alg`} is * set * - False otherwise */ requestJwtResponse?: boolean}
function assertReadableResponse(response: Response) { if (response.bodyUsed) { throw new TypeError('"response" body has been used already') }}
/** * Performs an Introspection Request at the * {@link AuthorizationServer.introspection_endpoint `as.introspection_endpoint`}. * * @param as Authorization Server Metadata. * @param client Client Metadata. * @param token Token to introspect. You can provide the `token_type_hint` parameter via * {@link IntrospectionRequestOptions.additionalParameters options}. * @see [RFC 7662 - OAuth 2.0 Token Introspection](https://www.rfc-editor.org/rfc/rfc7662.html#section-2) * @see [draft-ietf-oauth-jwt-introspection-response-12 - JWT Response for OAuth Token Introspection](https://www.ietf.org/archive/id/draft-ietf-oauth-jwt-introspection-response-12.html#section-4) */export async function introspectionRequest( as: AuthorizationServer, client: Client, token: string, options?: IntrospectionRequestOptions,): Promise<Response> { assertAs(as) assertClient(client) if (!validateString(token)) { throw new TypeError('"token" must be a non-empty string') } if (typeof as.introspection_endpoint !== 'string') { throw new TypeError('"as.introspection_endpoint" must be a string') } const url = new URL(as.introspection_endpoint) const body = new URLSearchParams(options?.additionalParameters) body.set('token', token) const headers = prepareHeaders(options?.headers) if (options?.requestJwtResponse ?? client.introspection_signed_response_alg) { headers.set('accept', 'application/token-introspection+jwt') } else { headers.set('accept', 'application/json') } return authenticatedRequest(as, client, 'POST', url, body, headers, options)}
export interface IntrospectionResponse { readonly active: boolean readonly client_id?: string readonly exp?: number readonly iat?: number readonly sid?: string readonly iss?: string readonly jti?: string readonly username?: string readonly aud?: string | string[] readonly scope: string readonly sub?: string readonly nbf?: number readonly token_type?: string readonly cnf?: { readonly 'x5t#S256'?: string readonly jkt?: string readonly [claim: string]: JsonValue | undefined } readonly [claim: string]: JsonValue | undefined}
/** * Validates Response instance to be one coming from the * {@link AuthorizationServer.introspection_endpoint `as.introspection_endpoint`}. * * @param as Authorization Server Metadata. * @param client Client Metadata. * @param response Resolved value from {@link introspectionRequest}. * * @returns Resolves with an object representing the parsed successful response, or an object * representing an OAuth 2.0 protocol style error. Use {@link isOAuth2Error} to determine if an * OAuth 2.0 error was returned. * @see [RFC 7662 - OAuth 2.0 Token Introspection](https://www.rfc-editor.org/rfc/rfc7662.html#section-2) * @see [draft-ietf-oauth-jwt-introspection-response-12 - JWT Response for OAuth Token Introspection](https://www.ietf.org/archive/id/draft-ietf-oauth-jwt-introspection-response-12.html#section-5) */export async function processIntrospectionResponse( as: AuthorizationServer, client: Client, response: Response, options?: HttpRequestOptions,): Promise<IntrospectionResponse | OAuth2Error> { assertAs(as) assertClient(client) if (!(response instanceof Response)) { throw new TypeError('"response" must be an instance of Response') } if (response.status !== 200) { let err: OAuth2Error | undefined if ((err = await handleOAuthBodyError(response))) { return err } throw new OPE('"response" is not a conform Introspection Endpoint response') } let json: JsonValue if (getContentType(response) === 'application/token-introspection+jwt') { if (typeof as.jwks_uri !== 'string') { throw new TypeError('"as.jwks_uri" must be a string') } const { claims } = await validateJwt( await preserveBodyStream(response).text(), checkSigningAlgorithm.bind( undefined, client.introspection_signed_response_alg, as.introspection_signing_alg_values_supported, ), getPublicSigKeyFromIssuerJwksUri.bind(undefined, as, options), ) .then(checkJwtType.bind(undefined, 'token-introspection+jwt')) .then(validatePresence.bind(undefined, ['aud', 'iat', 'iss'])) .then(validateIssuer.bind(undefined, as.issuer)) .then(validateAudience.bind(undefined, client.client_id)) json = <JsonValue>claims.token_introspection if (!isJsonObject(json)) { throw new OPE('JWT "token_introspection" claim must be a JSON object') } } else { try { json = await preserveBodyStream(response).json() } catch { throw new OPE('failed to parse "response" body as JSON') } if (!isJsonObject(json)) { throw new OPE('"response" body must be a top level object') } } if (typeof json.active !== 'boolean') { throw new OPE('"response" body "active" property must be a boolean') } return <IntrospectionResponse>json}
/** @ignore */export interface JwksRequestOptions extends HttpRequestOptions {}
/** * Performs a request to the {@link AuthorizationServer.jwks_uri `as.jwks_uri`}. * * @ignore * * @param as Authorization Server Metadata. * * @see [JWK Set Format](https://www.rfc-editor.org/rfc/rfc7517.html#section-5) * @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 jwksRequest( as: AuthorizationServer, options?: JwksRequestOptions,): Promise<Response> { assertAs(as) if (typeof as.jwks_uri !== 'string') { throw new TypeError('"as.jwks_uri" must be a string') } const url = new URL(as.jwks_uri) const headers = prepareHeaders(options?.headers) headers.set('accept', 'application/json') headers.append('accept', 'application/jwk-set+json') return fetch(url.href, { headers, method: 'GET', redirect: 'manual', signal: options?.signal ? signal(options.signal) : null, }).then(processDpopNonce)}
/** * JSON Web Key Set * * @ignore */export interface JsonWebKeySet { /** Array of JWK Values */ readonly keys: JWK[]}
/** * Validates Response instance to be one coming from the * {@link AuthorizationServer.jwks_uri `as.jwks_uri`}. * * @ignore * * @param response Resolved value from {@link jwksRequest}. * * @returns Resolves with an object representing the parsed successful response. * * @see [JWK Set Format](https://www.rfc-editor.org/rfc/rfc7517.html#section-5) */export async function processJwksResponse(response: Response): Promise<JsonWebKeySet> { 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 JSON Web Key Set response') } let json: JsonValue try { json = await preserveBodyStream(response).json() } catch { throw new OPE('failed to parse "response" body as JSON') } if (!isJsonObject<JsonWebKeySet>(json)) { throw new OPE('"response" body must be a top level object') } if (!Array.isArray(json.keys)) { throw new OPE('"response" body "keys" property must be an array') } if (!Array.prototype.every.call(json.keys, isJsonObject)) { throw new OPE('"response" body "keys" property members must be JWK formatted objects') } return json}
async function handleOAuthBodyError(response: Response): Promise<OAuth2Error | undefined> { if (response.status > 399 && response.status < 500) { try { const json: JsonValue = await preserveBodyStream(response).json() if (isJsonObject(json) && typeof json.error === 'string' && json.error.length) { if (json.error_description !== undefined && typeof json.error_description !== 'string') { delete json.error_description } if (json.error_uri !== undefined && typeof json.error_uri !== 'string') { delete json.error_uri } if (json.algs !== undefined && typeof json.algs !== 'string') { delete json.algs } if (json.scope !== undefined && typeof json.scope !== 'string') { delete json.scope } return <OAuth2Error>json } } catch {} } return undefined}
function checkSupportedJwsAlg(alg: unknown) { if (!SUPPORTED_JWS_ALGS.includes(<any>alg)) { throw new UnsupportedOperationError('unsupported JWS "alg" identifier') } return <JWSAlgorithm>alg}
function checkRsaKeyAlgorithm(algorithm: RsaKeyAlgorithm) { if (typeof algorithm.modulusLength !== 'number' || algorithm.modulusLength < 2048) { throw new OPE(`${algorithm.name} modulusLength must be at least 2048 bits`) }}
function subtleAlgorithm(key: CryptoKey): Algorithm | RsaPssParams | EcdsaParams { switch (key.algorithm.name) { case 'ECDSA': return <EcdsaParams>{ name: key.algorithm.name, hash: { name: 'SHA-256' } } case 'RSA-PSS': checkRsaKeyAlgorithm(<RsaKeyAlgorithm>key.algorithm) return <RsaPssParams>{ name: key.algorithm.name, saltLength: 256 >> 3, } case 'RSASSA-PKCS1-v1_5': checkRsaKeyAlgorithm(<RsaKeyAlgorithm>key.algorithm) return { name: key.algorithm.name } case 'Ed25519': return { name: key.algorithm.name } } throw new UnsupportedOperationError()}
/** Minimal JWT validation implementation. */async function validateJwt( jws: string, checkAlg: (h: CompactJWSHeaderParameters) => void, getKey: (h: CompactJWSHeaderParameters) => Promise<CryptoKey>,): Promise<ParsedJWT> { const { 0: protectedHeader, 1: payload, 2: signature, length } = jws.split('.') if (length === 5) { throw new UnsupportedOperationError('JWE structure JWTs are not supported') } if (length !== 3) { throw new OPE('Invalid JWT') } let header: JsonValue try { header = JSON.parse(buf(b64u(protectedHeader))) } catch { throw new OPE('failed to parse JWT Header body as base64url encoded JSON') } if (!isJsonObject<CompactJWSHeaderParameters>(header)) { throw new OPE('JWT Header must be a top level object') } checkAlg(header) if (header.crit !== undefined) { throw new OPE('unexpected JWT "crit" header parameter') } const key = await getKey(header) const input = `${protectedHeader}.${payload}` const verified = await crypto.subtle.verify( subtleAlgorithm(key), key, b64u(signature), buf(input), ) if (!verified) { throw new OPE('JWT signature verification failed') } let claims: JsonValue try { claims = JSON.parse(buf(b64u(payload))) } catch { throw new OPE('failed to parse JWT Payload body as base64url encoded JSON') } if (!isJsonObject<JWTPayload>(claims)) { throw new OPE('JWT Payload must be a top level object') } const now = epochTime() const tolerance = 30 if (claims.exp !== undefined) { if (typeof claims.exp !== 'number') { throw new OPE('unexpected JWT "exp" (expiration time) claim type') } if (claims.exp <= now - tolerance) { throw new OPE('unexpected JWT "exp" (expiration time) claim value, timestamp is <= now()') } } if (claims.iat !== undefined) { if (typeof claims.iat !== 'number') { throw new OPE('unexpected JWT "iat" (issued at) claim type') } } if (claims.iss !== undefined) { if (typeof claims.iss !== 'string') { throw new OPE('unexpected JWT "iss" (issuer) claim type') } } if (claims.nbf !== undefined) { if (typeof claims.nbf !== 'number') { throw new OPE('unexpected JWT "nbf" (not before) claim type') } if (claims.nbf > now + tolerance) { throw new OPE('unexpected JWT "nbf" (not before) claim value, timestamp is > now()') } } if (claims.aud !== undefined) { if (typeof claims.aud !== 'string' && !Array.isArray(claims.aud)) { throw new OPE('unexpected JWT "aud" (audience) claim type') } } return { header, claims }}
/** * Same as {@link validateAuthResponse} but for signed JARM responses. * * @param as Authorization Server Metadata. * @param client Client Metadata. * @param parameters JARM authorization response. * @param expectedState Expected `state` parameter value. Default is {@link expectNoState}. * * @returns Validated Authorization Response parameters or Authorization Error Response. * * @see [openid-financial-api-jarm-ID1 - JWT Secured Authorization Response Mode for OAuth 2.0 (JARM)](https://openid.net/specs/openid-financial-api-jarm-ID1.html) */export async function validateJwtAuthResponse( as: AuthorizationServer, client: Client, parameters: URLSearchParams | URL, expectedState?: string | typeof expectNoState | typeof skipStateCheck, options?: HttpRequestOptions,): Promise<CallbackParameters | OAuth2Error> { assertAs(as) assertClient(client) if (parameters instanceof URL) { parameters = parameters.searchParams } if (!(parameters instanceof URLSearchParams)) { throw new TypeError('"parameters" must be an instance of URLSearchParams, or URL') } const response = getURLSearchParameter(parameters, 'response') if (!response) { throw new OPE('"parameters" does not contain a JARM response') } if (typeof as.jwks_uri !== 'string') { throw new TypeError('"as.jwks_uri" must be a string') } const { claims } = await validateJwt( response, checkSigningAlgorithm.bind( undefined, client.authorization_signed_response_alg, as.authorization_signing_alg_values_supported, ), getPublicSigKeyFromIssuerJwksUri.bind(undefined, as, options), ) .then(validatePresence.bind(undefined, ['aud', 'exp', 'iss'])) .then(validateIssuer.bind(undefined, as.issuer)) .then(validateAudience.bind(undefined, client.client_id)) const result = new URLSearchParams() for (const [key, value] of Object.entries(claims)) { // filters out timestamps if (typeof value === 'string' && key !== 'aud') { result.set(key, value) } } return validateAuthResponse(as, client, result, expectedState)}
/** * If configured must be the configured one (client) if not configured must be signalled by the * issuer to be supported (issuer) if not signalled must be fallback */function checkSigningAlgorithm( client: string | undefined, issuer: string[] | undefined, header: CompactJWSHeaderParameters,) { if (client !== undefined) { if (header.alg !== client) { throw new OPE('unexpected JWT "alg" header parameter') } return } if (Array.isArray(issuer)) { if (!issuer.includes(header.alg)) { throw new OPE('unexpected JWT "alg" header parameter') } return } if (header.alg !== 'RS256') { throw new OPE('unexpected JWT "alg" header parameter') }}
/** * Returns a parameter by name from URLSearchParams. It must be only provided once. Returns * undefined if the parameter is not present. */function getURLSearchParameter(parameters: URLSearchParams, name: string): string | undefined { const { 0: value, length } = parameters.getAll(name) if (length > 1) { throw new OPE(`"${name}" parameter must be provided only once`) } return value}
/** * DANGER ZONE * * Use this as a value to {@link validateAuthResponse} `expectedState` parameter to skip the `state` * value check. This should only ever be done if you use a `state` parameter value that is integrity * protected and bound to the browsing session. One such mechanism to do so is described in an I-D * [draft-bradley-oauth-jwt-encoded-state-09](https://datatracker.ietf.org/doc/html/draft-bradley-oauth-jwt-encoded-state-09). * It is expected you'll validate such `state` value yourself. */export const skipStateCheck = Symbol()
/** * Use this as a value to {@link validateAuthResponse} `expectedState` parameter to indicate no * `state` parameter value is expected, i.e. no `state` parameter value was sent with the * authorization request. */export const expectNoState = Symbol()
class CallbackParameters extends URLSearchParams {}
/** * Validates an OAuth 2.0 Authorization Response or Authorization Error Response message returned * from the authorization server's * {@link AuthorizationServer.authorization_endpoint `as.authorization_endpoint`}. * * @param as Authorization Server Metadata. * @param client Client Metadata. * @param parameters Authorization response. * @param expectedState Expected `state` parameter value. Default is {@link expectNoState}. * * @returns Validated Authorization Response parameters or Authorization Error Response. * * @see [RFC 6749 - The OAuth 2.0 Authorization Framework](https://www.rfc-editor.org/rfc/rfc6749.html#section-4.1.2) * @see [OpenID Connect Core 1.0](https://openid.net/specs/openid-connect-core-1_0.html#ClientAuthentication) * @see [RFC 9207 - OAuth 2.0 Authorization Server Issuer Identification](https://www.rfc-editor.org/rfc/rfc9207.html) */export function validateAuthResponse( as: AuthorizationServer, client: Client, parameters: URLSearchParams | URL, expectedState?: string | typeof expectNoState | typeof skipStateCheck,): CallbackParameters | OAuth2Error { assertAs(as) assertClient(client) if (parameters instanceof URL) { parameters = parameters.searchParams } if (!(parameters instanceof URLSearchParams)) { throw new TypeError('"parameters" must be an instance of URLSearchParams, or URL') } if (getURLSearchParameter(parameters, 'response')) { throw new OPE( '"parameters" contains a JARM response, use validateJwtAuthResponse() instead of validateAuthResponse()', ) } const iss = getURLSearchParameter(parameters, 'iss') const state = getURLSearchParameter(parameters, 'state') if (!iss && as.authorization_response_iss_parameter_supported) { throw new OPE('response parameter "iss" (issuer) missing') } if (iss && iss !== as.issuer) { throw new OPE('unexpected "iss" (issuer) response parameter value') } switch (expectedState) { case undefined: case expectNoState: if (state !== undefined) { throw new OPE('unexpected "state" response parameter encountered') } break case skipStateCheck: break default: if (!validateString(expectedState)) { throw new OPE('"expectedState" must be a non-empty string') } if (state === undefined) { throw new OPE('response parameter "state" missing') } if (state !== expectedState) { throw new OPE('unexpected "state" response parameter value') } } const error = getURLSearchParameter(parameters, 'error') if (error) { return { error, error_description: getURLSearchParameter(parameters, 'error_description'), error_uri: getURLSearchParameter(parameters, 'error_uri'), } } const id_token = getURLSearchParameter(parameters, 'id_token') const token = getURLSearchParameter(parameters, 'token') if (id_token !== undefined || token !== undefined) { throw new UnsupportedOperationError('implicit and hybrid flows are not supported') } return new CallbackParameters(parameters)}
type ReturnTypes = | TokenEndpointResponse | OAuth2TokenEndpointResponse | OpenIDTokenEndpointResponse | ClientCredentialsGrantResponse | DeviceAuthorizationResponse | IntrospectionResponse | OAuth2Error | PushedAuthorizationResponse | URLSearchParams | UserInfoResponseasync function importJwk(jwk: JWK) { const { alg, ext, key_ops, use, ...key } = jwk let algorithm: RsaHashedImportParams | EcKeyImportParams | Algorithm switch (alg) { case 'PS256': algorithm = { name: 'RSA-PSS', hash: { name: 'SHA-256' } } break case 'RS256': algorithm = { name: 'RSASSA-PKCS1-v1_5', hash: { name: 'SHA-256' } } break case 'ES256': algorithm = { name: 'ECDSA', namedCurve: 'P-256' } break case 'EdDSA': algorithm = { name: 'Ed25519' } break default: throw new UnsupportedOperationError() } return crypto.subtle.importKey('jwk', key, algorithm, true, ['verify'])}
export interface DeviceAuthorizationRequestOptions extends HttpRequestOptions, AuthenticatedRequestOptions {}/** * Performs a Device Authorization Request at the * {@link AuthorizationServer.device_authorization_endpoint `as.device_authorization_endpoint`}. * * @param as Authorization Server Metadata. * @param client Client Metadata. * @param parameters Device Authorization Request parameters. * * @see [RFC 8628 - OAuth 2.0 Device Authorization Grant](https://www.rfc-editor.org/rfc/rfc8628.html#section-3.1) */export async function deviceAuthorizationRequest( as: AuthorizationServer, client: Client, parameters: URLSearchParams, options?: DeviceAuthorizationRequestOptions,): Promise<Response> { assertAs(as) assertClient(client) if (!(parameters instanceof URLSearchParams)) { throw new TypeError('"parameters" must be an instance of URLSearchParams') } if (typeof as.device_authorization_endpoint !== 'string') { throw new TypeError('"as.device_authorization_endpoint" must be a string') } const url = new URL(as.device_authorization_endpoint) const body = new URLSearchParams(parameters) body.set('client_id', client.client_id) const headers = prepareHeaders(options?.headers) headers.set('accept', 'application/json') return authenticatedRequest(as, client, 'POST', url, body, headers, options)}
export interface DeviceAuthorizationResponse { readonly device_code: string readonly user_code: string readonly verification_uri: string readonly expires_in: number readonly verification_uri_complete?: string readonly interval?: number readonly [parameter: string]: JsonValue | undefined}
/** * Validates Response instance to be one coming from the * {@link AuthorizationServer.device_authorization_endpoint `as.device_authorization_endpoint`}. * * @param as Authorization Server Metadata. * @param client Client Metadata. * @param response Resolved value from {@link deviceAuthorizationRequest}. * * @returns Resolves with an object representing the parsed successful response, or an object * representing an OAuth 2.0 protocol style error. Use {@link isOAuth2Error} to determine if an * OAuth 2.0 error was returned. * @see [RFC 8628 - OAuth 2.0 Device Authorization Grant](https://www.rfc-editor.org/rfc/rfc8628.html#section-3.1) */export async function processDeviceAuthorizationResponse( as: AuthorizationServer, client: Client, response: Response,): Promise<DeviceAuthorizationResponse | OAuth2Error> { assertAs(as) assertClient(client) if (!(response instanceof Response)) { throw new TypeError('"response" must be an instance of Response') } if (response.status !== 200) { let err: OAuth2Error | undefined if ((err = await handleOAuthBodyError(response))) { return err } throw new OPE('"response" is not a conform Device Authorization Endpoint response') } let json: JsonValue try { json = await preserveBodyStream(response).json() } catch { throw new OPE('failed to parse "response" body as JSON') } if (!isJsonObject<DeviceAuthorizationResponse>(json)) { throw new OPE('"response" body must be a top level object') } if (!validateString(json.device_code)) { throw new OPE('"response" body "device_code" property must be a non-empty string') } if (!validateString(json.user_code)) { throw new OPE('"response" body "user_code" property must be a non-empty string') } if (!validateString(json.verification_uri)) { throw new OPE('"response" body "verification_uri" property must be a non-empty string') } if (typeof json.expires_in !== 'number' || json.expires_in <= 0) { throw new OPE('"response" body "expires_in" property must be a positive number') } if ( json.verification_uri_complete !== undefined && !validateString(json.verification_uri_complete) ) { throw new OPE('"response" body "verification_uri_complete" property must be a non-empty string') } if (json.interval !== undefined && (typeof json.interval !== 'number' || json.interval <= 0)) { throw new OPE('"response" body "interval" property must be a positive number') } return json}
/** * Performs a Device Authorization Grant request at the * {@link AuthorizationServer.token_endpoint `as.token_endpoint`}. * * @param as Authorization Server Metadata. * @param client Client Metadata. * @param deviceCode Device Code. * * @see [RFC 8628 - OAuth 2.0 Device Authorization Grant](https://www.rfc-editor.org/rfc/rfc8628.html#section-3.4) * @see [draft-ietf-oauth-dpop-10 - OAuth 2.0 Demonstrating Proof-of-Possession at the Application Layer (DPoP)](https://www.ietf.org/archive/id/draft-ietf-oauth-dpop-10.html#name-dpop-access-token-request) */export async function deviceCodeGrantRequest( as: AuthorizationServer, client: Client, deviceCode: string, options?: TokenEndpointRequestOptions,): Promise<Response> { assertAs(as) assertClient(client) if (!validateString(deviceCode)) { throw new TypeError('"deviceCode" must be a non-empty string') } const parameters = new URLSearchParams(options?.additionalParameters) parameters.set('device_code', deviceCode) return tokenEndpointRequest( as, client, 'urn:ietf:params:oauth:grant-type:device_code', parameters, options, )}
/** * Validates Device Authorization Grant Response instance to be one coming from the * {@link AuthorizationServer.token_endpoint `as.token_endpoint`}. * * @param as Authorization Server Metadata. * @param client Client Metadata. * @param response Resolved value from {@link deviceCodeGrantRequest}. * * @returns Resolves with an object representing the parsed successful response, or an object * representing an OAuth 2.0 protocol style error. Use {@link isOAuth2Error} to determine if an * OAuth 2.0 error was returned. * @see [RFC 8628 - OAuth 2.0 Device Authorization Grant](https://www.rfc-editor.org/rfc/rfc8628.html#section-3.4) */export async function processDeviceCodeResponse( as: AuthorizationServer, client: Client, response: Response, options?: HttpRequestOptions,): Promise<TokenEndpointResponse | OAuth2Error> { return processGenericAccessTokenResponse(as, client, response, options)}
export interface GenerateKeyPairOptions { /** Indicates whether or not the private key may be exported. Default is `false`. */ extractable?: boolean /** (RSA algorithms only) The length, in bits, of the RSA modulus. Default is `2048`. */ modulusLength?: number}
/** * Generates a CryptoKeyPair for a given JWS `alg` Algorithm identifier. * * @param alg Supported JWS `alg` Algorithm identifier. */export async function generateKeyPair(alg: JWSAlgorithm, options?: GenerateKeyPairOptions) { let algorithm: RsaHashedKeyGenParams | EcKeyGenParams | Algorithm if (!validateString(alg)) { throw new TypeError('"alg" must be a non-empty string') } switch (alg) { case 'PS256': algorithm = { name: 'RSA-PSS', hash: { name: 'SHA-256' }, modulusLength: options?.modulusLength ?? 2048, publicExponent: new Uint8Array([0x01, 0x00, 0x01]), } break case 'RS256': algorithm = { name: 'RSASSA-PKCS1-v1_5', hash: { name: 'SHA-256' }, modulusLength: options?.modulusLength ?? 2048, publicExponent: new Uint8Array([0x01, 0x00, 0x01]), } break case 'ES256': algorithm = { name: 'ECDSA', namedCurve: 'P-256' } break case 'EdDSA': algorithm = { name: 'Ed25519' } break default: throw new UnsupportedOperationError() } return <Promise<CryptoKeyPair>>( crypto.subtle.generateKey(algorithm, options?.extractable ?? false, ['sign', 'verify']) )}
/** * Calculates a base64url-encoded SHA-256 JWK Thumbprint. * * @ignore * * @param key A public extractable CryptoKey. * * @see [RFC 7638 - JSON Web Key (JWK) Thumbprint](https://www.rfc-editor.org/rfc/rfc7638.html) */export async function calculateJwkThumbprint(key: CryptoKey) { if (!isPublicKey(key) || !key.extractable) { throw new TypeError('"key" must be an extractable public CryptoKey') } // checks that the key is a supported one determineJWSAlgorithm(key) const jwk = await crypto.subtle.exportKey('jwk', key) let components: JsonValue switch (jwk.kty) { case 'EC': components = { crv: jwk.crv, kty: jwk.kty, x: jwk.x, y: jwk.y } break case 'OKP': components = { crv: jwk.crv, kty: jwk.kty, x: jwk.x } break case 'RSA': components = { e: jwk.e, kty: jwk.kty, n: jwk.n } break default: throw new UnsupportedOperationError() } return b64u(await crypto.subtle.digest({ name: 'SHA-256' }, buf(JSON.stringify(components))))}
oauth4webapi

Version Info

Tagged at
2 years ago