xmcp 1.1.3 → 1.3.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.
- package/dist/cloudflare.d.ts +1 -0
- package/dist/cloudflare.js +2 -2
- package/dist/config/index.d.ts +35 -35
- package/dist/config/schemas/experimental/index.d.ts +4 -4
- package/dist/config.js +1 -1
- package/dist/index.d.ts +6 -2
- package/dist/index.js +13 -13
- package/dist/node.d.ts +55 -0
- package/dist/node.js +1 -0
- package/dist/runtime/adapter-express.js +24 -22
- package/dist/runtime/adapter-fastify.js +24 -22
- package/dist/runtime/adapter-nestjs.js +24 -22
- package/dist/runtime/adapter-nextjs.js +24 -22
- package/dist/runtime/adapter-tanstack-cloudflare.js +240 -0
- package/dist/runtime/adapter-tanstack.js +244 -0
- package/dist/runtime/cloudflare-worker.js +32 -30
- package/dist/runtime/contexts/request-context.d.ts +24 -0
- package/dist/runtime/headers.js +1 -1
- package/dist/runtime/http.js +46 -44
- package/dist/runtime/stdio.js +19 -17
- package/dist/runtime/utils/content.d.ts +7 -0
- package/dist/runtime/utils/mcp-middleware.d.ts +14 -0
- package/dist/runtime/utils/server.d.ts +2 -1
- package/dist/runtime/utils/tools.d.ts +2 -1
- package/dist/runtime/utils/transformers/prompt.d.ts +7 -5
- package/dist/runtime/utils/transformers/tool.d.ts +1 -0
- package/dist/runtime/vercel.js +46 -44
- package/dist/types/declarations.d.ts +3 -0
- package/dist/types/mcp-middleware.d.ts +17 -0
- package/dist/types/prompt.d.ts +1 -0
- package/dist/types/resource.d.ts +3 -0
- package/dist/utils/context.d.ts +3 -1
- package/package.json +9 -2
package/dist/cloudflare.d.ts
CHANGED
|
@@ -1,3 +1,4 @@
|
|
|
1
1
|
export { cloudflareApiKeyAuthMiddleware as apiKeyAuthMiddleware } from "./runtime/platforms/cloudflare/middlewares/api-key";
|
|
2
2
|
export { cloudflareJwtAuthMiddleware as jwtAuthMiddleware, type CloudflareJWTAuthMiddlewareConfig as JWTAuthMiddlewareConfig, } from "./runtime/platforms/cloudflare/middlewares/jwt";
|
|
3
3
|
export type { WebMiddleware } from "./types/middleware";
|
|
4
|
+
export { image, audio, embeddedResource } from "./runtime/utils/content";
|
package/dist/cloudflare.js
CHANGED
|
@@ -1,3 +1,3 @@
|
|
|
1
|
-
!function(e,t){if("object"==typeof exports&&"object"==typeof module)module.exports=t(require("zod/v3"));else if("function"==typeof define&&define.amd)define(["zod/v3"],t);else{var r="object"==typeof exports?t(require("zod/v3")):t(e["zod/v3"]);for(var a in r)("object"==typeof exports?exports:e)[a]=r[a]}}(this,e=>(()=>{"use strict";var t={4953(t){t.exports=e}},r={};function a(e){var i=r[e];if(void 0!==i)return i.exports;var o=r[e]={exports:{}};return t[e](o,o.exports,a),o.exports}a.d=(e,t)=>{for(var r in t)a.o(t,r)&&!a.o(e,r)&&Object.defineProperty(e,r,{enumerable:!0,get:t[r]})},a.o=(e,t)=>Object.prototype.hasOwnProperty.call(e,t),a.r=e=>{"undefined"!=typeof Symbol&&Symbol.toStringTag&&Object.defineProperty(e,Symbol.toStringTag,{value:"Module"}),Object.defineProperty(e,"__esModule",{value:!0})};var i={};return(()=>{let e;a.r(i),a.d(i,{jwtAuthMiddleware:()=>er,apiKeyAuthMiddleware:()=>n});var t=a(4953);let r=t.z.object({apiKey:t.z.string().optional(),headerName:t.z.string().optional(),validateApiKey:t.z.function().args(t.z.string()).returns(t.z.promise(t.z.boolean())).optional()}).strict().refine(e=>void 0!==e.apiKey||void 0!==e.validateApiKey,{message:"Either 'apiKey' or 'validateApiKey' must be provided"}).refine(e=>void 0===e.apiKey||void 0===e.validateApiKey,{message:"'apiKey' and 'validateApiKey' are mutually exclusive - provide only one"}),o="Unauthorized: Missing or invalid API key";function n(e){let t=r.safeParse(e);if(!t.success){let r="apiKey"in e,a="validateApiKey"in e;if(r&&a)throw Error("'apiKey' and 'validateApiKey' are mutually exclusive - provide only one");if(r||a)throw Error(`Invalid configuration: ${t.error.message}`);throw Error("Either 'apiKey' or 'validateApiKey' must be provided")}let a=e.headerName??"x-api-key",i="apiKey"in e?e.apiKey:void 0,n="validateApiKey"in e?e.validateApiKey:void 0;return async t=>{let r=t.headers.get(a);if(!r||"apiKey"in e&&r!==i||n&&!await n(r))return s(o)}}function s(e){return new Response(JSON.stringify({error:e}),{status:401,headers:{"Content-Type":"application/json"}})}let c=new TextEncoder,l=new TextDecoder;function d(e){let t=new Uint8Array(e.length);for(let r=0;r<e.length;r++){let a=e.charCodeAt(r);if(a>127)throw TypeError("non-ASCII string encountered in encode()");t[r]=a}return t}function y(e){if(Uint8Array.fromBase64)return Uint8Array.fromBase64(e);let t=atob(e),r=new Uint8Array(t.length);for(let e=0;e<t.length;e++)r[e]=t.charCodeAt(e);return r}function p(e){if(Uint8Array.fromBase64)return Uint8Array.fromBase64("string"==typeof e?e:l.decode(e),{alphabet:"base64url"});let t=e;t instanceof Uint8Array&&(t=l.decode(t)),t=t.replace(/-/g,"+").replace(/_/g,"/");try{return y(t)}catch{throw TypeError("The input to be decoded is not correctly encoded.")}}function u(e){if("object"!=typeof e||null===e||"[object Object]"!==Object.prototype.toString.call(e))return!1;if(null===Object.getPrototypeOf(e))return!0;let t=e;for(;null!==Object.getPrototypeOf(t);)t=Object.getPrototypeOf(t);return Object.getPrototypeOf(e)===t}class f extends Error{static code="ERR_JOSE_GENERIC";code="ERR_JOSE_GENERIC";constructor(e,t){super(e,t),this.name=this.constructor.name,Error.captureStackTrace?.(this,this.constructor)}}class h extends f{static code="ERR_JWT_CLAIM_VALIDATION_FAILED";code="ERR_JWT_CLAIM_VALIDATION_FAILED";claim;reason;payload;constructor(e,t,r="unspecified",a="unspecified"){super(e,{cause:{claim:r,reason:a,payload:t}}),this.claim=r,this.reason=a,this.payload=t}}class m extends f{static code="ERR_JWT_EXPIRED";code="ERR_JWT_EXPIRED";claim;reason;payload;constructor(e,t,r="unspecified",a="unspecified"){super(e,{cause:{claim:r,reason:a,payload:t}}),this.claim=r,this.reason=a,this.payload=t}}class S extends f{static code="ERR_JOSE_ALG_NOT_ALLOWED";code="ERR_JOSE_ALG_NOT_ALLOWED"}class w extends f{static code="ERR_JOSE_NOT_SUPPORTED";code="ERR_JOSE_NOT_SUPPORTED"}class E extends f{static code="ERR_JWS_INVALID";code="ERR_JWS_INVALID"}class g extends f{static code="ERR_JWT_INVALID";code="ERR_JWT_INVALID"}class A extends f{[Symbol.asyncIterator];static code="ERR_JWKS_MULTIPLE_MATCHING_KEYS";code="ERR_JWKS_MULTIPLE_MATCHING_KEYS";constructor(e="multiple matching keys found in the JSON Web Key Set",t){super(e,t)}}class b extends f{static code="ERR_JWS_SIGNATURE_VERIFICATION_FAILED";code="ERR_JWS_SIGNATURE_VERIFICATION_FAILED";constructor(e="signature verification failed",t){super(e,t)}}let v=(e,t="algorithm.name")=>TypeError(`CryptoKey does not support this operation, its ${t} must be ${e}`);function K(e){return parseInt(e.name.slice(4),10)}function P(e,t,...r){if((r=r.filter(Boolean)).length>2){let t=r.pop();e+=`one of type ${r.join(", ")}, or ${t}.`}else 2===r.length?e+=`one of type ${r[0]} or ${r[1]}.`:e+=`of type ${r[0]}.`;return null==t?e+=` Received ${t}`:"function"==typeof t&&t.name?e+=` Received function ${t.name}`:"object"==typeof t&&null!=t&&t.constructor?.name&&(e+=` Received an instance of ${t.constructor.name}`),e}let k=(e,t,...r)=>P(`Key for the ${e} algorithm must be `,t,...r);async function T(e,t,r){if(t instanceof Uint8Array){if(!e.startsWith("HS"))throw TypeError(((e,...t)=>P("Key must be ",e,...t))(t,"CryptoKey","KeyObject","JSON Web Key"));return crypto.subtle.importKey("raw",t,{hash:`SHA-${e.slice(-3)}`,name:"HMAC"},!1,[r])}return!function(e,t,r){switch(t){case"HS256":case"HS384":case"HS512":{if("HMAC"!==e.algorithm.name)throw v("HMAC");let r=parseInt(t.slice(2),10);if(K(e.algorithm.hash)!==r)throw v(`SHA-${r}`,"algorithm.hash");break}case"RS256":case"RS384":case"RS512":{if("RSASSA-PKCS1-v1_5"!==e.algorithm.name)throw v("RSASSA-PKCS1-v1_5");let r=parseInt(t.slice(2),10);if(K(e.algorithm.hash)!==r)throw v(`SHA-${r}`,"algorithm.hash");break}case"PS256":case"PS384":case"PS512":{if("RSA-PSS"!==e.algorithm.name)throw v("RSA-PSS");let r=parseInt(t.slice(2),10);if(K(e.algorithm.hash)!==r)throw v(`SHA-${r}`,"algorithm.hash");break}case"Ed25519":case"EdDSA":if("Ed25519"!==e.algorithm.name)throw v("Ed25519");break;case"ML-DSA-44":case"ML-DSA-65":case"ML-DSA-87":let a;if(a=e.algorithm,a.name!==t)throw v(t);break;case"ES256":case"ES384":case"ES512":{if("ECDSA"!==e.algorithm.name)throw v("ECDSA");let r=function(e){switch(e){case"ES256":return"P-256";case"ES384":return"P-384";case"ES512":return"P-521";default:throw Error("unreachable")}}(t);if(e.algorithm.namedCurve!==r)throw v(r,"algorithm.namedCurve");break}default:throw TypeError("CryptoKey does not support this operation")}if(r&&!e.usages.includes(r))throw TypeError(`CryptoKey does not support this operation, its usages must include ${r}.`)}(t,e,r),t}async function C(e,t,r,a){let i=await T(e,t,"verify");!function(e,t){if(e.startsWith("RS")||e.startsWith("PS")){let{modulusLength:r}=t.algorithm;if("number"!=typeof r||r<2048)throw TypeError(`${e} requires key modulusLength to be 2048 bits or larger`)}}(e,i);let o=function(e,t){let r=`SHA-${e.slice(-3)}`;switch(e){case"HS256":case"HS384":case"HS512":return{hash:r,name:"HMAC"};case"PS256":case"PS384":case"PS512":return{hash:r,name:"RSA-PSS",saltLength:parseInt(e.slice(-3),10)>>3};case"RS256":case"RS384":case"RS512":return{hash:r,name:"RSASSA-PKCS1-v1_5"};case"ES256":case"ES384":case"ES512":return{hash:r,name:"ECDSA",namedCurve:t.namedCurve};case"Ed25519":case"EdDSA":return{name:"Ed25519"};case"ML-DSA-44":case"ML-DSA-65":case"ML-DSA-87":return{name:e};default:throw new w(`alg ${e} is not supported either by JOSE or your javascript runtime`)}}(e,i.algorithm);try{return await crypto.subtle.verify(o,i,r,a)}catch{return!1}}let R=e=>{if(e?.[Symbol.toStringTag]==="CryptoKey")return!0;try{return e instanceof CryptoKey}catch{return!1}},I=e=>e?.[Symbol.toStringTag]==="KeyObject",O=e=>R(e)||I(e),W=e=>u(e)&&"string"==typeof e.kty,_=e=>e?.[Symbol.toStringTag],H=(e,t,r)=>{if(void 0!==t.use){let e;switch(r){case"sign":case"verify":e="sig";break;case"encrypt":case"decrypt":e="enc"}if(t.use!==e)throw TypeError(`Invalid key for this operation, its "use" must be "${e}" when present`)}if(void 0!==t.alg&&t.alg!==e)throw TypeError(`Invalid key for this operation, its "alg" must be "${e}" when present`);if(Array.isArray(t.key_ops)){let a;switch(!0){case"sign"===r||"verify"===r:case"dir"===e:case e.includes("CBC-HS"):a=r;break;case e.startsWith("PBES2"):a="deriveBits";break;case/^A\d{3}(?:GCM)?(?:KW)?$/.test(e):a=!e.includes("GCM")&&e.endsWith("KW")?"encrypt"===r?"wrapKey":"unwrapKey":r;break;case"encrypt"===r&&e.startsWith("RSA"):a="wrapKey";break;case"decrypt"===r:a=e.startsWith("RSA")?"unwrapKey":"deriveBits"}if(a&&t.key_ops?.includes?.(a)===!1)throw TypeError(`Invalid key for this operation, its "key_ops" must include "${a}" when present`)}return!0};async function D(e){if(!e.alg)throw TypeError('"alg" argument is required when "jwk.alg" is not present');let{algorithm:t,keyUsages:r}=function(e){let t,r;switch(e.kty){case"AKP":switch(e.alg){case"ML-DSA-44":case"ML-DSA-65":case"ML-DSA-87":t={name:e.alg},r=e.priv?["sign"]:["verify"];break;default:throw new w('Invalid or unsupported JWK "alg" (Algorithm) Parameter value')}break;case"RSA":switch(e.alg){case"PS256":case"PS384":case"PS512":t={name:"RSA-PSS",hash:`SHA-${e.alg.slice(-3)}`},r=e.d?["sign"]:["verify"];break;case"RS256":case"RS384":case"RS512":t={name:"RSASSA-PKCS1-v1_5",hash:`SHA-${e.alg.slice(-3)}`},r=e.d?["sign"]:["verify"];break;case"RSA-OAEP":case"RSA-OAEP-256":case"RSA-OAEP-384":case"RSA-OAEP-512":t={name:"RSA-OAEP",hash:`SHA-${parseInt(e.alg.slice(-3),10)||1}`},r=e.d?["decrypt","unwrapKey"]:["encrypt","wrapKey"];break;default:throw new w('Invalid or unsupported JWK "alg" (Algorithm) Parameter value')}break;case"EC":switch(e.alg){case"ES256":t={name:"ECDSA",namedCurve:"P-256"},r=e.d?["sign"]:["verify"];break;case"ES384":t={name:"ECDSA",namedCurve:"P-384"},r=e.d?["sign"]:["verify"];break;case"ES512":t={name:"ECDSA",namedCurve:"P-521"},r=e.d?["sign"]:["verify"];break;case"ECDH-ES":case"ECDH-ES+A128KW":case"ECDH-ES+A192KW":case"ECDH-ES+A256KW":t={name:"ECDH",namedCurve:e.crv},r=e.d?["deriveBits"]:[];break;default:throw new w('Invalid or unsupported JWK "alg" (Algorithm) Parameter value')}break;case"OKP":switch(e.alg){case"Ed25519":case"EdDSA":t={name:"Ed25519"},r=e.d?["sign"]:["verify"];break;case"ECDH-ES":case"ECDH-ES+A128KW":case"ECDH-ES+A192KW":case"ECDH-ES+A256KW":t={name:e.crv},r=e.d?["deriveBits"]:[];break;default:throw new w('Invalid or unsupported JWK "alg" (Algorithm) Parameter value')}break;default:throw new w('Invalid or unsupported JWK "kty" (Key Type) Parameter value')}return{algorithm:t,keyUsages:r}}(e),a={...e};return"AKP"!==a.kty&&delete a.alg,delete a.use,crypto.subtle.importKey("jwk",a,t,e.ext??(!e.d&&!e.priv),e.key_ops??r)}let J=async(t,r,a,i=!1)=>{let o=(e||=new WeakMap).get(t);if(o?.[a])return o[a];let n=await D({...r,alg:a});return i&&Object.freeze(t),o?o[a]=n:e.set(t,{[a]:n}),n};async function x(t,r){if(t instanceof Uint8Array||R(t))return t;if(I(t)){if("secret"===t.type)return t.export();if("toCryptoKey"in t&&"function"==typeof t.toCryptoKey)try{return((t,r)=>{let a,i=(e||=new WeakMap).get(t);if(i?.[r])return i[r];let o="public"===t.type,n=!!o;if("x25519"===t.asymmetricKeyType){switch(r){case"ECDH-ES":case"ECDH-ES+A128KW":case"ECDH-ES+A192KW":case"ECDH-ES+A256KW":break;default:throw TypeError("given KeyObject instance cannot be used for this algorithm")}a=t.toCryptoKey(t.asymmetricKeyType,n,o?[]:["deriveBits"])}if("ed25519"===t.asymmetricKeyType){if("EdDSA"!==r&&"Ed25519"!==r)throw TypeError("given KeyObject instance cannot be used for this algorithm");a=t.toCryptoKey(t.asymmetricKeyType,n,[o?"verify":"sign"])}switch(t.asymmetricKeyType){case"ml-dsa-44":case"ml-dsa-65":case"ml-dsa-87":if(r!==t.asymmetricKeyType.toUpperCase())throw TypeError("given KeyObject instance cannot be used for this algorithm");a=t.toCryptoKey(t.asymmetricKeyType,n,[o?"verify":"sign"])}if("rsa"===t.asymmetricKeyType){let e;switch(r){case"RSA-OAEP":e="SHA-1";break;case"RS256":case"PS256":case"RSA-OAEP-256":e="SHA-256";break;case"RS384":case"PS384":case"RSA-OAEP-384":e="SHA-384";break;case"RS512":case"PS512":case"RSA-OAEP-512":e="SHA-512";break;default:throw TypeError("given KeyObject instance cannot be used for this algorithm")}if(r.startsWith("RSA-OAEP"))return t.toCryptoKey({name:"RSA-OAEP",hash:e},n,o?["encrypt"]:["decrypt"]);a=t.toCryptoKey({name:r.startsWith("PS")?"RSA-PSS":"RSASSA-PKCS1-v1_5",hash:e},n,[o?"verify":"sign"])}if("ec"===t.asymmetricKeyType){let e=new Map([["prime256v1","P-256"],["secp384r1","P-384"],["secp521r1","P-521"]]).get(t.asymmetricKeyDetails?.namedCurve);if(!e)throw TypeError("given KeyObject instance cannot be used for this algorithm");"ES256"===r&&"P-256"===e&&(a=t.toCryptoKey({name:"ECDSA",namedCurve:e},n,[o?"verify":"sign"])),"ES384"===r&&"P-384"===e&&(a=t.toCryptoKey({name:"ECDSA",namedCurve:e},n,[o?"verify":"sign"])),"ES512"===r&&"P-521"===e&&(a=t.toCryptoKey({name:"ECDSA",namedCurve:e},n,[o?"verify":"sign"])),r.startsWith("ECDH-ES")&&(a=t.toCryptoKey({name:"ECDH",namedCurve:e},n,o?[]:["deriveBits"]))}if(!a)throw TypeError("given KeyObject instance cannot be used for this algorithm");return i?i[r]=a:e.set(t,{[r]:a}),a})(t,r)}catch(e){if(e instanceof TypeError)throw e}let a=t.export({format:"jwk"});return J(t,a,r)}if(W(t))return t.k?p(t.k):J(t,t,r,!0);throw Error("unreachable")}async function j(e,t,r){let a,i;if(!u(e))throw new E("Flattened JWS must be an object");if(void 0===e.protected&&void 0===e.header)throw new E('Flattened JWS must have either of the "protected" or "header" members');if(void 0!==e.protected&&"string"!=typeof e.protected)throw new E("JWS Protected Header incorrect type");if(void 0===e.payload)throw new E("JWS Payload missing");if("string"!=typeof e.signature)throw new E("JWS Signature missing or incorrect type");if(void 0!==e.header&&!u(e.header))throw new E("JWS Unprotected Header incorrect type");let o={};if(e.protected)try{let t=p(e.protected);o=JSON.parse(l.decode(t))}catch{throw new E("JWS Protected Header is invalid")}if(!function(...e){let t,r=e.filter(Boolean);if(0===r.length||1===r.length)return!0;for(let e of r){let r=Object.keys(e);if(!t||0===t.size){t=new Set(r);continue}for(let e of r){if(t.has(e))return!1;t.add(e)}}return!0}(o,e.header))throw new E("JWS Protected and JWS Unprotected Header Parameter names must be disjoint");let n={...o,...e.header},s=function(e,t,r,a,i){let o;if(void 0!==i.crit&&a?.crit===void 0)throw new e('"crit" (Critical) Header Parameter MUST be integrity protected');if(!a||void 0===a.crit)return new Set;if(!Array.isArray(a.crit)||0===a.crit.length||a.crit.some(e=>"string"!=typeof e||0===e.length))throw new e('"crit" (Critical) Header Parameter MUST be an array of non-empty strings when present');for(let n of(o=void 0!==r?new Map([...Object.entries(r),...t.entries()]):t,a.crit)){if(!o.has(n))throw new w(`Extension Header Parameter "${n}" is not recognized`);if(void 0===i[n])throw new e(`Extension Header Parameter "${n}" is missing`);if(o.get(n)&&void 0===a[n])throw new e(`Extension Header Parameter "${n}" MUST be integrity protected`)}return new Set(a.crit)}(E,new Map([["b64",!0]]),r?.crit,o,n),y=!0;if(s.has("b64")&&"boolean"!=typeof(y=o.b64))throw new E('The "b64" (base64url-encode payload) Header Parameter must be a boolean');let{alg:f}=n;if("string"!=typeof f||!f)throw new E('JWS "alg" (Algorithm) Header Parameter missing or invalid');let h=r&&function(e,t){if(void 0!==t&&(!Array.isArray(t)||t.some(e=>"string"!=typeof e)))throw TypeError(`"${e}" option must be an array of strings`);if(t)return new Set(t)}("algorithms",r.algorithms);if(h&&!h.has(f))throw new S('"alg" (Algorithm) Header Parameter value not allowed');if(y){if("string"!=typeof e.payload)throw new E("JWS Payload must be a string")}else if("string"!=typeof e.payload&&!(e.payload instanceof Uint8Array))throw new E("JWS Payload must be a string or an Uint8Array instance");let m=!1;"function"==typeof t&&(t=await t(o,e),m=!0);var g=t,A="verify";switch(f.substring(0,2)){case"A1":case"A2":case"di":case"HS":case"PB":((e,t,r)=>{if(!(t instanceof Uint8Array)){if(W(t)){if("oct"===t.kty&&"string"==typeof t.k&&H(e,t,r))return;throw TypeError('JSON Web Key for symmetric algorithms must have JWK "kty" (Key Type) equal to "oct" and the JWK "k" (Key Value) present')}if(!O(t))throw TypeError(k(e,t,"CryptoKey","KeyObject","JSON Web Key","Uint8Array"));if("secret"!==t.type)throw TypeError(`${_(t)} instances for symmetric algorithms must be of type "secret"`)}})(f,g,A);break;default:((e,t,r)=>{if(W(t))switch(r){case"decrypt":case"sign":if("oct"!==t.kty&&("AKP"===t.kty&&"string"==typeof t.priv||"string"==typeof t.d)&&H(e,t,r))return;throw TypeError("JSON Web Key for this operation must be a private JWK");case"encrypt":case"verify":if("oct"!==t.kty&&void 0===t.d&&void 0===t.priv&&H(e,t,r))return;throw TypeError("JSON Web Key for this operation must be a public JWK")}if(!O(t))throw TypeError(k(e,t,"CryptoKey","KeyObject","JSON Web Key"));if("secret"===t.type)throw TypeError(`${_(t)} instances for asymmetric algorithms must not be of type "secret"`);if("public"===t.type)switch(r){case"sign":throw TypeError(`${_(t)} instances for asymmetric algorithm signing must be of type "private"`);case"decrypt":throw TypeError(`${_(t)} instances for asymmetric algorithm decryption must be of type "private"`)}if("private"===t.type)switch(r){case"verify":throw TypeError(`${_(t)} instances for asymmetric algorithm verifying must be of type "public"`);case"encrypt":throw TypeError(`${_(t)} instances for asymmetric algorithm encryption must be of type "public"`)}})(f,g,A)}let v=function(...e){let t=new Uint8Array(e.reduce((e,{length:t})=>e+t,0)),r=0;for(let a of e)t.set(a,r),r+=a.length;return t}(void 0!==e.protected?d(e.protected):new Uint8Array,d("."),"string"==typeof e.payload?y?d(e.payload):c.encode(e.payload):e.payload);try{a=p(e.signature)}catch{throw new E("Failed to base64url decode the signature")}let K=await x(t,f);if(!await C(f,K,a,v))throw new b;if(y)try{i=p(e.payload)}catch{throw new E("Failed to base64url decode the payload")}else i="string"==typeof e.payload?c.encode(e.payload):e.payload;let P={payload:i};return(void 0!==e.protected&&(P.protectedHeader=o),void 0!==e.header&&(P.unprotectedHeader=e.header),m)?{...P,key:K}:P}async function M(e,t,r){if(e instanceof Uint8Array&&(e=l.decode(e)),"string"!=typeof e)throw new E("Compact JWS must be a string or Uint8Array");let{0:a,1:i,2:o,length:n}=e.split(".");if(3!==n)throw new E("Invalid Compact JWS");let s=await j({payload:i,protected:a,signature:o},t,r),c={payload:s.payload,protectedHeader:s.protectedHeader};return"function"==typeof t?{...c,key:s.key}:c}let N=/^(\+|\-)? ?(\d+|\d+\.\d+) ?(seconds?|secs?|s|minutes?|mins?|m|hours?|hrs?|h|days?|d|weeks?|w|years?|yrs?|y)(?: (ago|from now))?$/i;function L(e){let t,r=N.exec(e);if(!r||r[4]&&r[1])throw TypeError("Invalid time period format");let a=parseFloat(r[2]);switch(r[3].toLowerCase()){case"sec":case"secs":case"second":case"seconds":case"s":t=Math.round(a);break;case"minute":case"minutes":case"min":case"mins":case"m":t=Math.round(60*a);break;case"hour":case"hours":case"hr":case"hrs":case"h":t=Math.round(3600*a);break;case"day":case"days":case"d":t=Math.round(86400*a);break;case"week":case"weeks":case"w":t=Math.round(604800*a);break;default:t=Math.round(0x1e187e0*a)}return"-"===r[1]||"ago"===r[4]?-t:t}let $=e=>e.includes("/")?e.toLowerCase():`application/${e.toLowerCase()}`;async function U(e,t,r){let a=await M(e,t,r);if(a.protectedHeader.crit?.includes("b64")&&!1===a.protectedHeader.b64)throw new g("JWTs MUST NOT use unencoded payload");let i={payload:function(e,t,r={}){var a,i;let o,n;try{o=JSON.parse(l.decode(t))}catch{}if(!u(o))throw new g("JWT Claims Set must be a top-level JSON object");let{typ:s}=r;if(s&&("string"!=typeof e.typ||$(e.typ)!==$(s)))throw new h('unexpected "typ" JWT header value',o,"typ","check_failed");let{requiredClaims:c=[],issuer:d,subject:y,audience:p,maxTokenAge:f}=r,S=[...c];for(let e of(void 0!==f&&S.push("iat"),void 0!==p&&S.push("aud"),void 0!==y&&S.push("sub"),void 0!==d&&S.push("iss"),new Set(S.reverse())))if(!(e in o))throw new h(`missing required "${e}" claim`,o,e,"missing");if(d&&!(Array.isArray(d)?d:[d]).includes(o.iss))throw new h('unexpected "iss" claim value',o,"iss","check_failed");if(y&&o.sub!==y)throw new h('unexpected "sub" claim value',o,"sub","check_failed");if(p&&(a=o.aud,i="string"==typeof p?[p]:p,"string"==typeof a?!i.includes(a):!(Array.isArray(a)&&i.some(Set.prototype.has.bind(new Set(a))))))throw new h('unexpected "aud" claim value',o,"aud","check_failed");switch(typeof r.clockTolerance){case"string":n=L(r.clockTolerance);break;case"number":n=r.clockTolerance;break;case"undefined":n=0;break;default:throw TypeError("Invalid clockTolerance option type")}let{currentDate:w}=r,E=Math.floor((w||new Date).getTime()/1e3);if((void 0!==o.iat||f)&&"number"!=typeof o.iat)throw new h('"iat" claim must be a number',o,"iat","invalid");if(void 0!==o.nbf){if("number"!=typeof o.nbf)throw new h('"nbf" claim must be a number',o,"nbf","invalid");if(o.nbf>E+n)throw new h('"nbf" claim timestamp check failed',o,"nbf","check_failed")}if(void 0!==o.exp){if("number"!=typeof o.exp)throw new h('"exp" claim must be a number',o,"exp","invalid");if(o.exp<=E-n)throw new m('"exp" claim timestamp check failed',o,"exp","check_failed")}if(f){let e=E-o.iat;if(e-n>("number"==typeof f?f:L(f)))throw new m('"iat" claim timestamp check failed (too far in the past)',o,"iat","check_failed");if(e<0-n)throw new h('"iat" claim timestamp check failed (it should be in the past)',o,"iat","check_failed")}return o}(a.protectedHeader,a.payload,r),protectedHeader:a.protectedHeader};return"function"==typeof t?{...i,key:a.key}:i}let B=(e,t)=>{if(e.byteLength!==t.length)return!1;for(let r=0;r<e.byteLength;r++)if(e[r]!==t[r])return!1;return!0},z=e=>({data:e,pos:0}),G=e=>{let t=e.data[e.pos++];if(128&t){let r=127&t,a=0;for(let t=0;t<r;t++)a=a<<8|e.data[e.pos++];return a}return t},F=(e,t=1)=>{if(t<=0)return;e.pos++;let r=G(e);e.pos+=r,t>1&&F(e,t-1)},V=(e,t,r)=>{if(e.data[e.pos++]!==t)throw Error(r)},X=(e,t)=>{let r=e.data.subarray(e.pos,e.pos+t);return e.pos+=t,r},q=async(e,t,r,a)=>{let i,o,n="spki"===e,s=()=>n?["verify"]:["sign"];switch(r){case"PS256":case"PS384":case"PS512":i={name:"RSA-PSS",hash:`SHA-${r.slice(-3)}`},o=s();break;case"RS256":case"RS384":case"RS512":i={name:"RSASSA-PKCS1-v1_5",hash:`SHA-${r.slice(-3)}`},o=s();break;case"RSA-OAEP":case"RSA-OAEP-256":case"RSA-OAEP-384":case"RSA-OAEP-512":i={name:"RSA-OAEP",hash:`SHA-${parseInt(r.slice(-3),10)||1}`},o=n?["encrypt","wrapKey"]:["decrypt","unwrapKey"];break;case"ES256":case"ES384":case"ES512":i={name:"ECDSA",namedCurve:({ES256:"P-256",ES384:"P-384",ES512:"P-521"})[r]},o=s();break;case"ECDH-ES":case"ECDH-ES+A128KW":case"ECDH-ES+A192KW":case"ECDH-ES+A256KW":try{let e=a.getNamedCurve(t);i="X25519"===e?{name:"X25519"}:{name:"ECDH",namedCurve:e}}catch(e){throw new w("Invalid or unsupported key format")}o=n?[]:["deriveBits"];break;case"Ed25519":case"EdDSA":i={name:"Ed25519"},o=s();break;case"ML-DSA-44":case"ML-DSA-65":case"ML-DSA-87":i={name:r},o=s();break;default:throw new w('Invalid or unsupported "alg" (Algorithm) value')}return crypto.subtle.importKey(e,t,i,a?.extractable??!!n,o)},Y=(e,t)=>y(e.replace(t,"")),Q=(e,t,r)=>{let a=Y(e,/(?:-----(?:BEGIN|END) PUBLIC KEY-----|\s)/g),i=r;return t?.startsWith?.("ECDH-ES")&&((i||={}).getNamedCurve=e=>{let t=z(e);return V(t,48,"Invalid SPKI structure"),G(t),V(t,48,"Expected algorithm identifier"),G(t),t.pos,(e=>{let t,r=(V(e,6,"Expected algorithm OID"),t=G(e),X(e,t));if(B(r,[43,101,110]))return"X25519";if(!B(r,[42,134,72,206,61,2,1]))throw Error("Unsupported key algorithm");V(e,6,"Expected curve OID");let a=G(e),i=X(e,a);for(let{name:e,oid:t}of[{name:"P-256",oid:[42,134,72,206,61,3,1,7]},{name:"P-384",oid:[43,129,4,0,34]},{name:"P-521",oid:[43,129,4,0,35]}])if(B(i,t))return e;throw Error("Unsupported named curve")})(t)}),q("spki",a,t,i)};async function Z(e,t,r){if("string"!=typeof e||0!==e.indexOf("-----BEGIN PUBLIC KEY-----"))throw TypeError('"spki" must be SPKI formatted string');return Q(e,t,r)}async function ee(e,t,r){if("string"!=typeof e||0!==e.indexOf("-----BEGIN CERTIFICATE-----"))throw TypeError('"x509" must be X.509 formatted string');return((e,t,r)=>{var a,i,o;let n,s;try{let t,r,i;t=z(a=Y(e,/(?:-----(?:BEGIN|END) CERTIFICATE-----|\s)/g)),V(t,48,"Invalid certificate structure"),G(t),V(t,48,"Invalid tbsCertificate structure"),G(t),160===a[t.pos]?F(t,6):F(t,5),r=t.pos,V(t,48,"Invalid SPKI structure"),i=G(t),n=a.subarray(r,r+i+(t.pos-r))}catch(e){throw TypeError("Failed to parse the X.509 certificate",{cause:e})}return Q((i=function(e){if(Uint8Array.prototype.toBase64)return e.toBase64();let t=[];for(let r=0;r<e.length;r+=32768)t.push(String.fromCharCode.apply(null,e.subarray(r,r+32768)));return btoa(t.join(""))}(n),o="PUBLIC KEY",s=(i.match(/.{1,64}/g)||[]).join("\n"),`-----BEGIN ${o}-----
|
|
1
|
+
!function(e,t){if("object"==typeof exports&&"object"==typeof module)module.exports=t(require("zod/v3"));else if("function"==typeof define&&define.amd)define(["zod/v3"],t);else{var r="object"==typeof exports?t(require("zod/v3")):t(e["zod/v3"]);for(var a in r)("object"==typeof exports?exports:e)[a]=r[a]}}(this,e=>(()=>{"use strict";var t={4953(t){t.exports=e}},r={};function a(e){var i=r[e];if(void 0!==i)return i.exports;var o=r[e]={exports:{}};return t[e](o,o.exports,a),o.exports}a.d=(e,t)=>{for(var r in t)a.o(t,r)&&!a.o(e,r)&&Object.defineProperty(e,r,{enumerable:!0,get:t[r]})},a.o=(e,t)=>Object.prototype.hasOwnProperty.call(e,t),a.r=e=>{"undefined"!=typeof Symbol&&Symbol.toStringTag&&Object.defineProperty(e,Symbol.toStringTag,{value:"Module"}),Object.defineProperty(e,"__esModule",{value:!0})};var i={};return(()=>{let e;a.r(i),a.d(i,{embeddedResource:()=>el,image:()=>es,jwtAuthMiddleware:()=>er,apiKeyAuthMiddleware:()=>n,audio:()=>ec});var t=a(4953);let r=t.z.object({apiKey:t.z.string().optional(),headerName:t.z.string().optional(),validateApiKey:t.z.function().args(t.z.string()).returns(t.z.promise(t.z.boolean())).optional()}).strict().refine(e=>void 0!==e.apiKey||void 0!==e.validateApiKey,{message:"Either 'apiKey' or 'validateApiKey' must be provided"}).refine(e=>void 0===e.apiKey||void 0===e.validateApiKey,{message:"'apiKey' and 'validateApiKey' are mutually exclusive - provide only one"}),o="Unauthorized: Missing or invalid API key";function n(e){let t=r.safeParse(e);if(!t.success){let r="apiKey"in e,a="validateApiKey"in e;if(r&&a)throw Error("'apiKey' and 'validateApiKey' are mutually exclusive - provide only one");if(r||a)throw Error(`Invalid configuration: ${t.error.message}`);throw Error("Either 'apiKey' or 'validateApiKey' must be provided")}let a=e.headerName??"x-api-key",i="apiKey"in e?e.apiKey:void 0,n="validateApiKey"in e?e.validateApiKey:void 0;return async t=>{let r=t.headers.get(a);if(!r||"apiKey"in e&&r!==i||n&&!await n(r))return s(o)}}function s(e){return new Response(JSON.stringify({error:e}),{status:401,headers:{"Content-Type":"application/json"}})}let c=new TextEncoder,l=new TextDecoder;function d(e){let t=new Uint8Array(e.length);for(let r=0;r<e.length;r++){let a=e.charCodeAt(r);if(a>127)throw TypeError("non-ASCII string encountered in encode()");t[r]=a}return t}function y(e){if(Uint8Array.fromBase64)return Uint8Array.fromBase64(e);let t=atob(e),r=new Uint8Array(t.length);for(let e=0;e<t.length;e++)r[e]=t.charCodeAt(e);return r}function p(e){if(Uint8Array.fromBase64)return Uint8Array.fromBase64("string"==typeof e?e:l.decode(e),{alphabet:"base64url"});let t=e;t instanceof Uint8Array&&(t=l.decode(t)),t=t.replace(/-/g,"+").replace(/_/g,"/");try{return y(t)}catch{throw TypeError("The input to be decoded is not correctly encoded.")}}function u(e){if("object"!=typeof e||null===e||"[object Object]"!==Object.prototype.toString.call(e))return!1;if(null===Object.getPrototypeOf(e))return!0;let t=e;for(;null!==Object.getPrototypeOf(t);)t=Object.getPrototypeOf(t);return Object.getPrototypeOf(e)===t}class f extends Error{static code="ERR_JOSE_GENERIC";code="ERR_JOSE_GENERIC";constructor(e,t){super(e,t),this.name=this.constructor.name,Error.captureStackTrace?.(this,this.constructor)}}class h extends f{static code="ERR_JWT_CLAIM_VALIDATION_FAILED";code="ERR_JWT_CLAIM_VALIDATION_FAILED";claim;reason;payload;constructor(e,t,r="unspecified",a="unspecified"){super(e,{cause:{claim:r,reason:a,payload:t}}),this.claim=r,this.reason=a,this.payload=t}}class m extends f{static code="ERR_JWT_EXPIRED";code="ERR_JWT_EXPIRED";claim;reason;payload;constructor(e,t,r="unspecified",a="unspecified"){super(e,{cause:{claim:r,reason:a,payload:t}}),this.claim=r,this.reason=a,this.payload=t}}class S extends f{static code="ERR_JOSE_ALG_NOT_ALLOWED";code="ERR_JOSE_ALG_NOT_ALLOWED"}class w extends f{static code="ERR_JOSE_NOT_SUPPORTED";code="ERR_JOSE_NOT_SUPPORTED"}class g extends f{static code="ERR_JWS_INVALID";code="ERR_JWS_INVALID"}class E extends f{static code="ERR_JWT_INVALID";code="ERR_JWT_INVALID"}class A extends f{[Symbol.asyncIterator];static code="ERR_JWKS_MULTIPLE_MATCHING_KEYS";code="ERR_JWKS_MULTIPLE_MATCHING_KEYS";constructor(e="multiple matching keys found in the JSON Web Key Set",t){super(e,t)}}class b extends f{static code="ERR_JWS_SIGNATURE_VERIFICATION_FAILED";code="ERR_JWS_SIGNATURE_VERIFICATION_FAILED";constructor(e="signature verification failed",t){super(e,t)}}let v=(e,t="algorithm.name")=>TypeError(`CryptoKey does not support this operation, its ${t} must be ${e}`);function K(e){return parseInt(e.name.slice(4),10)}function P(e,t,...r){if((r=r.filter(Boolean)).length>2){let t=r.pop();e+=`one of type ${r.join(", ")}, or ${t}.`}else 2===r.length?e+=`one of type ${r[0]} or ${r[1]}.`:e+=`of type ${r[0]}.`;return null==t?e+=` Received ${t}`:"function"==typeof t&&t.name?e+=` Received function ${t.name}`:"object"==typeof t&&null!=t&&t.constructor?.name&&(e+=` Received an instance of ${t.constructor.name}`),e}let k=(e,t,...r)=>P(`Key for the ${e} algorithm must be `,t,...r);async function C(e,t,r){if(t instanceof Uint8Array){if(!e.startsWith("HS"))throw TypeError(((e,...t)=>P("Key must be ",e,...t))(t,"CryptoKey","KeyObject","JSON Web Key"));return crypto.subtle.importKey("raw",t,{hash:`SHA-${e.slice(-3)}`,name:"HMAC"},!1,[r])}return!function(e,t,r){switch(t){case"HS256":case"HS384":case"HS512":{if("HMAC"!==e.algorithm.name)throw v("HMAC");let r=parseInt(t.slice(2),10);if(K(e.algorithm.hash)!==r)throw v(`SHA-${r}`,"algorithm.hash");break}case"RS256":case"RS384":case"RS512":{if("RSASSA-PKCS1-v1_5"!==e.algorithm.name)throw v("RSASSA-PKCS1-v1_5");let r=parseInt(t.slice(2),10);if(K(e.algorithm.hash)!==r)throw v(`SHA-${r}`,"algorithm.hash");break}case"PS256":case"PS384":case"PS512":{if("RSA-PSS"!==e.algorithm.name)throw v("RSA-PSS");let r=parseInt(t.slice(2),10);if(K(e.algorithm.hash)!==r)throw v(`SHA-${r}`,"algorithm.hash");break}case"Ed25519":case"EdDSA":if("Ed25519"!==e.algorithm.name)throw v("Ed25519");break;case"ML-DSA-44":case"ML-DSA-65":case"ML-DSA-87":let a;if(a=e.algorithm,a.name!==t)throw v(t);break;case"ES256":case"ES384":case"ES512":{if("ECDSA"!==e.algorithm.name)throw v("ECDSA");let r=function(e){switch(e){case"ES256":return"P-256";case"ES384":return"P-384";case"ES512":return"P-521";default:throw Error("unreachable")}}(t);if(e.algorithm.namedCurve!==r)throw v(r,"algorithm.namedCurve");break}default:throw TypeError("CryptoKey does not support this operation")}if(r&&!e.usages.includes(r))throw TypeError(`CryptoKey does not support this operation, its usages must include ${r}.`)}(t,e,r),t}async function T(e,t,r,a){let i=await C(e,t,"verify");!function(e,t){if(e.startsWith("RS")||e.startsWith("PS")){let{modulusLength:r}=t.algorithm;if("number"!=typeof r||r<2048)throw TypeError(`${e} requires key modulusLength to be 2048 bits or larger`)}}(e,i);let o=function(e,t){let r=`SHA-${e.slice(-3)}`;switch(e){case"HS256":case"HS384":case"HS512":return{hash:r,name:"HMAC"};case"PS256":case"PS384":case"PS512":return{hash:r,name:"RSA-PSS",saltLength:parseInt(e.slice(-3),10)>>3};case"RS256":case"RS384":case"RS512":return{hash:r,name:"RSASSA-PKCS1-v1_5"};case"ES256":case"ES384":case"ES512":return{hash:r,name:"ECDSA",namedCurve:t.namedCurve};case"Ed25519":case"EdDSA":return{name:"Ed25519"};case"ML-DSA-44":case"ML-DSA-65":case"ML-DSA-87":return{name:e};default:throw new w(`alg ${e} is not supported either by JOSE or your javascript runtime`)}}(e,i.algorithm);try{return await crypto.subtle.verify(o,i,r,a)}catch{return!1}}let R=e=>{if(e?.[Symbol.toStringTag]==="CryptoKey")return!0;try{return e instanceof CryptoKey}catch{return!1}},I=e=>e?.[Symbol.toStringTag]==="KeyObject",O=e=>R(e)||I(e),W=e=>u(e)&&"string"==typeof e.kty,_=e=>e?.[Symbol.toStringTag],H=(e,t,r)=>{if(void 0!==t.use){let e;switch(r){case"sign":case"verify":e="sig";break;case"encrypt":case"decrypt":e="enc"}if(t.use!==e)throw TypeError(`Invalid key for this operation, its "use" must be "${e}" when present`)}if(void 0!==t.alg&&t.alg!==e)throw TypeError(`Invalid key for this operation, its "alg" must be "${e}" when present`);if(Array.isArray(t.key_ops)){let a;switch(!0){case"sign"===r||"verify"===r:case"dir"===e:case e.includes("CBC-HS"):a=r;break;case e.startsWith("PBES2"):a="deriveBits";break;case/^A\d{3}(?:GCM)?(?:KW)?$/.test(e):a=!e.includes("GCM")&&e.endsWith("KW")?"encrypt"===r?"wrapKey":"unwrapKey":r;break;case"encrypt"===r&&e.startsWith("RSA"):a="wrapKey";break;case"decrypt"===r:a=e.startsWith("RSA")?"unwrapKey":"deriveBits"}if(a&&t.key_ops?.includes?.(a)===!1)throw TypeError(`Invalid key for this operation, its "key_ops" must include "${a}" when present`)}return!0};async function D(e){if(!e.alg)throw TypeError('"alg" argument is required when "jwk.alg" is not present');let{algorithm:t,keyUsages:r}=function(e){let t,r;switch(e.kty){case"AKP":switch(e.alg){case"ML-DSA-44":case"ML-DSA-65":case"ML-DSA-87":t={name:e.alg},r=e.priv?["sign"]:["verify"];break;default:throw new w('Invalid or unsupported JWK "alg" (Algorithm) Parameter value')}break;case"RSA":switch(e.alg){case"PS256":case"PS384":case"PS512":t={name:"RSA-PSS",hash:`SHA-${e.alg.slice(-3)}`},r=e.d?["sign"]:["verify"];break;case"RS256":case"RS384":case"RS512":t={name:"RSASSA-PKCS1-v1_5",hash:`SHA-${e.alg.slice(-3)}`},r=e.d?["sign"]:["verify"];break;case"RSA-OAEP":case"RSA-OAEP-256":case"RSA-OAEP-384":case"RSA-OAEP-512":t={name:"RSA-OAEP",hash:`SHA-${parseInt(e.alg.slice(-3),10)||1}`},r=e.d?["decrypt","unwrapKey"]:["encrypt","wrapKey"];break;default:throw new w('Invalid or unsupported JWK "alg" (Algorithm) Parameter value')}break;case"EC":switch(e.alg){case"ES256":t={name:"ECDSA",namedCurve:"P-256"},r=e.d?["sign"]:["verify"];break;case"ES384":t={name:"ECDSA",namedCurve:"P-384"},r=e.d?["sign"]:["verify"];break;case"ES512":t={name:"ECDSA",namedCurve:"P-521"},r=e.d?["sign"]:["verify"];break;case"ECDH-ES":case"ECDH-ES+A128KW":case"ECDH-ES+A192KW":case"ECDH-ES+A256KW":t={name:"ECDH",namedCurve:e.crv},r=e.d?["deriveBits"]:[];break;default:throw new w('Invalid or unsupported JWK "alg" (Algorithm) Parameter value')}break;case"OKP":switch(e.alg){case"Ed25519":case"EdDSA":t={name:"Ed25519"},r=e.d?["sign"]:["verify"];break;case"ECDH-ES":case"ECDH-ES+A128KW":case"ECDH-ES+A192KW":case"ECDH-ES+A256KW":t={name:e.crv},r=e.d?["deriveBits"]:[];break;default:throw new w('Invalid or unsupported JWK "alg" (Algorithm) Parameter value')}break;default:throw new w('Invalid or unsupported JWK "kty" (Key Type) Parameter value')}return{algorithm:t,keyUsages:r}}(e),a={...e};return"AKP"!==a.kty&&delete a.alg,delete a.use,crypto.subtle.importKey("jwk",a,t,e.ext??(!e.d&&!e.priv),e.key_ops??r)}let J=async(t,r,a,i=!1)=>{let o=(e||=new WeakMap).get(t);if(o?.[a])return o[a];let n=await D({...r,alg:a});return i&&Object.freeze(t),o?o[a]=n:e.set(t,{[a]:n}),n};async function x(t,r){if(t instanceof Uint8Array||R(t))return t;if(I(t)){if("secret"===t.type)return t.export();if("toCryptoKey"in t&&"function"==typeof t.toCryptoKey)try{return((t,r)=>{let a,i=(e||=new WeakMap).get(t);if(i?.[r])return i[r];let o="public"===t.type,n=!!o;if("x25519"===t.asymmetricKeyType){switch(r){case"ECDH-ES":case"ECDH-ES+A128KW":case"ECDH-ES+A192KW":case"ECDH-ES+A256KW":break;default:throw TypeError("given KeyObject instance cannot be used for this algorithm")}a=t.toCryptoKey(t.asymmetricKeyType,n,o?[]:["deriveBits"])}if("ed25519"===t.asymmetricKeyType){if("EdDSA"!==r&&"Ed25519"!==r)throw TypeError("given KeyObject instance cannot be used for this algorithm");a=t.toCryptoKey(t.asymmetricKeyType,n,[o?"verify":"sign"])}switch(t.asymmetricKeyType){case"ml-dsa-44":case"ml-dsa-65":case"ml-dsa-87":if(r!==t.asymmetricKeyType.toUpperCase())throw TypeError("given KeyObject instance cannot be used for this algorithm");a=t.toCryptoKey(t.asymmetricKeyType,n,[o?"verify":"sign"])}if("rsa"===t.asymmetricKeyType){let e;switch(r){case"RSA-OAEP":e="SHA-1";break;case"RS256":case"PS256":case"RSA-OAEP-256":e="SHA-256";break;case"RS384":case"PS384":case"RSA-OAEP-384":e="SHA-384";break;case"RS512":case"PS512":case"RSA-OAEP-512":e="SHA-512";break;default:throw TypeError("given KeyObject instance cannot be used for this algorithm")}if(r.startsWith("RSA-OAEP"))return t.toCryptoKey({name:"RSA-OAEP",hash:e},n,o?["encrypt"]:["decrypt"]);a=t.toCryptoKey({name:r.startsWith("PS")?"RSA-PSS":"RSASSA-PKCS1-v1_5",hash:e},n,[o?"verify":"sign"])}if("ec"===t.asymmetricKeyType){let e=new Map([["prime256v1","P-256"],["secp384r1","P-384"],["secp521r1","P-521"]]).get(t.asymmetricKeyDetails?.namedCurve);if(!e)throw TypeError("given KeyObject instance cannot be used for this algorithm");"ES256"===r&&"P-256"===e&&(a=t.toCryptoKey({name:"ECDSA",namedCurve:e},n,[o?"verify":"sign"])),"ES384"===r&&"P-384"===e&&(a=t.toCryptoKey({name:"ECDSA",namedCurve:e},n,[o?"verify":"sign"])),"ES512"===r&&"P-521"===e&&(a=t.toCryptoKey({name:"ECDSA",namedCurve:e},n,[o?"verify":"sign"])),r.startsWith("ECDH-ES")&&(a=t.toCryptoKey({name:"ECDH",namedCurve:e},n,o?[]:["deriveBits"]))}if(!a)throw TypeError("given KeyObject instance cannot be used for this algorithm");return i?i[r]=a:e.set(t,{[r]:a}),a})(t,r)}catch(e){if(e instanceof TypeError)throw e}let a=t.export({format:"jwk"});return J(t,a,r)}if(W(t))return t.k?p(t.k):J(t,t,r,!0);throw Error("unreachable")}async function j(e,t,r){let a,i;if(!u(e))throw new g("Flattened JWS must be an object");if(void 0===e.protected&&void 0===e.header)throw new g('Flattened JWS must have either of the "protected" or "header" members');if(void 0!==e.protected&&"string"!=typeof e.protected)throw new g("JWS Protected Header incorrect type");if(void 0===e.payload)throw new g("JWS Payload missing");if("string"!=typeof e.signature)throw new g("JWS Signature missing or incorrect type");if(void 0!==e.header&&!u(e.header))throw new g("JWS Unprotected Header incorrect type");let o={};if(e.protected)try{let t=p(e.protected);o=JSON.parse(l.decode(t))}catch{throw new g("JWS Protected Header is invalid")}if(!function(...e){let t,r=e.filter(Boolean);if(0===r.length||1===r.length)return!0;for(let e of r){let r=Object.keys(e);if(!t||0===t.size){t=new Set(r);continue}for(let e of r){if(t.has(e))return!1;t.add(e)}}return!0}(o,e.header))throw new g("JWS Protected and JWS Unprotected Header Parameter names must be disjoint");let n={...o,...e.header},s=function(e,t,r,a,i){let o;if(void 0!==i.crit&&a?.crit===void 0)throw new e('"crit" (Critical) Header Parameter MUST be integrity protected');if(!a||void 0===a.crit)return new Set;if(!Array.isArray(a.crit)||0===a.crit.length||a.crit.some(e=>"string"!=typeof e||0===e.length))throw new e('"crit" (Critical) Header Parameter MUST be an array of non-empty strings when present');for(let n of(o=void 0!==r?new Map([...Object.entries(r),...t.entries()]):t,a.crit)){if(!o.has(n))throw new w(`Extension Header Parameter "${n}" is not recognized`);if(void 0===i[n])throw new e(`Extension Header Parameter "${n}" is missing`);if(o.get(n)&&void 0===a[n])throw new e(`Extension Header Parameter "${n}" MUST be integrity protected`)}return new Set(a.crit)}(g,new Map([["b64",!0]]),r?.crit,o,n),y=!0;if(s.has("b64")&&"boolean"!=typeof(y=o.b64))throw new g('The "b64" (base64url-encode payload) Header Parameter must be a boolean');let{alg:f}=n;if("string"!=typeof f||!f)throw new g('JWS "alg" (Algorithm) Header Parameter missing or invalid');let h=r&&function(e,t){if(void 0!==t&&(!Array.isArray(t)||t.some(e=>"string"!=typeof e)))throw TypeError(`"${e}" option must be an array of strings`);if(t)return new Set(t)}("algorithms",r.algorithms);if(h&&!h.has(f))throw new S('"alg" (Algorithm) Header Parameter value not allowed');if(y){if("string"!=typeof e.payload)throw new g("JWS Payload must be a string")}else if("string"!=typeof e.payload&&!(e.payload instanceof Uint8Array))throw new g("JWS Payload must be a string or an Uint8Array instance");let m=!1;"function"==typeof t&&(t=await t(o,e),m=!0);var E=t,A="verify";switch(f.substring(0,2)){case"A1":case"A2":case"di":case"HS":case"PB":((e,t,r)=>{if(!(t instanceof Uint8Array)){if(W(t)){if("oct"===t.kty&&"string"==typeof t.k&&H(e,t,r))return;throw TypeError('JSON Web Key for symmetric algorithms must have JWK "kty" (Key Type) equal to "oct" and the JWK "k" (Key Value) present')}if(!O(t))throw TypeError(k(e,t,"CryptoKey","KeyObject","JSON Web Key","Uint8Array"));if("secret"!==t.type)throw TypeError(`${_(t)} instances for symmetric algorithms must be of type "secret"`)}})(f,E,A);break;default:((e,t,r)=>{if(W(t))switch(r){case"decrypt":case"sign":if("oct"!==t.kty&&("AKP"===t.kty&&"string"==typeof t.priv||"string"==typeof t.d)&&H(e,t,r))return;throw TypeError("JSON Web Key for this operation must be a private JWK");case"encrypt":case"verify":if("oct"!==t.kty&&void 0===t.d&&void 0===t.priv&&H(e,t,r))return;throw TypeError("JSON Web Key for this operation must be a public JWK")}if(!O(t))throw TypeError(k(e,t,"CryptoKey","KeyObject","JSON Web Key"));if("secret"===t.type)throw TypeError(`${_(t)} instances for asymmetric algorithms must not be of type "secret"`);if("public"===t.type)switch(r){case"sign":throw TypeError(`${_(t)} instances for asymmetric algorithm signing must be of type "private"`);case"decrypt":throw TypeError(`${_(t)} instances for asymmetric algorithm decryption must be of type "private"`)}if("private"===t.type)switch(r){case"verify":throw TypeError(`${_(t)} instances for asymmetric algorithm verifying must be of type "public"`);case"encrypt":throw TypeError(`${_(t)} instances for asymmetric algorithm encryption must be of type "public"`)}})(f,E,A)}let v=function(...e){let t=new Uint8Array(e.reduce((e,{length:t})=>e+t,0)),r=0;for(let a of e)t.set(a,r),r+=a.length;return t}(void 0!==e.protected?d(e.protected):new Uint8Array,d("."),"string"==typeof e.payload?y?d(e.payload):c.encode(e.payload):e.payload);try{a=p(e.signature)}catch{throw new g("Failed to base64url decode the signature")}let K=await x(t,f);if(!await T(f,K,a,v))throw new b;if(y)try{i=p(e.payload)}catch{throw new g("Failed to base64url decode the payload")}else i="string"==typeof e.payload?c.encode(e.payload):e.payload;let P={payload:i};return(void 0!==e.protected&&(P.protectedHeader=o),void 0!==e.header&&(P.unprotectedHeader=e.header),m)?{...P,key:K}:P}async function M(e,t,r){if(e instanceof Uint8Array&&(e=l.decode(e)),"string"!=typeof e)throw new g("Compact JWS must be a string or Uint8Array");let{0:a,1:i,2:o,length:n}=e.split(".");if(3!==n)throw new g("Invalid Compact JWS");let s=await j({payload:i,protected:a,signature:o},t,r),c={payload:s.payload,protectedHeader:s.protectedHeader};return"function"==typeof t?{...c,key:s.key}:c}let N=/^(\+|\-)? ?(\d+|\d+\.\d+) ?(seconds?|secs?|s|minutes?|mins?|m|hours?|hrs?|h|days?|d|weeks?|w|years?|yrs?|y)(?: (ago|from now))?$/i;function L(e){let t,r=N.exec(e);if(!r||r[4]&&r[1])throw TypeError("Invalid time period format");let a=parseFloat(r[2]);switch(r[3].toLowerCase()){case"sec":case"secs":case"second":case"seconds":case"s":t=Math.round(a);break;case"minute":case"minutes":case"min":case"mins":case"m":t=Math.round(60*a);break;case"hour":case"hours":case"hr":case"hrs":case"h":t=Math.round(3600*a);break;case"day":case"days":case"d":t=Math.round(86400*a);break;case"week":case"weeks":case"w":t=Math.round(604800*a);break;default:t=Math.round(0x1e187e0*a)}return"-"===r[1]||"ago"===r[4]?-t:t}let $=e=>e.includes("/")?e.toLowerCase():`application/${e.toLowerCase()}`;async function U(e,t,r){let a=await M(e,t,r);if(a.protectedHeader.crit?.includes("b64")&&!1===a.protectedHeader.b64)throw new E("JWTs MUST NOT use unencoded payload");let i={payload:function(e,t,r={}){var a,i;let o,n;try{o=JSON.parse(l.decode(t))}catch{}if(!u(o))throw new E("JWT Claims Set must be a top-level JSON object");let{typ:s}=r;if(s&&("string"!=typeof e.typ||$(e.typ)!==$(s)))throw new h('unexpected "typ" JWT header value',o,"typ","check_failed");let{requiredClaims:c=[],issuer:d,subject:y,audience:p,maxTokenAge:f}=r,S=[...c];for(let e of(void 0!==f&&S.push("iat"),void 0!==p&&S.push("aud"),void 0!==y&&S.push("sub"),void 0!==d&&S.push("iss"),new Set(S.reverse())))if(!(e in o))throw new h(`missing required "${e}" claim`,o,e,"missing");if(d&&!(Array.isArray(d)?d:[d]).includes(o.iss))throw new h('unexpected "iss" claim value',o,"iss","check_failed");if(y&&o.sub!==y)throw new h('unexpected "sub" claim value',o,"sub","check_failed");if(p&&(a=o.aud,i="string"==typeof p?[p]:p,"string"==typeof a?!i.includes(a):!(Array.isArray(a)&&i.some(Set.prototype.has.bind(new Set(a))))))throw new h('unexpected "aud" claim value',o,"aud","check_failed");switch(typeof r.clockTolerance){case"string":n=L(r.clockTolerance);break;case"number":n=r.clockTolerance;break;case"undefined":n=0;break;default:throw TypeError("Invalid clockTolerance option type")}let{currentDate:w}=r,g=Math.floor((w||new Date).getTime()/1e3);if((void 0!==o.iat||f)&&"number"!=typeof o.iat)throw new h('"iat" claim must be a number',o,"iat","invalid");if(void 0!==o.nbf){if("number"!=typeof o.nbf)throw new h('"nbf" claim must be a number',o,"nbf","invalid");if(o.nbf>g+n)throw new h('"nbf" claim timestamp check failed',o,"nbf","check_failed")}if(void 0!==o.exp){if("number"!=typeof o.exp)throw new h('"exp" claim must be a number',o,"exp","invalid");if(o.exp<=g-n)throw new m('"exp" claim timestamp check failed',o,"exp","check_failed")}if(f){let e=g-o.iat;if(e-n>("number"==typeof f?f:L(f)))throw new m('"iat" claim timestamp check failed (too far in the past)',o,"iat","check_failed");if(e<0-n)throw new h('"iat" claim timestamp check failed (it should be in the past)',o,"iat","check_failed")}return o}(a.protectedHeader,a.payload,r),protectedHeader:a.protectedHeader};return"function"==typeof t?{...i,key:a.key}:i}let B=(e,t)=>{if(e.byteLength!==t.length)return!1;for(let r=0;r<e.byteLength;r++)if(e[r]!==t[r])return!1;return!0},z=e=>({data:e,pos:0}),G=e=>{let t=e.data[e.pos++];if(128&t){let r=127&t,a=0;for(let t=0;t<r;t++)a=a<<8|e.data[e.pos++];return a}return t},F=(e,t=1)=>{if(t<=0)return;e.pos++;let r=G(e);e.pos+=r,t>1&&F(e,t-1)},V=(e,t,r)=>{if(e.data[e.pos++]!==t)throw Error(r)},X=(e,t)=>{let r=e.data.subarray(e.pos,e.pos+t);return e.pos+=t,r},q=async(e,t,r,a)=>{let i,o,n="spki"===e,s=()=>n?["verify"]:["sign"];switch(r){case"PS256":case"PS384":case"PS512":i={name:"RSA-PSS",hash:`SHA-${r.slice(-3)}`},o=s();break;case"RS256":case"RS384":case"RS512":i={name:"RSASSA-PKCS1-v1_5",hash:`SHA-${r.slice(-3)}`},o=s();break;case"RSA-OAEP":case"RSA-OAEP-256":case"RSA-OAEP-384":case"RSA-OAEP-512":i={name:"RSA-OAEP",hash:`SHA-${parseInt(r.slice(-3),10)||1}`},o=n?["encrypt","wrapKey"]:["decrypt","unwrapKey"];break;case"ES256":case"ES384":case"ES512":i={name:"ECDSA",namedCurve:({ES256:"P-256",ES384:"P-384",ES512:"P-521"})[r]},o=s();break;case"ECDH-ES":case"ECDH-ES+A128KW":case"ECDH-ES+A192KW":case"ECDH-ES+A256KW":try{let e=a.getNamedCurve(t);i="X25519"===e?{name:"X25519"}:{name:"ECDH",namedCurve:e}}catch(e){throw new w("Invalid or unsupported key format")}o=n?[]:["deriveBits"];break;case"Ed25519":case"EdDSA":i={name:"Ed25519"},o=s();break;case"ML-DSA-44":case"ML-DSA-65":case"ML-DSA-87":i={name:r},o=s();break;default:throw new w('Invalid or unsupported "alg" (Algorithm) value')}return crypto.subtle.importKey(e,t,i,a?.extractable??!!n,o)},Y=(e,t)=>y(e.replace(t,"")),Q=(e,t,r)=>{let a=Y(e,/(?:-----(?:BEGIN|END) PUBLIC KEY-----|\s)/g),i=r;return t?.startsWith?.("ECDH-ES")&&((i||={}).getNamedCurve=e=>{let t=z(e);return V(t,48,"Invalid SPKI structure"),G(t),V(t,48,"Expected algorithm identifier"),G(t),t.pos,(e=>{let t,r=(V(e,6,"Expected algorithm OID"),t=G(e),X(e,t));if(B(r,[43,101,110]))return"X25519";if(!B(r,[42,134,72,206,61,2,1]))throw Error("Unsupported key algorithm");V(e,6,"Expected curve OID");let a=G(e),i=X(e,a);for(let{name:e,oid:t}of[{name:"P-256",oid:[42,134,72,206,61,3,1,7]},{name:"P-384",oid:[43,129,4,0,34]},{name:"P-521",oid:[43,129,4,0,35]}])if(B(i,t))return e;throw Error("Unsupported named curve")})(t)}),q("spki",a,t,i)};async function Z(e,t,r){if("string"!=typeof e||0!==e.indexOf("-----BEGIN PUBLIC KEY-----"))throw TypeError('"spki" must be SPKI formatted string');return Q(e,t,r)}async function ee(e,t,r){if("string"!=typeof e||0!==e.indexOf("-----BEGIN CERTIFICATE-----"))throw TypeError('"x509" must be X.509 formatted string');return((e,t,r)=>{var a,i,o;let n,s;try{let t,r,i;t=z(a=Y(e,/(?:-----(?:BEGIN|END) CERTIFICATE-----|\s)/g)),V(t,48,"Invalid certificate structure"),G(t),V(t,48,"Invalid tbsCertificate structure"),G(t),160===a[t.pos]?F(t,6):F(t,5),r=t.pos,V(t,48,"Invalid SPKI structure"),i=G(t),n=a.subarray(r,r+i+(t.pos-r))}catch(e){throw TypeError("Failed to parse the X.509 certificate",{cause:e})}return Q((i=function(e){if(Uint8Array.prototype.toBase64)return e.toBase64();let t=[];for(let r=0;r<e.length;r+=32768)t.push(String.fromCharCode.apply(null,e.subarray(r,r+32768)));return btoa(t.join(""))}(n),o="PUBLIC KEY",s=(i.match(/.{1,64}/g)||[]).join("\n"),`-----BEGIN ${o}-----
|
|
2
2
|
${s}
|
|
3
|
-
-----END ${o}-----`),t,r)})(e,t,r)}async function et(e,t,r){let a;if(!u(e))throw TypeError("JWK must be an object");switch(t??=e.alg,a??=r?.extractable??e.ext,e.kty){case"oct":if("string"!=typeof e.k||!e.k)throw TypeError('missing "k" (Key Value) Parameter value');return p(e.k);case"RSA":if("oth"in e&&void 0!==e.oth)throw new w('RSA JWK "oth" (Other Primes Info) Parameter value is not supported');return D({...e,alg:t,ext:a});case"AKP":if("string"!=typeof e.alg||!e.alg)throw TypeError('missing "alg" (Algorithm) Parameter value');if(void 0!==t&&t!==e.alg)throw TypeError("JWK alg and alg option value mismatch");return D({...e,ext:a});case"EC":case"OKP":return D({...e,alg:t,ext:a});default:throw new w('Unsupported "kty" (Key Type) Parameter value')}}function er(e){return async t=>{let r=function(e){if(!e)return null;let[t,r]=e.split(" ");return t&&r&&"bearer"===t.toLowerCase()&&r.trim()||null}(t.headers.get("authorization"));if(!r)return ea("Unauthorized: Missing or malformed Authorization header");try{await ei(r,e);return}catch{return ea("Unauthorized: Invalid or expired token")}}}function ea(e){return new Response(JSON.stringify({error:e}),{status:401,headers:{"Content-Type":"application/json"}})}async function ei(e,t){var r;let a,{secret:i,...o}=t,n=function(e){let t;if("string"==typeof e){let r=e.split(".");(3===r.length||5===r.length)&&([t]=r)}else if("object"==typeof e&&e)if("protected"in e)t=e.protected;else throw TypeError("Token does not contain a Protected Header");try{if("string"!=typeof t||!t)throw Error();let e=JSON.parse(l.decode(p(t)));if(!u(e))throw Error();return e}catch{throw TypeError("Invalid Token or Protected Header formatting")}}(e),s=o.algorithms?.[0]??("string"==typeof n.alg?n.alg:void 0);if(!s)throw Error("Missing JWT algorithm");let c=await eo(i,s),d=(a={},(r=o).algorithms&&(a.algorithms=r.algorithms),r.audience&&("string"==typeof r.audience?a.audience=r.audience:Array.isArray(r.audience)&&(a.audience=r.audience)),r.issuer&&(a.issuer=r.issuer),r.subject&&(a.subject=r.subject),void 0!==r.clockTolerance&&(a.clockTolerance=r.clockTolerance),void 0!==r.maxAge&&(a.maxTokenAge=r.maxAge),a),{payload:y}=await U(e,c,d);return y}async function eo(e,t){let r=e.trim();if(r.startsWith("{"))try{let e=JSON.parse(r);return await et(e,t)}catch{return new TextEncoder().encode(e)}return r.includes("BEGIN CERTIFICATE")?await ee(r,t):r.includes("BEGIN PUBLIC KEY")?await Z(r,t):new TextEncoder().encode(e)}})(),i})());
|
|
3
|
+
-----END ${o}-----`),t,r)})(e,t,r)}async function et(e,t,r){let a;if(!u(e))throw TypeError("JWK must be an object");switch(t??=e.alg,a??=r?.extractable??e.ext,e.kty){case"oct":if("string"!=typeof e.k||!e.k)throw TypeError('missing "k" (Key Value) Parameter value');return p(e.k);case"RSA":if("oth"in e&&void 0!==e.oth)throw new w('RSA JWK "oth" (Other Primes Info) Parameter value is not supported');return D({...e,alg:t,ext:a});case"AKP":if("string"!=typeof e.alg||!e.alg)throw TypeError('missing "alg" (Algorithm) Parameter value');if(void 0!==t&&t!==e.alg)throw TypeError("JWK alg and alg option value mismatch");return D({...e,ext:a});case"EC":case"OKP":return D({...e,alg:t,ext:a});default:throw new w('Unsupported "kty" (Key Type) Parameter value')}}function er(e){return async t=>{let r=function(e){if(!e)return null;let[t,r]=e.split(" ");return t&&r&&"bearer"===t.toLowerCase()&&r.trim()||null}(t.headers.get("authorization"));if(!r)return ea("Unauthorized: Missing or malformed Authorization header");try{await ei(r,e);return}catch{return ea("Unauthorized: Invalid or expired token")}}}function ea(e){return new Response(JSON.stringify({error:e}),{status:401,headers:{"Content-Type":"application/json"}})}async function ei(e,t){var r;let a,{secret:i,...o}=t,n=function(e){let t;if("string"==typeof e){let r=e.split(".");(3===r.length||5===r.length)&&([t]=r)}else if("object"==typeof e&&e)if("protected"in e)t=e.protected;else throw TypeError("Token does not contain a Protected Header");try{if("string"!=typeof t||!t)throw Error();let e=JSON.parse(l.decode(p(t)));if(!u(e))throw Error();return e}catch{throw TypeError("Invalid Token or Protected Header formatting")}}(e),s=o.algorithms?.[0]??("string"==typeof n.alg?n.alg:void 0);if(!s)throw Error("Missing JWT algorithm");let c=await eo(i,s),d=(a={},(r=o).algorithms&&(a.algorithms=r.algorithms),r.audience&&("string"==typeof r.audience?a.audience=r.audience:Array.isArray(r.audience)&&(a.audience=r.audience)),r.issuer&&(a.issuer=r.issuer),r.subject&&(a.subject=r.subject),void 0!==r.clockTolerance&&(a.clockTolerance=r.clockTolerance),void 0!==r.maxAge&&(a.maxTokenAge=r.maxAge),a),{payload:y}=await U(e,c,d);return y}async function eo(e,t){let r=e.trim();if(r.startsWith("{"))try{let e=JSON.parse(r);return await et(e,t)}catch{return new TextEncoder().encode(e)}return r.includes("BEGIN CERTIFICATE")?await ee(r,t):r.includes("BEGIN PUBLIC KEY")?await Z(r,t):new TextEncoder().encode(e)}function en(e){let t;if(e instanceof Uint8Array)t=e;else if(e instanceof ArrayBuffer)t=new Uint8Array(e);else throw TypeError("Expected bytes as a Uint8Array or ArrayBuffer");let r="";for(let e=0;e<t.length;e+=32768)r+=String.fromCharCode(...t.subarray(e,e+32768));return btoa(r)}function es(e,t){return{type:"image",data:en(e),mimeType:t}}function ec(e,t){return{type:"audio",data:en(e),mimeType:t}}function el(e,t,r){return{type:"resource",resource:{uri:e,...void 0===r?{}:{mimeType:r},..."string"==typeof t?{text:t}:{blob:en(t)}}}}})(),i})());
|
package/dist/config/index.d.ts
CHANGED
|
@@ -120,11 +120,11 @@ export declare const configSchema: z.ZodObject<{
|
|
|
120
120
|
} | undefined;
|
|
121
121
|
}>]>>;
|
|
122
122
|
experimental: z.ZodOptional<z.ZodObject<{
|
|
123
|
-
adapter: z.ZodOptional<z.ZodEnum<["express", "nextjs", "nestjs", "fastify"]>>;
|
|
123
|
+
adapter: z.ZodOptional<z.ZodEnum<["express", "nextjs", "nestjs", "fastify", "tanstack"]>>;
|
|
124
124
|
}, "strip", z.ZodTypeAny, {
|
|
125
|
-
adapter?: "express" | "nextjs" | "nestjs" | "fastify" | undefined;
|
|
125
|
+
adapter?: "express" | "nextjs" | "nestjs" | "fastify" | "tanstack" | undefined;
|
|
126
126
|
}, {
|
|
127
|
-
adapter?: "express" | "nextjs" | "nestjs" | "fastify" | undefined;
|
|
127
|
+
adapter?: "express" | "nextjs" | "nestjs" | "fastify" | "tanstack" | undefined;
|
|
128
128
|
}>>;
|
|
129
129
|
paths: z.ZodOptional<z.ZodEffects<z.ZodObject<{
|
|
130
130
|
tools: z.ZodOptional<z.ZodDefault<z.ZodUnion<[z.ZodBoolean, z.ZodString]>>>;
|
|
@@ -226,6 +226,21 @@ export declare const configSchema: z.ZodObject<{
|
|
|
226
226
|
skipTypeCheck?: boolean | undefined;
|
|
227
227
|
}>>;
|
|
228
228
|
}, "strip", z.ZodTypeAny, {
|
|
229
|
+
http?: boolean | {
|
|
230
|
+
port: number;
|
|
231
|
+
host: string;
|
|
232
|
+
bodySizeLimit: number;
|
|
233
|
+
debug: boolean;
|
|
234
|
+
endpoint: string;
|
|
235
|
+
cors: {
|
|
236
|
+
origin: string | boolean | string[];
|
|
237
|
+
methods: string | string[];
|
|
238
|
+
allowedHeaders: string | string[];
|
|
239
|
+
exposedHeaders: string | string[];
|
|
240
|
+
credentials: boolean;
|
|
241
|
+
maxAge: number;
|
|
242
|
+
};
|
|
243
|
+
} | undefined;
|
|
229
244
|
template?: {
|
|
230
245
|
name: string;
|
|
231
246
|
description: string;
|
|
@@ -242,23 +257,8 @@ export declare const configSchema: z.ZodObject<{
|
|
|
242
257
|
debug: boolean;
|
|
243
258
|
silent: boolean;
|
|
244
259
|
} | undefined;
|
|
245
|
-
http?: boolean | {
|
|
246
|
-
port: number;
|
|
247
|
-
host: string;
|
|
248
|
-
bodySizeLimit: number;
|
|
249
|
-
debug: boolean;
|
|
250
|
-
endpoint: string;
|
|
251
|
-
cors: {
|
|
252
|
-
origin: string | boolean | string[];
|
|
253
|
-
methods: string | string[];
|
|
254
|
-
allowedHeaders: string | string[];
|
|
255
|
-
exposedHeaders: string | string[];
|
|
256
|
-
credentials: boolean;
|
|
257
|
-
maxAge: number;
|
|
258
|
-
};
|
|
259
|
-
} | undefined;
|
|
260
260
|
experimental?: {
|
|
261
|
-
adapter?: "express" | "nextjs" | "nestjs" | "fastify" | undefined;
|
|
261
|
+
adapter?: "express" | "nextjs" | "nestjs" | "fastify" | "tanstack" | undefined;
|
|
262
262
|
} | undefined;
|
|
263
263
|
paths?: {
|
|
264
264
|
tools: string | boolean;
|
|
@@ -270,6 +270,21 @@ export declare const configSchema: z.ZodObject<{
|
|
|
270
270
|
skipTypeCheck: boolean;
|
|
271
271
|
} | undefined;
|
|
272
272
|
}, {
|
|
273
|
+
http?: boolean | {
|
|
274
|
+
port?: number | undefined;
|
|
275
|
+
host?: string | undefined;
|
|
276
|
+
bodySizeLimit?: number | undefined;
|
|
277
|
+
debug?: boolean | undefined;
|
|
278
|
+
endpoint?: string | undefined;
|
|
279
|
+
cors?: {
|
|
280
|
+
origin?: string | boolean | string[] | undefined;
|
|
281
|
+
methods?: string | string[] | undefined;
|
|
282
|
+
allowedHeaders?: string | string[] | undefined;
|
|
283
|
+
exposedHeaders?: string | string[] | undefined;
|
|
284
|
+
credentials?: boolean | undefined;
|
|
285
|
+
maxAge?: number | undefined;
|
|
286
|
+
} | undefined;
|
|
287
|
+
} | undefined;
|
|
273
288
|
template?: {
|
|
274
289
|
name?: string | undefined;
|
|
275
290
|
description?: string | undefined;
|
|
@@ -286,23 +301,8 @@ export declare const configSchema: z.ZodObject<{
|
|
|
286
301
|
debug?: boolean | undefined;
|
|
287
302
|
silent?: boolean | undefined;
|
|
288
303
|
} | undefined;
|
|
289
|
-
http?: boolean | {
|
|
290
|
-
port?: number | undefined;
|
|
291
|
-
host?: string | undefined;
|
|
292
|
-
bodySizeLimit?: number | undefined;
|
|
293
|
-
debug?: boolean | undefined;
|
|
294
|
-
endpoint?: string | undefined;
|
|
295
|
-
cors?: {
|
|
296
|
-
origin?: string | boolean | string[] | undefined;
|
|
297
|
-
methods?: string | string[] | undefined;
|
|
298
|
-
allowedHeaders?: string | string[] | undefined;
|
|
299
|
-
exposedHeaders?: string | string[] | undefined;
|
|
300
|
-
credentials?: boolean | undefined;
|
|
301
|
-
maxAge?: number | undefined;
|
|
302
|
-
} | undefined;
|
|
303
|
-
} | undefined;
|
|
304
304
|
experimental?: {
|
|
305
|
-
adapter?: "express" | "nextjs" | "nestjs" | "fastify" | undefined;
|
|
305
|
+
adapter?: "express" | "nextjs" | "nestjs" | "fastify" | "tanstack" | undefined;
|
|
306
306
|
} | undefined;
|
|
307
307
|
paths?: {
|
|
308
308
|
tools?: string | boolean | undefined;
|
|
@@ -1,11 +1,11 @@
|
|
|
1
1
|
import { z } from "zod/v3";
|
|
2
|
-
export declare const adapterConfigSchema: z.ZodEnum<["express", "nextjs", "nestjs", "fastify"]>;
|
|
2
|
+
export declare const adapterConfigSchema: z.ZodEnum<["express", "nextjs", "nestjs", "fastify", "tanstack"]>;
|
|
3
3
|
export type AdapterConfig = z.infer<typeof adapterConfigSchema>;
|
|
4
4
|
export declare const experimentalConfigSchema: z.ZodObject<{
|
|
5
|
-
adapter: z.ZodOptional<z.ZodEnum<["express", "nextjs", "nestjs", "fastify"]>>;
|
|
5
|
+
adapter: z.ZodOptional<z.ZodEnum<["express", "nextjs", "nestjs", "fastify", "tanstack"]>>;
|
|
6
6
|
}, "strip", z.ZodTypeAny, {
|
|
7
|
-
adapter?: "express" | "nextjs" | "nestjs" | "fastify" | undefined;
|
|
7
|
+
adapter?: "express" | "nextjs" | "nestjs" | "fastify" | "tanstack" | undefined;
|
|
8
8
|
}, {
|
|
9
|
-
adapter?: "express" | "nextjs" | "nestjs" | "fastify" | undefined;
|
|
9
|
+
adapter?: "express" | "nextjs" | "nestjs" | "fastify" | "tanstack" | undefined;
|
|
10
10
|
}>;
|
|
11
11
|
export type ExperimentalConfig = z.infer<typeof experimentalConfigSchema>;
|
package/dist/config.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
!function(e,t){if("object"==typeof exports&&"object"==typeof module)module.exports=t(require("zod/v3"));else if("function"==typeof define&&define.amd)define(["zod/v3"],t);else{var o="object"==typeof exports?t(require("zod/v3")):t(e["zod/v3"]);for(var r in o)("object"==typeof exports?exports:e)[r]=o[r]}}(this,e=>(()=>{"use strict";var t={4953(t){t.exports=e}},o={};function r(e){var n=o[e];if(void 0!==n)return n.exports;var s=o[e]={exports:{}};return t[e](s,s.exports,r),s.exports}r.n=e=>{var t=e&&e.__esModule?()=>e.default:()=>e;return r.d(t,{a:t}),t},r.d=(e,t)=>{for(var o in t)r.o(t,o)&&!r.o(e,o)&&Object.defineProperty(e,o,{enumerable:!0,get:t[o]})},r.o=(e,t)=>Object.prototype.hasOwnProperty.call(e,t),r.r=e=>{"undefined"!=typeof Symbol&&Symbol.toStringTag&&Object.defineProperty(e,Symbol.toStringTag,{value:"Module"}),Object.defineProperty(e,"__esModule",{value:!0})};var n={};return(()=>{r.r(n),r.d(n,{getResolvedHttpConfig:()=>A,configSchema:()=>
|
|
1
|
+
!function(e,t){if("object"==typeof exports&&"object"==typeof module)module.exports=t(require("zod/v3"));else if("function"==typeof define&&define.amd)define(["zod/v3"],t);else{var o="object"==typeof exports?t(require("zod/v3")):t(e["zod/v3"]);for(var r in o)("object"==typeof exports?exports:e)[r]=o[r]}}(this,e=>(()=>{"use strict";var t={4953(t){t.exports=e}},o={};function r(e){var n=o[e];if(void 0!==n)return n.exports;var s=o[e]={exports:{}};return t[e](s,s.exports,r),s.exports}r.n=e=>{var t=e&&e.__esModule?()=>e.default:()=>e;return r.d(t,{a:t}),t},r.d=(e,t)=>{for(var o in t)r.o(t,o)&&!r.o(e,o)&&Object.defineProperty(e,o,{enumerable:!0,get:t[o]})},r.o=(e,t)=>Object.prototype.hasOwnProperty.call(e,t),r.r=e=>{"undefined"!=typeof Symbol&&Symbol.toStringTag&&Object.defineProperty(e,Symbol.toStringTag,{value:"Module"}),Object.defineProperty(e,"__esModule",{value:!0})};var n={};return(()=>{r.r(n),r.d(n,{getResolvedHttpConfig:()=>A,configSchema:()=>M,getResolvedStdioConfig:()=>E,getResolvedTypescriptConfig:()=>k,getResolvedCorsConfig:()=>S,getResolvedPathsConfig:()=>T,getResolvedExperimentalConfig:()=>R,getResolvedTemplateConfig:()=>P});var e=r(4953),t=r.n(e);let o=["x-mcp-client-name","x-mcp-client-version","x-mcp-client-title","x-mcp-client-website-url","x-mcp-client-description"],s={origin:"*",methods:["GET","POST"],allowedHeaders:["Content-Type","Authorization","mcp-session-id","mcp-protocol-version","mcp-method","mcp-name",...o],exposedHeaders:["Content-Type","Authorization","mcp-session-id"],credentials:!1,maxAge:86400},l=e.z.object({origin:e.z.union([e.z.string(),e.z.array(e.z.string()),e.z.boolean()]).default(s.origin),methods:e.z.union([e.z.string(),e.z.array(e.z.string())]).default([...s.methods]),allowedHeaders:e.z.union([e.z.string(),e.z.array(e.z.string())]).default([...s.allowedHeaders]),exposedHeaders:e.z.union([e.z.string(),e.z.array(e.z.string())]).default([...s.exposedHeaders]),credentials:e.z.boolean().default(s.credentials),maxAge:e.z.number().default(s.maxAge)}),i=l.parse({}),a=l.partial().transform(e=>{let t=Object.fromEntries(Object.entries(e).filter(([e,t])=>void 0!==t)),r={...i,...t};if(Array.isArray(r.allowedHeaders)){let e=new Set(r.allowedHeaders);for(let t of(e.add("mcp-session-id"),e.add("mcp-protocol-version"),e.add("mcp-method"),e.add("mcp-name"),o))e.add(t);r.allowedHeaders=Array.from(e)}if(Array.isArray(r.exposedHeaders)){let e=new Set(r.exposedHeaders);e.add("mcp-session-id"),r.exposedHeaders=Array.from(e)}return r}),p=e.z.object({port:e.z.number().default(3001),host:e.z.string().default("127.0.0.1"),bodySizeLimit:e.z.number().default(0xa00000),debug:e.z.boolean().default(!1),endpoint:e.z.string().default("/mcp"),cors:a}),u=p.partial().transform(e=>{let t=p.parse({cors:{}}),o=Object.fromEntries(Object.entries(e).filter(([e,t])=>void 0!==t));return{...t,...o}}),d=e.z.union([e.z.boolean(),u]);d.transform(e=>"boolean"==typeof e?e?{}:null:e).pipe(e.z.union([e.z.literal(null),u]));let f=e.z.object({debug:e.z.boolean().default(!1),silent:e.z.boolean().default(!1)}),c=f.partial().transform(e=>{let t=f.parse({}),o=Object.fromEntries(Object.entries(e).filter(([e,t])=>void 0!==t));return{...t,...o}}),m=e.z.union([e.z.boolean(),c]).optional(),z=e.z.enum(["express","nextjs","nestjs","fastify","tanstack"]),b=e.z.object({adapter:z.optional()}),g=e.z.object({tools:e.z.union([e.z.boolean(),e.z.string()]).default(!0),prompts:e.z.union([e.z.boolean(),e.z.string()]).default(!0),resources:e.z.union([e.z.boolean(),e.z.string()]).default(!0)}),y=g.partial().transform(e=>{let t=g.parse({}),o=Object.fromEntries(Object.entries(e).filter(([e,t])=>void 0!==t));return{...t,...o}}),j="src/tools",v="src/prompts",x="src/resources",h=t().function().args(t().any()).returns(t().any()).optional(),O=e.z.object({name:e.z.string().default("xmcp server"),description:e.z.string().default("This MCP server was bootstrapped with xmcp."),icons:e.z.array(e.z.object({src:e.z.string(),mimeType:e.z.string().optional(),sizes:e.z.array(e.z.string()).optional(),theme:e.z.enum(["light","dark"]).optional()})).optional(),instructions:e.z.string().optional(),homePage:e.z.string().optional()}),H=O.partial().transform(e=>{let t=O.parse({}),o=Object.fromEntries(Object.entries(e).filter(([e,t])=>void 0!==t));return{...t,...o}}),w=e.z.object({skipTypeCheck:e.z.boolean().default(!1)}),C=w.partial().transform(e=>{let t=w.parse({}),o=Object.fromEntries(Object.entries(e).filter(([e,t])=>void 0!==t));return{...t,...o}});function A(e){if("boolean"==typeof e){if(!e)return null;let t=d.parse({});return"object"!=typeof t||null===t?null:t}if("object"==typeof e&&null!==e){let t=d.parse(e);return"object"!=typeof t||null===t?null:t}return null}function S(e){return a.parse(e?.cors??{})}function T(e){let t=e?.paths;if(!t)return{tools:j,prompts:v,resources:x};let o={tools:j,prompts:v,resources:x};return"boolean"==typeof t.tools?o.tools=t.tools?j:null:"string"==typeof t.tools&&(o.tools=t.tools),"boolean"==typeof t.prompts?o.prompts=t.prompts?v:null:"string"==typeof t.prompts&&(o.prompts=t.prompts),"boolean"==typeof t.resources?o.resources=t.resources?x:null:"string"==typeof t.resources&&(o.resources=t.resources),o}function E(e){let t=e?.stdio;if("boolean"==typeof t){if(!t)return null;let e=m.parse({});return"object"!=typeof e||null===e?null:e}if(t){let e=m.parse(t);return"object"!=typeof e||null===e?null:e}let o=m.parse({});return"object"!=typeof o||null===o?null:o}function P(e){let t=e?.template;return H.parse(t??{})}function R(e){let t=e?.experimental;return{adapter:t?.adapter}}function k(e){let t=e?.typescript;return C.parse(t??{})}let M=e.z.object({stdio:m.optional(),http:d.optional(),experimental:b.optional(),paths:y.optional(),bundler:h.optional(),template:H.optional(),typescript:C.optional()})})(),n})());
|
package/dist/index.d.ts
CHANGED
|
@@ -1,14 +1,18 @@
|
|
|
1
1
|
export type { Middleware, WebMiddleware, WebMiddlewareContext, } from "./types/middleware";
|
|
2
|
+
export type { McpMiddleware, McpMiddlewareContext, McpMiddlewareMethod, McpMiddlewareNext, McpMiddlewareResult, } from "./types/mcp-middleware";
|
|
2
3
|
export type { ToolMetadata, ToolSchema, ToolOutputSchema, ToolExtraArguments, InferSchema, ElicitResult, SampleRequest, SampleResult, } from "./types/tool";
|
|
3
4
|
export type { McpClientInfo } from "./types/client-info";
|
|
4
|
-
export type { PromptMetadata } from "./types/prompt";
|
|
5
|
-
export type { ResourceMetadata } from "./types/resource";
|
|
5
|
+
export type { PromptMetadata, PromptMessage, GetPromptResult, } from "./types/prompt";
|
|
6
|
+
export type { ResourceMetadata, ResourceCompletions } from "./types/resource";
|
|
6
7
|
export type { UIMetadata } from "./types/ui-meta";
|
|
7
8
|
export type { XmcpConfigInputSchema as XmcpConfig } from "./config";
|
|
8
9
|
import "./types/declarations";
|
|
9
10
|
export { apiKeyAuthMiddleware } from "./auth/api-key";
|
|
10
11
|
export { jwtAuthMiddleware } from "./auth/jwt";
|
|
11
12
|
export { createContext } from "./utils/context";
|
|
13
|
+
export { image, audio, embeddedResource } from "./runtime/utils/content";
|
|
14
|
+
export { getRequestContext } from "./runtime/contexts/request-context";
|
|
15
|
+
export type { RequestContext } from "./runtime/contexts/request-context";
|
|
12
16
|
export { completable, UrlElicitationRequiredError, inputRequired, inputResponse, acceptedContent, isInputRequiredResult, createRequestStateCodec, } from "@modelcontextprotocol/server";
|
|
13
17
|
export type { InputRequiredResult, InputRequests, InputResponses, RequestStateCodec, } from "@modelcontextprotocol/server";
|
|
14
18
|
export { createHTTPClient, createSTDIOClient, listSTDIOClientTools, callSTDIOClientTool, disconnectSTDIOClient, } from "./client";
|