UNPKG

eve

Version:

Filesystem-first framework for durable backend AI agents that run anywhere.

2 lines 65.7 kB
import{r as e}from"../_chunks/workflow/chunk-BHKSVoKr.js";const t=new TextEncoder,n=new TextDecoder,r=2**32;function i(...e){let t=e.reduce((e,{length:t})=>e+t,0),n=new Uint8Array(t),r=0;for(let t of e)n.set(t,r),r+=t.length;return n}function a(e,t,n){if(t<0||t>=r)throw RangeError(`value must be >= 0 and <= ${r-1}. Received ${t}`);e.set([t>>>24,t>>>16,t>>>8,t&255],n)}function o(e){let t=Math.floor(e/r),n=e%r,i=new Uint8Array(8);return a(i,t,0),a(i,n,4),i}function s(e){let t=new Uint8Array(4);return a(t,e),t}function c(e){let t=new Uint8Array(e.length);for(let n=0;n<e.length;n++){let r=e.charCodeAt(n);if(r>127)throw TypeError(`non-ASCII string encountered in encode()`);t[n]=r}return t}function l(e){if(Uint8Array.prototype.toBase64)return e.toBase64();let t=32768,n=[];for(let r=0;r<e.length;r+=t)n.push(String.fromCharCode.apply(null,e.subarray(r,r+t)));return btoa(n.join(``))}function u(e){if(Uint8Array.fromBase64)return Uint8Array.fromBase64(e);let t=atob(e),n=new Uint8Array(t.length);for(let e=0;e<t.length;e++)n[e]=t.charCodeAt(e);return n}var d=e({decode:()=>f,encode:()=>p});function f(e){if(Uint8Array.fromBase64)return Uint8Array.fromBase64(typeof e==`string`?e:n.decode(e),{alphabet:`base64url`});let t=e;t instanceof Uint8Array&&(t=n.decode(t)),t=t.replace(/-/g,`+`).replace(/_/g,`/`);try{return u(t)}catch{throw TypeError(`The input to be decoded is not correctly encoded.`)}}function p(e){let n=e;return typeof n==`string`&&(n=t.encode(n)),Uint8Array.prototype.toBase64?n.toBase64({alphabet:`base64url`,omitPadding:!0}):l(n).replace(/=/g,``).replace(/\+/g,`-`).replace(/\//g,`_`)}const m=(e,t=`algorithm.name`)=>TypeError(`CryptoKey does not support this operation, its ${t} must be ${e}`),h=(e,t)=>e.name===t;function g(e){return parseInt(e.name.slice(4),10)}function _(e,t){if(g(e.hash)!==t)throw m(`SHA-${t}`,`algorithm.hash`)}function v(e){switch(e){case`ES256`:return`P-256`;case`ES384`:return`P-384`;case`ES512`:return`P-521`;default:throw Error(`unreachable`)}}function y(e,t){if(t&&!e.usages.includes(t))throw TypeError(`CryptoKey does not support this operation, its usages must include ${t}.`)}function ee(e,t,n){switch(t){case`HS256`:case`HS384`:case`HS512`:if(!h(e.algorithm,`HMAC`))throw m(`HMAC`);_(e.algorithm,parseInt(t.slice(2),10));break;case`RS256`:case`RS384`:case`RS512`:if(!h(e.algorithm,`RSASSA-PKCS1-v1_5`))throw m(`RSASSA-PKCS1-v1_5`);_(e.algorithm,parseInt(t.slice(2),10));break;case`PS256`:case`PS384`:case`PS512`:if(!h(e.algorithm,`RSA-PSS`))throw m(`RSA-PSS`);_(e.algorithm,parseInt(t.slice(2),10));break;case`Ed25519`:case`EdDSA`:if(!h(e.algorithm,`Ed25519`))throw m(`Ed25519`);break;case`ML-DSA-44`:case`ML-DSA-65`:case`ML-DSA-87`:if(!h(e.algorithm,t))throw m(t);break;case`ES256`:case`ES384`:case`ES512`:{if(!h(e.algorithm,`ECDSA`))throw m(`ECDSA`);let n=v(t);if(e.algorithm.namedCurve!==n)throw m(n,`algorithm.namedCurve`);break}default:throw TypeError(`CryptoKey does not support this operation`)}y(e,n)}function b(e,t,n){switch(t){case`A128GCM`:case`A192GCM`:case`A256GCM`:{if(!h(e.algorithm,`AES-GCM`))throw m(`AES-GCM`);let n=parseInt(t.slice(1,4),10);if(e.algorithm.length!==n)throw m(n,`algorithm.length`);break}case`A128KW`:case`A192KW`:case`A256KW`:{if(!h(e.algorithm,`AES-KW`))throw m(`AES-KW`);let n=parseInt(t.slice(1,4),10);if(e.algorithm.length!==n)throw m(n,`algorithm.length`);break}case`ECDH`:switch(e.algorithm.name){case`ECDH`:case`X25519`:break;default:throw m(`ECDH or X25519`)}break;case`PBES2-HS256+A128KW`:case`PBES2-HS384+A192KW`:case`PBES2-HS512+A256KW`:if(!h(e.algorithm,`PBKDF2`))throw m(`PBKDF2`);break;case`RSA-OAEP`:case`RSA-OAEP-256`:case`RSA-OAEP-384`:case`RSA-OAEP-512`:if(!h(e.algorithm,`RSA-OAEP`))throw m(`RSA-OAEP`);_(e.algorithm,parseInt(t.slice(9),10)||1);break;default:throw TypeError(`CryptoKey does not support this operation`)}y(e,n)}function x(e,t,...n){if(n=n.filter(Boolean),n.length>2){let t=n.pop();e+=`one of type ${n.join(`, `)}, or ${t}.`}else n.length===2?e+=`one of type ${n[0]} or ${n[1]}.`:e+=`of type ${n[0]}.`;return t==null?e+=` Received ${t}`:typeof t==`function`&&t.name?e+=` Received function ${t.name}`:typeof t==`object`&&t&&t.constructor?.name&&(e+=` Received an instance of ${t.constructor.name}`),e}const S=(e,...t)=>x(`Key must be `,e,...t),te=(e,t,...n)=>x(`Key for the ${e} algorithm must be `,t,...n);var ne=e({JOSEAlgNotAllowed:()=>ie,JOSEError:()=>C,JOSENotSupported:()=>T,JWEDecryptionFailed:()=>E,JWEInvalid:()=>D,JWKInvalid:()=>ae,JWKSInvalid:()=>oe,JWKSMultipleMatchingKeys:()=>ce,JWKSNoMatchingKey:()=>se,JWKSTimeout:()=>le,JWSInvalid:()=>O,JWSSignatureVerificationFailed:()=>ue,JWTClaimValidationFailed:()=>w,JWTExpired:()=>re,JWTInvalid:()=>k}),C=class 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)}},w=class extends C{static code=`ERR_JWT_CLAIM_VALIDATION_FAILED`;code=`ERR_JWT_CLAIM_VALIDATION_FAILED`;claim;reason;payload;constructor(e,t,n=`unspecified`,r=`unspecified`){super(e,{cause:{claim:n,reason:r,payload:t}}),this.claim=n,this.reason=r,this.payload=t}},re=class extends C{static code=`ERR_JWT_EXPIRED`;code=`ERR_JWT_EXPIRED`;claim;reason;payload;constructor(e,t,n=`unspecified`,r=`unspecified`){super(e,{cause:{claim:n,reason:r,payload:t}}),this.claim=n,this.reason=r,this.payload=t}},ie=class extends C{static code=`ERR_JOSE_ALG_NOT_ALLOWED`;code=`ERR_JOSE_ALG_NOT_ALLOWED`},T=class extends C{static code=`ERR_JOSE_NOT_SUPPORTED`;code=`ERR_JOSE_NOT_SUPPORTED`},E=class extends C{static code=`ERR_JWE_DECRYPTION_FAILED`;code=`ERR_JWE_DECRYPTION_FAILED`;constructor(e=`decryption operation failed`,t){super(e,t)}},D=class extends C{static code=`ERR_JWE_INVALID`;code=`ERR_JWE_INVALID`},O=class extends C{static code=`ERR_JWS_INVALID`;code=`ERR_JWS_INVALID`},k=class extends C{static code=`ERR_JWT_INVALID`;code=`ERR_JWT_INVALID`},ae=class extends C{static code=`ERR_JWK_INVALID`;code=`ERR_JWK_INVALID`},oe=class extends C{static code=`ERR_JWKS_INVALID`;code=`ERR_JWKS_INVALID`},se=class extends C{static code=`ERR_JWKS_NO_MATCHING_KEY`;code=`ERR_JWKS_NO_MATCHING_KEY`;constructor(e=`no applicable key found in the JSON Web Key Set`,t){super(e,t)}},ce=class extends C{[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)}},le=class extends C{static code=`ERR_JWKS_TIMEOUT`;code=`ERR_JWKS_TIMEOUT`;constructor(e=`request timed out`,t){super(e,t)}},ue=class extends C{static code=`ERR_JWS_SIGNATURE_VERIFICATION_FAILED`;code=`ERR_JWS_SIGNATURE_VERIFICATION_FAILED`;constructor(e=`signature verification failed`,t){super(e,t)}};function A(e){if(!j(e))throw Error(`CryptoKey instance expected`)}const j=e=>{if(e?.[Symbol.toStringTag]===`CryptoKey`)return!0;try{return e instanceof CryptoKey}catch{return!1}},de=e=>e?.[Symbol.toStringTag]===`KeyObject`,fe=e=>j(e)||de(e);function pe(e){switch(e){case`A128GCM`:return 128;case`A192GCM`:return 192;case`A256GCM`:case`A128CBC-HS256`:return 256;case`A192CBC-HS384`:return 384;case`A256CBC-HS512`:return 512;default:throw new T(`Unsupported JWE Algorithm: ${e}`)}}const M=e=>crypto.getRandomValues(new Uint8Array(pe(e)>>3));function me(e,t){let n=e.byteLength<<3;if(n!==t)throw new D(`Invalid Content Encryption Key length. Expected ${t} bits, got ${n} bits`)}function he(e){switch(e){case`A128GCM`:case`A128GCMKW`:case`A192GCM`:case`A192GCMKW`:case`A256GCM`:case`A256GCMKW`:return 96;case`A128CBC-HS256`:case`A192CBC-HS384`:case`A256CBC-HS512`:return 128;default:throw new T(`Unsupported JWE Algorithm: ${e}`)}}const ge=e=>crypto.getRandomValues(new Uint8Array(he(e)>>3));function _e(e,t){if(t.length<<3!==he(e))throw new D(`Invalid Initialization Vector length`)}async function ve(e,t,n){if(!(t instanceof Uint8Array))throw TypeError(S(t,`Uint8Array`));let r=parseInt(e.slice(1,4),10);return{encKey:await crypto.subtle.importKey(`raw`,t.subarray(r>>3),`AES-CBC`,!1,[n]),macKey:await crypto.subtle.importKey(`raw`,t.subarray(0,r>>3),{hash:`SHA-${r<<1}`,name:`HMAC`},!1,[`sign`]),keySize:r}}async function ye(e,t,n){return new Uint8Array((await crypto.subtle.sign(`HMAC`,e,t)).slice(0,n>>3))}async function be(e,t,n,r,a){let{encKey:s,macKey:c,keySize:l}=await ve(e,n,`encrypt`),u=new Uint8Array(await crypto.subtle.encrypt({iv:r,name:`AES-CBC`},s,t));return{ciphertext:u,tag:await ye(c,i(a,r,u,o(a.length<<3)),l),iv:r}}async function xe(e,t){if(!(e instanceof Uint8Array))throw TypeError(`First argument must be a buffer`);if(!(t instanceof Uint8Array))throw TypeError(`Second argument must be a buffer`);let n={name:`HMAC`,hash:`SHA-256`},r=await crypto.subtle.generateKey(n,!1,[`sign`]),i=new Uint8Array(await crypto.subtle.sign(n,r,e)),a=new Uint8Array(await crypto.subtle.sign(n,r,t)),o=0,s=-1;for(;++s<32;)o|=i[s]^a[s];return o===0}async function Se(e,t,n,r,a,s){let{encKey:c,macKey:l,keySize:u}=await ve(e,t,`decrypt`),d=await ye(l,i(s,r,n,o(s.length<<3)),u),f;try{f=await xe(a,d)}catch{}if(!f)throw new E;let p;try{p=new Uint8Array(await crypto.subtle.decrypt({iv:r,name:`AES-CBC`},c,n))}catch{}if(!p)throw new E;return p}async function Ce(e,t,n,r,i){let a;n instanceof Uint8Array?a=await crypto.subtle.importKey(`raw`,n,`AES-GCM`,!1,[`encrypt`]):(b(n,e,`encrypt`),a=n);let o=new Uint8Array(await crypto.subtle.encrypt({additionalData:i,iv:r,name:`AES-GCM`,tagLength:128},a,t)),s=o.slice(-16);return{ciphertext:o.slice(0,-16),tag:s,iv:r}}async function we(e,t,n,r,a,o){let s;t instanceof Uint8Array?s=await crypto.subtle.importKey(`raw`,t,`AES-GCM`,!1,[`decrypt`]):(b(t,e,`decrypt`),s=t);try{return new Uint8Array(await crypto.subtle.decrypt({additionalData:o,iv:r,name:`AES-GCM`,tagLength:128},s,i(n,a)))}catch{throw new E}}const Te=`Unsupported JWE Content Encryption Algorithm`;async function Ee(e,t,n,r,i){if(!j(n)&&!(n instanceof Uint8Array))throw TypeError(S(n,`CryptoKey`,`KeyObject`,`Uint8Array`,`JSON Web Key`));switch(r?_e(e,r):r=ge(e),e){case`A128CBC-HS256`:case`A192CBC-HS384`:case`A256CBC-HS512`:return n instanceof Uint8Array&&me(n,parseInt(e.slice(-3),10)),be(e,t,n,r,i);case`A128GCM`:case`A192GCM`:case`A256GCM`:return n instanceof Uint8Array&&me(n,parseInt(e.slice(1,4),10)),Ce(e,t,n,r,i);default:throw new T(Te)}}async function De(e,t,n,r,i,a){if(!j(t)&&!(t instanceof Uint8Array))throw TypeError(S(t,`CryptoKey`,`KeyObject`,`Uint8Array`,`JSON Web Key`));if(!r)throw new D(`JWE Initialization Vector missing`);if(!i)throw new D(`JWE Authentication Tag missing`);switch(_e(e,r),e){case`A128CBC-HS256`:case`A192CBC-HS384`:case`A256CBC-HS512`:return t instanceof Uint8Array&&me(t,parseInt(e.slice(-3),10)),Se(e,t,n,r,i,a);case`A128GCM`:case`A192GCM`:case`A256GCM`:return t instanceof Uint8Array&&me(t,parseInt(e.slice(1,4),10)),we(e,t,n,r,i,a);default:throw new T(Te)}}const Oe=Symbol();function N(e,t){if(e)throw TypeError(`${t} can only be called once`)}function P(e,t,n){try{return f(e)}catch{throw new n(`Failed to base64url decode the ${t}`)}}async function ke(e,t){let n=`SHA-${e.slice(-3)}`;return new Uint8Array(await crypto.subtle.digest(n,t))}const Ae=e=>typeof e==`object`&&!!e;function F(e){if(!Ae(e)||Object.prototype.toString.call(e)!==`[object Object]`)return!1;if(Object.getPrototypeOf(e)===null)return!0;let t=e;for(;Object.getPrototypeOf(t)!==null;)t=Object.getPrototypeOf(t);return Object.getPrototypeOf(e)===t}function I(...e){let t=e.filter(Boolean);if(t.length===0||t.length===1)return!0;let n;for(let e of t){let t=Object.keys(e);if(!n||n.size===0){n=new Set(t);continue}for(let e of t){if(n.has(e))return!1;n.add(e)}}return!0}const L=e=>F(e)&&typeof e.kty==`string`,je=e=>e.kty!==`oct`&&(e.kty===`AKP`&&typeof e.priv==`string`||typeof e.d==`string`),Me=e=>e.kty!==`oct`&&e.d===void 0&&e.priv===void 0,Ne=e=>e.kty===`oct`&&typeof e.k==`string`;function Pe(e,t){if(e.algorithm.length!==parseInt(t.slice(1,4),10))throw TypeError(`Invalid key size for alg: ${t}`)}function Fe(e,t,n){return e instanceof Uint8Array?crypto.subtle.importKey(`raw`,e,`AES-KW`,!0,[n]):(b(e,t,n),e)}async function Ie(e,t,n){let r=await Fe(t,e,`wrapKey`);Pe(r,e);let i=await crypto.subtle.importKey(`raw`,n,{hash:`SHA-256`,name:`HMAC`},!0,[`sign`]);return new Uint8Array(await crypto.subtle.wrapKey(`raw`,i,r,`AES-KW`))}async function Le(e,t,n){let r=await Fe(t,e,`unwrapKey`);Pe(r,e);let i=await crypto.subtle.unwrapKey(`raw`,n,r,`AES-KW`,{hash:`SHA-256`,name:`HMAC`},!0,[`sign`]);return new Uint8Array(await crypto.subtle.exportKey(`raw`,i))}function Re(e){return i(s(e.length),e)}async function ze(e,t,n){let r=t>>3,i=Math.ceil(r/32),a=new Uint8Array(i*32);for(let t=1;t<=i;t++){let r=new Uint8Array(4+e.length+n.length);r.set(s(t),0),r.set(e,4),r.set(n,4+e.length);let i=await ke(`sha256`,r);a.set(i,(t-1)*32)}return a.slice(0,r)}async function Be(e,t,n,r,a=new Uint8Array,o=new Uint8Array){b(e,`ECDH`),b(t,`ECDH`,`deriveBits`);let l=i(Re(c(n)),Re(a),Re(o),s(r),new Uint8Array);return ze(new Uint8Array(await crypto.subtle.deriveBits({name:e.algorithm.name,public:e},t,Ve(e))),r,l)}function Ve(e){return e.algorithm.name===`X25519`?256:Math.ceil(parseInt(e.algorithm.namedCurve.slice(-3),10)/8)<<3}function He(e){switch(e.algorithm.namedCurve){case`P-256`:case`P-384`:case`P-521`:return!0;default:return e.algorithm.name===`X25519`}}function Ue(e,t){return e instanceof Uint8Array?crypto.subtle.importKey(`raw`,e,`PBKDF2`,!1,[`deriveBits`]):(b(e,t,`deriveBits`),e)}const We=(e,t)=>i(c(e),Uint8Array.of(0),t);async function Ge(e,t,n,r){if(!(e instanceof Uint8Array)||e.length<8)throw new D(`PBES2 Salt Input must be 8 or more octets`);if(!Number.isSafeInteger(n)||Math.sign(n)!==1)throw new D(`PBES2 Count Input must be a positive integer`);let i=We(t,e),a=parseInt(t.slice(13,16),10),o={hash:`SHA-${t.slice(8,11)}`,iterations:n,name:`PBKDF2`,salt:i},s=await Ue(r,t);return new Uint8Array(await crypto.subtle.deriveBits(o,s,a))}async function Ke(e,t,n,r=2048,i=crypto.getRandomValues(new Uint8Array(16))){let a=await Ge(i,e,r,t);return{encryptedKey:await Ie(e.slice(-6),a,n),p2c:r,p2s:p(i)}}async function qe(e,t,n,r,i){let a=await Ge(i,e,r,t);return Le(e.slice(-6),a,n)}function R(e,t){if(e.startsWith(`RS`)||e.startsWith(`PS`)){let{modulusLength:n}=t.algorithm;if(typeof n!=`number`||n<2048)throw TypeError(`${e} requires key modulusLength to be 2048 bits or larger`)}}function Je(e,t){let n=`SHA-${e.slice(-3)}`;switch(e){case`HS256`:case`HS384`:case`HS512`:return{hash:n,name:`HMAC`};case`PS256`:case`PS384`:case`PS512`:return{hash:n,name:`RSA-PSS`,saltLength:parseInt(e.slice(-3),10)>>3};case`RS256`:case`RS384`:case`RS512`:return{hash:n,name:`RSASSA-PKCS1-v1_5`};case`ES256`:case`ES384`:case`ES512`:return{hash:n,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 T(`alg ${e} is not supported either by JOSE or your javascript runtime`)}}async function Ye(e,t,n){if(t instanceof Uint8Array){if(!e.startsWith(`HS`))throw TypeError(S(t,`CryptoKey`,`KeyObject`,`JSON Web Key`));return crypto.subtle.importKey(`raw`,t,{hash:`SHA-${e.slice(-3)}`,name:`HMAC`},!1,[n])}return ee(t,e,n),t}async function Xe(e,t,n){let r=await Ye(e,t,`sign`);R(e,r);let i=await crypto.subtle.sign(Je(e,r.algorithm),r,n);return new Uint8Array(i)}async function Ze(e,t,n,r){let i=await Ye(e,t,`verify`);R(e,i);let a=Je(e,i.algorithm);try{return await crypto.subtle.verify(a,i,n,r)}catch{return!1}}const Qe=e=>{switch(e){case`RSA-OAEP`:case`RSA-OAEP-256`:case`RSA-OAEP-384`:case`RSA-OAEP-512`:return`RSA-OAEP`;default:throw new T(`alg ${e} is not supported either by JOSE or your javascript runtime`)}};async function $e(e,t,n){return b(t,e,`encrypt`),R(e,t),new Uint8Array(await crypto.subtle.encrypt(Qe(e),t,n))}async function et(e,t,n){return b(t,e,`decrypt`),R(e,t),new Uint8Array(await crypto.subtle.decrypt(Qe(e),t,n))}const z=`Invalid or unsupported JWK "alg" (Algorithm) Parameter value`;function tt(e){let t,n;switch(e.kty){case`AKP`:switch(e.alg){case`ML-DSA-44`:case`ML-DSA-65`:case`ML-DSA-87`:t={name:e.alg},n=e.priv?[`sign`]:[`verify`];break;default:throw new T(z)}break;case`RSA`:switch(e.alg){case`PS256`:case`PS384`:case`PS512`:t={name:`RSA-PSS`,hash:`SHA-${e.alg.slice(-3)}`},n=e.d?[`sign`]:[`verify`];break;case`RS256`:case`RS384`:case`RS512`:t={name:`RSASSA-PKCS1-v1_5`,hash:`SHA-${e.alg.slice(-3)}`},n=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}`},n=e.d?[`decrypt`,`unwrapKey`]:[`encrypt`,`wrapKey`];break;default:throw new T(z)}break;case`EC`:switch(e.alg){case`ES256`:case`ES384`:case`ES512`:t={name:`ECDSA`,namedCurve:{ES256:`P-256`,ES384:`P-384`,ES512:`P-521`}[e.alg]},n=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},n=e.d?[`deriveBits`]:[];break;default:throw new T(z)}break;case`OKP`:switch(e.alg){case`Ed25519`:case`EdDSA`:t={name:`Ed25519`},n=e.d?[`sign`]:[`verify`];break;case`ECDH-ES`:case`ECDH-ES+A128KW`:case`ECDH-ES+A192KW`:case`ECDH-ES+A256KW`:t={name:e.crv},n=e.d?[`deriveBits`]:[];break;default:throw new T(z)}break;default:throw new T(`Invalid or unsupported JWK "kty" (Key Type) Parameter value`)}return{algorithm:t,keyUsages:n}}async function B(e){if(!e.alg)throw TypeError(`"alg" argument is required when "jwk.alg" is not present`);let{algorithm:t,keyUsages:n}=tt(e),r={...e};return r.kty!==`AKP`&&delete r.alg,delete r.use,crypto.subtle.importKey(`jwk`,r,t,e.ext??!(e.d||e.priv),e.key_ops??n)}const V=`given KeyObject instance cannot be used for this algorithm`;let H;const nt=async(e,t,n,r=!1)=>{H||=new WeakMap;let i=H.get(e);if(i?.[n])return i[n];let a=await B({...t,alg:n});return r&&Object.freeze(e),i?i[n]=a:H.set(e,{[n]:a}),a},rt=(e,t)=>{H||=new WeakMap;let n=H.get(e);if(n?.[t])return n[t];let r=e.type===`public`,i=!!r,a;if(e.asymmetricKeyType===`x25519`){switch(t){case`ECDH-ES`:case`ECDH-ES+A128KW`:case`ECDH-ES+A192KW`:case`ECDH-ES+A256KW`:break;default:throw TypeError(V)}a=e.toCryptoKey(e.asymmetricKeyType,i,r?[]:[`deriveBits`])}if(e.asymmetricKeyType===`ed25519`){if(t!==`EdDSA`&&t!==`Ed25519`)throw TypeError(V);a=e.toCryptoKey(e.asymmetricKeyType,i,[r?`verify`:`sign`])}switch(e.asymmetricKeyType){case`ml-dsa-44`:case`ml-dsa-65`:case`ml-dsa-87`:if(t!==e.asymmetricKeyType.toUpperCase())throw TypeError(V);a=e.toCryptoKey(e.asymmetricKeyType,i,[r?`verify`:`sign`])}if(e.asymmetricKeyType===`rsa`){let n;switch(t){case`RSA-OAEP`:n=`SHA-1`;break;case`RS256`:case`PS256`:case`RSA-OAEP-256`:n=`SHA-256`;break;case`RS384`:case`PS384`:case`RSA-OAEP-384`:n=`SHA-384`;break;case`RS512`:case`PS512`:case`RSA-OAEP-512`:n=`SHA-512`;break;default:throw TypeError(V)}if(t.startsWith(`RSA-OAEP`))return e.toCryptoKey({name:`RSA-OAEP`,hash:n},i,r?[`encrypt`]:[`decrypt`]);a=e.toCryptoKey({name:t.startsWith(`PS`)?`RSA-PSS`:`RSASSA-PKCS1-v1_5`,hash:n},i,[r?`verify`:`sign`])}if(e.asymmetricKeyType===`ec`){let n=new Map([[`prime256v1`,`P-256`],[`secp384r1`,`P-384`],[`secp521r1`,`P-521`]]).get(e.asymmetricKeyDetails?.namedCurve);if(!n)throw TypeError(V);let o={ES256:`P-256`,ES384:`P-384`,ES512:`P-521`};o[t]&&n===o[t]&&(a=e.toCryptoKey({name:`ECDSA`,namedCurve:n},i,[r?`verify`:`sign`])),t.startsWith(`ECDH-ES`)&&(a=e.toCryptoKey({name:`ECDH`,namedCurve:n},i,r?[]:[`deriveBits`]))}if(!a)throw TypeError(V);return n?n[t]=a:H.set(e,{[t]:a}),a};async function U(e,t){if(e instanceof Uint8Array||j(e))return e;if(de(e)){if(e.type===`secret`)return e.export();if(`toCryptoKey`in e&&typeof e.toCryptoKey==`function`)try{return rt(e,t)}catch(e){if(e instanceof TypeError)throw e}return nt(e,e.export({format:`jwk`}),t)}if(L(e))return e.k?f(e.k):nt(e,e,t,!0);throw Error(`unreachable`)}const it=(e,t)=>`-----BEGIN ${t}-----\n${(e.match(/.{1,64}/g)||[]).join(` `)}\n-----END ${t}-----`,at=async(e,t,n)=>{if(de(n)){if(n.type!==e)throw TypeError(`key is not a ${e} key`);return n.export({format:`pem`,type:t})}if(!j(n))throw TypeError(S(n,`CryptoKey`,`KeyObject`));if(!n.extractable)throw TypeError(`CryptoKey is not extractable`);if(n.type!==e)throw TypeError(`key is not a ${e} key`);return it(l(new Uint8Array(await crypto.subtle.exportKey(t,n))),`${e.toUpperCase()} KEY`)},ot=e=>at(`public`,`spki`,e),st=e=>at(`private`,`pkcs8`,e),ct=(e,t)=>{if(e.byteLength!==t.length)return!1;for(let n=0;n<e.byteLength;n++)if(e[n]!==t[n])return!1;return!0},lt=e=>({data:e,pos:0}),W=e=>{let t=e.data[e.pos++];if(t&128){let n=t&127,r=0;for(let t=0;t<n;t++)r=r<<8|e.data[e.pos++];return r}return t},ut=(e,t=1)=>{if(t<=0)return;e.pos++;let n=W(e);e.pos+=n,t>1&&ut(e,t-1)},G=(e,t,n)=>{if(e.data[e.pos++]!==t)throw Error(n)},dt=(e,t)=>{let n=e.data.subarray(e.pos,e.pos+t);return e.pos+=t,n},ft=e=>(G(e,6,`Expected algorithm OID`),dt(e,W(e)));function pt(e){G(e,48,`Invalid PKCS#8 structure`),W(e),G(e,2,`Expected version field`);let t=W(e);e.pos+=t,G(e,48,`Expected algorithm identifier`);let n=W(e);return{algIdStart:e.pos,algIdLength:n}}function mt(e){G(e,48,`Invalid SPKI structure`),W(e),G(e,48,`Expected algorithm identifier`);let t=W(e);return{algIdStart:e.pos,algIdLength:t}}const ht=e=>{let t=ft(e);if(ct(t,[43,101,110]))return`X25519`;if(!ct(t,[42,134,72,206,61,2,1]))throw Error(`Unsupported key algorithm`);G(e,6,`Expected curve OID`);let n=dt(e,W(e));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(ct(n,t))return e;throw Error(`Unsupported named curve`)},gt=async(e,t,n,r)=>{let i,a,o=e===`spki`,s=()=>o?[`verify`]:[`sign`],c=()=>o?[`encrypt`,`wrapKey`]:[`decrypt`,`unwrapKey`];switch(n){case`PS256`:case`PS384`:case`PS512`:i={name:`RSA-PSS`,hash:`SHA-${n.slice(-3)}`},a=s();break;case`RS256`:case`RS384`:case`RS512`:i={name:`RSASSA-PKCS1-v1_5`,hash:`SHA-${n.slice(-3)}`},a=s();break;case`RSA-OAEP`:case`RSA-OAEP-256`:case`RSA-OAEP-384`:case`RSA-OAEP-512`:i={name:`RSA-OAEP`,hash:`SHA-${parseInt(n.slice(-3),10)||1}`},a=c();break;case`ES256`:case`ES384`:case`ES512`:i={name:`ECDSA`,namedCurve:{ES256:`P-256`,ES384:`P-384`,ES512:`P-521`}[n]},a=s();break;case`ECDH-ES`:case`ECDH-ES+A128KW`:case`ECDH-ES+A192KW`:case`ECDH-ES+A256KW`:try{let e=r.getNamedCurve(t);i=e===`X25519`?{name:`X25519`}:{name:`ECDH`,namedCurve:e}}catch{throw new T(`Invalid or unsupported key format`)}a=o?[]:[`deriveBits`];break;case`Ed25519`:case`EdDSA`:i={name:`Ed25519`},a=s();break;case`ML-DSA-44`:case`ML-DSA-65`:case`ML-DSA-87`:i={name:n},a=s();break;default:throw new T(`Invalid or unsupported "alg" (Algorithm) value`)}return crypto.subtle.importKey(e,t,i,r?.extractable??!!o,a)},_t=(e,t)=>u(e.replace(t,``)),vt=(e,t,n)=>{let r=_t(e,/(?:-----(?:BEGIN|END) PRIVATE KEY-----|\s)/g),i=n;return t?.startsWith?.(`ECDH-ES`)&&(i||={},i.getNamedCurve=e=>{let t=lt(e);return pt(t),ht(t)}),gt(`pkcs8`,r,t,i)},yt=(e,t,n)=>{let r=_t(e,/(?:-----(?:BEGIN|END) PUBLIC KEY-----|\s)/g),i=n;return t?.startsWith?.(`ECDH-ES`)&&(i||={},i.getNamedCurve=e=>{let t=lt(e);return mt(t),ht(t)}),gt(`spki`,r,t,i)};function bt(e){let t=lt(e);G(t,48,`Invalid certificate structure`),W(t),G(t,48,`Invalid tbsCertificate structure`),W(t),e[t.pos]===160?ut(t,6):ut(t,5);let n=t.pos;G(t,48,`Invalid SPKI structure`);let r=W(t);return e.subarray(n,n+r+(t.pos-n))}function xt(e){return bt(_t(e,/(?:-----(?:BEGIN|END) CERTIFICATE-----|\s)/g))}const St=(e,t,n)=>{let r;try{r=xt(e)}catch(e){throw TypeError(`Failed to parse the X.509 certificate`,{cause:e})}return yt(it(l(r),`PUBLIC KEY`),t,n)};async function Ct(e,t,n){if(typeof e!=`string`||e.indexOf(`-----BEGIN PUBLIC KEY-----`)!==0)throw TypeError(`"spki" must be SPKI formatted string`);return yt(e,t,n)}async function wt(e,t,n){if(typeof e!=`string`||e.indexOf(`-----BEGIN CERTIFICATE-----`)!==0)throw TypeError(`"x509" must be X.509 formatted string`);return St(e,t,n)}async function Tt(e,t,n){if(typeof e!=`string`||e.indexOf(`-----BEGIN PRIVATE KEY-----`)!==0)throw TypeError(`"pkcs8" must be PKCS#8 formatted string`);return vt(e,t,n)}async function Et(e,t,n){if(!F(e))throw TypeError(`JWK must be an object`);let r;switch(t??=e.alg,r??=n?.extractable??e.ext,e.kty){case`oct`:if(typeof e.k!=`string`||!e.k)throw TypeError(`missing "k" (Key Value) Parameter value`);return f(e.k);case`RSA`:if(`oth`in e&&e.oth!==void 0)throw new T(`RSA JWK "oth" (Other Primes Info) Parameter value is not supported`);return B({...e,alg:t,ext:r});case`AKP`:if(typeof e.alg!=`string`||!e.alg)throw TypeError(`missing "alg" (Algorithm) Parameter value`);if(t!==void 0&&t!==e.alg)throw TypeError(`JWK alg and alg option value mismatch`);return B({...e,ext:r});case`EC`:case`OKP`:return B({...e,alg:t,ext:r});default:throw new T(`Unsupported "kty" (Key Type) Parameter value`)}}async function Dt(e){if(de(e))if(e.type===`secret`)e=e.export();else return e.export({format:`jwk`});if(e instanceof Uint8Array)return{kty:`oct`,k:p(e)};if(!j(e))throw TypeError(S(e,`CryptoKey`,`KeyObject`,`Uint8Array`));if(!e.extractable)throw TypeError(`non-extractable CryptoKey cannot be exported as a JWK`);let{ext:t,key_ops:n,alg:r,use:i,...a}=await crypto.subtle.exportKey(`jwk`,e);return a.kty===`AKP`&&(a.alg=r),a}async function Ot(e){return ot(e)}async function kt(e){return st(e)}async function At(e){return Dt(e)}async function jt(e,t,n,r){let i=await Ee(e.slice(0,7),n,t,r,new Uint8Array);return{encryptedKey:i.ciphertext,iv:p(i.iv),tag:p(i.tag)}}async function Mt(e,t,n,r,i){return De(e.slice(0,7),t,n,r,i,new Uint8Array)}const Nt=`Invalid or unsupported "alg" (JWE Algorithm) header value`;function K(e){if(e===void 0)throw new D(`JWE Encrypted Key missing`)}async function Pt(e,t,n,r,i){switch(e){case`dir`:if(n!==void 0)throw new D(`Encountered unexpected JWE Encrypted Key`);return t;case`ECDH-ES`:if(n!==void 0)throw new D(`Encountered unexpected JWE Encrypted Key`);case`ECDH-ES+A128KW`:case`ECDH-ES+A192KW`:case`ECDH-ES+A256KW`:{if(!F(r.epk))throw new D(`JOSE Header "epk" (Ephemeral Public Key) missing or invalid`);if(A(t),!He(t))throw new T(`ECDH with the provided key is not allowed or not supported by your javascript runtime`);let i=await Et(r.epk,e);A(i);let a,o;if(r.apu!==void 0){if(typeof r.apu!=`string`)throw new D(`JOSE Header "apu" (Agreement PartyUInfo) invalid`);a=P(r.apu,`apu`,D)}if(r.apv!==void 0){if(typeof r.apv!=`string`)throw new D(`JOSE Header "apv" (Agreement PartyVInfo) invalid`);o=P(r.apv,`apv`,D)}let s=await Be(i,t,e===`ECDH-ES`?r.enc:e,e===`ECDH-ES`?pe(r.enc):parseInt(e.slice(-5,-2),10),a,o);return e===`ECDH-ES`?s:(K(n),Le(e.slice(-6),s,n))}case`RSA-OAEP`:case`RSA-OAEP-256`:case`RSA-OAEP-384`:case`RSA-OAEP-512`:return K(n),A(t),et(e,t,n);case`PBES2-HS256+A128KW`:case`PBES2-HS384+A192KW`:case`PBES2-HS512+A256KW`:{if(K(n),typeof r.p2c!=`number`)throw new D(`JOSE Header "p2c" (PBES2 Count) missing or invalid`);let a=i?.maxPBES2Count||1e4;if(r.p2c>a)throw new D(`JOSE Header "p2c" (PBES2 Count) out is of acceptable bounds`);if(typeof r.p2s!=`string`)throw new D(`JOSE Header "p2s" (PBES2 Salt) missing or invalid`);let o;return o=P(r.p2s,`p2s`,D),qe(e,t,n,r.p2c,o)}case`A128KW`:case`A192KW`:case`A256KW`:return K(n),Le(e,t,n);case`A128GCMKW`:case`A192GCMKW`:case`A256GCMKW`:{if(K(n),typeof r.iv!=`string`)throw new D(`JOSE Header "iv" (Initialization Vector) missing or invalid`);if(typeof r.tag!=`string`)throw new D(`JOSE Header "tag" (Authentication Tag) missing or invalid`);let i;i=P(r.iv,`iv`,D);let a;return a=P(r.tag,`tag`,D),Mt(e,t,n,i,a)}default:throw new T(Nt)}}async function Ft(e,t,n,r,i={}){let a,o,s;switch(e){case`dir`:s=n;break;case`ECDH-ES`:case`ECDH-ES+A128KW`:case`ECDH-ES+A192KW`:case`ECDH-ES+A256KW`:{if(A(n),!He(n))throw new T(`ECDH with the provided key is not allowed or not supported by your javascript runtime`);let{apu:c,apv:l}=i,u;u=i.epk?await U(i.epk,e):(await crypto.subtle.generateKey(n.algorithm,!0,[`deriveBits`])).privateKey;let{x:d,y:f,crv:m,kty:h}=await At(u),g=await Be(n,u,e===`ECDH-ES`?t:e,e===`ECDH-ES`?pe(t):parseInt(e.slice(-5,-2),10),c,l);if(o={epk:{x:d,crv:m,kty:h}},h===`EC`&&(o.epk.y=f),c&&(o.apu=p(c)),l&&(o.apv=p(l)),e===`ECDH-ES`){s=g;break}s=r||M(t),a=await Ie(e.slice(-6),g,s);break}case`RSA-OAEP`:case`RSA-OAEP-256`:case`RSA-OAEP-384`:case`RSA-OAEP-512`:s=r||M(t),A(n),a=await $e(e,n,s);break;case`PBES2-HS256+A128KW`:case`PBES2-HS384+A192KW`:case`PBES2-HS512+A256KW`:{s=r||M(t);let{p2c:c,p2s:l}=i;({encryptedKey:a,...o}=await Ke(e,n,s,c,l));break}case`A128KW`:case`A192KW`:case`A256KW`:s=r||M(t),a=await Ie(e,n,s);break;case`A128GCMKW`:case`A192GCMKW`:case`A256GCMKW`:{s=r||M(t);let{iv:c}=i;({encryptedKey:a,...o}=await jt(e,n,s,c));break}default:throw new T(Nt)}return{cek:s,encryptedKey:a,parameters:o}}function q(e,t,n,r,i){if(i.crit!==void 0&&r?.crit===void 0)throw new e(`"crit" (Critical) Header Parameter MUST be integrity protected`);if(!r||r.crit===void 0)return new Set;if(!Array.isArray(r.crit)||r.crit.length===0||r.crit.some(e=>typeof e!=`string`||e.length===0))throw new e(`"crit" (Critical) Header Parameter MUST be an array of non-empty strings when present`);let a;a=n===void 0?t:new Map([...Object.entries(n),...t.entries()]);for(let t of r.crit){if(!a.has(t))throw new T(`Extension Header Parameter "${t}" is not recognized`);if(i[t]===void 0)throw new e(`Extension Header Parameter "${t}" is missing`);if(a.get(t)&&r[t]===void 0)throw new e(`Extension Header Parameter "${t}" MUST be integrity protected`)}return new Set(r.crit)}function It(e,t){if(t!==void 0&&(!Array.isArray(t)||t.some(e=>typeof e!=`string`)))throw TypeError(`"${e}" option must be an array of strings`);if(t)return new Set(t)}const J=e=>e?.[Symbol.toStringTag],Lt=(e,t,n)=>{if(t.use!==void 0){let e;switch(n){case`sign`:case`verify`:e=`sig`;break;case`encrypt`:case`decrypt`:e=`enc`;break}if(t.use!==e)throw TypeError(`Invalid key for this operation, its "use" must be "${e}" when present`)}if(t.alg!==void 0&&t.alg!==e)throw TypeError(`Invalid key for this operation, its "alg" must be "${e}" when present`);if(Array.isArray(t.key_ops)){let r;switch(!0){case n===`sign`||n===`verify`:case e===`dir`:case e.includes(`CBC-HS`):r=n;break;case e.startsWith(`PBES2`):r=`deriveBits`;break;case/^A\d{3}(?:GCM)?(?:KW)?$/.test(e):r=!e.includes(`GCM`)&&e.endsWith(`KW`)?n===`encrypt`?`wrapKey`:`unwrapKey`:n;break;case n===`encrypt`&&e.startsWith(`RSA`):r=`wrapKey`;break;case n===`decrypt`:r=e.startsWith(`RSA`)?`unwrapKey`:`deriveBits`;break}if(r&&t.key_ops?.includes?.(r)===!1)throw TypeError(`Invalid key for this operation, its "key_ops" must include "${r}" when present`)}return!0},Rt=(e,t,n)=>{if(!(t instanceof Uint8Array)){if(L(t)){if(Ne(t)&&Lt(e,t,n))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(!fe(t))throw TypeError(te(e,t,`CryptoKey`,`KeyObject`,`JSON Web Key`,`Uint8Array`));if(t.type!==`secret`)throw TypeError(`${J(t)} instances for symmetric algorithms must be of type "secret"`)}},zt=(e,t,n)=>{if(L(t))switch(n){case`decrypt`:case`sign`:if(je(t)&&Lt(e,t,n))return;throw TypeError(`JSON Web Key for this operation must be a private JWK`);case`encrypt`:case`verify`:if(Me(t)&&Lt(e,t,n))return;throw TypeError(`JSON Web Key for this operation must be a public JWK`)}if(!fe(t))throw TypeError(te(e,t,`CryptoKey`,`KeyObject`,`JSON Web Key`));if(t.type===`secret`)throw TypeError(`${J(t)} instances for asymmetric algorithms must not be of type "secret"`);if(t.type===`public`)switch(n){case`sign`:throw TypeError(`${J(t)} instances for asymmetric algorithm signing must be of type "private"`);case`decrypt`:throw TypeError(`${J(t)} instances for asymmetric algorithm decryption must be of type "private"`)}if(t.type===`private`)switch(n){case`verify`:throw TypeError(`${J(t)} instances for asymmetric algorithm verifying must be of type "public"`);case`encrypt`:throw TypeError(`${J(t)} instances for asymmetric algorithm encryption must be of type "public"`)}};function Y(e,t,n){switch(e.substring(0,2)){case`A1`:case`A2`:case`di`:case`HS`:case`PB`:Rt(e,t,n);break;default:zt(e,t,n)}}function Bt(e){if(globalThis[e]===void 0)throw new T(`JWE "zip" (Compression Algorithm) Header Parameter requires the ${e} API.`)}async function Vt(e){Bt(`CompressionStream`);let t=new CompressionStream(`deflate-raw`),n=t.writable.getWriter();n.write(e).catch(()=>{}),n.close().catch(()=>{});let r=[],a=t.readable.getReader();for(;;){let{value:e,done:t}=await a.read();if(t)break;r.push(e)}return i(...r)}async function Ht(e,t){Bt(`DecompressionStream`);let n=new DecompressionStream(`deflate-raw`),r=n.writable.getWriter();r.write(e).catch(()=>{}),r.close().catch(()=>{});let a=[],o=0,s=n.readable.getReader();for(;;){let{value:e,done:n}=await s.read();if(n)break;if(a.push(e),o+=e.byteLength,t!==1/0&&o>t)throw new D(`Decompressed plaintext exceeded the configured limit`)}return i(...a)}async function Ut(e,t,r){if(!F(e))throw new D(`Flattened JWE must be an object`);if(e.protected===void 0&&e.header===void 0&&e.unprotected===void 0)throw new D(`JOSE Header missing`);if(e.iv!==void 0&&typeof e.iv!=`string`)throw new D(`JWE Initialization Vector incorrect type`);if(typeof e.ciphertext!=`string`)throw new D(`JWE Ciphertext missing or incorrect type`);if(e.tag!==void 0&&typeof e.tag!=`string`)throw new D(`JWE Authentication Tag incorrect type`);if(e.protected!==void 0&&typeof e.protected!=`string`)throw new D(`JWE Protected Header incorrect type`);if(e.encrypted_key!==void 0&&typeof e.encrypted_key!=`string`)throw new D(`JWE Encrypted Key incorrect type`);if(e.aad!==void 0&&typeof e.aad!=`string`)throw new D(`JWE AAD incorrect type`);if(e.header!==void 0&&!F(e.header))throw new D(`JWE Shared Unprotected Header incorrect type`);if(e.unprotected!==void 0&&!F(e.unprotected))throw new D(`JWE Per-Recipient Unprotected Header incorrect type`);let a;if(e.protected)try{let t=f(e.protected);a=JSON.parse(n.decode(t))}catch{throw new D(`JWE Protected Header is invalid`)}if(!I(a,e.header,e.unprotected))throw new D(`JWE Protected, JWE Unprotected Header, and JWE Per-Recipient Unprotected Header Parameter names must be disjoint`);let o={...a,...e.header,...e.unprotected};if(q(D,new Map,r?.crit,a,o),o.zip!==void 0&&o.zip!==`DEF`)throw new T(`Unsupported JWE "zip" (Compression Algorithm) Header Parameter value.`);if(o.zip!==void 0&&!a?.zip)throw new D(`JWE "zip" (Compression Algorithm) Header Parameter MUST be in a protected header.`);let{alg:s,enc:l}=o;if(typeof s!=`string`||!s)throw new D(`missing JWE Algorithm (alg) in JWE Header`);if(typeof l!=`string`||!l)throw new D(`missing JWE Encryption Algorithm (enc) in JWE Header`);let u=r&&It(`keyManagementAlgorithms`,r.keyManagementAlgorithms),d=r&&It(`contentEncryptionAlgorithms`,r.contentEncryptionAlgorithms);if(u&&!u.has(s)||!u&&s.startsWith(`PBES2`))throw new ie(`"alg" (Algorithm) Header Parameter value not allowed`);if(d&&!d.has(l))throw new ie(`"enc" (Encryption Algorithm) Header Parameter value not allowed`);let p;e.encrypted_key!==void 0&&(p=P(e.encrypted_key,`encrypted_key`,D));let m=!1;typeof t==`function`&&(t=await t(a,e),m=!0),Y(s===`dir`?l:s,t,`decrypt`);let h=await U(t,s),g;try{g=await Pt(s,h,p,o,r)}catch(e){if(e instanceof TypeError||e instanceof D||e instanceof T)throw e;g=M(l)}let _,v;e.iv!==void 0&&(_=P(e.iv,`iv`,D)),e.tag!==void 0&&(v=P(e.tag,`tag`,D));let y=e.protected===void 0?new Uint8Array:c(e.protected),ee;ee=e.aad===void 0?y:i(y,c(`.`),c(e.aad));let b=P(e.ciphertext,`ciphertext`,D),x=await De(l,g,b,_,v,ee),S={plaintext:x};if(o.zip===`DEF`){let e=r?.maxDecompressedLength??25e4;if(e===0)throw new T(`JWE "zip" (Compression Algorithm) Header Parameter is not supported.`);if(e!==1/0&&(!Number.isSafeInteger(e)||e<1))throw TypeError(`maxDecompressedLength must be 0, a positive safe integer, or Infinity`);S.plaintext=await Ht(x,e).catch(e=>{throw e instanceof D?e:new D(`Failed to decompress plaintext`,{cause:e})})}return e.protected!==void 0&&(S.protectedHeader=a),e.aad!==void 0&&(S.additionalAuthenticatedData=P(e.aad,`aad`,D)),e.unprotected!==void 0&&(S.sharedUnprotectedHeader=e.unprotected),e.header!==void 0&&(S.unprotectedHeader=e.header),m?{...S,key:h}:S}async function Wt(e,t,r){if(e instanceof Uint8Array&&(e=n.decode(e)),typeof e!=`string`)throw new D(`Compact JWE must be a string or Uint8Array`);let{0:i,1:a,2:o,3:s,4:c,length:l}=e.split(`.`);if(l!==5)throw new D(`Invalid Compact JWE`);let u=await Ut({ciphertext:s,iv:o||void 0,protected:i,tag:c||void 0,encrypted_key:a||void 0},t,r),d={plaintext:u.plaintext,protectedHeader:u.protectedHeader};return typeof t==`function`?{...d,key:u.key}:d}async function Gt(e,t,n){if(!F(e))throw new D(`General JWE must be an object`);if(!Array.isArray(e.recipients)||!e.recipients.every(F))throw new D(`JWE Recipients missing or incorrect type`);if(!e.recipients.length)throw new D(`JWE Recipients has no members`);for(let r of e.recipients)try{return await Ut({aad:e.aad,ciphertext:e.ciphertext,encrypted_key:r.encrypted_key,header:r.header,iv:e.iv,protected:e.protected,tag:e.tag,unprotected:e.unprotected},t,n)}catch{}throw new E}var Kt=class{#e;#t;#n;#r;#i;#a;#o;#s;constructor(e){if(!(e instanceof Uint8Array))throw TypeError(`plaintext must be an instance of Uint8Array`);this.#e=e}setKeyManagementParameters(e){return N(this.#s,`setKeyManagementParameters`),this.#s=e,this}setProtectedHeader(e){return N(this.#t,`setProtectedHeader`),this.#t=e,this}setSharedUnprotectedHeader(e){return N(this.#n,`setSharedUnprotectedHeader`),this.#n=e,this}setUnprotectedHeader(e){return N(this.#r,`setUnprotectedHeader`),this.#r=e,this}setAdditionalAuthenticatedData(e){return this.#i=e,this}setContentEncryptionKey(e){return N(this.#a,`setContentEncryptionKey`),this.#a=e,this}setInitializationVector(e){return N(this.#o,`setInitializationVector`),this.#o=e,this}async encrypt(e,t){if(!this.#t&&!this.#r&&!this.#n)throw new D(`either setProtectedHeader, setUnprotectedHeader, or sharedUnprotectedHeader must be called before #encrypt()`);if(!I(this.#t,this.#r,this.#n))throw new D(`JWE Protected, JWE Shared Unprotected and JWE Per-Recipient Header Parameter names must be disjoint`);let n={...this.#t,...this.#r,...this.#n};if(q(D,new Map,t?.crit,this.#t,n),n.zip!==void 0&&n.zip!==`DEF`)throw new T(`Unsupported JWE "zip" (Compression Algorithm) Header Parameter value.`);if(n.zip!==void 0&&!this.#t?.zip)throw new D(`JWE "zip" (Compression Algorithm) Header Parameter MUST be in a protected header.`);let{alg:r,enc:a}=n;if(typeof r!=`string`||!r)throw new D(`JWE "alg" (Algorithm) Header Parameter missing or invalid`);if(typeof a!=`string`||!a)throw new D(`JWE "enc" (Encryption Algorithm) Header Parameter missing or invalid`);let o;if(this.#a&&(r===`dir`||r===`ECDH-ES`))throw TypeError(`setContentEncryptionKey cannot be called with JWE "alg" (Algorithm) Header ${r}`);Y(r===`dir`?a:r,e,`encrypt`);let s;{let n,i=await U(e,r);({cek:s,encryptedKey:o,parameters:n}=await Ft(r,a,i,this.#a,this.#s)),n&&(t&&Oe in t?this.#r?this.#r={...this.#r,...n}:this.setUnprotectedHeader(n):this.#t?this.#t={...this.#t,...n}:this.setProtectedHeader(n))}let l,u,d,f;if(this.#t?(u=p(JSON.stringify(this.#t)),d=c(u)):(u=``,d=new Uint8Array),this.#i){f=p(this.#i);let e=c(f);l=i(d,c(`.`),e)}else l=d;let m=this.#e;n.zip===`DEF`&&(m=await Vt(m).catch(e=>{throw new D(`Failed to compress plaintext`,{cause:e})}));let{ciphertext:h,tag:g,iv:_}=await Ee(a,m,s,this.#o,l),v={ciphertext:p(h)};return _&&(v.iv=p(_)),g&&(v.tag=p(g)),o&&(v.encrypted_key=p(o)),f&&(v.aad=f),this.#t&&(v.protected=u),this.#n&&(v.unprotected=this.#n),this.#r&&(v.header=this.#r),v}},qt=class{#e;unprotectedHeader;keyManagementParameters;key;options;constructor(e,t,n){this.#e=e,this.key=t,this.options=n}setUnprotectedHeader(e){return N(this.unprotectedHeader,`setUnprotectedHeader`),this.unprotectedHeader=e,this}setKeyManagementParameters(e){return N(this.keyManagementParameters,`setKeyManagementParameters`),this.keyManagementParameters=e,this}addRecipient(...e){return this.#e.addRecipient(...e)}encrypt(...e){return this.#e.encrypt(...e)}done(){return this.#e}},Jt=class{#e;#t=[];#n;#r;#i;constructor(e){this.#e=e}addRecipient(e,t){let n=new qt(this,e,{crit:t?.crit});return this.#t.push(n),n}setProtectedHeader(e){return N(this.#n,`setProtectedHeader`),this.#n=e,this}setSharedUnprotectedHeader(e){return N(this.#r,`setSharedUnprotectedHeader`),this.#r=e,this}setAdditionalAuthenticatedData(e){return this.#i=e,this}async encrypt(){if(!this.#t.length)throw new D(`at least one recipient must be added`);if(this.#t.length===1){let[e]=this.#t,t=await new Kt(this.#e).setAdditionalAuthenticatedData(this.#i).setProtectedHeader(this.#n).setSharedUnprotectedHeader(this.#r).setUnprotectedHeader(e.unprotectedHeader).encrypt(e.key,{...e.options}),n={ciphertext:t.ciphertext,iv:t.iv,recipients:[{}],tag:t.tag};return t.aad&&(n.aad=t.aad),t.protected&&(n.protected=t.protected),t.unprotected&&(n.unprotected=t.unprotected),t.encrypted_key&&(n.recipients[0].encrypted_key=t.encrypted_key),t.header&&(n.recipients[0].header=t.header),n}let e;for(let t=0;t<this.#t.length;t++){let n=this.#t[t];if(!I(this.#n,this.#r,n.unprotectedHeader))throw new D(`JWE Protected, JWE Shared Unprotected and JWE Per-Recipient Header Parameter names must be disjoint`);let r={...this.#n,...this.#r,...n.unprotectedHeader},{alg:i}=r;if(typeof i!=`string`||!i)throw new D(`JWE "alg" (Algorithm) Header Parameter missing or invalid`);if(i===`dir`||i===`ECDH-ES`)throw new D(`"dir" and "ECDH-ES" alg may only be used with a single recipient`);if(typeof r.enc!=`string`||!r.enc)throw new D(`JWE "enc" (Encryption Algorithm) Header Parameter missing or invalid`);if(!e)e=r.enc;else if(e!==r.enc)throw new D(`JWE "enc" (Encryption Algorithm) Header Parameter must be the same for all recipients`);if(q(D,new Map,n.options.crit,this.#n,r),r.zip!==void 0&&r.zip!==`DEF`)throw new T(`Unsupported JWE "zip" (Compression Algorithm) Header Parameter value.`);if(r.zip!==void 0&&!this.#n?.zip)throw new D(`JWE "zip" (Compression Algorithm) Header Parameter MUST be in a protected header.`)}let t=M(e),n={ciphertext:``,recipients:[]};for(let r=0;r<this.#t.length;r++){let i=this.#t[r],a={};if(n.recipients.push(a),r===0){let e=await new Kt(this.#e).setAdditionalAuthenticatedData(this.#i).setContentEncryptionKey(t).setProtectedHeader(this.#n).setSharedUnprotectedHeader(this.#r).setUnprotectedHeader(i.unprotectedHeader).setKeyManagementParameters(i.keyManagementParameters).encrypt(i.key,{...i.options,[Oe]:!0});n.ciphertext=e.ciphertext,n.iv=e.iv,n.tag=e.tag,e.aad&&(n.aad=e.aad),e.protected&&(n.protected=e.protected),e.unprotected&&(n.unprotected=e.unprotected),a.encrypted_key=e.encrypted_key,e.header&&(a.header=e.header);continue}let o=i.unprotectedHeader?.alg||this.#n?.alg||this.#r?.alg;Y(o===`dir`?e:o,i.key,`encrypt`);let s=await U(i.key,o),{encryptedKey:c,parameters:l}=await Ft(o,e,s,t,i.keyManagementParameters);a.encrypted_key=p(c),(i.unprotectedHeader||l)&&(a.header={...i.unprotectedHeader,...l})}return n}};async function Yt(e,r,a){if(!F(e))throw new O(`Flattened JWS must be an object`);if(e.protected===void 0&&e.header===void 0)throw new O(`Flattened JWS must have either of the "protected" or "header" members`);if(e.protected!==void 0&&typeof e.protected!=`string`)throw new O(`JWS Protected Header incorrect type`);if(e.payload===void 0)throw new O(`JWS Payload missing`);if(typeof e.signature!=`string`)throw new O(`JWS Signature missing or incorrect type`);if(e.header!==void 0&&!F(e.header))throw new O(`JWS Unprotected Header incorrect type`);let o={};if(e.protected)try{let t=f(e.protected);o=JSON.parse(n.decode(t))}catch{throw new O(`JWS Protected Header is invalid`)}if(!I(o,e.header))throw new O(`JWS Protected and JWS Unprotected Header Parameter names must be disjoint`);let s={...o,...e.header},l=q(O,new Map([[`b64`,!0]]),a?.crit,o,s),u=!0;if(l.has(`b64`)&&(u=o.b64,typeof u!=`boolean`))throw new O(`The "b64" (base64url-encode payload) Header Parameter must be a boolean`);let{alg:d}=s;if(typeof d!=`string`||!d)throw new O(`JWS "alg" (Algorithm) Header Parameter missing or invalid`);let p=a&&It(`algorithms`,a.algorithms);if(p&&!p.has(d))throw new ie(`"alg" (Algorithm) Header Parameter value not allowed`);if(u){if(typeof e.payload!=`string`)throw new O(`JWS Payload must be a string`)}else if(typeof e.payload!=`string`&&!(e.payload instanceof Uint8Array))throw new O(`JWS Payload must be a string or an Uint8Array instance`);let m=!1;typeof r==`function`&&(r=await r(o,e),m=!0),Y(d,r,`verify`);let h=i(e.protected===void 0?new Uint8Array:c(e.protected),c(`.`),typeof e.payload==`string`?u?c(e.payload):t.encode(e.payload):e.payload),g=P(e.signature,`signature`,O),_=await U(r,d);if(!await Ze(d,_,g,h))throw new ue;let v;v=u?P(e.payload,`payload`,O):typeof e.payload==`string`?t.encode(e.payload):e.payload;let y={payload:v};return e.protected!==void 0&&(y.protectedHeader=o),e.header!==void 0&&(y.unprotectedHeader=e.header),m?{...y,key:_}:y}async function Xt(e,t,r){if(e instanceof Uint8Array&&(e=n.decode(e)),typeof e!=`string`)throw new O(`Compact JWS must be a string or Uint8Array`);let{0:i,1:a,2:o,length:s}=e.split(`.`);if(s!==3)throw new O(`Invalid Compact JWS`);let c=await Yt({payload:a,protected:i,signature:o},t,r),l={payload:c.payload,protectedHeader:c.protectedHeader};return typeof t==`function`?{...l,key:c.key}:l}async function Zt(e,t,n){if(!F(e))throw new O(`General JWS must be an object`);if(!Array.isArray(e.signatures)||!e.signatures.every(F))throw new O(`JWS Signatures missing or incorrect type`);for(let r of e.signatures)try{return await Yt({header:r.header,payload:e.payload,protected:r.protected,signature:r.signature},t,n)}catch{}throw new ue}const X=e=>Math.floor(e.getTime()/1e3),Qt=/^(\+|\-)? ?(\d+|\d+\.\d+) ?(seconds?|secs?|s|minutes?|mins?|m|hours?|hrs?|h|days?|d|weeks?|w|years?|yrs?|y)(?: (ago|from now))?$/i;function Z(e){let t=Qt.exec(e);if(!t||t[4]&&t[1])throw TypeError(`Invalid time period format`);let n=parseFloat(t[2]),r=t[3].toLowerCase(),i;switch(r){case`sec`:case`secs`:case`second`:case`seconds`:case`s`:i=Math.round(n);break;case`minute`:case`minutes`:case`min`:case`mins`:case`m`:i=Math.round(n*60);break;case`hour`:case`hours`:case`hr`:case`hrs`:case`h`:i=Math.round(n*3600);break;case`day`:case`days`:case`d`:i=Math.round(n*86400);break;case`week`:case`weeks`:case`w`:i=Math.round(n*604800);break;default:i=Math.round(n*31557600);break}return t[1]===`-`||t[4]===`ago`?-i:i}function Q(e,t){if(!Number.isFinite(t))throw TypeError(`Invalid ${e} input`);return t}const $t=e=>e.includes(`/`)?e.toLowerCase():`application/${e.toLowerCase()}`,en=(e,t)=>typeof e==`string`?t.includes(e):Array.isArray(e)?t.some(Set.prototype.has.bind(new Set(e))):!1;function tn(e,t,r={}){let i;try{i=JSON.parse(n.decode(t))}catch{}if(!F(i))throw new k(`JWT Claims Set must be a top-level JSON object`);let{typ:a}=r;if(a&&(typeof e.typ!=`string`||$t(e.typ)!==$t(a)))throw new w(`unexpected "typ" JWT header value`,i,`typ`,`check_failed`);let{requiredClaims:o=[],issuer:s,subject:c,audience:l,maxTokenAge:u}=r,d=[...o];u!==void 0&&d.push(`iat`),l!==void 0&&d.push(`aud`),c!==void 0&&d.push(`sub`),s!==void 0&&d.push(`iss`);for(let e of new Set(d.reverse()))if(!(e in i))throw new w(`missing required "${e}" claim`,i,e,`missing`);if(s&&!(Array.isArray(s)?s:[s]).includes(i.iss))throw new w(`unexpected "iss" claim value`,i,`iss`,`check_failed`);if(c&&i.sub!==c)throw new w(`unexpected "sub" claim value`,i,`sub`,`check_failed`);if(l&&!en(i.aud,typeof l==`string`?[l]:l))throw new w(`unexpected "aud" claim value`,i,`aud`,`check_failed`);let f;switch(typeof r.clockTolerance){case`string`:f=Z(r.clockTolerance);break;case`number`:f=r.clockTolerance;break;case`undefined`:f=0;break;default:throw TypeError(`Invalid clockTolerance option type`)}let{currentDate:p}=r,m=X(p||new Date);if((i.iat!==void 0||u)&&typeof i.iat!=`number`)throw new w(`"iat" claim must be a number`,i,`iat`,`invalid`);if(i.nbf!==void 0){if(typeof i.nbf!=`number`)throw new w(`"nbf" claim must be a number`,i,`nbf`,`invalid`);if(i.nbf>m+f)throw new w(`"nbf" claim timestamp check failed`,i,`nbf`,`check_failed`)}if(i.exp!==void 0){if(typeof i.exp!=`number`)throw new w(`"exp" claim must be a number`,i,`exp`,`invalid`);if(i.exp<=m-f)throw new re(`"exp" claim timestamp check failed`,i,`exp`,`check_failed`)}if(u){let e=m-i.iat,t=typeof u==`number`?u:Z(u);if(e-f>t)throw new re(`"iat" claim timestamp check failed (too far in the past)`,i,`iat`,`check_failed`);if(e<0-f)throw new w(`"iat" claim timestamp check failed (it should be in the past)`,i,`iat`,`check_failed`)}return i}var nn=class{#e;constructor(e){if(!F(e))throw TypeError(`JWT Claims Set MUST be an object`);this.#e=structuredClone(e)}data(){return t.encode(JSON.stringify(this.#e))}get iss(){return this.#e.iss}set iss(e){this.#e.iss=e}get sub(){return this.#e.sub}set sub(e){this.#e.sub=e}get aud(){return this.#e.aud}set aud(e){this.#e.aud=e}set jti(e){this.#e.jti=e}set nbf(e){typeof e==`number`?this.#e.nbf=Q(`setNotBefore`,e):e instanceof Date?this.#e.nbf=Q(`setNotBefore`,X(e)):this.#e.nbf=X(new Date)+Z(e)}set exp(e){typeof e==`number`?this.#e.exp=Q(`setExpirationTime`,e):e instanceof Date?this.#e.exp=Q(`setExpirationTime`,X(e)):this.#e.exp=X(new Date)+Z(e)}set iat(e){e===void 0?this.#e.iat=X(new Date):e instanceof Date?this.#e.iat=Q(`setIssuedAt`,X(e)):typeof e==`string`?this.#e.iat=Q(`setIssuedAt`,X(new Date)+Z(e)):this.#e.iat=Q(`setIssuedAt`,e)}};async function rn(e,t,n){let r=await Xt(e,t,n);if(r.protectedHeader.crit?.includes(`b64`)&&r.protectedHeader.b64===!1)throw new k(`JWTs MUST NOT use unencoded payload`);let i={payload:tn(r.protectedHeader,r.payload,n),protectedHeader:r.protectedHeader};return typeof t==`function`?{...i,key:r.key}:i}async function an(e,t,n){let r=await Wt(e,t,n),i=tn(r.protectedHeader,r.plaintext,n),{protectedHeader:a}=r;if(a.iss!==void 0&&a.iss!==i.iss)throw new w(`replicated "iss" claim header parameter mismatch`,i,`iss`,`mismatch`);if(a.sub!==void 0&&a.sub!==i.sub)throw new w(`replicated "sub" claim head