@gusto/baerly-storage 0.6.0 → 0.7.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 (218) hide show
  1. package/README.md +47 -124
  2. package/dist/API.md +161 -512
  3. package/dist/CHANGELOG.md +1137 -378
  4. package/dist/RECIPES.md +398 -80
  5. package/dist/THIRD-PARTY-LICENSES.txt +5 -26
  6. package/dist/{app-config-DyiFK3_k.d.ts → app-config-C6qW7m8S.d.ts} +119 -111
  7. package/dist/app-config.d.ts +31 -1
  8. package/dist/app-config.js +1 -2
  9. package/dist/app-config.js.map +1 -1
  10. package/dist/auth.d.ts +33 -28
  11. package/dist/auth.js +549 -985
  12. package/dist/auth.js.map +1 -1
  13. package/dist/baerly.js +130 -138
  14. package/dist/baerly.js.map +1 -1
  15. package/dist/baerly.spec.json +97 -22
  16. package/dist/capacity-warning-header-BlVopyiI.js +16 -0
  17. package/dist/capacity-warning-header-BlVopyiI.js.map +1 -0
  18. package/dist/{client-ypCm3zjt.d.ts → client-CHQTXpef.d.ts} +121 -36
  19. package/dist/client-react.d.ts +67 -20
  20. package/dist/client-react.js +240 -54
  21. package/dist/client-react.js.map +1 -1
  22. package/dist/client.d.ts +5 -4
  23. package/dist/client.js +51 -16
  24. package/dist/client.js.map +1 -1
  25. package/dist/{cloudflare-wrVYf4bb.js → cloudflare-CKHYXccw.js} +61 -82
  26. package/dist/cloudflare-CKHYXccw.js.map +1 -0
  27. package/dist/cloudflare.d.ts +106 -71
  28. package/dist/cloudflare.js +334 -271
  29. package/dist/cloudflare.js.map +1 -1
  30. package/dist/code-resolution-CL_7L0wS.js +22 -0
  31. package/dist/code-resolution-CL_7L0wS.js.map +1 -0
  32. package/dist/collection-api-DbyhLAY8.d.ts +1001 -0
  33. package/dist/config-DEzInG6M.js +4035 -0
  34. package/dist/config-DEzInG6M.js.map +1 -0
  35. package/dist/constants-D3GSH3tc.js +469 -0
  36. package/dist/constants-D3GSH3tc.js.map +1 -0
  37. package/dist/{context-DRZ3tZ5l.js → context-rlpSnHFA.js} +17 -17
  38. package/dist/context-rlpSnHFA.js.map +1 -0
  39. package/dist/cost-B52llVDx.js +330 -0
  40. package/dist/cost-B52llVDx.js.map +1 -0
  41. package/dist/{current-json-C6nhPOm1.js → current-json-CC6lE4Aj.js} +115 -32
  42. package/dist/current-json-CC6lE4Aj.js.map +1 -0
  43. package/dist/db-plFUNTSF.d.ts +130 -0
  44. package/dist/db-read-seams-BSs0m1z1.js +3261 -0
  45. package/dist/db-read-seams-BSs0m1z1.js.map +1 -0
  46. package/dist/{deploy-Di_Q01qx.js → deploy-Obj4nE-Z.js} +10 -14
  47. package/dist/deploy-Obj4nE-Z.js.map +1 -0
  48. package/dist/{dev-banner-CWHIk8tH.d.ts → dev-banner-B5AUHmu1.d.ts} +1 -4
  49. package/dist/dev-landing-BI5UdmOb.d.ts +32 -0
  50. package/dist/dev-landing-CD-si4dW.js +50 -0
  51. package/dist/dev-landing-CD-si4dW.js.map +1 -0
  52. package/dist/dev-vite.d.ts +9 -14
  53. package/dist/dev-vite.js +11 -10
  54. package/dist/dev-vite.js.map +1 -1
  55. package/dist/dev.d.ts +3 -2
  56. package/dist/dev.js +2 -1
  57. package/dist/doctor-BA0i-YAN.js +270 -0
  58. package/dist/doctor-BA0i-YAN.js.map +1 -0
  59. package/dist/dump-D1vX8ozg.js +133 -0
  60. package/dist/dump-D1vX8ozg.js.map +1 -0
  61. package/dist/errors-7Rk1HGCE.js +160 -0
  62. package/dist/errors-7Rk1HGCE.js.map +1 -0
  63. package/dist/{validate-DtljsCh1.js → export-BVL2EvYE.js} +409 -19
  64. package/dist/export-BVL2EvYE.js.map +1 -0
  65. package/dist/fsck-BWkPgov4.js +145 -0
  66. package/dist/fsck-BWkPgov4.js.map +1 -0
  67. package/dist/{gcs-admin-Bx6xSNJj.d.ts → gcs-admin-Dso1HWQj.d.ts} +18 -14
  68. package/dist/gcs.d.ts +19 -7
  69. package/dist/gcs.js +1 -2
  70. package/dist/{goog4-signer-Z7KnJ1su.js → goog4-signer-CeLIABoE.js} +102 -92
  71. package/dist/goog4-signer-CeLIABoE.js.map +1 -0
  72. package/dist/{http-7zT29K3P.js → http-Z5rZyYMX.js} +898 -271
  73. package/dist/http-Z5rZyYMX.js.map +1 -0
  74. package/dist/http-transport-DNUM8kU-.js +1299 -0
  75. package/dist/http-transport-DNUM8kU-.js.map +1 -0
  76. package/dist/http.d.ts +366 -294
  77. package/dist/http.js +2 -2
  78. package/dist/index-JJrIu1pO.d.ts +135 -0
  79. package/dist/index-LEgHN0qJ.d.ts +50 -0
  80. package/dist/{index-DP3ClvcA.d.ts → index-RiEYj8t0.d.ts} +291 -78
  81. package/dist/index.d.ts +27 -6
  82. package/dist/index.js +3 -5
  83. package/dist/inspect-BTsVYZKd.js +196 -0
  84. package/dist/inspect-BTsVYZKd.js.map +1 -0
  85. package/dist/{key-Di6yyxFu.js → key-C4FPZ9Io.js} +3 -4
  86. package/dist/{key-Di6yyxFu.js.map → key-C4FPZ9Io.js.map} +1 -1
  87. package/dist/ledger-Dj_bGgo0.js +192 -0
  88. package/dist/ledger-Dj_bGgo0.js.map +1 -0
  89. package/dist/legacy-names-DgZBtgOh.js +47 -0
  90. package/dist/legacy-names-DgZBtgOh.js.map +1 -0
  91. package/dist/log-C9W15Dfo.d.ts +94 -0
  92. package/dist/log-tail-DWJbneBF.js +142 -0
  93. package/dist/log-tail-DWJbneBF.js.map +1 -0
  94. package/dist/log-walk-C-vA-WGJ.js +111 -0
  95. package/dist/log-walk-C-vA-WGJ.js.map +1 -0
  96. package/dist/maintenance-Dd-Yakqj.js +1709 -0
  97. package/dist/maintenance-Dd-Yakqj.js.map +1 -0
  98. package/dist/maintenance-DevB6z4e.js +2237 -0
  99. package/dist/maintenance-DevB6z4e.js.map +1 -0
  100. package/dist/maintenance.d.ts +100 -3
  101. package/dist/maintenance.js +1 -3
  102. package/dist/node.d.ts +119 -92
  103. package/dist/node.js +3 -3
  104. package/dist/{observability-Ch-VQJyE.js → observability-C-ISCCLE.js} +1247 -326
  105. package/dist/observability-C-ISCCLE.js.map +1 -0
  106. package/dist/observability.d.ts +27 -3
  107. package/dist/observability.js +3 -3
  108. package/dist/path-segment-DBXG26PW.js +363 -0
  109. package/dist/path-segment-DBXG26PW.js.map +1 -0
  110. package/dist/{plan-C4qgiXSg.js → plan-BvQbaNMe.js} +19 -11
  111. package/dist/plan-BvQbaNMe.js.map +1 -0
  112. package/dist/request-CRWiTrza.js +272 -0
  113. package/dist/request-CRWiTrza.js.map +1 -0
  114. package/dist/restore-U6Im8V1V.js +1467 -0
  115. package/dist/restore-U6Im8V1V.js.map +1 -0
  116. package/dist/retry-OBtLB2GC.js +126 -0
  117. package/dist/retry-OBtLB2GC.js.map +1 -0
  118. package/dist/rolldown-runtime-D3KUYPsf.js +12 -0
  119. package/dist/{runtime-spec--LykAdl1.js → runtime-spec-B5mg3pHF.js} +189 -28
  120. package/dist/runtime-spec-B5mg3pHF.js.map +1 -0
  121. package/dist/{s3-http-DD5gDc7t.d.ts → s3-http-DBC_wiCL.d.ts} +14 -8
  122. package/dist/s3.d.ts +20 -7
  123. package/dist/s3.js +4 -5
  124. package/dist/s3.js.map +1 -1
  125. package/dist/{sha256-CqcKTjw9.js → sha256-4FfGQNPw.js} +9 -9
  126. package/dist/sha256-4FfGQNPw.js.map +1 -0
  127. package/dist/{shared-secret-DgEicd3x.js → shared-secret-Vkur-8r0.js} +27 -15
  128. package/dist/shared-secret-Vkur-8r0.js.map +1 -0
  129. package/dist/{aws4fetch.esm-CXE5ZbAa.js → sigv4-sign-5IUflUD_.js} +143 -96
  130. package/dist/sigv4-sign-5IUflUD_.js.map +1 -0
  131. package/dist/snapshot-CknzkDM0.js +148 -0
  132. package/dist/snapshot-CknzkDM0.js.map +1 -0
  133. package/dist/{src-BMFfDUI2.js → src-Actga-bO.js} +949 -363
  134. package/dist/src-Actga-bO.js.map +1 -0
  135. package/dist/src-D0MQfvOp.js +812 -0
  136. package/dist/src-D0MQfvOp.js.map +1 -0
  137. package/dist/src-Dr9uo3dc.js +501 -0
  138. package/dist/src-Dr9uo3dc.js.map +1 -0
  139. package/dist/{subcommand-BV68pqwJ.js → subcommand-BLoF66dG.js} +89 -16
  140. package/dist/subcommand-BLoF66dG.js.map +1 -0
  141. package/dist/{time-DUqvFMHq.js → time-DRxTP9iv.js} +15 -34
  142. package/dist/time-DRxTP9iv.js.map +1 -0
  143. package/dist/types-suVbsEWS.d.ts +116 -0
  144. package/dist/{usage-BMZR8o6U.js → usage-CPzVhrQr.js} +40 -45
  145. package/dist/usage-CPzVhrQr.js.map +1 -0
  146. package/dist/uuid-BuT_c404.js +333 -0
  147. package/dist/uuid-BuT_c404.js.map +1 -0
  148. package/dist/verifier-Bmlmndzo.d.ts +95 -0
  149. package/dist/{wire-izfGZDvr.js → wire-DndvKU-K.js} +2 -3
  150. package/dist/wire-DndvKU-K.js.map +1 -0
  151. package/package.json +90 -69
  152. package/dist/aws4fetch.esm-CXE5ZbAa.js.map +0 -1
  153. package/dist/bytes-BXdamO3L.js +0 -11
  154. package/dist/bytes-BXdamO3L.js.map +0 -1
  155. package/dist/cloudflare-wrVYf4bb.js.map +0 -1
  156. package/dist/config-B6nTy8e2.js +0 -3095
  157. package/dist/config-B6nTy8e2.js.map +0 -1
  158. package/dist/constants-CfeMWQWk.js +0 -222
  159. package/dist/constants-CfeMWQWk.js.map +0 -1
  160. package/dist/context-DRZ3tZ5l.js.map +0 -1
  161. package/dist/cost-_SE_SVgZ.js +0 -203
  162. package/dist/cost-_SE_SVgZ.js.map +0 -1
  163. package/dist/current-json-C6nhPOm1.js.map +0 -1
  164. package/dist/db-DjjthkTi.d.ts +0 -254
  165. package/dist/deploy-Di_Q01qx.js.map +0 -1
  166. package/dist/doctor-RWVRpvat.js +0 -102
  167. package/dist/doctor-RWVRpvat.js.map +0 -1
  168. package/dist/dump-m2vEYDNY.js +0 -94
  169. package/dist/dump-m2vEYDNY.js.map +0 -1
  170. package/dist/errors-Dfa3p78c.js +0 -78
  171. package/dist/errors-Dfa3p78c.js.map +0 -1
  172. package/dist/export-DenKwEQu.js +0 -401
  173. package/dist/export-DenKwEQu.js.map +0 -1
  174. package/dist/fsck-2Vq-7-e2.js +0 -279
  175. package/dist/fsck-2Vq-7-e2.js.map +0 -1
  176. package/dist/goog4-signer-Z7KnJ1su.js.map +0 -1
  177. package/dist/http-7zT29K3P.js.map +0 -1
  178. package/dist/http-transport-BTgVCY5r.js +0 -1250
  179. package/dist/http-transport-BTgVCY5r.js.map +0 -1
  180. package/dist/index-BHz92Acj.d.ts +0 -162
  181. package/dist/index-CEZKQsKt.d.ts +0 -1113
  182. package/dist/index-uE-w2dgj.d.ts +0 -115
  183. package/dist/indexes-Dn9hbGQG.d.ts +0 -22
  184. package/dist/inspect-BpYbH1DM.js +0 -133
  185. package/dist/inspect-BpYbH1DM.js.map +0 -1
  186. package/dist/log-tail-QWU4wlu-.js +0 -514
  187. package/dist/log-tail-QWU4wlu-.js.map +0 -1
  188. package/dist/maintenance-BGHGt2Yg.d.ts +0 -537
  189. package/dist/maintenance-DULFcpd1.js +0 -2144
  190. package/dist/maintenance-DULFcpd1.js.map +0 -1
  191. package/dist/maintenance-fEi-UZ2o.js +0 -1412
  192. package/dist/maintenance-fEi-UZ2o.js.map +0 -1
  193. package/dist/normalize-rjnZLwS4.js +0 -133
  194. package/dist/normalize-rjnZLwS4.js.map +0 -1
  195. package/dist/observability-Ch-VQJyE.js.map +0 -1
  196. package/dist/plan-C4qgiXSg.js.map +0 -1
  197. package/dist/query-C43r-6ib.js +0 -1773
  198. package/dist/query-C43r-6ib.js.map +0 -1
  199. package/dist/rebuild-index-BH1dc1p6.js +0 -81
  200. package/dist/rebuild-index-BH1dc1p6.js.map +0 -1
  201. package/dist/request-u0M51mhJ.js +0 -72
  202. package/dist/request-u0M51mhJ.js.map +0 -1
  203. package/dist/restore-D0VYWzfP.js +0 -778
  204. package/dist/restore-D0VYWzfP.js.map +0 -1
  205. package/dist/rolldown-runtime-EAsCxrDo.js +0 -14
  206. package/dist/runtime-spec--LykAdl1.js.map +0 -1
  207. package/dist/sha256-CqcKTjw9.js.map +0 -1
  208. package/dist/shared-secret-DgEicd3x.js.map +0 -1
  209. package/dist/src-BMFfDUI2.js.map +0 -1
  210. package/dist/src-DYZ4H1aF.js +0 -392
  211. package/dist/src-DYZ4H1aF.js.map +0 -1
  212. package/dist/src-DvbTEya2.js +0 -536
  213. package/dist/src-DvbTEya2.js.map +0 -1
  214. package/dist/subcommand-BV68pqwJ.js.map +0 -1
  215. package/dist/time-DUqvFMHq.js.map +0 -1
  216. package/dist/usage-BMZR8o6U.js.map +0 -1
  217. package/dist/validate-DtljsCh1.js.map +0 -1
  218. package/dist/wire-izfGZDvr.js.map +0 -1
