@leed-ai/git-gateway-auth-jwt 0.0.0-stage → 0.1.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSE +201 -0
- package/README.md +24 -2
- package/dist/base64url.d.ts +5 -0
- package/dist/base64url.js +17 -0
- package/dist/base64url.js.map +1 -0
- package/dist/jwks-Bk8zq_xG.d.ts +48 -0
- package/dist/jwks-source.d.ts +30 -0
- package/dist/jwks-source.js +84 -0
- package/dist/jwks-source.js.map +1 -0
- package/dist/jwt-authenticator.d.ts +25 -0
- package/dist/jwt-authenticator.js +72 -0
- package/dist/jwt-authenticator.js.map +1 -0
- package/dist/jwt-verify.d.ts +18 -0
- package/dist/jwt-verify.js +157 -0
- package/dist/jwt-verify.js.map +1 -0
- package/dist/package-name.d.ts +3 -0
- package/dist/package-name.js +6 -0
- package/dist/package-name.js.map +1 -0
- package/dist/schemas/jwks.d.ts +2 -0
- package/dist/schemas/jwks.js +67 -0
- package/dist/schemas/jwks.js.map +1 -0
- package/dist/schemas/jwt-algorithm.d.ts +17 -0
- package/dist/schemas/jwt-algorithm.js +35 -0
- package/dist/schemas/jwt-algorithm.js.map +1 -0
- package/dist/schemas/jwt-authenticator-config.d.ts +41 -0
- package/dist/schemas/jwt-authenticator-config.js +57 -0
- package/dist/schemas/jwt-authenticator-config.js.map +1 -0
- package/dist/schemas/jwt-parts.d.ts +20 -0
- package/dist/schemas/jwt-parts.js +40 -0
- package/dist/schemas/jwt-parts.js.map +1 -0
- package/package.json +103 -4
- package/src/base64url.ts +16 -0
- package/src/jwks-source.ts +109 -0
- package/src/jwt-authenticator.ts +100 -0
- package/src/jwt-verify.ts +135 -0
- package/src/package-name.ts +4 -0
- package/src/schemas/jwks.ts +96 -0
- package/src/schemas/jwt-algorithm.ts +28 -0
- package/src/schemas/jwt-authenticator-config.ts +111 -0
- package/src/schemas/jwt-parts.ts +60 -0
package/LICENSE
ADDED
|
@@ -0,0 +1,201 @@
|
|
|
1
|
+
Apache License
|
|
2
|
+
Version 2.0, January 2004
|
|
3
|
+
http://www.apache.org/licenses/
|
|
4
|
+
|
|
5
|
+
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
|
|
6
|
+
|
|
7
|
+
1. Definitions.
|
|
8
|
+
|
|
9
|
+
"License" shall mean the terms and conditions for use, reproduction,
|
|
10
|
+
and distribution as defined by Sections 1 through 9 of this document.
|
|
11
|
+
|
|
12
|
+
"Licensor" shall mean the copyright owner or entity authorized by
|
|
13
|
+
the copyright owner that is granting the License.
|
|
14
|
+
|
|
15
|
+
"Legal Entity" shall mean the union of the acting entity and all
|
|
16
|
+
other entities that control, are controlled by, or are under common
|
|
17
|
+
control with that entity. For the purposes of this definition,
|
|
18
|
+
"control" means (i) the power, direct or indirect, to cause the
|
|
19
|
+
direction or management of such entity, whether by contract or
|
|
20
|
+
otherwise, or (ii) ownership of fifty percent (50%) or more of the
|
|
21
|
+
outstanding shares, or (iii) beneficial ownership of such entity.
|
|
22
|
+
|
|
23
|
+
"You" (or "Your") shall mean an individual or Legal Entity
|
|
24
|
+
exercising permissions granted by this License.
|
|
25
|
+
|
|
26
|
+
"Source" form shall mean the preferred form for making modifications,
|
|
27
|
+
including but not limited to software source code, documentation
|
|
28
|
+
source, and configuration files.
|
|
29
|
+
|
|
30
|
+
"Object" form shall mean any form resulting from mechanical
|
|
31
|
+
transformation or translation of a Source form, including but
|
|
32
|
+
not limited to compiled object code, generated documentation,
|
|
33
|
+
and conversions to other media types.
|
|
34
|
+
|
|
35
|
+
"Work" shall mean the work of authorship, whether in Source or
|
|
36
|
+
Object form, made available under the License, as indicated by a
|
|
37
|
+
copyright notice that is included in or attached to the work
|
|
38
|
+
(an example is provided in the Appendix below).
|
|
39
|
+
|
|
40
|
+
"Derivative Works" shall mean any work, whether in Source or Object
|
|
41
|
+
form, that is based on (or derived from) the Work and for which the
|
|
42
|
+
editorial revisions, annotations, elaborations, or other modifications
|
|
43
|
+
represent, as a whole, an original work of authorship. For the purposes
|
|
44
|
+
of this License, Derivative Works shall not include works that remain
|
|
45
|
+
separable from, or merely link (or bind by name) to the interfaces of,
|
|
46
|
+
the Work and Derivative Works thereof.
|
|
47
|
+
|
|
48
|
+
"Contribution" shall mean any work of authorship, including
|
|
49
|
+
the original version of the Work and any modifications or additions
|
|
50
|
+
to that Work or Derivative Works thereof, that is intentionally
|
|
51
|
+
submitted to Licensor for inclusion in the Work by the copyright owner
|
|
52
|
+
or by an individual or Legal Entity authorized to submit on behalf of
|
|
53
|
+
the copyright owner. For the purposes of this definition, "submitted"
|
|
54
|
+
means any form of electronic, verbal, or written communication sent
|
|
55
|
+
to the Licensor or its representatives, including but not limited to
|
|
56
|
+
communication on electronic mailing lists, source code control systems,
|
|
57
|
+
and issue tracking systems that are managed by, or on behalf of, the
|
|
58
|
+
Licensor for the purpose of discussing and improving the Work, but
|
|
59
|
+
excluding communication that is conspicuously marked or otherwise
|
|
60
|
+
designated in writing by the copyright owner as "Not a Contribution."
|
|
61
|
+
|
|
62
|
+
"Contributor" shall mean Licensor and any individual or Legal Entity
|
|
63
|
+
on behalf of whom a Contribution has been received by Licensor and
|
|
64
|
+
subsequently incorporated within the Work.
|
|
65
|
+
|
|
66
|
+
2. Grant of Copyright License. Subject to the terms and conditions of
|
|
67
|
+
this License, each Contributor hereby grants to You a perpetual,
|
|
68
|
+
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
|
69
|
+
copyright license to reproduce, prepare Derivative Works of,
|
|
70
|
+
publicly display, publicly perform, sublicense, and distribute the
|
|
71
|
+
Work and such Derivative Works in Source or Object form.
|
|
72
|
+
|
|
73
|
+
3. Grant of Patent License. Subject to the terms and conditions of
|
|
74
|
+
this License, each Contributor hereby grants to You a perpetual,
|
|
75
|
+
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
|
76
|
+
(except as stated in this section) patent license to make, have made,
|
|
77
|
+
use, offer to sell, sell, import, and otherwise transfer the Work,
|
|
78
|
+
where such license applies only to those patent claims licensable
|
|
79
|
+
by such Contributor that are necessarily infringed by their
|
|
80
|
+
Contribution(s) alone or by combination of their Contribution(s)
|
|
81
|
+
with the Work to which such Contribution(s) was submitted. If You
|
|
82
|
+
institute patent litigation against any entity (including a
|
|
83
|
+
cross-claim or counterclaim in a lawsuit) alleging that the Work
|
|
84
|
+
or a Contribution incorporated within the Work constitutes direct
|
|
85
|
+
or contributory patent infringement, then any patent licenses
|
|
86
|
+
granted to You under this License for that Work shall terminate
|
|
87
|
+
as of the date such litigation is filed.
|
|
88
|
+
|
|
89
|
+
4. Redistribution. You may reproduce and distribute copies of the
|
|
90
|
+
Work or Derivative Works thereof in any medium, with or without
|
|
91
|
+
modifications, and in Source or Object form, provided that You
|
|
92
|
+
meet the following conditions:
|
|
93
|
+
|
|
94
|
+
(a) You must give any other recipients of the Work or
|
|
95
|
+
Derivative Works a copy of this License; and
|
|
96
|
+
|
|
97
|
+
(b) You must cause any modified files to carry prominent notices
|
|
98
|
+
stating that You changed the files; and
|
|
99
|
+
|
|
100
|
+
(c) You must retain, in the Source form of any Derivative Works
|
|
101
|
+
that You distribute, all copyright, patent, trademark, and
|
|
102
|
+
attribution notices from the Source form of the Work,
|
|
103
|
+
excluding those notices that do not pertain to any part of
|
|
104
|
+
the Derivative Works; and
|
|
105
|
+
|
|
106
|
+
(d) If the Work includes a "NOTICE" text file as part of its
|
|
107
|
+
distribution, then any Derivative Works that You distribute must
|
|
108
|
+
include a readable copy of the attribution notices contained
|
|
109
|
+
within such NOTICE file, excluding those notices that do not
|
|
110
|
+
pertain to any part of the Derivative Works, in at least one
|
|
111
|
+
of the following places: within a NOTICE text file distributed
|
|
112
|
+
as part of the Derivative Works; within the Source form or
|
|
113
|
+
documentation, if provided along with the Derivative Works; or,
|
|
114
|
+
within a display generated by the Derivative Works, if and
|
|
115
|
+
wherever such third-party notices normally appear. The contents
|
|
116
|
+
of the NOTICE file are for informational purposes only and
|
|
117
|
+
do not modify the License. You may add Your own attribution
|
|
118
|
+
notices within Derivative Works that You distribute, alongside
|
|
119
|
+
or as an addendum to the NOTICE text from the Work, provided
|
|
120
|
+
that such additional attribution notices cannot be construed
|
|
121
|
+
as modifying the License.
|
|
122
|
+
|
|
123
|
+
You may add Your own copyright statement to Your modifications and
|
|
124
|
+
may provide additional or different license terms and conditions
|
|
125
|
+
for use, reproduction, or distribution of Your modifications, or
|
|
126
|
+
for any such Derivative Works as a whole, provided Your use,
|
|
127
|
+
reproduction, and distribution of the Work otherwise complies with
|
|
128
|
+
the conditions stated in this License.
|
|
129
|
+
|
|
130
|
+
5. Submission of Contributions. Unless You explicitly state otherwise,
|
|
131
|
+
any Contribution intentionally submitted for inclusion in the Work
|
|
132
|
+
by You to the Licensor shall be under the terms and conditions of
|
|
133
|
+
this License, without any additional terms or conditions.
|
|
134
|
+
Notwithstanding the above, nothing herein shall supersede or modify
|
|
135
|
+
the terms of any separate license agreement you may have executed
|
|
136
|
+
with Licensor regarding such Contributions.
|
|
137
|
+
|
|
138
|
+
6. Trademarks. This License does not grant permission to use the trade
|
|
139
|
+
names, trademarks, service marks, or product names of the Licensor,
|
|
140
|
+
except as required for reasonable and customary use in describing the
|
|
141
|
+
origin of the Work and reproducing the content of the NOTICE file.
|
|
142
|
+
|
|
143
|
+
7. Disclaimer of Warranty. Unless required by applicable law or
|
|
144
|
+
agreed to in writing, Licensor provides the Work (and each
|
|
145
|
+
Contributor provides its Contributions) on an "AS IS" BASIS,
|
|
146
|
+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
|
|
147
|
+
implied, including, without limitation, any warranties or conditions
|
|
148
|
+
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
|
|
149
|
+
PARTICULAR PURPOSE. You are solely responsible for determining the
|
|
150
|
+
appropriateness of using or redistributing the Work and assume any
|
|
151
|
+
risks associated with Your exercise of permissions under this License.
|
|
152
|
+
|
|
153
|
+
8. Limitation of Liability. In no event and under no legal theory,
|
|
154
|
+
whether in tort (including negligence), contract, or otherwise,
|
|
155
|
+
unless required by applicable law (such as deliberate and grossly
|
|
156
|
+
negligent acts) or agreed to in writing, shall any Contributor be
|
|
157
|
+
liable to You for damages, including any direct, indirect, special,
|
|
158
|
+
incidental, or consequential damages of any character arising as a
|
|
159
|
+
result of this License or out of the use or inability to use the
|
|
160
|
+
Work (including but not limited to damages for loss of goodwill,
|
|
161
|
+
work stoppage, computer failure or malfunction, or any and all
|
|
162
|
+
other commercial damages or losses), even if such Contributor
|
|
163
|
+
has been advised of the possibility of such damages.
|
|
164
|
+
|
|
165
|
+
9. Accepting Warranty or Additional Liability. While redistributing
|
|
166
|
+
the Work or Derivative Works thereof, You may choose to offer,
|
|
167
|
+
and charge a fee for, acceptance of support, warranty, indemnity,
|
|
168
|
+
or other liability obligations and/or rights consistent with this
|
|
169
|
+
License. However, in accepting such obligations, You may act only
|
|
170
|
+
on Your own behalf and on Your sole responsibility, not on behalf
|
|
171
|
+
of any other Contributor, and only if You agree to indemnify,
|
|
172
|
+
defend, and hold each Contributor harmless for any liability
|
|
173
|
+
incurred by, or claims asserted against, such Contributor by reason
|
|
174
|
+
of your accepting any such warranty or additional liability.
|
|
175
|
+
|
|
176
|
+
END OF TERMS AND CONDITIONS
|
|
177
|
+
|
|
178
|
+
APPENDIX: How to apply the Apache License to your work.
|
|
179
|
+
|
|
180
|
+
To apply the Apache License to your work, attach the following
|
|
181
|
+
boilerplate notice, with the fields enclosed by brackets "[]"
|
|
182
|
+
replaced with your own identifying information. (Don't include
|
|
183
|
+
the brackets!) The text should be enclosed in the appropriate
|
|
184
|
+
comment syntax for the file format. We also recommend that a
|
|
185
|
+
file or class name and description of purpose be included on the
|
|
186
|
+
same "printed page" as the copyright notice for easier
|
|
187
|
+
identification within third-party archives.
|
|
188
|
+
|
|
189
|
+
Copyright [yyyy] [name of copyright owner]
|
|
190
|
+
|
|
191
|
+
Licensed under the Apache License, Version 2.0 (the "License");
|
|
192
|
+
you may not use this file except in compliance with the License.
|
|
193
|
+
You may obtain a copy of the License at
|
|
194
|
+
|
|
195
|
+
http://www.apache.org/licenses/LICENSE-2.0
|
|
196
|
+
|
|
197
|
+
Unless required by applicable law or agreed to in writing, software
|
|
198
|
+
distributed under the License is distributed on an "AS IS" BASIS,
|
|
199
|
+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
|
200
|
+
See the License for the specific language governing permissions and
|
|
201
|
+
limitations under the License.
|
package/README.md
CHANGED
|
@@ -1,3 +1,25 @@
|
|
|
1
|
-
#
|
|
1
|
+
# @leed-ai/git-gateway-auth-jwt
|
|
2
2
|
|
|
3
|
-
|
|
3
|
+
Reference git-gateway authenticator: bearer or Basic-password JWTs verified against a JWKS (OIDC).
|
|
4
|
+
|
|
5
|
+
Part of [git-gateway](https://github.com/leed-ai/git-gateway). Status: in development; see the [design](https://github.com/leed-ai/git-gateway/blob/main/docs/design.md).
|
|
6
|
+
|
|
7
|
+
Peer dependencies: `zod` (`^4`). Install them alongside this package.
|
|
8
|
+
|
|
9
|
+
## Usage
|
|
10
|
+
|
|
11
|
+
```ts
|
|
12
|
+
import { JwtAuthenticator } from '@leed-ai/git-gateway-auth-jwt/jwt-authenticator';
|
|
13
|
+
|
|
14
|
+
const authenticator = new JwtAuthenticator({
|
|
15
|
+
issuer: 'https://auth.example.com', // keys discovered from <issuer>/.well-known/openid-configuration
|
|
16
|
+
audience: ['git.example.com'],
|
|
17
|
+
algorithms: ['RS256', 'ES256'],
|
|
18
|
+
});
|
|
19
|
+
```
|
|
20
|
+
|
|
21
|
+
git sends the token as the HTTP Basic password (a credential helper returns it); a Bearer header works too. The token must be signed by one of the issuer's keys with an accepted algorithm, carry the issuer, an accepted audience and an unexpired `exp`. Claims map to the principal (`sub`, `name`, `email`, `roles` by default; see `JwtClaimMapping`), and the principal's `expiresAt` is the token's expiry plus the clock tolerance (`clockToleranceSeconds`), so no cached decision outlives the token's acceptance. Keys are cached (`jwksCacheSeconds`) and refetched early when a token names an unknown `kid`; the issuer is asked at most every 10 seconds, and when a refetch fails the last keys fetched keep being served, so an issuer outage only stops authentication before any key has been fetched.
|
|
22
|
+
|
|
23
|
+
## License
|
|
24
|
+
|
|
25
|
+
Apache-2.0
|
|
@@ -0,0 +1,5 @@
|
|
|
1
|
+
/** Decodes unpadded base64url (RFC 4648 §5) into bytes; throws on characters outside the alphabet. */
|
|
2
|
+
export declare function decodeBase64Url(text: string): Uint8Array;
|
|
3
|
+
/** Encodes bytes as unpadded base64url. */
|
|
4
|
+
export declare function encodeBase64Url(bytes: Uint8Array): string;
|
|
5
|
+
//# sourceMappingURL=base64url.d.ts.map
|
|
@@ -0,0 +1,17 @@
|
|
|
1
|
+
// src/base64url.ts
|
|
2
|
+
/** Decodes unpadded base64url (RFC 4648 §5) into bytes; throws on characters outside the alphabet. */
|
|
3
|
+
function decodeBase64Url(text) {
|
|
4
|
+
if (!/^[A-Za-z0-9_-]*$/.test(text)) throw new Error("not base64url");
|
|
5
|
+
const base64 = text.replaceAll("-", "+").replaceAll("_", "/");
|
|
6
|
+
const padded = base64 + "=".repeat((4 - base64.length % 4) % 4);
|
|
7
|
+
return Uint8Array.from(atob(padded), (char) => char.codePointAt(0) ?? 0);
|
|
8
|
+
}
|
|
9
|
+
/** Encodes bytes as unpadded base64url. */
|
|
10
|
+
function encodeBase64Url(bytes) {
|
|
11
|
+
let binary = "";
|
|
12
|
+
for (const byte of bytes) binary += String.fromCodePoint(byte);
|
|
13
|
+
return btoa(binary).replaceAll("+", "-").replaceAll("/", "_").replace(/=+$/, "");
|
|
14
|
+
}
|
|
15
|
+
export { decodeBase64Url, encodeBase64Url };
|
|
16
|
+
|
|
17
|
+
//# sourceMappingURL=base64url.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"base64url.js","names":[],"sources":["../src/base64url.ts"],"sourcesContent":["// SPDX-License-Identifier: Apache-2.0\n\n/** Decodes unpadded base64url (RFC 4648 §5) into bytes; throws on characters outside the alphabet. */\nexport function decodeBase64Url(text: string): Uint8Array {\n if (!/^[A-Za-z0-9_-]*$/.test(text)) throw new Error('not base64url');\n const base64 = text.replaceAll('-', '+').replaceAll('_', '/');\n const padded = base64 + '='.repeat((4 - (base64.length % 4)) % 4);\n return Uint8Array.from(atob(padded), (char) => char.codePointAt(0) ?? 0);\n}\n\n/** Encodes bytes as unpadded base64url. */\nexport function encodeBase64Url(bytes: Uint8Array): string {\n let binary = '';\n for (const byte of bytes) binary += String.fromCodePoint(byte);\n return btoa(binary).replaceAll('+', '-').replaceAll('/', '_').replace(/=+$/, '');\n}\n"],"mappings":";;AAGA,SAAgB,gBAAgB,MAA0B;CACxD,IAAI,CAAC,mBAAmB,KAAK,IAAI,GAAG,MAAM,IAAI,MAAM,eAAe;CACnE,MAAM,SAAS,KAAK,WAAW,KAAK,GAAG,CAAC,CAAC,WAAW,KAAK,GAAG;CAC5D,MAAM,SAAS,SAAS,IAAI,QAAQ,IAAK,OAAO,SAAS,KAAM,CAAC;CAChE,OAAO,WAAW,KAAK,KAAK,MAAM,IAAI,SAAS,KAAK,YAAY,CAAC,KAAK,CAAC;AACzE;;AAGA,SAAgB,gBAAgB,OAA2B;CACzD,IAAI,SAAS;CACb,KAAK,MAAM,QAAQ,OAAO,UAAU,OAAO,cAAc,IAAI;CAC7D,OAAO,KAAK,MAAM,CAAC,CAAC,WAAW,KAAK,GAAG,CAAC,CAAC,WAAW,KAAK,GAAG,CAAC,CAAC,QAAQ,OAAO,EAAE;AACjF"}
|
|
@@ -0,0 +1,48 @@
|
|
|
1
|
+
import { z } from "zod";
|
|
2
|
+
/** One public key of a JWK Set. */
|
|
3
|
+
declare const Jwk: z.ZodObject<{
|
|
4
|
+
kty: z.ZodEnum<{
|
|
5
|
+
EC: "EC";
|
|
6
|
+
OKP: "OKP";
|
|
7
|
+
RSA: "RSA";
|
|
8
|
+
}>;
|
|
9
|
+
kid: z.ZodOptional<z.ZodString>;
|
|
10
|
+
alg: z.ZodOptional<z.ZodString>;
|
|
11
|
+
use: z.ZodOptional<z.ZodString>;
|
|
12
|
+
n: z.ZodOptional<z.ZodString>;
|
|
13
|
+
e: z.ZodOptional<z.ZodString>;
|
|
14
|
+
crv: z.ZodOptional<z.ZodString>;
|
|
15
|
+
x: z.ZodOptional<z.ZodString>;
|
|
16
|
+
y: z.ZodOptional<z.ZodString>;
|
|
17
|
+
}, z.core.$loose>;
|
|
18
|
+
/** A JSON Web Key, inferred from {@link Jwk}. */
|
|
19
|
+
type Jwk = z.infer<typeof Jwk>;
|
|
20
|
+
/** A JWK Set document. */
|
|
21
|
+
declare const JwkSet: z.ZodObject<{
|
|
22
|
+
keys: z.ZodArray<z.ZodObject<{
|
|
23
|
+
kty: z.ZodEnum<{
|
|
24
|
+
EC: "EC";
|
|
25
|
+
OKP: "OKP";
|
|
26
|
+
RSA: "RSA";
|
|
27
|
+
}>;
|
|
28
|
+
kid: z.ZodOptional<z.ZodString>;
|
|
29
|
+
alg: z.ZodOptional<z.ZodString>;
|
|
30
|
+
use: z.ZodOptional<z.ZodString>;
|
|
31
|
+
n: z.ZodOptional<z.ZodString>;
|
|
32
|
+
e: z.ZodOptional<z.ZodString>;
|
|
33
|
+
crv: z.ZodOptional<z.ZodString>;
|
|
34
|
+
x: z.ZodOptional<z.ZodString>;
|
|
35
|
+
y: z.ZodOptional<z.ZodString>;
|
|
36
|
+
}, z.core.$loose>>;
|
|
37
|
+
}, z.core.$loose>;
|
|
38
|
+
/** A JWK Set, inferred from {@link JwkSet}. */
|
|
39
|
+
type JwkSet = z.infer<typeof JwkSet>;
|
|
40
|
+
/** The part of an OpenID Provider configuration the authenticator reads. */
|
|
41
|
+
declare const OidcDiscovery: z.ZodObject<{
|
|
42
|
+
issuer: z.ZodString;
|
|
43
|
+
jwks_uri: z.ZodURL;
|
|
44
|
+
}, z.core.$loose>;
|
|
45
|
+
/** An OIDC discovery document, inferred from {@link OidcDiscovery}. */
|
|
46
|
+
type OidcDiscovery = z.infer<typeof OidcDiscovery>;
|
|
47
|
+
export { JwkSet as n, OidcDiscovery as r, Jwk as t };
|
|
48
|
+
//# sourceMappingURL=jwks-Bk8zq_xG.d.ts.map
|
|
@@ -0,0 +1,30 @@
|
|
|
1
|
+
import { t as Jwk } from "./jwks-Bk8zq_xG.js";
|
|
2
|
+
/** Fetches over HTTP; the global `fetch` by default. */
|
|
3
|
+
export type JwksFetch = (request: Request) => Promise<Response>;
|
|
4
|
+
/** Options of a {@link JwksSource}. */
|
|
5
|
+
export interface JwksSourceOptions {
|
|
6
|
+
readonly issuer: string;
|
|
7
|
+
/** The JWK Set URL, or null to discover it from the issuer's OpenID configuration. */
|
|
8
|
+
readonly jwksUrl: string | null;
|
|
9
|
+
/** Seconds keys are reused. */
|
|
10
|
+
readonly cacheSeconds: number;
|
|
11
|
+
readonly fetch: JwksFetch;
|
|
12
|
+
/** The clock in milliseconds since the epoch. */
|
|
13
|
+
readonly now: () => number;
|
|
14
|
+
}
|
|
15
|
+
/**
|
|
16
|
+
* The issuer's signing keys, fetched (through OIDC discovery when no JWKS URL is configured) and
|
|
17
|
+
* cached for `cacheSeconds`. A key id not in the cached set triggers one early refetch, so key
|
|
18
|
+
* rotation is picked up without waiting for the cache to expire. Every fetch attempt, failed or
|
|
19
|
+
* not, starts a {@link MIN_REFRESH_MS} window in which the issuer is not asked again. When a
|
|
20
|
+
* refresh fails the last keys fetched are served (stale on error), so an issuer outage does not
|
|
21
|
+
* stop authentication; only with no keys ever fetched does the failure surface. Concurrent
|
|
22
|
+
* callers share one fetch.
|
|
23
|
+
*/
|
|
24
|
+
export declare class JwksSource {
|
|
25
|
+
#private;
|
|
26
|
+
constructor(options: JwksSourceOptions);
|
|
27
|
+
/** The keys that may have signed a token naming `kid` (every key when the token names none). */
|
|
28
|
+
keysFor(kid: string | undefined): Promise<readonly Jwk[]>;
|
|
29
|
+
}
|
|
30
|
+
//# sourceMappingURL=jwks-source.d.ts.map
|
|
@@ -0,0 +1,84 @@
|
|
|
1
|
+
import { JwkSet, OidcDiscovery } from "./schemas/jwks.js";
|
|
2
|
+
// src/jwks-source.ts
|
|
3
|
+
/**
|
|
4
|
+
* The issuer is asked at most this often (an unknown key id, or a retry after a failed fetch), so
|
|
5
|
+
* bad tokens or an issuer outage cannot hammer it.
|
|
6
|
+
*/
|
|
7
|
+
const MIN_REFRESH_MS = 1e4;
|
|
8
|
+
async function getJson(fetcher, url) {
|
|
9
|
+
const response = await fetcher(new Request(url, { headers: { Accept: "application/json" } }));
|
|
10
|
+
if (!response.ok) throw new Error(`GET ${url} answered ${response.status}`);
|
|
11
|
+
return response.json();
|
|
12
|
+
}
|
|
13
|
+
/**
|
|
14
|
+
* The issuer's signing keys, fetched (through OIDC discovery when no JWKS URL is configured) and
|
|
15
|
+
* cached for `cacheSeconds`. A key id not in the cached set triggers one early refetch, so key
|
|
16
|
+
* rotation is picked up without waiting for the cache to expire. Every fetch attempt, failed or
|
|
17
|
+
* not, starts a {@link MIN_REFRESH_MS} window in which the issuer is not asked again. When a
|
|
18
|
+
* refresh fails the last keys fetched are served (stale on error), so an issuer outage does not
|
|
19
|
+
* stop authentication; only with no keys ever fetched does the failure surface. Concurrent
|
|
20
|
+
* callers share one fetch.
|
|
21
|
+
*/
|
|
22
|
+
var JwksSource = class {
|
|
23
|
+
#options;
|
|
24
|
+
#keys = null;
|
|
25
|
+
/** When the keys were last fetched successfully. */
|
|
26
|
+
#fetchedAt = Number.NEGATIVE_INFINITY;
|
|
27
|
+
/** When the issuer was last asked, whatever the outcome. */
|
|
28
|
+
#attemptedAt = Number.NEGATIVE_INFINITY;
|
|
29
|
+
/** Why the last attempt failed, while no keys have ever been fetched. */
|
|
30
|
+
#lastError = null;
|
|
31
|
+
#pending = null;
|
|
32
|
+
/** The JWK Set URL once known (configured, or discovered once). */
|
|
33
|
+
#jwksUrl;
|
|
34
|
+
constructor(options) {
|
|
35
|
+
this.#options = options;
|
|
36
|
+
this.#jwksUrl = options.jwksUrl;
|
|
37
|
+
}
|
|
38
|
+
/** The keys that may have signed a token naming `kid` (every key when the token names none). */
|
|
39
|
+
async keysFor(kid) {
|
|
40
|
+
const fresh = this.#options.now() - this.#fetchedAt < this.#options.cacheSeconds * 1e3;
|
|
41
|
+
let keys = this.#keys !== null && fresh ? this.#keys : await this.#refresh();
|
|
42
|
+
const matching = (set) => kid === void 0 ? set : set.filter((key) => key.kid === kid);
|
|
43
|
+
if (matching(keys).length === 0 && kid !== void 0) keys = await this.#refresh();
|
|
44
|
+
return matching(keys);
|
|
45
|
+
}
|
|
46
|
+
/**
|
|
47
|
+
* Fetches the keys unless the issuer was asked less than {@link MIN_REFRESH_MS} ago; serves the
|
|
48
|
+
* cached keys when it was, or when the fetch fails.
|
|
49
|
+
*/
|
|
50
|
+
async #refresh() {
|
|
51
|
+
if (this.#pending !== null) return this.#pending;
|
|
52
|
+
if (this.#options.now() - this.#attemptedAt < MIN_REFRESH_MS) {
|
|
53
|
+
if (this.#keys !== null) return this.#keys;
|
|
54
|
+
throw this.#lastError ?? /* @__PURE__ */ new Error("the issuer keys are not available yet");
|
|
55
|
+
}
|
|
56
|
+
this.#attemptedAt = this.#options.now();
|
|
57
|
+
this.#pending = this.#load().catch((error) => {
|
|
58
|
+
if (this.#keys !== null) return this.#keys;
|
|
59
|
+
this.#lastError = error;
|
|
60
|
+
throw error;
|
|
61
|
+
}).finally(() => {
|
|
62
|
+
this.#pending = null;
|
|
63
|
+
});
|
|
64
|
+
return this.#pending;
|
|
65
|
+
}
|
|
66
|
+
async #load() {
|
|
67
|
+
const { issuer, fetch: fetcher } = this.#options;
|
|
68
|
+
let url = this.#jwksUrl;
|
|
69
|
+
if (url === null) {
|
|
70
|
+
const discovery = OidcDiscovery.parse(await getJson(fetcher, `${issuer.replace(/\/$/, "")}/.well-known/openid-configuration`));
|
|
71
|
+
if (discovery.issuer !== issuer) throw new Error(`the discovery document names issuer ${discovery.issuer}`);
|
|
72
|
+
url = discovery.jwks_uri;
|
|
73
|
+
this.#jwksUrl = url;
|
|
74
|
+
}
|
|
75
|
+
const set = JwkSet.parse(await getJson(fetcher, url));
|
|
76
|
+
this.#keys = set.keys;
|
|
77
|
+
this.#fetchedAt = this.#options.now();
|
|
78
|
+
this.#lastError = null;
|
|
79
|
+
return set.keys;
|
|
80
|
+
}
|
|
81
|
+
};
|
|
82
|
+
export { JwksSource };
|
|
83
|
+
|
|
84
|
+
//# sourceMappingURL=jwks-source.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"jwks-source.js","names":[],"sources":["../src/jwks-source.ts"],"sourcesContent":["// SPDX-License-Identifier: Apache-2.0\nimport { JwkSet, OidcDiscovery, type Jwk } from './schemas/jwks.ts';\n\n/** Fetches over HTTP; the global `fetch` by default. */\nexport type JwksFetch = (request: Request) => Promise<Response>;\n\n/** Options of a {@link JwksSource}. */\nexport interface JwksSourceOptions {\n readonly issuer: string;\n /** The JWK Set URL, or null to discover it from the issuer's OpenID configuration. */\n readonly jwksUrl: string | null;\n /** Seconds keys are reused. */\n readonly cacheSeconds: number;\n readonly fetch: JwksFetch;\n /** The clock in milliseconds since the epoch. */\n readonly now: () => number;\n}\n\n/**\n * The issuer is asked at most this often (an unknown key id, or a retry after a failed fetch), so\n * bad tokens or an issuer outage cannot hammer it.\n */\nconst MIN_REFRESH_MS = 10_000;\n\nasync function getJson(fetcher: JwksFetch, url: string): Promise<unknown> {\n const response = await fetcher(new Request(url, { headers: { Accept: 'application/json' } }));\n if (!response.ok) throw new Error(`GET ${url} answered ${response.status}`);\n return response.json();\n}\n\n/**\n * The issuer's signing keys, fetched (through OIDC discovery when no JWKS URL is configured) and\n * cached for `cacheSeconds`. A key id not in the cached set triggers one early refetch, so key\n * rotation is picked up without waiting for the cache to expire. Every fetch attempt, failed or\n * not, starts a {@link MIN_REFRESH_MS} window in which the issuer is not asked again. When a\n * refresh fails the last keys fetched are served (stale on error), so an issuer outage does not\n * stop authentication; only with no keys ever fetched does the failure surface. Concurrent\n * callers share one fetch.\n */\nexport class JwksSource {\n readonly #options: JwksSourceOptions;\n #keys: readonly Jwk[] | null = null;\n /** When the keys were last fetched successfully. */\n #fetchedAt = Number.NEGATIVE_INFINITY;\n /** When the issuer was last asked, whatever the outcome. */\n #attemptedAt = Number.NEGATIVE_INFINITY;\n /** Why the last attempt failed, while no keys have ever been fetched. */\n #lastError: unknown = null;\n #pending: Promise<readonly Jwk[]> | null = null;\n /** The JWK Set URL once known (configured, or discovered once). */\n #jwksUrl: string | null;\n\n constructor(options: JwksSourceOptions) {\n this.#options = options;\n this.#jwksUrl = options.jwksUrl;\n }\n\n /** The keys that may have signed a token naming `kid` (every key when the token names none). */\n async keysFor(kid: string | undefined): Promise<readonly Jwk[]> {\n const fresh = this.#options.now() - this.#fetchedAt < this.#options.cacheSeconds * 1000;\n let keys = this.#keys !== null && fresh ? this.#keys : await this.#refresh();\n const matching = (set: readonly Jwk[]): readonly Jwk[] =>\n kid === undefined ? set : set.filter((key) => key.kid === kid);\n if (matching(keys).length === 0 && kid !== undefined) keys = await this.#refresh();\n return matching(keys);\n }\n\n /**\n * Fetches the keys unless the issuer was asked less than {@link MIN_REFRESH_MS} ago; serves the\n * cached keys when it was, or when the fetch fails.\n */\n async #refresh(): Promise<readonly Jwk[]> {\n if (this.#pending !== null) return this.#pending;\n if (this.#options.now() - this.#attemptedAt < MIN_REFRESH_MS) {\n if (this.#keys !== null) return this.#keys;\n throw this.#lastError ?? new Error('the issuer keys are not available yet');\n }\n this.#attemptedAt = this.#options.now();\n this.#pending = this.#load()\n .catch((error: unknown) => {\n if (this.#keys !== null) return this.#keys;\n this.#lastError = error;\n throw error;\n })\n .finally(() => {\n this.#pending = null;\n });\n return this.#pending;\n }\n\n async #load(): Promise<readonly Jwk[]> {\n const { issuer, fetch: fetcher } = this.#options;\n let url = this.#jwksUrl;\n if (url === null) {\n const discovery = OidcDiscovery.parse(\n await getJson(fetcher, `${issuer.replace(/\\/$/, '')}/.well-known/openid-configuration`),\n );\n if (discovery.issuer !== issuer)\n throw new Error(`the discovery document names issuer ${discovery.issuer}`);\n url = discovery.jwks_uri;\n this.#jwksUrl = url;\n }\n const set = JwkSet.parse(await getJson(fetcher, url));\n this.#keys = set.keys;\n this.#fetchedAt = this.#options.now();\n this.#lastError = null;\n return set.keys;\n }\n}\n"],"mappings":";;;;;;AAsBA,MAAM,iBAAiB;AAEvB,eAAe,QAAQ,SAAoB,KAA+B;CACxE,MAAM,WAAW,MAAM,QAAQ,IAAI,QAAQ,KAAK,EAAE,SAAS,EAAE,QAAQ,mBAAmB,EAAE,CAAC,CAAC;CAC5F,IAAI,CAAC,SAAS,IAAI,MAAM,IAAI,MAAM,OAAO,IAAI,YAAY,SAAS,QAAQ;CAC1E,OAAO,SAAS,KAAK;AACvB;;;;;;;;;;AAWA,IAAa,aAAb,MAAwB;CACtB;CACA,QAA+B;;CAE/B,aAAa,OAAO;;CAEpB,eAAe,OAAO;;CAEtB,aAAsB;CACtB,WAA2C;;CAE3C;CAEA,YAAY,SAA4B;EACtC,KAAK,WAAW;EAChB,KAAK,WAAW,QAAQ;CAC1B;;CAGA,MAAM,QAAQ,KAAkD;EAC9D,MAAM,QAAQ,KAAK,SAAS,IAAI,IAAI,KAAK,aAAa,KAAK,SAAS,eAAe;EACnF,IAAI,OAAO,KAAK,UAAU,QAAQ,QAAQ,KAAK,QAAQ,MAAM,KAAK,SAAS;EAC3E,MAAM,YAAY,QAChB,QAAQ,KAAA,IAAY,MAAM,IAAI,QAAQ,QAAQ,IAAI,QAAQ,GAAG;EAC/D,IAAI,SAAS,IAAI,CAAC,CAAC,WAAW,KAAK,QAAQ,KAAA,GAAW,OAAO,MAAM,KAAK,SAAS;EACjF,OAAO,SAAS,IAAI;CACtB;;;;;CAMA,MAAM,WAAoC;EACxC,IAAI,KAAK,aAAa,MAAM,OAAO,KAAK;EACxC,IAAI,KAAK,SAAS,IAAI,IAAI,KAAK,eAAe,gBAAgB;GAC5D,IAAI,KAAK,UAAU,MAAM,OAAO,KAAK;GACrC,MAAM,KAAK,8BAAc,IAAI,MAAM,uCAAuC;EAC5E;EACA,KAAK,eAAe,KAAK,SAAS,IAAI;EACtC,KAAK,WAAW,KAAK,MAAM,CAAC,CACzB,OAAO,UAAmB;GACzB,IAAI,KAAK,UAAU,MAAM,OAAO,KAAK;GACrC,KAAK,aAAa;GAClB,MAAM;EACR,CAAC,CAAC,CACD,cAAc;GACb,KAAK,WAAW;EAClB,CAAC;EACH,OAAO,KAAK;CACd;CAEA,MAAM,QAAiC;EACrC,MAAM,EAAE,QAAQ,OAAO,YAAY,KAAK;EACxC,IAAI,MAAM,KAAK;EACf,IAAI,QAAQ,MAAM;GAChB,MAAM,YAAY,cAAc,MAC9B,MAAM,QAAQ,SAAS,GAAG,OAAO,QAAQ,OAAO,EAAE,EAAE,kCAAkC,CACxF;GACA,IAAI,UAAU,WAAW,QACvB,MAAM,IAAI,MAAM,uCAAuC,UAAU,QAAQ;GAC3E,MAAM,UAAU;GAChB,KAAK,WAAW;EAClB;EACA,MAAM,MAAM,OAAO,MAAM,MAAM,QAAQ,SAAS,GAAG,CAAC;EACpD,KAAK,QAAQ,IAAI;EACjB,KAAK,aAAa,KAAK,SAAS,IAAI;EACpC,KAAK,aAAa;EAClB,OAAO,IAAI;CACb;AACF"}
|
|
@@ -0,0 +1,25 @@
|
|
|
1
|
+
import { JwksFetch } from "./jwks-source.js";
|
|
2
|
+
import { JwtAuthenticatorConfigInput } from "./schemas/jwt-authenticator-config.js";
|
|
3
|
+
import { PrincipalInput } from "@leed-ai/git-gateway-contract/proxy/principal";
|
|
4
|
+
import { Authenticator } from "@leed-ai/git-gateway-contract/proxy/gateway-hooks";
|
|
5
|
+
/** Options beyond the configuration: how keys are fetched and the clock (both injectable for tests). */
|
|
6
|
+
export interface JwtAuthenticatorOptions {
|
|
7
|
+
/** Fetches the discovery document and JWK Set; default the global `fetch`. */
|
|
8
|
+
readonly fetch?: JwksFetch;
|
|
9
|
+
/** The clock; default the system clock. */
|
|
10
|
+
readonly now?: () => Date;
|
|
11
|
+
}
|
|
12
|
+
/**
|
|
13
|
+
* The reference {@link Authenticator}: the bearer credential (a Bearer header, or the password of
|
|
14
|
+
* the HTTP Basic credentials git sends, so a credential helper can supply the token) must be a JWT
|
|
15
|
+
* signed by one of the issuer's keys (JWKS, discovered through OIDC unless a URL is configured)
|
|
16
|
+
* with an accepted algorithm, carry the configured issuer and an accepted audience, and be
|
|
17
|
+
* within its "nbf"/"exp" window. Its claims are mapped to a principal whose `expiresAt` is the
|
|
18
|
+
* token's expiry, so no cached decision outlives the token. Anything else is null — a 401.
|
|
19
|
+
*/
|
|
20
|
+
export declare class JwtAuthenticator implements Authenticator {
|
|
21
|
+
#private;
|
|
22
|
+
constructor(config: JwtAuthenticatorConfigInput, options?: JwtAuthenticatorOptions);
|
|
23
|
+
authenticate(request: Request): Promise<PrincipalInput | null>;
|
|
24
|
+
}
|
|
25
|
+
//# sourceMappingURL=jwt-authenticator.d.ts.map
|
|
@@ -0,0 +1,72 @@
|
|
|
1
|
+
import { JwksSource } from "./jwks-source.js";
|
|
2
|
+
import { decodeJwt, verifySignature } from "./jwt-verify.js";
|
|
3
|
+
import { JwtAlgorithm } from "./schemas/jwt-algorithm.js";
|
|
4
|
+
import { JwtAuthenticatorConfig } from "./schemas/jwt-authenticator-config.js";
|
|
5
|
+
import { z } from "zod";
|
|
6
|
+
import { Role } from "@leed-ai/git-gateway-contract/proxy/principal";
|
|
7
|
+
import { readCredential } from "@leed-ai/git-gateway-contract/proxy/request-credential";
|
|
8
|
+
// src/jwt-authenticator.ts
|
|
9
|
+
const SingleLine = z.string().min(1).max(255).regex(/^[^\n\0]+$/);
|
|
10
|
+
const Email = z.email().max(255);
|
|
11
|
+
function rolesOf(value) {
|
|
12
|
+
return (Array.isArray(value) ? value : typeof value === "string" ? value.split(/[\s,]+/) : []).filter((name) => Role.safeParse(name).success).slice(0, 100);
|
|
13
|
+
}
|
|
14
|
+
/**
|
|
15
|
+
* The reference {@link Authenticator}: the bearer credential (a Bearer header, or the password of
|
|
16
|
+
* the HTTP Basic credentials git sends, so a credential helper can supply the token) must be a JWT
|
|
17
|
+
* signed by one of the issuer's keys (JWKS, discovered through OIDC unless a URL is configured)
|
|
18
|
+
* with an accepted algorithm, carry the configured issuer and an accepted audience, and be
|
|
19
|
+
* within its "nbf"/"exp" window. Its claims are mapped to a principal whose `expiresAt` is the
|
|
20
|
+
* token's expiry, so no cached decision outlives the token. Anything else is null — a 401.
|
|
21
|
+
*/
|
|
22
|
+
var JwtAuthenticator = class {
|
|
23
|
+
#config;
|
|
24
|
+
#keys;
|
|
25
|
+
#now;
|
|
26
|
+
constructor(config, options = {}) {
|
|
27
|
+
this.#config = JwtAuthenticatorConfig.parse(config);
|
|
28
|
+
this.#now = options.now ?? (() => /* @__PURE__ */ new Date());
|
|
29
|
+
this.#keys = new JwksSource({
|
|
30
|
+
issuer: this.#config.issuer,
|
|
31
|
+
jwksUrl: this.#config.jwksUrl,
|
|
32
|
+
cacheSeconds: this.#config.jwksCacheSeconds,
|
|
33
|
+
fetch: options.fetch ?? (async (request) => fetch(request)),
|
|
34
|
+
now: () => this.#now().getTime()
|
|
35
|
+
});
|
|
36
|
+
}
|
|
37
|
+
async authenticate(request) {
|
|
38
|
+
const credential = readCredential(request);
|
|
39
|
+
const jwt = credential === null ? null : decodeJwt(credential.secret);
|
|
40
|
+
if (jwt === null || !this.#claimsValid(jwt)) return null;
|
|
41
|
+
const algorithm = JwtAlgorithm.safeParse(jwt.header.alg);
|
|
42
|
+
if (!algorithm.success || !this.#config.algorithms.includes(algorithm.data)) return null;
|
|
43
|
+
const keys = await this.#keys.keysFor(jwt.header.kid);
|
|
44
|
+
for (const key of keys) if (await verifySignature(jwt, algorithm.data, key)) return this.#principal(jwt);
|
|
45
|
+
return null;
|
|
46
|
+
}
|
|
47
|
+
#claimsValid({ claims }) {
|
|
48
|
+
const now = this.#now().getTime() / 1e3;
|
|
49
|
+
const tolerance = this.#config.clockToleranceSeconds;
|
|
50
|
+
if (claims.iss !== this.#config.issuer) return false;
|
|
51
|
+
if (!(Array.isArray(claims.aud) ? claims.aud : [claims.aud]).some((audience) => this.#config.audience.includes(audience))) return false;
|
|
52
|
+
if (claims.exp + tolerance <= now) return false;
|
|
53
|
+
return claims.nbf === void 0 || claims.nbf - tolerance <= now;
|
|
54
|
+
}
|
|
55
|
+
#principal({ claims }) {
|
|
56
|
+
const mapping = this.#config.claims;
|
|
57
|
+
const subject = SingleLine.safeParse(claims[mapping.subject]);
|
|
58
|
+
if (!subject.success) return null;
|
|
59
|
+
const name = SingleLine.safeParse(claims[mapping.name]);
|
|
60
|
+
const email = Email.safeParse(claims[mapping.email]);
|
|
61
|
+
return {
|
|
62
|
+
subject: subject.data,
|
|
63
|
+
name: name.success ? name.data : null,
|
|
64
|
+
email: email.success ? email.data : null,
|
|
65
|
+
roles: rolesOf(claims[mapping.roles]),
|
|
66
|
+
expiresAt: new Date(Math.min((claims.exp + this.#config.clockToleranceSeconds) * 1e3, 864e13)).toISOString()
|
|
67
|
+
};
|
|
68
|
+
}
|
|
69
|
+
};
|
|
70
|
+
export { JwtAuthenticator };
|
|
71
|
+
|
|
72
|
+
//# sourceMappingURL=jwt-authenticator.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"jwt-authenticator.js","names":[],"sources":["../src/jwt-authenticator.ts"],"sourcesContent":["// SPDX-License-Identifier: Apache-2.0\nimport type { Authenticator } from '@leed-ai/git-gateway-contract/proxy/gateway-hooks';\nimport { Role, type PrincipalInput } from '@leed-ai/git-gateway-contract/proxy/principal';\nimport { readCredential } from '@leed-ai/git-gateway-contract/proxy/request-credential';\nimport { z } from 'zod';\n\nimport { JwksSource, type JwksFetch } from './jwks-source.ts';\nimport { decodeJwt, verifySignature, type DecodedJwt } from './jwt-verify.ts';\nimport { JwtAlgorithm } from './schemas/jwt-algorithm.ts';\nimport {\n JwtAuthenticatorConfig,\n type JwtAuthenticatorConfigInput,\n} from './schemas/jwt-authenticator-config.ts';\n\n/** Options beyond the configuration: how keys are fetched and the clock (both injectable for tests). */\nexport interface JwtAuthenticatorOptions {\n /** Fetches the discovery document and JWK Set; default the global `fetch`. */\n readonly fetch?: JwksFetch;\n /** The clock; default the system clock. */\n readonly now?: () => Date;\n}\n\nconst SingleLine = z\n .string()\n .min(1)\n .max(255)\n .regex(/^[^\\n\\0]+$/);\nconst Email = z.email().max(255);\n\nfunction rolesOf(value: unknown): string[] {\n const names = Array.isArray(value) ? value : typeof value === 'string' ? value.split(/[\\s,]+/) : [];\n return names.filter((name): name is string => Role.safeParse(name).success).slice(0, 100);\n}\n\n/**\n * The reference {@link Authenticator}: the bearer credential (a Bearer header, or the password of\n * the HTTP Basic credentials git sends, so a credential helper can supply the token) must be a JWT\n * signed by one of the issuer's keys (JWKS, discovered through OIDC unless a URL is configured)\n * with an accepted algorithm, carry the configured issuer and an accepted audience, and be\n * within its \"nbf\"/\"exp\" window. Its claims are mapped to a principal whose `expiresAt` is the\n * token's expiry, so no cached decision outlives the token. Anything else is null — a 401.\n */\nexport class JwtAuthenticator implements Authenticator {\n readonly #config: JwtAuthenticatorConfig;\n readonly #keys: JwksSource;\n readonly #now: () => Date;\n\n constructor(config: JwtAuthenticatorConfigInput, options: JwtAuthenticatorOptions = {}) {\n this.#config = JwtAuthenticatorConfig.parse(config);\n this.#now = options.now ?? (() => new Date());\n this.#keys = new JwksSource({\n issuer: this.#config.issuer,\n jwksUrl: this.#config.jwksUrl,\n cacheSeconds: this.#config.jwksCacheSeconds,\n fetch: options.fetch ?? (async (request) => fetch(request)),\n now: () => this.#now().getTime(),\n });\n }\n\n async authenticate(request: Request): Promise<PrincipalInput | null> {\n const credential = readCredential(request);\n const jwt = credential === null ? null : decodeJwt(credential.secret);\n if (jwt === null || !this.#claimsValid(jwt)) return null;\n const algorithm = JwtAlgorithm.safeParse(jwt.header.alg);\n if (!algorithm.success || !this.#config.algorithms.includes(algorithm.data)) return null;\n const keys = await this.#keys.keysFor(jwt.header.kid);\n for (const key of keys) {\n if (await verifySignature(jwt, algorithm.data, key)) return this.#principal(jwt);\n }\n return null;\n }\n\n #claimsValid({ claims }: DecodedJwt): boolean {\n const now = this.#now().getTime() / 1000;\n const tolerance = this.#config.clockToleranceSeconds;\n if (claims.iss !== this.#config.issuer) return false;\n const audiences = Array.isArray(claims.aud) ? claims.aud : [claims.aud];\n if (!audiences.some((audience) => this.#config.audience.includes(audience))) return false;\n if (claims.exp + tolerance <= now) return false;\n return claims.nbf === undefined || claims.nbf - tolerance <= now;\n }\n\n #principal({ claims }: DecodedJwt): PrincipalInput | null {\n const mapping = this.#config.claims;\n const subject = SingleLine.safeParse(claims[mapping.subject]);\n if (!subject.success) return null;\n const name = SingleLine.safeParse(claims[mapping.name]);\n const email = Email.safeParse(claims[mapping.email]);\n return {\n subject: subject.data,\n name: name.success ? name.data : null,\n email: email.success ? email.data : null,\n roles: rolesOf(claims[mapping.roles]),\n // The token is accepted until exp plus the clock tolerance, so the principal lasts as long.\n expiresAt: new Date(\n Math.min((claims.exp + this.#config.clockToleranceSeconds) * 1000, 8.64e15),\n ).toISOString(),\n };\n }\n}\n"],"mappings":";;;;;;;;AAsBA,MAAM,aAAa,EAChB,OAAO,CAAC,CACR,IAAI,CAAC,CAAC,CACN,IAAI,GAAG,CAAC,CACR,MAAM,YAAY;AACrB,MAAM,QAAQ,EAAE,MAAM,CAAC,CAAC,IAAI,GAAG;AAE/B,SAAS,QAAQ,OAA0B;CAEzC,QADc,MAAM,QAAQ,KAAK,IAAI,QAAQ,OAAO,UAAU,WAAW,MAAM,MAAM,QAAQ,IAAI,CAAC,EAAA,CACrF,QAAQ,SAAyB,KAAK,UAAU,IAAI,CAAC,CAAC,OAAO,CAAC,CAAC,MAAM,GAAG,GAAG;AAC1F;;;;;;;;;AAUA,IAAa,mBAAb,MAAuD;CACrD;CACA;CACA;CAEA,YAAY,QAAqC,UAAmC,CAAC,GAAG;EACtF,KAAK,UAAU,uBAAuB,MAAM,MAAM;EAClD,KAAK,OAAO,QAAQ,8BAAc,IAAI,KAAK;EAC3C,KAAK,QAAQ,IAAI,WAAW;GAC1B,QAAQ,KAAK,QAAQ;GACrB,SAAS,KAAK,QAAQ;GACtB,cAAc,KAAK,QAAQ;GAC3B,OAAO,QAAQ,UAAU,OAAO,YAAY,MAAM,OAAO;GACzD,WAAW,KAAK,KAAK,CAAC,CAAC,QAAQ;EACjC,CAAC;CACH;CAEA,MAAM,aAAa,SAAkD;EACnE,MAAM,aAAa,eAAe,OAAO;EACzC,MAAM,MAAM,eAAe,OAAO,OAAO,UAAU,WAAW,MAAM;EACpE,IAAI,QAAQ,QAAQ,CAAC,KAAK,aAAa,GAAG,GAAG,OAAO;EACpD,MAAM,YAAY,aAAa,UAAU,IAAI,OAAO,GAAG;EACvD,IAAI,CAAC,UAAU,WAAW,CAAC,KAAK,QAAQ,WAAW,SAAS,UAAU,IAAI,GAAG,OAAO;EACpF,MAAM,OAAO,MAAM,KAAK,MAAM,QAAQ,IAAI,OAAO,GAAG;EACpD,KAAK,MAAM,OAAO,MAChB,IAAI,MAAM,gBAAgB,KAAK,UAAU,MAAM,GAAG,GAAG,OAAO,KAAK,WAAW,GAAG;EAEjF,OAAO;CACT;CAEA,aAAa,EAAE,UAA+B;EAC5C,MAAM,MAAM,KAAK,KAAK,CAAC,CAAC,QAAQ,IAAI;EACpC,MAAM,YAAY,KAAK,QAAQ;EAC/B,IAAI,OAAO,QAAQ,KAAK,QAAQ,QAAQ,OAAO;EAE/C,IAAI,EADc,MAAM,QAAQ,OAAO,GAAG,IAAI,OAAO,MAAM,CAAC,OAAO,GAAG,EAAA,CACvD,MAAM,aAAa,KAAK,QAAQ,SAAS,SAAS,QAAQ,CAAC,GAAG,OAAO;EACpF,IAAI,OAAO,MAAM,aAAa,KAAK,OAAO;EAC1C,OAAO,OAAO,QAAQ,KAAA,KAAa,OAAO,MAAM,aAAa;CAC/D;CAEA,WAAW,EAAE,UAA6C;EACxD,MAAM,UAAU,KAAK,QAAQ;EAC7B,MAAM,UAAU,WAAW,UAAU,OAAO,QAAQ,QAAQ;EAC5D,IAAI,CAAC,QAAQ,SAAS,OAAO;EAC7B,MAAM,OAAO,WAAW,UAAU,OAAO,QAAQ,KAAK;EACtD,MAAM,QAAQ,MAAM,UAAU,OAAO,QAAQ,MAAM;EACnD,OAAO;GACL,SAAS,QAAQ;GACjB,MAAM,KAAK,UAAU,KAAK,OAAO;GACjC,OAAO,MAAM,UAAU,MAAM,OAAO;GACpC,OAAO,QAAQ,OAAO,QAAQ,MAAM;GAEpC,WAAW,IAAI,KACb,KAAK,KAAK,OAAO,MAAM,KAAK,QAAQ,yBAAyB,KAAM,MAAO,CAC5E,CAAC,CAAC,YAAY;EAChB;CACF;AACF"}
|
|
@@ -0,0 +1,18 @@
|
|
|
1
|
+
import { t as Jwk } from "./jwks-Bk8zq_xG.js";
|
|
2
|
+
import { JwtAlgorithm } from "./schemas/jwt-algorithm.js";
|
|
3
|
+
import { JwtClaims, JwtHeader } from "./schemas/jwt-parts.js";
|
|
4
|
+
/** A JWT split into its parts, the header and claims parsed but nothing verified yet. */
|
|
5
|
+
export interface DecodedJwt {
|
|
6
|
+
readonly header: JwtHeader;
|
|
7
|
+
readonly claims: JwtClaims;
|
|
8
|
+
/** The bytes the signature covers: "<header>.<payload>" as sent. */
|
|
9
|
+
readonly signingInput: Uint8Array;
|
|
10
|
+
readonly signature: Uint8Array;
|
|
11
|
+
}
|
|
12
|
+
/** Splits and parses a compact JWS JWT; null when it is not one. */
|
|
13
|
+
export declare function decodeJwt(token: string): DecodedJwt | null;
|
|
14
|
+
/** Whether `key` may verify a token signed with `algorithm` (key type, curve and any "alg"/"use" agree). */
|
|
15
|
+
export declare function keyFits(key: Jwk, algorithm: JwtAlgorithm): boolean;
|
|
16
|
+
/** Verifies a decoded JWT's signature with one public key; false on any mismatch or import failure. */
|
|
17
|
+
export declare function verifySignature(jwt: DecodedJwt, algorithm: JwtAlgorithm, key: Jwk): Promise<boolean>;
|
|
18
|
+
//# sourceMappingURL=jwt-verify.d.ts.map
|