fix: the ep() function reads x-forwarded-host and x-... in...#2581
fix: the ep() function reads x-forwarded-host and x-... in...#2581orbisai0security wants to merge 1 commit into
Conversation
Automated security fix generated by OrbisAI Security
Greptile SummaryThis PR attempts to fix a host-header injection vulnerability in the
Confidence Score: 1/5Not safe to merge — the security vulnerability it claims to fix remains fully exploitable on any deployment that does not have BETTER_AUTH_URL configured. The patch adds a validation path that is only reached when specific environment variables are present. On deployments where none of the five BETTER_AUTH_URL-style env vars are set, the new code is never executed and x-forwarded-host is still trusted unconditionally — the same attack that generated the PR description still works. Additionally, the fix targets a compiled bundle artifact rather than the source, meaning any project rebuild silently reverts it. plugin/scripts/worker-service.cjs — the entire changed line needs attention; the fix is also missing from the source that generates this bundle
|
| Filename | Overview |
|---|---|
| plugin/scripts/worker-service.cjs | Adds an allowlist check for x-forwarded-host against the configured BETTER_AUTH_URL, but the check is skipped entirely when no base-URL env var is set, leaving the vulnerability intact for those deployments; also contains dead code (empty try-block) and a redundant inner if-guard. |
Flowchart
%%{init: {'theme': 'neutral'}}%%
flowchart TD
A["Request arrives with\nx-forwarded-host (s)\nx-forwarded-proto (o)"] --> B{"s && o && i &&\ny0(o,'proto') &&\ny0(s,'host')"}
B -- "No" --> Z["Fall through to\ndirect URL parsing"]
B -- "Yes (header values valid format)" --> C{"Bnt = BETTER_AUTH_URL\n|| ... env vars\n\nIs Bnt truthy?"}
C -- "No env var set\n(common case)" --> G["s unchanged\n(x-forwarded-host used as-is)"]
C -- "Yes" --> D["Parse URL(Bnt).host\n→ Hnt"]
D --> E["Dead code block:\nif(Hnt && s!==Hnt) {}"]
E --> F{"Parse URL(Bnt).host again\nif(!Hnt || s!==Hnt)\ns = null"}
F -- "Host mismatch\nor parse error" --> H["s = null"]
F -- "Hosts match" --> G
H --> I{"if(s)"}
G --> I
I -- "s is truthy" --> J["return Qd(o + '://' + s, e)\n✅ Protected if env var set\n❌ Unprotected if no env var"]
I -- "s is null" --> Z
style G fill:#ff9999
style E fill:#ffcc99
style J fill:#ffcc99
Prompt To Fix All With AI
Fix the following 3 code review issues. Work through them one at a time, proposing concise fixes.
---
### Issue 1 of 3
plugin/scripts/worker-service.cjs:787
**Incomplete fix — bypass when no base URL env var is configured**
The entire validation block is guarded by `if(Bnt)`, where `Bnt` is populated only when one of `BETTER_AUTH_URL`, `NEXT_PUBLIC_BETTER_AUTH_URL`, `PUBLIC_BETTER_AUTH_URL`, `NUXT_PUBLIC_BETTER_AUTH_URL`, or `NUXT_PUBLIC_AUTH_URL` is set. If none of these env vars are configured (a common deployment scenario), `Bnt` is falsy, the allowlist check is skipped entirely, and `s` (the value from `x-forwarded-host`) is passed unchanged to `Qd()`—exactly the same behavior as before this patch. The vulnerability described in the PR description is still fully exploitable on those deployments.
### Issue 2 of 3
plugin/scripts/worker-service.cjs:787
**Dead code in first try-block**
The first `try` block (`try{let Hnt=new URL(Bnt).host;if(Hnt&&s!==Hnt){}}catch{}`) has a completely empty `if` body and an empty `catch`. It computes `Hnt` and evaluates the comparison but does nothing regardless of the result. This appears to be an earlier draft of the fix that was accidentally left in. The effective logic is only in the second inner `if(Bnt)` block, which is itself redundant because it is already inside the outer `if(Bnt)` guard.
### Issue 3 of 3
plugin/scripts/worker-service.cjs:787
**Security fix applied to a compiled bundle, not the source**
`worker-service.cjs` is a minified, bundled artifact — not a hand-authored source file. The code containing the `ep()` / `x-forwarded-host` logic originates from the `better-auth` library (visible from symbol names like `BETTER_AUTH_URL`, `y0`, `Qd`). Patching the bundle directly means: (1) the fix will be silently overwritten the next time the project is rebuilt; (2) the upstream source still contains the vulnerability; and (3) reviewers cannot easily audit the change or reason about correctness. The fix should be applied in the original source (or as an upstream patch to `better-auth`) and the bundle regenerated.
Reviews (1): Last reviewed commit: "fix: V-003 security vulnerability" | Re-trigger Greptile
| @@ -784,7 +784,7 @@ return fn.apply(this, arguments) | |||
| </html> | |||
| `}function Ott(){return function(){this.error(404)}}function ktt(){return function(e){if(this.hasTrailingSlash()){this.error(404);return}var r=oH.original(this.req);r.path=null,r.pathname=Itt(r.pathname+"/");var n=_tt(Ttt.format(r)),i=Att("Redirecting","Redirecting to "+Ett(n));e.statusCode=301,e.setHeader("Content-Type","text/html; charset=UTF-8"),e.setHeader("Content-Length",Buffer.byteLength(i)),e.setHeader("Content-Security-Policy","default-src 'none'"),e.setHeader("X-Content-Type-Options","nosniff"),e.setHeader("Location",n),e.end(i)}}});var $ue=C((Hc,Wue)=>{"use strict";var AR=wce(),Rtt=require("node:events").EventEmitter,que=xce(),Fue=Cle(),zue=q4(),Bue=oue(),Hue=jue();Hc=Wue.exports=Ctt;function Ctt(){var t=function(e,r,n){t.handle(e,r,n)};return que(t,Rtt.prototype,!1),que(t,Fue,!1),t.request=Object.create(Bue,{app:{configurable:!0,enumerable:!0,writable:!0,value:t}}),t.response=Object.create(Hue,{app:{configurable:!0,enumerable:!0,writable:!0,value:t}}),t.init(),t}Hc.application=Fue;Hc.request=Bue;Hc.response=Hue;Hc.Route=zue.Route;Hc.Router=zue;Hc.json=AR.json;Hc.raw=AR.raw;Hc.static=Kue();Hc.text=AR.text;Hc.urlencoded=AR.urlencoded});var OR=C((WVt,Gue)=>{"use strict";Gue.exports=$ue()});var Zue=C((GVt,Jue)=>{"use strict";var Yue=Object.getOwnPropertySymbols,Ntt=Object.prototype.hasOwnProperty,Ptt=Object.prototype.propertyIsEnumerable;function Dtt(t){if(t==null)throw new TypeError("Object.assign cannot be called with null or undefined");return Object(t)}function Mtt(){try{if(!Object.assign)return!1;var t=new String("abc");if(t[5]="de",Object.getOwnPropertyNames(t)[0]==="5")return!1;for(var e={},r=0;r<10;r++)e["_"+String.fromCharCode(r)]=r;var n=Object.getOwnPropertyNames(e).map(function(s){return e[s]});if(n.join("")!=="0123456789")return!1;var i={};return"abcdefghijklmnopqrst".split("").forEach(function(s){i[s]=s}),Object.keys(Object.assign({},i)).join("")==="abcdefghijklmnopqrst"}catch{return!1}}Jue.exports=Mtt()?Object.assign:function(t,e){for(var r,n=Dtt(t),i,s=1;s<arguments.length;s++){r=Object(arguments[s]);for(var o in r)Ntt.call(r,o)&&(n[o]=r[o]);if(Yue){i=Yue(r);for(var a=0;a<i.length;a++)Ptt.call(r,i[a])&&(n[i[a]]=r[i[a]])}}return n}});var Que=C((VVt,Xue)=>{(function(){"use strict";var t=Zue(),e=nH(),r={origin:"*",methods:"GET,HEAD,PUT,PATCH,POST,DELETE",preflightContinue:!1,optionsSuccessStatus:204};function n(m){return typeof m=="string"||m instanceof String}function i(m,h){if(Array.isArray(h)){for(var y=0;y<h.length;++y)if(i(m,h[y]))return!0;return!1}else return n(h)?m===h:h instanceof RegExp?h.test(m):!!h}function s(m,h){var y=h.headers.origin,g=[],b;return!m.origin||m.origin==="*"?g.push([{key:"Access-Control-Allow-Origin",value:"*"}]):n(m.origin)?(g.push([{key:"Access-Control-Allow-Origin",value:m.origin}]),g.push([{key:"Vary",value:"Origin"}])):(b=i(y,m.origin),g.push([{key:"Access-Control-Allow-Origin",value:b?y:!1}]),g.push([{key:"Vary",value:"Origin"}])),g}function o(m){var h=m.methods;return h.join&&(h=m.methods.join(",")),{key:"Access-Control-Allow-Methods",value:h}}function a(m){return m.credentials===!0?{key:"Access-Control-Allow-Credentials",value:"true"}:null}function c(m,h){var y=m.allowedHeaders||m.headers,g=[];return y?y.join&&(y=y.join(",")):(y=h.headers["access-control-request-headers"],g.push([{key:"Vary",value:"Access-Control-Request-Headers"}])),y&&y.length&&g.push([{key:"Access-Control-Allow-Headers",value:y}]),g}function l(m){var h=m.exposedHeaders;if(h)h.join&&(h=h.join(","));else return null;return h&&h.length?{key:"Access-Control-Expose-Headers",value:h}:null}function u(m){var h=(typeof m.maxAge=="number"||m.maxAge)&&m.maxAge.toString();return h&&h.length?{key:"Access-Control-Max-Age",value:h}:null}function d(m,h){for(var y=0,g=m.length;y<g;y++){var b=m[y];b&&(Array.isArray(b)?d(b,h):b.key==="Vary"&&b.value?e(h,b.value):b.value&&h.setHeader(b.key,b.value))}}function p(m,h,y,g){var b=[],v=h.method&&h.method.toUpperCase&&h.method.toUpperCase();v==="OPTIONS"?(b.push(s(m,h)),b.push(a(m)),b.push(o(m)),b.push(c(m,h)),b.push(u(m)),b.push(l(m)),d(b,y),m.preflightContinue?g():(y.statusCode=m.optionsSuccessStatus,y.setHeader("Content-Length","0"),y.end())):(b.push(s(m,h)),b.push(a(m)),b.push(l(m)),d(b,y),g())}function f(m){var h=null;return typeof m=="function"?h=m:h=function(y,g){g(null,m)},function(g,b,v){h(g,function(_,w){if(_)v(_);else{var S=t({},r,w),x=null;S.origin&&typeof S.origin=="function"?x=S.origin:S.origin&&(x=function(O,N){N(null,S.origin)}),x?x(g.headers.origin,function(O,N){O||!N?v(O):(S.origin=N,p(S,g,b,v))}):v()}})}}Xue.exports=f})()});function rde(t,e,r,n){let i={error:t,message:e};return r&&(i.code=r),n&&(i.details=n),i}function ide(t,e){e.status(404).json(rde("NotFound",`Cannot ${t.method} ${t.path}`))}var Gs,nde,l0=I(()=>{"use strict";fe();Gs=class extends Error{constructor(r,n=500,i,s){super(r);this.statusCode=n;this.code=i;this.details=s;this.name="AppError"}statusCode;code;details};nde=(t,e,r,n)=>{let i=t instanceof Gs?t.statusCode:500;E.error("HTTP",`Error handling ${e.method} ${e.path}`,{statusCode:i,error:t.message,code:t instanceof Gs?t.code:void 0},t);let s=rde(t.name||"Error",t.message,t instanceof Gs?t.code:void 0,t instanceof Gs?t.details:void 0);r.status(i).json(s)}});function mH(t){return typeof t!="string"||t in{}}function hH(){return Object.create(null)}function pde(t){return typeof t=="string"&&!!t.trim()}function gH(t,e){var r=t.split(";").filter(pde),n=r.shift(),i=Ftt(n),s=i.name,o=i.value;if(e=e?Object.assign({},CR,e):CR,mH(s))return null;try{o=e.decodeValues?decodeURIComponent(o):o}catch(c){console.error("set-cookie-parser: failed to decode cookie value. Set options.decodeValues=false to disable decoding.",c)}var a=hH();return a.name=s,a.value=o,r.forEach(function(c){var l=c.split("="),u=l.shift().trimLeft().toLowerCase();if(!mH(u)){var d=l.join("=");if(u==="expires")a.expires=new Date(d);else if(u==="max-age"){var p=parseInt(d,10);Number.isNaN(p)||(a.maxAge=p)}else u==="secure"?a.secure=!0:u==="httponly"?a.httpOnly=!0:u==="samesite"?a.sameSite=d:u==="partitioned"?a.partitioned=!0:u&&(a[u]=d)}}),a}function Ftt(t){var e="",r="",n=t.split("=");return n.length>1?(e=n.shift(),r=n.join("=")):r=t,{name:e,value:r}}function Zb(t,e){if(e=e?Object.assign({},CR,e):CR,!t)return e.map?hH():[];if(t.headers)if(typeof t.headers.getSetCookie=="function")t=t.headers.getSetCookie();else if(t.headers["set-cookie"])t=t.headers["set-cookie"];else{var r=t.headers[Object.keys(t.headers).find(function(o){return o.toLowerCase()==="set-cookie"})];!r&&t.headers.cookie&&!e.silent&&console.warn("Warning: set-cookie-parser appears to have been called on a request object. It is designed to parse Set-Cookie headers from responses, not Cookie headers from requests. Set the option {silent: true} to suppress this warning."),t=r}var n=e.split,i=Array.isArray(t);if(n==="auto"&&(n=!i),i||(t=[t]),t=t.filter(pde),n&&(t=t.map(NR).flat()),e.map){var s=hH();return t.reduce(function(o,a){var c=gH(a,e);return c&&!mH(c.name)&&(o[c.name]=c),o},s)}else return t.map(function(o){return gH(o,e)}).filter(Boolean)}function NR(t){if(Array.isArray(t))return t;if(typeof t!="string")return[];var e=[],r=0,n,i,s,o,a;function c(){for(;r<t.length&&/\s/.test(t.charAt(r));)r+=1;return r<t.length}function l(){return i=t.charAt(r),i!=="="&&i!==";"&&i!==","}for(;r<t.length;){for(n=r,a=!1;c();)if(i=t.charAt(r),i===","){for(s=r,r+=1,c(),o=r;r<t.length&&l();)r+=1;r<t.length&&t.charAt(r)==="="?(a=!0,r=o,e.push(t.substring(n,s)),n=r):r=s+1}else r+=1;(!a||r>=t.length)&&e.push(t.substring(n,t.length))}return e}var CR,fde=I(()=>{CR={decodeValues:!0,map:!1,silent:!1,split:"auto"};Zb.parseSetCookie=Zb;Zb.parse=Zb;Zb.parseString=gH;Zb.splitCookiesString=NR});function Vtt(t,e){let r=t.headers;if(!r["content-type"])return null;let n=Number(r["content-length"]);if(t.httpVersionMajor===1&&isNaN(n)&&r["transfer-encoding"]==null||n===0)return null;let i=n;if(e){if(!i)i=e;else if(i>e)throw Error(`Received content-length of ${i}, but only accept up to ${e} bytes.`)}if(t.destroyed){let a=new ReadableStream;return a.cancel(),a}let s=0,o=!1;return new ReadableStream({start(a){t.on("error",c=>{o=!0,a.error(c)}),t.on("end",()=>{o||a.close()}),t.on("data",c=>{if(!o){if(s+=c.length,s>i){o=!0,a.error(new Error(`request body size exceeded ${n?"'content-length'":"BODY_SIZE_LIMIT"} of ${i}`));return}a.enqueue(c),(a.desiredSize===null||a.desiredSize<=0)&&t.pause()}})},pull(){t.resume()},cancel(a){o=!0,t.destroy(a)}})}function Ytt(t){let e=t.baseUrl,r=t.originalUrl;return!e||!r?e?e+t.url:t.url:e+t.url===r||r.split("?")[0].at(-1)==="/"?e+t.url:e}function gde({request:t,base:e,bodySizeLimit:r}){let n=t,i=Htt(t.headers),s,o=t.method;if(o!=="GET"&&o!=="HEAD"){if($tt(t))s=Vtt(t,r);else if(n.body!==void 0){let a=n.body,c=Gtt(a,i);s=new ReadableStream({start(l){l.enqueue(new TextEncoder().encode(c)),l.close()}})}}return new Request(e+Ytt(t),{duplex:"half",method:t.method,body:s,headers:t.headers})}async function yde(t,e){for(let[s,o]of e.headers)try{t.setHeader(s,s==="set-cookie"?NR(e.headers.get(s)):o)}catch(a){t.getHeaderNames().forEach(c=>t.removeHeader(c)),t.writeHead(500).end(String(a));return}if(t.statusCode=e.status,t.writeHead(e.status),!e.body){t.end();return}if(e.body.locked){t.end("Fatal error: Response body is locked. This can happen when the response was already read (for example through 'response.json()' or 'response.text()').");return}let r=e.body.getReader();if(t.destroyed){r.cancel();return}let n=s=>{t.off("close",n),t.off("error",n),r.cancel(s).catch(()=>{}),s&&t.destroy(s)};t.on("close",n),t.on("error",n),i();async function i(){try{for(;;){let{done:s,value:o}=await r.read();if(s)break;if(!t.write(o)){if(process.env.AWS_LAMBDA_FUNCTION_NAME||process.env.LAMBDA_TASK_ROOT)continue;t.once("drain",i);return}t.end()}}catch(s){n(s instanceof Error?s:new Error(String(s)))}}}var Btt,Htt,mde,hde,Wtt,$tt,Gtt,bde=I(()=>{fde();Btt=t=>Array.isArray(t)?t[0]:t,Htt=t=>{let e=Btt(t["content-type"]);return e?e.toLowerCase().startsWith("application/x-www-form-urlencoded"):!1},mde=t=>{if(typeof t!="object"||t===null)return!1;let e=Object.getPrototypeOf(t);return e===Object.prototype||e===null},hde=(t,e,r)=>{if(r!==void 0){if(Array.isArray(r)){for(let n of r)hde(t,e,n);return}if(r===null){t.append(e,"");return}if(mde(r)){t.append(e,JSON.stringify(r));return}t.append(e,`${r}`)}},Wtt=t=>{let e=new URLSearchParams;for(let[r,n]of Object.entries(t))hde(e,r,n);return e.toString()},$tt=t=>!t.destroyed&&t.readableEnded!==!0&&t.readable,Gtt=(t,e)=>typeof t=="string"?t:t instanceof URLSearchParams?t.toString():e&&mde(t)?Wtt(t):JSON.stringify(t)});function yH(t){return async(e,r)=>yde(r,await t(gde({base:`${e.headers["x-forwarded-proto"]||(e.socket.encrypted?"https":"http")}://${e.headers[":authority"]||e.headers.host}`,request:e})))}var vde=I(()=>{bde()});var _de={};ui(_de,{fromNodeHeaders:()=>Ztt,toNodeHandler:()=>Jtt});function Ztt(t){let e=new Headers;for(let[r,n]of Object.entries(t))n!==void 0&&(Array.isArray(n)?n.forEach(i=>e.append(r,i)):e.set(r,n));return e}var Jtt,Ede=I(()=>{vde();Jtt=t=>"handler"in t?yH(t.handler):yH(t)});function bH(t){return t==="-"||t==="^"||t==="$"||t==="+"||t==="."||t==="("||t===")"||t==="|"||t==="["||t==="]"||t==="{"||t==="}"||t==="*"||t==="?"||t==="\\"?`\\${t}`:t}function Xtt(t){let e="";for(let r=0;r<t.length;r++)e+=bH(t[r]);return e}function Sde(t,e=!0){if(Array.isArray(t))return`(?:${t.map(l=>`^${Sde(l,e)}$`).join("|")})`;let r="",n="",i=".";e===!0?(r="/",n="[/\\\\]",i="[^/\\\\]"):e&&(r=e,n=Xtt(r),n.length>1?(n=`(?:${n})`,i=`((?!${n}).)`):i=`[^${n}]`);let s=e?`${n}+?`:"",o=e?`${n}*?`:"",a=e?t.split(r):[t],c="";for(let l=0;l<a.length;l++){let u=a[l],d=a[l+1],p="";if(!(!u&&l>0)){if(e&&(l===a.length-1?p=o:d!=="**"?p=s:p=""),e&&u==="**"){p&&(c+=l===0?"":p,c+=`(?:${i}*?${p})*?`);continue}for(let f=0;f<u.length;f++){let m=u[f];m==="\\"?f<u.length-1&&(c+=bH(u[f+1]),f++):m==="?"?c+=i:m==="*"?c+=`${i}*?`:c+=bH(m)}c+=p}}return c}function Qtt(t,e){if(typeof e!="string")throw new TypeError(`Sample must be a string, but ${typeof e} given`);return t.test(e)}function Uh(t,e){if(typeof t!="string"&&!Array.isArray(t))throw new TypeError(`The first argument must be a single pattern string or an array of patterns, but ${typeof t} given`);if((typeof e=="string"||typeof e=="boolean")&&(e={separator:e}),arguments.length===2&&!(typeof e>"u"||typeof e=="object"&&e!==null&&!Array.isArray(e)))throw new TypeError(`The second argument must be an options object or a string/boolean separator, but ${typeof e} given`);if(e=e||{},e.separator==="\\")throw new Error("\\ is not a valid separator because it is used for escaping. Try setting the separator to `true` instead");let r=Sde(t,e.separator),n=new RegExp(`^${r}$`,e.flags),i=Qtt.bind(null,n);return i.options=e,i.pattern=t,i.regexp=n,i}var PR=I(()=>{});function ert(t){return t?t!=="false":!1}function hr(t,e){return typeof process<"u"&&process.env?process.env[t]??e:typeof Deno<"u"?Deno.env.get(t)??e:typeof Bun<"u"?Bun.env[t]??e:e}function MR(t,e=!0){let r=hr(t);return r?r!=="0"&&r.toLowerCase()!=="false"&&r!=="":e}var DR,p0,Zt,f0,xf,Jd,Nl,vH,_H=I(()=>{DR=Object.create(null),p0=t=>globalThis.process?.env||globalThis.Deno?.env.toObject()||globalThis.__env__||(t?DR:globalThis),Zt=new Proxy(DR,{get(t,e){return p0()[e]??DR[e]},has(t,e){return e in p0()||e in DR},set(t,e,r){let n=p0(!0);return n[e]=r,!0},deleteProperty(t,e){if(!e)return!1;let r=p0(!0);return delete r[e],!0},ownKeys(){let t=p0(!0);return Object.keys(t)}});f0=typeof process<"u"&&process.env&&process.env.NODE_ENV||"",xf=f0==="production",Jd=()=>f0==="dev"||f0==="development",Nl=()=>f0==="test"||ert(Zt.TEST);vH=Object.freeze({get BETTER_AUTH_SECRET(){return hr("BETTER_AUTH_SECRET")},get AUTH_SECRET(){return hr("AUTH_SECRET")},get BETTER_AUTH_TELEMETRY(){return hr("BETTER_AUTH_TELEMETRY")},get BETTER_AUTH_TELEMETRY_ID(){return hr("BETTER_AUTH_TELEMETRY_ID")},get NODE_ENV(){return hr("NODE_ENV","development")},get PACKAGE_VERSION(){return hr("PACKAGE_VERSION","0.0.0")},get BETTER_AUTH_TELEMETRY_ENDPOINT(){return hr("BETTER_AUTH_TELEMETRY_ENDPOINT","")}})});function LR(){if(hr("FORCE_COLOR")!==void 0)switch(hr("FORCE_COLOR")){case"":case"1":case"true":return Bi;case"2":return zu;case"3":return Ha;default:return m0}if(hr("NODE_DISABLE_COLORS")!==void 0&&hr("NODE_DISABLE_COLORS")!==""||hr("NO_COLOR")!==void 0&&hr("NO_COLOR")!==""||hr("TERM")==="dumb")return m0;if(hr("TMUX"))return Ha;if("TF_BUILD"in Zt&&"AGENT_NAME"in Zt)return Bi;if("CI"in Zt){for(let{0:t,1:e}of trt)if(t in Zt)return e;return hr("CI_NAME")==="codeship"?zu:m0}if("TEAMCITY_VERSION"in Zt)return/^(9\.(0*[1-9]\d*)\.|\d{2,}\.)/.exec(hr("TEAMCITY_VERSION"))!==null?Bi:m0;switch(hr("TERM_PROGRAM")){case"iTerm.app":return!hr("TERM_PROGRAM_VERSION")||/^[0-2]\./.exec(hr("TERM_PROGRAM_VERSION"))!==null?zu:Ha;case"HyperTerm":case"MacTerm":return Ha;case"Apple_Terminal":return zu}if(hr("COLORTERM")==="truecolor"||hr("COLORTERM")==="24bit")return Ha;if(hr("TERM")){if(/truecolor/.exec(hr("TERM"))!==null)return Ha;if(/^xterm-256/.exec(hr("TERM"))!==null)return zu;let t=hr("TERM").toLowerCase();if(wde[t])return wde[t];if(rrt.some(e=>e.exec(t)!==null))return Bi}return hr("COLORTERM")?Bi:m0}var m0,Bi,zu,Ha,wde,trt,rrt,EH=I(()=>{_H();m0=1,Bi=4,zu=8,Ha=24,wde={eterm:Bi,cons25:Bi,console:Bi,cygwin:Bi,dtterm:Bi,gnome:Bi,hurd:Bi,jfbterm:Bi,konsole:Bi,kterm:Bi,mlterm:Bi,mosh:Ha,putty:Bi,st:Bi,"rxvt-unicode-24bit":Ha,terminator:Ha,"xterm-kitty":Ha},trt=new Map(Object.entries({APPVEYOR:zu,BUILDKITE:zu,CIRCLECI:Ha,DRONE:zu,GITEA_ACTIONS:Ha,GITHUB_ACTIONS:Ha,GITLAB_CI:zu,TRAVIS:zu})),rrt=[/ansi/,/color/,/linux/,/direct/,/^con[0-9]*x[0-9]/,/^rxvt/,/^screen/,/^xterm/,/^vt100/,/^vt220/]});function Xb(t,e){return jR.indexOf(e)>=jR.indexOf(t)}var ni,jR,nrt,irt,Zd,De,bs=I(()=>{EH();ni={reset:"\x1B[0m",bright:"\x1B[1m",dim:"\x1B[2m",undim:"\x1B[22m",underscore:"\x1B[4m",blink:"\x1B[5m",reverse:"\x1B[7m",hidden:"\x1B[8m",fg:{black:"\x1B[30m",red:"\x1B[31m",green:"\x1B[32m",yellow:"\x1B[33m",blue:"\x1B[34m",magenta:"\x1B[35m",cyan:"\x1B[36m",white:"\x1B[37m"},bg:{black:"\x1B[40m",red:"\x1B[41m",green:"\x1B[42m",yellow:"\x1B[43m",blue:"\x1B[44m",magenta:"\x1B[45m",cyan:"\x1B[46m",white:"\x1B[47m"}},jR=["debug","info","success","warn","error"];nrt={info:ni.fg.blue,success:ni.fg.green,warn:ni.fg.yellow,error:ni.fg.red,debug:ni.fg.magenta},irt=(t,e,r)=>{let n=new Date().toISOString();return r?`${ni.dim}${n}${ni.reset} ${nrt[t]}${t.toUpperCase()}${ni.reset} ${ni.bright}[Better Auth]:${ni.reset} ${e}`:`${n} ${t.toUpperCase()} [Better Auth]: ${e}`},Zd=t=>{let e=t?.disabled!==!0,r=t?.level??"warn",n=t?.disableColors!==void 0?!t.disableColors:LR()!==1,i=(s,o,a=[])=>{if(!e||!Xb(r,s))return;let c=irt(s,o,n);if(!t||typeof t.log!="function"){s==="error"?console.error(c,...a):s==="warn"?console.warn(c,...a):console.log(c,...a);return}t.log(s==="success"?"info":s,o,...a)};return{...Object.fromEntries(jR.map(s=>[s,(...[o,...a])=>i(s,o,a)])),get level(){return r}}},De=Zd()});var vs=I(()=>{_H();bs()});function Qb(t){return Object.fromEntries(Object.entries(t).map(([e,r])=>[e,{code:e,message:r,toString:()=>e}]))}var h0=I(()=>{});var ae,Tde=I(()=>{h0();ae=Qb({USER_NOT_FOUND:"User not found",FAILED_TO_CREATE_USER:"Failed to create user",FAILED_TO_CREATE_SESSION:"Failed to create session",FAILED_TO_UPDATE_USER:"Failed to update user",FAILED_TO_GET_SESSION:"Failed to get session",INVALID_PASSWORD:"Invalid password",INVALID_EMAIL:"Invalid email",INVALID_EMAIL_OR_PASSWORD:"Invalid email or password",INVALID_USER:"Invalid user",SOCIAL_ACCOUNT_ALREADY_LINKED:"Social account already linked",PROVIDER_NOT_FOUND:"Provider not found",INVALID_TOKEN:"Invalid token",TOKEN_EXPIRED:"Token expired",ID_TOKEN_NOT_SUPPORTED:"id_token not supported",FAILED_TO_GET_USER_INFO:"Failed to get user info",USER_EMAIL_NOT_FOUND:"User email not found",EMAIL_NOT_VERIFIED:"Email not verified",PASSWORD_TOO_SHORT:"Password too short",PASSWORD_TOO_LONG:"Password too long",USER_ALREADY_EXISTS:"User already exists.",USER_ALREADY_EXISTS_USE_ANOTHER_EMAIL:"User already exists. Use another email.",EMAIL_CAN_NOT_BE_UPDATED:"Email can not be updated",CREDENTIAL_ACCOUNT_NOT_FOUND:"Credential account not found",SESSION_EXPIRED:"Session expired. Re-authenticate to perform this action.",FAILED_TO_UNLINK_LAST_ACCOUNT:"You can't unlink your last account",ACCOUNT_NOT_FOUND:"Account not found",USER_ALREADY_HAS_PASSWORD:"User already has a password. Provide that to delete the account.",CROSS_SITE_NAVIGATION_LOGIN_BLOCKED:"Cross-site navigation login blocked. This request appears to be a CSRF attack.",VERIFICATION_EMAIL_NOT_ENABLED:"Verification email isn't enabled",EMAIL_ALREADY_VERIFIED:"Email is already verified",EMAIL_MISMATCH:"Email mismatch",SESSION_NOT_FRESH:"Session is not fresh",LINKED_ACCOUNT_ALREADY_EXISTS:"Linked account already exists",INVALID_ORIGIN:"Invalid origin",INVALID_CALLBACK_URL:"Invalid callbackURL",INVALID_REDIRECT_URL:"Invalid redirectURL",INVALID_ERROR_CALLBACK_URL:"Invalid errorCallbackURL",INVALID_NEW_USER_CALLBACK_URL:"Invalid newUserCallbackURL",MISSING_OR_NULL_ORIGIN:"Missing or null Origin",CALLBACK_URL_REQUIRED:"callbackURL is required",FAILED_TO_CREATE_VERIFICATION:"Unable to create verification",FIELD_NOT_ALLOWED:"Field not allowed to be set",ASYNC_VALIDATION_NOT_SUPPORTED:"Async validation is not supported",VALIDATION_ERROR:"Validation Error",MISSING_FIELD:"Field is required",METHOD_NOT_ALLOWED_DEFER_SESSION_REQUIRED:"POST method requires deferSessionRefresh to be enabled in session config",BODY_MUST_BE_AN_OBJECT:"Body must be an object",PASSWORD_ALREADY_SET:"User already has a password set"})});function srt(){let t=Object.getOwnPropertyDescriptor(Error,"stackTraceLimit");return t===void 0?Object.isExtensible(Error):Object.prototype.hasOwnProperty.call(t,"writable")?t.writable:t.set!==void 0}function xde(t){let e=t.split(` | |||
| at `);return e.length<=1?t:(e.splice(1,1),e.join(` | |||
| at `))}function Ide(t,e){class r extends t{#e;constructor(...i){if(srt()){let o=Error.stackTraceLimit;Error.stackTraceLimit=0,super(...i),Error.stackTraceLimit=o}else super(...i);let s=new Error().stack;s&&(this.#e=xde(s.replace(/^Error/,this.name)))}get errorStack(){return this.#e}}return Object.defineProperty(r.prototype,"constructor",{get(){return e},enumerable:!1,configurable:!0}),r}var Ade,Ode,g0,UR,Xd,ua,If=I(()=>{Ade={OK:200,CREATED:201,ACCEPTED:202,NO_CONTENT:204,MULTIPLE_CHOICES:300,MOVED_PERMANENTLY:301,FOUND:302,SEE_OTHER:303,NOT_MODIFIED:304,TEMPORARY_REDIRECT:307,BAD_REQUEST:400,UNAUTHORIZED:401,PAYMENT_REQUIRED:402,FORBIDDEN:403,NOT_FOUND:404,METHOD_NOT_ALLOWED:405,NOT_ACCEPTABLE:406,PROXY_AUTHENTICATION_REQUIRED:407,REQUEST_TIMEOUT:408,CONFLICT:409,GONE:410,LENGTH_REQUIRED:411,PRECONDITION_FAILED:412,PAYLOAD_TOO_LARGE:413,URI_TOO_LONG:414,UNSUPPORTED_MEDIA_TYPE:415,RANGE_NOT_SATISFIABLE:416,EXPECTATION_FAILED:417,"I'M_A_TEAPOT":418,MISDIRECTED_REQUEST:421,UNPROCESSABLE_ENTITY:422,LOCKED:423,FAILED_DEPENDENCY:424,TOO_EARLY:425,UPGRADE_REQUIRED:426,PRECONDITION_REQUIRED:428,TOO_MANY_REQUESTS:429,REQUEST_HEADER_FIELDS_TOO_LARGE:431,UNAVAILABLE_FOR_LEGAL_REASONS:451,INTERNAL_SERVER_ERROR:500,NOT_IMPLEMENTED:501,BAD_GATEWAY:502,SERVICE_UNAVAILABLE:503,GATEWAY_TIMEOUT:504,HTTP_VERSION_NOT_SUPPORTED:505,VARIANT_ALSO_NEGOTIATES:506,INSUFFICIENT_STORAGE:507,LOOP_DETECTED:508,NOT_EXTENDED:510,NETWORK_AUTHENTICATION_REQUIRED:511},Ode=class extends Error{constructor(t="INTERNAL_SERVER_ERROR",e=void 0,r={},n=typeof t=="number"?t:Ade[t]){super(e?.message,e?.cause?{cause:e.cause}:void 0),this.status=t,this.body=e,this.headers=r,this.statusCode=n,this.name="APIError",this.status=t,this.headers=r,this.statusCode=n,this.body=e}},g0=class extends Ode{constructor(t,e){super(400,{message:t,code:"VALIDATION_ERROR"}),this.message=t,this.issues=e,this.issues=e}},UR=class extends Error{constructor(t){super(t),this.name="BetterCallError"}},Xd=Symbol.for("better-call:api-error-headers"),ua=Ide(Ode,Error)});var me,D,rt=I(()=>{Tde();If();me=class extends Error{constructor(t,e){super(t,e),this.name="BetterAuthError",this.message=t,this.stack=""}},D=class SH extends ua{constructor(...e){super(...e)}static fromStatus(e,r){return new SH(e,r)}static from(e,r){return new SH(e,{message:r.message,code:r.code})}}});function ort(t){let e=t.replace(/:\d+$/,"").replace(/^\[|\]$/g,"").toLowerCase();return e==="localhost"||e.endsWith(".localhost")||e==="::1"||e.startsWith("127.")}function art(t){try{return(new URL(t).pathname.replace(/\/+$/,"")||"/")!=="/"}catch{throw new me(`Invalid base URL: ${t}. Please provide a valid base URL.`)}}function crt(t){try{let e=new URL(t);if(e.protocol!=="http:"&&e.protocol!=="https:")throw new me(`Invalid base URL: ${t}. URL must include 'http://' or 'https://'`)}catch(e){throw e instanceof me?e:new me(`Invalid base URL: ${t}. Please provide a valid base URL.`,{cause:e})}}function Qd(t,e="/api/auth"){if(crt(t),art(t))return t;let r=t.replace(/\/+$/,"");return!e||e==="/"?r:(e=e.startsWith("/")?e:`/${e}`,`${r}${e}`)}function y0(t,e){return!t||t.trim()===""?!1:e==="proto"?t==="http"||t==="https":e==="host"?[/\.\./,/\0/,/[\s]/,/^[.]/,/[<>'"]/,/javascript:/i,/file:/i,/data:/i].some(r=>r.test(t))?!1:/^[a-zA-Z0-9]([a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?(\.[a-zA-Z0-9]([a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?)*(:[0-9]{1,5})?$/.test(t)||/^(\d{1,3}\.){3}\d{1,3}(:[0-9]{1,5})?$/.test(t)||/^\[[0-9a-fA-F:]+\](:[0-9]{1,5})?$/.test(t)||/^localhost(:[0-9]{1,5})?$/i.test(t):!1}function ep(t,e,r,n,i){if(t)return Qd(t,e);if(n!==!1){let a=Zt.BETTER_AUTH_URL||Zt.NEXT_PUBLIC_BETTER_AUTH_URL||Zt.PUBLIC_BETTER_AUTH_URL||Zt.NUXT_PUBLIC_BETTER_AUTH_URL||Zt.NUXT_PUBLIC_AUTH_URL||(Zt.BASE_URL!=="/"?Zt.BASE_URL:void 0);if(a)return Qd(a,e)}let s=r?.headers.get("x-forwarded-host"),o=r?.headers.get("x-forwarded-proto");if(s&&o&&i&&y0(o,"proto")&&y0(s,"host"))try{return Qd(`${o}://${s}`,e)}catch{}if(r){let a=Af(r.url);if(!a)throw new me("Could not get origin from request. Please provide a valid base URL.");return Qd(a,e)}if(typeof window<"u"&&window.location)return Qd(window.location.origin,e)}function Af(t){try{let e=new URL(t);return e.origin==="null"?null:e.origin}catch{return null}}function kde(t){try{return new URL(t).protocol}catch{return null}}function Rde(t){try{return new URL(t).host}catch{return null}}function Wa(t){return typeof t=="object"&&t!==null&&"allowedHosts"in t&&Array.isArray(t.allowedHosts)}function Bu(t){if(t instanceof Request)return!0;if(typeof t!="object"||t===null||Object.prototype.toString.call(t)!=="[object Request]")return!1;let e=t;return typeof e.url=="string"&&typeof e.headers=="object"&&e.headers!==null&&typeof e.headers.get=="function"}function Cde(t,e){let r=Bu(t)?t.headers:t;if(e){let i=r.get("x-forwarded-host");if(i&&y0(i,"host"))return i}let n=r.get("host");if(n&&y0(n,"host"))return n;if(Bu(t))try{return new URL(t.url).host}catch{return null}return null}function lrt(t,e,r){if(e==="http"||e==="https")return e;let n=Bu(t)?t.headers:t;if(r){let s=n.get("x-forwarded-proto");if(s&&y0(s,"proto"))return s}if(Bu(t))try{let s=new URL(t.url);if(s.protocol==="http:"||s.protocol==="https:")return s.protocol.slice(0,-1)}catch{}let i=Cde(t,r);return i&&ort(i)?"http":"https"}function drt(t,e,r,n){let i=Cde(e,n);if(!i){if(t.fallback)return Qd(t.fallback,r);throw new me("Could not determine host from request headers. Please provide a fallback URL in your baseURL config.")}if(t.allowedHosts.some(s=>urt(i,s)))return Qd(`${lrt(e,t.protocol,n)}://${i}`,r);if(t.fallback)return Qd(t.fallback,r);throw new me(`Host "${i}" is not in the allowed hosts list. Allowed hosts: ${t.allowedHosts.join(", ")}. Add this host to your allowedHosts config or provide a fallback URL.`)}function Nde(t,e,r,n,i){if(Wa(t))return r?drt(t,r,e,i):t.fallback?Qd(t.fallback,e):ep(void 0,e,void 0,n,i);let s=Bu(r)?r:void 0;return ep(typeof t=="string"?t:void 0,e,s,n,i)}var urt,Kh=I(()=>{PR();vs();rt();urt=(t,e)=>{if(!t||!e)return!1;let r=t.replace(/^https?:\/\//,"").split("/")[0].toLowerCase(),n=e.replace(/^https?:\/\//,"").split("/")[0].toLowerCase();return n.includes("*")||n.includes("?")?Uh(n)(r):r.toLowerCase()===n.toLowerCase()}});function Pde(t){switch(t){case"a-z":return"abcdefghijklmnopqrstuvwxyz";case"A-Z":return"ABCDEFGHIJKLMNOPQRSTUVWXYZ";case"0-9":return"0123456789";case"-_":return"-_";default:throw new Error(`Unsupported alphabet: ${t}`)}}function ev(...t){let e=t.map(Pde).join("");if(e.length===0)throw new Error("No valid characters provided for random string generation.");let r=e.length;return(n,...i)=>{if(n<=0)throw new Error("Length must be a positive integer.");let s=e,o=r;i.length>0&&(s=i.map(Pde).join(""),o=s.length);let a=Math.floor(256/o)*o,c=new Uint8Array(n*2),l=c.length,u="",d=l,p;for(;u.length<n;)d>=l&&(crypto.getRandomValues(c),d=0),p=c[d++],p<a&&(u+=s[p%o]);return u}}var KR=I(()=>{});var tp,b0=I(()=>{KR();tp=ev("a-z","0-9","A-Z","-_")});function prt(t){return t instanceof Uint8Array||ArrayBuffer.isView(t)&&t.constructor.name==="Uint8Array"&&"BYTES_PER_ELEMENT"in t&&t.BYTES_PER_ELEMENT===1}function qR(t,e=""){if(typeof t!="number"){let r=e&&`"${e}" `;throw new TypeError(`${r}expected number, got ${typeof t}`)}if(!Number.isSafeInteger(t)||t<0){let r=e&&`"${e}" `;throw new RangeError(`${r}expected integer >= 0, got ${t}`)}}function Of(t,e,r=""){let n=prt(t),i=t?.length,s=e!==void 0;if(!n||s&&i!==e){let o=r&&`"${r}" `,a=s?` of length ${e}`:"",c=n?`length=${i}`:`type=${typeof t}`,l=o+"expected Uint8Array"+a+", got "+c;throw n?new RangeError(l):new TypeError(l)}return t}function v0(t){if(typeof t!="function"||typeof t.create!="function")throw new TypeError("Hash must wrapped by utils.createHasher");if(qR(t.outputLen),qR(t.blockLen),t.outputLen<1)throw new Error('"outputLen" must be >= 1');if(t.blockLen<1)throw new Error('"blockLen" must be >= 1')}function tv(t,e=!0){if(t.destroyed)throw new Error("Hash instance has been destroyed");if(e&&t.finished)throw new Error("Hash#digest() has already been called")}function FR(t,e){Of(t,void 0,"digestInto() output");let r=e.outputLen;if(t.length<r)throw new RangeError('"digestInto() output" expected to be of length >='+r)}function rp(...t){for(let e=0;e<t.length;e++)t[e].fill(0)}function zR(t){return new DataView(t.buffer,t.byteOffset,t.byteLength)}function Pl(t,e){return t<<32-e|t>>>e}function Dde(t,e={}){let r=(i,s)=>t(s).update(i).digest(),n=t(void 0);return r.outputLen=n.outputLen,r.blockLen=n.blockLen,r.canXOF=n.canXOF,r.create=i=>t(i),Object.assign(r,e),Object.freeze(r)}var Mde,_0=I(()=>{Mde=t=>({oid:Uint8Array.from([6,9,96,134,72,1,101,3,4,2,t])})});var BR,wH,Lde=I(()=>{_0();BR=class{oHash;iHash;blockLen;outputLen;canXOF=!1;finished=!1;destroyed=!1;constructor(e,r){if(v0(e),Of(r,void 0,"key"),this.iHash=e.create(),typeof this.iHash.update!="function")throw new Error("Expected instance of class which extends utils.Hash");this.blockLen=this.iHash.blockLen,this.outputLen=this.iHash.outputLen;let n=this.blockLen,i=new Uint8Array(n);i.set(r.length>n?e.create().update(r).digest():r);for(let s=0;s<i.length;s++)i[s]^=54;this.iHash.update(i),this.oHash=e.create();for(let s=0;s<i.length;s++)i[s]^=106;this.oHash.update(i),rp(i)}update(e){return tv(this),this.iHash.update(e),this}digestInto(e){tv(this),FR(e,this),this.finished=!0;let r=e.subarray(0,this.outputLen);this.iHash.digestInto(r),this.oHash.update(r),this.oHash.digestInto(r),this.destroy()}digest(){let e=new Uint8Array(this.oHash.outputLen);return this.digestInto(e),e}_cloneInto(e){e||=Object.create(Object.getPrototypeOf(this),{});let{oHash:r,iHash:n,finished:i,destroyed:s,blockLen:o,outputLen:a}=this;return e=e,e.finished=i,e.destroyed=s,e.blockLen=o,e.outputLen=a,e.oHash=r._cloneInto(e.oHash),e.iHash=n._cloneInto(e.iHash),e}clone(){return this._cloneInto()}destroy(){this.destroyed=!0,this.oHash.destroy(),this.iHash.destroy()}},wH=(()=>{let t=((e,r,n)=>new BR(e,r).update(n).digest());return t.create=(e,r)=>new BR(e,r),t})()});function frt(t,e,r){return v0(t),r===void 0&&(r=new Uint8Array(t.outputLen)),wH(t,r,e)}function mrt(t,e,r,n=32){v0(t),qR(n,"length"),Of(e,void 0,"prk");let i=t.outputLen;if(e.length<i)throw new Error('"prk" must be at least HashLen octets');if(n>255*i)throw new Error("Length must be <= 255*HashLen");let s=Math.ceil(n/i);r===void 0?r=jde:Of(r,void 0,"info");let o=new Uint8Array(s*i),a=wH.create(t,e),c=a._cloneInto(),l=new Uint8Array(a.outputLen);for(let u=0;u<s;u++)TH[0]=u+1,c.update(u===0?jde:l).update(r).update(TH).digestInto(l),o.set(l,i*u),a._cloneInto(c);return a.destroy(),c.destroy(),rp(l,TH),o.slice(0,n)}var TH,jde,Ude,Kde=I(()=>{Lde();_0();TH=Uint8Array.of(0),jde=Uint8Array.of();Ude=(t,e,r,n,i)=>mrt(t,frt(t,e,r),n,i)});function qde(t,e,r){return t&e^~t&r}function Fde(t,e,r){return t&e^t&r^e&r}var HR,np,zde=I(()=>{_0();HR=class{blockLen;outputLen;canXOF=!1;padOffset;isLE;buffer;view;finished=!1;length=0;pos=0;destroyed=!1;constructor(e,r,n,i){this.blockLen=e,this.outputLen=r,this.padOffset=n,this.isLE=i,this.buffer=new Uint8Array(e),this.view=zR(this.buffer)}update(e){tv(this),Of(e);let{view:r,buffer:n,blockLen:i}=this,s=e.length;for(let o=0;o<s;){let a=Math.min(i-this.pos,s-o);if(a===i){let c=zR(e);for(;i<=s-o;o+=i)this.process(c,o);continue}n.set(e.subarray(o,o+a),this.pos),this.pos+=a,o+=a,this.pos===i&&(this.process(r,0),this.pos=0)}return this.length+=e.length,this.roundClean(),this}digestInto(e){tv(this),FR(e,this),this.finished=!0;let{buffer:r,view:n,blockLen:i,isLE:s}=this,{pos:o}=this;r[o++]=128,rp(this.buffer.subarray(o)),this.padOffset>i-o&&(this.process(n,0),o=0);for(let d=o;d<i;d++)r[d]=0;n.setBigUint64(i-8,BigInt(this.length*8),s),this.process(n,0);let a=zR(e),c=this.outputLen;if(c%4)throw new Error("_sha2: outputLen must be aligned to 32bit");let l=c/4,u=this.get();if(l>u.length)throw new Error("_sha2: outputLen bigger than state");for(let d=0;d<l;d++)a.setUint32(4*d,u[d],s)}digest(){let{buffer:e,outputLen:r}=this;this.digestInto(e);let n=e.slice(0,r);return this.destroy(),n}_cloneInto(e){e||=new this.constructor,e.set(...this.get());let{blockLen:r,buffer:n,length:i,finished:s,destroyed:o,pos:a}=this;return e.destroyed=o,e.finished=s,e.length=i,e.pos=a,i%r&&e.buffer.set(n),e}clone(){return this._cloneInto()}},np=Uint32Array.from([1779033703,3144134277,1013904242,2773480762,1359893119,2600822924,528734635,1541459225])});var hrt,kf,xH,IH,Bde,Hde=I(()=>{zde();_0();hrt=Uint32Array.from([1116352408,1899447441,3049323471,3921009573,961987163,1508970993,2453635748,2870763221,3624381080,310598401,607225278,1426881987,1925078388,2162078206,2614888103,3248222580,3835390401,4022224774,264347078,604807628,770255983,1249150122,1555081692,1996064986,2554220882,2821834349,2952996808,3210313671,3336571891,3584528711,113926993,338241895,666307205,773529912,1294757372,1396182291,1695183700,1986661051,2177026350,2456956037,2730485921,2820302411,3259730800,3345764771,3516065817,3600352804,4094571909,275423344,430227734,506948616,659060556,883997877,958139571,1322822218,1537002063,1747873779,1955562222,2024104815,2227730452,2361852424,2428436474,2756734187,3204031479,3329325298]),kf=new Uint32Array(64),xH=class extends HR{constructor(e){super(64,e,8,!1)}get(){let{A:e,B:r,C:n,D:i,E:s,F:o,G:a,H:c}=this;return[e,r,n,i,s,o,a,c]}set(e,r,n,i,s,o,a,c){this.A=e|0,this.B=r|0,this.C=n|0,this.D=i|0,this.E=s|0,this.F=o|0,this.G=a|0,this.H=c|0}process(e,r){for(let d=0;d<16;d++,r+=4)kf[d]=e.getUint32(r,!1);for(let d=16;d<64;d++){let p=kf[d-15],f=kf[d-2],m=Pl(p,7)^Pl(p,18)^p>>>3,h=Pl(f,17)^Pl(f,19)^f>>>10;kf[d]=h+kf[d-7]+m+kf[d-16]|0}let{A:n,B:i,C:s,D:o,E:a,F:c,G:l,H:u}=this;for(let d=0;d<64;d++){let p=Pl(a,6)^Pl(a,11)^Pl(a,25),f=u+p+qde(a,c,l)+hrt[d]+kf[d]|0,h=(Pl(n,2)^Pl(n,13)^Pl(n,22))+Fde(n,i,s)|0;u=l,l=c,c=a,a=o+f|0,o=s,s=i,i=n,n=f+h|0}n=n+this.A|0,i=i+this.B|0,s=s+this.C|0,o=o+this.D|0,a=a+this.E|0,c=c+this.F|0,l=l+this.G|0,u=u+this.H|0,this.set(n,i,s,o,a,c,l,u)}roundClean(){rp(kf)}destroy(){this.destroyed=!0,this.set(0,0,0,0,0,0,0,0),rp(this.buffer)}},IH=class extends xH{A=np[0]|0;B=np[1]|0;C=np[2]|0;D=np[3]|0;E=np[4]|0;F=np[5]|0;G=np[6]|0;H=np[7]|0;constructor(){super(32)}},Bde=Dde(()=>new IH,Mde(1))});function fi(...t){let e=t.reduce((i,{length:s})=>i+s,0),r=new Uint8Array(e),n=0;for(let i of t)r.set(i,n),n+=i.length;return r}function AH(t,e,r){if(e<0||e>=WR)throw new RangeError(`value must be >= 0 and <= ${WR-1}. Received ${e}`);t.set([e>>>24,e>>>16,e>>>8,e&255],r)}function OH(t){let e=Math.floor(t/WR),r=t%WR,n=new Uint8Array(8);return AH(n,e,0),AH(n,r,4),n}function $R(t){let e=new Uint8Array(4);return AH(e,t),e}function Bn(t){let e=new Uint8Array(t.length);for(let r=0;r<t.length;r++){let n=t.charCodeAt(r);if(n>127)throw new TypeError("non-ASCII string encountered in encode()");e[r]=n}return e}var qh,_s,WR,Vs=I(()=>{qh=new TextEncoder,_s=new TextDecoder,WR=2**32});function Wde(t){if(Uint8Array.prototype.toBase64)return t.toBase64();let e=32768,r=[];for(let n=0;n<t.length;n+=e)r.push(String.fromCharCode.apply(null,t.subarray(n,n+e)));return btoa(r.join(""))}function $de(t){if(Uint8Array.fromBase64)return Uint8Array.fromBase64(t);let e=atob(t),r=new Uint8Array(e.length);for(let n=0;n<e.length;n++)r[n]=e.charCodeAt(n);return r}var Gde=I(()=>{});var E0={};ui(E0,{decode:()=>_o,encode:()=>bn});function _o(t){if(Uint8Array.fromBase64)return Uint8Array.fromBase64(typeof t=="string"?t:_s.decode(t),{alphabet:"base64url"});let e=t;e instanceof Uint8Array&&(e=_s.decode(e)),e=e.replace(/-/g,"+").replace(/_/g,"/");try{return $de(e)}catch{throw new TypeError("The input to be decoded is not correctly encoded.")}}function bn(t){let e=t;return typeof e=="string"&&(e=qh.encode(e)),Uint8Array.prototype.toBase64?e.toBase64({alphabet:"base64url",omitPadding:!0}):Wde(e).replace(/=/g,"").replace(/\+/g,"-").replace(/\//g,"_")}var Ys=I(()=>{Vs();Gde()});function grt(t){return parseInt(t.name.slice(4),10)}function GR(t,e){if(grt(t.hash)!==e)throw Eo(`SHA-${e}`,"algorithm.hash")}function yrt(t){switch(t){case"ES256":return"P-256";case"ES384":return"P-384";case"ES512":return"P-521";default:throw new Error("unreachable")}}function Vde(t,e){if(e&&!t.usages.includes(e))throw new TypeError(`CryptoKey does not support this operation, its usages must include ${e}.`)}function Yde(t,e,r){switch(e){case"HS256":case"HS384":case"HS512":{if(!Hu(t.algorithm,"HMAC"))throw Eo("HMAC");GR(t.algorithm,parseInt(e.slice(2),10));break}case"RS256":case"RS384":case"RS512":{if(!Hu(t.algorithm,"RSASSA-PKCS1-v1_5"))throw Eo("RSASSA-PKCS1-v1_5");GR(t.algorithm,parseInt(e.slice(2),10));break}case"PS256":case"PS384":case"PS512":{if(!Hu(t.algorithm,"RSA-PSS"))throw Eo("RSA-PSS");GR(t.algorithm,parseInt(e.slice(2),10));break}case"Ed25519":case"EdDSA":{if(!Hu(t.algorithm,"Ed25519"))throw Eo("Ed25519");break}case"ML-DSA-44":case"ML-DSA-65":case"ML-DSA-87":{if(!Hu(t.algorithm,e))throw Eo(e);break}case"ES256":case"ES384":case"ES512":{if(!Hu(t.algorithm,"ECDSA"))throw Eo("ECDSA");let n=yrt(e);if(t.algorithm.namedCurve!==n)throw Eo(n,"algorithm.namedCurve");break}default:throw new TypeError("CryptoKey does not support this operation")}Vde(t,r)}function $a(t,e,r){switch(e){case"A128GCM":case"A192GCM":case"A256GCM":{if(!Hu(t.algorithm,"AES-GCM"))throw Eo("AES-GCM");let n=parseInt(e.slice(1,4),10);if(t.algorithm.length!==n)throw Eo(n,"algorithm.length");break}case"A128KW":case"A192KW":case"A256KW":{if(!Hu(t.algorithm,"AES-KW"))throw Eo("AES-KW");let n=parseInt(e.slice(1,4),10);if(t.algorithm.length!==n)throw Eo(n,"algorithm.length");break}case"ECDH":{switch(t.algorithm.name){case"ECDH":case"X25519":break;default:throw Eo("ECDH or X25519")}break}case"PBES2-HS256+A128KW":case"PBES2-HS384+A192KW":case"PBES2-HS512+A256KW":if(!Hu(t.algorithm,"PBKDF2"))throw Eo("PBKDF2");break;case"RSA-OAEP":case"RSA-OAEP-256":case"RSA-OAEP-384":case"RSA-OAEP-512":{if(!Hu(t.algorithm,"RSA-OAEP"))throw Eo("RSA-OAEP");GR(t.algorithm,parseInt(e.slice(9),10)||1);break}default:throw new TypeError("CryptoKey does not support this operation")}Vde(t,r)}var Eo,Hu,Fh=I(()=>{Eo=(t,e="algorithm.name")=>new TypeError(`CryptoKey does not support this operation, its ${e} must be ${t}`),Hu=(t,e)=>t.name===e});function Jde(t,e,...r){if(r=r.filter(Boolean),r.length>2){let n=r.pop();t+=`one of type ${r.join(", ")}, or ${n}.`}else r.length===2?t+=`one of type ${r[0]} or ${r[1]}.`:t+=`of type ${r[0]}.`;return e==null?t+=` Received ${e}`:typeof e=="function"&&e.name?t+=` Received function ${e.name}`:typeof e=="object"&&e!=null&&e.constructor?.name&&(t+=` Received an instance of ${e.constructor.name}`),t}var Wu,kH,rv=I(()=>{Wu=(t,...e)=>Jde("Key must be ",t,...e),kH=(t,e,...r)=>Jde(`Key for the ${t} algorithm must be `,e,...r)});var Si,Es,zh,Bh,Pt,nv,Me,zr,Js,VR,S0,iv,YR,JR,ZR,cn=I(()=>{Si=class extends Error{static code="ERR_JOSE_GENERIC";code="ERR_JOSE_GENERIC";constructor(e,r){super(e,r),this.name=this.constructor.name,Error.captureStackTrace?.(this,this.constructor)}},Es=class extends Si{static code="ERR_JWT_CLAIM_VALIDATION_FAILED";code="ERR_JWT_CLAIM_VALIDATION_FAILED";claim;reason;payload;constructor(e,r,n="unspecified",i="unspecified"){super(e,{cause:{claim:n,reason:i,payload:r}}),this.claim=n,this.reason=i,this.payload=r}},zh=class extends Si{static code="ERR_JWT_EXPIRED";code="ERR_JWT_EXPIRED";claim;reason;payload;constructor(e,r,n="unspecified",i="unspecified"){super(e,{cause:{claim:n,reason:i,payload:r}}),this.claim=n,this.reason=i,this.payload=r}},Bh=class extends Si{static code="ERR_JOSE_ALG_NOT_ALLOWED";code="ERR_JOSE_ALG_NOT_ALLOWED"},Pt=class extends Si{static code="ERR_JOSE_NOT_SUPPORTED";code="ERR_JOSE_NOT_SUPPORTED"},nv=class extends Si{static code="ERR_JWE_DECRYPTION_FAILED";code="ERR_JWE_DECRYPTION_FAILED";constructor(e="decryption operation failed",r){super(e,r)}},Me=class extends Si{static code="ERR_JWE_INVALID";code="ERR_JWE_INVALID"},zr=class extends Si{static code="ERR_JWS_INVALID";code="ERR_JWS_INVALID"},Js=class extends Si{static code="ERR_JWT_INVALID";code="ERR_JWT_INVALID"},VR=class extends Si{static code="ERR_JWK_INVALID";code="ERR_JWK_INVALID"},S0=class extends Si{static code="ERR_JWKS_INVALID";code="ERR_JWKS_INVALID"},iv=class extends Si{static code="ERR_JWKS_NO_MATCHING_KEY";code="ERR_JWKS_NO_MATCHING_KEY";constructor(e="no applicable key found in the JSON Web Key Set",r){super(e,r)}},YR=class extends Si{[Symbol.asyncIterator];static code="ERR_JWKS_MULTIPLE_MATCHING_KEYS";code="ERR_JWKS_MULTIPLE_MATCHING_KEYS";constructor(e="multiple matching keys found in the JSON Web Key Set",r){super(e,r)}},JR=class extends Si{static code="ERR_JWKS_TIMEOUT";code="ERR_JWKS_TIMEOUT";constructor(e="request timed out",r){super(e,r)}},ZR=class extends Si{static code="ERR_JWS_SIGNATURE_VERIFICATION_FAILED";code="ERR_JWS_SIGNATURE_VERIFICATION_FAILED";constructor(e="signature verification failed",r){super(e,r)}}});function sv(t){if(!ip(t))throw new Error("CryptoKey instance expected")}var ip,w0,T0,Hh=I(()=>{ip=t=>{if(t?.[Symbol.toStringTag]==="CryptoKey")return!0;try{return t instanceof CryptoKey}catch{return!1}},w0=t=>t?.[Symbol.toStringTag]==="KeyObject",T0=t=>ip(t)||w0(t)});function QR(t){switch(t){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 Pt(`Unsupported JWE Algorithm: ${t}`)}}function XR(t,e){let r=t.byteLength<<3;if(r!==e)throw new Me(`Invalid Content Encryption Key length. Expected ${e} bits, got ${r} bits`)}function Zde(t){switch(t){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 Pt(`Unsupported JWE Algorithm: ${t}`)}}function Xde(t,e){if(e.length<<3!==Zde(t))throw new Me("Invalid Initialization Vector length")}async function Qde(t,e,r){if(!(e instanceof Uint8Array))throw new TypeError(Wu(e,"Uint8Array"));let n=parseInt(t.slice(1,4),10),i=await crypto.subtle.importKey("raw",e.subarray(n>>3),"AES-CBC",!1,[r]),s=await crypto.subtle.importKey("raw",e.subarray(0,n>>3),{hash:`SHA-${n<<1}`,name:"HMAC"},!1,["sign"]);return{encKey:i,macKey:s,keySize:n}}async function epe(t,e,r){return new Uint8Array((await crypto.subtle.sign("HMAC",t,e)).slice(0,r>>3))}async function vrt(t,e,r,n,i){let{encKey:s,macKey:o,keySize:a}=await Qde(t,r,"encrypt"),c=new Uint8Array(await crypto.subtle.encrypt({iv:n,name:"AES-CBC"},s,e)),l=fi(i,n,c,OH(i.length<<3)),u=await epe(o,l,a);return{ciphertext:c,tag:u,iv:n}}async function _rt(t,e){if(!(t instanceof Uint8Array))throw new TypeError("First argument must be a buffer");if(!(e instanceof Uint8Array))throw new TypeError("Second argument must be a buffer");let r={name:"HMAC",hash:"SHA-256"},n=await crypto.subtle.generateKey(r,!1,["sign"]),i=new Uint8Array(await crypto.subtle.sign(r,n,t)),s=new Uint8Array(await crypto.subtle.sign(r,n,e)),o=0,a=-1;for(;++a<32;)o|=i[a]^s[a];return o===0}async function Ert(t,e,r,n,i,s){let{encKey:o,macKey:a,keySize:c}=await Qde(t,e,"decrypt"),l=fi(s,n,r,OH(s.length<<3)),u=await epe(a,l,c),d;try{d=await _rt(i,u)}catch{}if(!d)throw new nv;let p;try{p=new Uint8Array(await crypto.subtle.decrypt({iv:n,name:"AES-CBC"},o,r))}catch{}if(!p)throw new nv;return p}async function Srt(t,e,r,n,i){let s;r instanceof Uint8Array?s=await crypto.subtle.importKey("raw",r,"AES-GCM",!1,["encrypt"]):($a(r,t,"encrypt"),s=r);let o=new Uint8Array(await crypto.subtle.encrypt({additionalData:i,iv:n,name:"AES-GCM",tagLength:128},s,e)),a=o.slice(-16);return{ciphertext:o.slice(0,-16),tag:a,iv:n}}async function wrt(t,e,r,n,i,s){let o;e instanceof Uint8Array?o=await crypto.subtle.importKey("raw",e,"AES-GCM",!1,["decrypt"]):($a(e,t,"decrypt"),o=e);try{return new Uint8Array(await crypto.subtle.decrypt({additionalData:s,iv:n,name:"AES-GCM",tagLength:128},o,fi(r,i)))}catch{throw new nv}}async function eC(t,e,r,n,i){if(!ip(r)&&!(r instanceof Uint8Array))throw new TypeError(Wu(r,"CryptoKey","KeyObject","Uint8Array","JSON Web Key"));switch(n?Xde(t,n):n=brt(t),t){case"A128CBC-HS256":case"A192CBC-HS384":case"A256CBC-HS512":return r instanceof Uint8Array&&XR(r,parseInt(t.slice(-3),10)),vrt(t,e,r,n,i);case"A128GCM":case"A192GCM":case"A256GCM":return r instanceof Uint8Array&&XR(r,parseInt(t.slice(1,4),10)),Srt(t,e,r,n,i);default:throw new Pt(tpe)}}async function tC(t,e,r,n,i,s){if(!ip(e)&&!(e instanceof Uint8Array))throw new TypeError(Wu(e,"CryptoKey","KeyObject","Uint8Array","JSON Web Key"));if(!n)throw new Me("JWE Initialization Vector missing");if(!i)throw new Me("JWE Authentication Tag missing");switch(Xde(t,n),t){case"A128CBC-HS256":case"A192CBC-HS384":case"A256CBC-HS512":return e instanceof Uint8Array&&XR(e,parseInt(t.slice(-3),10)),Ert(t,e,r,n,i,s);case"A128GCM":case"A192GCM":case"A256GCM":return e instanceof Uint8Array&&XR(e,parseInt(t.slice(1,4),10)),wrt(t,e,r,n,i,s);default:throw new Pt(tpe)}}var Rf,brt,tpe,ov=I(()=>{Vs();Fh();rv();cn();Hh();Rf=t=>crypto.getRandomValues(new Uint8Array(QR(t)>>3));brt=t=>crypto.getRandomValues(new Uint8Array(Zde(t)>>3));tpe="Unsupported JWE Content Encryption Algorithm"});function So(t,e){if(t)throw new TypeError(`${e} can only be called once`)}function wo(t,e,r){try{return _o(t)}catch{throw new r(`Failed to base64url decode the ${e}`)}}async function rC(t,e){let r=`SHA-${t.slice(-3)}`;return new Uint8Array(await crypto.subtle.digest(r,e))}var rpe,sp=I(()=>{Ys();rpe=Symbol()});function vn(t){if(!Trt(t)||Object.prototype.toString.call(t)!=="[object Object]")return!1;if(Object.getPrototypeOf(t)===null)return!0;let e=t;for(;Object.getPrototypeOf(e)!==null;)e=Object.getPrototypeOf(e);return Object.getPrototypeOf(t)===e}function Cf(...t){let e=t.filter(Boolean);if(e.length===0||e.length===1)return!0;let r;for(let n of e){let i=Object.keys(n);if(!r||r.size===0){r=new Set(i);continue}for(let s of i){if(r.has(s))return!1;r.add(s)}}return!0}var Trt,Wh,npe,ipe,spe,Ss=I(()=>{Trt=t=>typeof t=="object"&&t!==null;Wh=t=>vn(t)&&typeof t.kty=="string",npe=t=>t.kty!=="oct"&&(t.kty==="AKP"&&typeof t.priv=="string"||typeof t.d=="string"),ipe=t=>t.kty!=="oct"&&t.d===void 0&&t.priv===void 0,spe=t=>t.kty==="oct"&&typeof t.k=="string"});function ope(t,e){if(t.algorithm.length!==parseInt(e.slice(1,4),10))throw new TypeError(`Invalid key size for alg: ${e}`)}function ape(t,e,r){return t instanceof Uint8Array?crypto.subtle.importKey("raw",t,"AES-KW",!0,[r]):($a(t,e,r),t)}async function x0(t,e,r){let n=await ape(e,t,"wrapKey");ope(n,t);let i=await crypto.subtle.importKey("raw",r,{hash:"SHA-256",name:"HMAC"},!0,["sign"]);return new Uint8Array(await crypto.subtle.wrapKey("raw",i,n,"AES-KW"))}async function I0(t,e,r){let n=await ape(e,t,"unwrapKey");ope(n,t);let i=await crypto.subtle.unwrapKey("raw",r,n,"AES-KW",{hash:"SHA-256",name:"HMAC"},!0,["sign"]);return new Uint8Array(await crypto.subtle.exportKey("raw",i))}var RH=I(()=>{Fh()});function CH(t){return fi($R(t.length),t)}async function Irt(t,e,r){let n=e>>3,i=32,s=Math.ceil(n/i),o=new Uint8Array(s*i);for(let a=1;a<=s;a++){let c=new Uint8Array(4+t.length+r.length);c.set($R(a),0),c.set(t,4),c.set(r,4+t.length);let l=await rC("sha256",c);o.set(l,(a-1)*i)}return o.slice(0,n)}async function NH(t,e,r,n,i=new Uint8Array,s=new Uint8Array){$a(t,"ECDH"),$a(e,"ECDH","deriveBits");let o=CH(Bn(r)),a=CH(i),c=CH(s),l=$R(n),u=new Uint8Array,d=fi(o,a,c,l,u),p=new Uint8Array(await crypto.subtle.deriveBits({name:t.algorithm.name,public:t},e,Art(t)));return Irt(p,n,d)}function Art(t){return t.algorithm.name==="X25519"?256:Math.ceil(parseInt(t.algorithm.namedCurve.slice(-3),10)/8)<<3}function PH(t){switch(t.algorithm.namedCurve){case"P-256":case"P-384":case"P-521":return!0;default:return t.algorithm.name==="X25519"}}var lpe=I(()=>{Vs();Fh();sp()});function krt(t,e){return t instanceof Uint8Array?crypto.subtle.importKey("raw",t,"PBKDF2",!1,["deriveBits"]):($a(t,e,"deriveBits"),t)}async function upe(t,e,r,n){if(!(t instanceof Uint8Array)||t.length<8)throw new Me("PBES2 Salt Input must be 8 or more octets");if(!Number.isSafeInteger(r)||Math.sign(r)!==1)throw new Me("PBES2 Count Input must be a positive integer");let i=Rrt(e,t),s=parseInt(e.slice(13,16),10),o={hash:`SHA-${e.slice(8,11)}`,iterations:r,name:"PBKDF2",salt:i},a=await krt(n,e);return new Uint8Array(await crypto.subtle.deriveBits(o,a,s))}async function dpe(t,e,r,n=2048,i=crypto.getRandomValues(new Uint8Array(16))){let s=await upe(i,t,n,e);return{encryptedKey:await x0(t.slice(-6),s,r),p2c:n,p2s:bn(i)}}async function ppe(t,e,r,n,i){let s=await upe(i,t,n,e);return I0(t.slice(-6),s,r)}var Rrt,fpe=I(()=>{Ys();RH();Fh();Vs();cn();Rrt=(t,e)=>fi(Bn(t),Uint8Array.of(0),e)});function A0(t,e){if(t.startsWith("RS")||t.startsWith("PS")){let{modulusLength:r}=e.algorithm;if(typeof r!="number"||r<2048)throw new TypeError(`${t} requires key modulusLength to be 2048 bits or larger`)}}function mpe(t,e){let r=`SHA-${t.slice(-3)}`;switch(t){case"HS256":case"HS384":case"HS512":return{hash:r,name:"HMAC"};case"PS256":case"PS384":case"PS512":return{hash:r,name:"RSA-PSS",saltLength:parseInt(t.slice(-3),10)>>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:e.namedCurve};case"Ed25519":case"EdDSA":return{name:"Ed25519"};case"ML-DSA-44":case"ML-DSA-65":case"ML-DSA-87":return{name:t};default:throw new Pt(`alg ${t} is not supported either by JOSE or your javascript runtime`)}}async function hpe(t,e,r){if(e instanceof Uint8Array){if(!t.startsWith("HS"))throw new TypeError(Wu(e,"CryptoKey","KeyObject","JSON Web Key"));return crypto.subtle.importKey("raw",e,{hash:`SHA-${t.slice(-3)}`,name:"HMAC"},!1,[r])}return Yde(e,t,r),e}async function gpe(t,e,r){let n=await hpe(t,e,"sign");A0(t,n);let i=await crypto.subtle.sign(mpe(t,n.algorithm),n,r);return new Uint8Array(i)}async function ype(t,e,r,n){let i=await hpe(t,e,"verify");A0(t,i);let s=mpe(t,i.algorithm);try{return await crypto.subtle.verify(s,i,r,n)}catch{return!1}}var nC=I(()=>{cn();Fh();rv()});async function vpe(t,e,r){return $a(e,t,"encrypt"),A0(t,e),new Uint8Array(await crypto.subtle.encrypt(bpe(t),e,r))}async function _pe(t,e,r){return $a(e,t,"decrypt"),A0(t,e),new Uint8Array(await crypto.subtle.decrypt(bpe(t),e,r))}var bpe,Epe=I(()=>{Fh();nC();cn();bpe=t=>{switch(t){case"RSA-OAEP":case"RSA-OAEP-256":case"RSA-OAEP-384":case"RSA-OAEP-512":return"RSA-OAEP";default:throw new Pt(`alg ${t} is not supported either by JOSE or your javascript runtime`)}}});function Prt(t){let e,r;switch(t.kty){case"AKP":{switch(t.alg){case"ML-DSA-44":case"ML-DSA-65":case"ML-DSA-87":e={name:t.alg},r=t.priv?["sign"]:["verify"];break;default:throw new Pt(iC)}break}case"RSA":{switch(t.alg){case"PS256":case"PS384":case"PS512":e={name:"RSA-PSS",hash:`SHA-${t.alg.slice(-3)}`},r=t.d?["sign"]:["verify"];break;case"RS256":case"RS384":case"RS512":e={name:"RSASSA-PKCS1-v1_5",hash:`SHA-${t.alg.slice(-3)}`},r=t.d?["sign"]:["verify"];break;case"RSA-OAEP":case"RSA-OAEP-256":case"RSA-OAEP-384":case"RSA-OAEP-512":e={name:"RSA-OAEP",hash:`SHA-${parseInt(t.alg.slice(-3),10)||1}`},r=t.d?["decrypt","unwrapKey"]:["encrypt","wrapKey"];break;default:throw new Pt(iC)}break}case"EC":{switch(t.alg){case"ES256":case"ES384":case"ES512":e={name:"ECDSA",namedCurve:{ES256:"P-256",ES384:"P-384",ES512:"P-521"}[t.alg]},r=t.d?["sign"]:["verify"];break;case"ECDH-ES":case"ECDH-ES+A128KW":case"ECDH-ES+A192KW":case"ECDH-ES+A256KW":e={name:"ECDH",namedCurve:t.crv},r=t.d?["deriveBits"]:[];break;default:throw new Pt(iC)}break}case"OKP":{switch(t.alg){case"Ed25519":case"EdDSA":e={name:"Ed25519"},r=t.d?["sign"]:["verify"];break;case"ECDH-ES":case"ECDH-ES+A128KW":case"ECDH-ES+A192KW":case"ECDH-ES+A256KW":e={name:t.crv},r=t.d?["deriveBits"]:[];break;default:throw new Pt(iC)}break}default:throw new Pt('Invalid or unsupported JWK "kty" (Key Type) Parameter value')}return{algorithm:e,keyUsages:r}}async function av(t){if(!t.alg)throw new TypeError('"alg" argument is required when "jwk.alg" is not present');let{algorithm:e,keyUsages:r}=Prt(t),n={...t};return n.kty!=="AKP"&&delete n.alg,delete n.use,crypto.subtle.importKey("jwk",n,e,t.ext??!(t.d||t.priv),t.key_ops??r)}var iC,DH=I(()=>{cn();iC='Invalid or unsupported JWK "alg" (Algorithm) Parameter value'});async function $u(t,e){if(t instanceof Uint8Array||ip(t))return t;if(w0(t)){if(t.type==="secret")return t.export();if("toCryptoKey"in t&&typeof t.toCryptoKey=="function")try{return Drt(t,e)}catch(n){if(n instanceof TypeError)throw n}let r=t.export({format:"jwk"});return Spe(t,r,e)}if(Wh(t))return t.k?_o(t.k):Spe(t,t,e,!0);throw new Error("unreachable")}var cv,lv,Spe,Drt,uv=I(()=>{Ss();Ys();DH();Hh();cv="given KeyObject instance cannot be used for this algorithm",Spe=async(t,e,r,n=!1)=>{lv||=new WeakMap;let i=lv.get(t);if(i?.[r])return i[r];let s=await av({...e,alg:r});return n&&Object.freeze(t),i?i[r]=s:lv.set(t,{[r]:s}),s},Drt=(t,e)=>{lv||=new WeakMap;let r=lv.get(t);if(r?.[e])return r[e];let n=t.type==="public",i=!!n,s;if(t.asymmetricKeyType==="x25519"){switch(e){case"ECDH-ES":case"ECDH-ES+A128KW":case"ECDH-ES+A192KW":case"ECDH-ES+A256KW":break;default:throw new TypeError(cv)}s=t.toCryptoKey(t.asymmetricKeyType,i,n?[]:["deriveBits"])}if(t.asymmetricKeyType==="ed25519"){if(e!=="EdDSA"&&e!=="Ed25519")throw new TypeError(cv);s=t.toCryptoKey(t.asymmetricKeyType,i,[n?"verify":"sign"])}switch(t.asymmetricKeyType){case"ml-dsa-44":case"ml-dsa-65":case"ml-dsa-87":{if(e!==t.asymmetricKeyType.toUpperCase())throw new TypeError(cv);s=t.toCryptoKey(t.asymmetricKeyType,i,[n?"verify":"sign"])}}if(t.asymmetricKeyType==="rsa"){let o;switch(e){case"RSA-OAEP":o="SHA-1";break;case"RS256":case"PS256":case"RSA-OAEP-256":o="SHA-256";break;case"RS384":case"PS384":case"RSA-OAEP-384":o="SHA-384";break;case"RS512":case"PS512":case"RSA-OAEP-512":o="SHA-512";break;default:throw new TypeError(cv)}if(e.startsWith("RSA-OAEP"))return t.toCryptoKey({name:"RSA-OAEP",hash:o},i,n?["encrypt"]:["decrypt"]);s=t.toCryptoKey({name:e.startsWith("PS")?"RSA-PSS":"RSASSA-PKCS1-v1_5",hash:o},i,[n?"verify":"sign"])}if(t.asymmetricKeyType==="ec"){let a=new Map([["prime256v1","P-256"],["secp384r1","P-384"],["secp521r1","P-521"]]).get(t.asymmetricKeyDetails?.namedCurve);if(!a)throw new TypeError(cv);let c={ES256:"P-256",ES384:"P-384",ES512:"P-521"};c[e]&&a===c[e]&&(s=t.toCryptoKey({name:"ECDSA",namedCurve:a},i,[n?"verify":"sign"])),e.startsWith("ECDH-ES")&&(s=t.toCryptoKey({name:"ECDH",namedCurve:a},i,n?[]:["deriveBits"]))}if(!s)throw new TypeError(cv);return r?r[e]=s:lv.set(t,{[e]:s}),s}});async function Ga(t,e,r){if(!vn(t))throw new TypeError("JWK must be an object");let n;switch(e??=t.alg,n??=r?.extractable??t.ext,t.kty){case"oct":if(typeof t.k!="string"||!t.k)throw new TypeError('missing "k" (Key Value) Parameter value');return _o(t.k);case"RSA":if("oth"in t&&t.oth!==void 0)throw new Pt('RSA JWK "oth" (Other Primes Info) Parameter value is not supported');return av({...t,alg:e,ext:n});case"AKP":{if(typeof t.alg!="string"||!t.alg)throw new TypeError('missing "alg" (Algorithm) Parameter value');if(e!==void 0&&e!==t.alg)throw new TypeError("JWK alg and alg option value mismatch");return av({...t,ext:n})}case"EC":case"OKP":return av({...t,alg:e,ext:n});default:throw new Pt('Unsupported "kty" (Key Type) Parameter value')}}var sC=I(()=>{Ys();DH();cn();Ss()});async function wpe(t){if(w0(t))if(t.type==="secret")t=t.export();else return t.export({format:"jwk"});if(t instanceof Uint8Array)return{kty:"oct",k:bn(t)};if(!ip(t))throw new TypeError(Wu(t,"CryptoKey","KeyObject","Uint8Array"));if(!t.extractable)throw new TypeError("non-extractable CryptoKey cannot be exported as a JWK");let{ext:e,key_ops:r,alg:n,use:i,...s}=await crypto.subtle.exportKey("jwk",t);return s.kty==="AKP"&&(s.alg=n),s}var Tpe=I(()=>{rv();Ys();Hh()});async function oC(t){return wpe(t)}var MH=I(()=>{Tpe()});async function xpe(t,e,r,n){let i=t.slice(0,7),s=await eC(i,r,e,n,new Uint8Array);return{encryptedKey:s.ciphertext,iv:bn(s.iv),tag:bn(s.tag)}}async function Ipe(t,e,r,n,i){let s=t.slice(0,7);return tC(s,e,r,n,i,new Uint8Array)}var Ape=I(()=>{ov();Ys()});function O0(t){if(t===void 0)throw new Me("JWE Encrypted Key missing")}async function kpe(t,e,r,n,i){switch(t){case"dir":{if(r!==void 0)throw new Me("Encountered unexpected JWE Encrypted Key");return e}case"ECDH-ES":if(r!==void 0)throw new Me("Encountered unexpected JWE Encrypted Key");case"ECDH-ES+A128KW":case"ECDH-ES+A192KW":case"ECDH-ES+A256KW":{if(!vn(n.epk))throw new Me('JOSE Header "epk" (Ephemeral Public Key) missing or invalid');if(sv(e),!PH(e))throw new Pt("ECDH with the provided key is not allowed or not supported by your javascript runtime");let s=await Ga(n.epk,t);sv(s);let o,a;if(n.apu!==void 0){if(typeof n.apu!="string")throw new Me('JOSE Header "apu" (Agreement PartyUInfo) invalid');o=wo(n.apu,"apu",Me)}if(n.apv!==void 0){if(typeof n.apv!="string")throw new Me('JOSE Header "apv" (Agreement PartyVInfo) invalid');a=wo(n.apv,"apv",Me)}let c=await NH(s,e,t==="ECDH-ES"?n.enc:t,t==="ECDH-ES"?QR(n.enc):parseInt(t.slice(-5,-2),10),o,a);return t==="ECDH-ES"?c:(O0(r),I0(t.slice(-6),c,r))}case"RSA-OAEP":case"RSA-OAEP-256":case"RSA-OAEP-384":case"RSA-OAEP-512":return O0(r),sv(e),_pe(t,e,r);case"PBES2-HS256+A128KW":case"PBES2-HS384+A192KW":case"PBES2-HS512+A256KW":{if(O0(r),typeof n.p2c!="number")throw new Me('JOSE Header "p2c" (PBES2 Count) missing or invalid');let s=i?.maxPBES2Count||1e4;if(n.p2c>s)throw new Me('JOSE Header "p2c" (PBES2 Count) out is of acceptable bounds');if(typeof n.p2s!="string")throw new Me('JOSE Header "p2s" (PBES2 Salt) missing or invalid');let o;return o=wo(n.p2s,"p2s",Me),ppe(t,e,r,n.p2c,o)}case"A128KW":case"A192KW":case"A256KW":return O0(r),I0(t,e,r);case"A128GCMKW":case"A192GCMKW":case"A256GCMKW":{if(O0(r),typeof n.iv!="string")throw new Me('JOSE Header "iv" (Initialization Vector) missing or invalid');if(typeof n.tag!="string")throw new Me('JOSE Header "tag" (Authentication Tag) missing or invalid');let s;s=wo(n.iv,"iv",Me);let o;return o=wo(n.tag,"tag",Me),Ipe(t,e,r,s,o)}default:throw new Pt(Ope)}}async function Rpe(t,e,r,n,i={}){let s,o,a;switch(t){case"dir":{a=r;break}case"ECDH-ES":case"ECDH-ES+A128KW":case"ECDH-ES+A192KW":case"ECDH-ES+A256KW":{if(sv(r),!PH(r))throw new Pt("ECDH with the provided key is not allowed or not supported by your javascript runtime");let{apu:c,apv:l}=i,u;i.epk?u=await $u(i.epk,t):u=(await crypto.subtle.generateKey(r.algorithm,!0,["deriveBits"])).privateKey;let{x:d,y:p,crv:f,kty:m}=await oC(u),h=await NH(r,u,t==="ECDH-ES"?e:t,t==="ECDH-ES"?QR(e):parseInt(t.slice(-5,-2),10),c,l);if(o={epk:{x:d,crv:f,kty:m}},m==="EC"&&(o.epk.y=p),c&&(o.apu=bn(c)),l&&(o.apv=bn(l)),t==="ECDH-ES"){a=h;break}a=n||Rf(e);let y=t.slice(-6);s=await x0(y,h,a);break}case"RSA-OAEP":case"RSA-OAEP-256":case"RSA-OAEP-384":case"RSA-OAEP-512":{a=n||Rf(e),sv(r),s=await vpe(t,r,a);break}case"PBES2-HS256+A128KW":case"PBES2-HS384+A192KW":case"PBES2-HS512+A256KW":{a=n||Rf(e);let{p2c:c,p2s:l}=i;({encryptedKey:s,...o}=await dpe(t,r,a,c,l));break}case"A128KW":case"A192KW":case"A256KW":{a=n||Rf(e),s=await x0(t,r,a);break}case"A128GCMKW":case"A192GCMKW":case"A256GCMKW":{a=n||Rf(e);let{iv:c}=i;({encryptedKey:s,...o}=await xpe(t,r,a,c));break}default:throw new Pt(Ope)}return{cek:a,encryptedKey:s,parameters:o}}var Ope,LH=I(()=>{RH();lpe();fpe();Epe();Ys();uv();cn();sp();ov();sC();MH();Ss();Ape();Hh();Ope='Invalid or unsupported "alg" (JWE Algorithm) header value'});function Nf(t,e,r,n,i){if(i.crit!==void 0&&n?.crit===void 0)throw new t('"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(o=>typeof o!="string"||o.length===0))throw new t('"crit" (Critical) Header Parameter MUST be an array of non-empty strings when present');let s;r!==void 0?s=new Map([...Object.entries(r),...e.entries()]):s=e;for(let o of n.crit){if(!s.has(o))throw new Pt(`Extension Header Parameter "${o}" is not recognized`);if(i[o]===void 0)throw new t(`Extension Header Parameter "${o}" is missing`);if(s.get(o)&&n[o]===void 0)throw new t(`Extension Header Parameter "${o}" MUST be integrity protected`)}return new Set(n.crit)}var k0=I(()=>{cn()});function R0(t,e){if(e!==void 0&&(!Array.isArray(e)||e.some(r=>typeof r!="string")))throw new TypeError(`"${t}" option must be an array of strings`);if(e)return new Set(e)}var jH=I(()=>{});function Pf(t,e,r){switch(t.substring(0,2)){case"A1":case"A2":case"di":case"HS":case"PB":Mrt(t,e,r);break;default:Lrt(t,e,r)}}var dv,UH,Mrt,Lrt,C0=I(()=>{rv();Hh();Ss();dv=t=>t?.[Symbol.toStringTag],UH=(t,e,r)=>{if(e.use!==void 0){let n;switch(r){case"sign":case"verify":n="sig";break;case"encrypt":case"decrypt":n="enc";break}if(e.use!==n)throw new TypeError(`Invalid key for this operation, its "use" must be "${n}" when present`)}if(e.alg!==void 0&&e.alg!==t)throw new TypeError(`Invalid key for this operation, its "alg" must be "${t}" when present`);if(Array.isArray(e.key_ops)){let n;switch(!0){case(r==="sign"||r==="verify"):case t==="dir":case t.includes("CBC-HS"):n=r;break;case t.startsWith("PBES2"):n="deriveBits";break;case/^A\d{3}(?:GCM)?(?:KW)?$/.test(t):!t.includes("GCM")&&t.endsWith("KW")?n=r==="encrypt"?"wrapKey":"unwrapKey":n=r;break;case(r==="encrypt"&&t.startsWith("RSA")):n="wrapKey";break;case r==="decrypt":n=t.startsWith("RSA")?"unwrapKey":"deriveBits";break}if(n&&e.key_ops?.includes?.(n)===!1)throw new TypeError(`Invalid key for this operation, its "key_ops" must include "${n}" when present`)}return!0},Mrt=(t,e,r)=>{if(!(e instanceof Uint8Array)){if(Wh(e)){if(spe(e)&&UH(t,e,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(!T0(e))throw new TypeError(kH(t,e,"CryptoKey","KeyObject","JSON Web Key","Uint8Array"));if(e.type!=="secret")throw new TypeError(`${dv(e)} instances for symmetric algorithms must be of type "secret"`)}},Lrt=(t,e,r)=>{if(Wh(e))switch(r){case"decrypt":case"sign":if(npe(e)&&UH(t,e,r))return;throw new TypeError("JSON Web Key for this operation must be a private JWK");case"encrypt":case"verify":if(ipe(e)&&UH(t,e,r))return;throw new TypeError("JSON Web Key for this operation must be a public JWK")}if(!T0(e))throw new TypeError(kH(t,e,"CryptoKey","KeyObject","JSON Web Key"));if(e.type==="secret")throw new TypeError(`${dv(e)} instances for asymmetric algorithms must not be of type "secret"`);if(e.type==="public")switch(r){case"sign":throw new TypeError(`${dv(e)} instances for asymmetric algorithm signing must be of type "private"`);case"decrypt":throw new TypeError(`${dv(e)} instances for asymmetric algorithm decryption must be of type "private"`)}if(e.type==="private")switch(r){case"verify":throw new TypeError(`${dv(e)} instances for asymmetric algorithm verifying must be of type "public"`);case"encrypt":throw new TypeError(`${dv(e)} instances for asymmetric algorithm encryption must be of type "public"`)}}});function Cpe(t){if(typeof globalThis[t]>"u")throw new Pt(`JWE "zip" (Compression Algorithm) Header Parameter requires the ${t} API.`)}async function Npe(t){Cpe("CompressionStream");let e=new CompressionStream("deflate-raw"),r=e.writable.getWriter();r.write(t).catch(()=>{}),r.close().catch(()=>{});let n=[],i=e.readable.getReader();for(;;){let{value:s,done:o}=await i.read();if(o)break;n.push(s)}return fi(...n)}async function Ppe(t,e){Cpe("DecompressionStream");let r=new DecompressionStream("deflate-raw"),n=r.writable.getWriter();n.write(t).catch(()=>{}),n.close().catch(()=>{});let i=[],s=0,o=r.readable.getReader();for(;;){let{value:a,done:c}=await o.read();if(c)break;if(i.push(a),s+=a.byteLength,e!==1/0&&s>e)throw new Me("Decompressed plaintext exceeded the configured limit")}return fi(...i)}var KH=I(()=>{cn();Vs()});async function Dpe(t,e,r){if(!vn(t))throw new Me("Flattened JWE must be an object");if(t.protected===void 0&&t.header===void 0&&t.unprotected===void 0)throw new Me("JOSE Header missing");if(t.iv!==void 0&&typeof t.iv!="string")throw new Me("JWE Initialization Vector incorrect type");if(typeof t.ciphertext!="string")throw new Me("JWE Ciphertext missing or incorrect type");if(t.tag!==void 0&&typeof t.tag!="string")throw new Me("JWE Authentication Tag incorrect type");if(t.protected!==void 0&&typeof t.protected!="string")throw new Me("JWE Protected Header incorrect type");if(t.encrypted_key!==void 0&&typeof t.encrypted_key!="string")throw new Me("JWE Encrypted Key incorrect type");if(t.aad!==void 0&&typeof t.aad!="string")throw new Me("JWE AAD incorrect type");if(t.header!==void 0&&!vn(t.header))throw new Me("JWE Shared Unprotected Header incorrect type");if(t.unprotected!==void 0&&!vn(t.unprotected))throw new Me("JWE Per-Recipient Unprotected Header incorrect type");let n;if(t.protected)try{let _=_o(t.protected);n=JSON.parse(_s.decode(_))}catch{throw new Me("JWE Protected Header is invalid")}if(!Cf(n,t.header,t.unprotected))throw new Me("JWE Protected, JWE Unprotected Header, and JWE Per-Recipient Unprotected Header Parameter names must be disjoint");let i={...n,...t.header,...t.unprotected};if(Nf(Me,new Map,r?.crit,n,i),i.zip!==void 0&&i.zip!=="DEF")throw new Pt('Unsupported JWE "zip" (Compression Algorithm) Header Parameter value.');if(i.zip!==void 0&&!n?.zip)throw new Me('JWE "zip" (Compression Algorithm) Header Parameter MUST be in a protected header.');let{alg:s,enc:o}=i;if(typeof s!="string"||!s)throw new Me("missing JWE Algorithm (alg) in JWE Header");if(typeof o!="string"||!o)throw new Me("missing JWE Encryption Algorithm (enc) in JWE Header");let a=r&&R0("keyManagementAlgorithms",r.keyManagementAlgorithms),c=r&&R0("contentEncryptionAlgorithms",r.contentEncryptionAlgorithms);if(a&&!a.has(s)||!a&&s.startsWith("PBES2"))throw new Bh('"alg" (Algorithm) Header Parameter value not allowed');if(c&&!c.has(o))throw new Bh('"enc" (Encryption Algorithm) Header Parameter value not allowed');let l;t.encrypted_key!==void 0&&(l=wo(t.encrypted_key,"encrypted_key",Me));let u=!1;typeof e=="function"&&(e=await e(n,t),u=!0),Pf(s==="dir"?o:s,e,"decrypt");let d=await $u(e,s),p;try{p=await kpe(s,d,l,i,r)}catch(_){if(_ instanceof TypeError||_ instanceof Me||_ instanceof Pt)throw _;p=Rf(o)}let f,m;t.iv!==void 0&&(f=wo(t.iv,"iv",Me)),t.tag!==void 0&&(m=wo(t.tag,"tag",Me));let h=t.protected!==void 0?Bn(t.protected):new Uint8Array,y;t.aad!==void 0?y=fi(h,Bn("."),Bn(t.aad)):y=h;let g=wo(t.ciphertext,"ciphertext",Me),b=await tC(o,p,g,f,m,y),v={plaintext:b};if(i.zip==="DEF"){let _=r?.maxDecompressedLength??25e4;if(_===0)throw new Pt('JWE "zip" (Compression Algorithm) Header Parameter is not supported.');if(_!==1/0&&(!Number.isSafeInteger(_)||_<1))throw new TypeError("maxDecompressedLength must be 0, a positive safe integer, or Infinity");v.plaintext=await Ppe(b,_).catch(w=>{throw w instanceof Me?w:new Me("Failed to decompress plaintext",{cause:w})})}return t.protected!==void 0&&(v.protectedHeader=n),t.aad!==void 0&&(v.additionalAuthenticatedData=wo(t.aad,"aad",Me)),t.unprotected!==void 0&&(v.sharedUnprotectedHeader=t.unprotected),t.header!==void 0&&(v.unprotectedHeader=t.header),u?{...v,key:d}:v}var Mpe=I(()=>{Ys();ov();sp();cn();Ss();Ss();LH();Vs();ov();k0();jH();uv();C0();KH()});async function Lpe(t,e,r){if(t instanceof Uint8Array&&(t=_s.decode(t)),typeof t!="string")throw new Me("Compact JWE must be a string or Uint8Array");let{0:n,1:i,2:s,3:o,4:a,length:c}=t.split(".");if(c!==5)throw new Me("Invalid Compact JWE");let l=await Dpe({ciphertext:o,iv:s||void 0,protected:n,tag:a||void 0,encrypted_key:i||void 0},e,r),u={plaintext:l.plaintext,protectedHeader:l.protectedHeader};return typeof e=="function"?{...u,key:l.key}:u}var jpe=I(()=>{Mpe();cn();Vs()});var aC,Upe=I(()=>{Ys();sp();ov();LH();cn();Ss();Vs();k0();uv();C0();KH();aC=class{#e;#t;#r;#n;#i;#p;#u;#a;constructor(e){if(!(e instanceof Uint8Array))throw new TypeError("plaintext must be an instance of Uint8Array");this.#e=e}setKeyManagementParameters(e){return So(this.#a,"setKeyManagementParameters"),this.#a=e,this}setProtectedHeader(e){return So(this.#t,"setProtectedHeader"),this.#t=e,this}setSharedUnprotectedHeader(e){return So(this.#r,"setSharedUnprotectedHeader"),this.#r=e,this}setUnprotectedHeader(e){return So(this.#n,"setUnprotectedHeader"),this.#n=e,this}setAdditionalAuthenticatedData(e){return this.#i=e,this}setContentEncryptionKey(e){return So(this.#p,"setContentEncryptionKey"),this.#p=e,this}setInitializationVector(e){return So(this.#u,"setInitializationVector"),this.#u=e,this}async encrypt(e,r){if(!this.#t&&!this.#n&&!this.#r)throw new Me("either setProtectedHeader, setUnprotectedHeader, or sharedUnprotectedHeader must be called before #encrypt()");if(!Cf(this.#t,this.#n,this.#r))throw new Me("JWE Protected, JWE Shared Unprotected and JWE Per-Recipient Header Parameter names must be disjoint");let n={...this.#t,...this.#n,...this.#r};if(Nf(Me,new Map,r?.crit,this.#t,n),n.zip!==void 0&&n.zip!=="DEF")throw new Pt('Unsupported JWE "zip" (Compression Algorithm) Header Parameter value.');if(n.zip!==void 0&&!this.#t?.zip)throw new Me('JWE "zip" (Compression Algorithm) Header Parameter MUST be in a protected header.');let{alg:i,enc:s}=n;if(typeof i!="string"||!i)throw new Me('JWE "alg" (Algorithm) Header Parameter missing or invalid');if(typeof s!="string"||!s)throw new Me('JWE "enc" (Encryption Algorithm) Header Parameter missing or invalid');let o;if(this.#p&&(i==="dir"||i==="ECDH-ES"))throw new TypeError(`setContentEncryptionKey cannot be called with JWE "alg" (Algorithm) Header ${i}`);Pf(i==="dir"?s:i,e,"encrypt");let a;{let g,b=await $u(e,i);({cek:a,encryptedKey:o,parameters:g}=await Rpe(i,s,b,this.#p,this.#a)),g&&(r&&rpe in r?this.#n?this.#n={...this.#n,...g}:this.setUnprotectedHeader(g):this.#t?this.#t={...this.#t,...g}:this.setProtectedHeader(g))}let c,l,u,d;if(this.#t?(l=bn(JSON.stringify(this.#t)),u=Bn(l)):(l="",u=new Uint8Array),this.#i){d=bn(this.#i);let g=Bn(d);c=fi(u,Bn("."),g)}else c=u;let p=this.#e;n.zip==="DEF"&&(p=await Npe(p).catch(g=>{throw new Me("Failed to compress plaintext",{cause:g})}));let{ciphertext:f,tag:m,iv:h}=await eC(s,p,a,this.#u,c),y={ciphertext:bn(f)};return h&&(y.iv=bn(h)),m&&(y.tag=bn(m)),o&&(y.encrypted_key=bn(o)),d&&(y.aad=d),this.#t&&(y.protected=l),this.#r&&(y.unprotected=this.#r),this.#n&&(y.header=this.#n),y}}});async function Kpe(t,e,r){if(!vn(t))throw new zr("Flattened JWS must be an object");if(t.protected===void 0&&t.header===void 0)throw new zr('Flattened JWS must have either of the "protected" or "header" members');if(t.protected!==void 0&&typeof t.protected!="string")throw new zr("JWS Protected Header incorrect type");if(t.payload===void 0)throw new zr("JWS Payload missing");if(typeof t.signature!="string")throw new zr("JWS Signature missing or incorrect type");if(t.header!==void 0&&!vn(t.header))throw new zr("JWS Unprotected Header incorrect type");let n={};if(t.protected)try{let y=_o(t.protected);n=JSON.parse(_s.decode(y))}catch{throw new zr("JWS Protected Header is invalid")}if(!Cf(n,t.header))throw new zr("JWS Protected and JWS Unprotected Header Parameter names must be disjoint");let i={...n,...t.header},s=Nf(zr,new Map([["b64",!0]]),r?.crit,n,i),o=!0;if(s.has("b64")&&(o=n.b64,typeof o!="boolean"))throw new zr('The "b64" (base64url-encode payload) Header Parameter must be a boolean');let{alg:a}=i;if(typeof a!="string"||!a)throw new zr('JWS "alg" (Algorithm) Header Parameter missing or invalid');let c=r&&R0("algorithms",r.algorithms);if(c&&!c.has(a))throw new Bh('"alg" (Algorithm) Header Parameter value not allowed');if(o){if(typeof t.payload!="string")throw new zr("JWS Payload must be a string")}else if(typeof t.payload!="string"&&!(t.payload instanceof Uint8Array))throw new zr("JWS Payload must be a string or an Uint8Array instance");let l=!1;typeof e=="function"&&(e=await e(n,t),l=!0),Pf(a,e,"verify");let u=fi(t.protected!==void 0?Bn(t.protected):new Uint8Array,Bn("."),typeof t.payload=="string"?o?Bn(t.payload):qh.encode(t.payload):t.payload),d=wo(t.signature,"signature",zr),p=await $u(e,a);if(!await ype(a,p,d,u))throw new ZR;let m;o?m=wo(t.payload,"payload",zr):typeof t.payload=="string"?m=qh.encode(t.payload):m=t.payload;let h={payload:m};return t.protected!==void 0&&(h.protectedHeader=n),t.header!==void 0&&(h.unprotectedHeader=t.header),l?{...h,key:p}:h}var qpe=I(()=>{Ys();nC();cn();Vs();sp();Ss();Ss();C0();k0();jH();uv()});async function Fpe(t,e,r){if(t instanceof Uint8Array&&(t=_s.decode(t)),typeof t!="string")throw new zr("Compact JWS must be a string or Uint8Array");let{0:n,1:i,2:s,length:o}=t.split(".");if(o!==3)throw new zr("Invalid Compact JWS");let a=await Kpe({payload:i,protected:n,signature:s},e,r),c={payload:a.payload,protectedHeader:a.protectedHeader};return typeof e=="function"?{...c,key:a.key}:c}var zpe=I(()=>{qpe();cn();Vs()});function N0(t){let e=Krt.exec(t);if(!e||e[4]&&e[1])throw new TypeError("Invalid time period format");let r=parseFloat(e[2]),n=e[3].toLowerCase(),i;switch(n){case"sec":case"secs":case"second":case"seconds":case"s":i=Math.round(r);break;case"minute":case"minutes":case"min":case"mins":case"m":i=Math.round(r*Hpe);break;case"hour":case"hours":case"hr":case"hrs":case"h":i=Math.round(r*Wpe);break;case"day":case"days":case"d":i=Math.round(r*qH);break;case"week":case"weeks":case"w":i=Math.round(r*jrt);break;default:i=Math.round(r*Urt);break}return e[1]==="-"||e[4]==="ago"?-i:i}function $h(t,e){if(!Number.isFinite(e))throw new TypeError(`Invalid ${t} input`);return e}function cC(t,e,r={}){let n;try{n=JSON.parse(_s.decode(e))}catch{}if(!vn(n))throw new Js("JWT Claims Set must be a top-level JSON object");let{typ:i}=r;if(i&&(typeof t.typ!="string"||Bpe(t.typ)!==Bpe(i)))throw new Es('unexpected "typ" JWT header value',n,"typ","check_failed");let{requiredClaims:s=[],issuer:o,subject:a,audience:c,maxTokenAge:l}=r,u=[...s];l!==void 0&&u.push("iat"),c!==void 0&&u.push("aud"),a!==void 0&&u.push("sub"),o!==void 0&&u.push("iss");for(let m of new Set(u.reverse()))if(!(m in n))throw new Es(`missing required "${m}" claim`,n,m,"missing");if(o&&!(Array.isArray(o)?o:[o]).includes(n.iss))throw new Es('unexpected "iss" claim value',n,"iss","check_failed");if(a&&n.sub!==a)throw new Es('unexpected "sub" claim value',n,"sub","check_failed");if(c&&!qrt(n.aud,typeof c=="string"?[c]:c))throw new Es('unexpected "aud" claim value',n,"aud","check_failed");let d;switch(typeof r.clockTolerance){case"string":d=N0(r.clockTolerance);break;case"number":d=r.clockTolerance;break;case"undefined":d=0;break;default:throw new TypeError("Invalid clockTolerance option type")}let{currentDate:p}=r,f=Df(p||new Date);if((n.iat!==void 0||l)&&typeof n.iat!="number")throw new Es('"iat" claim must be a number',n,"iat","invalid");if(n.nbf!==void 0){if(typeof n.nbf!="number")throw new Es('"nbf" claim must be a number',n,"nbf","invalid");if(n.nbf>f+d)throw new Es('"nbf" claim timestamp check failed',n,"nbf","check_failed")}if(n.exp!==void 0){if(typeof n.exp!="number")throw new Es('"exp" claim must be a number',n,"exp","invalid");if(n.exp<=f-d)throw new zh('"exp" claim timestamp check failed',n,"exp","check_failed")}if(l){let m=f-n.iat,h=typeof l=="number"?l:N0(l);if(m-d>h)throw new zh('"iat" claim timestamp check failed (too far in the past)',n,"iat","check_failed");if(m<0-d)throw new Es('"iat" claim timestamp check failed (it should be in the past)',n,"iat","check_failed")}return n}var Df,Hpe,Wpe,qH,jrt,Urt,Krt,Bpe,qrt,pv,P0=I(()=>{cn();Vs();Ss();Df=t=>Math.floor(t.getTime()/1e3),Hpe=60,Wpe=Hpe*60,qH=Wpe*24,jrt=qH*7,Urt=qH*365.25,Krt=/^(\+|\-)? ?(\d+|\d+\.\d+) ?(seconds?|secs?|s|minutes?|mins?|m|hours?|hrs?|h|days?|d|weeks?|w|years?|yrs?|y)(?: (ago|from now))?$/i;Bpe=t=>t.includes("/")?t.toLowerCase():`application/${t.toLowerCase()}`,qrt=(t,e)=>typeof t=="string"?e.includes(t):Array.isArray(t)?e.some(Set.prototype.has.bind(new Set(t))):!1;pv=class{#e;constructor(e){if(!vn(e))throw new TypeError("JWT Claims Set MUST be an object");this.#e=structuredClone(e)}data(){return qh.encode(JSON.stringify(this.#e))}get iss(){return this.#e.iss}set iss(e){this.#e.iss=e}get sub(){return this.#e.sub}set sub(e){this.#e.sub=e}get aud(){return this.#e.aud}set aud(e){this.#e.aud=e}set jti(e){this.#e.jti=e}set nbf(e){typeof e=="number"?this.#e.nbf=$h("setNotBefore",e):e instanceof Date?this.#e.nbf=$h("setNotBefore",Df(e)):this.#e.nbf=Df(new Date)+N0(e)}set exp(e){typeof e=="number"?this.#e.exp=$h("setExpirationTime",e):e instanceof Date?this.#e.exp=$h("setExpirationTime",Df(e)):this.#e.exp=Df(new Date)+N0(e)}set iat(e){e===void 0?this.#e.iat=Df(new Date):e instanceof Date?this.#e.iat=$h("setIssuedAt",Df(e)):typeof e=="string"?this.#e.iat=$h("setIssuedAt",Df(new Date)+N0(e)):this.#e.iat=$h("setIssuedAt",e)}}});async function To(t,e,r){let n=await Fpe(t,e,r);if(n.protectedHeader.crit?.includes("b64")&&n.protectedHeader.b64===!1)throw new Js("JWTs MUST NOT use unencoded payload");let s={payload:cC(n.protectedHeader,n.payload,r),protectedHeader:n.protectedHeader};return typeof e=="function"?{...s,key:n.key}:s}var $pe=I(()=>{zpe();P0();cn()});async function lC(t,e,r){let n=await Lpe(t,e,r),i=cC(n.protectedHeader,n.plaintext,r),{protectedHeader:s}=n;if(s.iss!==void 0&&s.iss!==i.iss)throw new Es('replicated "iss" claim header parameter mismatch',i,"iss","mismatch");if(s.sub!==void 0&&s.sub!==i.sub)throw new Es('replicated "sub" claim header parameter mismatch',i,"sub","mismatch");if(s.aud!==void 0&&JSON.stringify(s.aud)!==JSON.stringify(i.aud))throw new Es('replicated "aud" claim header parameter mismatch',i,"aud","mismatch");let o={payload:i,protectedHeader:s};return typeof e=="function"?{...o,key:n.key}:o}var Gpe=I(()=>{jpe();P0();cn()});var uC,Vpe=I(()=>{Upe();uC=class{#e;constructor(e){this.#e=new aC(e)}setContentEncryptionKey(e){return this.#e.setContentEncryptionKey(e),this}setInitializationVector(e){return this.#e.setInitializationVector(e),this}setProtectedHeader(e){return this.#e.setProtectedHeader(e),this}setKeyManagementParameters(e){return this.#e.setKeyManagementParameters(e),this}async encrypt(e,r){let n=await this.#e.encrypt(e,r);return[n.protected,n.encrypted_key,n.iv,n.ciphertext,n.tag].join(".")}}});var dC,Ype=I(()=>{Ys();nC();Ss();cn();Vs();C0();k0();uv();sp();dC=class{#e;#t;#r;constructor(e){if(!(e instanceof Uint8Array))throw new TypeError("payload must be an instance of Uint8Array");this.#e=e}setProtectedHeader(e){return So(this.#t,"setProtectedHeader"),this.#t=e,this}setUnprotectedHeader(e){return So(this.#r,"setUnprotectedHeader"),this.#r=e,this}async sign(e,r){if(!this.#t&&!this.#r)throw new zr("either setProtectedHeader or setUnprotectedHeader must be called before #sign()");if(!Cf(this.#t,this.#r))throw new zr("JWS Protected and JWS Unprotected Header Parameter names must be disjoint");let n={...this.#t,...this.#r},i=Nf(zr,new Map([["b64",!0]]),r?.crit,this.#t,n),s=!0;if(i.has("b64")&&(s=this.#t.b64,typeof s!="boolean"))throw new zr('The "b64" (base64url-encode payload) Header Parameter must be a boolean');let{alg:o}=n;if(typeof o!="string"||!o)throw new zr('JWS "alg" (Algorithm) Header Parameter missing or invalid');Pf(o,e,"sign");let a,c;s?(a=bn(this.#e),c=Bn(a)):(c=this.#e,a="");let l,u;this.#t?(l=bn(JSON.stringify(this.#t)),u=Bn(l)):(l="",u=new Uint8Array);let d=fi(u,Bn("."),c),p=await $u(e,o),f=await gpe(o,p,d),m={signature:bn(f),payload:a};return this.#r&&(m.header=this.#r),this.#t&&(m.protected=l),m}}});var pC,Jpe=I(()=>{Ype();pC=class{#e;constructor(e){this.#e=new dC(e)}setProtectedHeader(e){return this.#e.setProtectedHeader(e),this}async sign(e,r){let n=await this.#e.sign(e,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 D0,Zpe=I(()=>{Jpe();cn();P0();D0=class{#e;#t;constructor(e={}){this.#t=new pv(e)}setIssuer(e){return this.#t.iss=e,this}setSubject(e){return this.#t.sub=e,this}setAudience(e){return this.#t.aud=e,this}setJti(e){return this.#t.jti=e,this}setNotBefore(e){return this.#t.nbf=e,this}setExpirationTime(e){return this.#t.exp=e,this}setIssuedAt(e){return this.#t.iat=e,this}setProtectedHeader(e){return this.#e=e,this}async sign(e,r){let n=new pC(this.#t.data());if(n.setProtectedHeader(this.#e),Array.isArray(this.#e?.crit)&&this.#e.crit.includes("b64")&&this.#e.b64===!1)throw new Js("JWTs MUST NOT use unencoded payload");return n.sign(e,r)}}});var M0,Xpe=I(()=>{Vpe();P0();sp();M0=class{#e;#t;#r;#n;#i;#p;#u;#a;constructor(e={}){this.#a=new pv(e)}setIssuer(e){return this.#a.iss=e,this}setSubject(e){return this.#a.sub=e,this}setAudience(e){return this.#a.aud=e,this}setJti(e){return this.#a.jti=e,this}setNotBefore(e){return this.#a.nbf=e,this}setExpirationTime(e){return this.#a.exp=e,this}setIssuedAt(e){return this.#a.iat=e,this}setProtectedHeader(e){return So(this.#n,"setProtectedHeader"),this.#n=e,this}setKeyManagementParameters(e){return So(this.#r,"setKeyManagementParameters"),this.#r=e,this}setContentEncryptionKey(e){return So(this.#e,"setContentEncryptionKey"),this.#e=e,this}setInitializationVector(e){return So(this.#t,"setInitializationVector"),this.#t=e,this}replicateIssuerAsHeader(){return this.#i=!0,this}replicateSubjectAsHeader(){return this.#p=!0,this}replicateAudienceAsHeader(){return this.#u=!0,this}async encrypt(e,r){let n=new uC(this.#a.data());return this.#n&&(this.#i||this.#p||this.#u)&&(this.#n={...this.#n,iss:this.#i?this.#a.iss:void 0,sub:this.#p?this.#a.sub:void 0,aud:this.#u?this.#a.aud:void 0}),n.setProtectedHeader(this.#n),this.#t&&n.setInitializationVector(this.#t),this.#e&&n.setContentEncryptionKey(this.#e),this.#r&&n.setKeyManagementParameters(this.#r),n.encrypt(e,r)}}});async function fC(t,e){let r;if(Wh(t))r=t;else if(T0(t))r=await oC(t);else throw new TypeError(Wu(t,"CryptoKey","KeyObject","JSON Web Key"));if(e??="sha256",e!=="sha256"&&e!=="sha384"&&e!=="sha512")throw new TypeError('digestAlgorithm must one of "sha256", "sha384", or "sha512"');let n;switch(r.kty){case"AKP":Gu(r.alg,'"alg" (Algorithm) Parameter'),Gu(r.pub,'"pub" (Public key) Parameter'),n={alg:r.alg,kty:r.kty,pub:r.pub};break;case"EC":Gu(r.crv,'"crv" (Curve) Parameter'),Gu(r.x,'"x" (X Coordinate) Parameter'),Gu(r.y,'"y" (Y Coordinate) Parameter'),n={crv:r.crv,kty:r.kty,x:r.x,y:r.y};break;case"OKP":Gu(r.crv,'"crv" (Subtype of Key Pair) Parameter'),Gu(r.x,'"x" (Public Key) Parameter'),n={crv:r.crv,kty:r.kty,x:r.x};break;case"RSA":Gu(r.e,'"e" (Exponent) Parameter'),Gu(r.n,'"n" (Modulus) Parameter'),n={e:r.e,kty:r.kty,n:r.n};break;case"oct":Gu(r.k,'"k" (Key Value) Parameter'),n={k:r.k,kty:r.kty};break;default:throw new Pt('"kty" (Key Type) Parameter missing or unsupported')}let i=Bn(JSON.stringify(n));return bn(await rC(e,i))}var Gu,Qpe=I(()=>{sp();Ys();cn();Vs();Hh();Ss();MH();rv();Gu=(t,e)=>{if(typeof t!="string"||!t)throw new VR(`${e} missing or invalid`)}});function Frt(t){switch(typeof t=="string"&&t.slice(0,2)){case"RS":case"PS":return"RSA";case"ES":return"EC";case"Ed":return"OKP";case"ML":return"AKP";default:throw new Pt('Unsupported "alg" value for a JSON Web Key Set')}}function zrt(t){return t&&typeof t=="object"&&Array.isArray(t.keys)&&t.keys.every(Brt)}function Brt(t){return vn(t)}async function efe(t,e,r){let n=t.get(e)||t.set(e,{}).get(e);if(n[r]===void 0){let i=await Ga({...e,ext:!0},r);if(i instanceof Uint8Array||i.type!=="public")throw new S0("JSON Web Key Set members must be public keys");n[r]=i}return n[r]}function zH(t){let e=new FH(t),r=async(n,i)=>e.getKey(n,i);return Object.defineProperties(r,{jwks:{value:()=>structuredClone(e.jwks()),enumerable:!1,configurable:!1,writable:!1}}),r}var FH,tfe=I(()=>{sC();cn();Ss();FH=class{#e;#t=new WeakMap;constructor(e){if(!zrt(e))throw new S0("JSON Web Key Set malformed");this.#e=structuredClone(e)}jwks(){return this.#e}async getKey(e,r){let{alg:n,kid:i}={...e,...r?.header},s=Frt(n),o=this.#e.keys.filter(l=>{let u=s===l.kty;if(u&&typeof i=="string"&&(u=i===l.kid),u&&(typeof l.alg=="string"||s==="AKP")&&(u=n===l.alg),u&&typeof l.use=="string"&&(u=l.use==="sig"),u&&Array.isArray(l.key_ops)&&(u=l.key_ops.includes("verify")),u)switch(n){case"ES256":u=l.crv==="P-256";break;case"ES384":u=l.crv==="P-384";break;case"ES512":u=l.crv==="P-521";break;case"Ed25519":case"EdDSA":u=l.crv==="Ed25519";break}return u}),{0:a,length:c}=o;if(c===0)throw new iv;if(c!==1){let l=new YR,u=this.#t;throw l[Symbol.asyncIterator]=async function*(){for(let d of o)try{yield await efe(u,d,n)}catch{}},l}return efe(this.#t,a,n)}}});function Hrt(){return typeof WebSocketPair<"u"||typeof navigator<"u"&&navigator.userAgent==="Cloudflare-Workers"||typeof EdgeRuntime<"u"&&EdgeRuntime==="vercel"}async function Wrt(t,e,r,n=fetch){let i=await n(t,{method:"GET",signal:r,redirect:"manual",headers:e}).catch(s=>{throw s.name==="TimeoutError"?new JR:s});if(i.status!==200)throw new Si("Expected 200 OK from the JSON Web Key Set HTTP response");try{return await i.json()}catch{throw new Si("Failed to parse the JSON Web Key Set HTTP response as JSON")}}function $rt(t,e){return!(typeof t!="object"||t===null||!("uat"in t)||typeof t.uat!="number"||Date.now()-t.uat>=e||!("jwks"in t)||!vn(t.jwks)||!Array.isArray(t.jwks.keys)||!Array.prototype.every.call(t.jwks.keys,vn))}function WH(t,e){let r=new HH(t,e),n=async(i,s)=>r.getKey(i,s);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.jwks(),enumerable:!0,configurable:!1,writable:!1}}),n}var BH,rfe,mC,HH,nfe=I(()=>{cn();tfe();Ss();(typeof navigator>"u"||!navigator.userAgent?.startsWith?.("Mozilla/5.0 "))&&(BH="jose/v6.2.3");rfe=Symbol();mC=Symbol();HH=class{#e;#t;#r;#n;#i;#p;#u;#a;#o;#d;constructor(e,r){if(!(e instanceof URL))throw new TypeError("url must be an instance of URL");this.#e=new URL(e.href),this.#t=typeof r?.timeoutDuration=="number"?r?.timeoutDuration:5e3,this.#r=typeof r?.cooldownDuration=="number"?r?.cooldownDuration:3e4,this.#n=typeof r?.cacheMaxAge=="number"?r?.cacheMaxAge:6e5,this.#u=new Headers(r?.headers),BH&&!this.#u.has("User-Agent")&&this.#u.set("User-Agent",BH),this.#u.has("accept")||(this.#u.set("accept","application/json"),this.#u.append("accept","application/jwk-set+json")),this.#a=r?.[rfe],r?.[mC]!==void 0&&(this.#d=r?.[mC],$rt(r?.[mC],this.#n)&&(this.#i=this.#d.uat,this.#o=zH(this.#d.jwks)))}pendingFetch(){return!!this.#p}coolingDown(){return typeof this.#i=="number"?Date.now()<this.#i+this.#r:!1}fresh(){return typeof this.#i=="number"?Date.now()<this.#i+this.#n:!1}jwks(){return this.#o?.jwks()}async getKey(e,r){(!this.#o||!this.fresh())&&await this.reload();try{return await this.#o(e,r)}catch(n){if(n instanceof iv&&this.coolingDown()===!1)return await this.reload(),this.#o(e,r);throw n}}async reload(){this.#p&&Hrt()&&(this.#p=void 0),this.#p||=Wrt(this.#e.href,this.#u,AbortSignal.timeout(this.#t),this.#a).then(e=>{this.#o=zH(e),this.#d&&(this.#d.uat=Date.now(),this.#d.jwks=e),this.#i=Date.now(),this.#p=void 0}).catch(e=>{throw this.#p=void 0,e}),await this.#p}}});function Dl(t){let e;if(typeof t=="string"){let r=t.split(".");(r.length===3||r.length===5)&&([e]=r)}else if(typeof t=="object"&&t)if("protected"in t)e=t.protected;else throw new TypeError("Token does not contain a Protected Header");try{if(typeof e!="string"||!e)throw new Error;let r=JSON.parse(_s.decode(_o(e)));if(!vn(r))throw new Error;return r}catch{throw new TypeError("Invalid Token or Protected Header formatting")}}var ife=I(()=>{Ys();Vs();Ss()});function wi(t){if(typeof t!="string")throw new Js("JWTs must use Compact JWS serialization, JWT must be a string");let{1:e,length:r}=t.split(".");if(r===5)throw new Js("Only JWTs using Compact JWS serialization can be decoded");if(r!==3)throw new Js("Invalid JWT");if(!e)throw new Js("JWTs must contain a payload");let n;try{n=_o(e)}catch{throw new Js("Failed to base64url decode the payload")}let i;try{i=JSON.parse(_s.decode(n))}catch{throw new Js("Failed to parse the decoded payload as JSON")}if(!vn(i))throw new Js("Invalid JWT Claims Set");return i}var sfe=I(()=>{Ys();Vs();Ss();cn()});var Wc=I(()=>{$pe();Gpe();Zpe();Xpe();Qpe();nfe();sC();ife();sfe();Ys()});async function hC(t,e,r=3600){return await new D0(t).setProtectedHeader({alg:"HS256"}).setIssuedAt().setExpirationTime(Math.floor(Date.now()/1e3)+r).sign(new TextEncoder().encode(e))}async function $H(t,e){try{return(await To(t,new TextEncoder().encode(e))).payload}catch{return null}}function L0(t,e){return Ude(Bde,new TextEncoder().encode(t),new TextEncoder().encode(e),Grt,64)}function Yrt(t){if(typeof t=="string")return t;let e=t.keys.get(t.currentVersion);if(!e)throw new Error(`Secret version ${t.currentVersion} not found in keys`);return e}function ofe(t){if(typeof t=="string")return[{version:0,value:t}];let e=[];for(let[r,n]of t.keys)e.push({version:r,value:n});return t.legacySecret&&!e.some(r=>r.value===t.legacySecret)&&e.push({version:-1,value:t.legacySecret}),e}async function gC(t,e,r,n=3600){let i=L0(Yrt(e),r),s=await fC({kty:"oct",k:E0.encode(i)},"sha256");return await new M0(t).setProtectedHeader({alg:cfe,enc:lfe,kid:s}).setIssuedAt().setExpirationTime(Vrt()+n).setJti(crypto.randomUUID()).encrypt(i)}async function j0(t,e,r){if(!t)return null;let n=!1;try{n=Dl(t).kid!==void 0}catch{return null}try{let i=ofe(e),{payload:s}=await lC(t,async o=>{let a=o.kid;if(a!==void 0){for(let c of i){let l=L0(c.value,r);if(a===await fC({kty:"oct",k:E0.encode(l)},"sha256"))return l}throw new Error("no matching decryption secret")}return i.length===1,L0(i[0].value,r)},afe);return s}catch{if(n)return null;let i=ofe(e);if(i.length<=1)return null;for(let s=1;s<i.length;s++)try{let o=i[s],{payload:a}=await lC(t,L0(o.value,r),afe);return a}catch{continue}return null}}var Grt,Vrt,cfe,lfe,afe,U0=I(()=>{Kde();Hde();Wc();Grt=new Uint8Array([66,101,116,116,101,114,65,117,116,104,46,106,115,32,71,101,110,101,114,97,116,101,100,32,69,110,99,114,121,112,116,105,111,110,32,75,101,121]),Vrt=()=>Date.now()/1e3|0,cfe="dir",lfe="A256CBC-HS512";afe={clockTolerance:15,keyManagementAlgorithms:[cfe],contentEncryptionAlgorithms:[lfe,"A256GCM"]}});function ufe(t,e){return new Promise((r,n)=>{(0,yC.scrypt)(t.normalize("NFKC"),e,fv.dkLen,{N:fv.N,r:fv.r,p:fv.p,maxmem:128*fv.N*fv.r*2},(i,s)=>{i?n(i):r(s)})})}async function dfe(t){let e=(0,yC.randomBytes)(16).toString("hex"),r=await ufe(t,e);return`${e}:${r.toString("hex")}`}async function pfe(t,e){let[r,n]=t.split(":");if(!r||!n)throw new Error("Invalid password hash");return(await ufe(e,r)).toString("hex")===n}var yC,fv,ffe=I(()=>{yC=require("node:crypto"),fv={N:16384,r:16,p:1,dkLen:64}});var mfe,hfe,gfe=I(()=>{ffe();mfe=dfe,hfe=async({hash:t,password:e})=>pfe(t,e)});function Ml(){let t=typeof globalThis<"u"&&globalThis.crypto;if(t&&typeof t.subtle=="object"&&t.subtle!=null)return t.subtle;throw new Error("crypto.subtle must be defined")}var K0=I(()=>{});function bC(t){return t?"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_":"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"}function yfe(t,e,r){let n="",i=0,s=0;for(let o of t)for(i=i<<8|o,s+=8;s>=6;)s-=6,n+=e[i>>s&63];if(s>0&&(n+=e[i<<6-s&63]),r){let o=(4-n.length%4)%4;n+="=".repeat(o)}return n}function bfe(t,e){let r=new Map;for(let o=0;o<e.length;o++)r.set(e[o],o);let n=[],i=0,s=0;for(let o of t){if(o==="=")break;let a=r.get(o);if(a===void 0)throw new Error(`Invalid Base64 character: ${o}`);i=i<<6|a,s+=6,s>=8&&(s-=8,n.push(i>>s&255))}return Uint8Array.from(n)}var Hi,da,pa=I(()=>{Hi={encode(t,e={}){let r=bC(!1),n=typeof t=="string"?new TextEncoder().encode(t):new Uint8Array(t);return yfe(n,r,e.padding??!0)},decode(t){typeof t!="string"&&(t=new TextDecoder().decode(t));let e=t.includes("-")||t.includes("_"),r=bC(e);return bfe(t,r)}},da={encode(t,e={}){let r=bC(!0),n=typeof t=="string"?new TextEncoder().encode(t):new Uint8Array(t);return yfe(n,r,e.padding??!0)},decode(t){let e=t.includes("-")||t.includes("_"),r=bC(e);return bfe(t,r)}}});function op(t,e){return{digest:async r=>{let n=new TextEncoder,i=typeof r=="string"?n.encode(r):r,s=await Ml().digest(t,i);return e==="hex"?Array.from(new Uint8Array(s)).map(c=>c.toString(16).padStart(2,"0")).join(""):e==="base64"||e==="base64url"||e==="base64urlnopad"?e.includes("url")?da.encode(s,{padding:e!=="base64urlnopad"}):Hi.encode(s):s}}}var q0=I(()=>{pa();K0()});function Jrt(t){return t instanceof Uint8Array||ArrayBuffer.isView(t)&&t.constructor.name==="Uint8Array"&&"BYTES_PER_ELEMENT"in t&&t.BYTES_PER_ELEMENT===1}function vC(t){if(typeof t!="boolean")throw new TypeError(`boolean expected, not ${t}`)}function Mf(t){if(typeof t!="number")throw new TypeError("number expected, got "+typeof t);if(!Number.isSafeInteger(t)||t<0)throw new RangeError("positive integer expected, got "+t)}function Dn(t,e,r=""){let n=Jrt(t),i=t?.length,s=e!==void 0;if(!n||s&&i!==e){let o=r&&`"${r}" `,a=s?` of length ${e}`:"",c=n?`length=${i}`:`type=${typeof t}`,l=o+"expected Uint8Array"+a+", got "+c;throw n?new RangeError(l):new TypeError(l)}return t}function GH(t,e=!0){if(t.destroyed)throw new Error("Hash instance has been destroyed");if(e&&t.finished)throw new Error("Hash#digest() has already been called")}function _fe(t,e,r=!1){Dn(t,void 0,"output");let n=e.outputLen;if(t.length<n)throw new RangeError("digestInto() expects output buffer of length at least "+n);if(r&&!mv(t))throw new Error("invalid output, must be aligned")}function Vu(t){return new Uint32Array(t.buffer,t.byteOffset,Math.floor(t.byteLength/4))}function Ll(...t){for(let e=0;e<t.length;e++)t[e].fill(0)}function Zrt(t){return new DataView(t.buffer,t.byteOffset,t.byteLength)}function VH(t){if(Dn(t),Sfe)return t.toHex();let e="";for(let r=0;r<t.length;r++)e+=Qrt[t[r]];return e}function vfe(t){if(t>=ap._0&&t<=ap._9)return t-ap._0;if(t>=ap.A&&t<=ap.F)return t-(ap.A-10);if(t>=ap.a&&t<=ap.f)return t-(ap.a-10)}function wfe(t){if(typeof t!="string")throw new TypeError("hex string expected, got "+typeof t);if(Sfe)try{return Uint8Array.fromHex(t)}catch(i){throw i instanceof SyntaxError?new RangeError(i.message):i}let e=t.length,r=e/2;if(e%2)throw new RangeError("hex string expected, got unpadded hex of length "+e);let n=new Uint8Array(r);for(let i=0,s=0;i<r;i++,s+=2){let o=vfe(t.charCodeAt(s)),a=vfe(t.charCodeAt(s+1));if(o===void 0||a===void 0){let c=t[s]+t[s+1];throw new RangeError('hex string expected, got non-hex character "'+c+'" at index '+s)}n[i]=o*16+a}return n}function Tfe(t){if(typeof t!="string")throw new TypeError("string expected");return new Uint8Array(new TextEncoder().encode(t))}function ent(t,e){return!t.byteLength||!e.byteLength?!1:t.buffer===e.buffer&&t.byteOffset<e.byteOffset+e.byteLength&&e.byteOffset<t.byteOffset+t.byteLength}function xfe(...t){let e=0;for(let n=0;n<t.length;n++){let i=t[n];Dn(i),e+=i.length}let r=new Uint8Array(e);for(let n=0,i=0;n<t.length;n++){let s=t[n];r.set(s,i),i+=s.length}return r}function Ife(t,e){if(e==null||typeof e!="object")throw new Error("options must be defined");return Object.assign(t,e)}function Afe(t,e){if(t.length!==e.length)return!1;let r=0;for(let n=0;n<t.length;n++)r|=t[n]^e[n];return r===0}function Ofe(t,e,r){let n=e,i=r||(()=>[]),s=(a,c)=>n(c,...i(a)).update(a).digest(),o=n(new Uint8Array(t),...i(new Uint8Array(0)));return s.outputLen=o.outputLen,s.blockLen=o.blockLen,s.create=(a,...c)=>n(a,...c),s}function F0(t,e,r=!0){if(e===void 0)return new Uint8Array(t);if(Dn(e,void 0,"output"),e.length!==t)throw new Error('"output" expected Uint8Array of length '+t+", got: "+e.length);if(r&&!mv(e))throw new Error("invalid output, must be aligned");return e}function Rfe(t,e,r){Mf(t),Mf(e),vC(r);let n=new Uint8Array(16),i=Zrt(n);return i.setBigUint64(0,BigInt(e),r),i.setBigUint64(8,BigInt(t),r),n}function mv(t){return t.byteOffset%4===0}function hv(t){return Uint8Array.from(Dn(t))}function Cfe(t=32){Mf(t);let e=typeof globalThis=="object"?globalThis.crypto:null;if(typeof e?.getRandomValues!="function")throw new Error("crypto.getRandomValues must be defined");return e.getRandomValues(new Uint8Array(t))}function YH(t,e=Cfe){let{nonceLength:r}=t;Mf(r);let n=(s,o,a)=>{let c=xfe(s,o);return ent(a,o)||o.fill(0),c},i=((s,...o)=>({encrypt(a){Dn(a);let c=e(r),l=t(s,c,...o).encrypt(a);return l instanceof Promise?l.then(u=>n(c,u,a)):n(c,l,a)},decrypt(a){Dn(a);let c=a.subarray(0,r),l=a.subarray(r);return t(s,c,...o).decrypt(l)}}));return"blockSize"in t&&(i.blockSize=t.blockSize),"tagLength"in t&&(i.tagLength=t.tagLength),i}var Lf,Efe,ws,Xrt,Yu,Sfe,Qrt,ap,kfe,z0=I(()=>{Lf=new Uint8Array(new Uint32Array([287454020]).buffer)[0]===68,Efe=t=>t<<24&4278190080|t<<8&16711680|t>>>8&65280|t>>>24&255,ws=Lf?t=>t:t=>Efe(t)>>>0,Xrt=t=>{for(let e=0;e<t.length;e++)t[e]=Efe(t[e]);return t},Yu=Lf?t=>t:Xrt,Sfe=typeof Uint8Array.from([]).toHex=="function"&&typeof Uint8Array.fromHex=="function",Qrt=Array.from({length:256},(t,e)=>e.toString(16).padStart(2,"0"));ap={_0:48,_9:57,A:65,F:70,a:97,f:102};kfe=(t,e)=>{function r(n,...i){if(Dn(n,void 0,"key"),t.nonceLength!==void 0){let u=i[0];Dn(u,t.varSizeNonce?void 0:t.nonceLength,"nonce")}let s=t.tagLength;s&&i[1]!==void 0&&Dn(i[1],void 0,"AAD");let o=e(n,...i),a=(u,d)=>{if(d!==void 0){if(u!==2)throw new Error("cipher output not supported");Dn(d,void 0,"output")}},c=!1;return{encrypt(u,d){if(c)throw new Error("cannot encrypt() twice with same key + nonce");return c=!0,Dn(u),a(o.encrypt.length,d),o.encrypt(u,d)},decrypt(u,d){if(Dn(u),s&&u.length<s)throw new Error('"ciphertext" expected length bigger than tagLength='+s);return a(o.decrypt.length,d),o.decrypt(u,d)}}}return Object.assign(r,t),r}});function Le(t,e){return t<<e|t>>>32-e}function int(t,e,r,n,i,s,o,a){let c=i.length,l=new Uint8Array(B0),u=Vu(l),d=Lf&&mv(i)&&mv(s),p=d?Vu(i):Nfe,f=d?Vu(s):Nfe;if(!Lf){for(let m=0;m<c;o++){if(t(e,r,n,u,o,a),Yu(u),o>=JH)throw new Error("arx: counter overflow");let h=Math.min(B0,c-m);for(let y=0,g;y<h;y++)g=m+y,s[g]=i[g]^l[y];m+=h}return}for(let m=0;m<c;o++){if(t(e,r,n,u,o,a),o>=JH)throw new Error("arx: counter overflow");let h=Math.min(B0,c-m);if(d&&h===B0){let y=m/4;if(m%4!==0)throw new Error("arx: invalid block position");for(let g=0,b;g<nnt;g++)b=y+g,f[b]=p[b]^u[g];m+=B0;continue}for(let y=0,g;y<h;y++)g=m+y,s[g]=i[g]^l[y];m+=h}}function Dfe(t,e){let{allowShortKeys:r,extendNonceFn:n,counterLength:i,counterRight:s,rounds:o}=Ife({allowShortKeys:!1,counterLength:8,counterRight:!1,rounds:20},e);if(typeof t!="function")throw new Error("core must be a function");return Mf(i),Mf(o),vC(s),vC(r),(a,c,l,u,d=0)=>{Dn(a,void 0,"key"),Dn(c,void 0,"nonce"),Dn(l,void 0,"data");let p=l.length;if(u=F0(p,u,!1),Mf(d),d<0||d>=JH)throw new Error("arx: counter overflow");let f=[],m=a.length,h,y;if(m===32)f.push(h=hv(a)),y=rnt;else if(m===16&&r)h=new Uint8Array(32),h.set(a),h.set(a,16),y=tnt,f.push(h);else throw Dn(a,32,"arx key"),new Error("invalid key size");(!Lf||!mv(c))&&f.push(c=hv(c));let g=Vu(h);if(n){if(c.length!==24)throw new Error("arx: extended nonce must be 24 bytes");let _=c.subarray(0,16);if(Lf)n(y,g,Vu(_),g);else{let w=Yu(Uint32Array.from(y));n(w,g,Vu(_),g),Ll(w),Yu(g)}c=c.subarray(16)}else Lf||Yu(g);let b=16-i;if(b!==c.length)throw new Error(`arx: nonce must be ${b} or 16 bytes`);if(b!==12){let _=new Uint8Array(12);_.set(c,s?0:12-c.length),c=_,f.push(c)}let v=Yu(Vu(c));try{return int(t,y,g,v,l,u,d,o),u}finally{Ll(...f)}}}var Pfe,tnt,rnt,B0,nnt,JH,Nfe,Mfe=I(()=>{z0();Pfe=t=>Uint8Array.from(t.split(""),e=>e.charCodeAt(0)),tnt=Yu(Vu(Pfe("expand 16-byte k"))),rnt=Yu(Vu(Pfe("expand 32-byte k")));B0=64,nnt=16,JH=2**32-1,Nfe=Uint32Array.of()});function Ts(t,e){return t[e++]&255|(t[e++]&255)<<8}var ZH,Lfe,jfe=I(()=>{z0();ZH=class{blockLen=16;outputLen=16;buffer=new Uint8Array(16);r=new Uint16Array(10);h=new Uint16Array(10);pad=new Uint16Array(8);pos=0;finished=!1;destroyed=!1;constructor(e){e=hv(Dn(e,32,"key"));let r=Ts(e,0),n=Ts(e,2),i=Ts(e,4),s=Ts(e,6),o=Ts(e,8),a=Ts(e,10),c=Ts(e,12),l=Ts(e,14);this.r[0]=r&8191,this.r[1]=(r>>>13|n<<3)&8191,this.r[2]=(n>>>10|i<<6)&7939,this.r[3]=(i>>>7|s<<9)&8191,this.r[4]=(s>>>4|o<<12)&255,this.r[5]=o>>>1&8190,this.r[6]=(o>>>14|a<<2)&8191,this.r[7]=(a>>>11|c<<5)&8065,this.r[8]=(c>>>8|l<<8)&8191,this.r[9]=l>>>5&127;for(let u=0;u<8;u++)this.pad[u]=Ts(e,16+2*u)}process(e,r,n=!1){let i=n?0:2048,{h:s,r:o}=this,a=o[0],c=o[1],l=o[2],u=o[3],d=o[4],p=o[5],f=o[6],m=o[7],h=o[8],y=o[9],g=Ts(e,r+0),b=Ts(e,r+2),v=Ts(e,r+4),_=Ts(e,r+6),w=Ts(e,r+8),S=Ts(e,r+10),x=Ts(e,r+12),O=Ts(e,r+14),N=s[0]+(g&8191),k=s[1]+((g>>>13|b<<3)&8191),M=s[2]+((b>>>10|v<<6)&8191),K=s[3]+((v>>>7|_<<9)&8191),P=s[4]+((_>>>4|w<<12)&8191),j=s[5]+(w>>>1&8191),U=s[6]+((w>>>14|S<<2)&8191),q=s[7]+((S>>>11|x<<5)&8191),F=s[8]+((x>>>8|O<<8)&8191),Q=s[9]+(O>>>5|i),J=0,W=J+N*a+k*(5*y)+M*(5*h)+K*(5*m)+P*(5*f);J=W>>>13,W&=8191,W+=j*(5*p)+U*(5*d)+q*(5*u)+F*(5*l)+Q*(5*c),J+=W>>>13,W&=8191;let z=J+N*c+k*a+M*(5*y)+K*(5*h)+P*(5*m);J=z>>>13,z&=8191,z+=j*(5*f)+U*(5*p)+q*(5*d)+F*(5*u)+Q*(5*l),J+=z>>>13,z&=8191;let G=J+N*l+k*c+M*a+K*(5*y)+P*(5*h);J=G>>>13,G&=8191,G+=j*(5*m)+U*(5*f)+q*(5*p)+F*(5*d)+Q*(5*u),J+=G>>>13,G&=8191;let H=J+N*u+k*l+M*c+K*a+P*(5*y);J=H>>>13,H&=8191,H+=j*(5*h)+U*(5*m)+q*(5*f)+F*(5*p)+Q*(5*d),J+=H>>>13,H&=8191;let L=J+N*d+k*u+M*l+K*c+P*a;J=L>>>13,L&=8191,L+=j*(5*y)+U*(5*h)+q*(5*m)+F*(5*f)+Q*(5*p),J+=L>>>13,L&=8191;let B=J+N*p+k*d+M*u+K*l+P*c;J=B>>>13,B&=8191,B+=j*a+U*(5*y)+q*(5*h)+F*(5*m)+Q*(5*f),J+=B>>>13,B&=8191;let ie=J+N*f+k*p+M*d+K*u+P*l;J=ie>>>13,ie&=8191,ie+=j*c+U*a+q*(5*y)+F*(5*h)+Q*(5*m),J+=ie>>>13,ie&=8191;let xe=J+N*m+k*f+M*p+K*d+P*u;J=xe>>>13,xe&=8191,xe+=j*l+U*c+q*a+F*(5*y)+Q*(5*h),J+=xe>>>13,xe&=8191;let Ne=J+N*h+k*m+M*f+K*p+P*d;J=Ne>>>13,Ne&=8191,Ne+=j*u+U*l+q*c+F*a+Q*(5*y),J+=Ne>>>13,Ne&=8191;let bt=J+N*y+k*h+M*m+K*f+P*p;J=bt>>>13,bt&=8191,bt+=j*d+U*u+q*l+F*c+Q*a,J+=bt>>>13,bt&=8191,J=(J<<2)+J|0,J=J+W|0,W=J&8191,J=J>>>13,z+=J,s[0]=W,s[1]=z,s[2]=G,s[3]=H,s[4]=L,s[5]=B,s[6]=ie,s[7]=xe,s[8]=Ne,s[9]=bt}finalize(){let{h:e,pad:r}=this,n=new Uint16Array(10),i=e[1]>>>13;e[1]&=8191;for(let a=2;a<10;a++)e[a]+=i,i=e[a]>>>13,e[a]&=8191;e[0]+=i*5,i=e[0]>>>13,e[0]&=8191,e[1]+=i,i=e[1]>>>13,e[1]&=8191,e[2]+=i,n[0]=e[0]+5,i=n[0]>>>13,n[0]&=8191;for(let a=1;a<10;a++)n[a]=e[a]+i,i=n[a]>>>13,n[a]&=8191;n[9]-=8192;let s=(i^1)-1;for(let a=0;a<10;a++)n[a]&=s;s=~s;for(let a=0;a<10;a++)e[a]=e[a]&s|n[a];e[0]=(e[0]|e[1]<<13)&65535,e[1]=(e[1]>>>3|e[2]<<10)&65535,e[2]=(e[2]>>>6|e[3]<<7)&65535,e[3]=(e[3]>>>9|e[4]<<4)&65535,e[4]=(e[4]>>>12|e[5]<<1|e[6]<<14)&65535,e[5]=(e[6]>>>2|e[7]<<11)&65535,e[6]=(e[7]>>>5|e[8]<<8)&65535,e[7]=(e[8]>>>8|e[9]<<5)&65535;let o=e[0]+r[0];e[0]=o&65535;for(let a=1;a<8;a++)o=(e[a]+r[a]|0)+(o>>>16)|0,e[a]=o&65535;Ll(n)}update(e){GH(this),Dn(e),e=hv(e);let{buffer:r,blockLen:n}=this,i=e.length;for(let s=0;s<i;){let o=Math.min(n-this.pos,i-s);if(o===n){for(;n<=i-s;s+=n)this.process(e,s);continue}r.set(e.subarray(s,s+o),this.pos),this.pos+=o,s+=o,this.pos===n&&(this.process(r,0,!1),this.pos=0)}return this}destroy(){this.destroyed=!0,Ll(this.h,this.r,this.buffer,this.pad)}digestInto(e){GH(this),_fe(e,this),this.finished=!0;let{buffer:r,h:n}=this,{pos:i}=this;if(i){for(r[i++]=1;i<16;i++)r[i]=0;this.process(r,0,!0)}this.finalize();let s=0;for(let o=0;o<8;o++)e[s++]=n[o]>>>0,e[s++]=n[o]>>>8}digest(){let{buffer:e,outputLen:r}=this;this.digestInto(e);let n=e.slice(0,r);return this.destroy(),n}},Lfe=Ofe(32,t=>new ZH(t))});function snt(t,e,r,n,i,s=20){let o=t[0],a=t[1],c=t[2],l=t[3],u=e[0],d=e[1],p=e[2],f=e[3],m=e[4],h=e[5],y=e[6],g=e[7],b=i,v=r[0],_=r[1],w=r[2],S=o,x=a,O=c,N=l,k=u,M=d,K=p,P=f,j=m,U=h,q=y,F=g,Q=b,J=v,W=_,z=w;for(let H=0;H<s;H+=2)S=S+k|0,Q=Le(Q^S,16),j=j+Q|0,k=Le(k^j,12),S=S+k|0,Q=Le(Q^S,8),j=j+Q|0,k=Le(k^j,7),x=x+M|0,J=Le(J^x,16),U=U+J|0,M=Le(M^U,12),x=x+M|0,J=Le(J^x,8),U=U+J|0,M=Le(M^U,7),O=O+K|0,W=Le(W^O,16),q=q+W|0,K=Le(K^q,12),O=O+K|0,W=Le(W^O,8),q=q+W|0,K=Le(K^q,7),N=N+P|0,z=Le(z^N,16),F=F+z|0,P=Le(P^F,12),N=N+P|0,z=Le(z^N,8),F=F+z|0,P=Le(P^F,7),S=S+M|0,z=Le(z^S,16),q=q+z|0,M=Le(M^q,12),S=S+M|0,z=Le(z^S,8),q=q+z|0,M=Le(M^q,7),x=x+K|0,Q=Le(Q^x,16),F=F+Q|0,K=Le(K^F,12),x=x+K|0,Q=Le(Q^x,8),F=F+Q|0,K=Le(K^F,7),O=O+P|0,J=Le(J^O,16),j=j+J|0,P=Le(P^j,12),O=O+P|0,J=Le(J^O,8),j=j+J|0,P=Le(P^j,7),N=N+k|0,W=Le(W^N,16),U=U+W|0,k=Le(k^U,12),N=N+k|0,W=Le(W^N,8),U=U+W|0,k=Le(k^U,7);let G=0;n[G++]=o+S|0,n[G++]=a+x|0,n[G++]=c+O|0,n[G++]=l+N|0,n[G++]=u+k|0,n[G++]=d+M|0,n[G++]=p+K|0,n[G++]=f+P|0,n[G++]=m+j|0,n[G++]=h+U|0,n[G++]=y+q|0,n[G++]=g+F|0,n[G++]=b+Q|0,n[G++]=v+J|0,n[G++]=_+W|0,n[G++]=w+z|0}function ont(t,e,r,n){let i=ws(t[0]),s=ws(t[1]),o=ws(t[2]),a=ws(t[3]),c=ws(e[0]),l=ws(e[1]),u=ws(e[2]),d=ws(e[3]),p=ws(e[4]),f=ws(e[5]),m=ws(e[6]),h=ws(e[7]),y=ws(r[0]),g=ws(r[1]),b=ws(r[2]),v=ws(r[3]);for(let w=0;w<20;w+=2)i=i+c|0,y=Le(y^i,16),p=p+y|0,c=Le(c^p,12),i=i+c|0,y=Le(y^i,8),p=p+y|0,c=Le(c^p,7),s=s+l|0,g=Le(g^s,16),f=f+g|0,l=Le(l^f,12),s=s+l|0,g=Le(g^s,8),f=f+g|0,l=Le(l^f,7),o=o+u|0,b=Le(b^o,16),m=m+b|0,u=Le(u^m,12),o=o+u|0,b=Le(b^o,8),m=m+b|0,u=Le(u^m,7),a=a+d|0,v=Le(v^a,16),h=h+v|0,d=Le(d^h,12),a=a+d|0,v=Le(v^a,8),h=h+v|0,d=Le(d^h,7),i=i+l|0,v=Le(v^i,16),m=m+v|0,l=Le(l^m,12),i=i+l|0,v=Le(v^i,8),m=m+v|0,l=Le(l^m,7),s=s+u|0,y=Le(y^s,16),h=h+y|0,u=Le(u^h,12),s=s+u|0,y=Le(y^s,8),h=h+y|0,u=Le(u^h,7),o=o+d|0,g=Le(g^o,16),p=p+g|0,d=Le(d^p,12),o=o+d|0,g=Le(g^o,8),p=p+g|0,d=Le(d^p,7),a=a+c|0,b=Le(b^a,16),f=f+b|0,c=Le(c^f,12),a=a+c|0,b=Le(b^a,8),f=f+b|0,c=Le(c^f,7);let _=0;n[_++]=i,n[_++]=s,n[_++]=o,n[_++]=a,n[_++]=y,n[_++]=g,n[_++]=b,n[_++]=v,Yu(n)}function Kfe(t,e,r,n,i){i!==void 0&&Dn(i,void 0,"AAD");let s=t(e,r,lnt),o=Rfe(n.length,i?i.length:0,!0),a=Lfe.create(s);i&&Ufe(a,i),Ufe(a,n),a.update(o);let c=a.digest();return Ll(s,o),c}var ant,cnt,Ufe,lnt,unt,XH,qfe=I(()=>{Mfe();jfe();z0();ant=Dfe(snt,{counterRight:!1,counterLength:8,extendNonceFn:ont,allowShortKeys:!1}),cnt=new Uint8Array(16),Ufe=(t,e)=>{t.update(e);let r=e.length%16;r&&t.update(cnt.subarray(r))},lnt=new Uint8Array(32);unt=t=>(e,r,n)=>({encrypt(s,o){let a=s.length;o=F0(a+16,o,!1),o.set(s);let c=o.subarray(0,-16);t(e,r,c,c,1);let l=Kfe(t,e,r,c,n);return o.set(l,a),Ll(l),o},decrypt(s,o){o=F0(s.length-16,o,!1);let a=s.subarray(0,-16),c=s.subarray(-16),l=Kfe(t,e,r,a,n);if(!Afe(c,l))throw Ll(l),new Error("invalid tag");return o.set(s.subarray(0,-16)),t(e,r,o,o,1),Ll(l),o}}),XH=kfe({blockSize:64,nonceLength:24,tagLength:16},unt(ant))});function dnt(t){if(!t.startsWith(zfe))return null;let e=4,r=t.indexOf("$",e);if(r===-1)return null;let n=parseInt(t.slice(e,r),10);return!Number.isInteger(n)||n<0?null:{version:n,ciphertext:t.slice(r+1)}}function pnt(t,e){return`${zfe}${t}$${e}`}async function Ffe(t,e){let r=await op("SHA-256").digest(t),n=Tfe(e);return VH(YH(XH)(new Uint8Array(r)).encrypt(n))}async function QH(t,e){let r=await op("SHA-256").digest(t),n=wfe(e),i=YH(XH)(new Uint8Array(r));return new TextDecoder().decode(i.decrypt(n))}var zfe,_C,EC,SC=I(()=>{b0();K0();q0();qfe();z0();zfe="$ba$";_C=async({key:t,data:e})=>{if(typeof t=="string")return Ffe(t,e);let r=t.keys.get(t.currentVersion);if(!r)throw new Error(`Secret version ${t.currentVersion} not found in keys`);let n=await Ffe(r,e);return pnt(t.currentVersion,n)},EC=async({key:t,data:e})=>{if(typeof t=="string")return QH(t,e);let r=dnt(e);if(r){let n=t.keys.get(r.version);if(!n)throw new Error(`Secret version ${r.version} not found in keys (key may have been retired)`);return QH(n,r.ciphertext)}if(t.legacySecret)return QH(t.legacySecret,e);throw new Error("Cannot decrypt legacy bare-hex payload: no legacy secret available. Set BETTER_AUTH_SECRET for backwards compatibility.")}});var Zs,eW=I(()=>{Zs=t=>{let e=(t.plugins??[]).reduce((d,p)=>{let f=p.schema;if(!f)return d;for(let[m,h]of Object.entries(f))d[m]={fields:{...d[m]?.fields,...h.fields},modelName:h.modelName||m};return d},{}),r=t.rateLimit?.storage==="database",n={rateLimit:{modelName:t.rateLimit?.modelName||"rateLimit",fields:{key:{type:"string",unique:!0,required:!0,fieldName:t.rateLimit?.fields?.key||"key"},count:{type:"number",required:!0,fieldName:t.rateLimit?.fields?.count||"count"},lastRequest:{type:"number",bigint:!0,required:!0,fieldName:t.rateLimit?.fields?.lastRequest||"lastRequest",defaultValue:()=>Date.now()}}}},{user:i,session:s,account:o,verification:a,...c}=e,l={verification:{modelName:t.verification?.modelName||"verification",fields:{identifier:{type:"string",required:!0,fieldName:t.verification?.fields?.identifier||"identifier",index:!0},value:{type:"string",required:!0,fieldName:t.verification?.fields?.value||"value"},expiresAt:{type:"date",required:!0,fieldName:t.verification?.fields?.expiresAt||"expiresAt"},createdAt:{type:"date",required:!0,defaultValue:()=>new Date,fieldName:t.verification?.fields?.createdAt||"createdAt"},updatedAt:{type:"date",required:!0,defaultValue:()=>new Date,onUpdate:()=>new Date,fieldName:t.verification?.fields?.updatedAt||"updatedAt"},...a?.fields,...t.verification?.additionalFields},order:4}},u={session:{modelName:t.session?.modelName||"session",fields:{expiresAt:{type:"date",required:!0,fieldName:t.session?.fields?.expiresAt||"expiresAt"},token:{type:"string",required:!0,fieldName:t.session?.fields?.token||"token",unique:!0},createdAt:{type:"date",required:!0,fieldName:t.session?.fields?.createdAt||"createdAt",defaultValue:()=>new Date},updatedAt:{type:"date",required:!0,fieldName:t.session?.fields?.updatedAt||"updatedAt",onUpdate:()=>new Date},ipAddress:{type:"string",required:!1,fieldName:t.session?.fields?.ipAddress||"ipAddress"},userAgent:{type:"string",required:!1,fieldName:t.session?.fields?.userAgent||"userAgent"},userId:{type:"string",fieldName:t.session?.fields?.userId||"userId",references:{model:t.user?.modelName||"user",field:"id",onDelete:"cascade"},required:!0,index:!0},...s?.fields,...t.session?.additionalFields},order:2}};return{user:{modelName:t.user?.modelName||"user",fields:{name:{type:"string",required:!0,fieldName:t.user?.fields?.name||"name",sortable:!0},email:{type:"string",unique:!0,required:!0,fieldName:t.user?.fields?.email||"email",sortable:!0},emailVerified:{type:"boolean",defaultValue:!1,required:!0,fieldName:t.user?.fields?.emailVerified||"emailVerified",input:!1},image:{type:"string",required:!1,fieldName:t.user?.fields?.image||"image"},createdAt:{type:"date",defaultValue:()=>new Date,required:!0,fieldName:t.user?.fields?.createdAt||"createdAt"},updatedAt:{type:"date",defaultValue:()=>new Date,onUpdate:()=>new Date,required:!0,fieldName:t.user?.fields?.updatedAt||"updatedAt"},...i?.fields,...t.user?.additionalFields},order:1},...!t.secondaryStorage||t.session?.storeSessionInDatabase?u:{},account:{modelName:t.account?.modelName||"account",fields:{accountId:{type:"string",required:!0,fieldName:t.account?.fields?.accountId||"accountId"},providerId:{type:"string",required:!0,fieldName:t.account?.fields?.providerId||"providerId"},userId:{type:"string",references:{model:t.user?.modelName||"user",field:"id",onDelete:"cascade"},required:!0,fieldName:t.account?.fields?.userId||"userId",index:!0},accessToken:{type:"string",required:!1,returned:!1,fieldName:t.account?.fields?.accessToken||"accessToken"},refreshToken:{type:"string",required:!1,returned:!1,fieldName:t.account?.fields?.refreshToken||"refreshToken"},idToken:{type:"string",required:!1,returned:!1,fieldName:t.account?.fields?.idToken||"idToken"},accessTokenExpiresAt:{type:"date",required:!1,returned:!1,fieldName:t.account?.fields?.accessTokenExpiresAt||"accessTokenExpiresAt"},refreshTokenExpiresAt:{type:"date",required:!1,returned:!1,fieldName:t.account?.fields?.refreshTokenExpiresAt||"refreshTokenExpiresAt"},scope:{type:"string",required:!1,fieldName:t.account?.fields?.scope||"scope"},password:{type:"string",required:!1,returned:!1,fieldName:t.account?.fields?.password||"password"},createdAt:{type:"date",required:!0,fieldName:t.account?.fields?.createdAt||"createdAt",defaultValue:()=>new Date},updatedAt:{type:"date",required:!0,fieldName:t.account?.fields?.updatedAt||"updatedAt",onUpdate:()=>new Date},...o?.fields,...t.account?.additionalFields},order:3},...!t.secondaryStorage||t.verification?.storeInDatabase?l:{},...c,...r?n:{}}}});var Gh,Ju,gv=I(()=>{Gh=le(require("zod"),1),Ju=Gh.object({id:Gh.string(),createdAt:Gh.date().default(()=>new Date),updatedAt:Gh.date().default(()=>new Date)})});var Va,Bfe,Hfe=I(()=>{gv();Va=le(require("zod"),1),Bfe=Ju.extend({providerId:Va.string(),accountId:Va.string(),userId:Va.coerce.string(),accessToken:Va.string().nullish(),refreshToken:Va.string().nullish(),idToken:Va.string().nullish(),accessTokenExpiresAt:Va.date().nullish(),refreshTokenExpiresAt:Va.date().nullish(),scope:Va.string().nullish(),password:Va.string().nullish()})});var Vh,Wfe,$fe=I(()=>{Vh=le(require("zod"),1),Wfe=Vh.object({key:Vh.string(),count:Vh.number(),lastRequest:Vh.number()})});var jf,Gfe,Vfe=I(()=>{gv();jf=le(require("zod"),1),Gfe=Ju.extend({userId:jf.coerce.string(),expiresAt:jf.date(),token:jf.string(),ipAddress:jf.string().nullish(),userAgent:jf.string().nullish()})});var yv,Yfe,Jfe=I(()=>{gv();yv=le(require("zod"),1),Yfe=Ju.extend({email:yv.string().transform(t=>t.toLowerCase()),emailVerified:yv.boolean().default(!1),name:yv.string(),image:yv.string().nullish()})});var H0,Zfe,Xfe=I(()=>{gv();H0=le(require("zod"),1),Zfe=Ju.extend({value:H0.string(),expiresAt:H0.date(),identifier:H0.string()})});var tW={};ui(tW,{accountSchema:()=>Bfe,coreSchema:()=>Ju,getAuthTables:()=>Zs,rateLimitSchema:()=>Wfe,sessionSchema:()=>Gfe,userSchema:()=>Yfe,verificationSchema:()=>Zfe});var cp=I(()=>{eW();gv();Hfe();$fe();Vfe();Jfe();Xfe()});function Xs(t,e){if(!t||!e)return t;let r=Object.entries(e).filter(([,{returned:n}])=>n===!1).map(([n])=>n);return Object.entries(structuredClone(t)).filter(([n])=>!r.includes(n)).reduce((n,[i,s])=>({...n,[i]:s}),{})}var wC=I(()=>{});function Uf(t,e,r){let n=`${e}:${r}`;rW.has(t)||rW.set(t,new Map);let i=rW.get(t);if(i.has(n))return i.get(n);let s=r==="output"?Zs(t)[e]?.fields??{}:{},o=e==="user"||e==="session"||e==="account"?t[e]?.additionalFields:void 0,a={...s,...o??{}};for(let c of t.plugins||[])c.schema&&c.schema[e]&&(a={...a,...c.schema[e].fields});return i.set(n,a),a}function Br(t,e){return Xs(e,Uf(t,"user","output"))}function Wi(t,e){return Xs(e,Uf(t,"session","output"))}function TC(t,e){let{accessToken:r,refreshToken:n,idToken:i,accessTokenExpiresAt:s,refreshTokenExpiresAt:o,password:a,...c}=Xs(e,Uf(t,"account","output"));return c}function bv(t,e){let r=e.action||"create",n=e.fields,i=Object.create(null);for(let s in n){if(s in t){if(n[s].input===!1){if(n[s].defaultValue!==void 0&&r!=="update"){i[s]=n[s].defaultValue;continue}if(t[s])throw D.from("BAD_REQUEST",{...ae.FIELD_NOT_ALLOWED,message:`${s} is not allowed to be set`});continue}if(n[s].validator?.input&&t[s]!==void 0){let o=n[s].validator.input["~standard"].validate(t[s]);if(o instanceof Promise)throw D.from("INTERNAL_SERVER_ERROR",ae.ASYNC_VALIDATION_NOT_SUPPORTED);if("issues"in o&&o.issues)throw D.from("BAD_REQUEST",{...ae.VALIDATION_ERROR,message:o.issues[0]?.message||"Validation Error"});i[s]=o.value;continue}if(n[s].transform?.input&&t[s]!==void 0){i[s]=n[s].transform?.input(t[s]);continue}i[s]=t[s];continue}if(n[s].defaultValue!==void 0&&r==="create"){if(typeof n[s].defaultValue=="function"){i[s]=n[s].defaultValue();continue}i[s]=n[s].defaultValue;continue}if(n[s].required&&r==="create")throw D.from("BAD_REQUEST",{...ae.MISSING_FIELD,message:`${s} is required`})}return i}function vv(t,e={},r){return bv(e,{fields:Uf(t,"user","input"),action:r})}function Qfe(t,e){let r=Uf(t,"user","input");return bv(e||{},{fields:r})}function eme(t,e){return bv(e,{fields:Uf(t,"account","input")})}function xC(t,e,r){return bv(e,{fields:Uf(t,"session","input"),action:r})}function IC(t){let e=Uf(t,"session","input"),r={};for(let n in e)e[n].defaultValue!==void 0&&(r[n]=typeof e[n].defaultValue=="function"?e[n].defaultValue():e[n].defaultValue);return r}function AC(t,e){if(!e)return t;for(let r in e){let n=e[r]?.modelName;n&&(t[r].modelName=n);for(let i in t[r].fields){let s=e[r]?.fields?.[i];s&&(t[r].fields[i].fieldName=s)}}return t}var rW,jl=I(()=>{cp();rt();wC();rW=new WeakMap});var xo,Yh=I(()=>{xo=(t,e="ms")=>new Date(Date.now()+(e==="sec"?t*1e3:t))});function _v(t){return!!t&&(typeof t=="object"||typeof t=="function")&&typeof t.then=="function"}var OC=I(()=>{});function mnt(t){let e=fnt.exec(t);if(!e||e[4]&&e[1])throw new TypeError(`Invalid time string format: "${t}". Use formats like "7d", "30m", "1 hour", etc.`);let r=parseFloat(e[2]),n=e[3].toLowerCase(),i;switch(n){case"years":case"year":case"yrs":case"yr":case"y":i=r*315576e5;break;case"months":case"month":case"mo":i=r*2592e6;break;case"weeks":case"week":case"w":i=r*6048e5;break;case"days":case"day":case"d":i=r*864e5;break;case"hours":case"hour":case"hrs":case"hr":case"h":i=r*36e5;break;case"minutes":case"minute":case"mins":case"min":case"m":i=r*6e4;break;case"seconds":case"second":case"secs":case"sec":case"s":i=r*1e3;break;default:throw new TypeError(`Unknown time unit: "${n}"`)}return e[1]==="-"||e[4]==="ago"?-i:i}function tme(t){return Math.round(mnt(t)/1e3)}var fnt,rme=I(()=>{fnt=/^(\+|\-)? ?(\d+|\d+\.\d+) ?(seconds?|secs?|s|minutes?|mins?|m|hours?|hrs?|h|days?|d|weeks?|w|months?|mo|years?|yrs?|y)(?: (ago|from now))?$/i});var nme,ime=I(()=>{nme="__Secure-"});function sme(t){if(typeof t=="string"&&hnt.test(t)){let e=new Date(t);if(!isNaN(e.getTime()))return e}return t}function nW(t){if(t==null)return t;if(typeof t=="string")return sme(t);if(t instanceof Date)return t;if(Array.isArray(t))return t.map(nW);if(typeof t=="object"){let e={};for(let r of Object.keys(t))e[r]=nW(t[r]);return e}return t}function lr(t){try{return typeof t!="string"?t==null?null:nW(t):JSON.parse(t,(e,r)=>sme(r))}catch(e){return De.error("Error parsing JSON",{error:e}),null}}var hnt,lp=I(()=>{bs();hnt=/^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}(?:\.\d+)?Z$/});function gnt(t){let e=t.headers?.get("cookie");if(!e)return{};let r={},n=e.split("; ");for(let i of n){let[s,...o]=i.split("=");s&&o.length>0&&(r[s]=o.join("="))}return r}function ome(t){let e=t.split("."),r=e[e.length-1],n=parseInt(r||"0",10);return isNaN(n)?0:n}function ynt(t,e){let r={},n=gnt(e);for(let[i,s]of Object.entries(n))i.startsWith(t)&&(r[i]=s);return r}function bnt(t){return Object.keys(t).sort((e,r)=>ome(e)-ome(r)).map(e=>t[e]).join("")}function vnt(t,e,r,n){let i=Math.ceil(e.value.length/iW);if(i===1)return r[e.name]=e.value,[e];let s=[];for(let o=0;o<i;o++){let a=`${e.name}.${o}`,c=o*iW,l=e.value.substring(c,c+iW);s.push({...e,name:a,value:l}),r[a]=l}return n.debug(`CHUNKING_${t.toUpperCase()}_COOKIE`,{message:`${t} cookie exceeds allowed ${oW} bytes.`,emptyCookieSize:sW,valueSize:e.value.length,chunkCount:i,chunks:s.map(o=>o.value.length+sW)}),s}function ame(t,e){let r={};for(let n in t)r[n]={name:n,value:"",attributes:{...e,maxAge:0}};return r}function CC(t,e){let r=t.getCookie(e);if(r)return r;let n=[],i=t.headers?.get("cookie");if(!i)return null;let s={},o=i.split("; ");for(let a of o){let[c,...l]=a.split("=");c&&l.length>0&&(s[c]=l.join("="))}for(let[a,c]of Object.entries(s))if(a.startsWith(e+".")){let l=a.split(".").at(-1),u=parseInt(l||"0",10);isNaN(u)||n.push({index:u,value:c})}return n.length>0?(n.sort((a,c)=>a.index-c.index),n.map(a=>a.value).join("")):null}async function Kf(t,e){let r=t.context.authCookies.accountData,n={maxAge:300,...r.attributes},i=await gC(e,t.context.secretConfig,"better-auth-account",n.maxAge);if(i.length>oW){let s=kC(r.name,n,t),o=s.chunk(i,n);s.setCookies(o)}else{let s=kC(r.name,n,t);if(s.hasChunks()){let o=s.clean();s.setCookies(o)}t.setCookie(r.name,i,n)}}async function Ev(t){let e=CC(t,t.context.authCookies.accountData.name);if(e){let r=lr(await j0(e,t.context.secretConfig,"better-auth-account"));if(r)return r}return null}var Jh,oW,sW,iW,cme,RC,kC,lme,W0=I(()=>{U0();lp();Jh=le(require("zod"),1),oW=4096,sW=200,iW=oW-sW;cme=t=>(e,r,n)=>{let i=ynt(e,n),s=n.context.logger;return{getValue(){return bnt(i)},hasChunks(){return Object.keys(i).length>0},chunk(o,a){let c=ame(i,r);for(let d in i)delete i[d];let l=c,u=vnt(t,{name:e,value:o,attributes:{...r,...a}},i,s);for(let d of u)l[d.name]=d;return Object.values(l)},clean(){let o=ame(i,r);for(let a in i)delete i[a];return Object.values(o)},setCookies(o){for(let a of o)n.setCookie(a.name,a.value,a.attributes)}}},RC=cme("Session"),kC=cme("Account");lme=Jh.optional(Jh.object({disableCookieCache:Jh.coerce.boolean().meta({description:"Disable cookie cache and fetch session from database"}).optional(),disableRefresh:Jh.coerce.boolean().meta({description:"Disable session refresh. Useful for checking session status, without updating the session"}).optional()}))});var aW,_nt,cW,lW=I(()=>{aW=new Map,_nt=new TextEncoder,cW={decode:(t,e="utf-8")=>(aW.has(e)||aW.set(e,new TextDecoder(e)),aW.get(e).decode(t)),encode:_nt.encode}});var Ent,uW,ume=I(()=>{Ent="0123456789abcdef",uW={encode:t=>{if(typeof t=="string"&&(t=new TextEncoder().encode(t)),t.byteLength===0)return"";let e=new Uint8Array(t),r="";for(let n of e)r+=n.toString(16).padStart(2,"0");return r},decode:t=>{if(!t)return"";if(typeof t=="string"){if(t.length%2!==0)throw new Error("Invalid hexadecimal string");if(!new RegExp(`^[${Ent}]+$`).test(t))throw new Error("Invalid hexadecimal string");let e=new Uint8Array(t.length/2);for(let r=0;r<t.length;r+=2)e[r/2]=parseInt(t.slice(r,r+2),16);return new TextDecoder().decode(e)}return new TextDecoder().decode(t)}}});var NC,dW=I(()=>{ume();pa();K0();NC=(t="SHA-256",e="none")=>{let r={importKey:async(n,i)=>Ml().importKey("raw",typeof n=="string"?new TextEncoder().encode(n):n,{name:"HMAC",hash:{name:t}},!1,[i]),sign:async(n,i)=>{typeof n=="string"&&(n=await r.importKey(n,"sign"));let s=await Ml().sign("HMAC",n,typeof i=="string"?new TextEncoder().encode(i):i);return e==="hex"?uW.encode(s):e==="base64"||e==="base64url"||e==="base64urlnopad"?da.encode(s,{padding:e!=="base64urlnopad"}):s},verify:async(n,i,s)=>(typeof n=="string"&&(n=await r.importKey(n,"verify")),e==="hex"&&(s=uW.decode(s)),(e==="base64"||e==="base64url"||e==="base64urlnopad")&&(s=await Hi.decode(s)),Ml().verify("HMAC",n,typeof s=="string"?new TextEncoder().encode(s):s,typeof i=="string"?new TextEncoder().encode(i):i))};return r}});function $0(t){let e=typeof t.baseURL=="string"?t.baseURL:void 0,r=typeof t.baseURL=="object"&&t.baseURL!==null?t.baseURL.protocol:void 0,n=(t.advanced?.useSecureCookies!==void 0?t.advanced?.useSecureCookies:r==="https"||r!=="http"&&(e?e.startsWith("https://"):xf))?nme:"",i=!!t.advanced?.crossSubDomainCookies?.enabled,s=i?t.advanced?.crossSubDomainCookies?.domain||(e?new URL(e).hostname:void 0):void 0;if(i&&!s&&!Wa(t.baseURL))throw new me("baseURL is required when crossSubdomainCookies are enabled.");function o(a,c={}){let l=t.advanced?.cookiePrefix||"better-auth",u=t.advanced?.cookies?.[a]?.name||`${l}.${a}`,d=t.advanced?.cookies?.[a]?.attributes??{};return{name:`${n}${u}`,attributes:{secure:!!n,sameSite:"lax",path:"/",httpOnly:!0,...i?{domain:s}:{},...t.advanced?.defaultCookieAttributes,...c,...d}}}return o}function PC(t){let e=$0(t),r=e("session_token",{maxAge:t.session?.expiresIn||tme("7d")}),n=e("session_data",{maxAge:t.session?.cookieCache?.maxAge||300}),i=e("account_data",{maxAge:t.session?.cookieCache?.maxAge||300}),s=e("dont_remember");return{sessionToken:{name:r.name,attributes:r.attributes},sessionData:{name:n.name,attributes:n.attributes},dontRememberToken:{name:s.name,attributes:s.attributes},accountData:{name:i.name,attributes:i.attributes}}}async function G0(t,e,r){if(!t.context.options.session?.cookieCache?.enabled)return;let n=Xs(e.session,t.context.options.session?.additionalFields),i=Br(t.context.options,e.user),s=t.context.options.session?.cookieCache?.version,o="1";if(s){if(typeof s=="string")o=s;else if(typeof s=="function"){let p=s(e.session,e.user);o=_v(p)?await p:p}}let a={session:n,user:i,updatedAt:Date.now(),version:o},c={...t.context.authCookies.sessionData.attributes,maxAge:r?void 0:t.context.authCookies.sessionData.attributes.maxAge},l=xo(c.maxAge||60,"sec").getTime(),u=t.context.options.session?.cookieCache?.strategy||"compact",d;if(u==="jwe"?d=await gC(a,t.context.secretConfig,"better-auth-session",c.maxAge||300):u==="jwt"?d=await hC(a,t.context.secret,c.maxAge||300):d=da.encode(JSON.stringify({session:a,expiresAt:l,signature:await NC("SHA-256","base64urlnopad").sign(t.context.secret,JSON.stringify({...a,expiresAt:l}))}),{padding:!1}),d.length>4093){let p=RC(t.context.authCookies.sessionData.name,c,t),f=p.chunk(d,c);p.setCookies(f)}else{let p=RC(t.context.authCookies.sessionData.name,c,t);if(p.hasChunks()){let f=p.clean();p.setCookies(f)}t.setCookie(t.context.authCookies.sessionData.name,d,c)}if(t.context.options.account?.storeAccountCookie){let p=await Ev(t);p&&await Kf(t,p)}}async function jr(t,e,r,n){let i=await t.getSignedCookie(t.context.authCookies.dontRememberToken.name,t.context.secret);r=r!==void 0?r:!!i;let s=t.context.authCookies.sessionToken.attributes,o=r?void 0:t.context.sessionConfig.expiresIn;await t.setSignedCookie(t.context.authCookies.sessionToken.name,e.session.token,t.context.secret,{...s,maxAge:o,...n}),r&&await t.setSignedCookie(t.context.authCookies.dontRememberToken.name,"true",t.context.secret,t.context.authCookies.dontRememberToken.attributes),await G0(t,e,r),t.context.setNewSession(e)}function fa(t,e){t.setCookie(e.name,"",{...e.attributes,maxAge:0})}function qf(t,e){if(fa(t,t.context.authCookies.sessionToken),fa(t,t.context.authCookies.sessionData),t.context.options.account?.storeAccountCookie){fa(t,t.context.authCookies.accountData);let i=kC(t.context.authCookies.accountData.name,t.context.authCookies.accountData.attributes,t),s=i.clean();i.setCookies(s)}t.context.oauthConfig.storeStateStrategy==="cookie"&&fa(t,t.context.createAuthCookie("oauth_state"));let r=RC(t.context.authCookies.sessionData.name,t.context.authCookies.sessionData.attributes,t),n=r.clean();r.setCookies(n),e||fa(t,t.context.authCookies.dontRememberToken)}var Io=I(()=>{Kh();U0();jl();Yh();OC();rme();ime();W0();vs();rt();wC();pa();lW();dW()});async function pme(t,e,r){let n=tp(32);if(t.context.oauthConfig.storeStateStrategy==="cookie"){let o={...e,oauthState:n},a=await _C({key:t.context.secretConfig,data:JSON.stringify(o)}),c=t.context.createAuthCookie(r?.cookieName??"oauth_state",{maxAge:600});return t.setCookie(c.name,a,c.attributes),{state:n,codeVerifier:e.codeVerifier}}let i=t.context.createAuthCookie(r?.cookieName??"state",{maxAge:300});await t.setSignedCookie(i.name,n,t.context.secret,i.attributes);let s=new Date;if(s.setMinutes(s.getMinutes()+10),!await t.context.internalAdapter.createVerificationValue({value:JSON.stringify({...e,oauthState:n}),identifier:n,expiresAt:s}))throw new Zu("Unable to create verification. Make sure the database adapter is properly working and there is a verification table in the database",{code:"state_generation_error"});return{state:n,codeVerifier:e.codeVerifier}}async function fme(t,e,r){let n=t.context.oauthConfig.storeStateStrategy,i;if(n==="cookie"){let s=t.context.createAuthCookie(r?.cookieName??"oauth_state"),o=t.getCookie(s.name);if(!o)throw new Zu("State mismatch: auth state cookie not found",{code:"state_mismatch",details:{state:e}});try{let a=await EC({key:t.context.secretConfig,data:o});i=dme.parse(JSON.parse(a))}catch(a){throw new Zu("State invalid: Failed to decrypt or parse auth state",{code:"state_invalid",details:{state:e},cause:a})}if(!i.oauthState||i.oauthState!==e)throw new Zu("State mismatch: OAuth state parameter does not match stored state",{code:"state_security_mismatch",details:{state:e}});fa(t,s)}else{let s=await t.context.internalAdapter.findVerificationValue(e);if(!s)throw new Zu("State mismatch: verification not found",{code:"state_mismatch",details:{state:e}});if(i=dme.parse(JSON.parse(s.value)),i.oauthState!==void 0&&i.oauthState!==e)throw new Zu("State mismatch: OAuth state parameter does not match stored state",{code:"state_security_mismatch",details:{state:e}});let o=t.context.createAuthCookie(r?.cookieName??"state"),a=await t.getSignedCookie(o.name,t.context.secret);if(!(r?.skipStateCookieCheck??t.context.oauthConfig.skipStateCookieCheck)&&(!a||a!==e))throw new Zu("State mismatch: State not persisted correctly",{code:"state_security_mismatch",details:{state:e}});fa(t,o),await t.context.internalAdapter.deleteVerificationByIdentifier(e)}if(i.expiresAt<Date.now())throw new Zu("Invalid state: request expired",{code:"state_mismatch",details:{expiresAt:i.expiresAt}});return i}var xs,dme,Zu,mme=I(()=>{b0();SC();Io();rt();xs=le(require("zod"),1),dme=xs.looseObject({callbackURL:xs.string(),codeVerifier:xs.string(),errorURL:xs.string().optional(),newUserURL:xs.string().optional(),expiresAt:xs.number(),oauthState:xs.string().optional(),link:xs.object({email:xs.string(),userId:xs.coerce.string()}).optional(),requestSignUp:xs.boolean().optional()}),Zu=class extends me{code;details;constructor(t,e){super(t,e),this.code=e.code,this.details=e.details}}});function Zh(){return globalThis[V0]||(globalThis[V0]={version:pW,epoch:1,context:Snt},Y0=globalThis[V0]),Y0=globalThis[V0],Y0.version!==pW&&(Y0.version=pW,Y0.epoch++),globalThis[V0]}function fW(){return Zh().version}var V0,Y0,Snt,pW,J0=I(()=>{V0=Symbol.for("better-auth:global"),Y0=null,Snt={},pW="1.6.10"});async function Sv(){let t=await wnt;if(t===null)throw new Error("getAsyncLocalStorage is only available in server code");return t}var wnt,DC=I(()=>{wnt=import("node:async_hooks").then(t=>t.AsyncLocalStorage).catch(t=>{if("AsyncLocalStorage"in globalThis)return globalThis.AsyncLocalStorage;if(typeof window<"u")return null;throw console.warn("[better-auth] Warning: AsyncLocalStorage is not available in this environment. Some features may not work as expected."),console.warn("[better-auth] Please read more about this warning at https://better-auth.com/docs/installation#mount-handler"),console.warn("[better-auth] If you are using Cloudflare Workers, please see: https://developers.cloudflare.com/workers/configuration/compatibility-flags/#nodejs-compatibility-flag"),t})});async function up(){let t=(await hme()).getStore();if(!t)throw new Error("No auth context found. Please make sure you are calling this function within a `runWithEndpointContext` callback.");return t}async function wv(t,e){return(await hme()).run(t,e)}var hme,mW=I(()=>{J0();DC();hme=async()=>{let t=Zh();if(!t.context.endpointContextAsyncStorage){let e=await Sv();t.context.endpointContextAsyncStorage=new e}return t.context.endpointContextAsyncStorage}});async function yW(){return(await gW()).getStore()!==void 0}async function hW(){let t=(await gW()).getStore();if(!t)throw new Error("No request state found. Please make sure you are calling this function within a `runWithRequestState` callback.");return t}async function bW(t,e){return(await gW()).run(t,e)}function Z0(t){let e=Object.freeze({});return{get ref(){return e},async get(){let r=await hW();if(!r.has(e)){let n=await t();return r.set(e,n),n}return r.get(e)},async set(r){(await hW()).set(e,r)}}}var gW,gme=I(()=>{J0();DC();gW=async()=>{let t=Zh();if(!t.context.requestStateAsyncStorage){let e=await Sv();t.context.requestStateAsyncStorage=new e}return t.context.requestStateAsyncStorage}});var MC,Ue,vW,X0,Xh,yme=I(()=>{J0();DC();MC=async()=>{let t=Zh();if(!t.context.adapterAsyncStorage){let e=await Sv();t.context.adapterAsyncStorage=new e}return t.context.adapterAsyncStorage},Ue=async t=>MC().then(e=>e.getStore()?.adapter||t).catch(()=>t),vW=async(t,e)=>{let r=!1;return MC().then(async n=>{r=!0;let i=[],s,o,a=!1;try{s=await n.run({adapter:t,pendingHooks:i},e)}catch(c){o=c,a=!0}for(let c of i)await c();if(a)throw o;return s}).catch(n=>{if(!r)return e();throw n})},X0=async(t,e)=>{let r=!0;return MC().then(async n=>{r=!0;let i=[],s,o,a=!1;try{s=await t.transaction(async c=>n.run({adapter:c,pendingHooks:i},e))}catch(c){a=!0,o=c}for(let c of i)await c();if(a)throw o;return s}).catch(n=>{if(!r)return e();throw n})},Xh=async t=>MC().then(e=>{let r=e.getStore();if(r)r.pendingHooks.push(t);else return t()}).catch(()=>t())});var Xu=I(()=>{J0();mW();gme();yme()});var tZt,_W,bme=I(()=>{Xu();({get:tZt,set:_W}=Z0(()=>null))});async function LC(t,e,r){let n=t.body?.callbackURL||t.context.options.baseURL;if(!n)throw D.from("BAD_REQUEST",ae.CALLBACK_URL_REQUIRED);let i=tp(128),s={...r||{},callbackURL:n,codeVerifier:i,errorURL:t.body?.errorCallbackURL,newUserURL:t.body?.newUserCallbackURL,link:e,expiresAt:Date.now()+600*1e3,requestSignUp:t.body?.requestSignUp};await _W(s);try{return pme(t,s)}catch(o){throw t.context.logger.error("Failed to create verification",o),new D("INTERNAL_SERVER_ERROR",{message:"Unable to create verification",cause:o})}}async function vme(t){let e=t.query.state||t.body?.state,r=t.context.options.onAPIError?.errorURL||`${t.context.baseURL}/error`,n;try{n=await fme(t,e)}catch(i){throw t.context.logger.error("Failed to parse state",i),i instanceof Zu&&i.code==="state_security_mismatch"?t.redirect(`${r}?error=state_mismatch`):t.redirect(`${r}?error=please_restart_the_process`)}return n.errorURL||(n.errorURL=r),n&&await _W(n),n}var jC=I(()=>{b0();bme();mme();rt()});var Tv,UC=I(()=>{Tv={scope:"server"}});async function _me(t,e){let r=t.headers.get("content-type")||"",n=r.toLowerCase();if(t.body){if(e&&e.length>0&&!e.some(i=>{let s=n.split(";")[0].trim(),o=i.toLowerCase().trim();return s===o||s.includes(o)}))throw n?new ua(415,{message:`Content-Type "${r}" is not allowed. Allowed types: ${e.join(", ")}`,code:"UNSUPPORTED_MEDIA_TYPE"}):new ua(415,{message:`Content-Type is required. Allowed types: ${e.join(", ")}`,code:"UNSUPPORTED_MEDIA_TYPE"});if(Tnt.test(n))return await t.json();if(n.includes("application/x-www-form-urlencoded")){let i=await t.formData(),s={};return i.forEach((o,a)=>{s[a]=o.toString()}),s}if(n.includes("multipart/form-data")){let i=await t.formData(),s={};return i.forEach((o,a)=>{s[a]=o}),s}return n.includes("text/plain")?await t.text():n.includes("application/octet-stream")?await t.arrayBuffer():n.includes("application/pdf")||n.includes("image/")||n.includes("video/")?await t.blob():n.includes("application/stream")||t.body instanceof ReadableStream?t.body:await t.text()}}function dp(t){return t instanceof ua||t?.name==="APIError"}function Eme(t){try{return t.includes("%")?decodeURIComponent(t):t}catch{return t}}async function Sme(t){try{return{data:await t,error:null}}catch(e){return{data:null,error:e}}}function KC(t){return t instanceof Request||Object.prototype.toString.call(t)==="[object Request]"}var Tnt,Qh=I(()=>{If();Tnt=/^application\/([a-z0-9.+-]*\+)?json/i});function xnt(t){if(t===void 0)return!1;let e=typeof t;return e==="string"||e==="number"||e==="boolean"||e===null?!0:e!=="object"?!1:Array.isArray(t)?!0:t.buffer?!1:t.constructor&&t.constructor.name==="Object"||typeof t.toJSON=="function"}function Int(t,e,r){let n=0,i=new WeakMap;return JSON.stringify(t,(o,a)=>{if(typeof a=="bigint")return a.toString();if(typeof a=="object"&&a!==null){if(i.has(a))return`[Circular ref-${i.get(a)}]`;i.set(a,n++)}return e?e(o,a):a},r)}function Ant(t){return!t||typeof t!="object"?!1:"_flag"in t&&t._flag==="json"}function EW(t){for(let e of Ont)t.delete(e)}function Ul(t,e){if(t instanceof Response){if(e?.headers){let i=new Headers(e.headers);EW(i),i.forEach((s,o)=>{t.headers.set(o,s)})}return t}if(Ant(t)){let i=t.body,s=t.routerResponse;if(s instanceof Response)return s;let o=new Headers;if(s?.headers){let a=new Headers(s.headers);for(let[c,l]of a.entries())a.set(c,l)}if(t.headers)for(let[a,c]of new Headers(t.headers).entries())o.set(a,c);if(e?.headers){let a=new Headers(e.headers);EW(a);for(let[c,l]of a.entries())o.set(c,l)}return o.set("Content-Type","application/json"),new Response(JSON.stringify(i),{...s,headers:o,status:t.status??e?.status??s?.status,statusText:e?.statusText??s?.statusText})}if(dp(t))return Ul(t.body,{status:e?.status??t.statusCode,statusText:t.status.toString(),headers:e?.headers||t.headers});let r=t,n=new Headers(e?.headers);return EW(n),t?typeof t=="string"?(r=t,n.set("Content-Type","text/plain")):t instanceof ArrayBuffer||ArrayBuffer.isView(t)?(r=t,n.set("Content-Type","application/octet-stream")):t instanceof Blob?(r=t,n.set("Content-Type",t.type||"application/octet-stream")):t instanceof FormData?r=t:t instanceof URLSearchParams?(r=t,n.set("Content-Type","application/x-www-form-urlencoded")):t instanceof ReadableStream?(r=t,n.set("Content-Type","application/octet-stream")):xnt(t)&&(r=Int(t),n.set("Content-Type","application/json")):(t===null&&(r=JSON.stringify(null)),n.set("content-type","application/json")),new Response(r,{...e,headers:n})}var Ont,qC=I(()=>{If();Qh();Ont=new Set(["host","user-agent","referer","from","expect","authorization","proxy-authorization","cookie","origin","accept-charset","accept-encoding","accept-language","if-match","if-none-match","if-modified-since","if-unmodified-since","if-range","range","max-forwards","connection","keep-alive","transfer-encoding","te","upgrade","trailer","proxy-connection","content-length"])});var SW,wW,wme,knt,Tme,TW=I(()=>{K0();SW={name:"HMAC",hash:"SHA-256"},wW=async t=>{let e=typeof t=="string"?new TextEncoder().encode(t):t;return await Ml().importKey("raw",e,SW,!1,["sign","verify"])},wme=async(t,e,r)=>{try{let n=atob(t),i=new Uint8Array(n.length);for(let s=0,o=n.length;s<o;s++)i[s]=n.charCodeAt(s);return await Ml().verify(SW,r,i,new TextEncoder().encode(e))}catch{return!1}},knt=async(t,e)=>{let r=await wW(e),n=await Ml().sign(SW.name,r,new TextEncoder().encode(t));return btoa(String.fromCharCode(...new Uint8Array(n)))},Tme=async(t,e)=>{let r=await knt(t,e);return t=`${t}.${r}`,t=encodeURIComponent(t),t}});function xW(t){if(typeof t!="string")throw new TypeError("argument str must be a string");let e=new Map,r=0;for(;r<t.length;){let n=t.indexOf("=",r);if(n===-1)break;let i=t.indexOf(";",r);if(i===-1)i=t.length;else if(i<n){r=t.lastIndexOf(";",n-1)+1;continue}let s=t.slice(r,n).trim();if(!e.has(s)){let o=t.slice(n+1,i).trim();o.codePointAt(0)===34&&(o=o.slice(1,-1)),e.set(s,Eme(o))}r=i+1}return e}var FC,xme,IW,AW,OW=I(()=>{Qh();TW();FC=(t,e)=>{let r=t;if(e)if(e==="secure")r="__Secure-"+t;else if(e==="host")r="__Host-"+t;else return;return r};xme=(t,e,r={})=>{let n;if(r?.prefix==="secure"?n=`${`__Secure-${t}`}=${e}`:r?.prefix==="host"?n=`${`__Host-${t}`}=${e}`:n=`${t}=${e}`,t.startsWith("__Secure-")&&!r.secure&&(r.secure=!0),t.startsWith("__Host-")&&(r.secure||(r.secure=!0),r.path!=="/"&&(r.path="/"),r.domain&&(r.domain=void 0)),r&&typeof r.maxAge=="number"&&r.maxAge>=0){if(r.maxAge>3456e4)throw new Error("Cookies Max-Age SHOULD NOT be greater than 400 days (34560000 seconds) in duration.");n+=`; Max-Age=${Math.floor(r.maxAge)}`}if(r.domain&&r.prefix!=="host"&&(n+=`; Domain=${r.domain}`),r.path&&(n+=`; Path=${r.path}`),r.expires){if(r.expires.getTime()-Date.now()>3456e7)throw new Error("Cookies Expires SHOULD NOT be greater than 400 days (34560000 seconds) in the future.");n+=`; Expires=${r.expires.toUTCString()}`}return r.httpOnly&&(n+="; HttpOnly"),r.secure&&(n+="; Secure"),r.sameSite&&(n+=`; SameSite=${r.sameSite.charAt(0).toUpperCase()+r.sameSite.slice(1)}`),r.partitioned&&(r.secure||(r.secure=!0),n+="; Partitioned"),n},IW=(t,e,r)=>(e=encodeURIComponent(e),xme(t,e,r)),AW=async(t,e,r,n)=>(e=await Tme(e,r),xme(t,e,n))});async function Ame(t,e={}){let r={body:e.body,query:e.query};if(t.body){let n=await t.body["~standard"].validate(e.body);if(n.issues)return{data:null,error:Ime(n.issues,"body")};r.body=n.value}if(t.query){let n=await t.query["~standard"].validate(e.query);if(n.issues)return{data:null,error:Ime(n.issues,"query")};r.query=n.value}return t.requireHeaders&&!e.headers?{data:null,error:{message:"Headers is required",issues:[]}}:t.requireRequest&&!e.request?{data:null,error:{message:"Request is required",issues:[]}}:{data:r,error:null}}function Ime(t,e){return{message:t.map(r=>`[${r.path?.length?`${e}.`+r.path.map(n=>typeof n=="object"?n.key:n).join("."):e}] ${r.message}`).join("; "),issues:t}}var Ome=I(()=>{});var Q0,zC=I(()=>{If();Qh();Ome();TW();OW();Q0=async(t,{options:e,path:r})=>{let n=new Headers,i,{data:s,error:o}=await Ame(e,t);if(o)throw new g0(o.message,o.issues);let a="headers"in t?t.headers instanceof Headers?t.headers:new Headers(t.headers):"request"in t&&KC(t.request)?t.request.headers:null,c=a?.get("cookie"),l=c?xW(c):void 0,u={...t,body:s.body,query:s.query,path:t.path||r||"virtual:",context:"context"in t&&t.context?t.context:{},returned:void 0,headers:t?.headers,request:t?.request,params:"params"in t?t.params:void 0,method:t.method??(Array.isArray(e.method)?e.method[0]:e.method==="*"?"GET":e.method),setHeader:(d,p)=>{n.set(d,p)},getHeader:d=>a?a.get(d):null,getCookie:(d,p)=>{let f=FC(d,p);return f&&l?.get(f)||null},getSignedCookie:async(d,p,f)=>{let m=FC(d,f);if(!m)return null;let h=l?.get(m);if(!h)return null;let y=h.lastIndexOf(".");if(y<1)return null;let g=h.substring(0,y),b=h.substring(y+1);return b.length!==44||!b.endsWith("=")?null:await wme(b,g,await wW(p))?g:!1},setCookie:(d,p,f)=>{let m=IW(d,p,f);return n.append("set-cookie",m),m},setSignedCookie:async(d,p,f,m)=>{let h=await AW(d,p,f,m);return n.append("set-cookie",h),h},redirect:d=>(n.set("location",d),new ua("FOUND",void 0,n)),error:(d,p,f)=>new ua(d,p,f),setStatus:d=>{i=d},json:(d,p)=>t.asResponse?{body:p?.body||d,routerResponse:p,_flag:"json"}:d,responseHeaders:n,get responseStatus(){return i}};for(let d of e.use||[]){let p=await d({...u,returnHeaders:!0,asResponse:!1});p.response&&Object.assign(u.context,p.response),p.headers&&p.headers.forEach((f,m)=>{u.responseHeaders.set(m,f)})}return u}});function Ff(t,e,r){let n=typeof t=="string"?t:void 0,i=typeof e=="object"?e:t,s=typeof e=="function"?e:r;if((i.method==="GET"||i.method==="HEAD")&&i.body)throw new UR("Body is not allowed with GET or HEAD methods");if(n&&/\/{2,}/.test(n))throw new UR("Path cannot contain consecutive slashes");let o=async(...a)=>{let c=a[0]||{},{data:l,error:u}=await Sme(Q0(c,{options:i,path:n}));if(u)throw u instanceof g0?(i.onValidationError&&await i.onValidationError({message:u.message,issues:u.issues}),new ua(400,{message:u.message,code:"VALIDATION_ERROR"})):u;let d=await s(l).catch(async m=>{if(dp(m)){let h=i.onAPIError;if(h&&await h(m),c.asResponse)return m}throw m}),p=l.responseHeaders,f=l.responseStatus;return c.asResponse?Ul(d,{headers:p,status:f}):c.returnHeaders?c.returnStatus?{headers:p,response:d,status:f}:{headers:p,response:d}:c.returnStatus?{response:d,status:f}:d};return o.options=i,o.path=n,o}var BC=I(()=>{If();Qh();qC();zC();Ff.create=t=>(e,r,n)=>Ff(e,{...r,use:[...r?.use||[],...t?.use||[]]},n)});function zf(t,e){let r=async n=>{let i=n,s=typeof t=="function"?t:e,o=await Q0(i,{options:typeof t=="function"?{}:t,path:"/"});if(!s)throw new Error("handler must be defined");try{let a=await s(o),c=o.responseHeaders;return i.returnHeaders?{headers:c,response:a}:a}catch(a){throw dp(a)&&Object.defineProperty(a,Xd,{enumerable:!1,configurable:!0,get(){return o.responseHeaders}}),a}};return r.options=typeof t=="function"?{}:t,r}var kme=I(()=>{If();Qh();zC();BC();zf.create=t=>{function e(r,n){if(typeof r=="function")return zf({use:t?.use},r);if(!n)throw new Error("Middleware handler is required");return zf({...r,method:"*",use:[...t?.use||[],...r.use||[]]},n)}return e}});function Nme(t){switch(t.constructor.name){case"ZodString":return"string";case"ZodNumber":return"number";case"ZodBoolean":return"boolean";case"ZodObject":return"object";case"ZodArray":return"array";default:return"string"}}function Rme(t){let e=[];return t.metadata?.openapi?.parameters?(e.push(...t.metadata.openapi.parameters),e):(t.query instanceof pp.ZodObject&&Object.entries(t.query.shape).forEach(([r,n])=>{n instanceof pp.ZodObject&&e.push({name:r,in:"query",schema:{type:Nme(n),..."minLength"in n&&n.minLength?{minLength:n.minLength}:{},description:n.description}})}),e)}function Rnt(t){if(t.metadata?.openapi?.requestBody)return t.metadata.openapi.requestBody;if(t.body&&(t.body instanceof pp.ZodObject||t.body instanceof pp.ZodOptional)){let e=t.body.shape;if(!e)return;let r={},n=[];return Object.entries(e).forEach(([i,s])=>{s instanceof pp.ZodObject&&(r[i]={type:Nme(s),description:s.description},s instanceof pp.ZodOptional||n.push(i))}),{required:t.body instanceof pp.ZodOptional?!1:!!t.body,content:{"application/json":{schema:{type:"object",properties:r,required:n}}}}}}function Cme(t){return{400:{content:{"application/json":{schema:{type:"object",properties:{message:{type:"string"}},required:["message"]}}},description:"Bad Request. Usually due to missing parameters, or invalid parameters."},401:{content:{"application/json":{schema:{type:"object",properties:{message:{type:"string"}},required:["message"]}}},description:"Unauthorized. Due to missing or invalid authentication."},403:{content:{"application/json":{schema:{type:"object",properties:{message:{type:"string"}}}}},description:"Forbidden. You do not have permission to access this resource or to perform this action."},404:{content:{"application/json":{schema:{type:"object",properties:{message:{type:"string"}}}}},description:"Not Found. The requested resource was not found."},429:{content:{"application/json":{schema:{type:"object",properties:{message:{type:"string"}}}}},description:"Too Many Requests. You have exceeded the rate limit. Try again later."},500:{content:{"application/json":{schema:{type:"object",properties:{message:{type:"string"}}}}},description:"Internal Server Error. This is a problem with the server that you cannot fix."},...t}}async function RW(t,e){let r={schemas:{}};return Object.entries(t).forEach(([n,i])=>{let s=i.options;if(!(!i.path||s.metadata?.SERVER_ONLY)&&(s.method==="GET"&&(kW[i.path]={get:{tags:["Default",...s.metadata?.openapi?.tags||[]],description:s.metadata?.openapi?.description,operationId:s.metadata?.openapi?.operationId,security:[{bearerAuth:[]}],parameters:Rme(s),responses:Cme(s.metadata?.openapi?.responses)}}),s.method==="POST")){let o=Rnt(s);kW[i.path]={post:{tags:["Default",...s.metadata?.openapi?.tags||[]],description:s.metadata?.openapi?.description,operationId:s.metadata?.openapi?.operationId,security:[{bearerAuth:[]}],parameters:Rme(s),...o?{requestBody:o}:{requestBody:{content:{"application/json":{schema:{type:"object",properties:{}}}}}},responses:Cme(s.metadata?.openapi?.responses)}}}}),{openapi:"3.1.1",info:{title:"Better Auth",description:"API Reference for your Better Auth Instance",version:"1.1.0"},components:r,security:[{apiKeyCookie:[]}],servers:[{url:e?.url}],tags:[{name:"Default",description:"Default endpoints that are included with Better Auth by default. These endpoints are not part of any plugin."}],paths:kW}}var pp,kW,CW,NW=I(()=>{pp=require("zod"),kW={};CW=(t,e)=>`<!doctype html> | |||
| at `))}function Ide(t,e){class r extends t{#e;constructor(...i){if(srt()){let o=Error.stackTraceLimit;Error.stackTraceLimit=0,super(...i),Error.stackTraceLimit=o}else super(...i);let s=new Error().stack;s&&(this.#e=xde(s.replace(/^Error/,this.name)))}get errorStack(){return this.#e}}return Object.defineProperty(r.prototype,"constructor",{get(){return e},enumerable:!1,configurable:!0}),r}var Ade,Ode,g0,UR,Xd,ua,If=I(()=>{Ade={OK:200,CREATED:201,ACCEPTED:202,NO_CONTENT:204,MULTIPLE_CHOICES:300,MOVED_PERMANENTLY:301,FOUND:302,SEE_OTHER:303,NOT_MODIFIED:304,TEMPORARY_REDIRECT:307,BAD_REQUEST:400,UNAUTHORIZED:401,PAYMENT_REQUIRED:402,FORBIDDEN:403,NOT_FOUND:404,METHOD_NOT_ALLOWED:405,NOT_ACCEPTABLE:406,PROXY_AUTHENTICATION_REQUIRED:407,REQUEST_TIMEOUT:408,CONFLICT:409,GONE:410,LENGTH_REQUIRED:411,PRECONDITION_FAILED:412,PAYLOAD_TOO_LARGE:413,URI_TOO_LONG:414,UNSUPPORTED_MEDIA_TYPE:415,RANGE_NOT_SATISFIABLE:416,EXPECTATION_FAILED:417,"I'M_A_TEAPOT":418,MISDIRECTED_REQUEST:421,UNPROCESSABLE_ENTITY:422,LOCKED:423,FAILED_DEPENDENCY:424,TOO_EARLY:425,UPGRADE_REQUIRED:426,PRECONDITION_REQUIRED:428,TOO_MANY_REQUESTS:429,REQUEST_HEADER_FIELDS_TOO_LARGE:431,UNAVAILABLE_FOR_LEGAL_REASONS:451,INTERNAL_SERVER_ERROR:500,NOT_IMPLEMENTED:501,BAD_GATEWAY:502,SERVICE_UNAVAILABLE:503,GATEWAY_TIMEOUT:504,HTTP_VERSION_NOT_SUPPORTED:505,VARIANT_ALSO_NEGOTIATES:506,INSUFFICIENT_STORAGE:507,LOOP_DETECTED:508,NOT_EXTENDED:510,NETWORK_AUTHENTICATION_REQUIRED:511},Ode=class extends Error{constructor(t="INTERNAL_SERVER_ERROR",e=void 0,r={},n=typeof t=="number"?t:Ade[t]){super(e?.message,e?.cause?{cause:e.cause}:void 0),this.status=t,this.body=e,this.headers=r,this.statusCode=n,this.name="APIError",this.status=t,this.headers=r,this.statusCode=n,this.body=e}},g0=class extends Ode{constructor(t,e){super(400,{message:t,code:"VALIDATION_ERROR"}),this.message=t,this.issues=e,this.issues=e}},UR=class extends Error{constructor(t){super(t),this.name="BetterCallError"}},Xd=Symbol.for("better-call:api-error-headers"),ua=Ide(Ode,Error)});var me,D,rt=I(()=>{Tde();If();me=class extends Error{constructor(t,e){super(t,e),this.name="BetterAuthError",this.message=t,this.stack=""}},D=class SH extends ua{constructor(...e){super(...e)}static fromStatus(e,r){return new SH(e,r)}static from(e,r){return new SH(e,{message:r.message,code:r.code})}}});function ort(t){let e=t.replace(/:\d+$/,"").replace(/^\[|\]$/g,"").toLowerCase();return e==="localhost"||e.endsWith(".localhost")||e==="::1"||e.startsWith("127.")}function art(t){try{return(new URL(t).pathname.replace(/\/+$/,"")||"/")!=="/"}catch{throw new me(`Invalid base URL: ${t}. Please provide a valid base URL.`)}}function crt(t){try{let e=new URL(t);if(e.protocol!=="http:"&&e.protocol!=="https:")throw new me(`Invalid base URL: ${t}. URL must include 'http://' or 'https://'`)}catch(e){throw e instanceof me?e:new me(`Invalid base URL: ${t}. Please provide a valid base URL.`,{cause:e})}}function Qd(t,e="/api/auth"){if(crt(t),art(t))return t;let r=t.replace(/\/+$/,"");return!e||e==="/"?r:(e=e.startsWith("/")?e:`/${e}`,`${r}${e}`)}function y0(t,e){return!t||t.trim()===""?!1:e==="proto"?t==="http"||t==="https":e==="host"?[/\.\./,/\0/,/[\s]/,/^[.]/,/[<>'"]/,/javascript:/i,/file:/i,/data:/i].some(r=>r.test(t))?!1:/^[a-zA-Z0-9]([a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?(\.[a-zA-Z0-9]([a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?)*(:[0-9]{1,5})?$/.test(t)||/^(\d{1,3}\.){3}\d{1,3}(:[0-9]{1,5})?$/.test(t)||/^\[[0-9a-fA-F:]+\](:[0-9]{1,5})?$/.test(t)||/^localhost(:[0-9]{1,5})?$/i.test(t):!1}function ep(t,e,r,n,i){if(t)return Qd(t,e);if(n!==!1){let a=Zt.BETTER_AUTH_URL||Zt.NEXT_PUBLIC_BETTER_AUTH_URL||Zt.PUBLIC_BETTER_AUTH_URL||Zt.NUXT_PUBLIC_BETTER_AUTH_URL||Zt.NUXT_PUBLIC_AUTH_URL||(Zt.BASE_URL!=="/"?Zt.BASE_URL:void 0);if(a)return Qd(a,e)}let s=r?.headers.get("x-forwarded-host"),o=r?.headers.get("x-forwarded-proto");if(s&&o&&i&&y0(o,"proto")&&y0(s,"host")){let Bnt=Zt.BETTER_AUTH_URL||Zt.NEXT_PUBLIC_BETTER_AUTH_URL||Zt.PUBLIC_BETTER_AUTH_URL||Zt.NUXT_PUBLIC_BETTER_AUTH_URL||Zt.NUXT_PUBLIC_AUTH_URL;if(Bnt){try{let Hnt=new URL(Bnt).host;if(Hnt&&s!==Hnt){}}catch{}if(Bnt){try{let Hnt=new URL(Bnt).host;if(!Hnt||s!==Hnt)s=null}catch{s=null}}}if(s)try{return Qd(`${o}://${s}`,e)}catch{}}if(r){let a=Af(r.url);if(!a)throw new me("Could not get origin from request. Please provide a valid base URL.");return Qd(a,e)}if(typeof window<"u"&&window.location)return Qd(window.location.origin,e)}function Af(t){try{let e=new URL(t);return e.origin==="null"?null:e.origin}catch{return null}}function kde(t){try{return new URL(t).protocol}catch{return null}}function Rde(t){try{return new URL(t).host}catch{return null}}function Wa(t){return typeof t=="object"&&t!==null&&"allowedHosts"in t&&Array.isArray(t.allowedHosts)}function Bu(t){if(t instanceof Request)return!0;if(typeof t!="object"||t===null||Object.prototype.toString.call(t)!=="[object Request]")return!1;let e=t;return typeof e.url=="string"&&typeof e.headers=="object"&&e.headers!==null&&typeof e.headers.get=="function"}function Cde(t,e){let r=Bu(t)?t.headers:t;if(e){let i=r.get("x-forwarded-host");if(i&&y0(i,"host"))return i}let n=r.get("host");if(n&&y0(n,"host"))return n;if(Bu(t))try{return new URL(t.url).host}catch{return null}return null}function lrt(t,e,r){if(e==="http"||e==="https")return e;let n=Bu(t)?t.headers:t;if(r){let s=n.get("x-forwarded-proto");if(s&&y0(s,"proto"))return s}if(Bu(t))try{let s=new URL(t.url);if(s.protocol==="http:"||s.protocol==="https:")return s.protocol.slice(0,-1)}catch{}let i=Cde(t,r);return i&&ort(i)?"http":"https"}function drt(t,e,r,n){let i=Cde(e,n);if(!i){if(t.fallback)return Qd(t.fallback,r);throw new me("Could not determine host from request headers. Please provide a fallback URL in your baseURL config.")}if(t.allowedHosts.some(s=>urt(i,s)))return Qd(`${lrt(e,t.protocol,n)}://${i}`,r);if(t.fallback)return Qd(t.fallback,r);throw new me(`Host "${i}" is not in the allowed hosts list. Allowed hosts: ${t.allowedHosts.join(", ")}. Add this host to your allowedHosts config or provide a fallback URL.`)}function Nde(t,e,r,n,i){if(Wa(t))return r?drt(t,r,e,i):t.fallback?Qd(t.fallback,e):ep(void 0,e,void 0,n,i);let s=Bu(r)?r:void 0;return ep(typeof t=="string"?t:void 0,e,s,n,i)}var urt,Kh=I(()=>{PR();vs();rt();urt=(t,e)=>{if(!t||!e)return!1;let r=t.replace(/^https?:\/\//,"").split("/")[0].toLowerCase(),n=e.replace(/^https?:\/\//,"").split("/")[0].toLowerCase();return n.includes("*")||n.includes("?")?Uh(n)(r):r.toLowerCase()===n.toLowerCase()}});function Pde(t){switch(t){case"a-z":return"abcdefghijklmnopqrstuvwxyz";case"A-Z":return"ABCDEFGHIJKLMNOPQRSTUVWXYZ";case"0-9":return"0123456789";case"-_":return"-_";default:throw new Error(`Unsupported alphabet: ${t}`)}}function ev(...t){let e=t.map(Pde).join("");if(e.length===0)throw new Error("No valid characters provided for random string generation.");let r=e.length;return(n,...i)=>{if(n<=0)throw new Error("Length must be a positive integer.");let s=e,o=r;i.length>0&&(s=i.map(Pde).join(""),o=s.length);let a=Math.floor(256/o)*o,c=new Uint8Array(n*2),l=c.length,u="",d=l,p;for(;u.length<n;)d>=l&&(crypto.getRandomValues(c),d=0),p=c[d++],p<a&&(u+=s[p%o]);return u}}var KR=I(()=>{});var tp,b0=I(()=>{KR();tp=ev("a-z","0-9","A-Z","-_")});function prt(t){return t instanceof Uint8Array||ArrayBuffer.isView(t)&&t.constructor.name==="Uint8Array"&&"BYTES_PER_ELEMENT"in t&&t.BYTES_PER_ELEMENT===1}function qR(t,e=""){if(typeof t!="number"){let r=e&&`"${e}" `;throw new TypeError(`${r}expected number, got ${typeof t}`)}if(!Number.isSafeInteger(t)||t<0){let r=e&&`"${e}" `;throw new RangeError(`${r}expected integer >= 0, got ${t}`)}}function Of(t,e,r=""){let n=prt(t),i=t?.length,s=e!==void 0;if(!n||s&&i!==e){let o=r&&`"${r}" `,a=s?` of length ${e}`:"",c=n?`length=${i}`:`type=${typeof t}`,l=o+"expected Uint8Array"+a+", got "+c;throw n?new RangeError(l):new TypeError(l)}return t}function v0(t){if(typeof t!="function"||typeof t.create!="function")throw new TypeError("Hash must wrapped by utils.createHasher");if(qR(t.outputLen),qR(t.blockLen),t.outputLen<1)throw new Error('"outputLen" must be >= 1');if(t.blockLen<1)throw new Error('"blockLen" must be >= 1')}function tv(t,e=!0){if(t.destroyed)throw new Error("Hash instance has been destroyed");if(e&&t.finished)throw new Error("Hash#digest() has already been called")}function FR(t,e){Of(t,void 0,"digestInto() output");let r=e.outputLen;if(t.length<r)throw new RangeError('"digestInto() output" expected to be of length >='+r)}function rp(...t){for(let e=0;e<t.length;e++)t[e].fill(0)}function zR(t){return new DataView(t.buffer,t.byteOffset,t.byteLength)}function Pl(t,e){return t<<32-e|t>>>e}function Dde(t,e={}){let r=(i,s)=>t(s).update(i).digest(),n=t(void 0);return r.outputLen=n.outputLen,r.blockLen=n.blockLen,r.canXOF=n.canXOF,r.create=i=>t(i),Object.assign(r,e),Object.freeze(r)}var Mde,_0=I(()=>{Mde=t=>({oid:Uint8Array.from([6,9,96,134,72,1,101,3,4,2,t])})});var BR,wH,Lde=I(()=>{_0();BR=class{oHash;iHash;blockLen;outputLen;canXOF=!1;finished=!1;destroyed=!1;constructor(e,r){if(v0(e),Of(r,void 0,"key"),this.iHash=e.create(),typeof this.iHash.update!="function")throw new Error("Expected instance of class which extends utils.Hash");this.blockLen=this.iHash.blockLen,this.outputLen=this.iHash.outputLen;let n=this.blockLen,i=new Uint8Array(n);i.set(r.length>n?e.create().update(r).digest():r);for(let s=0;s<i.length;s++)i[s]^=54;this.iHash.update(i),this.oHash=e.create();for(let s=0;s<i.length;s++)i[s]^=106;this.oHash.update(i),rp(i)}update(e){return tv(this),this.iHash.update(e),this}digestInto(e){tv(this),FR(e,this),this.finished=!0;let r=e.subarray(0,this.outputLen);this.iHash.digestInto(r),this.oHash.update(r),this.oHash.digestInto(r),this.destroy()}digest(){let e=new Uint8Array(this.oHash.outputLen);return this.digestInto(e),e}_cloneInto(e){e||=Object.create(Object.getPrototypeOf(this),{});let{oHash:r,iHash:n,finished:i,destroyed:s,blockLen:o,outputLen:a}=this;return e=e,e.finished=i,e.destroyed=s,e.blockLen=o,e.outputLen=a,e.oHash=r._cloneInto(e.oHash),e.iHash=n._cloneInto(e.iHash),e}clone(){return this._cloneInto()}destroy(){this.destroyed=!0,this.oHash.destroy(),this.iHash.destroy()}},wH=(()=>{let t=((e,r,n)=>new BR(e,r).update(n).digest());return t.create=(e,r)=>new BR(e,r),t})()});function frt(t,e,r){return v0(t),r===void 0&&(r=new Uint8Array(t.outputLen)),wH(t,r,e)}function mrt(t,e,r,n=32){v0(t),qR(n,"length"),Of(e,void 0,"prk");let i=t.outputLen;if(e.length<i)throw new Error('"prk" must be at least HashLen octets');if(n>255*i)throw new Error("Length must be <= 255*HashLen");let s=Math.ceil(n/i);r===void 0?r=jde:Of(r,void 0,"info");let o=new Uint8Array(s*i),a=wH.create(t,e),c=a._cloneInto(),l=new Uint8Array(a.outputLen);for(let u=0;u<s;u++)TH[0]=u+1,c.update(u===0?jde:l).update(r).update(TH).digestInto(l),o.set(l,i*u),a._cloneInto(c);return a.destroy(),c.destroy(),rp(l,TH),o.slice(0,n)}var TH,jde,Ude,Kde=I(()=>{Lde();_0();TH=Uint8Array.of(0),jde=Uint8Array.of();Ude=(t,e,r,n,i)=>mrt(t,frt(t,e,r),n,i)});function qde(t,e,r){return t&e^~t&r}function Fde(t,e,r){return t&e^t&r^e&r}var HR,np,zde=I(()=>{_0();HR=class{blockLen;outputLen;canXOF=!1;padOffset;isLE;buffer;view;finished=!1;length=0;pos=0;destroyed=!1;constructor(e,r,n,i){this.blockLen=e,this.outputLen=r,this.padOffset=n,this.isLE=i,this.buffer=new Uint8Array(e),this.view=zR(this.buffer)}update(e){tv(this),Of(e);let{view:r,buffer:n,blockLen:i}=this,s=e.length;for(let o=0;o<s;){let a=Math.min(i-this.pos,s-o);if(a===i){let c=zR(e);for(;i<=s-o;o+=i)this.process(c,o);continue}n.set(e.subarray(o,o+a),this.pos),this.pos+=a,o+=a,this.pos===i&&(this.process(r,0),this.pos=0)}return this.length+=e.length,this.roundClean(),this}digestInto(e){tv(this),FR(e,this),this.finished=!0;let{buffer:r,view:n,blockLen:i,isLE:s}=this,{pos:o}=this;r[o++]=128,rp(this.buffer.subarray(o)),this.padOffset>i-o&&(this.process(n,0),o=0);for(let d=o;d<i;d++)r[d]=0;n.setBigUint64(i-8,BigInt(this.length*8),s),this.process(n,0);let a=zR(e),c=this.outputLen;if(c%4)throw new Error("_sha2: outputLen must be aligned to 32bit");let l=c/4,u=this.get();if(l>u.length)throw new Error("_sha2: outputLen bigger than state");for(let d=0;d<l;d++)a.setUint32(4*d,u[d],s)}digest(){let{buffer:e,outputLen:r}=this;this.digestInto(e);let n=e.slice(0,r);return this.destroy(),n}_cloneInto(e){e||=new this.constructor,e.set(...this.get());let{blockLen:r,buffer:n,length:i,finished:s,destroyed:o,pos:a}=this;return e.destroyed=o,e.finished=s,e.length=i,e.pos=a,i%r&&e.buffer.set(n),e}clone(){return this._cloneInto()}},np=Uint32Array.from([1779033703,3144134277,1013904242,2773480762,1359893119,2600822924,528734635,1541459225])});var hrt,kf,xH,IH,Bde,Hde=I(()=>{zde();_0();hrt=Uint32Array.from([1116352408,1899447441,3049323471,3921009573,961987163,1508970993,2453635748,2870763221,3624381080,310598401,607225278,1426881987,1925078388,2162078206,2614888103,3248222580,3835390401,4022224774,264347078,604807628,770255983,1249150122,1555081692,1996064986,2554220882,2821834349,2952996808,3210313671,3336571891,3584528711,113926993,338241895,666307205,773529912,1294757372,1396182291,1695183700,1986661051,2177026350,2456956037,2730485921,2820302411,3259730800,3345764771,3516065817,3600352804,4094571909,275423344,430227734,506948616,659060556,883997877,958139571,1322822218,1537002063,1747873779,1955562222,2024104815,2227730452,2361852424,2428436474,2756734187,3204031479,3329325298]),kf=new Uint32Array(64),xH=class extends HR{constructor(e){super(64,e,8,!1)}get(){let{A:e,B:r,C:n,D:i,E:s,F:o,G:a,H:c}=this;return[e,r,n,i,s,o,a,c]}set(e,r,n,i,s,o,a,c){this.A=e|0,this.B=r|0,this.C=n|0,this.D=i|0,this.E=s|0,this.F=o|0,this.G=a|0,this.H=c|0}process(e,r){for(let d=0;d<16;d++,r+=4)kf[d]=e.getUint32(r,!1);for(let d=16;d<64;d++){let p=kf[d-15],f=kf[d-2],m=Pl(p,7)^Pl(p,18)^p>>>3,h=Pl(f,17)^Pl(f,19)^f>>>10;kf[d]=h+kf[d-7]+m+kf[d-16]|0}let{A:n,B:i,C:s,D:o,E:a,F:c,G:l,H:u}=this;for(let d=0;d<64;d++){let p=Pl(a,6)^Pl(a,11)^Pl(a,25),f=u+p+qde(a,c,l)+hrt[d]+kf[d]|0,h=(Pl(n,2)^Pl(n,13)^Pl(n,22))+Fde(n,i,s)|0;u=l,l=c,c=a,a=o+f|0,o=s,s=i,i=n,n=f+h|0}n=n+this.A|0,i=i+this.B|0,s=s+this.C|0,o=o+this.D|0,a=a+this.E|0,c=c+this.F|0,l=l+this.G|0,u=u+this.H|0,this.set(n,i,s,o,a,c,l,u)}roundClean(){rp(kf)}destroy(){this.destroyed=!0,this.set(0,0,0,0,0,0,0,0),rp(this.buffer)}},IH=class extends xH{A=np[0]|0;B=np[1]|0;C=np[2]|0;D=np[3]|0;E=np[4]|0;F=np[5]|0;G=np[6]|0;H=np[7]|0;constructor(){super(32)}},Bde=Dde(()=>new IH,Mde(1))});function fi(...t){let e=t.reduce((i,{length:s})=>i+s,0),r=new Uint8Array(e),n=0;for(let i of t)r.set(i,n),n+=i.length;return r}function AH(t,e,r){if(e<0||e>=WR)throw new RangeError(`value must be >= 0 and <= ${WR-1}. Received ${e}`);t.set([e>>>24,e>>>16,e>>>8,e&255],r)}function OH(t){let e=Math.floor(t/WR),r=t%WR,n=new Uint8Array(8);return AH(n,e,0),AH(n,r,4),n}function $R(t){let e=new Uint8Array(4);return AH(e,t),e}function Bn(t){let e=new Uint8Array(t.length);for(let r=0;r<t.length;r++){let n=t.charCodeAt(r);if(n>127)throw new TypeError("non-ASCII string encountered in encode()");e[r]=n}return e}var qh,_s,WR,Vs=I(()=>{qh=new TextEncoder,_s=new TextDecoder,WR=2**32});function Wde(t){if(Uint8Array.prototype.toBase64)return t.toBase64();let e=32768,r=[];for(let n=0;n<t.length;n+=e)r.push(String.fromCharCode.apply(null,t.subarray(n,n+e)));return btoa(r.join(""))}function $de(t){if(Uint8Array.fromBase64)return Uint8Array.fromBase64(t);let e=atob(t),r=new Uint8Array(e.length);for(let n=0;n<e.length;n++)r[n]=e.charCodeAt(n);return r}var Gde=I(()=>{});var E0={};ui(E0,{decode:()=>_o,encode:()=>bn});function _o(t){if(Uint8Array.fromBase64)return Uint8Array.fromBase64(typeof t=="string"?t:_s.decode(t),{alphabet:"base64url"});let e=t;e instanceof Uint8Array&&(e=_s.decode(e)),e=e.replace(/-/g,"+").replace(/_/g,"/");try{return $de(e)}catch{throw new TypeError("The input to be decoded is not correctly encoded.")}}function bn(t){let e=t;return typeof e=="string"&&(e=qh.encode(e)),Uint8Array.prototype.toBase64?e.toBase64({alphabet:"base64url",omitPadding:!0}):Wde(e).replace(/=/g,"").replace(/\+/g,"-").replace(/\//g,"_")}var Ys=I(()=>{Vs();Gde()});function grt(t){return parseInt(t.name.slice(4),10)}function GR(t,e){if(grt(t.hash)!==e)throw Eo(`SHA-${e}`,"algorithm.hash")}function yrt(t){switch(t){case"ES256":return"P-256";case"ES384":return"P-384";case"ES512":return"P-521";default:throw new Error("unreachable")}}function Vde(t,e){if(e&&!t.usages.includes(e))throw new TypeError(`CryptoKey does not support this operation, its usages must include ${e}.`)}function Yde(t,e,r){switch(e){case"HS256":case"HS384":case"HS512":{if(!Hu(t.algorithm,"HMAC"))throw Eo("HMAC");GR(t.algorithm,parseInt(e.slice(2),10));break}case"RS256":case"RS384":case"RS512":{if(!Hu(t.algorithm,"RSASSA-PKCS1-v1_5"))throw Eo("RSASSA-PKCS1-v1_5");GR(t.algorithm,parseInt(e.slice(2),10));break}case"PS256":case"PS384":case"PS512":{if(!Hu(t.algorithm,"RSA-PSS"))throw Eo("RSA-PSS");GR(t.algorithm,parseInt(e.slice(2),10));break}case"Ed25519":case"EdDSA":{if(!Hu(t.algorithm,"Ed25519"))throw Eo("Ed25519");break}case"ML-DSA-44":case"ML-DSA-65":case"ML-DSA-87":{if(!Hu(t.algorithm,e))throw Eo(e);break}case"ES256":case"ES384":case"ES512":{if(!Hu(t.algorithm,"ECDSA"))throw Eo("ECDSA");let n=yrt(e);if(t.algorithm.namedCurve!==n)throw Eo(n,"algorithm.namedCurve");break}default:throw new TypeError("CryptoKey does not support this operation")}Vde(t,r)}function $a(t,e,r){switch(e){case"A128GCM":case"A192GCM":case"A256GCM":{if(!Hu(t.algorithm,"AES-GCM"))throw Eo("AES-GCM");let n=parseInt(e.slice(1,4),10);if(t.algorithm.length!==n)throw Eo(n,"algorithm.length");break}case"A128KW":case"A192KW":case"A256KW":{if(!Hu(t.algorithm,"AES-KW"))throw Eo("AES-KW");let n=parseInt(e.slice(1,4),10);if(t.algorithm.length!==n)throw Eo(n,"algorithm.length");break}case"ECDH":{switch(t.algorithm.name){case"ECDH":case"X25519":break;default:throw Eo("ECDH or X25519")}break}case"PBES2-HS256+A128KW":case"PBES2-HS384+A192KW":case"PBES2-HS512+A256KW":if(!Hu(t.algorithm,"PBKDF2"))throw Eo("PBKDF2");break;case"RSA-OAEP":case"RSA-OAEP-256":case"RSA-OAEP-384":case"RSA-OAEP-512":{if(!Hu(t.algorithm,"RSA-OAEP"))throw Eo("RSA-OAEP");GR(t.algorithm,parseInt(e.slice(9),10)||1);break}default:throw new TypeError("CryptoKey does not support this operation")}Vde(t,r)}var Eo,Hu,Fh=I(()=>{Eo=(t,e="algorithm.name")=>new TypeError(`CryptoKey does not support this operation, its ${e} must be ${t}`),Hu=(t,e)=>t.name===e});function Jde(t,e,...r){if(r=r.filter(Boolean),r.length>2){let n=r.pop();t+=`one of type ${r.join(", ")}, or ${n}.`}else r.length===2?t+=`one of type ${r[0]} or ${r[1]}.`:t+=`of type ${r[0]}.`;return e==null?t+=` Received ${e}`:typeof e=="function"&&e.name?t+=` Received function ${e.name}`:typeof e=="object"&&e!=null&&e.constructor?.name&&(t+=` Received an instance of ${e.constructor.name}`),t}var Wu,kH,rv=I(()=>{Wu=(t,...e)=>Jde("Key must be ",t,...e),kH=(t,e,...r)=>Jde(`Key for the ${t} algorithm must be `,e,...r)});var Si,Es,zh,Bh,Pt,nv,Me,zr,Js,VR,S0,iv,YR,JR,ZR,cn=I(()=>{Si=class extends Error{static code="ERR_JOSE_GENERIC";code="ERR_JOSE_GENERIC";constructor(e,r){super(e,r),this.name=this.constructor.name,Error.captureStackTrace?.(this,this.constructor)}},Es=class extends Si{static code="ERR_JWT_CLAIM_VALIDATION_FAILED";code="ERR_JWT_CLAIM_VALIDATION_FAILED";claim;reason;payload;constructor(e,r,n="unspecified",i="unspecified"){super(e,{cause:{claim:n,reason:i,payload:r}}),this.claim=n,this.reason=i,this.payload=r}},zh=class extends Si{static code="ERR_JWT_EXPIRED";code="ERR_JWT_EXPIRED";claim;reason;payload;constructor(e,r,n="unspecified",i="unspecified"){super(e,{cause:{claim:n,reason:i,payload:r}}),this.claim=n,this.reason=i,this.payload=r}},Bh=class extends Si{static code="ERR_JOSE_ALG_NOT_ALLOWED";code="ERR_JOSE_ALG_NOT_ALLOWED"},Pt=class extends Si{static code="ERR_JOSE_NOT_SUPPORTED";code="ERR_JOSE_NOT_SUPPORTED"},nv=class extends Si{static code="ERR_JWE_DECRYPTION_FAILED";code="ERR_JWE_DECRYPTION_FAILED";constructor(e="decryption operation failed",r){super(e,r)}},Me=class extends Si{static code="ERR_JWE_INVALID";code="ERR_JWE_INVALID"},zr=class extends Si{static code="ERR_JWS_INVALID";code="ERR_JWS_INVALID"},Js=class extends Si{static code="ERR_JWT_INVALID";code="ERR_JWT_INVALID"},VR=class extends Si{static code="ERR_JWK_INVALID";code="ERR_JWK_INVALID"},S0=class extends Si{static code="ERR_JWKS_INVALID";code="ERR_JWKS_INVALID"},iv=class extends Si{static code="ERR_JWKS_NO_MATCHING_KEY";code="ERR_JWKS_NO_MATCHING_KEY";constructor(e="no applicable key found in the JSON Web Key Set",r){super(e,r)}},YR=class extends Si{[Symbol.asyncIterator];static code="ERR_JWKS_MULTIPLE_MATCHING_KEYS";code="ERR_JWKS_MULTIPLE_MATCHING_KEYS";constructor(e="multiple matching keys found in the JSON Web Key Set",r){super(e,r)}},JR=class extends Si{static code="ERR_JWKS_TIMEOUT";code="ERR_JWKS_TIMEOUT";constructor(e="request timed out",r){super(e,r)}},ZR=class extends Si{static code="ERR_JWS_SIGNATURE_VERIFICATION_FAILED";code="ERR_JWS_SIGNATURE_VERIFICATION_FAILED";constructor(e="signature verification failed",r){super(e,r)}}});function sv(t){if(!ip(t))throw new Error("CryptoKey instance expected")}var ip,w0,T0,Hh=I(()=>{ip=t=>{if(t?.[Symbol.toStringTag]==="CryptoKey")return!0;try{return t instanceof CryptoKey}catch{return!1}},w0=t=>t?.[Symbol.toStringTag]==="KeyObject",T0=t=>ip(t)||w0(t)});function QR(t){switch(t){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 Pt(`Unsupported JWE Algorithm: ${t}`)}}function XR(t,e){let r=t.byteLength<<3;if(r!==e)throw new Me(`Invalid Content Encryption Key length. Expected ${e} bits, got ${r} bits`)}function Zde(t){switch(t){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 Pt(`Unsupported JWE Algorithm: ${t}`)}}function Xde(t,e){if(e.length<<3!==Zde(t))throw new Me("Invalid Initialization Vector length")}async function Qde(t,e,r){if(!(e instanceof Uint8Array))throw new TypeError(Wu(e,"Uint8Array"));let n=parseInt(t.slice(1,4),10),i=await crypto.subtle.importKey("raw",e.subarray(n>>3),"AES-CBC",!1,[r]),s=await crypto.subtle.importKey("raw",e.subarray(0,n>>3),{hash:`SHA-${n<<1}`,name:"HMAC"},!1,["sign"]);return{encKey:i,macKey:s,keySize:n}}async function epe(t,e,r){return new Uint8Array((await crypto.subtle.sign("HMAC",t,e)).slice(0,r>>3))}async function vrt(t,e,r,n,i){let{encKey:s,macKey:o,keySize:a}=await Qde(t,r,"encrypt"),c=new Uint8Array(await crypto.subtle.encrypt({iv:n,name:"AES-CBC"},s,e)),l=fi(i,n,c,OH(i.length<<3)),u=await epe(o,l,a);return{ciphertext:c,tag:u,iv:n}}async function _rt(t,e){if(!(t instanceof Uint8Array))throw new TypeError("First argument must be a buffer");if(!(e instanceof Uint8Array))throw new TypeError("Second argument must be a buffer");let r={name:"HMAC",hash:"SHA-256"},n=await crypto.subtle.generateKey(r,!1,["sign"]),i=new Uint8Array(await crypto.subtle.sign(r,n,t)),s=new Uint8Array(await crypto.subtle.sign(r,n,e)),o=0,a=-1;for(;++a<32;)o|=i[a]^s[a];return o===0}async function Ert(t,e,r,n,i,s){let{encKey:o,macKey:a,keySize:c}=await Qde(t,e,"decrypt"),l=fi(s,n,r,OH(s.length<<3)),u=await epe(a,l,c),d;try{d=await _rt(i,u)}catch{}if(!d)throw new nv;let p;try{p=new Uint8Array(await crypto.subtle.decrypt({iv:n,name:"AES-CBC"},o,r))}catch{}if(!p)throw new nv;return p}async function Srt(t,e,r,n,i){let s;r instanceof Uint8Array?s=await crypto.subtle.importKey("raw",r,"AES-GCM",!1,["encrypt"]):($a(r,t,"encrypt"),s=r);let o=new Uint8Array(await crypto.subtle.encrypt({additionalData:i,iv:n,name:"AES-GCM",tagLength:128},s,e)),a=o.slice(-16);return{ciphertext:o.slice(0,-16),tag:a,iv:n}}async function wrt(t,e,r,n,i,s){let o;e instanceof Uint8Array?o=await crypto.subtle.importKey("raw",e,"AES-GCM",!1,["decrypt"]):($a(e,t,"decrypt"),o=e);try{return new Uint8Array(await crypto.subtle.decrypt({additionalData:s,iv:n,name:"AES-GCM",tagLength:128},o,fi(r,i)))}catch{throw new nv}}async function eC(t,e,r,n,i){if(!ip(r)&&!(r instanceof Uint8Array))throw new TypeError(Wu(r,"CryptoKey","KeyObject","Uint8Array","JSON Web Key"));switch(n?Xde(t,n):n=brt(t),t){case"A128CBC-HS256":case"A192CBC-HS384":case"A256CBC-HS512":return r instanceof Uint8Array&&XR(r,parseInt(t.slice(-3),10)),vrt(t,e,r,n,i);case"A128GCM":case"A192GCM":case"A256GCM":return r instanceof Uint8Array&&XR(r,parseInt(t.slice(1,4),10)),Srt(t,e,r,n,i);default:throw new Pt(tpe)}}async function tC(t,e,r,n,i,s){if(!ip(e)&&!(e instanceof Uint8Array))throw new TypeError(Wu(e,"CryptoKey","KeyObject","Uint8Array","JSON Web Key"));if(!n)throw new Me("JWE Initialization Vector missing");if(!i)throw new Me("JWE Authentication Tag missing");switch(Xde(t,n),t){case"A128CBC-HS256":case"A192CBC-HS384":case"A256CBC-HS512":return e instanceof Uint8Array&&XR(e,parseInt(t.slice(-3),10)),Ert(t,e,r,n,i,s);case"A128GCM":case"A192GCM":case"A256GCM":return e instanceof Uint8Array&&XR(e,parseInt(t.slice(1,4),10)),wrt(t,e,r,n,i,s);default:throw new Pt(tpe)}}var Rf,brt,tpe,ov=I(()=>{Vs();Fh();rv();cn();Hh();Rf=t=>crypto.getRandomValues(new Uint8Array(QR(t)>>3));brt=t=>crypto.getRandomValues(new Uint8Array(Zde(t)>>3));tpe="Unsupported JWE Content Encryption Algorithm"});function So(t,e){if(t)throw new TypeError(`${e} can only be called once`)}function wo(t,e,r){try{return _o(t)}catch{throw new r(`Failed to base64url decode the ${e}`)}}async function rC(t,e){let r=`SHA-${t.slice(-3)}`;return new Uint8Array(await crypto.subtle.digest(r,e))}var rpe,sp=I(()=>{Ys();rpe=Symbol()});function vn(t){if(!Trt(t)||Object.prototype.toString.call(t)!=="[object Object]")return!1;if(Object.getPrototypeOf(t)===null)return!0;let e=t;for(;Object.getPrototypeOf(e)!==null;)e=Object.getPrototypeOf(e);return Object.getPrototypeOf(t)===e}function Cf(...t){let e=t.filter(Boolean);if(e.length===0||e.length===1)return!0;let r;for(let n of e){let i=Object.keys(n);if(!r||r.size===0){r=new Set(i);continue}for(let s of i){if(r.has(s))return!1;r.add(s)}}return!0}var Trt,Wh,npe,ipe,spe,Ss=I(()=>{Trt=t=>typeof t=="object"&&t!==null;Wh=t=>vn(t)&&typeof t.kty=="string",npe=t=>t.kty!=="oct"&&(t.kty==="AKP"&&typeof t.priv=="string"||typeof t.d=="string"),ipe=t=>t.kty!=="oct"&&t.d===void 0&&t.priv===void 0,spe=t=>t.kty==="oct"&&typeof t.k=="string"});function ope(t,e){if(t.algorithm.length!==parseInt(e.slice(1,4),10))throw new TypeError(`Invalid key size for alg: ${e}`)}function ape(t,e,r){return t instanceof Uint8Array?crypto.subtle.importKey("raw",t,"AES-KW",!0,[r]):($a(t,e,r),t)}async function x0(t,e,r){let n=await ape(e,t,"wrapKey");ope(n,t);let i=await crypto.subtle.importKey("raw",r,{hash:"SHA-256",name:"HMAC"},!0,["sign"]);return new Uint8Array(await crypto.subtle.wrapKey("raw",i,n,"AES-KW"))}async function I0(t,e,r){let n=await ape(e,t,"unwrapKey");ope(n,t);let i=await crypto.subtle.unwrapKey("raw",r,n,"AES-KW",{hash:"SHA-256",name:"HMAC"},!0,["sign"]);return new Uint8Array(await crypto.subtle.exportKey("raw",i))}var RH=I(()=>{Fh()});function CH(t){return fi($R(t.length),t)}async function Irt(t,e,r){let n=e>>3,i=32,s=Math.ceil(n/i),o=new Uint8Array(s*i);for(let a=1;a<=s;a++){let c=new Uint8Array(4+t.length+r.length);c.set($R(a),0),c.set(t,4),c.set(r,4+t.length);let l=await rC("sha256",c);o.set(l,(a-1)*i)}return o.slice(0,n)}async function NH(t,e,r,n,i=new Uint8Array,s=new Uint8Array){$a(t,"ECDH"),$a(e,"ECDH","deriveBits");let o=CH(Bn(r)),a=CH(i),c=CH(s),l=$R(n),u=new Uint8Array,d=fi(o,a,c,l,u),p=new Uint8Array(await crypto.subtle.deriveBits({name:t.algorithm.name,public:t},e,Art(t)));return Irt(p,n,d)}function Art(t){return t.algorithm.name==="X25519"?256:Math.ceil(parseInt(t.algorithm.namedCurve.slice(-3),10)/8)<<3}function PH(t){switch(t.algorithm.namedCurve){case"P-256":case"P-384":case"P-521":return!0;default:return t.algorithm.name==="X25519"}}var lpe=I(()=>{Vs();Fh();sp()});function krt(t,e){return t instanceof Uint8Array?crypto.subtle.importKey("raw",t,"PBKDF2",!1,["deriveBits"]):($a(t,e,"deriveBits"),t)}async function upe(t,e,r,n){if(!(t instanceof Uint8Array)||t.length<8)throw new Me("PBES2 Salt Input must be 8 or more octets");if(!Number.isSafeInteger(r)||Math.sign(r)!==1)throw new Me("PBES2 Count Input must be a positive integer");let i=Rrt(e,t),s=parseInt(e.slice(13,16),10),o={hash:`SHA-${e.slice(8,11)}`,iterations:r,name:"PBKDF2",salt:i},a=await krt(n,e);return new Uint8Array(await crypto.subtle.deriveBits(o,a,s))}async function dpe(t,e,r,n=2048,i=crypto.getRandomValues(new Uint8Array(16))){let s=await upe(i,t,n,e);return{encryptedKey:await x0(t.slice(-6),s,r),p2c:n,p2s:bn(i)}}async function ppe(t,e,r,n,i){let s=await upe(i,t,n,e);return I0(t.slice(-6),s,r)}var Rrt,fpe=I(()=>{Ys();RH();Fh();Vs();cn();Rrt=(t,e)=>fi(Bn(t),Uint8Array.of(0),e)});function A0(t,e){if(t.startsWith("RS")||t.startsWith("PS")){let{modulusLength:r}=e.algorithm;if(typeof r!="number"||r<2048)throw new TypeError(`${t} requires key modulusLength to be 2048 bits or larger`)}}function mpe(t,e){let r=`SHA-${t.slice(-3)}`;switch(t){case"HS256":case"HS384":case"HS512":return{hash:r,name:"HMAC"};case"PS256":case"PS384":case"PS512":return{hash:r,name:"RSA-PSS",saltLength:parseInt(t.slice(-3),10)>>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:e.namedCurve};case"Ed25519":case"EdDSA":return{name:"Ed25519"};case"ML-DSA-44":case"ML-DSA-65":case"ML-DSA-87":return{name:t};default:throw new Pt(`alg ${t} is not supported either by JOSE or your javascript runtime`)}}async function hpe(t,e,r){if(e instanceof Uint8Array){if(!t.startsWith("HS"))throw new TypeError(Wu(e,"CryptoKey","KeyObject","JSON Web Key"));return crypto.subtle.importKey("raw",e,{hash:`SHA-${t.slice(-3)}`,name:"HMAC"},!1,[r])}return Yde(e,t,r),e}async function gpe(t,e,r){let n=await hpe(t,e,"sign");A0(t,n);let i=await crypto.subtle.sign(mpe(t,n.algorithm),n,r);return new Uint8Array(i)}async function ype(t,e,r,n){let i=await hpe(t,e,"verify");A0(t,i);let s=mpe(t,i.algorithm);try{return await crypto.subtle.verify(s,i,r,n)}catch{return!1}}var nC=I(()=>{cn();Fh();rv()});async function vpe(t,e,r){return $a(e,t,"encrypt"),A0(t,e),new Uint8Array(await crypto.subtle.encrypt(bpe(t),e,r))}async function _pe(t,e,r){return $a(e,t,"decrypt"),A0(t,e),new Uint8Array(await crypto.subtle.decrypt(bpe(t),e,r))}var bpe,Epe=I(()=>{Fh();nC();cn();bpe=t=>{switch(t){case"RSA-OAEP":case"RSA-OAEP-256":case"RSA-OAEP-384":case"RSA-OAEP-512":return"RSA-OAEP";default:throw new Pt(`alg ${t} is not supported either by JOSE or your javascript runtime`)}}});function Prt(t){let e,r;switch(t.kty){case"AKP":{switch(t.alg){case"ML-DSA-44":case"ML-DSA-65":case"ML-DSA-87":e={name:t.alg},r=t.priv?["sign"]:["verify"];break;default:throw new Pt(iC)}break}case"RSA":{switch(t.alg){case"PS256":case"PS384":case"PS512":e={name:"RSA-PSS",hash:`SHA-${t.alg.slice(-3)}`},r=t.d?["sign"]:["verify"];break;case"RS256":case"RS384":case"RS512":e={name:"RSASSA-PKCS1-v1_5",hash:`SHA-${t.alg.slice(-3)}`},r=t.d?["sign"]:["verify"];break;case"RSA-OAEP":case"RSA-OAEP-256":case"RSA-OAEP-384":case"RSA-OAEP-512":e={name:"RSA-OAEP",hash:`SHA-${parseInt(t.alg.slice(-3),10)||1}`},r=t.d?["decrypt","unwrapKey"]:["encrypt","wrapKey"];break;default:throw new Pt(iC)}break}case"EC":{switch(t.alg){case"ES256":case"ES384":case"ES512":e={name:"ECDSA",namedCurve:{ES256:"P-256",ES384:"P-384",ES512:"P-521"}[t.alg]},r=t.d?["sign"]:["verify"];break;case"ECDH-ES":case"ECDH-ES+A128KW":case"ECDH-ES+A192KW":case"ECDH-ES+A256KW":e={name:"ECDH",namedCurve:t.crv},r=t.d?["deriveBits"]:[];break;default:throw new Pt(iC)}break}case"OKP":{switch(t.alg){case"Ed25519":case"EdDSA":e={name:"Ed25519"},r=t.d?["sign"]:["verify"];break;case"ECDH-ES":case"ECDH-ES+A128KW":case"ECDH-ES+A192KW":case"ECDH-ES+A256KW":e={name:t.crv},r=t.d?["deriveBits"]:[];break;default:throw new Pt(iC)}break}default:throw new Pt('Invalid or unsupported JWK "kty" (Key Type) Parameter value')}return{algorithm:e,keyUsages:r}}async function av(t){if(!t.alg)throw new TypeError('"alg" argument is required when "jwk.alg" is not present');let{algorithm:e,keyUsages:r}=Prt(t),n={...t};return n.kty!=="AKP"&&delete n.alg,delete n.use,crypto.subtle.importKey("jwk",n,e,t.ext??!(t.d||t.priv),t.key_ops??r)}var iC,DH=I(()=>{cn();iC='Invalid or unsupported JWK "alg" (Algorithm) Parameter value'});async function $u(t,e){if(t instanceof Uint8Array||ip(t))return t;if(w0(t)){if(t.type==="secret")return t.export();if("toCryptoKey"in t&&typeof t.toCryptoKey=="function")try{return Drt(t,e)}catch(n){if(n instanceof TypeError)throw n}let r=t.export({format:"jwk"});return Spe(t,r,e)}if(Wh(t))return t.k?_o(t.k):Spe(t,t,e,!0);throw new Error("unreachable")}var cv,lv,Spe,Drt,uv=I(()=>{Ss();Ys();DH();Hh();cv="given KeyObject instance cannot be used for this algorithm",Spe=async(t,e,r,n=!1)=>{lv||=new WeakMap;let i=lv.get(t);if(i?.[r])return i[r];let s=await av({...e,alg:r});return n&&Object.freeze(t),i?i[r]=s:lv.set(t,{[r]:s}),s},Drt=(t,e)=>{lv||=new WeakMap;let r=lv.get(t);if(r?.[e])return r[e];let n=t.type==="public",i=!!n,s;if(t.asymmetricKeyType==="x25519"){switch(e){case"ECDH-ES":case"ECDH-ES+A128KW":case"ECDH-ES+A192KW":case"ECDH-ES+A256KW":break;default:throw new TypeError(cv)}s=t.toCryptoKey(t.asymmetricKeyType,i,n?[]:["deriveBits"])}if(t.asymmetricKeyType==="ed25519"){if(e!=="EdDSA"&&e!=="Ed25519")throw new TypeError(cv);s=t.toCryptoKey(t.asymmetricKeyType,i,[n?"verify":"sign"])}switch(t.asymmetricKeyType){case"ml-dsa-44":case"ml-dsa-65":case"ml-dsa-87":{if(e!==t.asymmetricKeyType.toUpperCase())throw new TypeError(cv);s=t.toCryptoKey(t.asymmetricKeyType,i,[n?"verify":"sign"])}}if(t.asymmetricKeyType==="rsa"){let o;switch(e){case"RSA-OAEP":o="SHA-1";break;case"RS256":case"PS256":case"RSA-OAEP-256":o="SHA-256";break;case"RS384":case"PS384":case"RSA-OAEP-384":o="SHA-384";break;case"RS512":case"PS512":case"RSA-OAEP-512":o="SHA-512";break;default:throw new TypeError(cv)}if(e.startsWith("RSA-OAEP"))return t.toCryptoKey({name:"RSA-OAEP",hash:o},i,n?["encrypt"]:["decrypt"]);s=t.toCryptoKey({name:e.startsWith("PS")?"RSA-PSS":"RSASSA-PKCS1-v1_5",hash:o},i,[n?"verify":"sign"])}if(t.asymmetricKeyType==="ec"){let a=new Map([["prime256v1","P-256"],["secp384r1","P-384"],["secp521r1","P-521"]]).get(t.asymmetricKeyDetails?.namedCurve);if(!a)throw new TypeError(cv);let c={ES256:"P-256",ES384:"P-384",ES512:"P-521"};c[e]&&a===c[e]&&(s=t.toCryptoKey({name:"ECDSA",namedCurve:a},i,[n?"verify":"sign"])),e.startsWith("ECDH-ES")&&(s=t.toCryptoKey({name:"ECDH",namedCurve:a},i,n?[]:["deriveBits"]))}if(!s)throw new TypeError(cv);return r?r[e]=s:lv.set(t,{[e]:s}),s}});async function Ga(t,e,r){if(!vn(t))throw new TypeError("JWK must be an object");let n;switch(e??=t.alg,n??=r?.extractable??t.ext,t.kty){case"oct":if(typeof t.k!="string"||!t.k)throw new TypeError('missing "k" (Key Value) Parameter value');return _o(t.k);case"RSA":if("oth"in t&&t.oth!==void 0)throw new Pt('RSA JWK "oth" (Other Primes Info) Parameter value is not supported');return av({...t,alg:e,ext:n});case"AKP":{if(typeof t.alg!="string"||!t.alg)throw new TypeError('missing "alg" (Algorithm) Parameter value');if(e!==void 0&&e!==t.alg)throw new TypeError("JWK alg and alg option value mismatch");return av({...t,ext:n})}case"EC":case"OKP":return av({...t,alg:e,ext:n});default:throw new Pt('Unsupported "kty" (Key Type) Parameter value')}}var sC=I(()=>{Ys();DH();cn();Ss()});async function wpe(t){if(w0(t))if(t.type==="secret")t=t.export();else return t.export({format:"jwk"});if(t instanceof Uint8Array)return{kty:"oct",k:bn(t)};if(!ip(t))throw new TypeError(Wu(t,"CryptoKey","KeyObject","Uint8Array"));if(!t.extractable)throw new TypeError("non-extractable CryptoKey cannot be exported as a JWK");let{ext:e,key_ops:r,alg:n,use:i,...s}=await crypto.subtle.exportKey("jwk",t);return s.kty==="AKP"&&(s.alg=n),s}var Tpe=I(()=>{rv();Ys();Hh()});async function oC(t){return wpe(t)}var MH=I(()=>{Tpe()});async function xpe(t,e,r,n){let i=t.slice(0,7),s=await eC(i,r,e,n,new Uint8Array);return{encryptedKey:s.ciphertext,iv:bn(s.iv),tag:bn(s.tag)}}async function Ipe(t,e,r,n,i){let s=t.slice(0,7);return tC(s,e,r,n,i,new Uint8Array)}var Ape=I(()=>{ov();Ys()});function O0(t){if(t===void 0)throw new Me("JWE Encrypted Key missing")}async function kpe(t,e,r,n,i){switch(t){case"dir":{if(r!==void 0)throw new Me("Encountered unexpected JWE Encrypted Key");return e}case"ECDH-ES":if(r!==void 0)throw new Me("Encountered unexpected JWE Encrypted Key");case"ECDH-ES+A128KW":case"ECDH-ES+A192KW":case"ECDH-ES+A256KW":{if(!vn(n.epk))throw new Me('JOSE Header "epk" (Ephemeral Public Key) missing or invalid');if(sv(e),!PH(e))throw new Pt("ECDH with the provided key is not allowed or not supported by your javascript runtime");let s=await Ga(n.epk,t);sv(s);let o,a;if(n.apu!==void 0){if(typeof n.apu!="string")throw new Me('JOSE Header "apu" (Agreement PartyUInfo) invalid');o=wo(n.apu,"apu",Me)}if(n.apv!==void 0){if(typeof n.apv!="string")throw new Me('JOSE Header "apv" (Agreement PartyVInfo) invalid');a=wo(n.apv,"apv",Me)}let c=await NH(s,e,t==="ECDH-ES"?n.enc:t,t==="ECDH-ES"?QR(n.enc):parseInt(t.slice(-5,-2),10),o,a);return t==="ECDH-ES"?c:(O0(r),I0(t.slice(-6),c,r))}case"RSA-OAEP":case"RSA-OAEP-256":case"RSA-OAEP-384":case"RSA-OAEP-512":return O0(r),sv(e),_pe(t,e,r);case"PBES2-HS256+A128KW":case"PBES2-HS384+A192KW":case"PBES2-HS512+A256KW":{if(O0(r),typeof n.p2c!="number")throw new Me('JOSE Header "p2c" (PBES2 Count) missing or invalid');let s=i?.maxPBES2Count||1e4;if(n.p2c>s)throw new Me('JOSE Header "p2c" (PBES2 Count) out is of acceptable bounds');if(typeof n.p2s!="string")throw new Me('JOSE Header "p2s" (PBES2 Salt) missing or invalid');let o;return o=wo(n.p2s,"p2s",Me),ppe(t,e,r,n.p2c,o)}case"A128KW":case"A192KW":case"A256KW":return O0(r),I0(t,e,r);case"A128GCMKW":case"A192GCMKW":case"A256GCMKW":{if(O0(r),typeof n.iv!="string")throw new Me('JOSE Header "iv" (Initialization Vector) missing or invalid');if(typeof n.tag!="string")throw new Me('JOSE Header "tag" (Authentication Tag) missing or invalid');let s;s=wo(n.iv,"iv",Me);let o;return o=wo(n.tag,"tag",Me),Ipe(t,e,r,s,o)}default:throw new Pt(Ope)}}async function Rpe(t,e,r,n,i={}){let s,o,a;switch(t){case"dir":{a=r;break}case"ECDH-ES":case"ECDH-ES+A128KW":case"ECDH-ES+A192KW":case"ECDH-ES+A256KW":{if(sv(r),!PH(r))throw new Pt("ECDH with the provided key is not allowed or not supported by your javascript runtime");let{apu:c,apv:l}=i,u;i.epk?u=await $u(i.epk,t):u=(await crypto.subtle.generateKey(r.algorithm,!0,["deriveBits"])).privateKey;let{x:d,y:p,crv:f,kty:m}=await oC(u),h=await NH(r,u,t==="ECDH-ES"?e:t,t==="ECDH-ES"?QR(e):parseInt(t.slice(-5,-2),10),c,l);if(o={epk:{x:d,crv:f,kty:m}},m==="EC"&&(o.epk.y=p),c&&(o.apu=bn(c)),l&&(o.apv=bn(l)),t==="ECDH-ES"){a=h;break}a=n||Rf(e);let y=t.slice(-6);s=await x0(y,h,a);break}case"RSA-OAEP":case"RSA-OAEP-256":case"RSA-OAEP-384":case"RSA-OAEP-512":{a=n||Rf(e),sv(r),s=await vpe(t,r,a);break}case"PBES2-HS256+A128KW":case"PBES2-HS384+A192KW":case"PBES2-HS512+A256KW":{a=n||Rf(e);let{p2c:c,p2s:l}=i;({encryptedKey:s,...o}=await dpe(t,r,a,c,l));break}case"A128KW":case"A192KW":case"A256KW":{a=n||Rf(e),s=await x0(t,r,a);break}case"A128GCMKW":case"A192GCMKW":case"A256GCMKW":{a=n||Rf(e);let{iv:c}=i;({encryptedKey:s,...o}=await xpe(t,r,a,c));break}default:throw new Pt(Ope)}return{cek:a,encryptedKey:s,parameters:o}}var Ope,LH=I(()=>{RH();lpe();fpe();Epe();Ys();uv();cn();sp();ov();sC();MH();Ss();Ape();Hh();Ope='Invalid or unsupported "alg" (JWE Algorithm) header value'});function Nf(t,e,r,n,i){if(i.crit!==void 0&&n?.crit===void 0)throw new t('"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(o=>typeof o!="string"||o.length===0))throw new t('"crit" (Critical) Header Parameter MUST be an array of non-empty strings when present');let s;r!==void 0?s=new Map([...Object.entries(r),...e.entries()]):s=e;for(let o of n.crit){if(!s.has(o))throw new Pt(`Extension Header Parameter "${o}" is not recognized`);if(i[o]===void 0)throw new t(`Extension Header Parameter "${o}" is missing`);if(s.get(o)&&n[o]===void 0)throw new t(`Extension Header Parameter "${o}" MUST be integrity protected`)}return new Set(n.crit)}var k0=I(()=>{cn()});function R0(t,e){if(e!==void 0&&(!Array.isArray(e)||e.some(r=>typeof r!="string")))throw new TypeError(`"${t}" option must be an array of strings`);if(e)return new Set(e)}var jH=I(()=>{});function Pf(t,e,r){switch(t.substring(0,2)){case"A1":case"A2":case"di":case"HS":case"PB":Mrt(t,e,r);break;default:Lrt(t,e,r)}}var dv,UH,Mrt,Lrt,C0=I(()=>{rv();Hh();Ss();dv=t=>t?.[Symbol.toStringTag],UH=(t,e,r)=>{if(e.use!==void 0){let n;switch(r){case"sign":case"verify":n="sig";break;case"encrypt":case"decrypt":n="enc";break}if(e.use!==n)throw new TypeError(`Invalid key for this operation, its "use" must be "${n}" when present`)}if(e.alg!==void 0&&e.alg!==t)throw new TypeError(`Invalid key for this operation, its "alg" must be "${t}" when present`);if(Array.isArray(e.key_ops)){let n;switch(!0){case(r==="sign"||r==="verify"):case t==="dir":case t.includes("CBC-HS"):n=r;break;case t.startsWith("PBES2"):n="deriveBits";break;case/^A\d{3}(?:GCM)?(?:KW)?$/.test(t):!t.includes("GCM")&&t.endsWith("KW")?n=r==="encrypt"?"wrapKey":"unwrapKey":n=r;break;case(r==="encrypt"&&t.startsWith("RSA")):n="wrapKey";break;case r==="decrypt":n=t.startsWith("RSA")?"unwrapKey":"deriveBits";break}if(n&&e.key_ops?.includes?.(n)===!1)throw new TypeError(`Invalid key for this operation, its "key_ops" must include "${n}" when present`)}return!0},Mrt=(t,e,r)=>{if(!(e instanceof Uint8Array)){if(Wh(e)){if(spe(e)&&UH(t,e,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(!T0(e))throw new TypeError(kH(t,e,"CryptoKey","KeyObject","JSON Web Key","Uint8Array"));if(e.type!=="secret")throw new TypeError(`${dv(e)} instances for symmetric algorithms must be of type "secret"`)}},Lrt=(t,e,r)=>{if(Wh(e))switch(r){case"decrypt":case"sign":if(npe(e)&&UH(t,e,r))return;throw new TypeError("JSON Web Key for this operation must be a private JWK");case"encrypt":case"verify":if(ipe(e)&&UH(t,e,r))return;throw new TypeError("JSON Web Key for this operation must be a public JWK")}if(!T0(e))throw new TypeError(kH(t,e,"CryptoKey","KeyObject","JSON Web Key"));if(e.type==="secret")throw new TypeError(`${dv(e)} instances for asymmetric algorithms must not be of type "secret"`);if(e.type==="public")switch(r){case"sign":throw new TypeError(`${dv(e)} instances for asymmetric algorithm signing must be of type "private"`);case"decrypt":throw new TypeError(`${dv(e)} instances for asymmetric algorithm decryption must be of type "private"`)}if(e.type==="private")switch(r){case"verify":throw new TypeError(`${dv(e)} instances for asymmetric algorithm verifying must be of type "public"`);case"encrypt":throw new TypeError(`${dv(e)} instances for asymmetric algorithm encryption must be of type "public"`)}}});function Cpe(t){if(typeof globalThis[t]>"u")throw new Pt(`JWE "zip" (Compression Algorithm) Header Parameter requires the ${t} API.`)}async function Npe(t){Cpe("CompressionStream");let e=new CompressionStream("deflate-raw"),r=e.writable.getWriter();r.write(t).catch(()=>{}),r.close().catch(()=>{});let n=[],i=e.readable.getReader();for(;;){let{value:s,done:o}=await i.read();if(o)break;n.push(s)}return fi(...n)}async function Ppe(t,e){Cpe("DecompressionStream");let r=new DecompressionStream("deflate-raw"),n=r.writable.getWriter();n.write(t).catch(()=>{}),n.close().catch(()=>{});let i=[],s=0,o=r.readable.getReader();for(;;){let{value:a,done:c}=await o.read();if(c)break;if(i.push(a),s+=a.byteLength,e!==1/0&&s>e)throw new Me("Decompressed plaintext exceeded the configured limit")}return fi(...i)}var KH=I(()=>{cn();Vs()});async function Dpe(t,e,r){if(!vn(t))throw new Me("Flattened JWE must be an object");if(t.protected===void 0&&t.header===void 0&&t.unprotected===void 0)throw new Me("JOSE Header missing");if(t.iv!==void 0&&typeof t.iv!="string")throw new Me("JWE Initialization Vector incorrect type");if(typeof t.ciphertext!="string")throw new Me("JWE Ciphertext missing or incorrect type");if(t.tag!==void 0&&typeof t.tag!="string")throw new Me("JWE Authentication Tag incorrect type");if(t.protected!==void 0&&typeof t.protected!="string")throw new Me("JWE Protected Header incorrect type");if(t.encrypted_key!==void 0&&typeof t.encrypted_key!="string")throw new Me("JWE Encrypted Key incorrect type");if(t.aad!==void 0&&typeof t.aad!="string")throw new Me("JWE AAD incorrect type");if(t.header!==void 0&&!vn(t.header))throw new Me("JWE Shared Unprotected Header incorrect type");if(t.unprotected!==void 0&&!vn(t.unprotected))throw new Me("JWE Per-Recipient Unprotected Header incorrect type");let n;if(t.protected)try{let _=_o(t.protected);n=JSON.parse(_s.decode(_))}catch{throw new Me("JWE Protected Header is invalid")}if(!Cf(n,t.header,t.unprotected))throw new Me("JWE Protected, JWE Unprotected Header, and JWE Per-Recipient Unprotected Header Parameter names must be disjoint");let i={...n,...t.header,...t.unprotected};if(Nf(Me,new Map,r?.crit,n,i),i.zip!==void 0&&i.zip!=="DEF")throw new Pt('Unsupported JWE "zip" (Compression Algorithm) Header Parameter value.');if(i.zip!==void 0&&!n?.zip)throw new Me('JWE "zip" (Compression Algorithm) Header Parameter MUST be in a protected header.');let{alg:s,enc:o}=i;if(typeof s!="string"||!s)throw new Me("missing JWE Algorithm (alg) in JWE Header");if(typeof o!="string"||!o)throw new Me("missing JWE Encryption Algorithm (enc) in JWE Header");let a=r&&R0("keyManagementAlgorithms",r.keyManagementAlgorithms),c=r&&R0("contentEncryptionAlgorithms",r.contentEncryptionAlgorithms);if(a&&!a.has(s)||!a&&s.startsWith("PBES2"))throw new Bh('"alg" (Algorithm) Header Parameter value not allowed');if(c&&!c.has(o))throw new Bh('"enc" (Encryption Algorithm) Header Parameter value not allowed');let l;t.encrypted_key!==void 0&&(l=wo(t.encrypted_key,"encrypted_key",Me));let u=!1;typeof e=="function"&&(e=await e(n,t),u=!0),Pf(s==="dir"?o:s,e,"decrypt");let d=await $u(e,s),p;try{p=await kpe(s,d,l,i,r)}catch(_){if(_ instanceof TypeError||_ instanceof Me||_ instanceof Pt)throw _;p=Rf(o)}let f,m;t.iv!==void 0&&(f=wo(t.iv,"iv",Me)),t.tag!==void 0&&(m=wo(t.tag,"tag",Me));let h=t.protected!==void 0?Bn(t.protected):new Uint8Array,y;t.aad!==void 0?y=fi(h,Bn("."),Bn(t.aad)):y=h;let g=wo(t.ciphertext,"ciphertext",Me),b=await tC(o,p,g,f,m,y),v={plaintext:b};if(i.zip==="DEF"){let _=r?.maxDecompressedLength??25e4;if(_===0)throw new Pt('JWE "zip" (Compression Algorithm) Header Parameter is not supported.');if(_!==1/0&&(!Number.isSafeInteger(_)||_<1))throw new TypeError("maxDecompressedLength must be 0, a positive safe integer, or Infinity");v.plaintext=await Ppe(b,_).catch(w=>{throw w instanceof Me?w:new Me("Failed to decompress plaintext",{cause:w})})}return t.protected!==void 0&&(v.protectedHeader=n),t.aad!==void 0&&(v.additionalAuthenticatedData=wo(t.aad,"aad",Me)),t.unprotected!==void 0&&(v.sharedUnprotectedHeader=t.unprotected),t.header!==void 0&&(v.unprotectedHeader=t.header),u?{...v,key:d}:v}var Mpe=I(()=>{Ys();ov();sp();cn();Ss();Ss();LH();Vs();ov();k0();jH();uv();C0();KH()});async function Lpe(t,e,r){if(t instanceof Uint8Array&&(t=_s.decode(t)),typeof t!="string")throw new Me("Compact JWE must be a string or Uint8Array");let{0:n,1:i,2:s,3:o,4:a,length:c}=t.split(".");if(c!==5)throw new Me("Invalid Compact JWE");let l=await Dpe({ciphertext:o,iv:s||void 0,protected:n,tag:a||void 0,encrypted_key:i||void 0},e,r),u={plaintext:l.plaintext,protectedHeader:l.protectedHeader};return typeof e=="function"?{...u,key:l.key}:u}var jpe=I(()=>{Mpe();cn();Vs()});var aC,Upe=I(()=>{Ys();sp();ov();LH();cn();Ss();Vs();k0();uv();C0();KH();aC=class{#e;#t;#r;#n;#i;#p;#u;#a;constructor(e){if(!(e instanceof Uint8Array))throw new TypeError("plaintext must be an instance of Uint8Array");this.#e=e}setKeyManagementParameters(e){return So(this.#a,"setKeyManagementParameters"),this.#a=e,this}setProtectedHeader(e){return So(this.#t,"setProtectedHeader"),this.#t=e,this}setSharedUnprotectedHeader(e){return So(this.#r,"setSharedUnprotectedHeader"),this.#r=e,this}setUnprotectedHeader(e){return So(this.#n,"setUnprotectedHeader"),this.#n=e,this}setAdditionalAuthenticatedData(e){return this.#i=e,this}setContentEncryptionKey(e){return So(this.#p,"setContentEncryptionKey"),this.#p=e,this}setInitializationVector(e){return So(this.#u,"setInitializationVector"),this.#u=e,this}async encrypt(e,r){if(!this.#t&&!this.#n&&!this.#r)throw new Me("either setProtectedHeader, setUnprotectedHeader, or sharedUnprotectedHeader must be called before #encrypt()");if(!Cf(this.#t,this.#n,this.#r))throw new Me("JWE Protected, JWE Shared Unprotected and JWE Per-Recipient Header Parameter names must be disjoint");let n={...this.#t,...this.#n,...this.#r};if(Nf(Me,new Map,r?.crit,this.#t,n),n.zip!==void 0&&n.zip!=="DEF")throw new Pt('Unsupported JWE "zip" (Compression Algorithm) Header Parameter value.');if(n.zip!==void 0&&!this.#t?.zip)throw new Me('JWE "zip" (Compression Algorithm) Header Parameter MUST be in a protected header.');let{alg:i,enc:s}=n;if(typeof i!="string"||!i)throw new Me('JWE "alg" (Algorithm) Header Parameter missing or invalid');if(typeof s!="string"||!s)throw new Me('JWE "enc" (Encryption Algorithm) Header Parameter missing or invalid');let o;if(this.#p&&(i==="dir"||i==="ECDH-ES"))throw new TypeError(`setContentEncryptionKey cannot be called with JWE "alg" (Algorithm) Header ${i}`);Pf(i==="dir"?s:i,e,"encrypt");let a;{let g,b=await $u(e,i);({cek:a,encryptedKey:o,parameters:g}=await Rpe(i,s,b,this.#p,this.#a)),g&&(r&&rpe in r?this.#n?this.#n={...this.#n,...g}:this.setUnprotectedHeader(g):this.#t?this.#t={...this.#t,...g}:this.setProtectedHeader(g))}let c,l,u,d;if(this.#t?(l=bn(JSON.stringify(this.#t)),u=Bn(l)):(l="",u=new Uint8Array),this.#i){d=bn(this.#i);let g=Bn(d);c=fi(u,Bn("."),g)}else c=u;let p=this.#e;n.zip==="DEF"&&(p=await Npe(p).catch(g=>{throw new Me("Failed to compress plaintext",{cause:g})}));let{ciphertext:f,tag:m,iv:h}=await eC(s,p,a,this.#u,c),y={ciphertext:bn(f)};return h&&(y.iv=bn(h)),m&&(y.tag=bn(m)),o&&(y.encrypted_key=bn(o)),d&&(y.aad=d),this.#t&&(y.protected=l),this.#r&&(y.unprotected=this.#r),this.#n&&(y.header=this.#n),y}}});async function Kpe(t,e,r){if(!vn(t))throw new zr("Flattened JWS must be an object");if(t.protected===void 0&&t.header===void 0)throw new zr('Flattened JWS must have either of the "protected" or "header" members');if(t.protected!==void 0&&typeof t.protected!="string")throw new zr("JWS Protected Header incorrect type");if(t.payload===void 0)throw new zr("JWS Payload missing");if(typeof t.signature!="string")throw new zr("JWS Signature missing or incorrect type");if(t.header!==void 0&&!vn(t.header))throw new zr("JWS Unprotected Header incorrect type");let n={};if(t.protected)try{let y=_o(t.protected);n=JSON.parse(_s.decode(y))}catch{throw new zr("JWS Protected Header is invalid")}if(!Cf(n,t.header))throw new zr("JWS Protected and JWS Unprotected Header Parameter names must be disjoint");let i={...n,...t.header},s=Nf(zr,new Map([["b64",!0]]),r?.crit,n,i),o=!0;if(s.has("b64")&&(o=n.b64,typeof o!="boolean"))throw new zr('The "b64" (base64url-encode payload) Header Parameter must be a boolean');let{alg:a}=i;if(typeof a!="string"||!a)throw new zr('JWS "alg" (Algorithm) Header Parameter missing or invalid');let c=r&&R0("algorithms",r.algorithms);if(c&&!c.has(a))throw new Bh('"alg" (Algorithm) Header Parameter value not allowed');if(o){if(typeof t.payload!="string")throw new zr("JWS Payload must be a string")}else if(typeof t.payload!="string"&&!(t.payload instanceof Uint8Array))throw new zr("JWS Payload must be a string or an Uint8Array instance");let l=!1;typeof e=="function"&&(e=await e(n,t),l=!0),Pf(a,e,"verify");let u=fi(t.protected!==void 0?Bn(t.protected):new Uint8Array,Bn("."),typeof t.payload=="string"?o?Bn(t.payload):qh.encode(t.payload):t.payload),d=wo(t.signature,"signature",zr),p=await $u(e,a);if(!await ype(a,p,d,u))throw new ZR;let m;o?m=wo(t.payload,"payload",zr):typeof t.payload=="string"?m=qh.encode(t.payload):m=t.payload;let h={payload:m};return t.protected!==void 0&&(h.protectedHeader=n),t.header!==void 0&&(h.unprotectedHeader=t.header),l?{...h,key:p}:h}var qpe=I(()=>{Ys();nC();cn();Vs();sp();Ss();Ss();C0();k0();jH();uv()});async function Fpe(t,e,r){if(t instanceof Uint8Array&&(t=_s.decode(t)),typeof t!="string")throw new zr("Compact JWS must be a string or Uint8Array");let{0:n,1:i,2:s,length:o}=t.split(".");if(o!==3)throw new zr("Invalid Compact JWS");let a=await Kpe({payload:i,protected:n,signature:s},e,r),c={payload:a.payload,protectedHeader:a.protectedHeader};return typeof e=="function"?{...c,key:a.key}:c}var zpe=I(()=>{qpe();cn();Vs()});function N0(t){let e=Krt.exec(t);if(!e||e[4]&&e[1])throw new TypeError("Invalid time period format");let r=parseFloat(e[2]),n=e[3].toLowerCase(),i;switch(n){case"sec":case"secs":case"second":case"seconds":case"s":i=Math.round(r);break;case"minute":case"minutes":case"min":case"mins":case"m":i=Math.round(r*Hpe);break;case"hour":case"hours":case"hr":case"hrs":case"h":i=Math.round(r*Wpe);break;case"day":case"days":case"d":i=Math.round(r*qH);break;case"week":case"weeks":case"w":i=Math.round(r*jrt);break;default:i=Math.round(r*Urt);break}return e[1]==="-"||e[4]==="ago"?-i:i}function $h(t,e){if(!Number.isFinite(e))throw new TypeError(`Invalid ${t} input`);return e}function cC(t,e,r={}){let n;try{n=JSON.parse(_s.decode(e))}catch{}if(!vn(n))throw new Js("JWT Claims Set must be a top-level JSON object");let{typ:i}=r;if(i&&(typeof t.typ!="string"||Bpe(t.typ)!==Bpe(i)))throw new Es('unexpected "typ" JWT header value',n,"typ","check_failed");let{requiredClaims:s=[],issuer:o,subject:a,audience:c,maxTokenAge:l}=r,u=[...s];l!==void 0&&u.push("iat"),c!==void 0&&u.push("aud"),a!==void 0&&u.push("sub"),o!==void 0&&u.push("iss");for(let m of new Set(u.reverse()))if(!(m in n))throw new Es(`missing required "${m}" claim`,n,m,"missing");if(o&&!(Array.isArray(o)?o:[o]).includes(n.iss))throw new Es('unexpected "iss" claim value',n,"iss","check_failed");if(a&&n.sub!==a)throw new Es('unexpected "sub" claim value',n,"sub","check_failed");if(c&&!qrt(n.aud,typeof c=="string"?[c]:c))throw new Es('unexpected "aud" claim value',n,"aud","check_failed");let d;switch(typeof r.clockTolerance){case"string":d=N0(r.clockTolerance);break;case"number":d=r.clockTolerance;break;case"undefined":d=0;break;default:throw new TypeError("Invalid clockTolerance option type")}let{currentDate:p}=r,f=Df(p||new Date);if((n.iat!==void 0||l)&&typeof n.iat!="number")throw new Es('"iat" claim must be a number',n,"iat","invalid");if(n.nbf!==void 0){if(typeof n.nbf!="number")throw new Es('"nbf" claim must be a number',n,"nbf","invalid");if(n.nbf>f+d)throw new Es('"nbf" claim timestamp check failed',n,"nbf","check_failed")}if(n.exp!==void 0){if(typeof n.exp!="number")throw new Es('"exp" claim must be a number',n,"exp","invalid");if(n.exp<=f-d)throw new zh('"exp" claim timestamp check failed',n,"exp","check_failed")}if(l){let m=f-n.iat,h=typeof l=="number"?l:N0(l);if(m-d>h)throw new zh('"iat" claim timestamp check failed (too far in the past)',n,"iat","check_failed");if(m<0-d)throw new Es('"iat" claim timestamp check failed (it should be in the past)',n,"iat","check_failed")}return n}var Df,Hpe,Wpe,qH,jrt,Urt,Krt,Bpe,qrt,pv,P0=I(()=>{cn();Vs();Ss();Df=t=>Math.floor(t.getTime()/1e3),Hpe=60,Wpe=Hpe*60,qH=Wpe*24,jrt=qH*7,Urt=qH*365.25,Krt=/^(\+|\-)? ?(\d+|\d+\.\d+) ?(seconds?|secs?|s|minutes?|mins?|m|hours?|hrs?|h|days?|d|weeks?|w|years?|yrs?|y)(?: (ago|from now))?$/i;Bpe=t=>t.includes("/")?t.toLowerCase():`application/${t.toLowerCase()}`,qrt=(t,e)=>typeof t=="string"?e.includes(t):Array.isArray(t)?e.some(Set.prototype.has.bind(new Set(t))):!1;pv=class{#e;constructor(e){if(!vn(e))throw new TypeError("JWT Claims Set MUST be an object");this.#e=structuredClone(e)}data(){return qh.encode(JSON.stringify(this.#e))}get iss(){return this.#e.iss}set iss(e){this.#e.iss=e}get sub(){return this.#e.sub}set sub(e){this.#e.sub=e}get aud(){return this.#e.aud}set aud(e){this.#e.aud=e}set jti(e){this.#e.jti=e}set nbf(e){typeof e=="number"?this.#e.nbf=$h("setNotBefore",e):e instanceof Date?this.#e.nbf=$h("setNotBefore",Df(e)):this.#e.nbf=Df(new Date)+N0(e)}set exp(e){typeof e=="number"?this.#e.exp=$h("setExpirationTime",e):e instanceof Date?this.#e.exp=$h("setExpirationTime",Df(e)):this.#e.exp=Df(new Date)+N0(e)}set iat(e){e===void 0?this.#e.iat=Df(new Date):e instanceof Date?this.#e.iat=$h("setIssuedAt",Df(e)):typeof e=="string"?this.#e.iat=$h("setIssuedAt",Df(new Date)+N0(e)):this.#e.iat=$h("setIssuedAt",e)}}});async function To(t,e,r){let n=await Fpe(t,e,r);if(n.protectedHeader.crit?.includes("b64")&&n.protectedHeader.b64===!1)throw new Js("JWTs MUST NOT use unencoded payload");let s={payload:cC(n.protectedHeader,n.payload,r),protectedHeader:n.protectedHeader};return typeof e=="function"?{...s,key:n.key}:s}var $pe=I(()=>{zpe();P0();cn()});async function lC(t,e,r){let n=await Lpe(t,e,r),i=cC(n.protectedHeader,n.plaintext,r),{protectedHeader:s}=n;if(s.iss!==void 0&&s.iss!==i.iss)throw new Es('replicated "iss" claim header parameter mismatch',i,"iss","mismatch");if(s.sub!==void 0&&s.sub!==i.sub)throw new Es('replicated "sub" claim header parameter mismatch',i,"sub","mismatch");if(s.aud!==void 0&&JSON.stringify(s.aud)!==JSON.stringify(i.aud))throw new Es('replicated "aud" claim header parameter mismatch',i,"aud","mismatch");let o={payload:i,protectedHeader:s};return typeof e=="function"?{...o,key:n.key}:o}var Gpe=I(()=>{jpe();P0();cn()});var uC,Vpe=I(()=>{Upe();uC=class{#e;constructor(e){this.#e=new aC(e)}setContentEncryptionKey(e){return this.#e.setContentEncryptionKey(e),this}setInitializationVector(e){return this.#e.setInitializationVector(e),this}setProtectedHeader(e){return this.#e.setProtectedHeader(e),this}setKeyManagementParameters(e){return this.#e.setKeyManagementParameters(e),this}async encrypt(e,r){let n=await this.#e.encrypt(e,r);return[n.protected,n.encrypted_key,n.iv,n.ciphertext,n.tag].join(".")}}});var dC,Ype=I(()=>{Ys();nC();Ss();cn();Vs();C0();k0();uv();sp();dC=class{#e;#t;#r;constructor(e){if(!(e instanceof Uint8Array))throw new TypeError("payload must be an instance of Uint8Array");this.#e=e}setProtectedHeader(e){return So(this.#t,"setProtectedHeader"),this.#t=e,this}setUnprotectedHeader(e){return So(this.#r,"setUnprotectedHeader"),this.#r=e,this}async sign(e,r){if(!this.#t&&!this.#r)throw new zr("either setProtectedHeader or setUnprotectedHeader must be called before #sign()");if(!Cf(this.#t,this.#r))throw new zr("JWS Protected and JWS Unprotected Header Parameter names must be disjoint");let n={...this.#t,...this.#r},i=Nf(zr,new Map([["b64",!0]]),r?.crit,this.#t,n),s=!0;if(i.has("b64")&&(s=this.#t.b64,typeof s!="boolean"))throw new zr('The "b64" (base64url-encode payload) Header Parameter must be a boolean');let{alg:o}=n;if(typeof o!="string"||!o)throw new zr('JWS "alg" (Algorithm) Header Parameter missing or invalid');Pf(o,e,"sign");let a,c;s?(a=bn(this.#e),c=Bn(a)):(c=this.#e,a="");let l,u;this.#t?(l=bn(JSON.stringify(this.#t)),u=Bn(l)):(l="",u=new Uint8Array);let d=fi(u,Bn("."),c),p=await $u(e,o),f=await gpe(o,p,d),m={signature:bn(f),payload:a};return this.#r&&(m.header=this.#r),this.#t&&(m.protected=l),m}}});var pC,Jpe=I(()=>{Ype();pC=class{#e;constructor(e){this.#e=new dC(e)}setProtectedHeader(e){return this.#e.setProtectedHeader(e),this}async sign(e,r){let n=await this.#e.sign(e,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 D0,Zpe=I(()=>{Jpe();cn();P0();D0=class{#e;#t;constructor(e={}){this.#t=new pv(e)}setIssuer(e){return this.#t.iss=e,this}setSubject(e){return this.#t.sub=e,this}setAudience(e){return this.#t.aud=e,this}setJti(e){return this.#t.jti=e,this}setNotBefore(e){return this.#t.nbf=e,this}setExpirationTime(e){return this.#t.exp=e,this}setIssuedAt(e){return this.#t.iat=e,this}setProtectedHeader(e){return this.#e=e,this}async sign(e,r){let n=new pC(this.#t.data());if(n.setProtectedHeader(this.#e),Array.isArray(this.#e?.crit)&&this.#e.crit.includes("b64")&&this.#e.b64===!1)throw new Js("JWTs MUST NOT use unencoded payload");return n.sign(e,r)}}});var M0,Xpe=I(()=>{Vpe();P0();sp();M0=class{#e;#t;#r;#n;#i;#p;#u;#a;constructor(e={}){this.#a=new pv(e)}setIssuer(e){return this.#a.iss=e,this}setSubject(e){return this.#a.sub=e,this}setAudience(e){return this.#a.aud=e,this}setJti(e){return this.#a.jti=e,this}setNotBefore(e){return this.#a.nbf=e,this}setExpirationTime(e){return this.#a.exp=e,this}setIssuedAt(e){return this.#a.iat=e,this}setProtectedHeader(e){return So(this.#n,"setProtectedHeader"),this.#n=e,this}setKeyManagementParameters(e){return So(this.#r,"setKeyManagementParameters"),this.#r=e,this}setContentEncryptionKey(e){return So(this.#e,"setContentEncryptionKey"),this.#e=e,this}setInitializationVector(e){return So(this.#t,"setInitializationVector"),this.#t=e,this}replicateIssuerAsHeader(){return this.#i=!0,this}replicateSubjectAsHeader(){return this.#p=!0,this}replicateAudienceAsHeader(){return this.#u=!0,this}async encrypt(e,r){let n=new uC(this.#a.data());return this.#n&&(this.#i||this.#p||this.#u)&&(this.#n={...this.#n,iss:this.#i?this.#a.iss:void 0,sub:this.#p?this.#a.sub:void 0,aud:this.#u?this.#a.aud:void 0}),n.setProtectedHeader(this.#n),this.#t&&n.setInitializationVector(this.#t),this.#e&&n.setContentEncryptionKey(this.#e),this.#r&&n.setKeyManagementParameters(this.#r),n.encrypt(e,r)}}});async function fC(t,e){let r;if(Wh(t))r=t;else if(T0(t))r=await oC(t);else throw new TypeError(Wu(t,"CryptoKey","KeyObject","JSON Web Key"));if(e??="sha256",e!=="sha256"&&e!=="sha384"&&e!=="sha512")throw new TypeError('digestAlgorithm must one of "sha256", "sha384", or "sha512"');let n;switch(r.kty){case"AKP":Gu(r.alg,'"alg" (Algorithm) Parameter'),Gu(r.pub,'"pub" (Public key) Parameter'),n={alg:r.alg,kty:r.kty,pub:r.pub};break;case"EC":Gu(r.crv,'"crv" (Curve) Parameter'),Gu(r.x,'"x" (X Coordinate) Parameter'),Gu(r.y,'"y" (Y Coordinate) Parameter'),n={crv:r.crv,kty:r.kty,x:r.x,y:r.y};break;case"OKP":Gu(r.crv,'"crv" (Subtype of Key Pair) Parameter'),Gu(r.x,'"x" (Public Key) Parameter'),n={crv:r.crv,kty:r.kty,x:r.x};break;case"RSA":Gu(r.e,'"e" (Exponent) Parameter'),Gu(r.n,'"n" (Modulus) Parameter'),n={e:r.e,kty:r.kty,n:r.n};break;case"oct":Gu(r.k,'"k" (Key Value) Parameter'),n={k:r.k,kty:r.kty};break;default:throw new Pt('"kty" (Key Type) Parameter missing or unsupported')}let i=Bn(JSON.stringify(n));return bn(await rC(e,i))}var Gu,Qpe=I(()=>{sp();Ys();cn();Vs();Hh();Ss();MH();rv();Gu=(t,e)=>{if(typeof t!="string"||!t)throw new VR(`${e} missing or invalid`)}});function Frt(t){switch(typeof t=="string"&&t.slice(0,2)){case"RS":case"PS":return"RSA";case"ES":return"EC";case"Ed":return"OKP";case"ML":return"AKP";default:throw new Pt('Unsupported "alg" value for a JSON Web Key Set')}}function zrt(t){return t&&typeof t=="object"&&Array.isArray(t.keys)&&t.keys.every(Brt)}function Brt(t){return vn(t)}async function efe(t,e,r){let n=t.get(e)||t.set(e,{}).get(e);if(n[r]===void 0){let i=await Ga({...e,ext:!0},r);if(i instanceof Uint8Array||i.type!=="public")throw new S0("JSON Web Key Set members must be public keys");n[r]=i}return n[r]}function zH(t){let e=new FH(t),r=async(n,i)=>e.getKey(n,i);return Object.defineProperties(r,{jwks:{value:()=>structuredClone(e.jwks()),enumerable:!1,configurable:!1,writable:!1}}),r}var FH,tfe=I(()=>{sC();cn();Ss();FH=class{#e;#t=new WeakMap;constructor(e){if(!zrt(e))throw new S0("JSON Web Key Set malformed");this.#e=structuredClone(e)}jwks(){return this.#e}async getKey(e,r){let{alg:n,kid:i}={...e,...r?.header},s=Frt(n),o=this.#e.keys.filter(l=>{let u=s===l.kty;if(u&&typeof i=="string"&&(u=i===l.kid),u&&(typeof l.alg=="string"||s==="AKP")&&(u=n===l.alg),u&&typeof l.use=="string"&&(u=l.use==="sig"),u&&Array.isArray(l.key_ops)&&(u=l.key_ops.includes("verify")),u)switch(n){case"ES256":u=l.crv==="P-256";break;case"ES384":u=l.crv==="P-384";break;case"ES512":u=l.crv==="P-521";break;case"Ed25519":case"EdDSA":u=l.crv==="Ed25519";break}return u}),{0:a,length:c}=o;if(c===0)throw new iv;if(c!==1){let l=new YR,u=this.#t;throw l[Symbol.asyncIterator]=async function*(){for(let d of o)try{yield await efe(u,d,n)}catch{}},l}return efe(this.#t,a,n)}}});function Hrt(){return typeof WebSocketPair<"u"||typeof navigator<"u"&&navigator.userAgent==="Cloudflare-Workers"||typeof EdgeRuntime<"u"&&EdgeRuntime==="vercel"}async function Wrt(t,e,r,n=fetch){let i=await n(t,{method:"GET",signal:r,redirect:"manual",headers:e}).catch(s=>{throw s.name==="TimeoutError"?new JR:s});if(i.status!==200)throw new Si("Expected 200 OK from the JSON Web Key Set HTTP response");try{return await i.json()}catch{throw new Si("Failed to parse the JSON Web Key Set HTTP response as JSON")}}function $rt(t,e){return!(typeof t!="object"||t===null||!("uat"in t)||typeof t.uat!="number"||Date.now()-t.uat>=e||!("jwks"in t)||!vn(t.jwks)||!Array.isArray(t.jwks.keys)||!Array.prototype.every.call(t.jwks.keys,vn))}function WH(t,e){let r=new HH(t,e),n=async(i,s)=>r.getKey(i,s);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.jwks(),enumerable:!0,configurable:!1,writable:!1}}),n}var BH,rfe,mC,HH,nfe=I(()=>{cn();tfe();Ss();(typeof navigator>"u"||!navigator.userAgent?.startsWith?.("Mozilla/5.0 "))&&(BH="jose/v6.2.3");rfe=Symbol();mC=Symbol();HH=class{#e;#t;#r;#n;#i;#p;#u;#a;#o;#d;constructor(e,r){if(!(e instanceof URL))throw new TypeError("url must be an instance of URL");this.#e=new URL(e.href),this.#t=typeof r?.timeoutDuration=="number"?r?.timeoutDuration:5e3,this.#r=typeof r?.cooldownDuration=="number"?r?.cooldownDuration:3e4,this.#n=typeof r?.cacheMaxAge=="number"?r?.cacheMaxAge:6e5,this.#u=new Headers(r?.headers),BH&&!this.#u.has("User-Agent")&&this.#u.set("User-Agent",BH),this.#u.has("accept")||(this.#u.set("accept","application/json"),this.#u.append("accept","application/jwk-set+json")),this.#a=r?.[rfe],r?.[mC]!==void 0&&(this.#d=r?.[mC],$rt(r?.[mC],this.#n)&&(this.#i=this.#d.uat,this.#o=zH(this.#d.jwks)))}pendingFetch(){return!!this.#p}coolingDown(){return typeof this.#i=="number"?Date.now()<this.#i+this.#r:!1}fresh(){return typeof this.#i=="number"?Date.now()<this.#i+this.#n:!1}jwks(){return this.#o?.jwks()}async getKey(e,r){(!this.#o||!this.fresh())&&await this.reload();try{return await this.#o(e,r)}catch(n){if(n instanceof iv&&this.coolingDown()===!1)return await this.reload(),this.#o(e,r);throw n}}async reload(){this.#p&&Hrt()&&(this.#p=void 0),this.#p||=Wrt(this.#e.href,this.#u,AbortSignal.timeout(this.#t),this.#a).then(e=>{this.#o=zH(e),this.#d&&(this.#d.uat=Date.now(),this.#d.jwks=e),this.#i=Date.now(),this.#p=void 0}).catch(e=>{throw this.#p=void 0,e}),await this.#p}}});function Dl(t){let e;if(typeof t=="string"){let r=t.split(".");(r.length===3||r.length===5)&&([e]=r)}else if(typeof t=="object"&&t)if("protected"in t)e=t.protected;else throw new TypeError("Token does not contain a Protected Header");try{if(typeof e!="string"||!e)throw new Error;let r=JSON.parse(_s.decode(_o(e)));if(!vn(r))throw new Error;return r}catch{throw new TypeError("Invalid Token or Protected Header formatting")}}var ife=I(()=>{Ys();Vs();Ss()});function wi(t){if(typeof t!="string")throw new Js("JWTs must use Compact JWS serialization, JWT must be a string");let{1:e,length:r}=t.split(".");if(r===5)throw new Js("Only JWTs using Compact JWS serialization can be decoded");if(r!==3)throw new Js("Invalid JWT");if(!e)throw new Js("JWTs must contain a payload");let n;try{n=_o(e)}catch{throw new Js("Failed to base64url decode the payload")}let i;try{i=JSON.parse(_s.decode(n))}catch{throw new Js("Failed to parse the decoded payload as JSON")}if(!vn(i))throw new Js("Invalid JWT Claims Set");return i}var sfe=I(()=>{Ys();Vs();Ss();cn()});var Wc=I(()=>{$pe();Gpe();Zpe();Xpe();Qpe();nfe();sC();ife();sfe();Ys()});async function hC(t,e,r=3600){return await new D0(t).setProtectedHeader({alg:"HS256"}).setIssuedAt().setExpirationTime(Math.floor(Date.now()/1e3)+r).sign(new TextEncoder().encode(e))}async function $H(t,e){try{return(await To(t,new TextEncoder().encode(e))).payload}catch{return null}}function L0(t,e){return Ude(Bde,new TextEncoder().encode(t),new TextEncoder().encode(e),Grt,64)}function Yrt(t){if(typeof t=="string")return t;let e=t.keys.get(t.currentVersion);if(!e)throw new Error(`Secret version ${t.currentVersion} not found in keys`);return e}function ofe(t){if(typeof t=="string")return[{version:0,value:t}];let e=[];for(let[r,n]of t.keys)e.push({version:r,value:n});return t.legacySecret&&!e.some(r=>r.value===t.legacySecret)&&e.push({version:-1,value:t.legacySecret}),e}async function gC(t,e,r,n=3600){let i=L0(Yrt(e),r),s=await fC({kty:"oct",k:E0.encode(i)},"sha256");return await new M0(t).setProtectedHeader({alg:cfe,enc:lfe,kid:s}).setIssuedAt().setExpirationTime(Vrt()+n).setJti(crypto.randomUUID()).encrypt(i)}async function j0(t,e,r){if(!t)return null;let n=!1;try{n=Dl(t).kid!==void 0}catch{return null}try{let i=ofe(e),{payload:s}=await lC(t,async o=>{let a=o.kid;if(a!==void 0){for(let c of i){let l=L0(c.value,r);if(a===await fC({kty:"oct",k:E0.encode(l)},"sha256"))return l}throw new Error("no matching decryption secret")}return i.length===1,L0(i[0].value,r)},afe);return s}catch{if(n)return null;let i=ofe(e);if(i.length<=1)return null;for(let s=1;s<i.length;s++)try{let o=i[s],{payload:a}=await lC(t,L0(o.value,r),afe);return a}catch{continue}return null}}var Grt,Vrt,cfe,lfe,afe,U0=I(()=>{Kde();Hde();Wc();Grt=new Uint8Array([66,101,116,116,101,114,65,117,116,104,46,106,115,32,71,101,110,101,114,97,116,101,100,32,69,110,99,114,121,112,116,105,111,110,32,75,101,121]),Vrt=()=>Date.now()/1e3|0,cfe="dir",lfe="A256CBC-HS512";afe={clockTolerance:15,keyManagementAlgorithms:[cfe],contentEncryptionAlgorithms:[lfe,"A256GCM"]}});function ufe(t,e){return new Promise((r,n)=>{(0,yC.scrypt)(t.normalize("NFKC"),e,fv.dkLen,{N:fv.N,r:fv.r,p:fv.p,maxmem:128*fv.N*fv.r*2},(i,s)=>{i?n(i):r(s)})})}async function dfe(t){let e=(0,yC.randomBytes)(16).toString("hex"),r=await ufe(t,e);return`${e}:${r.toString("hex")}`}async function pfe(t,e){let[r,n]=t.split(":");if(!r||!n)throw new Error("Invalid password hash");return(await ufe(e,r)).toString("hex")===n}var yC,fv,ffe=I(()=>{yC=require("node:crypto"),fv={N:16384,r:16,p:1,dkLen:64}});var mfe,hfe,gfe=I(()=>{ffe();mfe=dfe,hfe=async({hash:t,password:e})=>pfe(t,e)});function Ml(){let t=typeof globalThis<"u"&&globalThis.crypto;if(t&&typeof t.subtle=="object"&&t.subtle!=null)return t.subtle;throw new Error("crypto.subtle must be defined")}var K0=I(()=>{});function bC(t){return t?"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_":"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"}function yfe(t,e,r){let n="",i=0,s=0;for(let o of t)for(i=i<<8|o,s+=8;s>=6;)s-=6,n+=e[i>>s&63];if(s>0&&(n+=e[i<<6-s&63]),r){let o=(4-n.length%4)%4;n+="=".repeat(o)}return n}function bfe(t,e){let r=new Map;for(let o=0;o<e.length;o++)r.set(e[o],o);let n=[],i=0,s=0;for(let o of t){if(o==="=")break;let a=r.get(o);if(a===void 0)throw new Error(`Invalid Base64 character: ${o}`);i=i<<6|a,s+=6,s>=8&&(s-=8,n.push(i>>s&255))}return Uint8Array.from(n)}var Hi,da,pa=I(()=>{Hi={encode(t,e={}){let r=bC(!1),n=typeof t=="string"?new TextEncoder().encode(t):new Uint8Array(t);return yfe(n,r,e.padding??!0)},decode(t){typeof t!="string"&&(t=new TextDecoder().decode(t));let e=t.includes("-")||t.includes("_"),r=bC(e);return bfe(t,r)}},da={encode(t,e={}){let r=bC(!0),n=typeof t=="string"?new TextEncoder().encode(t):new Uint8Array(t);return yfe(n,r,e.padding??!0)},decode(t){let e=t.includes("-")||t.includes("_"),r=bC(e);return bfe(t,r)}}});function op(t,e){return{digest:async r=>{let n=new TextEncoder,i=typeof r=="string"?n.encode(r):r,s=await Ml().digest(t,i);return e==="hex"?Array.from(new Uint8Array(s)).map(c=>c.toString(16).padStart(2,"0")).join(""):e==="base64"||e==="base64url"||e==="base64urlnopad"?e.includes("url")?da.encode(s,{padding:e!=="base64urlnopad"}):Hi.encode(s):s}}}var q0=I(()=>{pa();K0()});function Jrt(t){return t instanceof Uint8Array||ArrayBuffer.isView(t)&&t.constructor.name==="Uint8Array"&&"BYTES_PER_ELEMENT"in t&&t.BYTES_PER_ELEMENT===1}function vC(t){if(typeof t!="boolean")throw new TypeError(`boolean expected, not ${t}`)}function Mf(t){if(typeof t!="number")throw new TypeError("number expected, got "+typeof t);if(!Number.isSafeInteger(t)||t<0)throw new RangeError("positive integer expected, got "+t)}function Dn(t,e,r=""){let n=Jrt(t),i=t?.length,s=e!==void 0;if(!n||s&&i!==e){let o=r&&`"${r}" `,a=s?` of length ${e}`:"",c=n?`length=${i}`:`type=${typeof t}`,l=o+"expected Uint8Array"+a+", got "+c;throw n?new RangeError(l):new TypeError(l)}return t}function GH(t,e=!0){if(t.destroyed)throw new Error("Hash instance has been destroyed");if(e&&t.finished)throw new Error("Hash#digest() has already been called")}function _fe(t,e,r=!1){Dn(t,void 0,"output");let n=e.outputLen;if(t.length<n)throw new RangeError("digestInto() expects output buffer of length at least "+n);if(r&&!mv(t))throw new Error("invalid output, must be aligned")}function Vu(t){return new Uint32Array(t.buffer,t.byteOffset,Math.floor(t.byteLength/4))}function Ll(...t){for(let e=0;e<t.length;e++)t[e].fill(0)}function Zrt(t){return new DataView(t.buffer,t.byteOffset,t.byteLength)}function VH(t){if(Dn(t),Sfe)return t.toHex();let e="";for(let r=0;r<t.length;r++)e+=Qrt[t[r]];return e}function vfe(t){if(t>=ap._0&&t<=ap._9)return t-ap._0;if(t>=ap.A&&t<=ap.F)return t-(ap.A-10);if(t>=ap.a&&t<=ap.f)return t-(ap.a-10)}function wfe(t){if(typeof t!="string")throw new TypeError("hex string expected, got "+typeof t);if(Sfe)try{return Uint8Array.fromHex(t)}catch(i){throw i instanceof SyntaxError?new RangeError(i.message):i}let e=t.length,r=e/2;if(e%2)throw new RangeError("hex string expected, got unpadded hex of length "+e);let n=new Uint8Array(r);for(let i=0,s=0;i<r;i++,s+=2){let o=vfe(t.charCodeAt(s)),a=vfe(t.charCodeAt(s+1));if(o===void 0||a===void 0){let c=t[s]+t[s+1];throw new RangeError('hex string expected, got non-hex character "'+c+'" at index '+s)}n[i]=o*16+a}return n}function Tfe(t){if(typeof t!="string")throw new TypeError("string expected");return new Uint8Array(new TextEncoder().encode(t))}function ent(t,e){return!t.byteLength||!e.byteLength?!1:t.buffer===e.buffer&&t.byteOffset<e.byteOffset+e.byteLength&&e.byteOffset<t.byteOffset+t.byteLength}function xfe(...t){let e=0;for(let n=0;n<t.length;n++){let i=t[n];Dn(i),e+=i.length}let r=new Uint8Array(e);for(let n=0,i=0;n<t.length;n++){let s=t[n];r.set(s,i),i+=s.length}return r}function Ife(t,e){if(e==null||typeof e!="object")throw new Error("options must be defined");return Object.assign(t,e)}function Afe(t,e){if(t.length!==e.length)return!1;let r=0;for(let n=0;n<t.length;n++)r|=t[n]^e[n];return r===0}function Ofe(t,e,r){let n=e,i=r||(()=>[]),s=(a,c)=>n(c,...i(a)).update(a).digest(),o=n(new Uint8Array(t),...i(new Uint8Array(0)));return s.outputLen=o.outputLen,s.blockLen=o.blockLen,s.create=(a,...c)=>n(a,...c),s}function F0(t,e,r=!0){if(e===void 0)return new Uint8Array(t);if(Dn(e,void 0,"output"),e.length!==t)throw new Error('"output" expected Uint8Array of length '+t+", got: "+e.length);if(r&&!mv(e))throw new Error("invalid output, must be aligned");return e}function Rfe(t,e,r){Mf(t),Mf(e),vC(r);let n=new Uint8Array(16),i=Zrt(n);return i.setBigUint64(0,BigInt(e),r),i.setBigUint64(8,BigInt(t),r),n}function mv(t){return t.byteOffset%4===0}function hv(t){return Uint8Array.from(Dn(t))}function Cfe(t=32){Mf(t);let e=typeof globalThis=="object"?globalThis.crypto:null;if(typeof e?.getRandomValues!="function")throw new Error("crypto.getRandomValues must be defined");return e.getRandomValues(new Uint8Array(t))}function YH(t,e=Cfe){let{nonceLength:r}=t;Mf(r);let n=(s,o,a)=>{let c=xfe(s,o);return ent(a,o)||o.fill(0),c},i=((s,...o)=>({encrypt(a){Dn(a);let c=e(r),l=t(s,c,...o).encrypt(a);return l instanceof Promise?l.then(u=>n(c,u,a)):n(c,l,a)},decrypt(a){Dn(a);let c=a.subarray(0,r),l=a.subarray(r);return t(s,c,...o).decrypt(l)}}));return"blockSize"in t&&(i.blockSize=t.blockSize),"tagLength"in t&&(i.tagLength=t.tagLength),i}var Lf,Efe,ws,Xrt,Yu,Sfe,Qrt,ap,kfe,z0=I(()=>{Lf=new Uint8Array(new Uint32Array([287454020]).buffer)[0]===68,Efe=t=>t<<24&4278190080|t<<8&16711680|t>>>8&65280|t>>>24&255,ws=Lf?t=>t:t=>Efe(t)>>>0,Xrt=t=>{for(let e=0;e<t.length;e++)t[e]=Efe(t[e]);return t},Yu=Lf?t=>t:Xrt,Sfe=typeof Uint8Array.from([]).toHex=="function"&&typeof Uint8Array.fromHex=="function",Qrt=Array.from({length:256},(t,e)=>e.toString(16).padStart(2,"0"));ap={_0:48,_9:57,A:65,F:70,a:97,f:102};kfe=(t,e)=>{function r(n,...i){if(Dn(n,void 0,"key"),t.nonceLength!==void 0){let u=i[0];Dn(u,t.varSizeNonce?void 0:t.nonceLength,"nonce")}let s=t.tagLength;s&&i[1]!==void 0&&Dn(i[1],void 0,"AAD");let o=e(n,...i),a=(u,d)=>{if(d!==void 0){if(u!==2)throw new Error("cipher output not supported");Dn(d,void 0,"output")}},c=!1;return{encrypt(u,d){if(c)throw new Error("cannot encrypt() twice with same key + nonce");return c=!0,Dn(u),a(o.encrypt.length,d),o.encrypt(u,d)},decrypt(u,d){if(Dn(u),s&&u.length<s)throw new Error('"ciphertext" expected length bigger than tagLength='+s);return a(o.decrypt.length,d),o.decrypt(u,d)}}}return Object.assign(r,t),r}});function Le(t,e){return t<<e|t>>>32-e}function int(t,e,r,n,i,s,o,a){let c=i.length,l=new Uint8Array(B0),u=Vu(l),d=Lf&&mv(i)&&mv(s),p=d?Vu(i):Nfe,f=d?Vu(s):Nfe;if(!Lf){for(let m=0;m<c;o++){if(t(e,r,n,u,o,a),Yu(u),o>=JH)throw new Error("arx: counter overflow");let h=Math.min(B0,c-m);for(let y=0,g;y<h;y++)g=m+y,s[g]=i[g]^l[y];m+=h}return}for(let m=0;m<c;o++){if(t(e,r,n,u,o,a),o>=JH)throw new Error("arx: counter overflow");let h=Math.min(B0,c-m);if(d&&h===B0){let y=m/4;if(m%4!==0)throw new Error("arx: invalid block position");for(let g=0,b;g<nnt;g++)b=y+g,f[b]=p[b]^u[g];m+=B0;continue}for(let y=0,g;y<h;y++)g=m+y,s[g]=i[g]^l[y];m+=h}}function Dfe(t,e){let{allowShortKeys:r,extendNonceFn:n,counterLength:i,counterRight:s,rounds:o}=Ife({allowShortKeys:!1,counterLength:8,counterRight:!1,rounds:20},e);if(typeof t!="function")throw new Error("core must be a function");return Mf(i),Mf(o),vC(s),vC(r),(a,c,l,u,d=0)=>{Dn(a,void 0,"key"),Dn(c,void 0,"nonce"),Dn(l,void 0,"data");let p=l.length;if(u=F0(p,u,!1),Mf(d),d<0||d>=JH)throw new Error("arx: counter overflow");let f=[],m=a.length,h,y;if(m===32)f.push(h=hv(a)),y=rnt;else if(m===16&&r)h=new Uint8Array(32),h.set(a),h.set(a,16),y=tnt,f.push(h);else throw Dn(a,32,"arx key"),new Error("invalid key size");(!Lf||!mv(c))&&f.push(c=hv(c));let g=Vu(h);if(n){if(c.length!==24)throw new Error("arx: extended nonce must be 24 bytes");let _=c.subarray(0,16);if(Lf)n(y,g,Vu(_),g);else{let w=Yu(Uint32Array.from(y));n(w,g,Vu(_),g),Ll(w),Yu(g)}c=c.subarray(16)}else Lf||Yu(g);let b=16-i;if(b!==c.length)throw new Error(`arx: nonce must be ${b} or 16 bytes`);if(b!==12){let _=new Uint8Array(12);_.set(c,s?0:12-c.length),c=_,f.push(c)}let v=Yu(Vu(c));try{return int(t,y,g,v,l,u,d,o),u}finally{Ll(...f)}}}var Pfe,tnt,rnt,B0,nnt,JH,Nfe,Mfe=I(()=>{z0();Pfe=t=>Uint8Array.from(t.split(""),e=>e.charCodeAt(0)),tnt=Yu(Vu(Pfe("expand 16-byte k"))),rnt=Yu(Vu(Pfe("expand 32-byte k")));B0=64,nnt=16,JH=2**32-1,Nfe=Uint32Array.of()});function Ts(t,e){return t[e++]&255|(t[e++]&255)<<8}var ZH,Lfe,jfe=I(()=>{z0();ZH=class{blockLen=16;outputLen=16;buffer=new Uint8Array(16);r=new Uint16Array(10);h=new Uint16Array(10);pad=new Uint16Array(8);pos=0;finished=!1;destroyed=!1;constructor(e){e=hv(Dn(e,32,"key"));let r=Ts(e,0),n=Ts(e,2),i=Ts(e,4),s=Ts(e,6),o=Ts(e,8),a=Ts(e,10),c=Ts(e,12),l=Ts(e,14);this.r[0]=r&8191,this.r[1]=(r>>>13|n<<3)&8191,this.r[2]=(n>>>10|i<<6)&7939,this.r[3]=(i>>>7|s<<9)&8191,this.r[4]=(s>>>4|o<<12)&255,this.r[5]=o>>>1&8190,this.r[6]=(o>>>14|a<<2)&8191,this.r[7]=(a>>>11|c<<5)&8065,this.r[8]=(c>>>8|l<<8)&8191,this.r[9]=l>>>5&127;for(let u=0;u<8;u++)this.pad[u]=Ts(e,16+2*u)}process(e,r,n=!1){let i=n?0:2048,{h:s,r:o}=this,a=o[0],c=o[1],l=o[2],u=o[3],d=o[4],p=o[5],f=o[6],m=o[7],h=o[8],y=o[9],g=Ts(e,r+0),b=Ts(e,r+2),v=Ts(e,r+4),_=Ts(e,r+6),w=Ts(e,r+8),S=Ts(e,r+10),x=Ts(e,r+12),O=Ts(e,r+14),N=s[0]+(g&8191),k=s[1]+((g>>>13|b<<3)&8191),M=s[2]+((b>>>10|v<<6)&8191),K=s[3]+((v>>>7|_<<9)&8191),P=s[4]+((_>>>4|w<<12)&8191),j=s[5]+(w>>>1&8191),U=s[6]+((w>>>14|S<<2)&8191),q=s[7]+((S>>>11|x<<5)&8191),F=s[8]+((x>>>8|O<<8)&8191),Q=s[9]+(O>>>5|i),J=0,W=J+N*a+k*(5*y)+M*(5*h)+K*(5*m)+P*(5*f);J=W>>>13,W&=8191,W+=j*(5*p)+U*(5*d)+q*(5*u)+F*(5*l)+Q*(5*c),J+=W>>>13,W&=8191;let z=J+N*c+k*a+M*(5*y)+K*(5*h)+P*(5*m);J=z>>>13,z&=8191,z+=j*(5*f)+U*(5*p)+q*(5*d)+F*(5*u)+Q*(5*l),J+=z>>>13,z&=8191;let G=J+N*l+k*c+M*a+K*(5*y)+P*(5*h);J=G>>>13,G&=8191,G+=j*(5*m)+U*(5*f)+q*(5*p)+F*(5*d)+Q*(5*u),J+=G>>>13,G&=8191;let H=J+N*u+k*l+M*c+K*a+P*(5*y);J=H>>>13,H&=8191,H+=j*(5*h)+U*(5*m)+q*(5*f)+F*(5*p)+Q*(5*d),J+=H>>>13,H&=8191;let L=J+N*d+k*u+M*l+K*c+P*a;J=L>>>13,L&=8191,L+=j*(5*y)+U*(5*h)+q*(5*m)+F*(5*f)+Q*(5*p),J+=L>>>13,L&=8191;let B=J+N*p+k*d+M*u+K*l+P*c;J=B>>>13,B&=8191,B+=j*a+U*(5*y)+q*(5*h)+F*(5*m)+Q*(5*f),J+=B>>>13,B&=8191;let ie=J+N*f+k*p+M*d+K*u+P*l;J=ie>>>13,ie&=8191,ie+=j*c+U*a+q*(5*y)+F*(5*h)+Q*(5*m),J+=ie>>>13,ie&=8191;let xe=J+N*m+k*f+M*p+K*d+P*u;J=xe>>>13,xe&=8191,xe+=j*l+U*c+q*a+F*(5*y)+Q*(5*h),J+=xe>>>13,xe&=8191;let Ne=J+N*h+k*m+M*f+K*p+P*d;J=Ne>>>13,Ne&=8191,Ne+=j*u+U*l+q*c+F*a+Q*(5*y),J+=Ne>>>13,Ne&=8191;let bt=J+N*y+k*h+M*m+K*f+P*p;J=bt>>>13,bt&=8191,bt+=j*d+U*u+q*l+F*c+Q*a,J+=bt>>>13,bt&=8191,J=(J<<2)+J|0,J=J+W|0,W=J&8191,J=J>>>13,z+=J,s[0]=W,s[1]=z,s[2]=G,s[3]=H,s[4]=L,s[5]=B,s[6]=ie,s[7]=xe,s[8]=Ne,s[9]=bt}finalize(){let{h:e,pad:r}=this,n=new Uint16Array(10),i=e[1]>>>13;e[1]&=8191;for(let a=2;a<10;a++)e[a]+=i,i=e[a]>>>13,e[a]&=8191;e[0]+=i*5,i=e[0]>>>13,e[0]&=8191,e[1]+=i,i=e[1]>>>13,e[1]&=8191,e[2]+=i,n[0]=e[0]+5,i=n[0]>>>13,n[0]&=8191;for(let a=1;a<10;a++)n[a]=e[a]+i,i=n[a]>>>13,n[a]&=8191;n[9]-=8192;let s=(i^1)-1;for(let a=0;a<10;a++)n[a]&=s;s=~s;for(let a=0;a<10;a++)e[a]=e[a]&s|n[a];e[0]=(e[0]|e[1]<<13)&65535,e[1]=(e[1]>>>3|e[2]<<10)&65535,e[2]=(e[2]>>>6|e[3]<<7)&65535,e[3]=(e[3]>>>9|e[4]<<4)&65535,e[4]=(e[4]>>>12|e[5]<<1|e[6]<<14)&65535,e[5]=(e[6]>>>2|e[7]<<11)&65535,e[6]=(e[7]>>>5|e[8]<<8)&65535,e[7]=(e[8]>>>8|e[9]<<5)&65535;let o=e[0]+r[0];e[0]=o&65535;for(let a=1;a<8;a++)o=(e[a]+r[a]|0)+(o>>>16)|0,e[a]=o&65535;Ll(n)}update(e){GH(this),Dn(e),e=hv(e);let{buffer:r,blockLen:n}=this,i=e.length;for(let s=0;s<i;){let o=Math.min(n-this.pos,i-s);if(o===n){for(;n<=i-s;s+=n)this.process(e,s);continue}r.set(e.subarray(s,s+o),this.pos),this.pos+=o,s+=o,this.pos===n&&(this.process(r,0,!1),this.pos=0)}return this}destroy(){this.destroyed=!0,Ll(this.h,this.r,this.buffer,this.pad)}digestInto(e){GH(this),_fe(e,this),this.finished=!0;let{buffer:r,h:n}=this,{pos:i}=this;if(i){for(r[i++]=1;i<16;i++)r[i]=0;this.process(r,0,!0)}this.finalize();let s=0;for(let o=0;o<8;o++)e[s++]=n[o]>>>0,e[s++]=n[o]>>>8}digest(){let{buffer:e,outputLen:r}=this;this.digestInto(e);let n=e.slice(0,r);return this.destroy(),n}},Lfe=Ofe(32,t=>new ZH(t))});function snt(t,e,r,n,i,s=20){let o=t[0],a=t[1],c=t[2],l=t[3],u=e[0],d=e[1],p=e[2],f=e[3],m=e[4],h=e[5],y=e[6],g=e[7],b=i,v=r[0],_=r[1],w=r[2],S=o,x=a,O=c,N=l,k=u,M=d,K=p,P=f,j=m,U=h,q=y,F=g,Q=b,J=v,W=_,z=w;for(let H=0;H<s;H+=2)S=S+k|0,Q=Le(Q^S,16),j=j+Q|0,k=Le(k^j,12),S=S+k|0,Q=Le(Q^S,8),j=j+Q|0,k=Le(k^j,7),x=x+M|0,J=Le(J^x,16),U=U+J|0,M=Le(M^U,12),x=x+M|0,J=Le(J^x,8),U=U+J|0,M=Le(M^U,7),O=O+K|0,W=Le(W^O,16),q=q+W|0,K=Le(K^q,12),O=O+K|0,W=Le(W^O,8),q=q+W|0,K=Le(K^q,7),N=N+P|0,z=Le(z^N,16),F=F+z|0,P=Le(P^F,12),N=N+P|0,z=Le(z^N,8),F=F+z|0,P=Le(P^F,7),S=S+M|0,z=Le(z^S,16),q=q+z|0,M=Le(M^q,12),S=S+M|0,z=Le(z^S,8),q=q+z|0,M=Le(M^q,7),x=x+K|0,Q=Le(Q^x,16),F=F+Q|0,K=Le(K^F,12),x=x+K|0,Q=Le(Q^x,8),F=F+Q|0,K=Le(K^F,7),O=O+P|0,J=Le(J^O,16),j=j+J|0,P=Le(P^j,12),O=O+P|0,J=Le(J^O,8),j=j+J|0,P=Le(P^j,7),N=N+k|0,W=Le(W^N,16),U=U+W|0,k=Le(k^U,12),N=N+k|0,W=Le(W^N,8),U=U+W|0,k=Le(k^U,7);let G=0;n[G++]=o+S|0,n[G++]=a+x|0,n[G++]=c+O|0,n[G++]=l+N|0,n[G++]=u+k|0,n[G++]=d+M|0,n[G++]=p+K|0,n[G++]=f+P|0,n[G++]=m+j|0,n[G++]=h+U|0,n[G++]=y+q|0,n[G++]=g+F|0,n[G++]=b+Q|0,n[G++]=v+J|0,n[G++]=_+W|0,n[G++]=w+z|0}function ont(t,e,r,n){let i=ws(t[0]),s=ws(t[1]),o=ws(t[2]),a=ws(t[3]),c=ws(e[0]),l=ws(e[1]),u=ws(e[2]),d=ws(e[3]),p=ws(e[4]),f=ws(e[5]),m=ws(e[6]),h=ws(e[7]),y=ws(r[0]),g=ws(r[1]),b=ws(r[2]),v=ws(r[3]);for(let w=0;w<20;w+=2)i=i+c|0,y=Le(y^i,16),p=p+y|0,c=Le(c^p,12),i=i+c|0,y=Le(y^i,8),p=p+y|0,c=Le(c^p,7),s=s+l|0,g=Le(g^s,16),f=f+g|0,l=Le(l^f,12),s=s+l|0,g=Le(g^s,8),f=f+g|0,l=Le(l^f,7),o=o+u|0,b=Le(b^o,16),m=m+b|0,u=Le(u^m,12),o=o+u|0,b=Le(b^o,8),m=m+b|0,u=Le(u^m,7),a=a+d|0,v=Le(v^a,16),h=h+v|0,d=Le(d^h,12),a=a+d|0,v=Le(v^a,8),h=h+v|0,d=Le(d^h,7),i=i+l|0,v=Le(v^i,16),m=m+v|0,l=Le(l^m,12),i=i+l|0,v=Le(v^i,8),m=m+v|0,l=Le(l^m,7),s=s+u|0,y=Le(y^s,16),h=h+y|0,u=Le(u^h,12),s=s+u|0,y=Le(y^s,8),h=h+y|0,u=Le(u^h,7),o=o+d|0,g=Le(g^o,16),p=p+g|0,d=Le(d^p,12),o=o+d|0,g=Le(g^o,8),p=p+g|0,d=Le(d^p,7),a=a+c|0,b=Le(b^a,16),f=f+b|0,c=Le(c^f,12),a=a+c|0,b=Le(b^a,8),f=f+b|0,c=Le(c^f,7);let _=0;n[_++]=i,n[_++]=s,n[_++]=o,n[_++]=a,n[_++]=y,n[_++]=g,n[_++]=b,n[_++]=v,Yu(n)}function Kfe(t,e,r,n,i){i!==void 0&&Dn(i,void 0,"AAD");let s=t(e,r,lnt),o=Rfe(n.length,i?i.length:0,!0),a=Lfe.create(s);i&&Ufe(a,i),Ufe(a,n),a.update(o);let c=a.digest();return Ll(s,o),c}var ant,cnt,Ufe,lnt,unt,XH,qfe=I(()=>{Mfe();jfe();z0();ant=Dfe(snt,{counterRight:!1,counterLength:8,extendNonceFn:ont,allowShortKeys:!1}),cnt=new Uint8Array(16),Ufe=(t,e)=>{t.update(e);let r=e.length%16;r&&t.update(cnt.subarray(r))},lnt=new Uint8Array(32);unt=t=>(e,r,n)=>({encrypt(s,o){let a=s.length;o=F0(a+16,o,!1),o.set(s);let c=o.subarray(0,-16);t(e,r,c,c,1);let l=Kfe(t,e,r,c,n);return o.set(l,a),Ll(l),o},decrypt(s,o){o=F0(s.length-16,o,!1);let a=s.subarray(0,-16),c=s.subarray(-16),l=Kfe(t,e,r,a,n);if(!Afe(c,l))throw Ll(l),new Error("invalid tag");return o.set(s.subarray(0,-16)),t(e,r,o,o,1),Ll(l),o}}),XH=kfe({blockSize:64,nonceLength:24,tagLength:16},unt(ant))});function dnt(t){if(!t.startsWith(zfe))return null;let e=4,r=t.indexOf("$",e);if(r===-1)return null;let n=parseInt(t.slice(e,r),10);return!Number.isInteger(n)||n<0?null:{version:n,ciphertext:t.slice(r+1)}}function pnt(t,e){return`${zfe}${t}$${e}`}async function Ffe(t,e){let r=await op("SHA-256").digest(t),n=Tfe(e);return VH(YH(XH)(new Uint8Array(r)).encrypt(n))}async function QH(t,e){let r=await op("SHA-256").digest(t),n=wfe(e),i=YH(XH)(new Uint8Array(r));return new TextDecoder().decode(i.decrypt(n))}var zfe,_C,EC,SC=I(()=>{b0();K0();q0();qfe();z0();zfe="$ba$";_C=async({key:t,data:e})=>{if(typeof t=="string")return Ffe(t,e);let r=t.keys.get(t.currentVersion);if(!r)throw new Error(`Secret version ${t.currentVersion} not found in keys`);let n=await Ffe(r,e);return pnt(t.currentVersion,n)},EC=async({key:t,data:e})=>{if(typeof t=="string")return QH(t,e);let r=dnt(e);if(r){let n=t.keys.get(r.version);if(!n)throw new Error(`Secret version ${r.version} not found in keys (key may have been retired)`);return QH(n,r.ciphertext)}if(t.legacySecret)return QH(t.legacySecret,e);throw new Error("Cannot decrypt legacy bare-hex payload: no legacy secret available. Set BETTER_AUTH_SECRET for backwards compatibility.")}});var Zs,eW=I(()=>{Zs=t=>{let e=(t.plugins??[]).reduce((d,p)=>{let f=p.schema;if(!f)return d;for(let[m,h]of Object.entries(f))d[m]={fields:{...d[m]?.fields,...h.fields},modelName:h.modelName||m};return d},{}),r=t.rateLimit?.storage==="database",n={rateLimit:{modelName:t.rateLimit?.modelName||"rateLimit",fields:{key:{type:"string",unique:!0,required:!0,fieldName:t.rateLimit?.fields?.key||"key"},count:{type:"number",required:!0,fieldName:t.rateLimit?.fields?.count||"count"},lastRequest:{type:"number",bigint:!0,required:!0,fieldName:t.rateLimit?.fields?.lastRequest||"lastRequest",defaultValue:()=>Date.now()}}}},{user:i,session:s,account:o,verification:a,...c}=e,l={verification:{modelName:t.verification?.modelName||"verification",fields:{identifier:{type:"string",required:!0,fieldName:t.verification?.fields?.identifier||"identifier",index:!0},value:{type:"string",required:!0,fieldName:t.verification?.fields?.value||"value"},expiresAt:{type:"date",required:!0,fieldName:t.verification?.fields?.expiresAt||"expiresAt"},createdAt:{type:"date",required:!0,defaultValue:()=>new Date,fieldName:t.verification?.fields?.createdAt||"createdAt"},updatedAt:{type:"date",required:!0,defaultValue:()=>new Date,onUpdate:()=>new Date,fieldName:t.verification?.fields?.updatedAt||"updatedAt"},...a?.fields,...t.verification?.additionalFields},order:4}},u={session:{modelName:t.session?.modelName||"session",fields:{expiresAt:{type:"date",required:!0,fieldName:t.session?.fields?.expiresAt||"expiresAt"},token:{type:"string",required:!0,fieldName:t.session?.fields?.token||"token",unique:!0},createdAt:{type:"date",required:!0,fieldName:t.session?.fields?.createdAt||"createdAt",defaultValue:()=>new Date},updatedAt:{type:"date",required:!0,fieldName:t.session?.fields?.updatedAt||"updatedAt",onUpdate:()=>new Date},ipAddress:{type:"string",required:!1,fieldName:t.session?.fields?.ipAddress||"ipAddress"},userAgent:{type:"string",required:!1,fieldName:t.session?.fields?.userAgent||"userAgent"},userId:{type:"string",fieldName:t.session?.fields?.userId||"userId",references:{model:t.user?.modelName||"user",field:"id",onDelete:"cascade"},required:!0,index:!0},...s?.fields,...t.session?.additionalFields},order:2}};return{user:{modelName:t.user?.modelName||"user",fields:{name:{type:"string",required:!0,fieldName:t.user?.fields?.name||"name",sortable:!0},email:{type:"string",unique:!0,required:!0,fieldName:t.user?.fields?.email||"email",sortable:!0},emailVerified:{type:"boolean",defaultValue:!1,required:!0,fieldName:t.user?.fields?.emailVerified||"emailVerified",input:!1},image:{type:"string",required:!1,fieldName:t.user?.fields?.image||"image"},createdAt:{type:"date",defaultValue:()=>new Date,required:!0,fieldName:t.user?.fields?.createdAt||"createdAt"},updatedAt:{type:"date",defaultValue:()=>new Date,onUpdate:()=>new Date,required:!0,fieldName:t.user?.fields?.updatedAt||"updatedAt"},...i?.fields,...t.user?.additionalFields},order:1},...!t.secondaryStorage||t.session?.storeSessionInDatabase?u:{},account:{modelName:t.account?.modelName||"account",fields:{accountId:{type:"string",required:!0,fieldName:t.account?.fields?.accountId||"accountId"},providerId:{type:"string",required:!0,fieldName:t.account?.fields?.providerId||"providerId"},userId:{type:"string",references:{model:t.user?.modelName||"user",field:"id",onDelete:"cascade"},required:!0,fieldName:t.account?.fields?.userId||"userId",index:!0},accessToken:{type:"string",required:!1,returned:!1,fieldName:t.account?.fields?.accessToken||"accessToken"},refreshToken:{type:"string",required:!1,returned:!1,fieldName:t.account?.fields?.refreshToken||"refreshToken"},idToken:{type:"string",required:!1,returned:!1,fieldName:t.account?.fields?.idToken||"idToken"},accessTokenExpiresAt:{type:"date",required:!1,returned:!1,fieldName:t.account?.fields?.accessTokenExpiresAt||"accessTokenExpiresAt"},refreshTokenExpiresAt:{type:"date",required:!1,returned:!1,fieldName:t.account?.fields?.refreshTokenExpiresAt||"refreshTokenExpiresAt"},scope:{type:"string",required:!1,fieldName:t.account?.fields?.scope||"scope"},password:{type:"string",required:!1,returned:!1,fieldName:t.account?.fields?.password||"password"},createdAt:{type:"date",required:!0,fieldName:t.account?.fields?.createdAt||"createdAt",defaultValue:()=>new Date},updatedAt:{type:"date",required:!0,fieldName:t.account?.fields?.updatedAt||"updatedAt",onUpdate:()=>new Date},...o?.fields,...t.account?.additionalFields},order:3},...!t.secondaryStorage||t.verification?.storeInDatabase?l:{},...c,...r?n:{}}}});var Gh,Ju,gv=I(()=>{Gh=le(require("zod"),1),Ju=Gh.object({id:Gh.string(),createdAt:Gh.date().default(()=>new Date),updatedAt:Gh.date().default(()=>new Date)})});var Va,Bfe,Hfe=I(()=>{gv();Va=le(require("zod"),1),Bfe=Ju.extend({providerId:Va.string(),accountId:Va.string(),userId:Va.coerce.string(),accessToken:Va.string().nullish(),refreshToken:Va.string().nullish(),idToken:Va.string().nullish(),accessTokenExpiresAt:Va.date().nullish(),refreshTokenExpiresAt:Va.date().nullish(),scope:Va.string().nullish(),password:Va.string().nullish()})});var Vh,Wfe,$fe=I(()=>{Vh=le(require("zod"),1),Wfe=Vh.object({key:Vh.string(),count:Vh.number(),lastRequest:Vh.number()})});var jf,Gfe,Vfe=I(()=>{gv();jf=le(require("zod"),1),Gfe=Ju.extend({userId:jf.coerce.string(),expiresAt:jf.date(),token:jf.string(),ipAddress:jf.string().nullish(),userAgent:jf.string().nullish()})});var yv,Yfe,Jfe=I(()=>{gv();yv=le(require("zod"),1),Yfe=Ju.extend({email:yv.string().transform(t=>t.toLowerCase()),emailVerified:yv.boolean().default(!1),name:yv.string(),image:yv.string().nullish()})});var H0,Zfe,Xfe=I(()=>{gv();H0=le(require("zod"),1),Zfe=Ju.extend({value:H0.string(),expiresAt:H0.date(),identifier:H0.string()})});var tW={};ui(tW,{accountSchema:()=>Bfe,coreSchema:()=>Ju,getAuthTables:()=>Zs,rateLimitSchema:()=>Wfe,sessionSchema:()=>Gfe,userSchema:()=>Yfe,verificationSchema:()=>Zfe});var cp=I(()=>{eW();gv();Hfe();$fe();Vfe();Jfe();Xfe()});function Xs(t,e){if(!t||!e)return t;let r=Object.entries(e).filter(([,{returned:n}])=>n===!1).map(([n])=>n);return Object.entries(structuredClone(t)).filter(([n])=>!r.includes(n)).reduce((n,[i,s])=>({...n,[i]:s}),{})}var wC=I(()=>{});function Uf(t,e,r){let n=`${e}:${r}`;rW.has(t)||rW.set(t,new Map);let i=rW.get(t);if(i.has(n))return i.get(n);let s=r==="output"?Zs(t)[e]?.fields??{}:{},o=e==="user"||e==="session"||e==="account"?t[e]?.additionalFields:void 0,a={...s,...o??{}};for(let c of t.plugins||[])c.schema&&c.schema[e]&&(a={...a,...c.schema[e].fields});return i.set(n,a),a}function Br(t,e){return Xs(e,Uf(t,"user","output"))}function Wi(t,e){return Xs(e,Uf(t,"session","output"))}function TC(t,e){let{accessToken:r,refreshToken:n,idToken:i,accessTokenExpiresAt:s,refreshTokenExpiresAt:o,password:a,...c}=Xs(e,Uf(t,"account","output"));return c}function bv(t,e){let r=e.action||"create",n=e.fields,i=Object.create(null);for(let s in n){if(s in t){if(n[s].input===!1){if(n[s].defaultValue!==void 0&&r!=="update"){i[s]=n[s].defaultValue;continue}if(t[s])throw D.from("BAD_REQUEST",{...ae.FIELD_NOT_ALLOWED,message:`${s} is not allowed to be set`});continue}if(n[s].validator?.input&&t[s]!==void 0){let o=n[s].validator.input["~standard"].validate(t[s]);if(o instanceof Promise)throw D.from("INTERNAL_SERVER_ERROR",ae.ASYNC_VALIDATION_NOT_SUPPORTED);if("issues"in o&&o.issues)throw D.from("BAD_REQUEST",{...ae.VALIDATION_ERROR,message:o.issues[0]?.message||"Validation Error"});i[s]=o.value;continue}if(n[s].transform?.input&&t[s]!==void 0){i[s]=n[s].transform?.input(t[s]);continue}i[s]=t[s];continue}if(n[s].defaultValue!==void 0&&r==="create"){if(typeof n[s].defaultValue=="function"){i[s]=n[s].defaultValue();continue}i[s]=n[s].defaultValue;continue}if(n[s].required&&r==="create")throw D.from("BAD_REQUEST",{...ae.MISSING_FIELD,message:`${s} is required`})}return i}function vv(t,e={},r){return bv(e,{fields:Uf(t,"user","input"),action:r})}function Qfe(t,e){let r=Uf(t,"user","input");return bv(e||{},{fields:r})}function eme(t,e){return bv(e,{fields:Uf(t,"account","input")})}function xC(t,e,r){return bv(e,{fields:Uf(t,"session","input"),action:r})}function IC(t){let e=Uf(t,"session","input"),r={};for(let n in e)e[n].defaultValue!==void 0&&(r[n]=typeof e[n].defaultValue=="function"?e[n].defaultValue():e[n].defaultValue);return r}function AC(t,e){if(!e)return t;for(let r in e){let n=e[r]?.modelName;n&&(t[r].modelName=n);for(let i in t[r].fields){let s=e[r]?.fields?.[i];s&&(t[r].fields[i].fieldName=s)}}return t}var rW,jl=I(()=>{cp();rt();wC();rW=new WeakMap});var xo,Yh=I(()=>{xo=(t,e="ms")=>new Date(Date.now()+(e==="sec"?t*1e3:t))});function _v(t){return!!t&&(typeof t=="object"||typeof t=="function")&&typeof t.then=="function"}var OC=I(()=>{});function mnt(t){let e=fnt.exec(t);if(!e||e[4]&&e[1])throw new TypeError(`Invalid time string format: "${t}". Use formats like "7d", "30m", "1 hour", etc.`);let r=parseFloat(e[2]),n=e[3].toLowerCase(),i;switch(n){case"years":case"year":case"yrs":case"yr":case"y":i=r*315576e5;break;case"months":case"month":case"mo":i=r*2592e6;break;case"weeks":case"week":case"w":i=r*6048e5;break;case"days":case"day":case"d":i=r*864e5;break;case"hours":case"hour":case"hrs":case"hr":case"h":i=r*36e5;break;case"minutes":case"minute":case"mins":case"min":case"m":i=r*6e4;break;case"seconds":case"second":case"secs":case"sec":case"s":i=r*1e3;break;default:throw new TypeError(`Unknown time unit: "${n}"`)}return e[1]==="-"||e[4]==="ago"?-i:i}function tme(t){return Math.round(mnt(t)/1e3)}var fnt,rme=I(()=>{fnt=/^(\+|\-)? ?(\d+|\d+\.\d+) ?(seconds?|secs?|s|minutes?|mins?|m|hours?|hrs?|h|days?|d|weeks?|w|months?|mo|years?|yrs?|y)(?: (ago|from now))?$/i});var nme,ime=I(()=>{nme="__Secure-"});function sme(t){if(typeof t=="string"&&hnt.test(t)){let e=new Date(t);if(!isNaN(e.getTime()))return e}return t}function nW(t){if(t==null)return t;if(typeof t=="string")return sme(t);if(t instanceof Date)return t;if(Array.isArray(t))return t.map(nW);if(typeof t=="object"){let e={};for(let r of Object.keys(t))e[r]=nW(t[r]);return e}return t}function lr(t){try{return typeof t!="string"?t==null?null:nW(t):JSON.parse(t,(e,r)=>sme(r))}catch(e){return De.error("Error parsing JSON",{error:e}),null}}var hnt,lp=I(()=>{bs();hnt=/^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}(?:\.\d+)?Z$/});function gnt(t){let e=t.headers?.get("cookie");if(!e)return{};let r={},n=e.split("; ");for(let i of n){let[s,...o]=i.split("=");s&&o.length>0&&(r[s]=o.join("="))}return r}function ome(t){let e=t.split("."),r=e[e.length-1],n=parseInt(r||"0",10);return isNaN(n)?0:n}function ynt(t,e){let r={},n=gnt(e);for(let[i,s]of Object.entries(n))i.startsWith(t)&&(r[i]=s);return r}function bnt(t){return Object.keys(t).sort((e,r)=>ome(e)-ome(r)).map(e=>t[e]).join("")}function vnt(t,e,r,n){let i=Math.ceil(e.value.length/iW);if(i===1)return r[e.name]=e.value,[e];let s=[];for(let o=0;o<i;o++){let a=`${e.name}.${o}`,c=o*iW,l=e.value.substring(c,c+iW);s.push({...e,name:a,value:l}),r[a]=l}return n.debug(`CHUNKING_${t.toUpperCase()}_COOKIE`,{message:`${t} cookie exceeds allowed ${oW} bytes.`,emptyCookieSize:sW,valueSize:e.value.length,chunkCount:i,chunks:s.map(o=>o.value.length+sW)}),s}function ame(t,e){let r={};for(let n in t)r[n]={name:n,value:"",attributes:{...e,maxAge:0}};return r}function CC(t,e){let r=t.getCookie(e);if(r)return r;let n=[],i=t.headers?.get("cookie");if(!i)return null;let s={},o=i.split("; ");for(let a of o){let[c,...l]=a.split("=");c&&l.length>0&&(s[c]=l.join("="))}for(let[a,c]of Object.entries(s))if(a.startsWith(e+".")){let l=a.split(".").at(-1),u=parseInt(l||"0",10);isNaN(u)||n.push({index:u,value:c})}return n.length>0?(n.sort((a,c)=>a.index-c.index),n.map(a=>a.value).join("")):null}async function Kf(t,e){let r=t.context.authCookies.accountData,n={maxAge:300,...r.attributes},i=await gC(e,t.context.secretConfig,"better-auth-account",n.maxAge);if(i.length>oW){let s=kC(r.name,n,t),o=s.chunk(i,n);s.setCookies(o)}else{let s=kC(r.name,n,t);if(s.hasChunks()){let o=s.clean();s.setCookies(o)}t.setCookie(r.name,i,n)}}async function Ev(t){let e=CC(t,t.context.authCookies.accountData.name);if(e){let r=lr(await j0(e,t.context.secretConfig,"better-auth-account"));if(r)return r}return null}var Jh,oW,sW,iW,cme,RC,kC,lme,W0=I(()=>{U0();lp();Jh=le(require("zod"),1),oW=4096,sW=200,iW=oW-sW;cme=t=>(e,r,n)=>{let i=ynt(e,n),s=n.context.logger;return{getValue(){return bnt(i)},hasChunks(){return Object.keys(i).length>0},chunk(o,a){let c=ame(i,r);for(let d in i)delete i[d];let l=c,u=vnt(t,{name:e,value:o,attributes:{...r,...a}},i,s);for(let d of u)l[d.name]=d;return Object.values(l)},clean(){let o=ame(i,r);for(let a in i)delete i[a];return Object.values(o)},setCookies(o){for(let a of o)n.setCookie(a.name,a.value,a.attributes)}}},RC=cme("Session"),kC=cme("Account");lme=Jh.optional(Jh.object({disableCookieCache:Jh.coerce.boolean().meta({description:"Disable cookie cache and fetch session from database"}).optional(),disableRefresh:Jh.coerce.boolean().meta({description:"Disable session refresh. Useful for checking session status, without updating the session"}).optional()}))});var aW,_nt,cW,lW=I(()=>{aW=new Map,_nt=new TextEncoder,cW={decode:(t,e="utf-8")=>(aW.has(e)||aW.set(e,new TextDecoder(e)),aW.get(e).decode(t)),encode:_nt.encode}});var Ent,uW,ume=I(()=>{Ent="0123456789abcdef",uW={encode:t=>{if(typeof t=="string"&&(t=new TextEncoder().encode(t)),t.byteLength===0)return"";let e=new Uint8Array(t),r="";for(let n of e)r+=n.toString(16).padStart(2,"0");return r},decode:t=>{if(!t)return"";if(typeof t=="string"){if(t.length%2!==0)throw new Error("Invalid hexadecimal string");if(!new RegExp(`^[${Ent}]+$`).test(t))throw new Error("Invalid hexadecimal string");let e=new Uint8Array(t.length/2);for(let r=0;r<t.length;r+=2)e[r/2]=parseInt(t.slice(r,r+2),16);return new TextDecoder().decode(e)}return new TextDecoder().decode(t)}}});var NC,dW=I(()=>{ume();pa();K0();NC=(t="SHA-256",e="none")=>{let r={importKey:async(n,i)=>Ml().importKey("raw",typeof n=="string"?new TextEncoder().encode(n):n,{name:"HMAC",hash:{name:t}},!1,[i]),sign:async(n,i)=>{typeof n=="string"&&(n=await r.importKey(n,"sign"));let s=await Ml().sign("HMAC",n,typeof i=="string"?new TextEncoder().encode(i):i);return e==="hex"?uW.encode(s):e==="base64"||e==="base64url"||e==="base64urlnopad"?da.encode(s,{padding:e!=="base64urlnopad"}):s},verify:async(n,i,s)=>(typeof n=="string"&&(n=await r.importKey(n,"verify")),e==="hex"&&(s=uW.decode(s)),(e==="base64"||e==="base64url"||e==="base64urlnopad")&&(s=await Hi.decode(s)),Ml().verify("HMAC",n,typeof s=="string"?new TextEncoder().encode(s):s,typeof i=="string"?new TextEncoder().encode(i):i))};return r}});function $0(t){let e=typeof t.baseURL=="string"?t.baseURL:void 0,r=typeof t.baseURL=="object"&&t.baseURL!==null?t.baseURL.protocol:void 0,n=(t.advanced?.useSecureCookies!==void 0?t.advanced?.useSecureCookies:r==="https"||r!=="http"&&(e?e.startsWith("https://"):xf))?nme:"",i=!!t.advanced?.crossSubDomainCookies?.enabled,s=i?t.advanced?.crossSubDomainCookies?.domain||(e?new URL(e).hostname:void 0):void 0;if(i&&!s&&!Wa(t.baseURL))throw new me("baseURL is required when crossSubdomainCookies are enabled.");function o(a,c={}){let l=t.advanced?.cookiePrefix||"better-auth",u=t.advanced?.cookies?.[a]?.name||`${l}.${a}`,d=t.advanced?.cookies?.[a]?.attributes??{};return{name:`${n}${u}`,attributes:{secure:!!n,sameSite:"lax",path:"/",httpOnly:!0,...i?{domain:s}:{},...t.advanced?.defaultCookieAttributes,...c,...d}}}return o}function PC(t){let e=$0(t),r=e("session_token",{maxAge:t.session?.expiresIn||tme("7d")}),n=e("session_data",{maxAge:t.session?.cookieCache?.maxAge||300}),i=e("account_data",{maxAge:t.session?.cookieCache?.maxAge||300}),s=e("dont_remember");return{sessionToken:{name:r.name,attributes:r.attributes},sessionData:{name:n.name,attributes:n.attributes},dontRememberToken:{name:s.name,attributes:s.attributes},accountData:{name:i.name,attributes:i.attributes}}}async function G0(t,e,r){if(!t.context.options.session?.cookieCache?.enabled)return;let n=Xs(e.session,t.context.options.session?.additionalFields),i=Br(t.context.options,e.user),s=t.context.options.session?.cookieCache?.version,o="1";if(s){if(typeof s=="string")o=s;else if(typeof s=="function"){let p=s(e.session,e.user);o=_v(p)?await p:p}}let a={session:n,user:i,updatedAt:Date.now(),version:o},c={...t.context.authCookies.sessionData.attributes,maxAge:r?void 0:t.context.authCookies.sessionData.attributes.maxAge},l=xo(c.maxAge||60,"sec").getTime(),u=t.context.options.session?.cookieCache?.strategy||"compact",d;if(u==="jwe"?d=await gC(a,t.context.secretConfig,"better-auth-session",c.maxAge||300):u==="jwt"?d=await hC(a,t.context.secret,c.maxAge||300):d=da.encode(JSON.stringify({session:a,expiresAt:l,signature:await NC("SHA-256","base64urlnopad").sign(t.context.secret,JSON.stringify({...a,expiresAt:l}))}),{padding:!1}),d.length>4093){let p=RC(t.context.authCookies.sessionData.name,c,t),f=p.chunk(d,c);p.setCookies(f)}else{let p=RC(t.context.authCookies.sessionData.name,c,t);if(p.hasChunks()){let f=p.clean();p.setCookies(f)}t.setCookie(t.context.authCookies.sessionData.name,d,c)}if(t.context.options.account?.storeAccountCookie){let p=await Ev(t);p&&await Kf(t,p)}}async function jr(t,e,r,n){let i=await t.getSignedCookie(t.context.authCookies.dontRememberToken.name,t.context.secret);r=r!==void 0?r:!!i;let s=t.context.authCookies.sessionToken.attributes,o=r?void 0:t.context.sessionConfig.expiresIn;await t.setSignedCookie(t.context.authCookies.sessionToken.name,e.session.token,t.context.secret,{...s,maxAge:o,...n}),r&&await t.setSignedCookie(t.context.authCookies.dontRememberToken.name,"true",t.context.secret,t.context.authCookies.dontRememberToken.attributes),await G0(t,e,r),t.context.setNewSession(e)}function fa(t,e){t.setCookie(e.name,"",{...e.attributes,maxAge:0})}function qf(t,e){if(fa(t,t.context.authCookies.sessionToken),fa(t,t.context.authCookies.sessionData),t.context.options.account?.storeAccountCookie){fa(t,t.context.authCookies.accountData);let i=kC(t.context.authCookies.accountData.name,t.context.authCookies.accountData.attributes,t),s=i.clean();i.setCookies(s)}t.context.oauthConfig.storeStateStrategy==="cookie"&&fa(t,t.context.createAuthCookie("oauth_state"));let r=RC(t.context.authCookies.sessionData.name,t.context.authCookies.sessionData.attributes,t),n=r.clean();r.setCookies(n),e||fa(t,t.context.authCookies.dontRememberToken)}var Io=I(()=>{Kh();U0();jl();Yh();OC();rme();ime();W0();vs();rt();wC();pa();lW();dW()});async function pme(t,e,r){let n=tp(32);if(t.context.oauthConfig.storeStateStrategy==="cookie"){let o={...e,oauthState:n},a=await _C({key:t.context.secretConfig,data:JSON.stringify(o)}),c=t.context.createAuthCookie(r?.cookieName??"oauth_state",{maxAge:600});return t.setCookie(c.name,a,c.attributes),{state:n,codeVerifier:e.codeVerifier}}let i=t.context.createAuthCookie(r?.cookieName??"state",{maxAge:300});await t.setSignedCookie(i.name,n,t.context.secret,i.attributes);let s=new Date;if(s.setMinutes(s.getMinutes()+10),!await t.context.internalAdapter.createVerificationValue({value:JSON.stringify({...e,oauthState:n}),identifier:n,expiresAt:s}))throw new Zu("Unable to create verification. Make sure the database adapter is properly working and there is a verification table in the database",{code:"state_generation_error"});return{state:n,codeVerifier:e.codeVerifier}}async function fme(t,e,r){let n=t.context.oauthConfig.storeStateStrategy,i;if(n==="cookie"){let s=t.context.createAuthCookie(r?.cookieName??"oauth_state"),o=t.getCookie(s.name);if(!o)throw new Zu("State mismatch: auth state cookie not found",{code:"state_mismatch",details:{state:e}});try{let a=await EC({key:t.context.secretConfig,data:o});i=dme.parse(JSON.parse(a))}catch(a){throw new Zu("State invalid: Failed to decrypt or parse auth state",{code:"state_invalid",details:{state:e},cause:a})}if(!i.oauthState||i.oauthState!==e)throw new Zu("State mismatch: OAuth state parameter does not match stored state",{code:"state_security_mismatch",details:{state:e}});fa(t,s)}else{let s=await t.context.internalAdapter.findVerificationValue(e);if(!s)throw new Zu("State mismatch: verification not found",{code:"state_mismatch",details:{state:e}});if(i=dme.parse(JSON.parse(s.value)),i.oauthState!==void 0&&i.oauthState!==e)throw new Zu("State mismatch: OAuth state parameter does not match stored state",{code:"state_security_mismatch",details:{state:e}});let o=t.context.createAuthCookie(r?.cookieName??"state"),a=await t.getSignedCookie(o.name,t.context.secret);if(!(r?.skipStateCookieCheck??t.context.oauthConfig.skipStateCookieCheck)&&(!a||a!==e))throw new Zu("State mismatch: State not persisted correctly",{code:"state_security_mismatch",details:{state:e}});fa(t,o),await t.context.internalAdapter.deleteVerificationByIdentifier(e)}if(i.expiresAt<Date.now())throw new Zu("Invalid state: request expired",{code:"state_mismatch",details:{expiresAt:i.expiresAt}});return i}var xs,dme,Zu,mme=I(()=>{b0();SC();Io();rt();xs=le(require("zod"),1),dme=xs.looseObject({callbackURL:xs.string(),codeVerifier:xs.string(),errorURL:xs.string().optional(),newUserURL:xs.string().optional(),expiresAt:xs.number(),oauthState:xs.string().optional(),link:xs.object({email:xs.string(),userId:xs.coerce.string()}).optional(),requestSignUp:xs.boolean().optional()}),Zu=class extends me{code;details;constructor(t,e){super(t,e),this.code=e.code,this.details=e.details}}});function Zh(){return globalThis[V0]||(globalThis[V0]={version:pW,epoch:1,context:Snt},Y0=globalThis[V0]),Y0=globalThis[V0],Y0.version!==pW&&(Y0.version=pW,Y0.epoch++),globalThis[V0]}function fW(){return Zh().version}var V0,Y0,Snt,pW,J0=I(()=>{V0=Symbol.for("better-auth:global"),Y0=null,Snt={},pW="1.6.10"});async function Sv(){let t=await wnt;if(t===null)throw new Error("getAsyncLocalStorage is only available in server code");return t}var wnt,DC=I(()=>{wnt=import("node:async_hooks").then(t=>t.AsyncLocalStorage).catch(t=>{if("AsyncLocalStorage"in globalThis)return globalThis.AsyncLocalStorage;if(typeof window<"u")return null;throw console.warn("[better-auth] Warning: AsyncLocalStorage is not available in this environment. Some features may not work as expected."),console.warn("[better-auth] Please read more about this warning at https://better-auth.com/docs/installation#mount-handler"),console.warn("[better-auth] If you are using Cloudflare Workers, please see: https://developers.cloudflare.com/workers/configuration/compatibility-flags/#nodejs-compatibility-flag"),t})});async function up(){let t=(await hme()).getStore();if(!t)throw new Error("No auth context found. Please make sure you are calling this function within a `runWithEndpointContext` callback.");return t}async function wv(t,e){return(await hme()).run(t,e)}var hme,mW=I(()=>{J0();DC();hme=async()=>{let t=Zh();if(!t.context.endpointContextAsyncStorage){let e=await Sv();t.context.endpointContextAsyncStorage=new e}return t.context.endpointContextAsyncStorage}});async function yW(){return(await gW()).getStore()!==void 0}async function hW(){let t=(await gW()).getStore();if(!t)throw new Error("No request state found. Please make sure you are calling this function within a `runWithRequestState` callback.");return t}async function bW(t,e){return(await gW()).run(t,e)}function Z0(t){let e=Object.freeze({});return{get ref(){return e},async get(){let r=await hW();if(!r.has(e)){let n=await t();return r.set(e,n),n}return r.get(e)},async set(r){(await hW()).set(e,r)}}}var gW,gme=I(()=>{J0();DC();gW=async()=>{let t=Zh();if(!t.context.requestStateAsyncStorage){let e=await Sv();t.context.requestStateAsyncStorage=new e}return t.context.requestStateAsyncStorage}});var MC,Ue,vW,X0,Xh,yme=I(()=>{J0();DC();MC=async()=>{let t=Zh();if(!t.context.adapterAsyncStorage){let e=await Sv();t.context.adapterAsyncStorage=new e}return t.context.adapterAsyncStorage},Ue=async t=>MC().then(e=>e.getStore()?.adapter||t).catch(()=>t),vW=async(t,e)=>{let r=!1;return MC().then(async n=>{r=!0;let i=[],s,o,a=!1;try{s=await n.run({adapter:t,pendingHooks:i},e)}catch(c){o=c,a=!0}for(let c of i)await c();if(a)throw o;return s}).catch(n=>{if(!r)return e();throw n})},X0=async(t,e)=>{let r=!0;return MC().then(async n=>{r=!0;let i=[],s,o,a=!1;try{s=await t.transaction(async c=>n.run({adapter:c,pendingHooks:i},e))}catch(c){a=!0,o=c}for(let c of i)await c();if(a)throw o;return s}).catch(n=>{if(!r)return e();throw n})},Xh=async t=>MC().then(e=>{let r=e.getStore();if(r)r.pendingHooks.push(t);else return t()}).catch(()=>t())});var Xu=I(()=>{J0();mW();gme();yme()});var tZt,_W,bme=I(()=>{Xu();({get:tZt,set:_W}=Z0(()=>null))});async function LC(t,e,r){let n=t.body?.callbackURL||t.context.options.baseURL;if(!n)throw D.from("BAD_REQUEST",ae.CALLBACK_URL_REQUIRED);let i=tp(128),s={...r||{},callbackURL:n,codeVerifier:i,errorURL:t.body?.errorCallbackURL,newUserURL:t.body?.newUserCallbackURL,link:e,expiresAt:Date.now()+600*1e3,requestSignUp:t.body?.requestSignUp};await _W(s);try{return pme(t,s)}catch(o){throw t.context.logger.error("Failed to create verification",o),new D("INTERNAL_SERVER_ERROR",{message:"Unable to create verification",cause:o})}}async function vme(t){let e=t.query.state||t.body?.state,r=t.context.options.onAPIError?.errorURL||`${t.context.baseURL}/error`,n;try{n=await fme(t,e)}catch(i){throw t.context.logger.error("Failed to parse state",i),i instanceof Zu&&i.code==="state_security_mismatch"?t.redirect(`${r}?error=state_mismatch`):t.redirect(`${r}?error=please_restart_the_process`)}return n.errorURL||(n.errorURL=r),n&&await _W(n),n}var jC=I(()=>{b0();bme();mme();rt()});var Tv,UC=I(()=>{Tv={scope:"server"}});async function _me(t,e){let r=t.headers.get("content-type")||"",n=r.toLowerCase();if(t.body){if(e&&e.length>0&&!e.some(i=>{let s=n.split(";")[0].trim(),o=i.toLowerCase().trim();return s===o||s.includes(o)}))throw n?new ua(415,{message:`Content-Type "${r}" is not allowed. Allowed types: ${e.join(", ")}`,code:"UNSUPPORTED_MEDIA_TYPE"}):new ua(415,{message:`Content-Type is required. Allowed types: ${e.join(", ")}`,code:"UNSUPPORTED_MEDIA_TYPE"});if(Tnt.test(n))return await t.json();if(n.includes("application/x-www-form-urlencoded")){let i=await t.formData(),s={};return i.forEach((o,a)=>{s[a]=o.toString()}),s}if(n.includes("multipart/form-data")){let i=await t.formData(),s={};return i.forEach((o,a)=>{s[a]=o}),s}return n.includes("text/plain")?await t.text():n.includes("application/octet-stream")?await t.arrayBuffer():n.includes("application/pdf")||n.includes("image/")||n.includes("video/")?await t.blob():n.includes("application/stream")||t.body instanceof ReadableStream?t.body:await t.text()}}function dp(t){return t instanceof ua||t?.name==="APIError"}function Eme(t){try{return t.includes("%")?decodeURIComponent(t):t}catch{return t}}async function Sme(t){try{return{data:await t,error:null}}catch(e){return{data:null,error:e}}}function KC(t){return t instanceof Request||Object.prototype.toString.call(t)==="[object Request]"}var Tnt,Qh=I(()=>{If();Tnt=/^application\/([a-z0-9.+-]*\+)?json/i});function xnt(t){if(t===void 0)return!1;let e=typeof t;return e==="string"||e==="number"||e==="boolean"||e===null?!0:e!=="object"?!1:Array.isArray(t)?!0:t.buffer?!1:t.constructor&&t.constructor.name==="Object"||typeof t.toJSON=="function"}function Int(t,e,r){let n=0,i=new WeakMap;return JSON.stringify(t,(o,a)=>{if(typeof a=="bigint")return a.toString();if(typeof a=="object"&&a!==null){if(i.has(a))return`[Circular ref-${i.get(a)}]`;i.set(a,n++)}return e?e(o,a):a},r)}function Ant(t){return!t||typeof t!="object"?!1:"_flag"in t&&t._flag==="json"}function EW(t){for(let e of Ont)t.delete(e)}function Ul(t,e){if(t instanceof Response){if(e?.headers){let i=new Headers(e.headers);EW(i),i.forEach((s,o)=>{t.headers.set(o,s)})}return t}if(Ant(t)){let i=t.body,s=t.routerResponse;if(s instanceof Response)return s;let o=new Headers;i | |||
There was a problem hiding this comment.
Incomplete fix — bypass when no base URL env var is configured
The entire validation block is guarded by if(Bnt), where Bnt is populated only when one of BETTER_AUTH_URL, NEXT_PUBLIC_BETTER_AUTH_URL, PUBLIC_BETTER_AUTH_URL, NUXT_PUBLIC_BETTER_AUTH_URL, or NUXT_PUBLIC_AUTH_URL is set. If none of these env vars are configured (a common deployment scenario), Bnt is falsy, the allowlist check is skipped entirely, and s (the value from x-forwarded-host) is passed unchanged to Qd()—exactly the same behavior as before this patch. The vulnerability described in the PR description is still fully exploitable on those deployments.
Prompt To Fix With AI
This is a comment left during a code review.
Path: plugin/scripts/worker-service.cjs
Line: 787
Comment:
**Incomplete fix — bypass when no base URL env var is configured**
The entire validation block is guarded by `if(Bnt)`, where `Bnt` is populated only when one of `BETTER_AUTH_URL`, `NEXT_PUBLIC_BETTER_AUTH_URL`, `PUBLIC_BETTER_AUTH_URL`, `NUXT_PUBLIC_BETTER_AUTH_URL`, or `NUXT_PUBLIC_AUTH_URL` is set. If none of these env vars are configured (a common deployment scenario), `Bnt` is falsy, the allowlist check is skipped entirely, and `s` (the value from `x-forwarded-host`) is passed unchanged to `Qd()`—exactly the same behavior as before this patch. The vulnerability described in the PR description is still fully exploitable on those deployments.
How can I resolve this? If you propose a fix, please make it concise.| @@ -784,7 +784,7 @@ return fn.apply(this, arguments) | |||
| </html> | |||
| `}function Ott(){return function(){this.error(404)}}function ktt(){return function(e){if(this.hasTrailingSlash()){this.error(404);return}var r=oH.original(this.req);r.path=null,r.pathname=Itt(r.pathname+"/");var n=_tt(Ttt.format(r)),i=Att("Redirecting","Redirecting to "+Ett(n));e.statusCode=301,e.setHeader("Content-Type","text/html; charset=UTF-8"),e.setHeader("Content-Length",Buffer.byteLength(i)),e.setHeader("Content-Security-Policy","default-src 'none'"),e.setHeader("X-Content-Type-Options","nosniff"),e.setHeader("Location",n),e.end(i)}}});var $ue=C((Hc,Wue)=>{"use strict";var AR=wce(),Rtt=require("node:events").EventEmitter,que=xce(),Fue=Cle(),zue=q4(),Bue=oue(),Hue=jue();Hc=Wue.exports=Ctt;function Ctt(){var t=function(e,r,n){t.handle(e,r,n)};return que(t,Rtt.prototype,!1),que(t,Fue,!1),t.request=Object.create(Bue,{app:{configurable:!0,enumerable:!0,writable:!0,value:t}}),t.response=Object.create(Hue,{app:{configurable:!0,enumerable:!0,writable:!0,value:t}}),t.init(),t}Hc.application=Fue;Hc.request=Bue;Hc.response=Hue;Hc.Route=zue.Route;Hc.Router=zue;Hc.json=AR.json;Hc.raw=AR.raw;Hc.static=Kue();Hc.text=AR.text;Hc.urlencoded=AR.urlencoded});var OR=C((WVt,Gue)=>{"use strict";Gue.exports=$ue()});var Zue=C((GVt,Jue)=>{"use strict";var Yue=Object.getOwnPropertySymbols,Ntt=Object.prototype.hasOwnProperty,Ptt=Object.prototype.propertyIsEnumerable;function Dtt(t){if(t==null)throw new TypeError("Object.assign cannot be called with null or undefined");return Object(t)}function Mtt(){try{if(!Object.assign)return!1;var t=new String("abc");if(t[5]="de",Object.getOwnPropertyNames(t)[0]==="5")return!1;for(var e={},r=0;r<10;r++)e["_"+String.fromCharCode(r)]=r;var n=Object.getOwnPropertyNames(e).map(function(s){return e[s]});if(n.join("")!=="0123456789")return!1;var i={};return"abcdefghijklmnopqrst".split("").forEach(function(s){i[s]=s}),Object.keys(Object.assign({},i)).join("")==="abcdefghijklmnopqrst"}catch{return!1}}Jue.exports=Mtt()?Object.assign:function(t,e){for(var r,n=Dtt(t),i,s=1;s<arguments.length;s++){r=Object(arguments[s]);for(var o in r)Ntt.call(r,o)&&(n[o]=r[o]);if(Yue){i=Yue(r);for(var a=0;a<i.length;a++)Ptt.call(r,i[a])&&(n[i[a]]=r[i[a]])}}return n}});var Que=C((VVt,Xue)=>{(function(){"use strict";var t=Zue(),e=nH(),r={origin:"*",methods:"GET,HEAD,PUT,PATCH,POST,DELETE",preflightContinue:!1,optionsSuccessStatus:204};function n(m){return typeof m=="string"||m instanceof String}function i(m,h){if(Array.isArray(h)){for(var y=0;y<h.length;++y)if(i(m,h[y]))return!0;return!1}else return n(h)?m===h:h instanceof RegExp?h.test(m):!!h}function s(m,h){var y=h.headers.origin,g=[],b;return!m.origin||m.origin==="*"?g.push([{key:"Access-Control-Allow-Origin",value:"*"}]):n(m.origin)?(g.push([{key:"Access-Control-Allow-Origin",value:m.origin}]),g.push([{key:"Vary",value:"Origin"}])):(b=i(y,m.origin),g.push([{key:"Access-Control-Allow-Origin",value:b?y:!1}]),g.push([{key:"Vary",value:"Origin"}])),g}function o(m){var h=m.methods;return h.join&&(h=m.methods.join(",")),{key:"Access-Control-Allow-Methods",value:h}}function a(m){return m.credentials===!0?{key:"Access-Control-Allow-Credentials",value:"true"}:null}function c(m,h){var y=m.allowedHeaders||m.headers,g=[];return y?y.join&&(y=y.join(",")):(y=h.headers["access-control-request-headers"],g.push([{key:"Vary",value:"Access-Control-Request-Headers"}])),y&&y.length&&g.push([{key:"Access-Control-Allow-Headers",value:y}]),g}function l(m){var h=m.exposedHeaders;if(h)h.join&&(h=h.join(","));else return null;return h&&h.length?{key:"Access-Control-Expose-Headers",value:h}:null}function u(m){var h=(typeof m.maxAge=="number"||m.maxAge)&&m.maxAge.toString();return h&&h.length?{key:"Access-Control-Max-Age",value:h}:null}function d(m,h){for(var y=0,g=m.length;y<g;y++){var b=m[y];b&&(Array.isArray(b)?d(b,h):b.key==="Vary"&&b.value?e(h,b.value):b.value&&h.setHeader(b.key,b.value))}}function p(m,h,y,g){var b=[],v=h.method&&h.method.toUpperCase&&h.method.toUpperCase();v==="OPTIONS"?(b.push(s(m,h)),b.push(a(m)),b.push(o(m)),b.push(c(m,h)),b.push(u(m)),b.push(l(m)),d(b,y),m.preflightContinue?g():(y.statusCode=m.optionsSuccessStatus,y.setHeader("Content-Length","0"),y.end())):(b.push(s(m,h)),b.push(a(m)),b.push(l(m)),d(b,y),g())}function f(m){var h=null;return typeof m=="function"?h=m:h=function(y,g){g(null,m)},function(g,b,v){h(g,function(_,w){if(_)v(_);else{var S=t({},r,w),x=null;S.origin&&typeof S.origin=="function"?x=S.origin:S.origin&&(x=function(O,N){N(null,S.origin)}),x?x(g.headers.origin,function(O,N){O||!N?v(O):(S.origin=N,p(S,g,b,v))}):v()}})}}Xue.exports=f})()});function rde(t,e,r,n){let i={error:t,message:e};return r&&(i.code=r),n&&(i.details=n),i}function ide(t,e){e.status(404).json(rde("NotFound",`Cannot ${t.method} ${t.path}`))}var Gs,nde,l0=I(()=>{"use strict";fe();Gs=class extends Error{constructor(r,n=500,i,s){super(r);this.statusCode=n;this.code=i;this.details=s;this.name="AppError"}statusCode;code;details};nde=(t,e,r,n)=>{let i=t instanceof Gs?t.statusCode:500;E.error("HTTP",`Error handling ${e.method} ${e.path}`,{statusCode:i,error:t.message,code:t instanceof Gs?t.code:void 0},t);let s=rde(t.name||"Error",t.message,t instanceof Gs?t.code:void 0,t instanceof Gs?t.details:void 0);r.status(i).json(s)}});function mH(t){return typeof t!="string"||t in{}}function hH(){return Object.create(null)}function pde(t){return typeof t=="string"&&!!t.trim()}function gH(t,e){var r=t.split(";").filter(pde),n=r.shift(),i=Ftt(n),s=i.name,o=i.value;if(e=e?Object.assign({},CR,e):CR,mH(s))return null;try{o=e.decodeValues?decodeURIComponent(o):o}catch(c){console.error("set-cookie-parser: failed to decode cookie value. Set options.decodeValues=false to disable decoding.",c)}var a=hH();return a.name=s,a.value=o,r.forEach(function(c){var l=c.split("="),u=l.shift().trimLeft().toLowerCase();if(!mH(u)){var d=l.join("=");if(u==="expires")a.expires=new Date(d);else if(u==="max-age"){var p=parseInt(d,10);Number.isNaN(p)||(a.maxAge=p)}else u==="secure"?a.secure=!0:u==="httponly"?a.httpOnly=!0:u==="samesite"?a.sameSite=d:u==="partitioned"?a.partitioned=!0:u&&(a[u]=d)}}),a}function Ftt(t){var e="",r="",n=t.split("=");return n.length>1?(e=n.shift(),r=n.join("=")):r=t,{name:e,value:r}}function Zb(t,e){if(e=e?Object.assign({},CR,e):CR,!t)return e.map?hH():[];if(t.headers)if(typeof t.headers.getSetCookie=="function")t=t.headers.getSetCookie();else if(t.headers["set-cookie"])t=t.headers["set-cookie"];else{var r=t.headers[Object.keys(t.headers).find(function(o){return o.toLowerCase()==="set-cookie"})];!r&&t.headers.cookie&&!e.silent&&console.warn("Warning: set-cookie-parser appears to have been called on a request object. It is designed to parse Set-Cookie headers from responses, not Cookie headers from requests. Set the option {silent: true} to suppress this warning."),t=r}var n=e.split,i=Array.isArray(t);if(n==="auto"&&(n=!i),i||(t=[t]),t=t.filter(pde),n&&(t=t.map(NR).flat()),e.map){var s=hH();return t.reduce(function(o,a){var c=gH(a,e);return c&&!mH(c.name)&&(o[c.name]=c),o},s)}else return t.map(function(o){return gH(o,e)}).filter(Boolean)}function NR(t){if(Array.isArray(t))return t;if(typeof t!="string")return[];var e=[],r=0,n,i,s,o,a;function c(){for(;r<t.length&&/\s/.test(t.charAt(r));)r+=1;return r<t.length}function l(){return i=t.charAt(r),i!=="="&&i!==";"&&i!==","}for(;r<t.length;){for(n=r,a=!1;c();)if(i=t.charAt(r),i===","){for(s=r,r+=1,c(),o=r;r<t.length&&l();)r+=1;r<t.length&&t.charAt(r)==="="?(a=!0,r=o,e.push(t.substring(n,s)),n=r):r=s+1}else r+=1;(!a||r>=t.length)&&e.push(t.substring(n,t.length))}return e}var CR,fde=I(()=>{CR={decodeValues:!0,map:!1,silent:!1,split:"auto"};Zb.parseSetCookie=Zb;Zb.parse=Zb;Zb.parseString=gH;Zb.splitCookiesString=NR});function Vtt(t,e){let r=t.headers;if(!r["content-type"])return null;let n=Number(r["content-length"]);if(t.httpVersionMajor===1&&isNaN(n)&&r["transfer-encoding"]==null||n===0)return null;let i=n;if(e){if(!i)i=e;else if(i>e)throw Error(`Received content-length of ${i}, but only accept up to ${e} bytes.`)}if(t.destroyed){let a=new ReadableStream;return a.cancel(),a}let s=0,o=!1;return new ReadableStream({start(a){t.on("error",c=>{o=!0,a.error(c)}),t.on("end",()=>{o||a.close()}),t.on("data",c=>{if(!o){if(s+=c.length,s>i){o=!0,a.error(new Error(`request body size exceeded ${n?"'content-length'":"BODY_SIZE_LIMIT"} of ${i}`));return}a.enqueue(c),(a.desiredSize===null||a.desiredSize<=0)&&t.pause()}})},pull(){t.resume()},cancel(a){o=!0,t.destroy(a)}})}function Ytt(t){let e=t.baseUrl,r=t.originalUrl;return!e||!r?e?e+t.url:t.url:e+t.url===r||r.split("?")[0].at(-1)==="/"?e+t.url:e}function gde({request:t,base:e,bodySizeLimit:r}){let n=t,i=Htt(t.headers),s,o=t.method;if(o!=="GET"&&o!=="HEAD"){if($tt(t))s=Vtt(t,r);else if(n.body!==void 0){let a=n.body,c=Gtt(a,i);s=new ReadableStream({start(l){l.enqueue(new TextEncoder().encode(c)),l.close()}})}}return new Request(e+Ytt(t),{duplex:"half",method:t.method,body:s,headers:t.headers})}async function yde(t,e){for(let[s,o]of e.headers)try{t.setHeader(s,s==="set-cookie"?NR(e.headers.get(s)):o)}catch(a){t.getHeaderNames().forEach(c=>t.removeHeader(c)),t.writeHead(500).end(String(a));return}if(t.statusCode=e.status,t.writeHead(e.status),!e.body){t.end();return}if(e.body.locked){t.end("Fatal error: Response body is locked. This can happen when the response was already read (for example through 'response.json()' or 'response.text()').");return}let r=e.body.getReader();if(t.destroyed){r.cancel();return}let n=s=>{t.off("close",n),t.off("error",n),r.cancel(s).catch(()=>{}),s&&t.destroy(s)};t.on("close",n),t.on("error",n),i();async function i(){try{for(;;){let{done:s,value:o}=await r.read();if(s)break;if(!t.write(o)){if(process.env.AWS_LAMBDA_FUNCTION_NAME||process.env.LAMBDA_TASK_ROOT)continue;t.once("drain",i);return}t.end()}}catch(s){n(s instanceof Error?s:new Error(String(s)))}}}var Btt,Htt,mde,hde,Wtt,$tt,Gtt,bde=I(()=>{fde();Btt=t=>Array.isArray(t)?t[0]:t,Htt=t=>{let e=Btt(t["content-type"]);return e?e.toLowerCase().startsWith("application/x-www-form-urlencoded"):!1},mde=t=>{if(typeof t!="object"||t===null)return!1;let e=Object.getPrototypeOf(t);return e===Object.prototype||e===null},hde=(t,e,r)=>{if(r!==void 0){if(Array.isArray(r)){for(let n of r)hde(t,e,n);return}if(r===null){t.append(e,"");return}if(mde(r)){t.append(e,JSON.stringify(r));return}t.append(e,`${r}`)}},Wtt=t=>{let e=new URLSearchParams;for(let[r,n]of Object.entries(t))hde(e,r,n);return e.toString()},$tt=t=>!t.destroyed&&t.readableEnded!==!0&&t.readable,Gtt=(t,e)=>typeof t=="string"?t:t instanceof URLSearchParams?t.toString():e&&mde(t)?Wtt(t):JSON.stringify(t)});function yH(t){return async(e,r)=>yde(r,await t(gde({base:`${e.headers["x-forwarded-proto"]||(e.socket.encrypted?"https":"http")}://${e.headers[":authority"]||e.headers.host}`,request:e})))}var vde=I(()=>{bde()});var _de={};ui(_de,{fromNodeHeaders:()=>Ztt,toNodeHandler:()=>Jtt});function Ztt(t){let e=new Headers;for(let[r,n]of Object.entries(t))n!==void 0&&(Array.isArray(n)?n.forEach(i=>e.append(r,i)):e.set(r,n));return e}var Jtt,Ede=I(()=>{vde();Jtt=t=>"handler"in t?yH(t.handler):yH(t)});function bH(t){return t==="-"||t==="^"||t==="$"||t==="+"||t==="."||t==="("||t===")"||t==="|"||t==="["||t==="]"||t==="{"||t==="}"||t==="*"||t==="?"||t==="\\"?`\\${t}`:t}function Xtt(t){let e="";for(let r=0;r<t.length;r++)e+=bH(t[r]);return e}function Sde(t,e=!0){if(Array.isArray(t))return`(?:${t.map(l=>`^${Sde(l,e)}$`).join("|")})`;let r="",n="",i=".";e===!0?(r="/",n="[/\\\\]",i="[^/\\\\]"):e&&(r=e,n=Xtt(r),n.length>1?(n=`(?:${n})`,i=`((?!${n}).)`):i=`[^${n}]`);let s=e?`${n}+?`:"",o=e?`${n}*?`:"",a=e?t.split(r):[t],c="";for(let l=0;l<a.length;l++){let u=a[l],d=a[l+1],p="";if(!(!u&&l>0)){if(e&&(l===a.length-1?p=o:d!=="**"?p=s:p=""),e&&u==="**"){p&&(c+=l===0?"":p,c+=`(?:${i}*?${p})*?`);continue}for(let f=0;f<u.length;f++){let m=u[f];m==="\\"?f<u.length-1&&(c+=bH(u[f+1]),f++):m==="?"?c+=i:m==="*"?c+=`${i}*?`:c+=bH(m)}c+=p}}return c}function Qtt(t,e){if(typeof e!="string")throw new TypeError(`Sample must be a string, but ${typeof e} given`);return t.test(e)}function Uh(t,e){if(typeof t!="string"&&!Array.isArray(t))throw new TypeError(`The first argument must be a single pattern string or an array of patterns, but ${typeof t} given`);if((typeof e=="string"||typeof e=="boolean")&&(e={separator:e}),arguments.length===2&&!(typeof e>"u"||typeof e=="object"&&e!==null&&!Array.isArray(e)))throw new TypeError(`The second argument must be an options object or a string/boolean separator, but ${typeof e} given`);if(e=e||{},e.separator==="\\")throw new Error("\\ is not a valid separator because it is used for escaping. Try setting the separator to `true` instead");let r=Sde(t,e.separator),n=new RegExp(`^${r}$`,e.flags),i=Qtt.bind(null,n);return i.options=e,i.pattern=t,i.regexp=n,i}var PR=I(()=>{});function ert(t){return t?t!=="false":!1}function hr(t,e){return typeof process<"u"&&process.env?process.env[t]??e:typeof Deno<"u"?Deno.env.get(t)??e:typeof Bun<"u"?Bun.env[t]??e:e}function MR(t,e=!0){let r=hr(t);return r?r!=="0"&&r.toLowerCase()!=="false"&&r!=="":e}var DR,p0,Zt,f0,xf,Jd,Nl,vH,_H=I(()=>{DR=Object.create(null),p0=t=>globalThis.process?.env||globalThis.Deno?.env.toObject()||globalThis.__env__||(t?DR:globalThis),Zt=new Proxy(DR,{get(t,e){return p0()[e]??DR[e]},has(t,e){return e in p0()||e in DR},set(t,e,r){let n=p0(!0);return n[e]=r,!0},deleteProperty(t,e){if(!e)return!1;let r=p0(!0);return delete r[e],!0},ownKeys(){let t=p0(!0);return Object.keys(t)}});f0=typeof process<"u"&&process.env&&process.env.NODE_ENV||"",xf=f0==="production",Jd=()=>f0==="dev"||f0==="development",Nl=()=>f0==="test"||ert(Zt.TEST);vH=Object.freeze({get BETTER_AUTH_SECRET(){return hr("BETTER_AUTH_SECRET")},get AUTH_SECRET(){return hr("AUTH_SECRET")},get BETTER_AUTH_TELEMETRY(){return hr("BETTER_AUTH_TELEMETRY")},get BETTER_AUTH_TELEMETRY_ID(){return hr("BETTER_AUTH_TELEMETRY_ID")},get NODE_ENV(){return hr("NODE_ENV","development")},get PACKAGE_VERSION(){return hr("PACKAGE_VERSION","0.0.0")},get BETTER_AUTH_TELEMETRY_ENDPOINT(){return hr("BETTER_AUTH_TELEMETRY_ENDPOINT","")}})});function LR(){if(hr("FORCE_COLOR")!==void 0)switch(hr("FORCE_COLOR")){case"":case"1":case"true":return Bi;case"2":return zu;case"3":return Ha;default:return m0}if(hr("NODE_DISABLE_COLORS")!==void 0&&hr("NODE_DISABLE_COLORS")!==""||hr("NO_COLOR")!==void 0&&hr("NO_COLOR")!==""||hr("TERM")==="dumb")return m0;if(hr("TMUX"))return Ha;if("TF_BUILD"in Zt&&"AGENT_NAME"in Zt)return Bi;if("CI"in Zt){for(let{0:t,1:e}of trt)if(t in Zt)return e;return hr("CI_NAME")==="codeship"?zu:m0}if("TEAMCITY_VERSION"in Zt)return/^(9\.(0*[1-9]\d*)\.|\d{2,}\.)/.exec(hr("TEAMCITY_VERSION"))!==null?Bi:m0;switch(hr("TERM_PROGRAM")){case"iTerm.app":return!hr("TERM_PROGRAM_VERSION")||/^[0-2]\./.exec(hr("TERM_PROGRAM_VERSION"))!==null?zu:Ha;case"HyperTerm":case"MacTerm":return Ha;case"Apple_Terminal":return zu}if(hr("COLORTERM")==="truecolor"||hr("COLORTERM")==="24bit")return Ha;if(hr("TERM")){if(/truecolor/.exec(hr("TERM"))!==null)return Ha;if(/^xterm-256/.exec(hr("TERM"))!==null)return zu;let t=hr("TERM").toLowerCase();if(wde[t])return wde[t];if(rrt.some(e=>e.exec(t)!==null))return Bi}return hr("COLORTERM")?Bi:m0}var m0,Bi,zu,Ha,wde,trt,rrt,EH=I(()=>{_H();m0=1,Bi=4,zu=8,Ha=24,wde={eterm:Bi,cons25:Bi,console:Bi,cygwin:Bi,dtterm:Bi,gnome:Bi,hurd:Bi,jfbterm:Bi,konsole:Bi,kterm:Bi,mlterm:Bi,mosh:Ha,putty:Bi,st:Bi,"rxvt-unicode-24bit":Ha,terminator:Ha,"xterm-kitty":Ha},trt=new Map(Object.entries({APPVEYOR:zu,BUILDKITE:zu,CIRCLECI:Ha,DRONE:zu,GITEA_ACTIONS:Ha,GITHUB_ACTIONS:Ha,GITLAB_CI:zu,TRAVIS:zu})),rrt=[/ansi/,/color/,/linux/,/direct/,/^con[0-9]*x[0-9]/,/^rxvt/,/^screen/,/^xterm/,/^vt100/,/^vt220/]});function Xb(t,e){return jR.indexOf(e)>=jR.indexOf(t)}var ni,jR,nrt,irt,Zd,De,bs=I(()=>{EH();ni={reset:"\x1B[0m",bright:"\x1B[1m",dim:"\x1B[2m",undim:"\x1B[22m",underscore:"\x1B[4m",blink:"\x1B[5m",reverse:"\x1B[7m",hidden:"\x1B[8m",fg:{black:"\x1B[30m",red:"\x1B[31m",green:"\x1B[32m",yellow:"\x1B[33m",blue:"\x1B[34m",magenta:"\x1B[35m",cyan:"\x1B[36m",white:"\x1B[37m"},bg:{black:"\x1B[40m",red:"\x1B[41m",green:"\x1B[42m",yellow:"\x1B[43m",blue:"\x1B[44m",magenta:"\x1B[45m",cyan:"\x1B[46m",white:"\x1B[47m"}},jR=["debug","info","success","warn","error"];nrt={info:ni.fg.blue,success:ni.fg.green,warn:ni.fg.yellow,error:ni.fg.red,debug:ni.fg.magenta},irt=(t,e,r)=>{let n=new Date().toISOString();return r?`${ni.dim}${n}${ni.reset} ${nrt[t]}${t.toUpperCase()}${ni.reset} ${ni.bright}[Better Auth]:${ni.reset} ${e}`:`${n} ${t.toUpperCase()} [Better Auth]: ${e}`},Zd=t=>{let e=t?.disabled!==!0,r=t?.level??"warn",n=t?.disableColors!==void 0?!t.disableColors:LR()!==1,i=(s,o,a=[])=>{if(!e||!Xb(r,s))return;let c=irt(s,o,n);if(!t||typeof t.log!="function"){s==="error"?console.error(c,...a):s==="warn"?console.warn(c,...a):console.log(c,...a);return}t.log(s==="success"?"info":s,o,...a)};return{...Object.fromEntries(jR.map(s=>[s,(...[o,...a])=>i(s,o,a)])),get level(){return r}}},De=Zd()});var vs=I(()=>{_H();bs()});function Qb(t){return Object.fromEntries(Object.entries(t).map(([e,r])=>[e,{code:e,message:r,toString:()=>e}]))}var h0=I(()=>{});var ae,Tde=I(()=>{h0();ae=Qb({USER_NOT_FOUND:"User not found",FAILED_TO_CREATE_USER:"Failed to create user",FAILED_TO_CREATE_SESSION:"Failed to create session",FAILED_TO_UPDATE_USER:"Failed to update user",FAILED_TO_GET_SESSION:"Failed to get session",INVALID_PASSWORD:"Invalid password",INVALID_EMAIL:"Invalid email",INVALID_EMAIL_OR_PASSWORD:"Invalid email or password",INVALID_USER:"Invalid user",SOCIAL_ACCOUNT_ALREADY_LINKED:"Social account already linked",PROVIDER_NOT_FOUND:"Provider not found",INVALID_TOKEN:"Invalid token",TOKEN_EXPIRED:"Token expired",ID_TOKEN_NOT_SUPPORTED:"id_token not supported",FAILED_TO_GET_USER_INFO:"Failed to get user info",USER_EMAIL_NOT_FOUND:"User email not found",EMAIL_NOT_VERIFIED:"Email not verified",PASSWORD_TOO_SHORT:"Password too short",PASSWORD_TOO_LONG:"Password too long",USER_ALREADY_EXISTS:"User already exists.",USER_ALREADY_EXISTS_USE_ANOTHER_EMAIL:"User already exists. Use another email.",EMAIL_CAN_NOT_BE_UPDATED:"Email can not be updated",CREDENTIAL_ACCOUNT_NOT_FOUND:"Credential account not found",SESSION_EXPIRED:"Session expired. Re-authenticate to perform this action.",FAILED_TO_UNLINK_LAST_ACCOUNT:"You can't unlink your last account",ACCOUNT_NOT_FOUND:"Account not found",USER_ALREADY_HAS_PASSWORD:"User already has a password. Provide that to delete the account.",CROSS_SITE_NAVIGATION_LOGIN_BLOCKED:"Cross-site navigation login blocked. This request appears to be a CSRF attack.",VERIFICATION_EMAIL_NOT_ENABLED:"Verification email isn't enabled",EMAIL_ALREADY_VERIFIED:"Email is already verified",EMAIL_MISMATCH:"Email mismatch",SESSION_NOT_FRESH:"Session is not fresh",LINKED_ACCOUNT_ALREADY_EXISTS:"Linked account already exists",INVALID_ORIGIN:"Invalid origin",INVALID_CALLBACK_URL:"Invalid callbackURL",INVALID_REDIRECT_URL:"Invalid redirectURL",INVALID_ERROR_CALLBACK_URL:"Invalid errorCallbackURL",INVALID_NEW_USER_CALLBACK_URL:"Invalid newUserCallbackURL",MISSING_OR_NULL_ORIGIN:"Missing or null Origin",CALLBACK_URL_REQUIRED:"callbackURL is required",FAILED_TO_CREATE_VERIFICATION:"Unable to create verification",FIELD_NOT_ALLOWED:"Field not allowed to be set",ASYNC_VALIDATION_NOT_SUPPORTED:"Async validation is not supported",VALIDATION_ERROR:"Validation Error",MISSING_FIELD:"Field is required",METHOD_NOT_ALLOWED_DEFER_SESSION_REQUIRED:"POST method requires deferSessionRefresh to be enabled in session config",BODY_MUST_BE_AN_OBJECT:"Body must be an object",PASSWORD_ALREADY_SET:"User already has a password set"})});function srt(){let t=Object.getOwnPropertyDescriptor(Error,"stackTraceLimit");return t===void 0?Object.isExtensible(Error):Object.prototype.hasOwnProperty.call(t,"writable")?t.writable:t.set!==void 0}function xde(t){let e=t.split(` | |||
| at `);return e.length<=1?t:(e.splice(1,1),e.join(` | |||
| at `))}function Ide(t,e){class r extends t{#e;constructor(...i){if(srt()){let o=Error.stackTraceLimit;Error.stackTraceLimit=0,super(...i),Error.stackTraceLimit=o}else super(...i);let s=new Error().stack;s&&(this.#e=xde(s.replace(/^Error/,this.name)))}get errorStack(){return this.#e}}return Object.defineProperty(r.prototype,"constructor",{get(){return e},enumerable:!1,configurable:!0}),r}var Ade,Ode,g0,UR,Xd,ua,If=I(()=>{Ade={OK:200,CREATED:201,ACCEPTED:202,NO_CONTENT:204,MULTIPLE_CHOICES:300,MOVED_PERMANENTLY:301,FOUND:302,SEE_OTHER:303,NOT_MODIFIED:304,TEMPORARY_REDIRECT:307,BAD_REQUEST:400,UNAUTHORIZED:401,PAYMENT_REQUIRED:402,FORBIDDEN:403,NOT_FOUND:404,METHOD_NOT_ALLOWED:405,NOT_ACCEPTABLE:406,PROXY_AUTHENTICATION_REQUIRED:407,REQUEST_TIMEOUT:408,CONFLICT:409,GONE:410,LENGTH_REQUIRED:411,PRECONDITION_FAILED:412,PAYLOAD_TOO_LARGE:413,URI_TOO_LONG:414,UNSUPPORTED_MEDIA_TYPE:415,RANGE_NOT_SATISFIABLE:416,EXPECTATION_FAILED:417,"I'M_A_TEAPOT":418,MISDIRECTED_REQUEST:421,UNPROCESSABLE_ENTITY:422,LOCKED:423,FAILED_DEPENDENCY:424,TOO_EARLY:425,UPGRADE_REQUIRED:426,PRECONDITION_REQUIRED:428,TOO_MANY_REQUESTS:429,REQUEST_HEADER_FIELDS_TOO_LARGE:431,UNAVAILABLE_FOR_LEGAL_REASONS:451,INTERNAL_SERVER_ERROR:500,NOT_IMPLEMENTED:501,BAD_GATEWAY:502,SERVICE_UNAVAILABLE:503,GATEWAY_TIMEOUT:504,HTTP_VERSION_NOT_SUPPORTED:505,VARIANT_ALSO_NEGOTIATES:506,INSUFFICIENT_STORAGE:507,LOOP_DETECTED:508,NOT_EXTENDED:510,NETWORK_AUTHENTICATION_REQUIRED:511},Ode=class extends Error{constructor(t="INTERNAL_SERVER_ERROR",e=void 0,r={},n=typeof t=="number"?t:Ade[t]){super(e?.message,e?.cause?{cause:e.cause}:void 0),this.status=t,this.body=e,this.headers=r,this.statusCode=n,this.name="APIError",this.status=t,this.headers=r,this.statusCode=n,this.body=e}},g0=class extends Ode{constructor(t,e){super(400,{message:t,code:"VALIDATION_ERROR"}),this.message=t,this.issues=e,this.issues=e}},UR=class extends Error{constructor(t){super(t),this.name="BetterCallError"}},Xd=Symbol.for("better-call:api-error-headers"),ua=Ide(Ode,Error)});var me,D,rt=I(()=>{Tde();If();me=class extends Error{constructor(t,e){super(t,e),this.name="BetterAuthError",this.message=t,this.stack=""}},D=class SH extends ua{constructor(...e){super(...e)}static fromStatus(e,r){return new SH(e,r)}static from(e,r){return new SH(e,{message:r.message,code:r.code})}}});function ort(t){let e=t.replace(/:\d+$/,"").replace(/^\[|\]$/g,"").toLowerCase();return e==="localhost"||e.endsWith(".localhost")||e==="::1"||e.startsWith("127.")}function art(t){try{return(new URL(t).pathname.replace(/\/+$/,"")||"/")!=="/"}catch{throw new me(`Invalid base URL: ${t}. Please provide a valid base URL.`)}}function crt(t){try{let e=new URL(t);if(e.protocol!=="http:"&&e.protocol!=="https:")throw new me(`Invalid base URL: ${t}. URL must include 'http://' or 'https://'`)}catch(e){throw e instanceof me?e:new me(`Invalid base URL: ${t}. Please provide a valid base URL.`,{cause:e})}}function Qd(t,e="/api/auth"){if(crt(t),art(t))return t;let r=t.replace(/\/+$/,"");return!e||e==="/"?r:(e=e.startsWith("/")?e:`/${e}`,`${r}${e}`)}function y0(t,e){return!t||t.trim()===""?!1:e==="proto"?t==="http"||t==="https":e==="host"?[/\.\./,/\0/,/[\s]/,/^[.]/,/[<>'"]/,/javascript:/i,/file:/i,/data:/i].some(r=>r.test(t))?!1:/^[a-zA-Z0-9]([a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?(\.[a-zA-Z0-9]([a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?)*(:[0-9]{1,5})?$/.test(t)||/^(\d{1,3}\.){3}\d{1,3}(:[0-9]{1,5})?$/.test(t)||/^\[[0-9a-fA-F:]+\](:[0-9]{1,5})?$/.test(t)||/^localhost(:[0-9]{1,5})?$/i.test(t):!1}function ep(t,e,r,n,i){if(t)return Qd(t,e);if(n!==!1){let a=Zt.BETTER_AUTH_URL||Zt.NEXT_PUBLIC_BETTER_AUTH_URL||Zt.PUBLIC_BETTER_AUTH_URL||Zt.NUXT_PUBLIC_BETTER_AUTH_URL||Zt.NUXT_PUBLIC_AUTH_URL||(Zt.BASE_URL!=="/"?Zt.BASE_URL:void 0);if(a)return Qd(a,e)}let s=r?.headers.get("x-forwarded-host"),o=r?.headers.get("x-forwarded-proto");if(s&&o&&i&&y0(o,"proto")&&y0(s,"host"))try{return Qd(`${o}://${s}`,e)}catch{}if(r){let a=Af(r.url);if(!a)throw new me("Could not get origin from request. Please provide a valid base URL.");return Qd(a,e)}if(typeof window<"u"&&window.location)return Qd(window.location.origin,e)}function Af(t){try{let e=new URL(t);return e.origin==="null"?null:e.origin}catch{return null}}function kde(t){try{return new URL(t).protocol}catch{return null}}function Rde(t){try{return new URL(t).host}catch{return null}}function Wa(t){return typeof t=="object"&&t!==null&&"allowedHosts"in t&&Array.isArray(t.allowedHosts)}function Bu(t){if(t instanceof Request)return!0;if(typeof t!="object"||t===null||Object.prototype.toString.call(t)!=="[object Request]")return!1;let e=t;return typeof e.url=="string"&&typeof e.headers=="object"&&e.headers!==null&&typeof e.headers.get=="function"}function Cde(t,e){let r=Bu(t)?t.headers:t;if(e){let i=r.get("x-forwarded-host");if(i&&y0(i,"host"))return i}let n=r.get("host");if(n&&y0(n,"host"))return n;if(Bu(t))try{return new URL(t.url).host}catch{return null}return null}function lrt(t,e,r){if(e==="http"||e==="https")return e;let n=Bu(t)?t.headers:t;if(r){let s=n.get("x-forwarded-proto");if(s&&y0(s,"proto"))return s}if(Bu(t))try{let s=new URL(t.url);if(s.protocol==="http:"||s.protocol==="https:")return s.protocol.slice(0,-1)}catch{}let i=Cde(t,r);return i&&ort(i)?"http":"https"}function drt(t,e,r,n){let i=Cde(e,n);if(!i){if(t.fallback)return Qd(t.fallback,r);throw new me("Could not determine host from request headers. Please provide a fallback URL in your baseURL config.")}if(t.allowedHosts.some(s=>urt(i,s)))return Qd(`${lrt(e,t.protocol,n)}://${i}`,r);if(t.fallback)return Qd(t.fallback,r);throw new me(`Host "${i}" is not in the allowed hosts list. Allowed hosts: ${t.allowedHosts.join(", ")}. Add this host to your allowedHosts config or provide a fallback URL.`)}function Nde(t,e,r,n,i){if(Wa(t))return r?drt(t,r,e,i):t.fallback?Qd(t.fallback,e):ep(void 0,e,void 0,n,i);let s=Bu(r)?r:void 0;return ep(typeof t=="string"?t:void 0,e,s,n,i)}var urt,Kh=I(()=>{PR();vs();rt();urt=(t,e)=>{if(!t||!e)return!1;let r=t.replace(/^https?:\/\//,"").split("/")[0].toLowerCase(),n=e.replace(/^https?:\/\//,"").split("/")[0].toLowerCase();return n.includes("*")||n.includes("?")?Uh(n)(r):r.toLowerCase()===n.toLowerCase()}});function Pde(t){switch(t){case"a-z":return"abcdefghijklmnopqrstuvwxyz";case"A-Z":return"ABCDEFGHIJKLMNOPQRSTUVWXYZ";case"0-9":return"0123456789";case"-_":return"-_";default:throw new Error(`Unsupported alphabet: ${t}`)}}function ev(...t){let e=t.map(Pde).join("");if(e.length===0)throw new Error("No valid characters provided for random string generation.");let r=e.length;return(n,...i)=>{if(n<=0)throw new Error("Length must be a positive integer.");let s=e,o=r;i.length>0&&(s=i.map(Pde).join(""),o=s.length);let a=Math.floor(256/o)*o,c=new Uint8Array(n*2),l=c.length,u="",d=l,p;for(;u.length<n;)d>=l&&(crypto.getRandomValues(c),d=0),p=c[d++],p<a&&(u+=s[p%o]);return u}}var KR=I(()=>{});var tp,b0=I(()=>{KR();tp=ev("a-z","0-9","A-Z","-_")});function prt(t){return t instanceof Uint8Array||ArrayBuffer.isView(t)&&t.constructor.name==="Uint8Array"&&"BYTES_PER_ELEMENT"in t&&t.BYTES_PER_ELEMENT===1}function qR(t,e=""){if(typeof t!="number"){let r=e&&`"${e}" `;throw new TypeError(`${r}expected number, got ${typeof t}`)}if(!Number.isSafeInteger(t)||t<0){let r=e&&`"${e}" `;throw new RangeError(`${r}expected integer >= 0, got ${t}`)}}function Of(t,e,r=""){let n=prt(t),i=t?.length,s=e!==void 0;if(!n||s&&i!==e){let o=r&&`"${r}" `,a=s?` of length ${e}`:"",c=n?`length=${i}`:`type=${typeof t}`,l=o+"expected Uint8Array"+a+", got "+c;throw n?new RangeError(l):new TypeError(l)}return t}function v0(t){if(typeof t!="function"||typeof t.create!="function")throw new TypeError("Hash must wrapped by utils.createHasher");if(qR(t.outputLen),qR(t.blockLen),t.outputLen<1)throw new Error('"outputLen" must be >= 1');if(t.blockLen<1)throw new Error('"blockLen" must be >= 1')}function tv(t,e=!0){if(t.destroyed)throw new Error("Hash instance has been destroyed");if(e&&t.finished)throw new Error("Hash#digest() has already been called")}function FR(t,e){Of(t,void 0,"digestInto() output");let r=e.outputLen;if(t.length<r)throw new RangeError('"digestInto() output" expected to be of length >='+r)}function rp(...t){for(let e=0;e<t.length;e++)t[e].fill(0)}function zR(t){return new DataView(t.buffer,t.byteOffset,t.byteLength)}function Pl(t,e){return t<<32-e|t>>>e}function Dde(t,e={}){let r=(i,s)=>t(s).update(i).digest(),n=t(void 0);return r.outputLen=n.outputLen,r.blockLen=n.blockLen,r.canXOF=n.canXOF,r.create=i=>t(i),Object.assign(r,e),Object.freeze(r)}var Mde,_0=I(()=>{Mde=t=>({oid:Uint8Array.from([6,9,96,134,72,1,101,3,4,2,t])})});var BR,wH,Lde=I(()=>{_0();BR=class{oHash;iHash;blockLen;outputLen;canXOF=!1;finished=!1;destroyed=!1;constructor(e,r){if(v0(e),Of(r,void 0,"key"),this.iHash=e.create(),typeof this.iHash.update!="function")throw new Error("Expected instance of class which extends utils.Hash");this.blockLen=this.iHash.blockLen,this.outputLen=this.iHash.outputLen;let n=this.blockLen,i=new Uint8Array(n);i.set(r.length>n?e.create().update(r).digest():r);for(let s=0;s<i.length;s++)i[s]^=54;this.iHash.update(i),this.oHash=e.create();for(let s=0;s<i.length;s++)i[s]^=106;this.oHash.update(i),rp(i)}update(e){return tv(this),this.iHash.update(e),this}digestInto(e){tv(this),FR(e,this),this.finished=!0;let r=e.subarray(0,this.outputLen);this.iHash.digestInto(r),this.oHash.update(r),this.oHash.digestInto(r),this.destroy()}digest(){let e=new Uint8Array(this.oHash.outputLen);return this.digestInto(e),e}_cloneInto(e){e||=Object.create(Object.getPrototypeOf(this),{});let{oHash:r,iHash:n,finished:i,destroyed:s,blockLen:o,outputLen:a}=this;return e=e,e.finished=i,e.destroyed=s,e.blockLen=o,e.outputLen=a,e.oHash=r._cloneInto(e.oHash),e.iHash=n._cloneInto(e.iHash),e}clone(){return this._cloneInto()}destroy(){this.destroyed=!0,this.oHash.destroy(),this.iHash.destroy()}},wH=(()=>{let t=((e,r,n)=>new BR(e,r).update(n).digest());return t.create=(e,r)=>new BR(e,r),t})()});function frt(t,e,r){return v0(t),r===void 0&&(r=new Uint8Array(t.outputLen)),wH(t,r,e)}function mrt(t,e,r,n=32){v0(t),qR(n,"length"),Of(e,void 0,"prk");let i=t.outputLen;if(e.length<i)throw new Error('"prk" must be at least HashLen octets');if(n>255*i)throw new Error("Length must be <= 255*HashLen");let s=Math.ceil(n/i);r===void 0?r=jde:Of(r,void 0,"info");let o=new Uint8Array(s*i),a=wH.create(t,e),c=a._cloneInto(),l=new Uint8Array(a.outputLen);for(let u=0;u<s;u++)TH[0]=u+1,c.update(u===0?jde:l).update(r).update(TH).digestInto(l),o.set(l,i*u),a._cloneInto(c);return a.destroy(),c.destroy(),rp(l,TH),o.slice(0,n)}var TH,jde,Ude,Kde=I(()=>{Lde();_0();TH=Uint8Array.of(0),jde=Uint8Array.of();Ude=(t,e,r,n,i)=>mrt(t,frt(t,e,r),n,i)});function qde(t,e,r){return t&e^~t&r}function Fde(t,e,r){return t&e^t&r^e&r}var HR,np,zde=I(()=>{_0();HR=class{blockLen;outputLen;canXOF=!1;padOffset;isLE;buffer;view;finished=!1;length=0;pos=0;destroyed=!1;constructor(e,r,n,i){this.blockLen=e,this.outputLen=r,this.padOffset=n,this.isLE=i,this.buffer=new Uint8Array(e),this.view=zR(this.buffer)}update(e){tv(this),Of(e);let{view:r,buffer:n,blockLen:i}=this,s=e.length;for(let o=0;o<s;){let a=Math.min(i-this.pos,s-o);if(a===i){let c=zR(e);for(;i<=s-o;o+=i)this.process(c,o);continue}n.set(e.subarray(o,o+a),this.pos),this.pos+=a,o+=a,this.pos===i&&(this.process(r,0),this.pos=0)}return this.length+=e.length,this.roundClean(),this}digestInto(e){tv(this),FR(e,this),this.finished=!0;let{buffer:r,view:n,blockLen:i,isLE:s}=this,{pos:o}=this;r[o++]=128,rp(this.buffer.subarray(o)),this.padOffset>i-o&&(this.process(n,0),o=0);for(let d=o;d<i;d++)r[d]=0;n.setBigUint64(i-8,BigInt(this.length*8),s),this.process(n,0);let a=zR(e),c=this.outputLen;if(c%4)throw new Error("_sha2: outputLen must be aligned to 32bit");let l=c/4,u=this.get();if(l>u.length)throw new Error("_sha2: outputLen bigger than state");for(let d=0;d<l;d++)a.setUint32(4*d,u[d],s)}digest(){let{buffer:e,outputLen:r}=this;this.digestInto(e);let n=e.slice(0,r);return this.destroy(),n}_cloneInto(e){e||=new this.constructor,e.set(...this.get());let{blockLen:r,buffer:n,length:i,finished:s,destroyed:o,pos:a}=this;return e.destroyed=o,e.finished=s,e.length=i,e.pos=a,i%r&&e.buffer.set(n),e}clone(){return this._cloneInto()}},np=Uint32Array.from([1779033703,3144134277,1013904242,2773480762,1359893119,2600822924,528734635,1541459225])});var hrt,kf,xH,IH,Bde,Hde=I(()=>{zde();_0();hrt=Uint32Array.from([1116352408,1899447441,3049323471,3921009573,961987163,1508970993,2453635748,2870763221,3624381080,310598401,607225278,1426881987,1925078388,2162078206,2614888103,3248222580,3835390401,4022224774,264347078,604807628,770255983,1249150122,1555081692,1996064986,2554220882,2821834349,2952996808,3210313671,3336571891,3584528711,113926993,338241895,666307205,773529912,1294757372,1396182291,1695183700,1986661051,2177026350,2456956037,2730485921,2820302411,3259730800,3345764771,3516065817,3600352804,4094571909,275423344,430227734,506948616,659060556,883997877,958139571,1322822218,1537002063,1747873779,1955562222,2024104815,2227730452,2361852424,2428436474,2756734187,3204031479,3329325298]),kf=new Uint32Array(64),xH=class extends HR{constructor(e){super(64,e,8,!1)}get(){let{A:e,B:r,C:n,D:i,E:s,F:o,G:a,H:c}=this;return[e,r,n,i,s,o,a,c]}set(e,r,n,i,s,o,a,c){this.A=e|0,this.B=r|0,this.C=n|0,this.D=i|0,this.E=s|0,this.F=o|0,this.G=a|0,this.H=c|0}process(e,r){for(let d=0;d<16;d++,r+=4)kf[d]=e.getUint32(r,!1);for(let d=16;d<64;d++){let p=kf[d-15],f=kf[d-2],m=Pl(p,7)^Pl(p,18)^p>>>3,h=Pl(f,17)^Pl(f,19)^f>>>10;kf[d]=h+kf[d-7]+m+kf[d-16]|0}let{A:n,B:i,C:s,D:o,E:a,F:c,G:l,H:u}=this;for(let d=0;d<64;d++){let p=Pl(a,6)^Pl(a,11)^Pl(a,25),f=u+p+qde(a,c,l)+hrt[d]+kf[d]|0,h=(Pl(n,2)^Pl(n,13)^Pl(n,22))+Fde(n,i,s)|0;u=l,l=c,c=a,a=o+f|0,o=s,s=i,i=n,n=f+h|0}n=n+this.A|0,i=i+this.B|0,s=s+this.C|0,o=o+this.D|0,a=a+this.E|0,c=c+this.F|0,l=l+this.G|0,u=u+this.H|0,this.set(n,i,s,o,a,c,l,u)}roundClean(){rp(kf)}destroy(){this.destroyed=!0,this.set(0,0,0,0,0,0,0,0),rp(this.buffer)}},IH=class extends xH{A=np[0]|0;B=np[1]|0;C=np[2]|0;D=np[3]|0;E=np[4]|0;F=np[5]|0;G=np[6]|0;H=np[7]|0;constructor(){super(32)}},Bde=Dde(()=>new IH,Mde(1))});function fi(...t){let e=t.reduce((i,{length:s})=>i+s,0),r=new Uint8Array(e),n=0;for(let i of t)r.set(i,n),n+=i.length;return r}function AH(t,e,r){if(e<0||e>=WR)throw new RangeError(`value must be >= 0 and <= ${WR-1}. Received ${e}`);t.set([e>>>24,e>>>16,e>>>8,e&255],r)}function OH(t){let e=Math.floor(t/WR),r=t%WR,n=new Uint8Array(8);return AH(n,e,0),AH(n,r,4),n}function $R(t){let e=new Uint8Array(4);return AH(e,t),e}function Bn(t){let e=new Uint8Array(t.length);for(let r=0;r<t.length;r++){let n=t.charCodeAt(r);if(n>127)throw new TypeError("non-ASCII string encountered in encode()");e[r]=n}return e}var qh,_s,WR,Vs=I(()=>{qh=new TextEncoder,_s=new TextDecoder,WR=2**32});function Wde(t){if(Uint8Array.prototype.toBase64)return t.toBase64();let e=32768,r=[];for(let n=0;n<t.length;n+=e)r.push(String.fromCharCode.apply(null,t.subarray(n,n+e)));return btoa(r.join(""))}function $de(t){if(Uint8Array.fromBase64)return Uint8Array.fromBase64(t);let e=atob(t),r=new Uint8Array(e.length);for(let n=0;n<e.length;n++)r[n]=e.charCodeAt(n);return r}var Gde=I(()=>{});var E0={};ui(E0,{decode:()=>_o,encode:()=>bn});function _o(t){if(Uint8Array.fromBase64)return Uint8Array.fromBase64(typeof t=="string"?t:_s.decode(t),{alphabet:"base64url"});let e=t;e instanceof Uint8Array&&(e=_s.decode(e)),e=e.replace(/-/g,"+").replace(/_/g,"/");try{return $de(e)}catch{throw new TypeError("The input to be decoded is not correctly encoded.")}}function bn(t){let e=t;return typeof e=="string"&&(e=qh.encode(e)),Uint8Array.prototype.toBase64?e.toBase64({alphabet:"base64url",omitPadding:!0}):Wde(e).replace(/=/g,"").replace(/\+/g,"-").replace(/\//g,"_")}var Ys=I(()=>{Vs();Gde()});function grt(t){return parseInt(t.name.slice(4),10)}function GR(t,e){if(grt(t.hash)!==e)throw Eo(`SHA-${e}`,"algorithm.hash")}function yrt(t){switch(t){case"ES256":return"P-256";case"ES384":return"P-384";case"ES512":return"P-521";default:throw new Error("unreachable")}}function Vde(t,e){if(e&&!t.usages.includes(e))throw new TypeError(`CryptoKey does not support this operation, its usages must include ${e}.`)}function Yde(t,e,r){switch(e){case"HS256":case"HS384":case"HS512":{if(!Hu(t.algorithm,"HMAC"))throw Eo("HMAC");GR(t.algorithm,parseInt(e.slice(2),10));break}case"RS256":case"RS384":case"RS512":{if(!Hu(t.algorithm,"RSASSA-PKCS1-v1_5"))throw Eo("RSASSA-PKCS1-v1_5");GR(t.algorithm,parseInt(e.slice(2),10));break}case"PS256":case"PS384":case"PS512":{if(!Hu(t.algorithm,"RSA-PSS"))throw Eo("RSA-PSS");GR(t.algorithm,parseInt(e.slice(2),10));break}case"Ed25519":case"EdDSA":{if(!Hu(t.algorithm,"Ed25519"))throw Eo("Ed25519");break}case"ML-DSA-44":case"ML-DSA-65":case"ML-DSA-87":{if(!Hu(t.algorithm,e))throw Eo(e);break}case"ES256":case"ES384":case"ES512":{if(!Hu(t.algorithm,"ECDSA"))throw Eo("ECDSA");let n=yrt(e);if(t.algorithm.namedCurve!==n)throw Eo(n,"algorithm.namedCurve");break}default:throw new TypeError("CryptoKey does not support this operation")}Vde(t,r)}function $a(t,e,r){switch(e){case"A128GCM":case"A192GCM":case"A256GCM":{if(!Hu(t.algorithm,"AES-GCM"))throw Eo("AES-GCM");let n=parseInt(e.slice(1,4),10);if(t.algorithm.length!==n)throw Eo(n,"algorithm.length");break}case"A128KW":case"A192KW":case"A256KW":{if(!Hu(t.algorithm,"AES-KW"))throw Eo("AES-KW");let n=parseInt(e.slice(1,4),10);if(t.algorithm.length!==n)throw Eo(n,"algorithm.length");break}case"ECDH":{switch(t.algorithm.name){case"ECDH":case"X25519":break;default:throw Eo("ECDH or X25519")}break}case"PBES2-HS256+A128KW":case"PBES2-HS384+A192KW":case"PBES2-HS512+A256KW":if(!Hu(t.algorithm,"PBKDF2"))throw Eo("PBKDF2");break;case"RSA-OAEP":case"RSA-OAEP-256":case"RSA-OAEP-384":case"RSA-OAEP-512":{if(!Hu(t.algorithm,"RSA-OAEP"))throw Eo("RSA-OAEP");GR(t.algorithm,parseInt(e.slice(9),10)||1);break}default:throw new TypeError("CryptoKey does not support this operation")}Vde(t,r)}var Eo,Hu,Fh=I(()=>{Eo=(t,e="algorithm.name")=>new TypeError(`CryptoKey does not support this operation, its ${e} must be ${t}`),Hu=(t,e)=>t.name===e});function Jde(t,e,...r){if(r=r.filter(Boolean),r.length>2){let n=r.pop();t+=`one of type ${r.join(", ")}, or ${n}.`}else r.length===2?t+=`one of type ${r[0]} or ${r[1]}.`:t+=`of type ${r[0]}.`;return e==null?t+=` Received ${e}`:typeof e=="function"&&e.name?t+=` Received function ${e.name}`:typeof e=="object"&&e!=null&&e.constructor?.name&&(t+=` Received an instance of ${e.constructor.name}`),t}var Wu,kH,rv=I(()=>{Wu=(t,...e)=>Jde("Key must be ",t,...e),kH=(t,e,...r)=>Jde(`Key for the ${t} algorithm must be `,e,...r)});var Si,Es,zh,Bh,Pt,nv,Me,zr,Js,VR,S0,iv,YR,JR,ZR,cn=I(()=>{Si=class extends Error{static code="ERR_JOSE_GENERIC";code="ERR_JOSE_GENERIC";constructor(e,r){super(e,r),this.name=this.constructor.name,Error.captureStackTrace?.(this,this.constructor)}},Es=class extends Si{static code="ERR_JWT_CLAIM_VALIDATION_FAILED";code="ERR_JWT_CLAIM_VALIDATION_FAILED";claim;reason;payload;constructor(e,r,n="unspecified",i="unspecified"){super(e,{cause:{claim:n,reason:i,payload:r}}),this.claim=n,this.reason=i,this.payload=r}},zh=class extends Si{static code="ERR_JWT_EXPIRED";code="ERR_JWT_EXPIRED";claim;reason;payload;constructor(e,r,n="unspecified",i="unspecified"){super(e,{cause:{claim:n,reason:i,payload:r}}),this.claim=n,this.reason=i,this.payload=r}},Bh=class extends Si{static code="ERR_JOSE_ALG_NOT_ALLOWED";code="ERR_JOSE_ALG_NOT_ALLOWED"},Pt=class extends Si{static code="ERR_JOSE_NOT_SUPPORTED";code="ERR_JOSE_NOT_SUPPORTED"},nv=class extends Si{static code="ERR_JWE_DECRYPTION_FAILED";code="ERR_JWE_DECRYPTION_FAILED";constructor(e="decryption operation failed",r){super(e,r)}},Me=class extends Si{static code="ERR_JWE_INVALID";code="ERR_JWE_INVALID"},zr=class extends Si{static code="ERR_JWS_INVALID";code="ERR_JWS_INVALID"},Js=class extends Si{static code="ERR_JWT_INVALID";code="ERR_JWT_INVALID"},VR=class extends Si{static code="ERR_JWK_INVALID";code="ERR_JWK_INVALID"},S0=class extends Si{static code="ERR_JWKS_INVALID";code="ERR_JWKS_INVALID"},iv=class extends Si{static code="ERR_JWKS_NO_MATCHING_KEY";code="ERR_JWKS_NO_MATCHING_KEY";constructor(e="no applicable key found in the JSON Web Key Set",r){super(e,r)}},YR=class extends Si{[Symbol.asyncIterator];static code="ERR_JWKS_MULTIPLE_MATCHING_KEYS";code="ERR_JWKS_MULTIPLE_MATCHING_KEYS";constructor(e="multiple matching keys found in the JSON Web Key Set",r){super(e,r)}},JR=class extends Si{static code="ERR_JWKS_TIMEOUT";code="ERR_JWKS_TIMEOUT";constructor(e="request timed out",r){super(e,r)}},ZR=class extends Si{static code="ERR_JWS_SIGNATURE_VERIFICATION_FAILED";code="ERR_JWS_SIGNATURE_VERIFICATION_FAILED";constructor(e="signature verification failed",r){super(e,r)}}});function sv(t){if(!ip(t))throw new Error("CryptoKey instance expected")}var ip,w0,T0,Hh=I(()=>{ip=t=>{if(t?.[Symbol.toStringTag]==="CryptoKey")return!0;try{return t instanceof CryptoKey}catch{return!1}},w0=t=>t?.[Symbol.toStringTag]==="KeyObject",T0=t=>ip(t)||w0(t)});function QR(t){switch(t){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 Pt(`Unsupported JWE Algorithm: ${t}`)}}function XR(t,e){let r=t.byteLength<<3;if(r!==e)throw new Me(`Invalid Content Encryption Key length. Expected ${e} bits, got ${r} bits`)}function Zde(t){switch(t){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 Pt(`Unsupported JWE Algorithm: ${t}`)}}function Xde(t,e){if(e.length<<3!==Zde(t))throw new Me("Invalid Initialization Vector length")}async function Qde(t,e,r){if(!(e instanceof Uint8Array))throw new TypeError(Wu(e,"Uint8Array"));let n=parseInt(t.slice(1,4),10),i=await crypto.subtle.importKey("raw",e.subarray(n>>3),"AES-CBC",!1,[r]),s=await crypto.subtle.importKey("raw",e.subarray(0,n>>3),{hash:`SHA-${n<<1}`,name:"HMAC"},!1,["sign"]);return{encKey:i,macKey:s,keySize:n}}async function epe(t,e,r){return new Uint8Array((await crypto.subtle.sign("HMAC",t,e)).slice(0,r>>3))}async function vrt(t,e,r,n,i){let{encKey:s,macKey:o,keySize:a}=await Qde(t,r,"encrypt"),c=new Uint8Array(await crypto.subtle.encrypt({iv:n,name:"AES-CBC"},s,e)),l=fi(i,n,c,OH(i.length<<3)),u=await epe(o,l,a);return{ciphertext:c,tag:u,iv:n}}async function _rt(t,e){if(!(t instanceof Uint8Array))throw new TypeError("First argument must be a buffer");if(!(e instanceof Uint8Array))throw new TypeError("Second argument must be a buffer");let r={name:"HMAC",hash:"SHA-256"},n=await crypto.subtle.generateKey(r,!1,["sign"]),i=new Uint8Array(await crypto.subtle.sign(r,n,t)),s=new Uint8Array(await crypto.subtle.sign(r,n,e)),o=0,a=-1;for(;++a<32;)o|=i[a]^s[a];return o===0}async function Ert(t,e,r,n,i,s){let{encKey:o,macKey:a,keySize:c}=await Qde(t,e,"decrypt"),l=fi(s,n,r,OH(s.length<<3)),u=await epe(a,l,c),d;try{d=await _rt(i,u)}catch{}if(!d)throw new nv;let p;try{p=new Uint8Array(await crypto.subtle.decrypt({iv:n,name:"AES-CBC"},o,r))}catch{}if(!p)throw new nv;return p}async function Srt(t,e,r,n,i){let s;r instanceof Uint8Array?s=await crypto.subtle.importKey("raw",r,"AES-GCM",!1,["encrypt"]):($a(r,t,"encrypt"),s=r);let o=new Uint8Array(await crypto.subtle.encrypt({additionalData:i,iv:n,name:"AES-GCM",tagLength:128},s,e)),a=o.slice(-16);return{ciphertext:o.slice(0,-16),tag:a,iv:n}}async function wrt(t,e,r,n,i,s){let o;e instanceof Uint8Array?o=await crypto.subtle.importKey("raw",e,"AES-GCM",!1,["decrypt"]):($a(e,t,"decrypt"),o=e);try{return new Uint8Array(await crypto.subtle.decrypt({additionalData:s,iv:n,name:"AES-GCM",tagLength:128},o,fi(r,i)))}catch{throw new nv}}async function eC(t,e,r,n,i){if(!ip(r)&&!(r instanceof Uint8Array))throw new TypeError(Wu(r,"CryptoKey","KeyObject","Uint8Array","JSON Web Key"));switch(n?Xde(t,n):n=brt(t),t){case"A128CBC-HS256":case"A192CBC-HS384":case"A256CBC-HS512":return r instanceof Uint8Array&&XR(r,parseInt(t.slice(-3),10)),vrt(t,e,r,n,i);case"A128GCM":case"A192GCM":case"A256GCM":return r instanceof Uint8Array&&XR(r,parseInt(t.slice(1,4),10)),Srt(t,e,r,n,i);default:throw new Pt(tpe)}}async function tC(t,e,r,n,i,s){if(!ip(e)&&!(e instanceof Uint8Array))throw new TypeError(Wu(e,"CryptoKey","KeyObject","Uint8Array","JSON Web Key"));if(!n)throw new Me("JWE Initialization Vector missing");if(!i)throw new Me("JWE Authentication Tag missing");switch(Xde(t,n),t){case"A128CBC-HS256":case"A192CBC-HS384":case"A256CBC-HS512":return e instanceof Uint8Array&&XR(e,parseInt(t.slice(-3),10)),Ert(t,e,r,n,i,s);case"A128GCM":case"A192GCM":case"A256GCM":return e instanceof Uint8Array&&XR(e,parseInt(t.slice(1,4),10)),wrt(t,e,r,n,i,s);default:throw new Pt(tpe)}}var Rf,brt,tpe,ov=I(()=>{Vs();Fh();rv();cn();Hh();Rf=t=>crypto.getRandomValues(new Uint8Array(QR(t)>>3));brt=t=>crypto.getRandomValues(new Uint8Array(Zde(t)>>3));tpe="Unsupported JWE Content Encryption Algorithm"});function So(t,e){if(t)throw new TypeError(`${e} can only be called once`)}function wo(t,e,r){try{return _o(t)}catch{throw new r(`Failed to base64url decode the ${e}`)}}async function rC(t,e){let r=`SHA-${t.slice(-3)}`;return new Uint8Array(await crypto.subtle.digest(r,e))}var rpe,sp=I(()=>{Ys();rpe=Symbol()});function vn(t){if(!Trt(t)||Object.prototype.toString.call(t)!=="[object Object]")return!1;if(Object.getPrototypeOf(t)===null)return!0;let e=t;for(;Object.getPrototypeOf(e)!==null;)e=Object.getPrototypeOf(e);return Object.getPrototypeOf(t)===e}function Cf(...t){let e=t.filter(Boolean);if(e.length===0||e.length===1)return!0;let r;for(let n of e){let i=Object.keys(n);if(!r||r.size===0){r=new Set(i);continue}for(let s of i){if(r.has(s))return!1;r.add(s)}}return!0}var Trt,Wh,npe,ipe,spe,Ss=I(()=>{Trt=t=>typeof t=="object"&&t!==null;Wh=t=>vn(t)&&typeof t.kty=="string",npe=t=>t.kty!=="oct"&&(t.kty==="AKP"&&typeof t.priv=="string"||typeof t.d=="string"),ipe=t=>t.kty!=="oct"&&t.d===void 0&&t.priv===void 0,spe=t=>t.kty==="oct"&&typeof t.k=="string"});function ope(t,e){if(t.algorithm.length!==parseInt(e.slice(1,4),10))throw new TypeError(`Invalid key size for alg: ${e}`)}function ape(t,e,r){return t instanceof Uint8Array?crypto.subtle.importKey("raw",t,"AES-KW",!0,[r]):($a(t,e,r),t)}async function x0(t,e,r){let n=await ape(e,t,"wrapKey");ope(n,t);let i=await crypto.subtle.importKey("raw",r,{hash:"SHA-256",name:"HMAC"},!0,["sign"]);return new Uint8Array(await crypto.subtle.wrapKey("raw",i,n,"AES-KW"))}async function I0(t,e,r){let n=await ape(e,t,"unwrapKey");ope(n,t);let i=await crypto.subtle.unwrapKey("raw",r,n,"AES-KW",{hash:"SHA-256",name:"HMAC"},!0,["sign"]);return new Uint8Array(await crypto.subtle.exportKey("raw",i))}var RH=I(()=>{Fh()});function CH(t){return fi($R(t.length),t)}async function Irt(t,e,r){let n=e>>3,i=32,s=Math.ceil(n/i),o=new Uint8Array(s*i);for(let a=1;a<=s;a++){let c=new Uint8Array(4+t.length+r.length);c.set($R(a),0),c.set(t,4),c.set(r,4+t.length);let l=await rC("sha256",c);o.set(l,(a-1)*i)}return o.slice(0,n)}async function NH(t,e,r,n,i=new Uint8Array,s=new Uint8Array){$a(t,"ECDH"),$a(e,"ECDH","deriveBits");let o=CH(Bn(r)),a=CH(i),c=CH(s),l=$R(n),u=new Uint8Array,d=fi(o,a,c,l,u),p=new Uint8Array(await crypto.subtle.deriveBits({name:t.algorithm.name,public:t},e,Art(t)));return Irt(p,n,d)}function Art(t){return t.algorithm.name==="X25519"?256:Math.ceil(parseInt(t.algorithm.namedCurve.slice(-3),10)/8)<<3}function PH(t){switch(t.algorithm.namedCurve){case"P-256":case"P-384":case"P-521":return!0;default:return t.algorithm.name==="X25519"}}var lpe=I(()=>{Vs();Fh();sp()});function krt(t,e){return t instanceof Uint8Array?crypto.subtle.importKey("raw",t,"PBKDF2",!1,["deriveBits"]):($a(t,e,"deriveBits"),t)}async function upe(t,e,r,n){if(!(t instanceof Uint8Array)||t.length<8)throw new Me("PBES2 Salt Input must be 8 or more octets");if(!Number.isSafeInteger(r)||Math.sign(r)!==1)throw new Me("PBES2 Count Input must be a positive integer");let i=Rrt(e,t),s=parseInt(e.slice(13,16),10),o={hash:`SHA-${e.slice(8,11)}`,iterations:r,name:"PBKDF2",salt:i},a=await krt(n,e);return new Uint8Array(await crypto.subtle.deriveBits(o,a,s))}async function dpe(t,e,r,n=2048,i=crypto.getRandomValues(new Uint8Array(16))){let s=await upe(i,t,n,e);return{encryptedKey:await x0(t.slice(-6),s,r),p2c:n,p2s:bn(i)}}async function ppe(t,e,r,n,i){let s=await upe(i,t,n,e);return I0(t.slice(-6),s,r)}var Rrt,fpe=I(()=>{Ys();RH();Fh();Vs();cn();Rrt=(t,e)=>fi(Bn(t),Uint8Array.of(0),e)});function A0(t,e){if(t.startsWith("RS")||t.startsWith("PS")){let{modulusLength:r}=e.algorithm;if(typeof r!="number"||r<2048)throw new TypeError(`${t} requires key modulusLength to be 2048 bits or larger`)}}function mpe(t,e){let r=`SHA-${t.slice(-3)}`;switch(t){case"HS256":case"HS384":case"HS512":return{hash:r,name:"HMAC"};case"PS256":case"PS384":case"PS512":return{hash:r,name:"RSA-PSS",saltLength:parseInt(t.slice(-3),10)>>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:e.namedCurve};case"Ed25519":case"EdDSA":return{name:"Ed25519"};case"ML-DSA-44":case"ML-DSA-65":case"ML-DSA-87":return{name:t};default:throw new Pt(`alg ${t} is not supported either by JOSE or your javascript runtime`)}}async function hpe(t,e,r){if(e instanceof Uint8Array){if(!t.startsWith("HS"))throw new TypeError(Wu(e,"CryptoKey","KeyObject","JSON Web Key"));return crypto.subtle.importKey("raw",e,{hash:`SHA-${t.slice(-3)}`,name:"HMAC"},!1,[r])}return Yde(e,t,r),e}async function gpe(t,e,r){let n=await hpe(t,e,"sign");A0(t,n);let i=await crypto.subtle.sign(mpe(t,n.algorithm),n,r);return new Uint8Array(i)}async function ype(t,e,r,n){let i=await hpe(t,e,"verify");A0(t,i);let s=mpe(t,i.algorithm);try{return await crypto.subtle.verify(s,i,r,n)}catch{return!1}}var nC=I(()=>{cn();Fh();rv()});async function vpe(t,e,r){return $a(e,t,"encrypt"),A0(t,e),new Uint8Array(await crypto.subtle.encrypt(bpe(t),e,r))}async function _pe(t,e,r){return $a(e,t,"decrypt"),A0(t,e),new Uint8Array(await crypto.subtle.decrypt(bpe(t),e,r))}var bpe,Epe=I(()=>{Fh();nC();cn();bpe=t=>{switch(t){case"RSA-OAEP":case"RSA-OAEP-256":case"RSA-OAEP-384":case"RSA-OAEP-512":return"RSA-OAEP";default:throw new Pt(`alg ${t} is not supported either by JOSE or your javascript runtime`)}}});function Prt(t){let e,r;switch(t.kty){case"AKP":{switch(t.alg){case"ML-DSA-44":case"ML-DSA-65":case"ML-DSA-87":e={name:t.alg},r=t.priv?["sign"]:["verify"];break;default:throw new Pt(iC)}break}case"RSA":{switch(t.alg){case"PS256":case"PS384":case"PS512":e={name:"RSA-PSS",hash:`SHA-${t.alg.slice(-3)}`},r=t.d?["sign"]:["verify"];break;case"RS256":case"RS384":case"RS512":e={name:"RSASSA-PKCS1-v1_5",hash:`SHA-${t.alg.slice(-3)}`},r=t.d?["sign"]:["verify"];break;case"RSA-OAEP":case"RSA-OAEP-256":case"RSA-OAEP-384":case"RSA-OAEP-512":e={name:"RSA-OAEP",hash:`SHA-${parseInt(t.alg.slice(-3),10)||1}`},r=t.d?["decrypt","unwrapKey"]:["encrypt","wrapKey"];break;default:throw new Pt(iC)}break}case"EC":{switch(t.alg){case"ES256":case"ES384":case"ES512":e={name:"ECDSA",namedCurve:{ES256:"P-256",ES384:"P-384",ES512:"P-521"}[t.alg]},r=t.d?["sign"]:["verify"];break;case"ECDH-ES":case"ECDH-ES+A128KW":case"ECDH-ES+A192KW":case"ECDH-ES+A256KW":e={name:"ECDH",namedCurve:t.crv},r=t.d?["deriveBits"]:[];break;default:throw new Pt(iC)}break}case"OKP":{switch(t.alg){case"Ed25519":case"EdDSA":e={name:"Ed25519"},r=t.d?["sign"]:["verify"];break;case"ECDH-ES":case"ECDH-ES+A128KW":case"ECDH-ES+A192KW":case"ECDH-ES+A256KW":e={name:t.crv},r=t.d?["deriveBits"]:[];break;default:throw new Pt(iC)}break}default:throw new Pt('Invalid or unsupported JWK "kty" (Key Type) Parameter value')}return{algorithm:e,keyUsages:r}}async function av(t){if(!t.alg)throw new TypeError('"alg" argument is required when "jwk.alg" is not present');let{algorithm:e,keyUsages:r}=Prt(t),n={...t};return n.kty!=="AKP"&&delete n.alg,delete n.use,crypto.subtle.importKey("jwk",n,e,t.ext??!(t.d||t.priv),t.key_ops??r)}var iC,DH=I(()=>{cn();iC='Invalid or unsupported JWK "alg" (Algorithm) Parameter value'});async function $u(t,e){if(t instanceof Uint8Array||ip(t))return t;if(w0(t)){if(t.type==="secret")return t.export();if("toCryptoKey"in t&&typeof t.toCryptoKey=="function")try{return Drt(t,e)}catch(n){if(n instanceof TypeError)throw n}let r=t.export({format:"jwk"});return Spe(t,r,e)}if(Wh(t))return t.k?_o(t.k):Spe(t,t,e,!0);throw new Error("unreachable")}var cv,lv,Spe,Drt,uv=I(()=>{Ss();Ys();DH();Hh();cv="given KeyObject instance cannot be used for this algorithm",Spe=async(t,e,r,n=!1)=>{lv||=new WeakMap;let i=lv.get(t);if(i?.[r])return i[r];let s=await av({...e,alg:r});return n&&Object.freeze(t),i?i[r]=s:lv.set(t,{[r]:s}),s},Drt=(t,e)=>{lv||=new WeakMap;let r=lv.get(t);if(r?.[e])return r[e];let n=t.type==="public",i=!!n,s;if(t.asymmetricKeyType==="x25519"){switch(e){case"ECDH-ES":case"ECDH-ES+A128KW":case"ECDH-ES+A192KW":case"ECDH-ES+A256KW":break;default:throw new TypeError(cv)}s=t.toCryptoKey(t.asymmetricKeyType,i,n?[]:["deriveBits"])}if(t.asymmetricKeyType==="ed25519"){if(e!=="EdDSA"&&e!=="Ed25519")throw new TypeError(cv);s=t.toCryptoKey(t.asymmetricKeyType,i,[n?"verify":"sign"])}switch(t.asymmetricKeyType){case"ml-dsa-44":case"ml-dsa-65":case"ml-dsa-87":{if(e!==t.asymmetricKeyType.toUpperCase())throw new TypeError(cv);s=t.toCryptoKey(t.asymmetricKeyType,i,[n?"verify":"sign"])}}if(t.asymmetricKeyType==="rsa"){let o;switch(e){case"RSA-OAEP":o="SHA-1";break;case"RS256":case"PS256":case"RSA-OAEP-256":o="SHA-256";break;case"RS384":case"PS384":case"RSA-OAEP-384":o="SHA-384";break;case"RS512":case"PS512":case"RSA-OAEP-512":o="SHA-512";break;default:throw new TypeError(cv)}if(e.startsWith("RSA-OAEP"))return t.toCryptoKey({name:"RSA-OAEP",hash:o},i,n?["encrypt"]:["decrypt"]);s=t.toCryptoKey({name:e.startsWith("PS")?"RSA-PSS":"RSASSA-PKCS1-v1_5",hash:o},i,[n?"verify":"sign"])}if(t.asymmetricKeyType==="ec"){let a=new Map([["prime256v1","P-256"],["secp384r1","P-384"],["secp521r1","P-521"]]).get(t.asymmetricKeyDetails?.namedCurve);if(!a)throw new TypeError(cv);let c={ES256:"P-256",ES384:"P-384",ES512:"P-521"};c[e]&&a===c[e]&&(s=t.toCryptoKey({name:"ECDSA",namedCurve:a},i,[n?"verify":"sign"])),e.startsWith("ECDH-ES")&&(s=t.toCryptoKey({name:"ECDH",namedCurve:a},i,n?[]:["deriveBits"]))}if(!s)throw new TypeError(cv);return r?r[e]=s:lv.set(t,{[e]:s}),s}});async function Ga(t,e,r){if(!vn(t))throw new TypeError("JWK must be an object");let n;switch(e??=t.alg,n??=r?.extractable??t.ext,t.kty){case"oct":if(typeof t.k!="string"||!t.k)throw new TypeError('missing "k" (Key Value) Parameter value');return _o(t.k);case"RSA":if("oth"in t&&t.oth!==void 0)throw new Pt('RSA JWK "oth" (Other Primes Info) Parameter value is not supported');return av({...t,alg:e,ext:n});case"AKP":{if(typeof t.alg!="string"||!t.alg)throw new TypeError('missing "alg" (Algorithm) Parameter value');if(e!==void 0&&e!==t.alg)throw new TypeError("JWK alg and alg option value mismatch");return av({...t,ext:n})}case"EC":case"OKP":return av({...t,alg:e,ext:n});default:throw new Pt('Unsupported "kty" (Key Type) Parameter value')}}var sC=I(()=>{Ys();DH();cn();Ss()});async function wpe(t){if(w0(t))if(t.type==="secret")t=t.export();else return t.export({format:"jwk"});if(t instanceof Uint8Array)return{kty:"oct",k:bn(t)};if(!ip(t))throw new TypeError(Wu(t,"CryptoKey","KeyObject","Uint8Array"));if(!t.extractable)throw new TypeError("non-extractable CryptoKey cannot be exported as a JWK");let{ext:e,key_ops:r,alg:n,use:i,...s}=await crypto.subtle.exportKey("jwk",t);return s.kty==="AKP"&&(s.alg=n),s}var Tpe=I(()=>{rv();Ys();Hh()});async function oC(t){return wpe(t)}var MH=I(()=>{Tpe()});async function xpe(t,e,r,n){let i=t.slice(0,7),s=await eC(i,r,e,n,new Uint8Array);return{encryptedKey:s.ciphertext,iv:bn(s.iv),tag:bn(s.tag)}}async function Ipe(t,e,r,n,i){let s=t.slice(0,7);return tC(s,e,r,n,i,new Uint8Array)}var Ape=I(()=>{ov();Ys()});function O0(t){if(t===void 0)throw new Me("JWE Encrypted Key missing")}async function kpe(t,e,r,n,i){switch(t){case"dir":{if(r!==void 0)throw new Me("Encountered unexpected JWE Encrypted Key");return e}case"ECDH-ES":if(r!==void 0)throw new Me("Encountered unexpected JWE Encrypted Key");case"ECDH-ES+A128KW":case"ECDH-ES+A192KW":case"ECDH-ES+A256KW":{if(!vn(n.epk))throw new Me('JOSE Header "epk" (Ephemeral Public Key) missing or invalid');if(sv(e),!PH(e))throw new Pt("ECDH with the provided key is not allowed or not supported by your javascript runtime");let s=await Ga(n.epk,t);sv(s);let o,a;if(n.apu!==void 0){if(typeof n.apu!="string")throw new Me('JOSE Header "apu" (Agreement PartyUInfo) invalid');o=wo(n.apu,"apu",Me)}if(n.apv!==void 0){if(typeof n.apv!="string")throw new Me('JOSE Header "apv" (Agreement PartyVInfo) invalid');a=wo(n.apv,"apv",Me)}let c=await NH(s,e,t==="ECDH-ES"?n.enc:t,t==="ECDH-ES"?QR(n.enc):parseInt(t.slice(-5,-2),10),o,a);return t==="ECDH-ES"?c:(O0(r),I0(t.slice(-6),c,r))}case"RSA-OAEP":case"RSA-OAEP-256":case"RSA-OAEP-384":case"RSA-OAEP-512":return O0(r),sv(e),_pe(t,e,r);case"PBES2-HS256+A128KW":case"PBES2-HS384+A192KW":case"PBES2-HS512+A256KW":{if(O0(r),typeof n.p2c!="number")throw new Me('JOSE Header "p2c" (PBES2 Count) missing or invalid');let s=i?.maxPBES2Count||1e4;if(n.p2c>s)throw new Me('JOSE Header "p2c" (PBES2 Count) out is of acceptable bounds');if(typeof n.p2s!="string")throw new Me('JOSE Header "p2s" (PBES2 Salt) missing or invalid');let o;return o=wo(n.p2s,"p2s",Me),ppe(t,e,r,n.p2c,o)}case"A128KW":case"A192KW":case"A256KW":return O0(r),I0(t,e,r);case"A128GCMKW":case"A192GCMKW":case"A256GCMKW":{if(O0(r),typeof n.iv!="string")throw new Me('JOSE Header "iv" (Initialization Vector) missing or invalid');if(typeof n.tag!="string")throw new Me('JOSE Header "tag" (Authentication Tag) missing or invalid');let s;s=wo(n.iv,"iv",Me);let o;return o=wo(n.tag,"tag",Me),Ipe(t,e,r,s,o)}default:throw new Pt(Ope)}}async function Rpe(t,e,r,n,i={}){let s,o,a;switch(t){case"dir":{a=r;break}case"ECDH-ES":case"ECDH-ES+A128KW":case"ECDH-ES+A192KW":case"ECDH-ES+A256KW":{if(sv(r),!PH(r))throw new Pt("ECDH with the provided key is not allowed or not supported by your javascript runtime");let{apu:c,apv:l}=i,u;i.epk?u=await $u(i.epk,t):u=(await crypto.subtle.generateKey(r.algorithm,!0,["deriveBits"])).privateKey;let{x:d,y:p,crv:f,kty:m}=await oC(u),h=await NH(r,u,t==="ECDH-ES"?e:t,t==="ECDH-ES"?QR(e):parseInt(t.slice(-5,-2),10),c,l);if(o={epk:{x:d,crv:f,kty:m}},m==="EC"&&(o.epk.y=p),c&&(o.apu=bn(c)),l&&(o.apv=bn(l)),t==="ECDH-ES"){a=h;break}a=n||Rf(e);let y=t.slice(-6);s=await x0(y,h,a);break}case"RSA-OAEP":case"RSA-OAEP-256":case"RSA-OAEP-384":case"RSA-OAEP-512":{a=n||Rf(e),sv(r),s=await vpe(t,r,a);break}case"PBES2-HS256+A128KW":case"PBES2-HS384+A192KW":case"PBES2-HS512+A256KW":{a=n||Rf(e);let{p2c:c,p2s:l}=i;({encryptedKey:s,...o}=await dpe(t,r,a,c,l));break}case"A128KW":case"A192KW":case"A256KW":{a=n||Rf(e),s=await x0(t,r,a);break}case"A128GCMKW":case"A192GCMKW":case"A256GCMKW":{a=n||Rf(e);let{iv:c}=i;({encryptedKey:s,...o}=await xpe(t,r,a,c));break}default:throw new Pt(Ope)}return{cek:a,encryptedKey:s,parameters:o}}var Ope,LH=I(()=>{RH();lpe();fpe();Epe();Ys();uv();cn();sp();ov();sC();MH();Ss();Ape();Hh();Ope='Invalid or unsupported "alg" (JWE Algorithm) header value'});function Nf(t,e,r,n,i){if(i.crit!==void 0&&n?.crit===void 0)throw new t('"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(o=>typeof o!="string"||o.length===0))throw new t('"crit" (Critical) Header Parameter MUST be an array of non-empty strings when present');let s;r!==void 0?s=new Map([...Object.entries(r),...e.entries()]):s=e;for(let o of n.crit){if(!s.has(o))throw new Pt(`Extension Header Parameter "${o}" is not recognized`);if(i[o]===void 0)throw new t(`Extension Header Parameter "${o}" is missing`);if(s.get(o)&&n[o]===void 0)throw new t(`Extension Header Parameter "${o}" MUST be integrity protected`)}return new Set(n.crit)}var k0=I(()=>{cn()});function R0(t,e){if(e!==void 0&&(!Array.isArray(e)||e.some(r=>typeof r!="string")))throw new TypeError(`"${t}" option must be an array of strings`);if(e)return new Set(e)}var jH=I(()=>{});function Pf(t,e,r){switch(t.substring(0,2)){case"A1":case"A2":case"di":case"HS":case"PB":Mrt(t,e,r);break;default:Lrt(t,e,r)}}var dv,UH,Mrt,Lrt,C0=I(()=>{rv();Hh();Ss();dv=t=>t?.[Symbol.toStringTag],UH=(t,e,r)=>{if(e.use!==void 0){let n;switch(r){case"sign":case"verify":n="sig";break;case"encrypt":case"decrypt":n="enc";break}if(e.use!==n)throw new TypeError(`Invalid key for this operation, its "use" must be "${n}" when present`)}if(e.alg!==void 0&&e.alg!==t)throw new TypeError(`Invalid key for this operation, its "alg" must be "${t}" when present`);if(Array.isArray(e.key_ops)){let n;switch(!0){case(r==="sign"||r==="verify"):case t==="dir":case t.includes("CBC-HS"):n=r;break;case t.startsWith("PBES2"):n="deriveBits";break;case/^A\d{3}(?:GCM)?(?:KW)?$/.test(t):!t.includes("GCM")&&t.endsWith("KW")?n=r==="encrypt"?"wrapKey":"unwrapKey":n=r;break;case(r==="encrypt"&&t.startsWith("RSA")):n="wrapKey";break;case r==="decrypt":n=t.startsWith("RSA")?"unwrapKey":"deriveBits";break}if(n&&e.key_ops?.includes?.(n)===!1)throw new TypeError(`Invalid key for this operation, its "key_ops" must include "${n}" when present`)}return!0},Mrt=(t,e,r)=>{if(!(e instanceof Uint8Array)){if(Wh(e)){if(spe(e)&&UH(t,e,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(!T0(e))throw new TypeError(kH(t,e,"CryptoKey","KeyObject","JSON Web Key","Uint8Array"));if(e.type!=="secret")throw new TypeError(`${dv(e)} instances for symmetric algorithms must be of type "secret"`)}},Lrt=(t,e,r)=>{if(Wh(e))switch(r){case"decrypt":case"sign":if(npe(e)&&UH(t,e,r))return;throw new TypeError("JSON Web Key for this operation must be a private JWK");case"encrypt":case"verify":if(ipe(e)&&UH(t,e,r))return;throw new TypeError("JSON Web Key for this operation must be a public JWK")}if(!T0(e))throw new TypeError(kH(t,e,"CryptoKey","KeyObject","JSON Web Key"));if(e.type==="secret")throw new TypeError(`${dv(e)} instances for asymmetric algorithms must not be of type "secret"`);if(e.type==="public")switch(r){case"sign":throw new TypeError(`${dv(e)} instances for asymmetric algorithm signing must be of type "private"`);case"decrypt":throw new TypeError(`${dv(e)} instances for asymmetric algorithm decryption must be of type "private"`)}if(e.type==="private")switch(r){case"verify":throw new TypeError(`${dv(e)} instances for asymmetric algorithm verifying must be of type "public"`);case"encrypt":throw new TypeError(`${dv(e)} instances for asymmetric algorithm encryption must be of type "public"`)}}});function Cpe(t){if(typeof globalThis[t]>"u")throw new Pt(`JWE "zip" (Compression Algorithm) Header Parameter requires the ${t} API.`)}async function Npe(t){Cpe("CompressionStream");let e=new CompressionStream("deflate-raw"),r=e.writable.getWriter();r.write(t).catch(()=>{}),r.close().catch(()=>{});let n=[],i=e.readable.getReader();for(;;){let{value:s,done:o}=await i.read();if(o)break;n.push(s)}return fi(...n)}async function Ppe(t,e){Cpe("DecompressionStream");let r=new DecompressionStream("deflate-raw"),n=r.writable.getWriter();n.write(t).catch(()=>{}),n.close().catch(()=>{});let i=[],s=0,o=r.readable.getReader();for(;;){let{value:a,done:c}=await o.read();if(c)break;if(i.push(a),s+=a.byteLength,e!==1/0&&s>e)throw new Me("Decompressed plaintext exceeded the configured limit")}return fi(...i)}var KH=I(()=>{cn();Vs()});async function Dpe(t,e,r){if(!vn(t))throw new Me("Flattened JWE must be an object");if(t.protected===void 0&&t.header===void 0&&t.unprotected===void 0)throw new Me("JOSE Header missing");if(t.iv!==void 0&&typeof t.iv!="string")throw new Me("JWE Initialization Vector incorrect type");if(typeof t.ciphertext!="string")throw new Me("JWE Ciphertext missing or incorrect type");if(t.tag!==void 0&&typeof t.tag!="string")throw new Me("JWE Authentication Tag incorrect type");if(t.protected!==void 0&&typeof t.protected!="string")throw new Me("JWE Protected Header incorrect type");if(t.encrypted_key!==void 0&&typeof t.encrypted_key!="string")throw new Me("JWE Encrypted Key incorrect type");if(t.aad!==void 0&&typeof t.aad!="string")throw new Me("JWE AAD incorrect type");if(t.header!==void 0&&!vn(t.header))throw new Me("JWE Shared Unprotected Header incorrect type");if(t.unprotected!==void 0&&!vn(t.unprotected))throw new Me("JWE Per-Recipient Unprotected Header incorrect type");let n;if(t.protected)try{let _=_o(t.protected);n=JSON.parse(_s.decode(_))}catch{throw new Me("JWE Protected Header is invalid")}if(!Cf(n,t.header,t.unprotected))throw new Me("JWE Protected, JWE Unprotected Header, and JWE Per-Recipient Unprotected Header Parameter names must be disjoint");let i={...n,...t.header,...t.unprotected};if(Nf(Me,new Map,r?.crit,n,i),i.zip!==void 0&&i.zip!=="DEF")throw new Pt('Unsupported JWE "zip" (Compression Algorithm) Header Parameter value.');if(i.zip!==void 0&&!n?.zip)throw new Me('JWE "zip" (Compression Algorithm) Header Parameter MUST be in a protected header.');let{alg:s,enc:o}=i;if(typeof s!="string"||!s)throw new Me("missing JWE Algorithm (alg) in JWE Header");if(typeof o!="string"||!o)throw new Me("missing JWE Encryption Algorithm (enc) in JWE Header");let a=r&&R0("keyManagementAlgorithms",r.keyManagementAlgorithms),c=r&&R0("contentEncryptionAlgorithms",r.contentEncryptionAlgorithms);if(a&&!a.has(s)||!a&&s.startsWith("PBES2"))throw new Bh('"alg" (Algorithm) Header Parameter value not allowed');if(c&&!c.has(o))throw new Bh('"enc" (Encryption Algorithm) Header Parameter value not allowed');let l;t.encrypted_key!==void 0&&(l=wo(t.encrypted_key,"encrypted_key",Me));let u=!1;typeof e=="function"&&(e=await e(n,t),u=!0),Pf(s==="dir"?o:s,e,"decrypt");let d=await $u(e,s),p;try{p=await kpe(s,d,l,i,r)}catch(_){if(_ instanceof TypeError||_ instanceof Me||_ instanceof Pt)throw _;p=Rf(o)}let f,m;t.iv!==void 0&&(f=wo(t.iv,"iv",Me)),t.tag!==void 0&&(m=wo(t.tag,"tag",Me));let h=t.protected!==void 0?Bn(t.protected):new Uint8Array,y;t.aad!==void 0?y=fi(h,Bn("."),Bn(t.aad)):y=h;let g=wo(t.ciphertext,"ciphertext",Me),b=await tC(o,p,g,f,m,y),v={plaintext:b};if(i.zip==="DEF"){let _=r?.maxDecompressedLength??25e4;if(_===0)throw new Pt('JWE "zip" (Compression Algorithm) Header Parameter is not supported.');if(_!==1/0&&(!Number.isSafeInteger(_)||_<1))throw new TypeError("maxDecompressedLength must be 0, a positive safe integer, or Infinity");v.plaintext=await Ppe(b,_).catch(w=>{throw w instanceof Me?w:new Me("Failed to decompress plaintext",{cause:w})})}return t.protected!==void 0&&(v.protectedHeader=n),t.aad!==void 0&&(v.additionalAuthenticatedData=wo(t.aad,"aad",Me)),t.unprotected!==void 0&&(v.sharedUnprotectedHeader=t.unprotected),t.header!==void 0&&(v.unprotectedHeader=t.header),u?{...v,key:d}:v}var Mpe=I(()=>{Ys();ov();sp();cn();Ss();Ss();LH();Vs();ov();k0();jH();uv();C0();KH()});async function Lpe(t,e,r){if(t instanceof Uint8Array&&(t=_s.decode(t)),typeof t!="string")throw new Me("Compact JWE must be a string or Uint8Array");let{0:n,1:i,2:s,3:o,4:a,length:c}=t.split(".");if(c!==5)throw new Me("Invalid Compact JWE");let l=await Dpe({ciphertext:o,iv:s||void 0,protected:n,tag:a||void 0,encrypted_key:i||void 0},e,r),u={plaintext:l.plaintext,protectedHeader:l.protectedHeader};return typeof e=="function"?{...u,key:l.key}:u}var jpe=I(()=>{Mpe();cn();Vs()});var aC,Upe=I(()=>{Ys();sp();ov();LH();cn();Ss();Vs();k0();uv();C0();KH();aC=class{#e;#t;#r;#n;#i;#p;#u;#a;constructor(e){if(!(e instanceof Uint8Array))throw new TypeError("plaintext must be an instance of Uint8Array");this.#e=e}setKeyManagementParameters(e){return So(this.#a,"setKeyManagementParameters"),this.#a=e,this}setProtectedHeader(e){return So(this.#t,"setProtectedHeader"),this.#t=e,this}setSharedUnprotectedHeader(e){return So(this.#r,"setSharedUnprotectedHeader"),this.#r=e,this}setUnprotectedHeader(e){return So(this.#n,"setUnprotectedHeader"),this.#n=e,this}setAdditionalAuthenticatedData(e){return this.#i=e,this}setContentEncryptionKey(e){return So(this.#p,"setContentEncryptionKey"),this.#p=e,this}setInitializationVector(e){return So(this.#u,"setInitializationVector"),this.#u=e,this}async encrypt(e,r){if(!this.#t&&!this.#n&&!this.#r)throw new Me("either setProtectedHeader, setUnprotectedHeader, or sharedUnprotectedHeader must be called before #encrypt()");if(!Cf(this.#t,this.#n,this.#r))throw new Me("JWE Protected, JWE Shared Unprotected and JWE Per-Recipient Header Parameter names must be disjoint");let n={...this.#t,...this.#n,...this.#r};if(Nf(Me,new Map,r?.crit,this.#t,n),n.zip!==void 0&&n.zip!=="DEF")throw new Pt('Unsupported JWE "zip" (Compression Algorithm) Header Parameter value.');if(n.zip!==void 0&&!this.#t?.zip)throw new Me('JWE "zip" (Compression Algorithm) Header Parameter MUST be in a protected header.');let{alg:i,enc:s}=n;if(typeof i!="string"||!i)throw new Me('JWE "alg" (Algorithm) Header Parameter missing or invalid');if(typeof s!="string"||!s)throw new Me('JWE "enc" (Encryption Algorithm) Header Parameter missing or invalid');let o;if(this.#p&&(i==="dir"||i==="ECDH-ES"))throw new TypeError(`setContentEncryptionKey cannot be called with JWE "alg" (Algorithm) Header ${i}`);Pf(i==="dir"?s:i,e,"encrypt");let a;{let g,b=await $u(e,i);({cek:a,encryptedKey:o,parameters:g}=await Rpe(i,s,b,this.#p,this.#a)),g&&(r&&rpe in r?this.#n?this.#n={...this.#n,...g}:this.setUnprotectedHeader(g):this.#t?this.#t={...this.#t,...g}:this.setProtectedHeader(g))}let c,l,u,d;if(this.#t?(l=bn(JSON.stringify(this.#t)),u=Bn(l)):(l="",u=new Uint8Array),this.#i){d=bn(this.#i);let g=Bn(d);c=fi(u,Bn("."),g)}else c=u;let p=this.#e;n.zip==="DEF"&&(p=await Npe(p).catch(g=>{throw new Me("Failed to compress plaintext",{cause:g})}));let{ciphertext:f,tag:m,iv:h}=await eC(s,p,a,this.#u,c),y={ciphertext:bn(f)};return h&&(y.iv=bn(h)),m&&(y.tag=bn(m)),o&&(y.encrypted_key=bn(o)),d&&(y.aad=d),this.#t&&(y.protected=l),this.#r&&(y.unprotected=this.#r),this.#n&&(y.header=this.#n),y}}});async function Kpe(t,e,r){if(!vn(t))throw new zr("Flattened JWS must be an object");if(t.protected===void 0&&t.header===void 0)throw new zr('Flattened JWS must have either of the "protected" or "header" members');if(t.protected!==void 0&&typeof t.protected!="string")throw new zr("JWS Protected Header incorrect type");if(t.payload===void 0)throw new zr("JWS Payload missing");if(typeof t.signature!="string")throw new zr("JWS Signature missing or incorrect type");if(t.header!==void 0&&!vn(t.header))throw new zr("JWS Unprotected Header incorrect type");let n={};if(t.protected)try{let y=_o(t.protected);n=JSON.parse(_s.decode(y))}catch{throw new zr("JWS Protected Header is invalid")}if(!Cf(n,t.header))throw new zr("JWS Protected and JWS Unprotected Header Parameter names must be disjoint");let i={...n,...t.header},s=Nf(zr,new Map([["b64",!0]]),r?.crit,n,i),o=!0;if(s.has("b64")&&(o=n.b64,typeof o!="boolean"))throw new zr('The "b64" (base64url-encode payload) Header Parameter must be a boolean');let{alg:a}=i;if(typeof a!="string"||!a)throw new zr('JWS "alg" (Algorithm) Header Parameter missing or invalid');let c=r&&R0("algorithms",r.algorithms);if(c&&!c.has(a))throw new Bh('"alg" (Algorithm) Header Parameter value not allowed');if(o){if(typeof t.payload!="string")throw new zr("JWS Payload must be a string")}else if(typeof t.payload!="string"&&!(t.payload instanceof Uint8Array))throw new zr("JWS Payload must be a string or an Uint8Array instance");let l=!1;typeof e=="function"&&(e=await e(n,t),l=!0),Pf(a,e,"verify");let u=fi(t.protected!==void 0?Bn(t.protected):new Uint8Array,Bn("."),typeof t.payload=="string"?o?Bn(t.payload):qh.encode(t.payload):t.payload),d=wo(t.signature,"signature",zr),p=await $u(e,a);if(!await ype(a,p,d,u))throw new ZR;let m;o?m=wo(t.payload,"payload",zr):typeof t.payload=="string"?m=qh.encode(t.payload):m=t.payload;let h={payload:m};return t.protected!==void 0&&(h.protectedHeader=n),t.header!==void 0&&(h.unprotectedHeader=t.header),l?{...h,key:p}:h}var qpe=I(()=>{Ys();nC();cn();Vs();sp();Ss();Ss();C0();k0();jH();uv()});async function Fpe(t,e,r){if(t instanceof Uint8Array&&(t=_s.decode(t)),typeof t!="string")throw new zr("Compact JWS must be a string or Uint8Array");let{0:n,1:i,2:s,length:o}=t.split(".");if(o!==3)throw new zr("Invalid Compact JWS");let a=await Kpe({payload:i,protected:n,signature:s},e,r),c={payload:a.payload,protectedHeader:a.protectedHeader};return typeof e=="function"?{...c,key:a.key}:c}var zpe=I(()=>{qpe();cn();Vs()});function N0(t){let e=Krt.exec(t);if(!e||e[4]&&e[1])throw new TypeError("Invalid time period format");let r=parseFloat(e[2]),n=e[3].toLowerCase(),i;switch(n){case"sec":case"secs":case"second":case"seconds":case"s":i=Math.round(r);break;case"minute":case"minutes":case"min":case"mins":case"m":i=Math.round(r*Hpe);break;case"hour":case"hours":case"hr":case"hrs":case"h":i=Math.round(r*Wpe);break;case"day":case"days":case"d":i=Math.round(r*qH);break;case"week":case"weeks":case"w":i=Math.round(r*jrt);break;default:i=Math.round(r*Urt);break}return e[1]==="-"||e[4]==="ago"?-i:i}function $h(t,e){if(!Number.isFinite(e))throw new TypeError(`Invalid ${t} input`);return e}function cC(t,e,r={}){let n;try{n=JSON.parse(_s.decode(e))}catch{}if(!vn(n))throw new Js("JWT Claims Set must be a top-level JSON object");let{typ:i}=r;if(i&&(typeof t.typ!="string"||Bpe(t.typ)!==Bpe(i)))throw new Es('unexpected "typ" JWT header value',n,"typ","check_failed");let{requiredClaims:s=[],issuer:o,subject:a,audience:c,maxTokenAge:l}=r,u=[...s];l!==void 0&&u.push("iat"),c!==void 0&&u.push("aud"),a!==void 0&&u.push("sub"),o!==void 0&&u.push("iss");for(let m of new Set(u.reverse()))if(!(m in n))throw new Es(`missing required "${m}" claim`,n,m,"missing");if(o&&!(Array.isArray(o)?o:[o]).includes(n.iss))throw new Es('unexpected "iss" claim value',n,"iss","check_failed");if(a&&n.sub!==a)throw new Es('unexpected "sub" claim value',n,"sub","check_failed");if(c&&!qrt(n.aud,typeof c=="string"?[c]:c))throw new Es('unexpected "aud" claim value',n,"aud","check_failed");let d;switch(typeof r.clockTolerance){case"string":d=N0(r.clockTolerance);break;case"number":d=r.clockTolerance;break;case"undefined":d=0;break;default:throw new TypeError("Invalid clockTolerance option type")}let{currentDate:p}=r,f=Df(p||new Date);if((n.iat!==void 0||l)&&typeof n.iat!="number")throw new Es('"iat" claim must be a number',n,"iat","invalid");if(n.nbf!==void 0){if(typeof n.nbf!="number")throw new Es('"nbf" claim must be a number',n,"nbf","invalid");if(n.nbf>f+d)throw new Es('"nbf" claim timestamp check failed',n,"nbf","check_failed")}if(n.exp!==void 0){if(typeof n.exp!="number")throw new Es('"exp" claim must be a number',n,"exp","invalid");if(n.exp<=f-d)throw new zh('"exp" claim timestamp check failed',n,"exp","check_failed")}if(l){let m=f-n.iat,h=typeof l=="number"?l:N0(l);if(m-d>h)throw new zh('"iat" claim timestamp check failed (too far in the past)',n,"iat","check_failed");if(m<0-d)throw new Es('"iat" claim timestamp check failed (it should be in the past)',n,"iat","check_failed")}return n}var Df,Hpe,Wpe,qH,jrt,Urt,Krt,Bpe,qrt,pv,P0=I(()=>{cn();Vs();Ss();Df=t=>Math.floor(t.getTime()/1e3),Hpe=60,Wpe=Hpe*60,qH=Wpe*24,jrt=qH*7,Urt=qH*365.25,Krt=/^(\+|\-)? ?(\d+|\d+\.\d+) ?(seconds?|secs?|s|minutes?|mins?|m|hours?|hrs?|h|days?|d|weeks?|w|years?|yrs?|y)(?: (ago|from now))?$/i;Bpe=t=>t.includes("/")?t.toLowerCase():`application/${t.toLowerCase()}`,qrt=(t,e)=>typeof t=="string"?e.includes(t):Array.isArray(t)?e.some(Set.prototype.has.bind(new Set(t))):!1;pv=class{#e;constructor(e){if(!vn(e))throw new TypeError("JWT Claims Set MUST be an object");this.#e=structuredClone(e)}data(){return qh.encode(JSON.stringify(this.#e))}get iss(){return this.#e.iss}set iss(e){this.#e.iss=e}get sub(){return this.#e.sub}set sub(e){this.#e.sub=e}get aud(){return this.#e.aud}set aud(e){this.#e.aud=e}set jti(e){this.#e.jti=e}set nbf(e){typeof e=="number"?this.#e.nbf=$h("setNotBefore",e):e instanceof Date?this.#e.nbf=$h("setNotBefore",Df(e)):this.#e.nbf=Df(new Date)+N0(e)}set exp(e){typeof e=="number"?this.#e.exp=$h("setExpirationTime",e):e instanceof Date?this.#e.exp=$h("setExpirationTime",Df(e)):this.#e.exp=Df(new Date)+N0(e)}set iat(e){e===void 0?this.#e.iat=Df(new Date):e instanceof Date?this.#e.iat=$h("setIssuedAt",Df(e)):typeof e=="string"?this.#e.iat=$h("setIssuedAt",Df(new Date)+N0(e)):this.#e.iat=$h("setIssuedAt",e)}}});async function To(t,e,r){let n=await Fpe(t,e,r);if(n.protectedHeader.crit?.includes("b64")&&n.protectedHeader.b64===!1)throw new Js("JWTs MUST NOT use unencoded payload");let s={payload:cC(n.protectedHeader,n.payload,r),protectedHeader:n.protectedHeader};return typeof e=="function"?{...s,key:n.key}:s}var $pe=I(()=>{zpe();P0();cn()});async function lC(t,e,r){let n=await Lpe(t,e,r),i=cC(n.protectedHeader,n.plaintext,r),{protectedHeader:s}=n;if(s.iss!==void 0&&s.iss!==i.iss)throw new Es('replicated "iss" claim header parameter mismatch',i,"iss","mismatch");if(s.sub!==void 0&&s.sub!==i.sub)throw new Es('replicated "sub" claim header parameter mismatch',i,"sub","mismatch");if(s.aud!==void 0&&JSON.stringify(s.aud)!==JSON.stringify(i.aud))throw new Es('replicated "aud" claim header parameter mismatch',i,"aud","mismatch");let o={payload:i,protectedHeader:s};return typeof e=="function"?{...o,key:n.key}:o}var Gpe=I(()=>{jpe();P0();cn()});var uC,Vpe=I(()=>{Upe();uC=class{#e;constructor(e){this.#e=new aC(e)}setContentEncryptionKey(e){return this.#e.setContentEncryptionKey(e),this}setInitializationVector(e){return this.#e.setInitializationVector(e),this}setProtectedHeader(e){return this.#e.setProtectedHeader(e),this}setKeyManagementParameters(e){return this.#e.setKeyManagementParameters(e),this}async encrypt(e,r){let n=await this.#e.encrypt(e,r);return[n.protected,n.encrypted_key,n.iv,n.ciphertext,n.tag].join(".")}}});var dC,Ype=I(()=>{Ys();nC();Ss();cn();Vs();C0();k0();uv();sp();dC=class{#e;#t;#r;constructor(e){if(!(e instanceof Uint8Array))throw new TypeError("payload must be an instance of Uint8Array");this.#e=e}setProtectedHeader(e){return So(this.#t,"setProtectedHeader"),this.#t=e,this}setUnprotectedHeader(e){return So(this.#r,"setUnprotectedHeader"),this.#r=e,this}async sign(e,r){if(!this.#t&&!this.#r)throw new zr("either setProtectedHeader or setUnprotectedHeader must be called before #sign()");if(!Cf(this.#t,this.#r))throw new zr("JWS Protected and JWS Unprotected Header Parameter names must be disjoint");let n={...this.#t,...this.#r},i=Nf(zr,new Map([["b64",!0]]),r?.crit,this.#t,n),s=!0;if(i.has("b64")&&(s=this.#t.b64,typeof s!="boolean"))throw new zr('The "b64" (base64url-encode payload) Header Parameter must be a boolean');let{alg:o}=n;if(typeof o!="string"||!o)throw new zr('JWS "alg" (Algorithm) Header Parameter missing or invalid');Pf(o,e,"sign");let a,c;s?(a=bn(this.#e),c=Bn(a)):(c=this.#e,a="");let l,u;this.#t?(l=bn(JSON.stringify(this.#t)),u=Bn(l)):(l="",u=new Uint8Array);let d=fi(u,Bn("."),c),p=await $u(e,o),f=await gpe(o,p,d),m={signature:bn(f),payload:a};return this.#r&&(m.header=this.#r),this.#t&&(m.protected=l),m}}});var pC,Jpe=I(()=>{Ype();pC=class{#e;constructor(e){this.#e=new dC(e)}setProtectedHeader(e){return this.#e.setProtectedHeader(e),this}async sign(e,r){let n=await this.#e.sign(e,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 D0,Zpe=I(()=>{Jpe();cn();P0();D0=class{#e;#t;constructor(e={}){this.#t=new pv(e)}setIssuer(e){return this.#t.iss=e,this}setSubject(e){return this.#t.sub=e,this}setAudience(e){return this.#t.aud=e,this}setJti(e){return this.#t.jti=e,this}setNotBefore(e){return this.#t.nbf=e,this}setExpirationTime(e){return this.#t.exp=e,this}setIssuedAt(e){return this.#t.iat=e,this}setProtectedHeader(e){return this.#e=e,this}async sign(e,r){let n=new pC(this.#t.data());if(n.setProtectedHeader(this.#e),Array.isArray(this.#e?.crit)&&this.#e.crit.includes("b64")&&this.#e.b64===!1)throw new Js("JWTs MUST NOT use unencoded payload");return n.sign(e,r)}}});var M0,Xpe=I(()=>{Vpe();P0();sp();M0=class{#e;#t;#r;#n;#i;#p;#u;#a;constructor(e={}){this.#a=new pv(e)}setIssuer(e){return this.#a.iss=e,this}setSubject(e){return this.#a.sub=e,this}setAudience(e){return this.#a.aud=e,this}setJti(e){return this.#a.jti=e,this}setNotBefore(e){return this.#a.nbf=e,this}setExpirationTime(e){return this.#a.exp=e,this}setIssuedAt(e){return this.#a.iat=e,this}setProtectedHeader(e){return So(this.#n,"setProtectedHeader"),this.#n=e,this}setKeyManagementParameters(e){return So(this.#r,"setKeyManagementParameters"),this.#r=e,this}setContentEncryptionKey(e){return So(this.#e,"setContentEncryptionKey"),this.#e=e,this}setInitializationVector(e){return So(this.#t,"setInitializationVector"),this.#t=e,this}replicateIssuerAsHeader(){return this.#i=!0,this}replicateSubjectAsHeader(){return this.#p=!0,this}replicateAudienceAsHeader(){return this.#u=!0,this}async encrypt(e,r){let n=new uC(this.#a.data());return this.#n&&(this.#i||this.#p||this.#u)&&(this.#n={...this.#n,iss:this.#i?this.#a.iss:void 0,sub:this.#p?this.#a.sub:void 0,aud:this.#u?this.#a.aud:void 0}),n.setProtectedHeader(this.#n),this.#t&&n.setInitializationVector(this.#t),this.#e&&n.setContentEncryptionKey(this.#e),this.#r&&n.setKeyManagementParameters(this.#r),n.encrypt(e,r)}}});async function fC(t,e){let r;if(Wh(t))r=t;else if(T0(t))r=await oC(t);else throw new TypeError(Wu(t,"CryptoKey","KeyObject","JSON Web Key"));if(e??="sha256",e!=="sha256"&&e!=="sha384"&&e!=="sha512")throw new TypeError('digestAlgorithm must one of "sha256", "sha384", or "sha512"');let n;switch(r.kty){case"AKP":Gu(r.alg,'"alg" (Algorithm) Parameter'),Gu(r.pub,'"pub" (Public key) Parameter'),n={alg:r.alg,kty:r.kty,pub:r.pub};break;case"EC":Gu(r.crv,'"crv" (Curve) Parameter'),Gu(r.x,'"x" (X Coordinate) Parameter'),Gu(r.y,'"y" (Y Coordinate) Parameter'),n={crv:r.crv,kty:r.kty,x:r.x,y:r.y};break;case"OKP":Gu(r.crv,'"crv" (Subtype of Key Pair) Parameter'),Gu(r.x,'"x" (Public Key) Parameter'),n={crv:r.crv,kty:r.kty,x:r.x};break;case"RSA":Gu(r.e,'"e" (Exponent) Parameter'),Gu(r.n,'"n" (Modulus) Parameter'),n={e:r.e,kty:r.kty,n:r.n};break;case"oct":Gu(r.k,'"k" (Key Value) Parameter'),n={k:r.k,kty:r.kty};break;default:throw new Pt('"kty" (Key Type) Parameter missing or unsupported')}let i=Bn(JSON.stringify(n));return bn(await rC(e,i))}var Gu,Qpe=I(()=>{sp();Ys();cn();Vs();Hh();Ss();MH();rv();Gu=(t,e)=>{if(typeof t!="string"||!t)throw new VR(`${e} missing or invalid`)}});function Frt(t){switch(typeof t=="string"&&t.slice(0,2)){case"RS":case"PS":return"RSA";case"ES":return"EC";case"Ed":return"OKP";case"ML":return"AKP";default:throw new Pt('Unsupported "alg" value for a JSON Web Key Set')}}function zrt(t){return t&&typeof t=="object"&&Array.isArray(t.keys)&&t.keys.every(Brt)}function Brt(t){return vn(t)}async function efe(t,e,r){let n=t.get(e)||t.set(e,{}).get(e);if(n[r]===void 0){let i=await Ga({...e,ext:!0},r);if(i instanceof Uint8Array||i.type!=="public")throw new S0("JSON Web Key Set members must be public keys");n[r]=i}return n[r]}function zH(t){let e=new FH(t),r=async(n,i)=>e.getKey(n,i);return Object.defineProperties(r,{jwks:{value:()=>structuredClone(e.jwks()),enumerable:!1,configurable:!1,writable:!1}}),r}var FH,tfe=I(()=>{sC();cn();Ss();FH=class{#e;#t=new WeakMap;constructor(e){if(!zrt(e))throw new S0("JSON Web Key Set malformed");this.#e=structuredClone(e)}jwks(){return this.#e}async getKey(e,r){let{alg:n,kid:i}={...e,...r?.header},s=Frt(n),o=this.#e.keys.filter(l=>{let u=s===l.kty;if(u&&typeof i=="string"&&(u=i===l.kid),u&&(typeof l.alg=="string"||s==="AKP")&&(u=n===l.alg),u&&typeof l.use=="string"&&(u=l.use==="sig"),u&&Array.isArray(l.key_ops)&&(u=l.key_ops.includes("verify")),u)switch(n){case"ES256":u=l.crv==="P-256";break;case"ES384":u=l.crv==="P-384";break;case"ES512":u=l.crv==="P-521";break;case"Ed25519":case"EdDSA":u=l.crv==="Ed25519";break}return u}),{0:a,length:c}=o;if(c===0)throw new iv;if(c!==1){let l=new YR,u=this.#t;throw l[Symbol.asyncIterator]=async function*(){for(let d of o)try{yield await efe(u,d,n)}catch{}},l}return efe(this.#t,a,n)}}});function Hrt(){return typeof WebSocketPair<"u"||typeof navigator<"u"&&navigator.userAgent==="Cloudflare-Workers"||typeof EdgeRuntime<"u"&&EdgeRuntime==="vercel"}async function Wrt(t,e,r,n=fetch){let i=await n(t,{method:"GET",signal:r,redirect:"manual",headers:e}).catch(s=>{throw s.name==="TimeoutError"?new JR:s});if(i.status!==200)throw new Si("Expected 200 OK from the JSON Web Key Set HTTP response");try{return await i.json()}catch{throw new Si("Failed to parse the JSON Web Key Set HTTP response as JSON")}}function $rt(t,e){return!(typeof t!="object"||t===null||!("uat"in t)||typeof t.uat!="number"||Date.now()-t.uat>=e||!("jwks"in t)||!vn(t.jwks)||!Array.isArray(t.jwks.keys)||!Array.prototype.every.call(t.jwks.keys,vn))}function WH(t,e){let r=new HH(t,e),n=async(i,s)=>r.getKey(i,s);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.jwks(),enumerable:!0,configurable:!1,writable:!1}}),n}var BH,rfe,mC,HH,nfe=I(()=>{cn();tfe();Ss();(typeof navigator>"u"||!navigator.userAgent?.startsWith?.("Mozilla/5.0 "))&&(BH="jose/v6.2.3");rfe=Symbol();mC=Symbol();HH=class{#e;#t;#r;#n;#i;#p;#u;#a;#o;#d;constructor(e,r){if(!(e instanceof URL))throw new TypeError("url must be an instance of URL");this.#e=new URL(e.href),this.#t=typeof r?.timeoutDuration=="number"?r?.timeoutDuration:5e3,this.#r=typeof r?.cooldownDuration=="number"?r?.cooldownDuration:3e4,this.#n=typeof r?.cacheMaxAge=="number"?r?.cacheMaxAge:6e5,this.#u=new Headers(r?.headers),BH&&!this.#u.has("User-Agent")&&this.#u.set("User-Agent",BH),this.#u.has("accept")||(this.#u.set("accept","application/json"),this.#u.append("accept","application/jwk-set+json")),this.#a=r?.[rfe],r?.[mC]!==void 0&&(this.#d=r?.[mC],$rt(r?.[mC],this.#n)&&(this.#i=this.#d.uat,this.#o=zH(this.#d.jwks)))}pendingFetch(){return!!this.#p}coolingDown(){return typeof this.#i=="number"?Date.now()<this.#i+this.#r:!1}fresh(){return typeof this.#i=="number"?Date.now()<this.#i+this.#n:!1}jwks(){return this.#o?.jwks()}async getKey(e,r){(!this.#o||!this.fresh())&&await this.reload();try{return await this.#o(e,r)}catch(n){if(n instanceof iv&&this.coolingDown()===!1)return await this.reload(),this.#o(e,r);throw n}}async reload(){this.#p&&Hrt()&&(this.#p=void 0),this.#p||=Wrt(this.#e.href,this.#u,AbortSignal.timeout(this.#t),this.#a).then(e=>{this.#o=zH(e),this.#d&&(this.#d.uat=Date.now(),this.#d.jwks=e),this.#i=Date.now(),this.#p=void 0}).catch(e=>{throw this.#p=void 0,e}),await this.#p}}});function Dl(t){let e;if(typeof t=="string"){let r=t.split(".");(r.length===3||r.length===5)&&([e]=r)}else if(typeof t=="object"&&t)if("protected"in t)e=t.protected;else throw new TypeError("Token does not contain a Protected Header");try{if(typeof e!="string"||!e)throw new Error;let r=JSON.parse(_s.decode(_o(e)));if(!vn(r))throw new Error;return r}catch{throw new TypeError("Invalid Token or Protected Header formatting")}}var ife=I(()=>{Ys();Vs();Ss()});function wi(t){if(typeof t!="string")throw new Js("JWTs must use Compact JWS serialization, JWT must be a string");let{1:e,length:r}=t.split(".");if(r===5)throw new Js("Only JWTs using Compact JWS serialization can be decoded");if(r!==3)throw new Js("Invalid JWT");if(!e)throw new Js("JWTs must contain a payload");let n;try{n=_o(e)}catch{throw new Js("Failed to base64url decode the payload")}let i;try{i=JSON.parse(_s.decode(n))}catch{throw new Js("Failed to parse the decoded payload as JSON")}if(!vn(i))throw new Js("Invalid JWT Claims Set");return i}var sfe=I(()=>{Ys();Vs();Ss();cn()});var Wc=I(()=>{$pe();Gpe();Zpe();Xpe();Qpe();nfe();sC();ife();sfe();Ys()});async function hC(t,e,r=3600){return await new D0(t).setProtectedHeader({alg:"HS256"}).setIssuedAt().setExpirationTime(Math.floor(Date.now()/1e3)+r).sign(new TextEncoder().encode(e))}async function $H(t,e){try{return(await To(t,new TextEncoder().encode(e))).payload}catch{return null}}function L0(t,e){return Ude(Bde,new TextEncoder().encode(t),new TextEncoder().encode(e),Grt,64)}function Yrt(t){if(typeof t=="string")return t;let e=t.keys.get(t.currentVersion);if(!e)throw new Error(`Secret version ${t.currentVersion} not found in keys`);return e}function ofe(t){if(typeof t=="string")return[{version:0,value:t}];let e=[];for(let[r,n]of t.keys)e.push({version:r,value:n});return t.legacySecret&&!e.some(r=>r.value===t.legacySecret)&&e.push({version:-1,value:t.legacySecret}),e}async function gC(t,e,r,n=3600){let i=L0(Yrt(e),r),s=await fC({kty:"oct",k:E0.encode(i)},"sha256");return await new M0(t).setProtectedHeader({alg:cfe,enc:lfe,kid:s}).setIssuedAt().setExpirationTime(Vrt()+n).setJti(crypto.randomUUID()).encrypt(i)}async function j0(t,e,r){if(!t)return null;let n=!1;try{n=Dl(t).kid!==void 0}catch{return null}try{let i=ofe(e),{payload:s}=await lC(t,async o=>{let a=o.kid;if(a!==void 0){for(let c of i){let l=L0(c.value,r);if(a===await fC({kty:"oct",k:E0.encode(l)},"sha256"))return l}throw new Error("no matching decryption secret")}return i.length===1,L0(i[0].value,r)},afe);return s}catch{if(n)return null;let i=ofe(e);if(i.length<=1)return null;for(let s=1;s<i.length;s++)try{let o=i[s],{payload:a}=await lC(t,L0(o.value,r),afe);return a}catch{continue}return null}}var Grt,Vrt,cfe,lfe,afe,U0=I(()=>{Kde();Hde();Wc();Grt=new Uint8Array([66,101,116,116,101,114,65,117,116,104,46,106,115,32,71,101,110,101,114,97,116,101,100,32,69,110,99,114,121,112,116,105,111,110,32,75,101,121]),Vrt=()=>Date.now()/1e3|0,cfe="dir",lfe="A256CBC-HS512";afe={clockTolerance:15,keyManagementAlgorithms:[cfe],contentEncryptionAlgorithms:[lfe,"A256GCM"]}});function ufe(t,e){return new Promise((r,n)=>{(0,yC.scrypt)(t.normalize("NFKC"),e,fv.dkLen,{N:fv.N,r:fv.r,p:fv.p,maxmem:128*fv.N*fv.r*2},(i,s)=>{i?n(i):r(s)})})}async function dfe(t){let e=(0,yC.randomBytes)(16).toString("hex"),r=await ufe(t,e);return`${e}:${r.toString("hex")}`}async function pfe(t,e){let[r,n]=t.split(":");if(!r||!n)throw new Error("Invalid password hash");return(await ufe(e,r)).toString("hex")===n}var yC,fv,ffe=I(()=>{yC=require("node:crypto"),fv={N:16384,r:16,p:1,dkLen:64}});var mfe,hfe,gfe=I(()=>{ffe();mfe=dfe,hfe=async({hash:t,password:e})=>pfe(t,e)});function Ml(){let t=typeof globalThis<"u"&&globalThis.crypto;if(t&&typeof t.subtle=="object"&&t.subtle!=null)return t.subtle;throw new Error("crypto.subtle must be defined")}var K0=I(()=>{});function bC(t){return t?"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_":"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"}function yfe(t,e,r){let n="",i=0,s=0;for(let o of t)for(i=i<<8|o,s+=8;s>=6;)s-=6,n+=e[i>>s&63];if(s>0&&(n+=e[i<<6-s&63]),r){let o=(4-n.length%4)%4;n+="=".repeat(o)}return n}function bfe(t,e){let r=new Map;for(let o=0;o<e.length;o++)r.set(e[o],o);let n=[],i=0,s=0;for(let o of t){if(o==="=")break;let a=r.get(o);if(a===void 0)throw new Error(`Invalid Base64 character: ${o}`);i=i<<6|a,s+=6,s>=8&&(s-=8,n.push(i>>s&255))}return Uint8Array.from(n)}var Hi,da,pa=I(()=>{Hi={encode(t,e={}){let r=bC(!1),n=typeof t=="string"?new TextEncoder().encode(t):new Uint8Array(t);return yfe(n,r,e.padding??!0)},decode(t){typeof t!="string"&&(t=new TextDecoder().decode(t));let e=t.includes("-")||t.includes("_"),r=bC(e);return bfe(t,r)}},da={encode(t,e={}){let r=bC(!0),n=typeof t=="string"?new TextEncoder().encode(t):new Uint8Array(t);return yfe(n,r,e.padding??!0)},decode(t){let e=t.includes("-")||t.includes("_"),r=bC(e);return bfe(t,r)}}});function op(t,e){return{digest:async r=>{let n=new TextEncoder,i=typeof r=="string"?n.encode(r):r,s=await Ml().digest(t,i);return e==="hex"?Array.from(new Uint8Array(s)).map(c=>c.toString(16).padStart(2,"0")).join(""):e==="base64"||e==="base64url"||e==="base64urlnopad"?e.includes("url")?da.encode(s,{padding:e!=="base64urlnopad"}):Hi.encode(s):s}}}var q0=I(()=>{pa();K0()});function Jrt(t){return t instanceof Uint8Array||ArrayBuffer.isView(t)&&t.constructor.name==="Uint8Array"&&"BYTES_PER_ELEMENT"in t&&t.BYTES_PER_ELEMENT===1}function vC(t){if(typeof t!="boolean")throw new TypeError(`boolean expected, not ${t}`)}function Mf(t){if(typeof t!="number")throw new TypeError("number expected, got "+typeof t);if(!Number.isSafeInteger(t)||t<0)throw new RangeError("positive integer expected, got "+t)}function Dn(t,e,r=""){let n=Jrt(t),i=t?.length,s=e!==void 0;if(!n||s&&i!==e){let o=r&&`"${r}" `,a=s?` of length ${e}`:"",c=n?`length=${i}`:`type=${typeof t}`,l=o+"expected Uint8Array"+a+", got "+c;throw n?new RangeError(l):new TypeError(l)}return t}function GH(t,e=!0){if(t.destroyed)throw new Error("Hash instance has been destroyed");if(e&&t.finished)throw new Error("Hash#digest() has already been called")}function _fe(t,e,r=!1){Dn(t,void 0,"output");let n=e.outputLen;if(t.length<n)throw new RangeError("digestInto() expects output buffer of length at least "+n);if(r&&!mv(t))throw new Error("invalid output, must be aligned")}function Vu(t){return new Uint32Array(t.buffer,t.byteOffset,Math.floor(t.byteLength/4))}function Ll(...t){for(let e=0;e<t.length;e++)t[e].fill(0)}function Zrt(t){return new DataView(t.buffer,t.byteOffset,t.byteLength)}function VH(t){if(Dn(t),Sfe)return t.toHex();let e="";for(let r=0;r<t.length;r++)e+=Qrt[t[r]];return e}function vfe(t){if(t>=ap._0&&t<=ap._9)return t-ap._0;if(t>=ap.A&&t<=ap.F)return t-(ap.A-10);if(t>=ap.a&&t<=ap.f)return t-(ap.a-10)}function wfe(t){if(typeof t!="string")throw new TypeError("hex string expected, got "+typeof t);if(Sfe)try{return Uint8Array.fromHex(t)}catch(i){throw i instanceof SyntaxError?new RangeError(i.message):i}let e=t.length,r=e/2;if(e%2)throw new RangeError("hex string expected, got unpadded hex of length "+e);let n=new Uint8Array(r);for(let i=0,s=0;i<r;i++,s+=2){let o=vfe(t.charCodeAt(s)),a=vfe(t.charCodeAt(s+1));if(o===void 0||a===void 0){let c=t[s]+t[s+1];throw new RangeError('hex string expected, got non-hex character "'+c+'" at index '+s)}n[i]=o*16+a}return n}function Tfe(t){if(typeof t!="string")throw new TypeError("string expected");return new Uint8Array(new TextEncoder().encode(t))}function ent(t,e){return!t.byteLength||!e.byteLength?!1:t.buffer===e.buffer&&t.byteOffset<e.byteOffset+e.byteLength&&e.byteOffset<t.byteOffset+t.byteLength}function xfe(...t){let e=0;for(let n=0;n<t.length;n++){let i=t[n];Dn(i),e+=i.length}let r=new Uint8Array(e);for(let n=0,i=0;n<t.length;n++){let s=t[n];r.set(s,i),i+=s.length}return r}function Ife(t,e){if(e==null||typeof e!="object")throw new Error("options must be defined");return Object.assign(t,e)}function Afe(t,e){if(t.length!==e.length)return!1;let r=0;for(let n=0;n<t.length;n++)r|=t[n]^e[n];return r===0}function Ofe(t,e,r){let n=e,i=r||(()=>[]),s=(a,c)=>n(c,...i(a)).update(a).digest(),o=n(new Uint8Array(t),...i(new Uint8Array(0)));return s.outputLen=o.outputLen,s.blockLen=o.blockLen,s.create=(a,...c)=>n(a,...c),s}function F0(t,e,r=!0){if(e===void 0)return new Uint8Array(t);if(Dn(e,void 0,"output"),e.length!==t)throw new Error('"output" expected Uint8Array of length '+t+", got: "+e.length);if(r&&!mv(e))throw new Error("invalid output, must be aligned");return e}function Rfe(t,e,r){Mf(t),Mf(e),vC(r);let n=new Uint8Array(16),i=Zrt(n);return i.setBigUint64(0,BigInt(e),r),i.setBigUint64(8,BigInt(t),r),n}function mv(t){return t.byteOffset%4===0}function hv(t){return Uint8Array.from(Dn(t))}function Cfe(t=32){Mf(t);let e=typeof globalThis=="object"?globalThis.crypto:null;if(typeof e?.getRandomValues!="function")throw new Error("crypto.getRandomValues must be defined");return e.getRandomValues(new Uint8Array(t))}function YH(t,e=Cfe){let{nonceLength:r}=t;Mf(r);let n=(s,o,a)=>{let c=xfe(s,o);return ent(a,o)||o.fill(0),c},i=((s,...o)=>({encrypt(a){Dn(a);let c=e(r),l=t(s,c,...o).encrypt(a);return l instanceof Promise?l.then(u=>n(c,u,a)):n(c,l,a)},decrypt(a){Dn(a);let c=a.subarray(0,r),l=a.subarray(r);return t(s,c,...o).decrypt(l)}}));return"blockSize"in t&&(i.blockSize=t.blockSize),"tagLength"in t&&(i.tagLength=t.tagLength),i}var Lf,Efe,ws,Xrt,Yu,Sfe,Qrt,ap,kfe,z0=I(()=>{Lf=new Uint8Array(new Uint32Array([287454020]).buffer)[0]===68,Efe=t=>t<<24&4278190080|t<<8&16711680|t>>>8&65280|t>>>24&255,ws=Lf?t=>t:t=>Efe(t)>>>0,Xrt=t=>{for(let e=0;e<t.length;e++)t[e]=Efe(t[e]);return t},Yu=Lf?t=>t:Xrt,Sfe=typeof Uint8Array.from([]).toHex=="function"&&typeof Uint8Array.fromHex=="function",Qrt=Array.from({length:256},(t,e)=>e.toString(16).padStart(2,"0"));ap={_0:48,_9:57,A:65,F:70,a:97,f:102};kfe=(t,e)=>{function r(n,...i){if(Dn(n,void 0,"key"),t.nonceLength!==void 0){let u=i[0];Dn(u,t.varSizeNonce?void 0:t.nonceLength,"nonce")}let s=t.tagLength;s&&i[1]!==void 0&&Dn(i[1],void 0,"AAD");let o=e(n,...i),a=(u,d)=>{if(d!==void 0){if(u!==2)throw new Error("cipher output not supported");Dn(d,void 0,"output")}},c=!1;return{encrypt(u,d){if(c)throw new Error("cannot encrypt() twice with same key + nonce");return c=!0,Dn(u),a(o.encrypt.length,d),o.encrypt(u,d)},decrypt(u,d){if(Dn(u),s&&u.length<s)throw new Error('"ciphertext" expected length bigger than tagLength='+s);return a(o.decrypt.length,d),o.decrypt(u,d)}}}return Object.assign(r,t),r}});function Le(t,e){return t<<e|t>>>32-e}function int(t,e,r,n,i,s,o,a){let c=i.length,l=new Uint8Array(B0),u=Vu(l),d=Lf&&mv(i)&&mv(s),p=d?Vu(i):Nfe,f=d?Vu(s):Nfe;if(!Lf){for(let m=0;m<c;o++){if(t(e,r,n,u,o,a),Yu(u),o>=JH)throw new Error("arx: counter overflow");let h=Math.min(B0,c-m);for(let y=0,g;y<h;y++)g=m+y,s[g]=i[g]^l[y];m+=h}return}for(let m=0;m<c;o++){if(t(e,r,n,u,o,a),o>=JH)throw new Error("arx: counter overflow");let h=Math.min(B0,c-m);if(d&&h===B0){let y=m/4;if(m%4!==0)throw new Error("arx: invalid block position");for(let g=0,b;g<nnt;g++)b=y+g,f[b]=p[b]^u[g];m+=B0;continue}for(let y=0,g;y<h;y++)g=m+y,s[g]=i[g]^l[y];m+=h}}function Dfe(t,e){let{allowShortKeys:r,extendNonceFn:n,counterLength:i,counterRight:s,rounds:o}=Ife({allowShortKeys:!1,counterLength:8,counterRight:!1,rounds:20},e);if(typeof t!="function")throw new Error("core must be a function");return Mf(i),Mf(o),vC(s),vC(r),(a,c,l,u,d=0)=>{Dn(a,void 0,"key"),Dn(c,void 0,"nonce"),Dn(l,void 0,"data");let p=l.length;if(u=F0(p,u,!1),Mf(d),d<0||d>=JH)throw new Error("arx: counter overflow");let f=[],m=a.length,h,y;if(m===32)f.push(h=hv(a)),y=rnt;else if(m===16&&r)h=new Uint8Array(32),h.set(a),h.set(a,16),y=tnt,f.push(h);else throw Dn(a,32,"arx key"),new Error("invalid key size");(!Lf||!mv(c))&&f.push(c=hv(c));let g=Vu(h);if(n){if(c.length!==24)throw new Error("arx: extended nonce must be 24 bytes");let _=c.subarray(0,16);if(Lf)n(y,g,Vu(_),g);else{let w=Yu(Uint32Array.from(y));n(w,g,Vu(_),g),Ll(w),Yu(g)}c=c.subarray(16)}else Lf||Yu(g);let b=16-i;if(b!==c.length)throw new Error(`arx: nonce must be ${b} or 16 bytes`);if(b!==12){let _=new Uint8Array(12);_.set(c,s?0:12-c.length),c=_,f.push(c)}let v=Yu(Vu(c));try{return int(t,y,g,v,l,u,d,o),u}finally{Ll(...f)}}}var Pfe,tnt,rnt,B0,nnt,JH,Nfe,Mfe=I(()=>{z0();Pfe=t=>Uint8Array.from(t.split(""),e=>e.charCodeAt(0)),tnt=Yu(Vu(Pfe("expand 16-byte k"))),rnt=Yu(Vu(Pfe("expand 32-byte k")));B0=64,nnt=16,JH=2**32-1,Nfe=Uint32Array.of()});function Ts(t,e){return t[e++]&255|(t[e++]&255)<<8}var ZH,Lfe,jfe=I(()=>{z0();ZH=class{blockLen=16;outputLen=16;buffer=new Uint8Array(16);r=new Uint16Array(10);h=new Uint16Array(10);pad=new Uint16Array(8);pos=0;finished=!1;destroyed=!1;constructor(e){e=hv(Dn(e,32,"key"));let r=Ts(e,0),n=Ts(e,2),i=Ts(e,4),s=Ts(e,6),o=Ts(e,8),a=Ts(e,10),c=Ts(e,12),l=Ts(e,14);this.r[0]=r&8191,this.r[1]=(r>>>13|n<<3)&8191,this.r[2]=(n>>>10|i<<6)&7939,this.r[3]=(i>>>7|s<<9)&8191,this.r[4]=(s>>>4|o<<12)&255,this.r[5]=o>>>1&8190,this.r[6]=(o>>>14|a<<2)&8191,this.r[7]=(a>>>11|c<<5)&8065,this.r[8]=(c>>>8|l<<8)&8191,this.r[9]=l>>>5&127;for(let u=0;u<8;u++)this.pad[u]=Ts(e,16+2*u)}process(e,r,n=!1){let i=n?0:2048,{h:s,r:o}=this,a=o[0],c=o[1],l=o[2],u=o[3],d=o[4],p=o[5],f=o[6],m=o[7],h=o[8],y=o[9],g=Ts(e,r+0),b=Ts(e,r+2),v=Ts(e,r+4),_=Ts(e,r+6),w=Ts(e,r+8),S=Ts(e,r+10),x=Ts(e,r+12),O=Ts(e,r+14),N=s[0]+(g&8191),k=s[1]+((g>>>13|b<<3)&8191),M=s[2]+((b>>>10|v<<6)&8191),K=s[3]+((v>>>7|_<<9)&8191),P=s[4]+((_>>>4|w<<12)&8191),j=s[5]+(w>>>1&8191),U=s[6]+((w>>>14|S<<2)&8191),q=s[7]+((S>>>11|x<<5)&8191),F=s[8]+((x>>>8|O<<8)&8191),Q=s[9]+(O>>>5|i),J=0,W=J+N*a+k*(5*y)+M*(5*h)+K*(5*m)+P*(5*f);J=W>>>13,W&=8191,W+=j*(5*p)+U*(5*d)+q*(5*u)+F*(5*l)+Q*(5*c),J+=W>>>13,W&=8191;let z=J+N*c+k*a+M*(5*y)+K*(5*h)+P*(5*m);J=z>>>13,z&=8191,z+=j*(5*f)+U*(5*p)+q*(5*d)+F*(5*u)+Q*(5*l),J+=z>>>13,z&=8191;let G=J+N*l+k*c+M*a+K*(5*y)+P*(5*h);J=G>>>13,G&=8191,G+=j*(5*m)+U*(5*f)+q*(5*p)+F*(5*d)+Q*(5*u),J+=G>>>13,G&=8191;let H=J+N*u+k*l+M*c+K*a+P*(5*y);J=H>>>13,H&=8191,H+=j*(5*h)+U*(5*m)+q*(5*f)+F*(5*p)+Q*(5*d),J+=H>>>13,H&=8191;let L=J+N*d+k*u+M*l+K*c+P*a;J=L>>>13,L&=8191,L+=j*(5*y)+U*(5*h)+q*(5*m)+F*(5*f)+Q*(5*p),J+=L>>>13,L&=8191;let B=J+N*p+k*d+M*u+K*l+P*c;J=B>>>13,B&=8191,B+=j*a+U*(5*y)+q*(5*h)+F*(5*m)+Q*(5*f),J+=B>>>13,B&=8191;let ie=J+N*f+k*p+M*d+K*u+P*l;J=ie>>>13,ie&=8191,ie+=j*c+U*a+q*(5*y)+F*(5*h)+Q*(5*m),J+=ie>>>13,ie&=8191;let xe=J+N*m+k*f+M*p+K*d+P*u;J=xe>>>13,xe&=8191,xe+=j*l+U*c+q*a+F*(5*y)+Q*(5*h),J+=xe>>>13,xe&=8191;let Ne=J+N*h+k*m+M*f+K*p+P*d;J=Ne>>>13,Ne&=8191,Ne+=j*u+U*l+q*c+F*a+Q*(5*y),J+=Ne>>>13,Ne&=8191;let bt=J+N*y+k*h+M*m+K*f+P*p;J=bt>>>13,bt&=8191,bt+=j*d+U*u+q*l+F*c+Q*a,J+=bt>>>13,bt&=8191,J=(J<<2)+J|0,J=J+W|0,W=J&8191,J=J>>>13,z+=J,s[0]=W,s[1]=z,s[2]=G,s[3]=H,s[4]=L,s[5]=B,s[6]=ie,s[7]=xe,s[8]=Ne,s[9]=bt}finalize(){let{h:e,pad:r}=this,n=new Uint16Array(10),i=e[1]>>>13;e[1]&=8191;for(let a=2;a<10;a++)e[a]+=i,i=e[a]>>>13,e[a]&=8191;e[0]+=i*5,i=e[0]>>>13,e[0]&=8191,e[1]+=i,i=e[1]>>>13,e[1]&=8191,e[2]+=i,n[0]=e[0]+5,i=n[0]>>>13,n[0]&=8191;for(let a=1;a<10;a++)n[a]=e[a]+i,i=n[a]>>>13,n[a]&=8191;n[9]-=8192;let s=(i^1)-1;for(let a=0;a<10;a++)n[a]&=s;s=~s;for(let a=0;a<10;a++)e[a]=e[a]&s|n[a];e[0]=(e[0]|e[1]<<13)&65535,e[1]=(e[1]>>>3|e[2]<<10)&65535,e[2]=(e[2]>>>6|e[3]<<7)&65535,e[3]=(e[3]>>>9|e[4]<<4)&65535,e[4]=(e[4]>>>12|e[5]<<1|e[6]<<14)&65535,e[5]=(e[6]>>>2|e[7]<<11)&65535,e[6]=(e[7]>>>5|e[8]<<8)&65535,e[7]=(e[8]>>>8|e[9]<<5)&65535;let o=e[0]+r[0];e[0]=o&65535;for(let a=1;a<8;a++)o=(e[a]+r[a]|0)+(o>>>16)|0,e[a]=o&65535;Ll(n)}update(e){GH(this),Dn(e),e=hv(e);let{buffer:r,blockLen:n}=this,i=e.length;for(let s=0;s<i;){let o=Math.min(n-this.pos,i-s);if(o===n){for(;n<=i-s;s+=n)this.process(e,s);continue}r.set(e.subarray(s,s+o),this.pos),this.pos+=o,s+=o,this.pos===n&&(this.process(r,0,!1),this.pos=0)}return this}destroy(){this.destroyed=!0,Ll(this.h,this.r,this.buffer,this.pad)}digestInto(e){GH(this),_fe(e,this),this.finished=!0;let{buffer:r,h:n}=this,{pos:i}=this;if(i){for(r[i++]=1;i<16;i++)r[i]=0;this.process(r,0,!0)}this.finalize();let s=0;for(let o=0;o<8;o++)e[s++]=n[o]>>>0,e[s++]=n[o]>>>8}digest(){let{buffer:e,outputLen:r}=this;this.digestInto(e);let n=e.slice(0,r);return this.destroy(),n}},Lfe=Ofe(32,t=>new ZH(t))});function snt(t,e,r,n,i,s=20){let o=t[0],a=t[1],c=t[2],l=t[3],u=e[0],d=e[1],p=e[2],f=e[3],m=e[4],h=e[5],y=e[6],g=e[7],b=i,v=r[0],_=r[1],w=r[2],S=o,x=a,O=c,N=l,k=u,M=d,K=p,P=f,j=m,U=h,q=y,F=g,Q=b,J=v,W=_,z=w;for(let H=0;H<s;H+=2)S=S+k|0,Q=Le(Q^S,16),j=j+Q|0,k=Le(k^j,12),S=S+k|0,Q=Le(Q^S,8),j=j+Q|0,k=Le(k^j,7),x=x+M|0,J=Le(J^x,16),U=U+J|0,M=Le(M^U,12),x=x+M|0,J=Le(J^x,8),U=U+J|0,M=Le(M^U,7),O=O+K|0,W=Le(W^O,16),q=q+W|0,K=Le(K^q,12),O=O+K|0,W=Le(W^O,8),q=q+W|0,K=Le(K^q,7),N=N+P|0,z=Le(z^N,16),F=F+z|0,P=Le(P^F,12),N=N+P|0,z=Le(z^N,8),F=F+z|0,P=Le(P^F,7),S=S+M|0,z=Le(z^S,16),q=q+z|0,M=Le(M^q,12),S=S+M|0,z=Le(z^S,8),q=q+z|0,M=Le(M^q,7),x=x+K|0,Q=Le(Q^x,16),F=F+Q|0,K=Le(K^F,12),x=x+K|0,Q=Le(Q^x,8),F=F+Q|0,K=Le(K^F,7),O=O+P|0,J=Le(J^O,16),j=j+J|0,P=Le(P^j,12),O=O+P|0,J=Le(J^O,8),j=j+J|0,P=Le(P^j,7),N=N+k|0,W=Le(W^N,16),U=U+W|0,k=Le(k^U,12),N=N+k|0,W=Le(W^N,8),U=U+W|0,k=Le(k^U,7);let G=0;n[G++]=o+S|0,n[G++]=a+x|0,n[G++]=c+O|0,n[G++]=l+N|0,n[G++]=u+k|0,n[G++]=d+M|0,n[G++]=p+K|0,n[G++]=f+P|0,n[G++]=m+j|0,n[G++]=h+U|0,n[G++]=y+q|0,n[G++]=g+F|0,n[G++]=b+Q|0,n[G++]=v+J|0,n[G++]=_+W|0,n[G++]=w+z|0}function ont(t,e,r,n){let i=ws(t[0]),s=ws(t[1]),o=ws(t[2]),a=ws(t[3]),c=ws(e[0]),l=ws(e[1]),u=ws(e[2]),d=ws(e[3]),p=ws(e[4]),f=ws(e[5]),m=ws(e[6]),h=ws(e[7]),y=ws(r[0]),g=ws(r[1]),b=ws(r[2]),v=ws(r[3]);for(let w=0;w<20;w+=2)i=i+c|0,y=Le(y^i,16),p=p+y|0,c=Le(c^p,12),i=i+c|0,y=Le(y^i,8),p=p+y|0,c=Le(c^p,7),s=s+l|0,g=Le(g^s,16),f=f+g|0,l=Le(l^f,12),s=s+l|0,g=Le(g^s,8),f=f+g|0,l=Le(l^f,7),o=o+u|0,b=Le(b^o,16),m=m+b|0,u=Le(u^m,12),o=o+u|0,b=Le(b^o,8),m=m+b|0,u=Le(u^m,7),a=a+d|0,v=Le(v^a,16),h=h+v|0,d=Le(d^h,12),a=a+d|0,v=Le(v^a,8),h=h+v|0,d=Le(d^h,7),i=i+l|0,v=Le(v^i,16),m=m+v|0,l=Le(l^m,12),i=i+l|0,v=Le(v^i,8),m=m+v|0,l=Le(l^m,7),s=s+u|0,y=Le(y^s,16),h=h+y|0,u=Le(u^h,12),s=s+u|0,y=Le(y^s,8),h=h+y|0,u=Le(u^h,7),o=o+d|0,g=Le(g^o,16),p=p+g|0,d=Le(d^p,12),o=o+d|0,g=Le(g^o,8),p=p+g|0,d=Le(d^p,7),a=a+c|0,b=Le(b^a,16),f=f+b|0,c=Le(c^f,12),a=a+c|0,b=Le(b^a,8),f=f+b|0,c=Le(c^f,7);let _=0;n[_++]=i,n[_++]=s,n[_++]=o,n[_++]=a,n[_++]=y,n[_++]=g,n[_++]=b,n[_++]=v,Yu(n)}function Kfe(t,e,r,n,i){i!==void 0&&Dn(i,void 0,"AAD");let s=t(e,r,lnt),o=Rfe(n.length,i?i.length:0,!0),a=Lfe.create(s);i&&Ufe(a,i),Ufe(a,n),a.update(o);let c=a.digest();return Ll(s,o),c}var ant,cnt,Ufe,lnt,unt,XH,qfe=I(()=>{Mfe();jfe();z0();ant=Dfe(snt,{counterRight:!1,counterLength:8,extendNonceFn:ont,allowShortKeys:!1}),cnt=new Uint8Array(16),Ufe=(t,e)=>{t.update(e);let r=e.length%16;r&&t.update(cnt.subarray(r))},lnt=new Uint8Array(32);unt=t=>(e,r,n)=>({encrypt(s,o){let a=s.length;o=F0(a+16,o,!1),o.set(s);let c=o.subarray(0,-16);t(e,r,c,c,1);let l=Kfe(t,e,r,c,n);return o.set(l,a),Ll(l),o},decrypt(s,o){o=F0(s.length-16,o,!1);let a=s.subarray(0,-16),c=s.subarray(-16),l=Kfe(t,e,r,a,n);if(!Afe(c,l))throw Ll(l),new Error("invalid tag");return o.set(s.subarray(0,-16)),t(e,r,o,o,1),Ll(l),o}}),XH=kfe({blockSize:64,nonceLength:24,tagLength:16},unt(ant))});function dnt(t){if(!t.startsWith(zfe))return null;let e=4,r=t.indexOf("$",e);if(r===-1)return null;let n=parseInt(t.slice(e,r),10);return!Number.isInteger(n)||n<0?null:{version:n,ciphertext:t.slice(r+1)}}function pnt(t,e){return`${zfe}${t}$${e}`}async function Ffe(t,e){let r=await op("SHA-256").digest(t),n=Tfe(e);return VH(YH(XH)(new Uint8Array(r)).encrypt(n))}async function QH(t,e){let r=await op("SHA-256").digest(t),n=wfe(e),i=YH(XH)(new Uint8Array(r));return new TextDecoder().decode(i.decrypt(n))}var zfe,_C,EC,SC=I(()=>{b0();K0();q0();qfe();z0();zfe="$ba$";_C=async({key:t,data:e})=>{if(typeof t=="string")return Ffe(t,e);let r=t.keys.get(t.currentVersion);if(!r)throw new Error(`Secret version ${t.currentVersion} not found in keys`);let n=await Ffe(r,e);return pnt(t.currentVersion,n)},EC=async({key:t,data:e})=>{if(typeof t=="string")return QH(t,e);let r=dnt(e);if(r){let n=t.keys.get(r.version);if(!n)throw new Error(`Secret version ${r.version} not found in keys (key may have been retired)`);return QH(n,r.ciphertext)}if(t.legacySecret)return QH(t.legacySecret,e);throw new Error("Cannot decrypt legacy bare-hex payload: no legacy secret available. Set BETTER_AUTH_SECRET for backwards compatibility.")}});var Zs,eW=I(()=>{Zs=t=>{let e=(t.plugins??[]).reduce((d,p)=>{let f=p.schema;if(!f)return d;for(let[m,h]of Object.entries(f))d[m]={fields:{...d[m]?.fields,...h.fields},modelName:h.modelName||m};return d},{}),r=t.rateLimit?.storage==="database",n={rateLimit:{modelName:t.rateLimit?.modelName||"rateLimit",fields:{key:{type:"string",unique:!0,required:!0,fieldName:t.rateLimit?.fields?.key||"key"},count:{type:"number",required:!0,fieldName:t.rateLimit?.fields?.count||"count"},lastRequest:{type:"number",bigint:!0,required:!0,fieldName:t.rateLimit?.fields?.lastRequest||"lastRequest",defaultValue:()=>Date.now()}}}},{user:i,session:s,account:o,verification:a,...c}=e,l={verification:{modelName:t.verification?.modelName||"verification",fields:{identifier:{type:"string",required:!0,fieldName:t.verification?.fields?.identifier||"identifier",index:!0},value:{type:"string",required:!0,fieldName:t.verification?.fields?.value||"value"},expiresAt:{type:"date",required:!0,fieldName:t.verification?.fields?.expiresAt||"expiresAt"},createdAt:{type:"date",required:!0,defaultValue:()=>new Date,fieldName:t.verification?.fields?.createdAt||"createdAt"},updatedAt:{type:"date",required:!0,defaultValue:()=>new Date,onUpdate:()=>new Date,fieldName:t.verification?.fields?.updatedAt||"updatedAt"},...a?.fields,...t.verification?.additionalFields},order:4}},u={session:{modelName:t.session?.modelName||"session",fields:{expiresAt:{type:"date",required:!0,fieldName:t.session?.fields?.expiresAt||"expiresAt"},token:{type:"string",required:!0,fieldName:t.session?.fields?.token||"token",unique:!0},createdAt:{type:"date",required:!0,fieldName:t.session?.fields?.createdAt||"createdAt",defaultValue:()=>new Date},updatedAt:{type:"date",required:!0,fieldName:t.session?.fields?.updatedAt||"updatedAt",onUpdate:()=>new Date},ipAddress:{type:"string",required:!1,fieldName:t.session?.fields?.ipAddress||"ipAddress"},userAgent:{type:"string",required:!1,fieldName:t.session?.fields?.userAgent||"userAgent"},userId:{type:"string",fieldName:t.session?.fields?.userId||"userId",references:{model:t.user?.modelName||"user",field:"id",onDelete:"cascade"},required:!0,index:!0},...s?.fields,...t.session?.additionalFields},order:2}};return{user:{modelName:t.user?.modelName||"user",fields:{name:{type:"string",required:!0,fieldName:t.user?.fields?.name||"name",sortable:!0},email:{type:"string",unique:!0,required:!0,fieldName:t.user?.fields?.email||"email",sortable:!0},emailVerified:{type:"boolean",defaultValue:!1,required:!0,fieldName:t.user?.fields?.emailVerified||"emailVerified",input:!1},image:{type:"string",required:!1,fieldName:t.user?.fields?.image||"image"},createdAt:{type:"date",defaultValue:()=>new Date,required:!0,fieldName:t.user?.fields?.createdAt||"createdAt"},updatedAt:{type:"date",defaultValue:()=>new Date,onUpdate:()=>new Date,required:!0,fieldName:t.user?.fields?.updatedAt||"updatedAt"},...i?.fields,...t.user?.additionalFields},order:1},...!t.secondaryStorage||t.session?.storeSessionInDatabase?u:{},account:{modelName:t.account?.modelName||"account",fields:{accountId:{type:"string",required:!0,fieldName:t.account?.fields?.accountId||"accountId"},providerId:{type:"string",required:!0,fieldName:t.account?.fields?.providerId||"providerId"},userId:{type:"string",references:{model:t.user?.modelName||"user",field:"id",onDelete:"cascade"},required:!0,fieldName:t.account?.fields?.userId||"userId",index:!0},accessToken:{type:"string",required:!1,returned:!1,fieldName:t.account?.fields?.accessToken||"accessToken"},refreshToken:{type:"string",required:!1,returned:!1,fieldName:t.account?.fields?.refreshToken||"refreshToken"},idToken:{type:"string",required:!1,returned:!1,fieldName:t.account?.fields?.idToken||"idToken"},accessTokenExpiresAt:{type:"date",required:!1,returned:!1,fieldName:t.account?.fields?.accessTokenExpiresAt||"accessTokenExpiresAt"},refreshTokenExpiresAt:{type:"date",required:!1,returned:!1,fieldName:t.account?.fields?.refreshTokenExpiresAt||"refreshTokenExpiresAt"},scope:{type:"string",required:!1,fieldName:t.account?.fields?.scope||"scope"},password:{type:"string",required:!1,returned:!1,fieldName:t.account?.fields?.password||"password"},createdAt:{type:"date",required:!0,fieldName:t.account?.fields?.createdAt||"createdAt",defaultValue:()=>new Date},updatedAt:{type:"date",required:!0,fieldName:t.account?.fields?.updatedAt||"updatedAt",onUpdate:()=>new Date},...o?.fields,...t.account?.additionalFields},order:3},...!t.secondaryStorage||t.verification?.storeInDatabase?l:{},...c,...r?n:{}}}});var Gh,Ju,gv=I(()=>{Gh=le(require("zod"),1),Ju=Gh.object({id:Gh.string(),createdAt:Gh.date().default(()=>new Date),updatedAt:Gh.date().default(()=>new Date)})});var Va,Bfe,Hfe=I(()=>{gv();Va=le(require("zod"),1),Bfe=Ju.extend({providerId:Va.string(),accountId:Va.string(),userId:Va.coerce.string(),accessToken:Va.string().nullish(),refreshToken:Va.string().nullish(),idToken:Va.string().nullish(),accessTokenExpiresAt:Va.date().nullish(),refreshTokenExpiresAt:Va.date().nullish(),scope:Va.string().nullish(),password:Va.string().nullish()})});var Vh,Wfe,$fe=I(()=>{Vh=le(require("zod"),1),Wfe=Vh.object({key:Vh.string(),count:Vh.number(),lastRequest:Vh.number()})});var jf,Gfe,Vfe=I(()=>{gv();jf=le(require("zod"),1),Gfe=Ju.extend({userId:jf.coerce.string(),expiresAt:jf.date(),token:jf.string(),ipAddress:jf.string().nullish(),userAgent:jf.string().nullish()})});var yv,Yfe,Jfe=I(()=>{gv();yv=le(require("zod"),1),Yfe=Ju.extend({email:yv.string().transform(t=>t.toLowerCase()),emailVerified:yv.boolean().default(!1),name:yv.string(),image:yv.string().nullish()})});var H0,Zfe,Xfe=I(()=>{gv();H0=le(require("zod"),1),Zfe=Ju.extend({value:H0.string(),expiresAt:H0.date(),identifier:H0.string()})});var tW={};ui(tW,{accountSchema:()=>Bfe,coreSchema:()=>Ju,getAuthTables:()=>Zs,rateLimitSchema:()=>Wfe,sessionSchema:()=>Gfe,userSchema:()=>Yfe,verificationSchema:()=>Zfe});var cp=I(()=>{eW();gv();Hfe();$fe();Vfe();Jfe();Xfe()});function Xs(t,e){if(!t||!e)return t;let r=Object.entries(e).filter(([,{returned:n}])=>n===!1).map(([n])=>n);return Object.entries(structuredClone(t)).filter(([n])=>!r.includes(n)).reduce((n,[i,s])=>({...n,[i]:s}),{})}var wC=I(()=>{});function Uf(t,e,r){let n=`${e}:${r}`;rW.has(t)||rW.set(t,new Map);let i=rW.get(t);if(i.has(n))return i.get(n);let s=r==="output"?Zs(t)[e]?.fields??{}:{},o=e==="user"||e==="session"||e==="account"?t[e]?.additionalFields:void 0,a={...s,...o??{}};for(let c of t.plugins||[])c.schema&&c.schema[e]&&(a={...a,...c.schema[e].fields});return i.set(n,a),a}function Br(t,e){return Xs(e,Uf(t,"user","output"))}function Wi(t,e){return Xs(e,Uf(t,"session","output"))}function TC(t,e){let{accessToken:r,refreshToken:n,idToken:i,accessTokenExpiresAt:s,refreshTokenExpiresAt:o,password:a,...c}=Xs(e,Uf(t,"account","output"));return c}function bv(t,e){let r=e.action||"create",n=e.fields,i=Object.create(null);for(let s in n){if(s in t){if(n[s].input===!1){if(n[s].defaultValue!==void 0&&r!=="update"){i[s]=n[s].defaultValue;continue}if(t[s])throw D.from("BAD_REQUEST",{...ae.FIELD_NOT_ALLOWED,message:`${s} is not allowed to be set`});continue}if(n[s].validator?.input&&t[s]!==void 0){let o=n[s].validator.input["~standard"].validate(t[s]);if(o instanceof Promise)throw D.from("INTERNAL_SERVER_ERROR",ae.ASYNC_VALIDATION_NOT_SUPPORTED);if("issues"in o&&o.issues)throw D.from("BAD_REQUEST",{...ae.VALIDATION_ERROR,message:o.issues[0]?.message||"Validation Error"});i[s]=o.value;continue}if(n[s].transform?.input&&t[s]!==void 0){i[s]=n[s].transform?.input(t[s]);continue}i[s]=t[s];continue}if(n[s].defaultValue!==void 0&&r==="create"){if(typeof n[s].defaultValue=="function"){i[s]=n[s].defaultValue();continue}i[s]=n[s].defaultValue;continue}if(n[s].required&&r==="create")throw D.from("BAD_REQUEST",{...ae.MISSING_FIELD,message:`${s} is required`})}return i}function vv(t,e={},r){return bv(e,{fields:Uf(t,"user","input"),action:r})}function Qfe(t,e){let r=Uf(t,"user","input");return bv(e||{},{fields:r})}function eme(t,e){return bv(e,{fields:Uf(t,"account","input")})}function xC(t,e,r){return bv(e,{fields:Uf(t,"session","input"),action:r})}function IC(t){let e=Uf(t,"session","input"),r={};for(let n in e)e[n].defaultValue!==void 0&&(r[n]=typeof e[n].defaultValue=="function"?e[n].defaultValue():e[n].defaultValue);return r}function AC(t,e){if(!e)return t;for(let r in e){let n=e[r]?.modelName;n&&(t[r].modelName=n);for(let i in t[r].fields){let s=e[r]?.fields?.[i];s&&(t[r].fields[i].fieldName=s)}}return t}var rW,jl=I(()=>{cp();rt();wC();rW=new WeakMap});var xo,Yh=I(()=>{xo=(t,e="ms")=>new Date(Date.now()+(e==="sec"?t*1e3:t))});function _v(t){return!!t&&(typeof t=="object"||typeof t=="function")&&typeof t.then=="function"}var OC=I(()=>{});function mnt(t){let e=fnt.exec(t);if(!e||e[4]&&e[1])throw new TypeError(`Invalid time string format: "${t}". Use formats like "7d", "30m", "1 hour", etc.`);let r=parseFloat(e[2]),n=e[3].toLowerCase(),i;switch(n){case"years":case"year":case"yrs":case"yr":case"y":i=r*315576e5;break;case"months":case"month":case"mo":i=r*2592e6;break;case"weeks":case"week":case"w":i=r*6048e5;break;case"days":case"day":case"d":i=r*864e5;break;case"hours":case"hour":case"hrs":case"hr":case"h":i=r*36e5;break;case"minutes":case"minute":case"mins":case"min":case"m":i=r*6e4;break;case"seconds":case"second":case"secs":case"sec":case"s":i=r*1e3;break;default:throw new TypeError(`Unknown time unit: "${n}"`)}return e[1]==="-"||e[4]==="ago"?-i:i}function tme(t){return Math.round(mnt(t)/1e3)}var fnt,rme=I(()=>{fnt=/^(\+|\-)? ?(\d+|\d+\.\d+) ?(seconds?|secs?|s|minutes?|mins?|m|hours?|hrs?|h|days?|d|weeks?|w|months?|mo|years?|yrs?|y)(?: (ago|from now))?$/i});var nme,ime=I(()=>{nme="__Secure-"});function sme(t){if(typeof t=="string"&&hnt.test(t)){let e=new Date(t);if(!isNaN(e.getTime()))return e}return t}function nW(t){if(t==null)return t;if(typeof t=="string")return sme(t);if(t instanceof Date)return t;if(Array.isArray(t))return t.map(nW);if(typeof t=="object"){let e={};for(let r of Object.keys(t))e[r]=nW(t[r]);return e}return t}function lr(t){try{return typeof t!="string"?t==null?null:nW(t):JSON.parse(t,(e,r)=>sme(r))}catch(e){return De.error("Error parsing JSON",{error:e}),null}}var hnt,lp=I(()=>{bs();hnt=/^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}(?:\.\d+)?Z$/});function gnt(t){let e=t.headers?.get("cookie");if(!e)return{};let r={},n=e.split("; ");for(let i of n){let[s,...o]=i.split("=");s&&o.length>0&&(r[s]=o.join("="))}return r}function ome(t){let e=t.split("."),r=e[e.length-1],n=parseInt(r||"0",10);return isNaN(n)?0:n}function ynt(t,e){let r={},n=gnt(e);for(let[i,s]of Object.entries(n))i.startsWith(t)&&(r[i]=s);return r}function bnt(t){return Object.keys(t).sort((e,r)=>ome(e)-ome(r)).map(e=>t[e]).join("")}function vnt(t,e,r,n){let i=Math.ceil(e.value.length/iW);if(i===1)return r[e.name]=e.value,[e];let s=[];for(let o=0;o<i;o++){let a=`${e.name}.${o}`,c=o*iW,l=e.value.substring(c,c+iW);s.push({...e,name:a,value:l}),r[a]=l}return n.debug(`CHUNKING_${t.toUpperCase()}_COOKIE`,{message:`${t} cookie exceeds allowed ${oW} bytes.`,emptyCookieSize:sW,valueSize:e.value.length,chunkCount:i,chunks:s.map(o=>o.value.length+sW)}),s}function ame(t,e){let r={};for(let n in t)r[n]={name:n,value:"",attributes:{...e,maxAge:0}};return r}function CC(t,e){let r=t.getCookie(e);if(r)return r;let n=[],i=t.headers?.get("cookie");if(!i)return null;let s={},o=i.split("; ");for(let a of o){let[c,...l]=a.split("=");c&&l.length>0&&(s[c]=l.join("="))}for(let[a,c]of Object.entries(s))if(a.startsWith(e+".")){let l=a.split(".").at(-1),u=parseInt(l||"0",10);isNaN(u)||n.push({index:u,value:c})}return n.length>0?(n.sort((a,c)=>a.index-c.index),n.map(a=>a.value).join("")):null}async function Kf(t,e){let r=t.context.authCookies.accountData,n={maxAge:300,...r.attributes},i=await gC(e,t.context.secretConfig,"better-auth-account",n.maxAge);if(i.length>oW){let s=kC(r.name,n,t),o=s.chunk(i,n);s.setCookies(o)}else{let s=kC(r.name,n,t);if(s.hasChunks()){let o=s.clean();s.setCookies(o)}t.setCookie(r.name,i,n)}}async function Ev(t){let e=CC(t,t.context.authCookies.accountData.name);if(e){let r=lr(await j0(e,t.context.secretConfig,"better-auth-account"));if(r)return r}return null}var Jh,oW,sW,iW,cme,RC,kC,lme,W0=I(()=>{U0();lp();Jh=le(require("zod"),1),oW=4096,sW=200,iW=oW-sW;cme=t=>(e,r,n)=>{let i=ynt(e,n),s=n.context.logger;return{getValue(){return bnt(i)},hasChunks(){return Object.keys(i).length>0},chunk(o,a){let c=ame(i,r);for(let d in i)delete i[d];let l=c,u=vnt(t,{name:e,value:o,attributes:{...r,...a}},i,s);for(let d of u)l[d.name]=d;return Object.values(l)},clean(){let o=ame(i,r);for(let a in i)delete i[a];return Object.values(o)},setCookies(o){for(let a of o)n.setCookie(a.name,a.value,a.attributes)}}},RC=cme("Session"),kC=cme("Account");lme=Jh.optional(Jh.object({disableCookieCache:Jh.coerce.boolean().meta({description:"Disable cookie cache and fetch session from database"}).optional(),disableRefresh:Jh.coerce.boolean().meta({description:"Disable session refresh. Useful for checking session status, without updating the session"}).optional()}))});var aW,_nt,cW,lW=I(()=>{aW=new Map,_nt=new TextEncoder,cW={decode:(t,e="utf-8")=>(aW.has(e)||aW.set(e,new TextDecoder(e)),aW.get(e).decode(t)),encode:_nt.encode}});var Ent,uW,ume=I(()=>{Ent="0123456789abcdef",uW={encode:t=>{if(typeof t=="string"&&(t=new TextEncoder().encode(t)),t.byteLength===0)return"";let e=new Uint8Array(t),r="";for(let n of e)r+=n.toString(16).padStart(2,"0");return r},decode:t=>{if(!t)return"";if(typeof t=="string"){if(t.length%2!==0)throw new Error("Invalid hexadecimal string");if(!new RegExp(`^[${Ent}]+$`).test(t))throw new Error("Invalid hexadecimal string");let e=new Uint8Array(t.length/2);for(let r=0;r<t.length;r+=2)e[r/2]=parseInt(t.slice(r,r+2),16);return new TextDecoder().decode(e)}return new TextDecoder().decode(t)}}});var NC,dW=I(()=>{ume();pa();K0();NC=(t="SHA-256",e="none")=>{let r={importKey:async(n,i)=>Ml().importKey("raw",typeof n=="string"?new TextEncoder().encode(n):n,{name:"HMAC",hash:{name:t}},!1,[i]),sign:async(n,i)=>{typeof n=="string"&&(n=await r.importKey(n,"sign"));let s=await Ml().sign("HMAC",n,typeof i=="string"?new TextEncoder().encode(i):i);return e==="hex"?uW.encode(s):e==="base64"||e==="base64url"||e==="base64urlnopad"?da.encode(s,{padding:e!=="base64urlnopad"}):s},verify:async(n,i,s)=>(typeof n=="string"&&(n=await r.importKey(n,"verify")),e==="hex"&&(s=uW.decode(s)),(e==="base64"||e==="base64url"||e==="base64urlnopad")&&(s=await Hi.decode(s)),Ml().verify("HMAC",n,typeof s=="string"?new TextEncoder().encode(s):s,typeof i=="string"?new TextEncoder().encode(i):i))};return r}});function $0(t){let e=typeof t.baseURL=="string"?t.baseURL:void 0,r=typeof t.baseURL=="object"&&t.baseURL!==null?t.baseURL.protocol:void 0,n=(t.advanced?.useSecureCookies!==void 0?t.advanced?.useSecureCookies:r==="https"||r!=="http"&&(e?e.startsWith("https://"):xf))?nme:"",i=!!t.advanced?.crossSubDomainCookies?.enabled,s=i?t.advanced?.crossSubDomainCookies?.domain||(e?new URL(e).hostname:void 0):void 0;if(i&&!s&&!Wa(t.baseURL))throw new me("baseURL is required when crossSubdomainCookies are enabled.");function o(a,c={}){let l=t.advanced?.cookiePrefix||"better-auth",u=t.advanced?.cookies?.[a]?.name||`${l}.${a}`,d=t.advanced?.cookies?.[a]?.attributes??{};return{name:`${n}${u}`,attributes:{secure:!!n,sameSite:"lax",path:"/",httpOnly:!0,...i?{domain:s}:{},...t.advanced?.defaultCookieAttributes,...c,...d}}}return o}function PC(t){let e=$0(t),r=e("session_token",{maxAge:t.session?.expiresIn||tme("7d")}),n=e("session_data",{maxAge:t.session?.cookieCache?.maxAge||300}),i=e("account_data",{maxAge:t.session?.cookieCache?.maxAge||300}),s=e("dont_remember");return{sessionToken:{name:r.name,attributes:r.attributes},sessionData:{name:n.name,attributes:n.attributes},dontRememberToken:{name:s.name,attributes:s.attributes},accountData:{name:i.name,attributes:i.attributes}}}async function G0(t,e,r){if(!t.context.options.session?.cookieCache?.enabled)return;let n=Xs(e.session,t.context.options.session?.additionalFields),i=Br(t.context.options,e.user),s=t.context.options.session?.cookieCache?.version,o="1";if(s){if(typeof s=="string")o=s;else if(typeof s=="function"){let p=s(e.session,e.user);o=_v(p)?await p:p}}let a={session:n,user:i,updatedAt:Date.now(),version:o},c={...t.context.authCookies.sessionData.attributes,maxAge:r?void 0:t.context.authCookies.sessionData.attributes.maxAge},l=xo(c.maxAge||60,"sec").getTime(),u=t.context.options.session?.cookieCache?.strategy||"compact",d;if(u==="jwe"?d=await gC(a,t.context.secretConfig,"better-auth-session",c.maxAge||300):u==="jwt"?d=await hC(a,t.context.secret,c.maxAge||300):d=da.encode(JSON.stringify({session:a,expiresAt:l,signature:await NC("SHA-256","base64urlnopad").sign(t.context.secret,JSON.stringify({...a,expiresAt:l}))}),{padding:!1}),d.length>4093){let p=RC(t.context.authCookies.sessionData.name,c,t),f=p.chunk(d,c);p.setCookies(f)}else{let p=RC(t.context.authCookies.sessionData.name,c,t);if(p.hasChunks()){let f=p.clean();p.setCookies(f)}t.setCookie(t.context.authCookies.sessionData.name,d,c)}if(t.context.options.account?.storeAccountCookie){let p=await Ev(t);p&&await Kf(t,p)}}async function jr(t,e,r,n){let i=await t.getSignedCookie(t.context.authCookies.dontRememberToken.name,t.context.secret);r=r!==void 0?r:!!i;let s=t.context.authCookies.sessionToken.attributes,o=r?void 0:t.context.sessionConfig.expiresIn;await t.setSignedCookie(t.context.authCookies.sessionToken.name,e.session.token,t.context.secret,{...s,maxAge:o,...n}),r&&await t.setSignedCookie(t.context.authCookies.dontRememberToken.name,"true",t.context.secret,t.context.authCookies.dontRememberToken.attributes),await G0(t,e,r),t.context.setNewSession(e)}function fa(t,e){t.setCookie(e.name,"",{...e.attributes,maxAge:0})}function qf(t,e){if(fa(t,t.context.authCookies.sessionToken),fa(t,t.context.authCookies.sessionData),t.context.options.account?.storeAccountCookie){fa(t,t.context.authCookies.accountData);let i=kC(t.context.authCookies.accountData.name,t.context.authCookies.accountData.attributes,t),s=i.clean();i.setCookies(s)}t.context.oauthConfig.storeStateStrategy==="cookie"&&fa(t,t.context.createAuthCookie("oauth_state"));let r=RC(t.context.authCookies.sessionData.name,t.context.authCookies.sessionData.attributes,t),n=r.clean();r.setCookies(n),e||fa(t,t.context.authCookies.dontRememberToken)}var Io=I(()=>{Kh();U0();jl();Yh();OC();rme();ime();W0();vs();rt();wC();pa();lW();dW()});async function pme(t,e,r){let n=tp(32);if(t.context.oauthConfig.storeStateStrategy==="cookie"){let o={...e,oauthState:n},a=await _C({key:t.context.secretConfig,data:JSON.stringify(o)}),c=t.context.createAuthCookie(r?.cookieName??"oauth_state",{maxAge:600});return t.setCookie(c.name,a,c.attributes),{state:n,codeVerifier:e.codeVerifier}}let i=t.context.createAuthCookie(r?.cookieName??"state",{maxAge:300});await t.setSignedCookie(i.name,n,t.context.secret,i.attributes);let s=new Date;if(s.setMinutes(s.getMinutes()+10),!await t.context.internalAdapter.createVerificationValue({value:JSON.stringify({...e,oauthState:n}),identifier:n,expiresAt:s}))throw new Zu("Unable to create verification. Make sure the database adapter is properly working and there is a verification table in the database",{code:"state_generation_error"});return{state:n,codeVerifier:e.codeVerifier}}async function fme(t,e,r){let n=t.context.oauthConfig.storeStateStrategy,i;if(n==="cookie"){let s=t.context.createAuthCookie(r?.cookieName??"oauth_state"),o=t.getCookie(s.name);if(!o)throw new Zu("State mismatch: auth state cookie not found",{code:"state_mismatch",details:{state:e}});try{let a=await EC({key:t.context.secretConfig,data:o});i=dme.parse(JSON.parse(a))}catch(a){throw new Zu("State invalid: Failed to decrypt or parse auth state",{code:"state_invalid",details:{state:e},cause:a})}if(!i.oauthState||i.oauthState!==e)throw new Zu("State mismatch: OAuth state parameter does not match stored state",{code:"state_security_mismatch",details:{state:e}});fa(t,s)}else{let s=await t.context.internalAdapter.findVerificationValue(e);if(!s)throw new Zu("State mismatch: verification not found",{code:"state_mismatch",details:{state:e}});if(i=dme.parse(JSON.parse(s.value)),i.oauthState!==void 0&&i.oauthState!==e)throw new Zu("State mismatch: OAuth state parameter does not match stored state",{code:"state_security_mismatch",details:{state:e}});let o=t.context.createAuthCookie(r?.cookieName??"state"),a=await t.getSignedCookie(o.name,t.context.secret);if(!(r?.skipStateCookieCheck??t.context.oauthConfig.skipStateCookieCheck)&&(!a||a!==e))throw new Zu("State mismatch: State not persisted correctly",{code:"state_security_mismatch",details:{state:e}});fa(t,o),await t.context.internalAdapter.deleteVerificationByIdentifier(e)}if(i.expiresAt<Date.now())throw new Zu("Invalid state: request expired",{code:"state_mismatch",details:{expiresAt:i.expiresAt}});return i}var xs,dme,Zu,mme=I(()=>{b0();SC();Io();rt();xs=le(require("zod"),1),dme=xs.looseObject({callbackURL:xs.string(),codeVerifier:xs.string(),errorURL:xs.string().optional(),newUserURL:xs.string().optional(),expiresAt:xs.number(),oauthState:xs.string().optional(),link:xs.object({email:xs.string(),userId:xs.coerce.string()}).optional(),requestSignUp:xs.boolean().optional()}),Zu=class extends me{code;details;constructor(t,e){super(t,e),this.code=e.code,this.details=e.details}}});function Zh(){return globalThis[V0]||(globalThis[V0]={version:pW,epoch:1,context:Snt},Y0=globalThis[V0]),Y0=globalThis[V0],Y0.version!==pW&&(Y0.version=pW,Y0.epoch++),globalThis[V0]}function fW(){return Zh().version}var V0,Y0,Snt,pW,J0=I(()=>{V0=Symbol.for("better-auth:global"),Y0=null,Snt={},pW="1.6.10"});async function Sv(){let t=await wnt;if(t===null)throw new Error("getAsyncLocalStorage is only available in server code");return t}var wnt,DC=I(()=>{wnt=import("node:async_hooks").then(t=>t.AsyncLocalStorage).catch(t=>{if("AsyncLocalStorage"in globalThis)return globalThis.AsyncLocalStorage;if(typeof window<"u")return null;throw console.warn("[better-auth] Warning: AsyncLocalStorage is not available in this environment. Some features may not work as expected."),console.warn("[better-auth] Please read more about this warning at https://better-auth.com/docs/installation#mount-handler"),console.warn("[better-auth] If you are using Cloudflare Workers, please see: https://developers.cloudflare.com/workers/configuration/compatibility-flags/#nodejs-compatibility-flag"),t})});async function up(){let t=(await hme()).getStore();if(!t)throw new Error("No auth context found. Please make sure you are calling this function within a `runWithEndpointContext` callback.");return t}async function wv(t,e){return(await hme()).run(t,e)}var hme,mW=I(()=>{J0();DC();hme=async()=>{let t=Zh();if(!t.context.endpointContextAsyncStorage){let e=await Sv();t.context.endpointContextAsyncStorage=new e}return t.context.endpointContextAsyncStorage}});async function yW(){return(await gW()).getStore()!==void 0}async function hW(){let t=(await gW()).getStore();if(!t)throw new Error("No request state found. Please make sure you are calling this function within a `runWithRequestState` callback.");return t}async function bW(t,e){return(await gW()).run(t,e)}function Z0(t){let e=Object.freeze({});return{get ref(){return e},async get(){let r=await hW();if(!r.has(e)){let n=await t();return r.set(e,n),n}return r.get(e)},async set(r){(await hW()).set(e,r)}}}var gW,gme=I(()=>{J0();DC();gW=async()=>{let t=Zh();if(!t.context.requestStateAsyncStorage){let e=await Sv();t.context.requestStateAsyncStorage=new e}return t.context.requestStateAsyncStorage}});var MC,Ue,vW,X0,Xh,yme=I(()=>{J0();DC();MC=async()=>{let t=Zh();if(!t.context.adapterAsyncStorage){let e=await Sv();t.context.adapterAsyncStorage=new e}return t.context.adapterAsyncStorage},Ue=async t=>MC().then(e=>e.getStore()?.adapter||t).catch(()=>t),vW=async(t,e)=>{let r=!1;return MC().then(async n=>{r=!0;let i=[],s,o,a=!1;try{s=await n.run({adapter:t,pendingHooks:i},e)}catch(c){o=c,a=!0}for(let c of i)await c();if(a)throw o;return s}).catch(n=>{if(!r)return e();throw n})},X0=async(t,e)=>{let r=!0;return MC().then(async n=>{r=!0;let i=[],s,o,a=!1;try{s=await t.transaction(async c=>n.run({adapter:c,pendingHooks:i},e))}catch(c){a=!0,o=c}for(let c of i)await c();if(a)throw o;return s}).catch(n=>{if(!r)return e();throw n})},Xh=async t=>MC().then(e=>{let r=e.getStore();if(r)r.pendingHooks.push(t);else return t()}).catch(()=>t())});var Xu=I(()=>{J0();mW();gme();yme()});var tZt,_W,bme=I(()=>{Xu();({get:tZt,set:_W}=Z0(()=>null))});async function LC(t,e,r){let n=t.body?.callbackURL||t.context.options.baseURL;if(!n)throw D.from("BAD_REQUEST",ae.CALLBACK_URL_REQUIRED);let i=tp(128),s={...r||{},callbackURL:n,codeVerifier:i,errorURL:t.body?.errorCallbackURL,newUserURL:t.body?.newUserCallbackURL,link:e,expiresAt:Date.now()+600*1e3,requestSignUp:t.body?.requestSignUp};await _W(s);try{return pme(t,s)}catch(o){throw t.context.logger.error("Failed to create verification",o),new D("INTERNAL_SERVER_ERROR",{message:"Unable to create verification",cause:o})}}async function vme(t){let e=t.query.state||t.body?.state,r=t.context.options.onAPIError?.errorURL||`${t.context.baseURL}/error`,n;try{n=await fme(t,e)}catch(i){throw t.context.logger.error("Failed to parse state",i),i instanceof Zu&&i.code==="state_security_mismatch"?t.redirect(`${r}?error=state_mismatch`):t.redirect(`${r}?error=please_restart_the_process`)}return n.errorURL||(n.errorURL=r),n&&await _W(n),n}var jC=I(()=>{b0();bme();mme();rt()});var Tv,UC=I(()=>{Tv={scope:"server"}});async function _me(t,e){let r=t.headers.get("content-type")||"",n=r.toLowerCase();if(t.body){if(e&&e.length>0&&!e.some(i=>{let s=n.split(";")[0].trim(),o=i.toLowerCase().trim();return s===o||s.includes(o)}))throw n?new ua(415,{message:`Content-Type "${r}" is not allowed. Allowed types: ${e.join(", ")}`,code:"UNSUPPORTED_MEDIA_TYPE"}):new ua(415,{message:`Content-Type is required. Allowed types: ${e.join(", ")}`,code:"UNSUPPORTED_MEDIA_TYPE"});if(Tnt.test(n))return await t.json();if(n.includes("application/x-www-form-urlencoded")){let i=await t.formData(),s={};return i.forEach((o,a)=>{s[a]=o.toString()}),s}if(n.includes("multipart/form-data")){let i=await t.formData(),s={};return i.forEach((o,a)=>{s[a]=o}),s}return n.includes("text/plain")?await t.text():n.includes("application/octet-stream")?await t.arrayBuffer():n.includes("application/pdf")||n.includes("image/")||n.includes("video/")?await t.blob():n.includes("application/stream")||t.body instanceof ReadableStream?t.body:await t.text()}}function dp(t){return t instanceof ua||t?.name==="APIError"}function Eme(t){try{return t.includes("%")?decodeURIComponent(t):t}catch{return t}}async function Sme(t){try{return{data:await t,error:null}}catch(e){return{data:null,error:e}}}function KC(t){return t instanceof Request||Object.prototype.toString.call(t)==="[object Request]"}var Tnt,Qh=I(()=>{If();Tnt=/^application\/([a-z0-9.+-]*\+)?json/i});function xnt(t){if(t===void 0)return!1;let e=typeof t;return e==="string"||e==="number"||e==="boolean"||e===null?!0:e!=="object"?!1:Array.isArray(t)?!0:t.buffer?!1:t.constructor&&t.constructor.name==="Object"||typeof t.toJSON=="function"}function Int(t,e,r){let n=0,i=new WeakMap;return JSON.stringify(t,(o,a)=>{if(typeof a=="bigint")return a.toString();if(typeof a=="object"&&a!==null){if(i.has(a))return`[Circular ref-${i.get(a)}]`;i.set(a,n++)}return e?e(o,a):a},r)}function Ant(t){return!t||typeof t!="object"?!1:"_flag"in t&&t._flag==="json"}function EW(t){for(let e of Ont)t.delete(e)}function Ul(t,e){if(t instanceof Response){if(e?.headers){let i=new Headers(e.headers);EW(i),i.forEach((s,o)=>{t.headers.set(o,s)})}return t}if(Ant(t)){let i=t.body,s=t.routerResponse;if(s instanceof Response)return s;let o=new Headers;if(s?.headers){let a=new Headers(s.headers);for(let[c,l]of a.entries())a.set(c,l)}if(t.headers)for(let[a,c]of new Headers(t.headers).entries())o.set(a,c);if(e?.headers){let a=new Headers(e.headers);EW(a);for(let[c,l]of a.entries())o.set(c,l)}return o.set("Content-Type","application/json"),new Response(JSON.stringify(i),{...s,headers:o,status:t.status??e?.status??s?.status,statusText:e?.statusText??s?.statusText})}if(dp(t))return Ul(t.body,{status:e?.status??t.statusCode,statusText:t.status.toString(),headers:e?.headers||t.headers});let r=t,n=new Headers(e?.headers);return EW(n),t?typeof t=="string"?(r=t,n.set("Content-Type","text/plain")):t instanceof ArrayBuffer||ArrayBuffer.isView(t)?(r=t,n.set("Content-Type","application/octet-stream")):t instanceof Blob?(r=t,n.set("Content-Type",t.type||"application/octet-stream")):t instanceof FormData?r=t:t instanceof URLSearchParams?(r=t,n.set("Content-Type","application/x-www-form-urlencoded")):t instanceof ReadableStream?(r=t,n.set("Content-Type","application/octet-stream")):xnt(t)&&(r=Int(t),n.set("Content-Type","application/json")):(t===null&&(r=JSON.stringify(null)),n.set("content-type","application/json")),new Response(r,{...e,headers:n})}var Ont,qC=I(()=>{If();Qh();Ont=new Set(["host","user-agent","referer","from","expect","authorization","proxy-authorization","cookie","origin","accept-charset","accept-encoding","accept-language","if-match","if-none-match","if-modified-since","if-unmodified-since","if-range","range","max-forwards","connection","keep-alive","transfer-encoding","te","upgrade","trailer","proxy-connection","content-length"])});var SW,wW,wme,knt,Tme,TW=I(()=>{K0();SW={name:"HMAC",hash:"SHA-256"},wW=async t=>{let e=typeof t=="string"?new TextEncoder().encode(t):t;return await Ml().importKey("raw",e,SW,!1,["sign","verify"])},wme=async(t,e,r)=>{try{let n=atob(t),i=new Uint8Array(n.length);for(let s=0,o=n.length;s<o;s++)i[s]=n.charCodeAt(s);return await Ml().verify(SW,r,i,new TextEncoder().encode(e))}catch{return!1}},knt=async(t,e)=>{let r=await wW(e),n=await Ml().sign(SW.name,r,new TextEncoder().encode(t));return btoa(String.fromCharCode(...new Uint8Array(n)))},Tme=async(t,e)=>{let r=await knt(t,e);return t=`${t}.${r}`,t=encodeURIComponent(t),t}});function xW(t){if(typeof t!="string")throw new TypeError("argument str must be a string");let e=new Map,r=0;for(;r<t.length;){let n=t.indexOf("=",r);if(n===-1)break;let i=t.indexOf(";",r);if(i===-1)i=t.length;else if(i<n){r=t.lastIndexOf(";",n-1)+1;continue}let s=t.slice(r,n).trim();if(!e.has(s)){let o=t.slice(n+1,i).trim();o.codePointAt(0)===34&&(o=o.slice(1,-1)),e.set(s,Eme(o))}r=i+1}return e}var FC,xme,IW,AW,OW=I(()=>{Qh();TW();FC=(t,e)=>{let r=t;if(e)if(e==="secure")r="__Secure-"+t;else if(e==="host")r="__Host-"+t;else return;return r};xme=(t,e,r={})=>{let n;if(r?.prefix==="secure"?n=`${`__Secure-${t}`}=${e}`:r?.prefix==="host"?n=`${`__Host-${t}`}=${e}`:n=`${t}=${e}`,t.startsWith("__Secure-")&&!r.secure&&(r.secure=!0),t.startsWith("__Host-")&&(r.secure||(r.secure=!0),r.path!=="/"&&(r.path="/"),r.domain&&(r.domain=void 0)),r&&typeof r.maxAge=="number"&&r.maxAge>=0){if(r.maxAge>3456e4)throw new Error("Cookies Max-Age SHOULD NOT be greater than 400 days (34560000 seconds) in duration.");n+=`; Max-Age=${Math.floor(r.maxAge)}`}if(r.domain&&r.prefix!=="host"&&(n+=`; Domain=${r.domain}`),r.path&&(n+=`; Path=${r.path}`),r.expires){if(r.expires.getTime()-Date.now()>3456e7)throw new Error("Cookies Expires SHOULD NOT be greater than 400 days (34560000 seconds) in the future.");n+=`; Expires=${r.expires.toUTCString()}`}return r.httpOnly&&(n+="; HttpOnly"),r.secure&&(n+="; Secure"),r.sameSite&&(n+=`; SameSite=${r.sameSite.charAt(0).toUpperCase()+r.sameSite.slice(1)}`),r.partitioned&&(r.secure||(r.secure=!0),n+="; Partitioned"),n},IW=(t,e,r)=>(e=encodeURIComponent(e),xme(t,e,r)),AW=async(t,e,r,n)=>(e=await Tme(e,r),xme(t,e,n))});async function Ame(t,e={}){let r={body:e.body,query:e.query};if(t.body){let n=await t.body["~standard"].validate(e.body);if(n.issues)return{data:null,error:Ime(n.issues,"body")};r.body=n.value}if(t.query){let n=await t.query["~standard"].validate(e.query);if(n.issues)return{data:null,error:Ime(n.issues,"query")};r.query=n.value}return t.requireHeaders&&!e.headers?{data:null,error:{message:"Headers is required",issues:[]}}:t.requireRequest&&!e.request?{data:null,error:{message:"Request is required",issues:[]}}:{data:r,error:null}}function Ime(t,e){return{message:t.map(r=>`[${r.path?.length?`${e}.`+r.path.map(n=>typeof n=="object"?n.key:n).join("."):e}] ${r.message}`).join("; "),issues:t}}var Ome=I(()=>{});var Q0,zC=I(()=>{If();Qh();Ome();TW();OW();Q0=async(t,{options:e,path:r})=>{let n=new Headers,i,{data:s,error:o}=await Ame(e,t);if(o)throw new g0(o.message,o.issues);let a="headers"in t?t.headers instanceof Headers?t.headers:new Headers(t.headers):"request"in t&&KC(t.request)?t.request.headers:null,c=a?.get("cookie"),l=c?xW(c):void 0,u={...t,body:s.body,query:s.query,path:t.path||r||"virtual:",context:"context"in t&&t.context?t.context:{},returned:void 0,headers:t?.headers,request:t?.request,params:"params"in t?t.params:void 0,method:t.method??(Array.isArray(e.method)?e.method[0]:e.method==="*"?"GET":e.method),setHeader:(d,p)=>{n.set(d,p)},getHeader:d=>a?a.get(d):null,getCookie:(d,p)=>{let f=FC(d,p);return f&&l?.get(f)||null},getSignedCookie:async(d,p,f)=>{let m=FC(d,f);if(!m)return null;let h=l?.get(m);if(!h)return null;let y=h.lastIndexOf(".");if(y<1)return null;let g=h.substring(0,y),b=h.substring(y+1);return b.length!==44||!b.endsWith("=")?null:await wme(b,g,await wW(p))?g:!1},setCookie:(d,p,f)=>{let m=IW(d,p,f);return n.append("set-cookie",m),m},setSignedCookie:async(d,p,f,m)=>{let h=await AW(d,p,f,m);return n.append("set-cookie",h),h},redirect:d=>(n.set("location",d),new ua("FOUND",void 0,n)),error:(d,p,f)=>new ua(d,p,f),setStatus:d=>{i=d},json:(d,p)=>t.asResponse?{body:p?.body||d,routerResponse:p,_flag:"json"}:d,responseHeaders:n,get responseStatus(){return i}};for(let d of e.use||[]){let p=await d({...u,returnHeaders:!0,asResponse:!1});p.response&&Object.assign(u.context,p.response),p.headers&&p.headers.forEach((f,m)=>{u.responseHeaders.set(m,f)})}return u}});function Ff(t,e,r){let n=typeof t=="string"?t:void 0,i=typeof e=="object"?e:t,s=typeof e=="function"?e:r;if((i.method==="GET"||i.method==="HEAD")&&i.body)throw new UR("Body is not allowed with GET or HEAD methods");if(n&&/\/{2,}/.test(n))throw new UR("Path cannot contain consecutive slashes");let o=async(...a)=>{let c=a[0]||{},{data:l,error:u}=await Sme(Q0(c,{options:i,path:n}));if(u)throw u instanceof g0?(i.onValidationError&&await i.onValidationError({message:u.message,issues:u.issues}),new ua(400,{message:u.message,code:"VALIDATION_ERROR"})):u;let d=await s(l).catch(async m=>{if(dp(m)){let h=i.onAPIError;if(h&&await h(m),c.asResponse)return m}throw m}),p=l.responseHeaders,f=l.responseStatus;return c.asResponse?Ul(d,{headers:p,status:f}):c.returnHeaders?c.returnStatus?{headers:p,response:d,status:f}:{headers:p,response:d}:c.returnStatus?{response:d,status:f}:d};return o.options=i,o.path=n,o}var BC=I(()=>{If();Qh();qC();zC();Ff.create=t=>(e,r,n)=>Ff(e,{...r,use:[...r?.use||[],...t?.use||[]]},n)});function zf(t,e){let r=async n=>{let i=n,s=typeof t=="function"?t:e,o=await Q0(i,{options:typeof t=="function"?{}:t,path:"/"});if(!s)throw new Error("handler must be defined");try{let a=await s(o),c=o.responseHeaders;return i.returnHeaders?{headers:c,response:a}:a}catch(a){throw dp(a)&&Object.defineProperty(a,Xd,{enumerable:!1,configurable:!0,get(){return o.responseHeaders}}),a}};return r.options=typeof t=="function"?{}:t,r}var kme=I(()=>{If();Qh();zC();BC();zf.create=t=>{function e(r,n){if(typeof r=="function")return zf({use:t?.use},r);if(!n)throw new Error("Middleware handler is required");return zf({...r,method:"*",use:[...t?.use||[],...r.use||[]]},n)}return e}});function Nme(t){switch(t.constructor.name){case"ZodString":return"string";case"ZodNumber":return"number";case"ZodBoolean":return"boolean";case"ZodObject":return"object";case"ZodArray":return"array";default:return"string"}}function Rme(t){let e=[];return t.metadata?.openapi?.parameters?(e.push(...t.metadata.openapi.parameters),e):(t.query instanceof pp.ZodObject&&Object.entries(t.query.shape).forEach(([r,n])=>{n instanceof pp.ZodObject&&e.push({name:r,in:"query",schema:{type:Nme(n),..."minLength"in n&&n.minLength?{minLength:n.minLength}:{},description:n.description}})}),e)}function Rnt(t){if(t.metadata?.openapi?.requestBody)return t.metadata.openapi.requestBody;if(t.body&&(t.body instanceof pp.ZodObject||t.body instanceof pp.ZodOptional)){let e=t.body.shape;if(!e)return;let r={},n=[];return Object.entries(e).forEach(([i,s])=>{s instanceof pp.ZodObject&&(r[i]={type:Nme(s),description:s.description},s instanceof pp.ZodOptional||n.push(i))}),{required:t.body instanceof pp.ZodOptional?!1:!!t.body,content:{"application/json":{schema:{type:"object",properties:r,required:n}}}}}}function Cme(t){return{400:{content:{"application/json":{schema:{type:"object",properties:{message:{type:"string"}},required:["message"]}}},description:"Bad Request. Usually due to missing parameters, or invalid parameters."},401:{content:{"application/json":{schema:{type:"object",properties:{message:{type:"string"}},required:["message"]}}},description:"Unauthorized. Due to missing or invalid authentication."},403:{content:{"application/json":{schema:{type:"object",properties:{message:{type:"string"}}}}},description:"Forbidden. You do not have permission to access this resource or to perform this action."},404:{content:{"application/json":{schema:{type:"object",properties:{message:{type:"string"}}}}},description:"Not Found. The requested resource was not found."},429:{content:{"application/json":{schema:{type:"object",properties:{message:{type:"string"}}}}},description:"Too Many Requests. You have exceeded the rate limit. Try again later."},500:{content:{"application/json":{schema:{type:"object",properties:{message:{type:"string"}}}}},description:"Internal Server Error. This is a problem with the server that you cannot fix."},...t}}async function RW(t,e){let r={schemas:{}};return Object.entries(t).forEach(([n,i])=>{let s=i.options;if(!(!i.path||s.metadata?.SERVER_ONLY)&&(s.method==="GET"&&(kW[i.path]={get:{tags:["Default",...s.metadata?.openapi?.tags||[]],description:s.metadata?.openapi?.description,operationId:s.metadata?.openapi?.operationId,security:[{bearerAuth:[]}],parameters:Rme(s),responses:Cme(s.metadata?.openapi?.responses)}}),s.method==="POST")){let o=Rnt(s);kW[i.path]={post:{tags:["Default",...s.metadata?.openapi?.tags||[]],description:s.metadata?.openapi?.description,operationId:s.metadata?.openapi?.operationId,security:[{bearerAuth:[]}],parameters:Rme(s),...o?{requestBody:o}:{requestBody:{content:{"application/json":{schema:{type:"object",properties:{}}}}}},responses:Cme(s.metadata?.openapi?.responses)}}}}),{openapi:"3.1.1",info:{title:"Better Auth",description:"API Reference for your Better Auth Instance",version:"1.1.0"},components:r,security:[{apiKeyCookie:[]}],servers:[{url:e?.url}],tags:[{name:"Default",description:"Default endpoints that are included with Better Auth by default. These endpoints are not part of any plugin."}],paths:kW}}var pp,kW,CW,NW=I(()=>{pp=require("zod"),kW={};CW=(t,e)=>`<!doctype html> | |||
| at `))}function Ide(t,e){class r extends t{#e;constructor(...i){if(srt()){let o=Error.stackTraceLimit;Error.stackTraceLimit=0,super(...i),Error.stackTraceLimit=o}else super(...i);let s=new Error().stack;s&&(this.#e=xde(s.replace(/^Error/,this.name)))}get errorStack(){return this.#e}}return Object.defineProperty(r.prototype,"constructor",{get(){return e},enumerable:!1,configurable:!0}),r}var Ade,Ode,g0,UR,Xd,ua,If=I(()=>{Ade={OK:200,CREATED:201,ACCEPTED:202,NO_CONTENT:204,MULTIPLE_CHOICES:300,MOVED_PERMANENTLY:301,FOUND:302,SEE_OTHER:303,NOT_MODIFIED:304,TEMPORARY_REDIRECT:307,BAD_REQUEST:400,UNAUTHORIZED:401,PAYMENT_REQUIRED:402,FORBIDDEN:403,NOT_FOUND:404,METHOD_NOT_ALLOWED:405,NOT_ACCEPTABLE:406,PROXY_AUTHENTICATION_REQUIRED:407,REQUEST_TIMEOUT:408,CONFLICT:409,GONE:410,LENGTH_REQUIRED:411,PRECONDITION_FAILED:412,PAYLOAD_TOO_LARGE:413,URI_TOO_LONG:414,UNSUPPORTED_MEDIA_TYPE:415,RANGE_NOT_SATISFIABLE:416,EXPECTATION_FAILED:417,"I'M_A_TEAPOT":418,MISDIRECTED_REQUEST:421,UNPROCESSABLE_ENTITY:422,LOCKED:423,FAILED_DEPENDENCY:424,TOO_EARLY:425,UPGRADE_REQUIRED:426,PRECONDITION_REQUIRED:428,TOO_MANY_REQUESTS:429,REQUEST_HEADER_FIELDS_TOO_LARGE:431,UNAVAILABLE_FOR_LEGAL_REASONS:451,INTERNAL_SERVER_ERROR:500,NOT_IMPLEMENTED:501,BAD_GATEWAY:502,SERVICE_UNAVAILABLE:503,GATEWAY_TIMEOUT:504,HTTP_VERSION_NOT_SUPPORTED:505,VARIANT_ALSO_NEGOTIATES:506,INSUFFICIENT_STORAGE:507,LOOP_DETECTED:508,NOT_EXTENDED:510,NETWORK_AUTHENTICATION_REQUIRED:511},Ode=class extends Error{constructor(t="INTERNAL_SERVER_ERROR",e=void 0,r={},n=typeof t=="number"?t:Ade[t]){super(e?.message,e?.cause?{cause:e.cause}:void 0),this.status=t,this.body=e,this.headers=r,this.statusCode=n,this.name="APIError",this.status=t,this.headers=r,this.statusCode=n,this.body=e}},g0=class extends Ode{constructor(t,e){super(400,{message:t,code:"VALIDATION_ERROR"}),this.message=t,this.issues=e,this.issues=e}},UR=class extends Error{constructor(t){super(t),this.name="BetterCallError"}},Xd=Symbol.for("better-call:api-error-headers"),ua=Ide(Ode,Error)});var me,D,rt=I(()=>{Tde();If();me=class extends Error{constructor(t,e){super(t,e),this.name="BetterAuthError",this.message=t,this.stack=""}},D=class SH extends ua{constructor(...e){super(...e)}static fromStatus(e,r){return new SH(e,r)}static from(e,r){return new SH(e,{message:r.message,code:r.code})}}});function ort(t){let e=t.replace(/:\d+$/,"").replace(/^\[|\]$/g,"").toLowerCase();return e==="localhost"||e.endsWith(".localhost")||e==="::1"||e.startsWith("127.")}function art(t){try{return(new URL(t).pathname.replace(/\/+$/,"")||"/")!=="/"}catch{throw new me(`Invalid base URL: ${t}. Please provide a valid base URL.`)}}function crt(t){try{let e=new URL(t);if(e.protocol!=="http:"&&e.protocol!=="https:")throw new me(`Invalid base URL: ${t}. URL must include 'http://' or 'https://'`)}catch(e){throw e instanceof me?e:new me(`Invalid base URL: ${t}. Please provide a valid base URL.`,{cause:e})}}function Qd(t,e="/api/auth"){if(crt(t),art(t))return t;let r=t.replace(/\/+$/,"");return!e||e==="/"?r:(e=e.startsWith("/")?e:`/${e}`,`${r}${e}`)}function y0(t,e){return!t||t.trim()===""?!1:e==="proto"?t==="http"||t==="https":e==="host"?[/\.\./,/\0/,/[\s]/,/^[.]/,/[<>'"]/,/javascript:/i,/file:/i,/data:/i].some(r=>r.test(t))?!1:/^[a-zA-Z0-9]([a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?(\.[a-zA-Z0-9]([a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?)*(:[0-9]{1,5})?$/.test(t)||/^(\d{1,3}\.){3}\d{1,3}(:[0-9]{1,5})?$/.test(t)||/^\[[0-9a-fA-F:]+\](:[0-9]{1,5})?$/.test(t)||/^localhost(:[0-9]{1,5})?$/i.test(t):!1}function ep(t,e,r,n,i){if(t)return Qd(t,e);if(n!==!1){let a=Zt.BETTER_AUTH_URL||Zt.NEXT_PUBLIC_BETTER_AUTH_URL||Zt.PUBLIC_BETTER_AUTH_URL||Zt.NUXT_PUBLIC_BETTER_AUTH_URL||Zt.NUXT_PUBLIC_AUTH_URL||(Zt.BASE_URL!=="/"?Zt.BASE_URL:void 0);if(a)return Qd(a,e)}let s=r?.headers.get("x-forwarded-host"),o=r?.headers.get("x-forwarded-proto");if(s&&o&&i&&y0(o,"proto")&&y0(s,"host")){let Bnt=Zt.BETTER_AUTH_URL||Zt.NEXT_PUBLIC_BETTER_AUTH_URL||Zt.PUBLIC_BETTER_AUTH_URL||Zt.NUXT_PUBLIC_BETTER_AUTH_URL||Zt.NUXT_PUBLIC_AUTH_URL;if(Bnt){try{let Hnt=new URL(Bnt).host;if(Hnt&&s!==Hnt){}}catch{}if(Bnt){try{let Hnt=new URL(Bnt).host;if(!Hnt||s!==Hnt)s=null}catch{s=null}}}if(s)try{return Qd(`${o}://${s}`,e)}catch{}}if(r){let a=Af(r.url);if(!a)throw new me("Could not get origin from request. Please provide a valid base URL.");return Qd(a,e)}if(typeof window<"u"&&window.location)return Qd(window.location.origin,e)}function Af(t){try{let e=new URL(t);return e.origin==="null"?null:e.origin}catch{return null}}function kde(t){try{return new URL(t).protocol}catch{return null}}function Rde(t){try{return new URL(t).host}catch{return null}}function Wa(t){return typeof t=="object"&&t!==null&&"allowedHosts"in t&&Array.isArray(t.allowedHosts)}function Bu(t){if(t instanceof Request)return!0;if(typeof t!="object"||t===null||Object.prototype.toString.call(t)!=="[object Request]")return!1;let e=t;return typeof e.url=="string"&&typeof e.headers=="object"&&e.headers!==null&&typeof e.headers.get=="function"}function Cde(t,e){let r=Bu(t)?t.headers:t;if(e){let i=r.get("x-forwarded-host");if(i&&y0(i,"host"))return i}let n=r.get("host");if(n&&y0(n,"host"))return n;if(Bu(t))try{return new URL(t.url).host}catch{return null}return null}function lrt(t,e,r){if(e==="http"||e==="https")return e;let n=Bu(t)?t.headers:t;if(r){let s=n.get("x-forwarded-proto");if(s&&y0(s,"proto"))return s}if(Bu(t))try{let s=new URL(t.url);if(s.protocol==="http:"||s.protocol==="https:")return s.protocol.slice(0,-1)}catch{}let i=Cde(t,r);return i&&ort(i)?"http":"https"}function drt(t,e,r,n){let i=Cde(e,n);if(!i){if(t.fallback)return Qd(t.fallback,r);throw new me("Could not determine host from request headers. Please provide a fallback URL in your baseURL config.")}if(t.allowedHosts.some(s=>urt(i,s)))return Qd(`${lrt(e,t.protocol,n)}://${i}`,r);if(t.fallback)return Qd(t.fallback,r);throw new me(`Host "${i}" is not in the allowed hosts list. Allowed hosts: ${t.allowedHosts.join(", ")}. Add this host to your allowedHosts config or provide a fallback URL.`)}function Nde(t,e,r,n,i){if(Wa(t))return r?drt(t,r,e,i):t.fallback?Qd(t.fallback,e):ep(void 0,e,void 0,n,i);let s=Bu(r)?r:void 0;return ep(typeof t=="string"?t:void 0,e,s,n,i)}var urt,Kh=I(()=>{PR();vs();rt();urt=(t,e)=>{if(!t||!e)return!1;let r=t.replace(/^https?:\/\//,"").split("/")[0].toLowerCase(),n=e.replace(/^https?:\/\//,"").split("/")[0].toLowerCase();return n.includes("*")||n.includes("?")?Uh(n)(r):r.toLowerCase()===n.toLowerCase()}});function Pde(t){switch(t){case"a-z":return"abcdefghijklmnopqrstuvwxyz";case"A-Z":return"ABCDEFGHIJKLMNOPQRSTUVWXYZ";case"0-9":return"0123456789";case"-_":return"-_";default:throw new Error(`Unsupported alphabet: ${t}`)}}function ev(...t){let e=t.map(Pde).join("");if(e.length===0)throw new Error("No valid characters provided for random string generation.");let r=e.length;return(n,...i)=>{if(n<=0)throw new Error("Length must be a positive integer.");let s=e,o=r;i.length>0&&(s=i.map(Pde).join(""),o=s.length);let a=Math.floor(256/o)*o,c=new Uint8Array(n*2),l=c.length,u="",d=l,p;for(;u.length<n;)d>=l&&(crypto.getRandomValues(c),d=0),p=c[d++],p<a&&(u+=s[p%o]);return u}}var KR=I(()=>{});var tp,b0=I(()=>{KR();tp=ev("a-z","0-9","A-Z","-_")});function prt(t){return t instanceof Uint8Array||ArrayBuffer.isView(t)&&t.constructor.name==="Uint8Array"&&"BYTES_PER_ELEMENT"in t&&t.BYTES_PER_ELEMENT===1}function qR(t,e=""){if(typeof t!="number"){let r=e&&`"${e}" `;throw new TypeError(`${r}expected number, got ${typeof t}`)}if(!Number.isSafeInteger(t)||t<0){let r=e&&`"${e}" `;throw new RangeError(`${r}expected integer >= 0, got ${t}`)}}function Of(t,e,r=""){let n=prt(t),i=t?.length,s=e!==void 0;if(!n||s&&i!==e){let o=r&&`"${r}" `,a=s?` of length ${e}`:"",c=n?`length=${i}`:`type=${typeof t}`,l=o+"expected Uint8Array"+a+", got "+c;throw n?new RangeError(l):new TypeError(l)}return t}function v0(t){if(typeof t!="function"||typeof t.create!="function")throw new TypeError("Hash must wrapped by utils.createHasher");if(qR(t.outputLen),qR(t.blockLen),t.outputLen<1)throw new Error('"outputLen" must be >= 1');if(t.blockLen<1)throw new Error('"blockLen" must be >= 1')}function tv(t,e=!0){if(t.destroyed)throw new Error("Hash instance has been destroyed");if(e&&t.finished)throw new Error("Hash#digest() has already been called")}function FR(t,e){Of(t,void 0,"digestInto() output");let r=e.outputLen;if(t.length<r)throw new RangeError('"digestInto() output" expected to be of length >='+r)}function rp(...t){for(let e=0;e<t.length;e++)t[e].fill(0)}function zR(t){return new DataView(t.buffer,t.byteOffset,t.byteLength)}function Pl(t,e){return t<<32-e|t>>>e}function Dde(t,e={}){let r=(i,s)=>t(s).update(i).digest(),n=t(void 0);return r.outputLen=n.outputLen,r.blockLen=n.blockLen,r.canXOF=n.canXOF,r.create=i=>t(i),Object.assign(r,e),Object.freeze(r)}var Mde,_0=I(()=>{Mde=t=>({oid:Uint8Array.from([6,9,96,134,72,1,101,3,4,2,t])})});var BR,wH,Lde=I(()=>{_0();BR=class{oHash;iHash;blockLen;outputLen;canXOF=!1;finished=!1;destroyed=!1;constructor(e,r){if(v0(e),Of(r,void 0,"key"),this.iHash=e.create(),typeof this.iHash.update!="function")throw new Error("Expected instance of class which extends utils.Hash");this.blockLen=this.iHash.blockLen,this.outputLen=this.iHash.outputLen;let n=this.blockLen,i=new Uint8Array(n);i.set(r.length>n?e.create().update(r).digest():r);for(let s=0;s<i.length;s++)i[s]^=54;this.iHash.update(i),this.oHash=e.create();for(let s=0;s<i.length;s++)i[s]^=106;this.oHash.update(i),rp(i)}update(e){return tv(this),this.iHash.update(e),this}digestInto(e){tv(this),FR(e,this),this.finished=!0;let r=e.subarray(0,this.outputLen);this.iHash.digestInto(r),this.oHash.update(r),this.oHash.digestInto(r),this.destroy()}digest(){let e=new Uint8Array(this.oHash.outputLen);return this.digestInto(e),e}_cloneInto(e){e||=Object.create(Object.getPrototypeOf(this),{});let{oHash:r,iHash:n,finished:i,destroyed:s,blockLen:o,outputLen:a}=this;return e=e,e.finished=i,e.destroyed=s,e.blockLen=o,e.outputLen=a,e.oHash=r._cloneInto(e.oHash),e.iHash=n._cloneInto(e.iHash),e}clone(){return this._cloneInto()}destroy(){this.destroyed=!0,this.oHash.destroy(),this.iHash.destroy()}},wH=(()=>{let t=((e,r,n)=>new BR(e,r).update(n).digest());return t.create=(e,r)=>new BR(e,r),t})()});function frt(t,e,r){return v0(t),r===void 0&&(r=new Uint8Array(t.outputLen)),wH(t,r,e)}function mrt(t,e,r,n=32){v0(t),qR(n,"length"),Of(e,void 0,"prk");let i=t.outputLen;if(e.length<i)throw new Error('"prk" must be at least HashLen octets');if(n>255*i)throw new Error("Length must be <= 255*HashLen");let s=Math.ceil(n/i);r===void 0?r=jde:Of(r,void 0,"info");let o=new Uint8Array(s*i),a=wH.create(t,e),c=a._cloneInto(),l=new Uint8Array(a.outputLen);for(let u=0;u<s;u++)TH[0]=u+1,c.update(u===0?jde:l).update(r).update(TH).digestInto(l),o.set(l,i*u),a._cloneInto(c);return a.destroy(),c.destroy(),rp(l,TH),o.slice(0,n)}var TH,jde,Ude,Kde=I(()=>{Lde();_0();TH=Uint8Array.of(0),jde=Uint8Array.of();Ude=(t,e,r,n,i)=>mrt(t,frt(t,e,r),n,i)});function qde(t,e,r){return t&e^~t&r}function Fde(t,e,r){return t&e^t&r^e&r}var HR,np,zde=I(()=>{_0();HR=class{blockLen;outputLen;canXOF=!1;padOffset;isLE;buffer;view;finished=!1;length=0;pos=0;destroyed=!1;constructor(e,r,n,i){this.blockLen=e,this.outputLen=r,this.padOffset=n,this.isLE=i,this.buffer=new Uint8Array(e),this.view=zR(this.buffer)}update(e){tv(this),Of(e);let{view:r,buffer:n,blockLen:i}=this,s=e.length;for(let o=0;o<s;){let a=Math.min(i-this.pos,s-o);if(a===i){let c=zR(e);for(;i<=s-o;o+=i)this.process(c,o);continue}n.set(e.subarray(o,o+a),this.pos),this.pos+=a,o+=a,this.pos===i&&(this.process(r,0),this.pos=0)}return this.length+=e.length,this.roundClean(),this}digestInto(e){tv(this),FR(e,this),this.finished=!0;let{buffer:r,view:n,blockLen:i,isLE:s}=this,{pos:o}=this;r[o++]=128,rp(this.buffer.subarray(o)),this.padOffset>i-o&&(this.process(n,0),o=0);for(let d=o;d<i;d++)r[d]=0;n.setBigUint64(i-8,BigInt(this.length*8),s),this.process(n,0);let a=zR(e),c=this.outputLen;if(c%4)throw new Error("_sha2: outputLen must be aligned to 32bit");let l=c/4,u=this.get();if(l>u.length)throw new Error("_sha2: outputLen bigger than state");for(let d=0;d<l;d++)a.setUint32(4*d,u[d],s)}digest(){let{buffer:e,outputLen:r}=this;this.digestInto(e);let n=e.slice(0,r);return this.destroy(),n}_cloneInto(e){e||=new this.constructor,e.set(...this.get());let{blockLen:r,buffer:n,length:i,finished:s,destroyed:o,pos:a}=this;return e.destroyed=o,e.finished=s,e.length=i,e.pos=a,i%r&&e.buffer.set(n),e}clone(){return this._cloneInto()}},np=Uint32Array.from([1779033703,3144134277,1013904242,2773480762,1359893119,2600822924,528734635,1541459225])});var hrt,kf,xH,IH,Bde,Hde=I(()=>{zde();_0();hrt=Uint32Array.from([1116352408,1899447441,3049323471,3921009573,961987163,1508970993,2453635748,2870763221,3624381080,310598401,607225278,1426881987,1925078388,2162078206,2614888103,3248222580,3835390401,4022224774,264347078,604807628,770255983,1249150122,1555081692,1996064986,2554220882,2821834349,2952996808,3210313671,3336571891,3584528711,113926993,338241895,666307205,773529912,1294757372,1396182291,1695183700,1986661051,2177026350,2456956037,2730485921,2820302411,3259730800,3345764771,3516065817,3600352804,4094571909,275423344,430227734,506948616,659060556,883997877,958139571,1322822218,1537002063,1747873779,1955562222,2024104815,2227730452,2361852424,2428436474,2756734187,3204031479,3329325298]),kf=new Uint32Array(64),xH=class extends HR{constructor(e){super(64,e,8,!1)}get(){let{A:e,B:r,C:n,D:i,E:s,F:o,G:a,H:c}=this;return[e,r,n,i,s,o,a,c]}set(e,r,n,i,s,o,a,c){this.A=e|0,this.B=r|0,this.C=n|0,this.D=i|0,this.E=s|0,this.F=o|0,this.G=a|0,this.H=c|0}process(e,r){for(let d=0;d<16;d++,r+=4)kf[d]=e.getUint32(r,!1);for(let d=16;d<64;d++){let p=kf[d-15],f=kf[d-2],m=Pl(p,7)^Pl(p,18)^p>>>3,h=Pl(f,17)^Pl(f,19)^f>>>10;kf[d]=h+kf[d-7]+m+kf[d-16]|0}let{A:n,B:i,C:s,D:o,E:a,F:c,G:l,H:u}=this;for(let d=0;d<64;d++){let p=Pl(a,6)^Pl(a,11)^Pl(a,25),f=u+p+qde(a,c,l)+hrt[d]+kf[d]|0,h=(Pl(n,2)^Pl(n,13)^Pl(n,22))+Fde(n,i,s)|0;u=l,l=c,c=a,a=o+f|0,o=s,s=i,i=n,n=f+h|0}n=n+this.A|0,i=i+this.B|0,s=s+this.C|0,o=o+this.D|0,a=a+this.E|0,c=c+this.F|0,l=l+this.G|0,u=u+this.H|0,this.set(n,i,s,o,a,c,l,u)}roundClean(){rp(kf)}destroy(){this.destroyed=!0,this.set(0,0,0,0,0,0,0,0),rp(this.buffer)}},IH=class extends xH{A=np[0]|0;B=np[1]|0;C=np[2]|0;D=np[3]|0;E=np[4]|0;F=np[5]|0;G=np[6]|0;H=np[7]|0;constructor(){super(32)}},Bde=Dde(()=>new IH,Mde(1))});function fi(...t){let e=t.reduce((i,{length:s})=>i+s,0),r=new Uint8Array(e),n=0;for(let i of t)r.set(i,n),n+=i.length;return r}function AH(t,e,r){if(e<0||e>=WR)throw new RangeError(`value must be >= 0 and <= ${WR-1}. Received ${e}`);t.set([e>>>24,e>>>16,e>>>8,e&255],r)}function OH(t){let e=Math.floor(t/WR),r=t%WR,n=new Uint8Array(8);return AH(n,e,0),AH(n,r,4),n}function $R(t){let e=new Uint8Array(4);return AH(e,t),e}function Bn(t){let e=new Uint8Array(t.length);for(let r=0;r<t.length;r++){let n=t.charCodeAt(r);if(n>127)throw new TypeError("non-ASCII string encountered in encode()");e[r]=n}return e}var qh,_s,WR,Vs=I(()=>{qh=new TextEncoder,_s=new TextDecoder,WR=2**32});function Wde(t){if(Uint8Array.prototype.toBase64)return t.toBase64();let e=32768,r=[];for(let n=0;n<t.length;n+=e)r.push(String.fromCharCode.apply(null,t.subarray(n,n+e)));return btoa(r.join(""))}function $de(t){if(Uint8Array.fromBase64)return Uint8Array.fromBase64(t);let e=atob(t),r=new Uint8Array(e.length);for(let n=0;n<e.length;n++)r[n]=e.charCodeAt(n);return r}var Gde=I(()=>{});var E0={};ui(E0,{decode:()=>_o,encode:()=>bn});function _o(t){if(Uint8Array.fromBase64)return Uint8Array.fromBase64(typeof t=="string"?t:_s.decode(t),{alphabet:"base64url"});let e=t;e instanceof Uint8Array&&(e=_s.decode(e)),e=e.replace(/-/g,"+").replace(/_/g,"/");try{return $de(e)}catch{throw new TypeError("The input to be decoded is not correctly encoded.")}}function bn(t){let e=t;return typeof e=="string"&&(e=qh.encode(e)),Uint8Array.prototype.toBase64?e.toBase64({alphabet:"base64url",omitPadding:!0}):Wde(e).replace(/=/g,"").replace(/\+/g,"-").replace(/\//g,"_")}var Ys=I(()=>{Vs();Gde()});function grt(t){return parseInt(t.name.slice(4),10)}function GR(t,e){if(grt(t.hash)!==e)throw Eo(`SHA-${e}`,"algorithm.hash")}function yrt(t){switch(t){case"ES256":return"P-256";case"ES384":return"P-384";case"ES512":return"P-521";default:throw new Error("unreachable")}}function Vde(t,e){if(e&&!t.usages.includes(e))throw new TypeError(`CryptoKey does not support this operation, its usages must include ${e}.`)}function Yde(t,e,r){switch(e){case"HS256":case"HS384":case"HS512":{if(!Hu(t.algorithm,"HMAC"))throw Eo("HMAC");GR(t.algorithm,parseInt(e.slice(2),10));break}case"RS256":case"RS384":case"RS512":{if(!Hu(t.algorithm,"RSASSA-PKCS1-v1_5"))throw Eo("RSASSA-PKCS1-v1_5");GR(t.algorithm,parseInt(e.slice(2),10));break}case"PS256":case"PS384":case"PS512":{if(!Hu(t.algorithm,"RSA-PSS"))throw Eo("RSA-PSS");GR(t.algorithm,parseInt(e.slice(2),10));break}case"Ed25519":case"EdDSA":{if(!Hu(t.algorithm,"Ed25519"))throw Eo("Ed25519");break}case"ML-DSA-44":case"ML-DSA-65":case"ML-DSA-87":{if(!Hu(t.algorithm,e))throw Eo(e);break}case"ES256":case"ES384":case"ES512":{if(!Hu(t.algorithm,"ECDSA"))throw Eo("ECDSA");let n=yrt(e);if(t.algorithm.namedCurve!==n)throw Eo(n,"algorithm.namedCurve");break}default:throw new TypeError("CryptoKey does not support this operation")}Vde(t,r)}function $a(t,e,r){switch(e){case"A128GCM":case"A192GCM":case"A256GCM":{if(!Hu(t.algorithm,"AES-GCM"))throw Eo("AES-GCM");let n=parseInt(e.slice(1,4),10);if(t.algorithm.length!==n)throw Eo(n,"algorithm.length");break}case"A128KW":case"A192KW":case"A256KW":{if(!Hu(t.algorithm,"AES-KW"))throw Eo("AES-KW");let n=parseInt(e.slice(1,4),10);if(t.algorithm.length!==n)throw Eo(n,"algorithm.length");break}case"ECDH":{switch(t.algorithm.name){case"ECDH":case"X25519":break;default:throw Eo("ECDH or X25519")}break}case"PBES2-HS256+A128KW":case"PBES2-HS384+A192KW":case"PBES2-HS512+A256KW":if(!Hu(t.algorithm,"PBKDF2"))throw Eo("PBKDF2");break;case"RSA-OAEP":case"RSA-OAEP-256":case"RSA-OAEP-384":case"RSA-OAEP-512":{if(!Hu(t.algorithm,"RSA-OAEP"))throw Eo("RSA-OAEP");GR(t.algorithm,parseInt(e.slice(9),10)||1);break}default:throw new TypeError("CryptoKey does not support this operation")}Vde(t,r)}var Eo,Hu,Fh=I(()=>{Eo=(t,e="algorithm.name")=>new TypeError(`CryptoKey does not support this operation, its ${e} must be ${t}`),Hu=(t,e)=>t.name===e});function Jde(t,e,...r){if(r=r.filter(Boolean),r.length>2){let n=r.pop();t+=`one of type ${r.join(", ")}, or ${n}.`}else r.length===2?t+=`one of type ${r[0]} or ${r[1]}.`:t+=`of type ${r[0]}.`;return e==null?t+=` Received ${e}`:typeof e=="function"&&e.name?t+=` Received function ${e.name}`:typeof e=="object"&&e!=null&&e.constructor?.name&&(t+=` Received an instance of ${e.constructor.name}`),t}var Wu,kH,rv=I(()=>{Wu=(t,...e)=>Jde("Key must be ",t,...e),kH=(t,e,...r)=>Jde(`Key for the ${t} algorithm must be `,e,...r)});var Si,Es,zh,Bh,Pt,nv,Me,zr,Js,VR,S0,iv,YR,JR,ZR,cn=I(()=>{Si=class extends Error{static code="ERR_JOSE_GENERIC";code="ERR_JOSE_GENERIC";constructor(e,r){super(e,r),this.name=this.constructor.name,Error.captureStackTrace?.(this,this.constructor)}},Es=class extends Si{static code="ERR_JWT_CLAIM_VALIDATION_FAILED";code="ERR_JWT_CLAIM_VALIDATION_FAILED";claim;reason;payload;constructor(e,r,n="unspecified",i="unspecified"){super(e,{cause:{claim:n,reason:i,payload:r}}),this.claim=n,this.reason=i,this.payload=r}},zh=class extends Si{static code="ERR_JWT_EXPIRED";code="ERR_JWT_EXPIRED";claim;reason;payload;constructor(e,r,n="unspecified",i="unspecified"){super(e,{cause:{claim:n,reason:i,payload:r}}),this.claim=n,this.reason=i,this.payload=r}},Bh=class extends Si{static code="ERR_JOSE_ALG_NOT_ALLOWED";code="ERR_JOSE_ALG_NOT_ALLOWED"},Pt=class extends Si{static code="ERR_JOSE_NOT_SUPPORTED";code="ERR_JOSE_NOT_SUPPORTED"},nv=class extends Si{static code="ERR_JWE_DECRYPTION_FAILED";code="ERR_JWE_DECRYPTION_FAILED";constructor(e="decryption operation failed",r){super(e,r)}},Me=class extends Si{static code="ERR_JWE_INVALID";code="ERR_JWE_INVALID"},zr=class extends Si{static code="ERR_JWS_INVALID";code="ERR_JWS_INVALID"},Js=class extends Si{static code="ERR_JWT_INVALID";code="ERR_JWT_INVALID"},VR=class extends Si{static code="ERR_JWK_INVALID";code="ERR_JWK_INVALID"},S0=class extends Si{static code="ERR_JWKS_INVALID";code="ERR_JWKS_INVALID"},iv=class extends Si{static code="ERR_JWKS_NO_MATCHING_KEY";code="ERR_JWKS_NO_MATCHING_KEY";constructor(e="no applicable key found in the JSON Web Key Set",r){super(e,r)}},YR=class extends Si{[Symbol.asyncIterator];static code="ERR_JWKS_MULTIPLE_MATCHING_KEYS";code="ERR_JWKS_MULTIPLE_MATCHING_KEYS";constructor(e="multiple matching keys found in the JSON Web Key Set",r){super(e,r)}},JR=class extends Si{static code="ERR_JWKS_TIMEOUT";code="ERR_JWKS_TIMEOUT";constructor(e="request timed out",r){super(e,r)}},ZR=class extends Si{static code="ERR_JWS_SIGNATURE_VERIFICATION_FAILED";code="ERR_JWS_SIGNATURE_VERIFICATION_FAILED";constructor(e="signature verification failed",r){super(e,r)}}});function sv(t){if(!ip(t))throw new Error("CryptoKey instance expected")}var ip,w0,T0,Hh=I(()=>{ip=t=>{if(t?.[Symbol.toStringTag]==="CryptoKey")return!0;try{return t instanceof CryptoKey}catch{return!1}},w0=t=>t?.[Symbol.toStringTag]==="KeyObject",T0=t=>ip(t)||w0(t)});function QR(t){switch(t){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 Pt(`Unsupported JWE Algorithm: ${t}`)}}function XR(t,e){let r=t.byteLength<<3;if(r!==e)throw new Me(`Invalid Content Encryption Key length. Expected ${e} bits, got ${r} bits`)}function Zde(t){switch(t){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 Pt(`Unsupported JWE Algorithm: ${t}`)}}function Xde(t,e){if(e.length<<3!==Zde(t))throw new Me("Invalid Initialization Vector length")}async function Qde(t,e,r){if(!(e instanceof Uint8Array))throw new TypeError(Wu(e,"Uint8Array"));let n=parseInt(t.slice(1,4),10),i=await crypto.subtle.importKey("raw",e.subarray(n>>3),"AES-CBC",!1,[r]),s=await crypto.subtle.importKey("raw",e.subarray(0,n>>3),{hash:`SHA-${n<<1}`,name:"HMAC"},!1,["sign"]);return{encKey:i,macKey:s,keySize:n}}async function epe(t,e,r){return new Uint8Array((await crypto.subtle.sign("HMAC",t,e)).slice(0,r>>3))}async function vrt(t,e,r,n,i){let{encKey:s,macKey:o,keySize:a}=await Qde(t,r,"encrypt"),c=new Uint8Array(await crypto.subtle.encrypt({iv:n,name:"AES-CBC"},s,e)),l=fi(i,n,c,OH(i.length<<3)),u=await epe(o,l,a);return{ciphertext:c,tag:u,iv:n}}async function _rt(t,e){if(!(t instanceof Uint8Array))throw new TypeError("First argument must be a buffer");if(!(e instanceof Uint8Array))throw new TypeError("Second argument must be a buffer");let r={name:"HMAC",hash:"SHA-256"},n=await crypto.subtle.generateKey(r,!1,["sign"]),i=new Uint8Array(await crypto.subtle.sign(r,n,t)),s=new Uint8Array(await crypto.subtle.sign(r,n,e)),o=0,a=-1;for(;++a<32;)o|=i[a]^s[a];return o===0}async function Ert(t,e,r,n,i,s){let{encKey:o,macKey:a,keySize:c}=await Qde(t,e,"decrypt"),l=fi(s,n,r,OH(s.length<<3)),u=await epe(a,l,c),d;try{d=await _rt(i,u)}catch{}if(!d)throw new nv;let p;try{p=new Uint8Array(await crypto.subtle.decrypt({iv:n,name:"AES-CBC"},o,r))}catch{}if(!p)throw new nv;return p}async function Srt(t,e,r,n,i){let s;r instanceof Uint8Array?s=await crypto.subtle.importKey("raw",r,"AES-GCM",!1,["encrypt"]):($a(r,t,"encrypt"),s=r);let o=new Uint8Array(await crypto.subtle.encrypt({additionalData:i,iv:n,name:"AES-GCM",tagLength:128},s,e)),a=o.slice(-16);return{ciphertext:o.slice(0,-16),tag:a,iv:n}}async function wrt(t,e,r,n,i,s){let o;e instanceof Uint8Array?o=await crypto.subtle.importKey("raw",e,"AES-GCM",!1,["decrypt"]):($a(e,t,"decrypt"),o=e);try{return new Uint8Array(await crypto.subtle.decrypt({additionalData:s,iv:n,name:"AES-GCM",tagLength:128},o,fi(r,i)))}catch{throw new nv}}async function eC(t,e,r,n,i){if(!ip(r)&&!(r instanceof Uint8Array))throw new TypeError(Wu(r,"CryptoKey","KeyObject","Uint8Array","JSON Web Key"));switch(n?Xde(t,n):n=brt(t),t){case"A128CBC-HS256":case"A192CBC-HS384":case"A256CBC-HS512":return r instanceof Uint8Array&&XR(r,parseInt(t.slice(-3),10)),vrt(t,e,r,n,i);case"A128GCM":case"A192GCM":case"A256GCM":return r instanceof Uint8Array&&XR(r,parseInt(t.slice(1,4),10)),Srt(t,e,r,n,i);default:throw new Pt(tpe)}}async function tC(t,e,r,n,i,s){if(!ip(e)&&!(e instanceof Uint8Array))throw new TypeError(Wu(e,"CryptoKey","KeyObject","Uint8Array","JSON Web Key"));if(!n)throw new Me("JWE Initialization Vector missing");if(!i)throw new Me("JWE Authentication Tag missing");switch(Xde(t,n),t){case"A128CBC-HS256":case"A192CBC-HS384":case"A256CBC-HS512":return e instanceof Uint8Array&&XR(e,parseInt(t.slice(-3),10)),Ert(t,e,r,n,i,s);case"A128GCM":case"A192GCM":case"A256GCM":return e instanceof Uint8Array&&XR(e,parseInt(t.slice(1,4),10)),wrt(t,e,r,n,i,s);default:throw new Pt(tpe)}}var Rf,brt,tpe,ov=I(()=>{Vs();Fh();rv();cn();Hh();Rf=t=>crypto.getRandomValues(new Uint8Array(QR(t)>>3));brt=t=>crypto.getRandomValues(new Uint8Array(Zde(t)>>3));tpe="Unsupported JWE Content Encryption Algorithm"});function So(t,e){if(t)throw new TypeError(`${e} can only be called once`)}function wo(t,e,r){try{return _o(t)}catch{throw new r(`Failed to base64url decode the ${e}`)}}async function rC(t,e){let r=`SHA-${t.slice(-3)}`;return new Uint8Array(await crypto.subtle.digest(r,e))}var rpe,sp=I(()=>{Ys();rpe=Symbol()});function vn(t){if(!Trt(t)||Object.prototype.toString.call(t)!=="[object Object]")return!1;if(Object.getPrototypeOf(t)===null)return!0;let e=t;for(;Object.getPrototypeOf(e)!==null;)e=Object.getPrototypeOf(e);return Object.getPrototypeOf(t)===e}function Cf(...t){let e=t.filter(Boolean);if(e.length===0||e.length===1)return!0;let r;for(let n of e){let i=Object.keys(n);if(!r||r.size===0){r=new Set(i);continue}for(let s of i){if(r.has(s))return!1;r.add(s)}}return!0}var Trt,Wh,npe,ipe,spe,Ss=I(()=>{Trt=t=>typeof t=="object"&&t!==null;Wh=t=>vn(t)&&typeof t.kty=="string",npe=t=>t.kty!=="oct"&&(t.kty==="AKP"&&typeof t.priv=="string"||typeof t.d=="string"),ipe=t=>t.kty!=="oct"&&t.d===void 0&&t.priv===void 0,spe=t=>t.kty==="oct"&&typeof t.k=="string"});function ope(t,e){if(t.algorithm.length!==parseInt(e.slice(1,4),10))throw new TypeError(`Invalid key size for alg: ${e}`)}function ape(t,e,r){return t instanceof Uint8Array?crypto.subtle.importKey("raw",t,"AES-KW",!0,[r]):($a(t,e,r),t)}async function x0(t,e,r){let n=await ape(e,t,"wrapKey");ope(n,t);let i=await crypto.subtle.importKey("raw",r,{hash:"SHA-256",name:"HMAC"},!0,["sign"]);return new Uint8Array(await crypto.subtle.wrapKey("raw",i,n,"AES-KW"))}async function I0(t,e,r){let n=await ape(e,t,"unwrapKey");ope(n,t);let i=await crypto.subtle.unwrapKey("raw",r,n,"AES-KW",{hash:"SHA-256",name:"HMAC"},!0,["sign"]);return new Uint8Array(await crypto.subtle.exportKey("raw",i))}var RH=I(()=>{Fh()});function CH(t){return fi($R(t.length),t)}async function Irt(t,e,r){let n=e>>3,i=32,s=Math.ceil(n/i),o=new Uint8Array(s*i);for(let a=1;a<=s;a++){let c=new Uint8Array(4+t.length+r.length);c.set($R(a),0),c.set(t,4),c.set(r,4+t.length);let l=await rC("sha256",c);o.set(l,(a-1)*i)}return o.slice(0,n)}async function NH(t,e,r,n,i=new Uint8Array,s=new Uint8Array){$a(t,"ECDH"),$a(e,"ECDH","deriveBits");let o=CH(Bn(r)),a=CH(i),c=CH(s),l=$R(n),u=new Uint8Array,d=fi(o,a,c,l,u),p=new Uint8Array(await crypto.subtle.deriveBits({name:t.algorithm.name,public:t},e,Art(t)));return Irt(p,n,d)}function Art(t){return t.algorithm.name==="X25519"?256:Math.ceil(parseInt(t.algorithm.namedCurve.slice(-3),10)/8)<<3}function PH(t){switch(t.algorithm.namedCurve){case"P-256":case"P-384":case"P-521":return!0;default:return t.algorithm.name==="X25519"}}var lpe=I(()=>{Vs();Fh();sp()});function krt(t,e){return t instanceof Uint8Array?crypto.subtle.importKey("raw",t,"PBKDF2",!1,["deriveBits"]):($a(t,e,"deriveBits"),t)}async function upe(t,e,r,n){if(!(t instanceof Uint8Array)||t.length<8)throw new Me("PBES2 Salt Input must be 8 or more octets");if(!Number.isSafeInteger(r)||Math.sign(r)!==1)throw new Me("PBES2 Count Input must be a positive integer");let i=Rrt(e,t),s=parseInt(e.slice(13,16),10),o={hash:`SHA-${e.slice(8,11)}`,iterations:r,name:"PBKDF2",salt:i},a=await krt(n,e);return new Uint8Array(await crypto.subtle.deriveBits(o,a,s))}async function dpe(t,e,r,n=2048,i=crypto.getRandomValues(new Uint8Array(16))){let s=await upe(i,t,n,e);return{encryptedKey:await x0(t.slice(-6),s,r),p2c:n,p2s:bn(i)}}async function ppe(t,e,r,n,i){let s=await upe(i,t,n,e);return I0(t.slice(-6),s,r)}var Rrt,fpe=I(()=>{Ys();RH();Fh();Vs();cn();Rrt=(t,e)=>fi(Bn(t),Uint8Array.of(0),e)});function A0(t,e){if(t.startsWith("RS")||t.startsWith("PS")){let{modulusLength:r}=e.algorithm;if(typeof r!="number"||r<2048)throw new TypeError(`${t} requires key modulusLength to be 2048 bits or larger`)}}function mpe(t,e){let r=`SHA-${t.slice(-3)}`;switch(t){case"HS256":case"HS384":case"HS512":return{hash:r,name:"HMAC"};case"PS256":case"PS384":case"PS512":return{hash:r,name:"RSA-PSS",saltLength:parseInt(t.slice(-3),10)>>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:e.namedCurve};case"Ed25519":case"EdDSA":return{name:"Ed25519"};case"ML-DSA-44":case"ML-DSA-65":case"ML-DSA-87":return{name:t};default:throw new Pt(`alg ${t} is not supported either by JOSE or your javascript runtime`)}}async function hpe(t,e,r){if(e instanceof Uint8Array){if(!t.startsWith("HS"))throw new TypeError(Wu(e,"CryptoKey","KeyObject","JSON Web Key"));return crypto.subtle.importKey("raw",e,{hash:`SHA-${t.slice(-3)}`,name:"HMAC"},!1,[r])}return Yde(e,t,r),e}async function gpe(t,e,r){let n=await hpe(t,e,"sign");A0(t,n);let i=await crypto.subtle.sign(mpe(t,n.algorithm),n,r);return new Uint8Array(i)}async function ype(t,e,r,n){let i=await hpe(t,e,"verify");A0(t,i);let s=mpe(t,i.algorithm);try{return await crypto.subtle.verify(s,i,r,n)}catch{return!1}}var nC=I(()=>{cn();Fh();rv()});async function vpe(t,e,r){return $a(e,t,"encrypt"),A0(t,e),new Uint8Array(await crypto.subtle.encrypt(bpe(t),e,r))}async function _pe(t,e,r){return $a(e,t,"decrypt"),A0(t,e),new Uint8Array(await crypto.subtle.decrypt(bpe(t),e,r))}var bpe,Epe=I(()=>{Fh();nC();cn();bpe=t=>{switch(t){case"RSA-OAEP":case"RSA-OAEP-256":case"RSA-OAEP-384":case"RSA-OAEP-512":return"RSA-OAEP";default:throw new Pt(`alg ${t} is not supported either by JOSE or your javascript runtime`)}}});function Prt(t){let e,r;switch(t.kty){case"AKP":{switch(t.alg){case"ML-DSA-44":case"ML-DSA-65":case"ML-DSA-87":e={name:t.alg},r=t.priv?["sign"]:["verify"];break;default:throw new Pt(iC)}break}case"RSA":{switch(t.alg){case"PS256":case"PS384":case"PS512":e={name:"RSA-PSS",hash:`SHA-${t.alg.slice(-3)}`},r=t.d?["sign"]:["verify"];break;case"RS256":case"RS384":case"RS512":e={name:"RSASSA-PKCS1-v1_5",hash:`SHA-${t.alg.slice(-3)}`},r=t.d?["sign"]:["verify"];break;case"RSA-OAEP":case"RSA-OAEP-256":case"RSA-OAEP-384":case"RSA-OAEP-512":e={name:"RSA-OAEP",hash:`SHA-${parseInt(t.alg.slice(-3),10)||1}`},r=t.d?["decrypt","unwrapKey"]:["encrypt","wrapKey"];break;default:throw new Pt(iC)}break}case"EC":{switch(t.alg){case"ES256":case"ES384":case"ES512":e={name:"ECDSA",namedCurve:{ES256:"P-256",ES384:"P-384",ES512:"P-521"}[t.alg]},r=t.d?["sign"]:["verify"];break;case"ECDH-ES":case"ECDH-ES+A128KW":case"ECDH-ES+A192KW":case"ECDH-ES+A256KW":e={name:"ECDH",namedCurve:t.crv},r=t.d?["deriveBits"]:[];break;default:throw new Pt(iC)}break}case"OKP":{switch(t.alg){case"Ed25519":case"EdDSA":e={name:"Ed25519"},r=t.d?["sign"]:["verify"];break;case"ECDH-ES":case"ECDH-ES+A128KW":case"ECDH-ES+A192KW":case"ECDH-ES+A256KW":e={name:t.crv},r=t.d?["deriveBits"]:[];break;default:throw new Pt(iC)}break}default:throw new Pt('Invalid or unsupported JWK "kty" (Key Type) Parameter value')}return{algorithm:e,keyUsages:r}}async function av(t){if(!t.alg)throw new TypeError('"alg" argument is required when "jwk.alg" is not present');let{algorithm:e,keyUsages:r}=Prt(t),n={...t};return n.kty!=="AKP"&&delete n.alg,delete n.use,crypto.subtle.importKey("jwk",n,e,t.ext??!(t.d||t.priv),t.key_ops??r)}var iC,DH=I(()=>{cn();iC='Invalid or unsupported JWK "alg" (Algorithm) Parameter value'});async function $u(t,e){if(t instanceof Uint8Array||ip(t))return t;if(w0(t)){if(t.type==="secret")return t.export();if("toCryptoKey"in t&&typeof t.toCryptoKey=="function")try{return Drt(t,e)}catch(n){if(n instanceof TypeError)throw n}let r=t.export({format:"jwk"});return Spe(t,r,e)}if(Wh(t))return t.k?_o(t.k):Spe(t,t,e,!0);throw new Error("unreachable")}var cv,lv,Spe,Drt,uv=I(()=>{Ss();Ys();DH();Hh();cv="given KeyObject instance cannot be used for this algorithm",Spe=async(t,e,r,n=!1)=>{lv||=new WeakMap;let i=lv.get(t);if(i?.[r])return i[r];let s=await av({...e,alg:r});return n&&Object.freeze(t),i?i[r]=s:lv.set(t,{[r]:s}),s},Drt=(t,e)=>{lv||=new WeakMap;let r=lv.get(t);if(r?.[e])return r[e];let n=t.type==="public",i=!!n,s;if(t.asymmetricKeyType==="x25519"){switch(e){case"ECDH-ES":case"ECDH-ES+A128KW":case"ECDH-ES+A192KW":case"ECDH-ES+A256KW":break;default:throw new TypeError(cv)}s=t.toCryptoKey(t.asymmetricKeyType,i,n?[]:["deriveBits"])}if(t.asymmetricKeyType==="ed25519"){if(e!=="EdDSA"&&e!=="Ed25519")throw new TypeError(cv);s=t.toCryptoKey(t.asymmetricKeyType,i,[n?"verify":"sign"])}switch(t.asymmetricKeyType){case"ml-dsa-44":case"ml-dsa-65":case"ml-dsa-87":{if(e!==t.asymmetricKeyType.toUpperCase())throw new TypeError(cv);s=t.toCryptoKey(t.asymmetricKeyType,i,[n?"verify":"sign"])}}if(t.asymmetricKeyType==="rsa"){let o;switch(e){case"RSA-OAEP":o="SHA-1";break;case"RS256":case"PS256":case"RSA-OAEP-256":o="SHA-256";break;case"RS384":case"PS384":case"RSA-OAEP-384":o="SHA-384";break;case"RS512":case"PS512":case"RSA-OAEP-512":o="SHA-512";break;default:throw new TypeError(cv)}if(e.startsWith("RSA-OAEP"))return t.toCryptoKey({name:"RSA-OAEP",hash:o},i,n?["encrypt"]:["decrypt"]);s=t.toCryptoKey({name:e.startsWith("PS")?"RSA-PSS":"RSASSA-PKCS1-v1_5",hash:o},i,[n?"verify":"sign"])}if(t.asymmetricKeyType==="ec"){let a=new Map([["prime256v1","P-256"],["secp384r1","P-384"],["secp521r1","P-521"]]).get(t.asymmetricKeyDetails?.namedCurve);if(!a)throw new TypeError(cv);let c={ES256:"P-256",ES384:"P-384",ES512:"P-521"};c[e]&&a===c[e]&&(s=t.toCryptoKey({name:"ECDSA",namedCurve:a},i,[n?"verify":"sign"])),e.startsWith("ECDH-ES")&&(s=t.toCryptoKey({name:"ECDH",namedCurve:a},i,n?[]:["deriveBits"]))}if(!s)throw new TypeError(cv);return r?r[e]=s:lv.set(t,{[e]:s}),s}});async function Ga(t,e,r){if(!vn(t))throw new TypeError("JWK must be an object");let n;switch(e??=t.alg,n??=r?.extractable??t.ext,t.kty){case"oct":if(typeof t.k!="string"||!t.k)throw new TypeError('missing "k" (Key Value) Parameter value');return _o(t.k);case"RSA":if("oth"in t&&t.oth!==void 0)throw new Pt('RSA JWK "oth" (Other Primes Info) Parameter value is not supported');return av({...t,alg:e,ext:n});case"AKP":{if(typeof t.alg!="string"||!t.alg)throw new TypeError('missing "alg" (Algorithm) Parameter value');if(e!==void 0&&e!==t.alg)throw new TypeError("JWK alg and alg option value mismatch");return av({...t,ext:n})}case"EC":case"OKP":return av({...t,alg:e,ext:n});default:throw new Pt('Unsupported "kty" (Key Type) Parameter value')}}var sC=I(()=>{Ys();DH();cn();Ss()});async function wpe(t){if(w0(t))if(t.type==="secret")t=t.export();else return t.export({format:"jwk"});if(t instanceof Uint8Array)return{kty:"oct",k:bn(t)};if(!ip(t))throw new TypeError(Wu(t,"CryptoKey","KeyObject","Uint8Array"));if(!t.extractable)throw new TypeError("non-extractable CryptoKey cannot be exported as a JWK");let{ext:e,key_ops:r,alg:n,use:i,...s}=await crypto.subtle.exportKey("jwk",t);return s.kty==="AKP"&&(s.alg=n),s}var Tpe=I(()=>{rv();Ys();Hh()});async function oC(t){return wpe(t)}var MH=I(()=>{Tpe()});async function xpe(t,e,r,n){let i=t.slice(0,7),s=await eC(i,r,e,n,new Uint8Array);return{encryptedKey:s.ciphertext,iv:bn(s.iv),tag:bn(s.tag)}}async function Ipe(t,e,r,n,i){let s=t.slice(0,7);return tC(s,e,r,n,i,new Uint8Array)}var Ape=I(()=>{ov();Ys()});function O0(t){if(t===void 0)throw new Me("JWE Encrypted Key missing")}async function kpe(t,e,r,n,i){switch(t){case"dir":{if(r!==void 0)throw new Me("Encountered unexpected JWE Encrypted Key");return e}case"ECDH-ES":if(r!==void 0)throw new Me("Encountered unexpected JWE Encrypted Key");case"ECDH-ES+A128KW":case"ECDH-ES+A192KW":case"ECDH-ES+A256KW":{if(!vn(n.epk))throw new Me('JOSE Header "epk" (Ephemeral Public Key) missing or invalid');if(sv(e),!PH(e))throw new Pt("ECDH with the provided key is not allowed or not supported by your javascript runtime");let s=await Ga(n.epk,t);sv(s);let o,a;if(n.apu!==void 0){if(typeof n.apu!="string")throw new Me('JOSE Header "apu" (Agreement PartyUInfo) invalid');o=wo(n.apu,"apu",Me)}if(n.apv!==void 0){if(typeof n.apv!="string")throw new Me('JOSE Header "apv" (Agreement PartyVInfo) invalid');a=wo(n.apv,"apv",Me)}let c=await NH(s,e,t==="ECDH-ES"?n.enc:t,t==="ECDH-ES"?QR(n.enc):parseInt(t.slice(-5,-2),10),o,a);return t==="ECDH-ES"?c:(O0(r),I0(t.slice(-6),c,r))}case"RSA-OAEP":case"RSA-OAEP-256":case"RSA-OAEP-384":case"RSA-OAEP-512":return O0(r),sv(e),_pe(t,e,r);case"PBES2-HS256+A128KW":case"PBES2-HS384+A192KW":case"PBES2-HS512+A256KW":{if(O0(r),typeof n.p2c!="number")throw new Me('JOSE Header "p2c" (PBES2 Count) missing or invalid');let s=i?.maxPBES2Count||1e4;if(n.p2c>s)throw new Me('JOSE Header "p2c" (PBES2 Count) out is of acceptable bounds');if(typeof n.p2s!="string")throw new Me('JOSE Header "p2s" (PBES2 Salt) missing or invalid');let o;return o=wo(n.p2s,"p2s",Me),ppe(t,e,r,n.p2c,o)}case"A128KW":case"A192KW":case"A256KW":return O0(r),I0(t,e,r);case"A128GCMKW":case"A192GCMKW":case"A256GCMKW":{if(O0(r),typeof n.iv!="string")throw new Me('JOSE Header "iv" (Initialization Vector) missing or invalid');if(typeof n.tag!="string")throw new Me('JOSE Header "tag" (Authentication Tag) missing or invalid');let s;s=wo(n.iv,"iv",Me);let o;return o=wo(n.tag,"tag",Me),Ipe(t,e,r,s,o)}default:throw new Pt(Ope)}}async function Rpe(t,e,r,n,i={}){let s,o,a;switch(t){case"dir":{a=r;break}case"ECDH-ES":case"ECDH-ES+A128KW":case"ECDH-ES+A192KW":case"ECDH-ES+A256KW":{if(sv(r),!PH(r))throw new Pt("ECDH with the provided key is not allowed or not supported by your javascript runtime");let{apu:c,apv:l}=i,u;i.epk?u=await $u(i.epk,t):u=(await crypto.subtle.generateKey(r.algorithm,!0,["deriveBits"])).privateKey;let{x:d,y:p,crv:f,kty:m}=await oC(u),h=await NH(r,u,t==="ECDH-ES"?e:t,t==="ECDH-ES"?QR(e):parseInt(t.slice(-5,-2),10),c,l);if(o={epk:{x:d,crv:f,kty:m}},m==="EC"&&(o.epk.y=p),c&&(o.apu=bn(c)),l&&(o.apv=bn(l)),t==="ECDH-ES"){a=h;break}a=n||Rf(e);let y=t.slice(-6);s=await x0(y,h,a);break}case"RSA-OAEP":case"RSA-OAEP-256":case"RSA-OAEP-384":case"RSA-OAEP-512":{a=n||Rf(e),sv(r),s=await vpe(t,r,a);break}case"PBES2-HS256+A128KW":case"PBES2-HS384+A192KW":case"PBES2-HS512+A256KW":{a=n||Rf(e);let{p2c:c,p2s:l}=i;({encryptedKey:s,...o}=await dpe(t,r,a,c,l));break}case"A128KW":case"A192KW":case"A256KW":{a=n||Rf(e),s=await x0(t,r,a);break}case"A128GCMKW":case"A192GCMKW":case"A256GCMKW":{a=n||Rf(e);let{iv:c}=i;({encryptedKey:s,...o}=await xpe(t,r,a,c));break}default:throw new Pt(Ope)}return{cek:a,encryptedKey:s,parameters:o}}var Ope,LH=I(()=>{RH();lpe();fpe();Epe();Ys();uv();cn();sp();ov();sC();MH();Ss();Ape();Hh();Ope='Invalid or unsupported "alg" (JWE Algorithm) header value'});function Nf(t,e,r,n,i){if(i.crit!==void 0&&n?.crit===void 0)throw new t('"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(o=>typeof o!="string"||o.length===0))throw new t('"crit" (Critical) Header Parameter MUST be an array of non-empty strings when present');let s;r!==void 0?s=new Map([...Object.entries(r),...e.entries()]):s=e;for(let o of n.crit){if(!s.has(o))throw new Pt(`Extension Header Parameter "${o}" is not recognized`);if(i[o]===void 0)throw new t(`Extension Header Parameter "${o}" is missing`);if(s.get(o)&&n[o]===void 0)throw new t(`Extension Header Parameter "${o}" MUST be integrity protected`)}return new Set(n.crit)}var k0=I(()=>{cn()});function R0(t,e){if(e!==void 0&&(!Array.isArray(e)||e.some(r=>typeof r!="string")))throw new TypeError(`"${t}" option must be an array of strings`);if(e)return new Set(e)}var jH=I(()=>{});function Pf(t,e,r){switch(t.substring(0,2)){case"A1":case"A2":case"di":case"HS":case"PB":Mrt(t,e,r);break;default:Lrt(t,e,r)}}var dv,UH,Mrt,Lrt,C0=I(()=>{rv();Hh();Ss();dv=t=>t?.[Symbol.toStringTag],UH=(t,e,r)=>{if(e.use!==void 0){let n;switch(r){case"sign":case"verify":n="sig";break;case"encrypt":case"decrypt":n="enc";break}if(e.use!==n)throw new TypeError(`Invalid key for this operation, its "use" must be "${n}" when present`)}if(e.alg!==void 0&&e.alg!==t)throw new TypeError(`Invalid key for this operation, its "alg" must be "${t}" when present`);if(Array.isArray(e.key_ops)){let n;switch(!0){case(r==="sign"||r==="verify"):case t==="dir":case t.includes("CBC-HS"):n=r;break;case t.startsWith("PBES2"):n="deriveBits";break;case/^A\d{3}(?:GCM)?(?:KW)?$/.test(t):!t.includes("GCM")&&t.endsWith("KW")?n=r==="encrypt"?"wrapKey":"unwrapKey":n=r;break;case(r==="encrypt"&&t.startsWith("RSA")):n="wrapKey";break;case r==="decrypt":n=t.startsWith("RSA")?"unwrapKey":"deriveBits";break}if(n&&e.key_ops?.includes?.(n)===!1)throw new TypeError(`Invalid key for this operation, its "key_ops" must include "${n}" when present`)}return!0},Mrt=(t,e,r)=>{if(!(e instanceof Uint8Array)){if(Wh(e)){if(spe(e)&&UH(t,e,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(!T0(e))throw new TypeError(kH(t,e,"CryptoKey","KeyObject","JSON Web Key","Uint8Array"));if(e.type!=="secret")throw new TypeError(`${dv(e)} instances for symmetric algorithms must be of type "secret"`)}},Lrt=(t,e,r)=>{if(Wh(e))switch(r){case"decrypt":case"sign":if(npe(e)&&UH(t,e,r))return;throw new TypeError("JSON Web Key for this operation must be a private JWK");case"encrypt":case"verify":if(ipe(e)&&UH(t,e,r))return;throw new TypeError("JSON Web Key for this operation must be a public JWK")}if(!T0(e))throw new TypeError(kH(t,e,"CryptoKey","KeyObject","JSON Web Key"));if(e.type==="secret")throw new TypeError(`${dv(e)} instances for asymmetric algorithms must not be of type "secret"`);if(e.type==="public")switch(r){case"sign":throw new TypeError(`${dv(e)} instances for asymmetric algorithm signing must be of type "private"`);case"decrypt":throw new TypeError(`${dv(e)} instances for asymmetric algorithm decryption must be of type "private"`)}if(e.type==="private")switch(r){case"verify":throw new TypeError(`${dv(e)} instances for asymmetric algorithm verifying must be of type "public"`);case"encrypt":throw new TypeError(`${dv(e)} instances for asymmetric algorithm encryption must be of type "public"`)}}});function Cpe(t){if(typeof globalThis[t]>"u")throw new Pt(`JWE "zip" (Compression Algorithm) Header Parameter requires the ${t} API.`)}async function Npe(t){Cpe("CompressionStream");let e=new CompressionStream("deflate-raw"),r=e.writable.getWriter();r.write(t).catch(()=>{}),r.close().catch(()=>{});let n=[],i=e.readable.getReader();for(;;){let{value:s,done:o}=await i.read();if(o)break;n.push(s)}return fi(...n)}async function Ppe(t,e){Cpe("DecompressionStream");let r=new DecompressionStream("deflate-raw"),n=r.writable.getWriter();n.write(t).catch(()=>{}),n.close().catch(()=>{});let i=[],s=0,o=r.readable.getReader();for(;;){let{value:a,done:c}=await o.read();if(c)break;if(i.push(a),s+=a.byteLength,e!==1/0&&s>e)throw new Me("Decompressed plaintext exceeded the configured limit")}return fi(...i)}var KH=I(()=>{cn();Vs()});async function Dpe(t,e,r){if(!vn(t))throw new Me("Flattened JWE must be an object");if(t.protected===void 0&&t.header===void 0&&t.unprotected===void 0)throw new Me("JOSE Header missing");if(t.iv!==void 0&&typeof t.iv!="string")throw new Me("JWE Initialization Vector incorrect type");if(typeof t.ciphertext!="string")throw new Me("JWE Ciphertext missing or incorrect type");if(t.tag!==void 0&&typeof t.tag!="string")throw new Me("JWE Authentication Tag incorrect type");if(t.protected!==void 0&&typeof t.protected!="string")throw new Me("JWE Protected Header incorrect type");if(t.encrypted_key!==void 0&&typeof t.encrypted_key!="string")throw new Me("JWE Encrypted Key incorrect type");if(t.aad!==void 0&&typeof t.aad!="string")throw new Me("JWE AAD incorrect type");if(t.header!==void 0&&!vn(t.header))throw new Me("JWE Shared Unprotected Header incorrect type");if(t.unprotected!==void 0&&!vn(t.unprotected))throw new Me("JWE Per-Recipient Unprotected Header incorrect type");let n;if(t.protected)try{let _=_o(t.protected);n=JSON.parse(_s.decode(_))}catch{throw new Me("JWE Protected Header is invalid")}if(!Cf(n,t.header,t.unprotected))throw new Me("JWE Protected, JWE Unprotected Header, and JWE Per-Recipient Unprotected Header Parameter names must be disjoint");let i={...n,...t.header,...t.unprotected};if(Nf(Me,new Map,r?.crit,n,i),i.zip!==void 0&&i.zip!=="DEF")throw new Pt('Unsupported JWE "zip" (Compression Algorithm) Header Parameter value.');if(i.zip!==void 0&&!n?.zip)throw new Me('JWE "zip" (Compression Algorithm) Header Parameter MUST be in a protected header.');let{alg:s,enc:o}=i;if(typeof s!="string"||!s)throw new Me("missing JWE Algorithm (alg) in JWE Header");if(typeof o!="string"||!o)throw new Me("missing JWE Encryption Algorithm (enc) in JWE Header");let a=r&&R0("keyManagementAlgorithms",r.keyManagementAlgorithms),c=r&&R0("contentEncryptionAlgorithms",r.contentEncryptionAlgorithms);if(a&&!a.has(s)||!a&&s.startsWith("PBES2"))throw new Bh('"alg" (Algorithm) Header Parameter value not allowed');if(c&&!c.has(o))throw new Bh('"enc" (Encryption Algorithm) Header Parameter value not allowed');let l;t.encrypted_key!==void 0&&(l=wo(t.encrypted_key,"encrypted_key",Me));let u=!1;typeof e=="function"&&(e=await e(n,t),u=!0),Pf(s==="dir"?o:s,e,"decrypt");let d=await $u(e,s),p;try{p=await kpe(s,d,l,i,r)}catch(_){if(_ instanceof TypeError||_ instanceof Me||_ instanceof Pt)throw _;p=Rf(o)}let f,m;t.iv!==void 0&&(f=wo(t.iv,"iv",Me)),t.tag!==void 0&&(m=wo(t.tag,"tag",Me));let h=t.protected!==void 0?Bn(t.protected):new Uint8Array,y;t.aad!==void 0?y=fi(h,Bn("."),Bn(t.aad)):y=h;let g=wo(t.ciphertext,"ciphertext",Me),b=await tC(o,p,g,f,m,y),v={plaintext:b};if(i.zip==="DEF"){let _=r?.maxDecompressedLength??25e4;if(_===0)throw new Pt('JWE "zip" (Compression Algorithm) Header Parameter is not supported.');if(_!==1/0&&(!Number.isSafeInteger(_)||_<1))throw new TypeError("maxDecompressedLength must be 0, a positive safe integer, or Infinity");v.plaintext=await Ppe(b,_).catch(w=>{throw w instanceof Me?w:new Me("Failed to decompress plaintext",{cause:w})})}return t.protected!==void 0&&(v.protectedHeader=n),t.aad!==void 0&&(v.additionalAuthenticatedData=wo(t.aad,"aad",Me)),t.unprotected!==void 0&&(v.sharedUnprotectedHeader=t.unprotected),t.header!==void 0&&(v.unprotectedHeader=t.header),u?{...v,key:d}:v}var Mpe=I(()=>{Ys();ov();sp();cn();Ss();Ss();LH();Vs();ov();k0();jH();uv();C0();KH()});async function Lpe(t,e,r){if(t instanceof Uint8Array&&(t=_s.decode(t)),typeof t!="string")throw new Me("Compact JWE must be a string or Uint8Array");let{0:n,1:i,2:s,3:o,4:a,length:c}=t.split(".");if(c!==5)throw new Me("Invalid Compact JWE");let l=await Dpe({ciphertext:o,iv:s||void 0,protected:n,tag:a||void 0,encrypted_key:i||void 0},e,r),u={plaintext:l.plaintext,protectedHeader:l.protectedHeader};return typeof e=="function"?{...u,key:l.key}:u}var jpe=I(()=>{Mpe();cn();Vs()});var aC,Upe=I(()=>{Ys();sp();ov();LH();cn();Ss();Vs();k0();uv();C0();KH();aC=class{#e;#t;#r;#n;#i;#p;#u;#a;constructor(e){if(!(e instanceof Uint8Array))throw new TypeError("plaintext must be an instance of Uint8Array");this.#e=e}setKeyManagementParameters(e){return So(this.#a,"setKeyManagementParameters"),this.#a=e,this}setProtectedHeader(e){return So(this.#t,"setProtectedHeader"),this.#t=e,this}setSharedUnprotectedHeader(e){return So(this.#r,"setSharedUnprotectedHeader"),this.#r=e,this}setUnprotectedHeader(e){return So(this.#n,"setUnprotectedHeader"),this.#n=e,this}setAdditionalAuthenticatedData(e){return this.#i=e,this}setContentEncryptionKey(e){return So(this.#p,"setContentEncryptionKey"),this.#p=e,this}setInitializationVector(e){return So(this.#u,"setInitializationVector"),this.#u=e,this}async encrypt(e,r){if(!this.#t&&!this.#n&&!this.#r)throw new Me("either setProtectedHeader, setUnprotectedHeader, or sharedUnprotectedHeader must be called before #encrypt()");if(!Cf(this.#t,this.#n,this.#r))throw new Me("JWE Protected, JWE Shared Unprotected and JWE Per-Recipient Header Parameter names must be disjoint");let n={...this.#t,...this.#n,...this.#r};if(Nf(Me,new Map,r?.crit,this.#t,n),n.zip!==void 0&&n.zip!=="DEF")throw new Pt('Unsupported JWE "zip" (Compression Algorithm) Header Parameter value.');if(n.zip!==void 0&&!this.#t?.zip)throw new Me('JWE "zip" (Compression Algorithm) Header Parameter MUST be in a protected header.');let{alg:i,enc:s}=n;if(typeof i!="string"||!i)throw new Me('JWE "alg" (Algorithm) Header Parameter missing or invalid');if(typeof s!="string"||!s)throw new Me('JWE "enc" (Encryption Algorithm) Header Parameter missing or invalid');let o;if(this.#p&&(i==="dir"||i==="ECDH-ES"))throw new TypeError(`setContentEncryptionKey cannot be called with JWE "alg" (Algorithm) Header ${i}`);Pf(i==="dir"?s:i,e,"encrypt");let a;{let g,b=await $u(e,i);({cek:a,encryptedKey:o,parameters:g}=await Rpe(i,s,b,this.#p,this.#a)),g&&(r&&rpe in r?this.#n?this.#n={...this.#n,...g}:this.setUnprotectedHeader(g):this.#t?this.#t={...this.#t,...g}:this.setProtectedHeader(g))}let c,l,u,d;if(this.#t?(l=bn(JSON.stringify(this.#t)),u=Bn(l)):(l="",u=new Uint8Array),this.#i){d=bn(this.#i);let g=Bn(d);c=fi(u,Bn("."),g)}else c=u;let p=this.#e;n.zip==="DEF"&&(p=await Npe(p).catch(g=>{throw new Me("Failed to compress plaintext",{cause:g})}));let{ciphertext:f,tag:m,iv:h}=await eC(s,p,a,this.#u,c),y={ciphertext:bn(f)};return h&&(y.iv=bn(h)),m&&(y.tag=bn(m)),o&&(y.encrypted_key=bn(o)),d&&(y.aad=d),this.#t&&(y.protected=l),this.#r&&(y.unprotected=this.#r),this.#n&&(y.header=this.#n),y}}});async function Kpe(t,e,r){if(!vn(t))throw new zr("Flattened JWS must be an object");if(t.protected===void 0&&t.header===void 0)throw new zr('Flattened JWS must have either of the "protected" or "header" members');if(t.protected!==void 0&&typeof t.protected!="string")throw new zr("JWS Protected Header incorrect type");if(t.payload===void 0)throw new zr("JWS Payload missing");if(typeof t.signature!="string")throw new zr("JWS Signature missing or incorrect type");if(t.header!==void 0&&!vn(t.header))throw new zr("JWS Unprotected Header incorrect type");let n={};if(t.protected)try{let y=_o(t.protected);n=JSON.parse(_s.decode(y))}catch{throw new zr("JWS Protected Header is invalid")}if(!Cf(n,t.header))throw new zr("JWS Protected and JWS Unprotected Header Parameter names must be disjoint");let i={...n,...t.header},s=Nf(zr,new Map([["b64",!0]]),r?.crit,n,i),o=!0;if(s.has("b64")&&(o=n.b64,typeof o!="boolean"))throw new zr('The "b64" (base64url-encode payload) Header Parameter must be a boolean');let{alg:a}=i;if(typeof a!="string"||!a)throw new zr('JWS "alg" (Algorithm) Header Parameter missing or invalid');let c=r&&R0("algorithms",r.algorithms);if(c&&!c.has(a))throw new Bh('"alg" (Algorithm) Header Parameter value not allowed');if(o){if(typeof t.payload!="string")throw new zr("JWS Payload must be a string")}else if(typeof t.payload!="string"&&!(t.payload instanceof Uint8Array))throw new zr("JWS Payload must be a string or an Uint8Array instance");let l=!1;typeof e=="function"&&(e=await e(n,t),l=!0),Pf(a,e,"verify");let u=fi(t.protected!==void 0?Bn(t.protected):new Uint8Array,Bn("."),typeof t.payload=="string"?o?Bn(t.payload):qh.encode(t.payload):t.payload),d=wo(t.signature,"signature",zr),p=await $u(e,a);if(!await ype(a,p,d,u))throw new ZR;let m;o?m=wo(t.payload,"payload",zr):typeof t.payload=="string"?m=qh.encode(t.payload):m=t.payload;let h={payload:m};return t.protected!==void 0&&(h.protectedHeader=n),t.header!==void 0&&(h.unprotectedHeader=t.header),l?{...h,key:p}:h}var qpe=I(()=>{Ys();nC();cn();Vs();sp();Ss();Ss();C0();k0();jH();uv()});async function Fpe(t,e,r){if(t instanceof Uint8Array&&(t=_s.decode(t)),typeof t!="string")throw new zr("Compact JWS must be a string or Uint8Array");let{0:n,1:i,2:s,length:o}=t.split(".");if(o!==3)throw new zr("Invalid Compact JWS");let a=await Kpe({payload:i,protected:n,signature:s},e,r),c={payload:a.payload,protectedHeader:a.protectedHeader};return typeof e=="function"?{...c,key:a.key}:c}var zpe=I(()=>{qpe();cn();Vs()});function N0(t){let e=Krt.exec(t);if(!e||e[4]&&e[1])throw new TypeError("Invalid time period format");let r=parseFloat(e[2]),n=e[3].toLowerCase(),i;switch(n){case"sec":case"secs":case"second":case"seconds":case"s":i=Math.round(r);break;case"minute":case"minutes":case"min":case"mins":case"m":i=Math.round(r*Hpe);break;case"hour":case"hours":case"hr":case"hrs":case"h":i=Math.round(r*Wpe);break;case"day":case"days":case"d":i=Math.round(r*qH);break;case"week":case"weeks":case"w":i=Math.round(r*jrt);break;default:i=Math.round(r*Urt);break}return e[1]==="-"||e[4]==="ago"?-i:i}function $h(t,e){if(!Number.isFinite(e))throw new TypeError(`Invalid ${t} input`);return e}function cC(t,e,r={}){let n;try{n=JSON.parse(_s.decode(e))}catch{}if(!vn(n))throw new Js("JWT Claims Set must be a top-level JSON object");let{typ:i}=r;if(i&&(typeof t.typ!="string"||Bpe(t.typ)!==Bpe(i)))throw new Es('unexpected "typ" JWT header value',n,"typ","check_failed");let{requiredClaims:s=[],issuer:o,subject:a,audience:c,maxTokenAge:l}=r,u=[...s];l!==void 0&&u.push("iat"),c!==void 0&&u.push("aud"),a!==void 0&&u.push("sub"),o!==void 0&&u.push("iss");for(let m of new Set(u.reverse()))if(!(m in n))throw new Es(`missing required "${m}" claim`,n,m,"missing");if(o&&!(Array.isArray(o)?o:[o]).includes(n.iss))throw new Es('unexpected "iss" claim value',n,"iss","check_failed");if(a&&n.sub!==a)throw new Es('unexpected "sub" claim value',n,"sub","check_failed");if(c&&!qrt(n.aud,typeof c=="string"?[c]:c))throw new Es('unexpected "aud" claim value',n,"aud","check_failed");let d;switch(typeof r.clockTolerance){case"string":d=N0(r.clockTolerance);break;case"number":d=r.clockTolerance;break;case"undefined":d=0;break;default:throw new TypeError("Invalid clockTolerance option type")}let{currentDate:p}=r,f=Df(p||new Date);if((n.iat!==void 0||l)&&typeof n.iat!="number")throw new Es('"iat" claim must be a number',n,"iat","invalid");if(n.nbf!==void 0){if(typeof n.nbf!="number")throw new Es('"nbf" claim must be a number',n,"nbf","invalid");if(n.nbf>f+d)throw new Es('"nbf" claim timestamp check failed',n,"nbf","check_failed")}if(n.exp!==void 0){if(typeof n.exp!="number")throw new Es('"exp" claim must be a number',n,"exp","invalid");if(n.exp<=f-d)throw new zh('"exp" claim timestamp check failed',n,"exp","check_failed")}if(l){let m=f-n.iat,h=typeof l=="number"?l:N0(l);if(m-d>h)throw new zh('"iat" claim timestamp check failed (too far in the past)',n,"iat","check_failed");if(m<0-d)throw new Es('"iat" claim timestamp check failed (it should be in the past)',n,"iat","check_failed")}return n}var Df,Hpe,Wpe,qH,jrt,Urt,Krt,Bpe,qrt,pv,P0=I(()=>{cn();Vs();Ss();Df=t=>Math.floor(t.getTime()/1e3),Hpe=60,Wpe=Hpe*60,qH=Wpe*24,jrt=qH*7,Urt=qH*365.25,Krt=/^(\+|\-)? ?(\d+|\d+\.\d+) ?(seconds?|secs?|s|minutes?|mins?|m|hours?|hrs?|h|days?|d|weeks?|w|years?|yrs?|y)(?: (ago|from now))?$/i;Bpe=t=>t.includes("/")?t.toLowerCase():`application/${t.toLowerCase()}`,qrt=(t,e)=>typeof t=="string"?e.includes(t):Array.isArray(t)?e.some(Set.prototype.has.bind(new Set(t))):!1;pv=class{#e;constructor(e){if(!vn(e))throw new TypeError("JWT Claims Set MUST be an object");this.#e=structuredClone(e)}data(){return qh.encode(JSON.stringify(this.#e))}get iss(){return this.#e.iss}set iss(e){this.#e.iss=e}get sub(){return this.#e.sub}set sub(e){this.#e.sub=e}get aud(){return this.#e.aud}set aud(e){this.#e.aud=e}set jti(e){this.#e.jti=e}set nbf(e){typeof e=="number"?this.#e.nbf=$h("setNotBefore",e):e instanceof Date?this.#e.nbf=$h("setNotBefore",Df(e)):this.#e.nbf=Df(new Date)+N0(e)}set exp(e){typeof e=="number"?this.#e.exp=$h("setExpirationTime",e):e instanceof Date?this.#e.exp=$h("setExpirationTime",Df(e)):this.#e.exp=Df(new Date)+N0(e)}set iat(e){e===void 0?this.#e.iat=Df(new Date):e instanceof Date?this.#e.iat=$h("setIssuedAt",Df(e)):typeof e=="string"?this.#e.iat=$h("setIssuedAt",Df(new Date)+N0(e)):this.#e.iat=$h("setIssuedAt",e)}}});async function To(t,e,r){let n=await Fpe(t,e,r);if(n.protectedHeader.crit?.includes("b64")&&n.protectedHeader.b64===!1)throw new Js("JWTs MUST NOT use unencoded payload");let s={payload:cC(n.protectedHeader,n.payload,r),protectedHeader:n.protectedHeader};return typeof e=="function"?{...s,key:n.key}:s}var $pe=I(()=>{zpe();P0();cn()});async function lC(t,e,r){let n=await Lpe(t,e,r),i=cC(n.protectedHeader,n.plaintext,r),{protectedHeader:s}=n;if(s.iss!==void 0&&s.iss!==i.iss)throw new Es('replicated "iss" claim header parameter mismatch',i,"iss","mismatch");if(s.sub!==void 0&&s.sub!==i.sub)throw new Es('replicated "sub" claim header parameter mismatch',i,"sub","mismatch");if(s.aud!==void 0&&JSON.stringify(s.aud)!==JSON.stringify(i.aud))throw new Es('replicated "aud" claim header parameter mismatch',i,"aud","mismatch");let o={payload:i,protectedHeader:s};return typeof e=="function"?{...o,key:n.key}:o}var Gpe=I(()=>{jpe();P0();cn()});var uC,Vpe=I(()=>{Upe();uC=class{#e;constructor(e){this.#e=new aC(e)}setContentEncryptionKey(e){return this.#e.setContentEncryptionKey(e),this}setInitializationVector(e){return this.#e.setInitializationVector(e),this}setProtectedHeader(e){return this.#e.setProtectedHeader(e),this}setKeyManagementParameters(e){return this.#e.setKeyManagementParameters(e),this}async encrypt(e,r){let n=await this.#e.encrypt(e,r);return[n.protected,n.encrypted_key,n.iv,n.ciphertext,n.tag].join(".")}}});var dC,Ype=I(()=>{Ys();nC();Ss();cn();Vs();C0();k0();uv();sp();dC=class{#e;#t;#r;constructor(e){if(!(e instanceof Uint8Array))throw new TypeError("payload must be an instance of Uint8Array");this.#e=e}setProtectedHeader(e){return So(this.#t,"setProtectedHeader"),this.#t=e,this}setUnprotectedHeader(e){return So(this.#r,"setUnprotectedHeader"),this.#r=e,this}async sign(e,r){if(!this.#t&&!this.#r)throw new zr("either setProtectedHeader or setUnprotectedHeader must be called before #sign()");if(!Cf(this.#t,this.#r))throw new zr("JWS Protected and JWS Unprotected Header Parameter names must be disjoint");let n={...this.#t,...this.#r},i=Nf(zr,new Map([["b64",!0]]),r?.crit,this.#t,n),s=!0;if(i.has("b64")&&(s=this.#t.b64,typeof s!="boolean"))throw new zr('The "b64" (base64url-encode payload) Header Parameter must be a boolean');let{alg:o}=n;if(typeof o!="string"||!o)throw new zr('JWS "alg" (Algorithm) Header Parameter missing or invalid');Pf(o,e,"sign");let a,c;s?(a=bn(this.#e),c=Bn(a)):(c=this.#e,a="");let l,u;this.#t?(l=bn(JSON.stringify(this.#t)),u=Bn(l)):(l="",u=new Uint8Array);let d=fi(u,Bn("."),c),p=await $u(e,o),f=await gpe(o,p,d),m={signature:bn(f),payload:a};return this.#r&&(m.header=this.#r),this.#t&&(m.protected=l),m}}});var pC,Jpe=I(()=>{Ype();pC=class{#e;constructor(e){this.#e=new dC(e)}setProtectedHeader(e){return this.#e.setProtectedHeader(e),this}async sign(e,r){let n=await this.#e.sign(e,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 D0,Zpe=I(()=>{Jpe();cn();P0();D0=class{#e;#t;constructor(e={}){this.#t=new pv(e)}setIssuer(e){return this.#t.iss=e,this}setSubject(e){return this.#t.sub=e,this}setAudience(e){return this.#t.aud=e,this}setJti(e){return this.#t.jti=e,this}setNotBefore(e){return this.#t.nbf=e,this}setExpirationTime(e){return this.#t.exp=e,this}setIssuedAt(e){return this.#t.iat=e,this}setProtectedHeader(e){return this.#e=e,this}async sign(e,r){let n=new pC(this.#t.data());if(n.setProtectedHeader(this.#e),Array.isArray(this.#e?.crit)&&this.#e.crit.includes("b64")&&this.#e.b64===!1)throw new Js("JWTs MUST NOT use unencoded payload");return n.sign(e,r)}}});var M0,Xpe=I(()=>{Vpe();P0();sp();M0=class{#e;#t;#r;#n;#i;#p;#u;#a;constructor(e={}){this.#a=new pv(e)}setIssuer(e){return this.#a.iss=e,this}setSubject(e){return this.#a.sub=e,this}setAudience(e){return this.#a.aud=e,this}setJti(e){return this.#a.jti=e,this}setNotBefore(e){return this.#a.nbf=e,this}setExpirationTime(e){return this.#a.exp=e,this}setIssuedAt(e){return this.#a.iat=e,this}setProtectedHeader(e){return So(this.#n,"setProtectedHeader"),this.#n=e,this}setKeyManagementParameters(e){return So(this.#r,"setKeyManagementParameters"),this.#r=e,this}setContentEncryptionKey(e){return So(this.#e,"setContentEncryptionKey"),this.#e=e,this}setInitializationVector(e){return So(this.#t,"setInitializationVector"),this.#t=e,this}replicateIssuerAsHeader(){return this.#i=!0,this}replicateSubjectAsHeader(){return this.#p=!0,this}replicateAudienceAsHeader(){return this.#u=!0,this}async encrypt(e,r){let n=new uC(this.#a.data());return this.#n&&(this.#i||this.#p||this.#u)&&(this.#n={...this.#n,iss:this.#i?this.#a.iss:void 0,sub:this.#p?this.#a.sub:void 0,aud:this.#u?this.#a.aud:void 0}),n.setProtectedHeader(this.#n),this.#t&&n.setInitializationVector(this.#t),this.#e&&n.setContentEncryptionKey(this.#e),this.#r&&n.setKeyManagementParameters(this.#r),n.encrypt(e,r)}}});async function fC(t,e){let r;if(Wh(t))r=t;else if(T0(t))r=await oC(t);else throw new TypeError(Wu(t,"CryptoKey","KeyObject","JSON Web Key"));if(e??="sha256",e!=="sha256"&&e!=="sha384"&&e!=="sha512")throw new TypeError('digestAlgorithm must one of "sha256", "sha384", or "sha512"');let n;switch(r.kty){case"AKP":Gu(r.alg,'"alg" (Algorithm) Parameter'),Gu(r.pub,'"pub" (Public key) Parameter'),n={alg:r.alg,kty:r.kty,pub:r.pub};break;case"EC":Gu(r.crv,'"crv" (Curve) Parameter'),Gu(r.x,'"x" (X Coordinate) Parameter'),Gu(r.y,'"y" (Y Coordinate) Parameter'),n={crv:r.crv,kty:r.kty,x:r.x,y:r.y};break;case"OKP":Gu(r.crv,'"crv" (Subtype of Key Pair) Parameter'),Gu(r.x,'"x" (Public Key) Parameter'),n={crv:r.crv,kty:r.kty,x:r.x};break;case"RSA":Gu(r.e,'"e" (Exponent) Parameter'),Gu(r.n,'"n" (Modulus) Parameter'),n={e:r.e,kty:r.kty,n:r.n};break;case"oct":Gu(r.k,'"k" (Key Value) Parameter'),n={k:r.k,kty:r.kty};break;default:throw new Pt('"kty" (Key Type) Parameter missing or unsupported')}let i=Bn(JSON.stringify(n));return bn(await rC(e,i))}var Gu,Qpe=I(()=>{sp();Ys();cn();Vs();Hh();Ss();MH();rv();Gu=(t,e)=>{if(typeof t!="string"||!t)throw new VR(`${e} missing or invalid`)}});function Frt(t){switch(typeof t=="string"&&t.slice(0,2)){case"RS":case"PS":return"RSA";case"ES":return"EC";case"Ed":return"OKP";case"ML":return"AKP";default:throw new Pt('Unsupported "alg" value for a JSON Web Key Set')}}function zrt(t){return t&&typeof t=="object"&&Array.isArray(t.keys)&&t.keys.every(Brt)}function Brt(t){return vn(t)}async function efe(t,e,r){let n=t.get(e)||t.set(e,{}).get(e);if(n[r]===void 0){let i=await Ga({...e,ext:!0},r);if(i instanceof Uint8Array||i.type!=="public")throw new S0("JSON Web Key Set members must be public keys");n[r]=i}return n[r]}function zH(t){let e=new FH(t),r=async(n,i)=>e.getKey(n,i);return Object.defineProperties(r,{jwks:{value:()=>structuredClone(e.jwks()),enumerable:!1,configurable:!1,writable:!1}}),r}var FH,tfe=I(()=>{sC();cn();Ss();FH=class{#e;#t=new WeakMap;constructor(e){if(!zrt(e))throw new S0("JSON Web Key Set malformed");this.#e=structuredClone(e)}jwks(){return this.#e}async getKey(e,r){let{alg:n,kid:i}={...e,...r?.header},s=Frt(n),o=this.#e.keys.filter(l=>{let u=s===l.kty;if(u&&typeof i=="string"&&(u=i===l.kid),u&&(typeof l.alg=="string"||s==="AKP")&&(u=n===l.alg),u&&typeof l.use=="string"&&(u=l.use==="sig"),u&&Array.isArray(l.key_ops)&&(u=l.key_ops.includes("verify")),u)switch(n){case"ES256":u=l.crv==="P-256";break;case"ES384":u=l.crv==="P-384";break;case"ES512":u=l.crv==="P-521";break;case"Ed25519":case"EdDSA":u=l.crv==="Ed25519";break}return u}),{0:a,length:c}=o;if(c===0)throw new iv;if(c!==1){let l=new YR,u=this.#t;throw l[Symbol.asyncIterator]=async function*(){for(let d of o)try{yield await efe(u,d,n)}catch{}},l}return efe(this.#t,a,n)}}});function Hrt(){return typeof WebSocketPair<"u"||typeof navigator<"u"&&navigator.userAgent==="Cloudflare-Workers"||typeof EdgeRuntime<"u"&&EdgeRuntime==="vercel"}async function Wrt(t,e,r,n=fetch){let i=await n(t,{method:"GET",signal:r,redirect:"manual",headers:e}).catch(s=>{throw s.name==="TimeoutError"?new JR:s});if(i.status!==200)throw new Si("Expected 200 OK from the JSON Web Key Set HTTP response");try{return await i.json()}catch{throw new Si("Failed to parse the JSON Web Key Set HTTP response as JSON")}}function $rt(t,e){return!(typeof t!="object"||t===null||!("uat"in t)||typeof t.uat!="number"||Date.now()-t.uat>=e||!("jwks"in t)||!vn(t.jwks)||!Array.isArray(t.jwks.keys)||!Array.prototype.every.call(t.jwks.keys,vn))}function WH(t,e){let r=new HH(t,e),n=async(i,s)=>r.getKey(i,s);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.jwks(),enumerable:!0,configurable:!1,writable:!1}}),n}var BH,rfe,mC,HH,nfe=I(()=>{cn();tfe();Ss();(typeof navigator>"u"||!navigator.userAgent?.startsWith?.("Mozilla/5.0 "))&&(BH="jose/v6.2.3");rfe=Symbol();mC=Symbol();HH=class{#e;#t;#r;#n;#i;#p;#u;#a;#o;#d;constructor(e,r){if(!(e instanceof URL))throw new TypeError("url must be an instance of URL");this.#e=new URL(e.href),this.#t=typeof r?.timeoutDuration=="number"?r?.timeoutDuration:5e3,this.#r=typeof r?.cooldownDuration=="number"?r?.cooldownDuration:3e4,this.#n=typeof r?.cacheMaxAge=="number"?r?.cacheMaxAge:6e5,this.#u=new Headers(r?.headers),BH&&!this.#u.has("User-Agent")&&this.#u.set("User-Agent",BH),this.#u.has("accept")||(this.#u.set("accept","application/json"),this.#u.append("accept","application/jwk-set+json")),this.#a=r?.[rfe],r?.[mC]!==void 0&&(this.#d=r?.[mC],$rt(r?.[mC],this.#n)&&(this.#i=this.#d.uat,this.#o=zH(this.#d.jwks)))}pendingFetch(){return!!this.#p}coolingDown(){return typeof this.#i=="number"?Date.now()<this.#i+this.#r:!1}fresh(){return typeof this.#i=="number"?Date.now()<this.#i+this.#n:!1}jwks(){return this.#o?.jwks()}async getKey(e,r){(!this.#o||!this.fresh())&&await this.reload();try{return await this.#o(e,r)}catch(n){if(n instanceof iv&&this.coolingDown()===!1)return await this.reload(),this.#o(e,r);throw n}}async reload(){this.#p&&Hrt()&&(this.#p=void 0),this.#p||=Wrt(this.#e.href,this.#u,AbortSignal.timeout(this.#t),this.#a).then(e=>{this.#o=zH(e),this.#d&&(this.#d.uat=Date.now(),this.#d.jwks=e),this.#i=Date.now(),this.#p=void 0}).catch(e=>{throw this.#p=void 0,e}),await this.#p}}});function Dl(t){let e;if(typeof t=="string"){let r=t.split(".");(r.length===3||r.length===5)&&([e]=r)}else if(typeof t=="object"&&t)if("protected"in t)e=t.protected;else throw new TypeError("Token does not contain a Protected Header");try{if(typeof e!="string"||!e)throw new Error;let r=JSON.parse(_s.decode(_o(e)));if(!vn(r))throw new Error;return r}catch{throw new TypeError("Invalid Token or Protected Header formatting")}}var ife=I(()=>{Ys();Vs();Ss()});function wi(t){if(typeof t!="string")throw new Js("JWTs must use Compact JWS serialization, JWT must be a string");let{1:e,length:r}=t.split(".");if(r===5)throw new Js("Only JWTs using Compact JWS serialization can be decoded");if(r!==3)throw new Js("Invalid JWT");if(!e)throw new Js("JWTs must contain a payload");let n;try{n=_o(e)}catch{throw new Js("Failed to base64url decode the payload")}let i;try{i=JSON.parse(_s.decode(n))}catch{throw new Js("Failed to parse the decoded payload as JSON")}if(!vn(i))throw new Js("Invalid JWT Claims Set");return i}var sfe=I(()=>{Ys();Vs();Ss();cn()});var Wc=I(()=>{$pe();Gpe();Zpe();Xpe();Qpe();nfe();sC();ife();sfe();Ys()});async function hC(t,e,r=3600){return await new D0(t).setProtectedHeader({alg:"HS256"}).setIssuedAt().setExpirationTime(Math.floor(Date.now()/1e3)+r).sign(new TextEncoder().encode(e))}async function $H(t,e){try{return(await To(t,new TextEncoder().encode(e))).payload}catch{return null}}function L0(t,e){return Ude(Bde,new TextEncoder().encode(t),new TextEncoder().encode(e),Grt,64)}function Yrt(t){if(typeof t=="string")return t;let e=t.keys.get(t.currentVersion);if(!e)throw new Error(`Secret version ${t.currentVersion} not found in keys`);return e}function ofe(t){if(typeof t=="string")return[{version:0,value:t}];let e=[];for(let[r,n]of t.keys)e.push({version:r,value:n});return t.legacySecret&&!e.some(r=>r.value===t.legacySecret)&&e.push({version:-1,value:t.legacySecret}),e}async function gC(t,e,r,n=3600){let i=L0(Yrt(e),r),s=await fC({kty:"oct",k:E0.encode(i)},"sha256");return await new M0(t).setProtectedHeader({alg:cfe,enc:lfe,kid:s}).setIssuedAt().setExpirationTime(Vrt()+n).setJti(crypto.randomUUID()).encrypt(i)}async function j0(t,e,r){if(!t)return null;let n=!1;try{n=Dl(t).kid!==void 0}catch{return null}try{let i=ofe(e),{payload:s}=await lC(t,async o=>{let a=o.kid;if(a!==void 0){for(let c of i){let l=L0(c.value,r);if(a===await fC({kty:"oct",k:E0.encode(l)},"sha256"))return l}throw new Error("no matching decryption secret")}return i.length===1,L0(i[0].value,r)},afe);return s}catch{if(n)return null;let i=ofe(e);if(i.length<=1)return null;for(let s=1;s<i.length;s++)try{let o=i[s],{payload:a}=await lC(t,L0(o.value,r),afe);return a}catch{continue}return null}}var Grt,Vrt,cfe,lfe,afe,U0=I(()=>{Kde();Hde();Wc();Grt=new Uint8Array([66,101,116,116,101,114,65,117,116,104,46,106,115,32,71,101,110,101,114,97,116,101,100,32,69,110,99,114,121,112,116,105,111,110,32,75,101,121]),Vrt=()=>Date.now()/1e3|0,cfe="dir",lfe="A256CBC-HS512";afe={clockTolerance:15,keyManagementAlgorithms:[cfe],contentEncryptionAlgorithms:[lfe,"A256GCM"]}});function ufe(t,e){return new Promise((r,n)=>{(0,yC.scrypt)(t.normalize("NFKC"),e,fv.dkLen,{N:fv.N,r:fv.r,p:fv.p,maxmem:128*fv.N*fv.r*2},(i,s)=>{i?n(i):r(s)})})}async function dfe(t){let e=(0,yC.randomBytes)(16).toString("hex"),r=await ufe(t,e);return`${e}:${r.toString("hex")}`}async function pfe(t,e){let[r,n]=t.split(":");if(!r||!n)throw new Error("Invalid password hash");return(await ufe(e,r)).toString("hex")===n}var yC,fv,ffe=I(()=>{yC=require("node:crypto"),fv={N:16384,r:16,p:1,dkLen:64}});var mfe,hfe,gfe=I(()=>{ffe();mfe=dfe,hfe=async({hash:t,password:e})=>pfe(t,e)});function Ml(){let t=typeof globalThis<"u"&&globalThis.crypto;if(t&&typeof t.subtle=="object"&&t.subtle!=null)return t.subtle;throw new Error("crypto.subtle must be defined")}var K0=I(()=>{});function bC(t){return t?"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_":"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"}function yfe(t,e,r){let n="",i=0,s=0;for(let o of t)for(i=i<<8|o,s+=8;s>=6;)s-=6,n+=e[i>>s&63];if(s>0&&(n+=e[i<<6-s&63]),r){let o=(4-n.length%4)%4;n+="=".repeat(o)}return n}function bfe(t,e){let r=new Map;for(let o=0;o<e.length;o++)r.set(e[o],o);let n=[],i=0,s=0;for(let o of t){if(o==="=")break;let a=r.get(o);if(a===void 0)throw new Error(`Invalid Base64 character: ${o}`);i=i<<6|a,s+=6,s>=8&&(s-=8,n.push(i>>s&255))}return Uint8Array.from(n)}var Hi,da,pa=I(()=>{Hi={encode(t,e={}){let r=bC(!1),n=typeof t=="string"?new TextEncoder().encode(t):new Uint8Array(t);return yfe(n,r,e.padding??!0)},decode(t){typeof t!="string"&&(t=new TextDecoder().decode(t));let e=t.includes("-")||t.includes("_"),r=bC(e);return bfe(t,r)}},da={encode(t,e={}){let r=bC(!0),n=typeof t=="string"?new TextEncoder().encode(t):new Uint8Array(t);return yfe(n,r,e.padding??!0)},decode(t){let e=t.includes("-")||t.includes("_"),r=bC(e);return bfe(t,r)}}});function op(t,e){return{digest:async r=>{let n=new TextEncoder,i=typeof r=="string"?n.encode(r):r,s=await Ml().digest(t,i);return e==="hex"?Array.from(new Uint8Array(s)).map(c=>c.toString(16).padStart(2,"0")).join(""):e==="base64"||e==="base64url"||e==="base64urlnopad"?e.includes("url")?da.encode(s,{padding:e!=="base64urlnopad"}):Hi.encode(s):s}}}var q0=I(()=>{pa();K0()});function Jrt(t){return t instanceof Uint8Array||ArrayBuffer.isView(t)&&t.constructor.name==="Uint8Array"&&"BYTES_PER_ELEMENT"in t&&t.BYTES_PER_ELEMENT===1}function vC(t){if(typeof t!="boolean")throw new TypeError(`boolean expected, not ${t}`)}function Mf(t){if(typeof t!="number")throw new TypeError("number expected, got "+typeof t);if(!Number.isSafeInteger(t)||t<0)throw new RangeError("positive integer expected, got "+t)}function Dn(t,e,r=""){let n=Jrt(t),i=t?.length,s=e!==void 0;if(!n||s&&i!==e){let o=r&&`"${r}" `,a=s?` of length ${e}`:"",c=n?`length=${i}`:`type=${typeof t}`,l=o+"expected Uint8Array"+a+", got "+c;throw n?new RangeError(l):new TypeError(l)}return t}function GH(t,e=!0){if(t.destroyed)throw new Error("Hash instance has been destroyed");if(e&&t.finished)throw new Error("Hash#digest() has already been called")}function _fe(t,e,r=!1){Dn(t,void 0,"output");let n=e.outputLen;if(t.length<n)throw new RangeError("digestInto() expects output buffer of length at least "+n);if(r&&!mv(t))throw new Error("invalid output, must be aligned")}function Vu(t){return new Uint32Array(t.buffer,t.byteOffset,Math.floor(t.byteLength/4))}function Ll(...t){for(let e=0;e<t.length;e++)t[e].fill(0)}function Zrt(t){return new DataView(t.buffer,t.byteOffset,t.byteLength)}function VH(t){if(Dn(t),Sfe)return t.toHex();let e="";for(let r=0;r<t.length;r++)e+=Qrt[t[r]];return e}function vfe(t){if(t>=ap._0&&t<=ap._9)return t-ap._0;if(t>=ap.A&&t<=ap.F)return t-(ap.A-10);if(t>=ap.a&&t<=ap.f)return t-(ap.a-10)}function wfe(t){if(typeof t!="string")throw new TypeError("hex string expected, got "+typeof t);if(Sfe)try{return Uint8Array.fromHex(t)}catch(i){throw i instanceof SyntaxError?new RangeError(i.message):i}let e=t.length,r=e/2;if(e%2)throw new RangeError("hex string expected, got unpadded hex of length "+e);let n=new Uint8Array(r);for(let i=0,s=0;i<r;i++,s+=2){let o=vfe(t.charCodeAt(s)),a=vfe(t.charCodeAt(s+1));if(o===void 0||a===void 0){let c=t[s]+t[s+1];throw new RangeError('hex string expected, got non-hex character "'+c+'" at index '+s)}n[i]=o*16+a}return n}function Tfe(t){if(typeof t!="string")throw new TypeError("string expected");return new Uint8Array(new TextEncoder().encode(t))}function ent(t,e){return!t.byteLength||!e.byteLength?!1:t.buffer===e.buffer&&t.byteOffset<e.byteOffset+e.byteLength&&e.byteOffset<t.byteOffset+t.byteLength}function xfe(...t){let e=0;for(let n=0;n<t.length;n++){let i=t[n];Dn(i),e+=i.length}let r=new Uint8Array(e);for(let n=0,i=0;n<t.length;n++){let s=t[n];r.set(s,i),i+=s.length}return r}function Ife(t,e){if(e==null||typeof e!="object")throw new Error("options must be defined");return Object.assign(t,e)}function Afe(t,e){if(t.length!==e.length)return!1;let r=0;for(let n=0;n<t.length;n++)r|=t[n]^e[n];return r===0}function Ofe(t,e,r){let n=e,i=r||(()=>[]),s=(a,c)=>n(c,...i(a)).update(a).digest(),o=n(new Uint8Array(t),...i(new Uint8Array(0)));return s.outputLen=o.outputLen,s.blockLen=o.blockLen,s.create=(a,...c)=>n(a,...c),s}function F0(t,e,r=!0){if(e===void 0)return new Uint8Array(t);if(Dn(e,void 0,"output"),e.length!==t)throw new Error('"output" expected Uint8Array of length '+t+", got: "+e.length);if(r&&!mv(e))throw new Error("invalid output, must be aligned");return e}function Rfe(t,e,r){Mf(t),Mf(e),vC(r);let n=new Uint8Array(16),i=Zrt(n);return i.setBigUint64(0,BigInt(e),r),i.setBigUint64(8,BigInt(t),r),n}function mv(t){return t.byteOffset%4===0}function hv(t){return Uint8Array.from(Dn(t))}function Cfe(t=32){Mf(t);let e=typeof globalThis=="object"?globalThis.crypto:null;if(typeof e?.getRandomValues!="function")throw new Error("crypto.getRandomValues must be defined");return e.getRandomValues(new Uint8Array(t))}function YH(t,e=Cfe){let{nonceLength:r}=t;Mf(r);let n=(s,o,a)=>{let c=xfe(s,o);return ent(a,o)||o.fill(0),c},i=((s,...o)=>({encrypt(a){Dn(a);let c=e(r),l=t(s,c,...o).encrypt(a);return l instanceof Promise?l.then(u=>n(c,u,a)):n(c,l,a)},decrypt(a){Dn(a);let c=a.subarray(0,r),l=a.subarray(r);return t(s,c,...o).decrypt(l)}}));return"blockSize"in t&&(i.blockSize=t.blockSize),"tagLength"in t&&(i.tagLength=t.tagLength),i}var Lf,Efe,ws,Xrt,Yu,Sfe,Qrt,ap,kfe,z0=I(()=>{Lf=new Uint8Array(new Uint32Array([287454020]).buffer)[0]===68,Efe=t=>t<<24&4278190080|t<<8&16711680|t>>>8&65280|t>>>24&255,ws=Lf?t=>t:t=>Efe(t)>>>0,Xrt=t=>{for(let e=0;e<t.length;e++)t[e]=Efe(t[e]);return t},Yu=Lf?t=>t:Xrt,Sfe=typeof Uint8Array.from([]).toHex=="function"&&typeof Uint8Array.fromHex=="function",Qrt=Array.from({length:256},(t,e)=>e.toString(16).padStart(2,"0"));ap={_0:48,_9:57,A:65,F:70,a:97,f:102};kfe=(t,e)=>{function r(n,...i){if(Dn(n,void 0,"key"),t.nonceLength!==void 0){let u=i[0];Dn(u,t.varSizeNonce?void 0:t.nonceLength,"nonce")}let s=t.tagLength;s&&i[1]!==void 0&&Dn(i[1],void 0,"AAD");let o=e(n,...i),a=(u,d)=>{if(d!==void 0){if(u!==2)throw new Error("cipher output not supported");Dn(d,void 0,"output")}},c=!1;return{encrypt(u,d){if(c)throw new Error("cannot encrypt() twice with same key + nonce");return c=!0,Dn(u),a(o.encrypt.length,d),o.encrypt(u,d)},decrypt(u,d){if(Dn(u),s&&u.length<s)throw new Error('"ciphertext" expected length bigger than tagLength='+s);return a(o.decrypt.length,d),o.decrypt(u,d)}}}return Object.assign(r,t),r}});function Le(t,e){return t<<e|t>>>32-e}function int(t,e,r,n,i,s,o,a){let c=i.length,l=new Uint8Array(B0),u=Vu(l),d=Lf&&mv(i)&&mv(s),p=d?Vu(i):Nfe,f=d?Vu(s):Nfe;if(!Lf){for(let m=0;m<c;o++){if(t(e,r,n,u,o,a),Yu(u),o>=JH)throw new Error("arx: counter overflow");let h=Math.min(B0,c-m);for(let y=0,g;y<h;y++)g=m+y,s[g]=i[g]^l[y];m+=h}return}for(let m=0;m<c;o++){if(t(e,r,n,u,o,a),o>=JH)throw new Error("arx: counter overflow");let h=Math.min(B0,c-m);if(d&&h===B0){let y=m/4;if(m%4!==0)throw new Error("arx: invalid block position");for(let g=0,b;g<nnt;g++)b=y+g,f[b]=p[b]^u[g];m+=B0;continue}for(let y=0,g;y<h;y++)g=m+y,s[g]=i[g]^l[y];m+=h}}function Dfe(t,e){let{allowShortKeys:r,extendNonceFn:n,counterLength:i,counterRight:s,rounds:o}=Ife({allowShortKeys:!1,counterLength:8,counterRight:!1,rounds:20},e);if(typeof t!="function")throw new Error("core must be a function");return Mf(i),Mf(o),vC(s),vC(r),(a,c,l,u,d=0)=>{Dn(a,void 0,"key"),Dn(c,void 0,"nonce"),Dn(l,void 0,"data");let p=l.length;if(u=F0(p,u,!1),Mf(d),d<0||d>=JH)throw new Error("arx: counter overflow");let f=[],m=a.length,h,y;if(m===32)f.push(h=hv(a)),y=rnt;else if(m===16&&r)h=new Uint8Array(32),h.set(a),h.set(a,16),y=tnt,f.push(h);else throw Dn(a,32,"arx key"),new Error("invalid key size");(!Lf||!mv(c))&&f.push(c=hv(c));let g=Vu(h);if(n){if(c.length!==24)throw new Error("arx: extended nonce must be 24 bytes");let _=c.subarray(0,16);if(Lf)n(y,g,Vu(_),g);else{let w=Yu(Uint32Array.from(y));n(w,g,Vu(_),g),Ll(w),Yu(g)}c=c.subarray(16)}else Lf||Yu(g);let b=16-i;if(b!==c.length)throw new Error(`arx: nonce must be ${b} or 16 bytes`);if(b!==12){let _=new Uint8Array(12);_.set(c,s?0:12-c.length),c=_,f.push(c)}let v=Yu(Vu(c));try{return int(t,y,g,v,l,u,d,o),u}finally{Ll(...f)}}}var Pfe,tnt,rnt,B0,nnt,JH,Nfe,Mfe=I(()=>{z0();Pfe=t=>Uint8Array.from(t.split(""),e=>e.charCodeAt(0)),tnt=Yu(Vu(Pfe("expand 16-byte k"))),rnt=Yu(Vu(Pfe("expand 32-byte k")));B0=64,nnt=16,JH=2**32-1,Nfe=Uint32Array.of()});function Ts(t,e){return t[e++]&255|(t[e++]&255)<<8}var ZH,Lfe,jfe=I(()=>{z0();ZH=class{blockLen=16;outputLen=16;buffer=new Uint8Array(16);r=new Uint16Array(10);h=new Uint16Array(10);pad=new Uint16Array(8);pos=0;finished=!1;destroyed=!1;constructor(e){e=hv(Dn(e,32,"key"));let r=Ts(e,0),n=Ts(e,2),i=Ts(e,4),s=Ts(e,6),o=Ts(e,8),a=Ts(e,10),c=Ts(e,12),l=Ts(e,14);this.r[0]=r&8191,this.r[1]=(r>>>13|n<<3)&8191,this.r[2]=(n>>>10|i<<6)&7939,this.r[3]=(i>>>7|s<<9)&8191,this.r[4]=(s>>>4|o<<12)&255,this.r[5]=o>>>1&8190,this.r[6]=(o>>>14|a<<2)&8191,this.r[7]=(a>>>11|c<<5)&8065,this.r[8]=(c>>>8|l<<8)&8191,this.r[9]=l>>>5&127;for(let u=0;u<8;u++)this.pad[u]=Ts(e,16+2*u)}process(e,r,n=!1){let i=n?0:2048,{h:s,r:o}=this,a=o[0],c=o[1],l=o[2],u=o[3],d=o[4],p=o[5],f=o[6],m=o[7],h=o[8],y=o[9],g=Ts(e,r+0),b=Ts(e,r+2),v=Ts(e,r+4),_=Ts(e,r+6),w=Ts(e,r+8),S=Ts(e,r+10),x=Ts(e,r+12),O=Ts(e,r+14),N=s[0]+(g&8191),k=s[1]+((g>>>13|b<<3)&8191),M=s[2]+((b>>>10|v<<6)&8191),K=s[3]+((v>>>7|_<<9)&8191),P=s[4]+((_>>>4|w<<12)&8191),j=s[5]+(w>>>1&8191),U=s[6]+((w>>>14|S<<2)&8191),q=s[7]+((S>>>11|x<<5)&8191),F=s[8]+((x>>>8|O<<8)&8191),Q=s[9]+(O>>>5|i),J=0,W=J+N*a+k*(5*y)+M*(5*h)+K*(5*m)+P*(5*f);J=W>>>13,W&=8191,W+=j*(5*p)+U*(5*d)+q*(5*u)+F*(5*l)+Q*(5*c),J+=W>>>13,W&=8191;let z=J+N*c+k*a+M*(5*y)+K*(5*h)+P*(5*m);J=z>>>13,z&=8191,z+=j*(5*f)+U*(5*p)+q*(5*d)+F*(5*u)+Q*(5*l),J+=z>>>13,z&=8191;let G=J+N*l+k*c+M*a+K*(5*y)+P*(5*h);J=G>>>13,G&=8191,G+=j*(5*m)+U*(5*f)+q*(5*p)+F*(5*d)+Q*(5*u),J+=G>>>13,G&=8191;let H=J+N*u+k*l+M*c+K*a+P*(5*y);J=H>>>13,H&=8191,H+=j*(5*h)+U*(5*m)+q*(5*f)+F*(5*p)+Q*(5*d),J+=H>>>13,H&=8191;let L=J+N*d+k*u+M*l+K*c+P*a;J=L>>>13,L&=8191,L+=j*(5*y)+U*(5*h)+q*(5*m)+F*(5*f)+Q*(5*p),J+=L>>>13,L&=8191;let B=J+N*p+k*d+M*u+K*l+P*c;J=B>>>13,B&=8191,B+=j*a+U*(5*y)+q*(5*h)+F*(5*m)+Q*(5*f),J+=B>>>13,B&=8191;let ie=J+N*f+k*p+M*d+K*u+P*l;J=ie>>>13,ie&=8191,ie+=j*c+U*a+q*(5*y)+F*(5*h)+Q*(5*m),J+=ie>>>13,ie&=8191;let xe=J+N*m+k*f+M*p+K*d+P*u;J=xe>>>13,xe&=8191,xe+=j*l+U*c+q*a+F*(5*y)+Q*(5*h),J+=xe>>>13,xe&=8191;let Ne=J+N*h+k*m+M*f+K*p+P*d;J=Ne>>>13,Ne&=8191,Ne+=j*u+U*l+q*c+F*a+Q*(5*y),J+=Ne>>>13,Ne&=8191;let bt=J+N*y+k*h+M*m+K*f+P*p;J=bt>>>13,bt&=8191,bt+=j*d+U*u+q*l+F*c+Q*a,J+=bt>>>13,bt&=8191,J=(J<<2)+J|0,J=J+W|0,W=J&8191,J=J>>>13,z+=J,s[0]=W,s[1]=z,s[2]=G,s[3]=H,s[4]=L,s[5]=B,s[6]=ie,s[7]=xe,s[8]=Ne,s[9]=bt}finalize(){let{h:e,pad:r}=this,n=new Uint16Array(10),i=e[1]>>>13;e[1]&=8191;for(let a=2;a<10;a++)e[a]+=i,i=e[a]>>>13,e[a]&=8191;e[0]+=i*5,i=e[0]>>>13,e[0]&=8191,e[1]+=i,i=e[1]>>>13,e[1]&=8191,e[2]+=i,n[0]=e[0]+5,i=n[0]>>>13,n[0]&=8191;for(let a=1;a<10;a++)n[a]=e[a]+i,i=n[a]>>>13,n[a]&=8191;n[9]-=8192;let s=(i^1)-1;for(let a=0;a<10;a++)n[a]&=s;s=~s;for(let a=0;a<10;a++)e[a]=e[a]&s|n[a];e[0]=(e[0]|e[1]<<13)&65535,e[1]=(e[1]>>>3|e[2]<<10)&65535,e[2]=(e[2]>>>6|e[3]<<7)&65535,e[3]=(e[3]>>>9|e[4]<<4)&65535,e[4]=(e[4]>>>12|e[5]<<1|e[6]<<14)&65535,e[5]=(e[6]>>>2|e[7]<<11)&65535,e[6]=(e[7]>>>5|e[8]<<8)&65535,e[7]=(e[8]>>>8|e[9]<<5)&65535;let o=e[0]+r[0];e[0]=o&65535;for(let a=1;a<8;a++)o=(e[a]+r[a]|0)+(o>>>16)|0,e[a]=o&65535;Ll(n)}update(e){GH(this),Dn(e),e=hv(e);let{buffer:r,blockLen:n}=this,i=e.length;for(let s=0;s<i;){let o=Math.min(n-this.pos,i-s);if(o===n){for(;n<=i-s;s+=n)this.process(e,s);continue}r.set(e.subarray(s,s+o),this.pos),this.pos+=o,s+=o,this.pos===n&&(this.process(r,0,!1),this.pos=0)}return this}destroy(){this.destroyed=!0,Ll(this.h,this.r,this.buffer,this.pad)}digestInto(e){GH(this),_fe(e,this),this.finished=!0;let{buffer:r,h:n}=this,{pos:i}=this;if(i){for(r[i++]=1;i<16;i++)r[i]=0;this.process(r,0,!0)}this.finalize();let s=0;for(let o=0;o<8;o++)e[s++]=n[o]>>>0,e[s++]=n[o]>>>8}digest(){let{buffer:e,outputLen:r}=this;this.digestInto(e);let n=e.slice(0,r);return this.destroy(),n}},Lfe=Ofe(32,t=>new ZH(t))});function snt(t,e,r,n,i,s=20){let o=t[0],a=t[1],c=t[2],l=t[3],u=e[0],d=e[1],p=e[2],f=e[3],m=e[4],h=e[5],y=e[6],g=e[7],b=i,v=r[0],_=r[1],w=r[2],S=o,x=a,O=c,N=l,k=u,M=d,K=p,P=f,j=m,U=h,q=y,F=g,Q=b,J=v,W=_,z=w;for(let H=0;H<s;H+=2)S=S+k|0,Q=Le(Q^S,16),j=j+Q|0,k=Le(k^j,12),S=S+k|0,Q=Le(Q^S,8),j=j+Q|0,k=Le(k^j,7),x=x+M|0,J=Le(J^x,16),U=U+J|0,M=Le(M^U,12),x=x+M|0,J=Le(J^x,8),U=U+J|0,M=Le(M^U,7),O=O+K|0,W=Le(W^O,16),q=q+W|0,K=Le(K^q,12),O=O+K|0,W=Le(W^O,8),q=q+W|0,K=Le(K^q,7),N=N+P|0,z=Le(z^N,16),F=F+z|0,P=Le(P^F,12),N=N+P|0,z=Le(z^N,8),F=F+z|0,P=Le(P^F,7),S=S+M|0,z=Le(z^S,16),q=q+z|0,M=Le(M^q,12),S=S+M|0,z=Le(z^S,8),q=q+z|0,M=Le(M^q,7),x=x+K|0,Q=Le(Q^x,16),F=F+Q|0,K=Le(K^F,12),x=x+K|0,Q=Le(Q^x,8),F=F+Q|0,K=Le(K^F,7),O=O+P|0,J=Le(J^O,16),j=j+J|0,P=Le(P^j,12),O=O+P|0,J=Le(J^O,8),j=j+J|0,P=Le(P^j,7),N=N+k|0,W=Le(W^N,16),U=U+W|0,k=Le(k^U,12),N=N+k|0,W=Le(W^N,8),U=U+W|0,k=Le(k^U,7);let G=0;n[G++]=o+S|0,n[G++]=a+x|0,n[G++]=c+O|0,n[G++]=l+N|0,n[G++]=u+k|0,n[G++]=d+M|0,n[G++]=p+K|0,n[G++]=f+P|0,n[G++]=m+j|0,n[G++]=h+U|0,n[G++]=y+q|0,n[G++]=g+F|0,n[G++]=b+Q|0,n[G++]=v+J|0,n[G++]=_+W|0,n[G++]=w+z|0}function ont(t,e,r,n){let i=ws(t[0]),s=ws(t[1]),o=ws(t[2]),a=ws(t[3]),c=ws(e[0]),l=ws(e[1]),u=ws(e[2]),d=ws(e[3]),p=ws(e[4]),f=ws(e[5]),m=ws(e[6]),h=ws(e[7]),y=ws(r[0]),g=ws(r[1]),b=ws(r[2]),v=ws(r[3]);for(let w=0;w<20;w+=2)i=i+c|0,y=Le(y^i,16),p=p+y|0,c=Le(c^p,12),i=i+c|0,y=Le(y^i,8),p=p+y|0,c=Le(c^p,7),s=s+l|0,g=Le(g^s,16),f=f+g|0,l=Le(l^f,12),s=s+l|0,g=Le(g^s,8),f=f+g|0,l=Le(l^f,7),o=o+u|0,b=Le(b^o,16),m=m+b|0,u=Le(u^m,12),o=o+u|0,b=Le(b^o,8),m=m+b|0,u=Le(u^m,7),a=a+d|0,v=Le(v^a,16),h=h+v|0,d=Le(d^h,12),a=a+d|0,v=Le(v^a,8),h=h+v|0,d=Le(d^h,7),i=i+l|0,v=Le(v^i,16),m=m+v|0,l=Le(l^m,12),i=i+l|0,v=Le(v^i,8),m=m+v|0,l=Le(l^m,7),s=s+u|0,y=Le(y^s,16),h=h+y|0,u=Le(u^h,12),s=s+u|0,y=Le(y^s,8),h=h+y|0,u=Le(u^h,7),o=o+d|0,g=Le(g^o,16),p=p+g|0,d=Le(d^p,12),o=o+d|0,g=Le(g^o,8),p=p+g|0,d=Le(d^p,7),a=a+c|0,b=Le(b^a,16),f=f+b|0,c=Le(c^f,12),a=a+c|0,b=Le(b^a,8),f=f+b|0,c=Le(c^f,7);let _=0;n[_++]=i,n[_++]=s,n[_++]=o,n[_++]=a,n[_++]=y,n[_++]=g,n[_++]=b,n[_++]=v,Yu(n)}function Kfe(t,e,r,n,i){i!==void 0&&Dn(i,void 0,"AAD");let s=t(e,r,lnt),o=Rfe(n.length,i?i.length:0,!0),a=Lfe.create(s);i&&Ufe(a,i),Ufe(a,n),a.update(o);let c=a.digest();return Ll(s,o),c}var ant,cnt,Ufe,lnt,unt,XH,qfe=I(()=>{Mfe();jfe();z0();ant=Dfe(snt,{counterRight:!1,counterLength:8,extendNonceFn:ont,allowShortKeys:!1}),cnt=new Uint8Array(16),Ufe=(t,e)=>{t.update(e);let r=e.length%16;r&&t.update(cnt.subarray(r))},lnt=new Uint8Array(32);unt=t=>(e,r,n)=>({encrypt(s,o){let a=s.length;o=F0(a+16,o,!1),o.set(s);let c=o.subarray(0,-16);t(e,r,c,c,1);let l=Kfe(t,e,r,c,n);return o.set(l,a),Ll(l),o},decrypt(s,o){o=F0(s.length-16,o,!1);let a=s.subarray(0,-16),c=s.subarray(-16),l=Kfe(t,e,r,a,n);if(!Afe(c,l))throw Ll(l),new Error("invalid tag");return o.set(s.subarray(0,-16)),t(e,r,o,o,1),Ll(l),o}}),XH=kfe({blockSize:64,nonceLength:24,tagLength:16},unt(ant))});function dnt(t){if(!t.startsWith(zfe))return null;let e=4,r=t.indexOf("$",e);if(r===-1)return null;let n=parseInt(t.slice(e,r),10);return!Number.isInteger(n)||n<0?null:{version:n,ciphertext:t.slice(r+1)}}function pnt(t,e){return`${zfe}${t}$${e}`}async function Ffe(t,e){let r=await op("SHA-256").digest(t),n=Tfe(e);return VH(YH(XH)(new Uint8Array(r)).encrypt(n))}async function QH(t,e){let r=await op("SHA-256").digest(t),n=wfe(e),i=YH(XH)(new Uint8Array(r));return new TextDecoder().decode(i.decrypt(n))}var zfe,_C,EC,SC=I(()=>{b0();K0();q0();qfe();z0();zfe="$ba$";_C=async({key:t,data:e})=>{if(typeof t=="string")return Ffe(t,e);let r=t.keys.get(t.currentVersion);if(!r)throw new Error(`Secret version ${t.currentVersion} not found in keys`);let n=await Ffe(r,e);return pnt(t.currentVersion,n)},EC=async({key:t,data:e})=>{if(typeof t=="string")return QH(t,e);let r=dnt(e);if(r){let n=t.keys.get(r.version);if(!n)throw new Error(`Secret version ${r.version} not found in keys (key may have been retired)`);return QH(n,r.ciphertext)}if(t.legacySecret)return QH(t.legacySecret,e);throw new Error("Cannot decrypt legacy bare-hex payload: no legacy secret available. Set BETTER_AUTH_SECRET for backwards compatibility.")}});var Zs,eW=I(()=>{Zs=t=>{let e=(t.plugins??[]).reduce((d,p)=>{let f=p.schema;if(!f)return d;for(let[m,h]of Object.entries(f))d[m]={fields:{...d[m]?.fields,...h.fields},modelName:h.modelName||m};return d},{}),r=t.rateLimit?.storage==="database",n={rateLimit:{modelName:t.rateLimit?.modelName||"rateLimit",fields:{key:{type:"string",unique:!0,required:!0,fieldName:t.rateLimit?.fields?.key||"key"},count:{type:"number",required:!0,fieldName:t.rateLimit?.fields?.count||"count"},lastRequest:{type:"number",bigint:!0,required:!0,fieldName:t.rateLimit?.fields?.lastRequest||"lastRequest",defaultValue:()=>Date.now()}}}},{user:i,session:s,account:o,verification:a,...c}=e,l={verification:{modelName:t.verification?.modelName||"verification",fields:{identifier:{type:"string",required:!0,fieldName:t.verification?.fields?.identifier||"identifier",index:!0},value:{type:"string",required:!0,fieldName:t.verification?.fields?.value||"value"},expiresAt:{type:"date",required:!0,fieldName:t.verification?.fields?.expiresAt||"expiresAt"},createdAt:{type:"date",required:!0,defaultValue:()=>new Date,fieldName:t.verification?.fields?.createdAt||"createdAt"},updatedAt:{type:"date",required:!0,defaultValue:()=>new Date,onUpdate:()=>new Date,fieldName:t.verification?.fields?.updatedAt||"updatedAt"},...a?.fields,...t.verification?.additionalFields},order:4}},u={session:{modelName:t.session?.modelName||"session",fields:{expiresAt:{type:"date",required:!0,fieldName:t.session?.fields?.expiresAt||"expiresAt"},token:{type:"string",required:!0,fieldName:t.session?.fields?.token||"token",unique:!0},createdAt:{type:"date",required:!0,fieldName:t.session?.fields?.createdAt||"createdAt",defaultValue:()=>new Date},updatedAt:{type:"date",required:!0,fieldName:t.session?.fields?.updatedAt||"updatedAt",onUpdate:()=>new Date},ipAddress:{type:"string",required:!1,fieldName:t.session?.fields?.ipAddress||"ipAddress"},userAgent:{type:"string",required:!1,fieldName:t.session?.fields?.userAgent||"userAgent"},userId:{type:"string",fieldName:t.session?.fields?.userId||"userId",references:{model:t.user?.modelName||"user",field:"id",onDelete:"cascade"},required:!0,index:!0},...s?.fields,...t.session?.additionalFields},order:2}};return{user:{modelName:t.user?.modelName||"user",fields:{name:{type:"string",required:!0,fieldName:t.user?.fields?.name||"name",sortable:!0},email:{type:"string",unique:!0,required:!0,fieldName:t.user?.fields?.email||"email",sortable:!0},emailVerified:{type:"boolean",defaultValue:!1,required:!0,fieldName:t.user?.fields?.emailVerified||"emailVerified",input:!1},image:{type:"string",required:!1,fieldName:t.user?.fields?.image||"image"},createdAt:{type:"date",defaultValue:()=>new Date,required:!0,fieldName:t.user?.fields?.createdAt||"createdAt"},updatedAt:{type:"date",defaultValue:()=>new Date,onUpdate:()=>new Date,required:!0,fieldName:t.user?.fields?.updatedAt||"updatedAt"},...i?.fields,...t.user?.additionalFields},order:1},...!t.secondaryStorage||t.session?.storeSessionInDatabase?u:{},account:{modelName:t.account?.modelName||"account",fields:{accountId:{type:"string",required:!0,fieldName:t.account?.fields?.accountId||"accountId"},providerId:{type:"string",required:!0,fieldName:t.account?.fields?.providerId||"providerId"},userId:{type:"string",references:{model:t.user?.modelName||"user",field:"id",onDelete:"cascade"},required:!0,fieldName:t.account?.fields?.userId||"userId",index:!0},accessToken:{type:"string",required:!1,returned:!1,fieldName:t.account?.fields?.accessToken||"accessToken"},refreshToken:{type:"string",required:!1,returned:!1,fieldName:t.account?.fields?.refreshToken||"refreshToken"},idToken:{type:"string",required:!1,returned:!1,fieldName:t.account?.fields?.idToken||"idToken"},accessTokenExpiresAt:{type:"date",required:!1,returned:!1,fieldName:t.account?.fields?.accessTokenExpiresAt||"accessTokenExpiresAt"},refreshTokenExpiresAt:{type:"date",required:!1,returned:!1,fieldName:t.account?.fields?.refreshTokenExpiresAt||"refreshTokenExpiresAt"},scope:{type:"string",required:!1,fieldName:t.account?.fields?.scope||"scope"},password:{type:"string",required:!1,returned:!1,fieldName:t.account?.fields?.password||"password"},createdAt:{type:"date",required:!0,fieldName:t.account?.fields?.createdAt||"createdAt",defaultValue:()=>new Date},updatedAt:{type:"date",required:!0,fieldName:t.account?.fields?.updatedAt||"updatedAt",onUpdate:()=>new Date},...o?.fields,...t.account?.additionalFields},order:3},...!t.secondaryStorage||t.verification?.storeInDatabase?l:{},...c,...r?n:{}}}});var Gh,Ju,gv=I(()=>{Gh=le(require("zod"),1),Ju=Gh.object({id:Gh.string(),createdAt:Gh.date().default(()=>new Date),updatedAt:Gh.date().default(()=>new Date)})});var Va,Bfe,Hfe=I(()=>{gv();Va=le(require("zod"),1),Bfe=Ju.extend({providerId:Va.string(),accountId:Va.string(),userId:Va.coerce.string(),accessToken:Va.string().nullish(),refreshToken:Va.string().nullish(),idToken:Va.string().nullish(),accessTokenExpiresAt:Va.date().nullish(),refreshTokenExpiresAt:Va.date().nullish(),scope:Va.string().nullish(),password:Va.string().nullish()})});var Vh,Wfe,$fe=I(()=>{Vh=le(require("zod"),1),Wfe=Vh.object({key:Vh.string(),count:Vh.number(),lastRequest:Vh.number()})});var jf,Gfe,Vfe=I(()=>{gv();jf=le(require("zod"),1),Gfe=Ju.extend({userId:jf.coerce.string(),expiresAt:jf.date(),token:jf.string(),ipAddress:jf.string().nullish(),userAgent:jf.string().nullish()})});var yv,Yfe,Jfe=I(()=>{gv();yv=le(require("zod"),1),Yfe=Ju.extend({email:yv.string().transform(t=>t.toLowerCase()),emailVerified:yv.boolean().default(!1),name:yv.string(),image:yv.string().nullish()})});var H0,Zfe,Xfe=I(()=>{gv();H0=le(require("zod"),1),Zfe=Ju.extend({value:H0.string(),expiresAt:H0.date(),identifier:H0.string()})});var tW={};ui(tW,{accountSchema:()=>Bfe,coreSchema:()=>Ju,getAuthTables:()=>Zs,rateLimitSchema:()=>Wfe,sessionSchema:()=>Gfe,userSchema:()=>Yfe,verificationSchema:()=>Zfe});var cp=I(()=>{eW();gv();Hfe();$fe();Vfe();Jfe();Xfe()});function Xs(t,e){if(!t||!e)return t;let r=Object.entries(e).filter(([,{returned:n}])=>n===!1).map(([n])=>n);return Object.entries(structuredClone(t)).filter(([n])=>!r.includes(n)).reduce((n,[i,s])=>({...n,[i]:s}),{})}var wC=I(()=>{});function Uf(t,e,r){let n=`${e}:${r}`;rW.has(t)||rW.set(t,new Map);let i=rW.get(t);if(i.has(n))return i.get(n);let s=r==="output"?Zs(t)[e]?.fields??{}:{},o=e==="user"||e==="session"||e==="account"?t[e]?.additionalFields:void 0,a={...s,...o??{}};for(let c of t.plugins||[])c.schema&&c.schema[e]&&(a={...a,...c.schema[e].fields});return i.set(n,a),a}function Br(t,e){return Xs(e,Uf(t,"user","output"))}function Wi(t,e){return Xs(e,Uf(t,"session","output"))}function TC(t,e){let{accessToken:r,refreshToken:n,idToken:i,accessTokenExpiresAt:s,refreshTokenExpiresAt:o,password:a,...c}=Xs(e,Uf(t,"account","output"));return c}function bv(t,e){let r=e.action||"create",n=e.fields,i=Object.create(null);for(let s in n){if(s in t){if(n[s].input===!1){if(n[s].defaultValue!==void 0&&r!=="update"){i[s]=n[s].defaultValue;continue}if(t[s])throw D.from("BAD_REQUEST",{...ae.FIELD_NOT_ALLOWED,message:`${s} is not allowed to be set`});continue}if(n[s].validator?.input&&t[s]!==void 0){let o=n[s].validator.input["~standard"].validate(t[s]);if(o instanceof Promise)throw D.from("INTERNAL_SERVER_ERROR",ae.ASYNC_VALIDATION_NOT_SUPPORTED);if("issues"in o&&o.issues)throw D.from("BAD_REQUEST",{...ae.VALIDATION_ERROR,message:o.issues[0]?.message||"Validation Error"});i[s]=o.value;continue}if(n[s].transform?.input&&t[s]!==void 0){i[s]=n[s].transform?.input(t[s]);continue}i[s]=t[s];continue}if(n[s].defaultValue!==void 0&&r==="create"){if(typeof n[s].defaultValue=="function"){i[s]=n[s].defaultValue();continue}i[s]=n[s].defaultValue;continue}if(n[s].required&&r==="create")throw D.from("BAD_REQUEST",{...ae.MISSING_FIELD,message:`${s} is required`})}return i}function vv(t,e={},r){return bv(e,{fields:Uf(t,"user","input"),action:r})}function Qfe(t,e){let r=Uf(t,"user","input");return bv(e||{},{fields:r})}function eme(t,e){return bv(e,{fields:Uf(t,"account","input")})}function xC(t,e,r){return bv(e,{fields:Uf(t,"session","input"),action:r})}function IC(t){let e=Uf(t,"session","input"),r={};for(let n in e)e[n].defaultValue!==void 0&&(r[n]=typeof e[n].defaultValue=="function"?e[n].defaultValue():e[n].defaultValue);return r}function AC(t,e){if(!e)return t;for(let r in e){let n=e[r]?.modelName;n&&(t[r].modelName=n);for(let i in t[r].fields){let s=e[r]?.fields?.[i];s&&(t[r].fields[i].fieldName=s)}}return t}var rW,jl=I(()=>{cp();rt();wC();rW=new WeakMap});var xo,Yh=I(()=>{xo=(t,e="ms")=>new Date(Date.now()+(e==="sec"?t*1e3:t))});function _v(t){return!!t&&(typeof t=="object"||typeof t=="function")&&typeof t.then=="function"}var OC=I(()=>{});function mnt(t){let e=fnt.exec(t);if(!e||e[4]&&e[1])throw new TypeError(`Invalid time string format: "${t}". Use formats like "7d", "30m", "1 hour", etc.`);let r=parseFloat(e[2]),n=e[3].toLowerCase(),i;switch(n){case"years":case"year":case"yrs":case"yr":case"y":i=r*315576e5;break;case"months":case"month":case"mo":i=r*2592e6;break;case"weeks":case"week":case"w":i=r*6048e5;break;case"days":case"day":case"d":i=r*864e5;break;case"hours":case"hour":case"hrs":case"hr":case"h":i=r*36e5;break;case"minutes":case"minute":case"mins":case"min":case"m":i=r*6e4;break;case"seconds":case"second":case"secs":case"sec":case"s":i=r*1e3;break;default:throw new TypeError(`Unknown time unit: "${n}"`)}return e[1]==="-"||e[4]==="ago"?-i:i}function tme(t){return Math.round(mnt(t)/1e3)}var fnt,rme=I(()=>{fnt=/^(\+|\-)? ?(\d+|\d+\.\d+) ?(seconds?|secs?|s|minutes?|mins?|m|hours?|hrs?|h|days?|d|weeks?|w|months?|mo|years?|yrs?|y)(?: (ago|from now))?$/i});var nme,ime=I(()=>{nme="__Secure-"});function sme(t){if(typeof t=="string"&&hnt.test(t)){let e=new Date(t);if(!isNaN(e.getTime()))return e}return t}function nW(t){if(t==null)return t;if(typeof t=="string")return sme(t);if(t instanceof Date)return t;if(Array.isArray(t))return t.map(nW);if(typeof t=="object"){let e={};for(let r of Object.keys(t))e[r]=nW(t[r]);return e}return t}function lr(t){try{return typeof t!="string"?t==null?null:nW(t):JSON.parse(t,(e,r)=>sme(r))}catch(e){return De.error("Error parsing JSON",{error:e}),null}}var hnt,lp=I(()=>{bs();hnt=/^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}(?:\.\d+)?Z$/});function gnt(t){let e=t.headers?.get("cookie");if(!e)return{};let r={},n=e.split("; ");for(let i of n){let[s,...o]=i.split("=");s&&o.length>0&&(r[s]=o.join("="))}return r}function ome(t){let e=t.split("."),r=e[e.length-1],n=parseInt(r||"0",10);return isNaN(n)?0:n}function ynt(t,e){let r={},n=gnt(e);for(let[i,s]of Object.entries(n))i.startsWith(t)&&(r[i]=s);return r}function bnt(t){return Object.keys(t).sort((e,r)=>ome(e)-ome(r)).map(e=>t[e]).join("")}function vnt(t,e,r,n){let i=Math.ceil(e.value.length/iW);if(i===1)return r[e.name]=e.value,[e];let s=[];for(let o=0;o<i;o++){let a=`${e.name}.${o}`,c=o*iW,l=e.value.substring(c,c+iW);s.push({...e,name:a,value:l}),r[a]=l}return n.debug(`CHUNKING_${t.toUpperCase()}_COOKIE`,{message:`${t} cookie exceeds allowed ${oW} bytes.`,emptyCookieSize:sW,valueSize:e.value.length,chunkCount:i,chunks:s.map(o=>o.value.length+sW)}),s}function ame(t,e){let r={};for(let n in t)r[n]={name:n,value:"",attributes:{...e,maxAge:0}};return r}function CC(t,e){let r=t.getCookie(e);if(r)return r;let n=[],i=t.headers?.get("cookie");if(!i)return null;let s={},o=i.split("; ");for(let a of o){let[c,...l]=a.split("=");c&&l.length>0&&(s[c]=l.join("="))}for(let[a,c]of Object.entries(s))if(a.startsWith(e+".")){let l=a.split(".").at(-1),u=parseInt(l||"0",10);isNaN(u)||n.push({index:u,value:c})}return n.length>0?(n.sort((a,c)=>a.index-c.index),n.map(a=>a.value).join("")):null}async function Kf(t,e){let r=t.context.authCookies.accountData,n={maxAge:300,...r.attributes},i=await gC(e,t.context.secretConfig,"better-auth-account",n.maxAge);if(i.length>oW){let s=kC(r.name,n,t),o=s.chunk(i,n);s.setCookies(o)}else{let s=kC(r.name,n,t);if(s.hasChunks()){let o=s.clean();s.setCookies(o)}t.setCookie(r.name,i,n)}}async function Ev(t){let e=CC(t,t.context.authCookies.accountData.name);if(e){let r=lr(await j0(e,t.context.secretConfig,"better-auth-account"));if(r)return r}return null}var Jh,oW,sW,iW,cme,RC,kC,lme,W0=I(()=>{U0();lp();Jh=le(require("zod"),1),oW=4096,sW=200,iW=oW-sW;cme=t=>(e,r,n)=>{let i=ynt(e,n),s=n.context.logger;return{getValue(){return bnt(i)},hasChunks(){return Object.keys(i).length>0},chunk(o,a){let c=ame(i,r);for(let d in i)delete i[d];let l=c,u=vnt(t,{name:e,value:o,attributes:{...r,...a}},i,s);for(let d of u)l[d.name]=d;return Object.values(l)},clean(){let o=ame(i,r);for(let a in i)delete i[a];return Object.values(o)},setCookies(o){for(let a of o)n.setCookie(a.name,a.value,a.attributes)}}},RC=cme("Session"),kC=cme("Account");lme=Jh.optional(Jh.object({disableCookieCache:Jh.coerce.boolean().meta({description:"Disable cookie cache and fetch session from database"}).optional(),disableRefresh:Jh.coerce.boolean().meta({description:"Disable session refresh. Useful for checking session status, without updating the session"}).optional()}))});var aW,_nt,cW,lW=I(()=>{aW=new Map,_nt=new TextEncoder,cW={decode:(t,e="utf-8")=>(aW.has(e)||aW.set(e,new TextDecoder(e)),aW.get(e).decode(t)),encode:_nt.encode}});var Ent,uW,ume=I(()=>{Ent="0123456789abcdef",uW={encode:t=>{if(typeof t=="string"&&(t=new TextEncoder().encode(t)),t.byteLength===0)return"";let e=new Uint8Array(t),r="";for(let n of e)r+=n.toString(16).padStart(2,"0");return r},decode:t=>{if(!t)return"";if(typeof t=="string"){if(t.length%2!==0)throw new Error("Invalid hexadecimal string");if(!new RegExp(`^[${Ent}]+$`).test(t))throw new Error("Invalid hexadecimal string");let e=new Uint8Array(t.length/2);for(let r=0;r<t.length;r+=2)e[r/2]=parseInt(t.slice(r,r+2),16);return new TextDecoder().decode(e)}return new TextDecoder().decode(t)}}});var NC,dW=I(()=>{ume();pa();K0();NC=(t="SHA-256",e="none")=>{let r={importKey:async(n,i)=>Ml().importKey("raw",typeof n=="string"?new TextEncoder().encode(n):n,{name:"HMAC",hash:{name:t}},!1,[i]),sign:async(n,i)=>{typeof n=="string"&&(n=await r.importKey(n,"sign"));let s=await Ml().sign("HMAC",n,typeof i=="string"?new TextEncoder().encode(i):i);return e==="hex"?uW.encode(s):e==="base64"||e==="base64url"||e==="base64urlnopad"?da.encode(s,{padding:e!=="base64urlnopad"}):s},verify:async(n,i,s)=>(typeof n=="string"&&(n=await r.importKey(n,"verify")),e==="hex"&&(s=uW.decode(s)),(e==="base64"||e==="base64url"||e==="base64urlnopad")&&(s=await Hi.decode(s)),Ml().verify("HMAC",n,typeof s=="string"?new TextEncoder().encode(s):s,typeof i=="string"?new TextEncoder().encode(i):i))};return r}});function $0(t){let e=typeof t.baseURL=="string"?t.baseURL:void 0,r=typeof t.baseURL=="object"&&t.baseURL!==null?t.baseURL.protocol:void 0,n=(t.advanced?.useSecureCookies!==void 0?t.advanced?.useSecureCookies:r==="https"||r!=="http"&&(e?e.startsWith("https://"):xf))?nme:"",i=!!t.advanced?.crossSubDomainCookies?.enabled,s=i?t.advanced?.crossSubDomainCookies?.domain||(e?new URL(e).hostname:void 0):void 0;if(i&&!s&&!Wa(t.baseURL))throw new me("baseURL is required when crossSubdomainCookies are enabled.");function o(a,c={}){let l=t.advanced?.cookiePrefix||"better-auth",u=t.advanced?.cookies?.[a]?.name||`${l}.${a}`,d=t.advanced?.cookies?.[a]?.attributes??{};return{name:`${n}${u}`,attributes:{secure:!!n,sameSite:"lax",path:"/",httpOnly:!0,...i?{domain:s}:{},...t.advanced?.defaultCookieAttributes,...c,...d}}}return o}function PC(t){let e=$0(t),r=e("session_token",{maxAge:t.session?.expiresIn||tme("7d")}),n=e("session_data",{maxAge:t.session?.cookieCache?.maxAge||300}),i=e("account_data",{maxAge:t.session?.cookieCache?.maxAge||300}),s=e("dont_remember");return{sessionToken:{name:r.name,attributes:r.attributes},sessionData:{name:n.name,attributes:n.attributes},dontRememberToken:{name:s.name,attributes:s.attributes},accountData:{name:i.name,attributes:i.attributes}}}async function G0(t,e,r){if(!t.context.options.session?.cookieCache?.enabled)return;let n=Xs(e.session,t.context.options.session?.additionalFields),i=Br(t.context.options,e.user),s=t.context.options.session?.cookieCache?.version,o="1";if(s){if(typeof s=="string")o=s;else if(typeof s=="function"){let p=s(e.session,e.user);o=_v(p)?await p:p}}let a={session:n,user:i,updatedAt:Date.now(),version:o},c={...t.context.authCookies.sessionData.attributes,maxAge:r?void 0:t.context.authCookies.sessionData.attributes.maxAge},l=xo(c.maxAge||60,"sec").getTime(),u=t.context.options.session?.cookieCache?.strategy||"compact",d;if(u==="jwe"?d=await gC(a,t.context.secretConfig,"better-auth-session",c.maxAge||300):u==="jwt"?d=await hC(a,t.context.secret,c.maxAge||300):d=da.encode(JSON.stringify({session:a,expiresAt:l,signature:await NC("SHA-256","base64urlnopad").sign(t.context.secret,JSON.stringify({...a,expiresAt:l}))}),{padding:!1}),d.length>4093){let p=RC(t.context.authCookies.sessionData.name,c,t),f=p.chunk(d,c);p.setCookies(f)}else{let p=RC(t.context.authCookies.sessionData.name,c,t);if(p.hasChunks()){let f=p.clean();p.setCookies(f)}t.setCookie(t.context.authCookies.sessionData.name,d,c)}if(t.context.options.account?.storeAccountCookie){let p=await Ev(t);p&&await Kf(t,p)}}async function jr(t,e,r,n){let i=await t.getSignedCookie(t.context.authCookies.dontRememberToken.name,t.context.secret);r=r!==void 0?r:!!i;let s=t.context.authCookies.sessionToken.attributes,o=r?void 0:t.context.sessionConfig.expiresIn;await t.setSignedCookie(t.context.authCookies.sessionToken.name,e.session.token,t.context.secret,{...s,maxAge:o,...n}),r&&await t.setSignedCookie(t.context.authCookies.dontRememberToken.name,"true",t.context.secret,t.context.authCookies.dontRememberToken.attributes),await G0(t,e,r),t.context.setNewSession(e)}function fa(t,e){t.setCookie(e.name,"",{...e.attributes,maxAge:0})}function qf(t,e){if(fa(t,t.context.authCookies.sessionToken),fa(t,t.context.authCookies.sessionData),t.context.options.account?.storeAccountCookie){fa(t,t.context.authCookies.accountData);let i=kC(t.context.authCookies.accountData.name,t.context.authCookies.accountData.attributes,t),s=i.clean();i.setCookies(s)}t.context.oauthConfig.storeStateStrategy==="cookie"&&fa(t,t.context.createAuthCookie("oauth_state"));let r=RC(t.context.authCookies.sessionData.name,t.context.authCookies.sessionData.attributes,t),n=r.clean();r.setCookies(n),e||fa(t,t.context.authCookies.dontRememberToken)}var Io=I(()=>{Kh();U0();jl();Yh();OC();rme();ime();W0();vs();rt();wC();pa();lW();dW()});async function pme(t,e,r){let n=tp(32);if(t.context.oauthConfig.storeStateStrategy==="cookie"){let o={...e,oauthState:n},a=await _C({key:t.context.secretConfig,data:JSON.stringify(o)}),c=t.context.createAuthCookie(r?.cookieName??"oauth_state",{maxAge:600});return t.setCookie(c.name,a,c.attributes),{state:n,codeVerifier:e.codeVerifier}}let i=t.context.createAuthCookie(r?.cookieName??"state",{maxAge:300});await t.setSignedCookie(i.name,n,t.context.secret,i.attributes);let s=new Date;if(s.setMinutes(s.getMinutes()+10),!await t.context.internalAdapter.createVerificationValue({value:JSON.stringify({...e,oauthState:n}),identifier:n,expiresAt:s}))throw new Zu("Unable to create verification. Make sure the database adapter is properly working and there is a verification table in the database",{code:"state_generation_error"});return{state:n,codeVerifier:e.codeVerifier}}async function fme(t,e,r){let n=t.context.oauthConfig.storeStateStrategy,i;if(n==="cookie"){let s=t.context.createAuthCookie(r?.cookieName??"oauth_state"),o=t.getCookie(s.name);if(!o)throw new Zu("State mismatch: auth state cookie not found",{code:"state_mismatch",details:{state:e}});try{let a=await EC({key:t.context.secretConfig,data:o});i=dme.parse(JSON.parse(a))}catch(a){throw new Zu("State invalid: Failed to decrypt or parse auth state",{code:"state_invalid",details:{state:e},cause:a})}if(!i.oauthState||i.oauthState!==e)throw new Zu("State mismatch: OAuth state parameter does not match stored state",{code:"state_security_mismatch",details:{state:e}});fa(t,s)}else{let s=await t.context.internalAdapter.findVerificationValue(e);if(!s)throw new Zu("State mismatch: verification not found",{code:"state_mismatch",details:{state:e}});if(i=dme.parse(JSON.parse(s.value)),i.oauthState!==void 0&&i.oauthState!==e)throw new Zu("State mismatch: OAuth state parameter does not match stored state",{code:"state_security_mismatch",details:{state:e}});let o=t.context.createAuthCookie(r?.cookieName??"state"),a=await t.getSignedCookie(o.name,t.context.secret);if(!(r?.skipStateCookieCheck??t.context.oauthConfig.skipStateCookieCheck)&&(!a||a!==e))throw new Zu("State mismatch: State not persisted correctly",{code:"state_security_mismatch",details:{state:e}});fa(t,o),await t.context.internalAdapter.deleteVerificationByIdentifier(e)}if(i.expiresAt<Date.now())throw new Zu("Invalid state: request expired",{code:"state_mismatch",details:{expiresAt:i.expiresAt}});return i}var xs,dme,Zu,mme=I(()=>{b0();SC();Io();rt();xs=le(require("zod"),1),dme=xs.looseObject({callbackURL:xs.string(),codeVerifier:xs.string(),errorURL:xs.string().optional(),newUserURL:xs.string().optional(),expiresAt:xs.number(),oauthState:xs.string().optional(),link:xs.object({email:xs.string(),userId:xs.coerce.string()}).optional(),requestSignUp:xs.boolean().optional()}),Zu=class extends me{code;details;constructor(t,e){super(t,e),this.code=e.code,this.details=e.details}}});function Zh(){return globalThis[V0]||(globalThis[V0]={version:pW,epoch:1,context:Snt},Y0=globalThis[V0]),Y0=globalThis[V0],Y0.version!==pW&&(Y0.version=pW,Y0.epoch++),globalThis[V0]}function fW(){return Zh().version}var V0,Y0,Snt,pW,J0=I(()=>{V0=Symbol.for("better-auth:global"),Y0=null,Snt={},pW="1.6.10"});async function Sv(){let t=await wnt;if(t===null)throw new Error("getAsyncLocalStorage is only available in server code");return t}var wnt,DC=I(()=>{wnt=import("node:async_hooks").then(t=>t.AsyncLocalStorage).catch(t=>{if("AsyncLocalStorage"in globalThis)return globalThis.AsyncLocalStorage;if(typeof window<"u")return null;throw console.warn("[better-auth] Warning: AsyncLocalStorage is not available in this environment. Some features may not work as expected."),console.warn("[better-auth] Please read more about this warning at https://better-auth.com/docs/installation#mount-handler"),console.warn("[better-auth] If you are using Cloudflare Workers, please see: https://developers.cloudflare.com/workers/configuration/compatibility-flags/#nodejs-compatibility-flag"),t})});async function up(){let t=(await hme()).getStore();if(!t)throw new Error("No auth context found. Please make sure you are calling this function within a `runWithEndpointContext` callback.");return t}async function wv(t,e){return(await hme()).run(t,e)}var hme,mW=I(()=>{J0();DC();hme=async()=>{let t=Zh();if(!t.context.endpointContextAsyncStorage){let e=await Sv();t.context.endpointContextAsyncStorage=new e}return t.context.endpointContextAsyncStorage}});async function yW(){return(await gW()).getStore()!==void 0}async function hW(){let t=(await gW()).getStore();if(!t)throw new Error("No request state found. Please make sure you are calling this function within a `runWithRequestState` callback.");return t}async function bW(t,e){return(await gW()).run(t,e)}function Z0(t){let e=Object.freeze({});return{get ref(){return e},async get(){let r=await hW();if(!r.has(e)){let n=await t();return r.set(e,n),n}return r.get(e)},async set(r){(await hW()).set(e,r)}}}var gW,gme=I(()=>{J0();DC();gW=async()=>{let t=Zh();if(!t.context.requestStateAsyncStorage){let e=await Sv();t.context.requestStateAsyncStorage=new e}return t.context.requestStateAsyncStorage}});var MC,Ue,vW,X0,Xh,yme=I(()=>{J0();DC();MC=async()=>{let t=Zh();if(!t.context.adapterAsyncStorage){let e=await Sv();t.context.adapterAsyncStorage=new e}return t.context.adapterAsyncStorage},Ue=async t=>MC().then(e=>e.getStore()?.adapter||t).catch(()=>t),vW=async(t,e)=>{let r=!1;return MC().then(async n=>{r=!0;let i=[],s,o,a=!1;try{s=await n.run({adapter:t,pendingHooks:i},e)}catch(c){o=c,a=!0}for(let c of i)await c();if(a)throw o;return s}).catch(n=>{if(!r)return e();throw n})},X0=async(t,e)=>{let r=!0;return MC().then(async n=>{r=!0;let i=[],s,o,a=!1;try{s=await t.transaction(async c=>n.run({adapter:c,pendingHooks:i},e))}catch(c){a=!0,o=c}for(let c of i)await c();if(a)throw o;return s}).catch(n=>{if(!r)return e();throw n})},Xh=async t=>MC().then(e=>{let r=e.getStore();if(r)r.pendingHooks.push(t);else return t()}).catch(()=>t())});var Xu=I(()=>{J0();mW();gme();yme()});var tZt,_W,bme=I(()=>{Xu();({get:tZt,set:_W}=Z0(()=>null))});async function LC(t,e,r){let n=t.body?.callbackURL||t.context.options.baseURL;if(!n)throw D.from("BAD_REQUEST",ae.CALLBACK_URL_REQUIRED);let i=tp(128),s={...r||{},callbackURL:n,codeVerifier:i,errorURL:t.body?.errorCallbackURL,newUserURL:t.body?.newUserCallbackURL,link:e,expiresAt:Date.now()+600*1e3,requestSignUp:t.body?.requestSignUp};await _W(s);try{return pme(t,s)}catch(o){throw t.context.logger.error("Failed to create verification",o),new D("INTERNAL_SERVER_ERROR",{message:"Unable to create verification",cause:o})}}async function vme(t){let e=t.query.state||t.body?.state,r=t.context.options.onAPIError?.errorURL||`${t.context.baseURL}/error`,n;try{n=await fme(t,e)}catch(i){throw t.context.logger.error("Failed to parse state",i),i instanceof Zu&&i.code==="state_security_mismatch"?t.redirect(`${r}?error=state_mismatch`):t.redirect(`${r}?error=please_restart_the_process`)}return n.errorURL||(n.errorURL=r),n&&await _W(n),n}var jC=I(()=>{b0();bme();mme();rt()});var Tv,UC=I(()=>{Tv={scope:"server"}});async function _me(t,e){let r=t.headers.get("content-type")||"",n=r.toLowerCase();if(t.body){if(e&&e.length>0&&!e.some(i=>{let s=n.split(";")[0].trim(),o=i.toLowerCase().trim();return s===o||s.includes(o)}))throw n?new ua(415,{message:`Content-Type "${r}" is not allowed. Allowed types: ${e.join(", ")}`,code:"UNSUPPORTED_MEDIA_TYPE"}):new ua(415,{message:`Content-Type is required. Allowed types: ${e.join(", ")}`,code:"UNSUPPORTED_MEDIA_TYPE"});if(Tnt.test(n))return await t.json();if(n.includes("application/x-www-form-urlencoded")){let i=await t.formData(),s={};return i.forEach((o,a)=>{s[a]=o.toString()}),s}if(n.includes("multipart/form-data")){let i=await t.formData(),s={};return i.forEach((o,a)=>{s[a]=o}),s}return n.includes("text/plain")?await t.text():n.includes("application/octet-stream")?await t.arrayBuffer():n.includes("application/pdf")||n.includes("image/")||n.includes("video/")?await t.blob():n.includes("application/stream")||t.body instanceof ReadableStream?t.body:await t.text()}}function dp(t){return t instanceof ua||t?.name==="APIError"}function Eme(t){try{return t.includes("%")?decodeURIComponent(t):t}catch{return t}}async function Sme(t){try{return{data:await t,error:null}}catch(e){return{data:null,error:e}}}function KC(t){return t instanceof Request||Object.prototype.toString.call(t)==="[object Request]"}var Tnt,Qh=I(()=>{If();Tnt=/^application\/([a-z0-9.+-]*\+)?json/i});function xnt(t){if(t===void 0)return!1;let e=typeof t;return e==="string"||e==="number"||e==="boolean"||e===null?!0:e!=="object"?!1:Array.isArray(t)?!0:t.buffer?!1:t.constructor&&t.constructor.name==="Object"||typeof t.toJSON=="function"}function Int(t,e,r){let n=0,i=new WeakMap;return JSON.stringify(t,(o,a)=>{if(typeof a=="bigint")return a.toString();if(typeof a=="object"&&a!==null){if(i.has(a))return`[Circular ref-${i.get(a)}]`;i.set(a,n++)}return e?e(o,a):a},r)}function Ant(t){return!t||typeof t!="object"?!1:"_flag"in t&&t._flag==="json"}function EW(t){for(let e of Ont)t.delete(e)}function Ul(t,e){if(t instanceof Response){if(e?.headers){let i=new Headers(e.headers);EW(i),i.forEach((s,o)=>{t.headers.set(o,s)})}return t}if(Ant(t)){let i=t.body,s=t.routerResponse;if(s instanceof Response)return s;let o=new Headers;i | |||
There was a problem hiding this comment.
The first try block (try{let Hnt=new URL(Bnt).host;if(Hnt&&s!==Hnt){}}catch{}) has a completely empty if body and an empty catch. It computes Hnt and evaluates the comparison but does nothing regardless of the result. This appears to be an earlier draft of the fix that was accidentally left in. The effective logic is only in the second inner if(Bnt) block, which is itself redundant because it is already inside the outer if(Bnt) guard.
Prompt To Fix With AI
This is a comment left during a code review.
Path: plugin/scripts/worker-service.cjs
Line: 787
Comment:
**Dead code in first try-block**
The first `try` block (`try{let Hnt=new URL(Bnt).host;if(Hnt&&s!==Hnt){}}catch{}`) has a completely empty `if` body and an empty `catch`. It computes `Hnt` and evaluates the comparison but does nothing regardless of the result. This appears to be an earlier draft of the fix that was accidentally left in. The effective logic is only in the second inner `if(Bnt)` block, which is itself redundant because it is already inside the outer `if(Bnt)` guard.
How can I resolve this? If you propose a fix, please make it concise.| @@ -784,7 +784,7 @@ return fn.apply(this, arguments) | |||
| </html> | |||
| `}function Ott(){return function(){this.error(404)}}function ktt(){return function(e){if(this.hasTrailingSlash()){this.error(404);return}var r=oH.original(this.req);r.path=null,r.pathname=Itt(r.pathname+"/");var n=_tt(Ttt.format(r)),i=Att("Redirecting","Redirecting to "+Ett(n));e.statusCode=301,e.setHeader("Content-Type","text/html; charset=UTF-8"),e.setHeader("Content-Length",Buffer.byteLength(i)),e.setHeader("Content-Security-Policy","default-src 'none'"),e.setHeader("X-Content-Type-Options","nosniff"),e.setHeader("Location",n),e.end(i)}}});var $ue=C((Hc,Wue)=>{"use strict";var AR=wce(),Rtt=require("node:events").EventEmitter,que=xce(),Fue=Cle(),zue=q4(),Bue=oue(),Hue=jue();Hc=Wue.exports=Ctt;function Ctt(){var t=function(e,r,n){t.handle(e,r,n)};return que(t,Rtt.prototype,!1),que(t,Fue,!1),t.request=Object.create(Bue,{app:{configurable:!0,enumerable:!0,writable:!0,value:t}}),t.response=Object.create(Hue,{app:{configurable:!0,enumerable:!0,writable:!0,value:t}}),t.init(),t}Hc.application=Fue;Hc.request=Bue;Hc.response=Hue;Hc.Route=zue.Route;Hc.Router=zue;Hc.json=AR.json;Hc.raw=AR.raw;Hc.static=Kue();Hc.text=AR.text;Hc.urlencoded=AR.urlencoded});var OR=C((WVt,Gue)=>{"use strict";Gue.exports=$ue()});var Zue=C((GVt,Jue)=>{"use strict";var Yue=Object.getOwnPropertySymbols,Ntt=Object.prototype.hasOwnProperty,Ptt=Object.prototype.propertyIsEnumerable;function Dtt(t){if(t==null)throw new TypeError("Object.assign cannot be called with null or undefined");return Object(t)}function Mtt(){try{if(!Object.assign)return!1;var t=new String("abc");if(t[5]="de",Object.getOwnPropertyNames(t)[0]==="5")return!1;for(var e={},r=0;r<10;r++)e["_"+String.fromCharCode(r)]=r;var n=Object.getOwnPropertyNames(e).map(function(s){return e[s]});if(n.join("")!=="0123456789")return!1;var i={};return"abcdefghijklmnopqrst".split("").forEach(function(s){i[s]=s}),Object.keys(Object.assign({},i)).join("")==="abcdefghijklmnopqrst"}catch{return!1}}Jue.exports=Mtt()?Object.assign:function(t,e){for(var r,n=Dtt(t),i,s=1;s<arguments.length;s++){r=Object(arguments[s]);for(var o in r)Ntt.call(r,o)&&(n[o]=r[o]);if(Yue){i=Yue(r);for(var a=0;a<i.length;a++)Ptt.call(r,i[a])&&(n[i[a]]=r[i[a]])}}return n}});var Que=C((VVt,Xue)=>{(function(){"use strict";var t=Zue(),e=nH(),r={origin:"*",methods:"GET,HEAD,PUT,PATCH,POST,DELETE",preflightContinue:!1,optionsSuccessStatus:204};function n(m){return typeof m=="string"||m instanceof String}function i(m,h){if(Array.isArray(h)){for(var y=0;y<h.length;++y)if(i(m,h[y]))return!0;return!1}else return n(h)?m===h:h instanceof RegExp?h.test(m):!!h}function s(m,h){var y=h.headers.origin,g=[],b;return!m.origin||m.origin==="*"?g.push([{key:"Access-Control-Allow-Origin",value:"*"}]):n(m.origin)?(g.push([{key:"Access-Control-Allow-Origin",value:m.origin}]),g.push([{key:"Vary",value:"Origin"}])):(b=i(y,m.origin),g.push([{key:"Access-Control-Allow-Origin",value:b?y:!1}]),g.push([{key:"Vary",value:"Origin"}])),g}function o(m){var h=m.methods;return h.join&&(h=m.methods.join(",")),{key:"Access-Control-Allow-Methods",value:h}}function a(m){return m.credentials===!0?{key:"Access-Control-Allow-Credentials",value:"true"}:null}function c(m,h){var y=m.allowedHeaders||m.headers,g=[];return y?y.join&&(y=y.join(",")):(y=h.headers["access-control-request-headers"],g.push([{key:"Vary",value:"Access-Control-Request-Headers"}])),y&&y.length&&g.push([{key:"Access-Control-Allow-Headers",value:y}]),g}function l(m){var h=m.exposedHeaders;if(h)h.join&&(h=h.join(","));else return null;return h&&h.length?{key:"Access-Control-Expose-Headers",value:h}:null}function u(m){var h=(typeof m.maxAge=="number"||m.maxAge)&&m.maxAge.toString();return h&&h.length?{key:"Access-Control-Max-Age",value:h}:null}function d(m,h){for(var y=0,g=m.length;y<g;y++){var b=m[y];b&&(Array.isArray(b)?d(b,h):b.key==="Vary"&&b.value?e(h,b.value):b.value&&h.setHeader(b.key,b.value))}}function p(m,h,y,g){var b=[],v=h.method&&h.method.toUpperCase&&h.method.toUpperCase();v==="OPTIONS"?(b.push(s(m,h)),b.push(a(m)),b.push(o(m)),b.push(c(m,h)),b.push(u(m)),b.push(l(m)),d(b,y),m.preflightContinue?g():(y.statusCode=m.optionsSuccessStatus,y.setHeader("Content-Length","0"),y.end())):(b.push(s(m,h)),b.push(a(m)),b.push(l(m)),d(b,y),g())}function f(m){var h=null;return typeof m=="function"?h=m:h=function(y,g){g(null,m)},function(g,b,v){h(g,function(_,w){if(_)v(_);else{var S=t({},r,w),x=null;S.origin&&typeof S.origin=="function"?x=S.origin:S.origin&&(x=function(O,N){N(null,S.origin)}),x?x(g.headers.origin,function(O,N){O||!N?v(O):(S.origin=N,p(S,g,b,v))}):v()}})}}Xue.exports=f})()});function rde(t,e,r,n){let i={error:t,message:e};return r&&(i.code=r),n&&(i.details=n),i}function ide(t,e){e.status(404).json(rde("NotFound",`Cannot ${t.method} ${t.path}`))}var Gs,nde,l0=I(()=>{"use strict";fe();Gs=class extends Error{constructor(r,n=500,i,s){super(r);this.statusCode=n;this.code=i;this.details=s;this.name="AppError"}statusCode;code;details};nde=(t,e,r,n)=>{let i=t instanceof Gs?t.statusCode:500;E.error("HTTP",`Error handling ${e.method} ${e.path}`,{statusCode:i,error:t.message,code:t instanceof Gs?t.code:void 0},t);let s=rde(t.name||"Error",t.message,t instanceof Gs?t.code:void 0,t instanceof Gs?t.details:void 0);r.status(i).json(s)}});function mH(t){return typeof t!="string"||t in{}}function hH(){return Object.create(null)}function pde(t){return typeof t=="string"&&!!t.trim()}function gH(t,e){var r=t.split(";").filter(pde),n=r.shift(),i=Ftt(n),s=i.name,o=i.value;if(e=e?Object.assign({},CR,e):CR,mH(s))return null;try{o=e.decodeValues?decodeURIComponent(o):o}catch(c){console.error("set-cookie-parser: failed to decode cookie value. Set options.decodeValues=false to disable decoding.",c)}var a=hH();return a.name=s,a.value=o,r.forEach(function(c){var l=c.split("="),u=l.shift().trimLeft().toLowerCase();if(!mH(u)){var d=l.join("=");if(u==="expires")a.expires=new Date(d);else if(u==="max-age"){var p=parseInt(d,10);Number.isNaN(p)||(a.maxAge=p)}else u==="secure"?a.secure=!0:u==="httponly"?a.httpOnly=!0:u==="samesite"?a.sameSite=d:u==="partitioned"?a.partitioned=!0:u&&(a[u]=d)}}),a}function Ftt(t){var e="",r="",n=t.split("=");return n.length>1?(e=n.shift(),r=n.join("=")):r=t,{name:e,value:r}}function Zb(t,e){if(e=e?Object.assign({},CR,e):CR,!t)return e.map?hH():[];if(t.headers)if(typeof t.headers.getSetCookie=="function")t=t.headers.getSetCookie();else if(t.headers["set-cookie"])t=t.headers["set-cookie"];else{var r=t.headers[Object.keys(t.headers).find(function(o){return o.toLowerCase()==="set-cookie"})];!r&&t.headers.cookie&&!e.silent&&console.warn("Warning: set-cookie-parser appears to have been called on a request object. It is designed to parse Set-Cookie headers from responses, not Cookie headers from requests. Set the option {silent: true} to suppress this warning."),t=r}var n=e.split,i=Array.isArray(t);if(n==="auto"&&(n=!i),i||(t=[t]),t=t.filter(pde),n&&(t=t.map(NR).flat()),e.map){var s=hH();return t.reduce(function(o,a){var c=gH(a,e);return c&&!mH(c.name)&&(o[c.name]=c),o},s)}else return t.map(function(o){return gH(o,e)}).filter(Boolean)}function NR(t){if(Array.isArray(t))return t;if(typeof t!="string")return[];var e=[],r=0,n,i,s,o,a;function c(){for(;r<t.length&&/\s/.test(t.charAt(r));)r+=1;return r<t.length}function l(){return i=t.charAt(r),i!=="="&&i!==";"&&i!==","}for(;r<t.length;){for(n=r,a=!1;c();)if(i=t.charAt(r),i===","){for(s=r,r+=1,c(),o=r;r<t.length&&l();)r+=1;r<t.length&&t.charAt(r)==="="?(a=!0,r=o,e.push(t.substring(n,s)),n=r):r=s+1}else r+=1;(!a||r>=t.length)&&e.push(t.substring(n,t.length))}return e}var CR,fde=I(()=>{CR={decodeValues:!0,map:!1,silent:!1,split:"auto"};Zb.parseSetCookie=Zb;Zb.parse=Zb;Zb.parseString=gH;Zb.splitCookiesString=NR});function Vtt(t,e){let r=t.headers;if(!r["content-type"])return null;let n=Number(r["content-length"]);if(t.httpVersionMajor===1&&isNaN(n)&&r["transfer-encoding"]==null||n===0)return null;let i=n;if(e){if(!i)i=e;else if(i>e)throw Error(`Received content-length of ${i}, but only accept up to ${e} bytes.`)}if(t.destroyed){let a=new ReadableStream;return a.cancel(),a}let s=0,o=!1;return new ReadableStream({start(a){t.on("error",c=>{o=!0,a.error(c)}),t.on("end",()=>{o||a.close()}),t.on("data",c=>{if(!o){if(s+=c.length,s>i){o=!0,a.error(new Error(`request body size exceeded ${n?"'content-length'":"BODY_SIZE_LIMIT"} of ${i}`));return}a.enqueue(c),(a.desiredSize===null||a.desiredSize<=0)&&t.pause()}})},pull(){t.resume()},cancel(a){o=!0,t.destroy(a)}})}function Ytt(t){let e=t.baseUrl,r=t.originalUrl;return!e||!r?e?e+t.url:t.url:e+t.url===r||r.split("?")[0].at(-1)==="/"?e+t.url:e}function gde({request:t,base:e,bodySizeLimit:r}){let n=t,i=Htt(t.headers),s,o=t.method;if(o!=="GET"&&o!=="HEAD"){if($tt(t))s=Vtt(t,r);else if(n.body!==void 0){let a=n.body,c=Gtt(a,i);s=new ReadableStream({start(l){l.enqueue(new TextEncoder().encode(c)),l.close()}})}}return new Request(e+Ytt(t),{duplex:"half",method:t.method,body:s,headers:t.headers})}async function yde(t,e){for(let[s,o]of e.headers)try{t.setHeader(s,s==="set-cookie"?NR(e.headers.get(s)):o)}catch(a){t.getHeaderNames().forEach(c=>t.removeHeader(c)),t.writeHead(500).end(String(a));return}if(t.statusCode=e.status,t.writeHead(e.status),!e.body){t.end();return}if(e.body.locked){t.end("Fatal error: Response body is locked. This can happen when the response was already read (for example through 'response.json()' or 'response.text()').");return}let r=e.body.getReader();if(t.destroyed){r.cancel();return}let n=s=>{t.off("close",n),t.off("error",n),r.cancel(s).catch(()=>{}),s&&t.destroy(s)};t.on("close",n),t.on("error",n),i();async function i(){try{for(;;){let{done:s,value:o}=await r.read();if(s)break;if(!t.write(o)){if(process.env.AWS_LAMBDA_FUNCTION_NAME||process.env.LAMBDA_TASK_ROOT)continue;t.once("drain",i);return}t.end()}}catch(s){n(s instanceof Error?s:new Error(String(s)))}}}var Btt,Htt,mde,hde,Wtt,$tt,Gtt,bde=I(()=>{fde();Btt=t=>Array.isArray(t)?t[0]:t,Htt=t=>{let e=Btt(t["content-type"]);return e?e.toLowerCase().startsWith("application/x-www-form-urlencoded"):!1},mde=t=>{if(typeof t!="object"||t===null)return!1;let e=Object.getPrototypeOf(t);return e===Object.prototype||e===null},hde=(t,e,r)=>{if(r!==void 0){if(Array.isArray(r)){for(let n of r)hde(t,e,n);return}if(r===null){t.append(e,"");return}if(mde(r)){t.append(e,JSON.stringify(r));return}t.append(e,`${r}`)}},Wtt=t=>{let e=new URLSearchParams;for(let[r,n]of Object.entries(t))hde(e,r,n);return e.toString()},$tt=t=>!t.destroyed&&t.readableEnded!==!0&&t.readable,Gtt=(t,e)=>typeof t=="string"?t:t instanceof URLSearchParams?t.toString():e&&mde(t)?Wtt(t):JSON.stringify(t)});function yH(t){return async(e,r)=>yde(r,await t(gde({base:`${e.headers["x-forwarded-proto"]||(e.socket.encrypted?"https":"http")}://${e.headers[":authority"]||e.headers.host}`,request:e})))}var vde=I(()=>{bde()});var _de={};ui(_de,{fromNodeHeaders:()=>Ztt,toNodeHandler:()=>Jtt});function Ztt(t){let e=new Headers;for(let[r,n]of Object.entries(t))n!==void 0&&(Array.isArray(n)?n.forEach(i=>e.append(r,i)):e.set(r,n));return e}var Jtt,Ede=I(()=>{vde();Jtt=t=>"handler"in t?yH(t.handler):yH(t)});function bH(t){return t==="-"||t==="^"||t==="$"||t==="+"||t==="."||t==="("||t===")"||t==="|"||t==="["||t==="]"||t==="{"||t==="}"||t==="*"||t==="?"||t==="\\"?`\\${t}`:t}function Xtt(t){let e="";for(let r=0;r<t.length;r++)e+=bH(t[r]);return e}function Sde(t,e=!0){if(Array.isArray(t))return`(?:${t.map(l=>`^${Sde(l,e)}$`).join("|")})`;let r="",n="",i=".";e===!0?(r="/",n="[/\\\\]",i="[^/\\\\]"):e&&(r=e,n=Xtt(r),n.length>1?(n=`(?:${n})`,i=`((?!${n}).)`):i=`[^${n}]`);let s=e?`${n}+?`:"",o=e?`${n}*?`:"",a=e?t.split(r):[t],c="";for(let l=0;l<a.length;l++){let u=a[l],d=a[l+1],p="";if(!(!u&&l>0)){if(e&&(l===a.length-1?p=o:d!=="**"?p=s:p=""),e&&u==="**"){p&&(c+=l===0?"":p,c+=`(?:${i}*?${p})*?`);continue}for(let f=0;f<u.length;f++){let m=u[f];m==="\\"?f<u.length-1&&(c+=bH(u[f+1]),f++):m==="?"?c+=i:m==="*"?c+=`${i}*?`:c+=bH(m)}c+=p}}return c}function Qtt(t,e){if(typeof e!="string")throw new TypeError(`Sample must be a string, but ${typeof e} given`);return t.test(e)}function Uh(t,e){if(typeof t!="string"&&!Array.isArray(t))throw new TypeError(`The first argument must be a single pattern string or an array of patterns, but ${typeof t} given`);if((typeof e=="string"||typeof e=="boolean")&&(e={separator:e}),arguments.length===2&&!(typeof e>"u"||typeof e=="object"&&e!==null&&!Array.isArray(e)))throw new TypeError(`The second argument must be an options object or a string/boolean separator, but ${typeof e} given`);if(e=e||{},e.separator==="\\")throw new Error("\\ is not a valid separator because it is used for escaping. Try setting the separator to `true` instead");let r=Sde(t,e.separator),n=new RegExp(`^${r}$`,e.flags),i=Qtt.bind(null,n);return i.options=e,i.pattern=t,i.regexp=n,i}var PR=I(()=>{});function ert(t){return t?t!=="false":!1}function hr(t,e){return typeof process<"u"&&process.env?process.env[t]??e:typeof Deno<"u"?Deno.env.get(t)??e:typeof Bun<"u"?Bun.env[t]??e:e}function MR(t,e=!0){let r=hr(t);return r?r!=="0"&&r.toLowerCase()!=="false"&&r!=="":e}var DR,p0,Zt,f0,xf,Jd,Nl,vH,_H=I(()=>{DR=Object.create(null),p0=t=>globalThis.process?.env||globalThis.Deno?.env.toObject()||globalThis.__env__||(t?DR:globalThis),Zt=new Proxy(DR,{get(t,e){return p0()[e]??DR[e]},has(t,e){return e in p0()||e in DR},set(t,e,r){let n=p0(!0);return n[e]=r,!0},deleteProperty(t,e){if(!e)return!1;let r=p0(!0);return delete r[e],!0},ownKeys(){let t=p0(!0);return Object.keys(t)}});f0=typeof process<"u"&&process.env&&process.env.NODE_ENV||"",xf=f0==="production",Jd=()=>f0==="dev"||f0==="development",Nl=()=>f0==="test"||ert(Zt.TEST);vH=Object.freeze({get BETTER_AUTH_SECRET(){return hr("BETTER_AUTH_SECRET")},get AUTH_SECRET(){return hr("AUTH_SECRET")},get BETTER_AUTH_TELEMETRY(){return hr("BETTER_AUTH_TELEMETRY")},get BETTER_AUTH_TELEMETRY_ID(){return hr("BETTER_AUTH_TELEMETRY_ID")},get NODE_ENV(){return hr("NODE_ENV","development")},get PACKAGE_VERSION(){return hr("PACKAGE_VERSION","0.0.0")},get BETTER_AUTH_TELEMETRY_ENDPOINT(){return hr("BETTER_AUTH_TELEMETRY_ENDPOINT","")}})});function LR(){if(hr("FORCE_COLOR")!==void 0)switch(hr("FORCE_COLOR")){case"":case"1":case"true":return Bi;case"2":return zu;case"3":return Ha;default:return m0}if(hr("NODE_DISABLE_COLORS")!==void 0&&hr("NODE_DISABLE_COLORS")!==""||hr("NO_COLOR")!==void 0&&hr("NO_COLOR")!==""||hr("TERM")==="dumb")return m0;if(hr("TMUX"))return Ha;if("TF_BUILD"in Zt&&"AGENT_NAME"in Zt)return Bi;if("CI"in Zt){for(let{0:t,1:e}of trt)if(t in Zt)return e;return hr("CI_NAME")==="codeship"?zu:m0}if("TEAMCITY_VERSION"in Zt)return/^(9\.(0*[1-9]\d*)\.|\d{2,}\.)/.exec(hr("TEAMCITY_VERSION"))!==null?Bi:m0;switch(hr("TERM_PROGRAM")){case"iTerm.app":return!hr("TERM_PROGRAM_VERSION")||/^[0-2]\./.exec(hr("TERM_PROGRAM_VERSION"))!==null?zu:Ha;case"HyperTerm":case"MacTerm":return Ha;case"Apple_Terminal":return zu}if(hr("COLORTERM")==="truecolor"||hr("COLORTERM")==="24bit")return Ha;if(hr("TERM")){if(/truecolor/.exec(hr("TERM"))!==null)return Ha;if(/^xterm-256/.exec(hr("TERM"))!==null)return zu;let t=hr("TERM").toLowerCase();if(wde[t])return wde[t];if(rrt.some(e=>e.exec(t)!==null))return Bi}return hr("COLORTERM")?Bi:m0}var m0,Bi,zu,Ha,wde,trt,rrt,EH=I(()=>{_H();m0=1,Bi=4,zu=8,Ha=24,wde={eterm:Bi,cons25:Bi,console:Bi,cygwin:Bi,dtterm:Bi,gnome:Bi,hurd:Bi,jfbterm:Bi,konsole:Bi,kterm:Bi,mlterm:Bi,mosh:Ha,putty:Bi,st:Bi,"rxvt-unicode-24bit":Ha,terminator:Ha,"xterm-kitty":Ha},trt=new Map(Object.entries({APPVEYOR:zu,BUILDKITE:zu,CIRCLECI:Ha,DRONE:zu,GITEA_ACTIONS:Ha,GITHUB_ACTIONS:Ha,GITLAB_CI:zu,TRAVIS:zu})),rrt=[/ansi/,/color/,/linux/,/direct/,/^con[0-9]*x[0-9]/,/^rxvt/,/^screen/,/^xterm/,/^vt100/,/^vt220/]});function Xb(t,e){return jR.indexOf(e)>=jR.indexOf(t)}var ni,jR,nrt,irt,Zd,De,bs=I(()=>{EH();ni={reset:"\x1B[0m",bright:"\x1B[1m",dim:"\x1B[2m",undim:"\x1B[22m",underscore:"\x1B[4m",blink:"\x1B[5m",reverse:"\x1B[7m",hidden:"\x1B[8m",fg:{black:"\x1B[30m",red:"\x1B[31m",green:"\x1B[32m",yellow:"\x1B[33m",blue:"\x1B[34m",magenta:"\x1B[35m",cyan:"\x1B[36m",white:"\x1B[37m"},bg:{black:"\x1B[40m",red:"\x1B[41m",green:"\x1B[42m",yellow:"\x1B[43m",blue:"\x1B[44m",magenta:"\x1B[45m",cyan:"\x1B[46m",white:"\x1B[47m"}},jR=["debug","info","success","warn","error"];nrt={info:ni.fg.blue,success:ni.fg.green,warn:ni.fg.yellow,error:ni.fg.red,debug:ni.fg.magenta},irt=(t,e,r)=>{let n=new Date().toISOString();return r?`${ni.dim}${n}${ni.reset} ${nrt[t]}${t.toUpperCase()}${ni.reset} ${ni.bright}[Better Auth]:${ni.reset} ${e}`:`${n} ${t.toUpperCase()} [Better Auth]: ${e}`},Zd=t=>{let e=t?.disabled!==!0,r=t?.level??"warn",n=t?.disableColors!==void 0?!t.disableColors:LR()!==1,i=(s,o,a=[])=>{if(!e||!Xb(r,s))return;let c=irt(s,o,n);if(!t||typeof t.log!="function"){s==="error"?console.error(c,...a):s==="warn"?console.warn(c,...a):console.log(c,...a);return}t.log(s==="success"?"info":s,o,...a)};return{...Object.fromEntries(jR.map(s=>[s,(...[o,...a])=>i(s,o,a)])),get level(){return r}}},De=Zd()});var vs=I(()=>{_H();bs()});function Qb(t){return Object.fromEntries(Object.entries(t).map(([e,r])=>[e,{code:e,message:r,toString:()=>e}]))}var h0=I(()=>{});var ae,Tde=I(()=>{h0();ae=Qb({USER_NOT_FOUND:"User not found",FAILED_TO_CREATE_USER:"Failed to create user",FAILED_TO_CREATE_SESSION:"Failed to create session",FAILED_TO_UPDATE_USER:"Failed to update user",FAILED_TO_GET_SESSION:"Failed to get session",INVALID_PASSWORD:"Invalid password",INVALID_EMAIL:"Invalid email",INVALID_EMAIL_OR_PASSWORD:"Invalid email or password",INVALID_USER:"Invalid user",SOCIAL_ACCOUNT_ALREADY_LINKED:"Social account already linked",PROVIDER_NOT_FOUND:"Provider not found",INVALID_TOKEN:"Invalid token",TOKEN_EXPIRED:"Token expired",ID_TOKEN_NOT_SUPPORTED:"id_token not supported",FAILED_TO_GET_USER_INFO:"Failed to get user info",USER_EMAIL_NOT_FOUND:"User email not found",EMAIL_NOT_VERIFIED:"Email not verified",PASSWORD_TOO_SHORT:"Password too short",PASSWORD_TOO_LONG:"Password too long",USER_ALREADY_EXISTS:"User already exists.",USER_ALREADY_EXISTS_USE_ANOTHER_EMAIL:"User already exists. Use another email.",EMAIL_CAN_NOT_BE_UPDATED:"Email can not be updated",CREDENTIAL_ACCOUNT_NOT_FOUND:"Credential account not found",SESSION_EXPIRED:"Session expired. Re-authenticate to perform this action.",FAILED_TO_UNLINK_LAST_ACCOUNT:"You can't unlink your last account",ACCOUNT_NOT_FOUND:"Account not found",USER_ALREADY_HAS_PASSWORD:"User already has a password. Provide that to delete the account.",CROSS_SITE_NAVIGATION_LOGIN_BLOCKED:"Cross-site navigation login blocked. This request appears to be a CSRF attack.",VERIFICATION_EMAIL_NOT_ENABLED:"Verification email isn't enabled",EMAIL_ALREADY_VERIFIED:"Email is already verified",EMAIL_MISMATCH:"Email mismatch",SESSION_NOT_FRESH:"Session is not fresh",LINKED_ACCOUNT_ALREADY_EXISTS:"Linked account already exists",INVALID_ORIGIN:"Invalid origin",INVALID_CALLBACK_URL:"Invalid callbackURL",INVALID_REDIRECT_URL:"Invalid redirectURL",INVALID_ERROR_CALLBACK_URL:"Invalid errorCallbackURL",INVALID_NEW_USER_CALLBACK_URL:"Invalid newUserCallbackURL",MISSING_OR_NULL_ORIGIN:"Missing or null Origin",CALLBACK_URL_REQUIRED:"callbackURL is required",FAILED_TO_CREATE_VERIFICATION:"Unable to create verification",FIELD_NOT_ALLOWED:"Field not allowed to be set",ASYNC_VALIDATION_NOT_SUPPORTED:"Async validation is not supported",VALIDATION_ERROR:"Validation Error",MISSING_FIELD:"Field is required",METHOD_NOT_ALLOWED_DEFER_SESSION_REQUIRED:"POST method requires deferSessionRefresh to be enabled in session config",BODY_MUST_BE_AN_OBJECT:"Body must be an object",PASSWORD_ALREADY_SET:"User already has a password set"})});function srt(){let t=Object.getOwnPropertyDescriptor(Error,"stackTraceLimit");return t===void 0?Object.isExtensible(Error):Object.prototype.hasOwnProperty.call(t,"writable")?t.writable:t.set!==void 0}function xde(t){let e=t.split(` | |||
| at `);return e.length<=1?t:(e.splice(1,1),e.join(` | |||
| at `))}function Ide(t,e){class r extends t{#e;constructor(...i){if(srt()){let o=Error.stackTraceLimit;Error.stackTraceLimit=0,super(...i),Error.stackTraceLimit=o}else super(...i);let s=new Error().stack;s&&(this.#e=xde(s.replace(/^Error/,this.name)))}get errorStack(){return this.#e}}return Object.defineProperty(r.prototype,"constructor",{get(){return e},enumerable:!1,configurable:!0}),r}var Ade,Ode,g0,UR,Xd,ua,If=I(()=>{Ade={OK:200,CREATED:201,ACCEPTED:202,NO_CONTENT:204,MULTIPLE_CHOICES:300,MOVED_PERMANENTLY:301,FOUND:302,SEE_OTHER:303,NOT_MODIFIED:304,TEMPORARY_REDIRECT:307,BAD_REQUEST:400,UNAUTHORIZED:401,PAYMENT_REQUIRED:402,FORBIDDEN:403,NOT_FOUND:404,METHOD_NOT_ALLOWED:405,NOT_ACCEPTABLE:406,PROXY_AUTHENTICATION_REQUIRED:407,REQUEST_TIMEOUT:408,CONFLICT:409,GONE:410,LENGTH_REQUIRED:411,PRECONDITION_FAILED:412,PAYLOAD_TOO_LARGE:413,URI_TOO_LONG:414,UNSUPPORTED_MEDIA_TYPE:415,RANGE_NOT_SATISFIABLE:416,EXPECTATION_FAILED:417,"I'M_A_TEAPOT":418,MISDIRECTED_REQUEST:421,UNPROCESSABLE_ENTITY:422,LOCKED:423,FAILED_DEPENDENCY:424,TOO_EARLY:425,UPGRADE_REQUIRED:426,PRECONDITION_REQUIRED:428,TOO_MANY_REQUESTS:429,REQUEST_HEADER_FIELDS_TOO_LARGE:431,UNAVAILABLE_FOR_LEGAL_REASONS:451,INTERNAL_SERVER_ERROR:500,NOT_IMPLEMENTED:501,BAD_GATEWAY:502,SERVICE_UNAVAILABLE:503,GATEWAY_TIMEOUT:504,HTTP_VERSION_NOT_SUPPORTED:505,VARIANT_ALSO_NEGOTIATES:506,INSUFFICIENT_STORAGE:507,LOOP_DETECTED:508,NOT_EXTENDED:510,NETWORK_AUTHENTICATION_REQUIRED:511},Ode=class extends Error{constructor(t="INTERNAL_SERVER_ERROR",e=void 0,r={},n=typeof t=="number"?t:Ade[t]){super(e?.message,e?.cause?{cause:e.cause}:void 0),this.status=t,this.body=e,this.headers=r,this.statusCode=n,this.name="APIError",this.status=t,this.headers=r,this.statusCode=n,this.body=e}},g0=class extends Ode{constructor(t,e){super(400,{message:t,code:"VALIDATION_ERROR"}),this.message=t,this.issues=e,this.issues=e}},UR=class extends Error{constructor(t){super(t),this.name="BetterCallError"}},Xd=Symbol.for("better-call:api-error-headers"),ua=Ide(Ode,Error)});var me,D,rt=I(()=>{Tde();If();me=class extends Error{constructor(t,e){super(t,e),this.name="BetterAuthError",this.message=t,this.stack=""}},D=class SH extends ua{constructor(...e){super(...e)}static fromStatus(e,r){return new SH(e,r)}static from(e,r){return new SH(e,{message:r.message,code:r.code})}}});function ort(t){let e=t.replace(/:\d+$/,"").replace(/^\[|\]$/g,"").toLowerCase();return e==="localhost"||e.endsWith(".localhost")||e==="::1"||e.startsWith("127.")}function art(t){try{return(new URL(t).pathname.replace(/\/+$/,"")||"/")!=="/"}catch{throw new me(`Invalid base URL: ${t}. Please provide a valid base URL.`)}}function crt(t){try{let e=new URL(t);if(e.protocol!=="http:"&&e.protocol!=="https:")throw new me(`Invalid base URL: ${t}. URL must include 'http://' or 'https://'`)}catch(e){throw e instanceof me?e:new me(`Invalid base URL: ${t}. Please provide a valid base URL.`,{cause:e})}}function Qd(t,e="/api/auth"){if(crt(t),art(t))return t;let r=t.replace(/\/+$/,"");return!e||e==="/"?r:(e=e.startsWith("/")?e:`/${e}`,`${r}${e}`)}function y0(t,e){return!t||t.trim()===""?!1:e==="proto"?t==="http"||t==="https":e==="host"?[/\.\./,/\0/,/[\s]/,/^[.]/,/[<>'"]/,/javascript:/i,/file:/i,/data:/i].some(r=>r.test(t))?!1:/^[a-zA-Z0-9]([a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?(\.[a-zA-Z0-9]([a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?)*(:[0-9]{1,5})?$/.test(t)||/^(\d{1,3}\.){3}\d{1,3}(:[0-9]{1,5})?$/.test(t)||/^\[[0-9a-fA-F:]+\](:[0-9]{1,5})?$/.test(t)||/^localhost(:[0-9]{1,5})?$/i.test(t):!1}function ep(t,e,r,n,i){if(t)return Qd(t,e);if(n!==!1){let a=Zt.BETTER_AUTH_URL||Zt.NEXT_PUBLIC_BETTER_AUTH_URL||Zt.PUBLIC_BETTER_AUTH_URL||Zt.NUXT_PUBLIC_BETTER_AUTH_URL||Zt.NUXT_PUBLIC_AUTH_URL||(Zt.BASE_URL!=="/"?Zt.BASE_URL:void 0);if(a)return Qd(a,e)}let s=r?.headers.get("x-forwarded-host"),o=r?.headers.get("x-forwarded-proto");if(s&&o&&i&&y0(o,"proto")&&y0(s,"host"))try{return Qd(`${o}://${s}`,e)}catch{}if(r){let a=Af(r.url);if(!a)throw new me("Could not get origin from request. Please provide a valid base URL.");return Qd(a,e)}if(typeof window<"u"&&window.location)return Qd(window.location.origin,e)}function Af(t){try{let e=new URL(t);return e.origin==="null"?null:e.origin}catch{return null}}function kde(t){try{return new URL(t).protocol}catch{return null}}function Rde(t){try{return new URL(t).host}catch{return null}}function Wa(t){return typeof t=="object"&&t!==null&&"allowedHosts"in t&&Array.isArray(t.allowedHosts)}function Bu(t){if(t instanceof Request)return!0;if(typeof t!="object"||t===null||Object.prototype.toString.call(t)!=="[object Request]")return!1;let e=t;return typeof e.url=="string"&&typeof e.headers=="object"&&e.headers!==null&&typeof e.headers.get=="function"}function Cde(t,e){let r=Bu(t)?t.headers:t;if(e){let i=r.get("x-forwarded-host");if(i&&y0(i,"host"))return i}let n=r.get("host");if(n&&y0(n,"host"))return n;if(Bu(t))try{return new URL(t.url).host}catch{return null}return null}function lrt(t,e,r){if(e==="http"||e==="https")return e;let n=Bu(t)?t.headers:t;if(r){let s=n.get("x-forwarded-proto");if(s&&y0(s,"proto"))return s}if(Bu(t))try{let s=new URL(t.url);if(s.protocol==="http:"||s.protocol==="https:")return s.protocol.slice(0,-1)}catch{}let i=Cde(t,r);return i&&ort(i)?"http":"https"}function drt(t,e,r,n){let i=Cde(e,n);if(!i){if(t.fallback)return Qd(t.fallback,r);throw new me("Could not determine host from request headers. Please provide a fallback URL in your baseURL config.")}if(t.allowedHosts.some(s=>urt(i,s)))return Qd(`${lrt(e,t.protocol,n)}://${i}`,r);if(t.fallback)return Qd(t.fallback,r);throw new me(`Host "${i}" is not in the allowed hosts list. Allowed hosts: ${t.allowedHosts.join(", ")}. Add this host to your allowedHosts config or provide a fallback URL.`)}function Nde(t,e,r,n,i){if(Wa(t))return r?drt(t,r,e,i):t.fallback?Qd(t.fallback,e):ep(void 0,e,void 0,n,i);let s=Bu(r)?r:void 0;return ep(typeof t=="string"?t:void 0,e,s,n,i)}var urt,Kh=I(()=>{PR();vs();rt();urt=(t,e)=>{if(!t||!e)return!1;let r=t.replace(/^https?:\/\//,"").split("/")[0].toLowerCase(),n=e.replace(/^https?:\/\//,"").split("/")[0].toLowerCase();return n.includes("*")||n.includes("?")?Uh(n)(r):r.toLowerCase()===n.toLowerCase()}});function Pde(t){switch(t){case"a-z":return"abcdefghijklmnopqrstuvwxyz";case"A-Z":return"ABCDEFGHIJKLMNOPQRSTUVWXYZ";case"0-9":return"0123456789";case"-_":return"-_";default:throw new Error(`Unsupported alphabet: ${t}`)}}function ev(...t){let e=t.map(Pde).join("");if(e.length===0)throw new Error("No valid characters provided for random string generation.");let r=e.length;return(n,...i)=>{if(n<=0)throw new Error("Length must be a positive integer.");let s=e,o=r;i.length>0&&(s=i.map(Pde).join(""),o=s.length);let a=Math.floor(256/o)*o,c=new Uint8Array(n*2),l=c.length,u="",d=l,p;for(;u.length<n;)d>=l&&(crypto.getRandomValues(c),d=0),p=c[d++],p<a&&(u+=s[p%o]);return u}}var KR=I(()=>{});var tp,b0=I(()=>{KR();tp=ev("a-z","0-9","A-Z","-_")});function prt(t){return t instanceof Uint8Array||ArrayBuffer.isView(t)&&t.constructor.name==="Uint8Array"&&"BYTES_PER_ELEMENT"in t&&t.BYTES_PER_ELEMENT===1}function qR(t,e=""){if(typeof t!="number"){let r=e&&`"${e}" `;throw new TypeError(`${r}expected number, got ${typeof t}`)}if(!Number.isSafeInteger(t)||t<0){let r=e&&`"${e}" `;throw new RangeError(`${r}expected integer >= 0, got ${t}`)}}function Of(t,e,r=""){let n=prt(t),i=t?.length,s=e!==void 0;if(!n||s&&i!==e){let o=r&&`"${r}" `,a=s?` of length ${e}`:"",c=n?`length=${i}`:`type=${typeof t}`,l=o+"expected Uint8Array"+a+", got "+c;throw n?new RangeError(l):new TypeError(l)}return t}function v0(t){if(typeof t!="function"||typeof t.create!="function")throw new TypeError("Hash must wrapped by utils.createHasher");if(qR(t.outputLen),qR(t.blockLen),t.outputLen<1)throw new Error('"outputLen" must be >= 1');if(t.blockLen<1)throw new Error('"blockLen" must be >= 1')}function tv(t,e=!0){if(t.destroyed)throw new Error("Hash instance has been destroyed");if(e&&t.finished)throw new Error("Hash#digest() has already been called")}function FR(t,e){Of(t,void 0,"digestInto() output");let r=e.outputLen;if(t.length<r)throw new RangeError('"digestInto() output" expected to be of length >='+r)}function rp(...t){for(let e=0;e<t.length;e++)t[e].fill(0)}function zR(t){return new DataView(t.buffer,t.byteOffset,t.byteLength)}function Pl(t,e){return t<<32-e|t>>>e}function Dde(t,e={}){let r=(i,s)=>t(s).update(i).digest(),n=t(void 0);return r.outputLen=n.outputLen,r.blockLen=n.blockLen,r.canXOF=n.canXOF,r.create=i=>t(i),Object.assign(r,e),Object.freeze(r)}var Mde,_0=I(()=>{Mde=t=>({oid:Uint8Array.from([6,9,96,134,72,1,101,3,4,2,t])})});var BR,wH,Lde=I(()=>{_0();BR=class{oHash;iHash;blockLen;outputLen;canXOF=!1;finished=!1;destroyed=!1;constructor(e,r){if(v0(e),Of(r,void 0,"key"),this.iHash=e.create(),typeof this.iHash.update!="function")throw new Error("Expected instance of class which extends utils.Hash");this.blockLen=this.iHash.blockLen,this.outputLen=this.iHash.outputLen;let n=this.blockLen,i=new Uint8Array(n);i.set(r.length>n?e.create().update(r).digest():r);for(let s=0;s<i.length;s++)i[s]^=54;this.iHash.update(i),this.oHash=e.create();for(let s=0;s<i.length;s++)i[s]^=106;this.oHash.update(i),rp(i)}update(e){return tv(this),this.iHash.update(e),this}digestInto(e){tv(this),FR(e,this),this.finished=!0;let r=e.subarray(0,this.outputLen);this.iHash.digestInto(r),this.oHash.update(r),this.oHash.digestInto(r),this.destroy()}digest(){let e=new Uint8Array(this.oHash.outputLen);return this.digestInto(e),e}_cloneInto(e){e||=Object.create(Object.getPrototypeOf(this),{});let{oHash:r,iHash:n,finished:i,destroyed:s,blockLen:o,outputLen:a}=this;return e=e,e.finished=i,e.destroyed=s,e.blockLen=o,e.outputLen=a,e.oHash=r._cloneInto(e.oHash),e.iHash=n._cloneInto(e.iHash),e}clone(){return this._cloneInto()}destroy(){this.destroyed=!0,this.oHash.destroy(),this.iHash.destroy()}},wH=(()=>{let t=((e,r,n)=>new BR(e,r).update(n).digest());return t.create=(e,r)=>new BR(e,r),t})()});function frt(t,e,r){return v0(t),r===void 0&&(r=new Uint8Array(t.outputLen)),wH(t,r,e)}function mrt(t,e,r,n=32){v0(t),qR(n,"length"),Of(e,void 0,"prk");let i=t.outputLen;if(e.length<i)throw new Error('"prk" must be at least HashLen octets');if(n>255*i)throw new Error("Length must be <= 255*HashLen");let s=Math.ceil(n/i);r===void 0?r=jde:Of(r,void 0,"info");let o=new Uint8Array(s*i),a=wH.create(t,e),c=a._cloneInto(),l=new Uint8Array(a.outputLen);for(let u=0;u<s;u++)TH[0]=u+1,c.update(u===0?jde:l).update(r).update(TH).digestInto(l),o.set(l,i*u),a._cloneInto(c);return a.destroy(),c.destroy(),rp(l,TH),o.slice(0,n)}var TH,jde,Ude,Kde=I(()=>{Lde();_0();TH=Uint8Array.of(0),jde=Uint8Array.of();Ude=(t,e,r,n,i)=>mrt(t,frt(t,e,r),n,i)});function qde(t,e,r){return t&e^~t&r}function Fde(t,e,r){return t&e^t&r^e&r}var HR,np,zde=I(()=>{_0();HR=class{blockLen;outputLen;canXOF=!1;padOffset;isLE;buffer;view;finished=!1;length=0;pos=0;destroyed=!1;constructor(e,r,n,i){this.blockLen=e,this.outputLen=r,this.padOffset=n,this.isLE=i,this.buffer=new Uint8Array(e),this.view=zR(this.buffer)}update(e){tv(this),Of(e);let{view:r,buffer:n,blockLen:i}=this,s=e.length;for(let o=0;o<s;){let a=Math.min(i-this.pos,s-o);if(a===i){let c=zR(e);for(;i<=s-o;o+=i)this.process(c,o);continue}n.set(e.subarray(o,o+a),this.pos),this.pos+=a,o+=a,this.pos===i&&(this.process(r,0),this.pos=0)}return this.length+=e.length,this.roundClean(),this}digestInto(e){tv(this),FR(e,this),this.finished=!0;let{buffer:r,view:n,blockLen:i,isLE:s}=this,{pos:o}=this;r[o++]=128,rp(this.buffer.subarray(o)),this.padOffset>i-o&&(this.process(n,0),o=0);for(let d=o;d<i;d++)r[d]=0;n.setBigUint64(i-8,BigInt(this.length*8),s),this.process(n,0);let a=zR(e),c=this.outputLen;if(c%4)throw new Error("_sha2: outputLen must be aligned to 32bit");let l=c/4,u=this.get();if(l>u.length)throw new Error("_sha2: outputLen bigger than state");for(let d=0;d<l;d++)a.setUint32(4*d,u[d],s)}digest(){let{buffer:e,outputLen:r}=this;this.digestInto(e);let n=e.slice(0,r);return this.destroy(),n}_cloneInto(e){e||=new this.constructor,e.set(...this.get());let{blockLen:r,buffer:n,length:i,finished:s,destroyed:o,pos:a}=this;return e.destroyed=o,e.finished=s,e.length=i,e.pos=a,i%r&&e.buffer.set(n),e}clone(){return this._cloneInto()}},np=Uint32Array.from([1779033703,3144134277,1013904242,2773480762,1359893119,2600822924,528734635,1541459225])});var hrt,kf,xH,IH,Bde,Hde=I(()=>{zde();_0();hrt=Uint32Array.from([1116352408,1899447441,3049323471,3921009573,961987163,1508970993,2453635748,2870763221,3624381080,310598401,607225278,1426881987,1925078388,2162078206,2614888103,3248222580,3835390401,4022224774,264347078,604807628,770255983,1249150122,1555081692,1996064986,2554220882,2821834349,2952996808,3210313671,3336571891,3584528711,113926993,338241895,666307205,773529912,1294757372,1396182291,1695183700,1986661051,2177026350,2456956037,2730485921,2820302411,3259730800,3345764771,3516065817,3600352804,4094571909,275423344,430227734,506948616,659060556,883997877,958139571,1322822218,1537002063,1747873779,1955562222,2024104815,2227730452,2361852424,2428436474,2756734187,3204031479,3329325298]),kf=new Uint32Array(64),xH=class extends HR{constructor(e){super(64,e,8,!1)}get(){let{A:e,B:r,C:n,D:i,E:s,F:o,G:a,H:c}=this;return[e,r,n,i,s,o,a,c]}set(e,r,n,i,s,o,a,c){this.A=e|0,this.B=r|0,this.C=n|0,this.D=i|0,this.E=s|0,this.F=o|0,this.G=a|0,this.H=c|0}process(e,r){for(let d=0;d<16;d++,r+=4)kf[d]=e.getUint32(r,!1);for(let d=16;d<64;d++){let p=kf[d-15],f=kf[d-2],m=Pl(p,7)^Pl(p,18)^p>>>3,h=Pl(f,17)^Pl(f,19)^f>>>10;kf[d]=h+kf[d-7]+m+kf[d-16]|0}let{A:n,B:i,C:s,D:o,E:a,F:c,G:l,H:u}=this;for(let d=0;d<64;d++){let p=Pl(a,6)^Pl(a,11)^Pl(a,25),f=u+p+qde(a,c,l)+hrt[d]+kf[d]|0,h=(Pl(n,2)^Pl(n,13)^Pl(n,22))+Fde(n,i,s)|0;u=l,l=c,c=a,a=o+f|0,o=s,s=i,i=n,n=f+h|0}n=n+this.A|0,i=i+this.B|0,s=s+this.C|0,o=o+this.D|0,a=a+this.E|0,c=c+this.F|0,l=l+this.G|0,u=u+this.H|0,this.set(n,i,s,o,a,c,l,u)}roundClean(){rp(kf)}destroy(){this.destroyed=!0,this.set(0,0,0,0,0,0,0,0),rp(this.buffer)}},IH=class extends xH{A=np[0]|0;B=np[1]|0;C=np[2]|0;D=np[3]|0;E=np[4]|0;F=np[5]|0;G=np[6]|0;H=np[7]|0;constructor(){super(32)}},Bde=Dde(()=>new IH,Mde(1))});function fi(...t){let e=t.reduce((i,{length:s})=>i+s,0),r=new Uint8Array(e),n=0;for(let i of t)r.set(i,n),n+=i.length;return r}function AH(t,e,r){if(e<0||e>=WR)throw new RangeError(`value must be >= 0 and <= ${WR-1}. Received ${e}`);t.set([e>>>24,e>>>16,e>>>8,e&255],r)}function OH(t){let e=Math.floor(t/WR),r=t%WR,n=new Uint8Array(8);return AH(n,e,0),AH(n,r,4),n}function $R(t){let e=new Uint8Array(4);return AH(e,t),e}function Bn(t){let e=new Uint8Array(t.length);for(let r=0;r<t.length;r++){let n=t.charCodeAt(r);if(n>127)throw new TypeError("non-ASCII string encountered in encode()");e[r]=n}return e}var qh,_s,WR,Vs=I(()=>{qh=new TextEncoder,_s=new TextDecoder,WR=2**32});function Wde(t){if(Uint8Array.prototype.toBase64)return t.toBase64();let e=32768,r=[];for(let n=0;n<t.length;n+=e)r.push(String.fromCharCode.apply(null,t.subarray(n,n+e)));return btoa(r.join(""))}function $de(t){if(Uint8Array.fromBase64)return Uint8Array.fromBase64(t);let e=atob(t),r=new Uint8Array(e.length);for(let n=0;n<e.length;n++)r[n]=e.charCodeAt(n);return r}var Gde=I(()=>{});var E0={};ui(E0,{decode:()=>_o,encode:()=>bn});function _o(t){if(Uint8Array.fromBase64)return Uint8Array.fromBase64(typeof t=="string"?t:_s.decode(t),{alphabet:"base64url"});let e=t;e instanceof Uint8Array&&(e=_s.decode(e)),e=e.replace(/-/g,"+").replace(/_/g,"/");try{return $de(e)}catch{throw new TypeError("The input to be decoded is not correctly encoded.")}}function bn(t){let e=t;return typeof e=="string"&&(e=qh.encode(e)),Uint8Array.prototype.toBase64?e.toBase64({alphabet:"base64url",omitPadding:!0}):Wde(e).replace(/=/g,"").replace(/\+/g,"-").replace(/\//g,"_")}var Ys=I(()=>{Vs();Gde()});function grt(t){return parseInt(t.name.slice(4),10)}function GR(t,e){if(grt(t.hash)!==e)throw Eo(`SHA-${e}`,"algorithm.hash")}function yrt(t){switch(t){case"ES256":return"P-256";case"ES384":return"P-384";case"ES512":return"P-521";default:throw new Error("unreachable")}}function Vde(t,e){if(e&&!t.usages.includes(e))throw new TypeError(`CryptoKey does not support this operation, its usages must include ${e}.`)}function Yde(t,e,r){switch(e){case"HS256":case"HS384":case"HS512":{if(!Hu(t.algorithm,"HMAC"))throw Eo("HMAC");GR(t.algorithm,parseInt(e.slice(2),10));break}case"RS256":case"RS384":case"RS512":{if(!Hu(t.algorithm,"RSASSA-PKCS1-v1_5"))throw Eo("RSASSA-PKCS1-v1_5");GR(t.algorithm,parseInt(e.slice(2),10));break}case"PS256":case"PS384":case"PS512":{if(!Hu(t.algorithm,"RSA-PSS"))throw Eo("RSA-PSS");GR(t.algorithm,parseInt(e.slice(2),10));break}case"Ed25519":case"EdDSA":{if(!Hu(t.algorithm,"Ed25519"))throw Eo("Ed25519");break}case"ML-DSA-44":case"ML-DSA-65":case"ML-DSA-87":{if(!Hu(t.algorithm,e))throw Eo(e);break}case"ES256":case"ES384":case"ES512":{if(!Hu(t.algorithm,"ECDSA"))throw Eo("ECDSA");let n=yrt(e);if(t.algorithm.namedCurve!==n)throw Eo(n,"algorithm.namedCurve");break}default:throw new TypeError("CryptoKey does not support this operation")}Vde(t,r)}function $a(t,e,r){switch(e){case"A128GCM":case"A192GCM":case"A256GCM":{if(!Hu(t.algorithm,"AES-GCM"))throw Eo("AES-GCM");let n=parseInt(e.slice(1,4),10);if(t.algorithm.length!==n)throw Eo(n,"algorithm.length");break}case"A128KW":case"A192KW":case"A256KW":{if(!Hu(t.algorithm,"AES-KW"))throw Eo("AES-KW");let n=parseInt(e.slice(1,4),10);if(t.algorithm.length!==n)throw Eo(n,"algorithm.length");break}case"ECDH":{switch(t.algorithm.name){case"ECDH":case"X25519":break;default:throw Eo("ECDH or X25519")}break}case"PBES2-HS256+A128KW":case"PBES2-HS384+A192KW":case"PBES2-HS512+A256KW":if(!Hu(t.algorithm,"PBKDF2"))throw Eo("PBKDF2");break;case"RSA-OAEP":case"RSA-OAEP-256":case"RSA-OAEP-384":case"RSA-OAEP-512":{if(!Hu(t.algorithm,"RSA-OAEP"))throw Eo("RSA-OAEP");GR(t.algorithm,parseInt(e.slice(9),10)||1);break}default:throw new TypeError("CryptoKey does not support this operation")}Vde(t,r)}var Eo,Hu,Fh=I(()=>{Eo=(t,e="algorithm.name")=>new TypeError(`CryptoKey does not support this operation, its ${e} must be ${t}`),Hu=(t,e)=>t.name===e});function Jde(t,e,...r){if(r=r.filter(Boolean),r.length>2){let n=r.pop();t+=`one of type ${r.join(", ")}, or ${n}.`}else r.length===2?t+=`one of type ${r[0]} or ${r[1]}.`:t+=`of type ${r[0]}.`;return e==null?t+=` Received ${e}`:typeof e=="function"&&e.name?t+=` Received function ${e.name}`:typeof e=="object"&&e!=null&&e.constructor?.name&&(t+=` Received an instance of ${e.constructor.name}`),t}var Wu,kH,rv=I(()=>{Wu=(t,...e)=>Jde("Key must be ",t,...e),kH=(t,e,...r)=>Jde(`Key for the ${t} algorithm must be `,e,...r)});var Si,Es,zh,Bh,Pt,nv,Me,zr,Js,VR,S0,iv,YR,JR,ZR,cn=I(()=>{Si=class extends Error{static code="ERR_JOSE_GENERIC";code="ERR_JOSE_GENERIC";constructor(e,r){super(e,r),this.name=this.constructor.name,Error.captureStackTrace?.(this,this.constructor)}},Es=class extends Si{static code="ERR_JWT_CLAIM_VALIDATION_FAILED";code="ERR_JWT_CLAIM_VALIDATION_FAILED";claim;reason;payload;constructor(e,r,n="unspecified",i="unspecified"){super(e,{cause:{claim:n,reason:i,payload:r}}),this.claim=n,this.reason=i,this.payload=r}},zh=class extends Si{static code="ERR_JWT_EXPIRED";code="ERR_JWT_EXPIRED";claim;reason;payload;constructor(e,r,n="unspecified",i="unspecified"){super(e,{cause:{claim:n,reason:i,payload:r}}),this.claim=n,this.reason=i,this.payload=r}},Bh=class extends Si{static code="ERR_JOSE_ALG_NOT_ALLOWED";code="ERR_JOSE_ALG_NOT_ALLOWED"},Pt=class extends Si{static code="ERR_JOSE_NOT_SUPPORTED";code="ERR_JOSE_NOT_SUPPORTED"},nv=class extends Si{static code="ERR_JWE_DECRYPTION_FAILED";code="ERR_JWE_DECRYPTION_FAILED";constructor(e="decryption operation failed",r){super(e,r)}},Me=class extends Si{static code="ERR_JWE_INVALID";code="ERR_JWE_INVALID"},zr=class extends Si{static code="ERR_JWS_INVALID";code="ERR_JWS_INVALID"},Js=class extends Si{static code="ERR_JWT_INVALID";code="ERR_JWT_INVALID"},VR=class extends Si{static code="ERR_JWK_INVALID";code="ERR_JWK_INVALID"},S0=class extends Si{static code="ERR_JWKS_INVALID";code="ERR_JWKS_INVALID"},iv=class extends Si{static code="ERR_JWKS_NO_MATCHING_KEY";code="ERR_JWKS_NO_MATCHING_KEY";constructor(e="no applicable key found in the JSON Web Key Set",r){super(e,r)}},YR=class extends Si{[Symbol.asyncIterator];static code="ERR_JWKS_MULTIPLE_MATCHING_KEYS";code="ERR_JWKS_MULTIPLE_MATCHING_KEYS";constructor(e="multiple matching keys found in the JSON Web Key Set",r){super(e,r)}},JR=class extends Si{static code="ERR_JWKS_TIMEOUT";code="ERR_JWKS_TIMEOUT";constructor(e="request timed out",r){super(e,r)}},ZR=class extends Si{static code="ERR_JWS_SIGNATURE_VERIFICATION_FAILED";code="ERR_JWS_SIGNATURE_VERIFICATION_FAILED";constructor(e="signature verification failed",r){super(e,r)}}});function sv(t){if(!ip(t))throw new Error("CryptoKey instance expected")}var ip,w0,T0,Hh=I(()=>{ip=t=>{if(t?.[Symbol.toStringTag]==="CryptoKey")return!0;try{return t instanceof CryptoKey}catch{return!1}},w0=t=>t?.[Symbol.toStringTag]==="KeyObject",T0=t=>ip(t)||w0(t)});function QR(t){switch(t){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 Pt(`Unsupported JWE Algorithm: ${t}`)}}function XR(t,e){let r=t.byteLength<<3;if(r!==e)throw new Me(`Invalid Content Encryption Key length. Expected ${e} bits, got ${r} bits`)}function Zde(t){switch(t){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 Pt(`Unsupported JWE Algorithm: ${t}`)}}function Xde(t,e){if(e.length<<3!==Zde(t))throw new Me("Invalid Initialization Vector length")}async function Qde(t,e,r){if(!(e instanceof Uint8Array))throw new TypeError(Wu(e,"Uint8Array"));let n=parseInt(t.slice(1,4),10),i=await crypto.subtle.importKey("raw",e.subarray(n>>3),"AES-CBC",!1,[r]),s=await crypto.subtle.importKey("raw",e.subarray(0,n>>3),{hash:`SHA-${n<<1}`,name:"HMAC"},!1,["sign"]);return{encKey:i,macKey:s,keySize:n}}async function epe(t,e,r){return new Uint8Array((await crypto.subtle.sign("HMAC",t,e)).slice(0,r>>3))}async function vrt(t,e,r,n,i){let{encKey:s,macKey:o,keySize:a}=await Qde(t,r,"encrypt"),c=new Uint8Array(await crypto.subtle.encrypt({iv:n,name:"AES-CBC"},s,e)),l=fi(i,n,c,OH(i.length<<3)),u=await epe(o,l,a);return{ciphertext:c,tag:u,iv:n}}async function _rt(t,e){if(!(t instanceof Uint8Array))throw new TypeError("First argument must be a buffer");if(!(e instanceof Uint8Array))throw new TypeError("Second argument must be a buffer");let r={name:"HMAC",hash:"SHA-256"},n=await crypto.subtle.generateKey(r,!1,["sign"]),i=new Uint8Array(await crypto.subtle.sign(r,n,t)),s=new Uint8Array(await crypto.subtle.sign(r,n,e)),o=0,a=-1;for(;++a<32;)o|=i[a]^s[a];return o===0}async function Ert(t,e,r,n,i,s){let{encKey:o,macKey:a,keySize:c}=await Qde(t,e,"decrypt"),l=fi(s,n,r,OH(s.length<<3)),u=await epe(a,l,c),d;try{d=await _rt(i,u)}catch{}if(!d)throw new nv;let p;try{p=new Uint8Array(await crypto.subtle.decrypt({iv:n,name:"AES-CBC"},o,r))}catch{}if(!p)throw new nv;return p}async function Srt(t,e,r,n,i){let s;r instanceof Uint8Array?s=await crypto.subtle.importKey("raw",r,"AES-GCM",!1,["encrypt"]):($a(r,t,"encrypt"),s=r);let o=new Uint8Array(await crypto.subtle.encrypt({additionalData:i,iv:n,name:"AES-GCM",tagLength:128},s,e)),a=o.slice(-16);return{ciphertext:o.slice(0,-16),tag:a,iv:n}}async function wrt(t,e,r,n,i,s){let o;e instanceof Uint8Array?o=await crypto.subtle.importKey("raw",e,"AES-GCM",!1,["decrypt"]):($a(e,t,"decrypt"),o=e);try{return new Uint8Array(await crypto.subtle.decrypt({additionalData:s,iv:n,name:"AES-GCM",tagLength:128},o,fi(r,i)))}catch{throw new nv}}async function eC(t,e,r,n,i){if(!ip(r)&&!(r instanceof Uint8Array))throw new TypeError(Wu(r,"CryptoKey","KeyObject","Uint8Array","JSON Web Key"));switch(n?Xde(t,n):n=brt(t),t){case"A128CBC-HS256":case"A192CBC-HS384":case"A256CBC-HS512":return r instanceof Uint8Array&&XR(r,parseInt(t.slice(-3),10)),vrt(t,e,r,n,i);case"A128GCM":case"A192GCM":case"A256GCM":return r instanceof Uint8Array&&XR(r,parseInt(t.slice(1,4),10)),Srt(t,e,r,n,i);default:throw new Pt(tpe)}}async function tC(t,e,r,n,i,s){if(!ip(e)&&!(e instanceof Uint8Array))throw new TypeError(Wu(e,"CryptoKey","KeyObject","Uint8Array","JSON Web Key"));if(!n)throw new Me("JWE Initialization Vector missing");if(!i)throw new Me("JWE Authentication Tag missing");switch(Xde(t,n),t){case"A128CBC-HS256":case"A192CBC-HS384":case"A256CBC-HS512":return e instanceof Uint8Array&&XR(e,parseInt(t.slice(-3),10)),Ert(t,e,r,n,i,s);case"A128GCM":case"A192GCM":case"A256GCM":return e instanceof Uint8Array&&XR(e,parseInt(t.slice(1,4),10)),wrt(t,e,r,n,i,s);default:throw new Pt(tpe)}}var Rf,brt,tpe,ov=I(()=>{Vs();Fh();rv();cn();Hh();Rf=t=>crypto.getRandomValues(new Uint8Array(QR(t)>>3));brt=t=>crypto.getRandomValues(new Uint8Array(Zde(t)>>3));tpe="Unsupported JWE Content Encryption Algorithm"});function So(t,e){if(t)throw new TypeError(`${e} can only be called once`)}function wo(t,e,r){try{return _o(t)}catch{throw new r(`Failed to base64url decode the ${e}`)}}async function rC(t,e){let r=`SHA-${t.slice(-3)}`;return new Uint8Array(await crypto.subtle.digest(r,e))}var rpe,sp=I(()=>{Ys();rpe=Symbol()});function vn(t){if(!Trt(t)||Object.prototype.toString.call(t)!=="[object Object]")return!1;if(Object.getPrototypeOf(t)===null)return!0;let e=t;for(;Object.getPrototypeOf(e)!==null;)e=Object.getPrototypeOf(e);return Object.getPrototypeOf(t)===e}function Cf(...t){let e=t.filter(Boolean);if(e.length===0||e.length===1)return!0;let r;for(let n of e){let i=Object.keys(n);if(!r||r.size===0){r=new Set(i);continue}for(let s of i){if(r.has(s))return!1;r.add(s)}}return!0}var Trt,Wh,npe,ipe,spe,Ss=I(()=>{Trt=t=>typeof t=="object"&&t!==null;Wh=t=>vn(t)&&typeof t.kty=="string",npe=t=>t.kty!=="oct"&&(t.kty==="AKP"&&typeof t.priv=="string"||typeof t.d=="string"),ipe=t=>t.kty!=="oct"&&t.d===void 0&&t.priv===void 0,spe=t=>t.kty==="oct"&&typeof t.k=="string"});function ope(t,e){if(t.algorithm.length!==parseInt(e.slice(1,4),10))throw new TypeError(`Invalid key size for alg: ${e}`)}function ape(t,e,r){return t instanceof Uint8Array?crypto.subtle.importKey("raw",t,"AES-KW",!0,[r]):($a(t,e,r),t)}async function x0(t,e,r){let n=await ape(e,t,"wrapKey");ope(n,t);let i=await crypto.subtle.importKey("raw",r,{hash:"SHA-256",name:"HMAC"},!0,["sign"]);return new Uint8Array(await crypto.subtle.wrapKey("raw",i,n,"AES-KW"))}async function I0(t,e,r){let n=await ape(e,t,"unwrapKey");ope(n,t);let i=await crypto.subtle.unwrapKey("raw",r,n,"AES-KW",{hash:"SHA-256",name:"HMAC"},!0,["sign"]);return new Uint8Array(await crypto.subtle.exportKey("raw",i))}var RH=I(()=>{Fh()});function CH(t){return fi($R(t.length),t)}async function Irt(t,e,r){let n=e>>3,i=32,s=Math.ceil(n/i),o=new Uint8Array(s*i);for(let a=1;a<=s;a++){let c=new Uint8Array(4+t.length+r.length);c.set($R(a),0),c.set(t,4),c.set(r,4+t.length);let l=await rC("sha256",c);o.set(l,(a-1)*i)}return o.slice(0,n)}async function NH(t,e,r,n,i=new Uint8Array,s=new Uint8Array){$a(t,"ECDH"),$a(e,"ECDH","deriveBits");let o=CH(Bn(r)),a=CH(i),c=CH(s),l=$R(n),u=new Uint8Array,d=fi(o,a,c,l,u),p=new Uint8Array(await crypto.subtle.deriveBits({name:t.algorithm.name,public:t},e,Art(t)));return Irt(p,n,d)}function Art(t){return t.algorithm.name==="X25519"?256:Math.ceil(parseInt(t.algorithm.namedCurve.slice(-3),10)/8)<<3}function PH(t){switch(t.algorithm.namedCurve){case"P-256":case"P-384":case"P-521":return!0;default:return t.algorithm.name==="X25519"}}var lpe=I(()=>{Vs();Fh();sp()});function krt(t,e){return t instanceof Uint8Array?crypto.subtle.importKey("raw",t,"PBKDF2",!1,["deriveBits"]):($a(t,e,"deriveBits"),t)}async function upe(t,e,r,n){if(!(t instanceof Uint8Array)||t.length<8)throw new Me("PBES2 Salt Input must be 8 or more octets");if(!Number.isSafeInteger(r)||Math.sign(r)!==1)throw new Me("PBES2 Count Input must be a positive integer");let i=Rrt(e,t),s=parseInt(e.slice(13,16),10),o={hash:`SHA-${e.slice(8,11)}`,iterations:r,name:"PBKDF2",salt:i},a=await krt(n,e);return new Uint8Array(await crypto.subtle.deriveBits(o,a,s))}async function dpe(t,e,r,n=2048,i=crypto.getRandomValues(new Uint8Array(16))){let s=await upe(i,t,n,e);return{encryptedKey:await x0(t.slice(-6),s,r),p2c:n,p2s:bn(i)}}async function ppe(t,e,r,n,i){let s=await upe(i,t,n,e);return I0(t.slice(-6),s,r)}var Rrt,fpe=I(()=>{Ys();RH();Fh();Vs();cn();Rrt=(t,e)=>fi(Bn(t),Uint8Array.of(0),e)});function A0(t,e){if(t.startsWith("RS")||t.startsWith("PS")){let{modulusLength:r}=e.algorithm;if(typeof r!="number"||r<2048)throw new TypeError(`${t} requires key modulusLength to be 2048 bits or larger`)}}function mpe(t,e){let r=`SHA-${t.slice(-3)}`;switch(t){case"HS256":case"HS384":case"HS512":return{hash:r,name:"HMAC"};case"PS256":case"PS384":case"PS512":return{hash:r,name:"RSA-PSS",saltLength:parseInt(t.slice(-3),10)>>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:e.namedCurve};case"Ed25519":case"EdDSA":return{name:"Ed25519"};case"ML-DSA-44":case"ML-DSA-65":case"ML-DSA-87":return{name:t};default:throw new Pt(`alg ${t} is not supported either by JOSE or your javascript runtime`)}}async function hpe(t,e,r){if(e instanceof Uint8Array){if(!t.startsWith("HS"))throw new TypeError(Wu(e,"CryptoKey","KeyObject","JSON Web Key"));return crypto.subtle.importKey("raw",e,{hash:`SHA-${t.slice(-3)}`,name:"HMAC"},!1,[r])}return Yde(e,t,r),e}async function gpe(t,e,r){let n=await hpe(t,e,"sign");A0(t,n);let i=await crypto.subtle.sign(mpe(t,n.algorithm),n,r);return new Uint8Array(i)}async function ype(t,e,r,n){let i=await hpe(t,e,"verify");A0(t,i);let s=mpe(t,i.algorithm);try{return await crypto.subtle.verify(s,i,r,n)}catch{return!1}}var nC=I(()=>{cn();Fh();rv()});async function vpe(t,e,r){return $a(e,t,"encrypt"),A0(t,e),new Uint8Array(await crypto.subtle.encrypt(bpe(t),e,r))}async function _pe(t,e,r){return $a(e,t,"decrypt"),A0(t,e),new Uint8Array(await crypto.subtle.decrypt(bpe(t),e,r))}var bpe,Epe=I(()=>{Fh();nC();cn();bpe=t=>{switch(t){case"RSA-OAEP":case"RSA-OAEP-256":case"RSA-OAEP-384":case"RSA-OAEP-512":return"RSA-OAEP";default:throw new Pt(`alg ${t} is not supported either by JOSE or your javascript runtime`)}}});function Prt(t){let e,r;switch(t.kty){case"AKP":{switch(t.alg){case"ML-DSA-44":case"ML-DSA-65":case"ML-DSA-87":e={name:t.alg},r=t.priv?["sign"]:["verify"];break;default:throw new Pt(iC)}break}case"RSA":{switch(t.alg){case"PS256":case"PS384":case"PS512":e={name:"RSA-PSS",hash:`SHA-${t.alg.slice(-3)}`},r=t.d?["sign"]:["verify"];break;case"RS256":case"RS384":case"RS512":e={name:"RSASSA-PKCS1-v1_5",hash:`SHA-${t.alg.slice(-3)}`},r=t.d?["sign"]:["verify"];break;case"RSA-OAEP":case"RSA-OAEP-256":case"RSA-OAEP-384":case"RSA-OAEP-512":e={name:"RSA-OAEP",hash:`SHA-${parseInt(t.alg.slice(-3),10)||1}`},r=t.d?["decrypt","unwrapKey"]:["encrypt","wrapKey"];break;default:throw new Pt(iC)}break}case"EC":{switch(t.alg){case"ES256":case"ES384":case"ES512":e={name:"ECDSA",namedCurve:{ES256:"P-256",ES384:"P-384",ES512:"P-521"}[t.alg]},r=t.d?["sign"]:["verify"];break;case"ECDH-ES":case"ECDH-ES+A128KW":case"ECDH-ES+A192KW":case"ECDH-ES+A256KW":e={name:"ECDH",namedCurve:t.crv},r=t.d?["deriveBits"]:[];break;default:throw new Pt(iC)}break}case"OKP":{switch(t.alg){case"Ed25519":case"EdDSA":e={name:"Ed25519"},r=t.d?["sign"]:["verify"];break;case"ECDH-ES":case"ECDH-ES+A128KW":case"ECDH-ES+A192KW":case"ECDH-ES+A256KW":e={name:t.crv},r=t.d?["deriveBits"]:[];break;default:throw new Pt(iC)}break}default:throw new Pt('Invalid or unsupported JWK "kty" (Key Type) Parameter value')}return{algorithm:e,keyUsages:r}}async function av(t){if(!t.alg)throw new TypeError('"alg" argument is required when "jwk.alg" is not present');let{algorithm:e,keyUsages:r}=Prt(t),n={...t};return n.kty!=="AKP"&&delete n.alg,delete n.use,crypto.subtle.importKey("jwk",n,e,t.ext??!(t.d||t.priv),t.key_ops??r)}var iC,DH=I(()=>{cn();iC='Invalid or unsupported JWK "alg" (Algorithm) Parameter value'});async function $u(t,e){if(t instanceof Uint8Array||ip(t))return t;if(w0(t)){if(t.type==="secret")return t.export();if("toCryptoKey"in t&&typeof t.toCryptoKey=="function")try{return Drt(t,e)}catch(n){if(n instanceof TypeError)throw n}let r=t.export({format:"jwk"});return Spe(t,r,e)}if(Wh(t))return t.k?_o(t.k):Spe(t,t,e,!0);throw new Error("unreachable")}var cv,lv,Spe,Drt,uv=I(()=>{Ss();Ys();DH();Hh();cv="given KeyObject instance cannot be used for this algorithm",Spe=async(t,e,r,n=!1)=>{lv||=new WeakMap;let i=lv.get(t);if(i?.[r])return i[r];let s=await av({...e,alg:r});return n&&Object.freeze(t),i?i[r]=s:lv.set(t,{[r]:s}),s},Drt=(t,e)=>{lv||=new WeakMap;let r=lv.get(t);if(r?.[e])return r[e];let n=t.type==="public",i=!!n,s;if(t.asymmetricKeyType==="x25519"){switch(e){case"ECDH-ES":case"ECDH-ES+A128KW":case"ECDH-ES+A192KW":case"ECDH-ES+A256KW":break;default:throw new TypeError(cv)}s=t.toCryptoKey(t.asymmetricKeyType,i,n?[]:["deriveBits"])}if(t.asymmetricKeyType==="ed25519"){if(e!=="EdDSA"&&e!=="Ed25519")throw new TypeError(cv);s=t.toCryptoKey(t.asymmetricKeyType,i,[n?"verify":"sign"])}switch(t.asymmetricKeyType){case"ml-dsa-44":case"ml-dsa-65":case"ml-dsa-87":{if(e!==t.asymmetricKeyType.toUpperCase())throw new TypeError(cv);s=t.toCryptoKey(t.asymmetricKeyType,i,[n?"verify":"sign"])}}if(t.asymmetricKeyType==="rsa"){let o;switch(e){case"RSA-OAEP":o="SHA-1";break;case"RS256":case"PS256":case"RSA-OAEP-256":o="SHA-256";break;case"RS384":case"PS384":case"RSA-OAEP-384":o="SHA-384";break;case"RS512":case"PS512":case"RSA-OAEP-512":o="SHA-512";break;default:throw new TypeError(cv)}if(e.startsWith("RSA-OAEP"))return t.toCryptoKey({name:"RSA-OAEP",hash:o},i,n?["encrypt"]:["decrypt"]);s=t.toCryptoKey({name:e.startsWith("PS")?"RSA-PSS":"RSASSA-PKCS1-v1_5",hash:o},i,[n?"verify":"sign"])}if(t.asymmetricKeyType==="ec"){let a=new Map([["prime256v1","P-256"],["secp384r1","P-384"],["secp521r1","P-521"]]).get(t.asymmetricKeyDetails?.namedCurve);if(!a)throw new TypeError(cv);let c={ES256:"P-256",ES384:"P-384",ES512:"P-521"};c[e]&&a===c[e]&&(s=t.toCryptoKey({name:"ECDSA",namedCurve:a},i,[n?"verify":"sign"])),e.startsWith("ECDH-ES")&&(s=t.toCryptoKey({name:"ECDH",namedCurve:a},i,n?[]:["deriveBits"]))}if(!s)throw new TypeError(cv);return r?r[e]=s:lv.set(t,{[e]:s}),s}});async function Ga(t,e,r){if(!vn(t))throw new TypeError("JWK must be an object");let n;switch(e??=t.alg,n??=r?.extractable??t.ext,t.kty){case"oct":if(typeof t.k!="string"||!t.k)throw new TypeError('missing "k" (Key Value) Parameter value');return _o(t.k);case"RSA":if("oth"in t&&t.oth!==void 0)throw new Pt('RSA JWK "oth" (Other Primes Info) Parameter value is not supported');return av({...t,alg:e,ext:n});case"AKP":{if(typeof t.alg!="string"||!t.alg)throw new TypeError('missing "alg" (Algorithm) Parameter value');if(e!==void 0&&e!==t.alg)throw new TypeError("JWK alg and alg option value mismatch");return av({...t,ext:n})}case"EC":case"OKP":return av({...t,alg:e,ext:n});default:throw new Pt('Unsupported "kty" (Key Type) Parameter value')}}var sC=I(()=>{Ys();DH();cn();Ss()});async function wpe(t){if(w0(t))if(t.type==="secret")t=t.export();else return t.export({format:"jwk"});if(t instanceof Uint8Array)return{kty:"oct",k:bn(t)};if(!ip(t))throw new TypeError(Wu(t,"CryptoKey","KeyObject","Uint8Array"));if(!t.extractable)throw new TypeError("non-extractable CryptoKey cannot be exported as a JWK");let{ext:e,key_ops:r,alg:n,use:i,...s}=await crypto.subtle.exportKey("jwk",t);return s.kty==="AKP"&&(s.alg=n),s}var Tpe=I(()=>{rv();Ys();Hh()});async function oC(t){return wpe(t)}var MH=I(()=>{Tpe()});async function xpe(t,e,r,n){let i=t.slice(0,7),s=await eC(i,r,e,n,new Uint8Array);return{encryptedKey:s.ciphertext,iv:bn(s.iv),tag:bn(s.tag)}}async function Ipe(t,e,r,n,i){let s=t.slice(0,7);return tC(s,e,r,n,i,new Uint8Array)}var Ape=I(()=>{ov();Ys()});function O0(t){if(t===void 0)throw new Me("JWE Encrypted Key missing")}async function kpe(t,e,r,n,i){switch(t){case"dir":{if(r!==void 0)throw new Me("Encountered unexpected JWE Encrypted Key");return e}case"ECDH-ES":if(r!==void 0)throw new Me("Encountered unexpected JWE Encrypted Key");case"ECDH-ES+A128KW":case"ECDH-ES+A192KW":case"ECDH-ES+A256KW":{if(!vn(n.epk))throw new Me('JOSE Header "epk" (Ephemeral Public Key) missing or invalid');if(sv(e),!PH(e))throw new Pt("ECDH with the provided key is not allowed or not supported by your javascript runtime");let s=await Ga(n.epk,t);sv(s);let o,a;if(n.apu!==void 0){if(typeof n.apu!="string")throw new Me('JOSE Header "apu" (Agreement PartyUInfo) invalid');o=wo(n.apu,"apu",Me)}if(n.apv!==void 0){if(typeof n.apv!="string")throw new Me('JOSE Header "apv" (Agreement PartyVInfo) invalid');a=wo(n.apv,"apv",Me)}let c=await NH(s,e,t==="ECDH-ES"?n.enc:t,t==="ECDH-ES"?QR(n.enc):parseInt(t.slice(-5,-2),10),o,a);return t==="ECDH-ES"?c:(O0(r),I0(t.slice(-6),c,r))}case"RSA-OAEP":case"RSA-OAEP-256":case"RSA-OAEP-384":case"RSA-OAEP-512":return O0(r),sv(e),_pe(t,e,r);case"PBES2-HS256+A128KW":case"PBES2-HS384+A192KW":case"PBES2-HS512+A256KW":{if(O0(r),typeof n.p2c!="number")throw new Me('JOSE Header "p2c" (PBES2 Count) missing or invalid');let s=i?.maxPBES2Count||1e4;if(n.p2c>s)throw new Me('JOSE Header "p2c" (PBES2 Count) out is of acceptable bounds');if(typeof n.p2s!="string")throw new Me('JOSE Header "p2s" (PBES2 Salt) missing or invalid');let o;return o=wo(n.p2s,"p2s",Me),ppe(t,e,r,n.p2c,o)}case"A128KW":case"A192KW":case"A256KW":return O0(r),I0(t,e,r);case"A128GCMKW":case"A192GCMKW":case"A256GCMKW":{if(O0(r),typeof n.iv!="string")throw new Me('JOSE Header "iv" (Initialization Vector) missing or invalid');if(typeof n.tag!="string")throw new Me('JOSE Header "tag" (Authentication Tag) missing or invalid');let s;s=wo(n.iv,"iv",Me);let o;return o=wo(n.tag,"tag",Me),Ipe(t,e,r,s,o)}default:throw new Pt(Ope)}}async function Rpe(t,e,r,n,i={}){let s,o,a;switch(t){case"dir":{a=r;break}case"ECDH-ES":case"ECDH-ES+A128KW":case"ECDH-ES+A192KW":case"ECDH-ES+A256KW":{if(sv(r),!PH(r))throw new Pt("ECDH with the provided key is not allowed or not supported by your javascript runtime");let{apu:c,apv:l}=i,u;i.epk?u=await $u(i.epk,t):u=(await crypto.subtle.generateKey(r.algorithm,!0,["deriveBits"])).privateKey;let{x:d,y:p,crv:f,kty:m}=await oC(u),h=await NH(r,u,t==="ECDH-ES"?e:t,t==="ECDH-ES"?QR(e):parseInt(t.slice(-5,-2),10),c,l);if(o={epk:{x:d,crv:f,kty:m}},m==="EC"&&(o.epk.y=p),c&&(o.apu=bn(c)),l&&(o.apv=bn(l)),t==="ECDH-ES"){a=h;break}a=n||Rf(e);let y=t.slice(-6);s=await x0(y,h,a);break}case"RSA-OAEP":case"RSA-OAEP-256":case"RSA-OAEP-384":case"RSA-OAEP-512":{a=n||Rf(e),sv(r),s=await vpe(t,r,a);break}case"PBES2-HS256+A128KW":case"PBES2-HS384+A192KW":case"PBES2-HS512+A256KW":{a=n||Rf(e);let{p2c:c,p2s:l}=i;({encryptedKey:s,...o}=await dpe(t,r,a,c,l));break}case"A128KW":case"A192KW":case"A256KW":{a=n||Rf(e),s=await x0(t,r,a);break}case"A128GCMKW":case"A192GCMKW":case"A256GCMKW":{a=n||Rf(e);let{iv:c}=i;({encryptedKey:s,...o}=await xpe(t,r,a,c));break}default:throw new Pt(Ope)}return{cek:a,encryptedKey:s,parameters:o}}var Ope,LH=I(()=>{RH();lpe();fpe();Epe();Ys();uv();cn();sp();ov();sC();MH();Ss();Ape();Hh();Ope='Invalid or unsupported "alg" (JWE Algorithm) header value'});function Nf(t,e,r,n,i){if(i.crit!==void 0&&n?.crit===void 0)throw new t('"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(o=>typeof o!="string"||o.length===0))throw new t('"crit" (Critical) Header Parameter MUST be an array of non-empty strings when present');let s;r!==void 0?s=new Map([...Object.entries(r),...e.entries()]):s=e;for(let o of n.crit){if(!s.has(o))throw new Pt(`Extension Header Parameter "${o}" is not recognized`);if(i[o]===void 0)throw new t(`Extension Header Parameter "${o}" is missing`);if(s.get(o)&&n[o]===void 0)throw new t(`Extension Header Parameter "${o}" MUST be integrity protected`)}return new Set(n.crit)}var k0=I(()=>{cn()});function R0(t,e){if(e!==void 0&&(!Array.isArray(e)||e.some(r=>typeof r!="string")))throw new TypeError(`"${t}" option must be an array of strings`);if(e)return new Set(e)}var jH=I(()=>{});function Pf(t,e,r){switch(t.substring(0,2)){case"A1":case"A2":case"di":case"HS":case"PB":Mrt(t,e,r);break;default:Lrt(t,e,r)}}var dv,UH,Mrt,Lrt,C0=I(()=>{rv();Hh();Ss();dv=t=>t?.[Symbol.toStringTag],UH=(t,e,r)=>{if(e.use!==void 0){let n;switch(r){case"sign":case"verify":n="sig";break;case"encrypt":case"decrypt":n="enc";break}if(e.use!==n)throw new TypeError(`Invalid key for this operation, its "use" must be "${n}" when present`)}if(e.alg!==void 0&&e.alg!==t)throw new TypeError(`Invalid key for this operation, its "alg" must be "${t}" when present`);if(Array.isArray(e.key_ops)){let n;switch(!0){case(r==="sign"||r==="verify"):case t==="dir":case t.includes("CBC-HS"):n=r;break;case t.startsWith("PBES2"):n="deriveBits";break;case/^A\d{3}(?:GCM)?(?:KW)?$/.test(t):!t.includes("GCM")&&t.endsWith("KW")?n=r==="encrypt"?"wrapKey":"unwrapKey":n=r;break;case(r==="encrypt"&&t.startsWith("RSA")):n="wrapKey";break;case r==="decrypt":n=t.startsWith("RSA")?"unwrapKey":"deriveBits";break}if(n&&e.key_ops?.includes?.(n)===!1)throw new TypeError(`Invalid key for this operation, its "key_ops" must include "${n}" when present`)}return!0},Mrt=(t,e,r)=>{if(!(e instanceof Uint8Array)){if(Wh(e)){if(spe(e)&&UH(t,e,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(!T0(e))throw new TypeError(kH(t,e,"CryptoKey","KeyObject","JSON Web Key","Uint8Array"));if(e.type!=="secret")throw new TypeError(`${dv(e)} instances for symmetric algorithms must be of type "secret"`)}},Lrt=(t,e,r)=>{if(Wh(e))switch(r){case"decrypt":case"sign":if(npe(e)&&UH(t,e,r))return;throw new TypeError("JSON Web Key for this operation must be a private JWK");case"encrypt":case"verify":if(ipe(e)&&UH(t,e,r))return;throw new TypeError("JSON Web Key for this operation must be a public JWK")}if(!T0(e))throw new TypeError(kH(t,e,"CryptoKey","KeyObject","JSON Web Key"));if(e.type==="secret")throw new TypeError(`${dv(e)} instances for asymmetric algorithms must not be of type "secret"`);if(e.type==="public")switch(r){case"sign":throw new TypeError(`${dv(e)} instances for asymmetric algorithm signing must be of type "private"`);case"decrypt":throw new TypeError(`${dv(e)} instances for asymmetric algorithm decryption must be of type "private"`)}if(e.type==="private")switch(r){case"verify":throw new TypeError(`${dv(e)} instances for asymmetric algorithm verifying must be of type "public"`);case"encrypt":throw new TypeError(`${dv(e)} instances for asymmetric algorithm encryption must be of type "public"`)}}});function Cpe(t){if(typeof globalThis[t]>"u")throw new Pt(`JWE "zip" (Compression Algorithm) Header Parameter requires the ${t} API.`)}async function Npe(t){Cpe("CompressionStream");let e=new CompressionStream("deflate-raw"),r=e.writable.getWriter();r.write(t).catch(()=>{}),r.close().catch(()=>{});let n=[],i=e.readable.getReader();for(;;){let{value:s,done:o}=await i.read();if(o)break;n.push(s)}return fi(...n)}async function Ppe(t,e){Cpe("DecompressionStream");let r=new DecompressionStream("deflate-raw"),n=r.writable.getWriter();n.write(t).catch(()=>{}),n.close().catch(()=>{});let i=[],s=0,o=r.readable.getReader();for(;;){let{value:a,done:c}=await o.read();if(c)break;if(i.push(a),s+=a.byteLength,e!==1/0&&s>e)throw new Me("Decompressed plaintext exceeded the configured limit")}return fi(...i)}var KH=I(()=>{cn();Vs()});async function Dpe(t,e,r){if(!vn(t))throw new Me("Flattened JWE must be an object");if(t.protected===void 0&&t.header===void 0&&t.unprotected===void 0)throw new Me("JOSE Header missing");if(t.iv!==void 0&&typeof t.iv!="string")throw new Me("JWE Initialization Vector incorrect type");if(typeof t.ciphertext!="string")throw new Me("JWE Ciphertext missing or incorrect type");if(t.tag!==void 0&&typeof t.tag!="string")throw new Me("JWE Authentication Tag incorrect type");if(t.protected!==void 0&&typeof t.protected!="string")throw new Me("JWE Protected Header incorrect type");if(t.encrypted_key!==void 0&&typeof t.encrypted_key!="string")throw new Me("JWE Encrypted Key incorrect type");if(t.aad!==void 0&&typeof t.aad!="string")throw new Me("JWE AAD incorrect type");if(t.header!==void 0&&!vn(t.header))throw new Me("JWE Shared Unprotected Header incorrect type");if(t.unprotected!==void 0&&!vn(t.unprotected))throw new Me("JWE Per-Recipient Unprotected Header incorrect type");let n;if(t.protected)try{let _=_o(t.protected);n=JSON.parse(_s.decode(_))}catch{throw new Me("JWE Protected Header is invalid")}if(!Cf(n,t.header,t.unprotected))throw new Me("JWE Protected, JWE Unprotected Header, and JWE Per-Recipient Unprotected Header Parameter names must be disjoint");let i={...n,...t.header,...t.unprotected};if(Nf(Me,new Map,r?.crit,n,i),i.zip!==void 0&&i.zip!=="DEF")throw new Pt('Unsupported JWE "zip" (Compression Algorithm) Header Parameter value.');if(i.zip!==void 0&&!n?.zip)throw new Me('JWE "zip" (Compression Algorithm) Header Parameter MUST be in a protected header.');let{alg:s,enc:o}=i;if(typeof s!="string"||!s)throw new Me("missing JWE Algorithm (alg) in JWE Header");if(typeof o!="string"||!o)throw new Me("missing JWE Encryption Algorithm (enc) in JWE Header");let a=r&&R0("keyManagementAlgorithms",r.keyManagementAlgorithms),c=r&&R0("contentEncryptionAlgorithms",r.contentEncryptionAlgorithms);if(a&&!a.has(s)||!a&&s.startsWith("PBES2"))throw new Bh('"alg" (Algorithm) Header Parameter value not allowed');if(c&&!c.has(o))throw new Bh('"enc" (Encryption Algorithm) Header Parameter value not allowed');let l;t.encrypted_key!==void 0&&(l=wo(t.encrypted_key,"encrypted_key",Me));let u=!1;typeof e=="function"&&(e=await e(n,t),u=!0),Pf(s==="dir"?o:s,e,"decrypt");let d=await $u(e,s),p;try{p=await kpe(s,d,l,i,r)}catch(_){if(_ instanceof TypeError||_ instanceof Me||_ instanceof Pt)throw _;p=Rf(o)}let f,m;t.iv!==void 0&&(f=wo(t.iv,"iv",Me)),t.tag!==void 0&&(m=wo(t.tag,"tag",Me));let h=t.protected!==void 0?Bn(t.protected):new Uint8Array,y;t.aad!==void 0?y=fi(h,Bn("."),Bn(t.aad)):y=h;let g=wo(t.ciphertext,"ciphertext",Me),b=await tC(o,p,g,f,m,y),v={plaintext:b};if(i.zip==="DEF"){let _=r?.maxDecompressedLength??25e4;if(_===0)throw new Pt('JWE "zip" (Compression Algorithm) Header Parameter is not supported.');if(_!==1/0&&(!Number.isSafeInteger(_)||_<1))throw new TypeError("maxDecompressedLength must be 0, a positive safe integer, or Infinity");v.plaintext=await Ppe(b,_).catch(w=>{throw w instanceof Me?w:new Me("Failed to decompress plaintext",{cause:w})})}return t.protected!==void 0&&(v.protectedHeader=n),t.aad!==void 0&&(v.additionalAuthenticatedData=wo(t.aad,"aad",Me)),t.unprotected!==void 0&&(v.sharedUnprotectedHeader=t.unprotected),t.header!==void 0&&(v.unprotectedHeader=t.header),u?{...v,key:d}:v}var Mpe=I(()=>{Ys();ov();sp();cn();Ss();Ss();LH();Vs();ov();k0();jH();uv();C0();KH()});async function Lpe(t,e,r){if(t instanceof Uint8Array&&(t=_s.decode(t)),typeof t!="string")throw new Me("Compact JWE must be a string or Uint8Array");let{0:n,1:i,2:s,3:o,4:a,length:c}=t.split(".");if(c!==5)throw new Me("Invalid Compact JWE");let l=await Dpe({ciphertext:o,iv:s||void 0,protected:n,tag:a||void 0,encrypted_key:i||void 0},e,r),u={plaintext:l.plaintext,protectedHeader:l.protectedHeader};return typeof e=="function"?{...u,key:l.key}:u}var jpe=I(()=>{Mpe();cn();Vs()});var aC,Upe=I(()=>{Ys();sp();ov();LH();cn();Ss();Vs();k0();uv();C0();KH();aC=class{#e;#t;#r;#n;#i;#p;#u;#a;constructor(e){if(!(e instanceof Uint8Array))throw new TypeError("plaintext must be an instance of Uint8Array");this.#e=e}setKeyManagementParameters(e){return So(this.#a,"setKeyManagementParameters"),this.#a=e,this}setProtectedHeader(e){return So(this.#t,"setProtectedHeader"),this.#t=e,this}setSharedUnprotectedHeader(e){return So(this.#r,"setSharedUnprotectedHeader"),this.#r=e,this}setUnprotectedHeader(e){return So(this.#n,"setUnprotectedHeader"),this.#n=e,this}setAdditionalAuthenticatedData(e){return this.#i=e,this}setContentEncryptionKey(e){return So(this.#p,"setContentEncryptionKey"),this.#p=e,this}setInitializationVector(e){return So(this.#u,"setInitializationVector"),this.#u=e,this}async encrypt(e,r){if(!this.#t&&!this.#n&&!this.#r)throw new Me("either setProtectedHeader, setUnprotectedHeader, or sharedUnprotectedHeader must be called before #encrypt()");if(!Cf(this.#t,this.#n,this.#r))throw new Me("JWE Protected, JWE Shared Unprotected and JWE Per-Recipient Header Parameter names must be disjoint");let n={...this.#t,...this.#n,...this.#r};if(Nf(Me,new Map,r?.crit,this.#t,n),n.zip!==void 0&&n.zip!=="DEF")throw new Pt('Unsupported JWE "zip" (Compression Algorithm) Header Parameter value.');if(n.zip!==void 0&&!this.#t?.zip)throw new Me('JWE "zip" (Compression Algorithm) Header Parameter MUST be in a protected header.');let{alg:i,enc:s}=n;if(typeof i!="string"||!i)throw new Me('JWE "alg" (Algorithm) Header Parameter missing or invalid');if(typeof s!="string"||!s)throw new Me('JWE "enc" (Encryption Algorithm) Header Parameter missing or invalid');let o;if(this.#p&&(i==="dir"||i==="ECDH-ES"))throw new TypeError(`setContentEncryptionKey cannot be called with JWE "alg" (Algorithm) Header ${i}`);Pf(i==="dir"?s:i,e,"encrypt");let a;{let g,b=await $u(e,i);({cek:a,encryptedKey:o,parameters:g}=await Rpe(i,s,b,this.#p,this.#a)),g&&(r&&rpe in r?this.#n?this.#n={...this.#n,...g}:this.setUnprotectedHeader(g):this.#t?this.#t={...this.#t,...g}:this.setProtectedHeader(g))}let c,l,u,d;if(this.#t?(l=bn(JSON.stringify(this.#t)),u=Bn(l)):(l="",u=new Uint8Array),this.#i){d=bn(this.#i);let g=Bn(d);c=fi(u,Bn("."),g)}else c=u;let p=this.#e;n.zip==="DEF"&&(p=await Npe(p).catch(g=>{throw new Me("Failed to compress plaintext",{cause:g})}));let{ciphertext:f,tag:m,iv:h}=await eC(s,p,a,this.#u,c),y={ciphertext:bn(f)};return h&&(y.iv=bn(h)),m&&(y.tag=bn(m)),o&&(y.encrypted_key=bn(o)),d&&(y.aad=d),this.#t&&(y.protected=l),this.#r&&(y.unprotected=this.#r),this.#n&&(y.header=this.#n),y}}});async function Kpe(t,e,r){if(!vn(t))throw new zr("Flattened JWS must be an object");if(t.protected===void 0&&t.header===void 0)throw new zr('Flattened JWS must have either of the "protected" or "header" members');if(t.protected!==void 0&&typeof t.protected!="string")throw new zr("JWS Protected Header incorrect type");if(t.payload===void 0)throw new zr("JWS Payload missing");if(typeof t.signature!="string")throw new zr("JWS Signature missing or incorrect type");if(t.header!==void 0&&!vn(t.header))throw new zr("JWS Unprotected Header incorrect type");let n={};if(t.protected)try{let y=_o(t.protected);n=JSON.parse(_s.decode(y))}catch{throw new zr("JWS Protected Header is invalid")}if(!Cf(n,t.header))throw new zr("JWS Protected and JWS Unprotected Header Parameter names must be disjoint");let i={...n,...t.header},s=Nf(zr,new Map([["b64",!0]]),r?.crit,n,i),o=!0;if(s.has("b64")&&(o=n.b64,typeof o!="boolean"))throw new zr('The "b64" (base64url-encode payload) Header Parameter must be a boolean');let{alg:a}=i;if(typeof a!="string"||!a)throw new zr('JWS "alg" (Algorithm) Header Parameter missing or invalid');let c=r&&R0("algorithms",r.algorithms);if(c&&!c.has(a))throw new Bh('"alg" (Algorithm) Header Parameter value not allowed');if(o){if(typeof t.payload!="string")throw new zr("JWS Payload must be a string")}else if(typeof t.payload!="string"&&!(t.payload instanceof Uint8Array))throw new zr("JWS Payload must be a string or an Uint8Array instance");let l=!1;typeof e=="function"&&(e=await e(n,t),l=!0),Pf(a,e,"verify");let u=fi(t.protected!==void 0?Bn(t.protected):new Uint8Array,Bn("."),typeof t.payload=="string"?o?Bn(t.payload):qh.encode(t.payload):t.payload),d=wo(t.signature,"signature",zr),p=await $u(e,a);if(!await ype(a,p,d,u))throw new ZR;let m;o?m=wo(t.payload,"payload",zr):typeof t.payload=="string"?m=qh.encode(t.payload):m=t.payload;let h={payload:m};return t.protected!==void 0&&(h.protectedHeader=n),t.header!==void 0&&(h.unprotectedHeader=t.header),l?{...h,key:p}:h}var qpe=I(()=>{Ys();nC();cn();Vs();sp();Ss();Ss();C0();k0();jH();uv()});async function Fpe(t,e,r){if(t instanceof Uint8Array&&(t=_s.decode(t)),typeof t!="string")throw new zr("Compact JWS must be a string or Uint8Array");let{0:n,1:i,2:s,length:o}=t.split(".");if(o!==3)throw new zr("Invalid Compact JWS");let a=await Kpe({payload:i,protected:n,signature:s},e,r),c={payload:a.payload,protectedHeader:a.protectedHeader};return typeof e=="function"?{...c,key:a.key}:c}var zpe=I(()=>{qpe();cn();Vs()});function N0(t){let e=Krt.exec(t);if(!e||e[4]&&e[1])throw new TypeError("Invalid time period format");let r=parseFloat(e[2]),n=e[3].toLowerCase(),i;switch(n){case"sec":case"secs":case"second":case"seconds":case"s":i=Math.round(r);break;case"minute":case"minutes":case"min":case"mins":case"m":i=Math.round(r*Hpe);break;case"hour":case"hours":case"hr":case"hrs":case"h":i=Math.round(r*Wpe);break;case"day":case"days":case"d":i=Math.round(r*qH);break;case"week":case"weeks":case"w":i=Math.round(r*jrt);break;default:i=Math.round(r*Urt);break}return e[1]==="-"||e[4]==="ago"?-i:i}function $h(t,e){if(!Number.isFinite(e))throw new TypeError(`Invalid ${t} input`);return e}function cC(t,e,r={}){let n;try{n=JSON.parse(_s.decode(e))}catch{}if(!vn(n))throw new Js("JWT Claims Set must be a top-level JSON object");let{typ:i}=r;if(i&&(typeof t.typ!="string"||Bpe(t.typ)!==Bpe(i)))throw new Es('unexpected "typ" JWT header value',n,"typ","check_failed");let{requiredClaims:s=[],issuer:o,subject:a,audience:c,maxTokenAge:l}=r,u=[...s];l!==void 0&&u.push("iat"),c!==void 0&&u.push("aud"),a!==void 0&&u.push("sub"),o!==void 0&&u.push("iss");for(let m of new Set(u.reverse()))if(!(m in n))throw new Es(`missing required "${m}" claim`,n,m,"missing");if(o&&!(Array.isArray(o)?o:[o]).includes(n.iss))throw new Es('unexpected "iss" claim value',n,"iss","check_failed");if(a&&n.sub!==a)throw new Es('unexpected "sub" claim value',n,"sub","check_failed");if(c&&!qrt(n.aud,typeof c=="string"?[c]:c))throw new Es('unexpected "aud" claim value',n,"aud","check_failed");let d;switch(typeof r.clockTolerance){case"string":d=N0(r.clockTolerance);break;case"number":d=r.clockTolerance;break;case"undefined":d=0;break;default:throw new TypeError("Invalid clockTolerance option type")}let{currentDate:p}=r,f=Df(p||new Date);if((n.iat!==void 0||l)&&typeof n.iat!="number")throw new Es('"iat" claim must be a number',n,"iat","invalid");if(n.nbf!==void 0){if(typeof n.nbf!="number")throw new Es('"nbf" claim must be a number',n,"nbf","invalid");if(n.nbf>f+d)throw new Es('"nbf" claim timestamp check failed',n,"nbf","check_failed")}if(n.exp!==void 0){if(typeof n.exp!="number")throw new Es('"exp" claim must be a number',n,"exp","invalid");if(n.exp<=f-d)throw new zh('"exp" claim timestamp check failed',n,"exp","check_failed")}if(l){let m=f-n.iat,h=typeof l=="number"?l:N0(l);if(m-d>h)throw new zh('"iat" claim timestamp check failed (too far in the past)',n,"iat","check_failed");if(m<0-d)throw new Es('"iat" claim timestamp check failed (it should be in the past)',n,"iat","check_failed")}return n}var Df,Hpe,Wpe,qH,jrt,Urt,Krt,Bpe,qrt,pv,P0=I(()=>{cn();Vs();Ss();Df=t=>Math.floor(t.getTime()/1e3),Hpe=60,Wpe=Hpe*60,qH=Wpe*24,jrt=qH*7,Urt=qH*365.25,Krt=/^(\+|\-)? ?(\d+|\d+\.\d+) ?(seconds?|secs?|s|minutes?|mins?|m|hours?|hrs?|h|days?|d|weeks?|w|years?|yrs?|y)(?: (ago|from now))?$/i;Bpe=t=>t.includes("/")?t.toLowerCase():`application/${t.toLowerCase()}`,qrt=(t,e)=>typeof t=="string"?e.includes(t):Array.isArray(t)?e.some(Set.prototype.has.bind(new Set(t))):!1;pv=class{#e;constructor(e){if(!vn(e))throw new TypeError("JWT Claims Set MUST be an object");this.#e=structuredClone(e)}data(){return qh.encode(JSON.stringify(this.#e))}get iss(){return this.#e.iss}set iss(e){this.#e.iss=e}get sub(){return this.#e.sub}set sub(e){this.#e.sub=e}get aud(){return this.#e.aud}set aud(e){this.#e.aud=e}set jti(e){this.#e.jti=e}set nbf(e){typeof e=="number"?this.#e.nbf=$h("setNotBefore",e):e instanceof Date?this.#e.nbf=$h("setNotBefore",Df(e)):this.#e.nbf=Df(new Date)+N0(e)}set exp(e){typeof e=="number"?this.#e.exp=$h("setExpirationTime",e):e instanceof Date?this.#e.exp=$h("setExpirationTime",Df(e)):this.#e.exp=Df(new Date)+N0(e)}set iat(e){e===void 0?this.#e.iat=Df(new Date):e instanceof Date?this.#e.iat=$h("setIssuedAt",Df(e)):typeof e=="string"?this.#e.iat=$h("setIssuedAt",Df(new Date)+N0(e)):this.#e.iat=$h("setIssuedAt",e)}}});async function To(t,e,r){let n=await Fpe(t,e,r);if(n.protectedHeader.crit?.includes("b64")&&n.protectedHeader.b64===!1)throw new Js("JWTs MUST NOT use unencoded payload");let s={payload:cC(n.protectedHeader,n.payload,r),protectedHeader:n.protectedHeader};return typeof e=="function"?{...s,key:n.key}:s}var $pe=I(()=>{zpe();P0();cn()});async function lC(t,e,r){let n=await Lpe(t,e,r),i=cC(n.protectedHeader,n.plaintext,r),{protectedHeader:s}=n;if(s.iss!==void 0&&s.iss!==i.iss)throw new Es('replicated "iss" claim header parameter mismatch',i,"iss","mismatch");if(s.sub!==void 0&&s.sub!==i.sub)throw new Es('replicated "sub" claim header parameter mismatch',i,"sub","mismatch");if(s.aud!==void 0&&JSON.stringify(s.aud)!==JSON.stringify(i.aud))throw new Es('replicated "aud" claim header parameter mismatch',i,"aud","mismatch");let o={payload:i,protectedHeader:s};return typeof e=="function"?{...o,key:n.key}:o}var Gpe=I(()=>{jpe();P0();cn()});var uC,Vpe=I(()=>{Upe();uC=class{#e;constructor(e){this.#e=new aC(e)}setContentEncryptionKey(e){return this.#e.setContentEncryptionKey(e),this}setInitializationVector(e){return this.#e.setInitializationVector(e),this}setProtectedHeader(e){return this.#e.setProtectedHeader(e),this}setKeyManagementParameters(e){return this.#e.setKeyManagementParameters(e),this}async encrypt(e,r){let n=await this.#e.encrypt(e,r);return[n.protected,n.encrypted_key,n.iv,n.ciphertext,n.tag].join(".")}}});var dC,Ype=I(()=>{Ys();nC();Ss();cn();Vs();C0();k0();uv();sp();dC=class{#e;#t;#r;constructor(e){if(!(e instanceof Uint8Array))throw new TypeError("payload must be an instance of Uint8Array");this.#e=e}setProtectedHeader(e){return So(this.#t,"setProtectedHeader"),this.#t=e,this}setUnprotectedHeader(e){return So(this.#r,"setUnprotectedHeader"),this.#r=e,this}async sign(e,r){if(!this.#t&&!this.#r)throw new zr("either setProtectedHeader or setUnprotectedHeader must be called before #sign()");if(!Cf(this.#t,this.#r))throw new zr("JWS Protected and JWS Unprotected Header Parameter names must be disjoint");let n={...this.#t,...this.#r},i=Nf(zr,new Map([["b64",!0]]),r?.crit,this.#t,n),s=!0;if(i.has("b64")&&(s=this.#t.b64,typeof s!="boolean"))throw new zr('The "b64" (base64url-encode payload) Header Parameter must be a boolean');let{alg:o}=n;if(typeof o!="string"||!o)throw new zr('JWS "alg" (Algorithm) Header Parameter missing or invalid');Pf(o,e,"sign");let a,c;s?(a=bn(this.#e),c=Bn(a)):(c=this.#e,a="");let l,u;this.#t?(l=bn(JSON.stringify(this.#t)),u=Bn(l)):(l="",u=new Uint8Array);let d=fi(u,Bn("."),c),p=await $u(e,o),f=await gpe(o,p,d),m={signature:bn(f),payload:a};return this.#r&&(m.header=this.#r),this.#t&&(m.protected=l),m}}});var pC,Jpe=I(()=>{Ype();pC=class{#e;constructor(e){this.#e=new dC(e)}setProtectedHeader(e){return this.#e.setProtectedHeader(e),this}async sign(e,r){let n=await this.#e.sign(e,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 D0,Zpe=I(()=>{Jpe();cn();P0();D0=class{#e;#t;constructor(e={}){this.#t=new pv(e)}setIssuer(e){return this.#t.iss=e,this}setSubject(e){return this.#t.sub=e,this}setAudience(e){return this.#t.aud=e,this}setJti(e){return this.#t.jti=e,this}setNotBefore(e){return this.#t.nbf=e,this}setExpirationTime(e){return this.#t.exp=e,this}setIssuedAt(e){return this.#t.iat=e,this}setProtectedHeader(e){return this.#e=e,this}async sign(e,r){let n=new pC(this.#t.data());if(n.setProtectedHeader(this.#e),Array.isArray(this.#e?.crit)&&this.#e.crit.includes("b64")&&this.#e.b64===!1)throw new Js("JWTs MUST NOT use unencoded payload");return n.sign(e,r)}}});var M0,Xpe=I(()=>{Vpe();P0();sp();M0=class{#e;#t;#r;#n;#i;#p;#u;#a;constructor(e={}){this.#a=new pv(e)}setIssuer(e){return this.#a.iss=e,this}setSubject(e){return this.#a.sub=e,this}setAudience(e){return this.#a.aud=e,this}setJti(e){return this.#a.jti=e,this}setNotBefore(e){return this.#a.nbf=e,this}setExpirationTime(e){return this.#a.exp=e,this}setIssuedAt(e){return this.#a.iat=e,this}setProtectedHeader(e){return So(this.#n,"setProtectedHeader"),this.#n=e,this}setKeyManagementParameters(e){return So(this.#r,"setKeyManagementParameters"),this.#r=e,this}setContentEncryptionKey(e){return So(this.#e,"setContentEncryptionKey"),this.#e=e,this}setInitializationVector(e){return So(this.#t,"setInitializationVector"),this.#t=e,this}replicateIssuerAsHeader(){return this.#i=!0,this}replicateSubjectAsHeader(){return this.#p=!0,this}replicateAudienceAsHeader(){return this.#u=!0,this}async encrypt(e,r){let n=new uC(this.#a.data());return this.#n&&(this.#i||this.#p||this.#u)&&(this.#n={...this.#n,iss:this.#i?this.#a.iss:void 0,sub:this.#p?this.#a.sub:void 0,aud:this.#u?this.#a.aud:void 0}),n.setProtectedHeader(this.#n),this.#t&&n.setInitializationVector(this.#t),this.#e&&n.setContentEncryptionKey(this.#e),this.#r&&n.setKeyManagementParameters(this.#r),n.encrypt(e,r)}}});async function fC(t,e){let r;if(Wh(t))r=t;else if(T0(t))r=await oC(t);else throw new TypeError(Wu(t,"CryptoKey","KeyObject","JSON Web Key"));if(e??="sha256",e!=="sha256"&&e!=="sha384"&&e!=="sha512")throw new TypeError('digestAlgorithm must one of "sha256", "sha384", or "sha512"');let n;switch(r.kty){case"AKP":Gu(r.alg,'"alg" (Algorithm) Parameter'),Gu(r.pub,'"pub" (Public key) Parameter'),n={alg:r.alg,kty:r.kty,pub:r.pub};break;case"EC":Gu(r.crv,'"crv" (Curve) Parameter'),Gu(r.x,'"x" (X Coordinate) Parameter'),Gu(r.y,'"y" (Y Coordinate) Parameter'),n={crv:r.crv,kty:r.kty,x:r.x,y:r.y};break;case"OKP":Gu(r.crv,'"crv" (Subtype of Key Pair) Parameter'),Gu(r.x,'"x" (Public Key) Parameter'),n={crv:r.crv,kty:r.kty,x:r.x};break;case"RSA":Gu(r.e,'"e" (Exponent) Parameter'),Gu(r.n,'"n" (Modulus) Parameter'),n={e:r.e,kty:r.kty,n:r.n};break;case"oct":Gu(r.k,'"k" (Key Value) Parameter'),n={k:r.k,kty:r.kty};break;default:throw new Pt('"kty" (Key Type) Parameter missing or unsupported')}let i=Bn(JSON.stringify(n));return bn(await rC(e,i))}var Gu,Qpe=I(()=>{sp();Ys();cn();Vs();Hh();Ss();MH();rv();Gu=(t,e)=>{if(typeof t!="string"||!t)throw new VR(`${e} missing or invalid`)}});function Frt(t){switch(typeof t=="string"&&t.slice(0,2)){case"RS":case"PS":return"RSA";case"ES":return"EC";case"Ed":return"OKP";case"ML":return"AKP";default:throw new Pt('Unsupported "alg" value for a JSON Web Key Set')}}function zrt(t){return t&&typeof t=="object"&&Array.isArray(t.keys)&&t.keys.every(Brt)}function Brt(t){return vn(t)}async function efe(t,e,r){let n=t.get(e)||t.set(e,{}).get(e);if(n[r]===void 0){let i=await Ga({...e,ext:!0},r);if(i instanceof Uint8Array||i.type!=="public")throw new S0("JSON Web Key Set members must be public keys");n[r]=i}return n[r]}function zH(t){let e=new FH(t),r=async(n,i)=>e.getKey(n,i);return Object.defineProperties(r,{jwks:{value:()=>structuredClone(e.jwks()),enumerable:!1,configurable:!1,writable:!1}}),r}var FH,tfe=I(()=>{sC();cn();Ss();FH=class{#e;#t=new WeakMap;constructor(e){if(!zrt(e))throw new S0("JSON Web Key Set malformed");this.#e=structuredClone(e)}jwks(){return this.#e}async getKey(e,r){let{alg:n,kid:i}={...e,...r?.header},s=Frt(n),o=this.#e.keys.filter(l=>{let u=s===l.kty;if(u&&typeof i=="string"&&(u=i===l.kid),u&&(typeof l.alg=="string"||s==="AKP")&&(u=n===l.alg),u&&typeof l.use=="string"&&(u=l.use==="sig"),u&&Array.isArray(l.key_ops)&&(u=l.key_ops.includes("verify")),u)switch(n){case"ES256":u=l.crv==="P-256";break;case"ES384":u=l.crv==="P-384";break;case"ES512":u=l.crv==="P-521";break;case"Ed25519":case"EdDSA":u=l.crv==="Ed25519";break}return u}),{0:a,length:c}=o;if(c===0)throw new iv;if(c!==1){let l=new YR,u=this.#t;throw l[Symbol.asyncIterator]=async function*(){for(let d of o)try{yield await efe(u,d,n)}catch{}},l}return efe(this.#t,a,n)}}});function Hrt(){return typeof WebSocketPair<"u"||typeof navigator<"u"&&navigator.userAgent==="Cloudflare-Workers"||typeof EdgeRuntime<"u"&&EdgeRuntime==="vercel"}async function Wrt(t,e,r,n=fetch){let i=await n(t,{method:"GET",signal:r,redirect:"manual",headers:e}).catch(s=>{throw s.name==="TimeoutError"?new JR:s});if(i.status!==200)throw new Si("Expected 200 OK from the JSON Web Key Set HTTP response");try{return await i.json()}catch{throw new Si("Failed to parse the JSON Web Key Set HTTP response as JSON")}}function $rt(t,e){return!(typeof t!="object"||t===null||!("uat"in t)||typeof t.uat!="number"||Date.now()-t.uat>=e||!("jwks"in t)||!vn(t.jwks)||!Array.isArray(t.jwks.keys)||!Array.prototype.every.call(t.jwks.keys,vn))}function WH(t,e){let r=new HH(t,e),n=async(i,s)=>r.getKey(i,s);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.jwks(),enumerable:!0,configurable:!1,writable:!1}}),n}var BH,rfe,mC,HH,nfe=I(()=>{cn();tfe();Ss();(typeof navigator>"u"||!navigator.userAgent?.startsWith?.("Mozilla/5.0 "))&&(BH="jose/v6.2.3");rfe=Symbol();mC=Symbol();HH=class{#e;#t;#r;#n;#i;#p;#u;#a;#o;#d;constructor(e,r){if(!(e instanceof URL))throw new TypeError("url must be an instance of URL");this.#e=new URL(e.href),this.#t=typeof r?.timeoutDuration=="number"?r?.timeoutDuration:5e3,this.#r=typeof r?.cooldownDuration=="number"?r?.cooldownDuration:3e4,this.#n=typeof r?.cacheMaxAge=="number"?r?.cacheMaxAge:6e5,this.#u=new Headers(r?.headers),BH&&!this.#u.has("User-Agent")&&this.#u.set("User-Agent",BH),this.#u.has("accept")||(this.#u.set("accept","application/json"),this.#u.append("accept","application/jwk-set+json")),this.#a=r?.[rfe],r?.[mC]!==void 0&&(this.#d=r?.[mC],$rt(r?.[mC],this.#n)&&(this.#i=this.#d.uat,this.#o=zH(this.#d.jwks)))}pendingFetch(){return!!this.#p}coolingDown(){return typeof this.#i=="number"?Date.now()<this.#i+this.#r:!1}fresh(){return typeof this.#i=="number"?Date.now()<this.#i+this.#n:!1}jwks(){return this.#o?.jwks()}async getKey(e,r){(!this.#o||!this.fresh())&&await this.reload();try{return await this.#o(e,r)}catch(n){if(n instanceof iv&&this.coolingDown()===!1)return await this.reload(),this.#o(e,r);throw n}}async reload(){this.#p&&Hrt()&&(this.#p=void 0),this.#p||=Wrt(this.#e.href,this.#u,AbortSignal.timeout(this.#t),this.#a).then(e=>{this.#o=zH(e),this.#d&&(this.#d.uat=Date.now(),this.#d.jwks=e),this.#i=Date.now(),this.#p=void 0}).catch(e=>{throw this.#p=void 0,e}),await this.#p}}});function Dl(t){let e;if(typeof t=="string"){let r=t.split(".");(r.length===3||r.length===5)&&([e]=r)}else if(typeof t=="object"&&t)if("protected"in t)e=t.protected;else throw new TypeError("Token does not contain a Protected Header");try{if(typeof e!="string"||!e)throw new Error;let r=JSON.parse(_s.decode(_o(e)));if(!vn(r))throw new Error;return r}catch{throw new TypeError("Invalid Token or Protected Header formatting")}}var ife=I(()=>{Ys();Vs();Ss()});function wi(t){if(typeof t!="string")throw new Js("JWTs must use Compact JWS serialization, JWT must be a string");let{1:e,length:r}=t.split(".");if(r===5)throw new Js("Only JWTs using Compact JWS serialization can be decoded");if(r!==3)throw new Js("Invalid JWT");if(!e)throw new Js("JWTs must contain a payload");let n;try{n=_o(e)}catch{throw new Js("Failed to base64url decode the payload")}let i;try{i=JSON.parse(_s.decode(n))}catch{throw new Js("Failed to parse the decoded payload as JSON")}if(!vn(i))throw new Js("Invalid JWT Claims Set");return i}var sfe=I(()=>{Ys();Vs();Ss();cn()});var Wc=I(()=>{$pe();Gpe();Zpe();Xpe();Qpe();nfe();sC();ife();sfe();Ys()});async function hC(t,e,r=3600){return await new D0(t).setProtectedHeader({alg:"HS256"}).setIssuedAt().setExpirationTime(Math.floor(Date.now()/1e3)+r).sign(new TextEncoder().encode(e))}async function $H(t,e){try{return(await To(t,new TextEncoder().encode(e))).payload}catch{return null}}function L0(t,e){return Ude(Bde,new TextEncoder().encode(t),new TextEncoder().encode(e),Grt,64)}function Yrt(t){if(typeof t=="string")return t;let e=t.keys.get(t.currentVersion);if(!e)throw new Error(`Secret version ${t.currentVersion} not found in keys`);return e}function ofe(t){if(typeof t=="string")return[{version:0,value:t}];let e=[];for(let[r,n]of t.keys)e.push({version:r,value:n});return t.legacySecret&&!e.some(r=>r.value===t.legacySecret)&&e.push({version:-1,value:t.legacySecret}),e}async function gC(t,e,r,n=3600){let i=L0(Yrt(e),r),s=await fC({kty:"oct",k:E0.encode(i)},"sha256");return await new M0(t).setProtectedHeader({alg:cfe,enc:lfe,kid:s}).setIssuedAt().setExpirationTime(Vrt()+n).setJti(crypto.randomUUID()).encrypt(i)}async function j0(t,e,r){if(!t)return null;let n=!1;try{n=Dl(t).kid!==void 0}catch{return null}try{let i=ofe(e),{payload:s}=await lC(t,async o=>{let a=o.kid;if(a!==void 0){for(let c of i){let l=L0(c.value,r);if(a===await fC({kty:"oct",k:E0.encode(l)},"sha256"))return l}throw new Error("no matching decryption secret")}return i.length===1,L0(i[0].value,r)},afe);return s}catch{if(n)return null;let i=ofe(e);if(i.length<=1)return null;for(let s=1;s<i.length;s++)try{let o=i[s],{payload:a}=await lC(t,L0(o.value,r),afe);return a}catch{continue}return null}}var Grt,Vrt,cfe,lfe,afe,U0=I(()=>{Kde();Hde();Wc();Grt=new Uint8Array([66,101,116,116,101,114,65,117,116,104,46,106,115,32,71,101,110,101,114,97,116,101,100,32,69,110,99,114,121,112,116,105,111,110,32,75,101,121]),Vrt=()=>Date.now()/1e3|0,cfe="dir",lfe="A256CBC-HS512";afe={clockTolerance:15,keyManagementAlgorithms:[cfe],contentEncryptionAlgorithms:[lfe,"A256GCM"]}});function ufe(t,e){return new Promise((r,n)=>{(0,yC.scrypt)(t.normalize("NFKC"),e,fv.dkLen,{N:fv.N,r:fv.r,p:fv.p,maxmem:128*fv.N*fv.r*2},(i,s)=>{i?n(i):r(s)})})}async function dfe(t){let e=(0,yC.randomBytes)(16).toString("hex"),r=await ufe(t,e);return`${e}:${r.toString("hex")}`}async function pfe(t,e){let[r,n]=t.split(":");if(!r||!n)throw new Error("Invalid password hash");return(await ufe(e,r)).toString("hex")===n}var yC,fv,ffe=I(()=>{yC=require("node:crypto"),fv={N:16384,r:16,p:1,dkLen:64}});var mfe,hfe,gfe=I(()=>{ffe();mfe=dfe,hfe=async({hash:t,password:e})=>pfe(t,e)});function Ml(){let t=typeof globalThis<"u"&&globalThis.crypto;if(t&&typeof t.subtle=="object"&&t.subtle!=null)return t.subtle;throw new Error("crypto.subtle must be defined")}var K0=I(()=>{});function bC(t){return t?"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_":"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"}function yfe(t,e,r){let n="",i=0,s=0;for(let o of t)for(i=i<<8|o,s+=8;s>=6;)s-=6,n+=e[i>>s&63];if(s>0&&(n+=e[i<<6-s&63]),r){let o=(4-n.length%4)%4;n+="=".repeat(o)}return n}function bfe(t,e){let r=new Map;for(let o=0;o<e.length;o++)r.set(e[o],o);let n=[],i=0,s=0;for(let o of t){if(o==="=")break;let a=r.get(o);if(a===void 0)throw new Error(`Invalid Base64 character: ${o}`);i=i<<6|a,s+=6,s>=8&&(s-=8,n.push(i>>s&255))}return Uint8Array.from(n)}var Hi,da,pa=I(()=>{Hi={encode(t,e={}){let r=bC(!1),n=typeof t=="string"?new TextEncoder().encode(t):new Uint8Array(t);return yfe(n,r,e.padding??!0)},decode(t){typeof t!="string"&&(t=new TextDecoder().decode(t));let e=t.includes("-")||t.includes("_"),r=bC(e);return bfe(t,r)}},da={encode(t,e={}){let r=bC(!0),n=typeof t=="string"?new TextEncoder().encode(t):new Uint8Array(t);return yfe(n,r,e.padding??!0)},decode(t){let e=t.includes("-")||t.includes("_"),r=bC(e);return bfe(t,r)}}});function op(t,e){return{digest:async r=>{let n=new TextEncoder,i=typeof r=="string"?n.encode(r):r,s=await Ml().digest(t,i);return e==="hex"?Array.from(new Uint8Array(s)).map(c=>c.toString(16).padStart(2,"0")).join(""):e==="base64"||e==="base64url"||e==="base64urlnopad"?e.includes("url")?da.encode(s,{padding:e!=="base64urlnopad"}):Hi.encode(s):s}}}var q0=I(()=>{pa();K0()});function Jrt(t){return t instanceof Uint8Array||ArrayBuffer.isView(t)&&t.constructor.name==="Uint8Array"&&"BYTES_PER_ELEMENT"in t&&t.BYTES_PER_ELEMENT===1}function vC(t){if(typeof t!="boolean")throw new TypeError(`boolean expected, not ${t}`)}function Mf(t){if(typeof t!="number")throw new TypeError("number expected, got "+typeof t);if(!Number.isSafeInteger(t)||t<0)throw new RangeError("positive integer expected, got "+t)}function Dn(t,e,r=""){let n=Jrt(t),i=t?.length,s=e!==void 0;if(!n||s&&i!==e){let o=r&&`"${r}" `,a=s?` of length ${e}`:"",c=n?`length=${i}`:`type=${typeof t}`,l=o+"expected Uint8Array"+a+", got "+c;throw n?new RangeError(l):new TypeError(l)}return t}function GH(t,e=!0){if(t.destroyed)throw new Error("Hash instance has been destroyed");if(e&&t.finished)throw new Error("Hash#digest() has already been called")}function _fe(t,e,r=!1){Dn(t,void 0,"output");let n=e.outputLen;if(t.length<n)throw new RangeError("digestInto() expects output buffer of length at least "+n);if(r&&!mv(t))throw new Error("invalid output, must be aligned")}function Vu(t){return new Uint32Array(t.buffer,t.byteOffset,Math.floor(t.byteLength/4))}function Ll(...t){for(let e=0;e<t.length;e++)t[e].fill(0)}function Zrt(t){return new DataView(t.buffer,t.byteOffset,t.byteLength)}function VH(t){if(Dn(t),Sfe)return t.toHex();let e="";for(let r=0;r<t.length;r++)e+=Qrt[t[r]];return e}function vfe(t){if(t>=ap._0&&t<=ap._9)return t-ap._0;if(t>=ap.A&&t<=ap.F)return t-(ap.A-10);if(t>=ap.a&&t<=ap.f)return t-(ap.a-10)}function wfe(t){if(typeof t!="string")throw new TypeError("hex string expected, got "+typeof t);if(Sfe)try{return Uint8Array.fromHex(t)}catch(i){throw i instanceof SyntaxError?new RangeError(i.message):i}let e=t.length,r=e/2;if(e%2)throw new RangeError("hex string expected, got unpadded hex of length "+e);let n=new Uint8Array(r);for(let i=0,s=0;i<r;i++,s+=2){let o=vfe(t.charCodeAt(s)),a=vfe(t.charCodeAt(s+1));if(o===void 0||a===void 0){let c=t[s]+t[s+1];throw new RangeError('hex string expected, got non-hex character "'+c+'" at index '+s)}n[i]=o*16+a}return n}function Tfe(t){if(typeof t!="string")throw new TypeError("string expected");return new Uint8Array(new TextEncoder().encode(t))}function ent(t,e){return!t.byteLength||!e.byteLength?!1:t.buffer===e.buffer&&t.byteOffset<e.byteOffset+e.byteLength&&e.byteOffset<t.byteOffset+t.byteLength}function xfe(...t){let e=0;for(let n=0;n<t.length;n++){let i=t[n];Dn(i),e+=i.length}let r=new Uint8Array(e);for(let n=0,i=0;n<t.length;n++){let s=t[n];r.set(s,i),i+=s.length}return r}function Ife(t,e){if(e==null||typeof e!="object")throw new Error("options must be defined");return Object.assign(t,e)}function Afe(t,e){if(t.length!==e.length)return!1;let r=0;for(let n=0;n<t.length;n++)r|=t[n]^e[n];return r===0}function Ofe(t,e,r){let n=e,i=r||(()=>[]),s=(a,c)=>n(c,...i(a)).update(a).digest(),o=n(new Uint8Array(t),...i(new Uint8Array(0)));return s.outputLen=o.outputLen,s.blockLen=o.blockLen,s.create=(a,...c)=>n(a,...c),s}function F0(t,e,r=!0){if(e===void 0)return new Uint8Array(t);if(Dn(e,void 0,"output"),e.length!==t)throw new Error('"output" expected Uint8Array of length '+t+", got: "+e.length);if(r&&!mv(e))throw new Error("invalid output, must be aligned");return e}function Rfe(t,e,r){Mf(t),Mf(e),vC(r);let n=new Uint8Array(16),i=Zrt(n);return i.setBigUint64(0,BigInt(e),r),i.setBigUint64(8,BigInt(t),r),n}function mv(t){return t.byteOffset%4===0}function hv(t){return Uint8Array.from(Dn(t))}function Cfe(t=32){Mf(t);let e=typeof globalThis=="object"?globalThis.crypto:null;if(typeof e?.getRandomValues!="function")throw new Error("crypto.getRandomValues must be defined");return e.getRandomValues(new Uint8Array(t))}function YH(t,e=Cfe){let{nonceLength:r}=t;Mf(r);let n=(s,o,a)=>{let c=xfe(s,o);return ent(a,o)||o.fill(0),c},i=((s,...o)=>({encrypt(a){Dn(a);let c=e(r),l=t(s,c,...o).encrypt(a);return l instanceof Promise?l.then(u=>n(c,u,a)):n(c,l,a)},decrypt(a){Dn(a);let c=a.subarray(0,r),l=a.subarray(r);return t(s,c,...o).decrypt(l)}}));return"blockSize"in t&&(i.blockSize=t.blockSize),"tagLength"in t&&(i.tagLength=t.tagLength),i}var Lf,Efe,ws,Xrt,Yu,Sfe,Qrt,ap,kfe,z0=I(()=>{Lf=new Uint8Array(new Uint32Array([287454020]).buffer)[0]===68,Efe=t=>t<<24&4278190080|t<<8&16711680|t>>>8&65280|t>>>24&255,ws=Lf?t=>t:t=>Efe(t)>>>0,Xrt=t=>{for(let e=0;e<t.length;e++)t[e]=Efe(t[e]);return t},Yu=Lf?t=>t:Xrt,Sfe=typeof Uint8Array.from([]).toHex=="function"&&typeof Uint8Array.fromHex=="function",Qrt=Array.from({length:256},(t,e)=>e.toString(16).padStart(2,"0"));ap={_0:48,_9:57,A:65,F:70,a:97,f:102};kfe=(t,e)=>{function r(n,...i){if(Dn(n,void 0,"key"),t.nonceLength!==void 0){let u=i[0];Dn(u,t.varSizeNonce?void 0:t.nonceLength,"nonce")}let s=t.tagLength;s&&i[1]!==void 0&&Dn(i[1],void 0,"AAD");let o=e(n,...i),a=(u,d)=>{if(d!==void 0){if(u!==2)throw new Error("cipher output not supported");Dn(d,void 0,"output")}},c=!1;return{encrypt(u,d){if(c)throw new Error("cannot encrypt() twice with same key + nonce");return c=!0,Dn(u),a(o.encrypt.length,d),o.encrypt(u,d)},decrypt(u,d){if(Dn(u),s&&u.length<s)throw new Error('"ciphertext" expected length bigger than tagLength='+s);return a(o.decrypt.length,d),o.decrypt(u,d)}}}return Object.assign(r,t),r}});function Le(t,e){return t<<e|t>>>32-e}function int(t,e,r,n,i,s,o,a){let c=i.length,l=new Uint8Array(B0),u=Vu(l),d=Lf&&mv(i)&&mv(s),p=d?Vu(i):Nfe,f=d?Vu(s):Nfe;if(!Lf){for(let m=0;m<c;o++){if(t(e,r,n,u,o,a),Yu(u),o>=JH)throw new Error("arx: counter overflow");let h=Math.min(B0,c-m);for(let y=0,g;y<h;y++)g=m+y,s[g]=i[g]^l[y];m+=h}return}for(let m=0;m<c;o++){if(t(e,r,n,u,o,a),o>=JH)throw new Error("arx: counter overflow");let h=Math.min(B0,c-m);if(d&&h===B0){let y=m/4;if(m%4!==0)throw new Error("arx: invalid block position");for(let g=0,b;g<nnt;g++)b=y+g,f[b]=p[b]^u[g];m+=B0;continue}for(let y=0,g;y<h;y++)g=m+y,s[g]=i[g]^l[y];m+=h}}function Dfe(t,e){let{allowShortKeys:r,extendNonceFn:n,counterLength:i,counterRight:s,rounds:o}=Ife({allowShortKeys:!1,counterLength:8,counterRight:!1,rounds:20},e);if(typeof t!="function")throw new Error("core must be a function");return Mf(i),Mf(o),vC(s),vC(r),(a,c,l,u,d=0)=>{Dn(a,void 0,"key"),Dn(c,void 0,"nonce"),Dn(l,void 0,"data");let p=l.length;if(u=F0(p,u,!1),Mf(d),d<0||d>=JH)throw new Error("arx: counter overflow");let f=[],m=a.length,h,y;if(m===32)f.push(h=hv(a)),y=rnt;else if(m===16&&r)h=new Uint8Array(32),h.set(a),h.set(a,16),y=tnt,f.push(h);else throw Dn(a,32,"arx key"),new Error("invalid key size");(!Lf||!mv(c))&&f.push(c=hv(c));let g=Vu(h);if(n){if(c.length!==24)throw new Error("arx: extended nonce must be 24 bytes");let _=c.subarray(0,16);if(Lf)n(y,g,Vu(_),g);else{let w=Yu(Uint32Array.from(y));n(w,g,Vu(_),g),Ll(w),Yu(g)}c=c.subarray(16)}else Lf||Yu(g);let b=16-i;if(b!==c.length)throw new Error(`arx: nonce must be ${b} or 16 bytes`);if(b!==12){let _=new Uint8Array(12);_.set(c,s?0:12-c.length),c=_,f.push(c)}let v=Yu(Vu(c));try{return int(t,y,g,v,l,u,d,o),u}finally{Ll(...f)}}}var Pfe,tnt,rnt,B0,nnt,JH,Nfe,Mfe=I(()=>{z0();Pfe=t=>Uint8Array.from(t.split(""),e=>e.charCodeAt(0)),tnt=Yu(Vu(Pfe("expand 16-byte k"))),rnt=Yu(Vu(Pfe("expand 32-byte k")));B0=64,nnt=16,JH=2**32-1,Nfe=Uint32Array.of()});function Ts(t,e){return t[e++]&255|(t[e++]&255)<<8}var ZH,Lfe,jfe=I(()=>{z0();ZH=class{blockLen=16;outputLen=16;buffer=new Uint8Array(16);r=new Uint16Array(10);h=new Uint16Array(10);pad=new Uint16Array(8);pos=0;finished=!1;destroyed=!1;constructor(e){e=hv(Dn(e,32,"key"));let r=Ts(e,0),n=Ts(e,2),i=Ts(e,4),s=Ts(e,6),o=Ts(e,8),a=Ts(e,10),c=Ts(e,12),l=Ts(e,14);this.r[0]=r&8191,this.r[1]=(r>>>13|n<<3)&8191,this.r[2]=(n>>>10|i<<6)&7939,this.r[3]=(i>>>7|s<<9)&8191,this.r[4]=(s>>>4|o<<12)&255,this.r[5]=o>>>1&8190,this.r[6]=(o>>>14|a<<2)&8191,this.r[7]=(a>>>11|c<<5)&8065,this.r[8]=(c>>>8|l<<8)&8191,this.r[9]=l>>>5&127;for(let u=0;u<8;u++)this.pad[u]=Ts(e,16+2*u)}process(e,r,n=!1){let i=n?0:2048,{h:s,r:o}=this,a=o[0],c=o[1],l=o[2],u=o[3],d=o[4],p=o[5],f=o[6],m=o[7],h=o[8],y=o[9],g=Ts(e,r+0),b=Ts(e,r+2),v=Ts(e,r+4),_=Ts(e,r+6),w=Ts(e,r+8),S=Ts(e,r+10),x=Ts(e,r+12),O=Ts(e,r+14),N=s[0]+(g&8191),k=s[1]+((g>>>13|b<<3)&8191),M=s[2]+((b>>>10|v<<6)&8191),K=s[3]+((v>>>7|_<<9)&8191),P=s[4]+((_>>>4|w<<12)&8191),j=s[5]+(w>>>1&8191),U=s[6]+((w>>>14|S<<2)&8191),q=s[7]+((S>>>11|x<<5)&8191),F=s[8]+((x>>>8|O<<8)&8191),Q=s[9]+(O>>>5|i),J=0,W=J+N*a+k*(5*y)+M*(5*h)+K*(5*m)+P*(5*f);J=W>>>13,W&=8191,W+=j*(5*p)+U*(5*d)+q*(5*u)+F*(5*l)+Q*(5*c),J+=W>>>13,W&=8191;let z=J+N*c+k*a+M*(5*y)+K*(5*h)+P*(5*m);J=z>>>13,z&=8191,z+=j*(5*f)+U*(5*p)+q*(5*d)+F*(5*u)+Q*(5*l),J+=z>>>13,z&=8191;let G=J+N*l+k*c+M*a+K*(5*y)+P*(5*h);J=G>>>13,G&=8191,G+=j*(5*m)+U*(5*f)+q*(5*p)+F*(5*d)+Q*(5*u),J+=G>>>13,G&=8191;let H=J+N*u+k*l+M*c+K*a+P*(5*y);J=H>>>13,H&=8191,H+=j*(5*h)+U*(5*m)+q*(5*f)+F*(5*p)+Q*(5*d),J+=H>>>13,H&=8191;let L=J+N*d+k*u+M*l+K*c+P*a;J=L>>>13,L&=8191,L+=j*(5*y)+U*(5*h)+q*(5*m)+F*(5*f)+Q*(5*p),J+=L>>>13,L&=8191;let B=J+N*p+k*d+M*u+K*l+P*c;J=B>>>13,B&=8191,B+=j*a+U*(5*y)+q*(5*h)+F*(5*m)+Q*(5*f),J+=B>>>13,B&=8191;let ie=J+N*f+k*p+M*d+K*u+P*l;J=ie>>>13,ie&=8191,ie+=j*c+U*a+q*(5*y)+F*(5*h)+Q*(5*m),J+=ie>>>13,ie&=8191;let xe=J+N*m+k*f+M*p+K*d+P*u;J=xe>>>13,xe&=8191,xe+=j*l+U*c+q*a+F*(5*y)+Q*(5*h),J+=xe>>>13,xe&=8191;let Ne=J+N*h+k*m+M*f+K*p+P*d;J=Ne>>>13,Ne&=8191,Ne+=j*u+U*l+q*c+F*a+Q*(5*y),J+=Ne>>>13,Ne&=8191;let bt=J+N*y+k*h+M*m+K*f+P*p;J=bt>>>13,bt&=8191,bt+=j*d+U*u+q*l+F*c+Q*a,J+=bt>>>13,bt&=8191,J=(J<<2)+J|0,J=J+W|0,W=J&8191,J=J>>>13,z+=J,s[0]=W,s[1]=z,s[2]=G,s[3]=H,s[4]=L,s[5]=B,s[6]=ie,s[7]=xe,s[8]=Ne,s[9]=bt}finalize(){let{h:e,pad:r}=this,n=new Uint16Array(10),i=e[1]>>>13;e[1]&=8191;for(let a=2;a<10;a++)e[a]+=i,i=e[a]>>>13,e[a]&=8191;e[0]+=i*5,i=e[0]>>>13,e[0]&=8191,e[1]+=i,i=e[1]>>>13,e[1]&=8191,e[2]+=i,n[0]=e[0]+5,i=n[0]>>>13,n[0]&=8191;for(let a=1;a<10;a++)n[a]=e[a]+i,i=n[a]>>>13,n[a]&=8191;n[9]-=8192;let s=(i^1)-1;for(let a=0;a<10;a++)n[a]&=s;s=~s;for(let a=0;a<10;a++)e[a]=e[a]&s|n[a];e[0]=(e[0]|e[1]<<13)&65535,e[1]=(e[1]>>>3|e[2]<<10)&65535,e[2]=(e[2]>>>6|e[3]<<7)&65535,e[3]=(e[3]>>>9|e[4]<<4)&65535,e[4]=(e[4]>>>12|e[5]<<1|e[6]<<14)&65535,e[5]=(e[6]>>>2|e[7]<<11)&65535,e[6]=(e[7]>>>5|e[8]<<8)&65535,e[7]=(e[8]>>>8|e[9]<<5)&65535;let o=e[0]+r[0];e[0]=o&65535;for(let a=1;a<8;a++)o=(e[a]+r[a]|0)+(o>>>16)|0,e[a]=o&65535;Ll(n)}update(e){GH(this),Dn(e),e=hv(e);let{buffer:r,blockLen:n}=this,i=e.length;for(let s=0;s<i;){let o=Math.min(n-this.pos,i-s);if(o===n){for(;n<=i-s;s+=n)this.process(e,s);continue}r.set(e.subarray(s,s+o),this.pos),this.pos+=o,s+=o,this.pos===n&&(this.process(r,0,!1),this.pos=0)}return this}destroy(){this.destroyed=!0,Ll(this.h,this.r,this.buffer,this.pad)}digestInto(e){GH(this),_fe(e,this),this.finished=!0;let{buffer:r,h:n}=this,{pos:i}=this;if(i){for(r[i++]=1;i<16;i++)r[i]=0;this.process(r,0,!0)}this.finalize();let s=0;for(let o=0;o<8;o++)e[s++]=n[o]>>>0,e[s++]=n[o]>>>8}digest(){let{buffer:e,outputLen:r}=this;this.digestInto(e);let n=e.slice(0,r);return this.destroy(),n}},Lfe=Ofe(32,t=>new ZH(t))});function snt(t,e,r,n,i,s=20){let o=t[0],a=t[1],c=t[2],l=t[3],u=e[0],d=e[1],p=e[2],f=e[3],m=e[4],h=e[5],y=e[6],g=e[7],b=i,v=r[0],_=r[1],w=r[2],S=o,x=a,O=c,N=l,k=u,M=d,K=p,P=f,j=m,U=h,q=y,F=g,Q=b,J=v,W=_,z=w;for(let H=0;H<s;H+=2)S=S+k|0,Q=Le(Q^S,16),j=j+Q|0,k=Le(k^j,12),S=S+k|0,Q=Le(Q^S,8),j=j+Q|0,k=Le(k^j,7),x=x+M|0,J=Le(J^x,16),U=U+J|0,M=Le(M^U,12),x=x+M|0,J=Le(J^x,8),U=U+J|0,M=Le(M^U,7),O=O+K|0,W=Le(W^O,16),q=q+W|0,K=Le(K^q,12),O=O+K|0,W=Le(W^O,8),q=q+W|0,K=Le(K^q,7),N=N+P|0,z=Le(z^N,16),F=F+z|0,P=Le(P^F,12),N=N+P|0,z=Le(z^N,8),F=F+z|0,P=Le(P^F,7),S=S+M|0,z=Le(z^S,16),q=q+z|0,M=Le(M^q,12),S=S+M|0,z=Le(z^S,8),q=q+z|0,M=Le(M^q,7),x=x+K|0,Q=Le(Q^x,16),F=F+Q|0,K=Le(K^F,12),x=x+K|0,Q=Le(Q^x,8),F=F+Q|0,K=Le(K^F,7),O=O+P|0,J=Le(J^O,16),j=j+J|0,P=Le(P^j,12),O=O+P|0,J=Le(J^O,8),j=j+J|0,P=Le(P^j,7),N=N+k|0,W=Le(W^N,16),U=U+W|0,k=Le(k^U,12),N=N+k|0,W=Le(W^N,8),U=U+W|0,k=Le(k^U,7);let G=0;n[G++]=o+S|0,n[G++]=a+x|0,n[G++]=c+O|0,n[G++]=l+N|0,n[G++]=u+k|0,n[G++]=d+M|0,n[G++]=p+K|0,n[G++]=f+P|0,n[G++]=m+j|0,n[G++]=h+U|0,n[G++]=y+q|0,n[G++]=g+F|0,n[G++]=b+Q|0,n[G++]=v+J|0,n[G++]=_+W|0,n[G++]=w+z|0}function ont(t,e,r,n){let i=ws(t[0]),s=ws(t[1]),o=ws(t[2]),a=ws(t[3]),c=ws(e[0]),l=ws(e[1]),u=ws(e[2]),d=ws(e[3]),p=ws(e[4]),f=ws(e[5]),m=ws(e[6]),h=ws(e[7]),y=ws(r[0]),g=ws(r[1]),b=ws(r[2]),v=ws(r[3]);for(let w=0;w<20;w+=2)i=i+c|0,y=Le(y^i,16),p=p+y|0,c=Le(c^p,12),i=i+c|0,y=Le(y^i,8),p=p+y|0,c=Le(c^p,7),s=s+l|0,g=Le(g^s,16),f=f+g|0,l=Le(l^f,12),s=s+l|0,g=Le(g^s,8),f=f+g|0,l=Le(l^f,7),o=o+u|0,b=Le(b^o,16),m=m+b|0,u=Le(u^m,12),o=o+u|0,b=Le(b^o,8),m=m+b|0,u=Le(u^m,7),a=a+d|0,v=Le(v^a,16),h=h+v|0,d=Le(d^h,12),a=a+d|0,v=Le(v^a,8),h=h+v|0,d=Le(d^h,7),i=i+l|0,v=Le(v^i,16),m=m+v|0,l=Le(l^m,12),i=i+l|0,v=Le(v^i,8),m=m+v|0,l=Le(l^m,7),s=s+u|0,y=Le(y^s,16),h=h+y|0,u=Le(u^h,12),s=s+u|0,y=Le(y^s,8),h=h+y|0,u=Le(u^h,7),o=o+d|0,g=Le(g^o,16),p=p+g|0,d=Le(d^p,12),o=o+d|0,g=Le(g^o,8),p=p+g|0,d=Le(d^p,7),a=a+c|0,b=Le(b^a,16),f=f+b|0,c=Le(c^f,12),a=a+c|0,b=Le(b^a,8),f=f+b|0,c=Le(c^f,7);let _=0;n[_++]=i,n[_++]=s,n[_++]=o,n[_++]=a,n[_++]=y,n[_++]=g,n[_++]=b,n[_++]=v,Yu(n)}function Kfe(t,e,r,n,i){i!==void 0&&Dn(i,void 0,"AAD");let s=t(e,r,lnt),o=Rfe(n.length,i?i.length:0,!0),a=Lfe.create(s);i&&Ufe(a,i),Ufe(a,n),a.update(o);let c=a.digest();return Ll(s,o),c}var ant,cnt,Ufe,lnt,unt,XH,qfe=I(()=>{Mfe();jfe();z0();ant=Dfe(snt,{counterRight:!1,counterLength:8,extendNonceFn:ont,allowShortKeys:!1}),cnt=new Uint8Array(16),Ufe=(t,e)=>{t.update(e);let r=e.length%16;r&&t.update(cnt.subarray(r))},lnt=new Uint8Array(32);unt=t=>(e,r,n)=>({encrypt(s,o){let a=s.length;o=F0(a+16,o,!1),o.set(s);let c=o.subarray(0,-16);t(e,r,c,c,1);let l=Kfe(t,e,r,c,n);return o.set(l,a),Ll(l),o},decrypt(s,o){o=F0(s.length-16,o,!1);let a=s.subarray(0,-16),c=s.subarray(-16),l=Kfe(t,e,r,a,n);if(!Afe(c,l))throw Ll(l),new Error("invalid tag");return o.set(s.subarray(0,-16)),t(e,r,o,o,1),Ll(l),o}}),XH=kfe({blockSize:64,nonceLength:24,tagLength:16},unt(ant))});function dnt(t){if(!t.startsWith(zfe))return null;let e=4,r=t.indexOf("$",e);if(r===-1)return null;let n=parseInt(t.slice(e,r),10);return!Number.isInteger(n)||n<0?null:{version:n,ciphertext:t.slice(r+1)}}function pnt(t,e){return`${zfe}${t}$${e}`}async function Ffe(t,e){let r=await op("SHA-256").digest(t),n=Tfe(e);return VH(YH(XH)(new Uint8Array(r)).encrypt(n))}async function QH(t,e){let r=await op("SHA-256").digest(t),n=wfe(e),i=YH(XH)(new Uint8Array(r));return new TextDecoder().decode(i.decrypt(n))}var zfe,_C,EC,SC=I(()=>{b0();K0();q0();qfe();z0();zfe="$ba$";_C=async({key:t,data:e})=>{if(typeof t=="string")return Ffe(t,e);let r=t.keys.get(t.currentVersion);if(!r)throw new Error(`Secret version ${t.currentVersion} not found in keys`);let n=await Ffe(r,e);return pnt(t.currentVersion,n)},EC=async({key:t,data:e})=>{if(typeof t=="string")return QH(t,e);let r=dnt(e);if(r){let n=t.keys.get(r.version);if(!n)throw new Error(`Secret version ${r.version} not found in keys (key may have been retired)`);return QH(n,r.ciphertext)}if(t.legacySecret)return QH(t.legacySecret,e);throw new Error("Cannot decrypt legacy bare-hex payload: no legacy secret available. Set BETTER_AUTH_SECRET for backwards compatibility.")}});var Zs,eW=I(()=>{Zs=t=>{let e=(t.plugins??[]).reduce((d,p)=>{let f=p.schema;if(!f)return d;for(let[m,h]of Object.entries(f))d[m]={fields:{...d[m]?.fields,...h.fields},modelName:h.modelName||m};return d},{}),r=t.rateLimit?.storage==="database",n={rateLimit:{modelName:t.rateLimit?.modelName||"rateLimit",fields:{key:{type:"string",unique:!0,required:!0,fieldName:t.rateLimit?.fields?.key||"key"},count:{type:"number",required:!0,fieldName:t.rateLimit?.fields?.count||"count"},lastRequest:{type:"number",bigint:!0,required:!0,fieldName:t.rateLimit?.fields?.lastRequest||"lastRequest",defaultValue:()=>Date.now()}}}},{user:i,session:s,account:o,verification:a,...c}=e,l={verification:{modelName:t.verification?.modelName||"verification",fields:{identifier:{type:"string",required:!0,fieldName:t.verification?.fields?.identifier||"identifier",index:!0},value:{type:"string",required:!0,fieldName:t.verification?.fields?.value||"value"},expiresAt:{type:"date",required:!0,fieldName:t.verification?.fields?.expiresAt||"expiresAt"},createdAt:{type:"date",required:!0,defaultValue:()=>new Date,fieldName:t.verification?.fields?.createdAt||"createdAt"},updatedAt:{type:"date",required:!0,defaultValue:()=>new Date,onUpdate:()=>new Date,fieldName:t.verification?.fields?.updatedAt||"updatedAt"},...a?.fields,...t.verification?.additionalFields},order:4}},u={session:{modelName:t.session?.modelName||"session",fields:{expiresAt:{type:"date",required:!0,fieldName:t.session?.fields?.expiresAt||"expiresAt"},token:{type:"string",required:!0,fieldName:t.session?.fields?.token||"token",unique:!0},createdAt:{type:"date",required:!0,fieldName:t.session?.fields?.createdAt||"createdAt",defaultValue:()=>new Date},updatedAt:{type:"date",required:!0,fieldName:t.session?.fields?.updatedAt||"updatedAt",onUpdate:()=>new Date},ipAddress:{type:"string",required:!1,fieldName:t.session?.fields?.ipAddress||"ipAddress"},userAgent:{type:"string",required:!1,fieldName:t.session?.fields?.userAgent||"userAgent"},userId:{type:"string",fieldName:t.session?.fields?.userId||"userId",references:{model:t.user?.modelName||"user",field:"id",onDelete:"cascade"},required:!0,index:!0},...s?.fields,...t.session?.additionalFields},order:2}};return{user:{modelName:t.user?.modelName||"user",fields:{name:{type:"string",required:!0,fieldName:t.user?.fields?.name||"name",sortable:!0},email:{type:"string",unique:!0,required:!0,fieldName:t.user?.fields?.email||"email",sortable:!0},emailVerified:{type:"boolean",defaultValue:!1,required:!0,fieldName:t.user?.fields?.emailVerified||"emailVerified",input:!1},image:{type:"string",required:!1,fieldName:t.user?.fields?.image||"image"},createdAt:{type:"date",defaultValue:()=>new Date,required:!0,fieldName:t.user?.fields?.createdAt||"createdAt"},updatedAt:{type:"date",defaultValue:()=>new Date,onUpdate:()=>new Date,required:!0,fieldName:t.user?.fields?.updatedAt||"updatedAt"},...i?.fields,...t.user?.additionalFields},order:1},...!t.secondaryStorage||t.session?.storeSessionInDatabase?u:{},account:{modelName:t.account?.modelName||"account",fields:{accountId:{type:"string",required:!0,fieldName:t.account?.fields?.accountId||"accountId"},providerId:{type:"string",required:!0,fieldName:t.account?.fields?.providerId||"providerId"},userId:{type:"string",references:{model:t.user?.modelName||"user",field:"id",onDelete:"cascade"},required:!0,fieldName:t.account?.fields?.userId||"userId",index:!0},accessToken:{type:"string",required:!1,returned:!1,fieldName:t.account?.fields?.accessToken||"accessToken"},refreshToken:{type:"string",required:!1,returned:!1,fieldName:t.account?.fields?.refreshToken||"refreshToken"},idToken:{type:"string",required:!1,returned:!1,fieldName:t.account?.fields?.idToken||"idToken"},accessTokenExpiresAt:{type:"date",required:!1,returned:!1,fieldName:t.account?.fields?.accessTokenExpiresAt||"accessTokenExpiresAt"},refreshTokenExpiresAt:{type:"date",required:!1,returned:!1,fieldName:t.account?.fields?.refreshTokenExpiresAt||"refreshTokenExpiresAt"},scope:{type:"string",required:!1,fieldName:t.account?.fields?.scope||"scope"},password:{type:"string",required:!1,returned:!1,fieldName:t.account?.fields?.password||"password"},createdAt:{type:"date",required:!0,fieldName:t.account?.fields?.createdAt||"createdAt",defaultValue:()=>new Date},updatedAt:{type:"date",required:!0,fieldName:t.account?.fields?.updatedAt||"updatedAt",onUpdate:()=>new Date},...o?.fields,...t.account?.additionalFields},order:3},...!t.secondaryStorage||t.verification?.storeInDatabase?l:{},...c,...r?n:{}}}});var Gh,Ju,gv=I(()=>{Gh=le(require("zod"),1),Ju=Gh.object({id:Gh.string(),createdAt:Gh.date().default(()=>new Date),updatedAt:Gh.date().default(()=>new Date)})});var Va,Bfe,Hfe=I(()=>{gv();Va=le(require("zod"),1),Bfe=Ju.extend({providerId:Va.string(),accountId:Va.string(),userId:Va.coerce.string(),accessToken:Va.string().nullish(),refreshToken:Va.string().nullish(),idToken:Va.string().nullish(),accessTokenExpiresAt:Va.date().nullish(),refreshTokenExpiresAt:Va.date().nullish(),scope:Va.string().nullish(),password:Va.string().nullish()})});var Vh,Wfe,$fe=I(()=>{Vh=le(require("zod"),1),Wfe=Vh.object({key:Vh.string(),count:Vh.number(),lastRequest:Vh.number()})});var jf,Gfe,Vfe=I(()=>{gv();jf=le(require("zod"),1),Gfe=Ju.extend({userId:jf.coerce.string(),expiresAt:jf.date(),token:jf.string(),ipAddress:jf.string().nullish(),userAgent:jf.string().nullish()})});var yv,Yfe,Jfe=I(()=>{gv();yv=le(require("zod"),1),Yfe=Ju.extend({email:yv.string().transform(t=>t.toLowerCase()),emailVerified:yv.boolean().default(!1),name:yv.string(),image:yv.string().nullish()})});var H0,Zfe,Xfe=I(()=>{gv();H0=le(require("zod"),1),Zfe=Ju.extend({value:H0.string(),expiresAt:H0.date(),identifier:H0.string()})});var tW={};ui(tW,{accountSchema:()=>Bfe,coreSchema:()=>Ju,getAuthTables:()=>Zs,rateLimitSchema:()=>Wfe,sessionSchema:()=>Gfe,userSchema:()=>Yfe,verificationSchema:()=>Zfe});var cp=I(()=>{eW();gv();Hfe();$fe();Vfe();Jfe();Xfe()});function Xs(t,e){if(!t||!e)return t;let r=Object.entries(e).filter(([,{returned:n}])=>n===!1).map(([n])=>n);return Object.entries(structuredClone(t)).filter(([n])=>!r.includes(n)).reduce((n,[i,s])=>({...n,[i]:s}),{})}var wC=I(()=>{});function Uf(t,e,r){let n=`${e}:${r}`;rW.has(t)||rW.set(t,new Map);let i=rW.get(t);if(i.has(n))return i.get(n);let s=r==="output"?Zs(t)[e]?.fields??{}:{},o=e==="user"||e==="session"||e==="account"?t[e]?.additionalFields:void 0,a={...s,...o??{}};for(let c of t.plugins||[])c.schema&&c.schema[e]&&(a={...a,...c.schema[e].fields});return i.set(n,a),a}function Br(t,e){return Xs(e,Uf(t,"user","output"))}function Wi(t,e){return Xs(e,Uf(t,"session","output"))}function TC(t,e){let{accessToken:r,refreshToken:n,idToken:i,accessTokenExpiresAt:s,refreshTokenExpiresAt:o,password:a,...c}=Xs(e,Uf(t,"account","output"));return c}function bv(t,e){let r=e.action||"create",n=e.fields,i=Object.create(null);for(let s in n){if(s in t){if(n[s].input===!1){if(n[s].defaultValue!==void 0&&r!=="update"){i[s]=n[s].defaultValue;continue}if(t[s])throw D.from("BAD_REQUEST",{...ae.FIELD_NOT_ALLOWED,message:`${s} is not allowed to be set`});continue}if(n[s].validator?.input&&t[s]!==void 0){let o=n[s].validator.input["~standard"].validate(t[s]);if(o instanceof Promise)throw D.from("INTERNAL_SERVER_ERROR",ae.ASYNC_VALIDATION_NOT_SUPPORTED);if("issues"in o&&o.issues)throw D.from("BAD_REQUEST",{...ae.VALIDATION_ERROR,message:o.issues[0]?.message||"Validation Error"});i[s]=o.value;continue}if(n[s].transform?.input&&t[s]!==void 0){i[s]=n[s].transform?.input(t[s]);continue}i[s]=t[s];continue}if(n[s].defaultValue!==void 0&&r==="create"){if(typeof n[s].defaultValue=="function"){i[s]=n[s].defaultValue();continue}i[s]=n[s].defaultValue;continue}if(n[s].required&&r==="create")throw D.from("BAD_REQUEST",{...ae.MISSING_FIELD,message:`${s} is required`})}return i}function vv(t,e={},r){return bv(e,{fields:Uf(t,"user","input"),action:r})}function Qfe(t,e){let r=Uf(t,"user","input");return bv(e||{},{fields:r})}function eme(t,e){return bv(e,{fields:Uf(t,"account","input")})}function xC(t,e,r){return bv(e,{fields:Uf(t,"session","input"),action:r})}function IC(t){let e=Uf(t,"session","input"),r={};for(let n in e)e[n].defaultValue!==void 0&&(r[n]=typeof e[n].defaultValue=="function"?e[n].defaultValue():e[n].defaultValue);return r}function AC(t,e){if(!e)return t;for(let r in e){let n=e[r]?.modelName;n&&(t[r].modelName=n);for(let i in t[r].fields){let s=e[r]?.fields?.[i];s&&(t[r].fields[i].fieldName=s)}}return t}var rW,jl=I(()=>{cp();rt();wC();rW=new WeakMap});var xo,Yh=I(()=>{xo=(t,e="ms")=>new Date(Date.now()+(e==="sec"?t*1e3:t))});function _v(t){return!!t&&(typeof t=="object"||typeof t=="function")&&typeof t.then=="function"}var OC=I(()=>{});function mnt(t){let e=fnt.exec(t);if(!e||e[4]&&e[1])throw new TypeError(`Invalid time string format: "${t}". Use formats like "7d", "30m", "1 hour", etc.`);let r=parseFloat(e[2]),n=e[3].toLowerCase(),i;switch(n){case"years":case"year":case"yrs":case"yr":case"y":i=r*315576e5;break;case"months":case"month":case"mo":i=r*2592e6;break;case"weeks":case"week":case"w":i=r*6048e5;break;case"days":case"day":case"d":i=r*864e5;break;case"hours":case"hour":case"hrs":case"hr":case"h":i=r*36e5;break;case"minutes":case"minute":case"mins":case"min":case"m":i=r*6e4;break;case"seconds":case"second":case"secs":case"sec":case"s":i=r*1e3;break;default:throw new TypeError(`Unknown time unit: "${n}"`)}return e[1]==="-"||e[4]==="ago"?-i:i}function tme(t){return Math.round(mnt(t)/1e3)}var fnt,rme=I(()=>{fnt=/^(\+|\-)? ?(\d+|\d+\.\d+) ?(seconds?|secs?|s|minutes?|mins?|m|hours?|hrs?|h|days?|d|weeks?|w|months?|mo|years?|yrs?|y)(?: (ago|from now))?$/i});var nme,ime=I(()=>{nme="__Secure-"});function sme(t){if(typeof t=="string"&&hnt.test(t)){let e=new Date(t);if(!isNaN(e.getTime()))return e}return t}function nW(t){if(t==null)return t;if(typeof t=="string")return sme(t);if(t instanceof Date)return t;if(Array.isArray(t))return t.map(nW);if(typeof t=="object"){let e={};for(let r of Object.keys(t))e[r]=nW(t[r]);return e}return t}function lr(t){try{return typeof t!="string"?t==null?null:nW(t):JSON.parse(t,(e,r)=>sme(r))}catch(e){return De.error("Error parsing JSON",{error:e}),null}}var hnt,lp=I(()=>{bs();hnt=/^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}(?:\.\d+)?Z$/});function gnt(t){let e=t.headers?.get("cookie");if(!e)return{};let r={},n=e.split("; ");for(let i of n){let[s,...o]=i.split("=");s&&o.length>0&&(r[s]=o.join("="))}return r}function ome(t){let e=t.split("."),r=e[e.length-1],n=parseInt(r||"0",10);return isNaN(n)?0:n}function ynt(t,e){let r={},n=gnt(e);for(let[i,s]of Object.entries(n))i.startsWith(t)&&(r[i]=s);return r}function bnt(t){return Object.keys(t).sort((e,r)=>ome(e)-ome(r)).map(e=>t[e]).join("")}function vnt(t,e,r,n){let i=Math.ceil(e.value.length/iW);if(i===1)return r[e.name]=e.value,[e];let s=[];for(let o=0;o<i;o++){let a=`${e.name}.${o}`,c=o*iW,l=e.value.substring(c,c+iW);s.push({...e,name:a,value:l}),r[a]=l}return n.debug(`CHUNKING_${t.toUpperCase()}_COOKIE`,{message:`${t} cookie exceeds allowed ${oW} bytes.`,emptyCookieSize:sW,valueSize:e.value.length,chunkCount:i,chunks:s.map(o=>o.value.length+sW)}),s}function ame(t,e){let r={};for(let n in t)r[n]={name:n,value:"",attributes:{...e,maxAge:0}};return r}function CC(t,e){let r=t.getCookie(e);if(r)return r;let n=[],i=t.headers?.get("cookie");if(!i)return null;let s={},o=i.split("; ");for(let a of o){let[c,...l]=a.split("=");c&&l.length>0&&(s[c]=l.join("="))}for(let[a,c]of Object.entries(s))if(a.startsWith(e+".")){let l=a.split(".").at(-1),u=parseInt(l||"0",10);isNaN(u)||n.push({index:u,value:c})}return n.length>0?(n.sort((a,c)=>a.index-c.index),n.map(a=>a.value).join("")):null}async function Kf(t,e){let r=t.context.authCookies.accountData,n={maxAge:300,...r.attributes},i=await gC(e,t.context.secretConfig,"better-auth-account",n.maxAge);if(i.length>oW){let s=kC(r.name,n,t),o=s.chunk(i,n);s.setCookies(o)}else{let s=kC(r.name,n,t);if(s.hasChunks()){let o=s.clean();s.setCookies(o)}t.setCookie(r.name,i,n)}}async function Ev(t){let e=CC(t,t.context.authCookies.accountData.name);if(e){let r=lr(await j0(e,t.context.secretConfig,"better-auth-account"));if(r)return r}return null}var Jh,oW,sW,iW,cme,RC,kC,lme,W0=I(()=>{U0();lp();Jh=le(require("zod"),1),oW=4096,sW=200,iW=oW-sW;cme=t=>(e,r,n)=>{let i=ynt(e,n),s=n.context.logger;return{getValue(){return bnt(i)},hasChunks(){return Object.keys(i).length>0},chunk(o,a){let c=ame(i,r);for(let d in i)delete i[d];let l=c,u=vnt(t,{name:e,value:o,attributes:{...r,...a}},i,s);for(let d of u)l[d.name]=d;return Object.values(l)},clean(){let o=ame(i,r);for(let a in i)delete i[a];return Object.values(o)},setCookies(o){for(let a of o)n.setCookie(a.name,a.value,a.attributes)}}},RC=cme("Session"),kC=cme("Account");lme=Jh.optional(Jh.object({disableCookieCache:Jh.coerce.boolean().meta({description:"Disable cookie cache and fetch session from database"}).optional(),disableRefresh:Jh.coerce.boolean().meta({description:"Disable session refresh. Useful for checking session status, without updating the session"}).optional()}))});var aW,_nt,cW,lW=I(()=>{aW=new Map,_nt=new TextEncoder,cW={decode:(t,e="utf-8")=>(aW.has(e)||aW.set(e,new TextDecoder(e)),aW.get(e).decode(t)),encode:_nt.encode}});var Ent,uW,ume=I(()=>{Ent="0123456789abcdef",uW={encode:t=>{if(typeof t=="string"&&(t=new TextEncoder().encode(t)),t.byteLength===0)return"";let e=new Uint8Array(t),r="";for(let n of e)r+=n.toString(16).padStart(2,"0");return r},decode:t=>{if(!t)return"";if(typeof t=="string"){if(t.length%2!==0)throw new Error("Invalid hexadecimal string");if(!new RegExp(`^[${Ent}]+$`).test(t))throw new Error("Invalid hexadecimal string");let e=new Uint8Array(t.length/2);for(let r=0;r<t.length;r+=2)e[r/2]=parseInt(t.slice(r,r+2),16);return new TextDecoder().decode(e)}return new TextDecoder().decode(t)}}});var NC,dW=I(()=>{ume();pa();K0();NC=(t="SHA-256",e="none")=>{let r={importKey:async(n,i)=>Ml().importKey("raw",typeof n=="string"?new TextEncoder().encode(n):n,{name:"HMAC",hash:{name:t}},!1,[i]),sign:async(n,i)=>{typeof n=="string"&&(n=await r.importKey(n,"sign"));let s=await Ml().sign("HMAC",n,typeof i=="string"?new TextEncoder().encode(i):i);return e==="hex"?uW.encode(s):e==="base64"||e==="base64url"||e==="base64urlnopad"?da.encode(s,{padding:e!=="base64urlnopad"}):s},verify:async(n,i,s)=>(typeof n=="string"&&(n=await r.importKey(n,"verify")),e==="hex"&&(s=uW.decode(s)),(e==="base64"||e==="base64url"||e==="base64urlnopad")&&(s=await Hi.decode(s)),Ml().verify("HMAC",n,typeof s=="string"?new TextEncoder().encode(s):s,typeof i=="string"?new TextEncoder().encode(i):i))};return r}});function $0(t){let e=typeof t.baseURL=="string"?t.baseURL:void 0,r=typeof t.baseURL=="object"&&t.baseURL!==null?t.baseURL.protocol:void 0,n=(t.advanced?.useSecureCookies!==void 0?t.advanced?.useSecureCookies:r==="https"||r!=="http"&&(e?e.startsWith("https://"):xf))?nme:"",i=!!t.advanced?.crossSubDomainCookies?.enabled,s=i?t.advanced?.crossSubDomainCookies?.domain||(e?new URL(e).hostname:void 0):void 0;if(i&&!s&&!Wa(t.baseURL))throw new me("baseURL is required when crossSubdomainCookies are enabled.");function o(a,c={}){let l=t.advanced?.cookiePrefix||"better-auth",u=t.advanced?.cookies?.[a]?.name||`${l}.${a}`,d=t.advanced?.cookies?.[a]?.attributes??{};return{name:`${n}${u}`,attributes:{secure:!!n,sameSite:"lax",path:"/",httpOnly:!0,...i?{domain:s}:{},...t.advanced?.defaultCookieAttributes,...c,...d}}}return o}function PC(t){let e=$0(t),r=e("session_token",{maxAge:t.session?.expiresIn||tme("7d")}),n=e("session_data",{maxAge:t.session?.cookieCache?.maxAge||300}),i=e("account_data",{maxAge:t.session?.cookieCache?.maxAge||300}),s=e("dont_remember");return{sessionToken:{name:r.name,attributes:r.attributes},sessionData:{name:n.name,attributes:n.attributes},dontRememberToken:{name:s.name,attributes:s.attributes},accountData:{name:i.name,attributes:i.attributes}}}async function G0(t,e,r){if(!t.context.options.session?.cookieCache?.enabled)return;let n=Xs(e.session,t.context.options.session?.additionalFields),i=Br(t.context.options,e.user),s=t.context.options.session?.cookieCache?.version,o="1";if(s){if(typeof s=="string")o=s;else if(typeof s=="function"){let p=s(e.session,e.user);o=_v(p)?await p:p}}let a={session:n,user:i,updatedAt:Date.now(),version:o},c={...t.context.authCookies.sessionData.attributes,maxAge:r?void 0:t.context.authCookies.sessionData.attributes.maxAge},l=xo(c.maxAge||60,"sec").getTime(),u=t.context.options.session?.cookieCache?.strategy||"compact",d;if(u==="jwe"?d=await gC(a,t.context.secretConfig,"better-auth-session",c.maxAge||300):u==="jwt"?d=await hC(a,t.context.secret,c.maxAge||300):d=da.encode(JSON.stringify({session:a,expiresAt:l,signature:await NC("SHA-256","base64urlnopad").sign(t.context.secret,JSON.stringify({...a,expiresAt:l}))}),{padding:!1}),d.length>4093){let p=RC(t.context.authCookies.sessionData.name,c,t),f=p.chunk(d,c);p.setCookies(f)}else{let p=RC(t.context.authCookies.sessionData.name,c,t);if(p.hasChunks()){let f=p.clean();p.setCookies(f)}t.setCookie(t.context.authCookies.sessionData.name,d,c)}if(t.context.options.account?.storeAccountCookie){let p=await Ev(t);p&&await Kf(t,p)}}async function jr(t,e,r,n){let i=await t.getSignedCookie(t.context.authCookies.dontRememberToken.name,t.context.secret);r=r!==void 0?r:!!i;let s=t.context.authCookies.sessionToken.attributes,o=r?void 0:t.context.sessionConfig.expiresIn;await t.setSignedCookie(t.context.authCookies.sessionToken.name,e.session.token,t.context.secret,{...s,maxAge:o,...n}),r&&await t.setSignedCookie(t.context.authCookies.dontRememberToken.name,"true",t.context.secret,t.context.authCookies.dontRememberToken.attributes),await G0(t,e,r),t.context.setNewSession(e)}function fa(t,e){t.setCookie(e.name,"",{...e.attributes,maxAge:0})}function qf(t,e){if(fa(t,t.context.authCookies.sessionToken),fa(t,t.context.authCookies.sessionData),t.context.options.account?.storeAccountCookie){fa(t,t.context.authCookies.accountData);let i=kC(t.context.authCookies.accountData.name,t.context.authCookies.accountData.attributes,t),s=i.clean();i.setCookies(s)}t.context.oauthConfig.storeStateStrategy==="cookie"&&fa(t,t.context.createAuthCookie("oauth_state"));let r=RC(t.context.authCookies.sessionData.name,t.context.authCookies.sessionData.attributes,t),n=r.clean();r.setCookies(n),e||fa(t,t.context.authCookies.dontRememberToken)}var Io=I(()=>{Kh();U0();jl();Yh();OC();rme();ime();W0();vs();rt();wC();pa();lW();dW()});async function pme(t,e,r){let n=tp(32);if(t.context.oauthConfig.storeStateStrategy==="cookie"){let o={...e,oauthState:n},a=await _C({key:t.context.secretConfig,data:JSON.stringify(o)}),c=t.context.createAuthCookie(r?.cookieName??"oauth_state",{maxAge:600});return t.setCookie(c.name,a,c.attributes),{state:n,codeVerifier:e.codeVerifier}}let i=t.context.createAuthCookie(r?.cookieName??"state",{maxAge:300});await t.setSignedCookie(i.name,n,t.context.secret,i.attributes);let s=new Date;if(s.setMinutes(s.getMinutes()+10),!await t.context.internalAdapter.createVerificationValue({value:JSON.stringify({...e,oauthState:n}),identifier:n,expiresAt:s}))throw new Zu("Unable to create verification. Make sure the database adapter is properly working and there is a verification table in the database",{code:"state_generation_error"});return{state:n,codeVerifier:e.codeVerifier}}async function fme(t,e,r){let n=t.context.oauthConfig.storeStateStrategy,i;if(n==="cookie"){let s=t.context.createAuthCookie(r?.cookieName??"oauth_state"),o=t.getCookie(s.name);if(!o)throw new Zu("State mismatch: auth state cookie not found",{code:"state_mismatch",details:{state:e}});try{let a=await EC({key:t.context.secretConfig,data:o});i=dme.parse(JSON.parse(a))}catch(a){throw new Zu("State invalid: Failed to decrypt or parse auth state",{code:"state_invalid",details:{state:e},cause:a})}if(!i.oauthState||i.oauthState!==e)throw new Zu("State mismatch: OAuth state parameter does not match stored state",{code:"state_security_mismatch",details:{state:e}});fa(t,s)}else{let s=await t.context.internalAdapter.findVerificationValue(e);if(!s)throw new Zu("State mismatch: verification not found",{code:"state_mismatch",details:{state:e}});if(i=dme.parse(JSON.parse(s.value)),i.oauthState!==void 0&&i.oauthState!==e)throw new Zu("State mismatch: OAuth state parameter does not match stored state",{code:"state_security_mismatch",details:{state:e}});let o=t.context.createAuthCookie(r?.cookieName??"state"),a=await t.getSignedCookie(o.name,t.context.secret);if(!(r?.skipStateCookieCheck??t.context.oauthConfig.skipStateCookieCheck)&&(!a||a!==e))throw new Zu("State mismatch: State not persisted correctly",{code:"state_security_mismatch",details:{state:e}});fa(t,o),await t.context.internalAdapter.deleteVerificationByIdentifier(e)}if(i.expiresAt<Date.now())throw new Zu("Invalid state: request expired",{code:"state_mismatch",details:{expiresAt:i.expiresAt}});return i}var xs,dme,Zu,mme=I(()=>{b0();SC();Io();rt();xs=le(require("zod"),1),dme=xs.looseObject({callbackURL:xs.string(),codeVerifier:xs.string(),errorURL:xs.string().optional(),newUserURL:xs.string().optional(),expiresAt:xs.number(),oauthState:xs.string().optional(),link:xs.object({email:xs.string(),userId:xs.coerce.string()}).optional(),requestSignUp:xs.boolean().optional()}),Zu=class extends me{code;details;constructor(t,e){super(t,e),this.code=e.code,this.details=e.details}}});function Zh(){return globalThis[V0]||(globalThis[V0]={version:pW,epoch:1,context:Snt},Y0=globalThis[V0]),Y0=globalThis[V0],Y0.version!==pW&&(Y0.version=pW,Y0.epoch++),globalThis[V0]}function fW(){return Zh().version}var V0,Y0,Snt,pW,J0=I(()=>{V0=Symbol.for("better-auth:global"),Y0=null,Snt={},pW="1.6.10"});async function Sv(){let t=await wnt;if(t===null)throw new Error("getAsyncLocalStorage is only available in server code");return t}var wnt,DC=I(()=>{wnt=import("node:async_hooks").then(t=>t.AsyncLocalStorage).catch(t=>{if("AsyncLocalStorage"in globalThis)return globalThis.AsyncLocalStorage;if(typeof window<"u")return null;throw console.warn("[better-auth] Warning: AsyncLocalStorage is not available in this environment. Some features may not work as expected."),console.warn("[better-auth] Please read more about this warning at https://better-auth.com/docs/installation#mount-handler"),console.warn("[better-auth] If you are using Cloudflare Workers, please see: https://developers.cloudflare.com/workers/configuration/compatibility-flags/#nodejs-compatibility-flag"),t})});async function up(){let t=(await hme()).getStore();if(!t)throw new Error("No auth context found. Please make sure you are calling this function within a `runWithEndpointContext` callback.");return t}async function wv(t,e){return(await hme()).run(t,e)}var hme,mW=I(()=>{J0();DC();hme=async()=>{let t=Zh();if(!t.context.endpointContextAsyncStorage){let e=await Sv();t.context.endpointContextAsyncStorage=new e}return t.context.endpointContextAsyncStorage}});async function yW(){return(await gW()).getStore()!==void 0}async function hW(){let t=(await gW()).getStore();if(!t)throw new Error("No request state found. Please make sure you are calling this function within a `runWithRequestState` callback.");return t}async function bW(t,e){return(await gW()).run(t,e)}function Z0(t){let e=Object.freeze({});return{get ref(){return e},async get(){let r=await hW();if(!r.has(e)){let n=await t();return r.set(e,n),n}return r.get(e)},async set(r){(await hW()).set(e,r)}}}var gW,gme=I(()=>{J0();DC();gW=async()=>{let t=Zh();if(!t.context.requestStateAsyncStorage){let e=await Sv();t.context.requestStateAsyncStorage=new e}return t.context.requestStateAsyncStorage}});var MC,Ue,vW,X0,Xh,yme=I(()=>{J0();DC();MC=async()=>{let t=Zh();if(!t.context.adapterAsyncStorage){let e=await Sv();t.context.adapterAsyncStorage=new e}return t.context.adapterAsyncStorage},Ue=async t=>MC().then(e=>e.getStore()?.adapter||t).catch(()=>t),vW=async(t,e)=>{let r=!1;return MC().then(async n=>{r=!0;let i=[],s,o,a=!1;try{s=await n.run({adapter:t,pendingHooks:i},e)}catch(c){o=c,a=!0}for(let c of i)await c();if(a)throw o;return s}).catch(n=>{if(!r)return e();throw n})},X0=async(t,e)=>{let r=!0;return MC().then(async n=>{r=!0;let i=[],s,o,a=!1;try{s=await t.transaction(async c=>n.run({adapter:c,pendingHooks:i},e))}catch(c){a=!0,o=c}for(let c of i)await c();if(a)throw o;return s}).catch(n=>{if(!r)return e();throw n})},Xh=async t=>MC().then(e=>{let r=e.getStore();if(r)r.pendingHooks.push(t);else return t()}).catch(()=>t())});var Xu=I(()=>{J0();mW();gme();yme()});var tZt,_W,bme=I(()=>{Xu();({get:tZt,set:_W}=Z0(()=>null))});async function LC(t,e,r){let n=t.body?.callbackURL||t.context.options.baseURL;if(!n)throw D.from("BAD_REQUEST",ae.CALLBACK_URL_REQUIRED);let i=tp(128),s={...r||{},callbackURL:n,codeVerifier:i,errorURL:t.body?.errorCallbackURL,newUserURL:t.body?.newUserCallbackURL,link:e,expiresAt:Date.now()+600*1e3,requestSignUp:t.body?.requestSignUp};await _W(s);try{return pme(t,s)}catch(o){throw t.context.logger.error("Failed to create verification",o),new D("INTERNAL_SERVER_ERROR",{message:"Unable to create verification",cause:o})}}async function vme(t){let e=t.query.state||t.body?.state,r=t.context.options.onAPIError?.errorURL||`${t.context.baseURL}/error`,n;try{n=await fme(t,e)}catch(i){throw t.context.logger.error("Failed to parse state",i),i instanceof Zu&&i.code==="state_security_mismatch"?t.redirect(`${r}?error=state_mismatch`):t.redirect(`${r}?error=please_restart_the_process`)}return n.errorURL||(n.errorURL=r),n&&await _W(n),n}var jC=I(()=>{b0();bme();mme();rt()});var Tv,UC=I(()=>{Tv={scope:"server"}});async function _me(t,e){let r=t.headers.get("content-type")||"",n=r.toLowerCase();if(t.body){if(e&&e.length>0&&!e.some(i=>{let s=n.split(";")[0].trim(),o=i.toLowerCase().trim();return s===o||s.includes(o)}))throw n?new ua(415,{message:`Content-Type "${r}" is not allowed. Allowed types: ${e.join(", ")}`,code:"UNSUPPORTED_MEDIA_TYPE"}):new ua(415,{message:`Content-Type is required. Allowed types: ${e.join(", ")}`,code:"UNSUPPORTED_MEDIA_TYPE"});if(Tnt.test(n))return await t.json();if(n.includes("application/x-www-form-urlencoded")){let i=await t.formData(),s={};return i.forEach((o,a)=>{s[a]=o.toString()}),s}if(n.includes("multipart/form-data")){let i=await t.formData(),s={};return i.forEach((o,a)=>{s[a]=o}),s}return n.includes("text/plain")?await t.text():n.includes("application/octet-stream")?await t.arrayBuffer():n.includes("application/pdf")||n.includes("image/")||n.includes("video/")?await t.blob():n.includes("application/stream")||t.body instanceof ReadableStream?t.body:await t.text()}}function dp(t){return t instanceof ua||t?.name==="APIError"}function Eme(t){try{return t.includes("%")?decodeURIComponent(t):t}catch{return t}}async function Sme(t){try{return{data:await t,error:null}}catch(e){return{data:null,error:e}}}function KC(t){return t instanceof Request||Object.prototype.toString.call(t)==="[object Request]"}var Tnt,Qh=I(()=>{If();Tnt=/^application\/([a-z0-9.+-]*\+)?json/i});function xnt(t){if(t===void 0)return!1;let e=typeof t;return e==="string"||e==="number"||e==="boolean"||e===null?!0:e!=="object"?!1:Array.isArray(t)?!0:t.buffer?!1:t.constructor&&t.constructor.name==="Object"||typeof t.toJSON=="function"}function Int(t,e,r){let n=0,i=new WeakMap;return JSON.stringify(t,(o,a)=>{if(typeof a=="bigint")return a.toString();if(typeof a=="object"&&a!==null){if(i.has(a))return`[Circular ref-${i.get(a)}]`;i.set(a,n++)}return e?e(o,a):a},r)}function Ant(t){return!t||typeof t!="object"?!1:"_flag"in t&&t._flag==="json"}function EW(t){for(let e of Ont)t.delete(e)}function Ul(t,e){if(t instanceof Response){if(e?.headers){let i=new Headers(e.headers);EW(i),i.forEach((s,o)=>{t.headers.set(o,s)})}return t}if(Ant(t)){let i=t.body,s=t.routerResponse;if(s instanceof Response)return s;let o=new Headers;if(s?.headers){let a=new Headers(s.headers);for(let[c,l]of a.entries())a.set(c,l)}if(t.headers)for(let[a,c]of new Headers(t.headers).entries())o.set(a,c);if(e?.headers){let a=new Headers(e.headers);EW(a);for(let[c,l]of a.entries())o.set(c,l)}return o.set("Content-Type","application/json"),new Response(JSON.stringify(i),{...s,headers:o,status:t.status??e?.status??s?.status,statusText:e?.statusText??s?.statusText})}if(dp(t))return Ul(t.body,{status:e?.status??t.statusCode,statusText:t.status.toString(),headers:e?.headers||t.headers});let r=t,n=new Headers(e?.headers);return EW(n),t?typeof t=="string"?(r=t,n.set("Content-Type","text/plain")):t instanceof ArrayBuffer||ArrayBuffer.isView(t)?(r=t,n.set("Content-Type","application/octet-stream")):t instanceof Blob?(r=t,n.set("Content-Type",t.type||"application/octet-stream")):t instanceof FormData?r=t:t instanceof URLSearchParams?(r=t,n.set("Content-Type","application/x-www-form-urlencoded")):t instanceof ReadableStream?(r=t,n.set("Content-Type","application/octet-stream")):xnt(t)&&(r=Int(t),n.set("Content-Type","application/json")):(t===null&&(r=JSON.stringify(null)),n.set("content-type","application/json")),new Response(r,{...e,headers:n})}var Ont,qC=I(()=>{If();Qh();Ont=new Set(["host","user-agent","referer","from","expect","authorization","proxy-authorization","cookie","origin","accept-charset","accept-encoding","accept-language","if-match","if-none-match","if-modified-since","if-unmodified-since","if-range","range","max-forwards","connection","keep-alive","transfer-encoding","te","upgrade","trailer","proxy-connection","content-length"])});var SW,wW,wme,knt,Tme,TW=I(()=>{K0();SW={name:"HMAC",hash:"SHA-256"},wW=async t=>{let e=typeof t=="string"?new TextEncoder().encode(t):t;return await Ml().importKey("raw",e,SW,!1,["sign","verify"])},wme=async(t,e,r)=>{try{let n=atob(t),i=new Uint8Array(n.length);for(let s=0,o=n.length;s<o;s++)i[s]=n.charCodeAt(s);return await Ml().verify(SW,r,i,new TextEncoder().encode(e))}catch{return!1}},knt=async(t,e)=>{let r=await wW(e),n=await Ml().sign(SW.name,r,new TextEncoder().encode(t));return btoa(String.fromCharCode(...new Uint8Array(n)))},Tme=async(t,e)=>{let r=await knt(t,e);return t=`${t}.${r}`,t=encodeURIComponent(t),t}});function xW(t){if(typeof t!="string")throw new TypeError("argument str must be a string");let e=new Map,r=0;for(;r<t.length;){let n=t.indexOf("=",r);if(n===-1)break;let i=t.indexOf(";",r);if(i===-1)i=t.length;else if(i<n){r=t.lastIndexOf(";",n-1)+1;continue}let s=t.slice(r,n).trim();if(!e.has(s)){let o=t.slice(n+1,i).trim();o.codePointAt(0)===34&&(o=o.slice(1,-1)),e.set(s,Eme(o))}r=i+1}return e}var FC,xme,IW,AW,OW=I(()=>{Qh();TW();FC=(t,e)=>{let r=t;if(e)if(e==="secure")r="__Secure-"+t;else if(e==="host")r="__Host-"+t;else return;return r};xme=(t,e,r={})=>{let n;if(r?.prefix==="secure"?n=`${`__Secure-${t}`}=${e}`:r?.prefix==="host"?n=`${`__Host-${t}`}=${e}`:n=`${t}=${e}`,t.startsWith("__Secure-")&&!r.secure&&(r.secure=!0),t.startsWith("__Host-")&&(r.secure||(r.secure=!0),r.path!=="/"&&(r.path="/"),r.domain&&(r.domain=void 0)),r&&typeof r.maxAge=="number"&&r.maxAge>=0){if(r.maxAge>3456e4)throw new Error("Cookies Max-Age SHOULD NOT be greater than 400 days (34560000 seconds) in duration.");n+=`; Max-Age=${Math.floor(r.maxAge)}`}if(r.domain&&r.prefix!=="host"&&(n+=`; Domain=${r.domain}`),r.path&&(n+=`; Path=${r.path}`),r.expires){if(r.expires.getTime()-Date.now()>3456e7)throw new Error("Cookies Expires SHOULD NOT be greater than 400 days (34560000 seconds) in the future.");n+=`; Expires=${r.expires.toUTCString()}`}return r.httpOnly&&(n+="; HttpOnly"),r.secure&&(n+="; Secure"),r.sameSite&&(n+=`; SameSite=${r.sameSite.charAt(0).toUpperCase()+r.sameSite.slice(1)}`),r.partitioned&&(r.secure||(r.secure=!0),n+="; Partitioned"),n},IW=(t,e,r)=>(e=encodeURIComponent(e),xme(t,e,r)),AW=async(t,e,r,n)=>(e=await Tme(e,r),xme(t,e,n))});async function Ame(t,e={}){let r={body:e.body,query:e.query};if(t.body){let n=await t.body["~standard"].validate(e.body);if(n.issues)return{data:null,error:Ime(n.issues,"body")};r.body=n.value}if(t.query){let n=await t.query["~standard"].validate(e.query);if(n.issues)return{data:null,error:Ime(n.issues,"query")};r.query=n.value}return t.requireHeaders&&!e.headers?{data:null,error:{message:"Headers is required",issues:[]}}:t.requireRequest&&!e.request?{data:null,error:{message:"Request is required",issues:[]}}:{data:r,error:null}}function Ime(t,e){return{message:t.map(r=>`[${r.path?.length?`${e}.`+r.path.map(n=>typeof n=="object"?n.key:n).join("."):e}] ${r.message}`).join("; "),issues:t}}var Ome=I(()=>{});var Q0,zC=I(()=>{If();Qh();Ome();TW();OW();Q0=async(t,{options:e,path:r})=>{let n=new Headers,i,{data:s,error:o}=await Ame(e,t);if(o)throw new g0(o.message,o.issues);let a="headers"in t?t.headers instanceof Headers?t.headers:new Headers(t.headers):"request"in t&&KC(t.request)?t.request.headers:null,c=a?.get("cookie"),l=c?xW(c):void 0,u={...t,body:s.body,query:s.query,path:t.path||r||"virtual:",context:"context"in t&&t.context?t.context:{},returned:void 0,headers:t?.headers,request:t?.request,params:"params"in t?t.params:void 0,method:t.method??(Array.isArray(e.method)?e.method[0]:e.method==="*"?"GET":e.method),setHeader:(d,p)=>{n.set(d,p)},getHeader:d=>a?a.get(d):null,getCookie:(d,p)=>{let f=FC(d,p);return f&&l?.get(f)||null},getSignedCookie:async(d,p,f)=>{let m=FC(d,f);if(!m)return null;let h=l?.get(m);if(!h)return null;let y=h.lastIndexOf(".");if(y<1)return null;let g=h.substring(0,y),b=h.substring(y+1);return b.length!==44||!b.endsWith("=")?null:await wme(b,g,await wW(p))?g:!1},setCookie:(d,p,f)=>{let m=IW(d,p,f);return n.append("set-cookie",m),m},setSignedCookie:async(d,p,f,m)=>{let h=await AW(d,p,f,m);return n.append("set-cookie",h),h},redirect:d=>(n.set("location",d),new ua("FOUND",void 0,n)),error:(d,p,f)=>new ua(d,p,f),setStatus:d=>{i=d},json:(d,p)=>t.asResponse?{body:p?.body||d,routerResponse:p,_flag:"json"}:d,responseHeaders:n,get responseStatus(){return i}};for(let d of e.use||[]){let p=await d({...u,returnHeaders:!0,asResponse:!1});p.response&&Object.assign(u.context,p.response),p.headers&&p.headers.forEach((f,m)=>{u.responseHeaders.set(m,f)})}return u}});function Ff(t,e,r){let n=typeof t=="string"?t:void 0,i=typeof e=="object"?e:t,s=typeof e=="function"?e:r;if((i.method==="GET"||i.method==="HEAD")&&i.body)throw new UR("Body is not allowed with GET or HEAD methods");if(n&&/\/{2,}/.test(n))throw new UR("Path cannot contain consecutive slashes");let o=async(...a)=>{let c=a[0]||{},{data:l,error:u}=await Sme(Q0(c,{options:i,path:n}));if(u)throw u instanceof g0?(i.onValidationError&&await i.onValidationError({message:u.message,issues:u.issues}),new ua(400,{message:u.message,code:"VALIDATION_ERROR"})):u;let d=await s(l).catch(async m=>{if(dp(m)){let h=i.onAPIError;if(h&&await h(m),c.asResponse)return m}throw m}),p=l.responseHeaders,f=l.responseStatus;return c.asResponse?Ul(d,{headers:p,status:f}):c.returnHeaders?c.returnStatus?{headers:p,response:d,status:f}:{headers:p,response:d}:c.returnStatus?{response:d,status:f}:d};return o.options=i,o.path=n,o}var BC=I(()=>{If();Qh();qC();zC();Ff.create=t=>(e,r,n)=>Ff(e,{...r,use:[...r?.use||[],...t?.use||[]]},n)});function zf(t,e){let r=async n=>{let i=n,s=typeof t=="function"?t:e,o=await Q0(i,{options:typeof t=="function"?{}:t,path:"/"});if(!s)throw new Error("handler must be defined");try{let a=await s(o),c=o.responseHeaders;return i.returnHeaders?{headers:c,response:a}:a}catch(a){throw dp(a)&&Object.defineProperty(a,Xd,{enumerable:!1,configurable:!0,get(){return o.responseHeaders}}),a}};return r.options=typeof t=="function"?{}:t,r}var kme=I(()=>{If();Qh();zC();BC();zf.create=t=>{function e(r,n){if(typeof r=="function")return zf({use:t?.use},r);if(!n)throw new Error("Middleware handler is required");return zf({...r,method:"*",use:[...t?.use||[],...r.use||[]]},n)}return e}});function Nme(t){switch(t.constructor.name){case"ZodString":return"string";case"ZodNumber":return"number";case"ZodBoolean":return"boolean";case"ZodObject":return"object";case"ZodArray":return"array";default:return"string"}}function Rme(t){let e=[];return t.metadata?.openapi?.parameters?(e.push(...t.metadata.openapi.parameters),e):(t.query instanceof pp.ZodObject&&Object.entries(t.query.shape).forEach(([r,n])=>{n instanceof pp.ZodObject&&e.push({name:r,in:"query",schema:{type:Nme(n),..."minLength"in n&&n.minLength?{minLength:n.minLength}:{},description:n.description}})}),e)}function Rnt(t){if(t.metadata?.openapi?.requestBody)return t.metadata.openapi.requestBody;if(t.body&&(t.body instanceof pp.ZodObject||t.body instanceof pp.ZodOptional)){let e=t.body.shape;if(!e)return;let r={},n=[];return Object.entries(e).forEach(([i,s])=>{s instanceof pp.ZodObject&&(r[i]={type:Nme(s),description:s.description},s instanceof pp.ZodOptional||n.push(i))}),{required:t.body instanceof pp.ZodOptional?!1:!!t.body,content:{"application/json":{schema:{type:"object",properties:r,required:n}}}}}}function Cme(t){return{400:{content:{"application/json":{schema:{type:"object",properties:{message:{type:"string"}},required:["message"]}}},description:"Bad Request. Usually due to missing parameters, or invalid parameters."},401:{content:{"application/json":{schema:{type:"object",properties:{message:{type:"string"}},required:["message"]}}},description:"Unauthorized. Due to missing or invalid authentication."},403:{content:{"application/json":{schema:{type:"object",properties:{message:{type:"string"}}}}},description:"Forbidden. You do not have permission to access this resource or to perform this action."},404:{content:{"application/json":{schema:{type:"object",properties:{message:{type:"string"}}}}},description:"Not Found. The requested resource was not found."},429:{content:{"application/json":{schema:{type:"object",properties:{message:{type:"string"}}}}},description:"Too Many Requests. You have exceeded the rate limit. Try again later."},500:{content:{"application/json":{schema:{type:"object",properties:{message:{type:"string"}}}}},description:"Internal Server Error. This is a problem with the server that you cannot fix."},...t}}async function RW(t,e){let r={schemas:{}};return Object.entries(t).forEach(([n,i])=>{let s=i.options;if(!(!i.path||s.metadata?.SERVER_ONLY)&&(s.method==="GET"&&(kW[i.path]={get:{tags:["Default",...s.metadata?.openapi?.tags||[]],description:s.metadata?.openapi?.description,operationId:s.metadata?.openapi?.operationId,security:[{bearerAuth:[]}],parameters:Rme(s),responses:Cme(s.metadata?.openapi?.responses)}}),s.method==="POST")){let o=Rnt(s);kW[i.path]={post:{tags:["Default",...s.metadata?.openapi?.tags||[]],description:s.metadata?.openapi?.description,operationId:s.metadata?.openapi?.operationId,security:[{bearerAuth:[]}],parameters:Rme(s),...o?{requestBody:o}:{requestBody:{content:{"application/json":{schema:{type:"object",properties:{}}}}}},responses:Cme(s.metadata?.openapi?.responses)}}}}),{openapi:"3.1.1",info:{title:"Better Auth",description:"API Reference for your Better Auth Instance",version:"1.1.0"},components:r,security:[{apiKeyCookie:[]}],servers:[{url:e?.url}],tags:[{name:"Default",description:"Default endpoints that are included with Better Auth by default. These endpoints are not part of any plugin."}],paths:kW}}var pp,kW,CW,NW=I(()=>{pp=require("zod"),kW={};CW=(t,e)=>`<!doctype html> | |||
| at `))}function Ide(t,e){class r extends t{#e;constructor(...i){if(srt()){let o=Error.stackTraceLimit;Error.stackTraceLimit=0,super(...i),Error.stackTraceLimit=o}else super(...i);let s=new Error().stack;s&&(this.#e=xde(s.replace(/^Error/,this.name)))}get errorStack(){return this.#e}}return Object.defineProperty(r.prototype,"constructor",{get(){return e},enumerable:!1,configurable:!0}),r}var Ade,Ode,g0,UR,Xd,ua,If=I(()=>{Ade={OK:200,CREATED:201,ACCEPTED:202,NO_CONTENT:204,MULTIPLE_CHOICES:300,MOVED_PERMANENTLY:301,FOUND:302,SEE_OTHER:303,NOT_MODIFIED:304,TEMPORARY_REDIRECT:307,BAD_REQUEST:400,UNAUTHORIZED:401,PAYMENT_REQUIRED:402,FORBIDDEN:403,NOT_FOUND:404,METHOD_NOT_ALLOWED:405,NOT_ACCEPTABLE:406,PROXY_AUTHENTICATION_REQUIRED:407,REQUEST_TIMEOUT:408,CONFLICT:409,GONE:410,LENGTH_REQUIRED:411,PRECONDITION_FAILED:412,PAYLOAD_TOO_LARGE:413,URI_TOO_LONG:414,UNSUPPORTED_MEDIA_TYPE:415,RANGE_NOT_SATISFIABLE:416,EXPECTATION_FAILED:417,"I'M_A_TEAPOT":418,MISDIRECTED_REQUEST:421,UNPROCESSABLE_ENTITY:422,LOCKED:423,FAILED_DEPENDENCY:424,TOO_EARLY:425,UPGRADE_REQUIRED:426,PRECONDITION_REQUIRED:428,TOO_MANY_REQUESTS:429,REQUEST_HEADER_FIELDS_TOO_LARGE:431,UNAVAILABLE_FOR_LEGAL_REASONS:451,INTERNAL_SERVER_ERROR:500,NOT_IMPLEMENTED:501,BAD_GATEWAY:502,SERVICE_UNAVAILABLE:503,GATEWAY_TIMEOUT:504,HTTP_VERSION_NOT_SUPPORTED:505,VARIANT_ALSO_NEGOTIATES:506,INSUFFICIENT_STORAGE:507,LOOP_DETECTED:508,NOT_EXTENDED:510,NETWORK_AUTHENTICATION_REQUIRED:511},Ode=class extends Error{constructor(t="INTERNAL_SERVER_ERROR",e=void 0,r={},n=typeof t=="number"?t:Ade[t]){super(e?.message,e?.cause?{cause:e.cause}:void 0),this.status=t,this.body=e,this.headers=r,this.statusCode=n,this.name="APIError",this.status=t,this.headers=r,this.statusCode=n,this.body=e}},g0=class extends Ode{constructor(t,e){super(400,{message:t,code:"VALIDATION_ERROR"}),this.message=t,this.issues=e,this.issues=e}},UR=class extends Error{constructor(t){super(t),this.name="BetterCallError"}},Xd=Symbol.for("better-call:api-error-headers"),ua=Ide(Ode,Error)});var me,D,rt=I(()=>{Tde();If();me=class extends Error{constructor(t,e){super(t,e),this.name="BetterAuthError",this.message=t,this.stack=""}},D=class SH extends ua{constructor(...e){super(...e)}static fromStatus(e,r){return new SH(e,r)}static from(e,r){return new SH(e,{message:r.message,code:r.code})}}});function ort(t){let e=t.replace(/:\d+$/,"").replace(/^\[|\]$/g,"").toLowerCase();return e==="localhost"||e.endsWith(".localhost")||e==="::1"||e.startsWith("127.")}function art(t){try{return(new URL(t).pathname.replace(/\/+$/,"")||"/")!=="/"}catch{throw new me(`Invalid base URL: ${t}. Please provide a valid base URL.`)}}function crt(t){try{let e=new URL(t);if(e.protocol!=="http:"&&e.protocol!=="https:")throw new me(`Invalid base URL: ${t}. URL must include 'http://' or 'https://'`)}catch(e){throw e instanceof me?e:new me(`Invalid base URL: ${t}. Please provide a valid base URL.`,{cause:e})}}function Qd(t,e="/api/auth"){if(crt(t),art(t))return t;let r=t.replace(/\/+$/,"");return!e||e==="/"?r:(e=e.startsWith("/")?e:`/${e}`,`${r}${e}`)}function y0(t,e){return!t||t.trim()===""?!1:e==="proto"?t==="http"||t==="https":e==="host"?[/\.\./,/\0/,/[\s]/,/^[.]/,/[<>'"]/,/javascript:/i,/file:/i,/data:/i].some(r=>r.test(t))?!1:/^[a-zA-Z0-9]([a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?(\.[a-zA-Z0-9]([a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?)*(:[0-9]{1,5})?$/.test(t)||/^(\d{1,3}\.){3}\d{1,3}(:[0-9]{1,5})?$/.test(t)||/^\[[0-9a-fA-F:]+\](:[0-9]{1,5})?$/.test(t)||/^localhost(:[0-9]{1,5})?$/i.test(t):!1}function ep(t,e,r,n,i){if(t)return Qd(t,e);if(n!==!1){let a=Zt.BETTER_AUTH_URL||Zt.NEXT_PUBLIC_BETTER_AUTH_URL||Zt.PUBLIC_BETTER_AUTH_URL||Zt.NUXT_PUBLIC_BETTER_AUTH_URL||Zt.NUXT_PUBLIC_AUTH_URL||(Zt.BASE_URL!=="/"?Zt.BASE_URL:void 0);if(a)return Qd(a,e)}let s=r?.headers.get("x-forwarded-host"),o=r?.headers.get("x-forwarded-proto");if(s&&o&&i&&y0(o,"proto")&&y0(s,"host")){let Bnt=Zt.BETTER_AUTH_URL||Zt.NEXT_PUBLIC_BETTER_AUTH_URL||Zt.PUBLIC_BETTER_AUTH_URL||Zt.NUXT_PUBLIC_BETTER_AUTH_URL||Zt.NUXT_PUBLIC_AUTH_URL;if(Bnt){try{let Hnt=new URL(Bnt).host;if(Hnt&&s!==Hnt){}}catch{}if(Bnt){try{let Hnt=new URL(Bnt).host;if(!Hnt||s!==Hnt)s=null}catch{s=null}}}if(s)try{return Qd(`${o}://${s}`,e)}catch{}}if(r){let a=Af(r.url);if(!a)throw new me("Could not get origin from request. Please provide a valid base URL.");return Qd(a,e)}if(typeof window<"u"&&window.location)return Qd(window.location.origin,e)}function Af(t){try{let e=new URL(t);return e.origin==="null"?null:e.origin}catch{return null}}function kde(t){try{return new URL(t).protocol}catch{return null}}function Rde(t){try{return new URL(t).host}catch{return null}}function Wa(t){return typeof t=="object"&&t!==null&&"allowedHosts"in t&&Array.isArray(t.allowedHosts)}function Bu(t){if(t instanceof Request)return!0;if(typeof t!="object"||t===null||Object.prototype.toString.call(t)!=="[object Request]")return!1;let e=t;return typeof e.url=="string"&&typeof e.headers=="object"&&e.headers!==null&&typeof e.headers.get=="function"}function Cde(t,e){let r=Bu(t)?t.headers:t;if(e){let i=r.get("x-forwarded-host");if(i&&y0(i,"host"))return i}let n=r.get("host");if(n&&y0(n,"host"))return n;if(Bu(t))try{return new URL(t.url).host}catch{return null}return null}function lrt(t,e,r){if(e==="http"||e==="https")return e;let n=Bu(t)?t.headers:t;if(r){let s=n.get("x-forwarded-proto");if(s&&y0(s,"proto"))return s}if(Bu(t))try{let s=new URL(t.url);if(s.protocol==="http:"||s.protocol==="https:")return s.protocol.slice(0,-1)}catch{}let i=Cde(t,r);return i&&ort(i)?"http":"https"}function drt(t,e,r,n){let i=Cde(e,n);if(!i){if(t.fallback)return Qd(t.fallback,r);throw new me("Could not determine host from request headers. Please provide a fallback URL in your baseURL config.")}if(t.allowedHosts.some(s=>urt(i,s)))return Qd(`${lrt(e,t.protocol,n)}://${i}`,r);if(t.fallback)return Qd(t.fallback,r);throw new me(`Host "${i}" is not in the allowed hosts list. Allowed hosts: ${t.allowedHosts.join(", ")}. Add this host to your allowedHosts config or provide a fallback URL.`)}function Nde(t,e,r,n,i){if(Wa(t))return r?drt(t,r,e,i):t.fallback?Qd(t.fallback,e):ep(void 0,e,void 0,n,i);let s=Bu(r)?r:void 0;return ep(typeof t=="string"?t:void 0,e,s,n,i)}var urt,Kh=I(()=>{PR();vs();rt();urt=(t,e)=>{if(!t||!e)return!1;let r=t.replace(/^https?:\/\//,"").split("/")[0].toLowerCase(),n=e.replace(/^https?:\/\//,"").split("/")[0].toLowerCase();return n.includes("*")||n.includes("?")?Uh(n)(r):r.toLowerCase()===n.toLowerCase()}});function Pde(t){switch(t){case"a-z":return"abcdefghijklmnopqrstuvwxyz";case"A-Z":return"ABCDEFGHIJKLMNOPQRSTUVWXYZ";case"0-9":return"0123456789";case"-_":return"-_";default:throw new Error(`Unsupported alphabet: ${t}`)}}function ev(...t){let e=t.map(Pde).join("");if(e.length===0)throw new Error("No valid characters provided for random string generation.");let r=e.length;return(n,...i)=>{if(n<=0)throw new Error("Length must be a positive integer.");let s=e,o=r;i.length>0&&(s=i.map(Pde).join(""),o=s.length);let a=Math.floor(256/o)*o,c=new Uint8Array(n*2),l=c.length,u="",d=l,p;for(;u.length<n;)d>=l&&(crypto.getRandomValues(c),d=0),p=c[d++],p<a&&(u+=s[p%o]);return u}}var KR=I(()=>{});var tp,b0=I(()=>{KR();tp=ev("a-z","0-9","A-Z","-_")});function prt(t){return t instanceof Uint8Array||ArrayBuffer.isView(t)&&t.constructor.name==="Uint8Array"&&"BYTES_PER_ELEMENT"in t&&t.BYTES_PER_ELEMENT===1}function qR(t,e=""){if(typeof t!="number"){let r=e&&`"${e}" `;throw new TypeError(`${r}expected number, got ${typeof t}`)}if(!Number.isSafeInteger(t)||t<0){let r=e&&`"${e}" `;throw new RangeError(`${r}expected integer >= 0, got ${t}`)}}function Of(t,e,r=""){let n=prt(t),i=t?.length,s=e!==void 0;if(!n||s&&i!==e){let o=r&&`"${r}" `,a=s?` of length ${e}`:"",c=n?`length=${i}`:`type=${typeof t}`,l=o+"expected Uint8Array"+a+", got "+c;throw n?new RangeError(l):new TypeError(l)}return t}function v0(t){if(typeof t!="function"||typeof t.create!="function")throw new TypeError("Hash must wrapped by utils.createHasher");if(qR(t.outputLen),qR(t.blockLen),t.outputLen<1)throw new Error('"outputLen" must be >= 1');if(t.blockLen<1)throw new Error('"blockLen" must be >= 1')}function tv(t,e=!0){if(t.destroyed)throw new Error("Hash instance has been destroyed");if(e&&t.finished)throw new Error("Hash#digest() has already been called")}function FR(t,e){Of(t,void 0,"digestInto() output");let r=e.outputLen;if(t.length<r)throw new RangeError('"digestInto() output" expected to be of length >='+r)}function rp(...t){for(let e=0;e<t.length;e++)t[e].fill(0)}function zR(t){return new DataView(t.buffer,t.byteOffset,t.byteLength)}function Pl(t,e){return t<<32-e|t>>>e}function Dde(t,e={}){let r=(i,s)=>t(s).update(i).digest(),n=t(void 0);return r.outputLen=n.outputLen,r.blockLen=n.blockLen,r.canXOF=n.canXOF,r.create=i=>t(i),Object.assign(r,e),Object.freeze(r)}var Mde,_0=I(()=>{Mde=t=>({oid:Uint8Array.from([6,9,96,134,72,1,101,3,4,2,t])})});var BR,wH,Lde=I(()=>{_0();BR=class{oHash;iHash;blockLen;outputLen;canXOF=!1;finished=!1;destroyed=!1;constructor(e,r){if(v0(e),Of(r,void 0,"key"),this.iHash=e.create(),typeof this.iHash.update!="function")throw new Error("Expected instance of class which extends utils.Hash");this.blockLen=this.iHash.blockLen,this.outputLen=this.iHash.outputLen;let n=this.blockLen,i=new Uint8Array(n);i.set(r.length>n?e.create().update(r).digest():r);for(let s=0;s<i.length;s++)i[s]^=54;this.iHash.update(i),this.oHash=e.create();for(let s=0;s<i.length;s++)i[s]^=106;this.oHash.update(i),rp(i)}update(e){return tv(this),this.iHash.update(e),this}digestInto(e){tv(this),FR(e,this),this.finished=!0;let r=e.subarray(0,this.outputLen);this.iHash.digestInto(r),this.oHash.update(r),this.oHash.digestInto(r),this.destroy()}digest(){let e=new Uint8Array(this.oHash.outputLen);return this.digestInto(e),e}_cloneInto(e){e||=Object.create(Object.getPrototypeOf(this),{});let{oHash:r,iHash:n,finished:i,destroyed:s,blockLen:o,outputLen:a}=this;return e=e,e.finished=i,e.destroyed=s,e.blockLen=o,e.outputLen=a,e.oHash=r._cloneInto(e.oHash),e.iHash=n._cloneInto(e.iHash),e}clone(){return this._cloneInto()}destroy(){this.destroyed=!0,this.oHash.destroy(),this.iHash.destroy()}},wH=(()=>{let t=((e,r,n)=>new BR(e,r).update(n).digest());return t.create=(e,r)=>new BR(e,r),t})()});function frt(t,e,r){return v0(t),r===void 0&&(r=new Uint8Array(t.outputLen)),wH(t,r,e)}function mrt(t,e,r,n=32){v0(t),qR(n,"length"),Of(e,void 0,"prk");let i=t.outputLen;if(e.length<i)throw new Error('"prk" must be at least HashLen octets');if(n>255*i)throw new Error("Length must be <= 255*HashLen");let s=Math.ceil(n/i);r===void 0?r=jde:Of(r,void 0,"info");let o=new Uint8Array(s*i),a=wH.create(t,e),c=a._cloneInto(),l=new Uint8Array(a.outputLen);for(let u=0;u<s;u++)TH[0]=u+1,c.update(u===0?jde:l).update(r).update(TH).digestInto(l),o.set(l,i*u),a._cloneInto(c);return a.destroy(),c.destroy(),rp(l,TH),o.slice(0,n)}var TH,jde,Ude,Kde=I(()=>{Lde();_0();TH=Uint8Array.of(0),jde=Uint8Array.of();Ude=(t,e,r,n,i)=>mrt(t,frt(t,e,r),n,i)});function qde(t,e,r){return t&e^~t&r}function Fde(t,e,r){return t&e^t&r^e&r}var HR,np,zde=I(()=>{_0();HR=class{blockLen;outputLen;canXOF=!1;padOffset;isLE;buffer;view;finished=!1;length=0;pos=0;destroyed=!1;constructor(e,r,n,i){this.blockLen=e,this.outputLen=r,this.padOffset=n,this.isLE=i,this.buffer=new Uint8Array(e),this.view=zR(this.buffer)}update(e){tv(this),Of(e);let{view:r,buffer:n,blockLen:i}=this,s=e.length;for(let o=0;o<s;){let a=Math.min(i-this.pos,s-o);if(a===i){let c=zR(e);for(;i<=s-o;o+=i)this.process(c,o);continue}n.set(e.subarray(o,o+a),this.pos),this.pos+=a,o+=a,this.pos===i&&(this.process(r,0),this.pos=0)}return this.length+=e.length,this.roundClean(),this}digestInto(e){tv(this),FR(e,this),this.finished=!0;let{buffer:r,view:n,blockLen:i,isLE:s}=this,{pos:o}=this;r[o++]=128,rp(this.buffer.subarray(o)),this.padOffset>i-o&&(this.process(n,0),o=0);for(let d=o;d<i;d++)r[d]=0;n.setBigUint64(i-8,BigInt(this.length*8),s),this.process(n,0);let a=zR(e),c=this.outputLen;if(c%4)throw new Error("_sha2: outputLen must be aligned to 32bit");let l=c/4,u=this.get();if(l>u.length)throw new Error("_sha2: outputLen bigger than state");for(let d=0;d<l;d++)a.setUint32(4*d,u[d],s)}digest(){let{buffer:e,outputLen:r}=this;this.digestInto(e);let n=e.slice(0,r);return this.destroy(),n}_cloneInto(e){e||=new this.constructor,e.set(...this.get());let{blockLen:r,buffer:n,length:i,finished:s,destroyed:o,pos:a}=this;return e.destroyed=o,e.finished=s,e.length=i,e.pos=a,i%r&&e.buffer.set(n),e}clone(){return this._cloneInto()}},np=Uint32Array.from([1779033703,3144134277,1013904242,2773480762,1359893119,2600822924,528734635,1541459225])});var hrt,kf,xH,IH,Bde,Hde=I(()=>{zde();_0();hrt=Uint32Array.from([1116352408,1899447441,3049323471,3921009573,961987163,1508970993,2453635748,2870763221,3624381080,310598401,607225278,1426881987,1925078388,2162078206,2614888103,3248222580,3835390401,4022224774,264347078,604807628,770255983,1249150122,1555081692,1996064986,2554220882,2821834349,2952996808,3210313671,3336571891,3584528711,113926993,338241895,666307205,773529912,1294757372,1396182291,1695183700,1986661051,2177026350,2456956037,2730485921,2820302411,3259730800,3345764771,3516065817,3600352804,4094571909,275423344,430227734,506948616,659060556,883997877,958139571,1322822218,1537002063,1747873779,1955562222,2024104815,2227730452,2361852424,2428436474,2756734187,3204031479,3329325298]),kf=new Uint32Array(64),xH=class extends HR{constructor(e){super(64,e,8,!1)}get(){let{A:e,B:r,C:n,D:i,E:s,F:o,G:a,H:c}=this;return[e,r,n,i,s,o,a,c]}set(e,r,n,i,s,o,a,c){this.A=e|0,this.B=r|0,this.C=n|0,this.D=i|0,this.E=s|0,this.F=o|0,this.G=a|0,this.H=c|0}process(e,r){for(let d=0;d<16;d++,r+=4)kf[d]=e.getUint32(r,!1);for(let d=16;d<64;d++){let p=kf[d-15],f=kf[d-2],m=Pl(p,7)^Pl(p,18)^p>>>3,h=Pl(f,17)^Pl(f,19)^f>>>10;kf[d]=h+kf[d-7]+m+kf[d-16]|0}let{A:n,B:i,C:s,D:o,E:a,F:c,G:l,H:u}=this;for(let d=0;d<64;d++){let p=Pl(a,6)^Pl(a,11)^Pl(a,25),f=u+p+qde(a,c,l)+hrt[d]+kf[d]|0,h=(Pl(n,2)^Pl(n,13)^Pl(n,22))+Fde(n,i,s)|0;u=l,l=c,c=a,a=o+f|0,o=s,s=i,i=n,n=f+h|0}n=n+this.A|0,i=i+this.B|0,s=s+this.C|0,o=o+this.D|0,a=a+this.E|0,c=c+this.F|0,l=l+this.G|0,u=u+this.H|0,this.set(n,i,s,o,a,c,l,u)}roundClean(){rp(kf)}destroy(){this.destroyed=!0,this.set(0,0,0,0,0,0,0,0),rp(this.buffer)}},IH=class extends xH{A=np[0]|0;B=np[1]|0;C=np[2]|0;D=np[3]|0;E=np[4]|0;F=np[5]|0;G=np[6]|0;H=np[7]|0;constructor(){super(32)}},Bde=Dde(()=>new IH,Mde(1))});function fi(...t){let e=t.reduce((i,{length:s})=>i+s,0),r=new Uint8Array(e),n=0;for(let i of t)r.set(i,n),n+=i.length;return r}function AH(t,e,r){if(e<0||e>=WR)throw new RangeError(`value must be >= 0 and <= ${WR-1}. Received ${e}`);t.set([e>>>24,e>>>16,e>>>8,e&255],r)}function OH(t){let e=Math.floor(t/WR),r=t%WR,n=new Uint8Array(8);return AH(n,e,0),AH(n,r,4),n}function $R(t){let e=new Uint8Array(4);return AH(e,t),e}function Bn(t){let e=new Uint8Array(t.length);for(let r=0;r<t.length;r++){let n=t.charCodeAt(r);if(n>127)throw new TypeError("non-ASCII string encountered in encode()");e[r]=n}return e}var qh,_s,WR,Vs=I(()=>{qh=new TextEncoder,_s=new TextDecoder,WR=2**32});function Wde(t){if(Uint8Array.prototype.toBase64)return t.toBase64();let e=32768,r=[];for(let n=0;n<t.length;n+=e)r.push(String.fromCharCode.apply(null,t.subarray(n,n+e)));return btoa(r.join(""))}function $de(t){if(Uint8Array.fromBase64)return Uint8Array.fromBase64(t);let e=atob(t),r=new Uint8Array(e.length);for(let n=0;n<e.length;n++)r[n]=e.charCodeAt(n);return r}var Gde=I(()=>{});var E0={};ui(E0,{decode:()=>_o,encode:()=>bn});function _o(t){if(Uint8Array.fromBase64)return Uint8Array.fromBase64(typeof t=="string"?t:_s.decode(t),{alphabet:"base64url"});let e=t;e instanceof Uint8Array&&(e=_s.decode(e)),e=e.replace(/-/g,"+").replace(/_/g,"/");try{return $de(e)}catch{throw new TypeError("The input to be decoded is not correctly encoded.")}}function bn(t){let e=t;return typeof e=="string"&&(e=qh.encode(e)),Uint8Array.prototype.toBase64?e.toBase64({alphabet:"base64url",omitPadding:!0}):Wde(e).replace(/=/g,"").replace(/\+/g,"-").replace(/\//g,"_")}var Ys=I(()=>{Vs();Gde()});function grt(t){return parseInt(t.name.slice(4),10)}function GR(t,e){if(grt(t.hash)!==e)throw Eo(`SHA-${e}`,"algorithm.hash")}function yrt(t){switch(t){case"ES256":return"P-256";case"ES384":return"P-384";case"ES512":return"P-521";default:throw new Error("unreachable")}}function Vde(t,e){if(e&&!t.usages.includes(e))throw new TypeError(`CryptoKey does not support this operation, its usages must include ${e}.`)}function Yde(t,e,r){switch(e){case"HS256":case"HS384":case"HS512":{if(!Hu(t.algorithm,"HMAC"))throw Eo("HMAC");GR(t.algorithm,parseInt(e.slice(2),10));break}case"RS256":case"RS384":case"RS512":{if(!Hu(t.algorithm,"RSASSA-PKCS1-v1_5"))throw Eo("RSASSA-PKCS1-v1_5");GR(t.algorithm,parseInt(e.slice(2),10));break}case"PS256":case"PS384":case"PS512":{if(!Hu(t.algorithm,"RSA-PSS"))throw Eo("RSA-PSS");GR(t.algorithm,parseInt(e.slice(2),10));break}case"Ed25519":case"EdDSA":{if(!Hu(t.algorithm,"Ed25519"))throw Eo("Ed25519");break}case"ML-DSA-44":case"ML-DSA-65":case"ML-DSA-87":{if(!Hu(t.algorithm,e))throw Eo(e);break}case"ES256":case"ES384":case"ES512":{if(!Hu(t.algorithm,"ECDSA"))throw Eo("ECDSA");let n=yrt(e);if(t.algorithm.namedCurve!==n)throw Eo(n,"algorithm.namedCurve");break}default:throw new TypeError("CryptoKey does not support this operation")}Vde(t,r)}function $a(t,e,r){switch(e){case"A128GCM":case"A192GCM":case"A256GCM":{if(!Hu(t.algorithm,"AES-GCM"))throw Eo("AES-GCM");let n=parseInt(e.slice(1,4),10);if(t.algorithm.length!==n)throw Eo(n,"algorithm.length");break}case"A128KW":case"A192KW":case"A256KW":{if(!Hu(t.algorithm,"AES-KW"))throw Eo("AES-KW");let n=parseInt(e.slice(1,4),10);if(t.algorithm.length!==n)throw Eo(n,"algorithm.length");break}case"ECDH":{switch(t.algorithm.name){case"ECDH":case"X25519":break;default:throw Eo("ECDH or X25519")}break}case"PBES2-HS256+A128KW":case"PBES2-HS384+A192KW":case"PBES2-HS512+A256KW":if(!Hu(t.algorithm,"PBKDF2"))throw Eo("PBKDF2");break;case"RSA-OAEP":case"RSA-OAEP-256":case"RSA-OAEP-384":case"RSA-OAEP-512":{if(!Hu(t.algorithm,"RSA-OAEP"))throw Eo("RSA-OAEP");GR(t.algorithm,parseInt(e.slice(9),10)||1);break}default:throw new TypeError("CryptoKey does not support this operation")}Vde(t,r)}var Eo,Hu,Fh=I(()=>{Eo=(t,e="algorithm.name")=>new TypeError(`CryptoKey does not support this operation, its ${e} must be ${t}`),Hu=(t,e)=>t.name===e});function Jde(t,e,...r){if(r=r.filter(Boolean),r.length>2){let n=r.pop();t+=`one of type ${r.join(", ")}, or ${n}.`}else r.length===2?t+=`one of type ${r[0]} or ${r[1]}.`:t+=`of type ${r[0]}.`;return e==null?t+=` Received ${e}`:typeof e=="function"&&e.name?t+=` Received function ${e.name}`:typeof e=="object"&&e!=null&&e.constructor?.name&&(t+=` Received an instance of ${e.constructor.name}`),t}var Wu,kH,rv=I(()=>{Wu=(t,...e)=>Jde("Key must be ",t,...e),kH=(t,e,...r)=>Jde(`Key for the ${t} algorithm must be `,e,...r)});var Si,Es,zh,Bh,Pt,nv,Me,zr,Js,VR,S0,iv,YR,JR,ZR,cn=I(()=>{Si=class extends Error{static code="ERR_JOSE_GENERIC";code="ERR_JOSE_GENERIC";constructor(e,r){super(e,r),this.name=this.constructor.name,Error.captureStackTrace?.(this,this.constructor)}},Es=class extends Si{static code="ERR_JWT_CLAIM_VALIDATION_FAILED";code="ERR_JWT_CLAIM_VALIDATION_FAILED";claim;reason;payload;constructor(e,r,n="unspecified",i="unspecified"){super(e,{cause:{claim:n,reason:i,payload:r}}),this.claim=n,this.reason=i,this.payload=r}},zh=class extends Si{static code="ERR_JWT_EXPIRED";code="ERR_JWT_EXPIRED";claim;reason;payload;constructor(e,r,n="unspecified",i="unspecified"){super(e,{cause:{claim:n,reason:i,payload:r}}),this.claim=n,this.reason=i,this.payload=r}},Bh=class extends Si{static code="ERR_JOSE_ALG_NOT_ALLOWED";code="ERR_JOSE_ALG_NOT_ALLOWED"},Pt=class extends Si{static code="ERR_JOSE_NOT_SUPPORTED";code="ERR_JOSE_NOT_SUPPORTED"},nv=class extends Si{static code="ERR_JWE_DECRYPTION_FAILED";code="ERR_JWE_DECRYPTION_FAILED";constructor(e="decryption operation failed",r){super(e,r)}},Me=class extends Si{static code="ERR_JWE_INVALID";code="ERR_JWE_INVALID"},zr=class extends Si{static code="ERR_JWS_INVALID";code="ERR_JWS_INVALID"},Js=class extends Si{static code="ERR_JWT_INVALID";code="ERR_JWT_INVALID"},VR=class extends Si{static code="ERR_JWK_INVALID";code="ERR_JWK_INVALID"},S0=class extends Si{static code="ERR_JWKS_INVALID";code="ERR_JWKS_INVALID"},iv=class extends Si{static code="ERR_JWKS_NO_MATCHING_KEY";code="ERR_JWKS_NO_MATCHING_KEY";constructor(e="no applicable key found in the JSON Web Key Set",r){super(e,r)}},YR=class extends Si{[Symbol.asyncIterator];static code="ERR_JWKS_MULTIPLE_MATCHING_KEYS";code="ERR_JWKS_MULTIPLE_MATCHING_KEYS";constructor(e="multiple matching keys found in the JSON Web Key Set",r){super(e,r)}},JR=class extends Si{static code="ERR_JWKS_TIMEOUT";code="ERR_JWKS_TIMEOUT";constructor(e="request timed out",r){super(e,r)}},ZR=class extends Si{static code="ERR_JWS_SIGNATURE_VERIFICATION_FAILED";code="ERR_JWS_SIGNATURE_VERIFICATION_FAILED";constructor(e="signature verification failed",r){super(e,r)}}});function sv(t){if(!ip(t))throw new Error("CryptoKey instance expected")}var ip,w0,T0,Hh=I(()=>{ip=t=>{if(t?.[Symbol.toStringTag]==="CryptoKey")return!0;try{return t instanceof CryptoKey}catch{return!1}},w0=t=>t?.[Symbol.toStringTag]==="KeyObject",T0=t=>ip(t)||w0(t)});function QR(t){switch(t){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 Pt(`Unsupported JWE Algorithm: ${t}`)}}function XR(t,e){let r=t.byteLength<<3;if(r!==e)throw new Me(`Invalid Content Encryption Key length. Expected ${e} bits, got ${r} bits`)}function Zde(t){switch(t){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 Pt(`Unsupported JWE Algorithm: ${t}`)}}function Xde(t,e){if(e.length<<3!==Zde(t))throw new Me("Invalid Initialization Vector length")}async function Qde(t,e,r){if(!(e instanceof Uint8Array))throw new TypeError(Wu(e,"Uint8Array"));let n=parseInt(t.slice(1,4),10),i=await crypto.subtle.importKey("raw",e.subarray(n>>3),"AES-CBC",!1,[r]),s=await crypto.subtle.importKey("raw",e.subarray(0,n>>3),{hash:`SHA-${n<<1}`,name:"HMAC"},!1,["sign"]);return{encKey:i,macKey:s,keySize:n}}async function epe(t,e,r){return new Uint8Array((await crypto.subtle.sign("HMAC",t,e)).slice(0,r>>3))}async function vrt(t,e,r,n,i){let{encKey:s,macKey:o,keySize:a}=await Qde(t,r,"encrypt"),c=new Uint8Array(await crypto.subtle.encrypt({iv:n,name:"AES-CBC"},s,e)),l=fi(i,n,c,OH(i.length<<3)),u=await epe(o,l,a);return{ciphertext:c,tag:u,iv:n}}async function _rt(t,e){if(!(t instanceof Uint8Array))throw new TypeError("First argument must be a buffer");if(!(e instanceof Uint8Array))throw new TypeError("Second argument must be a buffer");let r={name:"HMAC",hash:"SHA-256"},n=await crypto.subtle.generateKey(r,!1,["sign"]),i=new Uint8Array(await crypto.subtle.sign(r,n,t)),s=new Uint8Array(await crypto.subtle.sign(r,n,e)),o=0,a=-1;for(;++a<32;)o|=i[a]^s[a];return o===0}async function Ert(t,e,r,n,i,s){let{encKey:o,macKey:a,keySize:c}=await Qde(t,e,"decrypt"),l=fi(s,n,r,OH(s.length<<3)),u=await epe(a,l,c),d;try{d=await _rt(i,u)}catch{}if(!d)throw new nv;let p;try{p=new Uint8Array(await crypto.subtle.decrypt({iv:n,name:"AES-CBC"},o,r))}catch{}if(!p)throw new nv;return p}async function Srt(t,e,r,n,i){let s;r instanceof Uint8Array?s=await crypto.subtle.importKey("raw",r,"AES-GCM",!1,["encrypt"]):($a(r,t,"encrypt"),s=r);let o=new Uint8Array(await crypto.subtle.encrypt({additionalData:i,iv:n,name:"AES-GCM",tagLength:128},s,e)),a=o.slice(-16);return{ciphertext:o.slice(0,-16),tag:a,iv:n}}async function wrt(t,e,r,n,i,s){let o;e instanceof Uint8Array?o=await crypto.subtle.importKey("raw",e,"AES-GCM",!1,["decrypt"]):($a(e,t,"decrypt"),o=e);try{return new Uint8Array(await crypto.subtle.decrypt({additionalData:s,iv:n,name:"AES-GCM",tagLength:128},o,fi(r,i)))}catch{throw new nv}}async function eC(t,e,r,n,i){if(!ip(r)&&!(r instanceof Uint8Array))throw new TypeError(Wu(r,"CryptoKey","KeyObject","Uint8Array","JSON Web Key"));switch(n?Xde(t,n):n=brt(t),t){case"A128CBC-HS256":case"A192CBC-HS384":case"A256CBC-HS512":return r instanceof Uint8Array&&XR(r,parseInt(t.slice(-3),10)),vrt(t,e,r,n,i);case"A128GCM":case"A192GCM":case"A256GCM":return r instanceof Uint8Array&&XR(r,parseInt(t.slice(1,4),10)),Srt(t,e,r,n,i);default:throw new Pt(tpe)}}async function tC(t,e,r,n,i,s){if(!ip(e)&&!(e instanceof Uint8Array))throw new TypeError(Wu(e,"CryptoKey","KeyObject","Uint8Array","JSON Web Key"));if(!n)throw new Me("JWE Initialization Vector missing");if(!i)throw new Me("JWE Authentication Tag missing");switch(Xde(t,n),t){case"A128CBC-HS256":case"A192CBC-HS384":case"A256CBC-HS512":return e instanceof Uint8Array&&XR(e,parseInt(t.slice(-3),10)),Ert(t,e,r,n,i,s);case"A128GCM":case"A192GCM":case"A256GCM":return e instanceof Uint8Array&&XR(e,parseInt(t.slice(1,4),10)),wrt(t,e,r,n,i,s);default:throw new Pt(tpe)}}var Rf,brt,tpe,ov=I(()=>{Vs();Fh();rv();cn();Hh();Rf=t=>crypto.getRandomValues(new Uint8Array(QR(t)>>3));brt=t=>crypto.getRandomValues(new Uint8Array(Zde(t)>>3));tpe="Unsupported JWE Content Encryption Algorithm"});function So(t,e){if(t)throw new TypeError(`${e} can only be called once`)}function wo(t,e,r){try{return _o(t)}catch{throw new r(`Failed to base64url decode the ${e}`)}}async function rC(t,e){let r=`SHA-${t.slice(-3)}`;return new Uint8Array(await crypto.subtle.digest(r,e))}var rpe,sp=I(()=>{Ys();rpe=Symbol()});function vn(t){if(!Trt(t)||Object.prototype.toString.call(t)!=="[object Object]")return!1;if(Object.getPrototypeOf(t)===null)return!0;let e=t;for(;Object.getPrototypeOf(e)!==null;)e=Object.getPrototypeOf(e);return Object.getPrototypeOf(t)===e}function Cf(...t){let e=t.filter(Boolean);if(e.length===0||e.length===1)return!0;let r;for(let n of e){let i=Object.keys(n);if(!r||r.size===0){r=new Set(i);continue}for(let s of i){if(r.has(s))return!1;r.add(s)}}return!0}var Trt,Wh,npe,ipe,spe,Ss=I(()=>{Trt=t=>typeof t=="object"&&t!==null;Wh=t=>vn(t)&&typeof t.kty=="string",npe=t=>t.kty!=="oct"&&(t.kty==="AKP"&&typeof t.priv=="string"||typeof t.d=="string"),ipe=t=>t.kty!=="oct"&&t.d===void 0&&t.priv===void 0,spe=t=>t.kty==="oct"&&typeof t.k=="string"});function ope(t,e){if(t.algorithm.length!==parseInt(e.slice(1,4),10))throw new TypeError(`Invalid key size for alg: ${e}`)}function ape(t,e,r){return t instanceof Uint8Array?crypto.subtle.importKey("raw",t,"AES-KW",!0,[r]):($a(t,e,r),t)}async function x0(t,e,r){let n=await ape(e,t,"wrapKey");ope(n,t);let i=await crypto.subtle.importKey("raw",r,{hash:"SHA-256",name:"HMAC"},!0,["sign"]);return new Uint8Array(await crypto.subtle.wrapKey("raw",i,n,"AES-KW"))}async function I0(t,e,r){let n=await ape(e,t,"unwrapKey");ope(n,t);let i=await crypto.subtle.unwrapKey("raw",r,n,"AES-KW",{hash:"SHA-256",name:"HMAC"},!0,["sign"]);return new Uint8Array(await crypto.subtle.exportKey("raw",i))}var RH=I(()=>{Fh()});function CH(t){return fi($R(t.length),t)}async function Irt(t,e,r){let n=e>>3,i=32,s=Math.ceil(n/i),o=new Uint8Array(s*i);for(let a=1;a<=s;a++){let c=new Uint8Array(4+t.length+r.length);c.set($R(a),0),c.set(t,4),c.set(r,4+t.length);let l=await rC("sha256",c);o.set(l,(a-1)*i)}return o.slice(0,n)}async function NH(t,e,r,n,i=new Uint8Array,s=new Uint8Array){$a(t,"ECDH"),$a(e,"ECDH","deriveBits");let o=CH(Bn(r)),a=CH(i),c=CH(s),l=$R(n),u=new Uint8Array,d=fi(o,a,c,l,u),p=new Uint8Array(await crypto.subtle.deriveBits({name:t.algorithm.name,public:t},e,Art(t)));return Irt(p,n,d)}function Art(t){return t.algorithm.name==="X25519"?256:Math.ceil(parseInt(t.algorithm.namedCurve.slice(-3),10)/8)<<3}function PH(t){switch(t.algorithm.namedCurve){case"P-256":case"P-384":case"P-521":return!0;default:return t.algorithm.name==="X25519"}}var lpe=I(()=>{Vs();Fh();sp()});function krt(t,e){return t instanceof Uint8Array?crypto.subtle.importKey("raw",t,"PBKDF2",!1,["deriveBits"]):($a(t,e,"deriveBits"),t)}async function upe(t,e,r,n){if(!(t instanceof Uint8Array)||t.length<8)throw new Me("PBES2 Salt Input must be 8 or more octets");if(!Number.isSafeInteger(r)||Math.sign(r)!==1)throw new Me("PBES2 Count Input must be a positive integer");let i=Rrt(e,t),s=parseInt(e.slice(13,16),10),o={hash:`SHA-${e.slice(8,11)}`,iterations:r,name:"PBKDF2",salt:i},a=await krt(n,e);return new Uint8Array(await crypto.subtle.deriveBits(o,a,s))}async function dpe(t,e,r,n=2048,i=crypto.getRandomValues(new Uint8Array(16))){let s=await upe(i,t,n,e);return{encryptedKey:await x0(t.slice(-6),s,r),p2c:n,p2s:bn(i)}}async function ppe(t,e,r,n,i){let s=await upe(i,t,n,e);return I0(t.slice(-6),s,r)}var Rrt,fpe=I(()=>{Ys();RH();Fh();Vs();cn();Rrt=(t,e)=>fi(Bn(t),Uint8Array.of(0),e)});function A0(t,e){if(t.startsWith("RS")||t.startsWith("PS")){let{modulusLength:r}=e.algorithm;if(typeof r!="number"||r<2048)throw new TypeError(`${t} requires key modulusLength to be 2048 bits or larger`)}}function mpe(t,e){let r=`SHA-${t.slice(-3)}`;switch(t){case"HS256":case"HS384":case"HS512":return{hash:r,name:"HMAC"};case"PS256":case"PS384":case"PS512":return{hash:r,name:"RSA-PSS",saltLength:parseInt(t.slice(-3),10)>>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:e.namedCurve};case"Ed25519":case"EdDSA":return{name:"Ed25519"};case"ML-DSA-44":case"ML-DSA-65":case"ML-DSA-87":return{name:t};default:throw new Pt(`alg ${t} is not supported either by JOSE or your javascript runtime`)}}async function hpe(t,e,r){if(e instanceof Uint8Array){if(!t.startsWith("HS"))throw new TypeError(Wu(e,"CryptoKey","KeyObject","JSON Web Key"));return crypto.subtle.importKey("raw",e,{hash:`SHA-${t.slice(-3)}`,name:"HMAC"},!1,[r])}return Yde(e,t,r),e}async function gpe(t,e,r){let n=await hpe(t,e,"sign");A0(t,n);let i=await crypto.subtle.sign(mpe(t,n.algorithm),n,r);return new Uint8Array(i)}async function ype(t,e,r,n){let i=await hpe(t,e,"verify");A0(t,i);let s=mpe(t,i.algorithm);try{return await crypto.subtle.verify(s,i,r,n)}catch{return!1}}var nC=I(()=>{cn();Fh();rv()});async function vpe(t,e,r){return $a(e,t,"encrypt"),A0(t,e),new Uint8Array(await crypto.subtle.encrypt(bpe(t),e,r))}async function _pe(t,e,r){return $a(e,t,"decrypt"),A0(t,e),new Uint8Array(await crypto.subtle.decrypt(bpe(t),e,r))}var bpe,Epe=I(()=>{Fh();nC();cn();bpe=t=>{switch(t){case"RSA-OAEP":case"RSA-OAEP-256":case"RSA-OAEP-384":case"RSA-OAEP-512":return"RSA-OAEP";default:throw new Pt(`alg ${t} is not supported either by JOSE or your javascript runtime`)}}});function Prt(t){let e,r;switch(t.kty){case"AKP":{switch(t.alg){case"ML-DSA-44":case"ML-DSA-65":case"ML-DSA-87":e={name:t.alg},r=t.priv?["sign"]:["verify"];break;default:throw new Pt(iC)}break}case"RSA":{switch(t.alg){case"PS256":case"PS384":case"PS512":e={name:"RSA-PSS",hash:`SHA-${t.alg.slice(-3)}`},r=t.d?["sign"]:["verify"];break;case"RS256":case"RS384":case"RS512":e={name:"RSASSA-PKCS1-v1_5",hash:`SHA-${t.alg.slice(-3)}`},r=t.d?["sign"]:["verify"];break;case"RSA-OAEP":case"RSA-OAEP-256":case"RSA-OAEP-384":case"RSA-OAEP-512":e={name:"RSA-OAEP",hash:`SHA-${parseInt(t.alg.slice(-3),10)||1}`},r=t.d?["decrypt","unwrapKey"]:["encrypt","wrapKey"];break;default:throw new Pt(iC)}break}case"EC":{switch(t.alg){case"ES256":case"ES384":case"ES512":e={name:"ECDSA",namedCurve:{ES256:"P-256",ES384:"P-384",ES512:"P-521"}[t.alg]},r=t.d?["sign"]:["verify"];break;case"ECDH-ES":case"ECDH-ES+A128KW":case"ECDH-ES+A192KW":case"ECDH-ES+A256KW":e={name:"ECDH",namedCurve:t.crv},r=t.d?["deriveBits"]:[];break;default:throw new Pt(iC)}break}case"OKP":{switch(t.alg){case"Ed25519":case"EdDSA":e={name:"Ed25519"},r=t.d?["sign"]:["verify"];break;case"ECDH-ES":case"ECDH-ES+A128KW":case"ECDH-ES+A192KW":case"ECDH-ES+A256KW":e={name:t.crv},r=t.d?["deriveBits"]:[];break;default:throw new Pt(iC)}break}default:throw new Pt('Invalid or unsupported JWK "kty" (Key Type) Parameter value')}return{algorithm:e,keyUsages:r}}async function av(t){if(!t.alg)throw new TypeError('"alg" argument is required when "jwk.alg" is not present');let{algorithm:e,keyUsages:r}=Prt(t),n={...t};return n.kty!=="AKP"&&delete n.alg,delete n.use,crypto.subtle.importKey("jwk",n,e,t.ext??!(t.d||t.priv),t.key_ops??r)}var iC,DH=I(()=>{cn();iC='Invalid or unsupported JWK "alg" (Algorithm) Parameter value'});async function $u(t,e){if(t instanceof Uint8Array||ip(t))return t;if(w0(t)){if(t.type==="secret")return t.export();if("toCryptoKey"in t&&typeof t.toCryptoKey=="function")try{return Drt(t,e)}catch(n){if(n instanceof TypeError)throw n}let r=t.export({format:"jwk"});return Spe(t,r,e)}if(Wh(t))return t.k?_o(t.k):Spe(t,t,e,!0);throw new Error("unreachable")}var cv,lv,Spe,Drt,uv=I(()=>{Ss();Ys();DH();Hh();cv="given KeyObject instance cannot be used for this algorithm",Spe=async(t,e,r,n=!1)=>{lv||=new WeakMap;let i=lv.get(t);if(i?.[r])return i[r];let s=await av({...e,alg:r});return n&&Object.freeze(t),i?i[r]=s:lv.set(t,{[r]:s}),s},Drt=(t,e)=>{lv||=new WeakMap;let r=lv.get(t);if(r?.[e])return r[e];let n=t.type==="public",i=!!n,s;if(t.asymmetricKeyType==="x25519"){switch(e){case"ECDH-ES":case"ECDH-ES+A128KW":case"ECDH-ES+A192KW":case"ECDH-ES+A256KW":break;default:throw new TypeError(cv)}s=t.toCryptoKey(t.asymmetricKeyType,i,n?[]:["deriveBits"])}if(t.asymmetricKeyType==="ed25519"){if(e!=="EdDSA"&&e!=="Ed25519")throw new TypeError(cv);s=t.toCryptoKey(t.asymmetricKeyType,i,[n?"verify":"sign"])}switch(t.asymmetricKeyType){case"ml-dsa-44":case"ml-dsa-65":case"ml-dsa-87":{if(e!==t.asymmetricKeyType.toUpperCase())throw new TypeError(cv);s=t.toCryptoKey(t.asymmetricKeyType,i,[n?"verify":"sign"])}}if(t.asymmetricKeyType==="rsa"){let o;switch(e){case"RSA-OAEP":o="SHA-1";break;case"RS256":case"PS256":case"RSA-OAEP-256":o="SHA-256";break;case"RS384":case"PS384":case"RSA-OAEP-384":o="SHA-384";break;case"RS512":case"PS512":case"RSA-OAEP-512":o="SHA-512";break;default:throw new TypeError(cv)}if(e.startsWith("RSA-OAEP"))return t.toCryptoKey({name:"RSA-OAEP",hash:o},i,n?["encrypt"]:["decrypt"]);s=t.toCryptoKey({name:e.startsWith("PS")?"RSA-PSS":"RSASSA-PKCS1-v1_5",hash:o},i,[n?"verify":"sign"])}if(t.asymmetricKeyType==="ec"){let a=new Map([["prime256v1","P-256"],["secp384r1","P-384"],["secp521r1","P-521"]]).get(t.asymmetricKeyDetails?.namedCurve);if(!a)throw new TypeError(cv);let c={ES256:"P-256",ES384:"P-384",ES512:"P-521"};c[e]&&a===c[e]&&(s=t.toCryptoKey({name:"ECDSA",namedCurve:a},i,[n?"verify":"sign"])),e.startsWith("ECDH-ES")&&(s=t.toCryptoKey({name:"ECDH",namedCurve:a},i,n?[]:["deriveBits"]))}if(!s)throw new TypeError(cv);return r?r[e]=s:lv.set(t,{[e]:s}),s}});async function Ga(t,e,r){if(!vn(t))throw new TypeError("JWK must be an object");let n;switch(e??=t.alg,n??=r?.extractable??t.ext,t.kty){case"oct":if(typeof t.k!="string"||!t.k)throw new TypeError('missing "k" (Key Value) Parameter value');return _o(t.k);case"RSA":if("oth"in t&&t.oth!==void 0)throw new Pt('RSA JWK "oth" (Other Primes Info) Parameter value is not supported');return av({...t,alg:e,ext:n});case"AKP":{if(typeof t.alg!="string"||!t.alg)throw new TypeError('missing "alg" (Algorithm) Parameter value');if(e!==void 0&&e!==t.alg)throw new TypeError("JWK alg and alg option value mismatch");return av({...t,ext:n})}case"EC":case"OKP":return av({...t,alg:e,ext:n});default:throw new Pt('Unsupported "kty" (Key Type) Parameter value')}}var sC=I(()=>{Ys();DH();cn();Ss()});async function wpe(t){if(w0(t))if(t.type==="secret")t=t.export();else return t.export({format:"jwk"});if(t instanceof Uint8Array)return{kty:"oct",k:bn(t)};if(!ip(t))throw new TypeError(Wu(t,"CryptoKey","KeyObject","Uint8Array"));if(!t.extractable)throw new TypeError("non-extractable CryptoKey cannot be exported as a JWK");let{ext:e,key_ops:r,alg:n,use:i,...s}=await crypto.subtle.exportKey("jwk",t);return s.kty==="AKP"&&(s.alg=n),s}var Tpe=I(()=>{rv();Ys();Hh()});async function oC(t){return wpe(t)}var MH=I(()=>{Tpe()});async function xpe(t,e,r,n){let i=t.slice(0,7),s=await eC(i,r,e,n,new Uint8Array);return{encryptedKey:s.ciphertext,iv:bn(s.iv),tag:bn(s.tag)}}async function Ipe(t,e,r,n,i){let s=t.slice(0,7);return tC(s,e,r,n,i,new Uint8Array)}var Ape=I(()=>{ov();Ys()});function O0(t){if(t===void 0)throw new Me("JWE Encrypted Key missing")}async function kpe(t,e,r,n,i){switch(t){case"dir":{if(r!==void 0)throw new Me("Encountered unexpected JWE Encrypted Key");return e}case"ECDH-ES":if(r!==void 0)throw new Me("Encountered unexpected JWE Encrypted Key");case"ECDH-ES+A128KW":case"ECDH-ES+A192KW":case"ECDH-ES+A256KW":{if(!vn(n.epk))throw new Me('JOSE Header "epk" (Ephemeral Public Key) missing or invalid');if(sv(e),!PH(e))throw new Pt("ECDH with the provided key is not allowed or not supported by your javascript runtime");let s=await Ga(n.epk,t);sv(s);let o,a;if(n.apu!==void 0){if(typeof n.apu!="string")throw new Me('JOSE Header "apu" (Agreement PartyUInfo) invalid');o=wo(n.apu,"apu",Me)}if(n.apv!==void 0){if(typeof n.apv!="string")throw new Me('JOSE Header "apv" (Agreement PartyVInfo) invalid');a=wo(n.apv,"apv",Me)}let c=await NH(s,e,t==="ECDH-ES"?n.enc:t,t==="ECDH-ES"?QR(n.enc):parseInt(t.slice(-5,-2),10),o,a);return t==="ECDH-ES"?c:(O0(r),I0(t.slice(-6),c,r))}case"RSA-OAEP":case"RSA-OAEP-256":case"RSA-OAEP-384":case"RSA-OAEP-512":return O0(r),sv(e),_pe(t,e,r);case"PBES2-HS256+A128KW":case"PBES2-HS384+A192KW":case"PBES2-HS512+A256KW":{if(O0(r),typeof n.p2c!="number")throw new Me('JOSE Header "p2c" (PBES2 Count) missing or invalid');let s=i?.maxPBES2Count||1e4;if(n.p2c>s)throw new Me('JOSE Header "p2c" (PBES2 Count) out is of acceptable bounds');if(typeof n.p2s!="string")throw new Me('JOSE Header "p2s" (PBES2 Salt) missing or invalid');let o;return o=wo(n.p2s,"p2s",Me),ppe(t,e,r,n.p2c,o)}case"A128KW":case"A192KW":case"A256KW":return O0(r),I0(t,e,r);case"A128GCMKW":case"A192GCMKW":case"A256GCMKW":{if(O0(r),typeof n.iv!="string")throw new Me('JOSE Header "iv" (Initialization Vector) missing or invalid');if(typeof n.tag!="string")throw new Me('JOSE Header "tag" (Authentication Tag) missing or invalid');let s;s=wo(n.iv,"iv",Me);let o;return o=wo(n.tag,"tag",Me),Ipe(t,e,r,s,o)}default:throw new Pt(Ope)}}async function Rpe(t,e,r,n,i={}){let s,o,a;switch(t){case"dir":{a=r;break}case"ECDH-ES":case"ECDH-ES+A128KW":case"ECDH-ES+A192KW":case"ECDH-ES+A256KW":{if(sv(r),!PH(r))throw new Pt("ECDH with the provided key is not allowed or not supported by your javascript runtime");let{apu:c,apv:l}=i,u;i.epk?u=await $u(i.epk,t):u=(await crypto.subtle.generateKey(r.algorithm,!0,["deriveBits"])).privateKey;let{x:d,y:p,crv:f,kty:m}=await oC(u),h=await NH(r,u,t==="ECDH-ES"?e:t,t==="ECDH-ES"?QR(e):parseInt(t.slice(-5,-2),10),c,l);if(o={epk:{x:d,crv:f,kty:m}},m==="EC"&&(o.epk.y=p),c&&(o.apu=bn(c)),l&&(o.apv=bn(l)),t==="ECDH-ES"){a=h;break}a=n||Rf(e);let y=t.slice(-6);s=await x0(y,h,a);break}case"RSA-OAEP":case"RSA-OAEP-256":case"RSA-OAEP-384":case"RSA-OAEP-512":{a=n||Rf(e),sv(r),s=await vpe(t,r,a);break}case"PBES2-HS256+A128KW":case"PBES2-HS384+A192KW":case"PBES2-HS512+A256KW":{a=n||Rf(e);let{p2c:c,p2s:l}=i;({encryptedKey:s,...o}=await dpe(t,r,a,c,l));break}case"A128KW":case"A192KW":case"A256KW":{a=n||Rf(e),s=await x0(t,r,a);break}case"A128GCMKW":case"A192GCMKW":case"A256GCMKW":{a=n||Rf(e);let{iv:c}=i;({encryptedKey:s,...o}=await xpe(t,r,a,c));break}default:throw new Pt(Ope)}return{cek:a,encryptedKey:s,parameters:o}}var Ope,LH=I(()=>{RH();lpe();fpe();Epe();Ys();uv();cn();sp();ov();sC();MH();Ss();Ape();Hh();Ope='Invalid or unsupported "alg" (JWE Algorithm) header value'});function Nf(t,e,r,n,i){if(i.crit!==void 0&&n?.crit===void 0)throw new t('"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(o=>typeof o!="string"||o.length===0))throw new t('"crit" (Critical) Header Parameter MUST be an array of non-empty strings when present');let s;r!==void 0?s=new Map([...Object.entries(r),...e.entries()]):s=e;for(let o of n.crit){if(!s.has(o))throw new Pt(`Extension Header Parameter "${o}" is not recognized`);if(i[o]===void 0)throw new t(`Extension Header Parameter "${o}" is missing`);if(s.get(o)&&n[o]===void 0)throw new t(`Extension Header Parameter "${o}" MUST be integrity protected`)}return new Set(n.crit)}var k0=I(()=>{cn()});function R0(t,e){if(e!==void 0&&(!Array.isArray(e)||e.some(r=>typeof r!="string")))throw new TypeError(`"${t}" option must be an array of strings`);if(e)return new Set(e)}var jH=I(()=>{});function Pf(t,e,r){switch(t.substring(0,2)){case"A1":case"A2":case"di":case"HS":case"PB":Mrt(t,e,r);break;default:Lrt(t,e,r)}}var dv,UH,Mrt,Lrt,C0=I(()=>{rv();Hh();Ss();dv=t=>t?.[Symbol.toStringTag],UH=(t,e,r)=>{if(e.use!==void 0){let n;switch(r){case"sign":case"verify":n="sig";break;case"encrypt":case"decrypt":n="enc";break}if(e.use!==n)throw new TypeError(`Invalid key for this operation, its "use" must be "${n}" when present`)}if(e.alg!==void 0&&e.alg!==t)throw new TypeError(`Invalid key for this operation, its "alg" must be "${t}" when present`);if(Array.isArray(e.key_ops)){let n;switch(!0){case(r==="sign"||r==="verify"):case t==="dir":case t.includes("CBC-HS"):n=r;break;case t.startsWith("PBES2"):n="deriveBits";break;case/^A\d{3}(?:GCM)?(?:KW)?$/.test(t):!t.includes("GCM")&&t.endsWith("KW")?n=r==="encrypt"?"wrapKey":"unwrapKey":n=r;break;case(r==="encrypt"&&t.startsWith("RSA")):n="wrapKey";break;case r==="decrypt":n=t.startsWith("RSA")?"unwrapKey":"deriveBits";break}if(n&&e.key_ops?.includes?.(n)===!1)throw new TypeError(`Invalid key for this operation, its "key_ops" must include "${n}" when present`)}return!0},Mrt=(t,e,r)=>{if(!(e instanceof Uint8Array)){if(Wh(e)){if(spe(e)&&UH(t,e,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(!T0(e))throw new TypeError(kH(t,e,"CryptoKey","KeyObject","JSON Web Key","Uint8Array"));if(e.type!=="secret")throw new TypeError(`${dv(e)} instances for symmetric algorithms must be of type "secret"`)}},Lrt=(t,e,r)=>{if(Wh(e))switch(r){case"decrypt":case"sign":if(npe(e)&&UH(t,e,r))return;throw new TypeError("JSON Web Key for this operation must be a private JWK");case"encrypt":case"verify":if(ipe(e)&&UH(t,e,r))return;throw new TypeError("JSON Web Key for this operation must be a public JWK")}if(!T0(e))throw new TypeError(kH(t,e,"CryptoKey","KeyObject","JSON Web Key"));if(e.type==="secret")throw new TypeError(`${dv(e)} instances for asymmetric algorithms must not be of type "secret"`);if(e.type==="public")switch(r){case"sign":throw new TypeError(`${dv(e)} instances for asymmetric algorithm signing must be of type "private"`);case"decrypt":throw new TypeError(`${dv(e)} instances for asymmetric algorithm decryption must be of type "private"`)}if(e.type==="private")switch(r){case"verify":throw new TypeError(`${dv(e)} instances for asymmetric algorithm verifying must be of type "public"`);case"encrypt":throw new TypeError(`${dv(e)} instances for asymmetric algorithm encryption must be of type "public"`)}}});function Cpe(t){if(typeof globalThis[t]>"u")throw new Pt(`JWE "zip" (Compression Algorithm) Header Parameter requires the ${t} API.`)}async function Npe(t){Cpe("CompressionStream");let e=new CompressionStream("deflate-raw"),r=e.writable.getWriter();r.write(t).catch(()=>{}),r.close().catch(()=>{});let n=[],i=e.readable.getReader();for(;;){let{value:s,done:o}=await i.read();if(o)break;n.push(s)}return fi(...n)}async function Ppe(t,e){Cpe("DecompressionStream");let r=new DecompressionStream("deflate-raw"),n=r.writable.getWriter();n.write(t).catch(()=>{}),n.close().catch(()=>{});let i=[],s=0,o=r.readable.getReader();for(;;){let{value:a,done:c}=await o.read();if(c)break;if(i.push(a),s+=a.byteLength,e!==1/0&&s>e)throw new Me("Decompressed plaintext exceeded the configured limit")}return fi(...i)}var KH=I(()=>{cn();Vs()});async function Dpe(t,e,r){if(!vn(t))throw new Me("Flattened JWE must be an object");if(t.protected===void 0&&t.header===void 0&&t.unprotected===void 0)throw new Me("JOSE Header missing");if(t.iv!==void 0&&typeof t.iv!="string")throw new Me("JWE Initialization Vector incorrect type");if(typeof t.ciphertext!="string")throw new Me("JWE Ciphertext missing or incorrect type");if(t.tag!==void 0&&typeof t.tag!="string")throw new Me("JWE Authentication Tag incorrect type");if(t.protected!==void 0&&typeof t.protected!="string")throw new Me("JWE Protected Header incorrect type");if(t.encrypted_key!==void 0&&typeof t.encrypted_key!="string")throw new Me("JWE Encrypted Key incorrect type");if(t.aad!==void 0&&typeof t.aad!="string")throw new Me("JWE AAD incorrect type");if(t.header!==void 0&&!vn(t.header))throw new Me("JWE Shared Unprotected Header incorrect type");if(t.unprotected!==void 0&&!vn(t.unprotected))throw new Me("JWE Per-Recipient Unprotected Header incorrect type");let n;if(t.protected)try{let _=_o(t.protected);n=JSON.parse(_s.decode(_))}catch{throw new Me("JWE Protected Header is invalid")}if(!Cf(n,t.header,t.unprotected))throw new Me("JWE Protected, JWE Unprotected Header, and JWE Per-Recipient Unprotected Header Parameter names must be disjoint");let i={...n,...t.header,...t.unprotected};if(Nf(Me,new Map,r?.crit,n,i),i.zip!==void 0&&i.zip!=="DEF")throw new Pt('Unsupported JWE "zip" (Compression Algorithm) Header Parameter value.');if(i.zip!==void 0&&!n?.zip)throw new Me('JWE "zip" (Compression Algorithm) Header Parameter MUST be in a protected header.');let{alg:s,enc:o}=i;if(typeof s!="string"||!s)throw new Me("missing JWE Algorithm (alg) in JWE Header");if(typeof o!="string"||!o)throw new Me("missing JWE Encryption Algorithm (enc) in JWE Header");let a=r&&R0("keyManagementAlgorithms",r.keyManagementAlgorithms),c=r&&R0("contentEncryptionAlgorithms",r.contentEncryptionAlgorithms);if(a&&!a.has(s)||!a&&s.startsWith("PBES2"))throw new Bh('"alg" (Algorithm) Header Parameter value not allowed');if(c&&!c.has(o))throw new Bh('"enc" (Encryption Algorithm) Header Parameter value not allowed');let l;t.encrypted_key!==void 0&&(l=wo(t.encrypted_key,"encrypted_key",Me));let u=!1;typeof e=="function"&&(e=await e(n,t),u=!0),Pf(s==="dir"?o:s,e,"decrypt");let d=await $u(e,s),p;try{p=await kpe(s,d,l,i,r)}catch(_){if(_ instanceof TypeError||_ instanceof Me||_ instanceof Pt)throw _;p=Rf(o)}let f,m;t.iv!==void 0&&(f=wo(t.iv,"iv",Me)),t.tag!==void 0&&(m=wo(t.tag,"tag",Me));let h=t.protected!==void 0?Bn(t.protected):new Uint8Array,y;t.aad!==void 0?y=fi(h,Bn("."),Bn(t.aad)):y=h;let g=wo(t.ciphertext,"ciphertext",Me),b=await tC(o,p,g,f,m,y),v={plaintext:b};if(i.zip==="DEF"){let _=r?.maxDecompressedLength??25e4;if(_===0)throw new Pt('JWE "zip" (Compression Algorithm) Header Parameter is not supported.');if(_!==1/0&&(!Number.isSafeInteger(_)||_<1))throw new TypeError("maxDecompressedLength must be 0, a positive safe integer, or Infinity");v.plaintext=await Ppe(b,_).catch(w=>{throw w instanceof Me?w:new Me("Failed to decompress plaintext",{cause:w})})}return t.protected!==void 0&&(v.protectedHeader=n),t.aad!==void 0&&(v.additionalAuthenticatedData=wo(t.aad,"aad",Me)),t.unprotected!==void 0&&(v.sharedUnprotectedHeader=t.unprotected),t.header!==void 0&&(v.unprotectedHeader=t.header),u?{...v,key:d}:v}var Mpe=I(()=>{Ys();ov();sp();cn();Ss();Ss();LH();Vs();ov();k0();jH();uv();C0();KH()});async function Lpe(t,e,r){if(t instanceof Uint8Array&&(t=_s.decode(t)),typeof t!="string")throw new Me("Compact JWE must be a string or Uint8Array");let{0:n,1:i,2:s,3:o,4:a,length:c}=t.split(".");if(c!==5)throw new Me("Invalid Compact JWE");let l=await Dpe({ciphertext:o,iv:s||void 0,protected:n,tag:a||void 0,encrypted_key:i||void 0},e,r),u={plaintext:l.plaintext,protectedHeader:l.protectedHeader};return typeof e=="function"?{...u,key:l.key}:u}var jpe=I(()=>{Mpe();cn();Vs()});var aC,Upe=I(()=>{Ys();sp();ov();LH();cn();Ss();Vs();k0();uv();C0();KH();aC=class{#e;#t;#r;#n;#i;#p;#u;#a;constructor(e){if(!(e instanceof Uint8Array))throw new TypeError("plaintext must be an instance of Uint8Array");this.#e=e}setKeyManagementParameters(e){return So(this.#a,"setKeyManagementParameters"),this.#a=e,this}setProtectedHeader(e){return So(this.#t,"setProtectedHeader"),this.#t=e,this}setSharedUnprotectedHeader(e){return So(this.#r,"setSharedUnprotectedHeader"),this.#r=e,this}setUnprotectedHeader(e){return So(this.#n,"setUnprotectedHeader"),this.#n=e,this}setAdditionalAuthenticatedData(e){return this.#i=e,this}setContentEncryptionKey(e){return So(this.#p,"setContentEncryptionKey"),this.#p=e,this}setInitializationVector(e){return So(this.#u,"setInitializationVector"),this.#u=e,this}async encrypt(e,r){if(!this.#t&&!this.#n&&!this.#r)throw new Me("either setProtectedHeader, setUnprotectedHeader, or sharedUnprotectedHeader must be called before #encrypt()");if(!Cf(this.#t,this.#n,this.#r))throw new Me("JWE Protected, JWE Shared Unprotected and JWE Per-Recipient Header Parameter names must be disjoint");let n={...this.#t,...this.#n,...this.#r};if(Nf(Me,new Map,r?.crit,this.#t,n),n.zip!==void 0&&n.zip!=="DEF")throw new Pt('Unsupported JWE "zip" (Compression Algorithm) Header Parameter value.');if(n.zip!==void 0&&!this.#t?.zip)throw new Me('JWE "zip" (Compression Algorithm) Header Parameter MUST be in a protected header.');let{alg:i,enc:s}=n;if(typeof i!="string"||!i)throw new Me('JWE "alg" (Algorithm) Header Parameter missing or invalid');if(typeof s!="string"||!s)throw new Me('JWE "enc" (Encryption Algorithm) Header Parameter missing or invalid');let o;if(this.#p&&(i==="dir"||i==="ECDH-ES"))throw new TypeError(`setContentEncryptionKey cannot be called with JWE "alg" (Algorithm) Header ${i}`);Pf(i==="dir"?s:i,e,"encrypt");let a;{let g,b=await $u(e,i);({cek:a,encryptedKey:o,parameters:g}=await Rpe(i,s,b,this.#p,this.#a)),g&&(r&&rpe in r?this.#n?this.#n={...this.#n,...g}:this.setUnprotectedHeader(g):this.#t?this.#t={...this.#t,...g}:this.setProtectedHeader(g))}let c,l,u,d;if(this.#t?(l=bn(JSON.stringify(this.#t)),u=Bn(l)):(l="",u=new Uint8Array),this.#i){d=bn(this.#i);let g=Bn(d);c=fi(u,Bn("."),g)}else c=u;let p=this.#e;n.zip==="DEF"&&(p=await Npe(p).catch(g=>{throw new Me("Failed to compress plaintext",{cause:g})}));let{ciphertext:f,tag:m,iv:h}=await eC(s,p,a,this.#u,c),y={ciphertext:bn(f)};return h&&(y.iv=bn(h)),m&&(y.tag=bn(m)),o&&(y.encrypted_key=bn(o)),d&&(y.aad=d),this.#t&&(y.protected=l),this.#r&&(y.unprotected=this.#r),this.#n&&(y.header=this.#n),y}}});async function Kpe(t,e,r){if(!vn(t))throw new zr("Flattened JWS must be an object");if(t.protected===void 0&&t.header===void 0)throw new zr('Flattened JWS must have either of the "protected" or "header" members');if(t.protected!==void 0&&typeof t.protected!="string")throw new zr("JWS Protected Header incorrect type");if(t.payload===void 0)throw new zr("JWS Payload missing");if(typeof t.signature!="string")throw new zr("JWS Signature missing or incorrect type");if(t.header!==void 0&&!vn(t.header))throw new zr("JWS Unprotected Header incorrect type");let n={};if(t.protected)try{let y=_o(t.protected);n=JSON.parse(_s.decode(y))}catch{throw new zr("JWS Protected Header is invalid")}if(!Cf(n,t.header))throw new zr("JWS Protected and JWS Unprotected Header Parameter names must be disjoint");let i={...n,...t.header},s=Nf(zr,new Map([["b64",!0]]),r?.crit,n,i),o=!0;if(s.has("b64")&&(o=n.b64,typeof o!="boolean"))throw new zr('The "b64" (base64url-encode payload) Header Parameter must be a boolean');let{alg:a}=i;if(typeof a!="string"||!a)throw new zr('JWS "alg" (Algorithm) Header Parameter missing or invalid');let c=r&&R0("algorithms",r.algorithms);if(c&&!c.has(a))throw new Bh('"alg" (Algorithm) Header Parameter value not allowed');if(o){if(typeof t.payload!="string")throw new zr("JWS Payload must be a string")}else if(typeof t.payload!="string"&&!(t.payload instanceof Uint8Array))throw new zr("JWS Payload must be a string or an Uint8Array instance");let l=!1;typeof e=="function"&&(e=await e(n,t),l=!0),Pf(a,e,"verify");let u=fi(t.protected!==void 0?Bn(t.protected):new Uint8Array,Bn("."),typeof t.payload=="string"?o?Bn(t.payload):qh.encode(t.payload):t.payload),d=wo(t.signature,"signature",zr),p=await $u(e,a);if(!await ype(a,p,d,u))throw new ZR;let m;o?m=wo(t.payload,"payload",zr):typeof t.payload=="string"?m=qh.encode(t.payload):m=t.payload;let h={payload:m};return t.protected!==void 0&&(h.protectedHeader=n),t.header!==void 0&&(h.unprotectedHeader=t.header),l?{...h,key:p}:h}var qpe=I(()=>{Ys();nC();cn();Vs();sp();Ss();Ss();C0();k0();jH();uv()});async function Fpe(t,e,r){if(t instanceof Uint8Array&&(t=_s.decode(t)),typeof t!="string")throw new zr("Compact JWS must be a string or Uint8Array");let{0:n,1:i,2:s,length:o}=t.split(".");if(o!==3)throw new zr("Invalid Compact JWS");let a=await Kpe({payload:i,protected:n,signature:s},e,r),c={payload:a.payload,protectedHeader:a.protectedHeader};return typeof e=="function"?{...c,key:a.key}:c}var zpe=I(()=>{qpe();cn();Vs()});function N0(t){let e=Krt.exec(t);if(!e||e[4]&&e[1])throw new TypeError("Invalid time period format");let r=parseFloat(e[2]),n=e[3].toLowerCase(),i;switch(n){case"sec":case"secs":case"second":case"seconds":case"s":i=Math.round(r);break;case"minute":case"minutes":case"min":case"mins":case"m":i=Math.round(r*Hpe);break;case"hour":case"hours":case"hr":case"hrs":case"h":i=Math.round(r*Wpe);break;case"day":case"days":case"d":i=Math.round(r*qH);break;case"week":case"weeks":case"w":i=Math.round(r*jrt);break;default:i=Math.round(r*Urt);break}return e[1]==="-"||e[4]==="ago"?-i:i}function $h(t,e){if(!Number.isFinite(e))throw new TypeError(`Invalid ${t} input`);return e}function cC(t,e,r={}){let n;try{n=JSON.parse(_s.decode(e))}catch{}if(!vn(n))throw new Js("JWT Claims Set must be a top-level JSON object");let{typ:i}=r;if(i&&(typeof t.typ!="string"||Bpe(t.typ)!==Bpe(i)))throw new Es('unexpected "typ" JWT header value',n,"typ","check_failed");let{requiredClaims:s=[],issuer:o,subject:a,audience:c,maxTokenAge:l}=r,u=[...s];l!==void 0&&u.push("iat"),c!==void 0&&u.push("aud"),a!==void 0&&u.push("sub"),o!==void 0&&u.push("iss");for(let m of new Set(u.reverse()))if(!(m in n))throw new Es(`missing required "${m}" claim`,n,m,"missing");if(o&&!(Array.isArray(o)?o:[o]).includes(n.iss))throw new Es('unexpected "iss" claim value',n,"iss","check_failed");if(a&&n.sub!==a)throw new Es('unexpected "sub" claim value',n,"sub","check_failed");if(c&&!qrt(n.aud,typeof c=="string"?[c]:c))throw new Es('unexpected "aud" claim value',n,"aud","check_failed");let d;switch(typeof r.clockTolerance){case"string":d=N0(r.clockTolerance);break;case"number":d=r.clockTolerance;break;case"undefined":d=0;break;default:throw new TypeError("Invalid clockTolerance option type")}let{currentDate:p}=r,f=Df(p||new Date);if((n.iat!==void 0||l)&&typeof n.iat!="number")throw new Es('"iat" claim must be a number',n,"iat","invalid");if(n.nbf!==void 0){if(typeof n.nbf!="number")throw new Es('"nbf" claim must be a number',n,"nbf","invalid");if(n.nbf>f+d)throw new Es('"nbf" claim timestamp check failed',n,"nbf","check_failed")}if(n.exp!==void 0){if(typeof n.exp!="number")throw new Es('"exp" claim must be a number',n,"exp","invalid");if(n.exp<=f-d)throw new zh('"exp" claim timestamp check failed',n,"exp","check_failed")}if(l){let m=f-n.iat,h=typeof l=="number"?l:N0(l);if(m-d>h)throw new zh('"iat" claim timestamp check failed (too far in the past)',n,"iat","check_failed");if(m<0-d)throw new Es('"iat" claim timestamp check failed (it should be in the past)',n,"iat","check_failed")}return n}var Df,Hpe,Wpe,qH,jrt,Urt,Krt,Bpe,qrt,pv,P0=I(()=>{cn();Vs();Ss();Df=t=>Math.floor(t.getTime()/1e3),Hpe=60,Wpe=Hpe*60,qH=Wpe*24,jrt=qH*7,Urt=qH*365.25,Krt=/^(\+|\-)? ?(\d+|\d+\.\d+) ?(seconds?|secs?|s|minutes?|mins?|m|hours?|hrs?|h|days?|d|weeks?|w|years?|yrs?|y)(?: (ago|from now))?$/i;Bpe=t=>t.includes("/")?t.toLowerCase():`application/${t.toLowerCase()}`,qrt=(t,e)=>typeof t=="string"?e.includes(t):Array.isArray(t)?e.some(Set.prototype.has.bind(new Set(t))):!1;pv=class{#e;constructor(e){if(!vn(e))throw new TypeError("JWT Claims Set MUST be an object");this.#e=structuredClone(e)}data(){return qh.encode(JSON.stringify(this.#e))}get iss(){return this.#e.iss}set iss(e){this.#e.iss=e}get sub(){return this.#e.sub}set sub(e){this.#e.sub=e}get aud(){return this.#e.aud}set aud(e){this.#e.aud=e}set jti(e){this.#e.jti=e}set nbf(e){typeof e=="number"?this.#e.nbf=$h("setNotBefore",e):e instanceof Date?this.#e.nbf=$h("setNotBefore",Df(e)):this.#e.nbf=Df(new Date)+N0(e)}set exp(e){typeof e=="number"?this.#e.exp=$h("setExpirationTime",e):e instanceof Date?this.#e.exp=$h("setExpirationTime",Df(e)):this.#e.exp=Df(new Date)+N0(e)}set iat(e){e===void 0?this.#e.iat=Df(new Date):e instanceof Date?this.#e.iat=$h("setIssuedAt",Df(e)):typeof e=="string"?this.#e.iat=$h("setIssuedAt",Df(new Date)+N0(e)):this.#e.iat=$h("setIssuedAt",e)}}});async function To(t,e,r){let n=await Fpe(t,e,r);if(n.protectedHeader.crit?.includes("b64")&&n.protectedHeader.b64===!1)throw new Js("JWTs MUST NOT use unencoded payload");let s={payload:cC(n.protectedHeader,n.payload,r),protectedHeader:n.protectedHeader};return typeof e=="function"?{...s,key:n.key}:s}var $pe=I(()=>{zpe();P0();cn()});async function lC(t,e,r){let n=await Lpe(t,e,r),i=cC(n.protectedHeader,n.plaintext,r),{protectedHeader:s}=n;if(s.iss!==void 0&&s.iss!==i.iss)throw new Es('replicated "iss" claim header parameter mismatch',i,"iss","mismatch");if(s.sub!==void 0&&s.sub!==i.sub)throw new Es('replicated "sub" claim header parameter mismatch',i,"sub","mismatch");if(s.aud!==void 0&&JSON.stringify(s.aud)!==JSON.stringify(i.aud))throw new Es('replicated "aud" claim header parameter mismatch',i,"aud","mismatch");let o={payload:i,protectedHeader:s};return typeof e=="function"?{...o,key:n.key}:o}var Gpe=I(()=>{jpe();P0();cn()});var uC,Vpe=I(()=>{Upe();uC=class{#e;constructor(e){this.#e=new aC(e)}setContentEncryptionKey(e){return this.#e.setContentEncryptionKey(e),this}setInitializationVector(e){return this.#e.setInitializationVector(e),this}setProtectedHeader(e){return this.#e.setProtectedHeader(e),this}setKeyManagementParameters(e){return this.#e.setKeyManagementParameters(e),this}async encrypt(e,r){let n=await this.#e.encrypt(e,r);return[n.protected,n.encrypted_key,n.iv,n.ciphertext,n.tag].join(".")}}});var dC,Ype=I(()=>{Ys();nC();Ss();cn();Vs();C0();k0();uv();sp();dC=class{#e;#t;#r;constructor(e){if(!(e instanceof Uint8Array))throw new TypeError("payload must be an instance of Uint8Array");this.#e=e}setProtectedHeader(e){return So(this.#t,"setProtectedHeader"),this.#t=e,this}setUnprotectedHeader(e){return So(this.#r,"setUnprotectedHeader"),this.#r=e,this}async sign(e,r){if(!this.#t&&!this.#r)throw new zr("either setProtectedHeader or setUnprotectedHeader must be called before #sign()");if(!Cf(this.#t,this.#r))throw new zr("JWS Protected and JWS Unprotected Header Parameter names must be disjoint");let n={...this.#t,...this.#r},i=Nf(zr,new Map([["b64",!0]]),r?.crit,this.#t,n),s=!0;if(i.has("b64")&&(s=this.#t.b64,typeof s!="boolean"))throw new zr('The "b64" (base64url-encode payload) Header Parameter must be a boolean');let{alg:o}=n;if(typeof o!="string"||!o)throw new zr('JWS "alg" (Algorithm) Header Parameter missing or invalid');Pf(o,e,"sign");let a,c;s?(a=bn(this.#e),c=Bn(a)):(c=this.#e,a="");let l,u;this.#t?(l=bn(JSON.stringify(this.#t)),u=Bn(l)):(l="",u=new Uint8Array);let d=fi(u,Bn("."),c),p=await $u(e,o),f=await gpe(o,p,d),m={signature:bn(f),payload:a};return this.#r&&(m.header=this.#r),this.#t&&(m.protected=l),m}}});var pC,Jpe=I(()=>{Ype();pC=class{#e;constructor(e){this.#e=new dC(e)}setProtectedHeader(e){return this.#e.setProtectedHeader(e),this}async sign(e,r){let n=await this.#e.sign(e,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 D0,Zpe=I(()=>{Jpe();cn();P0();D0=class{#e;#t;constructor(e={}){this.#t=new pv(e)}setIssuer(e){return this.#t.iss=e,this}setSubject(e){return this.#t.sub=e,this}setAudience(e){return this.#t.aud=e,this}setJti(e){return this.#t.jti=e,this}setNotBefore(e){return this.#t.nbf=e,this}setExpirationTime(e){return this.#t.exp=e,this}setIssuedAt(e){return this.#t.iat=e,this}setProtectedHeader(e){return this.#e=e,this}async sign(e,r){let n=new pC(this.#t.data());if(n.setProtectedHeader(this.#e),Array.isArray(this.#e?.crit)&&this.#e.crit.includes("b64")&&this.#e.b64===!1)throw new Js("JWTs MUST NOT use unencoded payload");return n.sign(e,r)}}});var M0,Xpe=I(()=>{Vpe();P0();sp();M0=class{#e;#t;#r;#n;#i;#p;#u;#a;constructor(e={}){this.#a=new pv(e)}setIssuer(e){return this.#a.iss=e,this}setSubject(e){return this.#a.sub=e,this}setAudience(e){return this.#a.aud=e,this}setJti(e){return this.#a.jti=e,this}setNotBefore(e){return this.#a.nbf=e,this}setExpirationTime(e){return this.#a.exp=e,this}setIssuedAt(e){return this.#a.iat=e,this}setProtectedHeader(e){return So(this.#n,"setProtectedHeader"),this.#n=e,this}setKeyManagementParameters(e){return So(this.#r,"setKeyManagementParameters"),this.#r=e,this}setContentEncryptionKey(e){return So(this.#e,"setContentEncryptionKey"),this.#e=e,this}setInitializationVector(e){return So(this.#t,"setInitializationVector"),this.#t=e,this}replicateIssuerAsHeader(){return this.#i=!0,this}replicateSubjectAsHeader(){return this.#p=!0,this}replicateAudienceAsHeader(){return this.#u=!0,this}async encrypt(e,r){let n=new uC(this.#a.data());return this.#n&&(this.#i||this.#p||this.#u)&&(this.#n={...this.#n,iss:this.#i?this.#a.iss:void 0,sub:this.#p?this.#a.sub:void 0,aud:this.#u?this.#a.aud:void 0}),n.setProtectedHeader(this.#n),this.#t&&n.setInitializationVector(this.#t),this.#e&&n.setContentEncryptionKey(this.#e),this.#r&&n.setKeyManagementParameters(this.#r),n.encrypt(e,r)}}});async function fC(t,e){let r;if(Wh(t))r=t;else if(T0(t))r=await oC(t);else throw new TypeError(Wu(t,"CryptoKey","KeyObject","JSON Web Key"));if(e??="sha256",e!=="sha256"&&e!=="sha384"&&e!=="sha512")throw new TypeError('digestAlgorithm must one of "sha256", "sha384", or "sha512"');let n;switch(r.kty){case"AKP":Gu(r.alg,'"alg" (Algorithm) Parameter'),Gu(r.pub,'"pub" (Public key) Parameter'),n={alg:r.alg,kty:r.kty,pub:r.pub};break;case"EC":Gu(r.crv,'"crv" (Curve) Parameter'),Gu(r.x,'"x" (X Coordinate) Parameter'),Gu(r.y,'"y" (Y Coordinate) Parameter'),n={crv:r.crv,kty:r.kty,x:r.x,y:r.y};break;case"OKP":Gu(r.crv,'"crv" (Subtype of Key Pair) Parameter'),Gu(r.x,'"x" (Public Key) Parameter'),n={crv:r.crv,kty:r.kty,x:r.x};break;case"RSA":Gu(r.e,'"e" (Exponent) Parameter'),Gu(r.n,'"n" (Modulus) Parameter'),n={e:r.e,kty:r.kty,n:r.n};break;case"oct":Gu(r.k,'"k" (Key Value) Parameter'),n={k:r.k,kty:r.kty};break;default:throw new Pt('"kty" (Key Type) Parameter missing or unsupported')}let i=Bn(JSON.stringify(n));return bn(await rC(e,i))}var Gu,Qpe=I(()=>{sp();Ys();cn();Vs();Hh();Ss();MH();rv();Gu=(t,e)=>{if(typeof t!="string"||!t)throw new VR(`${e} missing or invalid`)}});function Frt(t){switch(typeof t=="string"&&t.slice(0,2)){case"RS":case"PS":return"RSA";case"ES":return"EC";case"Ed":return"OKP";case"ML":return"AKP";default:throw new Pt('Unsupported "alg" value for a JSON Web Key Set')}}function zrt(t){return t&&typeof t=="object"&&Array.isArray(t.keys)&&t.keys.every(Brt)}function Brt(t){return vn(t)}async function efe(t,e,r){let n=t.get(e)||t.set(e,{}).get(e);if(n[r]===void 0){let i=await Ga({...e,ext:!0},r);if(i instanceof Uint8Array||i.type!=="public")throw new S0("JSON Web Key Set members must be public keys");n[r]=i}return n[r]}function zH(t){let e=new FH(t),r=async(n,i)=>e.getKey(n,i);return Object.defineProperties(r,{jwks:{value:()=>structuredClone(e.jwks()),enumerable:!1,configurable:!1,writable:!1}}),r}var FH,tfe=I(()=>{sC();cn();Ss();FH=class{#e;#t=new WeakMap;constructor(e){if(!zrt(e))throw new S0("JSON Web Key Set malformed");this.#e=structuredClone(e)}jwks(){return this.#e}async getKey(e,r){let{alg:n,kid:i}={...e,...r?.header},s=Frt(n),o=this.#e.keys.filter(l=>{let u=s===l.kty;if(u&&typeof i=="string"&&(u=i===l.kid),u&&(typeof l.alg=="string"||s==="AKP")&&(u=n===l.alg),u&&typeof l.use=="string"&&(u=l.use==="sig"),u&&Array.isArray(l.key_ops)&&(u=l.key_ops.includes("verify")),u)switch(n){case"ES256":u=l.crv==="P-256";break;case"ES384":u=l.crv==="P-384";break;case"ES512":u=l.crv==="P-521";break;case"Ed25519":case"EdDSA":u=l.crv==="Ed25519";break}return u}),{0:a,length:c}=o;if(c===0)throw new iv;if(c!==1){let l=new YR,u=this.#t;throw l[Symbol.asyncIterator]=async function*(){for(let d of o)try{yield await efe(u,d,n)}catch{}},l}return efe(this.#t,a,n)}}});function Hrt(){return typeof WebSocketPair<"u"||typeof navigator<"u"&&navigator.userAgent==="Cloudflare-Workers"||typeof EdgeRuntime<"u"&&EdgeRuntime==="vercel"}async function Wrt(t,e,r,n=fetch){let i=await n(t,{method:"GET",signal:r,redirect:"manual",headers:e}).catch(s=>{throw s.name==="TimeoutError"?new JR:s});if(i.status!==200)throw new Si("Expected 200 OK from the JSON Web Key Set HTTP response");try{return await i.json()}catch{throw new Si("Failed to parse the JSON Web Key Set HTTP response as JSON")}}function $rt(t,e){return!(typeof t!="object"||t===null||!("uat"in t)||typeof t.uat!="number"||Date.now()-t.uat>=e||!("jwks"in t)||!vn(t.jwks)||!Array.isArray(t.jwks.keys)||!Array.prototype.every.call(t.jwks.keys,vn))}function WH(t,e){let r=new HH(t,e),n=async(i,s)=>r.getKey(i,s);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.jwks(),enumerable:!0,configurable:!1,writable:!1}}),n}var BH,rfe,mC,HH,nfe=I(()=>{cn();tfe();Ss();(typeof navigator>"u"||!navigator.userAgent?.startsWith?.("Mozilla/5.0 "))&&(BH="jose/v6.2.3");rfe=Symbol();mC=Symbol();HH=class{#e;#t;#r;#n;#i;#p;#u;#a;#o;#d;constructor(e,r){if(!(e instanceof URL))throw new TypeError("url must be an instance of URL");this.#e=new URL(e.href),this.#t=typeof r?.timeoutDuration=="number"?r?.timeoutDuration:5e3,this.#r=typeof r?.cooldownDuration=="number"?r?.cooldownDuration:3e4,this.#n=typeof r?.cacheMaxAge=="number"?r?.cacheMaxAge:6e5,this.#u=new Headers(r?.headers),BH&&!this.#u.has("User-Agent")&&this.#u.set("User-Agent",BH),this.#u.has("accept")||(this.#u.set("accept","application/json"),this.#u.append("accept","application/jwk-set+json")),this.#a=r?.[rfe],r?.[mC]!==void 0&&(this.#d=r?.[mC],$rt(r?.[mC],this.#n)&&(this.#i=this.#d.uat,this.#o=zH(this.#d.jwks)))}pendingFetch(){return!!this.#p}coolingDown(){return typeof this.#i=="number"?Date.now()<this.#i+this.#r:!1}fresh(){return typeof this.#i=="number"?Date.now()<this.#i+this.#n:!1}jwks(){return this.#o?.jwks()}async getKey(e,r){(!this.#o||!this.fresh())&&await this.reload();try{return await this.#o(e,r)}catch(n){if(n instanceof iv&&this.coolingDown()===!1)return await this.reload(),this.#o(e,r);throw n}}async reload(){this.#p&&Hrt()&&(this.#p=void 0),this.#p||=Wrt(this.#e.href,this.#u,AbortSignal.timeout(this.#t),this.#a).then(e=>{this.#o=zH(e),this.#d&&(this.#d.uat=Date.now(),this.#d.jwks=e),this.#i=Date.now(),this.#p=void 0}).catch(e=>{throw this.#p=void 0,e}),await this.#p}}});function Dl(t){let e;if(typeof t=="string"){let r=t.split(".");(r.length===3||r.length===5)&&([e]=r)}else if(typeof t=="object"&&t)if("protected"in t)e=t.protected;else throw new TypeError("Token does not contain a Protected Header");try{if(typeof e!="string"||!e)throw new Error;let r=JSON.parse(_s.decode(_o(e)));if(!vn(r))throw new Error;return r}catch{throw new TypeError("Invalid Token or Protected Header formatting")}}var ife=I(()=>{Ys();Vs();Ss()});function wi(t){if(typeof t!="string")throw new Js("JWTs must use Compact JWS serialization, JWT must be a string");let{1:e,length:r}=t.split(".");if(r===5)throw new Js("Only JWTs using Compact JWS serialization can be decoded");if(r!==3)throw new Js("Invalid JWT");if(!e)throw new Js("JWTs must contain a payload");let n;try{n=_o(e)}catch{throw new Js("Failed to base64url decode the payload")}let i;try{i=JSON.parse(_s.decode(n))}catch{throw new Js("Failed to parse the decoded payload as JSON")}if(!vn(i))throw new Js("Invalid JWT Claims Set");return i}var sfe=I(()=>{Ys();Vs();Ss();cn()});var Wc=I(()=>{$pe();Gpe();Zpe();Xpe();Qpe();nfe();sC();ife();sfe();Ys()});async function hC(t,e,r=3600){return await new D0(t).setProtectedHeader({alg:"HS256"}).setIssuedAt().setExpirationTime(Math.floor(Date.now()/1e3)+r).sign(new TextEncoder().encode(e))}async function $H(t,e){try{return(await To(t,new TextEncoder().encode(e))).payload}catch{return null}}function L0(t,e){return Ude(Bde,new TextEncoder().encode(t),new TextEncoder().encode(e),Grt,64)}function Yrt(t){if(typeof t=="string")return t;let e=t.keys.get(t.currentVersion);if(!e)throw new Error(`Secret version ${t.currentVersion} not found in keys`);return e}function ofe(t){if(typeof t=="string")return[{version:0,value:t}];let e=[];for(let[r,n]of t.keys)e.push({version:r,value:n});return t.legacySecret&&!e.some(r=>r.value===t.legacySecret)&&e.push({version:-1,value:t.legacySecret}),e}async function gC(t,e,r,n=3600){let i=L0(Yrt(e),r),s=await fC({kty:"oct",k:E0.encode(i)},"sha256");return await new M0(t).setProtectedHeader({alg:cfe,enc:lfe,kid:s}).setIssuedAt().setExpirationTime(Vrt()+n).setJti(crypto.randomUUID()).encrypt(i)}async function j0(t,e,r){if(!t)return null;let n=!1;try{n=Dl(t).kid!==void 0}catch{return null}try{let i=ofe(e),{payload:s}=await lC(t,async o=>{let a=o.kid;if(a!==void 0){for(let c of i){let l=L0(c.value,r);if(a===await fC({kty:"oct",k:E0.encode(l)},"sha256"))return l}throw new Error("no matching decryption secret")}return i.length===1,L0(i[0].value,r)},afe);return s}catch{if(n)return null;let i=ofe(e);if(i.length<=1)return null;for(let s=1;s<i.length;s++)try{let o=i[s],{payload:a}=await lC(t,L0(o.value,r),afe);return a}catch{continue}return null}}var Grt,Vrt,cfe,lfe,afe,U0=I(()=>{Kde();Hde();Wc();Grt=new Uint8Array([66,101,116,116,101,114,65,117,116,104,46,106,115,32,71,101,110,101,114,97,116,101,100,32,69,110,99,114,121,112,116,105,111,110,32,75,101,121]),Vrt=()=>Date.now()/1e3|0,cfe="dir",lfe="A256CBC-HS512";afe={clockTolerance:15,keyManagementAlgorithms:[cfe],contentEncryptionAlgorithms:[lfe,"A256GCM"]}});function ufe(t,e){return new Promise((r,n)=>{(0,yC.scrypt)(t.normalize("NFKC"),e,fv.dkLen,{N:fv.N,r:fv.r,p:fv.p,maxmem:128*fv.N*fv.r*2},(i,s)=>{i?n(i):r(s)})})}async function dfe(t){let e=(0,yC.randomBytes)(16).toString("hex"),r=await ufe(t,e);return`${e}:${r.toString("hex")}`}async function pfe(t,e){let[r,n]=t.split(":");if(!r||!n)throw new Error("Invalid password hash");return(await ufe(e,r)).toString("hex")===n}var yC,fv,ffe=I(()=>{yC=require("node:crypto"),fv={N:16384,r:16,p:1,dkLen:64}});var mfe,hfe,gfe=I(()=>{ffe();mfe=dfe,hfe=async({hash:t,password:e})=>pfe(t,e)});function Ml(){let t=typeof globalThis<"u"&&globalThis.crypto;if(t&&typeof t.subtle=="object"&&t.subtle!=null)return t.subtle;throw new Error("crypto.subtle must be defined")}var K0=I(()=>{});function bC(t){return t?"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_":"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"}function yfe(t,e,r){let n="",i=0,s=0;for(let o of t)for(i=i<<8|o,s+=8;s>=6;)s-=6,n+=e[i>>s&63];if(s>0&&(n+=e[i<<6-s&63]),r){let o=(4-n.length%4)%4;n+="=".repeat(o)}return n}function bfe(t,e){let r=new Map;for(let o=0;o<e.length;o++)r.set(e[o],o);let n=[],i=0,s=0;for(let o of t){if(o==="=")break;let a=r.get(o);if(a===void 0)throw new Error(`Invalid Base64 character: ${o}`);i=i<<6|a,s+=6,s>=8&&(s-=8,n.push(i>>s&255))}return Uint8Array.from(n)}var Hi,da,pa=I(()=>{Hi={encode(t,e={}){let r=bC(!1),n=typeof t=="string"?new TextEncoder().encode(t):new Uint8Array(t);return yfe(n,r,e.padding??!0)},decode(t){typeof t!="string"&&(t=new TextDecoder().decode(t));let e=t.includes("-")||t.includes("_"),r=bC(e);return bfe(t,r)}},da={encode(t,e={}){let r=bC(!0),n=typeof t=="string"?new TextEncoder().encode(t):new Uint8Array(t);return yfe(n,r,e.padding??!0)},decode(t){let e=t.includes("-")||t.includes("_"),r=bC(e);return bfe(t,r)}}});function op(t,e){return{digest:async r=>{let n=new TextEncoder,i=typeof r=="string"?n.encode(r):r,s=await Ml().digest(t,i);return e==="hex"?Array.from(new Uint8Array(s)).map(c=>c.toString(16).padStart(2,"0")).join(""):e==="base64"||e==="base64url"||e==="base64urlnopad"?e.includes("url")?da.encode(s,{padding:e!=="base64urlnopad"}):Hi.encode(s):s}}}var q0=I(()=>{pa();K0()});function Jrt(t){return t instanceof Uint8Array||ArrayBuffer.isView(t)&&t.constructor.name==="Uint8Array"&&"BYTES_PER_ELEMENT"in t&&t.BYTES_PER_ELEMENT===1}function vC(t){if(typeof t!="boolean")throw new TypeError(`boolean expected, not ${t}`)}function Mf(t){if(typeof t!="number")throw new TypeError("number expected, got "+typeof t);if(!Number.isSafeInteger(t)||t<0)throw new RangeError("positive integer expected, got "+t)}function Dn(t,e,r=""){let n=Jrt(t),i=t?.length,s=e!==void 0;if(!n||s&&i!==e){let o=r&&`"${r}" `,a=s?` of length ${e}`:"",c=n?`length=${i}`:`type=${typeof t}`,l=o+"expected Uint8Array"+a+", got "+c;throw n?new RangeError(l):new TypeError(l)}return t}function GH(t,e=!0){if(t.destroyed)throw new Error("Hash instance has been destroyed");if(e&&t.finished)throw new Error("Hash#digest() has already been called")}function _fe(t,e,r=!1){Dn(t,void 0,"output");let n=e.outputLen;if(t.length<n)throw new RangeError("digestInto() expects output buffer of length at least "+n);if(r&&!mv(t))throw new Error("invalid output, must be aligned")}function Vu(t){return new Uint32Array(t.buffer,t.byteOffset,Math.floor(t.byteLength/4))}function Ll(...t){for(let e=0;e<t.length;e++)t[e].fill(0)}function Zrt(t){return new DataView(t.buffer,t.byteOffset,t.byteLength)}function VH(t){if(Dn(t),Sfe)return t.toHex();let e="";for(let r=0;r<t.length;r++)e+=Qrt[t[r]];return e}function vfe(t){if(t>=ap._0&&t<=ap._9)return t-ap._0;if(t>=ap.A&&t<=ap.F)return t-(ap.A-10);if(t>=ap.a&&t<=ap.f)return t-(ap.a-10)}function wfe(t){if(typeof t!="string")throw new TypeError("hex string expected, got "+typeof t);if(Sfe)try{return Uint8Array.fromHex(t)}catch(i){throw i instanceof SyntaxError?new RangeError(i.message):i}let e=t.length,r=e/2;if(e%2)throw new RangeError("hex string expected, got unpadded hex of length "+e);let n=new Uint8Array(r);for(let i=0,s=0;i<r;i++,s+=2){let o=vfe(t.charCodeAt(s)),a=vfe(t.charCodeAt(s+1));if(o===void 0||a===void 0){let c=t[s]+t[s+1];throw new RangeError('hex string expected, got non-hex character "'+c+'" at index '+s)}n[i]=o*16+a}return n}function Tfe(t){if(typeof t!="string")throw new TypeError("string expected");return new Uint8Array(new TextEncoder().encode(t))}function ent(t,e){return!t.byteLength||!e.byteLength?!1:t.buffer===e.buffer&&t.byteOffset<e.byteOffset+e.byteLength&&e.byteOffset<t.byteOffset+t.byteLength}function xfe(...t){let e=0;for(let n=0;n<t.length;n++){let i=t[n];Dn(i),e+=i.length}let r=new Uint8Array(e);for(let n=0,i=0;n<t.length;n++){let s=t[n];r.set(s,i),i+=s.length}return r}function Ife(t,e){if(e==null||typeof e!="object")throw new Error("options must be defined");return Object.assign(t,e)}function Afe(t,e){if(t.length!==e.length)return!1;let r=0;for(let n=0;n<t.length;n++)r|=t[n]^e[n];return r===0}function Ofe(t,e,r){let n=e,i=r||(()=>[]),s=(a,c)=>n(c,...i(a)).update(a).digest(),o=n(new Uint8Array(t),...i(new Uint8Array(0)));return s.outputLen=o.outputLen,s.blockLen=o.blockLen,s.create=(a,...c)=>n(a,...c),s}function F0(t,e,r=!0){if(e===void 0)return new Uint8Array(t);if(Dn(e,void 0,"output"),e.length!==t)throw new Error('"output" expected Uint8Array of length '+t+", got: "+e.length);if(r&&!mv(e))throw new Error("invalid output, must be aligned");return e}function Rfe(t,e,r){Mf(t),Mf(e),vC(r);let n=new Uint8Array(16),i=Zrt(n);return i.setBigUint64(0,BigInt(e),r),i.setBigUint64(8,BigInt(t),r),n}function mv(t){return t.byteOffset%4===0}function hv(t){return Uint8Array.from(Dn(t))}function Cfe(t=32){Mf(t);let e=typeof globalThis=="object"?globalThis.crypto:null;if(typeof e?.getRandomValues!="function")throw new Error("crypto.getRandomValues must be defined");return e.getRandomValues(new Uint8Array(t))}function YH(t,e=Cfe){let{nonceLength:r}=t;Mf(r);let n=(s,o,a)=>{let c=xfe(s,o);return ent(a,o)||o.fill(0),c},i=((s,...o)=>({encrypt(a){Dn(a);let c=e(r),l=t(s,c,...o).encrypt(a);return l instanceof Promise?l.then(u=>n(c,u,a)):n(c,l,a)},decrypt(a){Dn(a);let c=a.subarray(0,r),l=a.subarray(r);return t(s,c,...o).decrypt(l)}}));return"blockSize"in t&&(i.blockSize=t.blockSize),"tagLength"in t&&(i.tagLength=t.tagLength),i}var Lf,Efe,ws,Xrt,Yu,Sfe,Qrt,ap,kfe,z0=I(()=>{Lf=new Uint8Array(new Uint32Array([287454020]).buffer)[0]===68,Efe=t=>t<<24&4278190080|t<<8&16711680|t>>>8&65280|t>>>24&255,ws=Lf?t=>t:t=>Efe(t)>>>0,Xrt=t=>{for(let e=0;e<t.length;e++)t[e]=Efe(t[e]);return t},Yu=Lf?t=>t:Xrt,Sfe=typeof Uint8Array.from([]).toHex=="function"&&typeof Uint8Array.fromHex=="function",Qrt=Array.from({length:256},(t,e)=>e.toString(16).padStart(2,"0"));ap={_0:48,_9:57,A:65,F:70,a:97,f:102};kfe=(t,e)=>{function r(n,...i){if(Dn(n,void 0,"key"),t.nonceLength!==void 0){let u=i[0];Dn(u,t.varSizeNonce?void 0:t.nonceLength,"nonce")}let s=t.tagLength;s&&i[1]!==void 0&&Dn(i[1],void 0,"AAD");let o=e(n,...i),a=(u,d)=>{if(d!==void 0){if(u!==2)throw new Error("cipher output not supported");Dn(d,void 0,"output")}},c=!1;return{encrypt(u,d){if(c)throw new Error("cannot encrypt() twice with same key + nonce");return c=!0,Dn(u),a(o.encrypt.length,d),o.encrypt(u,d)},decrypt(u,d){if(Dn(u),s&&u.length<s)throw new Error('"ciphertext" expected length bigger than tagLength='+s);return a(o.decrypt.length,d),o.decrypt(u,d)}}}return Object.assign(r,t),r}});function Le(t,e){return t<<e|t>>>32-e}function int(t,e,r,n,i,s,o,a){let c=i.length,l=new Uint8Array(B0),u=Vu(l),d=Lf&&mv(i)&&mv(s),p=d?Vu(i):Nfe,f=d?Vu(s):Nfe;if(!Lf){for(let m=0;m<c;o++){if(t(e,r,n,u,o,a),Yu(u),o>=JH)throw new Error("arx: counter overflow");let h=Math.min(B0,c-m);for(let y=0,g;y<h;y++)g=m+y,s[g]=i[g]^l[y];m+=h}return}for(let m=0;m<c;o++){if(t(e,r,n,u,o,a),o>=JH)throw new Error("arx: counter overflow");let h=Math.min(B0,c-m);if(d&&h===B0){let y=m/4;if(m%4!==0)throw new Error("arx: invalid block position");for(let g=0,b;g<nnt;g++)b=y+g,f[b]=p[b]^u[g];m+=B0;continue}for(let y=0,g;y<h;y++)g=m+y,s[g]=i[g]^l[y];m+=h}}function Dfe(t,e){let{allowShortKeys:r,extendNonceFn:n,counterLength:i,counterRight:s,rounds:o}=Ife({allowShortKeys:!1,counterLength:8,counterRight:!1,rounds:20},e);if(typeof t!="function")throw new Error("core must be a function");return Mf(i),Mf(o),vC(s),vC(r),(a,c,l,u,d=0)=>{Dn(a,void 0,"key"),Dn(c,void 0,"nonce"),Dn(l,void 0,"data");let p=l.length;if(u=F0(p,u,!1),Mf(d),d<0||d>=JH)throw new Error("arx: counter overflow");let f=[],m=a.length,h,y;if(m===32)f.push(h=hv(a)),y=rnt;else if(m===16&&r)h=new Uint8Array(32),h.set(a),h.set(a,16),y=tnt,f.push(h);else throw Dn(a,32,"arx key"),new Error("invalid key size");(!Lf||!mv(c))&&f.push(c=hv(c));let g=Vu(h);if(n){if(c.length!==24)throw new Error("arx: extended nonce must be 24 bytes");let _=c.subarray(0,16);if(Lf)n(y,g,Vu(_),g);else{let w=Yu(Uint32Array.from(y));n(w,g,Vu(_),g),Ll(w),Yu(g)}c=c.subarray(16)}else Lf||Yu(g);let b=16-i;if(b!==c.length)throw new Error(`arx: nonce must be ${b} or 16 bytes`);if(b!==12){let _=new Uint8Array(12);_.set(c,s?0:12-c.length),c=_,f.push(c)}let v=Yu(Vu(c));try{return int(t,y,g,v,l,u,d,o),u}finally{Ll(...f)}}}var Pfe,tnt,rnt,B0,nnt,JH,Nfe,Mfe=I(()=>{z0();Pfe=t=>Uint8Array.from(t.split(""),e=>e.charCodeAt(0)),tnt=Yu(Vu(Pfe("expand 16-byte k"))),rnt=Yu(Vu(Pfe("expand 32-byte k")));B0=64,nnt=16,JH=2**32-1,Nfe=Uint32Array.of()});function Ts(t,e){return t[e++]&255|(t[e++]&255)<<8}var ZH,Lfe,jfe=I(()=>{z0();ZH=class{blockLen=16;outputLen=16;buffer=new Uint8Array(16);r=new Uint16Array(10);h=new Uint16Array(10);pad=new Uint16Array(8);pos=0;finished=!1;destroyed=!1;constructor(e){e=hv(Dn(e,32,"key"));let r=Ts(e,0),n=Ts(e,2),i=Ts(e,4),s=Ts(e,6),o=Ts(e,8),a=Ts(e,10),c=Ts(e,12),l=Ts(e,14);this.r[0]=r&8191,this.r[1]=(r>>>13|n<<3)&8191,this.r[2]=(n>>>10|i<<6)&7939,this.r[3]=(i>>>7|s<<9)&8191,this.r[4]=(s>>>4|o<<12)&255,this.r[5]=o>>>1&8190,this.r[6]=(o>>>14|a<<2)&8191,this.r[7]=(a>>>11|c<<5)&8065,this.r[8]=(c>>>8|l<<8)&8191,this.r[9]=l>>>5&127;for(let u=0;u<8;u++)this.pad[u]=Ts(e,16+2*u)}process(e,r,n=!1){let i=n?0:2048,{h:s,r:o}=this,a=o[0],c=o[1],l=o[2],u=o[3],d=o[4],p=o[5],f=o[6],m=o[7],h=o[8],y=o[9],g=Ts(e,r+0),b=Ts(e,r+2),v=Ts(e,r+4),_=Ts(e,r+6),w=Ts(e,r+8),S=Ts(e,r+10),x=Ts(e,r+12),O=Ts(e,r+14),N=s[0]+(g&8191),k=s[1]+((g>>>13|b<<3)&8191),M=s[2]+((b>>>10|v<<6)&8191),K=s[3]+((v>>>7|_<<9)&8191),P=s[4]+((_>>>4|w<<12)&8191),j=s[5]+(w>>>1&8191),U=s[6]+((w>>>14|S<<2)&8191),q=s[7]+((S>>>11|x<<5)&8191),F=s[8]+((x>>>8|O<<8)&8191),Q=s[9]+(O>>>5|i),J=0,W=J+N*a+k*(5*y)+M*(5*h)+K*(5*m)+P*(5*f);J=W>>>13,W&=8191,W+=j*(5*p)+U*(5*d)+q*(5*u)+F*(5*l)+Q*(5*c),J+=W>>>13,W&=8191;let z=J+N*c+k*a+M*(5*y)+K*(5*h)+P*(5*m);J=z>>>13,z&=8191,z+=j*(5*f)+U*(5*p)+q*(5*d)+F*(5*u)+Q*(5*l),J+=z>>>13,z&=8191;let G=J+N*l+k*c+M*a+K*(5*y)+P*(5*h);J=G>>>13,G&=8191,G+=j*(5*m)+U*(5*f)+q*(5*p)+F*(5*d)+Q*(5*u),J+=G>>>13,G&=8191;let H=J+N*u+k*l+M*c+K*a+P*(5*y);J=H>>>13,H&=8191,H+=j*(5*h)+U*(5*m)+q*(5*f)+F*(5*p)+Q*(5*d),J+=H>>>13,H&=8191;let L=J+N*d+k*u+M*l+K*c+P*a;J=L>>>13,L&=8191,L+=j*(5*y)+U*(5*h)+q*(5*m)+F*(5*f)+Q*(5*p),J+=L>>>13,L&=8191;let B=J+N*p+k*d+M*u+K*l+P*c;J=B>>>13,B&=8191,B+=j*a+U*(5*y)+q*(5*h)+F*(5*m)+Q*(5*f),J+=B>>>13,B&=8191;let ie=J+N*f+k*p+M*d+K*u+P*l;J=ie>>>13,ie&=8191,ie+=j*c+U*a+q*(5*y)+F*(5*h)+Q*(5*m),J+=ie>>>13,ie&=8191;let xe=J+N*m+k*f+M*p+K*d+P*u;J=xe>>>13,xe&=8191,xe+=j*l+U*c+q*a+F*(5*y)+Q*(5*h),J+=xe>>>13,xe&=8191;let Ne=J+N*h+k*m+M*f+K*p+P*d;J=Ne>>>13,Ne&=8191,Ne+=j*u+U*l+q*c+F*a+Q*(5*y),J+=Ne>>>13,Ne&=8191;let bt=J+N*y+k*h+M*m+K*f+P*p;J=bt>>>13,bt&=8191,bt+=j*d+U*u+q*l+F*c+Q*a,J+=bt>>>13,bt&=8191,J=(J<<2)+J|0,J=J+W|0,W=J&8191,J=J>>>13,z+=J,s[0]=W,s[1]=z,s[2]=G,s[3]=H,s[4]=L,s[5]=B,s[6]=ie,s[7]=xe,s[8]=Ne,s[9]=bt}finalize(){let{h:e,pad:r}=this,n=new Uint16Array(10),i=e[1]>>>13;e[1]&=8191;for(let a=2;a<10;a++)e[a]+=i,i=e[a]>>>13,e[a]&=8191;e[0]+=i*5,i=e[0]>>>13,e[0]&=8191,e[1]+=i,i=e[1]>>>13,e[1]&=8191,e[2]+=i,n[0]=e[0]+5,i=n[0]>>>13,n[0]&=8191;for(let a=1;a<10;a++)n[a]=e[a]+i,i=n[a]>>>13,n[a]&=8191;n[9]-=8192;let s=(i^1)-1;for(let a=0;a<10;a++)n[a]&=s;s=~s;for(let a=0;a<10;a++)e[a]=e[a]&s|n[a];e[0]=(e[0]|e[1]<<13)&65535,e[1]=(e[1]>>>3|e[2]<<10)&65535,e[2]=(e[2]>>>6|e[3]<<7)&65535,e[3]=(e[3]>>>9|e[4]<<4)&65535,e[4]=(e[4]>>>12|e[5]<<1|e[6]<<14)&65535,e[5]=(e[6]>>>2|e[7]<<11)&65535,e[6]=(e[7]>>>5|e[8]<<8)&65535,e[7]=(e[8]>>>8|e[9]<<5)&65535;let o=e[0]+r[0];e[0]=o&65535;for(let a=1;a<8;a++)o=(e[a]+r[a]|0)+(o>>>16)|0,e[a]=o&65535;Ll(n)}update(e){GH(this),Dn(e),e=hv(e);let{buffer:r,blockLen:n}=this,i=e.length;for(let s=0;s<i;){let o=Math.min(n-this.pos,i-s);if(o===n){for(;n<=i-s;s+=n)this.process(e,s);continue}r.set(e.subarray(s,s+o),this.pos),this.pos+=o,s+=o,this.pos===n&&(this.process(r,0,!1),this.pos=0)}return this}destroy(){this.destroyed=!0,Ll(this.h,this.r,this.buffer,this.pad)}digestInto(e){GH(this),_fe(e,this),this.finished=!0;let{buffer:r,h:n}=this,{pos:i}=this;if(i){for(r[i++]=1;i<16;i++)r[i]=0;this.process(r,0,!0)}this.finalize();let s=0;for(let o=0;o<8;o++)e[s++]=n[o]>>>0,e[s++]=n[o]>>>8}digest(){let{buffer:e,outputLen:r}=this;this.digestInto(e);let n=e.slice(0,r);return this.destroy(),n}},Lfe=Ofe(32,t=>new ZH(t))});function snt(t,e,r,n,i,s=20){let o=t[0],a=t[1],c=t[2],l=t[3],u=e[0],d=e[1],p=e[2],f=e[3],m=e[4],h=e[5],y=e[6],g=e[7],b=i,v=r[0],_=r[1],w=r[2],S=o,x=a,O=c,N=l,k=u,M=d,K=p,P=f,j=m,U=h,q=y,F=g,Q=b,J=v,W=_,z=w;for(let H=0;H<s;H+=2)S=S+k|0,Q=Le(Q^S,16),j=j+Q|0,k=Le(k^j,12),S=S+k|0,Q=Le(Q^S,8),j=j+Q|0,k=Le(k^j,7),x=x+M|0,J=Le(J^x,16),U=U+J|0,M=Le(M^U,12),x=x+M|0,J=Le(J^x,8),U=U+J|0,M=Le(M^U,7),O=O+K|0,W=Le(W^O,16),q=q+W|0,K=Le(K^q,12),O=O+K|0,W=Le(W^O,8),q=q+W|0,K=Le(K^q,7),N=N+P|0,z=Le(z^N,16),F=F+z|0,P=Le(P^F,12),N=N+P|0,z=Le(z^N,8),F=F+z|0,P=Le(P^F,7),S=S+M|0,z=Le(z^S,16),q=q+z|0,M=Le(M^q,12),S=S+M|0,z=Le(z^S,8),q=q+z|0,M=Le(M^q,7),x=x+K|0,Q=Le(Q^x,16),F=F+Q|0,K=Le(K^F,12),x=x+K|0,Q=Le(Q^x,8),F=F+Q|0,K=Le(K^F,7),O=O+P|0,J=Le(J^O,16),j=j+J|0,P=Le(P^j,12),O=O+P|0,J=Le(J^O,8),j=j+J|0,P=Le(P^j,7),N=N+k|0,W=Le(W^N,16),U=U+W|0,k=Le(k^U,12),N=N+k|0,W=Le(W^N,8),U=U+W|0,k=Le(k^U,7);let G=0;n[G++]=o+S|0,n[G++]=a+x|0,n[G++]=c+O|0,n[G++]=l+N|0,n[G++]=u+k|0,n[G++]=d+M|0,n[G++]=p+K|0,n[G++]=f+P|0,n[G++]=m+j|0,n[G++]=h+U|0,n[G++]=y+q|0,n[G++]=g+F|0,n[G++]=b+Q|0,n[G++]=v+J|0,n[G++]=_+W|0,n[G++]=w+z|0}function ont(t,e,r,n){let i=ws(t[0]),s=ws(t[1]),o=ws(t[2]),a=ws(t[3]),c=ws(e[0]),l=ws(e[1]),u=ws(e[2]),d=ws(e[3]),p=ws(e[4]),f=ws(e[5]),m=ws(e[6]),h=ws(e[7]),y=ws(r[0]),g=ws(r[1]),b=ws(r[2]),v=ws(r[3]);for(let w=0;w<20;w+=2)i=i+c|0,y=Le(y^i,16),p=p+y|0,c=Le(c^p,12),i=i+c|0,y=Le(y^i,8),p=p+y|0,c=Le(c^p,7),s=s+l|0,g=Le(g^s,16),f=f+g|0,l=Le(l^f,12),s=s+l|0,g=Le(g^s,8),f=f+g|0,l=Le(l^f,7),o=o+u|0,b=Le(b^o,16),m=m+b|0,u=Le(u^m,12),o=o+u|0,b=Le(b^o,8),m=m+b|0,u=Le(u^m,7),a=a+d|0,v=Le(v^a,16),h=h+v|0,d=Le(d^h,12),a=a+d|0,v=Le(v^a,8),h=h+v|0,d=Le(d^h,7),i=i+l|0,v=Le(v^i,16),m=m+v|0,l=Le(l^m,12),i=i+l|0,v=Le(v^i,8),m=m+v|0,l=Le(l^m,7),s=s+u|0,y=Le(y^s,16),h=h+y|0,u=Le(u^h,12),s=s+u|0,y=Le(y^s,8),h=h+y|0,u=Le(u^h,7),o=o+d|0,g=Le(g^o,16),p=p+g|0,d=Le(d^p,12),o=o+d|0,g=Le(g^o,8),p=p+g|0,d=Le(d^p,7),a=a+c|0,b=Le(b^a,16),f=f+b|0,c=Le(c^f,12),a=a+c|0,b=Le(b^a,8),f=f+b|0,c=Le(c^f,7);let _=0;n[_++]=i,n[_++]=s,n[_++]=o,n[_++]=a,n[_++]=y,n[_++]=g,n[_++]=b,n[_++]=v,Yu(n)}function Kfe(t,e,r,n,i){i!==void 0&&Dn(i,void 0,"AAD");let s=t(e,r,lnt),o=Rfe(n.length,i?i.length:0,!0),a=Lfe.create(s);i&&Ufe(a,i),Ufe(a,n),a.update(o);let c=a.digest();return Ll(s,o),c}var ant,cnt,Ufe,lnt,unt,XH,qfe=I(()=>{Mfe();jfe();z0();ant=Dfe(snt,{counterRight:!1,counterLength:8,extendNonceFn:ont,allowShortKeys:!1}),cnt=new Uint8Array(16),Ufe=(t,e)=>{t.update(e);let r=e.length%16;r&&t.update(cnt.subarray(r))},lnt=new Uint8Array(32);unt=t=>(e,r,n)=>({encrypt(s,o){let a=s.length;o=F0(a+16,o,!1),o.set(s);let c=o.subarray(0,-16);t(e,r,c,c,1);let l=Kfe(t,e,r,c,n);return o.set(l,a),Ll(l),o},decrypt(s,o){o=F0(s.length-16,o,!1);let a=s.subarray(0,-16),c=s.subarray(-16),l=Kfe(t,e,r,a,n);if(!Afe(c,l))throw Ll(l),new Error("invalid tag");return o.set(s.subarray(0,-16)),t(e,r,o,o,1),Ll(l),o}}),XH=kfe({blockSize:64,nonceLength:24,tagLength:16},unt(ant))});function dnt(t){if(!t.startsWith(zfe))return null;let e=4,r=t.indexOf("$",e);if(r===-1)return null;let n=parseInt(t.slice(e,r),10);return!Number.isInteger(n)||n<0?null:{version:n,ciphertext:t.slice(r+1)}}function pnt(t,e){return`${zfe}${t}$${e}`}async function Ffe(t,e){let r=await op("SHA-256").digest(t),n=Tfe(e);return VH(YH(XH)(new Uint8Array(r)).encrypt(n))}async function QH(t,e){let r=await op("SHA-256").digest(t),n=wfe(e),i=YH(XH)(new Uint8Array(r));return new TextDecoder().decode(i.decrypt(n))}var zfe,_C,EC,SC=I(()=>{b0();K0();q0();qfe();z0();zfe="$ba$";_C=async({key:t,data:e})=>{if(typeof t=="string")return Ffe(t,e);let r=t.keys.get(t.currentVersion);if(!r)throw new Error(`Secret version ${t.currentVersion} not found in keys`);let n=await Ffe(r,e);return pnt(t.currentVersion,n)},EC=async({key:t,data:e})=>{if(typeof t=="string")return QH(t,e);let r=dnt(e);if(r){let n=t.keys.get(r.version);if(!n)throw new Error(`Secret version ${r.version} not found in keys (key may have been retired)`);return QH(n,r.ciphertext)}if(t.legacySecret)return QH(t.legacySecret,e);throw new Error("Cannot decrypt legacy bare-hex payload: no legacy secret available. Set BETTER_AUTH_SECRET for backwards compatibility.")}});var Zs,eW=I(()=>{Zs=t=>{let e=(t.plugins??[]).reduce((d,p)=>{let f=p.schema;if(!f)return d;for(let[m,h]of Object.entries(f))d[m]={fields:{...d[m]?.fields,...h.fields},modelName:h.modelName||m};return d},{}),r=t.rateLimit?.storage==="database",n={rateLimit:{modelName:t.rateLimit?.modelName||"rateLimit",fields:{key:{type:"string",unique:!0,required:!0,fieldName:t.rateLimit?.fields?.key||"key"},count:{type:"number",required:!0,fieldName:t.rateLimit?.fields?.count||"count"},lastRequest:{type:"number",bigint:!0,required:!0,fieldName:t.rateLimit?.fields?.lastRequest||"lastRequest",defaultValue:()=>Date.now()}}}},{user:i,session:s,account:o,verification:a,...c}=e,l={verification:{modelName:t.verification?.modelName||"verification",fields:{identifier:{type:"string",required:!0,fieldName:t.verification?.fields?.identifier||"identifier",index:!0},value:{type:"string",required:!0,fieldName:t.verification?.fields?.value||"value"},expiresAt:{type:"date",required:!0,fieldName:t.verification?.fields?.expiresAt||"expiresAt"},createdAt:{type:"date",required:!0,defaultValue:()=>new Date,fieldName:t.verification?.fields?.createdAt||"createdAt"},updatedAt:{type:"date",required:!0,defaultValue:()=>new Date,onUpdate:()=>new Date,fieldName:t.verification?.fields?.updatedAt||"updatedAt"},...a?.fields,...t.verification?.additionalFields},order:4}},u={session:{modelName:t.session?.modelName||"session",fields:{expiresAt:{type:"date",required:!0,fieldName:t.session?.fields?.expiresAt||"expiresAt"},token:{type:"string",required:!0,fieldName:t.session?.fields?.token||"token",unique:!0},createdAt:{type:"date",required:!0,fieldName:t.session?.fields?.createdAt||"createdAt",defaultValue:()=>new Date},updatedAt:{type:"date",required:!0,fieldName:t.session?.fields?.updatedAt||"updatedAt",onUpdate:()=>new Date},ipAddress:{type:"string",required:!1,fieldName:t.session?.fields?.ipAddress||"ipAddress"},userAgent:{type:"string",required:!1,fieldName:t.session?.fields?.userAgent||"userAgent"},userId:{type:"string",fieldName:t.session?.fields?.userId||"userId",references:{model:t.user?.modelName||"user",field:"id",onDelete:"cascade"},required:!0,index:!0},...s?.fields,...t.session?.additionalFields},order:2}};return{user:{modelName:t.user?.modelName||"user",fields:{name:{type:"string",required:!0,fieldName:t.user?.fields?.name||"name",sortable:!0},email:{type:"string",unique:!0,required:!0,fieldName:t.user?.fields?.email||"email",sortable:!0},emailVerified:{type:"boolean",defaultValue:!1,required:!0,fieldName:t.user?.fields?.emailVerified||"emailVerified",input:!1},image:{type:"string",required:!1,fieldName:t.user?.fields?.image||"image"},createdAt:{type:"date",defaultValue:()=>new Date,required:!0,fieldName:t.user?.fields?.createdAt||"createdAt"},updatedAt:{type:"date",defaultValue:()=>new Date,onUpdate:()=>new Date,required:!0,fieldName:t.user?.fields?.updatedAt||"updatedAt"},...i?.fields,...t.user?.additionalFields},order:1},...!t.secondaryStorage||t.session?.storeSessionInDatabase?u:{},account:{modelName:t.account?.modelName||"account",fields:{accountId:{type:"string",required:!0,fieldName:t.account?.fields?.accountId||"accountId"},providerId:{type:"string",required:!0,fieldName:t.account?.fields?.providerId||"providerId"},userId:{type:"string",references:{model:t.user?.modelName||"user",field:"id",onDelete:"cascade"},required:!0,fieldName:t.account?.fields?.userId||"userId",index:!0},accessToken:{type:"string",required:!1,returned:!1,fieldName:t.account?.fields?.accessToken||"accessToken"},refreshToken:{type:"string",required:!1,returned:!1,fieldName:t.account?.fields?.refreshToken||"refreshToken"},idToken:{type:"string",required:!1,returned:!1,fieldName:t.account?.fields?.idToken||"idToken"},accessTokenExpiresAt:{type:"date",required:!1,returned:!1,fieldName:t.account?.fields?.accessTokenExpiresAt||"accessTokenExpiresAt"},refreshTokenExpiresAt:{type:"date",required:!1,returned:!1,fieldName:t.account?.fields?.refreshTokenExpiresAt||"refreshTokenExpiresAt"},scope:{type:"string",required:!1,fieldName:t.account?.fields?.scope||"scope"},password:{type:"string",required:!1,returned:!1,fieldName:t.account?.fields?.password||"password"},createdAt:{type:"date",required:!0,fieldName:t.account?.fields?.createdAt||"createdAt",defaultValue:()=>new Date},updatedAt:{type:"date",required:!0,fieldName:t.account?.fields?.updatedAt||"updatedAt",onUpdate:()=>new Date},...o?.fields,...t.account?.additionalFields},order:3},...!t.secondaryStorage||t.verification?.storeInDatabase?l:{},...c,...r?n:{}}}});var Gh,Ju,gv=I(()=>{Gh=le(require("zod"),1),Ju=Gh.object({id:Gh.string(),createdAt:Gh.date().default(()=>new Date),updatedAt:Gh.date().default(()=>new Date)})});var Va,Bfe,Hfe=I(()=>{gv();Va=le(require("zod"),1),Bfe=Ju.extend({providerId:Va.string(),accountId:Va.string(),userId:Va.coerce.string(),accessToken:Va.string().nullish(),refreshToken:Va.string().nullish(),idToken:Va.string().nullish(),accessTokenExpiresAt:Va.date().nullish(),refreshTokenExpiresAt:Va.date().nullish(),scope:Va.string().nullish(),password:Va.string().nullish()})});var Vh,Wfe,$fe=I(()=>{Vh=le(require("zod"),1),Wfe=Vh.object({key:Vh.string(),count:Vh.number(),lastRequest:Vh.number()})});var jf,Gfe,Vfe=I(()=>{gv();jf=le(require("zod"),1),Gfe=Ju.extend({userId:jf.coerce.string(),expiresAt:jf.date(),token:jf.string(),ipAddress:jf.string().nullish(),userAgent:jf.string().nullish()})});var yv,Yfe,Jfe=I(()=>{gv();yv=le(require("zod"),1),Yfe=Ju.extend({email:yv.string().transform(t=>t.toLowerCase()),emailVerified:yv.boolean().default(!1),name:yv.string(),image:yv.string().nullish()})});var H0,Zfe,Xfe=I(()=>{gv();H0=le(require("zod"),1),Zfe=Ju.extend({value:H0.string(),expiresAt:H0.date(),identifier:H0.string()})});var tW={};ui(tW,{accountSchema:()=>Bfe,coreSchema:()=>Ju,getAuthTables:()=>Zs,rateLimitSchema:()=>Wfe,sessionSchema:()=>Gfe,userSchema:()=>Yfe,verificationSchema:()=>Zfe});var cp=I(()=>{eW();gv();Hfe();$fe();Vfe();Jfe();Xfe()});function Xs(t,e){if(!t||!e)return t;let r=Object.entries(e).filter(([,{returned:n}])=>n===!1).map(([n])=>n);return Object.entries(structuredClone(t)).filter(([n])=>!r.includes(n)).reduce((n,[i,s])=>({...n,[i]:s}),{})}var wC=I(()=>{});function Uf(t,e,r){let n=`${e}:${r}`;rW.has(t)||rW.set(t,new Map);let i=rW.get(t);if(i.has(n))return i.get(n);let s=r==="output"?Zs(t)[e]?.fields??{}:{},o=e==="user"||e==="session"||e==="account"?t[e]?.additionalFields:void 0,a={...s,...o??{}};for(let c of t.plugins||[])c.schema&&c.schema[e]&&(a={...a,...c.schema[e].fields});return i.set(n,a),a}function Br(t,e){return Xs(e,Uf(t,"user","output"))}function Wi(t,e){return Xs(e,Uf(t,"session","output"))}function TC(t,e){let{accessToken:r,refreshToken:n,idToken:i,accessTokenExpiresAt:s,refreshTokenExpiresAt:o,password:a,...c}=Xs(e,Uf(t,"account","output"));return c}function bv(t,e){let r=e.action||"create",n=e.fields,i=Object.create(null);for(let s in n){if(s in t){if(n[s].input===!1){if(n[s].defaultValue!==void 0&&r!=="update"){i[s]=n[s].defaultValue;continue}if(t[s])throw D.from("BAD_REQUEST",{...ae.FIELD_NOT_ALLOWED,message:`${s} is not allowed to be set`});continue}if(n[s].validator?.input&&t[s]!==void 0){let o=n[s].validator.input["~standard"].validate(t[s]);if(o instanceof Promise)throw D.from("INTERNAL_SERVER_ERROR",ae.ASYNC_VALIDATION_NOT_SUPPORTED);if("issues"in o&&o.issues)throw D.from("BAD_REQUEST",{...ae.VALIDATION_ERROR,message:o.issues[0]?.message||"Validation Error"});i[s]=o.value;continue}if(n[s].transform?.input&&t[s]!==void 0){i[s]=n[s].transform?.input(t[s]);continue}i[s]=t[s];continue}if(n[s].defaultValue!==void 0&&r==="create"){if(typeof n[s].defaultValue=="function"){i[s]=n[s].defaultValue();continue}i[s]=n[s].defaultValue;continue}if(n[s].required&&r==="create")throw D.from("BAD_REQUEST",{...ae.MISSING_FIELD,message:`${s} is required`})}return i}function vv(t,e={},r){return bv(e,{fields:Uf(t,"user","input"),action:r})}function Qfe(t,e){let r=Uf(t,"user","input");return bv(e||{},{fields:r})}function eme(t,e){return bv(e,{fields:Uf(t,"account","input")})}function xC(t,e,r){return bv(e,{fields:Uf(t,"session","input"),action:r})}function IC(t){let e=Uf(t,"session","input"),r={};for(let n in e)e[n].defaultValue!==void 0&&(r[n]=typeof e[n].defaultValue=="function"?e[n].defaultValue():e[n].defaultValue);return r}function AC(t,e){if(!e)return t;for(let r in e){let n=e[r]?.modelName;n&&(t[r].modelName=n);for(let i in t[r].fields){let s=e[r]?.fields?.[i];s&&(t[r].fields[i].fieldName=s)}}return t}var rW,jl=I(()=>{cp();rt();wC();rW=new WeakMap});var xo,Yh=I(()=>{xo=(t,e="ms")=>new Date(Date.now()+(e==="sec"?t*1e3:t))});function _v(t){return!!t&&(typeof t=="object"||typeof t=="function")&&typeof t.then=="function"}var OC=I(()=>{});function mnt(t){let e=fnt.exec(t);if(!e||e[4]&&e[1])throw new TypeError(`Invalid time string format: "${t}". Use formats like "7d", "30m", "1 hour", etc.`);let r=parseFloat(e[2]),n=e[3].toLowerCase(),i;switch(n){case"years":case"year":case"yrs":case"yr":case"y":i=r*315576e5;break;case"months":case"month":case"mo":i=r*2592e6;break;case"weeks":case"week":case"w":i=r*6048e5;break;case"days":case"day":case"d":i=r*864e5;break;case"hours":case"hour":case"hrs":case"hr":case"h":i=r*36e5;break;case"minutes":case"minute":case"mins":case"min":case"m":i=r*6e4;break;case"seconds":case"second":case"secs":case"sec":case"s":i=r*1e3;break;default:throw new TypeError(`Unknown time unit: "${n}"`)}return e[1]==="-"||e[4]==="ago"?-i:i}function tme(t){return Math.round(mnt(t)/1e3)}var fnt,rme=I(()=>{fnt=/^(\+|\-)? ?(\d+|\d+\.\d+) ?(seconds?|secs?|s|minutes?|mins?|m|hours?|hrs?|h|days?|d|weeks?|w|months?|mo|years?|yrs?|y)(?: (ago|from now))?$/i});var nme,ime=I(()=>{nme="__Secure-"});function sme(t){if(typeof t=="string"&&hnt.test(t)){let e=new Date(t);if(!isNaN(e.getTime()))return e}return t}function nW(t){if(t==null)return t;if(typeof t=="string")return sme(t);if(t instanceof Date)return t;if(Array.isArray(t))return t.map(nW);if(typeof t=="object"){let e={};for(let r of Object.keys(t))e[r]=nW(t[r]);return e}return t}function lr(t){try{return typeof t!="string"?t==null?null:nW(t):JSON.parse(t,(e,r)=>sme(r))}catch(e){return De.error("Error parsing JSON",{error:e}),null}}var hnt,lp=I(()=>{bs();hnt=/^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}(?:\.\d+)?Z$/});function gnt(t){let e=t.headers?.get("cookie");if(!e)return{};let r={},n=e.split("; ");for(let i of n){let[s,...o]=i.split("=");s&&o.length>0&&(r[s]=o.join("="))}return r}function ome(t){let e=t.split("."),r=e[e.length-1],n=parseInt(r||"0",10);return isNaN(n)?0:n}function ynt(t,e){let r={},n=gnt(e);for(let[i,s]of Object.entries(n))i.startsWith(t)&&(r[i]=s);return r}function bnt(t){return Object.keys(t).sort((e,r)=>ome(e)-ome(r)).map(e=>t[e]).join("")}function vnt(t,e,r,n){let i=Math.ceil(e.value.length/iW);if(i===1)return r[e.name]=e.value,[e];let s=[];for(let o=0;o<i;o++){let a=`${e.name}.${o}`,c=o*iW,l=e.value.substring(c,c+iW);s.push({...e,name:a,value:l}),r[a]=l}return n.debug(`CHUNKING_${t.toUpperCase()}_COOKIE`,{message:`${t} cookie exceeds allowed ${oW} bytes.`,emptyCookieSize:sW,valueSize:e.value.length,chunkCount:i,chunks:s.map(o=>o.value.length+sW)}),s}function ame(t,e){let r={};for(let n in t)r[n]={name:n,value:"",attributes:{...e,maxAge:0}};return r}function CC(t,e){let r=t.getCookie(e);if(r)return r;let n=[],i=t.headers?.get("cookie");if(!i)return null;let s={},o=i.split("; ");for(let a of o){let[c,...l]=a.split("=");c&&l.length>0&&(s[c]=l.join("="))}for(let[a,c]of Object.entries(s))if(a.startsWith(e+".")){let l=a.split(".").at(-1),u=parseInt(l||"0",10);isNaN(u)||n.push({index:u,value:c})}return n.length>0?(n.sort((a,c)=>a.index-c.index),n.map(a=>a.value).join("")):null}async function Kf(t,e){let r=t.context.authCookies.accountData,n={maxAge:300,...r.attributes},i=await gC(e,t.context.secretConfig,"better-auth-account",n.maxAge);if(i.length>oW){let s=kC(r.name,n,t),o=s.chunk(i,n);s.setCookies(o)}else{let s=kC(r.name,n,t);if(s.hasChunks()){let o=s.clean();s.setCookies(o)}t.setCookie(r.name,i,n)}}async function Ev(t){let e=CC(t,t.context.authCookies.accountData.name);if(e){let r=lr(await j0(e,t.context.secretConfig,"better-auth-account"));if(r)return r}return null}var Jh,oW,sW,iW,cme,RC,kC,lme,W0=I(()=>{U0();lp();Jh=le(require("zod"),1),oW=4096,sW=200,iW=oW-sW;cme=t=>(e,r,n)=>{let i=ynt(e,n),s=n.context.logger;return{getValue(){return bnt(i)},hasChunks(){return Object.keys(i).length>0},chunk(o,a){let c=ame(i,r);for(let d in i)delete i[d];let l=c,u=vnt(t,{name:e,value:o,attributes:{...r,...a}},i,s);for(let d of u)l[d.name]=d;return Object.values(l)},clean(){let o=ame(i,r);for(let a in i)delete i[a];return Object.values(o)},setCookies(o){for(let a of o)n.setCookie(a.name,a.value,a.attributes)}}},RC=cme("Session"),kC=cme("Account");lme=Jh.optional(Jh.object({disableCookieCache:Jh.coerce.boolean().meta({description:"Disable cookie cache and fetch session from database"}).optional(),disableRefresh:Jh.coerce.boolean().meta({description:"Disable session refresh. Useful for checking session status, without updating the session"}).optional()}))});var aW,_nt,cW,lW=I(()=>{aW=new Map,_nt=new TextEncoder,cW={decode:(t,e="utf-8")=>(aW.has(e)||aW.set(e,new TextDecoder(e)),aW.get(e).decode(t)),encode:_nt.encode}});var Ent,uW,ume=I(()=>{Ent="0123456789abcdef",uW={encode:t=>{if(typeof t=="string"&&(t=new TextEncoder().encode(t)),t.byteLength===0)return"";let e=new Uint8Array(t),r="";for(let n of e)r+=n.toString(16).padStart(2,"0");return r},decode:t=>{if(!t)return"";if(typeof t=="string"){if(t.length%2!==0)throw new Error("Invalid hexadecimal string");if(!new RegExp(`^[${Ent}]+$`).test(t))throw new Error("Invalid hexadecimal string");let e=new Uint8Array(t.length/2);for(let r=0;r<t.length;r+=2)e[r/2]=parseInt(t.slice(r,r+2),16);return new TextDecoder().decode(e)}return new TextDecoder().decode(t)}}});var NC,dW=I(()=>{ume();pa();K0();NC=(t="SHA-256",e="none")=>{let r={importKey:async(n,i)=>Ml().importKey("raw",typeof n=="string"?new TextEncoder().encode(n):n,{name:"HMAC",hash:{name:t}},!1,[i]),sign:async(n,i)=>{typeof n=="string"&&(n=await r.importKey(n,"sign"));let s=await Ml().sign("HMAC",n,typeof i=="string"?new TextEncoder().encode(i):i);return e==="hex"?uW.encode(s):e==="base64"||e==="base64url"||e==="base64urlnopad"?da.encode(s,{padding:e!=="base64urlnopad"}):s},verify:async(n,i,s)=>(typeof n=="string"&&(n=await r.importKey(n,"verify")),e==="hex"&&(s=uW.decode(s)),(e==="base64"||e==="base64url"||e==="base64urlnopad")&&(s=await Hi.decode(s)),Ml().verify("HMAC",n,typeof s=="string"?new TextEncoder().encode(s):s,typeof i=="string"?new TextEncoder().encode(i):i))};return r}});function $0(t){let e=typeof t.baseURL=="string"?t.baseURL:void 0,r=typeof t.baseURL=="object"&&t.baseURL!==null?t.baseURL.protocol:void 0,n=(t.advanced?.useSecureCookies!==void 0?t.advanced?.useSecureCookies:r==="https"||r!=="http"&&(e?e.startsWith("https://"):xf))?nme:"",i=!!t.advanced?.crossSubDomainCookies?.enabled,s=i?t.advanced?.crossSubDomainCookies?.domain||(e?new URL(e).hostname:void 0):void 0;if(i&&!s&&!Wa(t.baseURL))throw new me("baseURL is required when crossSubdomainCookies are enabled.");function o(a,c={}){let l=t.advanced?.cookiePrefix||"better-auth",u=t.advanced?.cookies?.[a]?.name||`${l}.${a}`,d=t.advanced?.cookies?.[a]?.attributes??{};return{name:`${n}${u}`,attributes:{secure:!!n,sameSite:"lax",path:"/",httpOnly:!0,...i?{domain:s}:{},...t.advanced?.defaultCookieAttributes,...c,...d}}}return o}function PC(t){let e=$0(t),r=e("session_token",{maxAge:t.session?.expiresIn||tme("7d")}),n=e("session_data",{maxAge:t.session?.cookieCache?.maxAge||300}),i=e("account_data",{maxAge:t.session?.cookieCache?.maxAge||300}),s=e("dont_remember");return{sessionToken:{name:r.name,attributes:r.attributes},sessionData:{name:n.name,attributes:n.attributes},dontRememberToken:{name:s.name,attributes:s.attributes},accountData:{name:i.name,attributes:i.attributes}}}async function G0(t,e,r){if(!t.context.options.session?.cookieCache?.enabled)return;let n=Xs(e.session,t.context.options.session?.additionalFields),i=Br(t.context.options,e.user),s=t.context.options.session?.cookieCache?.version,o="1";if(s){if(typeof s=="string")o=s;else if(typeof s=="function"){let p=s(e.session,e.user);o=_v(p)?await p:p}}let a={session:n,user:i,updatedAt:Date.now(),version:o},c={...t.context.authCookies.sessionData.attributes,maxAge:r?void 0:t.context.authCookies.sessionData.attributes.maxAge},l=xo(c.maxAge||60,"sec").getTime(),u=t.context.options.session?.cookieCache?.strategy||"compact",d;if(u==="jwe"?d=await gC(a,t.context.secretConfig,"better-auth-session",c.maxAge||300):u==="jwt"?d=await hC(a,t.context.secret,c.maxAge||300):d=da.encode(JSON.stringify({session:a,expiresAt:l,signature:await NC("SHA-256","base64urlnopad").sign(t.context.secret,JSON.stringify({...a,expiresAt:l}))}),{padding:!1}),d.length>4093){let p=RC(t.context.authCookies.sessionData.name,c,t),f=p.chunk(d,c);p.setCookies(f)}else{let p=RC(t.context.authCookies.sessionData.name,c,t);if(p.hasChunks()){let f=p.clean();p.setCookies(f)}t.setCookie(t.context.authCookies.sessionData.name,d,c)}if(t.context.options.account?.storeAccountCookie){let p=await Ev(t);p&&await Kf(t,p)}}async function jr(t,e,r,n){let i=await t.getSignedCookie(t.context.authCookies.dontRememberToken.name,t.context.secret);r=r!==void 0?r:!!i;let s=t.context.authCookies.sessionToken.attributes,o=r?void 0:t.context.sessionConfig.expiresIn;await t.setSignedCookie(t.context.authCookies.sessionToken.name,e.session.token,t.context.secret,{...s,maxAge:o,...n}),r&&await t.setSignedCookie(t.context.authCookies.dontRememberToken.name,"true",t.context.secret,t.context.authCookies.dontRememberToken.attributes),await G0(t,e,r),t.context.setNewSession(e)}function fa(t,e){t.setCookie(e.name,"",{...e.attributes,maxAge:0})}function qf(t,e){if(fa(t,t.context.authCookies.sessionToken),fa(t,t.context.authCookies.sessionData),t.context.options.account?.storeAccountCookie){fa(t,t.context.authCookies.accountData);let i=kC(t.context.authCookies.accountData.name,t.context.authCookies.accountData.attributes,t),s=i.clean();i.setCookies(s)}t.context.oauthConfig.storeStateStrategy==="cookie"&&fa(t,t.context.createAuthCookie("oauth_state"));let r=RC(t.context.authCookies.sessionData.name,t.context.authCookies.sessionData.attributes,t),n=r.clean();r.setCookies(n),e||fa(t,t.context.authCookies.dontRememberToken)}var Io=I(()=>{Kh();U0();jl();Yh();OC();rme();ime();W0();vs();rt();wC();pa();lW();dW()});async function pme(t,e,r){let n=tp(32);if(t.context.oauthConfig.storeStateStrategy==="cookie"){let o={...e,oauthState:n},a=await _C({key:t.context.secretConfig,data:JSON.stringify(o)}),c=t.context.createAuthCookie(r?.cookieName??"oauth_state",{maxAge:600});return t.setCookie(c.name,a,c.attributes),{state:n,codeVerifier:e.codeVerifier}}let i=t.context.createAuthCookie(r?.cookieName??"state",{maxAge:300});await t.setSignedCookie(i.name,n,t.context.secret,i.attributes);let s=new Date;if(s.setMinutes(s.getMinutes()+10),!await t.context.internalAdapter.createVerificationValue({value:JSON.stringify({...e,oauthState:n}),identifier:n,expiresAt:s}))throw new Zu("Unable to create verification. Make sure the database adapter is properly working and there is a verification table in the database",{code:"state_generation_error"});return{state:n,codeVerifier:e.codeVerifier}}async function fme(t,e,r){let n=t.context.oauthConfig.storeStateStrategy,i;if(n==="cookie"){let s=t.context.createAuthCookie(r?.cookieName??"oauth_state"),o=t.getCookie(s.name);if(!o)throw new Zu("State mismatch: auth state cookie not found",{code:"state_mismatch",details:{state:e}});try{let a=await EC({key:t.context.secretConfig,data:o});i=dme.parse(JSON.parse(a))}catch(a){throw new Zu("State invalid: Failed to decrypt or parse auth state",{code:"state_invalid",details:{state:e},cause:a})}if(!i.oauthState||i.oauthState!==e)throw new Zu("State mismatch: OAuth state parameter does not match stored state",{code:"state_security_mismatch",details:{state:e}});fa(t,s)}else{let s=await t.context.internalAdapter.findVerificationValue(e);if(!s)throw new Zu("State mismatch: verification not found",{code:"state_mismatch",details:{state:e}});if(i=dme.parse(JSON.parse(s.value)),i.oauthState!==void 0&&i.oauthState!==e)throw new Zu("State mismatch: OAuth state parameter does not match stored state",{code:"state_security_mismatch",details:{state:e}});let o=t.context.createAuthCookie(r?.cookieName??"state"),a=await t.getSignedCookie(o.name,t.context.secret);if(!(r?.skipStateCookieCheck??t.context.oauthConfig.skipStateCookieCheck)&&(!a||a!==e))throw new Zu("State mismatch: State not persisted correctly",{code:"state_security_mismatch",details:{state:e}});fa(t,o),await t.context.internalAdapter.deleteVerificationByIdentifier(e)}if(i.expiresAt<Date.now())throw new Zu("Invalid state: request expired",{code:"state_mismatch",details:{expiresAt:i.expiresAt}});return i}var xs,dme,Zu,mme=I(()=>{b0();SC();Io();rt();xs=le(require("zod"),1),dme=xs.looseObject({callbackURL:xs.string(),codeVerifier:xs.string(),errorURL:xs.string().optional(),newUserURL:xs.string().optional(),expiresAt:xs.number(),oauthState:xs.string().optional(),link:xs.object({email:xs.string(),userId:xs.coerce.string()}).optional(),requestSignUp:xs.boolean().optional()}),Zu=class extends me{code;details;constructor(t,e){super(t,e),this.code=e.code,this.details=e.details}}});function Zh(){return globalThis[V0]||(globalThis[V0]={version:pW,epoch:1,context:Snt},Y0=globalThis[V0]),Y0=globalThis[V0],Y0.version!==pW&&(Y0.version=pW,Y0.epoch++),globalThis[V0]}function fW(){return Zh().version}var V0,Y0,Snt,pW,J0=I(()=>{V0=Symbol.for("better-auth:global"),Y0=null,Snt={},pW="1.6.10"});async function Sv(){let t=await wnt;if(t===null)throw new Error("getAsyncLocalStorage is only available in server code");return t}var wnt,DC=I(()=>{wnt=import("node:async_hooks").then(t=>t.AsyncLocalStorage).catch(t=>{if("AsyncLocalStorage"in globalThis)return globalThis.AsyncLocalStorage;if(typeof window<"u")return null;throw console.warn("[better-auth] Warning: AsyncLocalStorage is not available in this environment. Some features may not work as expected."),console.warn("[better-auth] Please read more about this warning at https://better-auth.com/docs/installation#mount-handler"),console.warn("[better-auth] If you are using Cloudflare Workers, please see: https://developers.cloudflare.com/workers/configuration/compatibility-flags/#nodejs-compatibility-flag"),t})});async function up(){let t=(await hme()).getStore();if(!t)throw new Error("No auth context found. Please make sure you are calling this function within a `runWithEndpointContext` callback.");return t}async function wv(t,e){return(await hme()).run(t,e)}var hme,mW=I(()=>{J0();DC();hme=async()=>{let t=Zh();if(!t.context.endpointContextAsyncStorage){let e=await Sv();t.context.endpointContextAsyncStorage=new e}return t.context.endpointContextAsyncStorage}});async function yW(){return(await gW()).getStore()!==void 0}async function hW(){let t=(await gW()).getStore();if(!t)throw new Error("No request state found. Please make sure you are calling this function within a `runWithRequestState` callback.");return t}async function bW(t,e){return(await gW()).run(t,e)}function Z0(t){let e=Object.freeze({});return{get ref(){return e},async get(){let r=await hW();if(!r.has(e)){let n=await t();return r.set(e,n),n}return r.get(e)},async set(r){(await hW()).set(e,r)}}}var gW,gme=I(()=>{J0();DC();gW=async()=>{let t=Zh();if(!t.context.requestStateAsyncStorage){let e=await Sv();t.context.requestStateAsyncStorage=new e}return t.context.requestStateAsyncStorage}});var MC,Ue,vW,X0,Xh,yme=I(()=>{J0();DC();MC=async()=>{let t=Zh();if(!t.context.adapterAsyncStorage){let e=await Sv();t.context.adapterAsyncStorage=new e}return t.context.adapterAsyncStorage},Ue=async t=>MC().then(e=>e.getStore()?.adapter||t).catch(()=>t),vW=async(t,e)=>{let r=!1;return MC().then(async n=>{r=!0;let i=[],s,o,a=!1;try{s=await n.run({adapter:t,pendingHooks:i},e)}catch(c){o=c,a=!0}for(let c of i)await c();if(a)throw o;return s}).catch(n=>{if(!r)return e();throw n})},X0=async(t,e)=>{let r=!0;return MC().then(async n=>{r=!0;let i=[],s,o,a=!1;try{s=await t.transaction(async c=>n.run({adapter:c,pendingHooks:i},e))}catch(c){a=!0,o=c}for(let c of i)await c();if(a)throw o;return s}).catch(n=>{if(!r)return e();throw n})},Xh=async t=>MC().then(e=>{let r=e.getStore();if(r)r.pendingHooks.push(t);else return t()}).catch(()=>t())});var Xu=I(()=>{J0();mW();gme();yme()});var tZt,_W,bme=I(()=>{Xu();({get:tZt,set:_W}=Z0(()=>null))});async function LC(t,e,r){let n=t.body?.callbackURL||t.context.options.baseURL;if(!n)throw D.from("BAD_REQUEST",ae.CALLBACK_URL_REQUIRED);let i=tp(128),s={...r||{},callbackURL:n,codeVerifier:i,errorURL:t.body?.errorCallbackURL,newUserURL:t.body?.newUserCallbackURL,link:e,expiresAt:Date.now()+600*1e3,requestSignUp:t.body?.requestSignUp};await _W(s);try{return pme(t,s)}catch(o){throw t.context.logger.error("Failed to create verification",o),new D("INTERNAL_SERVER_ERROR",{message:"Unable to create verification",cause:o})}}async function vme(t){let e=t.query.state||t.body?.state,r=t.context.options.onAPIError?.errorURL||`${t.context.baseURL}/error`,n;try{n=await fme(t,e)}catch(i){throw t.context.logger.error("Failed to parse state",i),i instanceof Zu&&i.code==="state_security_mismatch"?t.redirect(`${r}?error=state_mismatch`):t.redirect(`${r}?error=please_restart_the_process`)}return n.errorURL||(n.errorURL=r),n&&await _W(n),n}var jC=I(()=>{b0();bme();mme();rt()});var Tv,UC=I(()=>{Tv={scope:"server"}});async function _me(t,e){let r=t.headers.get("content-type")||"",n=r.toLowerCase();if(t.body){if(e&&e.length>0&&!e.some(i=>{let s=n.split(";")[0].trim(),o=i.toLowerCase().trim();return s===o||s.includes(o)}))throw n?new ua(415,{message:`Content-Type "${r}" is not allowed. Allowed types: ${e.join(", ")}`,code:"UNSUPPORTED_MEDIA_TYPE"}):new ua(415,{message:`Content-Type is required. Allowed types: ${e.join(", ")}`,code:"UNSUPPORTED_MEDIA_TYPE"});if(Tnt.test(n))return await t.json();if(n.includes("application/x-www-form-urlencoded")){let i=await t.formData(),s={};return i.forEach((o,a)=>{s[a]=o.toString()}),s}if(n.includes("multipart/form-data")){let i=await t.formData(),s={};return i.forEach((o,a)=>{s[a]=o}),s}return n.includes("text/plain")?await t.text():n.includes("application/octet-stream")?await t.arrayBuffer():n.includes("application/pdf")||n.includes("image/")||n.includes("video/")?await t.blob():n.includes("application/stream")||t.body instanceof ReadableStream?t.body:await t.text()}}function dp(t){return t instanceof ua||t?.name==="APIError"}function Eme(t){try{return t.includes("%")?decodeURIComponent(t):t}catch{return t}}async function Sme(t){try{return{data:await t,error:null}}catch(e){return{data:null,error:e}}}function KC(t){return t instanceof Request||Object.prototype.toString.call(t)==="[object Request]"}var Tnt,Qh=I(()=>{If();Tnt=/^application\/([a-z0-9.+-]*\+)?json/i});function xnt(t){if(t===void 0)return!1;let e=typeof t;return e==="string"||e==="number"||e==="boolean"||e===null?!0:e!=="object"?!1:Array.isArray(t)?!0:t.buffer?!1:t.constructor&&t.constructor.name==="Object"||typeof t.toJSON=="function"}function Int(t,e,r){let n=0,i=new WeakMap;return JSON.stringify(t,(o,a)=>{if(typeof a=="bigint")return a.toString();if(typeof a=="object"&&a!==null){if(i.has(a))return`[Circular ref-${i.get(a)}]`;i.set(a,n++)}return e?e(o,a):a},r)}function Ant(t){return!t||typeof t!="object"?!1:"_flag"in t&&t._flag==="json"}function EW(t){for(let e of Ont)t.delete(e)}function Ul(t,e){if(t instanceof Response){if(e?.headers){let i=new Headers(e.headers);EW(i),i.forEach((s,o)=>{t.headers.set(o,s)})}return t}if(Ant(t)){let i=t.body,s=t.routerResponse;if(s instanceof Response)return s;let o=new Headers;i | |||
There was a problem hiding this comment.
Security fix applied to a compiled bundle, not the source
worker-service.cjs is a minified, bundled artifact — not a hand-authored source file. The code containing the ep() / x-forwarded-host logic originates from the better-auth library (visible from symbol names like BETTER_AUTH_URL, y0, Qd). Patching the bundle directly means: (1) the fix will be silently overwritten the next time the project is rebuilt; (2) the upstream source still contains the vulnerability; and (3) reviewers cannot easily audit the change or reason about correctness. The fix should be applied in the original source (or as an upstream patch to better-auth) and the bundle regenerated.
Prompt To Fix With AI
This is a comment left during a code review.
Path: plugin/scripts/worker-service.cjs
Line: 787
Comment:
**Security fix applied to a compiled bundle, not the source**
`worker-service.cjs` is a minified, bundled artifact — not a hand-authored source file. The code containing the `ep()` / `x-forwarded-host` logic originates from the `better-auth` library (visible from symbol names like `BETTER_AUTH_URL`, `y0`, `Qd`). Patching the bundle directly means: (1) the fix will be silently overwritten the next time the project is rebuilt; (2) the upstream source still contains the vulnerability; and (3) reviewers cannot easily audit the change or reason about correctness. The fix should be applied in the original source (or as an upstream patch to `better-auth`) and the bundle regenerated.
How can I resolve this? If you propose a fix, please make it concise.
Summary
Fix high severity security issue in
plugin/scripts/worker-service.cjs.Vulnerability
V-003plugin/scripts/worker-service.cjs:1Description: The ep() function reads x-forwarded-host and x-forwarded-proto headers to construct the base URL when no explicit baseURL is configured. The y0() validation only checks hostname format (valid syntax), not whether the host is in an allowlist. An attacker who can inject these headers — either by accessing the application directly or via a misconfigured proxy — can cause the application to generate OAuth redirect URIs, email verification links, and password reset links pointing to an attacker-controlled domain.
Changes
plugin/scripts/worker-service.cjsVerification
Automated security fix by OrbisAI Security