package/dist/auth.js CHANGED
@@ -1,19 +1,21 @@
1
- import { n as BEARER_JWT_CONFIG_RESOLUTION, r as CLOUDFLARE_ACCESS_CONFIG_RESOLUTION, t as sharedSecret } from "./shared-secret-DgEicd3x.js";
2
- import { t as BaerlyError } from "./errors-Dfa3p78c.js";
3
- //#region node_modules/.pnpm/jose@6.2.3/node_modules/jose/dist/webapi/lib/buffer_utils.js
1
+ import { i as CLOUDFLARE_ACCESS_CONFIG_RESOLUTION, n as BEARER_JWT_CONFIG_RESOLUTION, r as CF_ACCESS_TEAM_NAME_PATTERN, t as sharedSecret } from "./shared-secret-Vkur-8r0.js";
2
+ import { t as BaerlyError } from "./errors-7Rk1HGCE.js";
3
+ // node_modules/.pnpm/jose@6.2.17/node_modules/jose/dist/webapi/lib/buffer_utils.js
4
4
  const encoder = new TextEncoder();
5
5
  const decoder = new TextDecoder();
6
+ const strictDecoder = new TextDecoder("utf-8", { fatal: !0 });
6
7
  function concat(...buffers) {
7
- const size = buffers.reduce((acc, { length }) => acc + length, 0);
8
- const buf = new Uint8Array(size);
8
+ const size = buffers.reduce((acc, { length }) => acc + length, 0), buf = new Uint8Array(size);
9
9
  let i = 0;
10
- for (const buffer of buffers) {
11
- buf.set(buffer, i);
12
- i += buffer.length;
13
- }
10
+ for (const buffer of buffers) buf.set(buffer, i), i += buffer.length;
14
11
  return buf;
15
12
  }
13
+ const NON_ASCII = /[^\x00-\x7f]/;
16
14
  function encode(string) {
15
+ if (typeof string == "string" && string.length >= 128) {
16
+ if (NON_ASCII.test(string)) throw new TypeError("non-ASCII string encountered in encode()");
17
+ return encoder.encode(string);
18
+ }
17
19
  const bytes = new Uint8Array(string.length);
18
20
  for (let i = 0; i < string.length; i++) {
19
21
  const code = string.charCodeAt(i);
@@ -22,37 +24,22 @@ function encode(string) {
22
24
  }
23
25
  return bytes;
24
26
  }
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);
27
+ function decodeBase64(encoded, url = !1) {
28
+ if (Uint8Array.fromBase64) return Uint8Array.fromBase64(encoded, { alphabet: url ? "base64url" : "base64" });
29
+ if (url) {
30
+ if (encoded.includes("+") || encoded.includes("/")) throw new TypeError("Invalid base64url");
31
+ encoded = encoded.replace(/-/g, "+").replace(/_/g, "/");
32
+ }
33
+ const binary = atob(encoded), bytes = new Uint8Array(binary.length);
31
34
  for (let i = 0; i < binary.length; i++) bytes[i] = binary.charCodeAt(i);
32
35
  return bytes;
33
36
  }
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/util/errors.js
37
+ // node_modules/.pnpm/jose@6.2.17/node_modules/jose/dist/webapi/util/errors.js
49
38
  var JOSEError = class extends Error {
50
39
  static code = "ERR_JOSE_GENERIC";
51
40
  code = "ERR_JOSE_GENERIC";
52
41
  constructor(message, options) {
53
- super(message, options);
54
- this.name = this.constructor.name;
55
- Error.captureStackTrace?.(this, this.constructor);
42
+ super(message, options), this.name = this.constructor.name, Error.captureStackTrace?.(this, this.constructor);
56
43
  }
57
44
  };
58
45
  var JWTClaimValidationFailed = class extends JOSEError {
@@ -66,10 +53,7 @@ var JWTClaimValidationFailed = class extends JOSEError {
66
53
  claim,
67
54
  reason,
68
55
  payload
69
- } });
70
- this.claim = claim;
71
- this.reason = reason;
72
- this.payload = payload;
56
+ } }), this.claim = claim, this.reason = reason, this.payload = payload;
73
57
  }
74
58
  };
75
59
  var JWTExpired = class extends JOSEError {
@@ -83,10 +67,7 @@ var JWTExpired = class extends JOSEError {
83
67
  claim,
84
68
  reason,
85
69
  payload
86
- } });
87
- this.claim = claim;
88
- this.reason = reason;
89
- this.payload = payload;
70
+ } }), this.claim = claim, this.reason = reason, this.payload = payload;
90
71
  }
91
72
  };
92
73
  var JOSEAlgNotAllowed = class extends JOSEError {
@@ -117,7 +98,7 @@ var JWKSNoMatchingKey = class extends JOSEError {
117
98
  }
118
99
  };
