@casys/mcp-erpnext 3.0.3 → 3.0.4

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/mcp-erpnext.mjs CHANGED
@@ -3115,6 +3115,7 @@ var require_utils2 = __commonJS({
3115
3115
  "use strict";
3116
3116
  var isUUID = RegExp.prototype.test.bind(/^[\da-f]{8}-[\da-f]{4}-[\da-f]{4}-[\da-f]{4}-[\da-f]{12}$/iu);
3117
3117
  var isIPv4 = RegExp.prototype.test.bind(/^(?:(?:25[0-5]|2[0-4]\d|1\d{2}|[1-9]\d|\d)\.){3}(?:25[0-5]|2[0-4]\d|1\d{2}|[1-9]\d|\d)$/u);
3118
+ var isPort = RegExp.prototype.test.bind(/^\d*$/u);
3118
3119
  var isHexPair = RegExp.prototype.test.bind(/^[\da-f]{2}$/iu);
3119
3120
  var isUnreserved = RegExp.prototype.test.bind(/^[\da-z\-._~]$/iu);
3120
3121
  var isPathCharacter = RegExp.prototype.test.bind(/^[A-Za-z0-9\-._~!$&'()*+,;=:@/]$/u);
@@ -3580,8 +3581,12 @@ var require_utils2 = __commonJS({
3580
3581
  uriTokens.push(host);
3581
3582
  }
3582
3583
  if (typeof component.port === "number" || typeof component.port === "string") {
3584
+ const port = String(component.port);
3585
+ if (!isPort(port)) {
3586
+ throw new TypeError("URI port is malformed.");
3587
+ }
3583
3588
  uriTokens.push(":");
3584
- uriTokens.push(String(component.port));
3589
+ uriTokens.push(port);
3585
3590
  }
3586
3591
  return uriTokens.length ? uriTokens.join("") : void 0;
3587
3592
  }
@@ -4024,12 +4029,15 @@ var require_fast_uri2 = __commonJS({
4024
4029
  }
4025
4030
  return false;
4026
4031
  }
4032
+ function isIPLiteral(host) {
4033
+ return host[0] === "[" && host[host.length - 1] === "]";
4034
+ }
4027
4035
  function hasMalformedComponentPercentEncoding(matches) {
4028
4036
  const host = matches[4];
4029
- return hasMalformedPercentEncoding(matches[3]) || host !== void 0 && !(host[0] === "[" && host[host.length - 1] === "]") && hasMalformedPercentEncoding(host) || hasMalformedPercentEncoding(matches[6]) || hasMalformedPercentEncoding(matches[7]) || hasMalformedPercentEncoding(matches[8]);
4037
+ return hasMalformedPercentEncoding(matches[3]) || host !== void 0 && !isIPLiteral(host) && hasMalformedPercentEncoding(host) || hasMalformedPercentEncoding(matches[6]) || hasMalformedPercentEncoding(matches[7]) || hasMalformedPercentEncoding(matches[8]);
4030
4038
  }
4031
4039
  function canonicalizeHost(parsed, options, schemeHandler, isIP) {
4032
- if (!options.unicodeSupport && (!schemeHandler || !schemeHandler.unicodeSupport) && parsed.host && parsed.host[0] !== "[" && (options.domainHost || schemeHandler && schemeHandler.domainHost) && isIP === false && nonSimpleDomain(parsed.host)) {
4040
+ if (!options.unicodeSupport && (!schemeHandler || !schemeHandler.unicodeSupport) && parsed.host && !isIPLiteral(parsed.host) && (options.domainHost || schemeHandler && schemeHandler.domainHost) && isIP === false && nonSimpleDomain(parsed.host)) {
4033
4041
  try {
4034
4042
  parsed.host = new URL("http://" + parsed.host).hostname;
4035
4043
  } catch (e) {
@@ -4116,10 +4124,11 @@ var require_fast_uri2 = __commonJS({
4116
4124
  if (parsed.host) {
4117
4125
  const ipv4result = isIPv4(parsed.host);
4118
4126
  if (ipv4result === false) {
4119
- const bracketedIPLiteral = parsed.host[0] === "[" && parsed.host[parsed.host.length - 1] === "]";
4127
+ const bracketedIPLiteral = isIPLiteral(parsed.host);
4128
+ const hasIPLiteralBracket = parsed.host.indexOf("[") !== -1 || parsed.host.indexOf("]") !== -1;
4120
4129
  const ipv6result = normalizeIPv6(parsed.host);
4121
4130
  isIP = ipv6result.isIPV6 || ipv6result.isIPVFuture === true;
4122
- malformedIPLiteral = bracketedIPLiteral && ipv6result.error === true;
4131
+ malformedIPLiteral = hasIPLiteralBracket && (!bracketedIPLiteral || ipv6result.error === true);
4123
4132
  parsed.host = isIP ? ipv6result.host : ipv6result.host.toLowerCase();
4124
4133
  if (malformedIPLiteral) {
4125
4134
  parsed.error = parsed.error || "URI host is malformed.";
@@ -4142,7 +4151,9 @@ var require_fast_uri2 = __commonJS({
4142
4151
  parsed.error = parsed.error || "URI is not a " + options.reference + " reference.";
4143
4152
  }
4144
4153
  const schemeHandler = getSchemeHandler(options.scheme || parsed.scheme);
4145
- malformedHost = canonicalizeHost(parsed, options, schemeHandler, isIP);
4154
+ if (!malformedIPLiteral) {
4155
+ malformedHost = canonicalizeHost(parsed, options, schemeHandler, isIP);
4156
+ }
4146
4157
  if (!schemeHandler || schemeHandler && !schemeHandler.skipNormalize) {
4147
4158
  if (uri.indexOf("%") !== -1) {
4148
4159
  if (parsed.host !== void 0 && !malformedIPLiteral) {
@@ -18595,9 +18606,9 @@ function cloneIssues(issues) {
18595
18606
  }
18596
18607
  var recursive = /* @__PURE__ */ new WeakMap();
18597
18608
  function isRecursive(inst, stack) {
18598
- const cached3 = recursive.get(inst);
18599
- if (cached3 !== void 0)
18600
- return cached3;
18609
+ const cached2 = recursive.get(inst);
18610
+ if (cached2 !== void 0)
18611
+ return cached2;
18601
18612
  if (stack.has(inst))
18602
18613
  return true;
18603
18614
  stack.add(inst);
@@ -39108,13 +39119,14 @@ var Hono = class _Hono {
39108
39119
  const allMethods = [...METHODS, METHOD_NAME_ALL_LOWERCASE];
39109
39120
  allMethods.forEach((method) => {
39110
39121
  this[method] = (args1, ...args) => {
39122
+ const methodName = method.toUpperCase();
39111
39123
  if (typeof args1 === "string") {
39112
39124
  this.#path = args1;
39113
39125
  } else {
39114
- this.#addRoute(method, this.#path, args1);
39126
+ this.#addRoute(methodName, this.#path, args1);
39115
39127
  }
39116
39128
  args.forEach((handler) => {
39117
- this.#addRoute(method, this.#path, handler);
39129
+ this.#addRoute(methodName, this.#path, handler);
39118
39130
  });
39119
39131
  return this;
39120
39132
  };
@@ -39123,9 +39135,10 @@ var Hono = class _Hono {
39123
39135
  for (const p of [path].flat()) {
39124
39136
  this.#path = p;
39125
39137
  for (const m of [method].flat()) {
39126
- handlers.map((handler) => {
39127
- this.#addRoute(m.toUpperCase(), this.#path, handler);
39128
- });
39138
+ const methodName = m.toUpperCase();
39139
+ for (const handler of handlers) {
39140
+ this.#addRoute(methodName, this.#path, handler);
39141
+ }
39129
39142
  }
39130
39143
  }
39131
39144
  return this;
@@ -39326,7 +39339,6 @@ var Hono = class _Hono {
39326
39339
  return this;
39327
39340
  }
39328
39341
  #addRoute(method, path, handler, baseRoutePath) {
39329
- method = method.toUpperCase();
39330
39342
  path = mergePath(this._basePath, path);
39331
39343
  const r = {
39332
39344
  basePath: baseRoutePath !== void 0 ? mergePath(this._basePath, baseRoutePath) : this._basePath,
@@ -41579,88 +41591,48 @@ var decoder = new TextDecoder();
41579
41591
  var strictDecoder = new TextDecoder("utf-8", { fatal: true });
41580
41592
  var MAX_INT32 = 2 ** 32;
41581
41593
  function concat(...buffers) {
41582
- const size = buffers.reduce((acc, { length }) => acc + length, 0);
41583
- const buf = new Uint8Array(size);
41594
+ const size = buffers.reduce((acc, { length }) => acc + length, 0), buf = new Uint8Array(size);
41584
41595
  let i = 0;
41585
- for (const buffer of buffers) {
41586
- buf.set(buffer, i);
41587
- i += buffer.length;
41588
- }
41596
+ for (const buffer of buffers)
41597
+ buf.set(buffer, i), i += buffer.length;
41589
41598
  return buf;
41590
41599
  }
41600
+ var NON_ASCII = /[^\x00-\x7f]/;
41591
41601
  function encode2(string4) {
41602
+ if (typeof string4 == "string" && string4.length >= 128) {
41603
+ if (NON_ASCII.test(string4))
41604
+ throw new TypeError("non-ASCII string encountered in encode()");
41605
+ return encoder.encode(string4);
41606
+ }
41592
41607
  const bytes = new Uint8Array(string4.length);
41593
41608
  for (let i = 0; i < string4.length; i++) {
41594
41609
  const code = string4.charCodeAt(i);
41595
- if (code > 127) {
41610
+ if (code > 127)
41596
41611
  throw new TypeError("non-ASCII string encountered in encode()");
41597
- }
41598
41612
  bytes[i] = code;
41599
41613
  }
41600
41614
  return bytes;
41601
41615
  }
41602
-
41603
- // node_modules/jose/dist/webapi/lib/crypto_key.js
41604
- var unusable = (name, prop = "algorithm.name") => new TypeError(`CryptoKey does not support this operation, its ${prop} must be ${name}`);
41605
- function checkUsage(key, usage) {
41606
- if (usage && !key.usages.includes(usage)) {
41607
- throw new TypeError(`CryptoKey does not support this operation, its usages must include ${usage}.`);
41608
- }
41609
- }
41610
- function checkModulusLength(alg, key) {
41611
- const { modulusLength } = key.algorithm;
41612
- if (typeof modulusLength !== "number" || modulusLength < 2048) {
41613
- throw new TypeError(`${alg} requires key modulusLength to be 2048 bits or larger`);
41616
+ function decodeBase64(encoded, url2 = false) {
41617
+ if (Uint8Array.fromBase64)
41618
+ return Uint8Array.fromBase64(encoded, { alphabet: url2 ? "base64url" : "base64" });
41619
+ if (url2) {
41620
+ if (encoded.includes("+") || encoded.includes("/"))
41621
+ throw new TypeError("Invalid base64url");
41622
+ encoded = encoded.replace(/-/g, "+").replace(/_/g, "/");
41614
41623
  }
41624
+ const binary = atob(encoded), bytes = new Uint8Array(binary.length);
41625
+ for (let i = 0; i < binary.length; i++)
41626
+ bytes[i] = binary.charCodeAt(i);
41627
+ return bytes;
41615
41628
  }
41616
- function checkCryptoKey(key, expected, usage) {
41617
- const algorithm = key.algorithm;
41618
- if (algorithm.name !== expected.name) {
41619
- throw unusable(expected.name);
41620
- }
41621
- if (expected.hash && algorithm.hash?.name !== expected.hash) {
41622
- throw unusable(expected.hash, "algorithm.hash");
41623
- }
41624
- if (expected.namedCurve && algorithm.namedCurve !== expected.namedCurve) {
41625
- throw unusable(expected.namedCurve, "algorithm.namedCurve");
41626
- }
41627
- if (expected.length !== void 0 && algorithm.length !== expected.length) {
41628
- throw unusable(expected.length, "algorithm.length");
41629
- }
41630
- checkUsage(key, usage);
41631
- }
41632
-
41633
- // node_modules/jose/dist/webapi/lib/invalid_key_input.js
41634
- function message(msg, actual, ...types) {
41635
- if (types.length > 2) {
41636
- const last = types.pop();
41637
- msg += `one of type ${types.join(", ")}, or ${last}.`;
41638
- } else if (types.length === 2) {
41639
- msg += `one of type ${types[0]} or ${types[1]}.`;
41640
- } else {
41641
- msg += `of type ${types[0]}.`;
41642
- }
41643
- if (actual == null) {
41644
- msg += ` Received ${actual}`;
41645
- } else if (typeof actual === "function" && actual.name) {
41646
- msg += ` Received function ${actual.name}`;
41647
- } else if (typeof actual === "object" && actual != null) {
41648
- if (actual.constructor?.name) {
41649
- msg += ` Received an instance of ${actual.constructor.name}`;
41650
- }
41651
- }
41652
- return msg;
41653
- }
41654
- var withAlg = (alg, actual, ...types) => message(`Key for the ${alg} algorithm must be `, actual, ...types);
41655
41629
 
41656
41630
  // node_modules/jose/dist/webapi/util/errors.js
41657
41631
  var JOSEError = class extends Error {
41658
41632
  static code = "ERR_JOSE_GENERIC";
41659
41633
  code = "ERR_JOSE_GENERIC";
41660
41634
  constructor(message2, options) {
41661
- super(message2, options);
41662
- this.name = this.constructor.name;
41663
- Error.captureStackTrace?.(this, this.constructor);
41635
+ super(message2, options), this.name = this.constructor.name, Error.captureStackTrace?.(this, this.constructor);
41664
41636
  }
41665
41637
  };
41666
41638
  var JWTClaimValidationFailed = class extends JOSEError {
@@ -41670,10 +41642,7 @@ var JWTClaimValidationFailed = class extends JOSEError {
41670
41642
  reason;
41671
41643
  payload;
41672
41644
  constructor(message2, payload, claim2 = "unspecified", reason = "unspecified") {
41673
- super(message2, { cause: { claim: claim2, reason, payload } });
41674
- this.claim = claim2;
41675
- this.reason = reason;
41676
- this.payload = payload;
41645
+ super(message2, { cause: { claim: claim2, reason, payload } }), this.claim = claim2, this.reason = reason, this.payload = payload;
41677
41646
  }
41678
41647
  };
41679
41648
  var JWTExpired = class extends JOSEError {
@@ -41683,10 +41652,7 @@ var JWTExpired = class extends JOSEError {
41683
41652
  reason;
41684
41653
  payload;
41685
41654
  constructor(message2, payload, claim2 = "unspecified", reason = "unspecified") {
41686
- super(message2, { cause: { claim: claim2, reason, payload } });
41687
- this.claim = claim2;
41688
- this.reason = reason;
41689
- this.payload = payload;
41655
+ super(message2, { cause: { claim: claim2, reason, payload } }), this.claim = claim2, this.reason = reason, this.payload = payload;
41690
41656
  }
41691
41657
  };
41692
41658
  var JOSEAlgNotAllowed = class extends JOSEError {
@@ -41740,73 +41706,37 @@ var JWSSignatureVerificationFailed = class extends JOSEError {
41740
41706
  }
41741
41707
  };
41742
41708
 
41743
- // node_modules/jose/dist/webapi/lib/is_key_like.js
41744
- var isCryptoKey = (key) => {
41745
- if (key?.[Symbol.toStringTag] === "CryptoKey")
41746
- return true;
41747
- try {
41748
- return key instanceof CryptoKey;
41749
- } catch {
41750
- return false;
41751
- }
41752
- };
41753
- var isKeyObject = (key) => key?.[Symbol.toStringTag] === "KeyObject";
41754
- var isKeyLike = (key) => isCryptoKey(key) || isKeyObject(key);
41755
-
41756
- // node_modules/jose/dist/webapi/lib/base64.js
41757
- function decodeBase64(encoded) {
41758
- if (Uint8Array.fromBase64) {
41759
- return Uint8Array.fromBase64(encoded);
41760
- }
41761
- const binary = atob(encoded);
41762
- const bytes = new Uint8Array(binary.length);
41763
- for (let i = 0; i < binary.length; i++) {
41764
- bytes[i] = binary.charCodeAt(i);
41765
- }
41766
- return bytes;
41767
- }
41768
-
41769
41709
  // node_modules/jose/dist/webapi/util/base64url.js
41770
41710
  var invalid = "The input to be decoded is not correctly encoded.";
41771
41711
  function decode2(input) {
41772
- if (Uint8Array.fromBase64) {
41773
- try {
41774
- return Uint8Array.fromBase64(typeof input === "string" ? input : decoder.decode(input), {
41775
- alphabet: "base64url"
41776
- });
41777
- } catch (cause) {
41778
- throw new TypeError(invalid, { cause });
41779
- }
41780
- }
41781
- let encoded = input;
41782
- if (encoded instanceof Uint8Array) {
41783
- encoded = decoder.decode(encoded);
41784
- }
41785
- if (encoded.includes("+") || encoded.includes("/")) {
41786
- throw new TypeError(invalid);
41787
- }
41788
- encoded = encoded.replace(/-/g, "+").replace(/_/g, "/");
41789
41712
  try {
41790
- return decodeBase64(encoded);
41791
- } catch {
41792
- throw new TypeError(invalid);
41713
+ return decodeBase64(typeof input == "string" ? input : decoder.decode(input), true);
41714
+ } catch (cause) {
41715
+ throw new TypeError(invalid, { cause });
41793
41716
  }
41794
41717
  }
41795
41718
 
41796
- // node_modules/jose/dist/webapi/lib/type_checks.js
41719
+ // node_modules/jose/dist/webapi/lib/validate.js
41797
41720
  function isObject2(input) {
41798
- if (typeof input !== "object" || input === null || Object.prototype.toString.call(input) !== "[object Object]") {
41721
+ if (typeof input != "object" || input === null || Object.prototype.toString.call(input) !== "[object Object]")
41799
41722
  return false;
41800
- }
41801
41723
  const prototype = Object.getPrototypeOf(input);
41802
41724
  return prototype === null || Object.getPrototypeOf(prototype) === null;
41803
41725
  }
41804
41726
  function isJwkSet(input) {
41805
41727
  return isObject2(input) && Array.isArray(input.keys) && Array.from(input.keys).every(isObject2);
41806
41728
  }
41807
-
41808
- // node_modules/jose/dist/webapi/lib/helpers.js
41809
- var unprotected = Symbol();
41729
+ function isDisjoint(...headers) {
41730
+ const parameters = /* @__PURE__ */ new Set();
41731
+ for (const header of headers)
41732
+ if (header)
41733
+ for (const parameter of Object.keys(header)) {
41734
+ if (parameters.has(parameter))
41735
+ return false;
41736
+ parameters.add(parameter);
41737
+ }
41738
+ return true;
41739
+ }
41810
41740
  function decodeBase64url(value, label, ErrorClass) {
41811
41741
  try {
41812
41742
  return decode2(value);
@@ -41828,48 +41758,42 @@ function parseJoseHeader(b64, ErrorClass, message2) {
41828
41758
  } catch {
41829
41759
  throw new ErrorClass(message2);
41830
41760
  }
41831
- if (!isObject2(parsed)) {
41761
+ if (!isObject2(parsed))
41832
41762
  throw new ErrorClass(message2);
41833
- }
41834
41763
  return parsed;
41835
41764
  }
41836
-
41837
- // node_modules/jose/dist/webapi/lib/jwk_to_key.js
41838
- async function jwkToKey(entry, jwk) {
41839
- if (jwk.kty === "RSA" && "oth" in jwk && jwk.oth !== void 0) {
41840
- throw new JOSENotSupported('RSA JWK "oth" (Other Primes Info) Parameter value is not supported');
41841
- }
41842
- if (!entry.kty.includes(jwk.kty)) {
41843
- throw new JOSENotSupported('Invalid or unsupported JWK "alg" (Algorithm) Parameter value');
41844
- }
41845
- const algorithm = entry.resolve?.({ kty: jwk.kty, crv: jwk.crv }) ?? entry.subtle;
41846
- const isPrivate = !!(jwk.d || jwk.priv);
41847
- const keyData = { ...jwk };
41848
- if (keyData.kty !== "AKP") {
41849
- delete keyData.alg;
41850
- }
41851
- delete keyData.use;
41852
- return crypto.subtle.importKey("jwk", keyData, algorithm, jwk.ext ?? !isPrivate, jwk.key_ops ?? entry.usages[isPrivate ? 1 : 0]);
41853
- }
41854
-
41855
- // node_modules/jose/dist/webapi/lib/jwk_metadata.js
41856
- function snapshotJwk(jwk) {
41857
- return { __proto__: null, ...jwk };
41765
+ var JWS_RECOGNIZED = { __proto__: null, b64: true };
41766
+ function validateAlgorithms(option, algorithms) {
41767
+ if (algorithms !== void 0 && (!Array.isArray(algorithms) || algorithms.some((s) => typeof s != "string")))
41768
+ throw new TypeError(`"${option}" option must be an array of strings`);
41769
+ return algorithms === void 0 ? void 0 : new Set(algorithms);
41858
41770
  }
41859
- function normalizeJwk(jwk) {
41860
- const normalized = snapshotJwk(jwk);
41861
- if (normalized.ext !== void 0 && typeof normalized.ext !== "boolean") {
41862
- throw new TypeError('"ext" (Extractable) Parameter must be a boolean');
41771
+ function validateCrit(Err, recognizedDefault, recognizedOption, protectedHeader, joseHeader) {
41772
+ if (joseHeader.crit !== void 0 && protectedHeader?.crit === void 0)
41773
+ throw new Err('"crit" (Critical) Header Parameter MUST be integrity protected');
41774
+ if (!protectedHeader || protectedHeader.crit === void 0)
41775
+ return [];
41776
+ if (!Array.isArray(protectedHeader.crit) || protectedHeader.crit.length === 0 || protectedHeader.crit.some((input) => typeof input != "string" || input.length === 0))
41777
+ throw new Err('"crit" (Critical) Header Parameter MUST be an array of non-empty strings when present');
41778
+ const recognized = recognizedOption === void 0 ? recognizedDefault : { __proto__: null, ...recognizedOption, ...recognizedDefault };
41779
+ for (const parameter of protectedHeader.crit) {
41780
+ if (!(parameter in recognized))
41781
+ throw new JOSENotSupported(`Extension Header Parameter "${parameter}" is not recognized`);
41782
+ if (!Object.hasOwn(joseHeader, parameter) || joseHeader[parameter] === void 0)
41783
+ throw new Err(`Extension Header Parameter "${parameter}" is missing`);
41784
+ if (recognized[parameter] && (!Object.hasOwn(protectedHeader, parameter) || protectedHeader[parameter] === void 0))
41785
+ throw new Err(`Extension Header Parameter "${parameter}" MUST be integrity protected`);
41863
41786
  }
41864
- if (normalized.key_ops !== void 0) {
41865
- const value = normalized.key_ops;
41866
- const keyOps = Array.isArray(value) ? [...value] : void 0;
41867
- if (!keyOps || keyOps.some((operation) => typeof operation !== "string") || new Set(keyOps).size !== keyOps.length) {
41868
- throw new TypeError('"key_ops" (Key Operations) Parameter must be an array of unique strings');
41869
- }
41870
- normalized.key_ops = keyOps;
41787
+ return protectedHeader.crit;
41788
+ }
41789
+ function validateB64(protectedHeader, extensions) {
41790
+ if (extensions.includes("b64")) {
41791
+ const b64 = protectedHeader.b64;
41792
+ if (typeof b64 != "boolean")
41793
+ throw new JWSInvalid('The "b64" (base64url-encode payload) Header Parameter must be a boolean');
41794
+ return b64;
41871
41795
  }
41872
- return normalized;
41796
+ return true;
41873
41797
  }
41874
41798
 
41875
41799
  // node_modules/jose/dist/webapi/lib/key.js
@@ -41878,60 +41802,55 @@ var jwkMatchesOp = (entry, key, usage) => {
41878
41802
  const { alg } = entry;
41879
41803
  if (key.use !== void 0) {
41880
41804
  const expected = usage === "sign" || usage === "verify" ? "sig" : "enc";
41881
- if (key.use !== expected) {
41805
+ if (key.use !== expected)
41882
41806
  throw new TypeError(`Invalid key for this operation, its "use" must be "${expected}" when present`);
41883
- }
41884
41807
  }
41885
- if (key.alg !== void 0 && key.alg !== alg) {
41808
+ if (key.alg !== void 0 && key.alg !== alg)
41886
41809
  throw new TypeError(`Invalid key for this operation, its "alg" must be "${alg}" when present`);
41887
- }
41888
41810
  if (Array.isArray(key.key_ops)) {
41889
41811
  const expectedKeyOp = usage === "encrypt" || usage === "decrypt" ? entry.ops?.[usage === "encrypt" ? 0 : 1] : usage;
41890
- if (expectedKeyOp && !key.key_ops.includes(expectedKeyOp)) {
41812
+ if (expectedKeyOp && !key.key_ops.includes(expectedKeyOp))
41891
41813
  throw new TypeError(`Invalid key for this operation, its "key_ops" must include "${expectedKeyOp}" when present`);
41892
- }
41893
41814
  }
41894
41815
  };
41895
- function checkKeyType(entry, key, usage) {
41896
- const { alg, secret } = entry;
41897
- const privateKey = usage === "decrypt" || usage === "sign";
41816
+ async function prepareKey(entry, key, usage) {
41817
+ const { alg, secret } = entry, privateKey = usage === "decrypt" || usage === "sign";
41898
41818
  if (secret && key instanceof Uint8Array)
41899
- return [BYTES, key];
41819
+ return key;
41820
+ let normalized, keyObject;
41900
41821
  if (isObject2(key)) {
41901
- const normalized = normalizeJwk(key);
41902
- if (typeof normalized.kty !== "string") {
41903
- throw new TypeError(secret ? withAlg(alg, key, "CryptoKey", "KeyObject", "JSON Web Key", "Uint8Array") : withAlg(alg, key, "CryptoKey", "KeyObject", "JSON Web Key"));
41904
- }
41905
- const valid = secret ? normalized.kty === "oct" && typeof normalized.k === "string" : normalized.kty !== "oct" && (privateKey ? normalized.kty === "AKP" && typeof normalized.priv === "string" || typeof normalized.d === "string" : normalized.d === void 0 && normalized.priv === void 0);
41906
- if (!valid) {
41907
- 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 ${privateKey ? "private" : "public"} JWK`);
41908
- }
41909
- jwkMatchesOp(entry, normalized, usage);
41910
- return [JWK, key, normalized];
41911
- }
41912
- if (!isKeyLike(key)) {
41913
- throw new TypeError(secret ? withAlg(alg, key, "CryptoKey", "KeyObject", "JSON Web Key", "Uint8Array") : withAlg(alg, key, "CryptoKey", "KeyObject", "JSON Web Key"));
41914
- }
41915
- if (secret) {
41916
- if (key.type !== "secret") {
41917
- throw new TypeError(`${tag(key)} instances for symmetric algorithms must be of type "secret"`);
41822
+ if (normalized = normalizeJwk(key), typeof normalized.kty != "string")
41823
+ throw invalidKeyType(alg, key, secret);
41824
+ if (!(secret ? normalized.kty === "oct" && typeof normalized.k == "string" : normalized.kty !== "oct" && (privateKey ? normalized.kty === "AKP" && typeof normalized.priv == "string" || typeof normalized.d == "string" : normalized.d === void 0 && normalized.priv === void 0)))
41825
+ 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 ${privateKey ? "private" : "public"} JWK`);
41826
+ if (jwkMatchesOp(entry, normalized, usage), normalized.kty === "oct")
41827
+ return decode2(normalized.k);
41828
+ if (!Object.isFrozen(key)) {
41829
+ const { key_ops } = key;
41830
+ Array.isArray(key_ops) && Object.freeze(key_ops), Object.freeze(key);
41918
41831
  }
41919
41832
  } else {
41920
- if (key.type === "secret") {
41921
- throw new TypeError(`${tag(key)} instances for asymmetric algorithms must not be of type "secret"`);
41922
- }
41923
- const expectedType = privateKey ? "private" : "public";
41924
- if ((key.type === "public" || key.type === "private") && key.type !== expectedType) {
41925
- const operation = usage === "sign" ? "signing" : usage === "verify" ? "verifying" : `${usage.slice(0, -1)}tion`;
41926
- throw new TypeError(`${tag(key)} instances for asymmetric algorithm ${operation} must be of type "${expectedType}"`);
41927
- }
41833
+ if (!isKeyLike(key))
41834
+ throw invalidKeyType(alg, key, secret);
41835
+ const expectedType = secret ? "secret" : privateKey ? "private" : "public";
41836
+ if (key.type !== expectedType && (secret || ["secret", "public", "private"].includes(key.type)))
41837
+ throw new TypeError(`${tag(key)} instances must be of type "${expectedType}" for the ${alg} algorithm`);
41838
+ if (isCryptoKey(key))
41839
+ return key;
41840
+ if (keyObject = key, keyObject.type === "secret")
41841
+ return keyObject.export();
41928
41842
  }
41929
- return isCryptoKey(key) ? [CRYPTO, key] : [KEYOBJECT, key];
41843
+ cache ||= /* @__PURE__ */ new WeakMap();
41844
+ const cacheKey = key;
41845
+ let cached2 = cache.get(cacheKey);
41846
+ if (cached2?.[alg])
41847
+ return cached2[alg];
41848
+ if (cached2 || cache.set(cacheKey, cached2 = {}), keyObject && typeof keyObject.toCryptoKey == "function") {
41849
+ const isPublic = keyObject.type === "public", crv = nist[keyObject.asymmetricKeyDetails?.namedCurve], params = entry.resolve?.({ crv, asymmetricKeyType: keyObject.asymmetricKeyType }) ?? entry.subtle;
41850
+ return cached2[alg] = keyObject.toCryptoKey(params, isPublic, entry.usages[isPublic ? 0 : 1]);
41851
+ }
41852
+ return normalized ??= keyObject.export({ format: "jwk" }), normalized.alg = alg, cached2[alg] = await jwkToKey(entry, normalized);
41930
41853
  }
41931
- var BYTES = 0;
41932
- var CRYPTO = 1;
41933
- var KEYOBJECT = 2;
41934
- var JWK = 3;
41935
41854
  var cache;
41936
41855
  var nist = {
41937
41856
  __proto__: null,
@@ -41939,139 +41858,83 @@ var nist = {
41939
41858
  secp384r1: "P-384",
41940
41859
  secp521r1: "P-521"
41941
41860
  };
41942
- function cached2(key, alg, value) {
41943
- cache ||= /* @__PURE__ */ new WeakMap();
41944
- const entry = cache.get(key);
41945
- if (value) {
41946
- if (entry) {
41947
- entry[alg] = value;
41948
- } else {
41949
- cache.set(key, { [alg]: value });
41950
- }
41951
- }
41952
- return value ?? entry?.[alg];
41953
- }
41954
- var handleJWK = async (key, jwk, entry) => cached2(key, entry.alg) ?? cached2(key, entry.alg, await jwkToKey(entry, { ...jwk, alg: entry.alg }));
41955
- var handleKeyObject = (keyObject, entry) => {
41956
- const hit = cached2(keyObject, entry.alg);
41957
- if (hit)
41958
- return hit;
41959
- const isPublic = keyObject.type === "public";
41960
- const usages = entry.usages[isPublic ? 0 : 1];
41961
- const { asymmetricKeyType } = keyObject;
41962
- const crv = nist[keyObject.asymmetricKeyDetails?.namedCurve];
41963
- const params = entry.resolve?.({ crv, asymmetricKeyType }) ?? entry.subtle;
41964
- return cached2(keyObject, entry.alg, keyObject.toCryptoKey(params, isPublic, usages));
41861
+ var isCryptoKey = (key) => {
41862
+ if (key?.[Symbol.toStringTag] === "CryptoKey")
41863
+ return true;
41864
+ try {
41865
+ return key instanceof CryptoKey;
41866
+ } catch {
41867
+ return false;
41868
+ }
41965
41869
  };
41966
- async function prepareKey(entry, key, usage) {
41967
- const tagged = checkKeyType(entry, key, usage);
41968
- switch (tagged[0]) {
41969
- case BYTES:
41970
- case CRYPTO:
41971
- return tagged[1];
41972
- case JWK: {
41973
- const key2 = tagged[1];
41974
- const normalized = tagged[2];
41975
- if (normalized.kty === "oct") {
41976
- return decode2(normalized.k);
41977
- }
41978
- if (!Object.isFrozen(key2)) {
41979
- const { key_ops } = key2;
41980
- if (Array.isArray(key_ops))
41981
- Object.freeze(key_ops);
41982
- Object.freeze(key2);
41983
- }
41984
- return handleJWK(key2, normalized, entry);
41985
- }
41986
- case KEYOBJECT: {
41987
- const keyObject = tagged[1];
41988
- if (keyObject.type === "secret") {
41989
- return keyObject.export();
41990
- }
41991
- if ("toCryptoKey" in keyObject && typeof keyObject.toCryptoKey === "function") {
41992
- return handleKeyObject(keyObject, entry);
41993
- }
41994
- return handleJWK(keyObject, keyObject.export({ format: "jwk" }), entry);
41995
- }
41870
+ var isKeyObject = (key) => key?.[Symbol.toStringTag] === "KeyObject";
41871
+ var isKeyLike = (key) => isCryptoKey(key) || isKeyObject(key);
41872
+ function message(msg, actual, ...types) {
41873
+ if (types.length > 2) {
41874
+ const last = types.pop();
41875
+ msg += `one of type ${types.join(", ")}, or ${last}.`;
41876
+ } else types.length === 2 ? msg += `one of type ${types[0]} or ${types[1]}.` : msg += `of type ${types[0]}.`;
41877
+ 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;
41878
+ }
41879
+ function invalidKeyType(alg, actual, secret) {
41880
+ const types = ["CryptoKey", "KeyObject", "JSON Web Key"];
41881
+ return secret && types.push("Uint8Array"), new TypeError(message(`Key for the ${alg} algorithm must be `, actual, ...types));
41882
+ }
41883
+ var unusable = (name, prop = "algorithm.name") => new TypeError(`CryptoKey does not support this operation, its ${prop} must be ${name}`);
41884
+ function checkUsage(key, usage) {
41885
+ if (usage && !key.usages.includes(usage))
41886
+ throw new TypeError(`CryptoKey does not support this operation, its usages must include ${usage}.`);
41887
+ }
41888
+ function checkModulusLength(alg, key) {
41889
+ const { modulusLength } = key.algorithm;
41890
+ if (typeof modulusLength != "number" || modulusLength < 2048)
41891
+ throw new TypeError(`${alg} requires key modulusLength to be 2048 bits or larger`);
41892
+ }
41893
+ function checkCryptoKey(key, expected, usage) {
41894
+ const algorithm = key.algorithm;
41895
+ if (algorithm.name !== expected.name)
41896
+ throw unusable(expected.name);
41897
+ if (expected.hash && algorithm.hash?.name !== expected.hash)
41898
+ throw unusable(expected.hash, "algorithm.hash");
41899
+ if (expected.namedCurve && algorithm.namedCurve !== expected.namedCurve)
41900
+ throw unusable(expected.namedCurve, "algorithm.namedCurve");
41901
+ if (expected.length !== void 0 && algorithm.length !== expected.length)
41902
+ throw unusable(expected.length, "algorithm.length");
41903
+ checkUsage(key, usage);
41904
+ }
41905
+ function snapshotJwk(jwk) {
41906
+ return { __proto__: null, ...jwk };
41907
+ }
41908
+ function normalizeJwk(jwk) {
41909
+ const normalized = snapshotJwk(jwk);
41910
+ if (normalized.ext !== void 0 && typeof normalized.ext != "boolean")
41911
+ throw new TypeError('"ext" (Extractable) Parameter must be a boolean');
41912
+ if (normalized.key_ops !== void 0) {
41913
+ const value = normalized.key_ops, keyOps = Array.isArray(value) ? [...value] : void 0;
41914
+ if (!keyOps || keyOps.some((operation) => typeof operation != "string") || new Set(keyOps).size !== keyOps.length)
41915
+ throw new TypeError('"key_ops" (Key Operations) Parameter must be an array of unique strings');
41916
+ normalized.key_ops = keyOps;
41996
41917
  }
41918
+ return normalized;
41919
+ }
41920
+ async function jwkToKey(entry, jwk, extractable) {
41921
+ if (!entry.kty.includes(jwk.kty))
41922
+ throw new JOSENotSupported('Invalid or unsupported JWK "alg" (Algorithm) Parameter value');
41923
+ const algorithm = entry.resolve?.({ kty: jwk.kty, crv: jwk.crv }) ?? entry.subtle, isPrivate = !!(jwk.d || jwk.priv), keyData = { ...jwk, ext: extractable ?? jwk.ext };
41924
+ 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]);
41925
+ }
41926
+ async function rawKey(key, expected, usage, extractable = false) {
41927
+ return key instanceof Uint8Array && (key = await crypto.subtle.importKey("raw", key, expected, extractable, [usage])), checkCryptoKey(key, expected, usage), key;
41997
41928
  }
41998
41929
 
41999
41930
  // node_modules/jose/dist/webapi/lib/key_descriptor.js
42000
41931
  function table(entries) {
42001
41932
  const out = { __proto__: null };
42002
- for (const alg in entries) {
41933
+ for (const alg in entries)
42003
41934
  out[alg] = { ...entries[alg], alg };
42004
- }
42005
41935
  return out;
42006
41936
  }
42007
41937
 
42008
- // node_modules/jose/dist/webapi/lib/options.js
42009
- var JWS_RECOGNIZED = { __proto__: null, b64: true };
42010
- function validateAlgorithms(option, algorithms) {
42011
- if (algorithms !== void 0 && (!Array.isArray(algorithms) || algorithms.some((s) => typeof s !== "string"))) {
42012
- throw new TypeError(`"${option}" option must be an array of strings`);
42013
- }
42014
- if (!algorithms) {
42015
- return void 0;
42016
- }
42017
- return new Set(algorithms);
42018
- }
42019
- function validateCrit(Err, recognizedDefault, recognizedOption, protectedHeader, joseHeader) {
42020
- if (joseHeader.crit !== void 0 && protectedHeader?.crit === void 0) {
42021
- throw new Err('"crit" (Critical) Header Parameter MUST be integrity protected');
42022
- }
42023
- if (!protectedHeader || protectedHeader.crit === void 0) {
42024
- return [];
42025
- }
42026
- if (!Array.isArray(protectedHeader.crit) || protectedHeader.crit.length === 0 || protectedHeader.crit.some((input) => typeof input !== "string" || input.length === 0)) {
42027
- throw new Err('"crit" (Critical) Header Parameter MUST be an array of non-empty strings when present');
42028
- }
42029
- const recognized = recognizedOption === void 0 ? recognizedDefault : { __proto__: null, ...recognizedOption, ...recognizedDefault };
42030
- for (const parameter of protectedHeader.crit) {
42031
- if (!(parameter in recognized)) {
42032
- throw new JOSENotSupported(`Extension Header Parameter "${parameter}" is not recognized`);
42033
- }
42034
- if (!Object.hasOwn(joseHeader, parameter) || joseHeader[parameter] === void 0) {
42035
- throw new Err(`Extension Header Parameter "${parameter}" is missing`);
42036
- }
42037
- if (recognized[parameter] && (!Object.hasOwn(protectedHeader, parameter) || protectedHeader[parameter] === void 0)) {
42038
- throw new Err(`Extension Header Parameter "${parameter}" MUST be integrity protected`);
42039
- }
42040
- }
42041
- return protectedHeader.crit;
42042
- }
42043
- function validateB64(protectedHeader, extensions) {
42044
- if (extensions.includes("b64")) {
42045
- const b64 = protectedHeader.b64;
42046
- if (typeof b64 !== "boolean") {
42047
- throw new JWSInvalid('The "b64" (base64url-encode payload) Header Parameter must be a boolean');
42048
- }
42049
- return b64;
42050
- }
42051
- return true;
42052
- }
42053
-
42054
- // node_modules/jose/dist/webapi/lib/signing.js
42055
- async function getSigKey(entry, key, usage) {
42056
- if (key instanceof Uint8Array) {
42057
- return crypto.subtle.importKey("raw", key, entry.subtle, false, [
42058
- usage
42059
- ]);
42060
- }
42061
- checkCryptoKey(key, entry.subtle, usage);
42062
- if (entry.minRsaBits)
42063
- checkModulusLength(entry.alg, key);
42064
- return key;
42065
- }
42066
- async function verify(entry, key, signature, data) {
42067
- const cryptoKey = await getSigKey(entry, key, "verify");
42068
- try {
42069
- return await crypto.subtle.verify(entry.signing, cryptoKey, signature, data);
42070
- } catch {
42071
- return false;
42072
- }
42073
- }
42074
-
42075
41938
  // node_modules/jose/dist/webapi/lib/jws_algorithms.js
42076
41939
  var sig = [["verify"], ["sign"]];
42077
41940
  function hmac(bits) {
@@ -42079,8 +41942,7 @@ function hmac(bits) {
42079
41942
  return { kty: ["oct"], secret: true, subtle, signing: subtle, usages: sig };
42080
41943
  }
42081
41944
  function rsa(bits, saltLength) {
42082
- const name = saltLength ? "RSA-PSS" : "RSASSA-PKCS1-v1_5";
42083
- const subtle = { name, hash: `SHA-${bits}` };
41945
+ const subtle = { name: saltLength ? "RSA-PSS" : "RSASSA-PKCS1-v1_5", hash: `SHA-${bits}` };
42084
41946
  return {
42085
41947
  kty: ["RSA"],
42086
41948
  subtle,
@@ -42109,8 +41971,7 @@ function eddsa() {
42109
41971
  };
42110
41972
  }
42111
41973
  function mldsa(bits) {
42112
- const name = `ML-DSA-${bits}`;
42113
- const subtle = { name };
41974
+ const subtle = { name: `ML-DSA-${bits}` };
42114
41975
  return {
42115
41976
  kty: ["AKP"],
42116
41977
  subtle,
@@ -42138,10 +41999,9 @@ var JWS = table({
42138
41999
  "ML-DSA-87": mldsa(87)
42139
42000
  });
42140
42001
  function jwsAlgorithm(alg) {
42141
- const entry = typeof alg === "string" ? JWS[alg] : void 0;
42142
- if (!entry) {
42002
+ const entry = typeof alg == "string" ? JWS[alg] : void 0;
42003
+ if (!entry)
42143
42004
  throw new JOSENotSupported(`alg ${alg} is not supported either by JOSE or your javascript runtime`);
42144
- }
42145
42005
  return entry;
42146
42006
  }
42147
42007
 
@@ -42149,19 +42009,8 @@ function jwsAlgorithm(alg) {
42149
42009
  function prepareVerify(options) {
42150
42010
  return [options && validateAlgorithms("algorithms", options.algorithms), options?.crit];
42151
42011
  }
42152
- function parseProtectedHeader(encodedProtected, parsedProtected = encodedProtected === void 0 ? {} : parseJoseHeader(encodedProtected, JWSInvalid, "JWS Protected Header is invalid")) {
42153
- return parsedProtected;
42154
- }
42155
- function validateJwsHeaders(parsedProt, joseHeader, shared) {
42156
- const b64 = validateB64(parsedProt, validateCrit(JWSInvalid, JWS_RECOGNIZED, shared[1], parsedProt, joseHeader));
42157
- const alg = joseHeader.alg;
42158
- if (typeof alg !== "string" || !alg) {
42159
- throw new JWSInvalid('JWS "alg" (Algorithm) Header Parameter missing or invalid');
42160
- }
42161
- if (shared[0] && !shared[0].has(alg)) {
42162
- throw new JOSEAlgNotAllowed('"alg" (Algorithm) Header Parameter value not allowed');
42163
- }
42164
- return [b64, alg];
42012
+ function parseProtectedHeader(encodedProtected) {
42013
+ return encodedProtected === void 0 ? {} : parseJoseHeader(encodedProtected, JWSInvalid, "JWS Protected Header is invalid");
42165
42014
  }
42166
42015
  function encodeCompactUnencodedPayload(payload) {
42167
42016
  try {
@@ -42170,39 +42019,42 @@ function encodeCompactUnencodedPayload(payload) {
42170
42019
  throw new JWSInvalid("JWS Compact Serialization payload must use only ASCII characters");
42171
42020
  }
42172
42021
  }
42173
- async function verifyPrepared(jws, shared, key, encodedProtected, parsedProt, alg, signingPayload) {
42022
+ async function verifySignature(jws, shared, key, encodeUnencodedPayload, parsedProtected) {
42023
+ const { protected: encodedProtected, header, payload: inputPayload } = jws, parsedProt = parsedProtected ?? parseProtectedHeader(encodedProtected);
42024
+ if (!isDisjoint(parsedProt, header))
42025
+ throw new JWSInvalid("JWS Protected and JWS Unprotected Header Parameter names must be disjoint");
42026
+ const joseHeader = { ...parsedProt, ...header }, b64 = validateB64(parsedProt, validateCrit(JWSInvalid, JWS_RECOGNIZED, shared[1], parsedProt, joseHeader)), { alg } = joseHeader;
42027
+ if (typeof alg != "string" || !alg)
42028
+ throw new JWSInvalid('JWS "alg" (Algorithm) Header Parameter missing or invalid');
42029
+ if (shared[0] && !shared[0].has(alg))
42030
+ throw new JOSEAlgNotAllowed('"alg" (Algorithm) Header Parameter value not allowed');
42031
+ if (b64) {
42032
+ if (typeof inputPayload != "string")
42033
+ throw new JWSInvalid("JWS Payload must be a string");
42034
+ } else if (typeof inputPayload != "string" && !(inputPayload instanceof Uint8Array))
42035
+ throw new JWSInvalid("JWS Payload must be a string or an Uint8Array instance");
42036
+ const signingPayload = b64 || typeof inputPayload != "string" ? inputPayload : encodeUnencodedPayload(inputPayload);
42174
42037
  let resolvedKey = false;
42175
- if (typeof key === "function") {
42176
- key = await key(parsedProt, jws);
42177
- resolvedKey = true;
42178
- }
42179
- const b64 = typeof signingPayload === "string";
42180
- const entry = jwsAlgorithm(alg);
42181
- const data = concat(encodedProtected !== void 0 ? encode2(encodedProtected) : new Uint8Array(), encode2("."), b64 ? shared[2] ??= encodeBase64url(signingPayload, "payload", JWSInvalid) : signingPayload);
42182
- const signature = decodeBase64url(jws.signature, "signature", JWSInvalid);
42183
- const k = await prepareKey(entry, key, "verify");
42184
- if (!await verify(entry, k, signature, data)) {
42185
- throw new JWSSignatureVerificationFailed();
42038
+ typeof key == "function" && (key = await key(parsedProt, jws), resolvedKey = true);
42039
+ const entry = jwsAlgorithm(alg), data = concat(encodedProtected !== void 0 ? encode2(encodedProtected) : new Uint8Array(), encode2("."), typeof signingPayload == "string" ? shared[2] ??= encodeBase64url(signingPayload, "payload", JWSInvalid) : signingPayload), signature = decodeBase64url(jws.signature, "signature", JWSInvalid), k = await prepareKey(entry, key, "verify"), cryptoKey = await rawKey(k, entry.subtle, "verify");
42040
+ entry.minRsaBits && checkModulusLength(entry.alg, cryptoKey);
42041
+ let verified = false;
42042
+ try {
42043
+ verified = await crypto.subtle.verify(entry.signing, cryptoKey, signature, data);
42044
+ } catch {
42186
42045
  }
42187
- const payload = b64 ? decodeBase64url(signingPayload, "payload", JWSInvalid) : signingPayload;
42188
- return [payload, parsedProt, b64, k, resolvedKey];
42046
+ if (!verified)
42047
+ throw new JWSSignatureVerificationFailed();
42048
+ const result = { payload: typeof signingPayload == "string" ? decodeBase64url(signingPayload, "payload", JWSInvalid) : signingPayload };
42049
+ return encodedProtected !== void 0 && (result.protectedHeader = parsedProt), header !== void 0 && (result.unprotectedHeader = header), resolvedKey ? [{ ...result, key: k }, b64] : [result, b64];
42189
42050
  }
42190
42051
  async function verifyCompact(jws, shared, key) {
42191
- if (jws instanceof Uint8Array) {
42192
- jws = decoder.decode(jws);
42193
- }
42194
- if (typeof jws !== "string") {
42052
+ if (jws instanceof Uint8Array && (jws = decoder.decode(jws)), typeof jws != "string")
42195
42053
  throw new JWSInvalid("Compact JWS must be a string or Uint8Array");
42196
- }
42197
42054
  const { 0: protectedHeader, 1: payload, 2: signature, length } = jws.split(".");
42198
- if (length !== 3) {
42055
+ if (length !== 3)
42199
42056
  throw new JWSInvalid("Invalid Compact JWS");
42200
- }
42201
- const compactJws = { payload, protected: protectedHeader, signature };
42202
- const parsedProt = parseProtectedHeader(protectedHeader);
42203
- const [b64, alg] = validateJwsHeaders(parsedProt, parsedProt, shared);
42204
- const signingPayload = b64 ? payload : encodeCompactUnencodedPayload(payload);
42205
- return verifyPrepared(compactJws, shared, key, protectedHeader, parsedProt, alg, signingPayload);
42057
+ return verifySignature({ payload, protected: protectedHeader, signature }, shared, key, encodeCompactUnencodedPayload);
42206
42058
  }
42207
42059
 
42208
42060
  // node_modules/jose/dist/webapi/lib/jwt_claims_set.js
@@ -42221,50 +42073,29 @@ function invalidDuration() {
42221
42073
  throw new TypeError("Invalid time period format");
42222
42074
  }
42223
42075
  function secs(str) {
42224
- if (typeof str !== "string") {
42225
- invalidDuration();
42226
- }
42076
+ typeof str != "string" && invalidDuration();
42227
42077
  const matched = REGEX.exec(str);
42228
- if (!matched || matched[4] && matched[1]) {
42229
- invalidDuration();
42230
- }
42231
- const value = parseFloat(matched[2]);
42232
- const numericDate = Math.round(value * multipliers[matched[3][0].toLowerCase()]);
42233
- if (!Number.isFinite(numericDate)) {
42234
- invalidDuration();
42235
- }
42236
- if (matched[1] === "-" || matched[4] === "ago") {
42237
- return -numericDate;
42238
- }
42239
- return numericDate;
42078
+ (!matched || matched[4] && matched[1]) && invalidDuration();
42079
+ const value = parseFloat(matched[2]), numericDate2 = Math.round(value * multipliers[matched[3][0].toLowerCase()]);
42080
+ return Number.isFinite(numericDate2) || invalidDuration(), matched[1] === "-" || matched[4] === "ago" ? -numericDate2 : numericDate2;
42240
42081
  }
42241
42082
  function validateInput(label, input) {
42242
- if (!Number.isFinite(input)) {
42083
+ if (!Number.isFinite(input))
42243
42084
  throw new TypeError(`Invalid ${label} input`);
42244
- }
42245
42085
  return input;
42246
42086
  }
42247
42087
  var normalizeTyp = (value) => {
42248
42088
  const normalized = value.toLowerCase();
42249
42089
  return value.includes("/") ? normalized : `application/${normalized}`;
42250
42090
  };
42251
- var checkAudiencePresence = (audPayload, audOption) => {
42252
- if (typeof audPayload === "string") {
42253
- return audOption.includes(audPayload);
42254
- }
42255
- if (Array.isArray(audPayload)) {
42256
- return audOption.some((aud) => audPayload.includes(aud));
42257
- }
42258
- return false;
42259
- };
42091
+ var checkAudiencePresence = (audPayload, audOption) => typeof audPayload == "string" ? audOption.includes(audPayload) : Array.isArray(audPayload) ? audOption.some((aud) => audPayload.includes(aud)) : false;
42260
42092
  function validateNumericDate(payload, claim2, required2 = false) {
42261
42093
  const value = payload[claim2];
42262
- if (value === void 0 && !required2)
42263
- return void 0;
42264
- if (typeof value !== "number") {
42265
- throw new JWTClaimValidationFailed(`"${claim2}" claim must be a number`, payload, claim2, "invalid");
42094
+ if (!(value === void 0 && !required2)) {
42095
+ if (typeof value != "number")
42096
+ throw new JWTClaimValidationFailed(`"${claim2}" claim must be a number`, payload, claim2, "invalid");
42097
+ return value;
42266
42098
  }
42267
- return value;
42268
42099
  }
42269
42100
  function unexpectedClaim(payload, claim2) {
42270
42101
  throw new JWTClaimValidationFailed(`unexpected "${claim2}" claim value`, payload, claim2, checkFailed);
@@ -42275,107 +42106,70 @@ function validateClaimsSet(protectedHeader, encodedPayload, options = {}) {
42275
42106
  payload = JSON.parse(strictDecoder.decode(encodedPayload));
42276
42107
  } catch {
42277
42108
  }
42278
- if (!isObject2(payload)) {
42109
+ if (!isObject2(payload))
42279
42110
  throw new JWTInvalid("JWT Claims Set must be a top-level JSON object");
42280
- }
42281
42111
  const { typ } = options;
42282
- if (typ !== void 0 && (typeof protectedHeader.typ !== "string" || normalizeTyp(protectedHeader.typ) !== normalizeTyp(typ))) {
42112
+ if (typ !== void 0 && (typeof protectedHeader.typ != "string" || normalizeTyp(protectedHeader.typ) !== normalizeTyp(typ)))
42283
42113
  throw new JWTClaimValidationFailed('unexpected "typ" JWT header value', payload, "typ", checkFailed);
42284
- }
42285
- const { requiredClaims = [], issuer, subject, audience, maxTokenAge } = options;
42286
- const presenceCheck = [...requiredClaims];
42287
- if (maxTokenAge !== void 0)
42288
- presenceCheck.push("iat");
42289
- if (audience !== void 0)
42290
- presenceCheck.push("aud");
42291
- if (subject !== void 0)
42292
- presenceCheck.push("sub");
42293
- if (issuer !== void 0)
42294
- presenceCheck.push("iss");
42295
- for (const claim2 of new Set(presenceCheck.reverse())) {
42296
- if (!Object.hasOwn(payload, claim2)) {
42114
+ const { requiredClaims = [], issuer, subject, audience, maxTokenAge } = options, presenceCheck = [...requiredClaims];
42115
+ maxTokenAge !== void 0 && presenceCheck.push("iat"), audience !== void 0 && presenceCheck.push("aud"), subject !== void 0 && presenceCheck.push("sub"), issuer !== void 0 && presenceCheck.push("iss");
42116
+ for (const claim2 of new Set(presenceCheck.reverse()))
42117
+ if (!Object.hasOwn(payload, claim2))
42297
42118
  throw new JWTClaimValidationFailed(`missing required "${claim2}" claim`, payload, claim2, "missing");
42298
- }
42299
- }
42300
- if (issuer !== void 0 && !(Array.isArray(issuer) ? issuer : [issuer]).includes(payload.iss)) {
42301
- unexpectedClaim(payload, "iss");
42302
- }
42303
- if (subject !== void 0 && payload.sub !== subject) {
42304
- unexpectedClaim(payload, "sub");
42305
- }
42306
- if (audience !== void 0 && !checkAudiencePresence(payload.aud, typeof audience === "string" ? [audience] : audience)) {
42307
- unexpectedClaim(payload, "aud");
42308
- }
42119
+ issuer !== void 0 && !(Array.isArray(issuer) ? issuer : [issuer]).includes(payload.iss) && unexpectedClaim(payload, "iss"), subject !== void 0 && payload.sub !== subject && unexpectedClaim(payload, "sub"), audience !== void 0 && !checkAudiencePresence(payload.aud, typeof audience == "string" ? [audience] : audience) && unexpectedClaim(payload, "aud");
42309
42120
  const { clockTolerance } = options;
42310
42121
  let tolerance = 0;
42311
- if (typeof clockTolerance === "string") {
42122
+ if (typeof clockTolerance == "string")
42312
42123
  tolerance = secs(clockTolerance);
42313
- } else if (clockTolerance !== void 0) {
42314
- if (typeof clockTolerance !== "number") {
42124
+ else if (clockTolerance !== void 0) {
42125
+ if (typeof clockTolerance != "number")
42315
42126
  throw new TypeError("Invalid clockTolerance option type");
42316
- }
42317
42127
  tolerance = clockTolerance;
42318
42128
  }
42319
42129
  validateInput("clockTolerance option", tolerance);
42320
- const { currentDate } = options;
42321
- const now = validateInput("currentDate option", epoch(currentDate === void 0 ? /* @__PURE__ */ new Date() : currentDate));
42322
- const iat = validateNumericDate(payload, "iat", maxTokenAge !== void 0);
42323
- const nbf = validateNumericDate(payload, "nbf");
42324
- if (nbf !== void 0) {
42325
- if (nbf > now + tolerance) {
42326
- throw new JWTClaimValidationFailed('"nbf" claim timestamp check failed', payload, "nbf", checkFailed);
42327
- }
42328
- }
42130
+ const { currentDate } = options, now = validateInput("currentDate option", epoch(currentDate === void 0 ? /* @__PURE__ */ new Date() : currentDate)), iat = validateNumericDate(payload, "iat", maxTokenAge !== void 0), nbf = validateNumericDate(payload, "nbf");
42131
+ if (nbf !== void 0 && nbf > now + tolerance)
42132
+ throw new JWTClaimValidationFailed('"nbf" claim timestamp check failed', payload, "nbf", checkFailed);
42329
42133
  const exp = validateNumericDate(payload, "exp");
42330
- if (exp !== void 0) {
42331
- if (exp <= now - tolerance) {
42332
- throw new JWTExpired('"exp" claim timestamp check failed', payload, "exp", checkFailed);
42333
- }
42334
- }
42134
+ if (exp !== void 0 && exp <= now - tolerance)
42135
+ throw new JWTExpired('"exp" claim timestamp check failed', payload, "exp", checkFailed);
42335
42136
  if (maxTokenAge !== void 0) {
42336
- const age = now - iat;
42337
- const max = validateInput("maxTokenAge option", typeof maxTokenAge === "number" ? maxTokenAge : secs(maxTokenAge));
42338
- if (age - tolerance > max) {
42137
+ const age = now - iat, max = validateInput("maxTokenAge option", typeof maxTokenAge == "number" ? maxTokenAge : secs(maxTokenAge));
42138
+ if (age - tolerance > max)
42339
42139
  throw new JWTExpired('"iat" claim timestamp check failed (too far in the past)', payload, "iat", checkFailed);
42340
- }
42341
- if (age < -tolerance) {
42140
+ if (age < -tolerance)
42342
42141
  throw new JWTClaimValidationFailed('"iat" claim timestamp check failed (it should be in the past)', payload, "iat", checkFailed);
42343
- }
42344
42142
  }
42345
42143
  return payload;
42346
42144
  }
42347
42145
 
42348
42146
  // node_modules/jose/dist/webapi/jwt/verify.js
42349
42147
  async function jwtVerify(jwt, key, options) {
42350
- const verified = await verifyCompact(jwt, prepareVerify(options), key);
42351
- if (!verified[2]) {
42148
+ const [verified, b64] = await verifyCompact(jwt, prepareVerify(options), key);
42149
+ if (!b64)
42352
42150
  throw new JWTInvalid("JWTs MUST NOT use unencoded payload");
42353
- }
42354
- const payload = validateClaimsSet(verified[1], verified[0], options);
42355
- const result = { payload, protectedHeader: verified[1] };
42356
- if (typeof key === "function") {
42357
- return { ...result, key: verified[3] };
42358
- }
42359
- return result;
42151
+ const payload = validateClaimsSet(verified.protectedHeader, verified.payload, options);
42152
+ return { ...verified, payload };
42360
42153
  }
42361
42154
 
42362
42155
  // node_modules/jose/dist/webapi/jwks/local.js
42363
42156
  function isUsableJWK(jwk, entry, alg, kid) {
42364
- const { kty, key_ops, ext, kid: jwkKid, alg: jwkAlg, use, crv } = snapshotJwk(jwk);
42365
- const keyOps = Array.isArray(key_ops) ? [...key_ops] : key_ops;
42366
- 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);
42157
+ const { kty, key_ops: keyOps, ext, kid: jwkKid, alg: jwkAlg, use, crv } = jwk;
42158
+ 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);
42367
42159
  }
42368
42160
  async function importWithAlgCache(cache2, jwk, entry) {
42369
- const cached3 = cache2.get(jwk) || cache2.set(jwk, {}).get(jwk);
42370
- const { alg } = entry;
42371
- if (cached3[alg] === void 0) {
42372
- const key = await jwkToKey(entry, { ...jwk, alg, ext: true });
42373
- if (key.type !== "public") {
42374
- throw new JWKSInvalid("JSON Web Key Set members must be public keys");
42375
- }
42376
- cached3[alg] = key;
42161
+ const cached2 = cache2.get(jwk) || cache2.set(jwk, {}).get(jwk), { alg } = entry;
42162
+ if (cached2[alg] === void 0) {
42163
+ const pending = jwkToKey(entry, jwk, true).then((key) => {
42164
+ if (key.type !== "public")
42165
+ throw new JWKSInvalid("JSON Web Key Set members must be public keys");
42166
+ return cached2[alg] = key, key;
42167
+ }).catch((error2) => {
42168
+ throw cached2[alg] === pending && delete cached2[alg], error2;
42169
+ });
42170
+ cached2[alg] = pending;
42377
42171
  }
42378
- return cached3[alg];
42172
+ return cached2[alg];
42379
42173
  }
42380
42174
  function createLocalJWKSet(jwks) {
42381
42175
  let snapshot;
@@ -42383,51 +42177,42 @@ function createLocalJWKSet(jwks) {
42383
42177
  snapshot = structuredClone(jwks);
42384
42178
  } catch {
42385
42179
  }
42386
- if (!isJwkSet(snapshot)) {
42180
+ if (!isJwkSet(snapshot))
42387
42181
  throw new JWKSInvalid("JSON Web Key Set malformed");
42388
- }
42389
- const cached3 = /* @__PURE__ */ new WeakMap();
42390
- const localJWKSet = async (protectedHeader, token) => {
42391
- const { alg, kid } = { ...protectedHeader, ...token?.header };
42392
- const entry = typeof alg === "string" ? JWS[alg] : void 0;
42393
- if (!entry || entry.secret) {
42182
+ const metadata = snapshot.keys.map((jwk) => {
42183
+ const normalized = snapshotJwk(jwk);
42184
+ return Array.isArray(normalized.key_ops) && (normalized.key_ops = [...normalized.key_ops]), normalized;
42185
+ }), cached2 = /* @__PURE__ */ new WeakMap();
42186
+ return Object.defineProperty(async (protectedHeader, token) => {
42187
+ const { alg, kid } = { ...protectedHeader, ...token?.header }, entry = typeof alg == "string" ? JWS[alg] : void 0;
42188
+ if (!entry || entry.secret)
42394
42189
  throw new JOSENotSupported('Unsupported "alg" value for a JSON Web Key Set');
42395
- }
42396
- const candidates = snapshot.keys.filter((jwk2) => isUsableJWK(jwk2, entry, alg, kid));
42397
- const { 0: jwk, length } = candidates;
42398
- if (!length) {
42190
+ const candidates = snapshot.keys.filter((_, index) => isUsableJWK(metadata[index], entry, alg, kid)), { 0: jwk, length } = candidates;
42191
+ if (!length)
42399
42192
  throw new JWKSNoMatchingKey();
42400
- }
42401
42193
  if (length !== 1) {
42402
42194
  const error2 = new JWKSMultipleMatchingKeys();
42403
- error2[Symbol.asyncIterator] = async function* () {
42404
- for (const jwk2 of candidates) {
42195
+ throw error2[Symbol.asyncIterator] = async function* () {
42196
+ for (const jwk2 of candidates)
42405
42197
  try {
42406
- yield await importWithAlgCache(cached3, jwk2, entry);
42198
+ yield await importWithAlgCache(cached2, jwk2, entry);
42407
42199
  } catch {
42408
42200
  }
42409
- }
42410
- };
42411
- throw error2;
42201
+ }, error2;
42412
42202
  }
42413
- return importWithAlgCache(cached3, jwk, entry);
42414
- };
42415
- return Object.defineProperty(localJWKSet, "jwks", {
42203
+ return importWithAlgCache(cached2, jwk, entry);
42204
+ }, "jwks", {
42416
42205
  value: () => structuredClone(snapshot)
42417
42206
  });
42418
42207
  }
42419
42208
 
42420
42209
  // node_modules/jose/dist/webapi/jwks/remote.js
42421
42210
  function isCloudflareWorkers() {
42422
- return typeof WebSocketPair !== "undefined" || typeof navigator !== "undefined" && navigator.userAgent === "Cloudflare-Workers" || typeof EdgeRuntime !== "undefined" && EdgeRuntime === "vercel";
42211
+ return typeof WebSocketPair < "u" || typeof navigator < "u" && navigator.userAgent === "Cloudflare-Workers" || typeof EdgeRuntime < "u" && EdgeRuntime === "vercel";
42423
42212
  }
42424
42213
  var USER_AGENT;
42425
- if (typeof navigator === "undefined" || !navigator.userAgent?.startsWith?.("Mozilla/5.0 ")) {
42426
- const NAME = "jose";
42427
- const VERSION2 = "v6.2.10";
42428
- USER_AGENT = `${NAME}/${VERSION2}`;
42429
- }
42430
- var customFetch = Symbol();
42214
+ (typeof navigator > "u" || !navigator.userAgent?.startsWith?.("Mozilla/5.0 ")) && (USER_AGENT = "jose/v6.2.12");
42215
+ var customFetch = /* @__PURE__ */ Symbol();
42431
42216
  async function fetchJwks(url2, headers, signal, fetchImpl = fetch) {
42432
42217
  const response = await fetchImpl(url2, {
42433
42218
  method: "GET",
@@ -42435,106 +42220,64 @@ async function fetchJwks(url2, headers, signal, fetchImpl = fetch) {
42435
42220
  redirect: "manual",
42436
42221
  headers
42437
42222
  }).catch((err) => {
42438
- if (err.name === "TimeoutError") {
42439
- throw new JWKSTimeout();
42440
- }
42441
- throw err;
42223
+ throw err.name === "TimeoutError" ? new JWKSTimeout() : err;
42442
42224
  });
42443
- if (response.status !== 200) {
42225
+ if (response.status !== 200)
42444
42226
  throw new JOSEError("Expected 200 OK from the JSON Web Key Set HTTP response");
42445
- }
42446
42227
  try {
42447
42228
  return await response.json();
42448
42229
  } catch {
42449
42230
  throw new JOSEError("Failed to parse the JSON Web Key Set HTTP response as JSON");
42450
42231
  }
42451
42232
  }
42452
- var jwksCache = Symbol();
42233
+ var jwksCache = /* @__PURE__ */ Symbol();
42453
42234
  function isFreshFor(timestamp, duration3) {
42454
42235
  return Number.isFinite(timestamp) && Date.now() < timestamp + duration3;
42455
42236
  }
42456
42237
  function validateDuration(value, fallback, option) {
42457
- if (Number.isNaN(value)) {
42238
+ if (Number.isNaN(value))
42458
42239
  throw new TypeError(`"${option}" option must not be NaN`);
42459
- }
42460
- return typeof value === "number" ? value : fallback;
42240
+ return typeof value == "number" ? value : fallback;
42461
42241
  }
42462
42242
  function createRemoteJWKSet(url2, options) {
42463
- if (!(url2 instanceof URL)) {
42243
+ if (!(url2 instanceof URL))
42464
42244
  throw new TypeError("url must be an instance of URL");
42465
- }
42466
- const href = new URL(url2.href).href;
42467
- const opts = options ?? {};
42468
- const timeoutOption = opts.timeoutDuration;
42469
- if (typeof timeoutOption === "number" && (!Number.isInteger(timeoutOption) || timeoutOption < 0)) {
42245
+ const href = new URL(url2.href).href, opts = options ?? {}, timeoutOption = opts.timeoutDuration;
42246
+ if (typeof timeoutOption == "number" && (!Number.isInteger(timeoutOption) || timeoutOption < 0))
42470
42247
  throw new TypeError('"timeoutDuration" option must be a non-negative integer');
42471
- }
42472
- const timeoutDuration = typeof timeoutOption === "number" ? timeoutOption : 5e3;
42473
- const cooldownDuration = validateDuration(opts.cooldownDuration, 3e4, "cooldownDuration");
42474
- const cacheMaxAge = validateDuration(opts.cacheMaxAge, 6e5, "cacheMaxAge");
42475
- const headers = new Headers(opts.headers);
42476
- if (USER_AGENT && !headers.has("User-Agent")) {
42477
- headers.set("User-Agent", USER_AGENT);
42478
- }
42479
- if (!headers.has("accept")) {
42480
- headers.set("accept", "application/json, application/jwk-set+json");
42481
- }
42482
- const fetchImpl = opts[customFetch];
42483
- const cache2 = opts[jwksCache];
42484
- let jwksTimestamp;
42485
- let pendingFetch;
42486
- let reloadSequence = 0;
42487
- let appliedSequence = 0;
42488
- let local;
42489
- if (cache2 && typeof cache2 === "object") {
42248
+ const timeoutDuration = typeof timeoutOption == "number" ? timeoutOption : 5e3, cooldownDuration = validateDuration(opts.cooldownDuration, 3e4, "cooldownDuration"), cacheMaxAge = validateDuration(opts.cacheMaxAge, 6e5, "cacheMaxAge"), headers = new Headers(opts.headers);
42249
+ USER_AGENT && !headers.has("User-Agent") && headers.set("User-Agent", USER_AGENT), headers.has("accept") || headers.set("accept", "application/json, application/jwk-set+json");
42250
+ const fetchImpl = opts[customFetch], cache2 = opts[jwksCache];
42251
+ let jwksTimestamp, pendingFetch, reloadSequence = 0, appliedSequence = 0, local;
42252
+ if (cache2 && typeof cache2 == "object") {
42490
42253
  const { uat, jwks } = cache2;
42491
- if (isFreshFor(uat, cacheMaxAge) && isJwkSet(jwks)) {
42492
- jwksTimestamp = uat;
42493
- local = createLocalJWKSet(jwks);
42494
- }
42254
+ isFreshFor(uat, cacheMaxAge) && isJwkSet(jwks) && (jwksTimestamp = uat, local = createLocalJWKSet(jwks));
42495
42255
  }
42496
42256
  const reload = async () => {
42497
- if (pendingFetch && isCloudflareWorkers()) {
42498
- pendingFetch = void 0;
42499
- }
42500
- if (!pendingFetch) {
42501
- const sequence = ++reloadSequence;
42502
- const current = pendingFetch = fetchJwks(href, headers, AbortSignal.timeout(timeoutDuration), fetchImpl).then((json) => {
42257
+ if (pendingFetch && isCloudflareWorkers() && (pendingFetch = void 0), !pendingFetch) {
42258
+ const sequence = ++reloadSequence, current = pendingFetch = fetchJwks(href, headers, AbortSignal.timeout(timeoutDuration), fetchImpl).then((json) => {
42503
42259
  const next = createLocalJWKSet(json);
42504
- if (sequence <= appliedSequence) {
42260
+ if (sequence <= appliedSequence)
42505
42261
  return;
42506
- }
42507
42262
  local = next;
42508
42263
  const updatedAt = Date.now();
42509
- if (cache2) {
42510
- cache2.uat = updatedAt;
42511
- cache2.jwks = json;
42512
- }
42513
- jwksTimestamp = updatedAt;
42514
- appliedSequence = sequence;
42264
+ cache2 && (cache2.uat = updatedAt, cache2.jwks = json), jwksTimestamp = updatedAt, appliedSequence = sequence;
42515
42265
  }).finally(() => {
42516
- if (pendingFetch === current) {
42517
- pendingFetch = void 0;
42518
- }
42266
+ pendingFetch === current && (pendingFetch = void 0);
42519
42267
  });
42520
42268
  }
42521
42269
  await pendingFetch;
42522
42270
  };
42523
- const remoteJWKSet = async (protectedHeader, token) => {
42524
- if (!local || !isFreshFor(jwksTimestamp, cacheMaxAge)) {
42525
- await reload();
42526
- }
42271
+ return Object.defineProperties(async (protectedHeader, token) => {
42272
+ (!local || !isFreshFor(jwksTimestamp, cacheMaxAge)) && await reload();
42527
42273
  try {
42528
42274
  return await local(protectedHeader, token);
42529
42275
  } catch (err) {
42530
- if (err instanceof JWKSNoMatchingKey && !isFreshFor(jwksTimestamp, cooldownDuration)) {
42531
- await reload();
42532
- return local(protectedHeader, token);
42533
- }
42276
+ if (err instanceof JWKSNoMatchingKey && !isFreshFor(jwksTimestamp, cooldownDuration))
42277
+ return await reload(), local(protectedHeader, token);
42534
42278
  throw err;
42535
42279
  }
42536
- };
42537
- return Object.defineProperties(remoteJWKSet, {
42280
+ }, {
42538
42281
  coolingDown: {
42539
42282
  get: () => isFreshFor(jwksTimestamp, cooldownDuration),
42540
42283
  enumerable: true
@@ -42637,16 +42380,16 @@ var JwtAuthProvider = class _JwtAuthProvider extends AuthProvider {
42637
42380
  }
42638
42381
  async verifyToken(token) {
42639
42382
  const cacheKey = await this.hashToken(token);
42640
- const cached3 = this.tokenCache.get(cacheKey);
42641
- if (cached3 && Date.now() < cached3.expiresAt) {
42383
+ const cached2 = this.tokenCache.get(cacheKey);
42384
+ if (cached2 && Date.now() < cached2.expiresAt) {
42642
42385
  if (isOtelEnabled()) {
42643
42386
  recordAuthEvent("cache_hit", {
42644
- subject: cached3.authInfo.subject ?? ""
42387
+ subject: cached2.authInfo.subject ?? ""
42645
42388
  });
42646
42389
  }
42647
- return cached3.authInfo;
42390
+ return cached2.authInfo;
42648
42391
  }
42649
- if (cached3) this.tokenCache.delete(cacheKey);
42392
+ if (cached2) this.tokenCache.delete(cacheKey);
42650
42393
  try {
42651
42394
  const { payload } = await jwtVerify(token, this.jwks, {
42652
42395
  issuer: this.options.issuer,
@@ -48522,8 +48265,8 @@ var FrappeClient = class {
48522
48265
  async list(doctype, options = {}, opts = {}) {
48523
48266
  const cacheKey = `list:${doctype}:${stableStringify(options)}`;
48524
48267
  if (!opts.skipCache) {
48525
- const cached3 = this.cache.get(cacheKey);
48526
- if (cached3 !== void 0) return cached3;
48268
+ const cached2 = this.cache.get(cacheKey);
48269
+ if (cached2 !== void 0) return cached2;
48527
48270
  }
48528
48271
  const params = new URLSearchParams();
48529
48272
  if (options.fields && options.fields.length > 0) {
@@ -48563,8 +48306,8 @@ var FrappeClient = class {
48563
48306
  async get(doctype, name, opts = {}) {
48564
48307
  const cacheKey = `get:${doctype}:${name}`;
48565
48308
  if (!opts.skipCache) {
48566
- const cached3 = this.cache.get(cacheKey);
48567
- if (cached3 !== void 0) return cached3;
48309
+ const cached2 = this.cache.get(cacheKey);
48310
+ if (cached2 !== void 0) return cached2;
48568
48311
  }
48569
48312
  const res = await this.request(
48570
48313
  "GET",
@@ -53716,7 +53459,66 @@ function loadMethodAllowlist() {
53716
53459
  return parseAllowlist(env6("ERPNEXT_METHOD_ALLOWLIST"));
53717
53460
  }
53718
53461
 
53462
+ // src/tools/purchase-invoice-hints.ts
53463
+ var PURCHASE_INVOICE_DOCTYPE = "Purchase Invoice";
53464
+ var PARTY_ACCOUNT_HINT = "Set data.credit_to, or configure Supplier/Supplier Group accounts, or Company.default_payable_account.";
53465
+ var GRNI_HINT = "Company.stock_received_but_not_billed is required with perpetual inventory even if update_stock is 0.";
53466
+ function isPurchaseInvoiceDoctype(doctype) {
53467
+ return doctype === PURCHASE_INVOICE_DOCTYPE;
53468
+ }
53469
+ function stripHtml(text) {
53470
+ return text.replace(/<[^>]+>/g, " ").replace(/\s+/g, " ").trim();
53471
+ }
53472
+ function purchaseInvoiceAccountHint(text) {
53473
+ const haystack = stripHtml(text);
53474
+ if (isEmptyPartyAccountCurrencyNone(haystack)) {
53475
+ return PARTY_ACCOUNT_HINT;
53476
+ }
53477
+ if (/please set default stock received but not billed in company/i.test(
53478
+ haystack
53479
+ )) {
53480
+ return GRNI_HINT;
53481
+ }
53482
+ return void 0;
53483
+ }
53484
+ function annotateKnownPurchaseInvoiceAccountError(error2) {
53485
+ if (error2 instanceof FrappeAPIError && error2.status === 417) {
53486
+ let hint = purchaseInvoiceAccountHint(error2.message);
53487
+ if (!hint) {
53488
+ const bodyMessage = readErrorBodyMessage(error2.body);
53489
+ if (bodyMessage) {
53490
+ hint = purchaseInvoiceAccountHint(bodyMessage);
53491
+ }
53492
+ }
53493
+ if (hint && !error2.message.includes(hint)) {
53494
+ error2.message = `${error2.message} ${hint}`;
53495
+ }
53496
+ }
53497
+ throw error2;
53498
+ }
53499
+ async function withPurchaseInvoiceAccountHints(fn) {
53500
+ try {
53501
+ return await fn();
53502
+ } catch (error2) {
53503
+ annotateKnownPurchaseInvoiceAccountError(error2);
53504
+ }
53505
+ }
53506
+ function readErrorBodyMessage(body) {
53507
+ if (typeof body === "string") return body;
53508
+ if (body === null || typeof body !== "object" || Array.isArray(body)) {
53509
+ return void 0;
53510
+ }
53511
+ const message2 = body.message;
53512
+ return typeof message2 === "string" ? message2 : void 0;
53513
+ }
53514
+ function isEmptyPartyAccountCurrencyNone(text) {
53515
+ return /party account\s+(?:none\s+)?currency\s*\(\s*none\s*\)\s+and document currency\s*\([^)]*\)\s+should be same/i.test(text);
53516
+ }
53517
+
53719
53518
  // src/tools/operations.ts
53519
+ async function withPiAccountHintsIfNeeded(doctype, fn) {
53520
+ return isPurchaseInvoiceDoctype(doctype) ? await withPurchaseInvoiceAccountHints(fn) : await fn();
53521
+ }
53720
53522
  var operationsTools = [
53721
53523
  // ── File Attachments ───────────────────────────────────────────────────────
53722
53524
  {
@@ -53835,9 +53637,12 @@ var operationsTools = [
53835
53637
  "[erpnext_doc_create] 'data' must be an object with document fields"
53836
53638
  );
53837
53639
  }
53838
- const doc = await ctx.client.create(
53640
+ const doc = await withPiAccountHintsIfNeeded(
53839
53641
  input.doctype,
53840
- input.data
53642
+ () => ctx.client.create(
53643
+ input.doctype,
53644
+ input.data
53645
+ )
53841
53646
  );
53842
53647
  return {
53843
53648
  data: doc,
@@ -53881,10 +53686,13 @@ var operationsTools = [
53881
53686
  "[erpnext_doc_update] 'data' must be an object with fields to update"
53882
53687
  );
53883
53688
  }
53884
- const doc = await ctx.client.update(
53689
+ const doc = await withPiAccountHintsIfNeeded(
53885
53690
  input.doctype,
53886
- input.name,
53887
- input.data
53691
+ () => ctx.client.update(
53692
+ input.doctype,
53693
+ input.name,
53694
+ input.data
53695
+ )
53888
53696
  );
53889
53697
  return {
53890
53698
  data: doc,
@@ -53955,25 +53763,30 @@ var operationsTools = [
53955
53763
  if (!input.name) {
53956
53764
  throw new Error("[erpnext_doc_submit] 'name' is required");
53957
53765
  }
53958
- const doc = await ctx.client.get(
53959
- input.doctype,
53960
- input.name,
53961
- { skipCache: true }
53962
- );
53963
- const docWithDoctype = { ...doc, doctype: input.doctype };
53964
- const patchedDoc = withRoundedTotalFallback(docWithDoctype);
53965
- const result = await ctx.client.callMethod("frappe.client.submit", {
53966
- doc: patchedDoc
53766
+ return await withPiAccountHintsIfNeeded(input.doctype, async () => {
53767
+ const doc = await ctx.client.get(
53768
+ input.doctype,
53769
+ input.name,
53770
+ { skipCache: true }
53771
+ );
53772
+ const docWithDoctype = { ...doc, doctype: input.doctype };
53773
+ const patchedDoc = withRoundedTotalFallback(docWithDoctype);
53774
+ const result = await ctx.client.callMethod("frappe.client.submit", {
53775
+ doc: patchedDoc
53776
+ });
53777
+ ctx.client.invalidate(input.doctype, input.name);
53778
+ const warnings = roundedTotalFallbackWarning(
53779
+ docWithDoctype,
53780
+ patchedDoc
53781
+ );
53782
+ return {
53783
+ data: result,
53784
+ message: `${input.doctype} ${input.name} submitted successfully`,
53785
+ doctype: input.doctype,
53786
+ name: input.name,
53787
+ ...warnings.length > 0 ? { warnings } : {}
53788
+ };
53967
53789
  });
53968
- ctx.client.invalidate(input.doctype, input.name);
53969
- const warnings = roundedTotalFallbackWarning(docWithDoctype, patchedDoc);
53970
- return {
53971
- data: result,
53972
- message: `${input.doctype} ${input.name} submitted successfully`,
53973
- doctype: input.doctype,
53974
- name: input.name,
53975
- ...warnings.length > 0 ? { warnings } : {}
53976
- };
53977
53790
  }
53978
53791
  },
53979
53792
  // ── Generic Cancel ────────────────────────────────────────────────────────
@@ -57452,7 +57265,7 @@ async function main() {
57452
57265
  );
57453
57266
  const server = new McpApp({
57454
57267
  name: "mcp-erpnext",
57455
- version: "3.0.3",
57268
+ version: "3.0.4",
57456
57269
  transport: "stateless",
57457
57270
  cache: {
57458
57271
  ttlMs: 36e5,