@claxedo/workspace-relay-protocol 0.1.0 → 0.5.1

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