@happyvertical/auth 0.74.8
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/AGENT.md +33 -0
- package/LICENSE +7 -0
- package/README.md +73 -0
- package/dist/chunks/cognito-dmypylFX.js +128 -0
- package/dist/chunks/cognito-dmypylFX.js.map +1 -0
- package/dist/chunks/decode_jwt-D2OK1b8a.js +1395 -0
- package/dist/chunks/decode_jwt-D2OK1b8a.js.map +1 -0
- package/dist/chunks/github-NSZp5tVm.js +413 -0
- package/dist/chunks/github-NSZp5tVm.js.map +1 -0
- package/dist/chunks/google-HXk2ctYR.js +483 -0
- package/dist/chunks/google-HXk2ctYR.js.map +1 -0
- package/dist/chunks/index-BpsMhFXS.js +151 -0
- package/dist/chunks/index-BpsMhFXS.js.map +1 -0
- package/dist/chunks/kanidm-hkw-YPVF.js +747 -0
- package/dist/chunks/kanidm-hkw-YPVF.js.map +1 -0
- package/dist/chunks/keycloak-t6JEUeOz.js +871 -0
- package/dist/chunks/keycloak-t6JEUeOz.js.map +1 -0
- package/dist/cli/claude-context.d.ts +3 -0
- package/dist/cli/claude-context.d.ts.map +1 -0
- package/dist/cli/claude-context.js +21 -0
- package/dist/cli/claude-context.js.map +1 -0
- package/dist/index.d.ts +65 -0
- package/dist/index.d.ts.map +1 -0
- package/dist/index.js +499 -0
- package/dist/index.js.map +1 -0
- package/dist/shared/errors.d.ts +227 -0
- package/dist/shared/errors.d.ts.map +1 -0
- package/dist/shared/factory.d.ts +85 -0
- package/dist/shared/factory.d.ts.map +1 -0
- package/dist/shared/providers/cognito.d.ts +38 -0
- package/dist/shared/providers/cognito.d.ts.map +1 -0
- package/dist/shared/providers/github.d.ts +65 -0
- package/dist/shared/providers/github.d.ts.map +1 -0
- package/dist/shared/providers/google.d.ts +58 -0
- package/dist/shared/providers/google.d.ts.map +1 -0
- package/dist/shared/providers/kanidm.d.ts +78 -0
- package/dist/shared/providers/kanidm.d.ts.map +1 -0
- package/dist/shared/providers/keycloak.d.ts +67 -0
- package/dist/shared/providers/keycloak.d.ts.map +1 -0
- package/dist/shared/providers/nostr/index.d.ts +47 -0
- package/dist/shared/providers/nostr/index.d.ts.map +1 -0
- package/dist/shared/types.d.ts +812 -0
- package/dist/shared/types.d.ts.map +1 -0
- package/metadata.json +32 -0
- package/package.json +60 -0
|
@@ -0,0 +1,1395 @@
|
|
|
1
|
+
const encoder = new TextEncoder();
|
|
2
|
+
const decoder = new TextDecoder();
|
|
3
|
+
function concat(...buffers) {
|
|
4
|
+
const size = buffers.reduce((acc, { length }) => acc + length, 0);
|
|
5
|
+
const buf = new Uint8Array(size);
|
|
6
|
+
let i = 0;
|
|
7
|
+
for (const buffer of buffers) {
|
|
8
|
+
buf.set(buffer, i);
|
|
9
|
+
i += buffer.length;
|
|
10
|
+
}
|
|
11
|
+
return buf;
|
|
12
|
+
}
|
|
13
|
+
function encode(string) {
|
|
14
|
+
const bytes = new Uint8Array(string.length);
|
|
15
|
+
for (let i = 0; i < string.length; i++) {
|
|
16
|
+
const code = string.charCodeAt(i);
|
|
17
|
+
if (code > 127) {
|
|
18
|
+
throw new TypeError("non-ASCII string encountered in encode()");
|
|
19
|
+
}
|
|
20
|
+
bytes[i] = code;
|
|
21
|
+
}
|
|
22
|
+
return bytes;
|
|
23
|
+
}
|
|
24
|
+
function decodeBase64(encoded) {
|
|
25
|
+
if (Uint8Array.fromBase64) {
|
|
26
|
+
return Uint8Array.fromBase64(encoded);
|
|
27
|
+
}
|
|
28
|
+
const binary = atob(encoded);
|
|
29
|
+
const bytes = new Uint8Array(binary.length);
|
|
30
|
+
for (let i = 0; i < binary.length; i++) {
|
|
31
|
+
bytes[i] = binary.charCodeAt(i);
|
|
32
|
+
}
|
|
33
|
+
return bytes;
|
|
34
|
+
}
|
|
35
|
+
function decode(input) {
|
|
36
|
+
if (Uint8Array.fromBase64) {
|
|
37
|
+
return Uint8Array.fromBase64(typeof input === "string" ? input : decoder.decode(input), {
|
|
38
|
+
alphabet: "base64url"
|
|
39
|
+
});
|
|
40
|
+
}
|
|
41
|
+
let encoded = input;
|
|
42
|
+
if (encoded instanceof Uint8Array) {
|
|
43
|
+
encoded = decoder.decode(encoded);
|
|
44
|
+
}
|
|
45
|
+
encoded = encoded.replace(/-/g, "+").replace(/_/g, "/");
|
|
46
|
+
try {
|
|
47
|
+
return decodeBase64(encoded);
|
|
48
|
+
} catch {
|
|
49
|
+
throw new TypeError("The input to be decoded is not correctly encoded.");
|
|
50
|
+
}
|
|
51
|
+
}
|
|
52
|
+
const unusable = (name, prop = "algorithm.name") => new TypeError(`CryptoKey does not support this operation, its ${prop} must be ${name}`);
|
|
53
|
+
const isAlgorithm = (algorithm, name) => algorithm.name === name;
|
|
54
|
+
function getHashLength(hash) {
|
|
55
|
+
return parseInt(hash.name.slice(4), 10);
|
|
56
|
+
}
|
|
57
|
+
function checkHashLength(algorithm, expected) {
|
|
58
|
+
const actual = getHashLength(algorithm.hash);
|
|
59
|
+
if (actual !== expected)
|
|
60
|
+
throw unusable(`SHA-${expected}`, "algorithm.hash");
|
|
61
|
+
}
|
|
62
|
+
function getNamedCurve(alg) {
|
|
63
|
+
switch (alg) {
|
|
64
|
+
case "ES256":
|
|
65
|
+
return "P-256";
|
|
66
|
+
case "ES384":
|
|
67
|
+
return "P-384";
|
|
68
|
+
case "ES512":
|
|
69
|
+
return "P-521";
|
|
70
|
+
default:
|
|
71
|
+
throw new Error("unreachable");
|
|
72
|
+
}
|
|
73
|
+
}
|
|
74
|
+
function checkUsage(key, usage) {
|
|
75
|
+
if (!key.usages.includes(usage)) {
|
|
76
|
+
throw new TypeError(`CryptoKey does not support this operation, its usages must include ${usage}.`);
|
|
77
|
+
}
|
|
78
|
+
}
|
|
79
|
+
function checkSigCryptoKey(key, alg, usage) {
|
|
80
|
+
switch (alg) {
|
|
81
|
+
case "HS256":
|
|
82
|
+
case "HS384":
|
|
83
|
+
case "HS512": {
|
|
84
|
+
if (!isAlgorithm(key.algorithm, "HMAC"))
|
|
85
|
+
throw unusable("HMAC");
|
|
86
|
+
checkHashLength(key.algorithm, parseInt(alg.slice(2), 10));
|
|
87
|
+
break;
|
|
88
|
+
}
|
|
89
|
+
case "RS256":
|
|
90
|
+
case "RS384":
|
|
91
|
+
case "RS512": {
|
|
92
|
+
if (!isAlgorithm(key.algorithm, "RSASSA-PKCS1-v1_5"))
|
|
93
|
+
throw unusable("RSASSA-PKCS1-v1_5");
|
|
94
|
+
checkHashLength(key.algorithm, parseInt(alg.slice(2), 10));
|
|
95
|
+
break;
|
|
96
|
+
}
|
|
97
|
+
case "PS256":
|
|
98
|
+
case "PS384":
|
|
99
|
+
case "PS512": {
|
|
100
|
+
if (!isAlgorithm(key.algorithm, "RSA-PSS"))
|
|
101
|
+
throw unusable("RSA-PSS");
|
|
102
|
+
checkHashLength(key.algorithm, parseInt(alg.slice(2), 10));
|
|
103
|
+
break;
|
|
104
|
+
}
|
|
105
|
+
case "Ed25519":
|
|
106
|
+
case "EdDSA": {
|
|
107
|
+
if (!isAlgorithm(key.algorithm, "Ed25519"))
|
|
108
|
+
throw unusable("Ed25519");
|
|
109
|
+
break;
|
|
110
|
+
}
|
|
111
|
+
case "ML-DSA-44":
|
|
112
|
+
case "ML-DSA-65":
|
|
113
|
+
case "ML-DSA-87": {
|
|
114
|
+
if (!isAlgorithm(key.algorithm, alg))
|
|
115
|
+
throw unusable(alg);
|
|
116
|
+
break;
|
|
117
|
+
}
|
|
118
|
+
case "ES256":
|
|
119
|
+
case "ES384":
|
|
120
|
+
case "ES512": {
|
|
121
|
+
if (!isAlgorithm(key.algorithm, "ECDSA"))
|
|
122
|
+
throw unusable("ECDSA");
|
|
123
|
+
const expected = getNamedCurve(alg);
|
|
124
|
+
const actual = key.algorithm.namedCurve;
|
|
125
|
+
if (actual !== expected)
|
|
126
|
+
throw unusable(expected, "algorithm.namedCurve");
|
|
127
|
+
break;
|
|
128
|
+
}
|
|
129
|
+
default:
|
|
130
|
+
throw new TypeError("CryptoKey does not support this operation");
|
|
131
|
+
}
|
|
132
|
+
checkUsage(key, usage);
|
|
133
|
+
}
|
|
134
|
+
function message(msg, actual, ...types) {
|
|
135
|
+
types = types.filter(Boolean);
|
|
136
|
+
if (types.length > 2) {
|
|
137
|
+
const last = types.pop();
|
|
138
|
+
msg += `one of type ${types.join(", ")}, or ${last}.`;
|
|
139
|
+
} else if (types.length === 2) {
|
|
140
|
+
msg += `one of type ${types[0]} or ${types[1]}.`;
|
|
141
|
+
} else {
|
|
142
|
+
msg += `of type ${types[0]}.`;
|
|
143
|
+
}
|
|
144
|
+
if (actual == null) {
|
|
145
|
+
msg += ` Received ${actual}`;
|
|
146
|
+
} else if (typeof actual === "function" && actual.name) {
|
|
147
|
+
msg += ` Received function ${actual.name}`;
|
|
148
|
+
} else if (typeof actual === "object" && actual != null) {
|
|
149
|
+
if (actual.constructor?.name) {
|
|
150
|
+
msg += ` Received an instance of ${actual.constructor.name}`;
|
|
151
|
+
}
|
|
152
|
+
}
|
|
153
|
+
return msg;
|
|
154
|
+
}
|
|
155
|
+
const invalidKeyInput = (actual, ...types) => message("Key must be ", actual, ...types);
|
|
156
|
+
const withAlg = (alg, actual, ...types) => message(`Key for the ${alg} algorithm must be `, actual, ...types);
|
|
157
|
+
class JOSEError extends Error {
|
|
158
|
+
static code = "ERR_JOSE_GENERIC";
|
|
159
|
+
code = "ERR_JOSE_GENERIC";
|
|
160
|
+
constructor(message2, options) {
|
|
161
|
+
super(message2, options);
|
|
162
|
+
this.name = this.constructor.name;
|
|
163
|
+
Error.captureStackTrace?.(this, this.constructor);
|
|
164
|
+
}
|
|
165
|
+
}
|
|
166
|
+
class JWTClaimValidationFailed extends JOSEError {
|
|
167
|
+
static code = "ERR_JWT_CLAIM_VALIDATION_FAILED";
|
|
168
|
+
code = "ERR_JWT_CLAIM_VALIDATION_FAILED";
|
|
169
|
+
claim;
|
|
170
|
+
reason;
|
|
171
|
+
payload;
|
|
172
|
+
constructor(message2, payload, claim = "unspecified", reason = "unspecified") {
|
|
173
|
+
super(message2, { cause: { claim, reason, payload } });
|
|
174
|
+
this.claim = claim;
|
|
175
|
+
this.reason = reason;
|
|
176
|
+
this.payload = payload;
|
|
177
|
+
}
|
|
178
|
+
}
|
|
179
|
+
class JWTExpired extends JOSEError {
|
|
180
|
+
static code = "ERR_JWT_EXPIRED";
|
|
181
|
+
code = "ERR_JWT_EXPIRED";
|
|
182
|
+
claim;
|
|
183
|
+
reason;
|
|
184
|
+
payload;
|
|
185
|
+
constructor(message2, payload, claim = "unspecified", reason = "unspecified") {
|
|
186
|
+
super(message2, { cause: { claim, reason, payload } });
|
|
187
|
+
this.claim = claim;
|
|
188
|
+
this.reason = reason;
|
|
189
|
+
this.payload = payload;
|
|
190
|
+
}
|
|
191
|
+
}
|
|
192
|
+
class JOSEAlgNotAllowed extends JOSEError {
|
|
193
|
+
static code = "ERR_JOSE_ALG_NOT_ALLOWED";
|
|
194
|
+
code = "ERR_JOSE_ALG_NOT_ALLOWED";
|
|
195
|
+
}
|
|
196
|
+
class JOSENotSupported extends JOSEError {
|
|
197
|
+
static code = "ERR_JOSE_NOT_SUPPORTED";
|
|
198
|
+
code = "ERR_JOSE_NOT_SUPPORTED";
|
|
199
|
+
}
|
|
200
|
+
class JWSInvalid extends JOSEError {
|
|
201
|
+
static code = "ERR_JWS_INVALID";
|
|
202
|
+
code = "ERR_JWS_INVALID";
|
|
203
|
+
}
|
|
204
|
+
class JWTInvalid extends JOSEError {
|
|
205
|
+
static code = "ERR_JWT_INVALID";
|
|
206
|
+
code = "ERR_JWT_INVALID";
|
|
207
|
+
}
|
|
208
|
+
class JWKSInvalid extends JOSEError {
|
|
209
|
+
static code = "ERR_JWKS_INVALID";
|
|
210
|
+
code = "ERR_JWKS_INVALID";
|
|
211
|
+
}
|
|
212
|
+
class JWKSNoMatchingKey extends JOSEError {
|
|
213
|
+
static code = "ERR_JWKS_NO_MATCHING_KEY";
|
|
214
|
+
code = "ERR_JWKS_NO_MATCHING_KEY";
|
|
215
|
+
constructor(message2 = "no applicable key found in the JSON Web Key Set", options) {
|
|
216
|
+
super(message2, options);
|
|
217
|
+
}
|
|
218
|
+
}
|
|
219
|
+
class JWKSMultipleMatchingKeys extends JOSEError {
|
|
220
|
+
[Symbol.asyncIterator];
|
|
221
|
+
static code = "ERR_JWKS_MULTIPLE_MATCHING_KEYS";
|
|
222
|
+
code = "ERR_JWKS_MULTIPLE_MATCHING_KEYS";
|
|
223
|
+
constructor(message2 = "multiple matching keys found in the JSON Web Key Set", options) {
|
|
224
|
+
super(message2, options);
|
|
225
|
+
}
|
|
226
|
+
}
|
|
227
|
+
class JWKSTimeout extends JOSEError {
|
|
228
|
+
static code = "ERR_JWKS_TIMEOUT";
|
|
229
|
+
code = "ERR_JWKS_TIMEOUT";
|
|
230
|
+
constructor(message2 = "request timed out", options) {
|
|
231
|
+
super(message2, options);
|
|
232
|
+
}
|
|
233
|
+
}
|
|
234
|
+
class JWSSignatureVerificationFailed extends JOSEError {
|
|
235
|
+
static code = "ERR_JWS_SIGNATURE_VERIFICATION_FAILED";
|
|
236
|
+
code = "ERR_JWS_SIGNATURE_VERIFICATION_FAILED";
|
|
237
|
+
constructor(message2 = "signature verification failed", options) {
|
|
238
|
+
super(message2, options);
|
|
239
|
+
}
|
|
240
|
+
}
|
|
241
|
+
const isCryptoKey = (key) => {
|
|
242
|
+
if (key?.[Symbol.toStringTag] === "CryptoKey")
|
|
243
|
+
return true;
|
|
244
|
+
try {
|
|
245
|
+
return key instanceof CryptoKey;
|
|
246
|
+
} catch {
|
|
247
|
+
return false;
|
|
248
|
+
}
|
|
249
|
+
};
|
|
250
|
+
const isKeyObject = (key) => key?.[Symbol.toStringTag] === "KeyObject";
|
|
251
|
+
const isKeyLike = (key) => isCryptoKey(key) || isKeyObject(key);
|
|
252
|
+
function decodeBase64url(value, label, ErrorClass) {
|
|
253
|
+
try {
|
|
254
|
+
return decode(value);
|
|
255
|
+
} catch {
|
|
256
|
+
throw new ErrorClass(`Failed to base64url decode the ${label}`);
|
|
257
|
+
}
|
|
258
|
+
}
|
|
259
|
+
const isObjectLike = (value) => typeof value === "object" && value !== null;
|
|
260
|
+
function isObject(input) {
|
|
261
|
+
if (!isObjectLike(input) || Object.prototype.toString.call(input) !== "[object Object]") {
|
|
262
|
+
return false;
|
|
263
|
+
}
|
|
264
|
+
if (Object.getPrototypeOf(input) === null) {
|
|
265
|
+
return true;
|
|
266
|
+
}
|
|
267
|
+
let proto = input;
|
|
268
|
+
while (Object.getPrototypeOf(proto) !== null) {
|
|
269
|
+
proto = Object.getPrototypeOf(proto);
|
|
270
|
+
}
|
|
271
|
+
return Object.getPrototypeOf(input) === proto;
|
|
272
|
+
}
|
|
273
|
+
function isDisjoint(...headers) {
|
|
274
|
+
const sources = headers.filter(Boolean);
|
|
275
|
+
if (sources.length === 0 || sources.length === 1) {
|
|
276
|
+
return true;
|
|
277
|
+
}
|
|
278
|
+
let acc;
|
|
279
|
+
for (const header of sources) {
|
|
280
|
+
const parameters = Object.keys(header);
|
|
281
|
+
if (!acc || acc.size === 0) {
|
|
282
|
+
acc = new Set(parameters);
|
|
283
|
+
continue;
|
|
284
|
+
}
|
|
285
|
+
for (const parameter of parameters) {
|
|
286
|
+
if (acc.has(parameter)) {
|
|
287
|
+
return false;
|
|
288
|
+
}
|
|
289
|
+
acc.add(parameter);
|
|
290
|
+
}
|
|
291
|
+
}
|
|
292
|
+
return true;
|
|
293
|
+
}
|
|
294
|
+
const isJWK = (key) => isObject(key) && typeof key.kty === "string";
|
|
295
|
+
const isPrivateJWK = (key) => key.kty !== "oct" && (key.kty === "AKP" && typeof key.priv === "string" || typeof key.d === "string");
|
|
296
|
+
const isPublicJWK = (key) => key.kty !== "oct" && key.d === void 0 && key.priv === void 0;
|
|
297
|
+
const isSecretJWK = (key) => key.kty === "oct" && typeof key.k === "string";
|
|
298
|
+
function checkKeyLength(alg, key) {
|
|
299
|
+
if (alg.startsWith("RS") || alg.startsWith("PS")) {
|
|
300
|
+
const { modulusLength } = key.algorithm;
|
|
301
|
+
if (typeof modulusLength !== "number" || modulusLength < 2048) {
|
|
302
|
+
throw new TypeError(`${alg} requires key modulusLength to be 2048 bits or larger`);
|
|
303
|
+
}
|
|
304
|
+
}
|
|
305
|
+
}
|
|
306
|
+
function subtleAlgorithm(alg, algorithm) {
|
|
307
|
+
const hash = `SHA-${alg.slice(-3)}`;
|
|
308
|
+
switch (alg) {
|
|
309
|
+
case "HS256":
|
|
310
|
+
case "HS384":
|
|
311
|
+
case "HS512":
|
|
312
|
+
return { hash, name: "HMAC" };
|
|
313
|
+
case "PS256":
|
|
314
|
+
case "PS384":
|
|
315
|
+
case "PS512":
|
|
316
|
+
return { hash, name: "RSA-PSS", saltLength: parseInt(alg.slice(-3), 10) >> 3 };
|
|
317
|
+
case "RS256":
|
|
318
|
+
case "RS384":
|
|
319
|
+
case "RS512":
|
|
320
|
+
return { hash, name: "RSASSA-PKCS1-v1_5" };
|
|
321
|
+
case "ES256":
|
|
322
|
+
case "ES384":
|
|
323
|
+
case "ES512":
|
|
324
|
+
return { hash, name: "ECDSA", namedCurve: algorithm.namedCurve };
|
|
325
|
+
case "Ed25519":
|
|
326
|
+
case "EdDSA":
|
|
327
|
+
return { name: "Ed25519" };
|
|
328
|
+
case "ML-DSA-44":
|
|
329
|
+
case "ML-DSA-65":
|
|
330
|
+
case "ML-DSA-87":
|
|
331
|
+
return { name: alg };
|
|
332
|
+
default:
|
|
333
|
+
throw new JOSENotSupported(`alg ${alg} is not supported either by JOSE or your javascript runtime`);
|
|
334
|
+
}
|
|
335
|
+
}
|
|
336
|
+
async function getSigKey(alg, key, usage) {
|
|
337
|
+
if (key instanceof Uint8Array) {
|
|
338
|
+
if (!alg.startsWith("HS")) {
|
|
339
|
+
throw new TypeError(invalidKeyInput(key, "CryptoKey", "KeyObject", "JSON Web Key"));
|
|
340
|
+
}
|
|
341
|
+
return crypto.subtle.importKey("raw", key, { hash: `SHA-${alg.slice(-3)}`, name: "HMAC" }, false, [usage]);
|
|
342
|
+
}
|
|
343
|
+
checkSigCryptoKey(key, alg, usage);
|
|
344
|
+
return key;
|
|
345
|
+
}
|
|
346
|
+
async function verify(alg, key, signature, data) {
|
|
347
|
+
const cryptoKey = await getSigKey(alg, key, "verify");
|
|
348
|
+
checkKeyLength(alg, cryptoKey);
|
|
349
|
+
const algorithm = subtleAlgorithm(alg, cryptoKey.algorithm);
|
|
350
|
+
try {
|
|
351
|
+
return await crypto.subtle.verify(algorithm, cryptoKey, signature, data);
|
|
352
|
+
} catch {
|
|
353
|
+
return false;
|
|
354
|
+
}
|
|
355
|
+
}
|
|
356
|
+
const unsupportedAlg = 'Invalid or unsupported JWK "alg" (Algorithm) Parameter value';
|
|
357
|
+
function subtleMapping(jwk) {
|
|
358
|
+
let algorithm;
|
|
359
|
+
let keyUsages;
|
|
360
|
+
switch (jwk.kty) {
|
|
361
|
+
case "AKP": {
|
|
362
|
+
switch (jwk.alg) {
|
|
363
|
+
case "ML-DSA-44":
|
|
364
|
+
case "ML-DSA-65":
|
|
365
|
+
case "ML-DSA-87":
|
|
366
|
+
algorithm = { name: jwk.alg };
|
|
367
|
+
keyUsages = jwk.priv ? ["sign"] : ["verify"];
|
|
368
|
+
break;
|
|
369
|
+
default:
|
|
370
|
+
throw new JOSENotSupported(unsupportedAlg);
|
|
371
|
+
}
|
|
372
|
+
break;
|
|
373
|
+
}
|
|
374
|
+
case "RSA": {
|
|
375
|
+
switch (jwk.alg) {
|
|
376
|
+
case "PS256":
|
|
377
|
+
case "PS384":
|
|
378
|
+
case "PS512":
|
|
379
|
+
algorithm = { name: "RSA-PSS", hash: `SHA-${jwk.alg.slice(-3)}` };
|
|
380
|
+
keyUsages = jwk.d ? ["sign"] : ["verify"];
|
|
381
|
+
break;
|
|
382
|
+
case "RS256":
|
|
383
|
+
case "RS384":
|
|
384
|
+
case "RS512":
|
|
385
|
+
algorithm = { name: "RSASSA-PKCS1-v1_5", hash: `SHA-${jwk.alg.slice(-3)}` };
|
|
386
|
+
keyUsages = jwk.d ? ["sign"] : ["verify"];
|
|
387
|
+
break;
|
|
388
|
+
case "RSA-OAEP":
|
|
389
|
+
case "RSA-OAEP-256":
|
|
390
|
+
case "RSA-OAEP-384":
|
|
391
|
+
case "RSA-OAEP-512":
|
|
392
|
+
algorithm = {
|
|
393
|
+
name: "RSA-OAEP",
|
|
394
|
+
hash: `SHA-${parseInt(jwk.alg.slice(-3), 10) || 1}`
|
|
395
|
+
};
|
|
396
|
+
keyUsages = jwk.d ? ["decrypt", "unwrapKey"] : ["encrypt", "wrapKey"];
|
|
397
|
+
break;
|
|
398
|
+
default:
|
|
399
|
+
throw new JOSENotSupported(unsupportedAlg);
|
|
400
|
+
}
|
|
401
|
+
break;
|
|
402
|
+
}
|
|
403
|
+
case "EC": {
|
|
404
|
+
switch (jwk.alg) {
|
|
405
|
+
case "ES256":
|
|
406
|
+
case "ES384":
|
|
407
|
+
case "ES512":
|
|
408
|
+
algorithm = {
|
|
409
|
+
name: "ECDSA",
|
|
410
|
+
namedCurve: { ES256: "P-256", ES384: "P-384", ES512: "P-521" }[jwk.alg]
|
|
411
|
+
};
|
|
412
|
+
keyUsages = jwk.d ? ["sign"] : ["verify"];
|
|
413
|
+
break;
|
|
414
|
+
case "ECDH-ES":
|
|
415
|
+
case "ECDH-ES+A128KW":
|
|
416
|
+
case "ECDH-ES+A192KW":
|
|
417
|
+
case "ECDH-ES+A256KW":
|
|
418
|
+
algorithm = { name: "ECDH", namedCurve: jwk.crv };
|
|
419
|
+
keyUsages = jwk.d ? ["deriveBits"] : [];
|
|
420
|
+
break;
|
|
421
|
+
default:
|
|
422
|
+
throw new JOSENotSupported(unsupportedAlg);
|
|
423
|
+
}
|
|
424
|
+
break;
|
|
425
|
+
}
|
|
426
|
+
case "OKP": {
|
|
427
|
+
switch (jwk.alg) {
|
|
428
|
+
case "Ed25519":
|
|
429
|
+
case "EdDSA":
|
|
430
|
+
algorithm = { name: "Ed25519" };
|
|
431
|
+
keyUsages = jwk.d ? ["sign"] : ["verify"];
|
|
432
|
+
break;
|
|
433
|
+
case "ECDH-ES":
|
|
434
|
+
case "ECDH-ES+A128KW":
|
|
435
|
+
case "ECDH-ES+A192KW":
|
|
436
|
+
case "ECDH-ES+A256KW":
|
|
437
|
+
algorithm = { name: jwk.crv };
|
|
438
|
+
keyUsages = jwk.d ? ["deriveBits"] : [];
|
|
439
|
+
break;
|
|
440
|
+
default:
|
|
441
|
+
throw new JOSENotSupported(unsupportedAlg);
|
|
442
|
+
}
|
|
443
|
+
break;
|
|
444
|
+
}
|
|
445
|
+
default:
|
|
446
|
+
throw new JOSENotSupported('Invalid or unsupported JWK "kty" (Key Type) Parameter value');
|
|
447
|
+
}
|
|
448
|
+
return { algorithm, keyUsages };
|
|
449
|
+
}
|
|
450
|
+
async function jwkToKey(jwk) {
|
|
451
|
+
if (!jwk.alg) {
|
|
452
|
+
throw new TypeError('"alg" argument is required when "jwk.alg" is not present');
|
|
453
|
+
}
|
|
454
|
+
const { algorithm, keyUsages } = subtleMapping(jwk);
|
|
455
|
+
const keyData = { ...jwk };
|
|
456
|
+
if (keyData.kty !== "AKP") {
|
|
457
|
+
delete keyData.alg;
|
|
458
|
+
}
|
|
459
|
+
delete keyData.use;
|
|
460
|
+
return crypto.subtle.importKey("jwk", keyData, algorithm, jwk.ext ?? (jwk.d || jwk.priv ? false : true), jwk.key_ops ?? keyUsages);
|
|
461
|
+
}
|
|
462
|
+
const unusableForAlg = "given KeyObject instance cannot be used for this algorithm";
|
|
463
|
+
let cache;
|
|
464
|
+
const handleJWK = async (key, jwk, alg, freeze = false) => {
|
|
465
|
+
cache ||= /* @__PURE__ */ new WeakMap();
|
|
466
|
+
let cached = cache.get(key);
|
|
467
|
+
if (cached?.[alg]) {
|
|
468
|
+
return cached[alg];
|
|
469
|
+
}
|
|
470
|
+
const cryptoKey = await jwkToKey({ ...jwk, alg });
|
|
471
|
+
if (freeze)
|
|
472
|
+
Object.freeze(key);
|
|
473
|
+
if (!cached) {
|
|
474
|
+
cache.set(key, { [alg]: cryptoKey });
|
|
475
|
+
} else {
|
|
476
|
+
cached[alg] = cryptoKey;
|
|
477
|
+
}
|
|
478
|
+
return cryptoKey;
|
|
479
|
+
};
|
|
480
|
+
const handleKeyObject = (keyObject, alg) => {
|
|
481
|
+
cache ||= /* @__PURE__ */ new WeakMap();
|
|
482
|
+
let cached = cache.get(keyObject);
|
|
483
|
+
if (cached?.[alg]) {
|
|
484
|
+
return cached[alg];
|
|
485
|
+
}
|
|
486
|
+
const isPublic = keyObject.type === "public";
|
|
487
|
+
const extractable = isPublic ? true : false;
|
|
488
|
+
let cryptoKey;
|
|
489
|
+
if (keyObject.asymmetricKeyType === "x25519") {
|
|
490
|
+
switch (alg) {
|
|
491
|
+
case "ECDH-ES":
|
|
492
|
+
case "ECDH-ES+A128KW":
|
|
493
|
+
case "ECDH-ES+A192KW":
|
|
494
|
+
case "ECDH-ES+A256KW":
|
|
495
|
+
break;
|
|
496
|
+
default:
|
|
497
|
+
throw new TypeError(unusableForAlg);
|
|
498
|
+
}
|
|
499
|
+
cryptoKey = keyObject.toCryptoKey(keyObject.asymmetricKeyType, extractable, isPublic ? [] : ["deriveBits"]);
|
|
500
|
+
}
|
|
501
|
+
if (keyObject.asymmetricKeyType === "ed25519") {
|
|
502
|
+
if (alg !== "EdDSA" && alg !== "Ed25519") {
|
|
503
|
+
throw new TypeError(unusableForAlg);
|
|
504
|
+
}
|
|
505
|
+
cryptoKey = keyObject.toCryptoKey(keyObject.asymmetricKeyType, extractable, [
|
|
506
|
+
isPublic ? "verify" : "sign"
|
|
507
|
+
]);
|
|
508
|
+
}
|
|
509
|
+
switch (keyObject.asymmetricKeyType) {
|
|
510
|
+
case "ml-dsa-44":
|
|
511
|
+
case "ml-dsa-65":
|
|
512
|
+
case "ml-dsa-87": {
|
|
513
|
+
if (alg !== keyObject.asymmetricKeyType.toUpperCase()) {
|
|
514
|
+
throw new TypeError(unusableForAlg);
|
|
515
|
+
}
|
|
516
|
+
cryptoKey = keyObject.toCryptoKey(keyObject.asymmetricKeyType, extractable, [
|
|
517
|
+
isPublic ? "verify" : "sign"
|
|
518
|
+
]);
|
|
519
|
+
}
|
|
520
|
+
}
|
|
521
|
+
if (keyObject.asymmetricKeyType === "rsa") {
|
|
522
|
+
let hash;
|
|
523
|
+
switch (alg) {
|
|
524
|
+
case "RSA-OAEP":
|
|
525
|
+
hash = "SHA-1";
|
|
526
|
+
break;
|
|
527
|
+
case "RS256":
|
|
528
|
+
case "PS256":
|
|
529
|
+
case "RSA-OAEP-256":
|
|
530
|
+
hash = "SHA-256";
|
|
531
|
+
break;
|
|
532
|
+
case "RS384":
|
|
533
|
+
case "PS384":
|
|
534
|
+
case "RSA-OAEP-384":
|
|
535
|
+
hash = "SHA-384";
|
|
536
|
+
break;
|
|
537
|
+
case "RS512":
|
|
538
|
+
case "PS512":
|
|
539
|
+
case "RSA-OAEP-512":
|
|
540
|
+
hash = "SHA-512";
|
|
541
|
+
break;
|
|
542
|
+
default:
|
|
543
|
+
throw new TypeError(unusableForAlg);
|
|
544
|
+
}
|
|
545
|
+
if (alg.startsWith("RSA-OAEP")) {
|
|
546
|
+
return keyObject.toCryptoKey({
|
|
547
|
+
name: "RSA-OAEP",
|
|
548
|
+
hash
|
|
549
|
+
}, extractable, isPublic ? ["encrypt"] : ["decrypt"]);
|
|
550
|
+
}
|
|
551
|
+
cryptoKey = keyObject.toCryptoKey({
|
|
552
|
+
name: alg.startsWith("PS") ? "RSA-PSS" : "RSASSA-PKCS1-v1_5",
|
|
553
|
+
hash
|
|
554
|
+
}, extractable, [isPublic ? "verify" : "sign"]);
|
|
555
|
+
}
|
|
556
|
+
if (keyObject.asymmetricKeyType === "ec") {
|
|
557
|
+
const nist = /* @__PURE__ */ new Map([
|
|
558
|
+
["prime256v1", "P-256"],
|
|
559
|
+
["secp384r1", "P-384"],
|
|
560
|
+
["secp521r1", "P-521"]
|
|
561
|
+
]);
|
|
562
|
+
const namedCurve = nist.get(keyObject.asymmetricKeyDetails?.namedCurve);
|
|
563
|
+
if (!namedCurve) {
|
|
564
|
+
throw new TypeError(unusableForAlg);
|
|
565
|
+
}
|
|
566
|
+
const expectedCurve = { ES256: "P-256", ES384: "P-384", ES512: "P-521" };
|
|
567
|
+
if (expectedCurve[alg] && namedCurve === expectedCurve[alg]) {
|
|
568
|
+
cryptoKey = keyObject.toCryptoKey({
|
|
569
|
+
name: "ECDSA",
|
|
570
|
+
namedCurve
|
|
571
|
+
}, extractable, [isPublic ? "verify" : "sign"]);
|
|
572
|
+
}
|
|
573
|
+
if (alg.startsWith("ECDH-ES")) {
|
|
574
|
+
cryptoKey = keyObject.toCryptoKey({
|
|
575
|
+
name: "ECDH",
|
|
576
|
+
namedCurve
|
|
577
|
+
}, extractable, isPublic ? [] : ["deriveBits"]);
|
|
578
|
+
}
|
|
579
|
+
}
|
|
580
|
+
if (!cryptoKey) {
|
|
581
|
+
throw new TypeError(unusableForAlg);
|
|
582
|
+
}
|
|
583
|
+
if (!cached) {
|
|
584
|
+
cache.set(keyObject, { [alg]: cryptoKey });
|
|
585
|
+
} else {
|
|
586
|
+
cached[alg] = cryptoKey;
|
|
587
|
+
}
|
|
588
|
+
return cryptoKey;
|
|
589
|
+
};
|
|
590
|
+
async function normalizeKey(key, alg) {
|
|
591
|
+
if (key instanceof Uint8Array) {
|
|
592
|
+
return key;
|
|
593
|
+
}
|
|
594
|
+
if (isCryptoKey(key)) {
|
|
595
|
+
return key;
|
|
596
|
+
}
|
|
597
|
+
if (isKeyObject(key)) {
|
|
598
|
+
if (key.type === "secret") {
|
|
599
|
+
return key.export();
|
|
600
|
+
}
|
|
601
|
+
if ("toCryptoKey" in key && typeof key.toCryptoKey === "function") {
|
|
602
|
+
try {
|
|
603
|
+
return handleKeyObject(key, alg);
|
|
604
|
+
} catch (err) {
|
|
605
|
+
if (err instanceof TypeError) {
|
|
606
|
+
throw err;
|
|
607
|
+
}
|
|
608
|
+
}
|
|
609
|
+
}
|
|
610
|
+
let jwk = key.export({ format: "jwk" });
|
|
611
|
+
return handleJWK(key, jwk, alg);
|
|
612
|
+
}
|
|
613
|
+
if (isJWK(key)) {
|
|
614
|
+
if (key.k) {
|
|
615
|
+
return decode(key.k);
|
|
616
|
+
}
|
|
617
|
+
return handleJWK(key, key, alg, true);
|
|
618
|
+
}
|
|
619
|
+
throw new Error("unreachable");
|
|
620
|
+
}
|
|
621
|
+
async function importJWK(jwk, alg, options) {
|
|
622
|
+
if (!isObject(jwk)) {
|
|
623
|
+
throw new TypeError("JWK must be an object");
|
|
624
|
+
}
|
|
625
|
+
let ext;
|
|
626
|
+
alg ??= jwk.alg;
|
|
627
|
+
ext ??= jwk.ext;
|
|
628
|
+
switch (jwk.kty) {
|
|
629
|
+
case "oct":
|
|
630
|
+
if (typeof jwk.k !== "string" || !jwk.k) {
|
|
631
|
+
throw new TypeError('missing "k" (Key Value) Parameter value');
|
|
632
|
+
}
|
|
633
|
+
return decode(jwk.k);
|
|
634
|
+
case "RSA":
|
|
635
|
+
if ("oth" in jwk && jwk.oth !== void 0) {
|
|
636
|
+
throw new JOSENotSupported('RSA JWK "oth" (Other Primes Info) Parameter value is not supported');
|
|
637
|
+
}
|
|
638
|
+
return jwkToKey({ ...jwk, alg, ext });
|
|
639
|
+
case "AKP": {
|
|
640
|
+
if (typeof jwk.alg !== "string" || !jwk.alg) {
|
|
641
|
+
throw new TypeError('missing "alg" (Algorithm) Parameter value');
|
|
642
|
+
}
|
|
643
|
+
if (alg !== void 0 && alg !== jwk.alg) {
|
|
644
|
+
throw new TypeError("JWK alg and alg option value mismatch");
|
|
645
|
+
}
|
|
646
|
+
return jwkToKey({ ...jwk, ext });
|
|
647
|
+
}
|
|
648
|
+
case "EC":
|
|
649
|
+
case "OKP":
|
|
650
|
+
return jwkToKey({ ...jwk, alg, ext });
|
|
651
|
+
default:
|
|
652
|
+
throw new JOSENotSupported('Unsupported "kty" (Key Type) Parameter value');
|
|
653
|
+
}
|
|
654
|
+
}
|
|
655
|
+
function validateCrit(Err, recognizedDefault, recognizedOption, protectedHeader, joseHeader) {
|
|
656
|
+
if (joseHeader.crit !== void 0 && protectedHeader?.crit === void 0) {
|
|
657
|
+
throw new Err('"crit" (Critical) Header Parameter MUST be integrity protected');
|
|
658
|
+
}
|
|
659
|
+
if (!protectedHeader || protectedHeader.crit === void 0) {
|
|
660
|
+
return /* @__PURE__ */ new Set();
|
|
661
|
+
}
|
|
662
|
+
if (!Array.isArray(protectedHeader.crit) || protectedHeader.crit.length === 0 || protectedHeader.crit.some((input) => typeof input !== "string" || input.length === 0)) {
|
|
663
|
+
throw new Err('"crit" (Critical) Header Parameter MUST be an array of non-empty strings when present');
|
|
664
|
+
}
|
|
665
|
+
let recognized;
|
|
666
|
+
if (recognizedOption !== void 0) {
|
|
667
|
+
recognized = new Map([...Object.entries(recognizedOption), ...recognizedDefault.entries()]);
|
|
668
|
+
} else {
|
|
669
|
+
recognized = recognizedDefault;
|
|
670
|
+
}
|
|
671
|
+
for (const parameter of protectedHeader.crit) {
|
|
672
|
+
if (!recognized.has(parameter)) {
|
|
673
|
+
throw new JOSENotSupported(`Extension Header Parameter "${parameter}" is not recognized`);
|
|
674
|
+
}
|
|
675
|
+
if (joseHeader[parameter] === void 0) {
|
|
676
|
+
throw new Err(`Extension Header Parameter "${parameter}" is missing`);
|
|
677
|
+
}
|
|
678
|
+
if (recognized.get(parameter) && protectedHeader[parameter] === void 0) {
|
|
679
|
+
throw new Err(`Extension Header Parameter "${parameter}" MUST be integrity protected`);
|
|
680
|
+
}
|
|
681
|
+
}
|
|
682
|
+
return new Set(protectedHeader.crit);
|
|
683
|
+
}
|
|
684
|
+
function validateAlgorithms(option, algorithms) {
|
|
685
|
+
if (algorithms !== void 0 && (!Array.isArray(algorithms) || algorithms.some((s) => typeof s !== "string"))) {
|
|
686
|
+
throw new TypeError(`"${option}" option must be an array of strings`);
|
|
687
|
+
}
|
|
688
|
+
if (!algorithms) {
|
|
689
|
+
return void 0;
|
|
690
|
+
}
|
|
691
|
+
return new Set(algorithms);
|
|
692
|
+
}
|
|
693
|
+
const tag = (key) => key?.[Symbol.toStringTag];
|
|
694
|
+
const jwkMatchesOp = (alg, key, usage) => {
|
|
695
|
+
if (key.use !== void 0) {
|
|
696
|
+
let expected;
|
|
697
|
+
switch (usage) {
|
|
698
|
+
case "sign":
|
|
699
|
+
case "verify":
|
|
700
|
+
expected = "sig";
|
|
701
|
+
break;
|
|
702
|
+
case "encrypt":
|
|
703
|
+
case "decrypt":
|
|
704
|
+
expected = "enc";
|
|
705
|
+
break;
|
|
706
|
+
}
|
|
707
|
+
if (key.use !== expected) {
|
|
708
|
+
throw new TypeError(`Invalid key for this operation, its "use" must be "${expected}" when present`);
|
|
709
|
+
}
|
|
710
|
+
}
|
|
711
|
+
if (key.alg !== void 0 && key.alg !== alg) {
|
|
712
|
+
throw new TypeError(`Invalid key for this operation, its "alg" must be "${alg}" when present`);
|
|
713
|
+
}
|
|
714
|
+
if (Array.isArray(key.key_ops)) {
|
|
715
|
+
let expectedKeyOp;
|
|
716
|
+
switch (true) {
|
|
717
|
+
case usage === "verify":
|
|
718
|
+
case alg === "dir":
|
|
719
|
+
case alg.includes("CBC-HS"):
|
|
720
|
+
expectedKeyOp = usage;
|
|
721
|
+
break;
|
|
722
|
+
case alg.startsWith("PBES2"):
|
|
723
|
+
expectedKeyOp = "deriveBits";
|
|
724
|
+
break;
|
|
725
|
+
case /^A\d{3}(?:GCM)?(?:KW)?$/.test(alg):
|
|
726
|
+
if (!alg.includes("GCM") && alg.endsWith("KW")) {
|
|
727
|
+
expectedKeyOp = "unwrapKey";
|
|
728
|
+
} else {
|
|
729
|
+
expectedKeyOp = usage;
|
|
730
|
+
}
|
|
731
|
+
break;
|
|
732
|
+
case usage === "encrypt":
|
|
733
|
+
expectedKeyOp = "wrapKey";
|
|
734
|
+
break;
|
|
735
|
+
case usage === "decrypt":
|
|
736
|
+
expectedKeyOp = alg.startsWith("RSA") ? "unwrapKey" : "deriveBits";
|
|
737
|
+
break;
|
|
738
|
+
}
|
|
739
|
+
if (expectedKeyOp && key.key_ops?.includes?.(expectedKeyOp) === false) {
|
|
740
|
+
throw new TypeError(`Invalid key for this operation, its "key_ops" must include "${expectedKeyOp}" when present`);
|
|
741
|
+
}
|
|
742
|
+
}
|
|
743
|
+
return true;
|
|
744
|
+
};
|
|
745
|
+
const symmetricTypeCheck = (alg, key, usage) => {
|
|
746
|
+
if (key instanceof Uint8Array)
|
|
747
|
+
return;
|
|
748
|
+
if (isJWK(key)) {
|
|
749
|
+
if (isSecretJWK(key) && jwkMatchesOp(alg, key, usage))
|
|
750
|
+
return;
|
|
751
|
+
throw new TypeError(`JSON Web Key for symmetric algorithms must have JWK "kty" (Key Type) equal to "oct" and the JWK "k" (Key Value) present`);
|
|
752
|
+
}
|
|
753
|
+
if (!isKeyLike(key)) {
|
|
754
|
+
throw new TypeError(withAlg(alg, key, "CryptoKey", "KeyObject", "JSON Web Key", "Uint8Array"));
|
|
755
|
+
}
|
|
756
|
+
if (key.type !== "secret") {
|
|
757
|
+
throw new TypeError(`${tag(key)} instances for symmetric algorithms must be of type "secret"`);
|
|
758
|
+
}
|
|
759
|
+
};
|
|
760
|
+
const asymmetricTypeCheck = (alg, key, usage) => {
|
|
761
|
+
if (isJWK(key)) {
|
|
762
|
+
switch (usage) {
|
|
763
|
+
case "decrypt":
|
|
764
|
+
case "sign":
|
|
765
|
+
if (isPrivateJWK(key) && jwkMatchesOp(alg, key, usage))
|
|
766
|
+
return;
|
|
767
|
+
throw new TypeError(`JSON Web Key for this operation must be a private JWK`);
|
|
768
|
+
case "encrypt":
|
|
769
|
+
case "verify":
|
|
770
|
+
if (isPublicJWK(key) && jwkMatchesOp(alg, key, usage))
|
|
771
|
+
return;
|
|
772
|
+
throw new TypeError(`JSON Web Key for this operation must be a public JWK`);
|
|
773
|
+
}
|
|
774
|
+
}
|
|
775
|
+
if (!isKeyLike(key)) {
|
|
776
|
+
throw new TypeError(withAlg(alg, key, "CryptoKey", "KeyObject", "JSON Web Key"));
|
|
777
|
+
}
|
|
778
|
+
if (key.type === "secret") {
|
|
779
|
+
throw new TypeError(`${tag(key)} instances for asymmetric algorithms must not be of type "secret"`);
|
|
780
|
+
}
|
|
781
|
+
if (key.type === "public") {
|
|
782
|
+
switch (usage) {
|
|
783
|
+
case "sign":
|
|
784
|
+
throw new TypeError(`${tag(key)} instances for asymmetric algorithm signing must be of type "private"`);
|
|
785
|
+
case "decrypt":
|
|
786
|
+
throw new TypeError(`${tag(key)} instances for asymmetric algorithm decryption must be of type "private"`);
|
|
787
|
+
}
|
|
788
|
+
}
|
|
789
|
+
if (key.type === "private") {
|
|
790
|
+
switch (usage) {
|
|
791
|
+
case "verify":
|
|
792
|
+
throw new TypeError(`${tag(key)} instances for asymmetric algorithm verifying must be of type "public"`);
|
|
793
|
+
case "encrypt":
|
|
794
|
+
throw new TypeError(`${tag(key)} instances for asymmetric algorithm encryption must be of type "public"`);
|
|
795
|
+
}
|
|
796
|
+
}
|
|
797
|
+
};
|
|
798
|
+
function checkKeyType(alg, key, usage) {
|
|
799
|
+
switch (alg.substring(0, 2)) {
|
|
800
|
+
case "A1":
|
|
801
|
+
case "A2":
|
|
802
|
+
case "di":
|
|
803
|
+
case "HS":
|
|
804
|
+
case "PB":
|
|
805
|
+
symmetricTypeCheck(alg, key, usage);
|
|
806
|
+
break;
|
|
807
|
+
default:
|
|
808
|
+
asymmetricTypeCheck(alg, key, usage);
|
|
809
|
+
}
|
|
810
|
+
}
|
|
811
|
+
async function flattenedVerify(jws, key, options) {
|
|
812
|
+
if (!isObject(jws)) {
|
|
813
|
+
throw new JWSInvalid("Flattened JWS must be an object");
|
|
814
|
+
}
|
|
815
|
+
if (jws.protected === void 0 && jws.header === void 0) {
|
|
816
|
+
throw new JWSInvalid('Flattened JWS must have either of the "protected" or "header" members');
|
|
817
|
+
}
|
|
818
|
+
if (jws.protected !== void 0 && typeof jws.protected !== "string") {
|
|
819
|
+
throw new JWSInvalid("JWS Protected Header incorrect type");
|
|
820
|
+
}
|
|
821
|
+
if (jws.payload === void 0) {
|
|
822
|
+
throw new JWSInvalid("JWS Payload missing");
|
|
823
|
+
}
|
|
824
|
+
if (typeof jws.signature !== "string") {
|
|
825
|
+
throw new JWSInvalid("JWS Signature missing or incorrect type");
|
|
826
|
+
}
|
|
827
|
+
if (jws.header !== void 0 && !isObject(jws.header)) {
|
|
828
|
+
throw new JWSInvalid("JWS Unprotected Header incorrect type");
|
|
829
|
+
}
|
|
830
|
+
let parsedProt = {};
|
|
831
|
+
if (jws.protected) {
|
|
832
|
+
try {
|
|
833
|
+
const protectedHeader = decode(jws.protected);
|
|
834
|
+
parsedProt = JSON.parse(decoder.decode(protectedHeader));
|
|
835
|
+
} catch {
|
|
836
|
+
throw new JWSInvalid("JWS Protected Header is invalid");
|
|
837
|
+
}
|
|
838
|
+
}
|
|
839
|
+
if (!isDisjoint(parsedProt, jws.header)) {
|
|
840
|
+
throw new JWSInvalid("JWS Protected and JWS Unprotected Header Parameter names must be disjoint");
|
|
841
|
+
}
|
|
842
|
+
const joseHeader = {
|
|
843
|
+
...parsedProt,
|
|
844
|
+
...jws.header
|
|
845
|
+
};
|
|
846
|
+
const extensions = validateCrit(JWSInvalid, /* @__PURE__ */ new Map([["b64", true]]), options?.crit, parsedProt, joseHeader);
|
|
847
|
+
let b64 = true;
|
|
848
|
+
if (extensions.has("b64")) {
|
|
849
|
+
b64 = parsedProt.b64;
|
|
850
|
+
if (typeof b64 !== "boolean") {
|
|
851
|
+
throw new JWSInvalid('The "b64" (base64url-encode payload) Header Parameter must be a boolean');
|
|
852
|
+
}
|
|
853
|
+
}
|
|
854
|
+
const { alg } = joseHeader;
|
|
855
|
+
if (typeof alg !== "string" || !alg) {
|
|
856
|
+
throw new JWSInvalid('JWS "alg" (Algorithm) Header Parameter missing or invalid');
|
|
857
|
+
}
|
|
858
|
+
const algorithms = options && validateAlgorithms("algorithms", options.algorithms);
|
|
859
|
+
if (algorithms && !algorithms.has(alg)) {
|
|
860
|
+
throw new JOSEAlgNotAllowed('"alg" (Algorithm) Header Parameter value not allowed');
|
|
861
|
+
}
|
|
862
|
+
if (b64) {
|
|
863
|
+
if (typeof jws.payload !== "string") {
|
|
864
|
+
throw new JWSInvalid("JWS Payload must be a string");
|
|
865
|
+
}
|
|
866
|
+
} else if (typeof jws.payload !== "string" && !(jws.payload instanceof Uint8Array)) {
|
|
867
|
+
throw new JWSInvalid("JWS Payload must be a string or an Uint8Array instance");
|
|
868
|
+
}
|
|
869
|
+
let resolvedKey = false;
|
|
870
|
+
if (typeof key === "function") {
|
|
871
|
+
key = await key(parsedProt, jws);
|
|
872
|
+
resolvedKey = true;
|
|
873
|
+
}
|
|
874
|
+
checkKeyType(alg, key, "verify");
|
|
875
|
+
const data = concat(jws.protected !== void 0 ? encode(jws.protected) : new Uint8Array(), encode("."), typeof jws.payload === "string" ? b64 ? encode(jws.payload) : encoder.encode(jws.payload) : jws.payload);
|
|
876
|
+
const signature = decodeBase64url(jws.signature, "signature", JWSInvalid);
|
|
877
|
+
const k = await normalizeKey(key, alg);
|
|
878
|
+
const verified = await verify(alg, k, signature, data);
|
|
879
|
+
if (!verified) {
|
|
880
|
+
throw new JWSSignatureVerificationFailed();
|
|
881
|
+
}
|
|
882
|
+
let payload;
|
|
883
|
+
if (b64) {
|
|
884
|
+
payload = decodeBase64url(jws.payload, "payload", JWSInvalid);
|
|
885
|
+
} else if (typeof jws.payload === "string") {
|
|
886
|
+
payload = encoder.encode(jws.payload);
|
|
887
|
+
} else {
|
|
888
|
+
payload = jws.payload;
|
|
889
|
+
}
|
|
890
|
+
const result = { payload };
|
|
891
|
+
if (jws.protected !== void 0) {
|
|
892
|
+
result.protectedHeader = parsedProt;
|
|
893
|
+
}
|
|
894
|
+
if (jws.header !== void 0) {
|
|
895
|
+
result.unprotectedHeader = jws.header;
|
|
896
|
+
}
|
|
897
|
+
if (resolvedKey) {
|
|
898
|
+
return { ...result, key: k };
|
|
899
|
+
}
|
|
900
|
+
return result;
|
|
901
|
+
}
|
|
902
|
+
async function compactVerify(jws, key, options) {
|
|
903
|
+
if (jws instanceof Uint8Array) {
|
|
904
|
+
jws = decoder.decode(jws);
|
|
905
|
+
}
|
|
906
|
+
if (typeof jws !== "string") {
|
|
907
|
+
throw new JWSInvalid("Compact JWS must be a string or Uint8Array");
|
|
908
|
+
}
|
|
909
|
+
const { 0: protectedHeader, 1: payload, 2: signature, length } = jws.split(".");
|
|
910
|
+
if (length !== 3) {
|
|
911
|
+
throw new JWSInvalid("Invalid Compact JWS");
|
|
912
|
+
}
|
|
913
|
+
const verified = await flattenedVerify({ payload, protected: protectedHeader, signature }, key, options);
|
|
914
|
+
const result = { payload: verified.payload, protectedHeader: verified.protectedHeader };
|
|
915
|
+
if (typeof key === "function") {
|
|
916
|
+
return { ...result, key: verified.key };
|
|
917
|
+
}
|
|
918
|
+
return result;
|
|
919
|
+
}
|
|
920
|
+
const epoch = (date) => Math.floor(date.getTime() / 1e3);
|
|
921
|
+
const minute = 60;
|
|
922
|
+
const hour = minute * 60;
|
|
923
|
+
const day = hour * 24;
|
|
924
|
+
const week = day * 7;
|
|
925
|
+
const year = day * 365.25;
|
|
926
|
+
const REGEX = /^(\+|\-)? ?(\d+|\d+\.\d+) ?(seconds?|secs?|s|minutes?|mins?|m|hours?|hrs?|h|days?|d|weeks?|w|years?|yrs?|y)(?: (ago|from now))?$/i;
|
|
927
|
+
function secs(str) {
|
|
928
|
+
const matched = REGEX.exec(str);
|
|
929
|
+
if (!matched || matched[4] && matched[1]) {
|
|
930
|
+
throw new TypeError("Invalid time period format");
|
|
931
|
+
}
|
|
932
|
+
const value = parseFloat(matched[2]);
|
|
933
|
+
const unit = matched[3].toLowerCase();
|
|
934
|
+
let numericDate;
|
|
935
|
+
switch (unit) {
|
|
936
|
+
case "sec":
|
|
937
|
+
case "secs":
|
|
938
|
+
case "second":
|
|
939
|
+
case "seconds":
|
|
940
|
+
case "s":
|
|
941
|
+
numericDate = Math.round(value);
|
|
942
|
+
break;
|
|
943
|
+
case "minute":
|
|
944
|
+
case "minutes":
|
|
945
|
+
case "min":
|
|
946
|
+
case "mins":
|
|
947
|
+
case "m":
|
|
948
|
+
numericDate = Math.round(value * minute);
|
|
949
|
+
break;
|
|
950
|
+
case "hour":
|
|
951
|
+
case "hours":
|
|
952
|
+
case "hr":
|
|
953
|
+
case "hrs":
|
|
954
|
+
case "h":
|
|
955
|
+
numericDate = Math.round(value * hour);
|
|
956
|
+
break;
|
|
957
|
+
case "day":
|
|
958
|
+
case "days":
|
|
959
|
+
case "d":
|
|
960
|
+
numericDate = Math.round(value * day);
|
|
961
|
+
break;
|
|
962
|
+
case "week":
|
|
963
|
+
case "weeks":
|
|
964
|
+
case "w":
|
|
965
|
+
numericDate = Math.round(value * week);
|
|
966
|
+
break;
|
|
967
|
+
default:
|
|
968
|
+
numericDate = Math.round(value * year);
|
|
969
|
+
break;
|
|
970
|
+
}
|
|
971
|
+
if (matched[1] === "-" || matched[4] === "ago") {
|
|
972
|
+
return -numericDate;
|
|
973
|
+
}
|
|
974
|
+
return numericDate;
|
|
975
|
+
}
|
|
976
|
+
const normalizeTyp = (value) => {
|
|
977
|
+
if (value.includes("/")) {
|
|
978
|
+
return value.toLowerCase();
|
|
979
|
+
}
|
|
980
|
+
return `application/${value.toLowerCase()}`;
|
|
981
|
+
};
|
|
982
|
+
const checkAudiencePresence = (audPayload, audOption) => {
|
|
983
|
+
if (typeof audPayload === "string") {
|
|
984
|
+
return audOption.includes(audPayload);
|
|
985
|
+
}
|
|
986
|
+
if (Array.isArray(audPayload)) {
|
|
987
|
+
return audOption.some(Set.prototype.has.bind(new Set(audPayload)));
|
|
988
|
+
}
|
|
989
|
+
return false;
|
|
990
|
+
};
|
|
991
|
+
function validateClaimsSet(protectedHeader, encodedPayload, options = {}) {
|
|
992
|
+
let payload;
|
|
993
|
+
try {
|
|
994
|
+
payload = JSON.parse(decoder.decode(encodedPayload));
|
|
995
|
+
} catch {
|
|
996
|
+
}
|
|
997
|
+
if (!isObject(payload)) {
|
|
998
|
+
throw new JWTInvalid("JWT Claims Set must be a top-level JSON object");
|
|
999
|
+
}
|
|
1000
|
+
const { typ } = options;
|
|
1001
|
+
if (typ && (typeof protectedHeader.typ !== "string" || normalizeTyp(protectedHeader.typ) !== normalizeTyp(typ))) {
|
|
1002
|
+
throw new JWTClaimValidationFailed('unexpected "typ" JWT header value', payload, "typ", "check_failed");
|
|
1003
|
+
}
|
|
1004
|
+
const { requiredClaims = [], issuer, subject, audience, maxTokenAge } = options;
|
|
1005
|
+
const presenceCheck = [...requiredClaims];
|
|
1006
|
+
if (maxTokenAge !== void 0)
|
|
1007
|
+
presenceCheck.push("iat");
|
|
1008
|
+
if (audience !== void 0)
|
|
1009
|
+
presenceCheck.push("aud");
|
|
1010
|
+
if (subject !== void 0)
|
|
1011
|
+
presenceCheck.push("sub");
|
|
1012
|
+
if (issuer !== void 0)
|
|
1013
|
+
presenceCheck.push("iss");
|
|
1014
|
+
for (const claim of new Set(presenceCheck.reverse())) {
|
|
1015
|
+
if (!(claim in payload)) {
|
|
1016
|
+
throw new JWTClaimValidationFailed(`missing required "${claim}" claim`, payload, claim, "missing");
|
|
1017
|
+
}
|
|
1018
|
+
}
|
|
1019
|
+
if (issuer && !(Array.isArray(issuer) ? issuer : [issuer]).includes(payload.iss)) {
|
|
1020
|
+
throw new JWTClaimValidationFailed('unexpected "iss" claim value', payload, "iss", "check_failed");
|
|
1021
|
+
}
|
|
1022
|
+
if (subject && payload.sub !== subject) {
|
|
1023
|
+
throw new JWTClaimValidationFailed('unexpected "sub" claim value', payload, "sub", "check_failed");
|
|
1024
|
+
}
|
|
1025
|
+
if (audience && !checkAudiencePresence(payload.aud, typeof audience === "string" ? [audience] : audience)) {
|
|
1026
|
+
throw new JWTClaimValidationFailed('unexpected "aud" claim value', payload, "aud", "check_failed");
|
|
1027
|
+
}
|
|
1028
|
+
let tolerance;
|
|
1029
|
+
switch (typeof options.clockTolerance) {
|
|
1030
|
+
case "string":
|
|
1031
|
+
tolerance = secs(options.clockTolerance);
|
|
1032
|
+
break;
|
|
1033
|
+
case "number":
|
|
1034
|
+
tolerance = options.clockTolerance;
|
|
1035
|
+
break;
|
|
1036
|
+
case "undefined":
|
|
1037
|
+
tolerance = 0;
|
|
1038
|
+
break;
|
|
1039
|
+
default:
|
|
1040
|
+
throw new TypeError("Invalid clockTolerance option type");
|
|
1041
|
+
}
|
|
1042
|
+
const { currentDate } = options;
|
|
1043
|
+
const now = epoch(currentDate || /* @__PURE__ */ new Date());
|
|
1044
|
+
if ((payload.iat !== void 0 || maxTokenAge) && typeof payload.iat !== "number") {
|
|
1045
|
+
throw new JWTClaimValidationFailed('"iat" claim must be a number', payload, "iat", "invalid");
|
|
1046
|
+
}
|
|
1047
|
+
if (payload.nbf !== void 0) {
|
|
1048
|
+
if (typeof payload.nbf !== "number") {
|
|
1049
|
+
throw new JWTClaimValidationFailed('"nbf" claim must be a number', payload, "nbf", "invalid");
|
|
1050
|
+
}
|
|
1051
|
+
if (payload.nbf > now + tolerance) {
|
|
1052
|
+
throw new JWTClaimValidationFailed('"nbf" claim timestamp check failed', payload, "nbf", "check_failed");
|
|
1053
|
+
}
|
|
1054
|
+
}
|
|
1055
|
+
if (payload.exp !== void 0) {
|
|
1056
|
+
if (typeof payload.exp !== "number") {
|
|
1057
|
+
throw new JWTClaimValidationFailed('"exp" claim must be a number', payload, "exp", "invalid");
|
|
1058
|
+
}
|
|
1059
|
+
if (payload.exp <= now - tolerance) {
|
|
1060
|
+
throw new JWTExpired('"exp" claim timestamp check failed', payload, "exp", "check_failed");
|
|
1061
|
+
}
|
|
1062
|
+
}
|
|
1063
|
+
if (maxTokenAge) {
|
|
1064
|
+
const age = now - payload.iat;
|
|
1065
|
+
const max = typeof maxTokenAge === "number" ? maxTokenAge : secs(maxTokenAge);
|
|
1066
|
+
if (age - tolerance > max) {
|
|
1067
|
+
throw new JWTExpired('"iat" claim timestamp check failed (too far in the past)', payload, "iat", "check_failed");
|
|
1068
|
+
}
|
|
1069
|
+
if (age < 0 - tolerance) {
|
|
1070
|
+
throw new JWTClaimValidationFailed('"iat" claim timestamp check failed (it should be in the past)', payload, "iat", "check_failed");
|
|
1071
|
+
}
|
|
1072
|
+
}
|
|
1073
|
+
return payload;
|
|
1074
|
+
}
|
|
1075
|
+
async function jwtVerify(jwt, key, options) {
|
|
1076
|
+
const verified = await compactVerify(jwt, key, options);
|
|
1077
|
+
if (verified.protectedHeader.crit?.includes("b64") && verified.protectedHeader.b64 === false) {
|
|
1078
|
+
throw new JWTInvalid("JWTs MUST NOT use unencoded payload");
|
|
1079
|
+
}
|
|
1080
|
+
const payload = validateClaimsSet(verified.protectedHeader, verified.payload, options);
|
|
1081
|
+
const result = { payload, protectedHeader: verified.protectedHeader };
|
|
1082
|
+
if (typeof key === "function") {
|
|
1083
|
+
return { ...result, key: verified.key };
|
|
1084
|
+
}
|
|
1085
|
+
return result;
|
|
1086
|
+
}
|
|
1087
|
+
function getKtyFromAlg(alg) {
|
|
1088
|
+
switch (typeof alg === "string" && alg.slice(0, 2)) {
|
|
1089
|
+
case "RS":
|
|
1090
|
+
case "PS":
|
|
1091
|
+
return "RSA";
|
|
1092
|
+
case "ES":
|
|
1093
|
+
return "EC";
|
|
1094
|
+
case "Ed":
|
|
1095
|
+
return "OKP";
|
|
1096
|
+
case "ML":
|
|
1097
|
+
return "AKP";
|
|
1098
|
+
default:
|
|
1099
|
+
throw new JOSENotSupported('Unsupported "alg" value for a JSON Web Key Set');
|
|
1100
|
+
}
|
|
1101
|
+
}
|
|
1102
|
+
function isJWKSLike(jwks) {
|
|
1103
|
+
return jwks && typeof jwks === "object" && Array.isArray(jwks.keys) && jwks.keys.every(isJWKLike);
|
|
1104
|
+
}
|
|
1105
|
+
function isJWKLike(key) {
|
|
1106
|
+
return isObject(key);
|
|
1107
|
+
}
|
|
1108
|
+
class LocalJWKSet {
|
|
1109
|
+
#jwks;
|
|
1110
|
+
#cached = /* @__PURE__ */ new WeakMap();
|
|
1111
|
+
constructor(jwks) {
|
|
1112
|
+
if (!isJWKSLike(jwks)) {
|
|
1113
|
+
throw new JWKSInvalid("JSON Web Key Set malformed");
|
|
1114
|
+
}
|
|
1115
|
+
this.#jwks = structuredClone(jwks);
|
|
1116
|
+
}
|
|
1117
|
+
jwks() {
|
|
1118
|
+
return this.#jwks;
|
|
1119
|
+
}
|
|
1120
|
+
async getKey(protectedHeader, token) {
|
|
1121
|
+
const { alg, kid } = { ...protectedHeader, ...token?.header };
|
|
1122
|
+
const kty = getKtyFromAlg(alg);
|
|
1123
|
+
const candidates = this.#jwks.keys.filter((jwk2) => {
|
|
1124
|
+
let candidate = kty === jwk2.kty;
|
|
1125
|
+
if (candidate && typeof kid === "string") {
|
|
1126
|
+
candidate = kid === jwk2.kid;
|
|
1127
|
+
}
|
|
1128
|
+
if (candidate && (typeof jwk2.alg === "string" || kty === "AKP")) {
|
|
1129
|
+
candidate = alg === jwk2.alg;
|
|
1130
|
+
}
|
|
1131
|
+
if (candidate && typeof jwk2.use === "string") {
|
|
1132
|
+
candidate = jwk2.use === "sig";
|
|
1133
|
+
}
|
|
1134
|
+
if (candidate && Array.isArray(jwk2.key_ops)) {
|
|
1135
|
+
candidate = jwk2.key_ops.includes("verify");
|
|
1136
|
+
}
|
|
1137
|
+
if (candidate) {
|
|
1138
|
+
switch (alg) {
|
|
1139
|
+
case "ES256":
|
|
1140
|
+
candidate = jwk2.crv === "P-256";
|
|
1141
|
+
break;
|
|
1142
|
+
case "ES384":
|
|
1143
|
+
candidate = jwk2.crv === "P-384";
|
|
1144
|
+
break;
|
|
1145
|
+
case "ES512":
|
|
1146
|
+
candidate = jwk2.crv === "P-521";
|
|
1147
|
+
break;
|
|
1148
|
+
case "Ed25519":
|
|
1149
|
+
case "EdDSA":
|
|
1150
|
+
candidate = jwk2.crv === "Ed25519";
|
|
1151
|
+
break;
|
|
1152
|
+
}
|
|
1153
|
+
}
|
|
1154
|
+
return candidate;
|
|
1155
|
+
});
|
|
1156
|
+
const { 0: jwk, length } = candidates;
|
|
1157
|
+
if (length === 0) {
|
|
1158
|
+
throw new JWKSNoMatchingKey();
|
|
1159
|
+
}
|
|
1160
|
+
if (length !== 1) {
|
|
1161
|
+
const error = new JWKSMultipleMatchingKeys();
|
|
1162
|
+
const _cached = this.#cached;
|
|
1163
|
+
error[Symbol.asyncIterator] = async function* () {
|
|
1164
|
+
for (const jwk2 of candidates) {
|
|
1165
|
+
try {
|
|
1166
|
+
yield await importWithAlgCache(_cached, jwk2, alg);
|
|
1167
|
+
} catch {
|
|
1168
|
+
}
|
|
1169
|
+
}
|
|
1170
|
+
};
|
|
1171
|
+
throw error;
|
|
1172
|
+
}
|
|
1173
|
+
return importWithAlgCache(this.#cached, jwk, alg);
|
|
1174
|
+
}
|
|
1175
|
+
}
|
|
1176
|
+
async function importWithAlgCache(cache2, jwk, alg) {
|
|
1177
|
+
const cached = cache2.get(jwk) || cache2.set(jwk, {}).get(jwk);
|
|
1178
|
+
if (cached[alg] === void 0) {
|
|
1179
|
+
const key = await importJWK({ ...jwk, ext: true }, alg);
|
|
1180
|
+
if (key instanceof Uint8Array || key.type !== "public") {
|
|
1181
|
+
throw new JWKSInvalid("JSON Web Key Set members must be public keys");
|
|
1182
|
+
}
|
|
1183
|
+
cached[alg] = key;
|
|
1184
|
+
}
|
|
1185
|
+
return cached[alg];
|
|
1186
|
+
}
|
|
1187
|
+
function createLocalJWKSet(jwks) {
|
|
1188
|
+
const set = new LocalJWKSet(jwks);
|
|
1189
|
+
const localJWKSet = async (protectedHeader, token) => set.getKey(protectedHeader, token);
|
|
1190
|
+
Object.defineProperties(localJWKSet, {
|
|
1191
|
+
jwks: {
|
|
1192
|
+
value: () => structuredClone(set.jwks()),
|
|
1193
|
+
enumerable: false,
|
|
1194
|
+
configurable: false,
|
|
1195
|
+
writable: false
|
|
1196
|
+
}
|
|
1197
|
+
});
|
|
1198
|
+
return localJWKSet;
|
|
1199
|
+
}
|
|
1200
|
+
function isCloudflareWorkers() {
|
|
1201
|
+
return typeof WebSocketPair !== "undefined" || typeof navigator !== "undefined" && navigator.userAgent === "Cloudflare-Workers" || typeof EdgeRuntime !== "undefined" && EdgeRuntime === "vercel";
|
|
1202
|
+
}
|
|
1203
|
+
let USER_AGENT;
|
|
1204
|
+
if (typeof navigator === "undefined" || !navigator.userAgent?.startsWith?.("Mozilla/5.0 ")) {
|
|
1205
|
+
const NAME = "jose";
|
|
1206
|
+
const VERSION = "v6.2.2";
|
|
1207
|
+
USER_AGENT = `${NAME}/${VERSION}`;
|
|
1208
|
+
}
|
|
1209
|
+
const customFetch = /* @__PURE__ */ Symbol();
|
|
1210
|
+
async function fetchJwks(url, headers, signal, fetchImpl = fetch) {
|
|
1211
|
+
const response = await fetchImpl(url, {
|
|
1212
|
+
method: "GET",
|
|
1213
|
+
signal,
|
|
1214
|
+
redirect: "manual",
|
|
1215
|
+
headers
|
|
1216
|
+
}).catch((err) => {
|
|
1217
|
+
if (err.name === "TimeoutError") {
|
|
1218
|
+
throw new JWKSTimeout();
|
|
1219
|
+
}
|
|
1220
|
+
throw err;
|
|
1221
|
+
});
|
|
1222
|
+
if (response.status !== 200) {
|
|
1223
|
+
throw new JOSEError("Expected 200 OK from the JSON Web Key Set HTTP response");
|
|
1224
|
+
}
|
|
1225
|
+
try {
|
|
1226
|
+
return await response.json();
|
|
1227
|
+
} catch {
|
|
1228
|
+
throw new JOSEError("Failed to parse the JSON Web Key Set HTTP response as JSON");
|
|
1229
|
+
}
|
|
1230
|
+
}
|
|
1231
|
+
const jwksCache = /* @__PURE__ */ Symbol();
|
|
1232
|
+
function isFreshJwksCache(input, cacheMaxAge) {
|
|
1233
|
+
if (typeof input !== "object" || input === null) {
|
|
1234
|
+
return false;
|
|
1235
|
+
}
|
|
1236
|
+
if (!("uat" in input) || typeof input.uat !== "number" || Date.now() - input.uat >= cacheMaxAge) {
|
|
1237
|
+
return false;
|
|
1238
|
+
}
|
|
1239
|
+
if (!("jwks" in input) || !isObject(input.jwks) || !Array.isArray(input.jwks.keys) || !Array.prototype.every.call(input.jwks.keys, isObject)) {
|
|
1240
|
+
return false;
|
|
1241
|
+
}
|
|
1242
|
+
return true;
|
|
1243
|
+
}
|
|
1244
|
+
class RemoteJWKSet {
|
|
1245
|
+
#url;
|
|
1246
|
+
#timeoutDuration;
|
|
1247
|
+
#cooldownDuration;
|
|
1248
|
+
#cacheMaxAge;
|
|
1249
|
+
#jwksTimestamp;
|
|
1250
|
+
#pendingFetch;
|
|
1251
|
+
#headers;
|
|
1252
|
+
#customFetch;
|
|
1253
|
+
#local;
|
|
1254
|
+
#cache;
|
|
1255
|
+
constructor(url, options) {
|
|
1256
|
+
if (!(url instanceof URL)) {
|
|
1257
|
+
throw new TypeError("url must be an instance of URL");
|
|
1258
|
+
}
|
|
1259
|
+
this.#url = new URL(url.href);
|
|
1260
|
+
this.#timeoutDuration = typeof options?.timeoutDuration === "number" ? options?.timeoutDuration : 5e3;
|
|
1261
|
+
this.#cooldownDuration = typeof options?.cooldownDuration === "number" ? options?.cooldownDuration : 3e4;
|
|
1262
|
+
this.#cacheMaxAge = typeof options?.cacheMaxAge === "number" ? options?.cacheMaxAge : 6e5;
|
|
1263
|
+
this.#headers = new Headers(options?.headers);
|
|
1264
|
+
if (USER_AGENT && !this.#headers.has("User-Agent")) {
|
|
1265
|
+
this.#headers.set("User-Agent", USER_AGENT);
|
|
1266
|
+
}
|
|
1267
|
+
if (!this.#headers.has("accept")) {
|
|
1268
|
+
this.#headers.set("accept", "application/json");
|
|
1269
|
+
this.#headers.append("accept", "application/jwk-set+json");
|
|
1270
|
+
}
|
|
1271
|
+
this.#customFetch = options?.[customFetch];
|
|
1272
|
+
if (options?.[jwksCache] !== void 0) {
|
|
1273
|
+
this.#cache = options?.[jwksCache];
|
|
1274
|
+
if (isFreshJwksCache(options?.[jwksCache], this.#cacheMaxAge)) {
|
|
1275
|
+
this.#jwksTimestamp = this.#cache.uat;
|
|
1276
|
+
this.#local = createLocalJWKSet(this.#cache.jwks);
|
|
1277
|
+
}
|
|
1278
|
+
}
|
|
1279
|
+
}
|
|
1280
|
+
pendingFetch() {
|
|
1281
|
+
return !!this.#pendingFetch;
|
|
1282
|
+
}
|
|
1283
|
+
coolingDown() {
|
|
1284
|
+
return typeof this.#jwksTimestamp === "number" ? Date.now() < this.#jwksTimestamp + this.#cooldownDuration : false;
|
|
1285
|
+
}
|
|
1286
|
+
fresh() {
|
|
1287
|
+
return typeof this.#jwksTimestamp === "number" ? Date.now() < this.#jwksTimestamp + this.#cacheMaxAge : false;
|
|
1288
|
+
}
|
|
1289
|
+
jwks() {
|
|
1290
|
+
return this.#local?.jwks();
|
|
1291
|
+
}
|
|
1292
|
+
async getKey(protectedHeader, token) {
|
|
1293
|
+
if (!this.#local || !this.fresh()) {
|
|
1294
|
+
await this.reload();
|
|
1295
|
+
}
|
|
1296
|
+
try {
|
|
1297
|
+
return await this.#local(protectedHeader, token);
|
|
1298
|
+
} catch (err) {
|
|
1299
|
+
if (err instanceof JWKSNoMatchingKey) {
|
|
1300
|
+
if (this.coolingDown() === false) {
|
|
1301
|
+
await this.reload();
|
|
1302
|
+
return this.#local(protectedHeader, token);
|
|
1303
|
+
}
|
|
1304
|
+
}
|
|
1305
|
+
throw err;
|
|
1306
|
+
}
|
|
1307
|
+
}
|
|
1308
|
+
async reload() {
|
|
1309
|
+
if (this.#pendingFetch && isCloudflareWorkers()) {
|
|
1310
|
+
this.#pendingFetch = void 0;
|
|
1311
|
+
}
|
|
1312
|
+
this.#pendingFetch ||= fetchJwks(this.#url.href, this.#headers, AbortSignal.timeout(this.#timeoutDuration), this.#customFetch).then((json) => {
|
|
1313
|
+
this.#local = createLocalJWKSet(json);
|
|
1314
|
+
if (this.#cache) {
|
|
1315
|
+
this.#cache.uat = Date.now();
|
|
1316
|
+
this.#cache.jwks = json;
|
|
1317
|
+
}
|
|
1318
|
+
this.#jwksTimestamp = Date.now();
|
|
1319
|
+
this.#pendingFetch = void 0;
|
|
1320
|
+
}).catch((err) => {
|
|
1321
|
+
this.#pendingFetch = void 0;
|
|
1322
|
+
throw err;
|
|
1323
|
+
});
|
|
1324
|
+
await this.#pendingFetch;
|
|
1325
|
+
}
|
|
1326
|
+
}
|
|
1327
|
+
function createRemoteJWKSet(url, options) {
|
|
1328
|
+
const set = new RemoteJWKSet(url, options);
|
|
1329
|
+
const remoteJWKSet = async (protectedHeader, token) => set.getKey(protectedHeader, token);
|
|
1330
|
+
Object.defineProperties(remoteJWKSet, {
|
|
1331
|
+
coolingDown: {
|
|
1332
|
+
get: () => set.coolingDown(),
|
|
1333
|
+
enumerable: true,
|
|
1334
|
+
configurable: false
|
|
1335
|
+
},
|
|
1336
|
+
fresh: {
|
|
1337
|
+
get: () => set.fresh(),
|
|
1338
|
+
enumerable: true,
|
|
1339
|
+
configurable: false
|
|
1340
|
+
},
|
|
1341
|
+
reload: {
|
|
1342
|
+
value: () => set.reload(),
|
|
1343
|
+
enumerable: true,
|
|
1344
|
+
configurable: false,
|
|
1345
|
+
writable: false
|
|
1346
|
+
},
|
|
1347
|
+
reloading: {
|
|
1348
|
+
get: () => set.pendingFetch(),
|
|
1349
|
+
enumerable: true,
|
|
1350
|
+
configurable: false
|
|
1351
|
+
},
|
|
1352
|
+
jwks: {
|
|
1353
|
+
value: () => set.jwks(),
|
|
1354
|
+
enumerable: true,
|
|
1355
|
+
configurable: false,
|
|
1356
|
+
writable: false
|
|
1357
|
+
}
|
|
1358
|
+
});
|
|
1359
|
+
return remoteJWKSet;
|
|
1360
|
+
}
|
|
1361
|
+
function decodeJwt(jwt) {
|
|
1362
|
+
if (typeof jwt !== "string")
|
|
1363
|
+
throw new JWTInvalid("JWTs must use Compact JWS serialization, JWT must be a string");
|
|
1364
|
+
const { 1: payload, length } = jwt.split(".");
|
|
1365
|
+
if (length === 5)
|
|
1366
|
+
throw new JWTInvalid("Only JWTs using Compact JWS serialization can be decoded");
|
|
1367
|
+
if (length !== 3)
|
|
1368
|
+
throw new JWTInvalid("Invalid JWT");
|
|
1369
|
+
if (!payload)
|
|
1370
|
+
throw new JWTInvalid("JWTs must contain a payload");
|
|
1371
|
+
let decoded;
|
|
1372
|
+
try {
|
|
1373
|
+
decoded = decode(payload);
|
|
1374
|
+
} catch {
|
|
1375
|
+
throw new JWTInvalid("Failed to base64url decode the payload");
|
|
1376
|
+
}
|
|
1377
|
+
let result;
|
|
1378
|
+
try {
|
|
1379
|
+
result = JSON.parse(decoder.decode(decoded));
|
|
1380
|
+
} catch {
|
|
1381
|
+
throw new JWTInvalid("Failed to parse the decoded payload as JSON");
|
|
1382
|
+
}
|
|
1383
|
+
if (!isObject(result))
|
|
1384
|
+
throw new JWTInvalid("Invalid JWT Claims Set");
|
|
1385
|
+
return result;
|
|
1386
|
+
}
|
|
1387
|
+
export {
|
|
1388
|
+
JWTExpired as J,
|
|
1389
|
+
JWTClaimValidationFailed as a,
|
|
1390
|
+
JWSSignatureVerificationFailed as b,
|
|
1391
|
+
createRemoteJWKSet as c,
|
|
1392
|
+
decodeJwt as d,
|
|
1393
|
+
jwtVerify as j
|
|
1394
|
+
};
|
|
1395
|
+
//# sourceMappingURL=decode_jwt-D2OK1b8a.js.map
|