@gusto/baerly-storage 0.1.0

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