UNPKG

xmcp

Version:

The TypeScript MCP framework

3 lines • 27.9 kB
!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}----- ${s} -----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})());