From 27d26a47494044adac8232c5d4e6f114d7a9d9cb Mon Sep 17 00:00:00 2001 From: Filip Skokan Date: Sun, 20 Oct 2024 22:57:39 +0200 Subject: [PATCH] chore(release): 5.9.6 --- CHANGELOG.md | 7 ++++ dist/browser/index.bundle.js | 2 +- dist/browser/index.bundle.min.js | 2 +- dist/browser/index.umd.js | 2 +- dist/browser/index.umd.min.js | 2 +- dist/browser/jwks/remote.js | 2 +- dist/deno/README.md | 64 ++++++++++++++++---------------- dist/deno/jwks/remote.ts | 2 +- dist/node/cjs/jwks/remote.js | 2 +- dist/node/esm/jwks/remote.js | 2 +- package-lock.json | 4 +- package.json | 2 +- src/jwks/remote.ts | 2 +- 13 files changed, 51 insertions(+), 44 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 7059f328de..700199d603 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -2,6 +2,13 @@ All notable changes to this project will be documented in this file. See [standard-version](https://github.com/conventional-changelog/standard-version) for commit guidelines. +## [5.9.6](https://github.com/panva/jose/compare/v5.9.5...v5.9.6) (2024-10-20) + + +### Reverts + +* Revert "refactor(build): simplify package exports" ([2ef3a52](https://github.com/panva/jose/commit/2ef3a5266e2f903aab2f8c9d43437151d7da0122)) + ## [5.9.5](https://github.com/panva/jose/compare/v5.9.4...v5.9.5) (2024-10-20) diff --git a/dist/browser/index.bundle.js b/dist/browser/index.bundle.js index d41a980f30..7516ba19e3 100644 --- a/dist/browser/index.bundle.js +++ b/dist/browser/index.bundle.js @@ -3118,7 +3118,7 @@ function isCloudflareWorkers() { var USER_AGENT; if (typeof navigator === "undefined" || !navigator.userAgent?.startsWith?.("Mozilla/5.0 ")) { const NAME = "jose"; - const VERSION = "v5.9.5"; + const VERSION = "v5.9.6"; USER_AGENT = `${NAME}/${VERSION}`; } var jwksCache = Symbol(); diff --git a/dist/browser/index.bundle.min.js b/dist/browser/index.bundle.min.js index eb3c7d83bf..b29b8ab227 100644 --- a/dist/browser/index.bundle.min.js +++ b/dist/browser/index.bundle.min.js @@ -1,4 +1,4 @@ var fr=Object.defineProperty;var yt=(e,t)=>{for(var r in t)fr(e,r,{get:t[r],enumerable:!0})};var f=crypto,K=e=>e instanceof CryptoKey;var ur=async(e,t)=>{let r=`SHA-${e.slice(-3)}`;return new Uint8Array(await f.subtle.digest(r,t))},We=ur;var w=new TextEncoder,x=new TextDecoder,ve=2**32;function W(...e){let t=e.reduce((o,{length:a})=>o+a,0),r=new Uint8Array(t),n=0;for(let o of e)r.set(o,n),n+=o.length;return r}function wt(e,t){return W(w.encode(e),new Uint8Array([0]),t)}function ze(e,t,r){if(t<0||t>=ve)throw new RangeError(`value must be >= 0 and <= ${ve-1}. Received ${t}`);e.set([t>>>24,t>>>16,t>>>8,t&255],r)}function Je(e){let t=Math.floor(e/ve),r=e%ve,n=new Uint8Array(8);return ze(n,t,0),ze(n,r,4),n}function Te(e){let t=new Uint8Array(4);return ze(t,e),t}function Ie(e){return W(Te(e.length),e)}async function Et(e,t,r){let n=Math.ceil((t>>3)/32),o=new Uint8Array(n*32);for(let a=0;a>3)}var Oe=e=>{let t=e;typeof t=="string"&&(t=w.encode(t));let r=32768,n=[];for(let o=0;oOe(e).replace(/=/g,"").replace(/\+/g,"-").replace(/\//g,"_"),Xe=e=>{let t=atob(e),r=new Uint8Array(t.length);for(let n=0;n{let t=e;t instanceof Uint8Array&&(t=x.decode(t)),t=t.replace(/-/g,"+").replace(/_/g,"/").replace(/\s/g,"");try{return Xe(t)}catch{throw new TypeError("The input to be decoded is not correctly encoded.")}};var St={};yt(St,{JOSEAlgNotAllowed:()=>N,JOSEError:()=>H,JOSENotSupported:()=>u,JWEDecryptionFailed:()=>O,JWEInvalid:()=>c,JWKInvalid:()=>ae,JWKSInvalid:()=>Z,JWKSMultipleMatchingKeys:()=>ie,JWKSNoMatchingKey:()=>k,JWKSTimeout:()=>se,JWSInvalid:()=>m,JWSSignatureVerificationFailed:()=>B,JWTClaimValidationFailed:()=>C,JWTExpired:()=>q,JWTInvalid:()=>_});var H=class extends Error{constructor(t,r){super(t,r),this.code="ERR_JOSE_GENERIC",this.name=this.constructor.name,Error.captureStackTrace?.(this,this.constructor)}};H.code="ERR_JOSE_GENERIC";var C=class extends H{constructor(t,r,n="unspecified",o="unspecified"){super(t,{cause:{claim:n,reason:o,payload:r}}),this.code="ERR_JWT_CLAIM_VALIDATION_FAILED",this.claim=n,this.reason=o,this.payload=r}};C.code="ERR_JWT_CLAIM_VALIDATION_FAILED";var q=class extends H{constructor(t,r,n="unspecified",o="unspecified"){super(t,{cause:{claim:n,reason:o,payload:r}}),this.code="ERR_JWT_EXPIRED",this.claim=n,this.reason=o,this.payload=r}};q.code="ERR_JWT_EXPIRED";var N=class extends H{constructor(){super(...arguments),this.code="ERR_JOSE_ALG_NOT_ALLOWED"}};N.code="ERR_JOSE_ALG_NOT_ALLOWED";var u=class extends H{constructor(){super(...arguments),this.code="ERR_JOSE_NOT_SUPPORTED"}};u.code="ERR_JOSE_NOT_SUPPORTED";var O=class extends H{constructor(t="decryption operation failed",r){super(t,r),this.code="ERR_JWE_DECRYPTION_FAILED"}};O.code="ERR_JWE_DECRYPTION_FAILED";var c=class extends H{constructor(){super(...arguments),this.code="ERR_JWE_INVALID"}};c.code="ERR_JWE_INVALID";var m=class extends H{constructor(){super(...arguments),this.code="ERR_JWS_INVALID"}};m.code="ERR_JWS_INVALID";var _=class extends H{constructor(){super(...arguments),this.code="ERR_JWT_INVALID"}};_.code="ERR_JWT_INVALID";var ae=class extends H{constructor(){super(...arguments),this.code="ERR_JWK_INVALID"}};ae.code="ERR_JWK_INVALID";var Z=class extends H{constructor(){super(...arguments),this.code="ERR_JWKS_INVALID"}};Z.code="ERR_JWKS_INVALID";var k=class extends H{constructor(t="no applicable key found in the JSON Web Key Set",r){super(t,r),this.code="ERR_JWKS_NO_MATCHING_KEY"}};k.code="ERR_JWKS_NO_MATCHING_KEY";var ie=class extends H{constructor(t="multiple matching keys found in the JSON Web Key Set",r){super(t,r),this.code="ERR_JWKS_MULTIPLE_MATCHING_KEYS"}};ie.code="ERR_JWKS_MULTIPLE_MATCHING_KEYS";var se=class extends H{constructor(t="request timed out",r){super(t,r),this.code="ERR_JWKS_TIMEOUT"}};se.code="ERR_JWKS_TIMEOUT";var B=class extends H{constructor(t="signature verification failed",r){super(t,r),this.code="ERR_JWS_SIGNATURE_VERIFICATION_FAILED"}};B.code="ERR_JWS_SIGNATURE_VERIFICATION_FAILED";var G=f.getRandomValues.bind(f);function Ye(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 u(`Unsupported JWE Algorithm: ${e}`)}}var bt=e=>G(new Uint8Array(Ye(e)>>3));var hr=(e,t)=>{if(t.length<<3!==Ye(e))throw new c("Invalid Initialization Vector length")},Re=hr;var lr=(e,t)=>{let r=e.byteLength<<3;if(r!==t)throw new c(`Invalid Content Encryption Key length. Expected ${t} bits, got ${r} bits`)},ce=lr;var mr=(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(;++oe.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 xt(e,t,...r){switch(t){case"HS256":case"HS384":case"HS512":{if(!F(e.algorithm,"HMAC"))throw v("HMAC");let n=parseInt(t.slice(2),10);if(Ue(e.algorithm.hash)!==n)throw v(`SHA-${n}`,"algorithm.hash");break}case"RS256":case"RS384":case"RS512":{if(!F(e.algorithm,"RSASSA-PKCS1-v1_5"))throw v("RSASSA-PKCS1-v1_5");let n=parseInt(t.slice(2),10);if(Ue(e.algorithm.hash)!==n)throw v(`SHA-${n}`,"algorithm.hash");break}case"PS256":case"PS384":case"PS512":{if(!F(e.algorithm,"RSA-PSS"))throw v("RSA-PSS");let n=parseInt(t.slice(2),10);if(Ue(e.algorithm.hash)!==n)throw v(`SHA-${n}`,"algorithm.hash");break}case"EdDSA":{if(e.algorithm.name!=="Ed25519"&&e.algorithm.name!=="Ed448")throw v("Ed25519 or Ed448");break}case"ES256":case"ES384":case"ES512":{if(!F(e.algorithm,"ECDSA"))throw v("ECDSA");let n=yr(t);if(e.algorithm.namedCurve!==n)throw v(n,"algorithm.namedCurve");break}default:throw new TypeError("CryptoKey does not support this operation")}Kt(e,r)}function I(e,t,...r){switch(t){case"A128GCM":case"A192GCM":case"A256GCM":{if(!F(e.algorithm,"AES-GCM"))throw v("AES-GCM");let n=parseInt(t.slice(1,4),10);if(e.algorithm.length!==n)throw v(n,"algorithm.length");break}case"A128KW":case"A192KW":case"A256KW":{if(!F(e.algorithm,"AES-KW"))throw v("AES-KW");let n=parseInt(t.slice(1,4),10);if(e.algorithm.length!==n)throw v(n,"algorithm.length");break}case"ECDH":{switch(e.algorithm.name){case"ECDH":case"X25519":case"X448":break;default:throw v("ECDH, X25519, or X448")}break}case"PBES2-HS256+A128KW":case"PBES2-HS384+A192KW":case"PBES2-HS512+A256KW":if(!F(e.algorithm,"PBKDF2"))throw v("PBKDF2");break;case"RSA-OAEP":case"RSA-OAEP-256":case"RSA-OAEP-384":case"RSA-OAEP-512":{if(!F(e.algorithm,"RSA-OAEP"))throw v("RSA-OAEP");let n=parseInt(t.slice(9),10)||1;if(Ue(e.algorithm.hash)!==n)throw v(`SHA-${n}`,"algorithm.hash");break}default:throw new TypeError("CryptoKey does not support this operation")}Kt(e,r)}function _t(e,t,...r){if(r=r.filter(Boolean),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?.name&&(e+=` Received an instance of ${t.constructor.name}`),e}var A=(e,...t)=>_t("Key must be ",e,...t);function qe(e,t,...r){return _t(`Key for the ${e} algorithm must be `,t,...r)}var Ze=e=>K(e)?!0:e?.[Symbol.toStringTag]==="KeyObject",b=["CryptoKey"];async function wr(e,t,r,n,o,a){if(!(t instanceof Uint8Array))throw new TypeError(A(t,"Uint8Array"));let i=parseInt(e.slice(1,4),10),s=await f.subtle.importKey("raw",t.subarray(i>>3),"AES-CBC",!1,["decrypt"]),d=await f.subtle.importKey("raw",t.subarray(0,i>>3),{hash:`SHA-${i<<1}`,name:"HMAC"},!1,["sign"]),p=W(a,n,r,Je(a.length<<3)),h=new Uint8Array((await f.subtle.sign("HMAC",d,p)).slice(0,i>>3)),l;try{l=At(o,h)}catch{}if(!l)throw new O;let T;try{T=new Uint8Array(await f.subtle.decrypt({iv:n,name:"AES-CBC"},s,r))}catch{}if(!T)throw new O;return T}async function Er(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,W(r,o)))}catch{throw new O}}var gr=async(e,t,r,n,o,a)=>{if(!K(t)&&!(t instanceof Uint8Array))throw new TypeError(A(t,...b,"Uint8Array"));if(!n)throw new c("JWE Initialization Vector missing");if(!o)throw new c("JWE Authentication Tag missing");switch(Re(e,n),e){case"A128CBC-HS256":case"A192CBC-HS384":case"A256CBC-HS512":return t instanceof Uint8Array&&ce(t,parseInt(e.slice(-3),10)),wr(e,t,r,n,o,a);case"A128GCM":case"A192GCM":case"A256GCM":return t instanceof Uint8Array&&ce(t,parseInt(e.slice(1,4),10)),Er(e,t,r,n,o,a);default:throw new u("Unsupported JWE Content Encryption Algorithm")}},De=gr;var Sr=(...e)=>{let t=e.filter(Boolean);if(t.length===0||t.length===1)return!0;let r;for(let n of t){let o=Object.keys(n);if(!r||r.size===0){r=new Set(o);continue}for(let a of o){if(r.has(a))return!1;r.add(a)}}return!0},R=Sr;function br(e){return typeof e=="object"&&e!==null}function y(e){if(!br(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"]],de=Ar;function Ht(e,t){if(e.algorithm.length!==parseInt(t.slice(1,4),10))throw new TypeError(`Invalid key size for alg: ${t}`)}function Ct(e,t,r){if(K(e))return I(e,t,r),e;if(e instanceof Uint8Array)return f.subtle.importKey("raw",e,"AES-KW",!0,[r]);throw new TypeError(A(e,...b,"Uint8Array"))}var me=async(e,t,r)=>{let n=await Ct(t,e,"wrapKey");Ht(n,e);let o=await f.subtle.importKey("raw",r,...de);return new Uint8Array(await f.subtle.wrapKey("raw",o,n,"AES-KW"))},ye=async(e,t,r)=>{let n=await Ct(t,e,"unwrapKey");Ht(n,e);let o=await f.subtle.unwrapKey("raw",r,n,"AES-KW",...de);return new Uint8Array(await f.subtle.exportKey("raw",o))};async function Me(e,t,r,n,o=new Uint8Array(0),a=new Uint8Array(0)){if(!K(e))throw new TypeError(A(e,...b));if(I(e,"ECDH"),!K(t))throw new TypeError(A(t,...b));I(t,"ECDH","deriveBits");let i=W(Ie(w.encode(r)),Ie(o),Ie(a),Te(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 Et(d,n,i)}async function Pt(e){if(!K(e))throw new TypeError(A(e,...b));return f.subtle.generateKey(e.algorithm,!0,["deriveBits"])}function Ne(e){if(!K(e))throw new TypeError(A(e,...b));return["P-256","P-384","P-521"].includes(e.algorithm.namedCurve)||e.algorithm.name==="X25519"||e.algorithm.name==="X448"}function Qe(e){if(!(e instanceof Uint8Array)||e.length<8)throw new c("PBES2 Salt Input must be 8 or more octets")}function Kr(e,t){if(e instanceof Uint8Array)return f.subtle.importKey("raw",e,"PBKDF2",!1,["deriveBits"]);if(K(e))return I(e,t,"deriveBits","deriveKey"),e;throw new TypeError(A(e,...b,"Uint8Array"))}async function vt(e,t,r,n){Qe(e);let o=wt(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 Kr(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 Jt=async(e,t,r,n=2048,o=G(new Uint8Array(16)))=>{let a=await vt(o,e,n,t);return{encryptedKey:await me(e.slice(-6),a,r),p2c:n,p2s:E(o)}},Tt=async(e,t,r,n,o)=>{let a=await vt(o,e,n,t);return ye(e.slice(-6),a,r)};function pe(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 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 It=async(e,t,r)=>{if(!K(t))throw new TypeError(A(t,...b));if(I(t,e,"encrypt","wrapKey"),Q(e,t),t.usages.includes("encrypt"))return new Uint8Array(await f.subtle.encrypt(pe(e),t,r));if(t.usages.includes("wrapKey")){let n=await f.subtle.importKey("raw",r,...de);return new Uint8Array(await f.subtle.wrapKey("raw",n,t,pe(e)))}throw new TypeError('RSA-OAEP key "usages" must include "encrypt" or "wrapKey" for this operation')},Ot=async(e,t,r)=>{if(!K(t))throw new TypeError(A(t,...b));if(I(t,e,"decrypt","unwrapKey"),Q(e,t),t.usages.includes("decrypt"))return new Uint8Array(await f.subtle.decrypt(pe(e),t,r));if(t.usages.includes("unwrapKey")){let n=await f.subtle.unwrapKey("raw",r,t,pe(e),...de);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 L(e){return y(e)&&typeof e.kty=="string"}function Rt(e){return e.kty!=="oct"&&typeof e.d=="string"}function Ut(e){return e.kty!=="oct"&&typeof e.d>"u"}function Dt(e){return L(e)&&e.kty==="oct"&&typeof e.k=="string"}function _r(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 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"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 u('Invalid or unsupported JWK "alg" (Algorithm) Parameter value')}break}default:throw new u('Invalid or unsupported JWK "kty" (Key Type) Parameter value')}return{algorithm:t,keyUsages:r}}var Hr=async e=>{if(!e.alg)throw new TypeError('"alg" argument is required when "jwk.alg" is not present');let{algorithm:t,keyUsages:r}=_r(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)},Le=Hr;var Mt=e=>g(e),fe,ue,Nt=e=>e?.[Symbol.toStringTag]==="KeyObject",$e=async(e,t,r,n,o=!1)=>{let a=e.get(t);if(a?.[n])return a[n];let i=await Le({...r,alg:n});return o&&Object.freeze(t),a?a[n]=i:e.set(t,{[n]:i}),i},Cr=(e,t)=>{if(Nt(e)){let r=e.export({format:"jwk"});return delete r.d,delete r.dp,delete r.dq,delete r.p,delete r.q,delete r.qi,r.k?Mt(r.k):(ue||(ue=new WeakMap),$e(ue,e,r,t))}return L(e)?e.k?g(e.k):(ue||(ue=new WeakMap),$e(ue,e,e,t,!0)):e},Pr=(e,t)=>{if(Nt(e)){let r=e.export({format:"jwk"});return r.k?Mt(r.k):(fe||(fe=new WeakMap),$e(fe,e,r,t))}return L(e)?e.k?g(e.k):(fe||(fe=new WeakMap),$e(fe,e,e,t,!0)):e},j={normalizePublicKey:Cr,normalizePrivateKey:Pr};function we(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 u(`Unsupported JWE Algorithm: ${e}`)}}var U=e=>G(new Uint8Array(we(e)>>3));var je=(e,t)=>{let r=(e.match(/.{1,64}/g)||[]).join(` `);return`-----BEGIN ${t}----- ${r} ------END ${t}-----`};var kt=async(e,t,r)=>{if(!K(r))throw new TypeError(A(r,...b));if(!r.extractable)throw new TypeError("CryptoKey is not extractable");if(r.type!==e)throw new TypeError(`key is not a ${e} key`);return je(Oe(new Uint8Array(await f.subtle.exportKey(t,r))),`${e.toUpperCase()} KEY`)},Bt=e=>kt("public","spki",e),Gt=e=>kt("private","pkcs8",e),V=(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])||V(e,t,n+1)},Lt=e=>{switch(!0){case V(e,[42,134,72,206,61,3,1,7]):return"P-256";case V(e,[43,129,4,0,34]):return"P-384";case V(e,[43,129,4,0,35]):return"P-521";case V(e,[43,101,110]):return"X25519";case V(e,[43,101,111]):return"X448";case V(e,[43,101,112]):return"Ed25519";case V(e,[43,101,113]):return"Ed448";default:throw new u("Invalid or unsupported EC Key Curve or OKP Key Sub Type")}},Ft=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=Lt(s);a=p.startsWith("P-")?{name:"ECDH",namedCurve:p}:{name:p},i=d?[]:["deriveBits"];break}case"EdDSA":a={name:Lt(s)},i=d?["verify"]:["sign"];break;default:throw new u('Invalid or unsupported "alg" (Algorithm) value')}return f.subtle.importKey(t,s,a,o?.extractable??!1,i)},Vt=(e,t,r)=>Ft(/(?:-----(?:BEGIN|END) PRIVATE KEY-----|\s)/g,"pkcs8",e,t,r),et=(e,t,r)=>Ft(/(?:-----(?:BEGIN|END) PUBLIC KEY-----|\s)/g,"spki",e,t,r);function $t(e){let t=[],r=0;for(;r=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{let n;try{n=vr(e)}catch(o){throw new TypeError("Failed to parse the X.509 certificate",{cause:o})}return et(n,t,r)};async function Jr(e,t,r){if(typeof e!="string"||e.indexOf("-----BEGIN PUBLIC KEY-----")!==0)throw new TypeError('"spki" must be SPKI formatted string');return et(e,t,r)}async function Tr(e,t,r){if(typeof e!="string"||e.indexOf("-----BEGIN CERTIFICATE-----")!==0)throw new TypeError('"x509" must be X.509 formatted string');return Xt(e,t,r)}async function Ir(e,t,r){if(typeof e!="string"||e.indexOf("-----BEGIN PRIVATE KEY-----")!==0)throw new TypeError('"pkcs8" must be PKCS#8 formatted string');return Vt(e,t,r)}async function $(e,t){if(!y(e))throw new TypeError("JWK must be an object");switch(t||(t=e.alg),e.kty){case"oct":if(typeof e.k!="string"||!e.k)throw new TypeError('missing "k" (Key Value) Parameter value');return 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 he=e=>e?.[Symbol.toStringTag],tt=(e,t,r)=>{if(t.use!==void 0&&t.use!=="sig")throw new TypeError("Invalid key for this operation, when present its use must be sig");if(t.key_ops!==void 0&&t.key_ops.includes?.(r)!==!0)throw new TypeError(`Invalid key for this operation, when present its key_ops must include ${r}`);if(t.alg!==void 0&&t.alg!==e)throw new TypeError(`Invalid key for this operation, when present its alg must be ${e}`);return!0},Or=(e,t,r,n)=>{if(!(t instanceof Uint8Array)){if(n&&L(t)){if(Dt(t)&&tt(e,t,r))return;throw new TypeError('JSON Web Key for symmetric algorithms must have JWK "kty" (Key Type) equal to "oct" and the JWK "k" (Key Value) present')}if(!Ze(t))throw new TypeError(qe(e,t,...b,"Uint8Array",n?"JSON Web Key":null));if(t.type!=="secret")throw new TypeError(`${he(t)} instances for symmetric algorithms must be of type "secret"`)}},Rr=(e,t,r,n)=>{if(n&&L(t))switch(r){case"sign":if(Rt(t)&&tt(e,t,r))return;throw new TypeError("JSON Web Key for this operation be a private JWK");case"verify":if(Ut(t)&&tt(e,t,r))return;throw new TypeError("JSON Web Key for this operation be a public JWK")}if(!Ze(t))throw new TypeError(qe(e,t,...b,n?"JSON Web Key":null));if(t.type==="secret")throw new TypeError(`${he(t)} instances for asymmetric algorithms must not be of type "secret"`);if(r==="sign"&&t.type==="public")throw new TypeError(`${he(t)} instances for asymmetric algorithm signing must be of type "private"`);if(r==="decrypt"&&t.type==="public")throw new TypeError(`${he(t)} instances for asymmetric algorithm decryption must be of type "private"`);if(t.algorithm&&r==="verify"&&t.type==="private")throw new TypeError(`${he(t)} instances for asymmetric algorithm verifying must be of type "public"`);if(t.algorithm&&r==="encrypt"&&t.type==="private")throw new TypeError(`${he(t)} instances for asymmetric algorithm encryption must be of type "public"`)};function Yt(e,t,r,n){t.startsWith("HS")||t==="dir"||t.startsWith("PBES2")||/^A\d{3}(?:GCM)?KW$/.test(t)?Or(t,r,n,e):Rr(t,r,n,e)}var ke=Yt.bind(void 0,!1),Ee=Yt.bind(void 0,!0);async function Ur(e,t,r,n,o){if(!(r instanceof Uint8Array))throw new TypeError(A(r,"Uint8Array"));let a=parseInt(e.slice(1,4),10),i=await f.subtle.importKey("raw",r.subarray(a>>3),"AES-CBC",!1,["encrypt"]),s=await f.subtle.importKey("raw",r.subarray(0,a>>3),{hash:`SHA-${a<<1}`,name:"HMAC"},!1,["sign"]),d=new Uint8Array(await f.subtle.encrypt({iv:n,name:"AES-CBC"},i,t)),p=W(o,n,d,Je(o.length<<3)),h=new Uint8Array((await f.subtle.sign("HMAC",s,p)).slice(0,a>>3));return{ciphertext:d,tag:h,iv:n}}async function Dr(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,iv:n}}var Mr=async(e,t,r,n,o)=>{if(!K(r)&&!(r instanceof Uint8Array))throw new TypeError(A(r,...b,"Uint8Array"));switch(n?Re(e,n):n=bt(e),e){case"A128CBC-HS256":case"A192CBC-HS384":case"A256CBC-HS512":return r instanceof Uint8Array&&ce(r,parseInt(e.slice(-3),10)),Ur(e,t,r,n,o);case"A128GCM":case"A192GCM":case"A256GCM":return r instanceof Uint8Array&&ce(r,parseInt(e.slice(1,4),10)),Dr(e,t,r,n,o);default:throw new u("Unsupported JWE Content Encryption Algorithm")}},Be=Mr;async function qt(e,t,r,n){let o=e.slice(0,7),a=await Be(o,r,t,n,new Uint8Array(0));return{encryptedKey:a.ciphertext,iv:E(a.iv),tag:E(a.tag)}}async function Zt(e,t,r,n,o){let a=e.slice(0,7);return De(a,t,r,n,o,new Uint8Array(0))}async function Nr(e,t,r,n,o){switch(ke(e,t,"decrypt"),t=await j.normalizePrivateKey?.(t,e)||t,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(!y(n.epk))throw new c('JOSE Header "epk" (Ephemeral Public Key) missing or invalid');if(!Ne(t))throw new u("ECDH with the provided key is not allowed or not supported by your javascript runtime");let a=await $(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=g(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=g(n.apv)}catch{throw new c("Failed to base64url decode the apv")}}let d=await Me(a,t,e==="ECDH-ES"?n.enc:e,e==="ECDH-ES"?we(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 ye(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 Ot(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=g(n.p2s)}catch{throw new c("Failed to base64url decode the p2s")}return Tt(e,t,r,n.p2c,i)}case"A128KW":case"A192KW":case"A256KW":{if(r===void 0)throw new c("JWE Encrypted Key missing");return ye(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=g(n.iv)}catch{throw new c("Failed to base64url decode the iv")}let i;try{i=g(n.tag)}catch{throw new c("Failed to base64url decode the tag")}return Zt(e,t,r,a,i)}default:throw new u('Invalid or unsupported "alg" (JWE Algorithm) header value')}}var Qt=Nr;function Lr(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 u(`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 D=Lr;var $r=(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)},ge=$r;async function Se(e,t,r){if(!y(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(e.iv!==void 0&&typeof e.iv!="string")throw new c("JWE Initialization Vector incorrect type");if(typeof e.ciphertext!="string")throw new c("JWE Ciphertext missing or incorrect type");if(e.tag!==void 0&&typeof e.tag!="string")throw new c("JWE Authentication Tag 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&&!y(e.header))throw new c("JWE Shared Unprotected Header incorrect type");if(e.unprotected!==void 0&&!y(e.unprotected))throw new c("JWE Per-Recipient Unprotected Header incorrect type");let n;if(e.protected)try{let oe=g(e.protected);n=JSON.parse(x.decode(oe))}catch{throw new c("JWE Protected Header is invalid")}if(!R(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(D(c,new Map,r?.crit,n,o),o.zip!==void 0)throw new u('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&&ge("keyManagementAlgorithms",r.keyManagementAlgorithms),d=r&&ge("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=g(e.encrypted_key)}catch{throw new c("Failed to base64url decode the encrypted_key")}let h=!1;typeof t=="function"&&(t=await t(n,e),h=!0);let l;try{l=await Qt(a,t,p,o,r)}catch(oe){if(oe instanceof TypeError||oe instanceof c||oe instanceof u)throw oe;l=U(i)}let T,J;if(e.iv!==void 0)try{T=g(e.iv)}catch{throw new c("Failed to base64url decode the iv")}if(e.tag!==void 0)try{J=g(e.tag)}catch{throw new c("Failed to base64url decode the tag")}let S=w.encode(e.protected??""),P;e.aad!==void 0?P=W(S,w.encode("."),w.encode(e.aad)):P=S;let Pe;try{Pe=g(e.ciphertext)}catch{throw new c("Failed to base64url decode the ciphertext")}let ne={plaintext:await De(i,l,Pe,T,J,P)};if(e.protected!==void 0&&(ne.protectedHeader=n),e.aad!==void 0)try{ne.additionalAuthenticatedData=g(e.aad)}catch{throw new c("Failed to base64url decode the aad")}return e.unprotected!==void 0&&(ne.sharedUnprotectedHeader=e.unprotected),e.header!==void 0&&(ne.unprotectedHeader=e.header),h?{...ne,key:t}:ne}async function rt(e,t,r){if(e instanceof Uint8Array&&(e=x.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 Se({ciphertext:i,iv:a||void 0,protected:n,tag:s||void 0,encrypted_key:o||void 0},t,r),h={plaintext:p.plaintext,protectedHeader:p.protectedHeader};return typeof t=="function"?{...h,key:p.key}:h}async function kr(e,t,r){if(!y(e))throw new c("General JWE must be an object");if(!Array.isArray(e.recipients)||!e.recipients.every(y))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 Se({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 O}var Ge=Symbol();var Br=async e=>{if(e instanceof Uint8Array)return{kty:"oct",k:E(e)};if(!K(e))throw new TypeError(A(e,...b,"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},jt=Br;async function Gr(e){return Bt(e)}async function Fr(e){return Gt(e)}async function nt(e){return jt(e)}async function Vr(e,t,r,n,o={}){let a,i,s;switch(ke(e,r,"encrypt"),r=await j.normalizePublicKey?.(r,e)||r,e){case"dir":{s=r;break}case"ECDH-ES":case"ECDH-ES+A128KW":case"ECDH-ES+A192KW":case"ECDH-ES+A256KW":{if(!Ne(r))throw new u("ECDH with the provided key is not allowed or not supported by your javascript runtime");let{apu:d,apv:p}=o,{epk:h}=o;h||(h=(await Pt(r)).privateKey);let{x:l,y:T,crv:J,kty:S}=await nt(h),P=await Me(r,h,e==="ECDH-ES"?t:e,e==="ECDH-ES"?we(t):parseInt(e.slice(-5,-2),10),d,p);if(i={epk:{x:l,crv:J,kty:S}},S==="EC"&&(i.epk.y=T),d&&(i.apu=E(d)),p&&(i.apv=E(p)),e==="ECDH-ES"){s=P;break}s=n||U(t);let Pe=e.slice(-6);a=await me(Pe,P,s);break}case"RSA1_5":case"RSA-OAEP":case"RSA-OAEP-256":case"RSA-OAEP-384":case"RSA-OAEP-512":{s=n||U(t),a=await It(e,r,s);break}case"PBES2-HS256+A128KW":case"PBES2-HS384+A192KW":case"PBES2-HS512+A256KW":{s=n||U(t);let{p2c:d,p2s:p}=o;({encryptedKey:a,...i}=await Jt(e,r,s,d,p));break}case"A128KW":case"A192KW":case"A256KW":{s=n||U(t),a=await me(e,r,s);break}case"A128GCMKW":case"A192GCMKW":case"A256GCMKW":{s=n||U(t);let{iv:d}=o;({encryptedKey:a,...i}=await qt(e,r,s,d));break}default:throw new u('Invalid or unsupported "alg" (JWE Algorithm) header value')}return{cek:s,encryptedKey:a,parameters:i}}var Fe=Vr;var z=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(!R(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(D(c,new Map,r?.crit,this._protectedHeader,n),n.zip!==void 0)throw new u('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(this._cek&&(o==="dir"||o==="ECDH-ES"))throw new TypeError(`setContentEncryptionKey cannot be called with JWE "alg" (Algorithm) Header ${o}`);let s;{let P;({cek:s,encryptedKey:i,parameters:P}=await Fe(o,a,t,this._cek,this._keyManagementParameters)),P&&(r&&Ge in r?this._unprotectedHeader?this._unprotectedHeader={...this._unprotectedHeader,...P}:this.setUnprotectedHeader(P):this._protectedHeader?this._protectedHeader={...this._protectedHeader,...P}:this.setProtectedHeader(P))}let d,p,h;this._protectedHeader?p=w.encode(E(JSON.stringify(this._protectedHeader))):p=w.encode(""),this._aad?(h=E(this._aad),d=W(p,w.encode("."),w.encode(h))):d=p;let{ciphertext:l,tag:T,iv:J}=await Be(a,this._plaintext,s,this._iv,d),S={ciphertext:E(l)};return J&&(S.iv=E(J)),T&&(S.tag=E(T)),i&&(S.encrypted_key=E(i)),h&&(S.aad=h),this._protectedHeader&&(S.protected=x.decode(p)),this._sharedUnprotectedHeader&&(S.unprotected=this._sharedUnprotectedHeader),this._unprotectedHeader&&(S.header=this._unprotectedHeader),S}};var ot=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}},at=class{constructor(t){this._recipients=[],this._plaintext=t}addRecipient(t,r){let n=new ot(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 z(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>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 u(`alg ${e} is not supported either by JOSE or your javascript runtime`)}}async function Ae(e,t,r){if(r==="sign"&&(t=await j.normalizePrivateKey(t,e)),r==="verify"&&(t=await j.normalizePublicKey(t,e)),K(t))return xt(t,e,r),t;if(t instanceof Uint8Array){if(!e.startsWith("HS"))throw new TypeError(A(t,...b));return f.subtle.importKey("raw",t,{hash:`SHA-${e.slice(-3)}`,name:"HMAC"},!1,[r])}throw new TypeError(A(t,...b,"Uint8Array","JSON Web Key"))}var zr=async(e,t,r,n)=>{let o=await Ae(e,t,"verify");Q(e,o);let a=be(e,o.algorithm);try{return await f.subtle.verify(a,o,r,n)}catch{return!1}},er=zr;async function Ke(e,t,r){if(!y(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&&!y(e.header))throw new m("JWS Unprotected Header incorrect type");let n={};if(e.protected)try{let P=g(e.protected);n=JSON.parse(x.decode(P))}catch{throw new m("JWS Protected Header is invalid")}if(!R(n,e.header))throw new m("JWS Protected and JWS Unprotected Header Parameter names must be disjoint");let o={...n,...e.header},a=D(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&&ge("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,Ee(s,t,"verify"),L(t)&&(t=await $(t,s))):Ee(s,t,"verify");let h=W(w.encode(e.protected??""),w.encode("."),typeof e.payload=="string"?w.encode(e.payload):e.payload),l;try{l=g(e.signature)}catch{throw new m("Failed to base64url decode the signature")}if(!await er(s,t,l,h))throw new B;let J;if(i)try{J=g(e.payload)}catch{throw new m("Failed to base64url decode the payload")}else typeof e.payload=="string"?J=w.encode(e.payload):J=e.payload;let S={payload:J};return e.protected!==void 0&&(S.protectedHeader=n),e.header!==void 0&&(S.unprotectedHeader=e.header),p?{...S,key:t}:S}async function it(e,t,r){if(e instanceof Uint8Array&&(e=x.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 Ke({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 Xr(e,t,r){if(!y(e))throw new m("General JWS must be an object");if(!Array.isArray(e.signatures)||!e.signatures.every(y))throw new m("JWS Signatures missing or incorrect type");for(let n of e.signatures)try{return await Ke({header:n.header,payload:e.payload,protected:n.protected,signature:n.signature},t,r)}catch{}throw new B}var M=e=>Math.floor(e.getTime()/1e3);var Yr=/^(\+|\-)? ?(\d+|\d+\.\d+) ?(seconds?|secs?|s|minutes?|mins?|m|hours?|hrs?|h|days?|d|weeks?|w|years?|yrs?|y)(?: (ago|from now))?$/i,ee=e=>{let t=Yr.exec(e);if(!t||t[4]&&t[1])throw new TypeError("Invalid time period format");let r=parseFloat(t[2]),n=t[3].toLowerCase(),o;switch(n){case"sec":case"secs":case"second":case"seconds":case"s":o=Math.round(r);break;case"minute":case"minutes":case"min":case"mins":case"m":o=Math.round(r*60);break;case"hour":case"hours":case"hr":case"hrs":case"h":o=Math.round(r*3600);break;case"day":case"days":case"d":o=Math.round(r*86400);break;case"week":case"weeks":case"w":o=Math.round(r*604800);break;default:o=Math.round(r*31557600);break}return t[1]==="-"||t[4]==="ago"?-o:o};var tr=e=>e.toLowerCase().replace(/^application\//,""),qr=(e,t)=>typeof e=="string"?t.includes(e):Array.isArray(e)?t.some(Set.prototype.has.bind(new Set(e))):!1,le=(e,t,r={})=>{let n;try{n=JSON.parse(x.decode(t))}catch{}if(!y(n))throw new _("JWT Claims Set must be a top-level JSON object");let{typ:o}=r;if(o&&(typeof e.typ!="string"||tr(e.typ)!==tr(o)))throw new C('unexpected "typ" JWT header value',n,"typ","check_failed");let{requiredClaims:a=[],issuer:i,subject:s,audience:d,maxTokenAge:p}=r,h=[...a];p!==void 0&&h.push("iat"),d!==void 0&&h.push("aud"),s!==void 0&&h.push("sub"),i!==void 0&&h.push("iss");for(let S of new Set(h.reverse()))if(!(S in n))throw new C(`missing required "${S}" claim`,n,S,"missing");if(i&&!(Array.isArray(i)?i:[i]).includes(n.iss))throw new C('unexpected "iss" claim value',n,"iss","check_failed");if(s&&n.sub!==s)throw new C('unexpected "sub" claim value',n,"sub","check_failed");if(d&&!qr(n.aud,typeof d=="string"?[d]:d))throw new C('unexpected "aud" claim value',n,"aud","check_failed");let l;switch(typeof r.clockTolerance){case"string":l=ee(r.clockTolerance);break;case"number":l=r.clockTolerance;break;case"undefined":l=0;break;default:throw new TypeError("Invalid clockTolerance option type")}let{currentDate:T}=r,J=M(T||new Date);if((n.iat!==void 0||p)&&typeof n.iat!="number")throw new C('"iat" claim must be a number',n,"iat","invalid");if(n.nbf!==void 0){if(typeof n.nbf!="number")throw new C('"nbf" claim must be a number',n,"nbf","invalid");if(n.nbf>J+l)throw new C('"nbf" claim timestamp check failed',n,"nbf","check_failed")}if(n.exp!==void 0){if(typeof n.exp!="number")throw new C('"exp" claim must be a number',n,"exp","invalid");if(n.exp<=J-l)throw new q('"exp" claim timestamp check failed',n,"exp","check_failed")}if(p){let S=J-n.iat,P=typeof p=="number"?p:ee(p);if(S-l>P)throw new q('"iat" claim timestamp check failed (too far in the past)',n,"iat","check_failed");if(S<0-l)throw new C('"iat" claim timestamp check failed (it should be in the past)',n,"iat","check_failed")}return n};async function Zr(e,t,r){let n=await it(e,t,r);if(n.protectedHeader.crit?.includes("b64")&&n.protectedHeader.b64===!1)throw new _("JWTs MUST NOT use unencoded payload");let a={payload:le(n.protectedHeader,n.payload,r),protectedHeader:n.protectedHeader};return typeof t=="function"?{...a,key:n.key}:a}async function Qr(e,t,r){let n=await rt(e,t,r),o=le(n.protectedHeader,n.plaintext,r),{protectedHeader:a}=n;if(a.iss!==void 0&&a.iss!==o.iss)throw new C('replicated "iss" claim header parameter mismatch',o,"iss","mismatch");if(a.sub!==void 0&&a.sub!==o.sub)throw new C('replicated "sub" claim header parameter mismatch',o,"sub","mismatch");if(a.aud!==void 0&&JSON.stringify(a.aud)!==JSON.stringify(o.aud))throw new C('replicated "aud" claim header parameter mismatch',o,"aud","mismatch");let i={payload:o,protectedHeader:a};return typeof t=="function"?{...i,key:n.key}:i}var xe=class{constructor(t){this._flattened=new z(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 Ae(e,t,"sign");Q(e,n);let o=await f.subtle.sign(be(e,n.algorithm),n,r);return new Uint8Array(o)},rr=jr;var te=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(!R(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=D(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');Ee(i,t,"sign");let s=this._payload;a&&(s=w.encode(E(s)));let d;this._protectedHeader?d=w.encode(E(JSON.stringify(this._protectedHeader))):d=w.encode("");let p=W(d,w.encode("."),s),h=await rr(i,t,p),l={signature:E(h),payload:""};return a&&(l.payload=x.decode(s)),this._unprotectedHeader&&(l.header=this._unprotectedHeader),this._protectedHeader&&(l.protected=x.decode(d)),l}};var _e=class{constructor(t){this._flattened=new te(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 st=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}},ct=class{constructor(t){this._signatures=[],this._payload=t}addSignature(t,r){let n=new st(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"u"?this._payload={...this._payload,iat:M(new Date)}:t instanceof Date?this._payload={...this._payload,iat:re("setIssuedAt",M(t))}:typeof t=="string"?this._payload={...this._payload,iat:re("setIssuedAt",M(new Date)+ee(t))}:this._payload={...this._payload,iat:re("setIssuedAt",t)},this}};var dt=class extends X{setProtectedHeader(t){return this._protectedHeader=t,this}async sign(t,r){let n=new _e(w.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 _("JWTs MUST NOT use unencoded payload");return n.sign(t,r)}};var pt=class extends X{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 xe(w.encode(JSON.stringify(this._payload)));return this._replicateIssuerAsHeader&&(this._protectedHeader={...this._protectedHeader,iss:this._payload.iss}),this._replicateSubjectAsHeader&&(this._protectedHeader={...this._protectedHeader,sub:this._payload.sub}),this._replicateAudienceAsHeader&&(this._protectedHeader={...this._protectedHeader,aud:this._payload.aud}),n.setProtectedHeader(this._protectedHeader),this._iv&&n.setInitializationVector(this._iv),this._cek&&n.setContentEncryptionKey(this._cek),this._keyManagementParameters&&n.setKeyManagementParameters(this._keyManagementParameters),n.encrypt(t,r)}};var Y=(e,t)=>{if(typeof e!="string"||!e)throw new ae(`${t} missing or invalid`)};async function nr(e,t){if(!y(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":Y(e.crv,'"crv" (Curve) Parameter'),Y(e.x,'"x" (X Coordinate) Parameter'),Y(e.y,'"y" (Y Coordinate) Parameter'),r={crv:e.crv,kty:e.kty,x:e.x,y:e.y};break;case"OKP":Y(e.crv,'"crv" (Subtype of Key Pair) Parameter'),Y(e.x,'"x" (Public Key) Parameter'),r={crv:e.crv,kty:e.kty,x:e.x};break;case"RSA":Y(e.e,'"e" (Exponent) Parameter'),Y(e.n,'"n" (Modulus) Parameter'),r={e:e.e,kty:e.kty,n:e.n};break;case"oct":Y(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=w.encode(JSON.stringify(r));return E(await We(t,n))}async function en(e,t){t??(t="sha256");let r=await nr(e,t);return`urn:ietf:params:oauth:jwk-thumbprint:sha-${t.slice(-3)}:${r}`}async function tn(e,t){let r={...e,...t?.header};if(!y(r.jwk))throw new m('"jwk" (JSON Web Key) Header Parameter must be a JSON object');let n=await $({...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 rn(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 u('Unsupported "alg" value for a JSON Web Key Set')}}function nn(e){return e&&typeof e=="object"&&Array.isArray(e.keys)&&e.keys.every(on)}function on(e){return y(e)}function ar(e){return typeof structuredClone=="function"?structuredClone(e):JSON.parse(JSON.stringify(e))}var ft=class{constructor(t){if(this._cached=new WeakMap,!nn(t))throw new Z("JSON Web Key Set malformed");this._jwks=ar(t)}async getKey(t,r){let{alg:n,kid:o}={...t,...r?.header},a=rn(n),i=this._jwks.keys.filter(p=>{let h=a===p.kty;if(h&&typeof o=="string"&&(h=o===p.kid),h&&typeof p.alg=="string"&&(h=n===p.alg),h&&typeof p.use=="string"&&(h=p.use==="sig"),h&&Array.isArray(p.key_ops)&&(h=p.key_ops.includes("verify")),h&&n==="EdDSA"&&(h=p.crv==="Ed25519"||p.crv==="Ed448"),h)switch(n){case"ES256":h=p.crv==="P-256";break;case"ES256K":h=p.crv==="secp256k1";break;case"ES384":h=p.crv==="P-384";break;case"ES512":h=p.crv==="P-521";break}return h}),{0:s,length:d}=i;if(d===0)throw new k;if(d!==1){let p=new ie,{_cached:h}=this;throw p[Symbol.asyncIterator]=async function*(){for(let l of i)try{yield await or(h,l,n)}catch{}},p}return or(this._cached,s,n)}};async function or(e,t,r){let n=e.get(t)||e.set(t,{}).get(t);if(n[r]===void 0){let o=await $({...t,ext:!0},r);if(o instanceof Uint8Array||o.type!=="public")throw new Z("JSON Web Key Set members must be public keys");n[r]=o}return n[r]}function Ve(e){let t=new ft(e),r=async(n,o)=>t.getKey(n,o);return Object.defineProperties(r,{jwks:{value:()=>ar(t._jwks),enumerable:!0,configurable:!1,writable:!1}}),r}var an=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 se: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")}},ir=an;function sn(){return typeof WebSocketPair<"u"||typeof navigator<"u"&&navigator.userAgent==="Cloudflare-Workers"||typeof EdgeRuntime<"u"&&EdgeRuntime==="vercel"}var ut;(typeof navigator>"u"||!navigator.userAgent?.startsWith?.("Mozilla/5.0 "))&&(ut="jose/v5.9.5");var He=Symbol();function cn(e,t){return!(typeof e!="object"||e===null||!("uat"in e)||typeof e.uat!="number"||Date.now()-e.uat>=t||!("jwks"in e)||!y(e.jwks)||!Array.isArray(e.jwks.keys)||!Array.prototype.every.call(e.jwks.keys,y))}var ht=class{constructor(t,r){if(!(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,r?.[He]!==void 0&&(this._cache=r?.[He],cn(r?.[He],this._cacheMaxAge)&&(this._jwksTimestamp=this._cache.uat,this._local=Ve(this._cache.jwks)))}coolingDown(){return typeof this._jwksTimestamp=="number"?Date.now(){this._local=Ve(r),this._cache&&(this._cache.uat=Date.now(),this._cache.jwks=r),this._jwksTimestamp=Date.now(),this._pendingFetch=void 0}).catch(r=>{throw this._pendingFetch=void 0,r})),await this._pendingFetch}};function dn(e,t){let r=new ht(e,t),n=async(o,a)=>r.getKey(o,a);return Object.defineProperties(n,{coolingDown:{get:()=>r.coolingDown(),enumerable:!0,configurable:!1},fresh:{get:()=>r.fresh(),enumerable:!0,configurable:!1},reload:{value:()=>r.reload(),enumerable:!0,configurable:!1,writable:!1},reloading:{get:()=>!!r._pendingFetch,enumerable:!0,configurable:!1},jwks:{value:()=>r._local?.jwks(),enumerable:!0,configurable:!1,writable:!1}}),n}var pn=He;var lt=class extends X{encode(){let t=E(JSON.stringify({alg:"none"})),r=E(JSON.stringify(this._payload));return`${t}.${r}.`}static decode(t,r){if(typeof t!="string")throw new _("Unsecured JWT must be a string");let{0:n,1:o,2:a,length:i}=t.split(".");if(i!==3||a!=="")throw new _("Invalid Unsecured JWT");let s;try{if(s=JSON.parse(x.decode(g(n))),s.alg!=="none")throw new Error}catch{throw new _("Invalid Unsecured JWT")}return{payload:le(s,g(o),r),header:s}}};var sr={};yt(sr,{decode:()=>Ce,encode:()=>fn});var fn=E,Ce=g;function un(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(x.decode(Ce(t)));if(!y(r))throw new Error;return r}catch{throw new TypeError("Invalid Token or Protected Header formatting")}}function hn(e){if(typeof e!="string")throw new _("JWTs must use Compact JWS serialization, JWT must be a string");let{1:t,length:r}=e.split(".");if(r===5)throw new _("Only JWTs using Compact JWS serialization can be decoded");if(r!==3)throw new _("Invalid JWT");if(!t)throw new _("JWTs must contain a payload");let n;try{n=Ce(t)}catch{throw new _("Failed to base64url decode the payload")}let o;try{o=JSON.parse(x.decode(n))}catch{throw new _("Failed to parse the decoded payload as JSON")}if(!y(o))throw new _("Invalid JWT Claims Set");return o}async function cr(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),G(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 u('Invalid or unsupported JWK "alg" (Algorithm) Parameter value')}return f.subtle.generateKey(n,t?.extractable??!1,o)}function mt(e){let t=e?.modulusLength??2048;if(typeof t!="number"||t<2048)throw new u("Invalid or unsupported modulusLength option provided, 2048 bits or larger keys must be used");return t}async function dr(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:mt(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:mt(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:mt(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 u("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 o=t?.crv??"P-256";switch(o){case"P-256":case"P-384":case"P-521":{r={name:"ECDH",namedCurve:o};break}case"X25519":case"X448":r={name:o};break;default:throw new u("Invalid or unsupported crv option provided, supported values are P-256, P-384, P-521, X25519, and X448")}break}default:throw new u('Invalid or unsupported JWK "alg" (Algorithm) Parameter value')}return f.subtle.generateKey(r,t?.extractable??!1,n)}async function ln(e,t){return dr(e,t)}async function mn(e,t){return cr(e,t)}var pr="WebCryptoAPI";var yn=pr;export{xe as CompactEncrypt,_e as CompactSign,tn as EmbeddedJWK,pt as EncryptJWT,z as FlattenedEncrypt,te as FlattenedSign,at as GeneralEncrypt,ct as GeneralSign,dt as SignJWT,lt as UnsecuredJWT,sr as base64url,nr as calculateJwkThumbprint,en as calculateJwkThumbprintUri,rt as compactDecrypt,it as compactVerify,Ve as createLocalJWKSet,dn as createRemoteJWKSet,yn as cryptoRuntime,hn as decodeJwt,un as decodeProtectedHeader,St as errors,pn as experimental_jwksCache,nt as exportJWK,Fr as exportPKCS8,Gr as exportSPKI,Se as flattenedDecrypt,Ke as flattenedVerify,kr as generalDecrypt,Xr as generalVerify,ln as generateKeyPair,mn as generateSecret,$ as importJWK,Ir as importPKCS8,Jr as importSPKI,Tr as importX509,He as jwksCache,Qr as jwtDecrypt,Zr as jwtVerify}; +-----END ${t}-----`};var kt=async(e,t,r)=>{if(!K(r))throw new TypeError(A(r,...b));if(!r.extractable)throw new TypeError("CryptoKey is not extractable");if(r.type!==e)throw new TypeError(`key is not a ${e} key`);return je(Oe(new Uint8Array(await f.subtle.exportKey(t,r))),`${e.toUpperCase()} KEY`)},Bt=e=>kt("public","spki",e),Gt=e=>kt("private","pkcs8",e),V=(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])||V(e,t,n+1)},Lt=e=>{switch(!0){case V(e,[42,134,72,206,61,3,1,7]):return"P-256";case V(e,[43,129,4,0,34]):return"P-384";case V(e,[43,129,4,0,35]):return"P-521";case V(e,[43,101,110]):return"X25519";case V(e,[43,101,111]):return"X448";case V(e,[43,101,112]):return"Ed25519";case V(e,[43,101,113]):return"Ed448";default:throw new u("Invalid or unsupported EC Key Curve or OKP Key Sub Type")}},Ft=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=Lt(s);a=p.startsWith("P-")?{name:"ECDH",namedCurve:p}:{name:p},i=d?[]:["deriveBits"];break}case"EdDSA":a={name:Lt(s)},i=d?["verify"]:["sign"];break;default:throw new u('Invalid or unsupported "alg" (Algorithm) value')}return f.subtle.importKey(t,s,a,o?.extractable??!1,i)},Vt=(e,t,r)=>Ft(/(?:-----(?:BEGIN|END) PRIVATE KEY-----|\s)/g,"pkcs8",e,t,r),et=(e,t,r)=>Ft(/(?:-----(?:BEGIN|END) PUBLIC KEY-----|\s)/g,"spki",e,t,r);function $t(e){let t=[],r=0;for(;r=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{let n;try{n=vr(e)}catch(o){throw new TypeError("Failed to parse the X.509 certificate",{cause:o})}return et(n,t,r)};async function Jr(e,t,r){if(typeof e!="string"||e.indexOf("-----BEGIN PUBLIC KEY-----")!==0)throw new TypeError('"spki" must be SPKI formatted string');return et(e,t,r)}async function Tr(e,t,r){if(typeof e!="string"||e.indexOf("-----BEGIN CERTIFICATE-----")!==0)throw new TypeError('"x509" must be X.509 formatted string');return Xt(e,t,r)}async function Ir(e,t,r){if(typeof e!="string"||e.indexOf("-----BEGIN PRIVATE KEY-----")!==0)throw new TypeError('"pkcs8" must be PKCS#8 formatted string');return Vt(e,t,r)}async function $(e,t){if(!y(e))throw new TypeError("JWK must be an object");switch(t||(t=e.alg),e.kty){case"oct":if(typeof e.k!="string"||!e.k)throw new TypeError('missing "k" (Key Value) Parameter value');return 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 he=e=>e?.[Symbol.toStringTag],tt=(e,t,r)=>{if(t.use!==void 0&&t.use!=="sig")throw new TypeError("Invalid key for this operation, when present its use must be sig");if(t.key_ops!==void 0&&t.key_ops.includes?.(r)!==!0)throw new TypeError(`Invalid key for this operation, when present its key_ops must include ${r}`);if(t.alg!==void 0&&t.alg!==e)throw new TypeError(`Invalid key for this operation, when present its alg must be ${e}`);return!0},Or=(e,t,r,n)=>{if(!(t instanceof Uint8Array)){if(n&&L(t)){if(Dt(t)&&tt(e,t,r))return;throw new TypeError('JSON Web Key for symmetric algorithms must have JWK "kty" (Key Type) equal to "oct" and the JWK "k" (Key Value) present')}if(!Ze(t))throw new TypeError(qe(e,t,...b,"Uint8Array",n?"JSON Web Key":null));if(t.type!=="secret")throw new TypeError(`${he(t)} instances for symmetric algorithms must be of type "secret"`)}},Rr=(e,t,r,n)=>{if(n&&L(t))switch(r){case"sign":if(Rt(t)&&tt(e,t,r))return;throw new TypeError("JSON Web Key for this operation be a private JWK");case"verify":if(Ut(t)&&tt(e,t,r))return;throw new TypeError("JSON Web Key for this operation be a public JWK")}if(!Ze(t))throw new TypeError(qe(e,t,...b,n?"JSON Web Key":null));if(t.type==="secret")throw new TypeError(`${he(t)} instances for asymmetric algorithms must not be of type "secret"`);if(r==="sign"&&t.type==="public")throw new TypeError(`${he(t)} instances for asymmetric algorithm signing must be of type "private"`);if(r==="decrypt"&&t.type==="public")throw new TypeError(`${he(t)} instances for asymmetric algorithm decryption must be of type "private"`);if(t.algorithm&&r==="verify"&&t.type==="private")throw new TypeError(`${he(t)} instances for asymmetric algorithm verifying must be of type "public"`);if(t.algorithm&&r==="encrypt"&&t.type==="private")throw new TypeError(`${he(t)} instances for asymmetric algorithm encryption must be of type "public"`)};function Yt(e,t,r,n){t.startsWith("HS")||t==="dir"||t.startsWith("PBES2")||/^A\d{3}(?:GCM)?KW$/.test(t)?Or(t,r,n,e):Rr(t,r,n,e)}var ke=Yt.bind(void 0,!1),Ee=Yt.bind(void 0,!0);async function Ur(e,t,r,n,o){if(!(r instanceof Uint8Array))throw new TypeError(A(r,"Uint8Array"));let a=parseInt(e.slice(1,4),10),i=await f.subtle.importKey("raw",r.subarray(a>>3),"AES-CBC",!1,["encrypt"]),s=await f.subtle.importKey("raw",r.subarray(0,a>>3),{hash:`SHA-${a<<1}`,name:"HMAC"},!1,["sign"]),d=new Uint8Array(await f.subtle.encrypt({iv:n,name:"AES-CBC"},i,t)),p=W(o,n,d,Je(o.length<<3)),h=new Uint8Array((await f.subtle.sign("HMAC",s,p)).slice(0,a>>3));return{ciphertext:d,tag:h,iv:n}}async function Dr(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,iv:n}}var Mr=async(e,t,r,n,o)=>{if(!K(r)&&!(r instanceof Uint8Array))throw new TypeError(A(r,...b,"Uint8Array"));switch(n?Re(e,n):n=bt(e),e){case"A128CBC-HS256":case"A192CBC-HS384":case"A256CBC-HS512":return r instanceof Uint8Array&&ce(r,parseInt(e.slice(-3),10)),Ur(e,t,r,n,o);case"A128GCM":case"A192GCM":case"A256GCM":return r instanceof Uint8Array&&ce(r,parseInt(e.slice(1,4),10)),Dr(e,t,r,n,o);default:throw new u("Unsupported JWE Content Encryption Algorithm")}},Be=Mr;async function qt(e,t,r,n){let o=e.slice(0,7),a=await Be(o,r,t,n,new Uint8Array(0));return{encryptedKey:a.ciphertext,iv:E(a.iv),tag:E(a.tag)}}async function Zt(e,t,r,n,o){let a=e.slice(0,7);return De(a,t,r,n,o,new Uint8Array(0))}async function Nr(e,t,r,n,o){switch(ke(e,t,"decrypt"),t=await j.normalizePrivateKey?.(t,e)||t,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(!y(n.epk))throw new c('JOSE Header "epk" (Ephemeral Public Key) missing or invalid');if(!Ne(t))throw new u("ECDH with the provided key is not allowed or not supported by your javascript runtime");let a=await $(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=g(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=g(n.apv)}catch{throw new c("Failed to base64url decode the apv")}}let d=await Me(a,t,e==="ECDH-ES"?n.enc:e,e==="ECDH-ES"?we(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 ye(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 Ot(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=g(n.p2s)}catch{throw new c("Failed to base64url decode the p2s")}return Tt(e,t,r,n.p2c,i)}case"A128KW":case"A192KW":case"A256KW":{if(r===void 0)throw new c("JWE Encrypted Key missing");return ye(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=g(n.iv)}catch{throw new c("Failed to base64url decode the iv")}let i;try{i=g(n.tag)}catch{throw new c("Failed to base64url decode the tag")}return Zt(e,t,r,a,i)}default:throw new u('Invalid or unsupported "alg" (JWE Algorithm) header value')}}var Qt=Nr;function Lr(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 u(`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 D=Lr;var $r=(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)},ge=$r;async function Se(e,t,r){if(!y(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(e.iv!==void 0&&typeof e.iv!="string")throw new c("JWE Initialization Vector incorrect type");if(typeof e.ciphertext!="string")throw new c("JWE Ciphertext missing or incorrect type");if(e.tag!==void 0&&typeof e.tag!="string")throw new c("JWE Authentication Tag 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&&!y(e.header))throw new c("JWE Shared Unprotected Header incorrect type");if(e.unprotected!==void 0&&!y(e.unprotected))throw new c("JWE Per-Recipient Unprotected Header incorrect type");let n;if(e.protected)try{let oe=g(e.protected);n=JSON.parse(x.decode(oe))}catch{throw new c("JWE Protected Header is invalid")}if(!R(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(D(c,new Map,r?.crit,n,o),o.zip!==void 0)throw new u('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&&ge("keyManagementAlgorithms",r.keyManagementAlgorithms),d=r&&ge("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=g(e.encrypted_key)}catch{throw new c("Failed to base64url decode the encrypted_key")}let h=!1;typeof t=="function"&&(t=await t(n,e),h=!0);let l;try{l=await Qt(a,t,p,o,r)}catch(oe){if(oe instanceof TypeError||oe instanceof c||oe instanceof u)throw oe;l=U(i)}let T,J;if(e.iv!==void 0)try{T=g(e.iv)}catch{throw new c("Failed to base64url decode the iv")}if(e.tag!==void 0)try{J=g(e.tag)}catch{throw new c("Failed to base64url decode the tag")}let S=w.encode(e.protected??""),P;e.aad!==void 0?P=W(S,w.encode("."),w.encode(e.aad)):P=S;let Pe;try{Pe=g(e.ciphertext)}catch{throw new c("Failed to base64url decode the ciphertext")}let ne={plaintext:await De(i,l,Pe,T,J,P)};if(e.protected!==void 0&&(ne.protectedHeader=n),e.aad!==void 0)try{ne.additionalAuthenticatedData=g(e.aad)}catch{throw new c("Failed to base64url decode the aad")}return e.unprotected!==void 0&&(ne.sharedUnprotectedHeader=e.unprotected),e.header!==void 0&&(ne.unprotectedHeader=e.header),h?{...ne,key:t}:ne}async function rt(e,t,r){if(e instanceof Uint8Array&&(e=x.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 Se({ciphertext:i,iv:a||void 0,protected:n,tag:s||void 0,encrypted_key:o||void 0},t,r),h={plaintext:p.plaintext,protectedHeader:p.protectedHeader};return typeof t=="function"?{...h,key:p.key}:h}async function kr(e,t,r){if(!y(e))throw new c("General JWE must be an object");if(!Array.isArray(e.recipients)||!e.recipients.every(y))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 Se({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 O}var Ge=Symbol();var Br=async e=>{if(e instanceof Uint8Array)return{kty:"oct",k:E(e)};if(!K(e))throw new TypeError(A(e,...b,"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},jt=Br;async function Gr(e){return Bt(e)}async function Fr(e){return Gt(e)}async function nt(e){return jt(e)}async function Vr(e,t,r,n,o={}){let a,i,s;switch(ke(e,r,"encrypt"),r=await j.normalizePublicKey?.(r,e)||r,e){case"dir":{s=r;break}case"ECDH-ES":case"ECDH-ES+A128KW":case"ECDH-ES+A192KW":case"ECDH-ES+A256KW":{if(!Ne(r))throw new u("ECDH with the provided key is not allowed or not supported by your javascript runtime");let{apu:d,apv:p}=o,{epk:h}=o;h||(h=(await Pt(r)).privateKey);let{x:l,y:T,crv:J,kty:S}=await nt(h),P=await Me(r,h,e==="ECDH-ES"?t:e,e==="ECDH-ES"?we(t):parseInt(e.slice(-5,-2),10),d,p);if(i={epk:{x:l,crv:J,kty:S}},S==="EC"&&(i.epk.y=T),d&&(i.apu=E(d)),p&&(i.apv=E(p)),e==="ECDH-ES"){s=P;break}s=n||U(t);let Pe=e.slice(-6);a=await me(Pe,P,s);break}case"RSA1_5":case"RSA-OAEP":case"RSA-OAEP-256":case"RSA-OAEP-384":case"RSA-OAEP-512":{s=n||U(t),a=await It(e,r,s);break}case"PBES2-HS256+A128KW":case"PBES2-HS384+A192KW":case"PBES2-HS512+A256KW":{s=n||U(t);let{p2c:d,p2s:p}=o;({encryptedKey:a,...i}=await Jt(e,r,s,d,p));break}case"A128KW":case"A192KW":case"A256KW":{s=n||U(t),a=await me(e,r,s);break}case"A128GCMKW":case"A192GCMKW":case"A256GCMKW":{s=n||U(t);let{iv:d}=o;({encryptedKey:a,...i}=await qt(e,r,s,d));break}default:throw new u('Invalid or unsupported "alg" (JWE Algorithm) header value')}return{cek:s,encryptedKey:a,parameters:i}}var Fe=Vr;var z=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(!R(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(D(c,new Map,r?.crit,this._protectedHeader,n),n.zip!==void 0)throw new u('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(this._cek&&(o==="dir"||o==="ECDH-ES"))throw new TypeError(`setContentEncryptionKey cannot be called with JWE "alg" (Algorithm) Header ${o}`);let s;{let P;({cek:s,encryptedKey:i,parameters:P}=await Fe(o,a,t,this._cek,this._keyManagementParameters)),P&&(r&&Ge in r?this._unprotectedHeader?this._unprotectedHeader={...this._unprotectedHeader,...P}:this.setUnprotectedHeader(P):this._protectedHeader?this._protectedHeader={...this._protectedHeader,...P}:this.setProtectedHeader(P))}let d,p,h;this._protectedHeader?p=w.encode(E(JSON.stringify(this._protectedHeader))):p=w.encode(""),this._aad?(h=E(this._aad),d=W(p,w.encode("."),w.encode(h))):d=p;let{ciphertext:l,tag:T,iv:J}=await Be(a,this._plaintext,s,this._iv,d),S={ciphertext:E(l)};return J&&(S.iv=E(J)),T&&(S.tag=E(T)),i&&(S.encrypted_key=E(i)),h&&(S.aad=h),this._protectedHeader&&(S.protected=x.decode(p)),this._sharedUnprotectedHeader&&(S.unprotected=this._sharedUnprotectedHeader),this._unprotectedHeader&&(S.header=this._unprotectedHeader),S}};var ot=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}},at=class{constructor(t){this._recipients=[],this._plaintext=t}addRecipient(t,r){let n=new ot(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 z(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>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 u(`alg ${e} is not supported either by JOSE or your javascript runtime`)}}async function Ae(e,t,r){if(r==="sign"&&(t=await j.normalizePrivateKey(t,e)),r==="verify"&&(t=await j.normalizePublicKey(t,e)),K(t))return xt(t,e,r),t;if(t instanceof Uint8Array){if(!e.startsWith("HS"))throw new TypeError(A(t,...b));return f.subtle.importKey("raw",t,{hash:`SHA-${e.slice(-3)}`,name:"HMAC"},!1,[r])}throw new TypeError(A(t,...b,"Uint8Array","JSON Web Key"))}var zr=async(e,t,r,n)=>{let o=await Ae(e,t,"verify");Q(e,o);let a=be(e,o.algorithm);try{return await f.subtle.verify(a,o,r,n)}catch{return!1}},er=zr;async function Ke(e,t,r){if(!y(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&&!y(e.header))throw new m("JWS Unprotected Header incorrect type");let n={};if(e.protected)try{let P=g(e.protected);n=JSON.parse(x.decode(P))}catch{throw new m("JWS Protected Header is invalid")}if(!R(n,e.header))throw new m("JWS Protected and JWS Unprotected Header Parameter names must be disjoint");let o={...n,...e.header},a=D(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&&ge("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,Ee(s,t,"verify"),L(t)&&(t=await $(t,s))):Ee(s,t,"verify");let h=W(w.encode(e.protected??""),w.encode("."),typeof e.payload=="string"?w.encode(e.payload):e.payload),l;try{l=g(e.signature)}catch{throw new m("Failed to base64url decode the signature")}if(!await er(s,t,l,h))throw new B;let J;if(i)try{J=g(e.payload)}catch{throw new m("Failed to base64url decode the payload")}else typeof e.payload=="string"?J=w.encode(e.payload):J=e.payload;let S={payload:J};return e.protected!==void 0&&(S.protectedHeader=n),e.header!==void 0&&(S.unprotectedHeader=e.header),p?{...S,key:t}:S}async function it(e,t,r){if(e instanceof Uint8Array&&(e=x.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 Ke({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 Xr(e,t,r){if(!y(e))throw new m("General JWS must be an object");if(!Array.isArray(e.signatures)||!e.signatures.every(y))throw new m("JWS Signatures missing or incorrect type");for(let n of e.signatures)try{return await Ke({header:n.header,payload:e.payload,protected:n.protected,signature:n.signature},t,r)}catch{}throw new B}var M=e=>Math.floor(e.getTime()/1e3);var Yr=/^(\+|\-)? ?(\d+|\d+\.\d+) ?(seconds?|secs?|s|minutes?|mins?|m|hours?|hrs?|h|days?|d|weeks?|w|years?|yrs?|y)(?: (ago|from now))?$/i,ee=e=>{let t=Yr.exec(e);if(!t||t[4]&&t[1])throw new TypeError("Invalid time period format");let r=parseFloat(t[2]),n=t[3].toLowerCase(),o;switch(n){case"sec":case"secs":case"second":case"seconds":case"s":o=Math.round(r);break;case"minute":case"minutes":case"min":case"mins":case"m":o=Math.round(r*60);break;case"hour":case"hours":case"hr":case"hrs":case"h":o=Math.round(r*3600);break;case"day":case"days":case"d":o=Math.round(r*86400);break;case"week":case"weeks":case"w":o=Math.round(r*604800);break;default:o=Math.round(r*31557600);break}return t[1]==="-"||t[4]==="ago"?-o:o};var tr=e=>e.toLowerCase().replace(/^application\//,""),qr=(e,t)=>typeof e=="string"?t.includes(e):Array.isArray(e)?t.some(Set.prototype.has.bind(new Set(e))):!1,le=(e,t,r={})=>{let n;try{n=JSON.parse(x.decode(t))}catch{}if(!y(n))throw new _("JWT Claims Set must be a top-level JSON object");let{typ:o}=r;if(o&&(typeof e.typ!="string"||tr(e.typ)!==tr(o)))throw new C('unexpected "typ" JWT header value',n,"typ","check_failed");let{requiredClaims:a=[],issuer:i,subject:s,audience:d,maxTokenAge:p}=r,h=[...a];p!==void 0&&h.push("iat"),d!==void 0&&h.push("aud"),s!==void 0&&h.push("sub"),i!==void 0&&h.push("iss");for(let S of new Set(h.reverse()))if(!(S in n))throw new C(`missing required "${S}" claim`,n,S,"missing");if(i&&!(Array.isArray(i)?i:[i]).includes(n.iss))throw new C('unexpected "iss" claim value',n,"iss","check_failed");if(s&&n.sub!==s)throw new C('unexpected "sub" claim value',n,"sub","check_failed");if(d&&!qr(n.aud,typeof d=="string"?[d]:d))throw new C('unexpected "aud" claim value',n,"aud","check_failed");let l;switch(typeof r.clockTolerance){case"string":l=ee(r.clockTolerance);break;case"number":l=r.clockTolerance;break;case"undefined":l=0;break;default:throw new TypeError("Invalid clockTolerance option type")}let{currentDate:T}=r,J=M(T||new Date);if((n.iat!==void 0||p)&&typeof n.iat!="number")throw new C('"iat" claim must be a number',n,"iat","invalid");if(n.nbf!==void 0){if(typeof n.nbf!="number")throw new C('"nbf" claim must be a number',n,"nbf","invalid");if(n.nbf>J+l)throw new C('"nbf" claim timestamp check failed',n,"nbf","check_failed")}if(n.exp!==void 0){if(typeof n.exp!="number")throw new C('"exp" claim must be a number',n,"exp","invalid");if(n.exp<=J-l)throw new q('"exp" claim timestamp check failed',n,"exp","check_failed")}if(p){let S=J-n.iat,P=typeof p=="number"?p:ee(p);if(S-l>P)throw new q('"iat" claim timestamp check failed (too far in the past)',n,"iat","check_failed");if(S<0-l)throw new C('"iat" claim timestamp check failed (it should be in the past)',n,"iat","check_failed")}return n};async function Zr(e,t,r){let n=await it(e,t,r);if(n.protectedHeader.crit?.includes("b64")&&n.protectedHeader.b64===!1)throw new _("JWTs MUST NOT use unencoded payload");let a={payload:le(n.protectedHeader,n.payload,r),protectedHeader:n.protectedHeader};return typeof t=="function"?{...a,key:n.key}:a}async function Qr(e,t,r){let n=await rt(e,t,r),o=le(n.protectedHeader,n.plaintext,r),{protectedHeader:a}=n;if(a.iss!==void 0&&a.iss!==o.iss)throw new C('replicated "iss" claim header parameter mismatch',o,"iss","mismatch");if(a.sub!==void 0&&a.sub!==o.sub)throw new C('replicated "sub" claim header parameter mismatch',o,"sub","mismatch");if(a.aud!==void 0&&JSON.stringify(a.aud)!==JSON.stringify(o.aud))throw new C('replicated "aud" claim header parameter mismatch',o,"aud","mismatch");let i={payload:o,protectedHeader:a};return typeof t=="function"?{...i,key:n.key}:i}var xe=class{constructor(t){this._flattened=new z(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 Ae(e,t,"sign");Q(e,n);let o=await f.subtle.sign(be(e,n.algorithm),n,r);return new Uint8Array(o)},rr=jr;var te=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(!R(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=D(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');Ee(i,t,"sign");let s=this._payload;a&&(s=w.encode(E(s)));let d;this._protectedHeader?d=w.encode(E(JSON.stringify(this._protectedHeader))):d=w.encode("");let p=W(d,w.encode("."),s),h=await rr(i,t,p),l={signature:E(h),payload:""};return a&&(l.payload=x.decode(s)),this._unprotectedHeader&&(l.header=this._unprotectedHeader),this._protectedHeader&&(l.protected=x.decode(d)),l}};var _e=class{constructor(t){this._flattened=new te(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 st=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}},ct=class{constructor(t){this._signatures=[],this._payload=t}addSignature(t,r){let n=new st(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"u"?this._payload={...this._payload,iat:M(new Date)}:t instanceof Date?this._payload={...this._payload,iat:re("setIssuedAt",M(t))}:typeof t=="string"?this._payload={...this._payload,iat:re("setIssuedAt",M(new Date)+ee(t))}:this._payload={...this._payload,iat:re("setIssuedAt",t)},this}};var dt=class extends X{setProtectedHeader(t){return this._protectedHeader=t,this}async sign(t,r){let n=new _e(w.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 _("JWTs MUST NOT use unencoded payload");return n.sign(t,r)}};var pt=class extends X{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 xe(w.encode(JSON.stringify(this._payload)));return this._replicateIssuerAsHeader&&(this._protectedHeader={...this._protectedHeader,iss:this._payload.iss}),this._replicateSubjectAsHeader&&(this._protectedHeader={...this._protectedHeader,sub:this._payload.sub}),this._replicateAudienceAsHeader&&(this._protectedHeader={...this._protectedHeader,aud:this._payload.aud}),n.setProtectedHeader(this._protectedHeader),this._iv&&n.setInitializationVector(this._iv),this._cek&&n.setContentEncryptionKey(this._cek),this._keyManagementParameters&&n.setKeyManagementParameters(this._keyManagementParameters),n.encrypt(t,r)}};var Y=(e,t)=>{if(typeof e!="string"||!e)throw new ae(`${t} missing or invalid`)};async function nr(e,t){if(!y(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":Y(e.crv,'"crv" (Curve) Parameter'),Y(e.x,'"x" (X Coordinate) Parameter'),Y(e.y,'"y" (Y Coordinate) Parameter'),r={crv:e.crv,kty:e.kty,x:e.x,y:e.y};break;case"OKP":Y(e.crv,'"crv" (Subtype of Key Pair) Parameter'),Y(e.x,'"x" (Public Key) Parameter'),r={crv:e.crv,kty:e.kty,x:e.x};break;case"RSA":Y(e.e,'"e" (Exponent) Parameter'),Y(e.n,'"n" (Modulus) Parameter'),r={e:e.e,kty:e.kty,n:e.n};break;case"oct":Y(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=w.encode(JSON.stringify(r));return E(await We(t,n))}async function en(e,t){t??(t="sha256");let r=await nr(e,t);return`urn:ietf:params:oauth:jwk-thumbprint:sha-${t.slice(-3)}:${r}`}async function tn(e,t){let r={...e,...t?.header};if(!y(r.jwk))throw new m('"jwk" (JSON Web Key) Header Parameter must be a JSON object');let n=await $({...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 rn(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 u('Unsupported "alg" value for a JSON Web Key Set')}}function nn(e){return e&&typeof e=="object"&&Array.isArray(e.keys)&&e.keys.every(on)}function on(e){return y(e)}function ar(e){return typeof structuredClone=="function"?structuredClone(e):JSON.parse(JSON.stringify(e))}var ft=class{constructor(t){if(this._cached=new WeakMap,!nn(t))throw new Z("JSON Web Key Set malformed");this._jwks=ar(t)}async getKey(t,r){let{alg:n,kid:o}={...t,...r?.header},a=rn(n),i=this._jwks.keys.filter(p=>{let h=a===p.kty;if(h&&typeof o=="string"&&(h=o===p.kid),h&&typeof p.alg=="string"&&(h=n===p.alg),h&&typeof p.use=="string"&&(h=p.use==="sig"),h&&Array.isArray(p.key_ops)&&(h=p.key_ops.includes("verify")),h&&n==="EdDSA"&&(h=p.crv==="Ed25519"||p.crv==="Ed448"),h)switch(n){case"ES256":h=p.crv==="P-256";break;case"ES256K":h=p.crv==="secp256k1";break;case"ES384":h=p.crv==="P-384";break;case"ES512":h=p.crv==="P-521";break}return h}),{0:s,length:d}=i;if(d===0)throw new k;if(d!==1){let p=new ie,{_cached:h}=this;throw p[Symbol.asyncIterator]=async function*(){for(let l of i)try{yield await or(h,l,n)}catch{}},p}return or(this._cached,s,n)}};async function or(e,t,r){let n=e.get(t)||e.set(t,{}).get(t);if(n[r]===void 0){let o=await $({...t,ext:!0},r);if(o instanceof Uint8Array||o.type!=="public")throw new Z("JSON Web Key Set members must be public keys");n[r]=o}return n[r]}function Ve(e){let t=new ft(e),r=async(n,o)=>t.getKey(n,o);return Object.defineProperties(r,{jwks:{value:()=>ar(t._jwks),enumerable:!0,configurable:!1,writable:!1}}),r}var an=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 se: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")}},ir=an;function sn(){return typeof WebSocketPair<"u"||typeof navigator<"u"&&navigator.userAgent==="Cloudflare-Workers"||typeof EdgeRuntime<"u"&&EdgeRuntime==="vercel"}var ut;(typeof navigator>"u"||!navigator.userAgent?.startsWith?.("Mozilla/5.0 "))&&(ut="jose/v5.9.6");var He=Symbol();function cn(e,t){return!(typeof e!="object"||e===null||!("uat"in e)||typeof e.uat!="number"||Date.now()-e.uat>=t||!("jwks"in e)||!y(e.jwks)||!Array.isArray(e.jwks.keys)||!Array.prototype.every.call(e.jwks.keys,y))}var ht=class{constructor(t,r){if(!(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,r?.[He]!==void 0&&(this._cache=r?.[He],cn(r?.[He],this._cacheMaxAge)&&(this._jwksTimestamp=this._cache.uat,this._local=Ve(this._cache.jwks)))}coolingDown(){return typeof this._jwksTimestamp=="number"?Date.now(){this._local=Ve(r),this._cache&&(this._cache.uat=Date.now(),this._cache.jwks=r),this._jwksTimestamp=Date.now(),this._pendingFetch=void 0}).catch(r=>{throw this._pendingFetch=void 0,r})),await this._pendingFetch}};function dn(e,t){let r=new ht(e,t),n=async(o,a)=>r.getKey(o,a);return Object.defineProperties(n,{coolingDown:{get:()=>r.coolingDown(),enumerable:!0,configurable:!1},fresh:{get:()=>r.fresh(),enumerable:!0,configurable:!1},reload:{value:()=>r.reload(),enumerable:!0,configurable:!1,writable:!1},reloading:{get:()=>!!r._pendingFetch,enumerable:!0,configurable:!1},jwks:{value:()=>r._local?.jwks(),enumerable:!0,configurable:!1,writable:!1}}),n}var pn=He;var lt=class extends X{encode(){let t=E(JSON.stringify({alg:"none"})),r=E(JSON.stringify(this._payload));return`${t}.${r}.`}static decode(t,r){if(typeof t!="string")throw new _("Unsecured JWT must be a string");let{0:n,1:o,2:a,length:i}=t.split(".");if(i!==3||a!=="")throw new _("Invalid Unsecured JWT");let s;try{if(s=JSON.parse(x.decode(g(n))),s.alg!=="none")throw new Error}catch{throw new _("Invalid Unsecured JWT")}return{payload:le(s,g(o),r),header:s}}};var sr={};yt(sr,{decode:()=>Ce,encode:()=>fn});var fn=E,Ce=g;function un(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(x.decode(Ce(t)));if(!y(r))throw new Error;return r}catch{throw new TypeError("Invalid Token or Protected Header formatting")}}function hn(e){if(typeof e!="string")throw new _("JWTs must use Compact JWS serialization, JWT must be a string");let{1:t,length:r}=e.split(".");if(r===5)throw new _("Only JWTs using Compact JWS serialization can be decoded");if(r!==3)throw new _("Invalid JWT");if(!t)throw new _("JWTs must contain a payload");let n;try{n=Ce(t)}catch{throw new _("Failed to base64url decode the payload")}let o;try{o=JSON.parse(x.decode(n))}catch{throw new _("Failed to parse the decoded payload as JSON")}if(!y(o))throw new _("Invalid JWT Claims Set");return o}async function cr(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),G(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 u('Invalid or unsupported JWK "alg" (Algorithm) Parameter value')}return f.subtle.generateKey(n,t?.extractable??!1,o)}function mt(e){let t=e?.modulusLength??2048;if(typeof t!="number"||t<2048)throw new u("Invalid or unsupported modulusLength option provided, 2048 bits or larger keys must be used");return t}async function dr(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:mt(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:mt(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:mt(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 u("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 o=t?.crv??"P-256";switch(o){case"P-256":case"P-384":case"P-521":{r={name:"ECDH",namedCurve:o};break}case"X25519":case"X448":r={name:o};break;default:throw new u("Invalid or unsupported crv option provided, supported values are P-256, P-384, P-521, X25519, and X448")}break}default:throw new u('Invalid or unsupported JWK "alg" (Algorithm) Parameter value')}return f.subtle.generateKey(r,t?.extractable??!1,n)}async function ln(e,t){return dr(e,t)}async function mn(e,t){return cr(e,t)}var pr="WebCryptoAPI";var yn=pr;export{xe as CompactEncrypt,_e as CompactSign,tn as EmbeddedJWK,pt as EncryptJWT,z as FlattenedEncrypt,te as FlattenedSign,at as GeneralEncrypt,ct as GeneralSign,dt as SignJWT,lt as UnsecuredJWT,sr as base64url,nr as calculateJwkThumbprint,en as calculateJwkThumbprintUri,rt as compactDecrypt,it as compactVerify,Ve as createLocalJWKSet,dn as createRemoteJWKSet,yn as cryptoRuntime,hn as decodeJwt,un as decodeProtectedHeader,St as errors,pn as experimental_jwksCache,nt as exportJWK,Fr as exportPKCS8,Gr as exportSPKI,Se as flattenedDecrypt,Ke as flattenedVerify,kr as generalDecrypt,Xr as generalVerify,ln as generateKeyPair,mn as generateSecret,$ as importJWK,Ir as importPKCS8,Jr as importSPKI,Tr as importX509,He as jwksCache,Qr as jwtDecrypt,Zr as jwtVerify}; diff --git a/dist/browser/index.umd.js b/dist/browser/index.umd.js index 1584e474c2..0767c9bce1 100644 --- a/dist/browser/index.umd.js +++ b/dist/browser/index.umd.js @@ -3124,7 +3124,7 @@ ${newlined} var USER_AGENT; if (typeof navigator === "undefined" || !navigator.userAgent?.startsWith?.("Mozilla/5.0 ")) { const NAME = "jose"; - const VERSION = "v5.9.5"; + const VERSION = "v5.9.6"; USER_AGENT = `${NAME}/${VERSION}`; } var jwksCache = Symbol(); diff --git a/dist/browser/index.umd.min.js b/dist/browser/index.umd.min.js index b4847f72e3..a578c83240 100644 --- a/dist/browser/index.umd.min.js +++ b/dist/browser/index.umd.min.js @@ -1,5 +1,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 fr=Object.defineProperty;var yt=(e,t)=>{for(var r in t)fr(e,r,{get:t[r],enumerable:!0});};var f=crypto,K=e=>e instanceof CryptoKey;var ur=async(e,t)=>{let r=`SHA-${e.slice(-3)}`;return new Uint8Array(await f.subtle.digest(r,t))},We=ur;var w=new TextEncoder,x=new TextDecoder,ve=2**32;function W(...e){let t=e.reduce((o,{length:a})=>o+a,0),r=new Uint8Array(t),n=0;for(let o of e)r.set(o,n),n+=o.length;return r}function wt(e,t){return W(w.encode(e),new Uint8Array([0]),t)}function ze(e,t,r){if(t<0||t>=ve)throw new RangeError(`value must be >= 0 and <= ${ve-1}. Received ${t}`);e.set([t>>>24,t>>>16,t>>>8,t&255],r);}function Je(e){let t=Math.floor(e/ve),r=e%ve,n=new Uint8Array(8);return ze(n,t,0),ze(n,r,4),n}function Te(e){let t=new Uint8Array(4);return ze(t,e),t}function Ie(e){return W(Te(e.length),e)}async function Et(e,t,r){let n=Math.ceil((t>>3)/32),o=new Uint8Array(n*32);for(let a=0;a>3)}var Oe=e=>{let t=e;typeof t=="string"&&(t=w.encode(t));let r=32768,n=[];for(let o=0;oOe(e).replace(/=/g,"").replace(/\+/g,"-").replace(/\//g,"_"),Xe=e=>{let t=atob(e),r=new Uint8Array(t.length);for(let n=0;n{let t=e;t instanceof Uint8Array&&(t=x.decode(t)),t=t.replace(/-/g,"+").replace(/_/g,"/").replace(/\s/g,"");try{return Xe(t)}catch{throw new TypeError("The input to be decoded is not correctly encoded.")}};var St={};yt(St,{JOSEAlgNotAllowed:()=>N,JOSEError:()=>H,JOSENotSupported:()=>u,JWEDecryptionFailed:()=>O,JWEInvalid:()=>c,JWKInvalid:()=>ae,JWKSInvalid:()=>Z,JWKSMultipleMatchingKeys:()=>ie,JWKSNoMatchingKey:()=>k,JWKSTimeout:()=>se,JWSInvalid:()=>m,JWSSignatureVerificationFailed:()=>B,JWTClaimValidationFailed:()=>C,JWTExpired:()=>q,JWTInvalid:()=>_});var H=class extends Error{constructor(t,r){super(t,r),this.code="ERR_JOSE_GENERIC",this.name=this.constructor.name,Error.captureStackTrace?.(this,this.constructor);}};H.code="ERR_JOSE_GENERIC";var C=class extends H{constructor(t,r,n="unspecified",o="unspecified"){super(t,{cause:{claim:n,reason:o,payload:r}}),this.code="ERR_JWT_CLAIM_VALIDATION_FAILED",this.claim=n,this.reason=o,this.payload=r;}};C.code="ERR_JWT_CLAIM_VALIDATION_FAILED";var q=class extends H{constructor(t,r,n="unspecified",o="unspecified"){super(t,{cause:{claim:n,reason:o,payload:r}}),this.code="ERR_JWT_EXPIRED",this.claim=n,this.reason=o,this.payload=r;}};q.code="ERR_JWT_EXPIRED";var N=class extends H{constructor(){super(...arguments),this.code="ERR_JOSE_ALG_NOT_ALLOWED";}};N.code="ERR_JOSE_ALG_NOT_ALLOWED";var u=class extends H{constructor(){super(...arguments),this.code="ERR_JOSE_NOT_SUPPORTED";}};u.code="ERR_JOSE_NOT_SUPPORTED";var O=class extends H{constructor(t="decryption operation failed",r){super(t,r),this.code="ERR_JWE_DECRYPTION_FAILED";}};O.code="ERR_JWE_DECRYPTION_FAILED";var c=class extends H{constructor(){super(...arguments),this.code="ERR_JWE_INVALID";}};c.code="ERR_JWE_INVALID";var m=class extends H{constructor(){super(...arguments),this.code="ERR_JWS_INVALID";}};m.code="ERR_JWS_INVALID";var _=class extends H{constructor(){super(...arguments),this.code="ERR_JWT_INVALID";}};_.code="ERR_JWT_INVALID";var ae=class extends H{constructor(){super(...arguments),this.code="ERR_JWK_INVALID";}};ae.code="ERR_JWK_INVALID";var Z=class extends H{constructor(){super(...arguments),this.code="ERR_JWKS_INVALID";}};Z.code="ERR_JWKS_INVALID";var k=class extends H{constructor(t="no applicable key found in the JSON Web Key Set",r){super(t,r),this.code="ERR_JWKS_NO_MATCHING_KEY";}};k.code="ERR_JWKS_NO_MATCHING_KEY";var ie=class extends H{constructor(t="multiple matching keys found in the JSON Web Key Set",r){super(t,r),this.code="ERR_JWKS_MULTIPLE_MATCHING_KEYS";}};ie.code="ERR_JWKS_MULTIPLE_MATCHING_KEYS";var se=class extends H{constructor(t="request timed out",r){super(t,r),this.code="ERR_JWKS_TIMEOUT";}};se.code="ERR_JWKS_TIMEOUT";var B=class extends H{constructor(t="signature verification failed",r){super(t,r),this.code="ERR_JWS_SIGNATURE_VERIFICATION_FAILED";}};B.code="ERR_JWS_SIGNATURE_VERIFICATION_FAILED";var G=f.getRandomValues.bind(f);function Ye(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 u(`Unsupported JWE Algorithm: ${e}`)}}var bt=e=>G(new Uint8Array(Ye(e)>>3));var hr=(e,t)=>{if(t.length<<3!==Ye(e))throw new c("Invalid Initialization Vector length")},Re=hr;var lr=(e,t)=>{let r=e.byteLength<<3;if(r!==t)throw new c(`Invalid Content Encryption Key length. Expected ${t} bits, got ${r} bits`)},ce=lr;var mr=(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(;++oe.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 xt(e,t,...r){switch(t){case"HS256":case"HS384":case"HS512":{if(!F(e.algorithm,"HMAC"))throw v("HMAC");let n=parseInt(t.slice(2),10);if(Ue(e.algorithm.hash)!==n)throw v(`SHA-${n}`,"algorithm.hash");break}case"RS256":case"RS384":case"RS512":{if(!F(e.algorithm,"RSASSA-PKCS1-v1_5"))throw v("RSASSA-PKCS1-v1_5");let n=parseInt(t.slice(2),10);if(Ue(e.algorithm.hash)!==n)throw v(`SHA-${n}`,"algorithm.hash");break}case"PS256":case"PS384":case"PS512":{if(!F(e.algorithm,"RSA-PSS"))throw v("RSA-PSS");let n=parseInt(t.slice(2),10);if(Ue(e.algorithm.hash)!==n)throw v(`SHA-${n}`,"algorithm.hash");break}case"EdDSA":{if(e.algorithm.name!=="Ed25519"&&e.algorithm.name!=="Ed448")throw v("Ed25519 or Ed448");break}case"ES256":case"ES384":case"ES512":{if(!F(e.algorithm,"ECDSA"))throw v("ECDSA");let n=yr(t);if(e.algorithm.namedCurve!==n)throw v(n,"algorithm.namedCurve");break}default:throw new TypeError("CryptoKey does not support this operation")}Kt(e,r);}function I(e,t,...r){switch(t){case"A128GCM":case"A192GCM":case"A256GCM":{if(!F(e.algorithm,"AES-GCM"))throw v("AES-GCM");let n=parseInt(t.slice(1,4),10);if(e.algorithm.length!==n)throw v(n,"algorithm.length");break}case"A128KW":case"A192KW":case"A256KW":{if(!F(e.algorithm,"AES-KW"))throw v("AES-KW");let n=parseInt(t.slice(1,4),10);if(e.algorithm.length!==n)throw v(n,"algorithm.length");break}case"ECDH":{switch(e.algorithm.name){case"ECDH":case"X25519":case"X448":break;default:throw v("ECDH, X25519, or X448")}break}case"PBES2-HS256+A128KW":case"PBES2-HS384+A192KW":case"PBES2-HS512+A256KW":if(!F(e.algorithm,"PBKDF2"))throw v("PBKDF2");break;case"RSA-OAEP":case"RSA-OAEP-256":case"RSA-OAEP-384":case"RSA-OAEP-512":{if(!F(e.algorithm,"RSA-OAEP"))throw v("RSA-OAEP");let n=parseInt(t.slice(9),10)||1;if(Ue(e.algorithm.hash)!==n)throw v(`SHA-${n}`,"algorithm.hash");break}default:throw new TypeError("CryptoKey does not support this operation")}Kt(e,r);}function _t(e,t,...r){if(r=r.filter(Boolean),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?.name&&(e+=` Received an instance of ${t.constructor.name}`),e}var A=(e,...t)=>_t("Key must be ",e,...t);function qe(e,t,...r){return _t(`Key for the ${e} algorithm must be `,t,...r)}var Ze=e=>K(e)?!0:e?.[Symbol.toStringTag]==="KeyObject",b=["CryptoKey"];async function wr(e,t,r,n,o,a){if(!(t instanceof Uint8Array))throw new TypeError(A(t,"Uint8Array"));let i=parseInt(e.slice(1,4),10),s=await f.subtle.importKey("raw",t.subarray(i>>3),"AES-CBC",!1,["decrypt"]),d=await f.subtle.importKey("raw",t.subarray(0,i>>3),{hash:`SHA-${i<<1}`,name:"HMAC"},!1,["sign"]),p=W(a,n,r,Je(a.length<<3)),h=new Uint8Array((await f.subtle.sign("HMAC",d,p)).slice(0,i>>3)),l;try{l=At(o,h);}catch{}if(!l)throw new O;let T;try{T=new Uint8Array(await f.subtle.decrypt({iv:n,name:"AES-CBC"},s,r));}catch{}if(!T)throw new O;return T}async function Er(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,W(r,o)))}catch{throw new O}}var gr=async(e,t,r,n,o,a)=>{if(!K(t)&&!(t instanceof Uint8Array))throw new TypeError(A(t,...b,"Uint8Array"));if(!n)throw new c("JWE Initialization Vector missing");if(!o)throw new c("JWE Authentication Tag missing");switch(Re(e,n),e){case"A128CBC-HS256":case"A192CBC-HS384":case"A256CBC-HS512":return t instanceof Uint8Array&&ce(t,parseInt(e.slice(-3),10)),wr(e,t,r,n,o,a);case"A128GCM":case"A192GCM":case"A256GCM":return t instanceof Uint8Array&&ce(t,parseInt(e.slice(1,4),10)),Er(e,t,r,n,o,a);default:throw new u("Unsupported JWE Content Encryption Algorithm")}},De=gr;var Sr=(...e)=>{let t=e.filter(Boolean);if(t.length===0||t.length===1)return !0;let r;for(let n of t){let o=Object.keys(n);if(!r||r.size===0){r=new Set(o);continue}for(let a of o){if(r.has(a))return !1;r.add(a);}}return !0},R=Sr;function br(e){return typeof e=="object"&&e!==null}function y(e){if(!br(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"]],de=Ar;function Ht(e,t){if(e.algorithm.length!==parseInt(t.slice(1,4),10))throw new TypeError(`Invalid key size for alg: ${t}`)}function Ct(e,t,r){if(K(e))return I(e,t,r),e;if(e instanceof Uint8Array)return f.subtle.importKey("raw",e,"AES-KW",!0,[r]);throw new TypeError(A(e,...b,"Uint8Array"))}var me=async(e,t,r)=>{let n=await Ct(t,e,"wrapKey");Ht(n,e);let o=await f.subtle.importKey("raw",r,...de);return new Uint8Array(await f.subtle.wrapKey("raw",o,n,"AES-KW"))},ye=async(e,t,r)=>{let n=await Ct(t,e,"unwrapKey");Ht(n,e);let o=await f.subtle.unwrapKey("raw",r,n,"AES-KW",...de);return new Uint8Array(await f.subtle.exportKey("raw",o))};async function Me(e,t,r,n,o=new Uint8Array(0),a=new Uint8Array(0)){if(!K(e))throw new TypeError(A(e,...b));if(I(e,"ECDH"),!K(t))throw new TypeError(A(t,...b));I(t,"ECDH","deriveBits");let i=W(Ie(w.encode(r)),Ie(o),Ie(a),Te(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 Et(d,n,i)}async function Pt(e){if(!K(e))throw new TypeError(A(e,...b));return f.subtle.generateKey(e.algorithm,!0,["deriveBits"])}function Ne(e){if(!K(e))throw new TypeError(A(e,...b));return ["P-256","P-384","P-521"].includes(e.algorithm.namedCurve)||e.algorithm.name==="X25519"||e.algorithm.name==="X448"}function Qe(e){if(!(e instanceof Uint8Array)||e.length<8)throw new c("PBES2 Salt Input must be 8 or more octets")}function Kr(e,t){if(e instanceof Uint8Array)return f.subtle.importKey("raw",e,"PBKDF2",!1,["deriveBits"]);if(K(e))return I(e,t,"deriveBits","deriveKey"),e;throw new TypeError(A(e,...b,"Uint8Array"))}async function vt(e,t,r,n){Qe(e);let o=wt(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 Kr(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 Jt=async(e,t,r,n=2048,o=G(new Uint8Array(16)))=>{let a=await vt(o,e,n,t);return {encryptedKey:await me(e.slice(-6),a,r),p2c:n,p2s:E(o)}},Tt=async(e,t,r,n,o)=>{let a=await vt(o,e,n,t);return ye(e.slice(-6),a,r)};function pe(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 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 It=async(e,t,r)=>{if(!K(t))throw new TypeError(A(t,...b));if(I(t,e,"encrypt","wrapKey"),Q(e,t),t.usages.includes("encrypt"))return new Uint8Array(await f.subtle.encrypt(pe(e),t,r));if(t.usages.includes("wrapKey")){let n=await f.subtle.importKey("raw",r,...de);return new Uint8Array(await f.subtle.wrapKey("raw",n,t,pe(e)))}throw new TypeError('RSA-OAEP key "usages" must include "encrypt" or "wrapKey" for this operation')},Ot=async(e,t,r)=>{if(!K(t))throw new TypeError(A(t,...b));if(I(t,e,"decrypt","unwrapKey"),Q(e,t),t.usages.includes("decrypt"))return new Uint8Array(await f.subtle.decrypt(pe(e),t,r));if(t.usages.includes("unwrapKey")){let n=await f.subtle.unwrapKey("raw",r,t,pe(e),...de);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 L(e){return y(e)&&typeof e.kty=="string"}function Rt(e){return e.kty!=="oct"&&typeof e.d=="string"}function Ut(e){return e.kty!=="oct"&&typeof e.d>"u"}function Dt(e){return L(e)&&e.kty==="oct"&&typeof e.k=="string"}function _r(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 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"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 u('Invalid or unsupported JWK "alg" (Algorithm) Parameter value')}break}default:throw new u('Invalid or unsupported JWK "kty" (Key Type) Parameter value')}return {algorithm:t,keyUsages:r}}var Hr=async e=>{if(!e.alg)throw new TypeError('"alg" argument is required when "jwk.alg" is not present');let{algorithm:t,keyUsages:r}=_r(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)},Le=Hr;var Mt=e=>g(e),fe,ue,Nt=e=>e?.[Symbol.toStringTag]==="KeyObject",$e=async(e,t,r,n,o=!1)=>{let a=e.get(t);if(a?.[n])return a[n];let i=await Le({...r,alg:n});return o&&Object.freeze(t),a?a[n]=i:e.set(t,{[n]:i}),i},Cr=(e,t)=>{if(Nt(e)){let r=e.export({format:"jwk"});return delete r.d,delete r.dp,delete r.dq,delete r.p,delete r.q,delete r.qi,r.k?Mt(r.k):(ue||(ue=new WeakMap),$e(ue,e,r,t))}return L(e)?e.k?g(e.k):(ue||(ue=new WeakMap),$e(ue,e,e,t,!0)):e},Pr=(e,t)=>{if(Nt(e)){let r=e.export({format:"jwk"});return r.k?Mt(r.k):(fe||(fe=new WeakMap),$e(fe,e,r,t))}return L(e)?e.k?g(e.k):(fe||(fe=new WeakMap),$e(fe,e,e,t,!0)):e},j={normalizePublicKey:Cr,normalizePrivateKey:Pr};function we(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 u(`Unsupported JWE Algorithm: ${e}`)}}var U=e=>G(new Uint8Array(we(e)>>3));var je=(e,t)=>{let r=(e.match(/.{1,64}/g)||[]).join(` `);return `-----BEGIN ${t}----- ${r} ------END ${t}-----`};var kt=async(e,t,r)=>{if(!K(r))throw new TypeError(A(r,...b));if(!r.extractable)throw new TypeError("CryptoKey is not extractable");if(r.type!==e)throw new TypeError(`key is not a ${e} key`);return je(Oe(new Uint8Array(await f.subtle.exportKey(t,r))),`${e.toUpperCase()} KEY`)},Bt=e=>kt("public","spki",e),Gt=e=>kt("private","pkcs8",e),V=(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])||V(e,t,n+1)},Lt=e=>{switch(!0){case V(e,[42,134,72,206,61,3,1,7]):return "P-256";case V(e,[43,129,4,0,34]):return "P-384";case V(e,[43,129,4,0,35]):return "P-521";case V(e,[43,101,110]):return "X25519";case V(e,[43,101,111]):return "X448";case V(e,[43,101,112]):return "Ed25519";case V(e,[43,101,113]):return "Ed448";default:throw new u("Invalid or unsupported EC Key Curve or OKP Key Sub Type")}},Ft=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=Lt(s);a=p.startsWith("P-")?{name:"ECDH",namedCurve:p}:{name:p},i=d?[]:["deriveBits"];break}case"EdDSA":a={name:Lt(s)},i=d?["verify"]:["sign"];break;default:throw new u('Invalid or unsupported "alg" (Algorithm) value')}return f.subtle.importKey(t,s,a,o?.extractable??!1,i)},Vt=(e,t,r)=>Ft(/(?:-----(?:BEGIN|END) PRIVATE KEY-----|\s)/g,"pkcs8",e,t,r),et=(e,t,r)=>Ft(/(?:-----(?:BEGIN|END) PUBLIC KEY-----|\s)/g,"spki",e,t,r);function $t(e){let t=[],r=0;for(;r=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{let n;try{n=vr(e);}catch(o){throw new TypeError("Failed to parse the X.509 certificate",{cause:o})}return et(n,t,r)};async function Jr(e,t,r){if(typeof e!="string"||e.indexOf("-----BEGIN PUBLIC KEY-----")!==0)throw new TypeError('"spki" must be SPKI formatted string');return et(e,t,r)}async function Tr(e,t,r){if(typeof e!="string"||e.indexOf("-----BEGIN CERTIFICATE-----")!==0)throw new TypeError('"x509" must be X.509 formatted string');return Xt(e,t,r)}async function Ir(e,t,r){if(typeof e!="string"||e.indexOf("-----BEGIN PRIVATE KEY-----")!==0)throw new TypeError('"pkcs8" must be PKCS#8 formatted string');return Vt(e,t,r)}async function $(e,t){if(!y(e))throw new TypeError("JWK must be an object");switch(t||(t=e.alg),e.kty){case"oct":if(typeof e.k!="string"||!e.k)throw new TypeError('missing "k" (Key Value) Parameter value');return 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 he=e=>e?.[Symbol.toStringTag],tt=(e,t,r)=>{if(t.use!==void 0&&t.use!=="sig")throw new TypeError("Invalid key for this operation, when present its use must be sig");if(t.key_ops!==void 0&&t.key_ops.includes?.(r)!==!0)throw new TypeError(`Invalid key for this operation, when present its key_ops must include ${r}`);if(t.alg!==void 0&&t.alg!==e)throw new TypeError(`Invalid key for this operation, when present its alg must be ${e}`);return !0},Or=(e,t,r,n)=>{if(!(t instanceof Uint8Array)){if(n&&L(t)){if(Dt(t)&&tt(e,t,r))return;throw new TypeError('JSON Web Key for symmetric algorithms must have JWK "kty" (Key Type) equal to "oct" and the JWK "k" (Key Value) present')}if(!Ze(t))throw new TypeError(qe(e,t,...b,"Uint8Array",n?"JSON Web Key":null));if(t.type!=="secret")throw new TypeError(`${he(t)} instances for symmetric algorithms must be of type "secret"`)}},Rr=(e,t,r,n)=>{if(n&&L(t))switch(r){case"sign":if(Rt(t)&&tt(e,t,r))return;throw new TypeError("JSON Web Key for this operation be a private JWK");case"verify":if(Ut(t)&&tt(e,t,r))return;throw new TypeError("JSON Web Key for this operation be a public JWK")}if(!Ze(t))throw new TypeError(qe(e,t,...b,n?"JSON Web Key":null));if(t.type==="secret")throw new TypeError(`${he(t)} instances for asymmetric algorithms must not be of type "secret"`);if(r==="sign"&&t.type==="public")throw new TypeError(`${he(t)} instances for asymmetric algorithm signing must be of type "private"`);if(r==="decrypt"&&t.type==="public")throw new TypeError(`${he(t)} instances for asymmetric algorithm decryption must be of type "private"`);if(t.algorithm&&r==="verify"&&t.type==="private")throw new TypeError(`${he(t)} instances for asymmetric algorithm verifying must be of type "public"`);if(t.algorithm&&r==="encrypt"&&t.type==="private")throw new TypeError(`${he(t)} instances for asymmetric algorithm encryption must be of type "public"`)};function Yt(e,t,r,n){t.startsWith("HS")||t==="dir"||t.startsWith("PBES2")||/^A\d{3}(?:GCM)?KW$/.test(t)?Or(t,r,n,e):Rr(t,r,n,e);}var ke=Yt.bind(void 0,!1),Ee=Yt.bind(void 0,!0);async function Ur(e,t,r,n,o){if(!(r instanceof Uint8Array))throw new TypeError(A(r,"Uint8Array"));let a=parseInt(e.slice(1,4),10),i=await f.subtle.importKey("raw",r.subarray(a>>3),"AES-CBC",!1,["encrypt"]),s=await f.subtle.importKey("raw",r.subarray(0,a>>3),{hash:`SHA-${a<<1}`,name:"HMAC"},!1,["sign"]),d=new Uint8Array(await f.subtle.encrypt({iv:n,name:"AES-CBC"},i,t)),p=W(o,n,d,Je(o.length<<3)),h=new Uint8Array((await f.subtle.sign("HMAC",s,p)).slice(0,a>>3));return {ciphertext:d,tag:h,iv:n}}async function Dr(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,iv:n}}var Mr=async(e,t,r,n,o)=>{if(!K(r)&&!(r instanceof Uint8Array))throw new TypeError(A(r,...b,"Uint8Array"));switch(n?Re(e,n):n=bt(e),e){case"A128CBC-HS256":case"A192CBC-HS384":case"A256CBC-HS512":return r instanceof Uint8Array&&ce(r,parseInt(e.slice(-3),10)),Ur(e,t,r,n,o);case"A128GCM":case"A192GCM":case"A256GCM":return r instanceof Uint8Array&&ce(r,parseInt(e.slice(1,4),10)),Dr(e,t,r,n,o);default:throw new u("Unsupported JWE Content Encryption Algorithm")}},Be=Mr;async function qt(e,t,r,n){let o=e.slice(0,7),a=await Be(o,r,t,n,new Uint8Array(0));return {encryptedKey:a.ciphertext,iv:E(a.iv),tag:E(a.tag)}}async function Zt(e,t,r,n,o){let a=e.slice(0,7);return De(a,t,r,n,o,new Uint8Array(0))}async function Nr(e,t,r,n,o){switch(ke(e,t,"decrypt"),t=await j.normalizePrivateKey?.(t,e)||t,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(!y(n.epk))throw new c('JOSE Header "epk" (Ephemeral Public Key) missing or invalid');if(!Ne(t))throw new u("ECDH with the provided key is not allowed or not supported by your javascript runtime");let a=await $(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=g(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=g(n.apv);}catch{throw new c("Failed to base64url decode the apv")}}let d=await Me(a,t,e==="ECDH-ES"?n.enc:e,e==="ECDH-ES"?we(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 ye(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 Ot(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=g(n.p2s);}catch{throw new c("Failed to base64url decode the p2s")}return Tt(e,t,r,n.p2c,i)}case"A128KW":case"A192KW":case"A256KW":{if(r===void 0)throw new c("JWE Encrypted Key missing");return ye(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=g(n.iv);}catch{throw new c("Failed to base64url decode the iv")}let i;try{i=g(n.tag);}catch{throw new c("Failed to base64url decode the tag")}return Zt(e,t,r,a,i)}default:throw new u('Invalid or unsupported "alg" (JWE Algorithm) header value')}}var Qt=Nr;function Lr(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 u(`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 D=Lr;var $r=(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)},ge=$r;async function Se(e,t,r){if(!y(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(e.iv!==void 0&&typeof e.iv!="string")throw new c("JWE Initialization Vector incorrect type");if(typeof e.ciphertext!="string")throw new c("JWE Ciphertext missing or incorrect type");if(e.tag!==void 0&&typeof e.tag!="string")throw new c("JWE Authentication Tag 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&&!y(e.header))throw new c("JWE Shared Unprotected Header incorrect type");if(e.unprotected!==void 0&&!y(e.unprotected))throw new c("JWE Per-Recipient Unprotected Header incorrect type");let n;if(e.protected)try{let oe=g(e.protected);n=JSON.parse(x.decode(oe));}catch{throw new c("JWE Protected Header is invalid")}if(!R(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(D(c,new Map,r?.crit,n,o),o.zip!==void 0)throw new u('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&&ge("keyManagementAlgorithms",r.keyManagementAlgorithms),d=r&&ge("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=g(e.encrypted_key);}catch{throw new c("Failed to base64url decode the encrypted_key")}let h=!1;typeof t=="function"&&(t=await t(n,e),h=!0);let l;try{l=await Qt(a,t,p,o,r);}catch(oe){if(oe instanceof TypeError||oe instanceof c||oe instanceof u)throw oe;l=U(i);}let T,J;if(e.iv!==void 0)try{T=g(e.iv);}catch{throw new c("Failed to base64url decode the iv")}if(e.tag!==void 0)try{J=g(e.tag);}catch{throw new c("Failed to base64url decode the tag")}let S=w.encode(e.protected??""),P;e.aad!==void 0?P=W(S,w.encode("."),w.encode(e.aad)):P=S;let Pe;try{Pe=g(e.ciphertext);}catch{throw new c("Failed to base64url decode the ciphertext")}let ne={plaintext:await De(i,l,Pe,T,J,P)};if(e.protected!==void 0&&(ne.protectedHeader=n),e.aad!==void 0)try{ne.additionalAuthenticatedData=g(e.aad);}catch{throw new c("Failed to base64url decode the aad")}return e.unprotected!==void 0&&(ne.sharedUnprotectedHeader=e.unprotected),e.header!==void 0&&(ne.unprotectedHeader=e.header),h?{...ne,key:t}:ne}async function rt(e,t,r){if(e instanceof Uint8Array&&(e=x.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 Se({ciphertext:i,iv:a||void 0,protected:n,tag:s||void 0,encrypted_key:o||void 0},t,r),h={plaintext:p.plaintext,protectedHeader:p.protectedHeader};return typeof t=="function"?{...h,key:p.key}:h}async function kr(e,t,r){if(!y(e))throw new c("General JWE must be an object");if(!Array.isArray(e.recipients)||!e.recipients.every(y))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 Se({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 O}var Ge=Symbol();var Br=async e=>{if(e instanceof Uint8Array)return {kty:"oct",k:E(e)};if(!K(e))throw new TypeError(A(e,...b,"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},jt=Br;async function Gr(e){return Bt(e)}async function Fr(e){return Gt(e)}async function nt(e){return jt(e)}async function Vr(e,t,r,n,o={}){let a,i,s;switch(ke(e,r,"encrypt"),r=await j.normalizePublicKey?.(r,e)||r,e){case"dir":{s=r;break}case"ECDH-ES":case"ECDH-ES+A128KW":case"ECDH-ES+A192KW":case"ECDH-ES+A256KW":{if(!Ne(r))throw new u("ECDH with the provided key is not allowed or not supported by your javascript runtime");let{apu:d,apv:p}=o,{epk:h}=o;h||(h=(await Pt(r)).privateKey);let{x:l,y:T,crv:J,kty:S}=await nt(h),P=await Me(r,h,e==="ECDH-ES"?t:e,e==="ECDH-ES"?we(t):parseInt(e.slice(-5,-2),10),d,p);if(i={epk:{x:l,crv:J,kty:S}},S==="EC"&&(i.epk.y=T),d&&(i.apu=E(d)),p&&(i.apv=E(p)),e==="ECDH-ES"){s=P;break}s=n||U(t);let Pe=e.slice(-6);a=await me(Pe,P,s);break}case"RSA1_5":case"RSA-OAEP":case"RSA-OAEP-256":case"RSA-OAEP-384":case"RSA-OAEP-512":{s=n||U(t),a=await It(e,r,s);break}case"PBES2-HS256+A128KW":case"PBES2-HS384+A192KW":case"PBES2-HS512+A256KW":{s=n||U(t);let{p2c:d,p2s:p}=o;({encryptedKey:a,...i}=await Jt(e,r,s,d,p));break}case"A128KW":case"A192KW":case"A256KW":{s=n||U(t),a=await me(e,r,s);break}case"A128GCMKW":case"A192GCMKW":case"A256GCMKW":{s=n||U(t);let{iv:d}=o;({encryptedKey:a,...i}=await qt(e,r,s,d));break}default:throw new u('Invalid or unsupported "alg" (JWE Algorithm) header value')}return {cek:s,encryptedKey:a,parameters:i}}var Fe=Vr;var z=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(!R(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(D(c,new Map,r?.crit,this._protectedHeader,n),n.zip!==void 0)throw new u('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(this._cek&&(o==="dir"||o==="ECDH-ES"))throw new TypeError(`setContentEncryptionKey cannot be called with JWE "alg" (Algorithm) Header ${o}`);let s;{let P;(({cek:s,encryptedKey:i,parameters:P}=await Fe(o,a,t,this._cek,this._keyManagementParameters))),P&&(r&&Ge in r?this._unprotectedHeader?this._unprotectedHeader={...this._unprotectedHeader,...P}:this.setUnprotectedHeader(P):this._protectedHeader?this._protectedHeader={...this._protectedHeader,...P}:this.setProtectedHeader(P));}let d,p,h;this._protectedHeader?p=w.encode(E(JSON.stringify(this._protectedHeader))):p=w.encode(""),this._aad?(h=E(this._aad),d=W(p,w.encode("."),w.encode(h))):d=p;let{ciphertext:l,tag:T,iv:J}=await Be(a,this._plaintext,s,this._iv,d),S={ciphertext:E(l)};return J&&(S.iv=E(J)),T&&(S.tag=E(T)),i&&(S.encrypted_key=E(i)),h&&(S.aad=h),this._protectedHeader&&(S.protected=x.decode(p)),this._sharedUnprotectedHeader&&(S.unprotected=this._sharedUnprotectedHeader),this._unprotectedHeader&&(S.header=this._unprotectedHeader),S}};var ot=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}},at=class{constructor(t){this._recipients=[],this._plaintext=t;}addRecipient(t,r){let n=new ot(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 z(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>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 u(`alg ${e} is not supported either by JOSE or your javascript runtime`)}}async function Ae(e,t,r){if(r==="sign"&&(t=await j.normalizePrivateKey(t,e)),r==="verify"&&(t=await j.normalizePublicKey(t,e)),K(t))return xt(t,e,r),t;if(t instanceof Uint8Array){if(!e.startsWith("HS"))throw new TypeError(A(t,...b));return f.subtle.importKey("raw",t,{hash:`SHA-${e.slice(-3)}`,name:"HMAC"},!1,[r])}throw new TypeError(A(t,...b,"Uint8Array","JSON Web Key"))}var zr=async(e,t,r,n)=>{let o=await Ae(e,t,"verify");Q(e,o);let a=be(e,o.algorithm);try{return await f.subtle.verify(a,o,r,n)}catch{return !1}},er=zr;async function Ke(e,t,r){if(!y(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&&!y(e.header))throw new m("JWS Unprotected Header incorrect type");let n={};if(e.protected)try{let P=g(e.protected);n=JSON.parse(x.decode(P));}catch{throw new m("JWS Protected Header is invalid")}if(!R(n,e.header))throw new m("JWS Protected and JWS Unprotected Header Parameter names must be disjoint");let o={...n,...e.header},a=D(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&&ge("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,Ee(s,t,"verify"),L(t)&&(t=await $(t,s))):Ee(s,t,"verify");let h=W(w.encode(e.protected??""),w.encode("."),typeof e.payload=="string"?w.encode(e.payload):e.payload),l;try{l=g(e.signature);}catch{throw new m("Failed to base64url decode the signature")}if(!await er(s,t,l,h))throw new B;let J;if(i)try{J=g(e.payload);}catch{throw new m("Failed to base64url decode the payload")}else typeof e.payload=="string"?J=w.encode(e.payload):J=e.payload;let S={payload:J};return e.protected!==void 0&&(S.protectedHeader=n),e.header!==void 0&&(S.unprotectedHeader=e.header),p?{...S,key:t}:S}async function it(e,t,r){if(e instanceof Uint8Array&&(e=x.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 Ke({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 Xr(e,t,r){if(!y(e))throw new m("General JWS must be an object");if(!Array.isArray(e.signatures)||!e.signatures.every(y))throw new m("JWS Signatures missing or incorrect type");for(let n of e.signatures)try{return await Ke({header:n.header,payload:e.payload,protected:n.protected,signature:n.signature},t,r)}catch{}throw new B}var M=e=>Math.floor(e.getTime()/1e3);var Yr=/^(\+|\-)? ?(\d+|\d+\.\d+) ?(seconds?|secs?|s|minutes?|mins?|m|hours?|hrs?|h|days?|d|weeks?|w|years?|yrs?|y)(?: (ago|from now))?$/i,ee=e=>{let t=Yr.exec(e);if(!t||t[4]&&t[1])throw new TypeError("Invalid time period format");let r=parseFloat(t[2]),n=t[3].toLowerCase(),o;switch(n){case"sec":case"secs":case"second":case"seconds":case"s":o=Math.round(r);break;case"minute":case"minutes":case"min":case"mins":case"m":o=Math.round(r*60);break;case"hour":case"hours":case"hr":case"hrs":case"h":o=Math.round(r*3600);break;case"day":case"days":case"d":o=Math.round(r*86400);break;case"week":case"weeks":case"w":o=Math.round(r*604800);break;default:o=Math.round(r*31557600);break}return t[1]==="-"||t[4]==="ago"?-o:o};var tr=e=>e.toLowerCase().replace(/^application\//,""),qr=(e,t)=>typeof e=="string"?t.includes(e):Array.isArray(e)?t.some(Set.prototype.has.bind(new Set(e))):!1,le=(e,t,r={})=>{let n;try{n=JSON.parse(x.decode(t));}catch{}if(!y(n))throw new _("JWT Claims Set must be a top-level JSON object");let{typ:o}=r;if(o&&(typeof e.typ!="string"||tr(e.typ)!==tr(o)))throw new C('unexpected "typ" JWT header value',n,"typ","check_failed");let{requiredClaims:a=[],issuer:i,subject:s,audience:d,maxTokenAge:p}=r,h=[...a];p!==void 0&&h.push("iat"),d!==void 0&&h.push("aud"),s!==void 0&&h.push("sub"),i!==void 0&&h.push("iss");for(let S of new Set(h.reverse()))if(!(S in n))throw new C(`missing required "${S}" claim`,n,S,"missing");if(i&&!(Array.isArray(i)?i:[i]).includes(n.iss))throw new C('unexpected "iss" claim value',n,"iss","check_failed");if(s&&n.sub!==s)throw new C('unexpected "sub" claim value',n,"sub","check_failed");if(d&&!qr(n.aud,typeof d=="string"?[d]:d))throw new C('unexpected "aud" claim value',n,"aud","check_failed");let l;switch(typeof r.clockTolerance){case"string":l=ee(r.clockTolerance);break;case"number":l=r.clockTolerance;break;case"undefined":l=0;break;default:throw new TypeError("Invalid clockTolerance option type")}let{currentDate:T}=r,J=M(T||new Date);if((n.iat!==void 0||p)&&typeof n.iat!="number")throw new C('"iat" claim must be a number',n,"iat","invalid");if(n.nbf!==void 0){if(typeof n.nbf!="number")throw new C('"nbf" claim must be a number',n,"nbf","invalid");if(n.nbf>J+l)throw new C('"nbf" claim timestamp check failed',n,"nbf","check_failed")}if(n.exp!==void 0){if(typeof n.exp!="number")throw new C('"exp" claim must be a number',n,"exp","invalid");if(n.exp<=J-l)throw new q('"exp" claim timestamp check failed',n,"exp","check_failed")}if(p){let S=J-n.iat,P=typeof p=="number"?p:ee(p);if(S-l>P)throw new q('"iat" claim timestamp check failed (too far in the past)',n,"iat","check_failed");if(S<0-l)throw new C('"iat" claim timestamp check failed (it should be in the past)',n,"iat","check_failed")}return n};async function Zr(e,t,r){let n=await it(e,t,r);if(n.protectedHeader.crit?.includes("b64")&&n.protectedHeader.b64===!1)throw new _("JWTs MUST NOT use unencoded payload");let a={payload:le(n.protectedHeader,n.payload,r),protectedHeader:n.protectedHeader};return typeof t=="function"?{...a,key:n.key}:a}async function Qr(e,t,r){let n=await rt(e,t,r),o=le(n.protectedHeader,n.plaintext,r),{protectedHeader:a}=n;if(a.iss!==void 0&&a.iss!==o.iss)throw new C('replicated "iss" claim header parameter mismatch',o,"iss","mismatch");if(a.sub!==void 0&&a.sub!==o.sub)throw new C('replicated "sub" claim header parameter mismatch',o,"sub","mismatch");if(a.aud!==void 0&&JSON.stringify(a.aud)!==JSON.stringify(o.aud))throw new C('replicated "aud" claim header parameter mismatch',o,"aud","mismatch");let i={payload:o,protectedHeader:a};return typeof t=="function"?{...i,key:n.key}:i}var xe=class{constructor(t){this._flattened=new z(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 Ae(e,t,"sign");Q(e,n);let o=await f.subtle.sign(be(e,n.algorithm),n,r);return new Uint8Array(o)},rr=jr;var te=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(!R(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=D(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');Ee(i,t,"sign");let s=this._payload;a&&(s=w.encode(E(s)));let d;this._protectedHeader?d=w.encode(E(JSON.stringify(this._protectedHeader))):d=w.encode("");let p=W(d,w.encode("."),s),h=await rr(i,t,p),l={signature:E(h),payload:""};return a&&(l.payload=x.decode(s)),this._unprotectedHeader&&(l.header=this._unprotectedHeader),this._protectedHeader&&(l.protected=x.decode(d)),l}};var _e=class{constructor(t){this._flattened=new te(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 st=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}},ct=class{constructor(t){this._signatures=[],this._payload=t;}addSignature(t,r){let n=new st(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"u"?this._payload={...this._payload,iat:M(new Date)}:t instanceof Date?this._payload={...this._payload,iat:re("setIssuedAt",M(t))}:typeof t=="string"?this._payload={...this._payload,iat:re("setIssuedAt",M(new Date)+ee(t))}:this._payload={...this._payload,iat:re("setIssuedAt",t)},this}};var dt=class extends X{setProtectedHeader(t){return this._protectedHeader=t,this}async sign(t,r){let n=new _e(w.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 _("JWTs MUST NOT use unencoded payload");return n.sign(t,r)}};var pt=class extends X{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 xe(w.encode(JSON.stringify(this._payload)));return this._replicateIssuerAsHeader&&(this._protectedHeader={...this._protectedHeader,iss:this._payload.iss}),this._replicateSubjectAsHeader&&(this._protectedHeader={...this._protectedHeader,sub:this._payload.sub}),this._replicateAudienceAsHeader&&(this._protectedHeader={...this._protectedHeader,aud:this._payload.aud}),n.setProtectedHeader(this._protectedHeader),this._iv&&n.setInitializationVector(this._iv),this._cek&&n.setContentEncryptionKey(this._cek),this._keyManagementParameters&&n.setKeyManagementParameters(this._keyManagementParameters),n.encrypt(t,r)}};var Y=(e,t)=>{if(typeof e!="string"||!e)throw new ae(`${t} missing or invalid`)};async function nr(e,t){if(!y(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":Y(e.crv,'"crv" (Curve) Parameter'),Y(e.x,'"x" (X Coordinate) Parameter'),Y(e.y,'"y" (Y Coordinate) Parameter'),r={crv:e.crv,kty:e.kty,x:e.x,y:e.y};break;case"OKP":Y(e.crv,'"crv" (Subtype of Key Pair) Parameter'),Y(e.x,'"x" (Public Key) Parameter'),r={crv:e.crv,kty:e.kty,x:e.x};break;case"RSA":Y(e.e,'"e" (Exponent) Parameter'),Y(e.n,'"n" (Modulus) Parameter'),r={e:e.e,kty:e.kty,n:e.n};break;case"oct":Y(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=w.encode(JSON.stringify(r));return E(await We(t,n))}async function en(e,t){t??(t="sha256");let r=await nr(e,t);return `urn:ietf:params:oauth:jwk-thumbprint:sha-${t.slice(-3)}:${r}`}async function tn(e,t){let r={...e,...t?.header};if(!y(r.jwk))throw new m('"jwk" (JSON Web Key) Header Parameter must be a JSON object');let n=await $({...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 rn(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 u('Unsupported "alg" value for a JSON Web Key Set')}}function nn(e){return e&&typeof e=="object"&&Array.isArray(e.keys)&&e.keys.every(on)}function on(e){return y(e)}function ar(e){return typeof structuredClone=="function"?structuredClone(e):JSON.parse(JSON.stringify(e))}var ft=class{constructor(t){if(this._cached=new WeakMap,!nn(t))throw new Z("JSON Web Key Set malformed");this._jwks=ar(t);}async getKey(t,r){let{alg:n,kid:o}={...t,...r?.header},a=rn(n),i=this._jwks.keys.filter(p=>{let h=a===p.kty;if(h&&typeof o=="string"&&(h=o===p.kid),h&&typeof p.alg=="string"&&(h=n===p.alg),h&&typeof p.use=="string"&&(h=p.use==="sig"),h&&Array.isArray(p.key_ops)&&(h=p.key_ops.includes("verify")),h&&n==="EdDSA"&&(h=p.crv==="Ed25519"||p.crv==="Ed448"),h)switch(n){case"ES256":h=p.crv==="P-256";break;case"ES256K":h=p.crv==="secp256k1";break;case"ES384":h=p.crv==="P-384";break;case"ES512":h=p.crv==="P-521";break}return h}),{0:s,length:d}=i;if(d===0)throw new k;if(d!==1){let p=new ie,{_cached:h}=this;throw p[Symbol.asyncIterator]=async function*(){for(let l of i)try{yield await or(h,l,n);}catch{}},p}return or(this._cached,s,n)}};async function or(e,t,r){let n=e.get(t)||e.set(t,{}).get(t);if(n[r]===void 0){let o=await $({...t,ext:!0},r);if(o instanceof Uint8Array||o.type!=="public")throw new Z("JSON Web Key Set members must be public keys");n[r]=o;}return n[r]}function Ve(e){let t=new ft(e),r=async(n,o)=>t.getKey(n,o);return Object.defineProperties(r,{jwks:{value:()=>ar(t._jwks),enumerable:!0,configurable:!1,writable:!1}}),r}var an=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 se: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")}},ir=an;function sn(){return typeof WebSocketPair<"u"||typeof navigator<"u"&&navigator.userAgent==="Cloudflare-Workers"||typeof EdgeRuntime<"u"&&EdgeRuntime==="vercel"}var ut;(typeof navigator>"u"||!navigator.userAgent?.startsWith?.("Mozilla/5.0 "))&&(ut="jose/v5.9.5");var He=Symbol();function cn(e,t){return !(typeof e!="object"||e===null||!("uat"in e)||typeof e.uat!="number"||Date.now()-e.uat>=t||!("jwks"in e)||!y(e.jwks)||!Array.isArray(e.jwks.keys)||!Array.prototype.every.call(e.jwks.keys,y))}var ht=class{constructor(t,r){if(!(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,r?.[He]!==void 0&&(this._cache=r?.[He],cn(r?.[He],this._cacheMaxAge)&&(this._jwksTimestamp=this._cache.uat,this._local=Ve(this._cache.jwks)));}coolingDown(){return typeof this._jwksTimestamp=="number"?Date.now(){this._local=Ve(r),this._cache&&(this._cache.uat=Date.now(),this._cache.jwks=r),this._jwksTimestamp=Date.now(),this._pendingFetch=void 0;}).catch(r=>{throw this._pendingFetch=void 0,r})),await this._pendingFetch;}};function dn(e,t){let r=new ht(e,t),n=async(o,a)=>r.getKey(o,a);return Object.defineProperties(n,{coolingDown:{get:()=>r.coolingDown(),enumerable:!0,configurable:!1},fresh:{get:()=>r.fresh(),enumerable:!0,configurable:!1},reload:{value:()=>r.reload(),enumerable:!0,configurable:!1,writable:!1},reloading:{get:()=>!!r._pendingFetch,enumerable:!0,configurable:!1},jwks:{value:()=>r._local?.jwks(),enumerable:!0,configurable:!1,writable:!1}}),n}var pn=He;var lt=class extends X{encode(){let t=E(JSON.stringify({alg:"none"})),r=E(JSON.stringify(this._payload));return `${t}.${r}.`}static decode(t,r){if(typeof t!="string")throw new _("Unsecured JWT must be a string");let{0:n,1:o,2:a,length:i}=t.split(".");if(i!==3||a!=="")throw new _("Invalid Unsecured JWT");let s;try{if(s=JSON.parse(x.decode(g(n))),s.alg!=="none")throw new Error}catch{throw new _("Invalid Unsecured JWT")}return {payload:le(s,g(o),r),header:s}}};var sr={};yt(sr,{decode:()=>Ce,encode:()=>fn});var fn=E,Ce=g;function un(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(x.decode(Ce(t)));if(!y(r))throw new Error;return r}catch{throw new TypeError("Invalid Token or Protected Header formatting")}}function hn(e){if(typeof e!="string")throw new _("JWTs must use Compact JWS serialization, JWT must be a string");let{1:t,length:r}=e.split(".");if(r===5)throw new _("Only JWTs using Compact JWS serialization can be decoded");if(r!==3)throw new _("Invalid JWT");if(!t)throw new _("JWTs must contain a payload");let n;try{n=Ce(t);}catch{throw new _("Failed to base64url decode the payload")}let o;try{o=JSON.parse(x.decode(n));}catch{throw new _("Failed to parse the decoded payload as JSON")}if(!y(o))throw new _("Invalid JWT Claims Set");return o}async function cr(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),G(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 u('Invalid or unsupported JWK "alg" (Algorithm) Parameter value')}return f.subtle.generateKey(n,t?.extractable??!1,o)}function mt(e){let t=e?.modulusLength??2048;if(typeof t!="number"||t<2048)throw new u("Invalid or unsupported modulusLength option provided, 2048 bits or larger keys must be used");return t}async function dr(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:mt(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:mt(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:mt(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 u("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 o=t?.crv??"P-256";switch(o){case"P-256":case"P-384":case"P-521":{r={name:"ECDH",namedCurve:o};break}case"X25519":case"X448":r={name:o};break;default:throw new u("Invalid or unsupported crv option provided, supported values are P-256, P-384, P-521, X25519, and X448")}break}default:throw new u('Invalid or unsupported JWK "alg" (Algorithm) Parameter value')}return f.subtle.generateKey(r,t?.extractable??!1,n)}async function ln(e,t){return dr(e,t)}async function mn(e,t){return cr(e,t)}var pr="WebCryptoAPI";var yn=pr; +-----END ${t}-----`};var kt=async(e,t,r)=>{if(!K(r))throw new TypeError(A(r,...b));if(!r.extractable)throw new TypeError("CryptoKey is not extractable");if(r.type!==e)throw new TypeError(`key is not a ${e} key`);return je(Oe(new Uint8Array(await f.subtle.exportKey(t,r))),`${e.toUpperCase()} KEY`)},Bt=e=>kt("public","spki",e),Gt=e=>kt("private","pkcs8",e),V=(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])||V(e,t,n+1)},Lt=e=>{switch(!0){case V(e,[42,134,72,206,61,3,1,7]):return "P-256";case V(e,[43,129,4,0,34]):return "P-384";case V(e,[43,129,4,0,35]):return "P-521";case V(e,[43,101,110]):return "X25519";case V(e,[43,101,111]):return "X448";case V(e,[43,101,112]):return "Ed25519";case V(e,[43,101,113]):return "Ed448";default:throw new u("Invalid or unsupported EC Key Curve or OKP Key Sub Type")}},Ft=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=Lt(s);a=p.startsWith("P-")?{name:"ECDH",namedCurve:p}:{name:p},i=d?[]:["deriveBits"];break}case"EdDSA":a={name:Lt(s)},i=d?["verify"]:["sign"];break;default:throw new u('Invalid or unsupported "alg" (Algorithm) value')}return f.subtle.importKey(t,s,a,o?.extractable??!1,i)},Vt=(e,t,r)=>Ft(/(?:-----(?:BEGIN|END) PRIVATE KEY-----|\s)/g,"pkcs8",e,t,r),et=(e,t,r)=>Ft(/(?:-----(?:BEGIN|END) PUBLIC KEY-----|\s)/g,"spki",e,t,r);function $t(e){let t=[],r=0;for(;r=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{let n;try{n=vr(e);}catch(o){throw new TypeError("Failed to parse the X.509 certificate",{cause:o})}return et(n,t,r)};async function Jr(e,t,r){if(typeof e!="string"||e.indexOf("-----BEGIN PUBLIC KEY-----")!==0)throw new TypeError('"spki" must be SPKI formatted string');return et(e,t,r)}async function Tr(e,t,r){if(typeof e!="string"||e.indexOf("-----BEGIN CERTIFICATE-----")!==0)throw new TypeError('"x509" must be X.509 formatted string');return Xt(e,t,r)}async function Ir(e,t,r){if(typeof e!="string"||e.indexOf("-----BEGIN PRIVATE KEY-----")!==0)throw new TypeError('"pkcs8" must be PKCS#8 formatted string');return Vt(e,t,r)}async function $(e,t){if(!y(e))throw new TypeError("JWK must be an object");switch(t||(t=e.alg),e.kty){case"oct":if(typeof e.k!="string"||!e.k)throw new TypeError('missing "k" (Key Value) Parameter value');return 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 he=e=>e?.[Symbol.toStringTag],tt=(e,t,r)=>{if(t.use!==void 0&&t.use!=="sig")throw new TypeError("Invalid key for this operation, when present its use must be sig");if(t.key_ops!==void 0&&t.key_ops.includes?.(r)!==!0)throw new TypeError(`Invalid key for this operation, when present its key_ops must include ${r}`);if(t.alg!==void 0&&t.alg!==e)throw new TypeError(`Invalid key for this operation, when present its alg must be ${e}`);return !0},Or=(e,t,r,n)=>{if(!(t instanceof Uint8Array)){if(n&&L(t)){if(Dt(t)&&tt(e,t,r))return;throw new TypeError('JSON Web Key for symmetric algorithms must have JWK "kty" (Key Type) equal to "oct" and the JWK "k" (Key Value) present')}if(!Ze(t))throw new TypeError(qe(e,t,...b,"Uint8Array",n?"JSON Web Key":null));if(t.type!=="secret")throw new TypeError(`${he(t)} instances for symmetric algorithms must be of type "secret"`)}},Rr=(e,t,r,n)=>{if(n&&L(t))switch(r){case"sign":if(Rt(t)&&tt(e,t,r))return;throw new TypeError("JSON Web Key for this operation be a private JWK");case"verify":if(Ut(t)&&tt(e,t,r))return;throw new TypeError("JSON Web Key for this operation be a public JWK")}if(!Ze(t))throw new TypeError(qe(e,t,...b,n?"JSON Web Key":null));if(t.type==="secret")throw new TypeError(`${he(t)} instances for asymmetric algorithms must not be of type "secret"`);if(r==="sign"&&t.type==="public")throw new TypeError(`${he(t)} instances for asymmetric algorithm signing must be of type "private"`);if(r==="decrypt"&&t.type==="public")throw new TypeError(`${he(t)} instances for asymmetric algorithm decryption must be of type "private"`);if(t.algorithm&&r==="verify"&&t.type==="private")throw new TypeError(`${he(t)} instances for asymmetric algorithm verifying must be of type "public"`);if(t.algorithm&&r==="encrypt"&&t.type==="private")throw new TypeError(`${he(t)} instances for asymmetric algorithm encryption must be of type "public"`)};function Yt(e,t,r,n){t.startsWith("HS")||t==="dir"||t.startsWith("PBES2")||/^A\d{3}(?:GCM)?KW$/.test(t)?Or(t,r,n,e):Rr(t,r,n,e);}var ke=Yt.bind(void 0,!1),Ee=Yt.bind(void 0,!0);async function Ur(e,t,r,n,o){if(!(r instanceof Uint8Array))throw new TypeError(A(r,"Uint8Array"));let a=parseInt(e.slice(1,4),10),i=await f.subtle.importKey("raw",r.subarray(a>>3),"AES-CBC",!1,["encrypt"]),s=await f.subtle.importKey("raw",r.subarray(0,a>>3),{hash:`SHA-${a<<1}`,name:"HMAC"},!1,["sign"]),d=new Uint8Array(await f.subtle.encrypt({iv:n,name:"AES-CBC"},i,t)),p=W(o,n,d,Je(o.length<<3)),h=new Uint8Array((await f.subtle.sign("HMAC",s,p)).slice(0,a>>3));return {ciphertext:d,tag:h,iv:n}}async function Dr(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,iv:n}}var Mr=async(e,t,r,n,o)=>{if(!K(r)&&!(r instanceof Uint8Array))throw new TypeError(A(r,...b,"Uint8Array"));switch(n?Re(e,n):n=bt(e),e){case"A128CBC-HS256":case"A192CBC-HS384":case"A256CBC-HS512":return r instanceof Uint8Array&&ce(r,parseInt(e.slice(-3),10)),Ur(e,t,r,n,o);case"A128GCM":case"A192GCM":case"A256GCM":return r instanceof Uint8Array&&ce(r,parseInt(e.slice(1,4),10)),Dr(e,t,r,n,o);default:throw new u("Unsupported JWE Content Encryption Algorithm")}},Be=Mr;async function qt(e,t,r,n){let o=e.slice(0,7),a=await Be(o,r,t,n,new Uint8Array(0));return {encryptedKey:a.ciphertext,iv:E(a.iv),tag:E(a.tag)}}async function Zt(e,t,r,n,o){let a=e.slice(0,7);return De(a,t,r,n,o,new Uint8Array(0))}async function Nr(e,t,r,n,o){switch(ke(e,t,"decrypt"),t=await j.normalizePrivateKey?.(t,e)||t,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(!y(n.epk))throw new c('JOSE Header "epk" (Ephemeral Public Key) missing or invalid');if(!Ne(t))throw new u("ECDH with the provided key is not allowed or not supported by your javascript runtime");let a=await $(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=g(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=g(n.apv);}catch{throw new c("Failed to base64url decode the apv")}}let d=await Me(a,t,e==="ECDH-ES"?n.enc:e,e==="ECDH-ES"?we(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 ye(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 Ot(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=g(n.p2s);}catch{throw new c("Failed to base64url decode the p2s")}return Tt(e,t,r,n.p2c,i)}case"A128KW":case"A192KW":case"A256KW":{if(r===void 0)throw new c("JWE Encrypted Key missing");return ye(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=g(n.iv);}catch{throw new c("Failed to base64url decode the iv")}let i;try{i=g(n.tag);}catch{throw new c("Failed to base64url decode the tag")}return Zt(e,t,r,a,i)}default:throw new u('Invalid or unsupported "alg" (JWE Algorithm) header value')}}var Qt=Nr;function Lr(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 u(`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 D=Lr;var $r=(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)},ge=$r;async function Se(e,t,r){if(!y(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(e.iv!==void 0&&typeof e.iv!="string")throw new c("JWE Initialization Vector incorrect type");if(typeof e.ciphertext!="string")throw new c("JWE Ciphertext missing or incorrect type");if(e.tag!==void 0&&typeof e.tag!="string")throw new c("JWE Authentication Tag 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&&!y(e.header))throw new c("JWE Shared Unprotected Header incorrect type");if(e.unprotected!==void 0&&!y(e.unprotected))throw new c("JWE Per-Recipient Unprotected Header incorrect type");let n;if(e.protected)try{let oe=g(e.protected);n=JSON.parse(x.decode(oe));}catch{throw new c("JWE Protected Header is invalid")}if(!R(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(D(c,new Map,r?.crit,n,o),o.zip!==void 0)throw new u('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&&ge("keyManagementAlgorithms",r.keyManagementAlgorithms),d=r&&ge("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=g(e.encrypted_key);}catch{throw new c("Failed to base64url decode the encrypted_key")}let h=!1;typeof t=="function"&&(t=await t(n,e),h=!0);let l;try{l=await Qt(a,t,p,o,r);}catch(oe){if(oe instanceof TypeError||oe instanceof c||oe instanceof u)throw oe;l=U(i);}let T,J;if(e.iv!==void 0)try{T=g(e.iv);}catch{throw new c("Failed to base64url decode the iv")}if(e.tag!==void 0)try{J=g(e.tag);}catch{throw new c("Failed to base64url decode the tag")}let S=w.encode(e.protected??""),P;e.aad!==void 0?P=W(S,w.encode("."),w.encode(e.aad)):P=S;let Pe;try{Pe=g(e.ciphertext);}catch{throw new c("Failed to base64url decode the ciphertext")}let ne={plaintext:await De(i,l,Pe,T,J,P)};if(e.protected!==void 0&&(ne.protectedHeader=n),e.aad!==void 0)try{ne.additionalAuthenticatedData=g(e.aad);}catch{throw new c("Failed to base64url decode the aad")}return e.unprotected!==void 0&&(ne.sharedUnprotectedHeader=e.unprotected),e.header!==void 0&&(ne.unprotectedHeader=e.header),h?{...ne,key:t}:ne}async function rt(e,t,r){if(e instanceof Uint8Array&&(e=x.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 Se({ciphertext:i,iv:a||void 0,protected:n,tag:s||void 0,encrypted_key:o||void 0},t,r),h={plaintext:p.plaintext,protectedHeader:p.protectedHeader};return typeof t=="function"?{...h,key:p.key}:h}async function kr(e,t,r){if(!y(e))throw new c("General JWE must be an object");if(!Array.isArray(e.recipients)||!e.recipients.every(y))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 Se({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 O}var Ge=Symbol();var Br=async e=>{if(e instanceof Uint8Array)return {kty:"oct",k:E(e)};if(!K(e))throw new TypeError(A(e,...b,"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},jt=Br;async function Gr(e){return Bt(e)}async function Fr(e){return Gt(e)}async function nt(e){return jt(e)}async function Vr(e,t,r,n,o={}){let a,i,s;switch(ke(e,r,"encrypt"),r=await j.normalizePublicKey?.(r,e)||r,e){case"dir":{s=r;break}case"ECDH-ES":case"ECDH-ES+A128KW":case"ECDH-ES+A192KW":case"ECDH-ES+A256KW":{if(!Ne(r))throw new u("ECDH with the provided key is not allowed or not supported by your javascript runtime");let{apu:d,apv:p}=o,{epk:h}=o;h||(h=(await Pt(r)).privateKey);let{x:l,y:T,crv:J,kty:S}=await nt(h),P=await Me(r,h,e==="ECDH-ES"?t:e,e==="ECDH-ES"?we(t):parseInt(e.slice(-5,-2),10),d,p);if(i={epk:{x:l,crv:J,kty:S}},S==="EC"&&(i.epk.y=T),d&&(i.apu=E(d)),p&&(i.apv=E(p)),e==="ECDH-ES"){s=P;break}s=n||U(t);let Pe=e.slice(-6);a=await me(Pe,P,s);break}case"RSA1_5":case"RSA-OAEP":case"RSA-OAEP-256":case"RSA-OAEP-384":case"RSA-OAEP-512":{s=n||U(t),a=await It(e,r,s);break}case"PBES2-HS256+A128KW":case"PBES2-HS384+A192KW":case"PBES2-HS512+A256KW":{s=n||U(t);let{p2c:d,p2s:p}=o;({encryptedKey:a,...i}=await Jt(e,r,s,d,p));break}case"A128KW":case"A192KW":case"A256KW":{s=n||U(t),a=await me(e,r,s);break}case"A128GCMKW":case"A192GCMKW":case"A256GCMKW":{s=n||U(t);let{iv:d}=o;({encryptedKey:a,...i}=await qt(e,r,s,d));break}default:throw new u('Invalid or unsupported "alg" (JWE Algorithm) header value')}return {cek:s,encryptedKey:a,parameters:i}}var Fe=Vr;var z=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(!R(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(D(c,new Map,r?.crit,this._protectedHeader,n),n.zip!==void 0)throw new u('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(this._cek&&(o==="dir"||o==="ECDH-ES"))throw new TypeError(`setContentEncryptionKey cannot be called with JWE "alg" (Algorithm) Header ${o}`);let s;{let P;(({cek:s,encryptedKey:i,parameters:P}=await Fe(o,a,t,this._cek,this._keyManagementParameters))),P&&(r&&Ge in r?this._unprotectedHeader?this._unprotectedHeader={...this._unprotectedHeader,...P}:this.setUnprotectedHeader(P):this._protectedHeader?this._protectedHeader={...this._protectedHeader,...P}:this.setProtectedHeader(P));}let d,p,h;this._protectedHeader?p=w.encode(E(JSON.stringify(this._protectedHeader))):p=w.encode(""),this._aad?(h=E(this._aad),d=W(p,w.encode("."),w.encode(h))):d=p;let{ciphertext:l,tag:T,iv:J}=await Be(a,this._plaintext,s,this._iv,d),S={ciphertext:E(l)};return J&&(S.iv=E(J)),T&&(S.tag=E(T)),i&&(S.encrypted_key=E(i)),h&&(S.aad=h),this._protectedHeader&&(S.protected=x.decode(p)),this._sharedUnprotectedHeader&&(S.unprotected=this._sharedUnprotectedHeader),this._unprotectedHeader&&(S.header=this._unprotectedHeader),S}};var ot=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}},at=class{constructor(t){this._recipients=[],this._plaintext=t;}addRecipient(t,r){let n=new ot(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 z(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>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 u(`alg ${e} is not supported either by JOSE or your javascript runtime`)}}async function Ae(e,t,r){if(r==="sign"&&(t=await j.normalizePrivateKey(t,e)),r==="verify"&&(t=await j.normalizePublicKey(t,e)),K(t))return xt(t,e,r),t;if(t instanceof Uint8Array){if(!e.startsWith("HS"))throw new TypeError(A(t,...b));return f.subtle.importKey("raw",t,{hash:`SHA-${e.slice(-3)}`,name:"HMAC"},!1,[r])}throw new TypeError(A(t,...b,"Uint8Array","JSON Web Key"))}var zr=async(e,t,r,n)=>{let o=await Ae(e,t,"verify");Q(e,o);let a=be(e,o.algorithm);try{return await f.subtle.verify(a,o,r,n)}catch{return !1}},er=zr;async function Ke(e,t,r){if(!y(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&&!y(e.header))throw new m("JWS Unprotected Header incorrect type");let n={};if(e.protected)try{let P=g(e.protected);n=JSON.parse(x.decode(P));}catch{throw new m("JWS Protected Header is invalid")}if(!R(n,e.header))throw new m("JWS Protected and JWS Unprotected Header Parameter names must be disjoint");let o={...n,...e.header},a=D(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&&ge("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,Ee(s,t,"verify"),L(t)&&(t=await $(t,s))):Ee(s,t,"verify");let h=W(w.encode(e.protected??""),w.encode("."),typeof e.payload=="string"?w.encode(e.payload):e.payload),l;try{l=g(e.signature);}catch{throw new m("Failed to base64url decode the signature")}if(!await er(s,t,l,h))throw new B;let J;if(i)try{J=g(e.payload);}catch{throw new m("Failed to base64url decode the payload")}else typeof e.payload=="string"?J=w.encode(e.payload):J=e.payload;let S={payload:J};return e.protected!==void 0&&(S.protectedHeader=n),e.header!==void 0&&(S.unprotectedHeader=e.header),p?{...S,key:t}:S}async function it(e,t,r){if(e instanceof Uint8Array&&(e=x.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 Ke({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 Xr(e,t,r){if(!y(e))throw new m("General JWS must be an object");if(!Array.isArray(e.signatures)||!e.signatures.every(y))throw new m("JWS Signatures missing or incorrect type");for(let n of e.signatures)try{return await Ke({header:n.header,payload:e.payload,protected:n.protected,signature:n.signature},t,r)}catch{}throw new B}var M=e=>Math.floor(e.getTime()/1e3);var Yr=/^(\+|\-)? ?(\d+|\d+\.\d+) ?(seconds?|secs?|s|minutes?|mins?|m|hours?|hrs?|h|days?|d|weeks?|w|years?|yrs?|y)(?: (ago|from now))?$/i,ee=e=>{let t=Yr.exec(e);if(!t||t[4]&&t[1])throw new TypeError("Invalid time period format");let r=parseFloat(t[2]),n=t[3].toLowerCase(),o;switch(n){case"sec":case"secs":case"second":case"seconds":case"s":o=Math.round(r);break;case"minute":case"minutes":case"min":case"mins":case"m":o=Math.round(r*60);break;case"hour":case"hours":case"hr":case"hrs":case"h":o=Math.round(r*3600);break;case"day":case"days":case"d":o=Math.round(r*86400);break;case"week":case"weeks":case"w":o=Math.round(r*604800);break;default:o=Math.round(r*31557600);break}return t[1]==="-"||t[4]==="ago"?-o:o};var tr=e=>e.toLowerCase().replace(/^application\//,""),qr=(e,t)=>typeof e=="string"?t.includes(e):Array.isArray(e)?t.some(Set.prototype.has.bind(new Set(e))):!1,le=(e,t,r={})=>{let n;try{n=JSON.parse(x.decode(t));}catch{}if(!y(n))throw new _("JWT Claims Set must be a top-level JSON object");let{typ:o}=r;if(o&&(typeof e.typ!="string"||tr(e.typ)!==tr(o)))throw new C('unexpected "typ" JWT header value',n,"typ","check_failed");let{requiredClaims:a=[],issuer:i,subject:s,audience:d,maxTokenAge:p}=r,h=[...a];p!==void 0&&h.push("iat"),d!==void 0&&h.push("aud"),s!==void 0&&h.push("sub"),i!==void 0&&h.push("iss");for(let S of new Set(h.reverse()))if(!(S in n))throw new C(`missing required "${S}" claim`,n,S,"missing");if(i&&!(Array.isArray(i)?i:[i]).includes(n.iss))throw new C('unexpected "iss" claim value',n,"iss","check_failed");if(s&&n.sub!==s)throw new C('unexpected "sub" claim value',n,"sub","check_failed");if(d&&!qr(n.aud,typeof d=="string"?[d]:d))throw new C('unexpected "aud" claim value',n,"aud","check_failed");let l;switch(typeof r.clockTolerance){case"string":l=ee(r.clockTolerance);break;case"number":l=r.clockTolerance;break;case"undefined":l=0;break;default:throw new TypeError("Invalid clockTolerance option type")}let{currentDate:T}=r,J=M(T||new Date);if((n.iat!==void 0||p)&&typeof n.iat!="number")throw new C('"iat" claim must be a number',n,"iat","invalid");if(n.nbf!==void 0){if(typeof n.nbf!="number")throw new C('"nbf" claim must be a number',n,"nbf","invalid");if(n.nbf>J+l)throw new C('"nbf" claim timestamp check failed',n,"nbf","check_failed")}if(n.exp!==void 0){if(typeof n.exp!="number")throw new C('"exp" claim must be a number',n,"exp","invalid");if(n.exp<=J-l)throw new q('"exp" claim timestamp check failed',n,"exp","check_failed")}if(p){let S=J-n.iat,P=typeof p=="number"?p:ee(p);if(S-l>P)throw new q('"iat" claim timestamp check failed (too far in the past)',n,"iat","check_failed");if(S<0-l)throw new C('"iat" claim timestamp check failed (it should be in the past)',n,"iat","check_failed")}return n};async function Zr(e,t,r){let n=await it(e,t,r);if(n.protectedHeader.crit?.includes("b64")&&n.protectedHeader.b64===!1)throw new _("JWTs MUST NOT use unencoded payload");let a={payload:le(n.protectedHeader,n.payload,r),protectedHeader:n.protectedHeader};return typeof t=="function"?{...a,key:n.key}:a}async function Qr(e,t,r){let n=await rt(e,t,r),o=le(n.protectedHeader,n.plaintext,r),{protectedHeader:a}=n;if(a.iss!==void 0&&a.iss!==o.iss)throw new C('replicated "iss" claim header parameter mismatch',o,"iss","mismatch");if(a.sub!==void 0&&a.sub!==o.sub)throw new C('replicated "sub" claim header parameter mismatch',o,"sub","mismatch");if(a.aud!==void 0&&JSON.stringify(a.aud)!==JSON.stringify(o.aud))throw new C('replicated "aud" claim header parameter mismatch',o,"aud","mismatch");let i={payload:o,protectedHeader:a};return typeof t=="function"?{...i,key:n.key}:i}var xe=class{constructor(t){this._flattened=new z(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 Ae(e,t,"sign");Q(e,n);let o=await f.subtle.sign(be(e,n.algorithm),n,r);return new Uint8Array(o)},rr=jr;var te=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(!R(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=D(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');Ee(i,t,"sign");let s=this._payload;a&&(s=w.encode(E(s)));let d;this._protectedHeader?d=w.encode(E(JSON.stringify(this._protectedHeader))):d=w.encode("");let p=W(d,w.encode("."),s),h=await rr(i,t,p),l={signature:E(h),payload:""};return a&&(l.payload=x.decode(s)),this._unprotectedHeader&&(l.header=this._unprotectedHeader),this._protectedHeader&&(l.protected=x.decode(d)),l}};var _e=class{constructor(t){this._flattened=new te(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 st=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}},ct=class{constructor(t){this._signatures=[],this._payload=t;}addSignature(t,r){let n=new st(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"u"?this._payload={...this._payload,iat:M(new Date)}:t instanceof Date?this._payload={...this._payload,iat:re("setIssuedAt",M(t))}:typeof t=="string"?this._payload={...this._payload,iat:re("setIssuedAt",M(new Date)+ee(t))}:this._payload={...this._payload,iat:re("setIssuedAt",t)},this}};var dt=class extends X{setProtectedHeader(t){return this._protectedHeader=t,this}async sign(t,r){let n=new _e(w.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 _("JWTs MUST NOT use unencoded payload");return n.sign(t,r)}};var pt=class extends X{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 xe(w.encode(JSON.stringify(this._payload)));return this._replicateIssuerAsHeader&&(this._protectedHeader={...this._protectedHeader,iss:this._payload.iss}),this._replicateSubjectAsHeader&&(this._protectedHeader={...this._protectedHeader,sub:this._payload.sub}),this._replicateAudienceAsHeader&&(this._protectedHeader={...this._protectedHeader,aud:this._payload.aud}),n.setProtectedHeader(this._protectedHeader),this._iv&&n.setInitializationVector(this._iv),this._cek&&n.setContentEncryptionKey(this._cek),this._keyManagementParameters&&n.setKeyManagementParameters(this._keyManagementParameters),n.encrypt(t,r)}};var Y=(e,t)=>{if(typeof e!="string"||!e)throw new ae(`${t} missing or invalid`)};async function nr(e,t){if(!y(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":Y(e.crv,'"crv" (Curve) Parameter'),Y(e.x,'"x" (X Coordinate) Parameter'),Y(e.y,'"y" (Y Coordinate) Parameter'),r={crv:e.crv,kty:e.kty,x:e.x,y:e.y};break;case"OKP":Y(e.crv,'"crv" (Subtype of Key Pair) Parameter'),Y(e.x,'"x" (Public Key) Parameter'),r={crv:e.crv,kty:e.kty,x:e.x};break;case"RSA":Y(e.e,'"e" (Exponent) Parameter'),Y(e.n,'"n" (Modulus) Parameter'),r={e:e.e,kty:e.kty,n:e.n};break;case"oct":Y(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=w.encode(JSON.stringify(r));return E(await We(t,n))}async function en(e,t){t??(t="sha256");let r=await nr(e,t);return `urn:ietf:params:oauth:jwk-thumbprint:sha-${t.slice(-3)}:${r}`}async function tn(e,t){let r={...e,...t?.header};if(!y(r.jwk))throw new m('"jwk" (JSON Web Key) Header Parameter must be a JSON object');let n=await $({...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 rn(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 u('Unsupported "alg" value for a JSON Web Key Set')}}function nn(e){return e&&typeof e=="object"&&Array.isArray(e.keys)&&e.keys.every(on)}function on(e){return y(e)}function ar(e){return typeof structuredClone=="function"?structuredClone(e):JSON.parse(JSON.stringify(e))}var ft=class{constructor(t){if(this._cached=new WeakMap,!nn(t))throw new Z("JSON Web Key Set malformed");this._jwks=ar(t);}async getKey(t,r){let{alg:n,kid:o}={...t,...r?.header},a=rn(n),i=this._jwks.keys.filter(p=>{let h=a===p.kty;if(h&&typeof o=="string"&&(h=o===p.kid),h&&typeof p.alg=="string"&&(h=n===p.alg),h&&typeof p.use=="string"&&(h=p.use==="sig"),h&&Array.isArray(p.key_ops)&&(h=p.key_ops.includes("verify")),h&&n==="EdDSA"&&(h=p.crv==="Ed25519"||p.crv==="Ed448"),h)switch(n){case"ES256":h=p.crv==="P-256";break;case"ES256K":h=p.crv==="secp256k1";break;case"ES384":h=p.crv==="P-384";break;case"ES512":h=p.crv==="P-521";break}return h}),{0:s,length:d}=i;if(d===0)throw new k;if(d!==1){let p=new ie,{_cached:h}=this;throw p[Symbol.asyncIterator]=async function*(){for(let l of i)try{yield await or(h,l,n);}catch{}},p}return or(this._cached,s,n)}};async function or(e,t,r){let n=e.get(t)||e.set(t,{}).get(t);if(n[r]===void 0){let o=await $({...t,ext:!0},r);if(o instanceof Uint8Array||o.type!=="public")throw new Z("JSON Web Key Set members must be public keys");n[r]=o;}return n[r]}function Ve(e){let t=new ft(e),r=async(n,o)=>t.getKey(n,o);return Object.defineProperties(r,{jwks:{value:()=>ar(t._jwks),enumerable:!0,configurable:!1,writable:!1}}),r}var an=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 se: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")}},ir=an;function sn(){return typeof WebSocketPair<"u"||typeof navigator<"u"&&navigator.userAgent==="Cloudflare-Workers"||typeof EdgeRuntime<"u"&&EdgeRuntime==="vercel"}var ut;(typeof navigator>"u"||!navigator.userAgent?.startsWith?.("Mozilla/5.0 "))&&(ut="jose/v5.9.6");var He=Symbol();function cn(e,t){return !(typeof e!="object"||e===null||!("uat"in e)||typeof e.uat!="number"||Date.now()-e.uat>=t||!("jwks"in e)||!y(e.jwks)||!Array.isArray(e.jwks.keys)||!Array.prototype.every.call(e.jwks.keys,y))}var ht=class{constructor(t,r){if(!(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,r?.[He]!==void 0&&(this._cache=r?.[He],cn(r?.[He],this._cacheMaxAge)&&(this._jwksTimestamp=this._cache.uat,this._local=Ve(this._cache.jwks)));}coolingDown(){return typeof this._jwksTimestamp=="number"?Date.now(){this._local=Ve(r),this._cache&&(this._cache.uat=Date.now(),this._cache.jwks=r),this._jwksTimestamp=Date.now(),this._pendingFetch=void 0;}).catch(r=>{throw this._pendingFetch=void 0,r})),await this._pendingFetch;}};function dn(e,t){let r=new ht(e,t),n=async(o,a)=>r.getKey(o,a);return Object.defineProperties(n,{coolingDown:{get:()=>r.coolingDown(),enumerable:!0,configurable:!1},fresh:{get:()=>r.fresh(),enumerable:!0,configurable:!1},reload:{value:()=>r.reload(),enumerable:!0,configurable:!1,writable:!1},reloading:{get:()=>!!r._pendingFetch,enumerable:!0,configurable:!1},jwks:{value:()=>r._local?.jwks(),enumerable:!0,configurable:!1,writable:!1}}),n}var pn=He;var lt=class extends X{encode(){let t=E(JSON.stringify({alg:"none"})),r=E(JSON.stringify(this._payload));return `${t}.${r}.`}static decode(t,r){if(typeof t!="string")throw new _("Unsecured JWT must be a string");let{0:n,1:o,2:a,length:i}=t.split(".");if(i!==3||a!=="")throw new _("Invalid Unsecured JWT");let s;try{if(s=JSON.parse(x.decode(g(n))),s.alg!=="none")throw new Error}catch{throw new _("Invalid Unsecured JWT")}return {payload:le(s,g(o),r),header:s}}};var sr={};yt(sr,{decode:()=>Ce,encode:()=>fn});var fn=E,Ce=g;function un(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(x.decode(Ce(t)));if(!y(r))throw new Error;return r}catch{throw new TypeError("Invalid Token or Protected Header formatting")}}function hn(e){if(typeof e!="string")throw new _("JWTs must use Compact JWS serialization, JWT must be a string");let{1:t,length:r}=e.split(".");if(r===5)throw new _("Only JWTs using Compact JWS serialization can be decoded");if(r!==3)throw new _("Invalid JWT");if(!t)throw new _("JWTs must contain a payload");let n;try{n=Ce(t);}catch{throw new _("Failed to base64url decode the payload")}let o;try{o=JSON.parse(x.decode(n));}catch{throw new _("Failed to parse the decoded payload as JSON")}if(!y(o))throw new _("Invalid JWT Claims Set");return o}async function cr(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),G(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 u('Invalid or unsupported JWK "alg" (Algorithm) Parameter value')}return f.subtle.generateKey(n,t?.extractable??!1,o)}function mt(e){let t=e?.modulusLength??2048;if(typeof t!="number"||t<2048)throw new u("Invalid or unsupported modulusLength option provided, 2048 bits or larger keys must be used");return t}async function dr(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:mt(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:mt(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:mt(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 u("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 o=t?.crv??"P-256";switch(o){case"P-256":case"P-384":case"P-521":{r={name:"ECDH",namedCurve:o};break}case"X25519":case"X448":r={name:o};break;default:throw new u("Invalid or unsupported crv option provided, supported values are P-256, P-384, P-521, X25519, and X448")}break}default:throw new u('Invalid or unsupported JWK "alg" (Algorithm) Parameter value')}return f.subtle.generateKey(r,t?.extractable??!1,n)}async function ln(e,t){return dr(e,t)}async function mn(e,t){return cr(e,t)}var pr="WebCryptoAPI";var yn=pr; exports.CompactEncrypt=xe;exports.CompactSign=_e;exports.EmbeddedJWK=tn;exports.EncryptJWT=pt;exports.FlattenedEncrypt=z;exports.FlattenedSign=te;exports.GeneralEncrypt=at;exports.GeneralSign=ct;exports.SignJWT=dt;exports.UnsecuredJWT=lt;exports.base64url=sr;exports.calculateJwkThumbprint=nr;exports.calculateJwkThumbprintUri=en;exports.compactDecrypt=rt;exports.compactVerify=it;exports.createLocalJWKSet=Ve;exports.createRemoteJWKSet=dn;exports.cryptoRuntime=yn;exports.decodeJwt=hn;exports.decodeProtectedHeader=un;exports.errors=St;exports.experimental_jwksCache=pn;exports.exportJWK=nt;exports.exportPKCS8=Fr;exports.exportSPKI=Gr;exports.flattenedDecrypt=Se;exports.flattenedVerify=Ke;exports.generalDecrypt=kr;exports.generalVerify=Xr;exports.generateKeyPair=ln;exports.generateSecret=mn;exports.importJWK=$;exports.importPKCS8=Ir;exports.importSPKI=Jr;exports.importX509=Tr;exports.jwksCache=He;exports.jwtDecrypt=Qr;exports.jwtVerify=Zr;})); \ No newline at end of file diff --git a/dist/browser/jwks/remote.js b/dist/browser/jwks/remote.js index ce2a9e8539..6e0e9556ca 100644 --- a/dist/browser/jwks/remote.js +++ b/dist/browser/jwks/remote.js @@ -10,7 +10,7 @@ function isCloudflareWorkers() { let USER_AGENT; if (typeof navigator === 'undefined' || !navigator.userAgent?.startsWith?.('Mozilla/5.0 ')) { const NAME = 'jose'; - const VERSION = 'v5.9.5'; + const VERSION = 'v5.9.6'; USER_AGENT = `${NAME}/${VERSION}`; } export const jwksCache = Symbol(); diff --git a/dist/deno/README.md b/dist/deno/README.md index f96c29fd9f..bdd4dc6b56 100644 --- a/dist/deno/README.md +++ b/dist/deno/README.md @@ -20,75 +20,75 @@ Support from the community to continue maintaining and improving this module is **`example`** Deno import ```js -import * as jose from 'https://deno.land/x/jose@v5.9.5/index.ts' +import * as jose from 'https://deno.land/x/jose@v5.9.6/index.ts' ``` ### JSON Web Tokens (JWT) The `jose` module supports JSON Web Tokens (JWT) and provides functionality for signing and verifying tokens, as well as their JWT Claims Set validation. -- [JWT Claims Set Validation & Signature Verification](https://github.com/panva/jose/blob/v5.9.5/docs/jwt/verify/functions/jwtVerify.md) using the `jwtVerify` function - - [Using a remote JSON Web Key Set (JWKS)](https://github.com/panva/jose/blob/v5.9.5/docs/jwks/remote/functions/createRemoteJWKSet.md) - - [Using a local JSON Web Key Set (JWKS)](https://github.com/panva/jose/blob/v5.9.5/docs/jwks/local/functions/createLocalJWKSet.md) -- [Signing](https://github.com/panva/jose/blob/v5.9.5/docs/jwt/sign/classes/SignJWT.md) using the `SignJWT` class +- [JWT Claims Set Validation & Signature Verification](https://github.com/panva/jose/blob/v5.9.6/docs/jwt/verify/functions/jwtVerify.md) using the `jwtVerify` function + - [Using a remote JSON Web Key Set (JWKS)](https://github.com/panva/jose/blob/v5.9.6/docs/jwks/remote/functions/createRemoteJWKSet.md) + - [Using a local JSON Web Key Set (JWKS)](https://github.com/panva/jose/blob/v5.9.6/docs/jwks/local/functions/createLocalJWKSet.md) +- [Signing](https://github.com/panva/jose/blob/v5.9.6/docs/jwt/sign/classes/SignJWT.md) using the `SignJWT` class - Utility functions - - [Decoding Token's Protected Header](https://github.com/panva/jose/blob/v5.9.5/docs/util/decode_protected_header/functions/decodeProtectedHeader.md) - - [Decoding JWT Claims Set](https://github.com/panva/jose/blob/v5.9.5/docs/util/decode_jwt/functions/decodeJwt.md) prior to its validation + - [Decoding Token's Protected Header](https://github.com/panva/jose/blob/v5.9.6/docs/util/decode_protected_header/functions/decodeProtectedHeader.md) + - [Decoding JWT Claims Set](https://github.com/panva/jose/blob/v5.9.6/docs/util/decode_jwt/functions/decodeJwt.md) prior to its validation ### Encrypted JSON Web Tokens The `jose` module supports encrypted JSON Web Tokens and provides functionality for encrypting and decrypting tokens, as well as their JWT Claims Set validation. -- [Decryption & JWT Claims Set Validation](https://github.com/panva/jose/blob/v5.9.5/docs/jwt/decrypt/functions/jwtDecrypt.md) using the `jwtDecrypt` function -- [Encryption](https://github.com/panva/jose/blob/v5.9.5/docs/jwt/encrypt/classes/EncryptJWT.md) using the `EncryptJWT` class +- [Decryption & JWT Claims Set Validation](https://github.com/panva/jose/blob/v5.9.6/docs/jwt/decrypt/functions/jwtDecrypt.md) using the `jwtDecrypt` function +- [Encryption](https://github.com/panva/jose/blob/v5.9.6/docs/jwt/encrypt/classes/EncryptJWT.md) using the `EncryptJWT` class - Utility functions - - [Decoding Token's Protected Header](https://github.com/panva/jose/blob/v5.9.5/docs/util/decode_protected_header/functions/decodeProtectedHeader.md) + - [Decoding Token's Protected Header](https://github.com/panva/jose/blob/v5.9.6/docs/util/decode_protected_header/functions/decodeProtectedHeader.md) ### Key Utilities The `jose` module supports importing, exporting, and generating keys and secrets in various formats, including PEM formats like SPKI, X.509 certificate, and PKCS #8, as well as JSON Web Key (JWK). - Key Import Functions - - [JWK Import](https://github.com/panva/jose/blob/v5.9.5/docs/key/import/functions/importJWK.md) - - [Public Key Import (SPKI)](https://github.com/panva/jose/blob/v5.9.5/docs/key/import/functions/importSPKI.md) - - [Public Key Import (X.509 Certificate)](https://github.com/panva/jose/blob/v5.9.5/docs/key/import/functions/importX509.md) - - [Private Key Import (PKCS #8)](https://github.com/panva/jose/blob/v5.9.5/docs/key/import/functions/importPKCS8.md) + - [JWK Import](https://github.com/panva/jose/blob/v5.9.6/docs/key/import/functions/importJWK.md) + - [Public Key Import (SPKI)](https://github.com/panva/jose/blob/v5.9.6/docs/key/import/functions/importSPKI.md) + - [Public Key Import (X.509 Certificate)](https://github.com/panva/jose/blob/v5.9.6/docs/key/import/functions/importX509.md) + - [Private Key Import (PKCS #8)](https://github.com/panva/jose/blob/v5.9.6/docs/key/import/functions/importPKCS8.md) - Key and Secret Generation Functions - - [Asymmetric Key Pair Generation](https://github.com/panva/jose/blob/v5.9.5/docs/key/generate_key_pair/functions/generateKeyPair.md) - - [Symmetric Secret Generation](https://github.com/panva/jose/blob/v5.9.5/docs/key/generate_secret/functions/generateSecret.md) + - [Asymmetric Key Pair Generation](https://github.com/panva/jose/blob/v5.9.6/docs/key/generate_key_pair/functions/generateKeyPair.md) + - [Symmetric Secret Generation](https://github.com/panva/jose/blob/v5.9.6/docs/key/generate_secret/functions/generateSecret.md) - Key Export Functions - - [JWK Export](https://github.com/panva/jose/blob/v5.9.5/docs/key/export/functions/exportJWK.md) - - [Private Key Export](https://github.com/panva/jose/blob/v5.9.5/docs/dkey/export/functions/exportPKCS8.md) - - [Public Key Export](https://github.com/panva/jose/blob/v5.9.5/docs/dkey/export/functions/exportSPKI.md) + - [JWK Export](https://github.com/panva/jose/blob/v5.9.6/docs/key/export/functions/exportJWK.md) + - [Private Key Export](https://github.com/panva/jose/blob/v5.9.6/docs/dkey/export/functions/exportPKCS8.md) + - [Public Key Export](https://github.com/panva/jose/blob/v5.9.6/docs/dkey/export/functions/exportSPKI.md) ### JSON Web Signature (JWS) The `jose` module supports signing and verification of JWS messages with arbitrary payloads in Compact, Flattened JSON, and General JSON serialization syntaxes. -- Signing - [Compact](https://github.com/panva/jose/blob/v5.9.5/docs/jws/compact/sign/classes/CompactSign.md), [Flattened JSON](https://github.com/panva/jose/blob/v5.9.5/docs/jws/flattened/sign/classes/FlattenedSign.md), [General JSON](https://github.com/panva/jose/blob/v5.9.5/docs/jws/general/sign/classes/GeneralSign.md) -- Verification - [Compact](https://github.com/panva/jose/blob/v5.9.5/docs/jws/compact/verify/functions/compactVerify.md), [Flattened JSON](https://github.com/panva/jose/blob/v5.9.5/docs/jws/flattened/verify/functions/flattenedVerify.md), [General JSON](https://github.com/panva/jose/blob/v5.9.5/docs/jws/general/verify/functions/generalVerify.md) - - [Using a remote JSON Web Key Set (JWKS)](https://github.com/panva/jose/blob/v5.9.5/docs/jwks/remote/functions/createRemoteJWKSet.md) - - [Using a local JSON Web Key Set (JWKS)](https://github.com/panva/jose/blob/v5.9.5/docs/jwks/local/functions/createLocalJWKSet.md) +- Signing - [Compact](https://github.com/panva/jose/blob/v5.9.6/docs/jws/compact/sign/classes/CompactSign.md), [Flattened JSON](https://github.com/panva/jose/blob/v5.9.6/docs/jws/flattened/sign/classes/FlattenedSign.md), [General JSON](https://github.com/panva/jose/blob/v5.9.6/docs/jws/general/sign/classes/GeneralSign.md) +- Verification - [Compact](https://github.com/panva/jose/blob/v5.9.6/docs/jws/compact/verify/functions/compactVerify.md), [Flattened JSON](https://github.com/panva/jose/blob/v5.9.6/docs/jws/flattened/verify/functions/flattenedVerify.md), [General JSON](https://github.com/panva/jose/blob/v5.9.6/docs/jws/general/verify/functions/generalVerify.md) + - [Using a remote JSON Web Key Set (JWKS)](https://github.com/panva/jose/blob/v5.9.6/docs/jwks/remote/functions/createRemoteJWKSet.md) + - [Using a local JSON Web Key Set (JWKS)](https://github.com/panva/jose/blob/v5.9.6/docs/jwks/local/functions/createLocalJWKSet.md) - Utility functions - - [Decoding Token's Protected Header](https://github.com/panva/jose/blob/v5.9.5/docs/util/decode_protected_header/functions/decodeProtectedHeader.md) + - [Decoding Token's Protected Header](https://github.com/panva/jose/blob/v5.9.6/docs/util/decode_protected_header/functions/decodeProtectedHeader.md) ### JSON Web Encryption (JWE) The `jose` module supports encryption and decryption of JWE messages with arbitrary plaintext in Compact, Flattened JSON, and General JSON serialization syntaxes. -- Encryption - [Compact](https://github.com/panva/jose/blob/v5.9.5/docs/jwe/compact/encrypt/classes/CompactEncrypt.md), [Flattened JSON](https://github.com/panva/jose/blob/v5.9.5/docs/jwe/flattened/encrypt/classes/FlattenedEncrypt.md), [General JSON](https://github.com/panva/jose/blob/v5.9.5/docs/jwe/general/encrypt/classes/GeneralEncrypt.md) -- Decryption - [Compact](https://github.com/panva/jose/blob/v5.9.5/docs/jwe/compact/decrypt/functions/compactDecrypt.md), [Flattened JSON](https://github.com/panva/jose/blob/v5.9.5/docs/jwe/flattened/decrypt/functions/flattenedDecrypt.md), [General JSON](https://github.com/panva/jose/blob/v5.9.5/docs/jwe/general/decrypt/functions/generalDecrypt.md) +- Encryption - [Compact](https://github.com/panva/jose/blob/v5.9.6/docs/jwe/compact/encrypt/classes/CompactEncrypt.md), [Flattened JSON](https://github.com/panva/jose/blob/v5.9.6/docs/jwe/flattened/encrypt/classes/FlattenedEncrypt.md), [General JSON](https://github.com/panva/jose/blob/v5.9.6/docs/jwe/general/encrypt/classes/GeneralEncrypt.md) +- Decryption - [Compact](https://github.com/panva/jose/blob/v5.9.6/docs/jwe/compact/decrypt/functions/compactDecrypt.md), [Flattened JSON](https://github.com/panva/jose/blob/v5.9.6/docs/jwe/flattened/decrypt/functions/flattenedDecrypt.md), [General JSON](https://github.com/panva/jose/blob/v5.9.6/docs/jwe/general/decrypt/functions/generalDecrypt.md) - Utility functions - - [Decoding Token's Protected Header](https://github.com/panva/jose/blob/v5.9.5/docs/util/decode_protected_header/functions/decodeProtectedHeader.md) + - [Decoding Token's Protected Header](https://github.com/panva/jose/blob/v5.9.6/docs/util/decode_protected_header/functions/decodeProtectedHeader.md) ### Other The following are additional features and utilities provided by the `jose` module: -- [Calculating JWK Thumbprint](https://github.com/panva/jose/blob/v5.9.5/docs/jwk/thumbprint/functions/calculateJwkThumbprint.md) -- [Calculating JWK Thumbprint URI](https://github.com/panva/jose/blob/v5.9.5/docs/jwk/thumbprint/functions/calculateJwkThumbprintUri.md) -- [Verification using a JWK Embedded in a JWS Header](https://github.com/panva/jose/blob/v5.9.5/docs/jwk/embedded/functions/EmbeddedJWK.md) -- [Unsecured JWT](https://github.com/panva/jose/blob/v5.9.5/docs/jwt/unsecured/classes/UnsecuredJWT.md) -- [JOSE Errors](https://github.com/panva/jose/blob/v5.9.5/docs/util/errors/README.md) +- [Calculating JWK Thumbprint](https://github.com/panva/jose/blob/v5.9.6/docs/jwk/thumbprint/functions/calculateJwkThumbprint.md) +- [Calculating JWK Thumbprint URI](https://github.com/panva/jose/blob/v5.9.6/docs/jwk/thumbprint/functions/calculateJwkThumbprintUri.md) +- [Verification using a JWK Embedded in a JWS Header](https://github.com/panva/jose/blob/v5.9.6/docs/jwk/embedded/functions/EmbeddedJWK.md) +- [Unsecured JWT](https://github.com/panva/jose/blob/v5.9.6/docs/jwt/unsecured/classes/UnsecuredJWT.md) +- [JOSE Errors](https://github.com/panva/jose/blob/v5.9.6/docs/util/errors/README.md) [sponsor-auth0]: https://auth0.com/signup?utm_source=external_sites&utm_medium=panva&utm_campaign=devn_signup diff --git a/dist/deno/jwks/remote.ts b/dist/deno/jwks/remote.ts index 9c47c9e1ce..c2561b526c 100644 --- a/dist/deno/jwks/remote.ts +++ b/dist/deno/jwks/remote.ts @@ -24,7 +24,7 @@ let USER_AGENT: string // @ts-ignore if (typeof navigator === 'undefined' || !navigator.userAgent?.startsWith?.('Mozilla/5.0 ')) { const NAME = 'jose' - const VERSION = 'v5.9.5' + const VERSION = 'v5.9.6' USER_AGENT = `${NAME}/${VERSION}` } diff --git a/dist/node/cjs/jwks/remote.js b/dist/node/cjs/jwks/remote.js index ced664bec7..c1f6cf5726 100644 --- a/dist/node/cjs/jwks/remote.js +++ b/dist/node/cjs/jwks/remote.js @@ -14,7 +14,7 @@ function isCloudflareWorkers() { let USER_AGENT; if (typeof navigator === 'undefined' || !navigator.userAgent?.startsWith?.('Mozilla/5.0 ')) { const NAME = 'jose'; - const VERSION = 'v5.9.5'; + const VERSION = 'v5.9.6'; USER_AGENT = `${NAME}/${VERSION}`; } exports.jwksCache = Symbol(); diff --git a/dist/node/esm/jwks/remote.js b/dist/node/esm/jwks/remote.js index 0aed5fc510..ae64e5bca5 100644 --- a/dist/node/esm/jwks/remote.js +++ b/dist/node/esm/jwks/remote.js @@ -10,7 +10,7 @@ function isCloudflareWorkers() { let USER_AGENT; if (typeof navigator === 'undefined' || !navigator.userAgent?.startsWith?.('Mozilla/5.0 ')) { const NAME = 'jose'; - const VERSION = 'v5.9.5'; + const VERSION = 'v5.9.6'; USER_AGENT = `${NAME}/${VERSION}`; } export const jwksCache = Symbol(); diff --git a/package-lock.json b/package-lock.json index 8171720e33..69996e9ae8 100644 --- a/package-lock.json +++ b/package-lock.json @@ -1,12 +1,12 @@ { "name": "jose", - "version": "5.9.5", + "version": "5.9.6", "lockfileVersion": 3, "requires": true, "packages": { "": { "name": "jose", - "version": "5.9.5", + "version": "5.9.6", "license": "MIT", "devDependencies": { "@types/node": "^20.16.13", diff --git a/package.json b/package.json index 4333a3393c..d7556ffe69 100644 --- a/package.json +++ b/package.json @@ -1,6 +1,6 @@ { "name": "jose", - "version": "5.9.5", + "version": "5.9.6", "description": "JWA, JWS, JWE, JWT, JWK, JWKS for Node.js, Browser, Cloudflare Workers, Deno, Bun, and other Web-interoperable runtimes", "keywords": [ "browser", diff --git a/src/jwks/remote.ts b/src/jwks/remote.ts index e7cad31d90..c2c66fa6b3 100644 --- a/src/jwks/remote.ts +++ b/src/jwks/remote.ts @@ -24,7 +24,7 @@ let USER_AGENT: string // @ts-ignore if (typeof navigator === 'undefined' || !navigator.userAgent?.startsWith?.('Mozilla/5.0 ')) { const NAME = 'jose' - const VERSION = 'v5.9.5' + const VERSION = 'v5.9.6' USER_AGENT = `${NAME}/${VERSION}` }