Huge News!Announcing our $40M Series B led by Abstract Ventures.Learn More
Socket
Sign inDemoInstall
Socket

jose-browser-runtime

Package Overview
Dependencies
Maintainers
1
Versions
132
Alerts
File Explorer

Advanced tools

Socket logo

Install Socket

Detect and block malicious and high-risk dependencies

Install

jose-browser-runtime - npm Package Compare versions

Comparing version 5.0.1 to 5.0.2

4

dist/browser/index.bundle.min.js

@@ -1,4 +0,4 @@

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

@@ -1,5 +0,5 @@

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

@@ -9,2 +9,8 @@ import fetchJwks from '../runtime/fetch_jwks.js';

}
let USER_AGENT;
if (typeof navigator === 'undefined' || !navigator.userAgent?.startsWith?.('Mozilla/5.0 ')) {
const NAME = 'jose';
const VERSION = 'v5.0.2';
USER_AGENT = `${NAME}/${VERSION}`;
}
class RemoteJWKSet extends LocalJWKSet {

@@ -56,2 +62,7 @@ constructor(url, options) {

}
const headers = new Headers(this._options.headers);
if (USER_AGENT && !headers.has('User-Agent')) {
headers.set('User-Agent', USER_AGENT);
this._options.headers = Object.fromEntries(headers.entries());
}
this._pendingFetch || (this._pendingFetch = fetchJwks(this._url, this._timeoutDuration, this._options)

@@ -58,0 +69,0 @@ .then((json) => {

@@ -13,3 +13,3 @@ # `jose` API Documentation

```js
import * as jose from 'https://deno.land/x/jose@v5.0.1/index.ts'
import * as jose from 'https://deno.land/x/jose@v5.0.2/index.ts'
```

@@ -21,9 +21,9 @@

- [Signing](https://github.com/panva/jose/blob/v5.0.1/docs/classes/jwt_sign.SignJWT.md) using the `SignJWT` class
- [Verification & JWT Claims Set Validation](https://github.com/panva/jose/blob/v5.0.1/docs/functions/jwt_verify.jwtVerify.md) using the `jwtVerify` function
- [Using a remote JWKS](https://github.com/panva/jose/blob/v5.0.1/docs/functions/jwks_remote.createRemoteJWKSet.md)
- [Using a local JWKS](https://github.com/panva/jose/blob/v5.0.1/docs/functions/jwks_local.createLocalJWKSet.md)
- [Signing](https://github.com/panva/jose/blob/v5.0.2/docs/classes/jwt_sign.SignJWT.md) using the `SignJWT` class
- [Verification & JWT Claims Set Validation](https://github.com/panva/jose/blob/v5.0.2/docs/functions/jwt_verify.jwtVerify.md) using the `jwtVerify` function
- [Using a remote JWKS](https://github.com/panva/jose/blob/v5.0.2/docs/functions/jwks_remote.createRemoteJWKSet.md)
- [Using a local JWKS](https://github.com/panva/jose/blob/v5.0.2/docs/functions/jwks_local.createLocalJWKSet.md)
- Utility functions
- [Decoding Token's Protected Header](https://github.com/panva/jose/blob/v5.0.1/docs/functions/util_decode_protected_header.decodeProtectedHeader.md)
- [Decoding JWT Claims Set](https://github.com/panva/jose/blob/v5.0.1/docs/functions/util_decode_jwt.decodeJwt.md) prior to its validation
- [Decoding Token's Protected Header](https://github.com/panva/jose/blob/v5.0.2/docs/functions/util_decode_protected_header.decodeProtectedHeader.md)
- [Decoding JWT Claims Set](https://github.com/panva/jose/blob/v5.0.2/docs/functions/util_decode_jwt.decodeJwt.md) prior to its validation

@@ -34,6 +34,6 @@ ### Encrypted JSON Web Tokens

- [Encryption](https://github.com/panva/jose/blob/v5.0.1/docs/classes/jwt_encrypt.EncryptJWT.md) using the `EncryptJWT` class
- [Decryption & JWT Claims Set Validation](https://github.com/panva/jose/blob/v5.0.1/docs/functions/jwt_decrypt.jwtDecrypt.md) using the `jwtDecrypt` function
- [Encryption](https://github.com/panva/jose/blob/v5.0.2/docs/classes/jwt_encrypt.EncryptJWT.md) using the `EncryptJWT` class
- [Decryption & JWT Claims Set Validation](https://github.com/panva/jose/blob/v5.0.2/docs/functions/jwt_decrypt.jwtDecrypt.md) using the `jwtDecrypt` function
- Utility functions
- [Decoding Token's Protected Header](https://github.com/panva/jose/blob/v5.0.1/docs/functions/util_decode_protected_header.decodeProtectedHeader.md)
- [Decoding Token's Protected Header](https://github.com/panva/jose/blob/v5.0.2/docs/functions/util_decode_protected_header.decodeProtectedHeader.md)

@@ -45,13 +45,13 @@ ### Key Utilities

- Key Import Functions
- [JWK Import](https://github.com/panva/jose/blob/v5.0.1/docs/functions/key_import.importJWK.md)
- [Public Key Import (SPKI)](https://github.com/panva/jose/blob/v5.0.1/docs/functions/key_import.importSPKI.md)
- [Public Key Import (X.509 Certificate)](https://github.com/panva/jose/blob/v5.0.1/docs/functions/key_import.importX509.md)
- [Private Key Import (PKCS #8)](https://github.com/panva/jose/blob/v5.0.1/docs/functions/key_import.importPKCS8.md)
- [JWK Import](https://github.com/panva/jose/blob/v5.0.2/docs/functions/key_import.importJWK.md)
- [Public Key Import (SPKI)](https://github.com/panva/jose/blob/v5.0.2/docs/functions/key_import.importSPKI.md)
- [Public Key Import (X.509 Certificate)](https://github.com/panva/jose/blob/v5.0.2/docs/functions/key_import.importX509.md)
- [Private Key Import (PKCS #8)](https://github.com/panva/jose/blob/v5.0.2/docs/functions/key_import.importPKCS8.md)
- Key and Secret Generation Functions
- [Asymmetric Key Pair Generation](https://github.com/panva/jose/blob/v5.0.1/docs/functions/key_generate_key_pair.generateKeyPair.md)
- [Symmetric Secret Generation](https://github.com/panva/jose/blob/v5.0.1/docs/functions/key_generate_secret.generateSecret.md)
- [Asymmetric Key Pair Generation](https://github.com/panva/jose/blob/v5.0.2/docs/functions/key_generate_key_pair.generateKeyPair.md)
- [Symmetric Secret Generation](https://github.com/panva/jose/blob/v5.0.2/docs/functions/key_generate_secret.generateSecret.md)
- Key Export Functions
- [JWK Export](https://github.com/panva/jose/blob/v5.0.1/docs/functions/key_export.exportJWK.md)
- [Private Key Export](https://github.com/panva/jose/blob/v5.0.1/docs/functions/key_export.exportPKCS8.md)
- [Public Key Export](https://github.com/panva/jose/blob/v5.0.1/docs/functions/key_export.exportSPKI.md)
- [JWK Export](https://github.com/panva/jose/blob/v5.0.2/docs/functions/key_export.exportJWK.md)
- [Private Key Export](https://github.com/panva/jose/blob/v5.0.2/docs/functions/key_export.exportPKCS8.md)
- [Public Key Export](https://github.com/panva/jose/blob/v5.0.2/docs/functions/key_export.exportSPKI.md)

@@ -62,8 +62,8 @@ ### JSON Web Signature (JWS)

- Signing - [Compact](https://github.com/panva/jose/blob/v5.0.1/docs/classes/jws_compact_sign.CompactSign.md), [Flattened JSON](https://github.com/panva/jose/blob/v5.0.1/docs/classes/jws_flattened_sign.FlattenedSign.md), [General JSON](https://github.com/panva/jose/blob/v5.0.1/docs/classes/jws_general_sign.GeneralSign.md)
- Verification - [Compact](https://github.com/panva/jose/blob/v5.0.1/docs/functions/jws_compact_verify.compactVerify.md), [Flattened JSON](https://github.com/panva/jose/blob/v5.0.1/docs/functions/jws_flattened_verify.flattenedVerify.md), [General JSON](https://github.com/panva/jose/blob/v5.0.1/docs/functions/jws_general_verify.generalVerify.md)
- [Verify using a remote JWKS](https://github.com/panva/jose/blob/v5.0.1/docs/functions/jwks_remote.createRemoteJWKSet.md)
- [Verify using a local JWKS](https://github.com/panva/jose/blob/v5.0.1/docs/functions/jwks_local.createLocalJWKSet.md)
- Signing - [Compact](https://github.com/panva/jose/blob/v5.0.2/docs/classes/jws_compact_sign.CompactSign.md), [Flattened JSON](https://github.com/panva/jose/blob/v5.0.2/docs/classes/jws_flattened_sign.FlattenedSign.md), [General JSON](https://github.com/panva/jose/blob/v5.0.2/docs/classes/jws_general_sign.GeneralSign.md)
- Verification - [Compact](https://github.com/panva/jose/blob/v5.0.2/docs/functions/jws_compact_verify.compactVerify.md), [Flattened JSON](https://github.com/panva/jose/blob/v5.0.2/docs/functions/jws_flattened_verify.flattenedVerify.md), [General JSON](https://github.com/panva/jose/blob/v5.0.2/docs/functions/jws_general_verify.generalVerify.md)
- [Verify using a remote JWKS](https://github.com/panva/jose/blob/v5.0.2/docs/functions/jwks_remote.createRemoteJWKSet.md)
- [Verify using a local JWKS](https://github.com/panva/jose/blob/v5.0.2/docs/functions/jwks_local.createLocalJWKSet.md)
- Utility functions
- [Decoding Token's Protected Header](https://github.com/panva/jose/blob/v5.0.1/docs/functions/util_decode_protected_header.decodeProtectedHeader.md)
- [Decoding Token's Protected Header](https://github.com/panva/jose/blob/v5.0.2/docs/functions/util_decode_protected_header.decodeProtectedHeader.md)

@@ -74,6 +74,6 @@ ### JSON Web Encryption (JWE)

- Encryption - [Compact](https://github.com/panva/jose/blob/v5.0.1/docs/classes/jwe_compact_encrypt.CompactEncrypt.md), [Flattened JSON](https://github.com/panva/jose/blob/v5.0.1/docs/classes/jwe_flattened_encrypt.FlattenedEncrypt.md), [General JSON](https://github.com/panva/jose/blob/v5.0.1/docs/classes/jwe_general_encrypt.GeneralEncrypt.md)
- Decryption - [Compact](https://github.com/panva/jose/blob/v5.0.1/docs/functions/jwe_compact_decrypt.compactDecrypt.md), [Flattened JSON](https://github.com/panva/jose/blob/v5.0.1/docs/functions/jwe_flattened_decrypt.flattenedDecrypt.md), [General JSON](https://github.com/panva/jose/blob/v5.0.1/docs/functions/jwe_general_decrypt.generalDecrypt.md)
- Encryption - [Compact](https://github.com/panva/jose/blob/v5.0.2/docs/classes/jwe_compact_encrypt.CompactEncrypt.md), [Flattened JSON](https://github.com/panva/jose/blob/v5.0.2/docs/classes/jwe_flattened_encrypt.FlattenedEncrypt.md), [General JSON](https://github.com/panva/jose/blob/v5.0.2/docs/classes/jwe_general_encrypt.GeneralEncrypt.md)
- Decryption - [Compact](https://github.com/panva/jose/blob/v5.0.2/docs/functions/jwe_compact_decrypt.compactDecrypt.md), [Flattened JSON](https://github.com/panva/jose/blob/v5.0.2/docs/functions/jwe_flattened_decrypt.flattenedDecrypt.md), [General JSON](https://github.com/panva/jose/blob/v5.0.2/docs/functions/jwe_general_decrypt.generalDecrypt.md)
- Utility functions
- [Decoding Token's Protected Header](https://github.com/panva/jose/blob/v5.0.1/docs/functions/util_decode_protected_header.decodeProtectedHeader.md)
- [Decoding Token's Protected Header](https://github.com/panva/jose/blob/v5.0.2/docs/functions/util_decode_protected_header.decodeProtectedHeader.md)

@@ -84,6 +84,6 @@ ### Other

- [Calculating JWK Thumbprint](https://github.com/panva/jose/blob/v5.0.1/docs/functions/jwk_thumbprint.calculateJwkThumbprint.md)
- [Calculating JWK Thumbprint URI](https://github.com/panva/jose/blob/v5.0.1/docs/functions/jwk_thumbprint.calculateJwkThumbprintUri.md)
- [Verification using a JWK Embedded in a JWS Header](https://github.com/panva/jose/blob/v5.0.1/docs/functions/jwk_embedded.EmbeddedJWK.md)
- [Unsecured JWT](https://github.com/panva/jose/blob/v5.0.1/docs/classes/jwt_unsecured.UnsecuredJWT.md)
- [JOSE Errors](https://github.com/panva/jose/blob/v5.0.1/docs/modules/util_errors.md)
- [Calculating JWK Thumbprint](https://github.com/panva/jose/blob/v5.0.2/docs/functions/jwk_thumbprint.calculateJwkThumbprint.md)
- [Calculating JWK Thumbprint URI](https://github.com/panva/jose/blob/v5.0.2/docs/functions/jwk_thumbprint.calculateJwkThumbprintUri.md)
- [Verification using a JWK Embedded in a JWS Header](https://github.com/panva/jose/blob/v5.0.2/docs/functions/jwk_embedded.EmbeddedJWK.md)
- [Unsecured JWT](https://github.com/panva/jose/blob/v5.0.2/docs/classes/jwt_unsecured.UnsecuredJWT.md)
- [JOSE Errors](https://github.com/panva/jose/blob/v5.0.2/docs/modules/util_errors.md)

@@ -12,4 +12,4 @@ import type { KeyLike, JWSHeaderParameters, JSONWebKeySet, FlattenedJWSInput } from '../types';

/**
* Returns a function that resolves to a key object from a locally stored, or otherwise available,
* JSON Web Key Set.
* Returns a function that resolves a JWS JOSE Header to a public key object from a locally stored,
* or otherwise available, JSON Web Key Set.
*

@@ -25,4 +25,7 @@ * It uses the "alg" (JWS Algorithm) Header Parameter to determine the right JWK "kty" (Key Type),

*
* Note: The function's purpose is to resolve public keys used for verifying signatures and will not
* work for public encryption keys.
*
* @param jwks JSON Web Key Set formatted object.
*/
export declare function createLocalJWKSet<KeyLikeType extends KeyLike = KeyLike>(jwks: JSONWebKeySet): (protectedHeader?: JWSHeaderParameters, token?: FlattenedJWSInput) => Promise<KeyLikeType>;

@@ -28,10 +28,14 @@ import type { KeyLike, JWSHeaderParameters, FlattenedJWSInput } from '../types';

agent?: any;
/** Optional headers to be sent with the HTTP request. */
/**
* Headers to be sent with the HTTP request. Default is that `User-Agent: jose/v${version}` header
* is added unless the runtime is a browser in which adding an explicit headers fetch
* configuration would cause an unnecessary CORS preflight request.
*/
headers?: Record<string, string>;
}
/**
* Returns a function that resolves to a key object downloaded from a remote endpoint returning a
* JSON Web Key Set, that is, for example, an OAuth 2.0 or OIDC jwks_uri. The JSON Web Key Set is
* fetched when no key matches the selection process but only as frequently as the
* `cooldownDuration` option allows to prevent abuse.
* Returns a function that resolves a JWS JOSE Header to a public key object downloaded from a
* remote endpoint returning a JSON Web Key Set, that is, for example, an OAuth 2.0 or OIDC
* jwks_uri. The JSON Web Key Set is fetched when no key matches the selection process but only as
* frequently as the `cooldownDuration` option allows to prevent abuse.
*

@@ -47,2 +51,5 @@ * It uses the "alg" (JWS Algorithm) Header Parameter to determine the right JWK "kty" (Key Type),

*
* Note: The function's purpose is to resolve public keys used for verifying signatures and will not
* work for public encryption keys.
*
* @param url URL to fetch the JSON Web Key Set from.

@@ -49,0 +56,0 @@ * @param options Options for the remote JSON Web Key Set.

{
"name": "jose-browser-runtime",
"version": "5.0.1",
"version": "5.0.2",
"homepage": "https://github.com/panva/jose",

@@ -5,0 +5,0 @@ "repository": "panva/jose",

Sorry, the diff of this file is too big to display

Sorry, the diff of this file is too big to display

SocketSocket SOC 2 Logo

Product

  • Package Alerts
  • Integrations
  • Docs
  • Pricing
  • FAQ
  • Roadmap
  • Changelog

Packages

npm

Stay in touch

Get open source security insights delivered straight into your inbox.


  • Terms
  • Privacy
  • Security

Made with ⚡️ by Socket Inc