@phosphor-tools/phosphor-mcp 0.2.0-dev.pr85.19 → 0.2.0-rc.9
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/cli.mjs +2534 -1119
- package/dist/webapi-CxKOxXjo-B4HF1Noo.mjs +3 -0
- package/package.json +3 -3
|
@@ -0,0 +1,3 @@
|
|
|
1
|
+
#!/usr/bin/env node
|
|
2
|
+
var e=Object.defineProperty,t=(t,n)=>{let r={};for(var i in t)e(r,i,{get:t[i],enumerable:!0});return n||e(r,Symbol.toStringTag,{value:`Module`}),r};const n=new TextEncoder,r=new TextDecoder,i=2**32;function a(...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 o(e,t,n){if(t<0||t>=i)throw RangeError(`value must be >= 0 and <= ${i-1}. Received ${t}`);e.set([t>>>24,t>>>16,t>>>8,t&255],n)}function s(e){let t=Math.floor(e/i),n=e%i,r=new Uint8Array(8);return o(r,t,0),o(r,n,4),r}function c(e){let t=new Uint8Array(4);return o(t,e),t}function l(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 u(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 d(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 f=t({decode:()=>p,encode:()=>m});function p(e){if(Uint8Array.fromBase64)return Uint8Array.fromBase64(typeof e==`string`?e:r.decode(e),{alphabet:`base64url`});let t=e;t instanceof Uint8Array&&(t=r.decode(t)),t=t.replace(/-/g,`+`).replace(/_/g,`/`);try{return d(t)}catch{throw TypeError(`The input to be decoded is not correctly encoded.`)}}function m(e){let t=e;return typeof t==`string`&&(t=n.encode(t)),Uint8Array.prototype.toBase64?t.toBase64({alphabet:`base64url`,omitPadding:!0}):u(t).replace(/=/g,``).replace(/\+/g,`-`).replace(/\//g,`_`)}const h=(e,t=`algorithm.name`)=>TypeError(`CryptoKey does not support this operation, its ${t} must be ${e}`),g=(e,t)=>e.name===t;function _(e){return parseInt(e.name.slice(4),10)}function v(e,t){if(_(e.hash)!==t)throw h(`SHA-${t}`,`algorithm.hash`)}function y(e){switch(e){case`ES256`:return`P-256`;case`ES384`:return`P-384`;case`ES512`:return`P-521`;default:throw Error(`unreachable`)}}function ee(e,t){if(t&&!e.usages.includes(t))throw TypeError(`CryptoKey does not support this operation, its usages must include ${t}.`)}function te(e,t,n){switch(t){case`HS256`:case`HS384`:case`HS512`:if(!g(e.algorithm,`HMAC`))throw h(`HMAC`);v(e.algorithm,parseInt(t.slice(2),10));break;case`RS256`:case`RS384`:case`RS512`:if(!g(e.algorithm,`RSASSA-PKCS1-v1_5`))throw h(`RSASSA-PKCS1-v1_5`);v(e.algorithm,parseInt(t.slice(2),10));break;case`PS256`:case`PS384`:case`PS512`:if(!g(e.algorithm,`RSA-PSS`))throw h(`RSA-PSS`);v(e.algorithm,parseInt(t.slice(2),10));break;case`Ed25519`:case`EdDSA`:if(!g(e.algorithm,`Ed25519`))throw h(`Ed25519`);break;case`ML-DSA-44`:case`ML-DSA-65`:case`ML-DSA-87`:if(!g(e.algorithm,t))throw h(t);break;case`ES256`:case`ES384`:case`ES512`:{if(!g(e.algorithm,`ECDSA`))throw h(`ECDSA`);let n=y(t);if(e.algorithm.namedCurve!==n)throw h(n,`algorithm.namedCurve`);break}default:throw TypeError(`CryptoKey does not support this operation`)}ee(e,n)}function b(e,t,n){switch(t){case`A128GCM`:case`A192GCM`:case`A256GCM`:{if(!g(e.algorithm,`AES-GCM`))throw h(`AES-GCM`);let n=parseInt(t.slice(1,4),10);if(e.algorithm.length!==n)throw h(n,`algorithm.length`);break}case`A128KW`:case`A192KW`:case`A256KW`:{if(!g(e.algorithm,`AES-KW`))throw h(`AES-KW`);let n=parseInt(t.slice(1,4),10);if(e.algorithm.length!==n)throw h(n,`algorithm.length`);break}case`ECDH`:switch(e.algorithm.name){case`ECDH`:case`X25519`:break;default:throw h(`ECDH or X25519`)}break;case`PBES2-HS256+A128KW`:case`PBES2-HS384+A192KW`:case`PBES2-HS512+A256KW`:if(!g(e.algorithm,`PBKDF2`))throw h(`PBKDF2`);break;case`RSA-OAEP`:case`RSA-OAEP-256`:case`RSA-OAEP-384`:case`RSA-OAEP-512`:if(!g(e.algorithm,`RSA-OAEP`))throw h(`RSA-OAEP`);v(e.algorithm,parseInt(t.slice(9),10)||1);break;default:throw TypeError(`CryptoKey does not support this operation`)}ee(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),ne=(e,t,...n)=>x(`Key for the ${e} algorithm must be `,t,...n);var re=t({JOSEAlgNotAllowed:()=>T,JOSEError:()=>C,JOSENotSupported:()=>E,JWEDecryptionFailed:()=>D,JWEInvalid:()=>O,JWKInvalid:()=>ae,JWKSInvalid:()=>oe,JWKSMultipleMatchingKeys:()=>ce,JWKSNoMatchingKey:()=>se,JWKSTimeout:()=>le,JWSInvalid:()=>k,JWSSignatureVerificationFailed:()=>ue,JWTClaimValidationFailed:()=>w,JWTExpired:()=>ie,JWTInvalid:()=>A}),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}},ie=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}},T=class extends C{static code=`ERR_JOSE_ALG_NOT_ALLOWED`;code=`ERR_JOSE_ALG_NOT_ALLOWED`},E=class extends C{static code=`ERR_JOSE_NOT_SUPPORTED`;code=`ERR_JOSE_NOT_SUPPORTED`},D=class extends C{static code=`ERR_JWE_DECRYPTION_FAILED`;code=`ERR_JWE_DECRYPTION_FAILED`;constructor(e=`decryption operation failed`,t){super(e,t)}},O=class extends C{static code=`ERR_JWE_INVALID`;code=`ERR_JWE_INVALID`},k=class extends C{static code=`ERR_JWS_INVALID`;code=`ERR_JWS_INVALID`},A=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 j(e){if(!M(e))throw Error(`CryptoKey instance expected`)}const M=e=>{if(e?.[Symbol.toStringTag]===`CryptoKey`)return!0;try{return e instanceof CryptoKey}catch{return!1}},N=e=>e?.[Symbol.toStringTag]===`KeyObject`,de=e=>M(e)||N(e);function fe(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 E(`Unsupported JWE Algorithm: ${e}`)}}const P=e=>crypto.getRandomValues(new Uint8Array(fe(e)>>3));function F(e,t){let n=e.byteLength<<3;if(n!==t)throw new O(`Invalid Content Encryption Key length. Expected ${t} bits, got ${n} bits`)}function pe(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 E(`Unsupported JWE Algorithm: ${e}`)}}const me=e=>crypto.getRandomValues(new Uint8Array(pe(e)>>3));function he(e,t){if(t.length<<3!==pe(e))throw new O(`Invalid Initialization Vector length`)}async function ge(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 _e(e,t,n){return new Uint8Array((await crypto.subtle.sign(`HMAC`,e,t)).slice(0,n>>3))}async function ve(e,t,n,r,i){let{encKey:o,macKey:c,keySize:l}=await ge(e,n,`encrypt`),u=new Uint8Array(await crypto.subtle.encrypt({iv:r,name:`AES-CBC`},o,t));return{ciphertext:u,tag:await _e(c,a(i,r,u,s(i.length<<3)),l),iv:r}}async function ye(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 be(e,t,n,r,i,o){let{encKey:c,macKey:l,keySize:u}=await ge(e,t,`decrypt`),d=await _e(l,a(o,r,n,s(o.length<<3)),u),f;try{f=await ye(i,d)}catch{}if(!f)throw new D;let p;try{p=new Uint8Array(await crypto.subtle.decrypt({iv:r,name:`AES-CBC`},c,n))}catch{}if(!p)throw new D;return p}async function xe(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 Se(e,t,n,r,i,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,a(n,i)))}catch{throw new D}}const Ce=`Unsupported JWE Content Encryption Algorithm`;async function we(e,t,n,r,i){if(!M(n)&&!(n instanceof Uint8Array))throw TypeError(S(n,`CryptoKey`,`KeyObject`,`Uint8Array`,`JSON Web Key`));switch(r?he(e,r):r=me(e),e){case`A128CBC-HS256`:case`A192CBC-HS384`:case`A256CBC-HS512`:return n instanceof Uint8Array&&F(n,parseInt(e.slice(-3),10)),ve(e,t,n,r,i);case`A128GCM`:case`A192GCM`:case`A256GCM`:return n instanceof Uint8Array&&F(n,parseInt(e.slice(1,4),10)),xe(e,t,n,r,i);default:throw new E(Ce)}}async function Te(e,t,n,r,i,a){if(!M(t)&&!(t instanceof Uint8Array))throw TypeError(S(t,`CryptoKey`,`KeyObject`,`Uint8Array`,`JSON Web Key`));if(!r)throw new O(`JWE Initialization Vector missing`);if(!i)throw new O(`JWE Authentication Tag missing`);switch(he(e,r),e){case`A128CBC-HS256`:case`A192CBC-HS384`:case`A256CBC-HS512`:return t instanceof Uint8Array&&F(t,parseInt(e.slice(-3),10)),be(e,t,n,r,i,a);case`A128GCM`:case`A192GCM`:case`A256GCM`:return t instanceof Uint8Array&&F(t,parseInt(e.slice(1,4),10)),Se(e,t,n,r,i,a);default:throw new E(Ce)}}const Ee=Symbol();function I(e,t){if(e)throw TypeError(`${t} can only be called once`)}function L(e,t,n){try{return p(e)}catch{throw new n(`Failed to base64url decode the ${t}`)}}async function De(e,t){let n=`SHA-${e.slice(-3)}`;return new Uint8Array(await crypto.subtle.digest(n,t))}const Oe=e=>typeof e==`object`&&!!e;function R(e){if(!Oe(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 z(...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 B=e=>R(e)&&typeof e.kty==`string`,ke=e=>e.kty!==`oct`&&(e.kty===`AKP`&&typeof e.priv==`string`||typeof e.d==`string`),Ae=e=>e.kty!==`oct`&&e.d===void 0&&e.priv===void 0,je=e=>e.kty===`oct`&&typeof e.k==`string`;function Me(e,t){if(e.algorithm.length!==parseInt(t.slice(1,4),10))throw TypeError(`Invalid key size for alg: ${t}`)}function Ne(e,t,n){return e instanceof Uint8Array?crypto.subtle.importKey(`raw`,e,`AES-KW`,!0,[n]):(b(e,t,n),e)}async function Pe(e,t,n){let r=await Ne(t,e,`wrapKey`);Me(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 Fe(e,t,n){let r=await Ne(t,e,`unwrapKey`);Me(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 Ie(e){return a(c(e.length),e)}async function Le(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(c(t),0),r.set(e,4),r.set(n,4+e.length);let i=await De(`sha256`,r);a.set(i,(t-1)*32)}return a.slice(0,r)}async function Re(e,t,n,r,i=new Uint8Array,o=new Uint8Array){b(e,`ECDH`),b(t,`ECDH`,`deriveBits`);let s=a(Ie(l(n)),Ie(i),Ie(o),c(r),new Uint8Array);return Le(new Uint8Array(await crypto.subtle.deriveBits({name:e.algorithm.name,public:e},t,ze(e))),r,s)}function ze(e){return e.algorithm.name===`X25519`?256:Math.ceil(parseInt(e.algorithm.namedCurve.slice(-3),10)/8)<<3}function Be(e){switch(e.algorithm.namedCurve){case`P-256`:case`P-384`:case`P-521`:return!0;default:return e.algorithm.name===`X25519`}}function Ve(e,t){return e instanceof Uint8Array?crypto.subtle.importKey(`raw`,e,`PBKDF2`,!1,[`deriveBits`]):(b(e,t,`deriveBits`),e)}const He=(e,t)=>a(l(e),Uint8Array.of(0),t);async function Ue(e,t,n,r){if(!(e instanceof Uint8Array)||e.length<8)throw new O(`PBES2 Salt Input must be 8 or more octets`);let i=He(t,e),a=parseInt(t.slice(13,16),10),o={hash:`SHA-${t.slice(8,11)}`,iterations:n,name:`PBKDF2`,salt:i},s=await Ve(r,t);return new Uint8Array(await crypto.subtle.deriveBits(o,s,a))}async function We(e,t,n,r=2048,i=crypto.getRandomValues(new Uint8Array(16))){let a=await Ue(i,e,r,t);return{encryptedKey:await Pe(e.slice(-6),a,n),p2c:r,p2s:m(i)}}async function Ge(e,t,n,r,i){let a=await Ue(i,e,r,t);return Fe(e.slice(-6),a,n)}function Ke(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 qe(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 E(`alg ${e} is not supported either by JOSE or your javascript runtime`)}}async function Je(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 te(t,e,n),t}async function Ye(e,t,n){let r=await Je(e,t,`sign`);Ke(e,r);let i=await crypto.subtle.sign(qe(e,r.algorithm),r,n);return new Uint8Array(i)}async function Xe(e,t,n,r){let i=await Je(e,t,`verify`);Ke(e,i);let a=qe(e,i.algorithm);try{return await crypto.subtle.verify(a,i,n,r)}catch{return!1}}const Ze=e=>{switch(e){case`RSA-OAEP`:case`RSA-OAEP-256`:case`RSA-OAEP-384`:case`RSA-OAEP-512`:return`RSA-OAEP`;default:throw new E(`alg ${e} is not supported either by JOSE or your javascript runtime`)}};async function Qe(e,t,n){return b(t,e,`encrypt`),Ke(e,t),new Uint8Array(await crypto.subtle.encrypt(Ze(e),t,n))}async function $e(e,t,n){return b(t,e,`decrypt`),Ke(e,t),new Uint8Array(await crypto.subtle.decrypt(Ze(e),t,n))}const et=`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 E(et)}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 E(et)}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 E(et)}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 E(et)}break;default:throw new E(`Invalid or unsupported JWK "kty" (Key Type) Parameter value`)}return{algorithm:t,keyUsages:n}}async function nt(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 rt=async(e,t,n,r=!1)=>{H||=new WeakMap;let i=H.get(e);if(i?.[n])return i[n];let a=await nt({...t,alg:n});return r&&Object.freeze(e),i?i[n]=a:H.set(e,{[n]:a}),a},it=(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||M(e))return e;if(N(e)){if(e.type===`secret`)return e.export();if(`toCryptoKey`in e&&typeof e.toCryptoKey==`function`)try{return it(e,t)}catch(e){if(e instanceof TypeError)throw e}return rt(e,e.export({format:`jwk`}),t)}if(B(e))return e.k?p(e.k):rt(e,e,t,!0);throw Error(`unreachable`)}const at=(e,t)=>`-----BEGIN ${t}-----\n${(e.match(/.{1,64}/g)||[]).join(`
|
|
3
|
+
`)}\n-----END ${t}-----`,ot=async(e,t,n)=>{if(N(n)){if(n.type!==e)throw TypeError(`key is not a ${e} key`);return n.export({format:`pem`,type:t})}if(!M(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 at(u(new Uint8Array(await crypto.subtle.exportKey(t,n))),`${e.toUpperCase()} KEY`)},st=e=>ot(`public`,`spki`,e),ct=e=>ot(`private`,`pkcs8`,e),lt=(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},ut=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},dt=(e,t=1)=>{if(t<=0)return;e.pos++;let n=W(e);e.pos+=n,t>1&&dt(e,t-1)},G=(e,t,n)=>{if(e.data[e.pos++]!==t)throw Error(n)},ft=(e,t)=>{let n=e.data.subarray(e.pos,e.pos+t);return e.pos+=t,n},pt=e=>(G(e,6,`Expected algorithm OID`),ft(e,W(e)));function mt(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 ht(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 gt=e=>{let t=pt(e);if(lt(t,[43,101,110]))return`X25519`;if(!lt(t,[42,134,72,206,61,2,1]))throw Error(`Unsupported key algorithm`);G(e,6,`Expected curve OID`);let n=ft(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(lt(n,t))return e;throw Error(`Unsupported named curve`)},_t=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 E(`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 E(`Invalid or unsupported "alg" (Algorithm) value`)}return crypto.subtle.importKey(e,t,i,r?.extractable??!!o,a)},vt=(e,t)=>d(e.replace(t,``)),yt=(e,t,n)=>{let r=vt(e,/(?:-----(?:BEGIN|END) PRIVATE KEY-----|\s)/g),i=n;return t?.startsWith?.(`ECDH-ES`)&&(i||={},i.getNamedCurve=e=>{let t=ut(e);return mt(t),gt(t)}),_t(`pkcs8`,r,t,i)},bt=(e,t,n)=>{let r=vt(e,/(?:-----(?:BEGIN|END) PUBLIC KEY-----|\s)/g),i=n;return t?.startsWith?.(`ECDH-ES`)&&(i||={},i.getNamedCurve=e=>{let t=ut(e);return ht(t),gt(t)}),_t(`spki`,r,t,i)};function xt(e){let t=ut(e);G(t,48,`Invalid certificate structure`),W(t),G(t,48,`Invalid tbsCertificate structure`),W(t),e[t.pos]===160?dt(t,6):dt(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 St(e){return xt(vt(e,/(?:-----(?:BEGIN|END) CERTIFICATE-----|\s)/g))}const Ct=(e,t,n)=>{let r;try{r=St(e)}catch(e){throw TypeError(`Failed to parse the X.509 certificate`,{cause:e})}return bt(at(u(r),`PUBLIC KEY`),t,n)};async function wt(e,t,n){if(typeof e!=`string`||e.indexOf(`-----BEGIN PUBLIC KEY-----`)!==0)throw TypeError(`"spki" must be SPKI formatted string`);return bt(e,t,n)}async function Tt(e,t,n){if(typeof e!=`string`||e.indexOf(`-----BEGIN CERTIFICATE-----`)!==0)throw TypeError(`"x509" must be X.509 formatted string`);return Ct(e,t,n)}async function Et(e,t,n){if(typeof e!=`string`||e.indexOf(`-----BEGIN PRIVATE KEY-----`)!==0)throw TypeError(`"pkcs8" must be PKCS#8 formatted string`);return yt(e,t,n)}async function Dt(e,t,n){if(!R(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 p(e.k);case`RSA`:if(`oth`in e&&e.oth!==void 0)throw new E(`RSA JWK "oth" (Other Primes Info) Parameter value is not supported`);return nt({...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 nt({...e,ext:r});case`EC`:case`OKP`:return nt({...e,alg:t,ext:r});default:throw new E(`Unsupported "kty" (Key Type) Parameter value`)}}async function Ot(e){if(N(e))if(e.type===`secret`)e=e.export();else return e.export({format:`jwk`});if(e instanceof Uint8Array)return{kty:`oct`,k:m(e)};if(!M(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 kt(e){return st(e)}async function At(e){return ct(e)}async function jt(e){return Ot(e)}async function Mt(e,t,n,r){let i=await we(e.slice(0,7),n,t,r,new Uint8Array);return{encryptedKey:i.ciphertext,iv:m(i.iv),tag:m(i.tag)}}async function Nt(e,t,n,r,i){return Te(e.slice(0,7),t,n,r,i,new Uint8Array)}const Pt=`Invalid or unsupported "alg" (JWE Algorithm) header value`;function K(e){if(e===void 0)throw new O(`JWE Encrypted Key missing`)}async function Ft(e,t,n,r,i){switch(e){case`dir`:if(n!==void 0)throw new O(`Encountered unexpected JWE Encrypted Key`);return t;case`ECDH-ES`:if(n!==void 0)throw new O(`Encountered unexpected JWE Encrypted Key`);case`ECDH-ES+A128KW`:case`ECDH-ES+A192KW`:case`ECDH-ES+A256KW`:{if(!R(r.epk))throw new O(`JOSE Header "epk" (Ephemeral Public Key) missing or invalid`);if(j(t),!Be(t))throw new E(`ECDH with the provided key is not allowed or not supported by your javascript runtime`);let i=await Dt(r.epk,e);j(i);let a,o;if(r.apu!==void 0){if(typeof r.apu!=`string`)throw new O(`JOSE Header "apu" (Agreement PartyUInfo) invalid`);a=L(r.apu,`apu`,O)}if(r.apv!==void 0){if(typeof r.apv!=`string`)throw new O(`JOSE Header "apv" (Agreement PartyVInfo) invalid`);o=L(r.apv,`apv`,O)}let s=await Re(i,t,e===`ECDH-ES`?r.enc:e,e===`ECDH-ES`?fe(r.enc):parseInt(e.slice(-5,-2),10),a,o);return e===`ECDH-ES`?s:(K(n),Fe(e.slice(-6),s,n))}case`RSA-OAEP`:case`RSA-OAEP-256`:case`RSA-OAEP-384`:case`RSA-OAEP-512`:return K(n),j(t),$e(e,t,n);case`PBES2-HS256+A128KW`:case`PBES2-HS384+A192KW`:case`PBES2-HS512+A256KW`:{if(K(n),typeof r.p2c!=`number`)throw new O(`JOSE Header "p2c" (PBES2 Count) missing or invalid`);let a=i?.maxPBES2Count||1e4;if(r.p2c>a)throw new O(`JOSE Header "p2c" (PBES2 Count) out is of acceptable bounds`);if(typeof r.p2s!=`string`)throw new O(`JOSE Header "p2s" (PBES2 Salt) missing or invalid`);let o;return o=L(r.p2s,`p2s`,O),Ge(e,t,n,r.p2c,o)}case`A128KW`:case`A192KW`:case`A256KW`:return K(n),Fe(e,t,n);case`A128GCMKW`:case`A192GCMKW`:case`A256GCMKW`:{if(K(n),typeof r.iv!=`string`)throw new O(`JOSE Header "iv" (Initialization Vector) missing or invalid`);if(typeof r.tag!=`string`)throw new O(`JOSE Header "tag" (Authentication Tag) missing or invalid`);let i;i=L(r.iv,`iv`,O);let a;return a=L(r.tag,`tag`,O),Nt(e,t,n,i,a)}default:throw new E(Pt)}}async function It(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(j(n),!Be(n))throw new E(`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:p,kty:h}=await jt(u),g=await Re(n,u,e===`ECDH-ES`?t:e,e===`ECDH-ES`?fe(t):parseInt(e.slice(-5,-2),10),c,l);if(o={epk:{x:d,crv:p,kty:h}},h===`EC`&&(o.epk.y=f),c&&(o.apu=m(c)),l&&(o.apv=m(l)),e===`ECDH-ES`){s=g;break}s=r||P(t),a=await Pe(e.slice(-6),g,s);break}case`RSA-OAEP`:case`RSA-OAEP-256`:case`RSA-OAEP-384`:case`RSA-OAEP-512`:s=r||P(t),j(n),a=await Qe(e,n,s);break;case`PBES2-HS256+A128KW`:case`PBES2-HS384+A192KW`:case`PBES2-HS512+A256KW`:{s=r||P(t);let{p2c:c,p2s:l}=i;({encryptedKey:a,...o}=await We(e,n,s,c,l));break}case`A128KW`:case`A192KW`:case`A256KW`:s=r||P(t),a=await Pe(e,n,s);break;case`A128GCMKW`:case`A192GCMKW`:case`A256GCMKW`:{s=r||P(t);let{iv:c}=i;({encryptedKey:a,...o}=await Mt(e,n,s,c));break}default:throw new E(Pt)}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 E(`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 Lt(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],Rt=(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},zt=(e,t,n)=>{if(!(t instanceof Uint8Array)){if(B(t)){if(je(t)&&Rt(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(!de(t))throw TypeError(ne(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"`)}},Bt=(e,t,n)=>{if(B(t))switch(n){case`decrypt`:case`sign`:if(ke(t)&&Rt(e,t,n))return;throw TypeError(`JSON Web Key for this operation must be a private JWK`);case`encrypt`:case`verify`:if(Ae(t)&&Rt(e,t,n))return;throw TypeError(`JSON Web Key for this operation must be a public JWK`)}if(!de(t))throw TypeError(ne(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`:zt(e,t,n);break;default:Bt(e,t,n)}}function Vt(e){if(globalThis[e]===void 0)throw new E(`JWE "zip" (Compression Algorithm) Header Parameter requires the ${e} API.`)}async function Ht(e){Vt(`CompressionStream`);let t=new CompressionStream(`deflate-raw`),n=t.writable.getWriter();n.write(e).catch(()=>{}),n.close().catch(()=>{});let r=[],i=t.readable.getReader();for(;;){let{value:e,done:t}=await i.read();if(t)break;r.push(e)}return a(...r)}async function Ut(e,t){Vt(`DecompressionStream`);let n=new DecompressionStream(`deflate-raw`),r=n.writable.getWriter();r.write(e).catch(()=>{}),r.close().catch(()=>{});let i=[],o=0,s=n.readable.getReader();for(;;){let{value:e,done:n}=await s.read();if(n)break;if(i.push(e),o+=e.byteLength,t!==1/0&&o>t)throw new O(`Decompressed plaintext exceeded the configured limit`)}return a(...i)}async function Wt(e,t,n){if(!R(e))throw new O(`Flattened JWE must be an object`);if(e.protected===void 0&&e.header===void 0&&e.unprotected===void 0)throw new O(`JOSE Header missing`);if(e.iv!==void 0&&typeof e.iv!=`string`)throw new O(`JWE Initialization Vector incorrect type`);if(typeof e.ciphertext!=`string`)throw new O(`JWE Ciphertext missing or incorrect type`);if(e.tag!==void 0&&typeof e.tag!=`string`)throw new O(`JWE Authentication Tag incorrect type`);if(e.protected!==void 0&&typeof e.protected!=`string`)throw new O(`JWE Protected Header incorrect type`);if(e.encrypted_key!==void 0&&typeof e.encrypted_key!=`string`)throw new O(`JWE Encrypted Key incorrect type`);if(e.aad!==void 0&&typeof e.aad!=`string`)throw new O(`JWE AAD incorrect type`);if(e.header!==void 0&&!R(e.header))throw new O(`JWE Shared Unprotected Header incorrect type`);if(e.unprotected!==void 0&&!R(e.unprotected))throw new O(`JWE Per-Recipient Unprotected Header incorrect type`);let i;if(e.protected)try{let t=p(e.protected);i=JSON.parse(r.decode(t))}catch{throw new O(`JWE Protected Header is invalid`)}if(!z(i,e.header,e.unprotected))throw new O(`JWE Protected, JWE Unprotected Header, and JWE Per-Recipient Unprotected Header Parameter names must be disjoint`);let o={...i,...e.header,...e.unprotected};if(q(O,new Map,n?.crit,i,o),o.zip!==void 0&&o.zip!==`DEF`)throw new E(`Unsupported JWE "zip" (Compression Algorithm) Header Parameter value.`);if(o.zip!==void 0&&!i?.zip)throw new O(`JWE "zip" (Compression Algorithm) Header Parameter MUST be in a protected header.`);let{alg:s,enc:c}=o;if(typeof s!=`string`||!s)throw new O(`missing JWE Algorithm (alg) in JWE Header`);if(typeof c!=`string`||!c)throw new O(`missing JWE Encryption Algorithm (enc) in JWE Header`);let u=n&&Lt(`keyManagementAlgorithms`,n.keyManagementAlgorithms),d=n&&Lt(`contentEncryptionAlgorithms`,n.contentEncryptionAlgorithms);if(u&&!u.has(s)||!u&&s.startsWith(`PBES2`))throw new T(`"alg" (Algorithm) Header Parameter value not allowed`);if(d&&!d.has(c))throw new T(`"enc" (Encryption Algorithm) Header Parameter value not allowed`);let f;e.encrypted_key!==void 0&&(f=L(e.encrypted_key,`encrypted_key`,O));let m=!1;typeof t==`function`&&(t=await t(i,e),m=!0),Y(s===`dir`?c:s,t,`decrypt`);let h=await U(t,s),g;try{g=await Ft(s,h,f,o,n)}catch(e){if(e instanceof TypeError||e instanceof O||e instanceof E)throw e;g=P(c)}let _,v;e.iv!==void 0&&(_=L(e.iv,`iv`,O)),e.tag!==void 0&&(v=L(e.tag,`tag`,O));let y=e.protected===void 0?new Uint8Array:l(e.protected),ee;ee=e.aad===void 0?y:a(y,l(`.`),l(e.aad));let te=L(e.ciphertext,`ciphertext`,O),b=await Te(c,g,te,_,v,ee),x={plaintext:b};if(o.zip===`DEF`){let e=n?.maxDecompressedLength??25e4;if(e===0)throw new E(`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`);x.plaintext=await Ut(b,e).catch(e=>{throw e instanceof O?e:new O(`Failed to decompress plaintext`,{cause:e})})}return e.protected!==void 0&&(x.protectedHeader=i),e.aad!==void 0&&(x.additionalAuthenticatedData=L(e.aad,`aad`,O)),e.unprotected!==void 0&&(x.sharedUnprotectedHeader=e.unprotected),e.header!==void 0&&(x.unprotectedHeader=e.header),m?{...x,key:h}:x}async function Gt(e,t,n){if(e instanceof Uint8Array&&(e=r.decode(e)),typeof e!=`string`)throw new O(`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 O(`Invalid Compact JWE`);let u=await Wt({ciphertext:s,iv:o||void 0,protected:i,tag:c||void 0,encrypted_key:a||void 0},t,n),d={plaintext:u.plaintext,protectedHeader:u.protectedHeader};return typeof t==`function`?{...d,key:u.key}:d}async function Kt(e,t,n){if(!R(e))throw new O(`General JWE must be an object`);if(!Array.isArray(e.recipients)||!e.recipients.every(R))throw new O(`JWE Recipients missing or incorrect type`);if(!e.recipients.length)throw new O(`JWE Recipients has no members`);for(let r of e.recipients)try{return await Wt({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 D}var qt=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 I(this.#s,`setKeyManagementParameters`),this.#s=e,this}setProtectedHeader(e){return I(this.#t,`setProtectedHeader`),this.#t=e,this}setSharedUnprotectedHeader(e){return I(this.#n,`setSharedUnprotectedHeader`),this.#n=e,this}setUnprotectedHeader(e){return I(this.#r,`setUnprotectedHeader`),this.#r=e,this}setAdditionalAuthenticatedData(e){return this.#i=e,this}setContentEncryptionKey(e){return I(this.#a,`setContentEncryptionKey`),this.#a=e,this}setInitializationVector(e){return I(this.#o,`setInitializationVector`),this.#o=e,this}async encrypt(e,t){if(!this.#t&&!this.#r&&!this.#n)throw new O(`either setProtectedHeader, setUnprotectedHeader, or sharedUnprotectedHeader must be called before #encrypt()`);if(!z(this.#t,this.#r,this.#n))throw new O(`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(O,new Map,t?.crit,this.#t,n),n.zip!==void 0&&n.zip!==`DEF`)throw new E(`Unsupported JWE "zip" (Compression Algorithm) Header Parameter value.`);if(n.zip!==void 0&&!this.#t?.zip)throw new O(`JWE "zip" (Compression Algorithm) Header Parameter MUST be in a protected header.`);let{alg:r,enc:i}=n;if(typeof r!=`string`||!r)throw new O(`JWE "alg" (Algorithm) Header Parameter missing or invalid`);if(typeof i!=`string`||!i)throw new O(`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`?i:r,e,`encrypt`);let s;{let n,a=await U(e,r);({cek:s,encryptedKey:o,parameters:n}=await It(r,i,a,this.#a,this.#s)),n&&(t&&Ee in t?this.#r?this.#r={...this.#r,...n}:this.setUnprotectedHeader(n):this.#t?this.#t={...this.#t,...n}:this.setProtectedHeader(n))}let c,u,d,f;if(this.#t?(u=m(JSON.stringify(this.#t)),d=l(u)):(u=``,d=new Uint8Array),this.#i){f=m(this.#i);let e=l(f);c=a(d,l(`.`),e)}else c=d;let p=this.#e;n.zip===`DEF`&&(p=await Ht(p).catch(e=>{throw new O(`Failed to compress plaintext`,{cause:e})}));let{ciphertext:h,tag:g,iv:_}=await we(i,p,s,this.#o,c),v={ciphertext:m(h)};return _&&(v.iv=m(_)),g&&(v.tag=m(g)),o&&(v.encrypted_key=m(o)),f&&(v.aad=f),this.#t&&(v.protected=u),this.#n&&(v.unprotected=this.#n),this.#r&&(v.header=this.#r),v}},Jt=class{#e;unprotectedHeader;keyManagementParameters;key;options;constructor(e,t,n){this.#e=e,this.key=t,this.options=n}setUnprotectedHeader(e){return I(this.unprotectedHeader,`setUnprotectedHeader`),this.unprotectedHeader=e,this}setKeyManagementParameters(e){return I(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}},Yt=class{#e;#t=[];#n;#r;#i;constructor(e){this.#e=e}addRecipient(e,t){let n=new Jt(this,e,{crit:t?.crit});return this.#t.push(n),n}setProtectedHeader(e){return I(this.#n,`setProtectedHeader`),this.#n=e,this}setSharedUnprotectedHeader(e){return I(this.#r,`setSharedUnprotectedHeader`),this.#r=e,this}setAdditionalAuthenticatedData(e){return this.#i=e,this}async encrypt(){if(!this.#t.length)throw new O(`at least one recipient must be added`);if(this.#t.length===1){let[e]=this.#t,t=await new qt(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(!z(this.#n,this.#r,n.unprotectedHeader))throw new O(`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 O(`JWE "alg" (Algorithm) Header Parameter missing or invalid`);if(i===`dir`||i===`ECDH-ES`)throw new O(`"dir" and "ECDH-ES" alg may only be used with a single recipient`);if(typeof r.enc!=`string`||!r.enc)throw new O(`JWE "enc" (Encryption Algorithm) Header Parameter missing or invalid`);if(!e)e=r.enc;else if(e!==r.enc)throw new O(`JWE "enc" (Encryption Algorithm) Header Parameter must be the same for all recipients`);if(q(O,new Map,n.options.crit,this.#n,r),r.zip!==void 0&&r.zip!==`DEF`)throw new E(`Unsupported JWE "zip" (Compression Algorithm) Header Parameter value.`);if(r.zip!==void 0&&!this.#n?.zip)throw new O(`JWE "zip" (Compression Algorithm) Header Parameter MUST be in a protected header.`)}let t=P(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 qt(this.#e).setAdditionalAuthenticatedData(this.#i).setContentEncryptionKey(t).setProtectedHeader(this.#n).setSharedUnprotectedHeader(this.#r).setUnprotectedHeader(i.unprotectedHeader).setKeyManagementParameters(i.keyManagementParameters).encrypt(i.key,{...i.options,[Ee]:!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 It(o,e,s,t,i.keyManagementParameters);a.encrypted_key=m(c),(i.unprotectedHeader||l)&&(a.header={...i.unprotectedHeader,...l})}return n}};async function Xt(e,t,i){if(!R(e))throw new k(`Flattened JWS must be an object`);if(e.protected===void 0&&e.header===void 0)throw new k(`Flattened JWS must have either of the "protected" or "header" members`);if(e.protected!==void 0&&typeof e.protected!=`string`)throw new k(`JWS Protected Header incorrect type`);if(e.payload===void 0)throw new k(`JWS Payload missing`);if(typeof e.signature!=`string`)throw new k(`JWS Signature missing or incorrect type`);if(e.header!==void 0&&!R(e.header))throw new k(`JWS Unprotected Header incorrect type`);let o={};if(e.protected)try{let t=p(e.protected);o=JSON.parse(r.decode(t))}catch{throw new k(`JWS Protected Header is invalid`)}if(!z(o,e.header))throw new k(`JWS Protected and JWS Unprotected Header Parameter names must be disjoint`);let s={...o,...e.header},c=q(k,new Map([[`b64`,!0]]),i?.crit,o,s),u=!0;if(c.has(`b64`)&&(u=o.b64,typeof u!=`boolean`))throw new k(`The "b64" (base64url-encode payload) Header Parameter must be a boolean`);let{alg:d}=s;if(typeof d!=`string`||!d)throw new k(`JWS "alg" (Algorithm) Header Parameter missing or invalid`);let f=i&&Lt(`algorithms`,i.algorithms);if(f&&!f.has(d))throw new T(`"alg" (Algorithm) Header Parameter value not allowed`);if(u){if(typeof e.payload!=`string`)throw new k(`JWS Payload must be a string`)}else if(typeof e.payload!=`string`&&!(e.payload instanceof Uint8Array))throw new k(`JWS Payload must be a string or an Uint8Array instance`);let m=!1;typeof t==`function`&&(t=await t(o,e),m=!0),Y(d,t,`verify`);let h=a(e.protected===void 0?new Uint8Array:l(e.protected),l(`.`),typeof e.payload==`string`?u?l(e.payload):n.encode(e.payload):e.payload),g=L(e.signature,`signature`,k),_=await U(t,d);if(!await Xe(d,_,g,h))throw new ue;let v;v=u?L(e.payload,`payload`,k):typeof e.payload==`string`?n.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 Zt(e,t,n){if(e instanceof Uint8Array&&(e=r.decode(e)),typeof e!=`string`)throw new k(`Compact JWS must be a string or Uint8Array`);let{0:i,1:a,2:o,length:s}=e.split(`.`);if(s!==3)throw new k(`Invalid Compact JWS`);let c=await Xt({payload:a,protected:i,signature:o},t,n),l={payload:c.payload,protectedHeader:c.protectedHeader};return typeof t==`function`?{...l,key:c.key}:l}async function Qt(e,t,n){if(!R(e))throw new k(`General JWS must be an object`);if(!Array.isArray(e.signatures)||!e.signatures.every(R))throw new k(`JWS Signatures missing or incorrect type`);for(let r of e.signatures)try{return await Xt({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),$t=3600,en=$t*24;en*7,en*365.25;const tn=/^(\+|\-)? ?(\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=tn.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*$t);break;case`day`:case`days`:case`d`:i=Math.round(n*en);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 nn=e=>e.includes(`/`)?e.toLowerCase():`application/${e.toLowerCase()}`,rn=(e,t)=>typeof e==`string`?t.includes(e):Array.isArray(e)?t.some(Set.prototype.has.bind(new Set(e))):!1;function an(e,t,n={}){let i;try{i=JSON.parse(r.decode(t))}catch{}if(!R(i))throw new A(`JWT Claims Set must be a top-level JSON object`);let{typ:a}=n;if(a&&(typeof e.typ!=`string`||nn(e.typ)!==nn(a)))throw new w(`unexpected "typ" JWT header value`,i,`typ`,`check_failed`);let{requiredClaims:o=[],issuer:s,subject:c,audience:l,maxTokenAge:u}=n,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&&!rn(i.aud,typeof l==`string`?[l]:l))throw new w(`unexpected "aud" claim value`,i,`aud`,`check_failed`);let f;switch(typeof n.clockTolerance){case`string`:f=Z(n.clockTolerance);break;case`number`:f=n.clockTolerance;break;case`undefined`:f=0;break;default:throw TypeError(`Invalid clockTolerance option type`)}let{currentDate:p}=n,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 ie(`"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 ie(`"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 on=class{#e;constructor(e){if(!R(e))throw TypeError(`JWT Claims Set MUST be an object`);this.#e=structuredClone(e)}data(){return n.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 sn(e,t,n){let r=await Zt(e,t,n);if(r.protectedHeader.crit?.includes(`b64`)&&r.protectedHeader.b64===!1)throw new A(`JWTs MUST NOT use unencoded payload`);let i={payload:an(r.protectedHeader,r.payload,n),protectedHeader:r.protectedHeader};return typeof t==`function`?{...i,key:r.key}:i}async function cn(e,t,n){let r=await Gt(e,t,n),i=an(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 header parameter mismatch`,i,`sub`,`mismatch`);if(a.aud!==void 0&&JSON.stringify(a.aud)!==JSON.stringify(i.aud))throw new w(`replicated "aud" claim header parameter mismatch`,i,`aud`,`mismatch`);let o={payload:i,protectedHeader:a};return typeof t==`function`?{...o,key:r.key}:o}var ln=class{#e;constructor(e){this.#e=new qt(e)}setContentEncryptionKey(e){return this.#e.setContentEncryptionKey(e),this}setInitializationVector(e){return this.#e.setInitializationVector(e),this}setProtectedHeader(e){return this.#e.setProtectedHeader(e),this}setKeyManagementParameters(e){return this.#e.setKeyManagementParameters(e),this}async encrypt(e,t){let n=await this.#e.encrypt(e,t);return[n.protected,n.encrypted_key,n.iv,n.ciphertext,n.tag].join(`.`)}},un=class{#e;#t;#n;constructor(e){if(!(e instanceof Uint8Array))throw TypeError(`payload must be an instance of Uint8Array`);this.#e=e}setProtectedHeader(e){return I(this.#t,`setProtectedHeader`),this.#t=e,this}setUnprotectedHeader(e){return I(this.#n,`setUnprotectedHeader`),this.#n=e,this}async sign(e,t){if(!this.#t&&!this.#n)throw new k(`either setProtectedHeader or setUnprotectedHeader must be called before #sign()`);if(!z(this.#t,this.#n))throw new k(`JWS Protected and JWS Unprotected Header Parameter names must be disjoint`);let n={...this.#t,...this.#n},r=q(k,new Map([[`b64`,!0]]),t?.crit,this.#t,n),i=!0;if(r.has(`b64`)&&(i=this.#t.b64,typeof i!=`boolean`))throw new k(`The "b64" (base64url-encode payload) Header Parameter must be a boolean`);let{alg:o}=n;if(typeof o!=`string`||!o)throw new k(`JWS "alg" (Algorithm) Header Parameter missing or invalid`);Y(o,e,`sign`);let s,c;i?(s=m(this.#e),c=l(s)):(c=this.#e,s=``);let u,d;this.#t?(u=m(JSON.stringify(this.#t)),d=l(u)):(u=``,d=new Uint8Array);let f=a(d,l(`.`),c),p={signature:m(await Ye(o,await U(e,o),f)),payload:s};return this.#n&&(p.header=this.#n),this.#t&&(p.protected=u),p}},dn=class{#e;constructor(e){this.#e=new un(e)}setProtectedHeader(e){return this.#e.setProtectedHeader(e),this}async sign(e,t){let n=await this.#e.sign(e,t);if(n.payload===void 0)throw TypeError(`use the flattened module for creating JWS with b64: false`);return`${n.protected}.${n.payload}.${n.signature}`}},fn=class{#e;protectedHeader;unprotectedHeader;options;key;constructor(e,t,n){this.#e=e,this.key=t,this.options=n}setProtectedHeader(e){return I(this.protectedHeader,`setProtectedHeader`),this.protectedHeader=e,this}setUnprotectedHeader(e){return I(this.unprotectedHeader,`setUnprotectedHeader`),this.unprotectedHeader=e,this}addSignature(...e){return this.#e.addSignature(...e)}sign(...e){return this.#e.sign(...e)}done(){return this.#e}},pn=class{#e;#t=[];constructor(e){this.#e=e}addSignature(e,t){let n=new fn(this,e,t);return this.#t.push(n),n}async sign(){if(!this.#t.length)throw new k(`at least one signature must be added`);let e={signatures:[],payload:``};for(let t=0;t<this.#t.length;t++){let n=this.#t[t],r=new un(this.#e);r.setProtectedHeader(n.protectedHeader),r.setUnprotectedHeader(n.unprotectedHeader);let{payload:i,...a}=await r.sign(n.key,n.options);if(t===0)e.payload=i;else if(e.payload!==i)throw new k(`inconsistent use of JWS Unencoded Payload (RFC7797)`);e.signatures.push(a)}return e}},mn=class{#e;#t;constructor(e={}){this.#t=new on(e)}setIssuer(e){return this.#t.iss=e,this}setSubject(e){return this.#t.sub=e,this}setAudience(e){return this.#t.aud=e,this}setJti(e){return this.#t.jti=e,this}setNotBefore(e){return this.#t.nbf=e,this}setExpirationTime(e){return this.#t.exp=e,this}setIssuedAt(e){return this.#t.iat=e,this}setProtectedHeader(e){return this.#e=e,this}async sign(e,t){let n=new dn(this.#t.data());if(n.setProtectedHeader(this.#e),Array.isArray(this.#e?.crit)&&this.#e.crit.includes(`b64`)&&this.#e.b64===!1)throw new A(`JWTs MUST NOT use unencoded payload`);return n.sign(e,t)}},hn=class{#e;#t;#n;#r;#i;#a;#o;#s;constructor(e={}){this.#s=new on(e)}setIssuer(e){return this.#s.iss=e,this}setSubject(e){return this.#s.sub=e,this}setAudience(e){return this.#s.aud=e,this}setJti(e){return this.#s.jti=e,this}setNotBefore(e){return this.#s.nbf=e,this}setExpirationTime(e){return this.#s.exp=e,this}setIssuedAt(e){return this.#s.iat=e,this}setProtectedHeader(e){return I(this.#r,`setProtectedHeader`),this.#r=e,this}setKeyManagementParameters(e){return I(this.#n,`setKeyManagementParameters`),this.#n=e,this}setContentEncryptionKey(e){return I(this.#e,`setContentEncryptionKey`),this.#e=e,this}setInitializationVector(e){return I(this.#t,`setInitializationVector`),this.#t=e,this}replicateIssuerAsHeader(){return this.#i=!0,this}replicateSubjectAsHeader(){return this.#a=!0,this}replicateAudienceAsHeader(){return this.#o=!0,this}async encrypt(e,t){let n=new ln(this.#s.data());return this.#r&&(this.#i||this.#a||this.#o)&&(this.#r={...this.#r,iss:this.#i?this.#s.iss:void 0,sub:this.#a?this.#s.sub:void 0,aud:this.#o?this.#s.aud:void 0}),n.setProtectedHeader(this.#r),this.#t&&n.setInitializationVector(this.#t),this.#e&&n.setContentEncryptionKey(this.#e),this.#n&&n.setKeyManagementParameters(this.#n),n.encrypt(e,t)}};const $=(e,t)=>{if(typeof e!=`string`||!e)throw new ae(`${t} missing or invalid`)};async function gn(e,t){let n;if(B(e))n=e;else if(de(e))n=await jt(e);else throw TypeError(S(e,`CryptoKey`,`KeyObject`,`JSON Web Key`));if(t??=`sha256`,t!==`sha256`&&t!==`sha384`&&t!==`sha512`)throw TypeError(`digestAlgorithm must one of "sha256", "sha384", or "sha512"`);let r;switch(n.kty){case`AKP`:$(n.alg,`"alg" (Algorithm) Parameter`),$(n.pub,`"pub" (Public key) Parameter`),r={alg:n.alg,kty:n.kty,pub:n.pub};break;case`EC`:$(n.crv,`"crv" (Curve) Parameter`),$(n.x,`"x" (X Coordinate) Parameter`),$(n.y,`"y" (Y Coordinate) Parameter`),r={crv:n.crv,kty:n.kty,x:n.x,y:n.y};break;case`OKP`:$(n.crv,`"crv" (Subtype of Key Pair) Parameter`),$(n.x,`"x" (Public Key) Parameter`),r={crv:n.crv,kty:n.kty,x:n.x};break;case`RSA`:$(n.e,`"e" (Exponent) Parameter`),$(n.n,`"n" (Modulus) Parameter`),r={e:n.e,kty:n.kty,n:n.n};break;case`oct`:$(n.k,`"k" (Key Value) Parameter`),r={k:n.k,kty:n.kty};break;default:throw new E(`"kty" (Key Type) Parameter missing or unsupported`)}let i=l(JSON.stringify(r));return m(await De(t,i))}async function _n(e,t){t??=`sha256`;let n=await gn(e,t);return`urn:ietf:params:oauth:jwk-thumbprint:sha-${t.slice(-3)}:${n}`}async function vn(e,t){let n={...e,...t?.header};if(!R(n.jwk))throw new k(`"jwk" (JSON Web Key) Header Parameter must be a JSON object`);let r=await Dt({...n.jwk,ext:!0},n.alg);if(r instanceof Uint8Array||r.type!==`public`)throw new k(`"jwk" (JSON Web Key) Header Parameter must be a public key`);return r}function yn(e){switch(typeof e==`string`&&e.slice(0,2)){case`RS`:case`PS`:return`RSA`;case`ES`:return`EC`;case`Ed`:return`OKP`;case`ML`:return`AKP`;default:throw new E(`Unsupported "alg" value for a JSON Web Key Set`)}}function bn(e){return e&&typeof e==`object`&&Array.isArray(e.keys)&&e.keys.every(xn)}function xn(e){return R(e)}var Sn=class{#e;#t=new WeakMap;constructor(e){if(!bn(e))throw new oe(`JSON Web Key Set malformed`);this.#e=structuredClone(e)}jwks(){return this.#e}async getKey(e,t){let{alg:n,kid:r}={...e,...t?.header},i=yn(n),a=this.#e.keys.filter(e=>{let t=i===e.kty;if(t&&typeof r==`string`&&(t=r===e.kid),t&&(typeof e.alg==`string`||i===`AKP`)&&(t=n===e.alg),t&&typeof e.use==`string`&&(t=e.use===`sig`),t&&Array.isArray(e.key_ops)&&(t=e.key_ops.includes(`verify`)),t)switch(n){case`ES256`:t=e.crv===`P-256`;break;case`ES384`:t=e.crv===`P-384`;break;case`ES512`:t=e.crv===`P-521`;break;case`Ed25519`:case`EdDSA`:t=e.crv===`Ed25519`;break}return t}),{0:o,length:s}=a;if(s===0)throw new se;if(s!==1){let e=new ce,t=this.#t;throw e[Symbol.asyncIterator]=async function*(){for(let e of a)try{yield await Cn(t,e,n)}catch{}},e}return Cn(this.#t,o,n)}};async function Cn(e,t,n){let r=e.get(t)||e.set(t,{}).get(t);if(r[n]===void 0){let e=await Dt({...t,ext:!0},n);if(e instanceof Uint8Array||e.type!==`public`)throw new oe(`JSON Web Key Set members must be public keys`);r[n]=e}return r[n]}function wn(e){let t=new Sn(e),n=async(e,n)=>t.getKey(e,n);return Object.defineProperties(n,{jwks:{value:()=>structuredClone(t.jwks()),enumerable:!1,configurable:!1,writable:!1}}),n}function Tn(){return typeof WebSocketPair<`u`||typeof navigator<`u`&&navigator.userAgent===`Cloudflare-Workers`||typeof EdgeRuntime<`u`&&EdgeRuntime===`vercel`}let En;(typeof navigator>`u`||!navigator.userAgent?.startsWith?.(`Mozilla/5.0 `))&&(En=`jose/v6.2.2`);const Dn=Symbol();async function On(e,t,n,r=fetch){let i=await r(e,{method:`GET`,signal:n,redirect:`manual`,headers:t}).catch(e=>{throw e.name===`TimeoutError`?new le:e});if(i.status!==200)throw new C(`Expected 200 OK from the JSON Web Key Set HTTP response`);try{return await i.json()}catch{throw new C(`Failed to parse the JSON Web Key Set HTTP response as JSON`)}}const kn=Symbol();function An(e,t){return!(typeof e!=`object`||!e||!(`uat`in e)||typeof e.uat!=`number`||Date.now()-e.uat>=t||!(`jwks`in e)||!R(e.jwks)||!Array.isArray(e.jwks.keys)||!Array.prototype.every.call(e.jwks.keys,R))}var jn=class{#e;#t;#n;#r;#i;#a;#o;#s;#c;#l;constructor(e,t){if(!(e instanceof URL))throw TypeError(`url must be an instance of URL`);this.#e=new URL(e.href),this.#t=typeof t?.timeoutDuration==`number`?t?.timeoutDuration:5e3,this.#n=typeof t?.cooldownDuration==`number`?t?.cooldownDuration:3e4,this.#r=typeof t?.cacheMaxAge==`number`?t?.cacheMaxAge:6e5,this.#o=new Headers(t?.headers),En&&!this.#o.has(`User-Agent`)&&this.#o.set(`User-Agent`,En),this.#o.has(`accept`)||(this.#o.set(`accept`,`application/json`),this.#o.append(`accept`,`application/jwk-set+json`)),this.#s=t?.[Dn],t?.[kn]!==void 0&&(this.#l=t?.[kn],An(t?.[kn],this.#r)&&(this.#i=this.#l.uat,this.#c=wn(this.#l.jwks)))}pendingFetch(){return!!this.#a}coolingDown(){return typeof this.#i==`number`?Date.now()<this.#i+this.#n:!1}fresh(){return typeof this.#i==`number`?Date.now()<this.#i+this.#r:!1}jwks(){return this.#c?.jwks()}async getKey(e,t){(!this.#c||!this.fresh())&&await this.reload();try{return await this.#c(e,t)}catch(n){if(n instanceof se&&this.coolingDown()===!1)return await this.reload(),this.#c(e,t);throw n}}async reload(){this.#a&&Tn()&&(this.#a=void 0),this.#a||=On(this.#e.href,this.#o,AbortSignal.timeout(this.#t),this.#s).then(e=>{this.#c=wn(e),this.#l&&(this.#l.uat=Date.now(),this.#l.jwks=e),this.#i=Date.now(),this.#a=void 0}).catch(e=>{throw this.#a=void 0,e}),await this.#a}};function Mn(e,t){let n=new jn(e,t),r=async(e,t)=>n.getKey(e,t);return Object.defineProperties(r,{coolingDown:{get:()=>n.coolingDown(),enumerable:!0,configurable:!1},fresh:{get:()=>n.fresh(),enumerable:!0,configurable:!1},reload:{value:()=>n.reload(),enumerable:!0,configurable:!1,writable:!1},reloading:{get:()=>n.pendingFetch(),enumerable:!0,configurable:!1},jwks:{value:()=>n.jwks(),enumerable:!0,configurable:!1,writable:!1}}),r}var Nn=class{#e;constructor(e={}){this.#e=new on(e)}encode(){return`${m(JSON.stringify({alg:`none`}))}.${m(this.#e.data())}.`}setIssuer(e){return this.#e.iss=e,this}setSubject(e){return this.#e.sub=e,this}setAudience(e){return this.#e.aud=e,this}setJti(e){return this.#e.jti=e,this}setNotBefore(e){return this.#e.nbf=e,this}setExpirationTime(e){return this.#e.exp=e,this}setIssuedAt(e){return this.#e.iat=e,this}static decode(e,t){if(typeof e!=`string`)throw new A(`Unsecured JWT must be a string`);let{0:n,1:i,2:a,length:o}=e.split(`.`);if(o!==3||a!==``)throw new A(`Invalid Unsecured JWT`);let s;try{if(s=JSON.parse(r.decode(p(n))),s.alg!==`none`)throw Error()}catch{throw new A(`Invalid Unsecured JWT`)}return{payload:an(s,p(i),t),header:s}}};function Pn(e){let t;if(typeof e==`string`){let n=e.split(`.`);(n.length===3||n.length===5)&&([t]=n)}else if(typeof e==`object`&&e)if(`protected`in e)t=e.protected;else throw TypeError(`Token does not contain a Protected Header`);try{if(typeof t!=`string`||!t)throw Error();let e=JSON.parse(r.decode(p(t)));if(!R(e))throw Error();return e}catch{throw TypeError(`Invalid Token or Protected Header formatting`)}}function Fn(e){if(typeof e!=`string`)throw new A(`JWTs must use Compact JWS serialization, JWT must be a string`);let{1:t,length:n}=e.split(`.`);if(n===5)throw new A(`Only JWTs using Compact JWS serialization can be decoded`);if(n!==3)throw new A(`Invalid JWT`);if(!t)throw new A(`JWTs must contain a payload`);let i;try{i=p(t)}catch{throw new A(`Failed to base64url decode the payload`)}let a;try{a=JSON.parse(r.decode(i))}catch{throw new A(`Failed to parse the decoded payload as JSON`)}if(!R(a))throw new A(`Invalid JWT Claims Set`);return a}function In(e){let t=e?.modulusLength??2048;if(typeof t!=`number`||t<2048)throw new E(`Invalid or unsupported modulusLength option provided, 2048 bits or larger keys must be used`);return t}async function Ln(e,t){let n,r;switch(e){case`PS256`:case`PS384`:case`PS512`:n={name:`RSA-PSS`,hash:`SHA-${e.slice(-3)}`,publicExponent:Uint8Array.of(1,0,1),modulusLength:In(t)},r=[`sign`,`verify`];break;case`RS256`:case`RS384`:case`RS512`:n={name:`RSASSA-PKCS1-v1_5`,hash:`SHA-${e.slice(-3)}`,publicExponent:Uint8Array.of(1,0,1),modulusLength:In(t)},r=[`sign`,`verify`];break;case`RSA-OAEP`:case`RSA-OAEP-256`:case`RSA-OAEP-384`:case`RSA-OAEP-512`:n={name:`RSA-OAEP`,hash:`SHA-${parseInt(e.slice(-3),10)||1}`,publicExponent:Uint8Array.of(1,0,1),modulusLength:In(t)},r=[`decrypt`,`unwrapKey`,`encrypt`,`wrapKey`];break;case`ES256`:n={name:`ECDSA`,namedCurve:`P-256`},r=[`sign`,`verify`];break;case`ES384`:n={name:`ECDSA`,namedCurve:`P-384`},r=[`sign`,`verify`];break;case`ES512`:n={name:`ECDSA`,namedCurve:`P-521`},r=[`sign`,`verify`];break;case`Ed25519`:case`EdDSA`:r=[`sign`,`verify`],n={name:`Ed25519`};break;case`ML-DSA-44`:case`ML-DSA-65`:case`ML-DSA-87`:r=[`sign`,`verify`],n={name:e};break;case`ECDH-ES`:case`ECDH-ES+A128KW`:case`ECDH-ES+A192KW`:case`ECDH-ES+A256KW`:{r=[`deriveBits`];let e=t?.crv??`P-256`;switch(e){case`P-256`:case`P-384`:case`P-521`:n={name:`ECDH`,namedCurve:e};break;case`X25519`:n={name:`X25519`};break;default:throw new E(`Invalid or unsupported crv option provided, supported values are P-256, P-384, P-521, and X25519`)}break}default:throw new E(`Invalid or unsupported JWK "alg" (Algorithm) Parameter value`)}return crypto.subtle.generateKey(n,t?.extractable??!1,r)}async function Rn(e,t){let n,r,i;switch(e){case`HS256`:case`HS384`:case`HS512`:n=parseInt(e.slice(-3),10),r={name:`HMAC`,hash:`SHA-${n}`,length:n},i=[`sign`,`verify`];break;case`A128CBC-HS256`:case`A192CBC-HS384`:case`A256CBC-HS512`:return n=parseInt(e.slice(-3),10),crypto.getRandomValues(new Uint8Array(n>>3));case`A128KW`:case`A192KW`:case`A256KW`:n=parseInt(e.slice(1,4),10),r={name:`AES-KW`,length:n},i=[`wrapKey`,`unwrapKey`];break;case`A128GCMKW`:case`A192GCMKW`:case`A256GCMKW`:case`A128GCM`:case`A192GCM`:case`A256GCM`:n=parseInt(e.slice(1,4),10),r={name:`AES-GCM`,length:n},i=[`encrypt`,`decrypt`];break;default:throw new E(`Invalid or unsupported JWK "alg" (Algorithm) Parameter value`)}return crypto.subtle.generateKey(r,t?.extractable??!1,i)}const zn=`WebCryptoAPI`;export{ln as CompactEncrypt,dn as CompactSign,vn as EmbeddedJWK,hn as EncryptJWT,qt as FlattenedEncrypt,un as FlattenedSign,Yt as GeneralEncrypt,pn as GeneralSign,mn as SignJWT,Nn as UnsecuredJWT,f as base64url,gn as calculateJwkThumbprint,_n as calculateJwkThumbprintUri,Gt as compactDecrypt,Zt as compactVerify,wn as createLocalJWKSet,Mn as createRemoteJWKSet,zn as cryptoRuntime,Dn as customFetch,Fn as decodeJwt,Pn as decodeProtectedHeader,re as errors,jt as exportJWK,At as exportPKCS8,kt as exportSPKI,Wt as flattenedDecrypt,Xt as flattenedVerify,Kt as generalDecrypt,Qt as generalVerify,Ln as generateKeyPair,Rn as generateSecret,Dt as importJWK,Et as importPKCS8,wt as importSPKI,Tt as importX509,kn as jwksCache,cn as jwtDecrypt,sn as jwtVerify};
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@phosphor-tools/phosphor-mcp",
|
|
3
|
-
"version": "0.2.0-
|
|
3
|
+
"version": "0.2.0-rc.9",
|
|
4
4
|
"description": "MCP server for electronic hardware design — datasheets, parts, schematics",
|
|
5
5
|
"license": "UNLICENSED",
|
|
6
6
|
"type": "module",
|
|
@@ -30,7 +30,7 @@
|
|
|
30
30
|
"pdf-lib": "^1.17.1",
|
|
31
31
|
"pdfjs-dist": "^5.6.205",
|
|
32
32
|
"posthog-node": "^5.0.0",
|
|
33
|
-
"zod": "^
|
|
33
|
+
"zod": "^4.0.0"
|
|
34
34
|
},
|
|
35
35
|
"optionalDependencies": {
|
|
36
36
|
"@phosphor-tools/cli-darwin-arm64": "workspace:*",
|
|
@@ -48,7 +48,7 @@
|
|
|
48
48
|
"@types/node": "^24.0.0",
|
|
49
49
|
"eslint": "^10.1.0",
|
|
50
50
|
"prettier": "^3.8.1",
|
|
51
|
-
"tsdown": "^0.
|
|
51
|
+
"tsdown": "^0.22.0",
|
|
52
52
|
"tsx": "^4.19.0",
|
|
53
53
|
"typescript": "^5.9.3",
|
|
54
54
|
"vitest": "^4.0.0"
|