jose/dist/browser/index.bundle.min.js
2021-11-05 23:44:40 +01:00

4 lines
56 KiB
JavaScript

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