mirror of
https://github.com/hanzoai/jose.git
synced 2026-09-24 17:00:01 +00:00
5 lines
63 KiB
JavaScript
5 lines
63 KiB
JavaScript
var Qt=Object.defineProperty;var dt=(e,t)=>{for(var r in t)Qt(e,r,{get:t[r],enumerable:!0})};var f=crypto,x=e=>e instanceof CryptoKey;var jt=async(e,t)=>{let r=`SHA-${e.slice(-3)}`;return new Uint8Array(await f.subtle.digest(r,t))},ve=jt;var w=new TextEncoder,H=new TextDecoder,xe=2**32;function J(...e){let t=e.reduce((o,{length:a})=>o+a,0),r=new Uint8Array(t),n=0;return e.forEach(o=>{r.set(o,n),n+=o.length}),r}function pt(e,t){return J(w.encode(e),new Uint8Array([0]),t)}function Me(e,t,r){if(t<0||t>=xe)throw new RangeError(`value must be >= 0 and <= ${xe-1}. Received ${t}`);e.set([t>>>24,t>>>16,t>>>8,t&255],r)}function Ke(e){let t=Math.floor(e/xe),r=e%xe,n=new Uint8Array(8);return Me(n,t,0),Me(n,r,4),n}function He(e){let t=new Uint8Array(4);return Me(t,e),t}function Ce(e){return J(He(e.length),e)}async function ut(e,t,r){let n=Math.ceil((t>>3)/32),o=new Uint8Array(n*32);for(let a=0;a<n;a++){let i=new Uint8Array(4+e.length+r.length);i.set(He(a+1)),i.set(e,4),i.set(r,4+e.length),o.set(await ve("sha256",i),a*32)}return o.slice(0,t>>3)}var Pe=e=>{let t=e;typeof t=="string"&&(t=w.encode(t));let r=32768,n=[];for(let o=0;o<t.length;o+=r)n.push(String.fromCharCode.apply(null,t.subarray(o,o+r)));return btoa(n.join(""))},E=e=>Pe(e).replace(/=/g,"").replace(/\+/g,"-").replace(/\//g,"_"),Ne=e=>{let t=atob(e),r=new Uint8Array(t.length);for(let n=0;n<t.length;n++)r[n]=t.charCodeAt(n);return r},S=e=>{let t=e;t instanceof Uint8Array&&(t=H.decode(t)),t=t.replace(/-/g,"+").replace(/_/g,"/").replace(/\s/g,"");try{return Ne(t)}catch(r){throw new TypeError("The input to be decoded is not correctly encoded.")}};var lt={};dt(lt,{JOSEAlgNotAllowed:()=>L,JOSEError:()=>C,JOSENotSupported:()=>l,JWEDecompressionFailed:()=>Le,JWEDecryptionFailed:()=>N,JWEInvalid:()=>u,JWKInvalid:()=>ce,JWKSInvalid:()=>B,JWKSMultipleMatchingKeys:()=>de,JWKSNoMatchingKey:()=>Y,JWKSTimeout:()=>pe,JWSInvalid:()=>h,JWSSignatureVerificationFailed:()=>q,JWTClaimValidationFailed:()=>W,JWTExpired:()=>te,JWTInvalid:()=>P});var C=class extends Error{static get code(){return"ERR_JOSE_GENERIC"}constructor(t){var r;super(t),this.code="ERR_JOSE_GENERIC",this.name=this.constructor.name,(r=Error.captureStackTrace)===null||r===void 0||r.call(Error,this,this.constructor)}},W=class extends C{static get code(){return"ERR_JWT_CLAIM_VALIDATION_FAILED"}constructor(t,r="unspecified",n="unspecified"){super(t),this.code="ERR_JWT_CLAIM_VALIDATION_FAILED",this.claim=r,this.reason=n}},te=class extends C{static get code(){return"ERR_JWT_EXPIRED"}constructor(t,r="unspecified",n="unspecified"){super(t),this.code="ERR_JWT_EXPIRED",this.claim=r,this.reason=n}},L=class extends C{constructor(){super(...arguments),this.code="ERR_JOSE_ALG_NOT_ALLOWED"}static get code(){return"ERR_JOSE_ALG_NOT_ALLOWED"}},l=class extends C{constructor(){super(...arguments),this.code="ERR_JOSE_NOT_SUPPORTED"}static get code(){return"ERR_JOSE_NOT_SUPPORTED"}},N=class extends C{constructor(){super(...arguments),this.code="ERR_JWE_DECRYPTION_FAILED",this.message="decryption operation failed"}static get code(){return"ERR_JWE_DECRYPTION_FAILED"}},Le=class extends C{constructor(){super(...arguments),this.code="ERR_JWE_DECOMPRESSION_FAILED",this.message="decompression operation failed"}static get code(){return"ERR_JWE_DECOMPRESSION_FAILED"}},u=class extends C{constructor(){super(...arguments),this.code="ERR_JWE_INVALID"}static get code(){return"ERR_JWE_INVALID"}},h=class extends C{constructor(){super(...arguments),this.code="ERR_JWS_INVALID"}static get code(){return"ERR_JWS_INVALID"}},P=class extends C{constructor(){super(...arguments),this.code="ERR_JWT_INVALID"}static get code(){return"ERR_JWT_INVALID"}},ce=class extends C{constructor(){super(...arguments),this.code="ERR_JWK_INVALID"}static get code(){return"ERR_JWK_INVALID"}},B=class extends C{constructor(){super(...arguments),this.code="ERR_JWKS_INVALID"}static get code(){return"ERR_JWKS_INVALID"}},Y=class extends C{constructor(){super(...arguments),this.code="ERR_JWKS_NO_MATCHING_KEY",this.message="no applicable key found in the JSON Web Key Set"}static get code(){return"ERR_JWKS_NO_MATCHING_KEY"}},de=class extends C{constructor(){super(...arguments),this.code="ERR_JWKS_MULTIPLE_MATCHING_KEYS",this.message="multiple matching keys found in the JSON Web Key Set"}static get code(){return"ERR_JWKS_MULTIPLE_MATCHING_KEYS"}},pe=class extends C{constructor(){super(...arguments),this.code="ERR_JWKS_TIMEOUT",this.message="request timed out"}static get code(){return"ERR_JWKS_TIMEOUT"}},q=class extends C{constructor(){super(...arguments),this.code="ERR_JWS_SIGNATURE_VERIFICATION_FAILED",this.message="signature verification failed"}static get code(){return"ERR_JWS_SIGNATURE_VERIFICATION_FAILED"}};var k=f.getRandomValues.bind(f);function Be(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 l(`Unsupported JWE Algorithm: ${e}`)}}var We=e=>k(new Uint8Array(Be(e)>>3));var er=(e,t)=>{if(t.length<<3!==Be(e))throw new u("Invalid Initialization Vector length")},Je=er;var tr=(e,t)=>{let r=e.byteLength<<3;if(r!==t)throw new u(`Invalid Content Encryption Key length. Expected ${t} bits, got ${r} bits`)},re=tr;var rr=(e,t)=>{if(!(e instanceof Uint8Array))throw new TypeError("First argument must be a buffer");if(!(t instanceof Uint8Array))throw new TypeError("Second argument must be a buffer");if(e.length!==t.length)throw new TypeError("Input buffers must have the same length");let r=e.length,n=0,o=-1;for(;++o<r;)n|=e[o]^t[o];return n===0},ht=rr;function I(e,t="algorithm.name"){return new TypeError(`CryptoKey does not support this operation, its ${t} must be ${e}`)}function $(e,t){return e.name===t}function Ie(e){return parseInt(e.name.slice(4),10)}function nr(e){switch(e){case"ES256":return"P-256";case"ES384":return"P-384";case"ES512":return"P-521";default:throw new Error("unreachable")}}function mt(e,t){if(t.length&&!t.some(r=>e.usages.includes(r))){let r="CryptoKey does not support this operation, its usages must include ";if(t.length>2){let n=t.pop();r+=`one of ${t.join(", ")}, or ${n}.`}else t.length===2?r+=`one of ${t[0]} or ${t[1]}.`:r+=`${t[0]}.`;throw new TypeError(r)}}function yt(e,t,...r){switch(t){case"HS256":case"HS384":case"HS512":{if(!$(e.algorithm,"HMAC"))throw I("HMAC");let n=parseInt(t.slice(2),10);if(Ie(e.algorithm.hash)!==n)throw I(`SHA-${n}`,"algorithm.hash");break}case"RS256":case"RS384":case"RS512":{if(!$(e.algorithm,"RSASSA-PKCS1-v1_5"))throw I("RSASSA-PKCS1-v1_5");let n=parseInt(t.slice(2),10);if(Ie(e.algorithm.hash)!==n)throw I(`SHA-${n}`,"algorithm.hash");break}case"PS256":case"PS384":case"PS512":{if(!$(e.algorithm,"RSA-PSS"))throw I("RSA-PSS");let n=parseInt(t.slice(2),10);if(Ie(e.algorithm.hash)!==n)throw I(`SHA-${n}`,"algorithm.hash");break}case"EdDSA":{if(e.algorithm.name!=="Ed25519"&&e.algorithm.name!=="Ed448")throw I("Ed25519 or Ed448");break}case"ES256":case"ES384":case"ES512":{if(!$(e.algorithm,"ECDSA"))throw I("ECDSA");let n=nr(t);if(e.algorithm.namedCurve!==n)throw I(n,"algorithm.namedCurve");break}default:throw new TypeError("CryptoKey does not support this operation")}mt(e,r)}function T(e,t,...r){switch(t){case"A128GCM":case"A192GCM":case"A256GCM":{if(!$(e.algorithm,"AES-GCM"))throw I("AES-GCM");let n=parseInt(t.slice(1,4),10);if(e.algorithm.length!==n)throw I(n,"algorithm.length");break}case"A128KW":case"A192KW":case"A256KW":{if(!$(e.algorithm,"AES-KW"))throw I("AES-KW");let n=parseInt(t.slice(1,4),10);if(e.algorithm.length!==n)throw I(n,"algorithm.length");break}case"ECDH":{switch(e.algorithm.name){case"ECDH":case"X25519":case"X448":break;default:throw I("ECDH, X25519, or X448")}break}case"PBES2-HS256+A128KW":case"PBES2-HS384+A192KW":case"PBES2-HS512+A256KW":if(!$(e.algorithm,"PBKDF2"))throw I("PBKDF2");break;case"RSA-OAEP":case"RSA-OAEP-256":case"RSA-OAEP-384":case"RSA-OAEP-512":{if(!$(e.algorithm,"RSA-OAEP"))throw I("RSA-OAEP");let n=parseInt(t.slice(9),10)||1;if(Ie(e.algorithm.hash)!==n)throw I(`SHA-${n}`,"algorithm.hash");break}default:throw new TypeError("CryptoKey does not support this operation")}mt(e,r)}function wt(e,t,...r){if(r.length>2){let n=r.pop();e+=`one of type ${r.join(", ")}, or ${n}.`}else r.length===2?e+=`one of type ${r[0]} or ${r[1]}.`:e+=`of type ${r[0]}.`;return t==null?e+=` Received ${t}`:typeof t=="function"&&t.name?e+=` Received function ${t.name}`:typeof t=="object"&&t!=null&&t.constructor&&t.constructor.name&&(e+=` Received an instance of ${t.constructor.name}`),e}var A=(e,...t)=>wt("Key must be ",e,...t);function ke(e,t,...r){return wt(`Key for the ${e} algorithm must be `,t,...r)}var $e=e=>x(e),m=["CryptoKey"];async function or(e,t,r,n,o,a){if(!(t instanceof Uint8Array))throw new TypeError(A(t,"Uint8Array"));let i=parseInt(e.slice(1,4),10),s=await f.subtle.importKey("raw",t.subarray(i>>3),"AES-CBC",!1,["decrypt"]),d=await f.subtle.importKey("raw",t.subarray(0,i>>3),{hash:`SHA-${i<<1}`,name:"HMAC"},!1,["sign"]),c=J(a,n,r,Ke(a.length<<3)),p=new Uint8Array((await f.subtle.sign("HMAC",d,c)).slice(0,i>>3)),g;try{g=ht(o,p)}catch(_){}if(!g)throw new N;let b;try{b=new Uint8Array(await f.subtle.decrypt({iv:n,name:"AES-CBC"},s,r))}catch(_){}if(!b)throw new N;return b}async function ar(e,t,r,n,o,a){let i;t instanceof Uint8Array?i=await f.subtle.importKey("raw",t,"AES-GCM",!1,["decrypt"]):(T(t,e,"decrypt"),i=t);try{return new Uint8Array(await f.subtle.decrypt({additionalData:a,iv:n,name:"AES-GCM",tagLength:128},i,J(r,o)))}catch(s){throw new N}}var ir=async(e,t,r,n,o,a)=>{if(!x(t)&&!(t instanceof Uint8Array))throw new TypeError(A(t,...m,"Uint8Array"));switch(Je(e,n),e){case"A128CBC-HS256":case"A192CBC-HS384":case"A256CBC-HS512":return t instanceof Uint8Array&&re(t,parseInt(e.slice(-3),10)),or(e,t,r,n,o,a);case"A128GCM":case"A192GCM":case"A256GCM":return t instanceof Uint8Array&&re(t,parseInt(e.slice(1,4),10)),ar(e,t,r,n,o,a);default:throw new l("Unsupported JWE Content Encryption Algorithm")}},Te=ir;var Et=async()=>{throw new l('JWE "zip" (Compression Algorithm) Header Parameter is not supported by your javascript runtime. You need to use the `inflateRaw` decrypt option to provide Inflate Raw implementation.')},gt=async()=>{throw new l('JWE "zip" (Compression Algorithm) Header Parameter is not supported by your javascript runtime. You need to use the `deflateRaw` encrypt option to provide Deflate Raw implementation.')};var sr=(...e)=>{let t=e.filter(Boolean);if(t.length===0||t.length===1)return!0;let r;for(let n of t){let o=Object.keys(n);if(!r||r.size===0){r=new Set(o);continue}for(let a of o){if(r.has(a))return!1;r.add(a)}}return!0},U=sr;function cr(e){return typeof e=="object"&&e!==null}function y(e){if(!cr(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}var dr=[{hash:"SHA-256",name:"HMAC"},!0,["sign"]],ne=dr;function St(e,t){if(e.algorithm.length!==parseInt(t.slice(1,4),10))throw new TypeError(`Invalid key size for alg: ${t}`)}function At(e,t,r){if(x(e))return T(e,t,r),e;if(e instanceof Uint8Array)return f.subtle.importKey("raw",e,"AES-KW",!0,[r]);throw new TypeError(A(e,...m,"Uint8Array"))}var ue=async(e,t,r)=>{let n=await At(t,e,"wrapKey");St(n,e);let o=await f.subtle.importKey("raw",r,...ne);return new Uint8Array(await f.subtle.wrapKey("raw",o,n,"AES-KW"))},fe=async(e,t,r)=>{let n=await At(t,e,"unwrapKey");St(n,e);let o=await f.subtle.unwrapKey("raw",r,n,"AES-KW",...ne);return new Uint8Array(await f.subtle.exportKey("raw",o))};async function Re(e,t,r,n,o=new Uint8Array(0),a=new Uint8Array(0)){if(!x(e))throw new TypeError(A(e,...m));if(T(e,"ECDH"),!x(t))throw new TypeError(A(t,...m));T(t,"ECDH","deriveBits");let i=J(Ce(w.encode(r)),Ce(o),Ce(a),He(n)),s;e.algorithm.name==="X25519"?s=256:e.algorithm.name==="X448"?s=448:s=Math.ceil(parseInt(e.algorithm.namedCurve.substr(-3),10)/8)<<3;let d=new Uint8Array(await f.subtle.deriveBits({name:e.algorithm.name,public:e},t,s));return ut(d,n,i)}async function bt(e){if(!x(e))throw new TypeError(A(e,...m));return f.subtle.generateKey(e.algorithm,!0,["deriveBits"])}function Oe(e){if(!x(e))throw new TypeError(A(e,...m));return["P-256","P-384","P-521"].includes(e.algorithm.namedCurve)||e.algorithm.name==="X25519"||e.algorithm.name==="X448"}function Ge(e){if(!(e instanceof Uint8Array)||e.length<8)throw new u("PBES2 Salt Input must be 8 or more octets")}function pr(e,t){if(e instanceof Uint8Array)return f.subtle.importKey("raw",e,"PBKDF2",!1,["deriveBits"]);if(x(e))return T(e,t,"deriveBits","deriveKey"),e;throw new TypeError(A(e,...m,"Uint8Array"))}async function vt(e,t,r,n){Ge(e);let o=pt(t,e),a=parseInt(t.slice(13,16),10),i={hash:`SHA-${t.slice(8,11)}`,iterations:r,name:"PBKDF2",salt:o},s={length:a,name:"AES-KW"},d=await pr(n,t);if(d.usages.includes("deriveBits"))return new Uint8Array(await f.subtle.deriveBits(i,d,a));if(d.usages.includes("deriveKey"))return f.subtle.deriveKey(i,d,s,!1,["wrapKey","unwrapKey"]);throw new TypeError('PBKDF2 key "usages" must include "deriveBits" or "deriveKey"')}var xt=async(e,t,r,n=2048,o=k(new Uint8Array(16)))=>{let a=await vt(o,e,n,t);return{encryptedKey:await ue(e.slice(-6),a,r),p2c:n,p2s:E(o)}},Kt=async(e,t,r,n,o)=>{let a=await vt(o,e,n,t);return fe(e.slice(-6),a,r)};function oe(e){switch(e){case"RSA-OAEP":case"RSA-OAEP-256":case"RSA-OAEP-384":case"RSA-OAEP-512":return"RSA-OAEP";default:throw new l(`alg ${e} is not supported either by JOSE or your javascript runtime`)}}var Z=(e,t)=>{if(e.startsWith("RS")||e.startsWith("PS")){let{modulusLength:r}=t.algorithm;if(typeof r!="number"||r<2048)throw new TypeError(`${e} requires key modulusLength to be 2048 bits or larger`)}};var Ht=async(e,t,r)=>{if(!x(t))throw new TypeError(A(t,...m));if(T(t,e,"encrypt","wrapKey"),Z(e,t),t.usages.includes("encrypt"))return new Uint8Array(await f.subtle.encrypt(oe(e),t,r));if(t.usages.includes("wrapKey")){let n=await f.subtle.importKey("raw",r,...ne);return new Uint8Array(await f.subtle.wrapKey("raw",n,t,oe(e)))}throw new TypeError('RSA-OAEP key "usages" must include "encrypt" or "wrapKey" for this operation')},Ct=async(e,t,r)=>{if(!x(t))throw new TypeError(A(t,...m));if(T(t,e,"decrypt","unwrapKey"),Z(e,t),t.usages.includes("decrypt"))return new Uint8Array(await f.subtle.decrypt(oe(e),t,r));if(t.usages.includes("unwrapKey")){let n=await f.subtle.unwrapKey("raw",r,t,oe(e),...ne);return new Uint8Array(await f.subtle.exportKey("raw",n))}throw new TypeError('RSA-OAEP key "usages" must include "decrypt" or "unwrapKey" for this operation')};function le(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 l(`Unsupported JWE Algorithm: ${e}`)}}var D=e=>k(new Uint8Array(le(e)>>3));var Fe=(e,t)=>{let r=(e.match(/.{1,64}/g)||[]).join(`
|
|
`);return`-----BEGIN ${t}-----
|
|
${r}
|
|
-----END ${t}-----`};var Jt=async(e,t,r)=>{if(!x(r))throw new TypeError(A(r,...m));if(!r.extractable)throw new TypeError("CryptoKey is not extractable");if(r.type!==e)throw new TypeError(`key is not a ${e} key`);return Fe(Pe(new Uint8Array(await f.subtle.exportKey(t,r))),`${e.toUpperCase()} KEY`)},It=e=>Jt("public","spki",e),Tt=e=>Jt("private","pkcs8",e),G=(e,t,r=0)=>{r===0&&(t.unshift(t.length),t.unshift(6));let n=e.indexOf(t[0],r);if(n===-1)return!1;let o=e.subarray(n,n+t.length);return o.length!==t.length?!1:o.every((a,i)=>a===t[i])||G(e,t,n+1)},Pt=e=>{switch(!0){case G(e,[42,134,72,206,61,3,1,7]):return"P-256";case G(e,[43,129,4,0,34]):return"P-384";case G(e,[43,129,4,0,35]):return"P-521";case G(e,[43,101,110]):return"X25519";case G(e,[43,101,111]):return"X448";case G(e,[43,101,112]):return"Ed25519";case G(e,[43,101,113]):return"Ed448";default:throw new l("Invalid or unsupported EC Key Curve or OKP Key Sub Type")}},Rt=async(e,t,r,n,o)=>{var a;let i,s,d=new Uint8Array(atob(r.replace(e,"")).split("").map(p=>p.charCodeAt(0))),c=t==="spki";switch(n){case"PS256":case"PS384":case"PS512":i={name:"RSA-PSS",hash:`SHA-${n.slice(-3)}`},s=c?["verify"]:["sign"];break;case"RS256":case"RS384":case"RS512":i={name:"RSASSA-PKCS1-v1_5",hash:`SHA-${n.slice(-3)}`},s=c?["verify"]:["sign"];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}`},s=c?["encrypt","wrapKey"]:["decrypt","unwrapKey"];break;case"ES256":i={name:"ECDSA",namedCurve:"P-256"},s=c?["verify"]:["sign"];break;case"ES384":i={name:"ECDSA",namedCurve:"P-384"},s=c?["verify"]:["sign"];break;case"ES512":i={name:"ECDSA",namedCurve:"P-521"},s=c?["verify"]:["sign"];break;case"ECDH-ES":case"ECDH-ES+A128KW":case"ECDH-ES+A192KW":case"ECDH-ES+A256KW":{let p=Pt(d);i=p.startsWith("P-")?{name:"ECDH",namedCurve:p}:{name:p},s=c?[]:["deriveBits"];break}case"EdDSA":i={name:Pt(d)},s=c?["verify"]:["sign"];break;default:throw new l('Invalid or unsupported "alg" (Algorithm) value')}return f.subtle.importKey(t,d,i,(a=o==null?void 0:o.extractable)!==null&&a!==void 0?a:!1,s)},Ot=(e,t,r)=>Rt(/(?:-----(?:BEGIN|END) PRIVATE KEY-----|\s)/g,"pkcs8",e,t,r),Ve=(e,t,r)=>Rt(/(?:-----(?:BEGIN|END) PUBLIC KEY-----|\s)/g,"spki",e,t,r);function Wt(e){let t=[],r=0;for(;r<e.length;){let n=Ut(e.subarray(r));t.push(n),r+=n.byteLength}return t}function Ut(e){let t=0,r=e[0]&31;if(t++,r===31){for(r=0;e[t]>=128;)r=r*128+e[t]-128,t++;r=r*128+e[t]-128,t++}let n=0;if(e[t]<128)n=e[t],t++;else if(n===128){for(n=0;e[t+n]!==0||e[t+n+1]!==0;){if(n>e.byteLength)throw new TypeError("invalid indefinite form length");n++}let a=t+n+2;return{byteLength:a,contents:e.subarray(t,t+n),raw:e.subarray(0,a)}}else{let a=e[t]&127;t++,n=0;for(let i=0;i<a;i++)n=n*256+e[t],t++}let o=t+n;return{byteLength:o,contents:e.subarray(t,o),raw:e.subarray(0,o)}}function ur(e){let t=Wt(Wt(Ut(e).contents)[0].contents);return Pe(t[t[0].raw[0]===160?6:5].raw)}function fr(e){let t=e.replace(/(?:-----(?:BEGIN|END) CERTIFICATE-----|\s)/g,""),r=Ne(t);return Fe(ur(r),"PUBLIC KEY")}var Dt=(e,t,r)=>{let n;try{n=fr(e)}catch(o){throw new TypeError("Failed to parse the X.509 certificate",{cause:o})}return Ve(n,t,r)};function lr(e){let t,r;switch(e.kty){case"oct":{switch(e.alg){case"HS256":case"HS384":case"HS512":t={name:"HMAC",hash:`SHA-${e.alg.slice(-3)}`},r=["sign","verify"];break;case"A128CBC-HS256":case"A192CBC-HS384":case"A256CBC-HS512":throw new l(`${e.alg} keys cannot be imported as CryptoKey instances`);case"A128GCM":case"A192GCM":case"A256GCM":case"A128GCMKW":case"A192GCMKW":case"A256GCMKW":t={name:"AES-GCM"},r=["encrypt","decrypt"];break;case"A128KW":case"A192KW":case"A256KW":t={name:"AES-KW"},r=["wrapKey","unwrapKey"];break;case"PBES2-HS256+A128KW":case"PBES2-HS384+A192KW":case"PBES2-HS512+A256KW":t={name:"PBKDF2"},r=["deriveBits"];break;default:throw new l('Invalid or unsupported JWK "alg" (Algorithm) Parameter value')}break}case"RSA":{switch(e.alg){case"PS256":case"PS384":case"PS512":t={name:"RSA-PSS",hash:`SHA-${e.alg.slice(-3)}`},r=e.d?["sign"]:["verify"];break;case"RS256":case"RS384":case"RS512":t={name:"RSASSA-PKCS1-v1_5",hash:`SHA-${e.alg.slice(-3)}`},r=e.d?["sign"]:["verify"];break;case"RSA-OAEP":case"RSA-OAEP-256":case"RSA-OAEP-384":case"RSA-OAEP-512":t={name:"RSA-OAEP",hash:`SHA-${parseInt(e.alg.slice(-3),10)||1}`},r=e.d?["decrypt","unwrapKey"]:["encrypt","wrapKey"];break;default:throw new l('Invalid or unsupported JWK "alg" (Algorithm) Parameter value')}break}case"EC":{switch(e.alg){case"ES256":t={name:"ECDSA",namedCurve:"P-256"},r=e.d?["sign"]:["verify"];break;case"ES384":t={name:"ECDSA",namedCurve:"P-384"},r=e.d?["sign"]:["verify"];break;case"ES512":t={name:"ECDSA",namedCurve:"P-521"},r=e.d?["sign"]:["verify"];break;case"ECDH-ES":case"ECDH-ES+A128KW":case"ECDH-ES+A192KW":case"ECDH-ES+A256KW":t={name:"ECDH",namedCurve:e.crv},r=e.d?["deriveBits"]:[];break;default:throw new l('Invalid or unsupported JWK "alg" (Algorithm) Parameter value')}break}case"OKP":{switch(e.alg){case"EdDSA":t={name:e.crv},r=e.d?["sign"]:["verify"];break;case"ECDH-ES":case"ECDH-ES+A128KW":case"ECDH-ES+A192KW":case"ECDH-ES+A256KW":t={name:e.crv},r=e.d?["deriveBits"]:[];break;default:throw new l('Invalid or unsupported JWK "alg" (Algorithm) Parameter value')}break}default:throw new l('Invalid or unsupported JWK "kty" (Key Type) Parameter value')}return{algorithm:t,keyUsages:r}}var hr=async e=>{var t,r;if(!e.alg)throw new TypeError('"alg" argument is required when "jwk.alg" is not present');let{algorithm:n,keyUsages:o}=lr(e),a=[n,(t=e.ext)!==null&&t!==void 0?t:!1,(r=e.key_ops)!==null&&r!==void 0?r:o];if(n.name==="PBKDF2")return f.subtle.importKey("raw",S(e.k),...a);let i={...e};return delete i.alg,delete i.use,f.subtle.importKey("jwk",i,...a)},ze=hr;async function mr(e,t,r){if(typeof e!="string"||e.indexOf("-----BEGIN PUBLIC KEY-----")!==0)throw new TypeError('"spki" must be SPKI formatted string');return Ve(e,t,r)}async function yr(e,t,r){if(typeof e!="string"||e.indexOf("-----BEGIN CERTIFICATE-----")!==0)throw new TypeError('"x509" must be X.509 formatted string');return Dt(e,t,r)}async function wr(e,t,r){if(typeof e!="string"||e.indexOf("-----BEGIN PRIVATE KEY-----")!==0)throw new TypeError('"pkcs8" must be PKCS#8 formatted string');return Ot(e,t,r)}async function Q(e,t,r){var n;if(!y(e))throw new TypeError("JWK must be an object");switch(t||(t=e.alg),e.kty){case"oct":if(typeof e.k!="string"||!e.k)throw new TypeError('missing "k" (Key Value) Parameter value');return r!=null||(r=e.ext!==!0),r?ze({...e,alg:t,ext:(n=e.ext)!==null&&n!==void 0?n:!1}):S(e.k);case"RSA":if(e.oth!==void 0)throw new l('RSA JWK "oth" (Other Primes Info) Parameter value is not supported');case"EC":case"OKP":return ze({...e,alg:t});default:throw new l('Unsupported "kty" (Key Type) Parameter value')}}var Er=(e,t)=>{if(!(t instanceof Uint8Array)){if(!$e(t))throw new TypeError(ke(e,t,...m,"Uint8Array"));if(t.type!=="secret")throw new TypeError(`${m.join(" or ")} instances for symmetric algorithms must be of type "secret"`)}},gr=(e,t,r)=>{if(!$e(t))throw new TypeError(ke(e,t,...m));if(t.type==="secret")throw new TypeError(`${m.join(" or ")} instances for asymmetric algorithms must not be of type "secret"`);if(r==="sign"&&t.type==="public")throw new TypeError(`${m.join(" or ")} instances for asymmetric algorithm signing must be of type "private"`);if(r==="decrypt"&&t.type==="public")throw new TypeError(`${m.join(" or ")} instances for asymmetric algorithm decryption must be of type "private"`);if(t.algorithm&&r==="verify"&&t.type==="private")throw new TypeError(`${m.join(" or ")} instances for asymmetric algorithm verifying must be of type "public"`);if(t.algorithm&&r==="encrypt"&&t.type==="private")throw new TypeError(`${m.join(" or ")} instances for asymmetric algorithm encryption must be of type "public"`)},Sr=(e,t,r)=>{e.startsWith("HS")||e==="dir"||e.startsWith("PBES2")||/^A\d{3}(?:GCM)?KW$/.test(e)?Er(e,t):gr(e,t,r)},F=Sr;async function Ar(e,t,r,n,o){if(!(r instanceof Uint8Array))throw new TypeError(A(r,"Uint8Array"));let a=parseInt(e.slice(1,4),10),i=await f.subtle.importKey("raw",r.subarray(a>>3),"AES-CBC",!1,["encrypt"]),s=await f.subtle.importKey("raw",r.subarray(0,a>>3),{hash:`SHA-${a<<1}`,name:"HMAC"},!1,["sign"]),d=new Uint8Array(await f.subtle.encrypt({iv:n,name:"AES-CBC"},i,t)),c=J(o,n,d,Ke(o.length<<3)),p=new Uint8Array((await f.subtle.sign("HMAC",s,c)).slice(0,a>>3));return{ciphertext:d,tag:p}}async function br(e,t,r,n,o){let a;r instanceof Uint8Array?a=await f.subtle.importKey("raw",r,"AES-GCM",!1,["encrypt"]):(T(r,e,"encrypt"),a=r);let i=new Uint8Array(await f.subtle.encrypt({additionalData:o,iv:n,name:"AES-GCM",tagLength:128},a,t)),s=i.slice(-16);return{ciphertext:i.slice(0,-16),tag:s}}var _r=async(e,t,r,n,o)=>{if(!x(r)&&!(r instanceof Uint8Array))throw new TypeError(A(r,...m,"Uint8Array"));switch(Je(e,n),e){case"A128CBC-HS256":case"A192CBC-HS384":case"A256CBC-HS512":return r instanceof Uint8Array&&re(r,parseInt(e.slice(-3),10)),Ar(e,t,r,n,o);case"A128GCM":case"A192GCM":case"A256GCM":return r instanceof Uint8Array&&re(r,parseInt(e.slice(1,4),10)),br(e,t,r,n,o);default:throw new l("Unsupported JWE Content Encryption Algorithm")}},he=_r;async function Mt(e,t,r,n){let o=e.slice(0,7);n||(n=We(o));let{ciphertext:a,tag:i}=await he(o,r,t,n,new Uint8Array(0));return{encryptedKey:a,iv:E(n),tag:E(i)}}async function Nt(e,t,r,n,o){let a=e.slice(0,7);return Te(a,t,r,n,o,new Uint8Array(0))}async function vr(e,t,r,n,o){switch(F(e,t,"decrypt"),e){case"dir":{if(r!==void 0)throw new u("Encountered unexpected JWE Encrypted Key");return t}case"ECDH-ES":if(r!==void 0)throw new u("Encountered unexpected JWE Encrypted Key");case"ECDH-ES+A128KW":case"ECDH-ES+A192KW":case"ECDH-ES+A256KW":{if(!y(n.epk))throw new u('JOSE Header "epk" (Ephemeral Public Key) missing or invalid');if(!Oe(t))throw new l("ECDH with the provided key is not allowed or not supported by your javascript runtime");let a=await Q(n.epk,e),i,s;if(n.apu!==void 0){if(typeof n.apu!="string")throw new u('JOSE Header "apu" (Agreement PartyUInfo) invalid');try{i=S(n.apu)}catch(c){throw new u("Failed to base64url decode the apu")}}if(n.apv!==void 0){if(typeof n.apv!="string")throw new u('JOSE Header "apv" (Agreement PartyVInfo) invalid');try{s=S(n.apv)}catch(c){throw new u("Failed to base64url decode the apv")}}let d=await Re(a,t,e==="ECDH-ES"?n.enc:e,e==="ECDH-ES"?le(n.enc):parseInt(e.slice(-5,-2),10),i,s);if(e==="ECDH-ES")return d;if(r===void 0)throw new u("JWE Encrypted Key missing");return fe(e.slice(-6),d,r)}case"RSA1_5":case"RSA-OAEP":case"RSA-OAEP-256":case"RSA-OAEP-384":case"RSA-OAEP-512":{if(r===void 0)throw new u("JWE Encrypted Key missing");return Ct(e,t,r)}case"PBES2-HS256+A128KW":case"PBES2-HS384+A192KW":case"PBES2-HS512+A256KW":{if(r===void 0)throw new u("JWE Encrypted Key missing");if(typeof n.p2c!="number")throw new u('JOSE Header "p2c" (PBES2 Count) missing or invalid');let a=(o==null?void 0:o.maxPBES2Count)||1e4;if(n.p2c>a)throw new u('JOSE Header "p2c" (PBES2 Count) out is of acceptable bounds');if(typeof n.p2s!="string")throw new u('JOSE Header "p2s" (PBES2 Salt) missing or invalid');let i;try{i=S(n.p2s)}catch(s){throw new u("Failed to base64url decode the p2s")}return Kt(e,t,r,n.p2c,i)}case"A128KW":case"A192KW":case"A256KW":{if(r===void 0)throw new u("JWE Encrypted Key missing");return fe(e,t,r)}case"A128GCMKW":case"A192GCMKW":case"A256GCMKW":{if(r===void 0)throw new u("JWE Encrypted Key missing");if(typeof n.iv!="string")throw new u('JOSE Header "iv" (Initialization Vector) missing or invalid');if(typeof n.tag!="string")throw new u('JOSE Header "tag" (Authentication Tag) missing or invalid');let a;try{a=S(n.iv)}catch(s){throw new u("Failed to base64url decode the iv")}let i;try{i=S(n.tag)}catch(s){throw new u("Failed to base64url decode the tag")}return Nt(e,t,r,a,i)}default:throw new l('Invalid or unsupported "alg" (JWE Algorithm) header value')}}var Lt=vr;function xr(e,t,r,n,o){if(o.crit!==void 0&&n.crit===void 0)throw new e('"crit" (Critical) Header Parameter MUST be integrity protected');if(!n||n.crit===void 0)return new Set;if(!Array.isArray(n.crit)||n.crit.length===0||n.crit.some(i=>typeof i!="string"||i.length===0))throw new e('"crit" (Critical) Header Parameter MUST be an array of non-empty strings when present');let a;r!==void 0?a=new Map([...Object.entries(r),...t.entries()]):a=t;for(let i of n.crit){if(!a.has(i))throw new l(`Extension Header Parameter "${i}" is not recognized`);if(o[i]===void 0)throw new e(`Extension Header Parameter "${i}" is missing`);if(a.get(i)&&n[i]===void 0)throw new e(`Extension Header Parameter "${i}" MUST be integrity protected`)}return new Set(n.crit)}var M=xr;var Kr=(e,t)=>{if(t!==void 0&&(!Array.isArray(t)||t.some(r=>typeof r!="string")))throw new TypeError(`"${e}" option must be an array of strings`);if(t)return new Set(t)},me=Kr;async function ye(e,t,r){var n;if(!y(e))throw new u("Flattened JWE must be an object");if(e.protected===void 0&&e.header===void 0&&e.unprotected===void 0)throw new u("JOSE Header missing");if(typeof e.iv!="string")throw new u("JWE Initialization Vector missing or incorrect type");if(typeof e.ciphertext!="string")throw new u("JWE Ciphertext missing or incorrect type");if(typeof e.tag!="string")throw new u("JWE Authentication Tag missing or incorrect type");if(e.protected!==void 0&&typeof e.protected!="string")throw new u("JWE Protected Header incorrect type");if(e.encrypted_key!==void 0&&typeof e.encrypted_key!="string")throw new u("JWE Encrypted Key incorrect type");if(e.aad!==void 0&&typeof e.aad!="string")throw new u("JWE AAD incorrect type");if(e.header!==void 0&&!y(e.header))throw new u("JWE Shared Unprotected Header incorrect type");if(e.unprotected!==void 0&&!y(e.unprotected))throw new u("JWE Per-Recipient Unprotected Header incorrect type");let o;if(e.protected)try{let R=S(e.protected);o=JSON.parse(H.decode(R))}catch(R){throw new u("JWE Protected Header is invalid")}if(!U(o,e.header,e.unprotected))throw new u("JWE Protected, JWE Unprotected Header, and JWE Per-Recipient Unprotected Header Parameter names must be disjoint");let a={...o,...e.header,...e.unprotected};if(M(u,new Map,r==null?void 0:r.crit,o,a),a.zip!==void 0){if(!o||!o.zip)throw new u('JWE "zip" (Compression Algorithm) Header MUST be integrity protected');if(a.zip!=="DEF")throw new l('Unsupported JWE "zip" (Compression Algorithm) Header Parameter value')}let{alg:i,enc:s}=a;if(typeof i!="string"||!i)throw new u("missing JWE Algorithm (alg) in JWE Header");if(typeof s!="string"||!s)throw new u("missing JWE Encryption Algorithm (enc) in JWE Header");let d=r&&me("keyManagementAlgorithms",r.keyManagementAlgorithms),c=r&&me("contentEncryptionAlgorithms",r.contentEncryptionAlgorithms);if(d&&!d.has(i))throw new L('"alg" (Algorithm) Header Parameter not allowed');if(c&&!c.has(s))throw new L('"enc" (Encryption Algorithm) Header Parameter not allowed');let p;if(e.encrypted_key!==void 0)try{p=S(e.encrypted_key)}catch(R){throw new u("Failed to base64url decode the encrypted_key")}let g=!1;typeof t=="function"&&(t=await t(o,e),g=!0);let b;try{b=await Lt(i,t,p,a,r)}catch(R){if(R instanceof TypeError||R instanceof u||R instanceof l)throw R;b=D(s)}let _,v;try{_=S(e.iv)}catch(R){throw new u("Failed to base64url decode the iv")}try{v=S(e.tag)}catch(R){throw new u("Failed to base64url decode the tag")}let K=w.encode((n=e.protected)!==null&&n!==void 0?n:""),O;e.aad!==void 0?O=J(K,w.encode("."),w.encode(e.aad)):O=K;let ct;try{ct=S(e.ciphertext)}catch(R){throw new u("Failed to base64url decode the ciphertext")}let De=await Te(s,b,ct,_,v,O);a.zip==="DEF"&&(De=await((r==null?void 0:r.inflateRaw)||Et)(De));let ee={plaintext:De};if(e.protected!==void 0&&(ee.protectedHeader=o),e.aad!==void 0)try{ee.additionalAuthenticatedData=S(e.aad)}catch(R){throw new u("Failed to base64url decode the aad")}return e.unprotected!==void 0&&(ee.sharedUnprotectedHeader=e.unprotected),e.header!==void 0&&(ee.unprotectedHeader=e.header),g?{...ee,key:t}:ee}async function Xe(e,t,r){if(e instanceof Uint8Array&&(e=H.decode(e)),typeof e!="string")throw new u("Compact JWE must be a string or Uint8Array");let{0:n,1:o,2:a,3:i,4:s,length:d}=e.split(".");if(d!==5)throw new u("Invalid Compact JWE");let c=await ye({ciphertext:i,iv:a||void 0,protected:n||void 0,tag:s||void 0,encrypted_key:o||void 0},t,r),p={plaintext:c.plaintext,protectedHeader:c.protectedHeader};return typeof t=="function"?{...p,key:c.key}:p}async function Hr(e,t,r){if(!y(e))throw new u("General JWE must be an object");if(!Array.isArray(e.recipients)||!e.recipients.every(y))throw new u("JWE Recipients missing or incorrect type");if(!e.recipients.length)throw new u("JWE Recipients has no members");for(let n of e.recipients)try{return await ye({aad:e.aad,ciphertext:e.ciphertext,encrypted_key:n.encrypted_key,header:n.header,iv:e.iv,protected:e.protected,tag:e.tag,unprotected:e.unprotected},t,r)}catch(o){}throw new N}var Cr=async e=>{if(e instanceof Uint8Array)return{kty:"oct",k:E(e)};if(!x(e))throw new TypeError(A(e,...m,"Uint8Array"));if(!e.extractable)throw new TypeError("non-extractable CryptoKey cannot be exported as a JWK");let{ext:t,key_ops:r,alg:n,use:o,...a}=await f.subtle.exportKey("jwk",e);return a},Bt=Cr;async function Pr(e){return It(e)}async function Wr(e){return Tt(e)}async function Ye(e){return Bt(e)}async function Jr(e,t,r,n,o={}){let a,i,s;switch(F(e,r,"encrypt"),e){case"dir":{s=r;break}case"ECDH-ES":case"ECDH-ES+A128KW":case"ECDH-ES+A192KW":case"ECDH-ES+A256KW":{if(!Oe(r))throw new l("ECDH with the provided key is not allowed or not supported by your javascript runtime");let{apu:d,apv:c}=o,{epk:p}=o;p||(p=(await bt(r)).privateKey);let{x:g,y:b,crv:_,kty:v}=await Ye(p),K=await Re(r,p,e==="ECDH-ES"?t:e,e==="ECDH-ES"?le(t):parseInt(e.slice(-5,-2),10),d,c);if(i={epk:{x:g,crv:_,kty:v}},v==="EC"&&(i.epk.y=b),d&&(i.apu=E(d)),c&&(i.apv=E(c)),e==="ECDH-ES"){s=K;break}s=n||D(t);let O=e.slice(-6);a=await ue(O,K,s);break}case"RSA1_5":case"RSA-OAEP":case"RSA-OAEP-256":case"RSA-OAEP-384":case"RSA-OAEP-512":{s=n||D(t),a=await Ht(e,r,s);break}case"PBES2-HS256+A128KW":case"PBES2-HS384+A192KW":case"PBES2-HS512+A256KW":{s=n||D(t);let{p2c:d,p2s:c}=o;({encryptedKey:a,...i}=await xt(e,r,s,d,c));break}case"A128KW":case"A192KW":case"A256KW":{s=n||D(t),a=await ue(e,r,s);break}case"A128GCMKW":case"A192GCMKW":case"A256GCMKW":{s=n||D(t);let{iv:d}=o;({encryptedKey:a,...i}=await Mt(e,r,s,d));break}default:throw new l('Invalid or unsupported "alg" (JWE Algorithm) header value')}return{cek:s,encryptedKey:a,parameters:i}}var Ue=Jr;var qe=Symbol(),V=class{constructor(t){if(!(t instanceof Uint8Array))throw new TypeError("plaintext must be an instance of Uint8Array");this._plaintext=t}setKeyManagementParameters(t){if(this._keyManagementParameters)throw new TypeError("setKeyManagementParameters can only be called once");return this._keyManagementParameters=t,this}setProtectedHeader(t){if(this._protectedHeader)throw new TypeError("setProtectedHeader can only be called once");return this._protectedHeader=t,this}setSharedUnprotectedHeader(t){if(this._sharedUnprotectedHeader)throw new TypeError("setSharedUnprotectedHeader can only be called once");return this._sharedUnprotectedHeader=t,this}setUnprotectedHeader(t){if(this._unprotectedHeader)throw new TypeError("setUnprotectedHeader can only be called once");return this._unprotectedHeader=t,this}setAdditionalAuthenticatedData(t){return this._aad=t,this}setContentEncryptionKey(t){if(this._cek)throw new TypeError("setContentEncryptionKey can only be called once");return this._cek=t,this}setInitializationVector(t){if(this._iv)throw new TypeError("setInitializationVector can only be called once");return this._iv=t,this}async encrypt(t,r){if(!this._protectedHeader&&!this._unprotectedHeader&&!this._sharedUnprotectedHeader)throw new u("either setProtectedHeader, setUnprotectedHeader, or sharedUnprotectedHeader must be called before #encrypt()");if(!U(this._protectedHeader,this._unprotectedHeader,this._sharedUnprotectedHeader))throw new u("JWE Protected, JWE Shared Unprotected and JWE Per-Recipient Header Parameter names must be disjoint");let n={...this._protectedHeader,...this._unprotectedHeader,...this._sharedUnprotectedHeader};if(M(u,new Map,r==null?void 0:r.crit,this._protectedHeader,n),n.zip!==void 0){if(!this._protectedHeader||!this._protectedHeader.zip)throw new u('JWE "zip" (Compression Algorithm) Header MUST be integrity protected');if(n.zip!=="DEF")throw new l('Unsupported JWE "zip" (Compression Algorithm) Header Parameter value')}let{alg:o,enc:a}=n;if(typeof o!="string"||!o)throw new u('JWE "alg" (Algorithm) Header Parameter missing or invalid');if(typeof a!="string"||!a)throw new u('JWE "enc" (Encryption Algorithm) Header Parameter missing or invalid');let i;if(o==="dir"){if(this._cek)throw new TypeError("setContentEncryptionKey cannot be called when using Direct Encryption")}else if(o==="ECDH-ES"&&this._cek)throw new TypeError("setContentEncryptionKey cannot be called when using Direct Key Agreement");let s;{let v;({cek:s,encryptedKey:i,parameters:v}=await Ue(o,a,t,this._cek,this._keyManagementParameters)),v&&(r&&qe in r?this._unprotectedHeader?this._unprotectedHeader={...this._unprotectedHeader,...v}:this.setUnprotectedHeader(v):this._protectedHeader?this._protectedHeader={...this._protectedHeader,...v}:this.setProtectedHeader(v))}this._iv||(this._iv=We(a));let d,c,p;this._protectedHeader?c=w.encode(E(JSON.stringify(this._protectedHeader))):c=w.encode(""),this._aad?(p=E(this._aad),d=J(c,w.encode("."),w.encode(p))):d=c;let g,b;if(n.zip==="DEF"){let v=await((r==null?void 0:r.deflateRaw)||gt)(this._plaintext);({ciphertext:g,tag:b}=await he(a,v,s,this._iv,d))}else({ciphertext:g,tag:b}=await he(a,this._plaintext,s,this._iv,d));let _={ciphertext:E(g),iv:E(this._iv),tag:E(b)};return i&&(_.encrypted_key=E(i)),p&&(_.aad=p),this._protectedHeader&&(_.protected=H.decode(c)),this._sharedUnprotectedHeader&&(_.unprotected=this._sharedUnprotectedHeader),this._unprotectedHeader&&(_.header=this._unprotectedHeader),_}};var Ze=class{constructor(t,r,n){this.parent=t,this.key=r,this.options=n}setUnprotectedHeader(t){if(this.unprotectedHeader)throw new TypeError("setUnprotectedHeader can only be called once");return this.unprotectedHeader=t,this}addRecipient(...t){return this.parent.addRecipient(...t)}encrypt(...t){return this.parent.encrypt(...t)}done(){return this.parent}},Qe=class{constructor(t){this._recipients=[],this._plaintext=t}addRecipient(t,r){let n=new Ze(this,t,{crit:r==null?void 0:r.crit});return this._recipients.push(n),n}setProtectedHeader(t){if(this._protectedHeader)throw new TypeError("setProtectedHeader can only be called once");return this._protectedHeader=t,this}setSharedUnprotectedHeader(t){if(this._unprotectedHeader)throw new TypeError("setSharedUnprotectedHeader can only be called once");return this._unprotectedHeader=t,this}setAdditionalAuthenticatedData(t){return this._aad=t,this}async encrypt(t){var r,n,o;if(!this._recipients.length)throw new u("at least one recipient must be added");if(t={deflateRaw:t==null?void 0:t.deflateRaw},this._recipients.length===1){let[d]=this._recipients,c=await new V(this._plaintext).setAdditionalAuthenticatedData(this._aad).setProtectedHeader(this._protectedHeader).setSharedUnprotectedHeader(this._unprotectedHeader).setUnprotectedHeader(d.unprotectedHeader).encrypt(d.key,{...d.options,...t}),p={ciphertext:c.ciphertext,iv:c.iv,recipients:[{}],tag:c.tag};return c.aad&&(p.aad=c.aad),c.protected&&(p.protected=c.protected),c.unprotected&&(p.unprotected=c.unprotected),c.encrypted_key&&(p.recipients[0].encrypted_key=c.encrypted_key),c.header&&(p.recipients[0].header=c.header),p}let a;for(let d=0;d<this._recipients.length;d++){let c=this._recipients[d];if(!U(this._protectedHeader,this._unprotectedHeader,c.unprotectedHeader))throw new u("JWE Protected, JWE Shared Unprotected and JWE Per-Recipient Header Parameter names must be disjoint");let p={...this._protectedHeader,...this._unprotectedHeader,...c.unprotectedHeader},{alg:g}=p;if(typeof g!="string"||!g)throw new u('JWE "alg" (Algorithm) Header Parameter missing or invalid');if(g==="dir"||g==="ECDH-ES")throw new u('"dir" and "ECDH-ES" alg may only be used with a single recipient');if(typeof p.enc!="string"||!p.enc)throw new u('JWE "enc" (Encryption Algorithm) Header Parameter missing or invalid');if(!a)a=p.enc;else if(a!==p.enc)throw new u('JWE "enc" (Encryption Algorithm) Header Parameter must be the same for all recipients');if(M(u,new Map,c.options.crit,this._protectedHeader,p),p.zip!==void 0&&(!this._protectedHeader||!this._protectedHeader.zip))throw new u('JWE "zip" (Compression Algorithm) Header MUST be integrity protected')}let i=D(a),s={ciphertext:"",iv:"",recipients:[],tag:""};for(let d=0;d<this._recipients.length;d++){let c=this._recipients[d],p={};s.recipients.push(p);let b={...this._protectedHeader,...this._unprotectedHeader,...c.unprotectedHeader}.alg.startsWith("PBES2")?2048+d:void 0;if(d===0){let K=await new V(this._plaintext).setAdditionalAuthenticatedData(this._aad).setContentEncryptionKey(i).setProtectedHeader(this._protectedHeader).setSharedUnprotectedHeader(this._unprotectedHeader).setUnprotectedHeader(c.unprotectedHeader).setKeyManagementParameters({p2c:b}).encrypt(c.key,{...c.options,...t,[qe]:!0});s.ciphertext=K.ciphertext,s.iv=K.iv,s.tag=K.tag,K.aad&&(s.aad=K.aad),K.protected&&(s.protected=K.protected),K.unprotected&&(s.unprotected=K.unprotected),p.encrypted_key=K.encrypted_key,K.header&&(p.header=K.header);continue}let{encryptedKey:_,parameters:v}=await Ue(((r=c.unprotectedHeader)===null||r===void 0?void 0:r.alg)||((n=this._protectedHeader)===null||n===void 0?void 0:n.alg)||((o=this._unprotectedHeader)===null||o===void 0?void 0:o.alg),a,c.key,i,{p2c:b});p.encrypted_key=E(_),(c.unprotectedHeader||v)&&(p.header={...c.unprotectedHeader,...v})}return s}};function we(e,t){let r=`SHA-${e.slice(-3)}`;switch(e){case"HS256":case"HS384":case"HS512":return{hash:r,name:"HMAC"};case"PS256":case"PS384":case"PS512":return{hash:r,name:"RSA-PSS",saltLength:e.slice(-3)>>3};case"RS256":case"RS384":case"RS512":return{hash:r,name:"RSASSA-PKCS1-v1_5"};case"ES256":case"ES384":case"ES512":return{hash:r,name:"ECDSA",namedCurve:t.namedCurve};case"EdDSA":return{name:t.name};default:throw new l(`alg ${e} is not supported either by JOSE or your javascript runtime`)}}function Ee(e,t,r){if(x(t))return yt(t,e,r),t;if(t instanceof Uint8Array){if(!e.startsWith("HS"))throw new TypeError(A(t,...m));return f.subtle.importKey("raw",t,{hash:`SHA-${e.slice(-3)}`,name:"HMAC"},!1,[r])}throw new TypeError(A(t,...m,"Uint8Array"))}var Ir=async(e,t,r,n)=>{let o=await Ee(e,t,"verify");Z(e,o);let a=we(e,o.algorithm);try{return await f.subtle.verify(a,o,r,n)}catch(i){return!1}},kt=Ir;async function ge(e,t,r){var n;if(!y(e))throw new h("Flattened JWS must be an object");if(e.protected===void 0&&e.header===void 0)throw new h('Flattened JWS must have either of the "protected" or "header" members');if(e.protected!==void 0&&typeof e.protected!="string")throw new h("JWS Protected Header incorrect type");if(e.payload===void 0)throw new h("JWS Payload missing");if(typeof e.signature!="string")throw new h("JWS Signature missing or incorrect type");if(e.header!==void 0&&!y(e.header))throw new h("JWS Unprotected Header incorrect type");let o={};if(e.protected)try{let O=S(e.protected);o=JSON.parse(H.decode(O))}catch(O){throw new h("JWS Protected Header is invalid")}if(!U(o,e.header))throw new h("JWS Protected and JWS Unprotected Header Parameter names must be disjoint");let a={...o,...e.header},i=M(h,new Map([["b64",!0]]),r==null?void 0:r.crit,o,a),s=!0;if(i.has("b64")&&(s=o.b64,typeof s!="boolean"))throw new h('The "b64" (base64url-encode payload) Header Parameter must be a boolean');let{alg:d}=a;if(typeof d!="string"||!d)throw new h('JWS "alg" (Algorithm) Header Parameter missing or invalid');let c=r&&me("algorithms",r.algorithms);if(c&&!c.has(d))throw new L('"alg" (Algorithm) Header Parameter not allowed');if(s){if(typeof e.payload!="string")throw new h("JWS Payload must be a string")}else if(typeof e.payload!="string"&&!(e.payload instanceof Uint8Array))throw new h("JWS Payload must be a string or an Uint8Array instance");let p=!1;typeof t=="function"&&(t=await t(o,e),p=!0),F(d,t,"verify");let g=J(w.encode((n=e.protected)!==null&&n!==void 0?n:""),w.encode("."),typeof e.payload=="string"?w.encode(e.payload):e.payload),b;try{b=S(e.signature)}catch(O){throw new h("Failed to base64url decode the signature")}if(!await kt(d,t,b,g))throw new q;let v;if(s)try{v=S(e.payload)}catch(O){throw new h("Failed to base64url decode the payload")}else typeof e.payload=="string"?v=w.encode(e.payload):v=e.payload;let K={payload:v};return e.protected!==void 0&&(K.protectedHeader=o),e.header!==void 0&&(K.unprotectedHeader=e.header),p?{...K,key:t}:K}async function je(e,t,r){if(e instanceof Uint8Array&&(e=H.decode(e)),typeof e!="string")throw new h("Compact JWS must be a string or Uint8Array");let{0:n,1:o,2:a,length:i}=e.split(".");if(i!==3)throw new h("Invalid Compact JWS");let s=await ge({payload:o,protected:n,signature:a},t,r),d={payload:s.payload,protectedHeader:s.protectedHeader};return typeof t=="function"?{...d,key:s.key}:d}async function Tr(e,t,r){if(!y(e))throw new h("General JWS must be an object");if(!Array.isArray(e.signatures)||!e.signatures.every(y))throw new h("JWS Signatures missing or incorrect type");for(let n of e.signatures)try{return await ge({header:n.header,payload:e.payload,protected:n.protected,signature:n.signature},t,r)}catch(o){}throw new q}var ae=e=>Math.floor(e.getTime()/1e3);var Rr=/^(\d+|\d+\.\d+) ?(seconds?|secs?|s|minutes?|mins?|m|hours?|hrs?|h|days?|d|weeks?|w|years?|yrs?|y)$/i,ie=e=>{let t=Rr.exec(e);if(!t)throw new TypeError("Invalid time period format");let r=parseFloat(t[1]);switch(t[2].toLowerCase()){case"sec":case"secs":case"second":case"seconds":case"s":return Math.round(r);case"minute":case"minutes":case"min":case"mins":case"m":return Math.round(r*60);case"hour":case"hours":case"hr":case"hrs":case"h":return Math.round(r*3600);case"day":case"days":case"d":return Math.round(r*86400);case"week":case"weeks":case"w":return Math.round(r*604800);default:return Math.round(r*31557600)}};var $t=e=>e.toLowerCase().replace(/^application\//,""),Or=(e,t)=>typeof e=="string"?t.includes(e):Array.isArray(e)?t.some(Set.prototype.has.bind(new Set(e))):!1,se=(e,t,r={})=>{let{typ:n}=r;if(n&&(typeof e.typ!="string"||$t(e.typ)!==$t(n)))throw new W('unexpected "typ" JWT header value',"typ","check_failed");let o;try{o=JSON.parse(H.decode(t))}catch(_){}if(!y(o))throw new P("JWT Claims Set must be a top-level JSON object");let{requiredClaims:a=[],issuer:i,subject:s,audience:d,maxTokenAge:c}=r;c!==void 0&&a.push("iat"),d!==void 0&&a.push("aud"),s!==void 0&&a.push("sub"),i!==void 0&&a.push("iss");for(let _ of new Set(a.reverse()))if(!(_ in o))throw new W(`missing required "${_}" claim`,_,"missing");if(i&&!(Array.isArray(i)?i:[i]).includes(o.iss))throw new W('unexpected "iss" claim value',"iss","check_failed");if(s&&o.sub!==s)throw new W('unexpected "sub" claim value',"sub","check_failed");if(d&&!Or(o.aud,typeof d=="string"?[d]:d))throw new W('unexpected "aud" claim value',"aud","check_failed");let p;switch(typeof r.clockTolerance){case"string":p=ie(r.clockTolerance);break;case"number":p=r.clockTolerance;break;case"undefined":p=0;break;default:throw new TypeError("Invalid clockTolerance option type")}let{currentDate:g}=r,b=ae(g||new Date);if((o.iat!==void 0||c)&&typeof o.iat!="number")throw new W('"iat" claim must be a number',"iat","invalid");if(o.nbf!==void 0){if(typeof o.nbf!="number")throw new W('"nbf" claim must be a number',"nbf","invalid");if(o.nbf>b+p)throw new W('"nbf" claim timestamp check failed',"nbf","check_failed")}if(o.exp!==void 0){if(typeof o.exp!="number")throw new W('"exp" claim must be a number',"exp","invalid");if(o.exp<=b-p)throw new te('"exp" claim timestamp check failed',"exp","check_failed")}if(c){let _=b-o.iat,v=typeof c=="number"?c:ie(c);if(_-p>v)throw new te('"iat" claim timestamp check failed (too far in the past)',"iat","check_failed");if(_<0-p)throw new W('"iat" claim timestamp check failed (it should be in the past)',"iat","check_failed")}return o};async function Ur(e,t,r){var n;let o=await je(e,t,r);if(!((n=o.protectedHeader.crit)===null||n===void 0)&&n.includes("b64")&&o.protectedHeader.b64===!1)throw new P("JWTs MUST NOT use unencoded payload");let i={payload:se(o.protectedHeader,o.payload,r),protectedHeader:o.protectedHeader};return typeof t=="function"?{...i,key:o.key}:i}async function Dr(e,t,r){let n=await Xe(e,t,r),o=se(n.protectedHeader,n.plaintext,r),{protectedHeader:a}=n;if(a.iss!==void 0&&a.iss!==o.iss)throw new W('replicated "iss" claim header parameter mismatch',"iss","mismatch");if(a.sub!==void 0&&a.sub!==o.sub)throw new W('replicated "sub" claim header parameter mismatch',"sub","mismatch");if(a.aud!==void 0&&JSON.stringify(a.aud)!==JSON.stringify(o.aud))throw new W('replicated "aud" claim header parameter mismatch',"aud","mismatch");let i={payload:o,protectedHeader:a};return typeof t=="function"?{...i,key:n.key}:i}var Se=class{constructor(t){this._flattened=new V(t)}setContentEncryptionKey(t){return this._flattened.setContentEncryptionKey(t),this}setInitializationVector(t){return this._flattened.setInitializationVector(t),this}setProtectedHeader(t){return this._flattened.setProtectedHeader(t),this}setKeyManagementParameters(t){return this._flattened.setKeyManagementParameters(t),this}async encrypt(t,r){let n=await this._flattened.encrypt(t,r);return[n.protected,n.encrypted_key,n.iv,n.ciphertext,n.tag].join(".")}};var Mr=async(e,t,r)=>{let n=await Ee(e,t,"sign");Z(e,n);let o=await f.subtle.sign(we(e,n.algorithm),n,r);return new Uint8Array(o)},Gt=Mr;var j=class{constructor(t){if(!(t instanceof Uint8Array))throw new TypeError("payload must be an instance of Uint8Array");this._payload=t}setProtectedHeader(t){if(this._protectedHeader)throw new TypeError("setProtectedHeader can only be called once");return this._protectedHeader=t,this}setUnprotectedHeader(t){if(this._unprotectedHeader)throw new TypeError("setUnprotectedHeader can only be called once");return this._unprotectedHeader=t,this}async sign(t,r){if(!this._protectedHeader&&!this._unprotectedHeader)throw new h("either setProtectedHeader or setUnprotectedHeader must be called before #sign()");if(!U(this._protectedHeader,this._unprotectedHeader))throw new h("JWS Protected and JWS Unprotected Header Parameter names must be disjoint");let n={...this._protectedHeader,...this._unprotectedHeader},o=M(h,new Map([["b64",!0]]),r==null?void 0:r.crit,this._protectedHeader,n),a=!0;if(o.has("b64")&&(a=this._protectedHeader.b64,typeof a!="boolean"))throw new h('The "b64" (base64url-encode payload) Header Parameter must be a boolean');let{alg:i}=n;if(typeof i!="string"||!i)throw new h('JWS "alg" (Algorithm) Header Parameter missing or invalid');F(i,t,"sign");let s=this._payload;a&&(s=w.encode(E(s)));let d;this._protectedHeader?d=w.encode(E(JSON.stringify(this._protectedHeader))):d=w.encode("");let c=J(d,w.encode("."),s),p=await Gt(i,t,c),g={signature:E(p),payload:""};return a&&(g.payload=H.decode(s)),this._unprotectedHeader&&(g.header=this._unprotectedHeader),this._protectedHeader&&(g.protected=H.decode(d)),g}};var Ae=class{constructor(t){this._flattened=new j(t)}setProtectedHeader(t){return this._flattened.setProtectedHeader(t),this}async sign(t,r){let n=await this._flattened.sign(t,r);if(n.payload===void 0)throw new TypeError("use the flattened module for creating JWS with b64: false");return`${n.protected}.${n.payload}.${n.signature}`}};var et=class{constructor(t,r,n){this.parent=t,this.key=r,this.options=n}setProtectedHeader(t){if(this.protectedHeader)throw new TypeError("setProtectedHeader can only be called once");return this.protectedHeader=t,this}setUnprotectedHeader(t){if(this.unprotectedHeader)throw new TypeError("setUnprotectedHeader can only be called once");return this.unprotectedHeader=t,this}addSignature(...t){return this.parent.addSignature(...t)}sign(...t){return this.parent.sign(...t)}done(){return this.parent}},tt=class{constructor(t){this._signatures=[],this._payload=t}addSignature(t,r){let n=new et(this,t,r);return this._signatures.push(n),n}async sign(){if(!this._signatures.length)throw new h("at least one signature must be added");let t={signatures:[],payload:""};for(let r=0;r<this._signatures.length;r++){let n=this._signatures[r],o=new j(this._payload);o.setProtectedHeader(n.protectedHeader),o.setUnprotectedHeader(n.unprotectedHeader);let{payload:a,...i}=await o.sign(n.key,n.options);if(r===0)t.payload=a;else if(t.payload!==a)throw new h("inconsistent use of JWS Unencoded Payload (RFC7797)");t.signatures.push(i)}return t}};var z=class{constructor(t){if(!y(t))throw new TypeError("JWT Claims Set MUST be an object");this._payload=t}setIssuer(t){return this._payload={...this._payload,iss:t},this}setSubject(t){return this._payload={...this._payload,sub:t},this}setAudience(t){return this._payload={...this._payload,aud:t},this}setJti(t){return this._payload={...this._payload,jti:t},this}setNotBefore(t){return typeof t=="number"?this._payload={...this._payload,nbf:t}:this._payload={...this._payload,nbf:ae(new Date)+ie(t)},this}setExpirationTime(t){return typeof t=="number"?this._payload={...this._payload,exp:t}:this._payload={...this._payload,exp:ae(new Date)+ie(t)},this}setIssuedAt(t){return typeof t=="undefined"?this._payload={...this._payload,iat:ae(new Date)}:this._payload={...this._payload,iat:t},this}};var rt=class extends z{setProtectedHeader(t){return this._protectedHeader=t,this}async sign(t,r){var n;let o=new Ae(w.encode(JSON.stringify(this._payload)));if(o.setProtectedHeader(this._protectedHeader),Array.isArray((n=this._protectedHeader)===null||n===void 0?void 0:n.crit)&&this._protectedHeader.crit.includes("b64")&&this._protectedHeader.b64===!1)throw new P("JWTs MUST NOT use unencoded payload");return o.sign(t,r)}};var nt=class extends z{setProtectedHeader(t){if(this._protectedHeader)throw new TypeError("setProtectedHeader can only be called once");return this._protectedHeader=t,this}setKeyManagementParameters(t){if(this._keyManagementParameters)throw new TypeError("setKeyManagementParameters can only be called once");return this._keyManagementParameters=t,this}setContentEncryptionKey(t){if(this._cek)throw new TypeError("setContentEncryptionKey can only be called once");return this._cek=t,this}setInitializationVector(t){if(this._iv)throw new TypeError("setInitializationVector can only be called once");return this._iv=t,this}replicateIssuerAsHeader(){return this._replicateIssuerAsHeader=!0,this}replicateSubjectAsHeader(){return this._replicateSubjectAsHeader=!0,this}replicateAudienceAsHeader(){return this._replicateAudienceAsHeader=!0,this}async encrypt(t,r){let n=new Se(w.encode(JSON.stringify(this._payload)));return this._replicateIssuerAsHeader&&(this._protectedHeader={...this._protectedHeader,iss:this._payload.iss}),this._replicateSubjectAsHeader&&(this._protectedHeader={...this._protectedHeader,sub:this._payload.sub}),this._replicateAudienceAsHeader&&(this._protectedHeader={...this._protectedHeader,aud:this._payload.aud}),n.setProtectedHeader(this._protectedHeader),this._iv&&n.setInitializationVector(this._iv),this._cek&&n.setContentEncryptionKey(this._cek),this._keyManagementParameters&&n.setKeyManagementParameters(this._keyManagementParameters),n.encrypt(t,r)}};var X=(e,t)=>{if(typeof e!="string"||!e)throw new ce(`${t} missing or invalid`)};async function Ft(e,t){if(!y(e))throw new TypeError("JWK must be an object");if(t!=null||(t="sha256"),t!=="sha256"&&t!=="sha384"&&t!=="sha512")throw new TypeError('digestAlgorithm must one of "sha256", "sha384", or "sha512"');let r;switch(e.kty){case"EC":X(e.crv,'"crv" (Curve) Parameter'),X(e.x,'"x" (X Coordinate) Parameter'),X(e.y,'"y" (Y Coordinate) Parameter'),r={crv:e.crv,kty:e.kty,x:e.x,y:e.y};break;case"OKP":X(e.crv,'"crv" (Subtype of Key Pair) Parameter'),X(e.x,'"x" (Public Key) Parameter'),r={crv:e.crv,kty:e.kty,x:e.x};break;case"RSA":X(e.e,'"e" (Exponent) Parameter'),X(e.n,'"n" (Modulus) Parameter'),r={e:e.e,kty:e.kty,n:e.n};break;case"oct":X(e.k,'"k" (Key Value) Parameter'),r={k:e.k,kty:e.kty};break;default:throw new l('"kty" (Key Type) Parameter missing or unsupported')}let n=w.encode(JSON.stringify(r));return E(await ve(t,n))}async function Nr(e,t){t!=null||(t="sha256");let r=await Ft(e,t);return`urn:ietf:params:oauth:jwk-thumbprint:sha-${t.slice(-3)}:${r}`}async function Lr(e,t){let r={...e,...t==null?void 0:t.header};if(!y(r.jwk))throw new h('"jwk" (JSON Web Key) Header Parameter must be a JSON object');let n=await Q({...r.jwk,ext:!0},r.alg,!0);if(n instanceof Uint8Array||n.type!=="public")throw new h('"jwk" (JSON Web Key) Header Parameter must be a public key');return n}function Br(e){switch(typeof e=="string"&&e.slice(0,2)){case"RS":case"PS":return"RSA";case"ES":return"EC";case"Ed":return"OKP";default:throw new l('Unsupported "alg" value for a JSON Web Key Set')}}function ot(e){return e&&typeof e=="object"&&Array.isArray(e.keys)&&e.keys.every(kr)}function kr(e){return y(e)}function $r(e){return typeof structuredClone=="function"?structuredClone(e):JSON.parse(JSON.stringify(e))}var be=class{constructor(t){if(this._cached=new WeakMap,!ot(t))throw new B("JSON Web Key Set malformed");this._jwks=$r(t)}async getKey(t,r){let{alg:n,kid:o}={...t,...r==null?void 0:r.header},a=Br(n),i=this._jwks.keys.filter(c=>{let p=a===c.kty;if(p&&typeof o=="string"&&(p=o===c.kid),p&&typeof c.alg=="string"&&(p=n===c.alg),p&&typeof c.use=="string"&&(p=c.use==="sig"),p&&Array.isArray(c.key_ops)&&(p=c.key_ops.includes("verify")),p&&n==="EdDSA"&&(p=c.crv==="Ed25519"||c.crv==="Ed448"),p)switch(n){case"ES256":p=c.crv==="P-256";break;case"ES256K":p=c.crv==="secp256k1";break;case"ES384":p=c.crv==="P-384";break;case"ES512":p=c.crv==="P-521";break}return p}),{0:s,length:d}=i;if(d===0)throw new Y;if(d!==1){let c=new de,{_cached:p}=this;throw c[Symbol.asyncIterator]=async function*(){for(let g of i)try{yield await Vt(p,g,n)}catch(b){continue}},c}return Vt(this._cached,s,n)}};async function Vt(e,t,r){let n=e.get(t)||e.set(t,{}).get(t);if(n[r]===void 0){let o=await Q({...t,ext:!0},r);if(o instanceof Uint8Array||o.type!=="public")throw new B("JSON Web Key Set members must be public keys");n[r]=o}return n[r]}function Gr(e){let t=new be(e);return async function(r,n){return t.getKey(r,n)}}var Fr=async(e,t,r)=>{let n,o,a=!1;typeof AbortController=="function"&&(n=new AbortController,o=setTimeout(()=>{a=!0,n.abort()},t));let i=await fetch(e.href,{signal:n?n.signal:void 0,redirect:"manual",headers:r.headers}).catch(s=>{throw a?new pe:s});if(o!==void 0&&clearTimeout(o),i.status!==200)throw new C("Expected 200 OK from the JSON Web Key Set HTTP response");try{return await i.json()}catch(s){throw new C("Failed to parse the JSON Web Key Set HTTP response as JSON")}},zt=Fr;function Vr(){return typeof WebSocketPair!="undefined"||typeof navigator!="undefined"&&navigator.userAgent==="Cloudflare-Workers"||typeof EdgeRuntime!="undefined"&&EdgeRuntime==="vercel"}var at=class extends be{constructor(t,r){if(super({keys:[]}),this._jwks=void 0,!(t instanceof URL))throw new TypeError("url must be an instance of URL");this._url=new URL(t.href),this._options={agent:r==null?void 0:r.agent,headers:r==null?void 0:r.headers},this._timeoutDuration=typeof(r==null?void 0:r.timeoutDuration)=="number"?r==null?void 0:r.timeoutDuration:5e3,this._cooldownDuration=typeof(r==null?void 0:r.cooldownDuration)=="number"?r==null?void 0:r.cooldownDuration:3e4,this._cacheMaxAge=typeof(r==null?void 0:r.cacheMaxAge)=="number"?r==null?void 0:r.cacheMaxAge:6e5}coolingDown(){return typeof this._jwksTimestamp=="number"?Date.now()<this._jwksTimestamp+this._cooldownDuration:!1}fresh(){return typeof this._jwksTimestamp=="number"?Date.now()<this._jwksTimestamp+this._cacheMaxAge:!1}async getKey(t,r){(!this._jwks||!this.fresh())&&await this.reload();try{return await super.getKey(t,r)}catch(n){if(n instanceof Y&&this.coolingDown()===!1)return await this.reload(),super.getKey(t,r);throw n}}async reload(){this._pendingFetch&&Vr()&&(this._pendingFetch=void 0),this._pendingFetch||(this._pendingFetch=zt(this._url,this._timeoutDuration,this._options).then(t=>{if(!ot(t))throw new B("JSON Web Key Set malformed");this._jwks={keys:t.keys},this._jwksTimestamp=Date.now(),this._pendingFetch=void 0}).catch(t=>{throw this._pendingFetch=void 0,t})),await this._pendingFetch}};function zr(e,t){let r=new at(e,t);return async function(n,o){return r.getKey(n,o)}}var it=class extends z{encode(){let t=E(JSON.stringify({alg:"none"})),r=E(JSON.stringify(this._payload));return`${t}.${r}.`}static decode(t,r){if(typeof t!="string")throw new P("Unsecured JWT must be a string");let{0:n,1:o,2:a,length:i}=t.split(".");if(i!==3||a!=="")throw new P("Invalid Unsecured JWT");let s;try{if(s=JSON.parse(H.decode(S(n))),s.alg!=="none")throw new Error}catch(c){throw new P("Invalid Unsecured JWT")}return{payload:se(s,S(o),r),header:s}}};var Xt={};dt(Xt,{decode:()=>_e,encode:()=>Xr});var Xr=E,_e=S;function Yr(e){let t;if(typeof e=="string"){let r=e.split(".");(r.length===3||r.length===5)&&([t]=r)}else if(typeof e=="object"&&e)if("protected"in e)t=e.protected;else throw new TypeError("Token does not contain a Protected Header");try{if(typeof t!="string"||!t)throw new Error;let r=JSON.parse(H.decode(_e(t)));if(!y(r))throw new Error;return r}catch(r){throw new TypeError("Invalid Token or Protected Header formatting")}}function qr(e){if(typeof e!="string")throw new P("JWTs must use Compact JWS serialization, JWT must be a string");let{1:t,length:r}=e.split(".");if(r===5)throw new P("Only JWTs using Compact JWS serialization can be decoded");if(r!==3)throw new P("Invalid JWT");if(!t)throw new P("JWTs must contain a payload");let n;try{n=_e(t)}catch(a){throw new P("Failed to base64url decode the payload")}let o;try{o=JSON.parse(H.decode(n))}catch(a){throw new P("Failed to parse the decoded payload as JSON")}if(!y(o))throw new P("Invalid JWT Claims Set");return o}async function Yt(e,t){var r;let n,o,a;switch(e){case"HS256":case"HS384":case"HS512":n=parseInt(e.slice(-3),10),o={name:"HMAC",hash:`SHA-${n}`,length:n},a=["sign","verify"];break;case"A128CBC-HS256":case"A192CBC-HS384":case"A256CBC-HS512":return n=parseInt(e.slice(-3),10),k(new Uint8Array(n>>3));case"A128KW":case"A192KW":case"A256KW":n=parseInt(e.slice(1,4),10),o={name:"AES-KW",length:n},a=["wrapKey","unwrapKey"];break;case"A128GCMKW":case"A192GCMKW":case"A256GCMKW":case"A128GCM":case"A192GCM":case"A256GCM":n=parseInt(e.slice(1,4),10),o={name:"AES-GCM",length:n},a=["encrypt","decrypt"];break;default:throw new l('Invalid or unsupported JWK "alg" (Algorithm) Parameter value')}return f.subtle.generateKey(o,(r=t==null?void 0:t.extractable)!==null&&r!==void 0?r:!1,a)}function st(e){var t;let r=(t=e==null?void 0:e.modulusLength)!==null&&t!==void 0?t:2048;if(typeof r!="number"||r<2048)throw new l("Invalid or unsupported modulusLength option provided, 2048 bits or larger keys must be used");return r}async function qt(e,t){var r,n,o;let a,i;switch(e){case"PS256":case"PS384":case"PS512":a={name:"RSA-PSS",hash:`SHA-${e.slice(-3)}`,publicExponent:new Uint8Array([1,0,1]),modulusLength:st(t)},i=["sign","verify"];break;case"RS256":case"RS384":case"RS512":a={name:"RSASSA-PKCS1-v1_5",hash:`SHA-${e.slice(-3)}`,publicExponent:new Uint8Array([1,0,1]),modulusLength:st(t)},i=["sign","verify"];break;case"RSA-OAEP":case"RSA-OAEP-256":case"RSA-OAEP-384":case"RSA-OAEP-512":a={name:"RSA-OAEP",hash:`SHA-${parseInt(e.slice(-3),10)||1}`,publicExponent:new Uint8Array([1,0,1]),modulusLength:st(t)},i=["decrypt","unwrapKey","encrypt","wrapKey"];break;case"ES256":a={name:"ECDSA",namedCurve:"P-256"},i=["sign","verify"];break;case"ES384":a={name:"ECDSA",namedCurve:"P-384"},i=["sign","verify"];break;case"ES512":a={name:"ECDSA",namedCurve:"P-521"},i=["sign","verify"];break;case"EdDSA":i=["sign","verify"];let s=(r=t==null?void 0:t.crv)!==null&&r!==void 0?r:"Ed25519";switch(s){case"Ed25519":case"Ed448":a={name:s};break;default:throw new l("Invalid or unsupported crv option provided")}break;case"ECDH-ES":case"ECDH-ES+A128KW":case"ECDH-ES+A192KW":case"ECDH-ES+A256KW":{i=["deriveKey","deriveBits"];let d=(n=t==null?void 0:t.crv)!==null&&n!==void 0?n:"P-256";switch(d){case"P-256":case"P-384":case"P-521":{a={name:"ECDH",namedCurve:d};break}case"X25519":case"X448":a={name:d};break;default:throw new l("Invalid or unsupported crv option provided, supported values are P-256, P-384, P-521, X25519, and X448")}break}default:throw new l('Invalid or unsupported JWK "alg" (Algorithm) Parameter value')}return f.subtle.generateKey(a,(o=t==null?void 0:t.extractable)!==null&&o!==void 0?o:!1,i)}async function Zr(e,t){return qt(e,t)}async function Qr(e,t){return Yt(e,t)}var Zt="WebCryptoAPI";var jr=Zt;export{Se as CompactEncrypt,Ae as CompactSign,Lr as EmbeddedJWK,nt as EncryptJWT,V as FlattenedEncrypt,j as FlattenedSign,Qe as GeneralEncrypt,tt as GeneralSign,rt as SignJWT,it as UnsecuredJWT,Xt as base64url,Ft as calculateJwkThumbprint,Nr as calculateJwkThumbprintUri,Xe as compactDecrypt,je as compactVerify,Gr as createLocalJWKSet,zr as createRemoteJWKSet,jr as cryptoRuntime,qr as decodeJwt,Yr as decodeProtectedHeader,lt as errors,Ye as exportJWK,Wr as exportPKCS8,Pr as exportSPKI,ye as flattenedDecrypt,ge as flattenedVerify,Hr as generalDecrypt,Tr as generalVerify,Zr as generateKeyPair,Qr as generateSecret,Q as importJWK,wr as importPKCS8,mr as importSPKI,yr as importX509,Dr as jwtDecrypt,Ur as jwtVerify};
|