119
100
  var JWKSMultipleMatchingKeys = class extends JOSEError {
120
- [Symbol.asyncIterator];
101
+ [Symbol.asyncIterator] = async function* () {};
121
102
  static code = "ERR_JWKS_MULTIPLE_MATCHING_KEYS";
122
103
  code = "ERR_JWKS_MULTIPLE_MATCHING_KEYS";
123
104
  constructor(message = "multiple matching keys found in the JSON Web Key Set", options) {
@@ -138,891 +119,509 @@ var JWSSignatureVerificationFailed = class extends JOSEError {
138
119
  super(message, options);
139
120
  }
140
121
  };
141
- //#endregion
142
- //#region node_modules/.pnpm/jose@6.2.3/node_modules/jose/dist/webapi/lib/crypto_key.js
143
- const unusable = (name, prop = "algorithm.name") => /* @__PURE__ */ new TypeError(`CryptoKey does not support this operation, its ${prop} must be ${name}`);
144
- const isAlgorithm = (algorithm, name) => algorithm.name === name;
145
- function getHashLength(hash) {
146
- return parseInt(hash.name.slice(4), 10);
147
- }
148
- function checkHashLength(algorithm, expected) {
149
- if (getHashLength(algorithm.hash) !== expected) throw unusable(`SHA-${expected}`, "algorithm.hash");
150
- }
151
- function getNamedCurve(alg) {
152
- switch (alg) {
153
- case "ES256": return "P-256";
154
- case "ES384": return "P-384";
155
- case "ES512": return "P-521";
156
- default: throw new Error("unreachable");
157
- }
158
- }
159
- function checkUsage(key, usage) {
160
- if (usage && !key.usages.includes(usage)) throw new TypeError(`CryptoKey does not support this operation, its usages must include ${usage}.`);
161
- }
162
- function checkSigCryptoKey(key, alg, usage) {
163
- switch (alg) {
164
- case "HS256":
165
- case "HS384":
166
- case "HS512":
167
- if (!isAlgorithm(key.algorithm, "HMAC")) throw unusable("HMAC");
168
- checkHashLength(key.algorithm, parseInt(alg.slice(2), 10));
169
- break;
170
- case "RS256":
171
- case "RS384":
172
- case "RS512":
173
- if (!isAlgorithm(key.algorithm, "RSASSA-PKCS1-v1_5")) throw unusable("RSASSA-PKCS1-v1_5");
174
- checkHashLength(key.algorithm, parseInt(alg.slice(2), 10));
175
- break;
176
- case "PS256":
177
- case "PS384":
178
- case "PS512":
179
- if (!isAlgorithm(key.algorithm, "RSA-PSS")) throw unusable("RSA-PSS");
180
- checkHashLength(key.algorithm, parseInt(alg.slice(2), 10));
181
- break;
182
- case "Ed25519":
183
- case "EdDSA":
184
- if (!isAlgorithm(key.algorithm, "Ed25519")) throw unusable("Ed25519");
185
- break;
186
- case "ML-DSA-44":
187
- case "ML-DSA-65":
188
- case "ML-DSA-87":
189
- if (!isAlgorithm(key.algorithm, alg)) throw unusable(alg);
190
- break;
191
- case "ES256":
192
- case "ES384":
193
- case "ES512": {
194
- if (!isAlgorithm(key.algorithm, "ECDSA")) throw unusable("ECDSA");
195
- const expected = getNamedCurve(alg);
196
- if (key.algorithm.namedCurve !== expected) throw unusable(expected, "algorithm.namedCurve");
197
- break;
198
- }
199
- default: throw new TypeError("CryptoKey does not support this operation");
122
+ // node_modules/.pnpm/jose@6.2.17/node_modules/jose/dist/webapi/util/base64url.js
123
+ const invalid = "The input to be decoded is not correctly encoded.";
124
+ function decode(input) {
125
+ try {
126
+ return decodeBase64(typeof input == "string" ? input : decoder.decode(input), !0);
127
+ } catch (cause) {
128
+ throw new TypeError(invalid, { cause });
200
129
  }
201
- checkUsage(key, usage);
202
130
  }
203
- //#endregion
204
- //#region node_modules/.pnpm/jose@6.2.3/node_modules/jose/dist/webapi/lib/invalid_key_input.js
205
- function message(msg, actual, ...types) {
206
- types = types.filter(Boolean);
207
- if (types.length > 2) {
208
- const last = types.pop();
209
- msg += `one of type ${types.join(", ")}, or ${last}.`;
210
- } else if (types.length === 2) msg += `one of type ${types[0]} or ${types[1]}.`;
211
- else msg += `of type ${types[0]}.`;
212
- if (actual == null) msg += ` Received ${actual}`;
213
- else if (typeof actual === "function" && actual.name) msg += ` Received function ${actual.name}`;
214
- else if (typeof actual === "object" && actual != null) {
215
- if (actual.constructor?.name) msg += ` Received an instance of ${actual.constructor.name}`;
216
- }
217
- return msg;
131
+ // node_modules/.pnpm/jose@6.2.17/node_modules/jose/dist/webapi/lib/validate.js
132
+ function isObject(input) {
133
+ if (typeof input != "object" || input === null || Object.prototype.toString.call(input) !== "[object Object]") return !1;
134
+ const prototype = Object.getPrototypeOf(input);
135
+ return prototype === null || Object.getPrototypeOf(prototype) === null;
218
136
  }
219
- const invalidKeyInput = (actual, ...types) => message("Key must be ", actual, ...types);
220
- const withAlg = (alg, actual, ...types) => message(`Key for the ${alg} algorithm must be `, actual, ...types);
221
- //#endregion
222
- //#region node_modules/.pnpm/jose@6.2.3/node_modules/jose/dist/webapi/lib/signing.js
223
- function checkKeyLength(alg, key) {
224
- if (alg.startsWith("RS") || alg.startsWith("PS")) {
225
- const { modulusLength } = key.algorithm;
226
- if (typeof modulusLength !== "number" || modulusLength < 2048) throw new TypeError(`${alg} requires key modulusLength to be 2048 bits or larger`);
227
- }
137
+ function isJwkSet(input) {
138
+ return isObject(input) && Array.isArray(input.keys) && Array.from(input.keys).every(isObject);
228
139
  }
229
- function subtleAlgorithm(alg, algorithm) {
230
- const hash = `SHA-${alg.slice(-3)}`;
231
- switch (alg) {
232
- case "HS256":
233
- case "HS384":
234
- case "HS512": return {
235
- hash,
236
- name: "HMAC"
237
- };
238
- case "PS256":
239
- case "PS384":
240
- case "PS512": return {
241
- hash,
242
- name: "RSA-PSS",
243
- saltLength: parseInt(alg.slice(-3), 10) >> 3
244
- };
245
- case "RS256":
246
- case "RS384":
247
- case "RS512": return {
248
- hash,
249
- name: "RSASSA-PKCS1-v1_5"
250
- };
251
- case "ES256":
252
- case "ES384":
253
- case "ES512": return {
254
- hash,
255
- name: "ECDSA",
256
- namedCurve: algorithm.namedCurve
257
- };
258
- case "Ed25519":
259
- case "EdDSA": return { name: "Ed25519" };
260
- case "ML-DSA-44":
261
- case "ML-DSA-65":
262
- case "ML-DSA-87": return { name: alg };
263
- default: throw new JOSENotSupported(`alg ${alg} is not supported either by JOSE or your javascript runtime`);
140
+ function isDisjoint(...headers) {
141
+ const parameters = /* @__PURE__ */ new Set();
142
+ for (const header of headers) if (header) for (const parameter of Object.keys(header)) {
143
+ if (parameters.has(parameter)) return !1;
144
+ parameters.add(parameter);
264
145
  }
146
+ return !0;
265
147
  }
266
- async function getSigKey(alg, key, usage) {
267
- if (key instanceof Uint8Array) {
268
- if (!alg.startsWith("HS")) throw new TypeError(invalidKeyInput(key, "CryptoKey", "KeyObject", "JSON Web Key"));
269
- return crypto.subtle.importKey("raw", key, {
270
- hash: `SHA-${alg.slice(-3)}`,
271
- name: "HMAC"
272
- }, false, [usage]);
148
+ function decodeBase64url(value, label, ErrorClass) {
149
+ try {
150
+ return decode(value);
151
+ } catch (cause) {
152
+ throw new ErrorClass(`Failed to base64url decode the ${label}`, { cause });
273
153
  }
274
- checkSigCryptoKey(key, alg, usage);
275
- return key;
276
154
  }
277
- async function verify(alg, key, signature, data) {
278
- const cryptoKey = await getSigKey(alg, key, "verify");
279
- checkKeyLength(alg, cryptoKey);
280
- const algorithm = subtleAlgorithm(alg, cryptoKey.algorithm);
155
+ function encodeAsciiMember(value, label, ErrorClass) {
281
156
  try {
282
- return await crypto.subtle.verify(algorithm, cryptoKey, signature, data);
283
- } catch {
284
- return false;
157
+ return encode(value);
158
+ } catch (cause) {
159
+ throw new ErrorClass(`The ${label} is not a valid base64url string`, { cause });
285
160
  }
286
161
  }
287
- //#endregion
288
- //#region node_modules/.pnpm/jose@6.2.3/node_modules/jose/dist/webapi/lib/helpers.js
289
- function decodeBase64url(value, label, ErrorClass) {
162
+ function parseJoseHeader(encodedProtectedHeader, ErrorClass, message) {
163
+ let parsed;
290
164
  try {
291
- return decode(value);
292
- } catch {
293
- throw new ErrorClass(`Failed to base64url decode the ${label}`);
165
+ parsed = JSON.parse(strictDecoder.decode(decode(encodedProtectedHeader)));
166
+ } catch (cause) {
167
+ throw new ErrorClass(message, { cause });
294
168
  }
169
+ if (!isObject(parsed)) throw new ErrorClass(message);
170
+ return parsed;
295
171
  }
296
- //#endregion
297
- //#region node_modules/.pnpm/jose@6.2.3/node_modules/jose/dist/webapi/lib/type_checks.js
298
- const isObjectLike = (value) => typeof value === "object" && value !== null;
299
- function isObject(input) {
300
- if (!isObjectLike(input) || Object.prototype.toString.call(input) !== "[object Object]") return false;
301
- if (Object.getPrototypeOf(input) === null) return true;
302
- let proto = input;
303
- while (Object.getPrototypeOf(proto) !== null) proto = Object.getPrototypeOf(proto);
304
- return Object.getPrototypeOf(input) === proto;
172
+ const JWS_RECOGNIZED = {
173
+ __proto__: null,
174
+ b64: !0
175
+ };
176
+ function validateAlgorithms(option, algorithms) {
177
+ if (algorithms !== void 0 && (!Array.isArray(algorithms) || algorithms.some((s) => typeof s != "string"))) throw new TypeError(`"${option}" option must be an array of strings`);
178
+ return algorithms === void 0 ? void 0 : new Set(algorithms);
305
179
  }
306
- function isDisjoint(...headers) {
307
- const sources = headers.filter(Boolean);
308
- if (sources.length === 0 || sources.length === 1) return true;
309
- let acc;
310
- for (const header of sources) {
311
- const parameters = Object.keys(header);
312
- if (!acc || acc.size === 0) {
313
- acc = new Set(parameters);
314
- continue;
315
- }
316
- for (const parameter of parameters) {
317
- if (acc.has(parameter)) return false;
318
- acc.add(parameter);
319
- }
180
+ function validateCrit(Err, recognizedDefault, recognizedOption, protectedHeader, joseHeader) {
181
+ if (joseHeader.crit !== void 0 && protectedHeader?.crit === void 0) throw new Err("\"crit\" (Critical) Header Parameter MUST be integrity protected");
182
+ if (!protectedHeader || protectedHeader.crit === void 0) return [];
183
+ 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");
184
+ const recognized = recognizedOption === void 0 ? recognizedDefault : {
185
+ __proto__: null,
186
+ ...recognizedOption,
187
+ ...recognizedDefault
188
+ };
189
+ for (const parameter of protectedHeader.crit) {
190
+ if (!(parameter in recognized)) throw new JOSENotSupported(`Extension Header Parameter "${parameter}" is not recognized`);
191
+ if (!Object.hasOwn(joseHeader, parameter) || joseHeader[parameter] === void 0) throw new Err(`Extension Header Parameter "${parameter}" is missing`);
192
+ if (recognized[parameter] && (!Object.hasOwn(protectedHeader, parameter) || protectedHeader[parameter] === void 0)) throw new Err(`Extension Header Parameter "${parameter}" MUST be integrity protected`);
320
193
  }
321
- return true;
194
+ return protectedHeader.crit;
322
195
  }
323
- const isJWK = (key) => isObject(key) && typeof key.kty === "string";
324
- const isPrivateJWK = (key) => key.kty !== "oct" && (key.kty === "AKP" && typeof key.priv === "string" || typeof key.d === "string");
325
- const isPublicJWK = (key) => key.kty !== "oct" && key.d === void 0 && key.priv === void 0;
326
- const isSecretJWK = (key) => key.kty === "oct" && typeof key.k === "string";
327
- //#endregion
328
- //#region node_modules/.pnpm/jose@6.2.3/node_modules/jose/dist/webapi/lib/is_key_like.js
329
- const isCryptoKey = (key) => {
330
- if (key?.[Symbol.toStringTag] === "CryptoKey") return true;
331
- try {
332
- return key instanceof CryptoKey;
333
- } catch {
334
- return false;
196
+ function validateB64(protectedHeader, extensions) {
197
+ if (extensions.includes("b64")) {
198
+ const b64 = protectedHeader.b64;
199
+ if (typeof b64 != "boolean") throw new JWSInvalid("The \"b64\" (base64url-encode payload) Header Parameter must be a boolean");
200
+ return b64;
335
201
  }
336
- };
337
- const isKeyObject = (key) => key?.[Symbol.toStringTag] === "KeyObject";
338
- const isKeyLike = (key) => isCryptoKey(key) || isKeyObject(key);
339
- //#endregion
340
- //#region node_modules/.pnpm/jose@6.2.3/node_modules/jose/dist/webapi/lib/check_key_type.js
341
- const tag = (key) => key?.[Symbol.toStringTag];
342
- const jwkMatchesOp = (alg, key, usage) => {
202
+ return !0;
203
+ }
204
+ // node_modules/.pnpm/jose@6.2.17/node_modules/jose/dist/webapi/lib/key.js
205
+ const tag = (key) => key[Symbol.toStringTag];
206
+ const jwkMatchesOp = (entry, key, usage) => {
207
+ const { alg } = entry;
343
208
  if (key.use !== void 0) {
344
- let expected;
345
- switch (usage) {
346
- case "sign":
347
- case "verify":
348
- expected = "sig";
349
- break;
350
- case "encrypt":
351
- case "decrypt":
352
- expected = "enc";
353
- break;
354
- }
209
+ const expected = usage === "sign" || usage === "verify" ? "sig" : "enc";
355
210
  if (key.use !== expected) throw new TypeError(`Invalid key for this operation, its "use" must be "${expected}" when present`);
356
211
  }
357
212
  if (key.alg !== void 0 && key.alg !== alg) throw new TypeError(`Invalid key for this operation, its "alg" must be "${alg}" when present`);
358
213
  if (Array.isArray(key.key_ops)) {
359
- let expectedKeyOp;
360
- switch (true) {
361
- case usage === "sign" || usage === "verify":
362
- case alg === "dir":
363
- case alg.includes("CBC-HS"):
364
- expectedKeyOp = usage;
365
- break;
366
- case alg.startsWith("PBES2"):
367
- expectedKeyOp = "deriveBits";
368
- break;
369
- case /^A\d{3}(?:GCM)?(?:KW)?$/.test(alg):
370
- if (!alg.includes("GCM") && alg.endsWith("KW")) expectedKeyOp = usage === "encrypt" ? "wrapKey" : "unwrapKey";
371
- else expectedKeyOp = usage;
372
- break;
373
- case usage === "encrypt" && alg.startsWith("RSA"):
374
- expectedKeyOp = "wrapKey";
375
- break;
376
- case usage === "decrypt":
377
- expectedKeyOp = alg.startsWith("RSA") ? "unwrapKey" : "deriveBits";
378
- break;
379
- }
380
- if (expectedKeyOp && key.key_ops?.includes?.(expectedKeyOp) === false) throw new TypeError(`Invalid key for this operation, its "key_ops" must include "${expectedKeyOp}" when present`);
214
+ const expectedKeyOp = usage === "encrypt" || usage === "decrypt" ? entry.ops?.[usage === "encrypt" ? 0 : 1] : usage;
215
+ if (expectedKeyOp && !key.key_ops.includes(expectedKeyOp)) throw new TypeError(`Invalid key for this operation, its "key_ops" must include "${expectedKeyOp}" when present`);
381
216
  }
382
- return true;
383
217
  };
384
- const symmetricTypeCheck = (alg, key, usage) => {
385
- if (key instanceof Uint8Array) return;
386
- if (isJWK(key)) {
387
- if (isSecretJWK(key) && jwkMatchesOp(alg, key, usage)) return;
388
- 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`);
389
- }
390
- if (!isKeyLike(key)) throw new TypeError(withAlg(alg, key, "CryptoKey", "KeyObject", "JSON Web Key", "Uint8Array"));
391
- if (key.type !== "secret") throw new TypeError(`${tag(key)} instances for symmetric algorithms must be of type "secret"`);
392
- };
393
- const asymmetricTypeCheck = (alg, key, usage) => {
394
- if (isJWK(key)) switch (usage) {
395
- case "decrypt":
396
- case "sign":
397
- if (isPrivateJWK(key) && jwkMatchesOp(alg, key, usage)) return;
398
- throw new TypeError(`JSON Web Key for this operation must be a private JWK`);
399
- case "encrypt":
400
- case "verify":
401
- if (isPublicJWK(key) && jwkMatchesOp(alg, key, usage)) return;
402
- throw new TypeError(`JSON Web Key for this operation must be a public JWK`);
403
- }
404
- if (!isKeyLike(key)) throw new TypeError(withAlg(alg, key, "CryptoKey", "KeyObject", "JSON Web Key"));
405
- if (key.type === "secret") throw new TypeError(`${tag(key)} instances for asymmetric algorithms must not be of type "secret"`);
406
- if (key.type === "public") switch (usage) {
407
- case "sign": throw new TypeError(`${tag(key)} instances for asymmetric algorithm signing must be of type "private"`);
408
- case "decrypt": throw new TypeError(`${tag(key)} instances for asymmetric algorithm decryption must be of type "private"`);
218
+ async function prepareKey(entry, key, usage) {
219
+ const { alg, secret } = entry, requiresPrivateKey = usage === "decrypt" || usage === "sign";
220
+ if (secret && key instanceof Uint8Array) return key;
221
+ let normalized, keyObject;
222
+ if (isObject(key)) {
223
+ if (normalized = normalizeJwk(key), typeof normalized.kty != "string") throw invalidKeyType(alg, key, secret);
224
+ if (!(secret ? normalized.kty === "oct" && typeof normalized.k == "string" : normalized.kty !== "oct" && (requiresPrivateKey ? normalized.kty === "AKP" && typeof normalized.priv == "string" || typeof normalized.d == "string" : normalized.d === void 0 && normalized.priv === void 0))) throw new TypeError(secret ? "JSON Web Key for symmetric algorithms must have JWK \"kty\" (Key Type) equal to \"oct\" and the JWK \"k\" (Key Value) present" : `JSON Web Key for this operation must be a ${requiresPrivateKey ? "private" : "public"} JWK`);
225
+ if (jwkMatchesOp(entry, normalized, usage), normalized.kty === "oct") return decode(normalized.k);
226
+ if (!Object.isFrozen(key)) {
227
+ const { key_ops } = key;
228
+ Array.isArray(key_ops) && Object.freeze(key_ops), Object.freeze(key);
229
+ }
230
+ } else {
231
+ if (!isKeyLike(key)) throw invalidKeyType(alg, key, secret);
232
+ const expectedType = secret ? "secret" : requiresPrivateKey ? "private" : "public";
233
+ if (key.type !== expectedType && (secret || [
234
+ "secret",
235
+ "public",
236
+ "private"
237
+ ].includes(key.type))) throw new TypeError(`${tag(key)} instances must be of type "${expectedType}" for the ${alg} algorithm`);
238
+ if (isCryptoKey(key)) return key;
239
+ if (keyObject = key, keyObject.type === "secret") return keyObject.export();
409
240
  }
410
- if (key.type === "private") switch (usage) {
411
- case "verify": throw new TypeError(`${tag(key)} instances for asymmetric algorithm verifying must be of type "public"`);
412
- case "encrypt": throw new TypeError(`${tag(key)} instances for asymmetric algorithm encryption must be of type "public"`);
241
+ cache ||= /* @__PURE__ */ new WeakMap();
242
+ const cacheKey = key;
243
+ let cached = cache.get(cacheKey);
244
+ if (cached?.[alg]) return cached[alg];
245
+ if (cached || cache.set(cacheKey, cached = {}), keyObject && typeof keyObject.toCryptoKey == "function") {
246
+ const isPublic = keyObject.type === "public", crv = nist[keyObject.asymmetricKeyDetails?.namedCurve], params = entry.resolve?.({
247
+ crv,
248
+ asymmetricKeyType: keyObject.asymmetricKeyType
249
+ }) ?? entry.subtle;
250
+ return cached[alg] = keyObject.toCryptoKey(params, isPublic, entry.usages[isPublic ? 0 : 1]);
413
251
  }
252
+ return normalized ??= keyObject.export({ format: "jwk" }), normalized.alg = alg, cached[alg] = await jwkToKey(entry, normalized);
253
+ }
254
+ let cache;
255
+ const nist = {
256
+ __proto__: null,
257
+ prime256v1: "P-256",
258
+ secp384r1: "P-384",
259
+ secp521r1: "P-521"
414
260
  };
415
- function checkKeyType(alg, key, usage) {
416
- switch (alg.substring(0, 2)) {
417
- case "A1":
418
- case "A2":
419
- case "di":
420
- case "HS":
421
- case "PB":
422
- symmetricTypeCheck(alg, key, usage);
423
- break;
424
- default: asymmetricTypeCheck(alg, key, usage);
261
+ const isCryptoKey = (key) => {
262
+ if (key?.[Symbol.toStringTag] === "CryptoKey") return !0;
263
+ try {
264
+ return key instanceof CryptoKey;
265
+ } catch {
266
+ return !1;
425
267
  }
268
+ };
269
+ const isKeyObject = (key) => key?.[Symbol.toStringTag] === "KeyObject";
270
+ const isKeyLike = (key) => isCryptoKey(key) || isKeyObject(key);
271
+ function message(msg, actual, ...types) {
272
+ if (types.length > 2) {
273
+ const last = types.pop();
274
+ msg += `one of type ${types.join(", ")}, or ${last}.`;
275
+ } else types.length === 2 ? msg += `one of type ${types[0]} or ${types[1]}.` : msg += `of type ${types[0]}.`;
276
+ return actual == null ? msg += ` Received ${actual}` : typeof actual == "function" && actual.name ? msg += ` Received function ${actual.name}` : typeof actual == "object" && actual != null && actual.constructor?.name && (msg += ` Received an instance of ${actual.constructor.name}`), msg;
426
277
  }
427
- //#endregion
428
- //#region node_modules/.pnpm/jose@6.2.3/node_modules/jose/dist/webapi/lib/validate_crit.js
429
- function validateCrit(Err, recognizedDefault, recognizedOption, protectedHeader, joseHeader) {
430
- if (joseHeader.crit !== void 0 && protectedHeader?.crit === void 0) throw new Err("\"crit\" (Critical) Header Parameter MUST be integrity protected");
431
- if (!protectedHeader || protectedHeader.crit === void 0) return /* @__PURE__ */ new Set();
432
- 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");
433
- let recognized;
434
- if (recognizedOption !== void 0) recognized = new Map([...Object.entries(recognizedOption), ...recognizedDefault.entries()]);
435
- else recognized = recognizedDefault;
436
- for (const parameter of protectedHeader.crit) {
437
- if (!recognized.has(parameter)) throw new JOSENotSupported(`Extension Header Parameter "${parameter}" is not recognized`);
438
- if (joseHeader[parameter] === void 0) throw new Err(`Extension Header Parameter "${parameter}" is missing`);
439
- if (recognized.get(parameter) && protectedHeader[parameter] === void 0) throw new Err(`Extension Header Parameter "${parameter}" MUST be integrity protected`);
440
- }
441
- return new Set(protectedHeader.crit);
278
+ function invalidKeyType(alg, actual, secret) {
279
+ const types = [
280
+ "CryptoKey",
281
+ "KeyObject",
282
+ "JSON Web Key"
283
+ ];
284
+ return secret && types.push("Uint8Array"), new TypeError(message(`Key for the ${alg} algorithm must be `, actual, ...types));
442
285
  }
443
- //#endregion
444
- //#region node_modules/.pnpm/jose@6.2.3/node_modules/jose/dist/webapi/lib/validate_algorithms.js
445
- function validateAlgorithms(option, algorithms) {
446
- if (algorithms !== void 0 && (!Array.isArray(algorithms) || algorithms.some((s) => typeof s !== "string"))) throw new TypeError(`"${option}" option must be an array of strings`);
447
- if (!algorithms) return;
448
- return new Set(algorithms);
286
+ const unusable = (name, prop = "algorithm.name") => /* @__PURE__ */ new TypeError(`CryptoKey does not support this operation, its ${prop} must be ${name}`);
287
+ function checkUsage(key, usage) {
288
+ if (usage && !key.usages.includes(usage)) throw new TypeError(`CryptoKey does not support this operation, its usages must include ${usage}.`);
449
289
  }
450
- //#endregion
451
- //#region node_modules/.pnpm/jose@6.2.3/node_modules/jose/dist/webapi/lib/jwk_to_key.js
452
- const unsupportedAlg = "Invalid or unsupported JWK \"alg\" (Algorithm) Parameter value";
453
- function subtleMapping(jwk) {
454
- let algorithm;
455
- let keyUsages;
456
- switch (jwk.kty) {
457
- case "AKP":
458
- switch (jwk.alg) {
459
- case "ML-DSA-44":
460
- case "ML-DSA-65":
461
- case "ML-DSA-87":
462
- algorithm = { name: jwk.alg };
463
- keyUsages = jwk.priv ? ["sign"] : ["verify"];
464
- break;
465
- default: throw new JOSENotSupported(unsupportedAlg);
466
- }
467
- break;
468
- case "RSA":
469
- switch (jwk.alg) {
470
- case "PS256":
471
- case "PS384":
472
- case "PS512":
473
- algorithm = {
474
- name: "RSA-PSS",
475
- hash: `SHA-${jwk.alg.slice(-3)}`
476
- };
477
- keyUsages = jwk.d ? ["sign"] : ["verify"];
478
- break;
479
- case "RS256":
480
- case "RS384":
481
- case "RS512":
482
- algorithm = {
483
- name: "RSASSA-PKCS1-v1_5",
484
- hash: `SHA-${jwk.alg.slice(-3)}`
485
- };
486
- keyUsages = jwk.d ? ["sign"] : ["verify"];
487
- break;
488
- case "RSA-OAEP":
489
- case "RSA-OAEP-256":
490
- case "RSA-OAEP-384":
491
- case "RSA-OAEP-512":
492
- algorithm = {
493
- name: "RSA-OAEP",
494
- hash: `SHA-${parseInt(jwk.alg.slice(-3), 10) || 1}`
495
- };
496
- keyUsages = jwk.d ? ["decrypt", "unwrapKey"] : ["encrypt", "wrapKey"];
497
- break;
498
- default: throw new JOSENotSupported(unsupportedAlg);
499
- }
500
- break;
501
- case "EC":
502
- switch (jwk.alg) {
503
- case "ES256":
504
- case "ES384":
505
- case "ES512":
506
- algorithm = {
507
- name: "ECDSA",
508
- namedCurve: {
509
- ES256: "P-256",
510
- ES384: "P-384",
511
- ES512: "P-521"
512
- }[jwk.alg]
513
- };
514
- keyUsages = jwk.d ? ["sign"] : ["verify"];
515
- break;
516
- case "ECDH-ES":
517
- case "ECDH-ES+A128KW":
518
- case "ECDH-ES+A192KW":
519
- case "ECDH-ES+A256KW":
520
- algorithm = {
521
- name: "ECDH",
522
- namedCurve: jwk.crv
523
- };
524
- keyUsages = jwk.d ? ["deriveBits"] : [];
525
- break;
526
- default: throw new JOSENotSupported(unsupportedAlg);
527
- }
528
- break;
529
- case "OKP":
530
- switch (jwk.alg) {
531
- case "Ed25519":
532
- case "EdDSA":
533
- algorithm = { name: "Ed25519" };
534
- keyUsages = jwk.d ? ["sign"] : ["verify"];
535
- break;
536
- case "ECDH-ES":
537
- case "ECDH-ES+A128KW":
538
- case "ECDH-ES+A192KW":
539
- case "ECDH-ES+A256KW":
540
- algorithm = { name: jwk.crv };
541
- keyUsages = jwk.d ? ["deriveBits"] : [];
542
- break;
543
- default: throw new JOSENotSupported(unsupportedAlg);
544
- }
545
- break;
546
- default: throw new JOSENotSupported("Invalid or unsupported JWK \"kty\" (Key Type) Parameter value");
547
- }
290
+ function checkModulusLength(alg, key) {
291
+ const { modulusLength } = key.algorithm;
292
+ if (typeof modulusLength != "number" || modulusLength < 2048) throw new TypeError(`${alg} requires key modulusLength to be 2048 bits or larger`);
293
+ }
294
+ function checkCryptoKey(key, expected, usage) {
295
+ const algorithm = key.algorithm;
296
+ if (algorithm.name !== expected.name) throw unusable(expected.name);
297
+ if (expected.hash && algorithm.hash?.name !== expected.hash) throw unusable(expected.hash, "algorithm.hash");
298
+ if (expected.namedCurve && algorithm.namedCurve !== expected.namedCurve) throw unusable(expected.namedCurve, "algorithm.namedCurve");
299
+ if (expected.length !== void 0 && algorithm.length !== expected.length) throw unusable(expected.length, "algorithm.length");
300
+ checkUsage(key, usage);
301
+ }
302
+ function snapshotJwk(jwk) {
548
303
  return {
549
- algorithm,
550
- keyUsages
304
+ __proto__: null,
305
+ ...jwk
551
306
  };
552
307
  }
553
- async function jwkToKey(jwk) {
554
- if (!jwk.alg) throw new TypeError("\"alg\" argument is required when \"jwk.alg\" is not present");
555
- const { algorithm, keyUsages } = subtleMapping(jwk);
556
- const keyData = { ...jwk };
557
- if (keyData.kty !== "AKP") delete keyData.alg;
558
- delete keyData.use;
559
- return crypto.subtle.importKey("jwk", keyData, algorithm, jwk.ext ?? (jwk.d || jwk.priv ? false : true), jwk.key_ops ?? keyUsages);
560
- }
561
- //#endregion
562
- //#region node_modules/.pnpm/jose@6.2.3/node_modules/jose/dist/webapi/lib/normalize_key.js
563
- const unusableForAlg = "given KeyObject instance cannot be used for this algorithm";
564
- let cache;
565
- const handleJWK = async (key, jwk, alg, freeze = false) => {
566
- cache ||= /* @__PURE__ */ new WeakMap();
567
- let cached = cache.get(key);
568
- if (cached?.[alg]) return cached[alg];
569
- const cryptoKey = await jwkToKey({
308
+ function normalizeJwk(jwk) {
309
+ const normalized = snapshotJwk(jwk);
310
+ if (normalized.ext !== void 0 && typeof normalized.ext != "boolean") throw new TypeError("\"ext\" (Extractable) Parameter must be a boolean");
311
+ if (normalized.key_ops !== void 0) {
312
+ const value = normalized.key_ops, keyOps = Array.isArray(value) ? [...value] : void 0;
313
+ if (!keyOps || keyOps.some((operation) => typeof operation != "string") || new Set(keyOps).size !== keyOps.length) throw new TypeError("\"key_ops\" (Key Operations) Parameter must be an array of unique strings");
314
+ normalized.key_ops = keyOps;
315
+ }
316
+ return normalized;
317
+ }
318
+ async function jwkToKey(entry, jwk, extractable) {
319
+ if (!entry.kty.includes(jwk.kty)) throw new JOSENotSupported("Invalid or unsupported JWK \"alg\" (Algorithm) Parameter value");
320
+ const algorithm = entry.resolve?.({
321
+ kty: jwk.kty,
322
+ crv: jwk.crv
323
+ }) ?? entry.subtle, isPrivate = !!(jwk.d || jwk.priv), keyData = {
570
324
  ...jwk,
325
+ ext: extractable ?? jwk.ext
326
+ };
327
+ return keyData.kty !== "AKP" && delete keyData.alg, delete keyData.use, crypto.subtle.importKey("jwk", keyData, algorithm, keyData.ext ?? !isPrivate, jwk.key_ops ?? entry.usages[isPrivate ? 1 : 0]);
328
+ }
329
+ async function rawKey(key, expected, usage, extractable = !1) {
330
+ return key instanceof Uint8Array && (key = await crypto.subtle.importKey("raw", key, expected, extractable, [usage])), checkCryptoKey(key, expected, usage), key;
331
+ }
332
+ // node_modules/.pnpm/jose@6.2.17/node_modules/jose/dist/webapi/lib/key_descriptor.js
333
+ function table(entries) {
334
+ const out = { __proto__: null };
335
+ for (const alg in entries) out[alg] = {
336
+ ...entries[alg],
571
337
  alg
572
- });
573
- if (freeze) Object.freeze(key);
574
- if (!cached) cache.set(key, { [alg]: cryptoKey });
575
- else cached[alg] = cryptoKey;
576
- return cryptoKey;
577
- };
578
- const handleKeyObject = (keyObject, alg) => {
579
- cache ||= /* @__PURE__ */ new WeakMap();
580
- let cached = cache.get(keyObject);
581
- if (cached?.[alg]) return cached[alg];
582
- const isPublic = keyObject.type === "public";
583
- const extractable = isPublic ? true : false;
584
- let cryptoKey;
585
- if (keyObject.asymmetricKeyType === "x25519") {
586
- switch (alg) {
587
- case "ECDH-ES":
588
- case "ECDH-ES+A128KW":
589
- case "ECDH-ES+A192KW":
590
- case "ECDH-ES+A256KW": break;
591
- default: throw new TypeError(unusableForAlg);
592
- }
593
- cryptoKey = keyObject.toCryptoKey(keyObject.asymmetricKeyType, extractable, isPublic ? [] : ["deriveBits"]);
594
- }
595
- if (keyObject.asymmetricKeyType === "ed25519") {
596
- if (alg !== "EdDSA" && alg !== "Ed25519") throw new TypeError(unusableForAlg);
597
- cryptoKey = keyObject.toCryptoKey(keyObject.asymmetricKeyType, extractable, [isPublic ? "verify" : "sign"]);
598
- }
599
- switch (keyObject.asymmetricKeyType) {
600
- case "ml-dsa-44":
601
- case "ml-dsa-65":
602
- case "ml-dsa-87":
603
- if (alg !== keyObject.asymmetricKeyType.toUpperCase()) throw new TypeError(unusableForAlg);
604
- cryptoKey = keyObject.toCryptoKey(keyObject.asymmetricKeyType, extractable, [isPublic ? "verify" : "sign"]);
605
- }
606
- if (keyObject.asymmetricKeyType === "rsa") {
607
- let hash;
608
- switch (alg) {
609
- case "RSA-OAEP":
610
- hash = "SHA-1";
611
- break;
612
- case "RS256":
613
- case "PS256":
614
- case "RSA-OAEP-256":
615
- hash = "SHA-256";
616
- break;
617
- case "RS384":
618
- case "PS384":
619
- case "RSA-OAEP-384":
620
- hash = "SHA-384";
621
- break;
622
- case "RS512":
623
- case "PS512":
624
- case "RSA-OAEP-512":
625
- hash = "SHA-512";
626
- break;
627
- default: throw new TypeError(unusableForAlg);
628
- }
629
- if (alg.startsWith("RSA-OAEP")) return keyObject.toCryptoKey({
630
- name: "RSA-OAEP",
631
- hash
632
- }, extractable, isPublic ? ["encrypt"] : ["decrypt"]);
633
- cryptoKey = keyObject.toCryptoKey({
634
- name: alg.startsWith("PS") ? "RSA-PSS" : "RSASSA-PKCS1-v1_5",
635
- hash
636
- }, extractable, [isPublic ? "verify" : "sign"]);
637
- }
638
- if (keyObject.asymmetricKeyType === "ec") {
639
- const namedCurve = (/* @__PURE__ */ new Map([
640
- ["prime256v1", "P-256"],
641
- ["secp384r1", "P-384"],
642
- ["secp521r1", "P-521"]
643
- ])).get(keyObject.asymmetricKeyDetails?.namedCurve);
644
- if (!namedCurve) throw new TypeError(unusableForAlg);
645
- const expectedCurve = {
646
- ES256: "P-256",
647
- ES384: "P-384",
648
- ES512: "P-521"
649
- };
650
- if (expectedCurve[alg] && namedCurve === expectedCurve[alg]) cryptoKey = keyObject.toCryptoKey({
338
+ };
339
+ return out;
340
+ }
341
+ // node_modules/.pnpm/jose@6.2.17/node_modules/jose/dist/webapi/lib/jws_algorithms.js
342
+ const sig = [["verify"], ["sign"]];
343
+ function hmac(bits) {
344
+ const subtle = {
345
+ name: "HMAC",
346
+ hash: `SHA-${bits}`
347
+ };
348
+ return {
349
+ kty: ["oct"],
350
+ secret: !0,
351
+ subtle,
352
+ signing: subtle,
353
+ usages: sig
354
+ };
355
+ }
356
+ function rsa(bits, saltLength) {
357
+ const subtle = {
358
+ name: saltLength ? "RSA-PSS" : "RSASSA-PKCS1-v1_5",
359
+ hash: `SHA-${bits}`
360
+ };
361
+ return {
362
+ kty: ["RSA"],
363
+ subtle,
364
+ signing: saltLength ? {
365
+ ...subtle,
366
+ saltLength
367
+ } : subtle,
368
+ usages: sig,
369
+ minRsaBits: 2048
370
+ };
371
+ }
372
+ function ecdsa(crv, bits) {
373
+ return {
374
+ kty: ["EC"],
375
+ crv,
376
+ subtle: {
651
377
  name: "ECDSA",
652
- namedCurve
653
- }, extractable, [isPublic ? "verify" : "sign"]);
654
- if (alg.startsWith("ECDH-ES")) cryptoKey = keyObject.toCryptoKey({
655
- name: "ECDH",
656
- namedCurve
657
- }, extractable, isPublic ? [] : ["deriveBits"]);
658
- }
659
- if (!cryptoKey) throw new TypeError(unusableForAlg);
660
- if (!cached) cache.set(keyObject, { [alg]: cryptoKey });
661
- else cached[alg] = cryptoKey;
662
- return cryptoKey;
663
- };
664
- async function normalizeKey(key, alg) {
665
- if (key instanceof Uint8Array) return key;
666
- if (isCryptoKey(key)) return key;
667
- if (isKeyObject(key)) {
668
- if (key.type === "secret") return key.export();
669
- if ("toCryptoKey" in key && typeof key.toCryptoKey === "function") try {
670
- return handleKeyObject(key, alg);
671
- } catch (err) {
672
- if (err instanceof TypeError) throw err;
673
- }
674
- return handleJWK(key, key.export({ format: "jwk" }), alg);
675
- }
676
- if (isJWK(key)) {
677
- if (key.k) return decode(key.k);
678
- return handleJWK(key, key, alg, true);
679
- }
680
- throw new Error("unreachable");
378
+ namedCurve: crv
379
+ },
380
+ signing: {
381
+ name: "ECDSA",
382
+ hash: `SHA-${bits}`
383
+ },
384
+ usages: sig
385
+ };
681
386
  }
682
- //#endregion
683
- //#region node_modules/.pnpm/jose@6.2.3/node_modules/jose/dist/webapi/jws/flattened/verify.js
684
- async function flattenedVerify(jws, key, options) {
685
- if (!isObject(jws)) throw new JWSInvalid("Flattened JWS must be an object");
686
- if (jws.protected === void 0 && jws.header === void 0) throw new JWSInvalid("Flattened JWS must have either of the \"protected\" or \"header\" members");
687
- if (jws.protected !== void 0 && typeof jws.protected !== "string") throw new JWSInvalid("JWS Protected Header incorrect type");
688
- if (jws.payload === void 0) throw new JWSInvalid("JWS Payload missing");
689
- if (typeof jws.signature !== "string") throw new JWSInvalid("JWS Signature missing or incorrect type");
690
- if (jws.header !== void 0 && !isObject(jws.header)) throw new JWSInvalid("JWS Unprotected Header incorrect type");
691
- let parsedProt = {};
692
- if (jws.protected) try {
693
- const protectedHeader = decode(jws.protected);
694
- parsedProt = JSON.parse(decoder.decode(protectedHeader));
695
- } catch {
696
- throw new JWSInvalid("JWS Protected Header is invalid");
697
- }
698
- if (!isDisjoint(parsedProt, jws.header)) throw new JWSInvalid("JWS Protected and JWS Unprotected Header Parameter names must be disjoint");
699
- const joseHeader = {
700
- ...parsedProt,
701
- ...jws.header
387
+ function eddsa() {
388
+ const subtle = { name: "Ed25519" };
389
+ return {
390
+ kty: ["OKP"],
391
+ crv: "Ed25519",
392
+ subtle,
393
+ signing: subtle,
394
+ usages: sig
702
395
  };
703
- const extensions = validateCrit(JWSInvalid, /* @__PURE__ */ new Map([["b64", true]]), options?.crit, parsedProt, joseHeader);
704
- let b64 = true;
705
- if (extensions.has("b64")) {
706
- b64 = parsedProt.b64;
707
- if (typeof b64 !== "boolean") throw new JWSInvalid("The \"b64\" (base64url-encode payload) Header Parameter must be a boolean");
396
+ }
397
+ function mldsa(parameterSet) {
398
+ const subtle = { name: `ML-DSA-${parameterSet}` };
399
+ return {
400
+ kty: ["AKP"],
401
+ subtle,
402
+ signing: subtle,
403
+ usages: sig
404
+ };
405
+ }
406
+ const JWS = table({
407
+ HS256: hmac(256),
408
+ HS384: hmac(384),
409
+ HS512: hmac(512),
410
+ RS256: rsa(256),
411
+ RS384: rsa(384),
412
+ RS512: rsa(512),
413
+ PS256: rsa(256, 32),
414
+ PS384: rsa(384, 48),
415
+ PS512: rsa(512, 64),
416
+ ES256: ecdsa("P-256", 256),
417
+ ES384: ecdsa("P-384", 384),
418
+ ES512: ecdsa("P-521", 512),
419
+ EdDSA: eddsa(),
420
+ Ed25519: eddsa(),
421
+ "ML-DSA-44": mldsa(44),
422
+ "ML-DSA-65": mldsa(65),
423
+ "ML-DSA-87": mldsa(87)
424
+ });
425
+ function jwsAlgorithm(alg) {
426
+ const entry = typeof alg == "string" ? JWS[alg] : void 0;
427
+ if (!entry) throw new JOSENotSupported(`alg ${alg} is not supported either by JOSE or your javascript runtime`);
428
+ return entry;
429
+ }
430
+ // node_modules/.pnpm/jose@6.2.17/node_modules/jose/dist/webapi/lib/jws_verify.js
431
+ function prepareVerify(options) {
432
+ return [options && validateAlgorithms("algorithms", options.algorithms), options?.crit];
433
+ }
434
+ function parseProtectedHeader(encodedProtectedHeader) {
435
+ return encodedProtectedHeader === void 0 ? {} : parseJoseHeader(encodedProtectedHeader, JWSInvalid, "JWS Protected Header is invalid");
436
+ }
437
+ function encodeCompactUnencodedPayload(payload) {
438
+ try {
439
+ return encode(payload);
440
+ } catch (cause) {
441
+ throw new JWSInvalid("JWS Compact Serialization payload must use only ASCII characters", { cause });
708
442
  }
709
- const { alg } = joseHeader;
710
- if (typeof alg !== "string" || !alg) throw new JWSInvalid("JWS \"alg\" (Algorithm) Header Parameter missing or invalid");
711
- const algorithms = options && validateAlgorithms("algorithms", options.algorithms);
712
- if (algorithms && !algorithms.has(alg)) throw new JOSEAlgNotAllowed("\"alg\" (Algorithm) Header Parameter value not allowed");
443
+ }
444
+ async function verifySignature(jws, shared, key, encodeUnencodedPayload, parsedProtected) {
445
+ const { protected: encodedProtectedHeader, header, payload: inputPayload } = jws, protectedHeader = parsedProtected ?? parseProtectedHeader(encodedProtectedHeader);
446
+ if (!isDisjoint(protectedHeader, header)) throw new JWSInvalid("JWS Protected and JWS Unprotected Header Parameter names must be disjoint");
447
+ const joseHeader = {
448
+ ...protectedHeader,
449
+ ...header
450
+ }, b64 = validateB64(protectedHeader, validateCrit(JWSInvalid, JWS_RECOGNIZED, shared[1], protectedHeader, joseHeader)), { alg } = joseHeader;
451
+ if (typeof alg != "string" || !alg) throw new JWSInvalid("JWS \"alg\" (Algorithm) Header Parameter missing or invalid");
452
+ if (shared[0] && !shared[0].has(alg)) throw new JOSEAlgNotAllowed("\"alg\" (Algorithm) Header Parameter value not allowed");
713
453
  if (b64) {
714
- if (typeof jws.payload !== "string") throw new JWSInvalid("JWS Payload must be a string");
715
- } else if (typeof jws.payload !== "string" && !(jws.payload instanceof Uint8Array)) throw new JWSInvalid("JWS Payload must be a string or an Uint8Array instance");
716
- let resolvedKey = false;
717
- if (typeof key === "function") {
718
- key = await key(parsedProt, jws);
719
- resolvedKey = true;
454
+ if (typeof inputPayload != "string") throw new JWSInvalid("JWS Payload must be a string");
455
+ } else if (typeof inputPayload != "string" && !(inputPayload instanceof Uint8Array)) throw new JWSInvalid("JWS Payload must be a string or an Uint8Array instance");
456
+ const signingPayload = b64 || typeof inputPayload != "string" ? inputPayload : encodeUnencodedPayload(inputPayload);
457
+ let resolvedKey = !1;
458
+ typeof key == "function" && (key = await key(protectedHeader, jws), resolvedKey = !0);
459
+ const entry = jwsAlgorithm(alg), signingInput = concat(encodedProtectedHeader !== void 0 ? encode(encodedProtectedHeader) : /* @__PURE__ */ new Uint8Array(), encode("."), typeof signingPayload == "string" ? shared[2] ??= encodeAsciiMember(signingPayload, "payload", JWSInvalid) : signingPayload), signature = decodeBase64url(jws.signature, "signature", JWSInvalid), verificationKey = await prepareKey(entry, key, "verify"), cryptoKey = await rawKey(verificationKey, entry.subtle, "verify");
460
+ entry.minRsaBits && checkModulusLength(entry.alg, cryptoKey);
461
+ let verified = !1;
462
+ try {
463
+ verified = await crypto.subtle.verify(entry.signing, cryptoKey, signature, signingInput);
464
+ } catch (cause) {
465
+ throw new JWSSignatureVerificationFailed(void 0, { cause });
720
466
  }
721
- checkKeyType(alg, key, "verify");
722
- const data = concat(jws.protected !== void 0 ? encode(jws.protected) : /* @__PURE__ */ new Uint8Array(), encode("."), typeof jws.payload === "string" ? b64 ? encode(jws.payload) : encoder.encode(jws.payload) : jws.payload);
723
- const signature = decodeBase64url(jws.signature, "signature", JWSInvalid);
724
- const k = await normalizeKey(key, alg);
725
- if (!await verify(alg, k, signature, data)) throw new JWSSignatureVerificationFailed();
726
- let payload;
727
- if (b64) payload = decodeBase64url(jws.payload, "payload", JWSInvalid);
728
- else if (typeof jws.payload === "string") payload = encoder.encode(jws.payload);
729
- else payload = jws.payload;
730
- const result = { payload };
731
- if (jws.protected !== void 0) result.protectedHeader = parsedProt;
732
- if (jws.header !== void 0) result.unprotectedHeader = jws.header;
733
- if (resolvedKey) return {
467
+ if (!verified) throw new JWSSignatureVerificationFailed();
468
+ const result = { payload: typeof signingPayload == "string" ? decodeBase64url(signingPayload, "payload", JWSInvalid) : signingPayload };
469
+ return encodedProtectedHeader !== void 0 && (result.protectedHeader = protectedHeader), header !== void 0 && (result.unprotectedHeader = header), resolvedKey ? [{
734
470
  ...result,
735
- key: k
736
- };
737
- return result;
471
+ key: verificationKey
472
+ }, b64] : [result, b64];
738
473
  }
739
- //#endregion
740
- //#region node_modules/.pnpm/jose@6.2.3/node_modules/jose/dist/webapi/jws/compact/verify.js
741
- async function compactVerify(jws, key, options) {
742
- if (jws instanceof Uint8Array) jws = decoder.decode(jws);
743
- if (typeof jws !== "string") throw new JWSInvalid("Compact JWS must be a string or Uint8Array");
474
+ async function verifyCompact(jws, shared, key) {
475
+ if (jws instanceof Uint8Array && (jws = decoder.decode(jws)), typeof jws != "string") throw new JWSInvalid("Compact JWS must be a string or Uint8Array");
744
476
  const { 0: protectedHeader, 1: payload, 2: signature, length } = jws.split(".");
745
477
  if (length !== 3) throw new JWSInvalid("Invalid Compact JWS");
746
- const verified = await flattenedVerify({
478
+ return verifySignature({
747
479
  payload,
748
480
  protected: protectedHeader,
749
481
  signature
750
- }, key, options);
751
- const result = {
752
- payload: verified.payload,
753
- protectedHeader: verified.protectedHeader
754
- };
755
- if (typeof key === "function") return {
756
- ...result,
757
- key: verified.key
758
- };
759
- return result;
482
+ }, shared, key, encodeCompactUnencodedPayload);
760
483
  }
761
- //#endregion
762
- //#region node_modules/.pnpm/jose@6.2.3/node_modules/jose/dist/webapi/lib/jwt_claims_set.js
484
+ // node_modules/.pnpm/jose@6.2.17/node_modules/jose/dist/webapi/lib/jwt_claims_set.js
763
485
  const epoch = (date) => Math.floor(date.getTime() / 1e3);
764
- const minute = 60;
765
- const hour = minute * 60;
766
- const day = hour * 24;
767
- const week = day * 7;
768
- const year = day * 365.25;
486
+ const multipliers = {
487
+ s: 1,
488
+ m: 60,
489
+ h: 3600,
490
+ d: 86400,
491
+ w: 604800,
492
+ y: 31557600
493
+ };
769
494
  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;
495
+ const checkFailed = "check_failed";
496
+ function invalidDuration() {
497
+ throw new TypeError("Invalid time period format");
498
+ }
770
499
  function secs(str) {
500
+ typeof str != "string" && invalidDuration();
771
501
  const matched = REGEX.exec(str);
772
- if (!matched || matched[4] && matched[1]) throw new TypeError("Invalid time period format");
773
- const value = parseFloat(matched[2]);
774
- const unit = matched[3].toLowerCase();
775
- let numericDate;
776
- switch (unit) {
777
- case "sec":
778
- case "secs":
779
- case "second":
780
- case "seconds":
781
- case "s":
782
- numericDate = Math.round(value);
783
- break;
784
- case "minute":
785
- case "minutes":
786
- case "min":
787
- case "mins":
788
- case "m":
789
- numericDate = Math.round(value * minute);
790
- break;
791
- case "hour":
792
- case "hours":
793
- case "hr":
794
- case "hrs":
795
- case "h":
796
- numericDate = Math.round(value * hour);
797
- break;
798
- case "day":
799
- case "days":
800
- case "d":
801
- numericDate = Math.round(value * day);
802
- break;
803
- case "week":
804
- case "weeks":
805
- case "w":
806
- numericDate = Math.round(value * week);
807
- break;
808
- default:
809
- numericDate = Math.round(value * year);
810
- break;
811
- }
812
- if (matched[1] === "-" || matched[4] === "ago") return -numericDate;
813
- return numericDate;
502
+ (!matched || matched[4] && matched[1]) && invalidDuration();
503
+ const value = parseFloat(matched[2]), durationSeconds = Math.round(value * multipliers[matched[3][0].toLowerCase()]);
504
+ return Number.isFinite(durationSeconds) || invalidDuration(), matched[1] === "-" || matched[4] === "ago" ? -durationSeconds : durationSeconds;
505
+ }
506
+ function validateInput(label, input) {
507
+ if (!Number.isFinite(input)) throw new TypeError(`Invalid ${label} input`);
508
+ return input;
814
509
  }
815
510
  const normalizeTyp = (value) => {
816
- if (value.includes("/")) return value.toLowerCase();
817
- return `application/${value.toLowerCase()}`;
511
+ const normalized = value.toLowerCase();
512
+ return value.includes("/") ? normalized : `application/${normalized}`;
818
513
  };
819
- const checkAudiencePresence = (audPayload, audOption) => {
820
- if (typeof audPayload === "string") return audOption.includes(audPayload);
821
- if (Array.isArray(audPayload)) return audOption.some(Set.prototype.has.bind(new Set(audPayload)));
822
- return false;
823
- };
824
- function validateClaimsSet(protectedHeader, encodedPayload, options = {}) {
825
- let payload;
826
- try {
827
- payload = JSON.parse(decoder.decode(encodedPayload));
828
- } catch {}
829
- if (!isObject(payload)) throw new JWTInvalid("JWT Claims Set must be a top-level JSON object");
830
- const { typ } = options;
831
- if (typ && (typeof protectedHeader.typ !== "string" || normalizeTyp(protectedHeader.typ) !== normalizeTyp(typ))) throw new JWTClaimValidationFailed("unexpected \"typ\" JWT header value", payload, "typ", "check_failed");
832
- const { requiredClaims = [], issuer, subject, audience, maxTokenAge } = options;
833
- const presenceCheck = [...requiredClaims];
834
- if (maxTokenAge !== void 0) presenceCheck.push("iat");
835
- if (audience !== void 0) presenceCheck.push("aud");
836
- if (subject !== void 0) presenceCheck.push("sub");
837
- if (issuer !== void 0) presenceCheck.push("iss");
838
- for (const claim of new Set(presenceCheck.reverse())) if (!(claim in payload)) throw new JWTClaimValidationFailed(`missing required "${claim}" claim`, payload, claim, "missing");
839
- if (issuer && !(Array.isArray(issuer) ? issuer : [issuer]).includes(payload.iss)) throw new JWTClaimValidationFailed("unexpected \"iss\" claim value", payload, "iss", "check_failed");
840
- if (subject && payload.sub !== subject) throw new JWTClaimValidationFailed("unexpected \"sub\" claim value", payload, "sub", "check_failed");
841
- if (audience && !checkAudiencePresence(payload.aud, typeof audience === "string" ? [audience] : audience)) throw new JWTClaimValidationFailed("unexpected \"aud\" claim value", payload, "aud", "check_failed");
842
- let tolerance;
843
- switch (typeof options.clockTolerance) {
844
- case "string":
845
- tolerance = secs(options.clockTolerance);
846
- break;
847
- case "number":
848
- tolerance = options.clockTolerance;
849
- break;
850
- case "undefined":
851
- tolerance = 0;
852
- break;
853
- default: throw new TypeError("Invalid clockTolerance option type");
854
- }
855
- const { currentDate } = options;
856
- const now = epoch(currentDate || /* @__PURE__ */ new Date());
857
- if ((payload.iat !== void 0 || maxTokenAge) && typeof payload.iat !== "number") throw new JWTClaimValidationFailed("\"iat\" claim must be a number", payload, "iat", "invalid");
858
- if (payload.nbf !== void 0) {
859
- if (typeof payload.nbf !== "number") throw new JWTClaimValidationFailed("\"nbf\" claim must be a number", payload, "nbf", "invalid");
860
- if (payload.nbf > now + tolerance) throw new JWTClaimValidationFailed("\"nbf\" claim timestamp check failed", payload, "nbf", "check_failed");
861
- }
862
- if (payload.exp !== void 0) {
863
- if (typeof payload.exp !== "number") throw new JWTClaimValidationFailed("\"exp\" claim must be a number", payload, "exp", "invalid");
864
- if (payload.exp <= now - tolerance) throw new JWTExpired("\"exp\" claim timestamp check failed", payload, "exp", "check_failed");
514
+ const checkAudiencePresence = (audPayload, audOption) => typeof audPayload == "string" ? audOption.includes(audPayload) : Array.isArray(audPayload) ? audOption.some((aud) => audPayload.includes(aud)) : !1;
515
+ function validateNumericDate(claimsSet, claim, required = !1) {
516
+ const value = claimsSet[claim];
517
+ if (!(value === void 0 && !required)) {
518
+ if (typeof value != "number") throw new JWTClaimValidationFailed(`"${claim}" claim must be a number`, claimsSet, claim, "invalid");
519
+ return value;
865
520
  }
866
- if (maxTokenAge) {
867
- const age = now - payload.iat;
868
- const max = typeof maxTokenAge === "number" ? maxTokenAge : secs(maxTokenAge);
869
- if (age - tolerance > max) throw new JWTExpired("\"iat\" claim timestamp check failed (too far in the past)", payload, "iat", "check_failed");
870
- if (age < 0 - tolerance) throw new JWTClaimValidationFailed("\"iat\" claim timestamp check failed (it should be in the past)", payload, "iat", "check_failed");
871
- }
872
- return payload;
873
521
  }
874
- //#endregion
875
- //#region node_modules/.pnpm/jose@6.2.3/node_modules/jose/dist/webapi/jwt/verify.js
522
+ function unexpectedClaim(claimsSet, claim) {
523
+ throw new JWTClaimValidationFailed(`unexpected "${claim}" claim value`, claimsSet, claim, checkFailed);
524
+ }
525
+ function validateClaimsSet(protectedHeader, claimsSetBytes, options = {}) {
526
+ let claimsSet;
527
+ try {
528
+ claimsSet = JSON.parse(strictDecoder.decode(claimsSetBytes));
529
+ } catch (cause) {
530
+ throw new JWTInvalid("JWT Claims Set must be a top-level JSON object", { cause });
531
+ }
532
+ if (!isObject(claimsSet)) throw new JWTInvalid("JWT Claims Set must be a top-level JSON object");
533
+ const { typ } = options;
534
+ if (typ !== void 0 && (typeof protectedHeader.typ != "string" || normalizeTyp(protectedHeader.typ) !== normalizeTyp(typ))) throw new JWTClaimValidationFailed("unexpected \"typ\" JWT header value", claimsSet, "typ", checkFailed);
535
+ const { requiredClaims = [], issuer, subject, audience, maxTokenAge } = options, presenceCheck = [...requiredClaims];
536
+ maxTokenAge !== void 0 && presenceCheck.push("iat"), audience !== void 0 && presenceCheck.push("aud"), subject !== void 0 && presenceCheck.push("sub"), issuer !== void 0 && presenceCheck.push("iss");
537
+ for (const claim of new Set(presenceCheck.reverse())) if (!Object.hasOwn(claimsSet, claim)) throw new JWTClaimValidationFailed(`missing required "${claim}" claim`, claimsSet, claim, "missing");
538
+ issuer !== void 0 && !(Array.isArray(issuer) ? issuer : [issuer]).includes(claimsSet.iss) && unexpectedClaim(claimsSet, "iss"), subject !== void 0 && claimsSet.sub !== subject && unexpectedClaim(claimsSet, "sub"), audience !== void 0 && !checkAudiencePresence(claimsSet.aud, typeof audience == "string" ? [audience] : audience) && unexpectedClaim(claimsSet, "aud");
539
+ const { clockTolerance } = options;
540
+ let tolerance = 0;
541
+ if (typeof clockTolerance == "string") tolerance = secs(clockTolerance);
542
+ else if (clockTolerance !== void 0) {
543
+ if (typeof clockTolerance != "number") throw new TypeError("Invalid clockTolerance option type");
544
+ tolerance = clockTolerance;
545
+ }
546
+ if (validateInput("clockTolerance option", tolerance), tolerance < 0) throw new TypeError("Invalid clockTolerance option input");
547
+ const { currentDate } = options, now = validateInput("currentDate option", epoch(currentDate === void 0 ? /* @__PURE__ */ new Date() : currentDate)), iat = validateNumericDate(claimsSet, "iat", maxTokenAge !== void 0), nbf = validateNumericDate(claimsSet, "nbf");
548
+ if (nbf !== void 0 && nbf > now + tolerance) throw new JWTClaimValidationFailed("\"nbf\" claim timestamp check failed", claimsSet, "nbf", checkFailed);
549
+ const exp = validateNumericDate(claimsSet, "exp");
550
+ if (exp !== void 0 && exp <= now - tolerance) throw new JWTExpired("\"exp\" claim timestamp check failed", claimsSet, "exp", checkFailed);
551
+ if (maxTokenAge !== void 0) {
552
+ const age = now - iat, max = validateInput("maxTokenAge option", typeof maxTokenAge == "number" ? maxTokenAge : secs(maxTokenAge));
553
+ if (max < 0) throw new TypeError("Invalid maxTokenAge option input");
554
+ if (age - tolerance > max) throw new JWTExpired("\"iat\" claim timestamp check failed (too far in the past)", claimsSet, "iat", checkFailed);
555
+ if (age < -tolerance) throw new JWTClaimValidationFailed("\"iat\" claim timestamp check failed (it should be in the past)", claimsSet, "iat", checkFailed);
556
+ }
557
+ return claimsSet;
558
+ }
559
+ // node_modules/.pnpm/jose@6.2.17/node_modules/jose/dist/webapi/jwt/verify.js
876
560
  async function jwtVerify(jwt, key, options) {
877
- const verified = await compactVerify(jwt, key, options);
878
- if (verified.protectedHeader.crit?.includes("b64") && verified.protectedHeader.b64 === false) throw new JWTInvalid("JWTs MUST NOT use unencoded payload");
879
- const result = {
880
- payload: validateClaimsSet(verified.protectedHeader, verified.payload, options),
881
- protectedHeader: verified.protectedHeader
882
- };
883
- if (typeof key === "function") return {
884
- ...result,
885
- key: verified.key
561
+ const [verified, b64] = await verifyCompact(jwt, prepareVerify(options), key);
562
+ if (!b64) throw new JWTInvalid("JWTs MUST NOT use unencoded payload");
563
+ const payload = validateClaimsSet(verified.protectedHeader, verified.payload, options);
564
+ return {
565
+ ...verified,
566
+ payload
886
567
  };
887
- return result;
888
568
  }
889
- //#endregion
890
- //#region node_modules/.pnpm/jose@6.2.3/node_modules/jose/dist/webapi/key/import.js
891
- async function importJWK(jwk, alg, options) {
892
- if (!isObject(jwk)) throw new TypeError("JWK must be an object");
893
- let ext;
894
- alg ??= jwk.alg;
895
- ext ??= options?.extractable ?? jwk.ext;
896
- switch (jwk.kty) {
897
- case "oct":
898
- if (typeof jwk.k !== "string" || !jwk.k) throw new TypeError("missing \"k\" (Key Value) Parameter value");
899
- return decode(jwk.k);
900
- case "RSA":
901
- if ("oth" in jwk && jwk.oth !== void 0) throw new JOSENotSupported("RSA JWK \"oth\" (Other Primes Info) Parameter value is not supported");
902
- return jwkToKey({
903
- ...jwk,
904
- alg,
905
- ext
906
- });
907
- case "AKP":
908
- if (typeof jwk.alg !== "string" || !jwk.alg) throw new TypeError("missing \"alg\" (Algorithm) Parameter value");
909
- if (alg !== void 0 && alg !== jwk.alg) throw new TypeError("JWK alg and alg option value mismatch");
910
- return jwkToKey({
911
- ...jwk,
912
- ext
913
- });
914
- case "EC":
915
- case "OKP": return jwkToKey({
916
- ...jwk,
917
- alg,
918
- ext
919
- });
920
- default: throw new JOSENotSupported("Unsupported \"kty\" (Key Type) Parameter value");
921
- }
569
+ // node_modules/.pnpm/jose@6.2.17/node_modules/jose/dist/webapi/jwks/local.js
570
+ function isUsableJWK(jwk, entry, alg, kid) {
571
+ const { kty, key_ops: keyOps, ext, kid: jwkKid, alg: jwkAlg, use, crv } = jwk;
572
+ return (ext === void 0 || typeof ext == "boolean") && (keyOps === void 0 || Array.isArray(keyOps) && keyOps.every((operation, index) => typeof operation == "string" && keyOps.indexOf(operation) === index) && keyOps.includes("verify")) && entry.kty.includes(kty) && (kid === void 0 || typeof kid == "string" && kid === jwkKid) && (jwkAlg === void 0 ? kty !== "AKP" : alg === jwkAlg) && (use === void 0 || use === "sig") && (!entry.crv || crv === entry.crv);
922
573
  }
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");
574
+ async function importWithAlgCache(cache, jwk, entry) {
575
+ const cached = cache.get(jwk) || cache.set(jwk, {}).get(jwk), { alg } = entry;
576
+ if (cached[alg] === void 0) {
577
+ const pending = jwkToKey(entry, jwk, !0).then((key) => {
578
+ if (key.type !== "public") throw new JWKSInvalid("JSON Web Key Set members must be public keys");
579
+ return cached[alg] = key, key;
580
+ }).catch((error) => {
581
+ throw cached[alg] === pending && delete cached[alg], error;
582
+ });
583
+ cached[alg] = pending;
933
584
  }
585
+ return cached[alg];
934
586
  }
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) {
587
+ function createLocalJWKSet(jwks) {
588
+ let snapshot;
589
+ try {
590
+ snapshot = structuredClone(jwks);
591
+ } catch (cause) {
592
+ throw new JWKSInvalid("JSON Web Key Set malformed", { cause });
593
+ }
594
+ if (!isJwkSet(snapshot)) throw new JWKSInvalid("JSON Web Key Set malformed");
595
+ const metadata = snapshot.keys.map((jwk) => {
596
+ const normalized = snapshotJwk(jwk);
597
+ return Array.isArray(normalized.key_ops) && (normalized.key_ops = [...normalized.key_ops]), normalized;
598
+ }), cached = /* @__PURE__ */ new WeakMap();
599
+ return Object.defineProperty(async (protectedHeader, token) => {
952
600
  const { alg, kid } = {
953
601
  ...protectedHeader,
954
602
  ...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();
603
+ }, entry = typeof alg == "string" ? JWS[alg] : void 0;
604
+ if (!entry || entry.secret) throw new JOSENotSupported("Unsupported \"alg\" value for a JSON Web Key Set");
605
+ const candidates = snapshot.keys.filter((_, index) => isUsableJWK(metadata[index], entry, alg, kid)), { 0: jwk, length } = candidates;
606
+ if (!length) throw new JWKSNoMatchingKey();
982
607
  if (length !== 1) {
983
608
  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);
609
+ throw error[Symbol.asyncIterator] = async function* () {
610
+ for (const jwk2 of candidates) try {
611
+ yield await importWithAlgCache(cached, jwk2, entry);
988
612
  } catch {}
989
- };
990
- throw error;
613
+ }, error;
991
614
  }
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;
615
+ return importWithAlgCache(cached, jwk, entry);
616
+ }, "jwks", { value: () => structuredClone(snapshot) });
1017
617
  }
1018
- //#endregion
1019
- //#region node_modules/.pnpm/jose@6.2.3/node_modules/jose/dist/webapi/jwks/remote.js
618
+ // node_modules/.pnpm/jose@6.2.17/node_modules/jose/dist/webapi/jwks/remote.js
1020
619
  function isCloudflareWorkers() {
1021
- return typeof WebSocketPair !== "undefined" || typeof navigator !== "undefined" && navigator.userAgent === "Cloudflare-Workers" || typeof EdgeRuntime !== "undefined" && EdgeRuntime === "vercel";
620
+ return typeof WebSocketPair < "u" || typeof navigator < "u" && navigator.userAgent === "Cloudflare-Workers" || typeof EdgeRuntime < "u" && EdgeRuntime === "vercel";
1022
621
  }
1023
622
  let USER_AGENT;
1024
- if (typeof navigator === "undefined" || !navigator.userAgent?.startsWith?.("Mozilla/5.0 ")) USER_AGENT = `jose/v6.2.3`;
1025
- const customFetch = Symbol();
623
+ (typeof navigator > "u" || !navigator.userAgent?.startsWith?.("Mozilla/5.0 ")) && (USER_AGENT = "jose/v6.2.17");
624
+ const customFetch = /* @__PURE__ */ Symbol();
1026
625
  async function fetchJwks(url, headers, signal, fetchImpl = fetch) {
1027
626
  const response = await fetchImpl(url, {
1028
627
  method: "GET",
@@ -1030,134 +629,82 @@ async function fetchJwks(url, headers, signal, fetchImpl = fetch) {
1030
629
  redirect: "manual",
1031
630
  headers
1032
631
  }).catch((err) => {
1033
- if (err.name === "TimeoutError") throw new JWKSTimeout();
1034
- throw err;
632
+ throw err.name === "TimeoutError" ? new JWKSTimeout(void 0, { cause: err }) : err;
1035
633
  });
1036
634
  if (response.status !== 200) throw new JOSEError("Expected 200 OK from the JSON Web Key Set HTTP response");
1037
635
  try {
1038
636
  return await response.json();
1039
- } catch {
1040
- throw new JOSEError("Failed to parse the JSON Web Key Set HTTP response as JSON");
637
+ } catch (cause) {
638
+ throw new JOSEError("Failed to parse the JSON Web Key Set HTTP response as JSON", { cause });
1041
639
  }
1042
640
  }
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;
641
+ const jwksCache = /* @__PURE__ */ Symbol();
642
+ function isFreshFor(timestamp, duration) {
643
+ return Number.isFinite(timestamp) && Date.now() < timestamp + duration;
1049
644
  }
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
- }
645
+ function validateDuration(value, fallback, option) {
646
+ if (Number.isNaN(value)) throw new TypeError(`"${option}" option must not be NaN`);
647
+ if (typeof value == "number" && value < 0) throw new TypeError(`"${option}" option must not be negative`);
648
+ return typeof value == "number" ? value : fallback;
649
+ }
650
+ function createRemoteJWKSet(url, options) {
651
+ if (!(url instanceof URL)) throw new TypeError("url must be an instance of URL");
652
+ const href = new URL(url.href).href, opts = options ?? {}, timeoutOption = opts.timeoutDuration;
653
+ if (typeof timeoutOption == "number" && (!Number.isInteger(timeoutOption) || timeoutOption < 0)) throw new TypeError("\"timeoutDuration\" option must be a non-negative integer");
654
+ const timeoutDuration = typeof timeoutOption == "number" ? timeoutOption : 5e3, cooldownDuration = validateDuration(opts.cooldownDuration, 3e4, "cooldownDuration"), cacheMaxAge = validateDuration(opts.cacheMaxAge, 6e5, "cacheMaxAge"), headers = new Headers(opts.headers);
655
+ USER_AGENT && !headers.has("User-Agent") && headers.set("User-Agent", USER_AGENT), headers.has("accept") || headers.set("accept", "application/json, application/jwk-set+json");
656
+ const fetchImpl = opts[customFetch], cache = opts[jwksCache];
657
+ let jwksTimestamp, pendingFetch, reloadSequence = 0, appliedSequence = 0, local;
658
+ if (cache && typeof cache == "object") {
659
+ const { uat, jwks } = cache;
660
+ isFreshFor(uat, cacheMaxAge) && isJwkSet(jwks) && (jwksTimestamp = uat, local = createLocalJWKSet(jwks));
661
+ }
662
+ const reload = async () => {
663
+ if (pendingFetch && isCloudflareWorkers() && (pendingFetch = void 0), !pendingFetch) {
664
+ const sequence = ++reloadSequence, current = pendingFetch = fetchJwks(href, headers, AbortSignal.timeout(timeoutDuration), fetchImpl).then((json) => {
665
+ const next = createLocalJWKSet(json);
666
+ if (sequence <= appliedSequence) return;
667
+ local = next;
668
+ const updatedAt = Date.now();
669
+ cache && (cache.uat = updatedAt, cache.jwks = json), jwksTimestamp = updatedAt, appliedSequence = sequence;
670
+ }).finally(() => {
671
+ pendingFetch === current && (pendingFetch = void 0);
672
+ });
1080
673
  }
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();
674
+ await pendingFetch;
675
+ };
676
+ return Object.defineProperties(async (protectedHeader, token) => {
677
+ (!local || !isFreshFor(jwksTimestamp, cacheMaxAge)) && await reload();
1096
678
  try {
1097
- return await this.#local(protectedHeader, token);
679
+ return await local(protectedHeader, token);
1098
680
  } catch (err) {
1099
- if (err instanceof JWKSNoMatchingKey) {
1100
- if (this.coolingDown() === false) {
1101
- await this.reload();
1102
- return this.#local(protectedHeader, token);
1103
- }
1104
- }
681
+ if (err instanceof JWKSNoMatchingKey && !isFreshFor(jwksTimestamp, cooldownDuration)) return await reload(), local(protectedHeader, token);
1105
682
  throw err;
1106
683
  }
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, {
684
+ }, {
1129
685
  coolingDown: {
1130
- get: () => set.coolingDown(),
1131
- enumerable: true,
1132
- configurable: false
686
+ get: () => isFreshFor(jwksTimestamp, cooldownDuration),
687
+ enumerable: !0
1133
688
  },
1134
689
  fresh: {
1135
- get: () => set.fresh(),
1136
- enumerable: true,
1137
- configurable: false
690
+ get: () => isFreshFor(jwksTimestamp, cacheMaxAge),
691
+ enumerable: !0
1138
692
  },
1139
693
  reload: {
1140
- value: () => set.reload(),
1141
- enumerable: true,
1142
- configurable: false,
1143
- writable: false
694
+ value: reload,
695
+ enumerable: !0
1144
696
  },
1145
697
  reloading: {
1146
- get: () => set.pendingFetch(),
1147
- enumerable: true,
1148
- configurable: false
698
+ get: () => !!pendingFetch,
699
+ enumerable: !0
1149
700
  },
1150
701
  jwks: {
1151
- value: () => set.jwks(),
1152
- enumerable: true,
1153
- configurable: false,
1154
- writable: false
702
+ value: () => local?.jwks(),
703
+ enumerable: !0
1155
704
  }
1156
705
  });
1157
- return remoteJWKSet;
1158
706
  }
1159
- //#endregion
1160
- //#region packages/server/src/auth/presets/bearer-jwt.ts
707
+ // packages/server/src/auth/presets/bearer-jwt.ts
1161
708
  const DEFAULT_ALGORITHMS = [
1162
709
  "RS256",
1163
710
  "ES256",
@@ -1185,11 +732,14 @@ const JWKS_KID_REFRESH_MIN_INTERVAL_MS = 6e4;
1185
732
  * `groups`, …) pass through verbatim. The kernel types it as
1186
733
  * `unknown` to keep `Verifier` plain; cast at the call site with the
1187
734
  * 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`.
735
+ * { sub: string }`. Token-level failures (bad signature, missing or
736
+ * past `exp`, wrong audience, missing/non-string tenant claim) return
737
+ * `null`. Every token must carry `exp` (RFC 9068 §2.2); a token without
738
+ * one is rejected, not accepted forever.
1190
739
  *
1191
740
  * @throws BaerlyError code="InvalidConfig" — required option
1192
- * missing, `issuer`/`audience` empty, `algorithms` empty.
741
+ * missing, `issuer`/`audience` empty, `algorithms` empty,
742
+ * `clockSkewMs` negative or non-finite, `jwksCacheTtlMs` negative.
1193
743
  * @throws BaerlyError code="NetworkError" — JWKS fetch failed AND
1194
744
  * the cache is cold. A stale cache hit on a network failure is
1195
745
  * preferred over throwing (jose serves the stale JWKS until the
@@ -1207,37 +757,54 @@ const JWKS_KID_REFRESH_MIN_INTERVAL_MS = 6e4;
1207
757
  * ```
1208
758
  */
1209
759
  const bearerJwt = (opts) => {
1210
- if (opts.issuer.length === 0) throw new BaerlyError("InvalidConfig", "bearerJwt: issuer must be non-empty", void 0, void 0, void 0, BEARER_JWT_CONFIG_RESOLUTION);
1211
- if (opts.audience.length === 0) throw new BaerlyError("InvalidConfig", "bearerJwt: audience must be non-empty", void 0, void 0, void 0, BEARER_JWT_CONFIG_RESOLUTION);
760
+ const verifyToken = makeTokenVerifier(opts);
761
+ return async (req) => {
762
+ const header = req.headers.get("Authorization") ?? "";
763
+ if (!header.startsWith("Bearer ")) return null;
764
+ return verifyToken(header.slice(7));
765
+ };
766
+ };
767
+ /**
768
+ * Validate `opts` and return the token-level verifier shared by
769
+ * {@link bearerJwt} (token from `Authorization: Bearer`) and
770
+ * `cloudflareAccess` (token from `Cf-Access-Jwt-Assertion`). Takes the
771
+ * raw JWT, so callers never rebuild a `Request` to move it between
772
+ * headers. Same results as `bearerJwt`: `null` for any token-level
773
+ * failure, `BaerlyError{NetworkError}` for a cold-cache JWKS failure.
774
+ */
775
+ const makeTokenVerifier = (opts) => {
776
+ if (opts.issuer.length === 0) throw new BaerlyError("InvalidConfig", "bearerJwt: issuer must be non-empty", { resolution: BEARER_JWT_CONFIG_RESOLUTION });
777
+ if (opts.audience.length === 0) throw new BaerlyError("InvalidConfig", "bearerJwt: audience must be non-empty", { resolution: BEARER_JWT_CONFIG_RESOLUTION });
1212
778
  const algorithms = opts.algorithms ?? DEFAULT_ALGORITHMS;
1213
- if (algorithms.length === 0) throw new BaerlyError("InvalidConfig", "bearerJwt: algorithms must be non-empty", void 0, void 0, void 0, BEARER_JWT_CONFIG_RESOLUTION);
779
+ if (algorithms.length === 0) throw new BaerlyError("InvalidConfig", "bearerJwt: algorithms must be non-empty", { resolution: BEARER_JWT_CONFIG_RESOLUTION });
1214
780
  if (opts.tenantPrefix !== void 0) {
1215
- if (opts.tenantClaim !== void 0) throw new BaerlyError("InvalidConfig", "bearerJwt: tenantPrefix and tenantClaim are mutually exclusive", void 0, void 0, void 0, BEARER_JWT_CONFIG_RESOLUTION);
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)})`, void 0, void 0, void 0, BEARER_JWT_CONFIG_RESOLUTION);
781
+ if (opts.tenantClaim !== void 0) throw new BaerlyError("InvalidConfig", "bearerJwt: tenantPrefix and tenantClaim are mutually exclusive", { resolution: BEARER_JWT_CONFIG_RESOLUTION });
782
+ 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)})`, { resolution: BEARER_JWT_CONFIG_RESOLUTION });
1217
783
  }
784
+ const clockSkewMs = opts.clockSkewMs ?? DEFAULT_CLOCK_SKEW_MS;
785
+ if (!(clockSkewMs >= 0) || !Number.isFinite(clockSkewMs)) throw new BaerlyError("InvalidConfig", `bearerJwt: clockSkewMs must be a finite number >= 0 (got ${String(clockSkewMs)})`, { resolution: BEARER_JWT_CONFIG_RESOLUTION });
786
+ const cacheMaxAge = opts.jwksCacheTtlMs ?? DEFAULT_JWKS_CACHE_TTL_MS;
787
+ if (!(cacheMaxAge >= 0)) throw new BaerlyError("InvalidConfig", `bearerJwt: jwksCacheTtlMs must be >= 0 (got ${String(cacheMaxAge)})`, { resolution: BEARER_JWT_CONFIG_RESOLUTION });
1218
788
  const tenantClaim = opts.tenantClaim ?? DEFAULT_TENANT_CLAIM;
1219
789
  const fixedTenantPrefix = opts.tenantPrefix;
1220
- const clockToleranceSec = (opts.clockSkewMs ?? DEFAULT_CLOCK_SKEW_MS) / 1e3;
1221
- const cacheMaxAge = opts.jwksCacheTtlMs ?? DEFAULT_JWKS_CACHE_TTL_MS;
790
+ const clockToleranceSec = clockSkewMs / 1e3;
1222
791
  const resolveKey = typeof opts.jwks === "string" ? createRemoteJWKSet(new URL(opts.jwks), {
1223
792
  cacheMaxAge,
1224
793
  cooldownDuration: JWKS_KID_REFRESH_MIN_INTERVAL_MS,
1225
794
  [customFetch]: opts.fetch
1226
795
  }) : 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);
796
+ return async (token) => {
1231
797
  let payload;
1232
798
  try {
1233
799
  ({payload} = await jwtVerify(token, resolveKey, {
1234
800
  issuer: opts.issuer,
1235
801
  audience: opts.audience,
1236
802
  algorithms: [...algorithms],
1237
- clockTolerance: clockToleranceSec
803
+ clockTolerance: clockToleranceSec,
804
+ requiredClaims: ["exp"]
1238
805
  }));
1239
806
  } catch (error) {
1240
- if (isJwksFetchFailure(error)) throw new BaerlyError("NetworkError", "bearerJwt: JWKS fetch failed", error);
807
+ if (isJwksFetchFailure(error)) throw new BaerlyError("NetworkError", "bearerJwt: JWKS fetch failed", { cause: error });
1241
808
  return null;
1242
809
  }
1243
810
  if (fixedTenantPrefix !== void 0) return {
@@ -1266,17 +833,17 @@ const isJwksFetchFailure = (error) => {
1266
833
  if (error instanceof JWKSInvalid || error instanceof JWKSTimeout) return true;
1267
834
  return !(error instanceof JOSEError);
1268
835
  };
1269
- //#endregion
1270
- //#region packages/server/src/auth/presets/cloudflare-access.ts
836
+ // packages/server/src/auth/presets/cloudflare-access.ts
1271
837
  /**
1272
838
  * Build a `Verifier` that consumes the `Cf-Access-Jwt-Assertion`
1273
839
  * header CF Access injects in front of a protected Worker. The
1274
840
  * Cloudflare-side scaffold (`examples/minimal-cloudflare/`) defaults
1275
841
  * to this factory.
1276
842
  *
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.
843
+ * Internally shares `bearerJwt`'s token verifier — pulls the JWT from
844
+ * the CF-specific header, points at CF Access's JWKS, and pins
845
+ * issuer/audience to the CF-Access shape. An `Authorization` header
846
+ * the app sent itself is never read.
1280
847
  *
1281
848
  * **Identity shape.** Same as {@link bearerJwt}: the returned
1282
849
  * `identity` is the verified JWT payload CF Access mints (after IdP
@@ -1284,8 +851,9 @@ const isJwksFetchFailure = (error) => {
1284
851
  * `identity.identity_nonce` — see Cloudflare's "Application Token"
1285
852
  * reference. The kernel types it as `unknown`; cast at the call site.
1286
853
  *
1287
- * @throws BaerlyError code="InvalidConfig" — `teamDomain` or
1288
- * `audienceTag` empty, or `audienceTag` not 64 lowercase-hex chars.
854
+ * @throws BaerlyError code="InvalidConfig" — `teamDomain` not a bare
855
+ * team name (`^[a-z0-9-]+$`), or `audienceTag` not 64 lowercase-hex
856
+ * chars.
1289
857
  *
1290
858
  * @example
1291
859
  * ```ts
@@ -1307,10 +875,10 @@ const isJwksFetchFailure = (error) => {
1307
875
  * ```
1308
876
  */
1309
877
  const cloudflareAccess = (opts) => {
1310
- if (opts.teamDomain.length === 0) throw new BaerlyError("InvalidConfig", "cloudflareAccess: teamDomain must be non-empty", void 0, void 0, void 0, CLOUDFLARE_ACCESS_CONFIG_RESOLUTION);
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)})`, void 0, void 0, void 0, CLOUDFLARE_ACCESS_CONFIG_RESOLUTION);
878
+ if (!CF_ACCESS_TEAM_NAME_PATTERN.test(opts.teamDomain)) throw new BaerlyError("InvalidConfig", `cloudflareAccess: teamDomain must be a bare team name of lowercase letters, digits and "-" (got ${JSON.stringify(opts.teamDomain)})`, { resolution: CLOUDFLARE_ACCESS_CONFIG_RESOLUTION });
879
+ 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)})`, { resolution: CLOUDFLARE_ACCESS_CONFIG_RESOLUTION });
1312
880
  const issuer = `https://${opts.teamDomain}.cloudflareaccess.com`;
1313
- const inner = bearerJwt({
881
+ const verifyToken = makeTokenVerifier({
1314
882
  jwks: `${issuer}/cdn-cgi/access/certs`,
1315
883
  issuer,
1316
884
  audience: opts.audienceTag,
@@ -1323,13 +891,9 @@ const cloudflareAccess = (opts) => {
1323
891
  return async (req) => {
1324
892
  const cfHeader = req.headers.get("Cf-Access-Jwt-Assertion");
1325
893
  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
- }));
894
+ return verifyToken(cfHeader);
1330
895
  };
1331
896
  };
1332
- //#endregion
1333
897
  export { bearerJwt, cloudflareAccess, sharedSecret };
1334
898
 
1335
899
  //# sourceMappingURL=auth.js.map