@tempoxyz/id 0.0.1 → 0.0.2
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/app/server/.vite/manifest.json +65 -65
- package/dist/app/server/assets/Grant-D_tun0mF.js.map +1 -1
- package/dist/app/server/assets/authorize-DXYo-K2n-B-6vqhvc.js +56 -0
- package/dist/app/server/assets/authorize-DXYo-K2n-B-6vqhvc.js.map +1 -0
- package/dist/app/server/assets/core-FSS9-r35.js +56 -0
- package/dist/app/server/assets/core-FSS9-r35.js.map +1 -0
- package/dist/app/server/assets/default-u_dwuiYb-Bby14ucv.js +2 -0
- package/dist/app/server/assets/{default-u_dwuiYb-DOrMMcg9.js.map → default-u_dwuiYb-Bby14ucv.js.map} +1 -1
- package/dist/app/server/assets/{dist-CoH0hD1s.js → dist-B9KiBJYw.js} +2 -2
- package/dist/app/server/assets/{dist-CoH0hD1s.js.map → dist-B9KiBJYw.js.map} +1 -1
- package/dist/app/server/assets/{dist-DcICI3fd.js → dist-CU1NXSiz.js} +2 -2
- package/dist/app/server/assets/{dist-DcICI3fd.js.map → dist-CU1NXSiz.js.map} +1 -1
- package/dist/app/server/assets/dist-CetH4JSY.js +1 -0
- package/dist/app/server/assets/{effect-QlVUlMFu-mXPkuQTb.js → effect-QlVUlMFu-Cm-eTtaO.js} +2 -2
- package/dist/app/server/assets/{effect-QlVUlMFu-mXPkuQTb.js.map → effect-QlVUlMFu-Cm-eTtaO.js.map} +1 -1
- package/dist/app/server/assets/factory-g3i_Ffi5.js +5 -0
- package/dist/app/server/assets/{factory-dvoOlKer.js.map → factory-g3i_Ffi5.js.map} +1 -1
- package/dist/app/server/assets/get-id-field-BpOAoqqI.js +6 -0
- package/dist/app/server/assets/get-id-field-BpOAoqqI.js.map +1 -0
- package/dist/app/server/assets/{index-CLddUTqr-CC33CMvS.js → index-CLddUTqr-CmgkbWi9.js} +2 -2
- package/dist/app/server/assets/{index-CLddUTqr-CC33CMvS.js.map → index-CLddUTqr-CmgkbWi9.js.map} +1 -1
- package/dist/app/server/assets/{index-DZEfthgZ-Ec2MMQ_e.js → index-DZEfthgZ-BnPmps9O.js} +2 -2
- package/dist/app/server/assets/{index-DZEfthgZ-Ec2MMQ_e.js.map → index-DZEfthgZ-BnPmps9O.js.map} +1 -1
- package/dist/app/server/assets/kysely-adapter-B8VoPArC.js +1 -0
- package/dist/app/server/assets/{schema-check-oLqvHR8y.js → schema-check-Bgwl1v0_.js} +2 -2
- package/dist/app/server/assets/{schema-check-oLqvHR8y.js.map → schema-check-Bgwl1v0_.js.map} +1 -1
- package/dist/app/server/assets/{sury-CWZTCd75-CDaOS2oM.js → sury-CWZTCd75-Bd_PzqCV.js} +2 -2
- package/dist/app/server/assets/{sury-CWZTCd75-CDaOS2oM.js.map → sury-CWZTCd75-Bd_PzqCV.js.map} +1 -1
- package/dist/app/server/assets/{valibot--1zFm7rT-CIKoH3MS.js → valibot--1zFm7rT-Dd2aEhWG.js} +2 -2
- package/dist/app/server/assets/{valibot--1zFm7rT-CIKoH3MS.js.map → valibot--1zFm7rT-Dd2aEhWG.js.map} +1 -1
- package/dist/app/server/assets/{valibot-D_HTw1Gn-BdPyLkXt.js → valibot-D_HTw1Gn-C1l3va6F.js} +2 -2
- package/dist/app/server/assets/{valibot-D_HTw1Gn-BdPyLkXt.js.map → valibot-D_HTw1Gn-C1l3va6F.js.map} +1 -1
- package/dist/app/server/assets/{zod-Bwrt9trS-BezI5Gi1.js → zod-Bwrt9trS-Dry2w0in.js} +2 -2
- package/dist/app/server/assets/{zod-Bwrt9trS-BezI5Gi1.js.map → zod-Bwrt9trS-Dry2w0in.js.map} +1 -1
- package/dist/app/server/assets/{zod-DSgpEGAE-DZ7M_Q33.js → zod-DSgpEGAE-BZMP86UA.js} +2 -2
- package/dist/app/server/assets/{zod-DSgpEGAE-DZ7M_Q33.js.map → zod-DSgpEGAE-BZMP86UA.js.map} +1 -1
- package/dist/app/server/index.js +35 -35
- package/dist/app/server/index.js.map +1 -1
- package/dist/client/Auth.d.ts +1 -1
- package/dist/client/Auth.d.ts.map +1 -1
- package/dist/client/Auth.js.map +1 -1
- package/dist/client/Decorator.d.ts +3 -1
- package/dist/client/Decorator.d.ts.map +1 -1
- package/dist/client/Decorator.js +1 -0
- package/dist/client/Decorator.js.map +1 -1
- package/dist/client/actions/passkey.d.ts +63 -2
- package/dist/client/actions/passkey.d.ts.map +1 -1
- package/dist/client/actions/passkey.js +121 -3
- package/dist/client/actions/passkey.js.map +1 -1
- package/dist/internal/Apps.d.ts +14 -0
- package/dist/internal/Apps.d.ts.map +1 -1
- package/dist/internal/Apps.js +14 -2
- package/dist/internal/Apps.js.map +1 -1
- package/dist/internal/Auth.d.ts +7 -0
- package/dist/internal/Auth.d.ts.map +1 -1
- package/dist/internal/Auth.js +2 -1
- package/dist/internal/Auth.js.map +1 -1
- package/dist/internal/Authorize.d.ts.map +1 -1
- package/dist/internal/Authorize.js +13 -13
- package/dist/internal/Authorize.js.map +1 -1
- package/dist/internal/ErrorResponse.d.ts +5 -0
- package/dist/internal/ErrorResponse.d.ts.map +1 -1
- package/dist/internal/ErrorResponse.js +8 -0
- package/dist/internal/ErrorResponse.js.map +1 -1
- package/dist/internal/KeyAuthorization.d.ts.map +1 -1
- package/dist/internal/KeyAuthorization.js +28 -28
- package/dist/internal/KeyAuthorization.js.map +1 -1
- package/dist/internal/Owner.d.ts +16 -0
- package/dist/internal/Owner.d.ts.map +1 -1
- package/dist/internal/Owner.js.map +1 -1
- package/dist/internal/Passkey.d.ts +66 -4
- package/dist/internal/Passkey.d.ts.map +1 -1
- package/dist/internal/Passkey.js +66 -30
- package/dist/internal/Passkey.js.map +1 -1
- package/dist/internal/Privy.d.ts +27 -0
- package/dist/internal/Privy.d.ts.map +1 -1
- package/dist/internal/Privy.js +82 -0
- package/dist/internal/Privy.js.map +1 -1
- package/dist/internal/TempoAccount.d.ts +57 -0
- package/dist/internal/TempoAccount.d.ts.map +1 -1
- package/dist/internal/TempoAccount.js +118 -5
- package/dist/internal/TempoAccount.js.map +1 -1
- package/dist/internal/owners/Privy.d.ts.map +1 -1
- package/dist/internal/owners/Privy.js +11 -2
- package/dist/internal/owners/Privy.js.map +1 -1
- package/package.json +1 -1
- package/src/api/account.ts +140 -103
- package/src/api/authenticate.ts +48 -51
- package/src/api/authorize.ts +35 -36
- package/src/api/device.ts +20 -23
- package/src/api/health.ts +1 -2
- package/src/api/lib/AccountStep.ts +75 -0
- package/src/api/lib/Auth.ts +6 -0
- package/src/api/lib/Cors.ts +3 -0
- package/src/api/lib/KeySigner.ts +1 -1
- package/src/api/oauth.ts +23 -22
- package/src/client/Auth.ts +1 -0
- package/src/client/Decorator.ts +6 -1
- package/src/client/actions/passkey.ts +197 -3
- package/src/internal/Apps.ts +26 -2
- package/src/internal/Auth.ts +4 -0
- package/src/internal/Authorize.ts +13 -15
- package/src/internal/ErrorResponse.ts +10 -0
- package/src/internal/KeyAuthorization.ts +28 -31
- package/src/internal/OpenApi.ts +35 -0
- package/src/internal/Owner.ts +16 -0
- package/src/internal/Passkey.ts +99 -34
- package/src/internal/Privy.ts +128 -0
- package/src/internal/TempoAccount.ts +221 -7
- package/src/internal/owners/Privy.ts +19 -6
- package/dist/app/server/assets/authorize-DXYo-K2n-rmQQ42x1.js +0 -56
- package/dist/app/server/assets/authorize-DXYo-K2n-rmQQ42x1.js.map +0 -1
- package/dist/app/server/assets/core-BBrZXfrB.js +0 -56
- package/dist/app/server/assets/core-BBrZXfrB.js.map +0 -1
- package/dist/app/server/assets/default-u_dwuiYb-DOrMMcg9.js +0 -2
- package/dist/app/server/assets/dist-CR6FW-yS.js +0 -1
- package/dist/app/server/assets/factory-dvoOlKer.js +0 -5
- package/dist/app/server/assets/get-id-field-OwLpfjj2.js +0 -6
- package/dist/app/server/assets/get-id-field-OwLpfjj2.js.map +0 -1
- package/dist/app/server/assets/kysely-adapter-B8tQwTcu.js +0 -1
|
@@ -1,56 +0,0 @@
|
|
|
1
|
-
import{r as e}from"./rolldown-runtime-BWaJ3C7D.js";import{Zt as t}from"./core-BBrZXfrB.js";import{$ as n,At as r,B as i,Ct as a,D as o,Dt as s,E as c,F as l,G as u,H as d,Ht as f,I as p,J as m,K as h,L as g,P as _,Q as v,R as y,St as b,T as x,Tt as S,U as C,V as w,Vt as T,W as E,Y as D,Z as O,_t as k,a as A,at as j,b as M,bt as N,d as P,dt as F,et as I,f as L,h as R,it as ee,j as te,jt as ne,kt as re,l as ie,lt as z,m as ae,mt as oe,o as se,or as ce,ot as le,p as ue,q as de,rt as fe,st as pe,t as me,tr as he,tt as ge,vt as _e,w as ve,wt as ye,x as B,xt as be,yt as xe,z as Se}from"./get-id-field-OwLpfjj2.js";import{a as Ce}from"./schema-check-oLqvHR8y.js";function we(e){return f(le,e)}function Te(e){return T(fe,e)}var Ee=Object.defineProperty,De=(e,t)=>{let n={};for(var r in e)Ee(n,r,{get:e[r],enumerable:!0});return t||Ee(n,Symbol.toStringTag,{value:`Module`}),n},Oe=`ba_iat`,ke=`ba_pl`,Ae=`ba_param`;function je(e){let t=new URLSearchParams,n=[...e.entries()].sort(([e,t],[n,r])=>e<n?-1:e>n?1:t<r?-1:+(t>r));for(let[e,r]of n)t.append(e,r);return t}function Me(e){e.delete(Ae);let t=[...new Set([...e.keys(),Ae])].sort();for(let n of t)e.append(Ae,n)}function Ne(e){let t=new URLSearchParams(e).get(Oe);if(!t)return null;let n=Number(t);return!Number.isFinite(n)||n<=0?null:new Date(n)}function Pe(e){let t=new URLSearchParams(e),n=t.get(`ba_pl`)??void 0;for(let e of[`sig`,`exp`,Oe,Ae,ke])t.delete(e);return{query:t.toString(),signedQueryIssuedAt:Ne(e)??void 0,postLoginClearedForSession:n}}var Fe=class{oHash;iHash;blockLen;outputLen;canXOF=!1;finished=!1;destroyed=!1;constructor(e,t){if(de(e),u(t,void 0,`key`),this.iHash=e.create(),typeof this.iHash.update!=`function`)throw Error(`expected Hash instance`);this.blockLen=this.iHash.blockLen,this.outputLen=this.iHash.outputLen;let n=this.blockLen,r=new Uint8Array(n);r.set(t.length>n?e.create().update(t).digest():t);for(let e=0;e<r.length;e++)r[e]^=54;this.iHash.update(r),this.oHash=e.create();for(let e=0;e<r.length;e++)r[e]^=106;this.oHash.update(r),O(r)}update(e){return h(this),this.iHash.update(e),this}digestInto(e){h(this),D(e,this),this.finished=!0;let t=e.subarray(0,this.outputLen);this.iHash.digestInto(t),this.oHash.update(t),this.oHash.digestInto(t),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:t,iHash:n,finished:r,destroyed:i,blockLen:a,outputLen:o,canXOF:s}=this;return e=e,e.finished=r,e.destroyed=i,e.blockLen=a,e.outputLen=o,e.canXOF=s,e.oHash=t._cloneInto(e.oHash),e.iHash=n._cloneInto(e.iHash),e}clone(){return this._cloneInto()}destroy(){this.destroyed=!0,this.oHash.destroy(),this.iHash.destroy()}},Ie=(()=>{let e=((e,t,n)=>new Fe(e,t).update(n).digest());return e.create=(e,t)=>new Fe(e,t),e})(),Le=Uint8Array.of(0),Re=Uint8Array.of();function ze(e,t,n,r=32,i){de(e),m(r,`length`),u(t,void 0,`prk`);let a=e.outputLen;if(t.length<a)throw Error(`"prk" must be at least HashLen octets`);if(r>255*a)throw Error(`Length must be <= 255*HashLen`);let o=Math.ceil(r/a);if(n===void 0?n=Re:u(n,void 0,`info`),!o)return i&&O(t),new Uint8Array;let s=i&&o===1?t:new Uint8Array(o*a),{iHash:c,oHash:l}=Ie.create(e,t),d=i?t:new Uint8Array(a),f=o>1?i?.iHash||e.create():void 0;for(let e=0;e<o-1;e++){Le[0]=e+1;let t=c._cloneInto(f);e&&t.update(d),t.update(n).update(Le).digestInto(d),l._cloneInto(f).update(d).digestInto(d),s.set(d,a*e)}if(Le[0]=o,o>1&&c.update(d),c.update(n).update(Le).digestInto(d),l.update(d).digestInto(d),s.set(d,a*(o-1)),c.destroy(),l.destroy(),f?.destroy(),d!==s&&O(d),O(Le),r===s.length)return s;let p=s.slice(0,r);return O(s),p}var Be=(e,t,n,r,i)=>{de(e),n===void 0&&(n=new Uint8Array(e.outputLen));let a=Ie.create(e,n).update(t);return ze(e,a.digest(),r,i,a)},Ve=e=>e/2**32|0,He=e=>e>>>0;function Ue(e,t,n,r){let i=Ve(n),a=He(n);e.setUint32(t,r?a:i,r),e.setUint32(t+4,r?i:a,r)}function We(e,t,n){return e&t^~e&n}function Ge(e,t,n){return e&t^e&n^t&n}var Ke=class{blockLen;outputLen;canXOF=!1;padOffset;isLE;buffer;view;finished=!1;length=0;pos=0;destroyed=!1;constructor(e,t,r,i){this.blockLen=e,this.outputLen=t,this.padOffset=r,this.isLE=i,this.buffer=new Uint8Array(e),this.view=n(this.buffer)}update(e){h(this),u(e);let{view:t,buffer:r,blockLen:i}=this,a=e.length,o=!1;for(let s=0;s<a;){let c=Math.min(i-this.pos,a-s);if(c===i){let t=n(e);for(;i<=a-s;s+=i)this.process(t,s);o=!0}else r.set(s===0&&c===a?e:e.subarray(s,s+c),this.pos),this.pos+=c,s+=c,this.pos===i&&(this.process(t,0),this.pos=0,o=!0)}return this.length+=e.length,o&&this.roundClean(),this}digestInto(e){h(this),D(e,this),this.finished=!0;let{buffer:t,view:r,blockLen:i,isLE:a}=this,{pos:o}=this;t[o++]=128,t.fill(0,o),this.padOffset>i-o&&(this.process(r,0),t.fill(0)),Ue(r,i-8,this.length*8,a),this.process(r,0),this.roundClean();let s=e===t?r:n(e),c=this.outputLen,l=c/4,u=this.get();if(c%4||l>u.length)throw Error(`invalid outputLen`);for(let e=0;e<l;e++)s.setUint32(4*e,u[e],a)}digest(){let{buffer:e,outputLen:t}=this;this.digestInto(e);let n=e.slice(0,t);return this.destroy(),n}_cloneIntoMeta(e){let{buffer:t,length:n,finished:r,destroyed:i,pos:a}=this;return e.destroyed=i,e.finished=r,e.length=n,e.pos=a,a&&e.buffer.set(t),e}clone(){return this._cloneInto()}},qe=Uint32Array.from([1779033703,3144134277,1013904242,2773480762,1359893119,2600822924,528734635,1541459225]),Je=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]),Ye=new Uint32Array(64),Xe=class extends Ke{A=0;B=0;C=0;D=0;E=0;F=0;G=0;H=0;constructor(e,t){super(64,e,8,!1),this.A=t[0]|0,this.B=t[1]|0,this.C=t[2]|0,this.D=t[3]|0,this.E=t[4]|0,this.F=t[5]|0,this.G=t[6]|0,this.H=t[7]|0}get(){let{A:e,B:t,C:n,D:r,E:i,F:a,G:o,H:s}=this;return[e,t,n,r,i,a,o,s]}set(e,t,n,r,i,a,o,s){this.A=e|0,this.B=t|0,this.C=n|0,this.D=r|0,this.E=i|0,this.F=a|0,this.G=o|0,this.H=s|0}_cloneInto(e){return(e||=new this.constructor).set(...this.get()),this._cloneIntoMeta(e)}process(e,t){for(let n=0;n<16;n++,t+=4)Ye[n]=e.getUint32(t,!1);for(let e=16;e<64;e++){let t=Ye[e-15],n=Ye[e-2],r=ge(t,7)^ge(t,18)^t>>>3,i=ge(n,17)^ge(n,19)^n>>>10;Ye[e]=i+Ye[e-7]+r+Ye[e-16]|0}let{A:n,B:r,C:i,D:a,E:o,F:s,G:c,H:l}=this;for(let e=0;e<64;e++){let t=ge(o,6)^ge(o,11)^ge(o,25),u=l+t+We(o,s,c)+Je[e]+Ye[e]|0,d=(ge(n,2)^ge(n,13)^ge(n,22))+Ge(n,r,i)|0;l=c,c=s,s=o,o=a+u|0,a=i,i=r,r=n,n=u+d|0}n=n+this.A|0,r=r+this.B|0,i=i+this.C|0,a=a+this.D|0,o=o+this.E|0,s=s+this.F|0,c=c+this.G|0,l=l+this.H|0,this.set(n,r,i,a,o,s,c,l)}roundClean(){O(Ye)}destroy(){this.destroyed=!0,this.set(0,0,0,0,0,0,0,0),O(this.buffer)}},Ze=class extends Xe{constructor(){super(32,qe)}},Qe=v(()=>new Ze,I(1)),$e=new TextEncoder,et=new TextDecoder,tt=new TextDecoder(`utf-8`,{fatal:!0}),nt=2**32;function rt(...e){let t=e.reduce((e,{length:t})=>e+t,0),n=new Uint8Array(t),r=0;for(let t of e)n.set(t,r),r+=t.length;return n}function it(e,t,n){if(t<0||t>=nt)throw RangeError(`value must be >= 0 and <= ${nt-1}. Received ${t}`);e.set([t>>>24,t>>>16,t>>>8,t&255],n)}function at(e){let t=Math.floor(e/nt),n=e%nt,r=new Uint8Array(8);return it(r,t,0),it(r,n,4),r}function ot(e){let t=new Uint8Array(4);return it(t,e),t}var st=/[^\x00-\x7f]/;function ct(e){if(typeof e==`string`&&e.length>=128){if(st.test(e))throw TypeError(`non-ASCII string encountered in encode()`);return $e.encode(e)}let t=new Uint8Array(e.length);for(let n=0;n<e.length;n++){let r=e.charCodeAt(n);if(r>127)throw TypeError(`non-ASCII string encountered in encode()`);t[n]=r}return t}function lt(e,t=!1){if(Uint8Array.prototype.toBase64)return e.toBase64({alphabet:t?`base64url`:`base64`,omitPadding:t});let n=32768,r=[];for(let t=0;t<e.length;t+=n)r.push(String.fromCharCode.apply(null,e.subarray(t,t+n)));let i=btoa(r.join(``));return t?i.replace(/=/g,``).replace(/\+/g,`-`).replace(/\//g,`_`):i}function ut(e,t=!1){if(Uint8Array.fromBase64)return Uint8Array.fromBase64(e,{alphabet:t?`base64url`:`base64`});if(t){if(e.includes(`+`)||e.includes(`/`))throw TypeError(`Invalid base64url`);e=e.replace(/-/g,`+`).replace(/_/g,`/`)}let n=atob(e),r=new Uint8Array(n.length);for(let e=0;e<n.length;e++)r[e]=n.charCodeAt(e);return r}async function dt(e,t){let n=`SHA-${e.slice(-3)}`;return new Uint8Array(await crypto.subtle.digest(n,t))}var V=class extends Error{static code=`ERR_JOSE_GENERIC`;code=`ERR_JOSE_GENERIC`;constructor(e,t){super(e,t),this.name=this.constructor.name,Error.captureStackTrace?.(this,this.constructor)}},ft=class extends V{static code=`ERR_JWT_CLAIM_VALIDATION_FAILED`;code=`ERR_JWT_CLAIM_VALIDATION_FAILED`;claim;reason;payload;constructor(e,t,n=`unspecified`,r=`unspecified`){super(e,{cause:{claim:n,reason:r,payload:t}}),this.claim=n,this.reason=r,this.payload=t}},pt=class extends V{static code=`ERR_JWT_EXPIRED`;code=`ERR_JWT_EXPIRED`;claim;reason;payload;constructor(e,t,n=`unspecified`,r=`unspecified`){super(e,{cause:{claim:n,reason:r,payload:t}}),this.claim=n,this.reason=r,this.payload=t}},mt=class extends V{static code=`ERR_JOSE_ALG_NOT_ALLOWED`;code=`ERR_JOSE_ALG_NOT_ALLOWED`},H=class extends V{static code=`ERR_JOSE_NOT_SUPPORTED`;code=`ERR_JOSE_NOT_SUPPORTED`},ht=class extends V{static code=`ERR_JWE_DECRYPTION_FAILED`;code=`ERR_JWE_DECRYPTION_FAILED`;constructor(e=`decryption operation failed`,t){super(e,t)}},U=class extends V{static code=`ERR_JWE_INVALID`;code=`ERR_JWE_INVALID`},W=class extends V{static code=`ERR_JWS_INVALID`;code=`ERR_JWS_INVALID`},gt=class extends V{static code=`ERR_JWT_INVALID`;code=`ERR_JWT_INVALID`},_t=class extends V{static code=`ERR_JWK_INVALID`;code=`ERR_JWK_INVALID`},vt=class extends V{static code=`ERR_JWKS_INVALID`;code=`ERR_JWKS_INVALID`},yt=class extends V{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`,t){super(e,t)}},bt=class extends V{[Symbol.asyncIterator]=async function*(){};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`,t){super(e,t)}},xt=class extends V{static code=`ERR_JWKS_TIMEOUT`;code=`ERR_JWKS_TIMEOUT`;constructor(e=`request timed out`,t){super(e,t)}},St=class extends V{static code=`ERR_JWS_SIGNATURE_VERIFICATION_FAILED`;code=`ERR_JWS_SIGNATURE_VERIFICATION_FAILED`;constructor(e=`signature verification failed`,t){super(e,t)}},Ct=`The input to be decoded is not correctly encoded.`;function wt(e){try{return ut(typeof e==`string`?e:et.decode(e),!0)}catch(e){throw TypeError(Ct,{cause:e})}}function G(e){return lt(typeof e==`string`?$e.encode(e):e,!0)}function Tt(e,t){if(!(e instanceof Uint8Array))throw TypeError(`${t} must be an instance of Uint8Array`)}function Et(e){if(typeof e!=`object`||!e||Object.prototype.toString.call(e)!==`[object Object]`)return!1;let t=Object.getPrototypeOf(e);return t===null||Object.getPrototypeOf(t)===null}function Dt(e){return Et(e)&&Array.isArray(e.keys)&&Array.from(e.keys).every(Et)}function Ot(...e){let t=new Set;for(let n of e)if(n)for(let e of Object.keys(n)){if(t.has(e))return!1;t.add(e)}return!0}function kt(e,t){if(e!==void 0)throw TypeError(`${t} can only be called once`)}function At(e,t,n){try{return wt(e)}catch{throw new n(`Failed to base64url decode the ${t}`)}}function jt(e,t,n){try{return ct(e)}catch{throw new n(`The ${t} is not a valid base64url string`)}}function Mt(e,t,n){let r;try{r=JSON.parse(tt.decode(wt(e)))}catch{throw new t(n)}if(!Et(r))throw new t(n);return r}var Nt={__proto__:null,b64:!0},Pt={__proto__:null};function Ft(e,t){if(t!==void 0&&(!Array.isArray(t)||t.some(e=>typeof e!=`string`)))throw TypeError(`"${e}" option must be an array of strings`);return t===void 0?void 0:new Set(t)}function It(e,t){let{crit:n}=t??{};if(Array.isArray(n)&&new Set(n).size!==n.length)throw new e(`"crit" (Critical) Header Parameter MUST NOT contain duplicate values`)}function Lt(e,t,n,r,i){if(i.crit!==void 0&&r?.crit===void 0)throw new e(`"crit" (Critical) Header Parameter MUST be integrity protected`);if(!r||r.crit===void 0)return[];if(!Array.isArray(r.crit)||r.crit.length===0||r.crit.some(e=>typeof e!=`string`||e.length===0))throw new e(`"crit" (Critical) Header Parameter MUST be an array of non-empty strings when present`);let a=n===void 0?t:{__proto__:null,...n,...t};for(let t of r.crit){if(!(t in a))throw new H(`Extension Header Parameter "${t}" is not recognized`);if(!Object.hasOwn(i,t)||i[t]===void 0)throw new e(`Extension Header Parameter "${t}" is missing`);if(a[t]&&(!Object.hasOwn(r,t)||r[t]===void 0))throw new e(`Extension Header Parameter "${t}" MUST be integrity protected`)}return r.crit}function Rt(e,t){if(t.includes(`b64`)){let t=e.b64;if(typeof t!=`boolean`)throw new W(`The "b64" (base64url-encode payload) Header Parameter must be a boolean`);return t}return!0}function zt(e,t){let n,r;try{n=JSON.stringify(t),r=JSON.parse(n)}catch(t){throw new e(`JOSE Header is not valid JSON`,{cause:t})}if(!Et(r))throw new e(`JOSE Header is not a JSON object`);return[r,n]}var Bt=e=>e[Symbol.toStringTag],Vt=(e,t,n)=>{let{alg:r}=e;if(t.use!==void 0){let e=n===`sign`||n===`verify`?`sig`:`enc`;if(t.use!==e)throw TypeError(`Invalid key for this operation, its "use" must be "${e}" when present`)}if(t.alg!==void 0&&t.alg!==r)throw TypeError(`Invalid key for this operation, its "alg" must be "${r}" when present`);if(Array.isArray(t.key_ops)){let r=n===`encrypt`||n===`decrypt`?e.ops?.[n===`encrypt`?0:1]:n;if(r&&!t.key_ops.includes(r))throw TypeError(`Invalid key for this operation, its "key_ops" must include "${r}" when present`)}};async function Ht(e,t,n){let{alg:r,secret:i}=e,a=n===`decrypt`||n===`sign`;if(i&&t instanceof Uint8Array)return t;let o,s;if(Et(t)){if(o=rn(t),typeof o.kty!=`string`)throw Zt(r,t,i);if(!(i?o.kty===`oct`&&typeof o.k==`string`:o.kty!==`oct`&&(a?o.kty===`AKP`&&typeof o.priv==`string`||typeof o.d==`string`:o.d===void 0&&o.priv===void 0)))throw TypeError(i?`JSON Web Key for symmetric algorithms must have JWK "kty" (Key Type) equal to "oct" and the JWK "k" (Key Value) present`:`JSON Web Key for this operation must be a ${a?`private`:`public`} JWK`);if(Vt(e,o,n),o.kty===`oct`)return wt(o.k);if(!Object.isFrozen(t)){let{key_ops:e}=t;Array.isArray(e)&&Object.freeze(e),Object.freeze(t)}}else{if(!Jt(t))throw Zt(r,t,i);let e=i?`secret`:a?`private`:`public`;if(t.type!==e&&(i||[`secret`,`public`,`private`].includes(t.type)))throw TypeError(`${Bt(t)} instances must be of type "${e}" for the ${r} algorithm`);if(Kt(t))return t;if(s=t,s.type===`secret`)return s.export()}Ut||=new WeakMap;let c=t,l=Ut.get(c);if(l?.[r])return l[r];if(l||Ut.set(c,l={}),s&&typeof s.toCryptoKey==`function`){let t=s.type===`public`,n=Wt[s.asymmetricKeyDetails?.namedCurve],i=e.resolve?.({crv:n,asymmetricKeyType:s.asymmetricKeyType})??e.subtle;return l[r]=s.toCryptoKey(i,t,e.usages[+!t])}return o??=s.export({format:`jwk`}),o.alg=r,l[r]=await on(e,o)}var Ut,Wt={__proto__:null,prime256v1:`P-256`,secp384r1:`P-384`,secp521r1:`P-521`};function Gt(e){if(!Kt(e))throw Error(`CryptoKey instance expected`)}var Kt=e=>{if(e?.[Symbol.toStringTag]===`CryptoKey`)return!0;try{return e instanceof CryptoKey}catch{return!1}},qt=e=>e?.[Symbol.toStringTag]===`KeyObject`,Jt=e=>Kt(e)||qt(e);function Yt(e,t,...n){if(n.length>2){let t=n.pop();e+=`one of type ${n.join(`, `)}, or ${t}.`}else n.length===2?e+=`one of type ${n[0]} or ${n[1]}.`:e+=`of type ${n[0]}.`;return t==null?e+=` Received ${t}`:typeof t==`function`&&t.name?e+=` Received function ${t.name}`:typeof t==`object`&&t&&t.constructor?.name&&(e+=` Received an instance of ${t.constructor.name}`),e}var Xt=(e,...t)=>Yt(`Key must be `,e,...t);function Zt(e,t,n){let r=[`CryptoKey`,`KeyObject`,`JSON Web Key`];return n&&r.push(`Uint8Array`),TypeError(Yt(`Key for the ${e} algorithm must be `,t,...r))}var Qt=(e,t=`algorithm.name`)=>TypeError(`CryptoKey does not support this operation, its ${t} must be ${e}`);function $t(e,t){if(t&&!e.usages.includes(t))throw TypeError(`CryptoKey does not support this operation, its usages must include ${t}.`)}function en(e,t){let{modulusLength:n}=t.algorithm;if(typeof n!=`number`||n<2048)throw TypeError(`${e} requires key modulusLength to be 2048 bits or larger`)}function tn(e,t,n){let r=e.algorithm;if(r.name!==t.name)throw Qt(t.name);if(t.hash&&r.hash?.name!==t.hash)throw Qt(t.hash,`algorithm.hash`);if(t.namedCurve&&r.namedCurve!==t.namedCurve)throw Qt(t.namedCurve,`algorithm.namedCurve`);if(t.length!==void 0&&r.length!==t.length)throw Qt(t.length,`algorithm.length`);$t(e,n)}function nn(e){return{__proto__:null,...e}}function rn(e){let t=nn(e);if(t.ext!==void 0&&typeof t.ext!=`boolean`)throw TypeError(`"ext" (Extractable) Parameter must be a boolean`);if(t.key_ops!==void 0){let e=t.key_ops,n=Array.isArray(e)?[...e]:void 0;if(!n||n.some(e=>typeof e!=`string`)||new Set(n).size!==n.length)throw TypeError(`"key_ops" (Key Operations) Parameter must be an array of unique strings`);t.key_ops=n}return t}function an(e){if(e!==void 0&&typeof e!=`boolean`)throw TypeError(`"extractable" option must be a boolean`);return e}async function on(e,t,n){if(!e.kty.includes(t.kty))throw new H(`Invalid or unsupported JWK "alg" (Algorithm) Parameter value`);let r=e.resolve?.({kty:t.kty,crv:t.crv})??e.subtle,i=!!(t.d||t.priv),a={...t,ext:n??t.ext};return a.kty!==`AKP`&&delete a.alg,delete a.use,crypto.subtle.importKey(`jwk`,a,r,a.ext??!i,t.key_ops??e.usages[+!!i])}async function sn(e,t,n,r=!1){return e instanceof Uint8Array&&(e=await crypto.subtle.importKey(`raw`,e,t,r,[n])),tn(e,t,n),e}var cn=e=>crypto.getRandomValues(new Uint8Array(e.cekBits>>3));function ln(e,t){let n=e.byteLength<<3;if(n!==t)throw new U(`Invalid Content Encryption Key length. Expected ${t} bits, got ${n} bits`)}var un=e=>crypto.getRandomValues(new Uint8Array(e.ivBits>>3));function dn(e,t){if(t.length<<3!==e.ivBits)throw new U(`Invalid Initialization Vector length`)}async function fn(e,t,n){if(!(t instanceof Uint8Array))throw TypeError(Xt(t,`Uint8Array`));let r=e.cekBits>>1;return[await crypto.subtle.importKey(`raw`,t.subarray(r>>3),`AES-CBC`,!1,[n]),await crypto.subtle.importKey(`raw`,t.subarray(0,r>>3),{hash:`SHA-${r<<1}`,name:`HMAC`},!1,[`sign`]),r]}async function pn(e,t,n){return new Uint8Array((await crypto.subtle.sign(`HMAC`,e,t)).slice(0,n>>3))}async function mn(e,t,n,r,i){let[a,o,s]=await fn(e,n,`encrypt`),c=new Uint8Array(await crypto.subtle.encrypt({iv:r,name:`AES-CBC`},a,t));return{ciphertext:c,tag:await pn(o,rt(i,r,c,at(i.length*8)),s),iv:r}}async function hn(e,t){let n={name:`HMAC`,hash:`SHA-256`},r=await crypto.subtle.generateKey(n,!1,[`sign`,`verify`]),i=await crypto.subtle.sign(n,r,e);return crypto.subtle.verify(n,r,i,t)}async function gn(e,t,n,r,i,a){let[o,s,c]=await fn(e,t,`decrypt`),l=await pn(s,rt(a,r,n,at(a.length*8)),c);try{if(await hn(i,l))return new Uint8Array(await crypto.subtle.decrypt({iv:r,name:`AES-CBC`},o,n))}catch{}throw new ht}async function _n(e,t,n,r,i){if(!Kt(n)&&!(n instanceof Uint8Array))throw TypeError(Xt(n,`CryptoKey`,`KeyObject`,`Uint8Array`,`JSON Web Key`));if(r?dn(e,r):r=un(e),n instanceof Uint8Array&&ln(n,e.cekBits),e.cbc)return mn(e,t,n,r,i);let a=await sn(n,e.subtle,`encrypt`),o=new Uint8Array(await crypto.subtle.encrypt({additionalData:i,iv:r,name:`AES-GCM`,tagLength:128},a,t));return{ciphertext:o.subarray(0,-16),tag:o.subarray(-16),iv:r}}async function vn(e,t,n,r,i,a){if(!Kt(t)&&!(t instanceof Uint8Array))throw TypeError(Xt(t,`CryptoKey`,`KeyObject`,`Uint8Array`,`JSON Web Key`));if(!r)throw new U(`JWE Initialization Vector missing`);if(!i)throw new U(`JWE Authentication Tag missing`);if(!e.cbc&&i.length!==16)throw new U(`Invalid Authentication Tag length`);if(dn(e,r),t instanceof Uint8Array&&ln(t,e.cekBits),e.cbc)return gn(e,t,n,r,i,a);let o=await sn(t,e.subtle,`decrypt`);try{return new Uint8Array(await crypto.subtle.decrypt({additionalData:a,iv:r,name:`AES-GCM`,tagLength:128},o,rt(n,i)))}catch{throw new ht}}function yn(e){let t={__proto__:null};for(let n in e)t[n]={...e[n],alg:n};return t}var bn=[[`encrypt`,`wrapKey`],[`decrypt`,`unwrapKey`]],xn=[[],[`deriveBits`]],Sn=[[],[]];function Cn(e){return{kty:[`RSA`],mode:`key-encryption`,subtle:{name:`RSA-OAEP`,hash:`SHA-${e}`},usages:bn,ops:[`wrapKey`,`unwrapKey`]}}function wn(e){return{kty:[`EC`,`OKP`],mode:e,subtle:{name:`ECDH`},resolve:({kty:e,crv:t,asymmetricKeyType:n})=>{if(t===`X25519`||n===`x25519`)return{name:`X25519`};if(e===`OKP`)throw new H(`Invalid or unsupported JWK "alg" (Algorithm) Parameter value`);return{name:`ECDH`,namedCurve:t}},usages:xn,ops:[void 0,`deriveBits`]}}function Tn(e,t=!1){return{kty:[`oct`],mode:`key-wrapping`,secret:!0,subtle:{name:t?`AES-GCM`:`AES-KW`,length:e},usages:Sn,ops:t?[`encrypt`,`decrypt`]:[`wrapKey`,`unwrapKey`]}}function En(){return{kty:[`oct`],mode:`key-wrapping`,secret:!0,subtle:{name:`PBKDF2`},usages:Sn,ops:[`deriveBits`,`deriveBits`]}}var Dn=yn({dir:{kty:[`oct`],mode:`direct-encryption`,secret:!0,subtle:{name:`AES-GCM`},usages:Sn,ops:[`encrypt`,`decrypt`]},"RSA-OAEP":Cn(1),"RSA-OAEP-256":Cn(256),"RSA-OAEP-384":Cn(384),"RSA-OAEP-512":Cn(512),"ECDH-ES":wn(`direct-key-agreement`),"ECDH-ES+A128KW":wn(`key-agreement-with-key-wrapping`),"ECDH-ES+A192KW":wn(`key-agreement-with-key-wrapping`),"ECDH-ES+A256KW":wn(`key-agreement-with-key-wrapping`),A128KW:Tn(128),A192KW:Tn(192),A256KW:Tn(256),A128GCMKW:Tn(128,!0),A192GCMKW:Tn(192,!0),A256GCMKW:Tn(256,!0),"PBES2-HS256+A128KW":En(),"PBES2-HS384+A192KW":En(),"PBES2-HS512+A256KW":En()}),On=[`encrypt`,`decrypt`];function kn(e,t=!1){return{kty:[`oct`],secret:!0,subtle:{name:t?`AES-CBC`:`AES-GCM`,length:e},usages:Sn,ops:On,cekBits:e,ivBits:t?128:96,cbc:t}}var An=yn({A128GCM:kn(128),A192GCM:kn(192),A256GCM:kn(256),"A128CBC-HS256":kn(256,!0),"A192CBC-HS384":kn(384,!0),"A256CBC-HS512":kn(512,!0)});function jn(e,t){throw new H(`Invalid or unsupported "${e}" (JWE ${t}) header value`)}function Mn(e){return(typeof e==`string`?Dn[e]:void 0)??jn(`alg`,`Algorithm`)}function Nn(e){return e.mode===`key-wrapping`||e.mode===`key-encryption`||e.mode===`key-agreement-with-key-wrapping`}function Pn(e){return(typeof e==`string`?An[e]:void 0)??jn(`enc`,`Encryption Algorithm`)}function Fn(e,t){if(e.algorithm.name!==`ECDH`&&e.algorithm.name!==`X25519`)throw TypeError(`CryptoKey does not support this operation, its algorithm.name must be ECDH or X25519`);$t(e,t)}async function In(e,t,n){let r=await sn(t,Mn(e).subtle,`wrapKey`,!0),i=await crypto.subtle.importKey(`raw`,n,{hash:`SHA-256`,name:`HMAC`},!0,[`sign`]);return new Uint8Array(await crypto.subtle.wrapKey(`raw`,i,r,`AES-KW`))}async function Ln(e,t,n){let r=await sn(t,Mn(e).subtle,`unwrapKey`,!0),i=await crypto.subtle.unwrapKey(`raw`,n,r,`AES-KW`,{hash:`SHA-256`,name:`HMAC`},!0,[`sign`]);return new Uint8Array(await crypto.subtle.exportKey(`raw`,i))}function Rn(e,t,n){tn(t,Mn(e).subtle,n),en(e,t)}async function zn(e,t,n,r){if(!(e instanceof Uint8Array)||e.length<8)throw new U(`PBES2 Salt Input must be 8 or more octets`);if(!Number.isSafeInteger(n)||Math.sign(n)!==1)throw new U(`PBES2 Count Input must be a positive integer`);let i=rt(ct(t),Uint8Array.of(0),e),a=parseInt(t.slice(13,16),10),o={hash:`SHA-${t.slice(8,11)}`,iterations:n,name:`PBKDF2`,salt:i},s=await sn(r,Mn(t).subtle,`deriveBits`);return new Uint8Array(await crypto.subtle.deriveBits(o,s,a))}function Bn(e){return rt(ot(e.length),e)}async function Vn(e,t,n){let r=t>>3,i=Math.ceil(r/32),a=new Uint8Array(i*32);for(let t=1;t<=i;t++){let r=await dt(`sha256`,rt(ot(t),e,n));a.set(r,(t-1)*32)}return a.slice(0,r)}async function Hn(e,t,n,r,i=new Uint8Array,a=new Uint8Array){Fn(e),Fn(t,`deriveBits`);let o=rt(Bn(ct(n)),Bn(i),Bn(a),ot(r));return Vn(new Uint8Array(await crypto.subtle.deriveBits({name:e.algorithm.name,public:e},t,e.algorithm.name===`X25519`?256:Math.ceil(parseInt(e.algorithm.namedCurve.slice(-3),10)/8)<<3)),r,o)}function Un(e){Gt(e);let t=e.algorithm.namedCurve;if(t!==`P-256`&&t!==`P-384`&&t!==`P-521`&&e.algorithm.name!==`X25519`)throw new H(`ECDH with the provided key is not allowed or not supported by your javascript runtime`)}function Wn(e,t){let n=e[t];if(n!==void 0){if(typeof n!=`string`)throw new U(`JOSE Header "${t}" (Agreement Party${t===`apu`?`U`:`V`}Info) invalid`);return At(n,t,U)}}function Gn(e,t){if(e!==void 0&&t!==void 0&&e.byteLength===t.byteLength){for(let n=0;n<e.byteLength;n++)if(e[n]!==t[n])return;throw new U(`JOSE Header "apu" and "apv" values must be distinct`)}}function Kn(e){if(e===void 0)throw new U(`JWE Encrypted Key missing`)}function qn(e){if(e!==void 0)throw new U(`Encountered unexpected JWE Encrypted Key`)}function Jn(e){if(e!==void 0&&e!==1/0&&(!Number.isSafeInteger(e)||e<1))throw TypeError(`maxPBES2Count must be a positive safe integer or Infinity`)}async function Yn(e,t,n,r,i,a){let{alg:o}=e,s=e.mode;if(s===`direct-encryption`)return qn(r),n;let c=s===`direct-key-agreement`;switch(c?qn(r):Kn(r),e.subtle.name){case`ECDH`:{let{epk:r}=i;if(!Et(r)||[`d`,`k`,`p`,`q`,`dp`,`dq`,`qi`,`oth`,`priv`].some(e=>Object.hasOwn(r,e)))throw new U(`JOSE Header "epk" (Ephemeral Public Key) missing or invalid`);Un(n);let a=await on(e,r),s=Wn(i,`apu`),l=Wn(i,`apv`);Gn(s,l);let u=await Hn(a,n,c?t.alg:o,c?t.cekBits:parseInt(o.slice(-5,-2),10),s,l);if(c)return u;n=u;break}case`RSA-OAEP`:return Gt(n),Rn(o,n,`decrypt`),new Uint8Array(await crypto.subtle.decrypt(`RSA-OAEP`,n,r));case`PBKDF2`:{if(typeof i.p2c!=`number`)throw new U(`JOSE Header "p2c" (PBES2 Count) missing or invalid`);Jn(a);let e=a??1e4;if(i.p2c>e)throw new U(`JOSE Header "p2c" (PBES2 Count) out is of acceptable bounds`);if(typeof i.p2s!=`string`)throw new U(`JOSE Header "p2s" (PBES2 Salt) missing or invalid`);n=await zn(At(i.p2s,`p2s`,U),o,i.p2c,n);break}case`AES-GCM`:{if(typeof i.iv!=`string`)throw new U(`JOSE Header "iv" (Initialization Vector) missing or invalid`);if(typeof i.tag!=`string`)throw new U(`JOSE Header "tag" (Authentication Tag) missing or invalid`);let e=At(i.iv,`iv`,U),t=At(i.tag,`tag`,U);if(e.byteLength!==12)throw new U(`Invalid Initialization Vector length`);if(t.byteLength!==16)throw new U(`Invalid Authentication Tag length`);return vn(Pn(o.slice(0,-2)),n,r,e,t,new Uint8Array)}}return Ln(o.slice(-6),n,r)}async function Xn(e,t,n,r,i,a={}){let{alg:o,mode:s}=e,c=Nn(e);if(i!==void 0&&!c)throw TypeError(`setContentEncryptionKey cannot be called with JWE "alg" (Algorithm) Header ${o}`);let l=await Ht(s===`direct-encryption`?t:e,n,`encrypt`);if(s===`direct-encryption`)return[l,void 0,void 0];let u=c?i??cn(t):void 0;u&&ln(u,t.cekBits);let d,f;switch(e.subtle.name){case`ECDH`:{Un(l);let{apu:n,apv:i}=a;n!==void 0&&Tt(n,`"apu"`),i!==void 0&&Tt(i,`"apv"`);let c=n??Wn(r,`apu`),u=i??Wn(r,`apv`);Gn(c,u);let d;d=a.epk===void 0?(await crypto.subtle.generateKey(l.algorithm,!0,[`deriveBits`])).privateKey:await Ht(e,a.epk,`decrypt`);let p=crypto.subtle,m=d;if(!m.extractable){if(typeof p.getPublicKey!=`function`)throw TypeError(`CryptoKey for "epk" must be extractable`);m=await p.getPublicKey(d,[])}let{x:h,y:g,crv:_,kty:v}=await p.exportKey(`jwk`,m),y=s===`direct-key-agreement`,b=await Hn(l,d,y?t.alg:o,y?t.cekBits:parseInt(o.slice(-5,-2),10),c,u),x={x:h,crv:_,kty:v};if(v===`EC`&&(x.y=g),f={epk:x},n!==void 0&&(f.apu=G(n)),i!==void 0&&(f.apv=G(i)),y)return[b,void 0,f];l=b;break}case`RSA-OAEP`:Gt(l),Rn(o,l,`encrypt`),d=new Uint8Array(await crypto.subtle.encrypt(`RSA-OAEP`,l,u));break;case`PBKDF2`:{let{p2c:e=2048,p2s:t=crypto.getRandomValues(new Uint8Array(16))}=a;l=await zn(t,o,e,l),f={p2c:e,p2s:G(t)};break}case`AES-GCM`:{let e=a.iv===void 0?crypto.getRandomValues(new Uint8Array(12)):a.iv;if(!(e instanceof Uint8Array))throw TypeError(`"iv" must be an instance of Uint8Array`);let t=await _n(Pn(o.slice(0,-2)),u,l,e,new Uint8Array);d=t.ciphertext,f={iv:G(t.iv),tag:G(t.tag)}}}if(d??=await In(o.slice(-6),l,u),!(d instanceof Uint8Array)||!d.byteLength)throw TypeError(`JWE key management algorithm did not produce an Encrypted Key`);return[u,d,f]}function Zn(e,t){if(e.zip!==void 0&&e.zip!==`DEF`)throw new H(`Unsupported JWE "zip" (Compression Algorithm) Header Parameter value.`);if(e.zip!==void 0&&!t?.zip)throw new U(`JWE "zip" (Compression Algorithm) Header Parameter MUST be in a protected header.`)}function Qn(e){if(typeof globalThis[e]>`u`)throw new H(`JWE "zip" (Compression Algorithm) Header Parameter requires the ${e} API.`)}async function $n(e,t,n=1/0){let r=e.writable.getWriter();r.write(t).catch(()=>{}),r.close().catch(()=>{});let i=[],a=0,o=e.readable.getReader();for(;;){let{value:e,done:t}=await o.read();if(t)break;if(i.push(e),a+=e.byteLength,n!==1/0&&a>n)throw new U(`Decompressed plaintext exceeded the configured limit`)}return rt(...i)}async function er(e){return Qn(`CompressionStream`),$n(new CompressionStream(`deflate-raw`),e)}async function tr(e,t){return Qn(`DecompressionStream`),$n(new DecompressionStream(`deflate-raw`),e,t)}function nr(e){let{protected:t,ciphertext:n,iv:r,tag:i,aad:a}=e,o;return t!==void 0&&(o=Mt(t,U,`JWE Protected Header is invalid`)),[o,At(n,`ciphertext`,U),r===void 0?void 0:At(r,`iv`,U),i===void 0?void 0:At(i,`tag`,U),jt((t??``)+(a===void 0?``:`.${a}`),`aad`,U)]}function rr(e){return[e&&Ft(`keyManagementAlgorithms`,e.keyManagementAlgorithms),e&&Ft(`contentEncryptionAlgorithms`,e.contentEncryptionAlgorithms),e?.crit,e?.maxPBES2Count,e?.maxDecompressedLength]}async function ir(e,t,n,r=nr(e)){let[i,a,o,s,c]=r,{header:l,unprotected:u,aad:d}=e,f;if(l!==void 0||u!==void 0){if(!Ot(i,l,u))throw new U(`JWE Protected, JWE Unprotected Header, and JWE Per-Recipient Unprotected Header Parameter names must be disjoint`);f={...i,...l,...u}}else f=i??{};let[p,m,h,g,_]=t,{encrypted_key:v}=e;Lt(U,Pt,h,i,f),Zn(f,i);let{alg:y,enc:b}=f;if(typeof y!=`string`||!y)throw new U(`missing JWE Algorithm (alg) in JWE Header`);let x=Dn[y];if(v===``&&(!x||!Nn(x)))throw new U(`JWE Encrypted Key incorrect type`);let S=x?.mode===`integrated-encryption`;if(!S&&(typeof b!=`string`||!b))throw new U(`missing JWE Encryption Algorithm (enc) in JWE Header`);if(p&&!p.has(y)||!p&&y.startsWith(`PBES2`))throw new mt(`"alg" (Algorithm) Header Parameter value not allowed`);let C;if(S){if(b!==void 0)throw new U(`JWE "enc" (Encryption Algorithm) Header Parameter must not be present for integrated encryption`);if(o?.byteLength)throw new U(`JWE Initialization Vector must be empty for integrated encryption`);if(s?.byteLength)throw new U(`JWE Authentication Tag must be empty for integrated encryption`)}else{if(m&&!m.has(b))throw new mt(`"enc" (Encryption Algorithm) Header Parameter value not allowed`);C=Pn(b)}let w;if(v!==void 0)try{w=At(v,`encrypted_key`,U)}catch(e){if(!x||!Nn(x))throw e;w=new Uint8Array}let T=!1;typeof n==`function`&&(n=await n(i,e),T=!0);let E=x??Mn(y);Nn(E)&&w===void 0&&(w=new Uint8Array);let D=await Ht(E.mode===`direct-encryption`?C:E,n,`decrypt`),O;if(E.mode===`integrated-encryption`)O=await E.decrypt(D,w,a,c,i,f);else{let e=C,t;try{t=await Yn(E,e,D,w,f,g),Nn(E)&&t instanceof Uint8Array&&t.byteLength<<3!==e.cekBits&&(t=cn(e))}catch(n){if(n instanceof TypeError||n instanceof U||n instanceof H)throw n;t=cn(e)}O=await vn(e,t,a,o,s,c)}if(f.zip===`DEF`){let e=_??25e4;if(e===0)throw new H(`JWE "zip" (Compression Algorithm) Header Parameter is not supported.`);if(e!==1/0&&(!Number.isSafeInteger(e)||e<1))throw TypeError(`maxDecompressedLength must be 0, a positive safe integer, or Infinity`);O=await tr(O,e).catch(e=>{throw e instanceof U?e:new U(`Failed to decompress plaintext`,{cause:e})})}return{plaintext:O,...i&&{protectedHeader:i},...d!==void 0&&{additionalAuthenticatedData:At(d,`aad`,U)},...u&&{sharedUnprotectedHeader:u},...l&&{unprotectedHeader:l},...T&&{key:D}}}async function ar(e,t,n){if(e instanceof Uint8Array&&(e=et.decode(e)),typeof e!=`string`)throw new U(`Compact JWE must be a string or Uint8Array`);let{0:r,1:i,2:a,3:o,4:s,length:c}=e.split(`.`);if(c!==5)throw new U(`Invalid Compact JWE`);return ir({ciphertext:o,iv:a||void 0,protected:r,tag:s||void 0,encrypted_key:i||void 0},t,n)}function or(e,t,n){if(!Ot(e,t,n))throw new U(`JWE Protected, JWE Shared Unprotected and JWE Per-Recipient Header Parameter names must be disjoint`)}function sr(e,t,n=!1){if(!e[1]&&!e[2]&&!e[3])throw new U(`either setProtectedHeader, setUnprotectedHeader, or sharedUnprotectedHeader must be called before #encrypt()`);t!==void 0&&(e[8]=t?.crit);let[,r,i,a,o,s,c,l,u]=e;if(o!==void 0&&Tt(o,`JWE Additional Authenticated Data`),s!==void 0&&Tt(s,`JWE Content Encryption Key`),c!==void 0&&Tt(c,`JWE Initialization Vector`),!n&&r!==void 0&&(r=zt(U,r)[0],e[1]=r),i!==void 0&&(i=zt(U,i)[0],e[2]=i),!n&&a!==void 0&&(a=zt(U,a)[0],e[3]=a),l!==void 0&&!Et(l))throw TypeError(`JWE Key Management Parameters must be an object`);or(r,i,a);let d={...r,...i,...a};It(U,r),Lt(U,Pt,u,r,d),Zn(d,r);let{alg:f,enc:p}=d;if(typeof f!=`string`||!f)throw new U(`JWE "alg" (Algorithm) Header Parameter missing or invalid`);let m=Dn[f];if(m?.mode===`integrated-encryption`){if(p!==void 0)throw new U(`JWE "enc" (Encryption Algorithm) Header Parameter must not be present for integrated encryption`);if(s!==void 0)throw TypeError(`setContentEncryptionKey cannot be called with JWE "alg" (Algorithm) Header ${f}`);if(c!==void 0)throw TypeError(`setInitializationVector cannot be called with JWE "alg" (Algorithm) Header ${f}`);return[d,void 0,m]}if(typeof p!=`string`||!p)throw new U(`JWE "enc" (Encryption Algorithm) Header Parameter missing or invalid`);return[d,Pn(p),m]}async function cr(e,t,n){let[r,i,a]=t,[o,s,c,l,u,d,f,p,,m]=e,h=s,g=c,_=a??Mn(r.alg),v,y,b;_.mode===`integrated-encryption`?b=await Ht(_,n,`encrypt`):[b,v,y]=await Xn(_,i,n,r,d,p),y&&(m?g=g?{...g,...y}:y:h=h?{...h,...y}:y,or(h,g,l));let x=h?G(JSON.stringify(h)):``,S=u?.byteLength?G(u):void 0,C=ct(S?`${x}.${S}`:x),w=o;r.zip===`DEF`&&(w=await er(w).catch(e=>{throw new U(`Failed to compress plaintext`,{cause:e})}));let T,E,D;_.mode===`integrated-encryption`?[v,T]=await _.encrypt(b,w,C,h,r,p):{ciphertext:T,tag:E,iv:D}=await _n(i,w,b,f,C);let O={ciphertext:G(T)};return D&&(O.iv=G(D)),E&&(O.tag=G(E)),v?.byteLength&&(O.encrypted_key=G(v)),S&&(O.aad=S),h&&(O.protected=x),l&&(O.unprotected=l),g&&(O.header=g),O}async function lr(e,t,n){return cr(e,sr(e,n),t)}function ur(e){return[e.protected,e.encrypted_key,e.iv,e.ciphertext,e.tag].join(`.`)}var dr=[[`verify`],[`sign`]];function fr(e){let t={name:`HMAC`,hash:`SHA-${e}`};return{kty:[`oct`],secret:!0,subtle:t,signing:t,usages:dr}}function pr(e,t){let n={name:t?`RSA-PSS`:`RSASSA-PKCS1-v1_5`,hash:`SHA-${e}`};return{kty:[`RSA`],subtle:n,signing:t?{...n,saltLength:t}:n,usages:dr,minRsaBits:2048}}function mr(e,t){return{kty:[`EC`],crv:e,subtle:{name:`ECDSA`,namedCurve:e},signing:{name:`ECDSA`,hash:`SHA-${t}`},usages:dr}}function hr(){let e={name:`Ed25519`};return{kty:[`OKP`],crv:`Ed25519`,subtle:e,signing:e,usages:dr}}function gr(e){let t={name:`ML-DSA-${e}`};return{kty:[`AKP`],subtle:t,signing:t,usages:dr}}var _r=yn({HS256:fr(256),HS384:fr(384),HS512:fr(512),RS256:pr(256),RS384:pr(384),RS512:pr(512),PS256:pr(256,32),PS384:pr(384,48),PS512:pr(512,64),ES256:mr(`P-256`,256),ES384:mr(`P-384`,384),ES512:mr(`P-521`,512),EdDSA:hr(),Ed25519:hr(),"ML-DSA-44":gr(44),"ML-DSA-65":gr(65),"ML-DSA-87":gr(87)});function vr(e){let t=typeof e==`string`?_r[e]:void 0;if(!t)throw new H(`alg ${e} is not supported either by JOSE or your javascript runtime`);return t}function yr(e){return[e&&Ft(`algorithms`,e.algorithms),e?.crit]}function br(e){return e===void 0?{}:Mt(e,W,`JWS Protected Header is invalid`)}function xr(e){try{return ct(e)}catch{throw new W(`JWS Compact Serialization payload must use only ASCII characters`)}}async function Sr(e,t,n,r,i){let{protected:a,header:o,payload:s}=e,c=i??br(a);if(!Ot(c,o))throw new W(`JWS Protected and JWS Unprotected Header Parameter names must be disjoint`);let l={...c,...o},u=Rt(c,Lt(W,Nt,t[1],c,l)),{alg:d}=l;if(typeof d!=`string`||!d)throw new W(`JWS "alg" (Algorithm) Header Parameter missing or invalid`);if(t[0]&&!t[0].has(d))throw new mt(`"alg" (Algorithm) Header Parameter value not allowed`);if(u){if(typeof s!=`string`)throw new W(`JWS Payload must be a string`)}else if(typeof s!=`string`&&!(s instanceof Uint8Array))throw new W(`JWS Payload must be a string or an Uint8Array instance`);let f=u||typeof s!=`string`?s:r(s),p=!1;typeof n==`function`&&(n=await n(c,e),p=!0);let m=vr(d),h=rt(a===void 0?new Uint8Array:ct(a),ct(`.`),typeof f==`string`?t[2]??=jt(f,`payload`,W):f),g=At(e.signature,`signature`,W),_=await Ht(m,n,`verify`),v=await sn(_,m.subtle,`verify`);m.minRsaBits&&en(m.alg,v);let y=!1;try{y=await crypto.subtle.verify(m.signing,v,g,h)}catch{}if(!y)throw new St;let b={payload:typeof f==`string`?At(f,`payload`,W):f};return a!==void 0&&(b.protectedHeader=c),o!==void 0&&(b.unprotectedHeader=o),p?[{...b,key:_},u]:[b,u]}async function Cr(e,t,n){if(e instanceof Uint8Array&&(e=et.decode(e)),typeof e!=`string`)throw new W(`Compact JWS must be a string or Uint8Array`);let{0:r,1:i,2:a,length:o}=e.split(`.`);if(o!==3)throw new W(`Invalid Compact JWS`);return Sr({payload:i,protected:r,signature:a},t,n,xr)}async function wr(e,t,n){let[r]=await Cr(e,yr(n),t);return r}var Tr=e=>Math.floor(e.getTime()/1e3),Er={s:1,m:60,h:3600,d:86400,w:604800,y:31557600},Dr=/^(\+|\-)? ?(\d+|\d+\.\d+) ?(seconds?|secs?|s|minutes?|mins?|m|hours?|hrs?|h|days?|d|weeks?|w|years?|yrs?|y)(?: (ago|from now))?$/i,Or=`check_failed`;function kr(){throw TypeError(`Invalid time period format`)}function Ar(e){typeof e!=`string`&&kr();let t=Dr.exec(e);(!t||t[4]&&t[1])&&kr();let n=parseFloat(t[2]),r=Math.round(n*Er[t[3][0].toLowerCase()]);return Number.isFinite(r)||kr(),t[1]===`-`||t[4]===`ago`?-r:r}function jr(e,t){if(!Number.isFinite(t))throw TypeError(`Invalid ${e} input`);return t}function Mr(e,t){if(typeof t!=`string`)throw TypeError(`"${e}" claim must be a string`)}function Nr(e){if(typeof e!=`string`&&(!Array.isArray(e)||Array.from(e).some(e=>typeof e!=`string`)))throw TypeError(`"aud" claim must be a string or an array of strings`)}function Pr(e,t){return typeof e==`number`?jr(t,e):e instanceof Date?jr(t,Tr(e)):Tr(new Date)+Ar(e)}var Fr=e=>{let t=e.toLowerCase();return e.includes(`/`)?t:`application/${t}`},Ir=(e,t)=>typeof e==`string`?t.includes(e):Array.isArray(e)?t.some(t=>e.includes(t)):!1;function Lr(e,t,n=!1){let r=e[t];if(r!==void 0||n){if(typeof r!=`number`)throw new ft(`"${t}" claim must be a number`,e,t,`invalid`);return r}}function Rr(e,t){throw new ft(`unexpected "${t}" claim value`,e,t,Or)}function zr(e,t,n={}){let r;try{r=JSON.parse(tt.decode(t))}catch{}if(!Et(r))throw new gt(`JWT Claims Set must be a top-level JSON object`);let{typ:i}=n;if(i!==void 0&&(typeof e.typ!=`string`||Fr(e.typ)!==Fr(i)))throw new ft(`unexpected "typ" JWT header value`,r,`typ`,Or);let{requiredClaims:a=[],issuer:o,subject:s,audience:c,maxTokenAge:l}=n,u=[...a];l!==void 0&&u.push(`iat`),c!==void 0&&u.push(`aud`),s!==void 0&&u.push(`sub`),o!==void 0&&u.push(`iss`);for(let e of new Set(u.reverse()))if(!Object.hasOwn(r,e))throw new ft(`missing required "${e}" claim`,r,e,`missing`);o!==void 0&&!(Array.isArray(o)?o:[o]).includes(r.iss)&&Rr(r,`iss`),s!==void 0&&r.sub!==s&&Rr(r,`sub`),c!==void 0&&!Ir(r.aud,typeof c==`string`?[c]:c)&&Rr(r,`aud`);let{clockTolerance:d}=n,f=0;if(typeof d==`string`)f=Ar(d);else if(d!==void 0){if(typeof d!=`number`)throw TypeError(`Invalid clockTolerance option type`);f=d}jr(`clockTolerance option`,f);let{currentDate:p}=n,m=jr(`currentDate option`,Tr(p===void 0?new Date:p)),h=Lr(r,`iat`,l!==void 0),g=Lr(r,`nbf`);if(g!==void 0&&g>m+f)throw new ft(`"nbf" claim timestamp check failed`,r,`nbf`,Or);let _=Lr(r,`exp`);if(_!==void 0&&_<=m-f)throw new pt(`"exp" claim timestamp check failed`,r,`exp`,Or);if(l!==void 0){let e=m-h,t=jr(`maxTokenAge option`,typeof l==`number`?l:Ar(l));if(e-f>t)throw new pt(`"iat" claim timestamp check failed (too far in the past)`,r,`iat`,Or);if(e<-f)throw new ft(`"iat" claim timestamp check failed (it should be in the past)`,r,`iat`,Or)}return r}var Br;function Vr(e){return Br.get(e)}function Hr(e){let t=Vr(e);for(let e of[`iat`,`nbf`,`exp`]){let n=t[e];if(typeof n==`number`&&!Number.isFinite(n))throw TypeError(`"${e}" claim must be a finite number`)}return $e.encode(JSON.stringify(t))}function Ur(e,t){return Vr(e)[t]}var Wr=class{constructor(e={}){if(!Et(e))throw TypeError(`JWT Claims Set MUST be an object`);(Br||=new WeakMap).set(this,structuredClone(e))}setIssuer(e){return Mr(`iss`,e),Vr(this).iss=e,this}setSubject(e){return Mr(`sub`,e),Vr(this).sub=e,this}setAudience(e){return Nr(e),Vr(this).aud=e,this}setJti(e){return Mr(`jti`,e),Vr(this).jti=e,this}setNotBefore(e){return Vr(this).nbf=Pr(e,`setNotBefore`),this}setExpirationTime(e){return Vr(this).exp=Pr(e,`setExpirationTime`),this}setIssuedAt(e){let t=Vr(this);return t.iat=e===void 0?Tr(new Date):typeof e==`string`?jr(`setIssuedAt`,Tr(new Date)+Ar(e)):Pr(e,`setIssuedAt`),this}};async function Gr(e,t,n){let[r,i]=await Cr(e,yr(n),t);if(!i)throw new gt(`JWTs MUST NOT use unencoded payload`);let a=zr(r.protectedHeader,r.payload,n);return{...r,payload:a}}async function Kr(e,t,n){let{plaintext:r,...i}=await ar(e,rr(n),t),{protectedHeader:a}=i,o=zr(a,r,n);for(let e of[`iss`,`sub`,`aud`])if(a[e]!==void 0&&(e===`aud`?JSON.stringify(a.aud)!==JSON.stringify(o.aud):a[e]!==o[e]))throw new ft(`replicated "${e}" claim header parameter mismatch`,o,e,`mismatch`);return{payload:o,...i}}async function qr(e,t,n){let[r,i,a,o]=e,s=``;if(i!==void 0){let e=zt(W,i);i=e[0],s=G(e[1])}if(a!==void 0&&(a=zt(W,a)[0]),!i&&!a)throw new W(`either setProtectedHeader or setUnprotectedHeader must be called before #sign()`);if(!Ot(i,a))throw new W(`JWS Protected and JWS Unprotected Header Parameter names must be disjoint`);let c={...i,...a};It(W,i);let l=Rt(i,Lt(W,Nt,o,i,c));l||n?.();let{alg:u}=c;if(typeof u!=`string`||!u)throw new W(`JWS "alg" (Algorithm) Header Parameter missing or invalid`);let d=vr(u),f=``,p=r,m;if(l){let t=e[4];t?(f=t[0]??=G(r),p=t[1]??=ct(f)):(f=G(r),m=$e.encode(`${s}.${f}`))}m??=rt(ct(s),ct(`.`),p);let h=await sn(await Ht(d,t,`sign`),d.subtle,`sign`);d.minRsaBits&&en(d.alg,h);let g={signature:G(new Uint8Array(await crypto.subtle.sign(d.signing,h,m))),payload:f};return i&&(g.protected=s),a&&(g.header=a),[g,l]}async function Jr(e,t,n,r,i){let[a]=await qr([e,t,void 0,n],r,i);return`${a.protected}.${a.payload}.${a.signature}`}var Yr=Wr,Xr=class extends Yr{#e;setProtectedHeader(e){return kt(this.#e,`setProtectedHeader`),this.#e=e,this}async sign(e,t){return Jr(Hr(this),this.#e,t?.crit,e,()=>{throw new gt(`JWTs MUST NOT use unencoded payload`)})}},Zr=Wr,Qr=class extends Zr{#e=[void 0];#t;#n;#r;setProtectedHeader(e){return kt(this.#e[1],`setProtectedHeader`),this.#e[1]=e,this}setKeyManagementParameters(e){return kt(this.#e[7],`setKeyManagementParameters`),this.#e[7]=e,this}setContentEncryptionKey(e){return kt(this.#e[5],`setContentEncryptionKey`),this.#e[5]=e,this}setInitializationVector(e){return kt(this.#e[6],`setInitializationVector`),this.#e[6]=e,this}replicateIssuerAsHeader(){return this.#t=!0,this}replicateSubjectAsHeader(){return this.#n=!0,this}replicateAudienceAsHeader(){return this.#r=!0,this}async encrypt(e,t){let n=Hr(this);this.#e[1]&&(this.#t||this.#n||this.#r)&&(this.#e[1]={...this.#e[1],iss:this.#t?Ur(this,`iss`):void 0,sub:this.#n?Ur(this,`sub`):void 0,aud:this.#r?Ur(this,`aud`):void 0});let r=[...this.#e];return r[0]=n,ur(await lr(r,e,t))}},$r=`"alg" (Algorithm)`;function ei(e=`JWK "alg" (Algorithm) Parameter`){throw new H(`Invalid or unsupported ${e} value`)}function ti(e,t){return(typeof e==`string`?_r[e]??Dn[e]:void 0)??ei(t)}var ni=(e,t)=>{if(e.byteLength!==t.length)return!1;for(let n=0;n<e.byteLength;n++)if(e[n]!==t[n])return!1;return!0},ri=e=>({data:e,pos:0}),ii=e=>{let t=e.data[e.pos++];if(t===void 0)throw Error(`Unexpected end of ASN.1 input`);return t},ai=e=>{let t=ii(e);if(t&128){let n=t&127,r=0;for(let t=0;t<n;t++)r=r<<8|ii(e);return r}return t},oi=(e,t,n)=>{if(ii(e)!==t)throw Error(n)},si=(e,t)=>{if(t<0||e.pos+t>e.data.length)throw Error(`Unexpected end of ASN.1 input`);let n=e.data.subarray(e.pos,e.pos+t);return e.pos+=t,n},ci=e=>(oi(e,6,`Expected algorithm OID`),si(e,ai(e)));function li(e,t){if(oi(e,48,`Invalid ${t===`spki`?`SPKI`:`PKCS#8`} structure`),ai(e),t===`pkcs8`){oi(e,2,`Expected version field`);let t=ai(e);e.pos+=t}oi(e,48,`Expected algorithm identifier`),ai(e)}var ui=e=>{let t=ci(e);if(ni(t,[43,101,110]))return`X25519`;if(!ni(t,[42,134,72,206,61,2,1]))throw Error(`Unsupported key algorithm`);oi(e,6,`Expected curve OID`);let n=si(e,ai(e));if(ni(n,[42,134,72,206,61,3,1,7]))return`P-256`;if(ni(n,[43,129,4,0,34]))return`P-384`;if(ni(n,[43,129,4,0,35]))return`P-521`;throw Error(`Unsupported named curve`)},di=async(e,t,n,r)=>{let i=an(r?.extractable),a=ti(n,$r);a.secret&&ei(`"alg" (Algorithm)`);let o=e===`spki`,s;if(a.resolve)try{let n=ri(t);li(n,e),s=a.resolve({crv:ui(n)})}catch{throw new H(`Invalid or unsupported key format`)}else s=a.subtle;return crypto.subtle.importKey(e,t,s,i??o,a.usages[+!o])},fi=(e,t)=>ut(e.replace(t,``)),pi=(e,t,n)=>di(`spki`,fi(e,/(?:-----(?:BEGIN|END) PUBLIC KEY-----|\s)/g),t,n);async function mi(e){if(qt(e)){if(e.type===`secret`)e=e.export();else return e.export({format:`jwk`})}if(e instanceof Uint8Array)return{kty:`oct`,k:G(e)};if(!Kt(e))throw TypeError(Xt(e,`CryptoKey`,`KeyObject`,`Uint8Array`));if(!e.extractable)throw TypeError(`non-extractable CryptoKey cannot be exported as a JWK`);let t=await crypto.subtle.exportKey(`jwk`,e);delete t.ext,delete t.key_ops,delete t.use,t.kty!==`AKP`&&delete t.alg;for(let e of Object.keys(t))t[e]===void 0&&delete t[e];return t}var hi=(e,t)=>{if(typeof e!=`string`||!e)throw new _t(`${t} missing or invalid`)};async function gi(e,t){let n;if(Et(e)){if(n=nn(e),typeof n.kty!=`string`)throw TypeError(Xt(e,`CryptoKey`,`KeyObject`,`JSON Web Key`))}else if(Jt(e))n=nn(await mi(e));else throw TypeError(Xt(e,`CryptoKey`,`KeyObject`,`JSON Web Key`));if(t??=`sha256`,t!==`sha256`&&t!==`sha384`&&t!==`sha512`)throw TypeError(`digestAlgorithm must one of "sha256", "sha384", or "sha512"`);let r;switch(n.kty){case`AKP`:hi(n.alg,`"alg" (Algorithm) Parameter`),hi(n.pub,`"pub" (Public key) Parameter`),r={alg:n.alg,kty:n.kty,pub:n.pub};break;case`EC`:hi(n.crv,`"crv" (Curve) Parameter`),hi(n.x,`"x" (X Coordinate) Parameter`),hi(n.y,`"y" (Y Coordinate) Parameter`),r={crv:n.crv,kty:n.kty,x:n.x,y:n.y};break;case`OKP`:hi(n.crv,`"crv" (Subtype of Key Pair) Parameter`),hi(n.x,`"x" (Public Key) Parameter`),r={crv:n.crv,kty:n.kty,x:n.x};break;case`RSA`:hi(n.e,`"e" (Exponent) Parameter`),hi(n.n,`"n" (Modulus) Parameter`),r={e:n.e,kty:n.kty,n:n.n};break;case`oct`:if(typeof n.k!=`string`)throw new _t(`"k" (Key Value) Parameter missing or invalid`);r={k:n.k,kty:n.kty};break;default:throw new H(`"kty" (Key Type) Parameter missing or unsupported`)}let i=ct(JSON.stringify(r));return G(await dt(t,i))}function _i(e,t,n,r){let{kty:i,key_ops:a,ext:o,kid:s,alg:c,use:l,crv:u}=e;return(o===void 0||typeof o==`boolean`)&&(a===void 0||Array.isArray(a)&&a.every((e,t)=>typeof e==`string`&&a.indexOf(e)===t)&&a.includes(`verify`))&&t.kty.includes(i)&&(r===void 0||typeof r==`string`&&r===s)&&(c===void 0?i!==`AKP`:n===c)&&(l===void 0||l===`sig`)&&(!t.crv||u===t.crv)}async function vi(e,t,n){let r=e.get(t)||e.set(t,{}).get(t),{alg:i}=n;if(r[i]===void 0){let e=on(n,t,!0).then(e=>{if(e.type!==`public`)throw new vt(`JSON Web Key Set members must be public keys`);return r[i]=e,e}).catch(t=>{throw r[i]===e&&delete r[i],t});r[i]=e}return r[i]}function yi(e){let t;try{t=structuredClone(e)}catch{}if(!Dt(t))throw new vt(`JSON Web Key Set malformed`);let n=t.keys.map(e=>{let t=nn(e);return Array.isArray(t.key_ops)&&(t.key_ops=[...t.key_ops]),t}),r=new WeakMap;return Object.defineProperty(async(e,i)=>{let{alg:a,kid:o}={...e,...i?.header},s=typeof a==`string`?_r[a]:void 0;if(!s||s.secret)throw new H(`Unsupported "alg" value for a JSON Web Key Set`);let c=t.keys.filter((e,t)=>_i(n[t],s,a,o)),{0:l,length:u}=c;if(!u)throw new yt;if(u!==1){let e=new bt;throw e[Symbol.asyncIterator]=async function*(){for(let e of c)try{yield await vi(r,e,s)}catch{}},e}return vi(r,l,s)},"jwks",{value:()=>structuredClone(t)})}async function bi(e,t,n){if(typeof e!=`string`||e.indexOf(`-----BEGIN PUBLIC KEY-----`)!==0)throw TypeError(`"spki" must be SPKI formatted string`);return pi(e,t,n)}async function xi(e,t,n){if(!Et(e))throw TypeError(`JWK must be an object`);let r=rn(e),i=an(n?.extractable),{alg:a}=r;if(t??=a,r.kty!==`oct`&&!t)throw TypeError(`"alg" argument is required when "jwk.alg" is not present`);switch(r.kty){case`oct`:if(typeof r.k!=`string`)throw TypeError(`missing "k" (Key Value) Parameter value`);return wt(r.k);case`AKP`:if(typeof a!=`string`||!a)throw TypeError(`missing "alg" (Algorithm) Parameter value`);if(t!==a)throw TypeError(`JWK alg and alg option value mismatch`);return on(ti(t),r,i);case`RSA`:case`EC`:case`OKP`:return on(ti(t),r,i);default:throw new H(`Unsupported "kty" (Key Type) Parameter value`)}}function Si(e){let t;if(typeof e==`string`){let n=e.split(`.`);(n.length===3||n.length===5)&&([t]=n)}else if(typeof e==`object`&&e){if(`protected`in e)t=e.protected;else throw TypeError(`Token does not contain a Protected Header`)}let n=`Invalid Token or Protected Header formatting`;if(typeof t!=`string`||!t)throw TypeError(n);return Mt(t,TypeError,n)}function Ci(e){if(typeof e!=`string`)throw new gt(`JWTs must use Compact JWS serialization, JWT must be a string`);let{1:t,length:n}=e.split(`.`);if(n===5)throw new gt(`Only JWTs using Compact JWS serialization can be decoded`);if(n!==3)throw new gt(`Invalid JWT`);if(!t)throw new gt(`JWTs must contain a payload`);let r;try{r=wt(t)}catch{throw new gt(`Failed to base64url decode the payload`)}let i;try{i=JSON.parse(tt.decode(r))}catch{throw new gt(`Failed to parse the decoded payload as JSON`)}if(!Et(i))throw new gt(`Invalid JWT Claims Set`);return i}function wi(e){let t=e?.modulusLength??2048;if(typeof t!=`number`||!Number.isInteger(t)||t<2048)throw new H(`Invalid or unsupported modulusLength option provided, 2048 bits or larger keys must be used`);return t}async function Ti(e,t){let n=an(t?.extractable),r=ti(e,$r);r.secret&&ei(`"alg" (Algorithm)`);let i;if(r.resolve){let e=t?.crv??`P-256`;if(![`P-256`,`P-384`,`P-521`,`X25519`].includes(e))throw new H(`Invalid or unsupported crv option provided, supported values are P-256, P-384, P-521, and X25519`);i=r.resolve({crv:e})}else{if(r.crv!==void 0&&t?.crv!==void 0&&t.crv!==r.crv)throw new H(`Invalid or unsupported crv option provided, the only supported value for ${e} is ${r.crv}`);i=r.kty[0]===`RSA`?{...r.subtle,publicExponent:Uint8Array.of(1,0,1),modulusLength:wi(t)}:r.subtle}return crypto.subtle.generateKey(i,n??!1,[...r.usages[1],...r.usages[0]])}async function Ei(e,t,n=3600){return await new Xr(e).setProtectedHeader({alg:`HS256`}).setIssuedAt().setExpirationTime(Math.floor(Date.now()/1e3)+n).sign(new TextEncoder().encode(t))}async function Di(e,t){try{return(await Gr(e,new TextEncoder().encode(t))).payload}catch{return null}}var Oi=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]),ki=()=>Date.now()/1e3|0,Ai=`dir`,ji=`A256CBC-HS512`;function Mi(e,t){return Be(Qe,new TextEncoder().encode(e),new TextEncoder().encode(t),Oi,64)}function Ni(e){if(typeof e==`string`)return e;let t=e.keys.get(e.currentVersion);if(!t)throw Error(`Secret version ${e.currentVersion} not found in keys`);return t}function Pi(e){if(typeof e==`string`)return[{version:0,value:e}];let t=[];for(let[n,r]of e.keys)t.push({version:n,value:r});return e.legacySecret&&!t.some(t=>t.value===e.legacySecret)&&t.push({version:-1,value:e.legacySecret}),t}async function Fi(e,t,n,r=3600){let i=Mi(Ni(t),n),a=await gi({kty:`oct`,k:G(i)},`sha256`);return await new Qr(e).setProtectedHeader({alg:Ai,enc:ji,kid:a}).setIssuedAt().setExpirationTime(ki()+r).setJti(crypto.randomUUID()).encrypt(i)}var Ii={clockTolerance:15,keyManagementAlgorithms:[Ai],contentEncryptionAlgorithms:[ji,`A256GCM`]};async function Li(e,t,n){if(!e)return null;let r=!1;try{r=Si(e).kid!==void 0}catch{return null}try{let r=Pi(t),{payload:i}=await Kr(e,async e=>{let t=e.kid;if(t!==void 0){for(let e of r){let r=Mi(e.value,n);if(t===await gi({kty:`oct`,k:G(r)},`sha256`))return r}throw Error(`no matching decryption secret`)}return r.length,Mi(r[0].value,n)},Ii);return i}catch{if(r)return null;let i=Pi(t);if(i.length<=1)return null;for(let t=1;t<i.length;t++)try{let r=i[t],{payload:a}=await Kr(e,Mi(r.value,n),Ii);return a}catch{continue}return null}}function Ri(e,t){typeof e==`string`&&(e=new TextEncoder().encode(e)),typeof t==`string`&&(t=new TextEncoder().encode(t));let n=new Uint8Array(e),r=new Uint8Array(t),i=n.length^r.length,a=Math.max(n.length,r.length);for(let e=0;e<a;e++)i|=(e<n.length?n[e]:0)^(e<r.length?r[e]:0);return i===0}var zi=E(`a-z`,`0-9`,`A-Z`,`-_`);function Bi(){let e=typeof globalThis<`u`&&globalThis.crypto;if(e&&typeof e.subtle==`object`&&e.subtle!=null)return e.subtle;throw Error(`crypto.subtle must be defined`)}function Vi(e,t){return{digest:async n=>{let r=C(n),i=await Bi().digest(e,r);return t===`hex`?Array.from(new Uint8Array(i)).map(e=>e.toString(16).padStart(2,`0`)).join(``):t===`base64`||t===`base64url`||t===`base64urlnopad`?t.includes(`url`)?d.encode(i,{padding:t!==`base64urlnopad`}):w.encode(i):i}}}function Hi(e){return e instanceof Uint8Array||ArrayBuffer.isView(e)&&e.constructor.name===`Uint8Array`&&`BYTES_PER_ELEMENT`in e&&e.BYTES_PER_ELEMENT===1}var Ui=e=>e?`"${e}" `:``;function Wi(e,t=``){if(typeof e!=`boolean`)throw TypeError(Ui(t)+`expected boolean, got type=`+typeof e);return e}function Gi(e,t=``){if(typeof e!=`number`)throw TypeError(Ui(t)+`expected number, got `+typeof e);if(!Number.isSafeInteger(e)||e<0)throw RangeError(Ui(t)+`expected integer >= 0, got `+e);return e}function K(e,t,n=``){if(Hi(e)&&(t===void 0||e.length===t))return e;t!==void 0&&Gi(t,`length`);let r=Hi(e),i=t===void 0?``:` of length ${t}`,a=r?`length=${e.length}`:`type=${typeof e}`,o=Ui(n)+`expected Uint8Array`+i+`, got `+a;throw r?RangeError(o):TypeError(o)}var Ki=(e,t)=>{if(typeof e!=`object`||!e||Array.isArray(e))throw TypeError(t===`object`?`expected valid options object`:`"${t}" expected object, got type=${typeof e}`)};function qi(e,t=!0){if(e.destroyed)throw Error(`hash was destroyed`);if(t&&e.finished)throw Error(`digest() was already called`)}function Ji(e,t){K(e,void 0,`output`);let n=t.outputLen;if(!(e.length>=n))throw RangeError(`"output" expected length >= `+n)}function Yi(e){return new Uint32Array(e.buffer,e.byteOffset,Math.floor(e.byteLength/4))}function Xi(...e){for(let t=0;t<e.length;t++)e[t].fill(0)}function Zi(e){return new DataView(e.buffer,e.byteOffset,e.byteLength)}var Qi=new Uint8Array(new Uint32Array([287454020]).buffer)[0]===68;function $i(e){return e<<24&4278190080|e<<8&16711680|e>>>8&65280|e>>>24&255}function ea(e){for(let t=0;t<e.length;t++)e[t]=$i(e[t]);return e}var ta=Qi?e=>e:ea,na=typeof Uint8Array.from([]).toHex==`function`&&typeof Uint8Array.fromHex==`function`,ra=Array.from({length:256},(e,t)=>t.toString(16).padStart(2,`0`));function ia(e){if(K(e),na)return e.toHex();let t=``;for(let n=0;n<e.length;n++)t+=ra[e[n]];return t}function aa(e){return e>=48&&e<=57?e-48:e>=65&&e<=70?e-55:e>=97&&e<=102?e-87:void 0}function oa(e){if(typeof e!=`string`)throw TypeError(`hex string expected, got `+typeof e);if(na)try{return Uint8Array.fromHex(e)}catch(e){throw e instanceof SyntaxError?RangeError(e.message):e}let t=e.length,n=t/2;if(t%2)throw RangeError(`hex string expected, got unpadded hex of length `+t);let r=new Uint8Array(n);for(let t=0,i=0;t<n;t++,i+=2){let n=aa(e.charCodeAt(i)),a=aa(e.charCodeAt(i+1));if(n===void 0||a===void 0){let t=e[i]+e[i+1];throw RangeError(`hex string expected, got non-hex character "`+t+`" at index `+i)}r[t]=n*16+a}return r}function sa(e){if(typeof e!=`string`)throw TypeError(`string expected`);return new Uint8Array(new TextEncoder().encode(e))}function ca(e,t){return!e.byteLength||!t.byteLength?!1:e.buffer===t.buffer&&e.byteOffset<t.byteOffset+t.byteLength&&t.byteOffset<e.byteOffset+e.byteLength}function la(e,t){if(ca(e,t)&&e.byteOffset<t.byteOffset)throw Error(`complex overlap of input and output is not supported`)}function ua(...e){let t=0;for(let n=0;n<e.length;n++){let r=e[n];K(r),t+=r.length}let n=new Uint8Array(t);for(let t=0,r=0;t<e.length;t++){let i=e[t];n.set(i,r),r+=i.length}return n}function da(e,t){return Ki(e,`defaults`),Ki(t,`opts`),Object.assign(e,t)}function fa(e,t){if(e=K(e),t=K(t),e.length!==t.length)return!1;let n=0;for(let r=0;r<e.length;r++)n|=e[r]^t[r];return n===0}function pa(e,t,n){let r=t,i=n||(()=>[]),a=(e,t)=>r(t,...i(e)).update(e).digest(),o=r(new Uint8Array(e),...i(new Uint8Array));return a.outputLen=o.outputLen,a.blockLen=o.blockLen,a.create=(e,...t)=>r(e,...t),a}var ma=(e,t)=>{function n(n,...r){if(K(n,void 0,`key`),e.nonceLength!==void 0){let t=r[0];K(t,e.varSizeNonce?void 0:e.nonceLength,`nonce`)}let i=e.tagLength,a=e.nonceLength===void 0?0:1;if(!e.withAAD){for(let e=a;e<r.length;e++)if(Hi(r[e]))throw Error(`AAD not supported`)}e.withAAD&&r[a]!==void 0&&K(r[a],void 0,`AAD`);let o=t(n,...r),s=(e,t)=>{if(t!==void 0){if(e!==2)throw Error(`cipher output not supported`);K(t,void 0,`output`)}},c=!1;return{encrypt(e,t){if(c)throw Error(`cannot encrypt() twice with same key + nonce`);return c=!0,K(e,void 0,`data`),s(o.encrypt.length,t),o.encrypt(e,t)},decrypt(e,t){if(K(e,void 0,`data`),i&&e.length<i)throw Error(`"ciphertext" expected length >= tagLength=`+i);return s(o.decrypt.length,t),o.decrypt(e,t)}}}return Object.assign(n,e),n};function ha(e,t,n=!0){if(t===void 0)return new Uint8Array(e);if(K(t,e,`output`),n&&!_a(t))throw Error(`invalid output, must be aligned`);return t}function ga(e,t,n){Gi(e),Gi(t),Wi(n);let r=new Uint8Array(16),i=Zi(r);return i.setBigUint64(0,BigInt(t),n),i.setBigUint64(8,BigInt(e),n),r}function _a(e){return e.byteOffset%4==0}function va(e){return Uint8Array.from(K(e))}function ya(e=32){Gi(e,`bytesLength`);let t=typeof globalThis==`object`?globalThis.crypto:null;if(typeof t?.getRandomValues!=`function`)throw Error(`crypto.getRandomValues must be defined`);if(e>65536)throw RangeError(`"bytesLength" expected <= 65536, got ${e}`);return t.getRandomValues(new Uint8Array(e))}function ba(e,t=ya){if(typeof e!=`function`)throw TypeError(`"fn" expected cipher constructor, got type=`+typeof e);if(typeof t!=`function`)throw TypeError(`"randomBytes_" expected function, got type=`+typeof t);let{nonceLength:n}=e;Gi(n,`fn.nonceLength`);let r=(e,t,n)=>{let r=ua(e,t);return ca(n,t)||t.fill(0),r},i=((i,...a)=>({encrypt(o){K(o,void 0,`data`);let s=t(n),c=e(i,s,...a).encrypt(o);return c instanceof Promise?c.then(e=>r(s,e,o)):r(s,c,o)},decrypt(t){K(t,void 0,`data`);let r=t.subarray(0,n),o=t.subarray(n);return e(i,r,...a).decrypt(o)}}));return`blockSize`in e&&(i.blockSize=e.blockSize),`tagLength`in e&&(i.tagLength=e.tagLength),`withAAD`in e&&(i.withAAD=e.withAAD),i}var xa=e=>Uint8Array.from(e.split(``),e=>e.charCodeAt(0)),Sa=ta(Yi(xa(`expand 16-byte k`))),Ca=ta(Yi(xa(`expand 32-byte k`)));function q(e,t){return e<<t|e>>>32-t}var wa=64,Ta=16,Ea=2**32-1,Da=Uint32Array.of();function Oa(e,t,n,r,i,a,o,s){let c=i.length,l=new Uint8Array(wa),u=Yi(l),d=Qi&&_a(i)&&_a(a),f=d?Yi(i):Da,p=d?Yi(a):Da;if(Qi)for(let m=0;m<c;o++){if(e(t,n,r,u,o,s),o>=Ea)throw Error(`arx: counter overflow`);let h=Math.min(wa,c-m);if(d&&h===wa){let e=m/4;if(m%4!=0)throw Error(`arx: invalid block position`);for(let t=0,n;t<Ta;t++)n=e+t,p[n]=f[n]^u[t];m+=wa}else{for(let e=0,t;e<h;e++)t=m+e,a[t]=i[t]^l[e];m+=h}}else for(let d=0;d<c;o++){if(e(t,n,r,u,o,s),ta(u),o>=Ea)throw Error(`arx: counter overflow`);let f=Math.min(wa,c-d);for(let e=0,t;e<f;e++)t=d+e,a[t]=i[t]^l[e];d+=f}}function ka(e,t){let{allowShortKeys:n,extendNonceFn:r,counterLength:i,counterRight:a,rounds:o}=da({allowShortKeys:!1,counterLength:8,counterRight:!1,rounds:20},t);if(typeof e!=`function`)throw Error(`core must be a function`);return Gi(i),Gi(o),Wi(a),Wi(n),(t,s,c,l,u=0)=>{K(t,void 0,`key`),K(s,void 0,`nonce`),K(c,void 0,`data`);let d=c.length,f=l!==void 0;if(l=ha(d,l,!1),f&&la(c,l),Gi(u),u<0||u>=Ea)throw Error(`arx: counter overflow`);let p=[],m=t.length,h,g;if(m===32)p.push(h=va(t)),g=Ca;else if(m===16&&n)h=new Uint8Array(32),h.set(t),h.set(t,16),g=Sa,p.push(h);else throw K(t,32,`arx key`),Error(`invalid key size`);(!Qi||!_a(s))&&p.push(s=va(s));let _=Yi(h);if(r){if(s.length!==24)throw Error(`arx: extended nonce must be 24 bytes`);let e=s.subarray(0,16);if(Qi)r(g,_,Yi(e),_);else{let t=ta(Uint32Array.from(g));r(t,_,Yi(e),_),Xi(t),ta(_)}s=s.subarray(16)}else Qi||ta(_);let v=16-i;if(v!==s.length)throw Error(`arx: nonce must be ${v} or 16 bytes`);if(v!==12){let e=new Uint8Array(12);e.set(s,a?0:12-s.length),s=e,p.push(s)}let y=ta(Yi(s));try{return Oa(e,g,_,y,c,l,u,o),l}finally{Xi(...p)}}}function J(e,t){return e[t++]&255|(e[t++]&255)<<8}var Aa=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=va(K(e,32,`key`));let t=J(e,0),n=J(e,2),r=J(e,4),i=J(e,6),a=J(e,8),o=J(e,10),s=J(e,12),c=J(e,14);this.r[0]=t&8191,this.r[1]=(t>>>13|n<<3)&8191,this.r[2]=(n>>>10|r<<6)&7939,this.r[3]=(r>>>7|i<<9)&8191,this.r[4]=(i>>>4|a<<12)&255,this.r[5]=a>>>1&8190,this.r[6]=(a>>>14|o<<2)&8191,this.r[7]=(o>>>11|s<<5)&8065,this.r[8]=(s>>>8|c<<8)&8191,this.r[9]=c>>>5&127;for(let t=0;t<8;t++)this.pad[t]=J(e,16+2*t)}process(e,t,n=!1){let r=n?0:2048,{h:i,r:a}=this,o=a[0],s=a[1],c=a[2],l=a[3],u=a[4],d=a[5],f=a[6],p=a[7],m=a[8],h=a[9],g=J(e,t+0),_=J(e,t+2),v=J(e,t+4),y=J(e,t+6),b=J(e,t+8),x=J(e,t+10),S=J(e,t+12),C=J(e,t+14),w=i[0]+(g&8191),T=i[1]+((g>>>13|_<<3)&8191),E=i[2]+((_>>>10|v<<6)&8191),D=i[3]+((v>>>7|y<<9)&8191),O=i[4]+((y>>>4|b<<12)&8191),k=i[5]+(b>>>1&8191),A=i[6]+((b>>>14|x<<2)&8191),j=i[7]+((x>>>11|S<<5)&8191),M=i[8]+((S>>>8|C<<8)&8191),N=i[9]+(C>>>5|r),P=0,F=P+w*o+5*h*T+5*m*E+5*p*D+5*f*O;P=F>>>13,F&=8191,F+=5*d*k+5*u*A+5*l*j+5*c*M+5*s*N,P+=F>>>13,F&=8191;let I=P+w*s+T*o+5*h*E+5*m*D+5*p*O;P=I>>>13,I&=8191,I+=5*f*k+5*d*A+5*u*j+5*l*M+5*c*N,P+=I>>>13,I&=8191;let L=P+w*c+T*s+E*o+5*h*D+5*m*O;P=L>>>13,L&=8191,L+=5*p*k+5*f*A+5*d*j+5*u*M+5*l*N,P+=L>>>13,L&=8191;let R=P+w*l+T*c+E*s+D*o+5*h*O;P=R>>>13,R&=8191,R+=5*m*k+5*p*A+5*f*j+5*d*M+5*u*N,P+=R>>>13,R&=8191;let ee=P+w*u+T*l+E*c+D*s+O*o;P=ee>>>13,ee&=8191,ee+=5*h*k+5*m*A+5*p*j+5*f*M+5*d*N,P+=ee>>>13,ee&=8191;let te=P+w*d+T*u+E*l+D*c+O*s;P=te>>>13,te&=8191,te+=k*o+5*h*A+5*m*j+5*p*M+5*f*N,P+=te>>>13,te&=8191;let ne=P+w*f+T*d+E*u+D*l+O*c;P=ne>>>13,ne&=8191,ne+=k*s+A*o+5*h*j+5*m*M+5*p*N,P+=ne>>>13,ne&=8191;let re=P+w*p+T*f+E*d+D*u+O*l;P=re>>>13,re&=8191,re+=k*c+A*s+j*o+5*h*M+5*m*N,P+=re>>>13,re&=8191;let ie=P+w*m+T*p+E*f+D*d+O*u;P=ie>>>13,ie&=8191,ie+=k*l+A*c+j*s+M*o+5*h*N,P+=ie>>>13,ie&=8191;let z=P+w*h+T*m+E*p+D*f+O*d;P=z>>>13,z&=8191,z+=k*u+A*l+j*c+M*s+N*o,P+=z>>>13,z&=8191,P=(P<<2)+P|0,P=P+F|0,F=P&8191,P>>>=13,I+=P,i[0]=F,i[1]=I,i[2]=L,i[3]=R,i[4]=ee,i[5]=te,i[6]=ne,i[7]=re,i[8]=ie,i[9]=z}finalize(){let{h:e,pad:t}=this,n=new Uint16Array(10),r=e[1]>>>13;e[1]&=8191;for(let t=2;t<10;t++)e[t]+=r,r=e[t]>>>13,e[t]&=8191;e[0]+=r*5,r=e[0]>>>13,e[0]&=8191,e[1]+=r,r=e[1]>>>13,e[1]&=8191,e[2]+=r,n[0]=e[0]+5,r=n[0]>>>13,n[0]&=8191;for(let t=1;t<10;t++)n[t]=e[t]+r,r=n[t]>>>13,n[t]&=8191;n[9]-=8192;let i=(r^1)-1;for(let e=0;e<10;e++)n[e]&=i;i=~i;for(let t=0;t<10;t++)e[t]=e[t]&i|n[t];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 a=e[0]+t[0];e[0]=a&65535;for(let n=1;n<8;n++)a=(e[n]+t[n]|0)+(a>>>16)|0,e[n]=a&65535;Xi(n)}update(e){qi(this),K(e),e=va(e);let{buffer:t,blockLen:n}=this,r=e.length;for(let i=0;i<r;){let a=Math.min(n-this.pos,r-i);if(a===n)for(;n<=r-i;i+=n)this.process(e,i);else t.set(e.subarray(i,i+a),this.pos),this.pos+=a,i+=a,this.pos===n&&(this.process(t,0,!1),this.pos=0)}return this}destroy(){this.destroyed=!0,Xi(this.h,this.r,this.buffer,this.pad)}digestInto(e){qi(this),Ji(e,this),this.finished=!0;let{buffer:t,h:n}=this,{pos:r}=this;if(r){for(t[r++]=1;r<16;r++)t[r]=0;this.process(t,0,!0)}this.finalize();let i=0;for(let t=0;t<8;t++)e[i++]=n[t]>>>0,e[i++]=n[t]>>>8}digest(){let{buffer:e,outputLen:t}=this;this.digestInto(e);let n=e.slice(0,t);return this.destroy(),n}},ja=pa(32,e=>new Aa(e));function Ma(e,t,n,r,i,a=20){let o=e[0],s=e[1],c=e[2],l=e[3],u=t[0],d=t[1],f=t[2],p=t[3],m=t[4],h=t[5],g=t[6],_=t[7],v=i,y=n[0],b=n[1],x=n[2],S=o,C=s,w=c,T=l,E=u,D=d,O=f,k=p,A=m,j=h,M=g,N=_,P=v,F=y,I=b,L=x;for(let e=0;e<a;e+=2)S=S+E|0,P=q(P^S,16),A=A+P|0,E=q(E^A,12),S=S+E|0,P=q(P^S,8),A=A+P|0,E=q(E^A,7),C=C+D|0,F=q(F^C,16),j=j+F|0,D=q(D^j,12),C=C+D|0,F=q(F^C,8),j=j+F|0,D=q(D^j,7),w=w+O|0,I=q(I^w,16),M=M+I|0,O=q(O^M,12),w=w+O|0,I=q(I^w,8),M=M+I|0,O=q(O^M,7),T=T+k|0,L=q(L^T,16),N=N+L|0,k=q(k^N,12),T=T+k|0,L=q(L^T,8),N=N+L|0,k=q(k^N,7),S=S+D|0,L=q(L^S,16),M=M+L|0,D=q(D^M,12),S=S+D|0,L=q(L^S,8),M=M+L|0,D=q(D^M,7),C=C+O|0,P=q(P^C,16),N=N+P|0,O=q(O^N,12),C=C+O|0,P=q(P^C,8),N=N+P|0,O=q(O^N,7),w=w+k|0,F=q(F^w,16),A=A+F|0,k=q(k^A,12),w=w+k|0,F=q(F^w,8),A=A+F|0,k=q(k^A,7),T=T+E|0,I=q(I^T,16),j=j+I|0,E=q(E^j,12),T=T+E|0,I=q(I^T,8),j=j+I|0,E=q(E^j,7);let R=0;r[R++]=o+S|0,r[R++]=s+C|0,r[R++]=c+w|0,r[R++]=l+T|0,r[R++]=u+E|0,r[R++]=d+D|0,r[R++]=f+O|0,r[R++]=p+k|0,r[R++]=m+A|0,r[R++]=h+j|0,r[R++]=g+M|0,r[R++]=_+N|0,r[R++]=v+P|0,r[R++]=y+F|0,r[R++]=b+I|0,r[R++]=x+L|0}function Na(e,t,n,r){let i=Qi?e:ta(e.slice(0,4)),a=Qi?t:ta(t.slice(0,8)),o=Qi?n:ta(n.slice(0,4)),s=new Uint32Array(16);Ma(i,a,o.subarray(1),s,o[0]);let c=0;r[c++]=s[0]-i[0]|0,r[c++]=s[1]-i[1]|0,r[c++]=s[2]-i[2]|0,r[c++]=s[3]-i[3]|0,r[c++]=s[12]-o[0]|0,r[c++]=s[13]-o[1]|0,r[c++]=s[14]-o[2]|0,r[c++]=s[15]-o[3]|0,ta(r),Qi||Xi(i,a,o),Xi(s)}var Pa=ka(Ma,{counterRight:!1,counterLength:8,extendNonceFn:Na,allowShortKeys:!1}),Fa=new Uint8Array(16),Ia=(e,t)=>{e.update(t);let n=t.length%16;n&&e.update(Fa.subarray(n))},La=new Uint8Array(32);function Ra(e,t,n,r,i){i!==void 0&&K(i,void 0,`AAD`);let a=e(t,n,La),o=ga(r.length,i?i.length:0,!0),s=ja.create(a);i&&Ia(s,i),Ia(s,r),s.update(o);let c=s.digest();return Xi(a,o),c}var za=ma({blockSize:64,nonceLength:24,tagLength:16,withAAD:!0},(e=>(t,n,r)=>({encrypt(i,a){let o=i.length;a=ha(o+16,a,!1),a.set(i);let s=a.subarray(0,-16);e(t,n,s,s,1);let c=Ra(e,t,n,s,r);return a.set(c,o),Xi(c),a},decrypt(i,a){a=ha(i.length-16,a,!1);let o=i.subarray(0,-16),s=i.subarray(-16),c=Ra(e,t,n,o,r);if(!fa(s,c))throw Xi(c),Error(`invalid tag`);return a.set(i.subarray(0,-16)),e(t,n,a,a,1),Xi(c),a}}))(Pa)),Ba={name:`HMAC`,hash:`SHA-256`},Va=`$ba$`;function Ha(e){if(!e.startsWith(Va))return null;let t=e.indexOf(`$`,4);if(t===-1)return null;let n=parseInt(e.slice(4,t),10);return!Number.isInteger(n)||n<0?null:{version:n,ciphertext:e.slice(t+1)}}function Ua(e,t){return`${Va}${e}$${t}`}async function Wa(e,t){let n=await Vi(`SHA-256`).digest(e),r=sa(t);return ia(ba(za)(new Uint8Array(n)).encrypt(r))}async function Ga(e,t){let n=await Vi(`SHA-256`).digest(e),r=oa(t),i=ba(za)(new Uint8Array(n));return new TextDecoder().decode(i.decrypt(r))}var Ka=async({key:e,data:t})=>{if(typeof e==`string`)return Wa(e,t);let n=e.keys.get(e.currentVersion);if(!n)throw Error(`Secret version ${e.currentVersion} not found in keys`);let r=await Wa(n,t);return Ua(e.currentVersion,r)},qa=async({key:e,data:t})=>{if(typeof e==`string`)return Ga(e,t);let n=Ha(t);if(n){let t=e.keys.get(n.version);if(!t)throw Error(`Secret version ${n.version} not found in keys (key may have been retired)`);return Ga(t,n.ciphertext)}if(e.legacySecret)return Ga(e.legacySecret,t);throw Error(`Cannot decrypt legacy bare-hex payload: no legacy secret available. Set BETTER_AUTH_SECRET for backwards compatibility.`)},Ja=async e=>{let t=typeof e==`string`?new TextEncoder().encode(e):e;return await Bi().importKey(`raw`,t,Ba,!1,[`sign`,`verify`])},Ya=async(e,t)=>{let n=await Ja(t),r=await Bi().sign(Ba.name,n,new TextEncoder().encode(e));return btoa(String.fromCharCode(...new Uint8Array(r)))},Xa={name:`HMAC`,hash:`SHA-256`},Za=async e=>{let t=typeof e==`string`?new TextEncoder().encode(e):e;return await Bi().importKey(`raw`,t,Xa,!1,[`sign`,`verify`])},Qa=async(e,t,n)=>{try{let r=atob(e),i=new Uint8Array(r.length);for(let e=0,t=r.length;e<t;e++)i[e]=r.charCodeAt(e);return await Bi().verify(Xa,n,i,new TextEncoder().encode(t))}catch{return!1}},$a=async(e,t)=>{let n=await Za(t),r=await Bi().sign(Xa.name,n,new TextEncoder().encode(e));return btoa(String.fromCharCode(...new Uint8Array(r)))},eo=async(e,t)=>{let n=await $a(e,t);return e=`${e}.${n}`,e=encodeURIComponent(e),e},to=/^application\/([a-z0-9.+-]*\+)?json/i;async function no(e,t){let n=e.headers.get(`content-type`)||``,r=n.toLowerCase();if(e.body){if(t&&t.length>0&&!t.some(e=>{let t=r.split(`;`)[0].trim(),n=e.toLowerCase().trim();return t===n||t.includes(n)}))throw r?new g(415,{message:`Content-Type "${n}" is not allowed. Allowed types: ${t.join(`, `)}`,code:`UNSUPPORTED_MEDIA_TYPE`}):new g(415,{message:`Content-Type is required. Allowed types: ${t.join(`, `)}`,code:`UNSUPPORTED_MEDIA_TYPE`});if(to.test(r))try{return await e.json()}catch(e){throw e instanceof SyntaxError?new g(400,{message:`Invalid JSON in request body`,code:`BAD_REQUEST`}):e}if(r.includes(`application/x-www-form-urlencoded`)){let t=await e.formData(),n={};return t.forEach((e,t)=>{n[t]=e.toString()}),n}if(r.includes(`multipart/form-data`)){let t=await e.formData(),n={};return t.forEach((e,t)=>{n[t]=e}),n}return r.includes(`text/plain`)?await e.text():r.includes(`application/octet-stream`)?await e.arrayBuffer():r.includes(`application/pdf`)||r.includes(`image/`)||r.includes(`video/`)?await e.blob():r.includes(`application/stream`)||e.body instanceof ReadableStream?e.body:await e.text()}}function ro(e){return e instanceof g||e?.name===`APIError`}function io(e){try{return e.includes(`%`)?decodeURIComponent(e):e}catch{return e}}async function ao(e){try{return{data:await e,error:null}}catch(e){return{data:null,error:e}}}function oo(e){return e instanceof Request||Object.prototype.toString.call(e)===`[object Request]`}var so={secure:`__Secure-`,host:`__Host-`},co=(e,t)=>{if(!t)return e;if(t===`secure`||t===`host`)return so[t]+e};function lo(e){if(typeof e!=`string`)throw TypeError(`argument str must be a string`);let t=new Map,n=0;for(;n<e.length;){let r=e.indexOf(`=`,n);if(r===-1)break;let i=e.indexOf(`;`,n);if(i===-1)i=e.length;else if(i<r){n=e.lastIndexOf(`;`,r-1)+1;continue}let a=e.slice(n,r).trim();if(!t.has(a)){let n=e.slice(r+1,i).trim();n.codePointAt(0)===34&&(n=n.slice(1,-1)),t.set(a,io(n))}n=i+1}return t}function uo(e,t,n={}){let r=co(e,n.prefix)??e,i={...n},a=r.toLowerCase();return a.startsWith(`__host-`)?(i.secure=!0,i.path=`/`,i.domain=void 0):a.startsWith(`__secure-`)&&(i.secure=!0),(i.partitioned===!0||i.sameSite?.toLowerCase()===`none`)&&(i.secure=!0),{name:r,value:t,options:i}}function fo({name:e,value:t,options:n}){let r=`${e}=${t}`;if(typeof n.maxAge==`number`&&n.maxAge>=0){if(n.maxAge>3456e4)throw Error(`Cookies Max-Age SHOULD NOT be greater than 400 days (34560000 seconds) in duration.`);r+=`; Max-Age=${Math.floor(n.maxAge)}`}if(n.domain&&(r+=`; Domain=${n.domain}`),n.path&&(r+=`; Path=${n.path}`),n.expires){if(n.expires.getTime()-Date.now()>3456e7)throw Error(`Cookies Expires SHOULD NOT be greater than 400 days (34560000 seconds) in the future.`);r+=`; Expires=${n.expires.toUTCString()}`}return n.httpOnly&&(r+=`; HttpOnly`),n.secure&&(r+=`; Secure`),n.sameSite&&(r+=`; SameSite=${n.sameSite.charAt(0).toUpperCase()+n.sameSite.slice(1)}`),n.partitioned&&(r+=`; Partitioned`),r}var po=(e,t,n)=>(t=encodeURIComponent(t),fo(uo(e,t,n))),mo=async(e,t,n,r)=>(t=await eo(t,n),fo(uo(e,t,r)));async function ho(e,t={}){let n={body:t.body,query:t.query};if(e.body){let r=await e.body[`~standard`].validate(t.body);if(r.issues)return{data:null,error:go(r.issues,`body`)};n.body=r.value}if(e.query){let r=await e.query[`~standard`].validate(t.query);if(r.issues)return{data:null,error:go(r.issues,`query`)};n.query=r.value}return e.requireHeaders&&!t.headers?{data:null,error:{message:`Headers is required`,issues:[]}}:e.requireRequest&&!t.request?{data:null,error:{message:`Request is required`,issues:[]}}:{data:n,error:null}}function go(e,t){return{message:e.map(e=>`[${e.path?.length?`${t}.`+e.path.map(e=>typeof e==`object`?e.key:e).join(`.`):t}] ${e.message}`).join(`; `),issues:e}}var _o=async(e,{options:t,path:n})=>{let r=new Headers,i,{data:a,error:o}=await ho(t,e);if(o)throw new Se(o.message,o.issues);let s=e.headers===void 0?`request`in e&&oo(e.request)?e.request.headers:null:e.headers instanceof Headers?e.headers:new Headers(e.headers),c=s?.get(`cookie`),l=c?lo(c):void 0,u={...e,body:a.body,query:a.query,path:e.path||n||`virtual:`,context:`context`in e&&e.context?e.context:{},returned:void 0,headers:e?.headers,request:e?.request,params:`params`in e?e.params:void 0,method:e.method??(Array.isArray(t.method)?t.method[0]:t.method===`*`?`GET`:t.method),setHeader:(e,t)=>{r.set(e,t)},getHeader:e=>s?s.get(e):null,getCookie:(e,t)=>{let n=co(e,t);return n&&l?.get(n)||null},getSignedCookie:async(e,t,n)=>{let r=co(e,n);if(!r)return null;let i=l?.get(r);if(!i)return null;let a=i.lastIndexOf(`.`);if(a<1)return null;let o=i.substring(0,a),s=i.substring(a+1);return s.length!==44||!s.endsWith(`=`)?null:await Qa(s,o,await Za(t))?o:!1},setCookie:(e,t,n)=>{let i=po(e,t,n);return r.append(`set-cookie`,i),i},setSignedCookie:async(e,t,n,i)=>{let a=await mo(e,t,n,i);return r.append(`set-cookie`,a),a},redirect:e=>(r.set(`location`,e),new g(`FOUND`,void 0,r)),error:(e,t,n)=>new g(e,t,n),setStatus:e=>{i=e},json:(t,n)=>e.asResponse?{body:n?.body||t,routerResponse:n,_flag:`json`}:t,responseHeaders:r,get responseStatus(){return i}};for(let e of t.use||[]){let t=await e({...u,returnHeaders:!0,asResponse:!1});t.response&&Object.assign(u.context,t.response),t.headers&&t.headers.forEach((e,t)=>{u.responseHeaders.set(t,e)})}return u};function vo(e){if(e===void 0)return!1;let t=typeof e;return t===`string`||t===`number`||t===`boolean`||t===null?!0:t===`object`?Array.isArray(e)?!0:e.buffer?!1:e.constructor&&e.constructor.name===`Object`||typeof e.toJSON==`function`:!1}function yo(e){let t=new WeakMap,n=new WeakMap,r=0,i=(e,n)=>{let r=n;for(;r;){if(r===e)return!0;r=t.get(r)}return!1};return JSON.stringify(e,function(e,a){if(typeof a==`bigint`)return a.toString();if(typeof a==`object`&&a){if(i(a,this))return`[Circular ref-${n.get(a)}]`;t.set(a,this),n.has(a)||n.set(a,r++)}return a})}function bo(e){return!e||typeof e!=`object`?!1:`_flag`in e&&e._flag===`json`}var xo=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`.split(`.`));function So(e){for(let t of xo)e.delete(t)}function Co(e,t){if(t)for(let[n,r]of new Headers(t).entries())n.toLowerCase()===`set-cookie`?e.append(n,r):e.set(n,r)}function wo(e,t){if(e instanceof Response){if(t?.headers){let n=new Headers(t.headers);So(n),Co(e.headers,n)}return e}if(bo(e)){let n=e.body,r=e.routerResponse;if(r instanceof Response)return r;let i=new Headers;if(Co(i,r?.headers),Co(i,e.headers),t?.headers){let e=new Headers(t.headers);So(e),Co(i,e)}i.set(`Content-Type`,`application/json`);let a=e.status??t?.status??r?.status,o=t?.statusText??r?.statusText;return new Response(JSON.stringify(n),{...r,headers:i,...a===void 0?{}:{status:a},...o===void 0?{}:{statusText:o}})}if(ro(e))return wo(e.body,{status:t?.status??e.statusCode,statusText:e.status.toString(),headers:t?.headers||e.headers});let n=e,r=new Headers(t?.headers);return So(r),e?typeof e==`string`?(n=e,r.set(`Content-Type`,`text/plain`)):e instanceof ArrayBuffer||ArrayBuffer.isView(e)?(n=e,r.set(`Content-Type`,`application/octet-stream`)):e instanceof Blob?(n=e,r.set(`Content-Type`,e.type||`application/octet-stream`)):e instanceof FormData?n=e:e instanceof URLSearchParams?(n=e,r.set(`Content-Type`,`application/x-www-form-urlencoded`)):e instanceof ReadableStream?(n=e,r.set(`Content-Type`,`application/octet-stream`)):vo(e)&&(n=yo(e),r.set(`Content-Type`,`application/json`)):(e===null&&(n=JSON.stringify(null)),r.set(`content-type`,`application/json`)),new Response(n,{...t,headers:r})}function To(e,t,n){let r=typeof e==`string`?e:void 0,i=typeof t==`object`?t:e,a=typeof t==`function`?t:n;if((i.method===`GET`||i.method===`HEAD`)&&i.body)throw new y(`Body is not allowed with GET or HEAD methods`);if(r&&/\/{2,}/.test(r))throw new y(`Path cannot contain consecutive slashes`);let o=async(...e)=>{let t=e[0]||{},{data:n,error:o}=await ao(_o(t,{options:i,path:r}));if(o)throw o instanceof Se?(i.onValidationError&&await i.onValidationError({message:o.message,issues:o.issues}),new g(400,{message:o.message,code:`VALIDATION_ERROR`})):o;let s=await a(n).catch(async e=>{if(ro(e)){let n=i.onAPIError;if(n&&await n(e),t.asResponse)return e}throw e}),c=n.responseHeaders,l=n.responseStatus;return t.asResponse?wo(s,l===void 0?{headers:c}:{headers:c,status:l}):t.returnHeaders?t.returnStatus?{headers:c,response:s,status:l}:{headers:c,response:s}:t.returnStatus?{response:s,status:l}:s};return o.options=i,o.path=r,o}function Eo(e,t){return[...e??[],...t??[]]}To.create=e=>{function t(...t){if(t.length===3){let[n,r,i]=t;return To(n,{...r,use:Eo(r.use,e?.use)},i)}let[n,r]=t;return To({...n,use:Eo(n.use,e?.use)},r)}return t};function Do(e,t){let n=async n=>{let r=n,a=typeof e==`function`?e:t,o=await _o(r,{options:typeof e==`function`?{}:e,path:`/`});if(!a)throw Error(`handler must be defined`);try{let e=await a(o),t=o.responseHeaders;return r.returnHeaders?{headers:t,response:e}:e}catch(e){throw ro(e)&&Object.defineProperty(e,i,{enumerable:!1,configurable:!0,get(){return o.responseHeaders}}),e}};return n.options=typeof e==`function`?{}:e,n}Do.create=e=>{function t(t,n){if(typeof t==`function`)return Do({use:e?.use},t);if(!n)throw Error(`Middleware handler is required`);return Do({...t,method:`*`,use:[...e?.use||[],...t.use||[]]},n)}return t};var Oo={};function ko(e){switch(e.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 Ao(e){let t=[];return e.metadata?.openapi?.parameters?(t.push(...e.metadata.openapi.parameters),t):(e.query instanceof ee&&Object.entries(e.query.shape).forEach(([e,n])=>{n instanceof ee&&t.push({name:e,in:`query`,schema:{type:ko(n),...`minLength`in n&&n.minLength?{minLength:n.minLength}:{},description:n.description}})}),t)}function jo(e){if(e.metadata?.openapi?.requestBody)return e.metadata.openapi.requestBody;if(e.body&&(e.body instanceof ee||e.body instanceof j)){let t=e.body.shape;if(!t)return;let n={},r=[];return Object.entries(t).forEach(([e,t])=>{t instanceof ee&&(n[e]={type:ko(t),description:t.description},t instanceof j||r.push(e))}),{required:e.body instanceof j?!1:!!e.body,content:{"application/json":{schema:{type:`object`,properties:n,required:r}}}}}}function Mo(e){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.`},...e}}async function No(e,t){return Object.entries(e).forEach(([e,t])=>{let n=t.options;if(t.path&&!n.metadata?.SERVER_ONLY&&(n.method===`GET`&&(Oo[t.path]={get:{tags:[`Default`,...n.metadata?.openapi?.tags||[]],description:n.metadata?.openapi?.description,operationId:n.metadata?.openapi?.operationId,security:[{bearerAuth:[]}],parameters:Ao(n),responses:Mo(n.metadata?.openapi?.responses)}}),n.method===`POST`)){let e=jo(n);Oo[t.path]={post:{tags:[`Default`,...n.metadata?.openapi?.tags||[]],description:n.metadata?.openapi?.description,operationId:n.metadata?.openapi?.operationId,security:[{bearerAuth:[]}],parameters:Ao(n),...e?{requestBody:e}:{requestBody:{content:{"application/json":{schema:{type:`object`,properties:{}}}}}},responses:Mo(n.metadata?.openapi?.responses)}}}}),{openapi:`3.1.1`,info:{title:`Better Auth`,description:`API Reference for your Better Auth Instance`,version:`1.1.0`},components:{schemas:{}},security:[{apiKeyCookie:[]}],servers:[{url:t?.url}],tags:[{name:`Default`,description:`Default endpoints that are included with Better Auth by default. These endpoints are not part of any plugin.`}],paths:Oo}}var Po=(e,t)=>`<!doctype html>
|
|
2
|
-
<html>
|
|
3
|
-
<head>
|
|
4
|
-
<title>Scalar API Reference</title>
|
|
5
|
-
<meta charset="utf-8" />
|
|
6
|
-
<meta
|
|
7
|
-
name="viewport"
|
|
8
|
-
content="width=device-width, initial-scale=1" />
|
|
9
|
-
</head>
|
|
10
|
-
<body>
|
|
11
|
-
<script
|
|
12
|
-
id="api-reference"
|
|
13
|
-
type="application/json">
|
|
14
|
-
${JSON.stringify(e)}
|
|
15
|
-
<\/script>
|
|
16
|
-
<script>
|
|
17
|
-
var configuration = {
|
|
18
|
-
favicon: ${t?.logo?`data:image/svg+xml;utf8,${encodeURIComponent(t.logo)}`:void 0} ,
|
|
19
|
-
theme: ${t?.theme||`saturn`},
|
|
20
|
-
metaData: {
|
|
21
|
-
title: ${t?.title||`Open API Reference`},
|
|
22
|
-
description: ${t?.description||`Better Call Open API`},
|
|
23
|
-
}
|
|
24
|
-
}
|
|
25
|
-
document.getElementById('api-reference').dataset.configuration =
|
|
26
|
-
JSON.stringify(configuration)
|
|
27
|
-
<\/script>
|
|
28
|
-
<script src="https://cdn.jsdelivr.net/npm/@scalar/api-reference"><\/script>
|
|
29
|
-
</body>
|
|
30
|
-
</html>`,Fo=(()=>{let e=function(){};return e.prototype=Object.create(null),Object.freeze(e.prototype),e})();function Io(){return{root:{key:``},static:new Fo}}function Lo(e){let t=0,n=0;for(;t<e.length;t++){let r=e.charCodeAt(t);if(r===92)t++;else if(r===40)n++;else if(r===41&&n>0)n--;else if(r===123&&n===0)break}if(t>=e.length)return;let r=t+1;for(n=0;r<e.length;r++){let t=e.charCodeAt(r);if(t===92)r++;else if(t===40)n++;else if(t===41&&n>0)n--;else if(t===125&&n===0)break}if(r>=e.length)return;let i=e[r+1],a=i===`?`||i===`+`||i===`*`;return[e.slice(0,t),e.slice(t+1,r),e.slice(r+(a?2:1)),a?i:void 0]}function Ro(e){if(!e.includes(`{`))return;let t=Lo(e);if(!t)return;let[n,r,i,a]=t;if(!a)return[n+r+i];if(a===`?`)return[n+r+i,n+i];if(r.includes(`/`))throw Error(`unsupported group repetition across segments`);return[`${n}(?:${r})${a}${i}`]}var zo=`__rou3_unnamed_`,Bo=`__rou3_esc_`;function Vo(e){return`${zo}${e}`}function Ho(e){return/^(?!__rou3_|_\d)[A-Za-z_]\w*$/.test(e)?e:Bo+e.replace(/[_-]/g,e=>e===`_`?`__`:`_h`)}function Uo(e){return e.charCodeAt(0)===95?e.startsWith(`__rou3_esc_`)?e.slice(11).replace(/__|_h/g,e=>e===`__`?`_`:`-`):e.startsWith(`__rou3_unnamed_`)?e.slice(15):e:e}function Wo(e){let t=0;for(let n=0;n<e.length;n++){let r=e.charCodeAt(n);if(r===92)n++;else if(r===40)t++;else if(r===41&&t>0)t--;else if(r===42&&t===0)return!0}return!1}function Go(e,t,n=Vo){let r=0,i=t,a=``;for(let t=0;t<e.length;t++){let o=e.charCodeAt(t);o===92?(a+=e[t],t+1<e.length&&(a+=e[++t])):o===40?(r++,a+=e[t]):o===41&&r>0?(r--,a+=e[t]):a+=o===42&&r===0?`(?<${n(i++)}>[^/]*)`:e[t]}return[a,i]}function Ko(e){return e.includes(`\\`)?e.replace(/\\([:(){}])/g,(e,t)=>`�`+`ABCDE`[`:(){}`.indexOf(t)]):e}function qo(e){return e.startsWith(`**`)?2:e===`*`||e.includes(`:`)||e.includes(`(`)||Wo(e)?1:e===`\\*`?`*`:e===`\\*\\*`?`**`:e.includes(`�`)?e.replace(/\uFFFD([A-E])/g,(e,t)=>t===`A`?`:`:t===`B`?`(`:t===`C`?`)`:t===`D`?`{`:`}`):e}function Jo(e){for(let t=0;t<e.length;t++){let n=e[t].charCodeAt(e[t].length-1);if(n!==63&&n!==43&&n!==42)continue;let r=e[t].match(/^(.*:[\w-]+(?:\([^)]*\))?)([?+*])$/);if(!r)continue;let i=e.slice(0,t),a=e.slice(t+1);if(r[2]===`?`)return[`/`+i.concat(r[1]).concat(a).join(`/`),`/`+i.concat(a).join(`/`)];let o=r[1].match(/:([\w-]+)/)?.[1]||`_`,s=`/`+[...i,`**:${o}`,...a].join(`/`),c=`/`+[...i,...a].join(`/`);return r[2]===`+`?[s]:[s,c]}}function Yo(e){if(!e.includes(`/.`))return e;let t=[];for(let n of e.split(`/`))if(n===`.`)continue;else n===`..`&&t.length>1?t.pop():t.push(n);return t.join(`/`)||`/`}function Xo(e){let t=e.split(`/`);return t.shift(),t[t.length-1]===``&&t.pop(),t}function Zo(e){let t=Xo(e);for(;t[t.length-1]===``;)t.pop();return t}function Qo(e,t){let n=new Fo;for(let[r,i]of t){let t=r<0?e.slice(-(r+1)).join(`/`):e[r];if(typeof i==`string`)n[i]=t;else{let e=t.match(i);if(e)for(let t in e.groups)n[Uo(t)]=e.groups[t]}}return n}function $o(e,t=``,n,r){t=t.toUpperCase(),n.charCodeAt(0)!==47&&(n=`/${n}`);let i=Ro(n);if(i){for(let n of i)$o(e,t,n,r);return}n=Ko(n);let a=Zo(n),o=Jo(a);if(o){for(let n of o)$o(e,t,n,r);return}let s=e.root,c=0,l=[],u=[];for(let e=0;e<a.length;e++){let t=a[e],n=qo(t);if(n===2){s.wildcard||(s.wildcard={key:`**`}),s=s.wildcard,l.push([-(e+1),t.split(`:`)[1]||`_`,t.length===2]);break}if(n===1){if(s.param||(s.param={key:`*`}),s=s.param,t===`*`)l.push([e,String(c++),!0]);else if(t.includes(`(`)||t.includes(`:`,1)||!/^:[\w-]+$/.test(t)){let[n,r]=es(t,c);c=r,u[e]=n,s.hasRegexParam=!0,l.push([e,n,!1])}else l.push([e,t.slice(1),!1]);continue}t=a[e]=n;let r=s.static?.[t];if(r)s=r;else{let e={key:t};s.static||(s.static=new Fo),s.static[t]=e,s=e}}let d=l.length>0,f=s.methods??=new Fo;(f[t]??=[]).push({data:r||null,paramsRegexp:u,paramsMap:d?l:void 0}),d||(e.static[`/`+a.join(`/`)]=s)}function es(e,t=0){let n=t,r=``,i=0;for(let t=0;t<e.length;t++){let n=e.charCodeAt(t);if(n===40)i++;else if(n===41&&i>0)i--;else if(n===92&&i===0&&t+1<e.length){let n=e[t+1];if(n!==`:`&&n!==`(`&&n!==`*`&&n!==`\\`){r+=``+n,t++;continue}}else if(n===46&&i===0){r+=`\\.`;continue}r+=e[t]}[r,n]=Go(r,n);let a=r.replace(/:([\w-]+)(?:\(([^)]*)\))?/g,(e,t,n)=>`(?<${Ho(t)}>${n||`[^/]+`})`).replace(/\((?![?<])/g,()=>`(?<${Vo(n++)}>`).replace(/\uFFFE(.)/g,(e,t)=>/[.*+?^${}()|[\]\\]/.test(t)?`\\${t}`:t);return[RegExp(`^${a}$`),n]}function ts(e,t=``,n,r){r?.normalize&&(n=Yo(n)),n.charCodeAt(n.length-1)===47&&(n=n.slice(0,-1));let i=e.static[n];if(i&&i.methods){let e=i.methods[t]||i.methods[``];if(e!==void 0)return e[0]}let a=Xo(n),o=ns(e.root,t,a,0);if(o!==void 0)return r?.params===!1?o:{data:o.data,params:o.paramsMap?Qo(a,o.paramsMap):void 0}}function ns(e,t,n,r){if(r===n.length){if(e.methods){let r=rs(e.methods,t,n,e.key===`*`,!1);if(r)return r}return e.param?.methods&&rs(e.param.methods,t,n,!0,!0)||e.wildcard?.methods&&rs(e.wildcard.methods,t,n,!0,!0)||void 0}let i=n[r];if(e.static){let a=e.static[i];if(a){let e=ns(a,t,n,r+1);if(e)return e}}if(e.param){let i=ns(e.param,t,n,r+1);if(i)return i}if(e.wildcard&&e.wildcard.methods)return rs(e.wildcard.methods,t,n,!0,!1)}function rs(e,t,n,r,i){let a=e[t]||e[``];if(!a)return;let o=a[0];if(a.length===1&&o.paramsRegexp.length===0){if(!i)return o;let e=o.paramsMap;return e?.[e.length-1]?.[2]?o:void 0}let s,c=-1;for(let e of a){let t=e.paramsMap,a=t?.[t.length-1]?.[2];if(i&&!a)continue;let o=r&&t&&!a?1:0,l=e.paramsRegexp;for(let e=0;e<l.length;e++)if(l[e]){if(!l[e].test(n[e])){o=-1;break}o++}o>c&&(s=e,c=o)}return s}function is(e,t=``,n,r){r?.normalize&&(n=Yo(n)),n.charCodeAt(n.length-1)===47&&(n=n.slice(0,-1));let i=Xo(n),a=as(e.root,t,i,0);return r?.params===!1?a:a.map(e=>({data:e.data,params:e.paramsMap?Qo(i,e.paramsMap):void 0}))}function as(e,t,n,r,i=[]){let a=n[r];if(e.wildcard&&e.wildcard.methods){let a=e.wildcard.methods[t]||e.wildcard.methods[``];if(a){if(r<n.length)os(i,a,!0);else{let e=[];for(let t of a){let n=t.paramsMap;n?.[n.length-1]?.[2]&&e.push(t)}os(i,e,!0)}}}if(e.param){if(r<n.length){let o=i.length;if(as(e.param,t,n,r+1,i),e.param.hasRegexParam)for(let e=i.length-1;e>=o;e--)i[e].paramsRegexp[r]?.test(a)===!1&&i.splice(e,1)}else if(e.param.methods){let n=e.param.methods[t]||e.param.methods[``];if(n){let e=[];for(let t of n){let n=t.paramsMap;n?.[n.length-1]?.[2]&&e.push(t)}os(i,e,!0)}}}if(r<n.length){let o=e.static?.[a];o&&as(o,t,n,r+1,i)}if(r===n.length&&e.methods){let n=e.methods[t]||e.methods[``];n&&os(i,n,e.key===`*`)}return i}function os(e,t,n){t.length>1&&(t=t.map(e=>{let t=0,{paramsRegexp:r,paramsMap:i}=e;for(let e=0;e<r.length;e++)r[e]&&t++;return n&&i&&!i[i.length-1][2]&&t++,[e,t]}).sort((e,t)=>e[1]-t[1]).map(e=>e[0]));for(let n of t)e.push(n)}var ss=(e,t)=>{if(!t?.openapi?.disabled){let n={path:`/api/reference`,...t?.openapi};e.openapi=To(n.path,{method:`GET`},async t=>{let r=await No(e);return new Response(Po(r,n.scalar),{headers:{"Content-Type":`text/html`}})})}let n=Io(),r=Io();for(let t of Object.values(e)){if(!t.options||!t.path||t.options?.metadata?.SERVER_ONLY)continue;let e=Array.isArray(t.options?.method)?t.options.method:[t.options?.method];for(let r of e)$o(n,r,t.path,t)}if(t?.routerMiddleware?.length)for(let{path:e,middleware:n}of t.routerMiddleware)$o(r,`*`,e,n);let i=t?.basePath&&t.basePath!==`/`?t.basePath.replace(/\/+$/,``):``,a=async e=>{let a=new URL(e.url),o=a.pathname,s;if(i){if(!o.startsWith(`${i}/`))return new Response(null,{status:404,statusText:`Not Found`});s=o.slice(i.length)}else s=o;if(s.length===0||/\/{2,}/.test(s))return new Response(null,{status:404,statusText:`Not Found`});let c=ts(n,e.method,s);if(s.endsWith(`/`)!==c?.data?.path?.endsWith(`/`)&&!t?.skipTrailingSlashes||!c?.data)return new Response(null,{status:404,statusText:`Not Found`});let l={};a.searchParams.forEach((e,t)=>{t in l?Array.isArray(l[t])?l[t].push(e):l[t]=[l[t],e]:l[t]=e});let u=c.data;try{let n=u.options.metadata?.allowedMediaTypes||t?.allowedMediaTypes,i={path:s,method:e.method,headers:e.headers,params:c.params?{...c.params}:{},request:e,body:u.options.disableBody?void 0:await no(u.options.cloneRequest?e.clone():e,n),query:l,_flag:`router`,asResponse:!0,context:t?.routerContext},a=is(r,`*`,s);if(a?.length)for(let{data:e,params:t}of a){let n=await e({...i,params:t?{...t}:{},asResponse:!1});if(n instanceof Response)return n}return await u(i)}catch(n){if(t?.onError)try{let r=await t.onError(n,e);if(r instanceof Response)return wo(r)}catch(e){if(ro(e))return wo(e);throw e}if(t?.throwError)throw n;return ro(n)?wo(n):(console.error(`# SERVER_ERROR: `,n),new Response(null,{status:500,statusText:`Internal Server Error`}))}};return{handler:async e=>{let n=await t?.onRequest?.(e);if(n instanceof Response)return n;let r=oo(n)?n:e,i=await a(r),o=await t?.onResponse?.(i,r);return o instanceof Response?o:i},endpoints:e}};function cs(e){return Object.fromEntries(Object.entries(e).map(([e,t])=>[e,{code:e,message:t,toString:()=>e}]))}var ls=cs({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`,CHANGE_EMAIL_DISABLED:`Change email is disabled`,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 us(e){return Array.isArray(e)?e.map(e=>typeof e==`string`?e.trim():``).filter(Boolean):typeof e==`string`?e.trim().split(/\s+/).filter(Boolean):[]}function ds(e){let t=e=>new Date(new Date().getTime()+e*1e3);return{tokenType:e.token_type,accessToken:e.access_token,refreshToken:e.refresh_token,accessTokenExpiresAt:e.expires_in?t(e.expires_in):void 0,refreshTokenExpiresAt:e.refresh_token_expires_in?t(e.refresh_token_expires_in):void 0,scopes:us(e.scope),idToken:e.id_token,raw:e}}function fs(e,t){let n=e?e.split(`,`).map(e=>e.trim()).filter(Boolean):[],r=(t??[]).map(e=>e.trim()).filter(Boolean);return[...new Set([...n,...r])].join(`,`)}function ps(e){let t=Array.isArray(e)?e[0]:e;return typeof t==`string`&&t.length>0?t:void 0}async function ms(e){let t=new TextEncoder().encode(e),n=await crypto.subtle.digest(`SHA-256`,t);return d.encode(new Uint8Array(n),{padding:!1})}var hs=/^Basic +(.*)$/i;function gs(e){return new URLSearchParams({v:e}).toString().slice(2)}function _s(e){let t=new URLSearchParams(`v=${e}`).get(`v`);if(t===null)throw Error(`form-url-encoded value could not be decoded`);return t}function vs(e,t){let n=`${gs(e)}:${gs(t)}`;return`Basic ${w.encode(n)}`}function ys(e){let t=e.match(hs);if(!t)throw Error(`Authorization header is not a Basic credential`);let n=t[1]??``,r=new TextDecoder().decode(w.decode(n)),i=r.indexOf(`:`);if(i===-1)throw Error(`Basic credential is missing the client id/secret separator`);let a=r.slice(0,i),o=r.slice(i+1);if(!a||!o)throw Error(`Basic credential client id and secret must both be non-empty`);return{clientId:_s(a),clientSecret:_s(o)}}var bs=[`RS256`,`RS384`,`RS512`,`PS256`,`PS384`,`PS512`,`ES256`,`ES384`,`ES512`,`EdDSA`],xs=`urn:ietf:params:oauth:client-assertion-type:jwt-bearer`;async function Ss({getClientAssertion:e,context:t}){return{client_assertion:await e(t),client_assertion_type:xs}}var Cs=class extends Error{constructor(e,t,n){super(t||e.toString(),{cause:n}),this.status=e,this.statusText=t,this.error=n,Error.captureStackTrace(this,this.constructor)}},ws=async(e,t)=>{let n=t||{},r={onRequest:[t?.onRequest],onResponse:[t?.onResponse],onSuccess:[t?.onSuccess],onError:[t?.onError],onRetry:[t?.onRetry]};if(!t||!t?.plugins)return{url:e,options:n,hooks:r};for(let i of t?.plugins||[]){if(i.init){let t=await i.init?.call(i,e.toString(),n);n=t.options||n,e=t.url}r.onRequest.push(i.hooks?.onRequest),r.onResponse.push(i.hooks?.onResponse),r.onSuccess.push(i.hooks?.onSuccess),r.onError.push(i.hooks?.onError),r.onRetry.push(i.hooks?.onRetry)}return{url:e,options:n,hooks:r}},Ts=class{constructor(e){this.options=e}shouldAttemptRetry(e,t){return this.options.shouldRetry?Promise.resolve(e<this.options.attempts&&this.options.shouldRetry(t)):Promise.resolve(e<this.options.attempts)}getDelay(){return this.options.delay}},Es=class{constructor(e){this.options=e}shouldAttemptRetry(e,t){return this.options.shouldRetry?Promise.resolve(e<this.options.attempts&&this.options.shouldRetry(t)):Promise.resolve(e<this.options.attempts)}getDelay(e){return Math.min(this.options.maxDelay,this.options.baseDelay*2**e)}};function Ds(e){if(typeof e==`number`)return new Ts({type:`linear`,attempts:e,delay:1e3});switch(e.type){case`linear`:return new Ts(e);case`exponential`:return new Es(e);default:throw Error(`Invalid retry strategy`)}}var Os=[`get`,`post`,`put`,`patch`,`delete`];function ks(e){if(!e.startsWith(`@`))return{method:void 0,path:e};let t=e.indexOf(`/`),n=e.slice(1,t===-1?void 0:t);return Os.includes(n)?{method:n,path:t===-1?e:e.slice(t+1)}:{method:void 0,path:e}}var As=e=>e===`.`||e===`..`,js=e=>e.split(`:`).map(e=>encodeURIComponent(e)).join(`:`);function Ms(e,t){let n=t.get(e);if(n===void 0)return js(e);if(As(n))throw TypeError(`Path parameters cannot be reserved path segments`);return encodeURIComponent(n)}function Ns(e,t){let{baseURL:n,params:r,query:i}=t||{query:{},params:{},baseURL:``},a=e.startsWith(`http`)?e.split(`/`).slice(0,3).join(`/`):n||``,{path:o}=ks(e);o!==e&&(e=`/${o}`),a.endsWith(`/`)||(a+=`/`);let[s,c]=e.replace(a,``).split(`?`),l=new URLSearchParams(c);for(let[e,t]of Object.entries(i||{})){if(t==null)continue;let n;if(typeof t==`string`)n=t;else if(Array.isArray(t)){for(let n of t)l.append(e,n);continue}else n=JSON.stringify(t);l.set(e,n)}let u=new Map;if(r){if(Array.isArray(r)){let e=s.split(`/`).filter(e=>e.startsWith(`:`));for(let[t,n]of e.entries()){let e=r[t];u.set(n,String(e))}}else for(let[e,t]of Object.entries(r))u.set(`:${e}`,String(t))}s=s.split(`/`).map(e=>Ms(e,u)).join(`/`),s=s.replace(/^\/+/,``);let d=l.toString();return d=d.length>0?`?${d}`.replace(/\+/g,`%20`):``,a.startsWith(`http`)?new URL(`${s}${d}`,a):`${a}${s}${d}`}var Ps=async e=>{let t={},n=async e=>typeof e==`function`?await e():e;if(e?.auth){if(e.auth.type===`Bearer`){let r=await n(e.auth.token);if(!r)return t;t.authorization=`Bearer ${r}`}else if(e.auth.type===`Basic`){let[r,i]=await Promise.all([n(e.auth.username),n(e.auth.password)]);if(!r||!i)return t;t.authorization=`Basic ${btoa(`${r}:${i}`)}`}else if(e.auth.type===`Custom`){let[r,i]=await Promise.all([n(e.auth.prefix),n(e.auth.value)]);if(!i)return t;t.authorization=`${r??``} ${i}`}}return t},Fs=/^application\/(?:[\w!#$%&*.^`~-]*\+)?json(;.+)?$/i;function Is(e){let t=e.headers.get(`content-type`),n=new Set([`image/svg`,`application/xml`,`application/xhtml`,`application/html`]);if(!t)return`json`;let r=t.split(`;`).shift()||``;return Fs.test(r)?`json`:n.has(r)||r.startsWith(`text/`)?`text`:`blob`}function Ls(e){try{return JSON.parse(e),!0}catch{return!1}}function Rs(e){if(e===void 0)return!1;let t=typeof e;return t===`string`||t===`number`||t===`boolean`||t===null?!0:t===`object`?Array.isArray(e)?!0:e.buffer?!1:e.constructor&&e.constructor.name===`Object`||typeof e.toJSON==`function`:!1}function zs(e){try{return JSON.parse(e)}catch{return e}}function Bs(e){return typeof e==`function`}function Vs(e){if(e?.customFetchImpl)return e.customFetchImpl;if(typeof globalThis<`u`&&Bs(globalThis.fetch))return globalThis.fetch;if(typeof window<`u`&&Bs(window.fetch))return window.fetch;throw Error(`No fetch implementation found`)}function Hs(...e){let t={};for(let n of e)if(n){if(n instanceof Headers)n.forEach((e,n)=>{t[n]=e});else{let e=Array.isArray(n)?n:Object.entries(n);for(let[n,r]of e)r!=null&&(t[n]=r)}}return t}async function Us(e){let t=new Headers(Hs(e?.headers,await Ps(e)));if(!t.has(`content-type`)){let n=Ws(e?.body);n&&t.set(`content-type`,n)}return t}function Ws(e){return Rs(e)?`application/json`:null}function Gs(e){let t=e.get(`content-type`);return t?t.split(`;`)[0].trim().toLowerCase():null}function Ks(e,t){let{body:n}=e;return n?!Rs(n)||typeof n==`string`?n:Gs(t)===`application/x-www-form-urlencoded`?new URLSearchParams(n).toString():JSON.stringify(n):null}function qs(e,t){if(t?.method)return t.method.toUpperCase();let{method:n}=ks(e);return n?n.toUpperCase():t?.body?`POST`:`GET`}function Js(e,t){let n;return!e?.signal&&e?.timeout&&(n=setTimeout(()=>t?.abort(),e?.timeout)),{abortTimeout:n,clearTimeout:()=>{n&&clearTimeout(n)}}}var Ys=class e extends Error{constructor(t,n){super(n||JSON.stringify(t,null,2)),this.issues=t,Object.setPrototypeOf(this,e.prototype)}};async function Xs(e,t){let n=await e[`~standard`].validate(t);if(n.issues)throw new Ys(n.issues);return n.value}function Zs(e){"@babel/helpers - typeof";return Zs=typeof Symbol==`function`&&typeof Symbol.iterator==`symbol`?function(e){return typeof e}:function(e){return e&&typeof Symbol==`function`&&e.constructor===Symbol&&e!==Symbol.prototype?`symbol`:typeof e},Zs(e)}function Qs(e,t){if(Zs(e)!=`object`||!e)return e;var n=e[Symbol.toPrimitive];if(n!==void 0){var r=n.call(e,t||`default`);if(Zs(r)!=`object`)return r;throw TypeError(`@@toPrimitive must return a primitive value.`)}return(t===`string`?String:Number)(e)}function $s(e){var t=Qs(e,`string`);return Zs(t)==`symbol`?t:t+``}function ec(e,t,n){return(t=$s(t))in e?Object.defineProperty(e,t,{value:n,enumerable:!0,configurable:!0,writable:!0}):e[t]=n,e}function tc(e,t){var n=Object.keys(e);if(Object.getOwnPropertySymbols){var r=Object.getOwnPropertySymbols(e);t&&(r=r.filter(function(t){return Object.getOwnPropertyDescriptor(e,t).enumerable})),n.push.apply(n,r)}return n}function nc(e){for(var t=1;t<arguments.length;t++){var n=arguments[t]==null?{}:arguments[t];t%2?tc(Object(n),!0).forEach(function(t){ec(e,t,n[t])}):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(n)):tc(Object(n)).forEach(function(t){Object.defineProperty(e,t,Object.getOwnPropertyDescriptor(n,t))})}return e}var rc=async(e,t)=>{var n;let{hooks:r,url:i,options:a}=await ws(e,t),o=Vs(a),s=new AbortController,c=a.signal??s.signal,l=Ns(i,a),u=await Us(a),d=Ks(a,u),f=qs(i,a),p=nc(nc({},a),{},{url:l,headers:u,body:d,method:f,signal:c});for(let e of r.onRequest)if(e){let t=await e(p);typeof t==`object`&&t&&Object.assign(p,t)}(`pipeTo`in p&&typeof p.pipeTo==`function`||typeof(t==null||(n=t.body)==null?void 0:n.pipe)==`function`)&&(`duplex`in p||(p.duplex=`half`));let{clearTimeout:m}=Js(a,s),h=await o(p.url,p);m();let g={response:h,request:p};for(let e of r.onResponse)if(e){var _;let n=await e(nc(nc({},g),{},{response:t!=null&&(_=t.hookOptions)!=null&&_.cloneResponse?h.clone():h}));n instanceof Response?h=n:typeof n==`object`&&n&&(h=n.response)}if(h.ok){if(p.method===`HEAD`)return{data:``,error:null};let e=Is(h),n={data:null,response:h,request:p};if(e===`json`||e===`text`){let e=await h.text();n.data=await(p.jsonParser??zs)(e)}else n.data=await h[e]();p?.output&&p.output&&!p.disableValidation&&(n.data=await Xs(p.output,n.data));for(let e of r.onSuccess)if(e){var v;await e(nc(nc({},n),{},{response:t!=null&&(v=t.hookOptions)!=null&&v.cloneResponse?h.clone():h}))}return t?.throw?n.data:{data:n.data,error:null}}let y=t?.jsonParser??zs,b=await h.text(),x=Ls(b),S=x?await y(b):null,C={response:h,responseText:b,request:p,error:nc(nc({},S),{},{status:h.status,statusText:h.statusText})};for(let e of r.onError)if(e){var w;await e(nc(nc({},C),{},{response:t!=null&&(w=t.hookOptions)!=null&&w.cloneResponse?h.clone():h}))}if(t?.retry){let n=Ds(t.retry),i=t.retryAttempt??0;if(await n.shouldAttemptRetry(i,h)){for(let e of r.onRetry)e&&await e(g);let a=n.getDelay(i);return await new Promise(e=>setTimeout(e,a)),await rc(e,nc(nc({},t),{},{retryAttempt:i+1}))}}if(t?.throw)throw new Cs(h.status,h.statusText,x?S:b);return{data:null,error:nc(nc({},S),{},{status:h.status,statusText:h.statusText})}},ic=new Set([301,302,303,307,308]);function ac(e){return e.type===`opaqueredirect`||ic.has(e.status)}function oc(e){return new B(`The OAuth endpoint "${e}" returned an HTTP redirect. Server-side OAuth fetches refuse redirects to prevent SSRF; configure the final endpoint URL.`)}async function sc(e,t){let n=!1,r=t?.onError,i=await rc(e,{...t,redirect:`manual`,async onError(e){ac(e.response)&&(n=!0),await r?.(e)}}).catch(t=>{throw n?oc(e):t});if(n)throw oc(e);return i}var cc=`dpop+jwt`,lc=[`EdDSA`,`ES256`,`ES512`,`PS256`,`RS256`],uc=300,dc=512,fc=new Set([`d`,`p`,`q`,`dp`,`dq`,`qi`,`oth`,`k`]);function pc(e){return{reserve:({key:t,expiresAt:n})=>e.reserveVerificationValue({identifier:`dpop-proof:${t}`,value:t,expiresAt:n})}}function Y(e,t){return Object.assign(Error(t),{code:e})}function mc(e){return e instanceof Error&&`code`in e&&e.code===`invalid_dpop_proof`}function hc(e){if(!e)return;let t=e.trim();if(!t)return;let n=/^([A-Za-z][A-Za-z0-9!#$%&'*+.^_`|~-]*)\s+(.+)$/.exec(t);if(!n)return{scheme:`Unknown`,token:t};let r=n[1]??``,i=n[2]?.trim()??``;return r.toLowerCase()===`bearer`?{scheme:`Bearer`,token:i}:r.toLowerCase()===`dpop`?{scheme:`DPoP`,token:i}:{scheme:`Unknown`,token:t}}function gc(e){return hc(e)?.token??e}function _c(e){let t=new URL(e);if(t.hash)throw Error(`DPoP proof htu must not contain a fragment`);return`${t.origin}${t.pathname}`}async function vc(e){let t=await crypto.subtle.digest(`SHA-256`,new TextEncoder().encode(e));return G(new Uint8Array(t))}async function yc(e){return gi(e,`sha256`)}function bc(e){if(!e||typeof e!=`object`||Array.isArray(e))return;let t=e.jkt;return typeof t==`string`&&t.length>0?t:void 0}function xc(e){return bc(e.cnf)}function Sc(e,t){let n=e[t];return typeof n==`string`&&n.length>0?n:void 0}function Cc(e,t){let n=e[t];return typeof n==`number`&&Number.isFinite(n)?n:void 0}function wc(e,t){if(!e||e===`none`||e.startsWith(`HS`))throw Y(`invalid_dpop_proof`,`DPoP proof must use an asymmetric JWS algorithm`);if(!t.includes(e))throw Y(`invalid_dpop_proof`,`DPoP proof uses an unsupported JWS algorithm`)}function Tc(e){if(!e||typeof e!=`object`||Array.isArray(e))throw Y(`invalid_dpop_proof`,`DPoP proof header must include a public jwk`);if(e.kty===`oct`)throw Y(`invalid_dpop_proof`,`DPoP proof jwk must be asymmetric`);for(let t of fc)if(t in e)throw Y(`invalid_dpop_proof`,`DPoP proof jwk must not contain private key material`)}async function Ec(e){let t=`${e.jkt}\n${e.htm}\n${e.htu}\n${e.jti}`,n=await crypto.subtle.digest(`SHA-256`,new TextEncoder().encode(t));return G(new Uint8Array(n))}async function Dc(e,t){if(e&&!await e.reserve(t))throw Y(`invalid_dpop_proof`,`DPoP proof jti has already been used`)}async function Oc({proofJwt:e,method:t,url:n,accessToken:r,expectedJkt:i,requireAth:a=!1,nowSeconds:o=Math.floor(Date.now()/1e3),proofMaxAgeSeconds:s=uc,signingAlgorithms:c=lc,replayStore:l}){if(!e||e.split(`.`).length!==3)throw Y(`invalid_dpop_proof`,`DPoP proof must be a compact JWT`);let u;try{u=Si(e)}catch(e){throw Y(`invalid_dpop_proof`,e instanceof Error?e.message:`DPoP proof header is invalid`)}if(u.typ!==`dpop+jwt`)throw Y(`invalid_dpop_proof`,`DPoP proof typ must be "dpop+jwt"`);wc(u.alg,c),Tc(u.jwk);let d;try{d=(await Gr(e,await xi(u.jwk,u.alg),{typ:cc})).payload}catch(e){throw Y(`invalid_dpop_proof`,e instanceof Error?e.message:`DPoP proof signature is invalid`)}let f=Sc(d,`htm`),p=Sc(d,`htu`),m=Sc(d,`jti`),h=Cc(d,`iat`);if(!f||!p||!m||h===void 0)throw Y(`invalid_dpop_proof`,`DPoP proof must include htm, htu, jti, and iat claims`);if(m.length>dc)throw Y(`invalid_dpop_proof`,`DPoP proof jti is too large`);if(f.toUpperCase()!==t.toUpperCase())throw Y(`invalid_dpop_proof`,`DPoP proof htm does not match the request method`);let g,_;try{g=_c(n),_=_c(p)}catch(e){throw Y(`invalid_dpop_proof`,e instanceof Error?e.message:`DPoP proof htu is invalid`)}if(_!==g)throw Y(`invalid_dpop_proof`,`DPoP proof htu does not match the request URL`);if(h>o+5||o-h>s)throw Y(`invalid_dpop_proof`,`DPoP proof iat is outside the accepted window`);let v=Sc(d,`ath`);if(a&&!v)throw Y(`invalid_dpop_proof`,`DPoP proof must include an ath claim`);if(r!==void 0&&v!==await vc(r))throw Y(`invalid_dpop_proof`,`DPoP proof ath does not match the access token`);let y=await yc(u.jwk);if(i!==void 0&&y!==i)throw Y(`invalid_dpop_proof`,`DPoP proof key does not match the bound token`);let b=await Ec({jkt:y,htm:f.toUpperCase(),htu:g,jti:m}),x=new Date((h+s)*1e3);return await Dc(l,{key:b,expiresAt:x,now:new Date(o*1e3)}),{jwk:u.jwk,jkt:y,jti:m,htm:f,htu:g,iat:h,ath:v,replayKey:b,expiresAt:x}}function kc(e,t){return Object.assign(Error(t),{code:e})}function Ac(e){return e instanceof Error&&`code`in e&&(e.code===`invalid_token`||e.code===`invalid_dpop_proof`)}async function jc({payload:e,authorization:t,proofJwt:n,method:r,url:i,replayStore:a,proofMaxAgeSeconds:o,signingAlgorithms:s}){let c=xc(e);if(c){if(t.scheme!==`DPoP`)throw kc(`invalid_token`,`DPoP-bound access token requires the DPoP authorization scheme`);if(!n)throw kc(`invalid_dpop_proof`,`DPoP proof header is required`);try{await Oc({proofJwt:n,method:r,url:i,accessToken:t.token,expectedJkt:c,requireAth:!0,proofMaxAgeSeconds:o,signingAlgorithms:s,replayStore:a})}catch(e){throw mc(e)?kc(`invalid_dpop_proof`,e.message):e}}else if(t.scheme===`DPoP`)throw kc(`invalid_token`,`DPoP authorization requires a DPoP-bound access token`)}xt.code,vt.code,bt.code;var Mc=new Map,Nc=new WeakMap,Pc=3e5,Fc=3e4,Ic=5e3;function Lc(e,t){let n=e.get(t);return n||(n={fetchedAt:0,refetchedAt:0},e.set(t,n)),n}function Rc(e,t){return e.pending!==void 0&&t-e.pending.startedAt<Ic}async function zc(e,t){let n=Date.now();if(!e.pending||!Rc(e,n)){let r={startedAt:n,promise:Vc(t).then(t=>(n>=e.fetchedAt&&(e.jwks=t,e.fetchedAt=n),t)).finally(()=>{e.pending===r&&(e.pending=void 0)})};e.pending=r}let{promise:r,startedAt:i}=e.pending,a;try{return await Promise.race([r,new Promise((e,t)=>{a=setTimeout(()=>t(new xt),i+Ic-n)})])}finally{clearTimeout(a)}}async function Bc(e,t,n){if(e.jwks!==t)return e.jwks;let r=Date.now();if(!Rc(e,r)){if(r-e.refetchedAt<Fc)return;e.refetchedAt=r}return zc(e,n)}async function Vc(e){try{let t=typeof e==`string`?await sc(e,{headers:{Accept:`application/json`}}).then(async e=>{if(e.error)throw Error(`Jwks failed: ${e.error.message??e.error.statusText}`);return e.data}):await e();if(!t)throw Error(`No jwks found`);return t}catch(e){if(e instanceof TypeError){try{ve.error(`JWKS fetch failed:`,e)}catch{}throw Error(`JWKS fetch failed`)}throw e}}async function Hc(e,t){return(await Uc(e,t)).jwks}async function Uc(e,t){let n;try{n=Si(e)}catch(e){throw e instanceof Error?e:Error(e)}let r=n.kid,i=typeof t.jwksFetch==`string`?Lc(Mc,t.jwksFetch):t.jwksCacheKey?Lc(Nc,t.jwksCacheKey):{fetchedAt:0,refetchedAt:0},a=Date.now()-i.fetchedAt<Pc?i.jwks:void 0;if(!a)return{jwks:await zc(i,t.jwksFetch),kid:r};let o=e=>Bc(i,e,t.jwksFetch);return!r||a.keys.some(e=>e.kid===r)?{jwks:a,kid:r,refresh:o}:{jwks:await o(a)??a,kid:r}}var Wc=Object.freeze(Object.keys({clientId:!0,clientSecret:!0,clientDiscoveryId:!0,disabled:!0,scopes:!0,clientCredentialsScopes:!0,userId:!0,createdAt:!0,updatedAt:!0,expiresAt:!0,name:!0,uri:!0,icon:!0,contacts:!0,tos:!0,policy:!0,softwareId:!0,softwareVersion:!0,softwareStatement:!0,redirectUris:!0,postLogoutRedirectUris:!0,backchannelLogoutUri:!0,backchannelLogoutSessionRequired:!0,frontchannelLogoutUri:!0,frontchannelLogoutSessionRequired:!0,tokenEndpointAuthMethod:!0,grantTypes:!0,responseTypes:!0,applicationType:!0,jwks:!0,jwksUri:!0,requirePKCE:!0,dpopBoundAccessTokens:!0,skipConsent:!0,enableEndSession:!0,subjectType:!0,sectorIdentifier:!0,referenceId:!0,metadata:!0})),Gc=`client_id.client_secret.client_secret_expires_at.scope.user_id.client_id_issued_at.client_name.client_uri.logo_uri.contacts.tos_uri.policy_uri.jwks.jwks_uri.software_id.software_version.software_statement.redirect_uris.post_logout_redirect_uris.backchannel_logout_uri.backchannel_logout_session_required.frontchannel_logout_uri.frontchannel_logout_session_required.token_endpoint_auth_method.grant_types.response_types.application_type.disabled.skip_consent.enable_end_session.require_pkce.dpop_bound_access_tokens.subject_type.reference_id`.split(`.`),Kc=new Set([...Wc,...Gc,`public`,`type`,`resources`,`client_credentials_scopes`]),qc=new Set(`disabled.client_secret.client_secret_expires_at.client_id_issued_at.skip_consent.enable_end_session.require_pkce.reference_id.user_id.resources.clientSecret.clientDiscoveryId.sectorIdentifier.skipConsent.enableEndSession.requirePKCE.referenceId.userId.clientId.applicationType.tokenEndpointAuthMethod.redirectUris.postLogoutRedirectUris.grantTypes.responseTypes.scopes.expiresAt.createdAt.updatedAt.softwareId.softwareVersion.softwareStatement.backchannelLogoutUri.backchannelLogoutSessionRequired.jwksUri.dpopBoundAccessTokens.subjectType`.split(`.`));function Jc(e){return qc.has(e)}function Yc(e){return Kc.has(e)}function Xc(e){if(e)return Object.fromEntries(Object.entries(e).filter(([e])=>!Kc.has(e)))}var Zc=[`authorization_code`,`client_credentials`,`refresh_token`],Qc=[`client_secret_basic`,`client_secret_post`,`private_key_jwt`],$c=[`none`,...Qc],el=new Set($c);function tl(e,t){if(!(t.trim().length>0))throw new B(`OAuth Provider extension ${e} cannot be empty`)}function nl(e,t){tl(e,t);let n;try{n=new URL(t)}catch{n=void 0}if(!n?.protocol)throw new B(`OAuth Provider extension ${e} must be an absolute URI: ${t}`)}function rl(e){nl(`grant type`,e)}function il(e){if(tl(`token_endpoint_auth_method`,e),el.has(e))throw new B(`OAuth Provider extension token_endpoint_auth_method is reserved: ${e}`)}function al(e){if(nl(`client_assertion_type`,e),e===`urn:ietf:params:oauth:client-assertion-type:jwt-bearer`)throw new B(`OAuth Provider extension client_assertion_type is reserved: ${e}`)}function ol(e){let t=Object.keys(e.grants??{});for(let e of t)rl(e);let n=[],r=[];for(let[t,i]of Object.entries(e.clientAuthentication??{})){il(t),n.push(t);let e=i.assertionTypes??[t];if(e.length===0)throw new B(`OAuth Provider extension client_assertion_type list cannot be empty for ${t}`);for(let t of e)al(t),r.push(t)}let i=(e.clientDiscovery?Array.isArray(e.clientDiscovery)?e.clientDiscovery:[e.clientDiscovery]:[]).map(e=>e.id);for(let e of i)tl(`client discovery id`,e);for(let t of e.clientMetadata?.fields??[])if(tl(`client metadata field`,t),Yc(t))throw new B(`OAuth Provider extension client metadata field is reserved: ${t}`);return{grantTypes:t,authMethods:n,assertionTypes:r,clientDiscoveryIds:i,interactionRequestParameters:Object.keys(e.interactionRequests??{})}}function sl(e,t){let n=new Set;for(let r of t){if(n.has(r))throw new B(`OAuth Provider extensions register ${e} "${r}" more than once. Extension contributions must be disjoint.`);n.add(r)}}function cl(e){let t=(e??[]).map(ol);sl(`grant type`,t.flatMap(e=>e.grantTypes)),sl(`token_endpoint_auth_method`,t.flatMap(e=>e.authMethods)),sl(`client_assertion_type`,t.flatMap(e=>e.assertionTypes)),sl(`client discovery id`,t.flatMap(e=>e.clientDiscoveryIds)),sl(`interaction request parameter`,t.flatMap(e=>e.interactionRequestParameters))}function ll(e){return e.extensions??[]}function ul(e){return ll(e).flatMap(e=>{let t=e.clientDiscovery;return t?Array.isArray(t)?t:[t]:[]})}function dl(e,t){let n=e.getPlugin(`oauth-provider`);if(!n)throw new B(`extendOAuthProvider requires the oauth-provider plugin.`);let r=n.options.extensions??[];if(r.includes(t))return;let i=[...r,t];cl(i),n.options.extensions=i}function fl(e){return ll(e).flatMap(e=>Object.keys(e.grants??{}))}function pl(e){return Array.from(new Set([...e.grantTypes??Zc,...fl(e)]))}function ml(e,t){let n=t;if(n.response_type===void 0&&n.request_uri===void 0)for(let t of ll(e))for(let[e,r]of Object.entries(t.interactionRequests??{})){let t=n[e];if(typeof t==`string`&&t)return{parameter:e,handler:r,value:t}}}function hl(e,t){for(let n of ll(e)){let e=n.grants?.[t];if(e)return e}}function gl(e){return ll(e).flatMap(e=>Object.keys(e.clientAuthentication??{}))}function _l(e,t){return Array.from(new Set([...t?.includeNone?[`none`]:[],...Qc,...gl(e)]))}function vl(e,t){return t?gl(e).includes(t):!1}function yl(e,t){if(t!==`urn:ietf:params:oauth:client-assertion-type:jwt-bearer`)for(let n of ll(e)){let e=n.clientAuthentication??{};for(let[n,r]of Object.entries(e))if((r.assertionTypes??[n]).includes(t))return{method:n,strategy:r}}}function bl(e,t,n,r){let i={...r};for(let a of ll(t)){let o=a.metadata?.({ctx:e,opts:t,type:n,document:r});for(let[e,t]of Object.entries(o??{}))e in i||(i[e]=t)}return i}async function xl(e,t){let n={};for(let r of ll(e)){let e=await t(r)??{};for(let[t,r]of Object.entries(e))t in n?ve.warn(`oauth-provider: two extensions contributed the claim "${t}"; keeping the first-registered value.`):n[t]=r}return n}function Sl(e,t){return xl(e,e=>e.claims?.accessToken?.(t))}function Cl(e,t){return xl(e,e=>e.claims?.idToken?.(t))}function wl(e,t){return xl(e,e=>e.claims?.userInfo?.(t))}function Tl(e){return ll(e).some(e=>e.clientMetadata)}function El(e){return new Set(ll(e).flatMap(e=>e.clientMetadata?.fields??[]))}async function Dl(e,t,n){let{metadata:r,...i}=t,a=El(e),o={client:Object.fromEntries(Object.entries(i).filter(([e])=>!a.has(e))),metadata:Xc(n)??{}};for(let t of ll(e))await t.clientMetadata?.validate?.(o)}function Ol(e){return ll(e).some(e=>e.claims?.userInfo)}function kl(e){if(!e)return;let[t,n,...r]=e.trim().split(/\s+/);if(t?.toLowerCase()===`bearer`){if(!n||r.length>0)throw new g(`BAD_REQUEST`,{error:`invalid_request`,error_description:`Malformed Bearer Authorization header`});return n}}function Al(){let e=new Map;return{get(t){let n=e.get(t);if(n){if(n.expiresAt&&n.expiresAt<new Date)e.delete(t);else return n}},set(t,n){e.set(t,n)}}}var jl=e=>e.getPlugin(`oauth-provider`),Ml=e=>{let t=e.getPlugin(`jwt`);if(!t)throw new B(`jwt_config`);return t};function Nl(e){if(e!=null){if(e instanceof Date)return Number.isFinite(e.getTime())?e:void 0;if(typeof e==`number`){if(!Number.isFinite(e))return;let t=new Date(e);return Number.isFinite(t.getTime())?t:void 0}if(typeof e==`string`){let t=e.trim();if(!t.length)return;let n=Number(t);if(Number.isFinite(n)){let e=new Date(n);return Number.isFinite(e.getTime())?e:void 0}let r=new Date(t);return Number.isFinite(r.getTime())?r:void 0}}}function Pl(e){if(e instanceof Date||!e||typeof e!=`object`)return Nl(e);let t=Nl(e.createdAt)??Nl(e.created_at);if(t)return t;let n=e.session;if(n&&typeof n==`object`)return Nl(n.createdAt)??Nl(n.created_at)}function Fl(e){if(typeof e==`string`)return[e];if(e?.length)return e}function Il(e){if(typeof e==`string`)return e;if(e?.length)return e.length===1?e.at(0):e}var Ll=new WeakMap;function Rl(e){let t=Ll.get(e);if(t)return t;let n=Al();return Ll.set(e,n),n}async function zl(e,t){let n=new URLSearchParams(e),r=n.get(`sig`),i=n.getAll(`sig`),a=Number(n.get(`exp`));n.delete(`sig`);let o=await Ya(je(n).toString(),t);return i.length===1&&!!r&&Ri(r,o)&&new Date(a*1e3)>=new Date}function Bl(e,t){if(e.cachedTrustedClients?.has(t))throw new g(`BAD_REQUEST`,{error:`invalid_client`,error_description:`trusted clients must be updated manually`})}async function Vl(e,t,n){let r=Rl(t),i=r.get(n);if(i&&!i.clientDiscoveryId)return Object.assign({},i);let a=await e.context.adapter.findOne({model:t.schema?.oauthClient?.modelName??`oauthClient`,where:[{field:`clientId`,value:n}]}),o=ul(t);if(a?.clientDiscoveryId){let t=a.clientDiscoveryId,r=o.find(e=>e.id===t);if(!r?.matches(n)||(a=await r.resolve(e,n,a),!a))return null}else if(a)return t.cachedTrustedClients?.has(n)&&r.set(n,Object.assign({},a)),a;else for(let t of o){if(!t.matches(n))continue;let r=await t.resolve(e,n,null);if(r){a=r;break}}return a}function Hl(e){return e.reduce((e,t)=>({...e,...t.discoveryMetadata??{}}),{})}var Ul=async e=>{let t=await Vi(`SHA-256`).digest(new TextEncoder().encode(e));return d.encode(new Uint8Array(t),{padding:!1})};async function Wl(e,t,n){if(t===`encrypted`)return await qa({key:e.context.secretConfig,data:n});if(typeof t==`object`&&`decrypt`in t)return await t.decrypt(n);throw new B(`Unsupported decryption storageMethod type '${t}'`)}async function Gl(e,t,n,r){let i=t.storeClientSecret??(t.disableJwtPlugin?`encrypted`:`hashed`);if(r&&t.prefix?.clientSecret){if(r.startsWith(t.prefix?.clientSecret))r=r.replace(t.prefix.clientSecret,``);else throw new g(`UNAUTHORIZED`,{error_description:`invalid client_secret`,error:`invalid_client`})}if(i===`hashed`){let e=r?await Ul(r):void 0;return!!e&&Ri(e,n)}if(typeof i==`object`&&`hash`in i){if(i.verify)return!!r&&await i.verify(r,n);{let e=r?await i.hash(r):void 0;return!!e&&Ri(e,n)}}if(i===`encrypted`)try{let t=await Wl(e,i,n);return!!r&&Ri(t,r)}catch{return!1}if(typeof i==`object`&&`decrypt`in i){let t=await Wl(e,i,n);return!!r&&Ri(t,r)}throw new B(`Unsupported verify storageMethod type '${i}'`)}async function Kl(e,t,n){let r=t.storeClientSecret??(t.disableJwtPlugin?`encrypted`:`hashed`);if(r===`encrypted`)return await Ka({key:e.context.secretConfig,data:n});if(r===`hashed`)return await Ul(n);if(typeof r==`object`&&`hash`in r)return await r.hash(n);if(typeof r==`object`&&`encrypt`in r)return await r.encrypt(n);throw new B(`Unsupported storeClientSecret type '${r}'`)}async function ql(e=`hashed`,t,n){if(e===`hashed`)return await Ul(t);if(typeof e==`object`&&`hash`in e)return await e.hash(t,n);throw new B(`storeToken: unsupported storageMethod type '${e}'`)}async function Jl(e=`hashed`,t,n){if(e===`hashed`)return await Ul(t);if(typeof e==`object`&&`hash`in e)return await e.hash(t,n);throw new B(`getStoredToken: unsupported storageMethod type '${e}'`)}var Yl=/^Basic +/i,Xl=/^([!#$%&'*+\-.^_`|~0-9A-Za-z]+)(?=\s|$)/;function Zl(e){return e.match(Xl)?.[1]}var Ql=[`client_secret`,`client_assertion`,`client_assertion_type`];function $l(e){throw new g(`BAD_REQUEST`,{error:`invalid_request`,error_description:e})}async function eu(e){if(!(e.headers.get(`content-type`)?.toLowerCase()??``).includes(`application/x-www-form-urlencoded`))return;let t;try{t=await e.clone().text()}catch{return}return t?new URLSearchParams(t):void 0}function tu(e,t,n=[]){let r={...t};for(let t of new Set(e.keys())){let i=e.getAll(t),a=i.filter(Boolean);if(a.length>1&&!n.includes(t))throw new g(`BAD_REQUEST`,{error:`invalid_request`,error_description:`${t} must not be repeated`});r[t]===i.at(-1)&&(a.length===0?delete r[t]:r[t]=a.length===1?a[0]:a)}return r}async function nu(e,t={}){let n;t.client_id!==void 0&&t.client_id!==``&&(typeof t.client_id!=`string`&&$l(`client_id must be a string`),n=t.client_id);let r={},i=(e,t)=>{t!==void 0&&t!==``&&(typeof t!=`string`&&$l(`${e} must be a string`),r[e]=t)};for(let e of Ql)Object.hasOwn(t,e)&&i(e,t[e]);let a=!!e?.headers.get(`authorization`);if(e&&(e.headers.get(`content-type`)?.toLowerCase()??``).includes(`application/x-www-form-urlencoded`)){let t=new URLSearchParams(await e.clone().text()),r=t.getAll(`client_id`).filter(e=>e.length>0);r.length>1&&$l(`client_id must not be repeated`),n=r[0];for(let e of Ql){let n=t.getAll(e).filter(e=>e.length>0);n.length>1&&$l(`${e} must not be repeated`),n.length===1&&i(e,n[0])}}let o=r.client_secret!==void 0,s=r.client_assertion!==void 0||r.client_assertion_type!==void 0;(a&&(o||s)||o&&s)&&$l(`A request must use only one client authentication method`),t.client_id=n;for(let e of Ql)t[e]=r[e];return{detected:a||Object.keys(r).length>0}}function ru(e){if(Yl.test(e))try{let{clientId:t,clientSecret:n}=ys(e);return{client_id:t,client_secret:n}}catch{throw new g(`UNAUTHORIZED`,{error_description:`invalid authorization header format`,error:`invalid_client`},{"WWW-Authenticate":`Basic`})}}function iu(e,t){let n=e.grantTypes&&e.grantTypes.length>0?e.grantTypes:[`authorization_code`];return t===`refresh_token`&&n.includes(`authorization_code`)?!0:n.includes(t)}function au(e,t,n){throw new g(e,{error:t,error_description:n})}function ou(e){let t=e?.trim();return t?t.split(/\s+/):[]}function su(e,t,n){let r=e.resources??[];return t.every(t=>e.scopes.includes(t))&&n.every(e=>r.includes(e))}function cu(e,t){if(!t||!e.scopes)return;let n=new Set(e.scopes);for(let e of t)if(!n.has(e))throw new g(`BAD_REQUEST`,{error_description:`client does not allow scope ${e}`,error:`invalid_scope`})}function lu(e,t){let n=t?.method===`client_secret_basic`,r=t?.scheme??(n?`Basic`:void 0);throw new g(r?`UNAUTHORIZED`:`BAD_REQUEST`,{error_description:e,error:`invalid_client`},r?{"WWW-Authenticate":r}:void 0)}async function uu(e,t,n,r,i,a,o,s){let c=await Vl(e,t,n);c||lu(`client not found`,{method:s}),c.disabled&&lu(`client is disabled`,{method:s});let l=c.tokenEndpointAuthMethod??`client_secret_basic`;if(s&&l!==s&&lu(`client registered for ${l} cannot use ${s}`,{method:s}),(c.tokenEndpointAuthMethod===`private_key_jwt`||vl(t,c.tokenEndpointAuthMethod))&&!a)throw new g(`BAD_REQUEST`,{error_description:`client registered for ${c.tokenEndpointAuthMethod} must use client_assertion`,error:`invalid_client`});if(a||(c.tokenEndpointAuthMethod!==`none`&&!r&&lu(`client secret must be provided`,{method:s}),r&&!c.clientSecret&&lu(`public client, client secret should not be received`,{method:s}),r&&!await Gl(e,t,c.clientSecret,r)&&lu(`invalid client_secret`,{method:s})),cu(c,i),o&&!iu(c,o))throw new g(`BAD_REQUEST`,{error_description:`client is not authorized to use grant type ${o}`,error:`unauthorized_client`});return c}function du(e){if(e)return typeof e==`string`?JSON.parse(e):e}function fu(e){return{clientId:e?.clientId,clientSecret:e?.kind===`client_secret`?e.clientSecret:void 0,preVerified:e?.kind===`pre_verified`,authMethod:e?.method,confirmation:e?.kind===`pre_verified`?e.confirmation:void 0}}async function pu(e,t,n){let r={...e.body??{}};await nu(e.request,r);let i=e.request?.headers.get(`authorization`)??void 0;if(r.client_assertion_type||r.client_assertion){if(!r.client_assertion||!r.client_assertion_type)throw new g(`BAD_REQUEST`,{error_description:`client_assertion and client_assertion_type must both be provided`,error:`invalid_client`});let i=r.client_assertion,a=r.client_assertion_type,o=yl(t,a);if(o){let s=await o.strategy.authenticate({ctx:e,opts:t,assertion:i,assertionType:a,clientId:r.client_id,expectedAudience:n});return{kind:`pre_verified`,method:o.method,clientId:s.clientId,confirmation:s.confirmation}}let{verifyClientAssertion:s}=await Promise.resolve().then(()=>Jg).then(e=>e.s);return{kind:`pre_verified`,method:`private_key_jwt`,clientId:(await s(e,t,i,a,r.client_id,n)).clientId}}if(i&&!Yl.test(i)){let e=Zl(i);if(!e)throw new g(`BAD_REQUEST`,{error:`invalid_request`,error_description:`Invalid authorization header format`});lu(`unsupported authorization scheme`,{scheme:e})}if(i&&Yl.test(i)){let e=ru(i);if(e)return{kind:`client_secret`,method:`client_secret_basic`,clientId:e.client_id,clientSecret:e.client_secret}}return r.client_id&&r.client_secret?{kind:`client_secret`,method:`client_secret_post`,clientId:r.client_id,clientSecret:r.client_secret}:r.client_id?{kind:`public`,method:`none`,clientId:r.client_id}:null}function mu(e){let t=e.split(` `).map(e=>e.trim()),n=new Set;for(let e of t)(e===`login`||e===`consent`||e===`create`||e===`select_account`||e===`none`)&&n.add(e);return new Set(n)}function hu(e,t){let n=(t??[]).map(e=>new URL(e)),r=n[0];return r&&n.every(e=>e.protocol===`https:`)?r.host:`client/${e}`}function gu(e){if(e.sectorIdentifier)return e.sectorIdentifier;let t=e.redirectUris?.[0];if(!t)throw new B(`Client has no redirect URIs for sector identifier`);return new URL(t).host}async function _u(e,t,n){return Ya(`${gu(t)}.${e}`,n)}async function vu(e,t,n){return t.subjectType===`pairwise`&&n.pairwiseSecret?_u(e,t,n.pairwiseSecret):e}async function yu(e,t){return await e.postLogin?.consentReferenceId?.(t)||void 0}async function bu(e,t,n,r){let i=[{field:`clientId`,value:t},{field:`userId`,value:n}];if(r)return e.context.adapter.findOne({model:`oauthConsent`,where:[...i,{field:`referenceId`,value:r}]});for(let t=0;;t+=100){let n=await e.context.adapter.findMany({model:`oauthConsent`,where:i,limit:100,offset:t,sortBy:{field:`id`,direction:`asc`}}),r=n.find(e=>!e.referenceId);if(r||n.length<100)return r??null}}function xu(e){let t=Object.create(null);for(let n of new Set(e.keys())){let r=e.getAll(n);t[n]=r.length===1?r[0]:r}return t}function Su(e,t){if(!t)return!1;let n=Nl(e);return n?n.getTime()>=t.getTime():!1}function Cu(e,t){let n=new URLSearchParams(e),r=n.get(`prompt`)?.split(` `),i=r?.findIndex(e=>e===t)??-1;return i>=0&&(r?.splice(i,1),r?.length?n.set(`prompt`,r.join(` `)):n.delete(`prompt`)),n}function wu(e){let t=new URLSearchParams(e);return t.delete(`max_age`),t}function Tu(e,t){if(e.tokenEndpointAuthMethod===`none`)return`pkce is required for public clients`;let n=t?.scopes??[],r=n.includes(`openid`),i=typeof t?.nonce==`string`&&t.nonce.length>0,a=r&&i;return n.includes(`offline_access`)&&!a?`pkce or OIDC nonce is required when requesting offline_access scope`:e.requirePKCE??!0?`pkce is required for this client`:!1}function Eu(e){return e instanceof g||e instanceof M||e?.name===`APIError`}var Du,Ou=!1;function ku(){try{return globalThis.process?.getBuiltinModule?.(`node:async_hooks`)?.AsyncLocalStorage}catch{return}}async function Au(){if(Du)return Du;let e=ku();if(e)return Du??=e,Du;try{let{AsyncLocalStorage:e}=await import(`node:async_hooks`);return Du??=e,Du}catch(e){let t=globalThis.AsyncLocalStorage;if(typeof t==`function`)return Du??=t,Du;throw typeof window<`u`?Error(`getAsyncLocalStorage is only available in server code`):(Ou||(Ou=!0,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`)),e)}}var ju=()=>c().context.endpointContextAsyncStorage,Mu=async()=>{let e=ju();if(e)return e;let t=await Au(),n=c().context;return n.endpointContextAsyncStorage??=new t};function Nu(){return o()}function Pu(){let e=Nu();if(!e)throw Error("No auth context found. Please make sure you are calling this function within a `runWithEndpointContext` callback.");return e}async function Fu(e,t){return(await Mu()).run(e,t)}var Iu={"Cache-Control":`no-store`,Pragma:`no-cache`};function Lu(e,t){Eu(t)&&e&&Object.defineProperty(t,i,{enumerable:!1,configurable:!0,value:e,writable:!1})}var Ru=Do(async()=>({})),zu=Do.create({use:[Ru,Do(async()=>({}))]}),Bu=To.create({use:[Ru]});function Vu(e,t){let n=t.metadata?.noStore===!0;return async t=>{if(n)for(let[e,n]of Object.entries(Iu))t.setHeader(e,n);try{return await Fu(t,()=>e(t))}catch(e){throw Lu(t.responseHeaders,e),e}}}function X(...e){if(e.length===3){let[t,n,r]=e;return Bu(t,n,Vu(r,n))}let[t,n]=e;return Bu(t,Vu(n,t))}function Hu(e){return{...e,metadata:{...e.metadata,SERVER_ONLY:!0}}}X.serverOnly=(e,t)=>X(Hu(e),t);function Uu(e){return e===`-`||e===`^`||e===`$`||e===`+`||e===`.`||e===`(`||e===`)`||e===`|`||e===`[`||e===`]`||e===`{`||e===`}`||e===`*`||e===`?`||e===`\\`?`\\${e}`:e}function Wu(e){let t=``;for(let n=0;n<e.length;n++)t+=Uu(e[n]);return t}function Gu(e,t=!0){if(Array.isArray(e))return`(?:${e.map(e=>`^${Gu(e,t)}$`).join(`|`)})`;let n=``,r=``,i=`.`;t===!0?(n=`/`,r=`[/\\\\]`,i=`[^/\\\\]`):t&&(n=t,r=Wu(n),r.length>1?(r=`(?:${r})`,i=`((?!${r}).)`):i=`[^${r}]`);let a=t?`${r}+?`:``,o=t?`${r}*?`:``,s=t?e.split(n):[e],c=``;for(let e=0;e<s.length;e++){let n=s[e],r=s[e+1],l=``;if(!(!n&&e>0)){if(t&&(l=e===s.length-1?o:r===`**`?``:a),t&&n===`**`)l&&(c+=e===0?``:l,c+=`(?:${i}*?${l})*?`);else{for(let e=0;e<n.length;e++){let t=n[e];t===`\\`?e<n.length-1&&(c+=Uu(n[e+1]),e++):c+=t===`?`?i:t===`*`?`${i}*?`:Uu(t)}c+=l}}}return c}function Ku(e,t){if(typeof t!=`string`)throw TypeError(`Sample must be a string, but ${typeof t} given`);return e.test(t)}function qu(e,t){if(typeof e!=`string`&&!Array.isArray(e))throw TypeError(`The first argument must be a single pattern string or an array of patterns, but ${typeof e} given`);if((typeof t==`string`||typeof t==`boolean`)&&(t={separator:t}),arguments.length===2&&!(t===void 0||typeof t==`object`&&t&&!Array.isArray(t)))throw TypeError(`The second argument must be an options object or a string/boolean separator, but ${typeof t} given`);if(t||={},t.separator===`\\`)throw Error("\\ is not a valid separator because it is used for escaping. Try setting the separator to `true` instead");let n=Gu(e,t.separator),r=RegExp(`^${n}$`,t.flags),i=Ku.bind(null,r);return i.options=t,i.pattern=e,i.regexp=r,i}var Ju=47;function Yu(e){let t=e.replace(/:\d+$/,``).replace(/^\[|\]$/g,``).toLowerCase();return t===`localhost`||t.endsWith(`.localhost`)||t===`::1`||t.startsWith(`127.`)}function Xu(e){let t=e.length;for(;t>0&&e.charCodeAt(t-1)===Ju;)t--;return t===e.length?e:e.slice(0,t)}function Zu(e){try{return(Xu(new URL(e).pathname)||`/`)!==`/`}catch{throw new B(`Invalid base URL: ${e}. Please provide a valid base URL.`)}}function Qu(e){try{let t=new URL(e);if(t.protocol!==`http:`&&t.protocol!==`https:`)throw new B(`Invalid base URL: ${e}. URL must include 'http://' or 'https://'`)}catch(t){throw t instanceof B?t:new B(`Invalid base URL: ${e}. Please provide a valid base URL.`,{cause:t})}}function $u(e,t=`/api/auth`){if(Qu(e),Zu(e))return e;let n=Xu(e);return!t||t===`/`?n:(t=t.startsWith(`/`)?t:`/${t}`,`${n}${t}`)}function ed(e,t){return!e||e.trim()===``?!1:t===`proto`?e===`http`||e===`https`:t===`host`?[/\.\./,/\0/,/[\s]/,/^[.]/,/[<>'"]/,/javascript:/i,/file:/i,/data:/i].some(t=>t.test(e))?!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(e)||/^(\d{1,3}\.){3}\d{1,3}(:[0-9]{1,5})?$/.test(e)||/^\[[0-9a-fA-F:]+\](:[0-9]{1,5})?$/.test(e)||/^localhost(:[0-9]{1,5})?$/i.test(e):!1}function td(e,t,n,r,i){if(e)return $u(e,t);if(r!==!1){let e=te.BETTER_AUTH_URL||te.NEXT_PUBLIC_BETTER_AUTH_URL||te.PUBLIC_BETTER_AUTH_URL||te.NUXT_PUBLIC_BETTER_AUTH_URL||te.NUXT_PUBLIC_AUTH_URL||(te.BASE_URL===`/`?void 0:te.BASE_URL);if(e)return $u(e,t)}let a=n?.headers.get(`x-forwarded-host`),o=n?.headers.get(`x-forwarded-proto`);if(a&&o&&i&&ed(o,`proto`)&&ed(a,`host`))try{return $u(`${o}://${a}`,t)}catch{}if(n){let e=nd(n.url);if(!e)throw new B(`Could not get origin from request. Please provide a valid base URL.`);return $u(e,t)}if(typeof window<`u`&&window.location)return $u(window.location.origin,t)}function nd(e){try{let t=new URL(e);return t.origin===`null`?null:t.origin}catch{return null}}function rd(e){try{return new URL(e).protocol}catch{return null}}function id(e){try{return new URL(e).host}catch{return null}}function ad(e){return typeof e==`object`&&!!e&&`allowedHosts`in e&&Array.isArray(e.allowedHosts)}function od(e){if(e instanceof Request)return!0;if(typeof e!=`object`||!e||Object.prototype.toString.call(e)!==`[object Request]`)return!1;let t=e;return typeof t.url==`string`&&typeof t.headers==`object`&&t.headers!==null&&typeof t.headers.get==`function`}function sd(e,t){let n=od(e)?e.headers:e;if(t){let e=n.get(`x-forwarded-host`);if(e&&ed(e,`host`))return e}let r=n.get(`host`);if(r&&ed(r,`host`))return r;if(od(e))try{return new URL(e.url).host}catch{return null}return null}function cd(e,t,n){if(t===`http`||t===`https`)return t;let r=od(e)?e.headers:e;if(n){let e=r.get(`x-forwarded-proto`);if(e&&ed(e,`proto`))return e}if(od(e))try{let t=new URL(e.url);if(t.protocol===`http:`||t.protocol===`https:`)return t.protocol.slice(0,-1)}catch{}let i=sd(e,n);return i&&Yu(i)?`http`:`https`}var ld=(e,t)=>{if(!e||!t)return!1;let n=e.replace(/^https?:\/\//,``).split(`/`)[0].toLowerCase(),r=t.replace(/^https?:\/\//,``).split(`/`)[0].toLowerCase();return r.includes(`*`)||r.includes(`?`)?qu(r)(n):n.toLowerCase()===r.toLowerCase()};function ud(e,t,n,r){let i=sd(t,r);if(!i){if(e.fallback)return $u(e.fallback,n);throw new B(`Could not determine host from request headers. Please provide a fallback URL in your baseURL config.`)}if(e.allowedHosts.some(e=>ld(i,e)))return $u(`${cd(t,e.protocol,r)}://${i}`,n);if(e.fallback)return $u(e.fallback,n);throw new B(`Host "${i}" is not in the allowed hosts list. Allowed hosts: ${e.allowedHosts.join(`, `)}. Add this host to your allowedHosts config or provide a fallback URL.`)}function dd(e,t,n,r,i){if(ad(e))return n?ud(e,n,t,i):e.fallback?$u(e.fallback,t):td(void 0,t,void 0,r,i);let a=od(n)?n:void 0;return td(typeof e==`string`?e:void 0,t,a,r,i)}function fd(e,t){let n;try{n=new URL(e).pathname.replace(/\/+$/,``)||`/`}catch{return`/`}let r=t.replace(/\/+$/,``);return r===``?n:n===r?`/`:n.startsWith(r+`/`)?n.slice(r.length).replace(/\/+$/,``)||`/`:n}var pd=`https://better-auth.invalid`;function md(e,t){let n=e.startsWith(`/`);if(e.startsWith(`//`)||e.startsWith(`/\\`))throw TypeError(`Expected an absolute or root-relative URL`);let r=n?new URL(e,pd):new URL(e);if(n&&r.origin!==pd)throw TypeError(`Expected an absolute or root-relative URL`);let i=t.toString();if(!i)return e;let a=r.search.endsWith(`&`)?``:`&`;return r.search=r.search?`${r.search}${a}${i}`:i,n?r.href.slice(r.origin.length):r.href}var hd=[`javascript:`,`data:`,`vbscript:`],gd=k(),_d=_e();function vd(e){return yd(e)||bd(e)}function yd(e){return he(gd,e)}function bd(e){return he(_d,e)}function xd(e){let t=e.toLowerCase();if(t.startsWith(`::ffff:`)){let e=t.substring(7);if(yd(e))return e}let n=e.split(`:`);if(n.length===7&&n[5]?.toLowerCase()===`ffff`){let e=n[6];if(e&&yd(e))return e}if(t.includes(`::ffff:`)||t.includes(`:ffff:`)){let t=Sd(e);if(t.length===8&&t[0]===`0000`&&t[1]===`0000`&&t[2]===`0000`&&t[3]===`0000`&&t[4]===`0000`&&t[5]===`ffff`&&t[6]&&t[7])return`${Number.parseInt(t[6].substring(0,2),16)}.${Number.parseInt(t[6].substring(2,4),16)}.${Number.parseInt(t[7].substring(0,2),16)}.${Number.parseInt(t[7].substring(2,4),16)}`}return null}function Sd(e){if(e.includes(`::`)){let t=e.split(`::`),n=t[0]?t[0].split(`:`):[],r=t[1]?t[1].split(`:`):[],i=8-n.length-r.length,a=Array(i).fill(`0000`),o=n.map(e=>e.padStart(4,`0`)),s=r.map(e=>e.padStart(4,`0`));return[...o,...a,...s]}return e.split(`:`).map(e=>e.padStart(4,`0`))}function Cd(e,t){let n=Sd(e);if(t!==void 0&&t<128){let e=Math.max(0,Math.floor(t));return n.map(t=>{if(e<=0)return`0000`;if(e>=16)return e-=16,t;let n=Number.parseInt(t,16)&65535<<16-e&65535;return e=0,n.toString(16).padStart(4,`0`)}).join(`:`).toLowerCase()}return n.join(`:`).toLowerCase()}function wd(e,t={}){if(yd(e)||!bd(e))return e.toLowerCase();let n=xd(e);return n?n.toLowerCase():Cd(e,t.ipv6Subnet??64)}function Td(e){if(yd(e))return Uint8Array.from(e.split(`.`).map(e=>Number(e)));if(!bd(e))return null;let t=xd(e);if(t)return Uint8Array.from(t.split(`.`).map(e=>Number(e)));let n=Sd(e),r=new Uint8Array(16);for(let e=0;e<8;e++){let t=Number.parseInt(n[e]??`0`,16);r[e*2]=t>>8&255,r[e*2+1]=t&255}return r}var Ed=/^\d+$/;function Dd(e){let t=e.lastIndexOf(`/`),n=Td(t===-1?e:e.slice(0,t));if(!n)return null;let r=n.length*8;if(t===-1)return{bytes:n,prefix:r};let i=e.slice(t+1);if(!Ed.test(i))return null;let a=Number(i);return a<=r?{bytes:n,prefix:a}:null}function Od(e,t){if(e.length!==t.bytes.length)return!1;let n=t.prefix;for(let r=0;r<e.length&&n>0;r++){let i=n>=8?8:n,a=i===8?255:255<<8-i&255;if(((e[r]??0)&a)!==((t.bytes[r]??0)&a))return!1;n-=8}return!0}function kd(e){return e.filter(e=>Dd(e)===null)}function Ad(e,t={}){let n=e.split(`,`).map(e=>e.trim()).filter(Boolean);if(n.length===0)return null;let r=(t.trustedProxies??[]).map(Dd).filter(e=>e!==null);if(r.length>0){for(let e=n.length-1;e>=0;e--){let i=n[e],a=i?Td(i):null;if(!i||!a)return null;if(!r.some(e=>Od(a,e)))return wd(i,{ipv6Subnet:t.ipv6Subnet})}return null}if(n.length!==1)return null;let i=n[0];return!i||!vd(i)?null:wd(i,{ipv6Subnet:t.ipv6Subnet})}var jd=`127.0.0.1`,Md=[`x-forwarded-for`];function Nd(e,t){if(t.advanced?.ipAddress?.disableIpTracking)return null;let n=`headers`in e?e.headers:e,r=t.advanced?.ipAddress?.ipAddressHeaders||Md;for(let e of r){let r=`get`in n?n.get(e):n[e];if(typeof r==`string`){let e=Ad(r,{ipv6Subnet:t.advanced?.ipAddress?.ipv6Subnet,trustedProxies:t.advanced?.ipAddress?.trustedProxies});if(e)return e}}return p()||_()?jd:null}function Pd(e,t){return`${e}|${t}`}var Fd=async()=>{let e=c(),t=e.context.requestStateAsyncStorage;if(t)return t;let n=await Au();return e.context.requestStateAsyncStorage??=new n,e.context.requestStateAsyncStorage};async function Id(){return(await Fd()).getStore()!==void 0}async function Ld(){let e=(await Fd()).getStore();if(!e)throw Error("No request state found. Please make sure you are calling this function within a `runWithRequestState` callback.");return e}async function Rd(e,t){return(await Fd()).run(e,t)}function zd(e){let t=Object.freeze({});return{get ref(){return t},async get(){let n=await Ld();if(!n.has(t)){let r=await e();return n.set(t,r),r}return n.get(t)},async set(e){(await Ld()).set(t,e)}}}var Bd=async()=>{let e=c(),t=e.context.adapterAsyncStorage;if(t)return t;let n=await Au();return e.context.adapterAsyncStorage??=new n,e.context.adapterAsyncStorage},Vd=async e=>Bd().then(t=>t.getStore()?.adapter||e).catch(()=>e),Hd=async(e,t)=>{let n=!1;return Bd().then(async r=>{n=!0;let i=[],a,o,s=!1;try{a=await r.run({adapter:e,pendingHooks:i,isTransactionActive:!1},t)}catch(e){o=e,s=!0}for(let e of i)await e();if(s)throw o;return a}).catch(e=>{if(!n)return t();throw e})},Ud=async(e,t,n)=>{let r=!1;return Bd().then(async i=>{if(r=!0,i.getStore()?.isTransactionActive)return t();let a=Ce(e)?.();a&&await a;let o=[],s,c,l=!1;try{s=await e.transaction(async e=>(o=[],i.run({adapter:e,pendingHooks:o,isTransactionActive:!0},t)))}catch(e){l=!0,c=e}let u=async e=>{for(let t of o)try{await t()}catch(t){if(!n?.onAfterCommitHookError){if(e===`throw`)throw t;try{ve.error(`Failed to run an after-commit hook for work that could not roll back`,t)}catch{}continue}try{await n.onAfterCommitHookError(t)}catch{}}};if(l)throw e.options?.adapterConfig.transaction===!1&&await u(`log`),c;return await u(`throw`),s}).catch(e=>{if(!r)return t();throw e})},Wd=async(e,t)=>{let n=async()=>{try{await e()}catch(e){if(!t?.onError)throw e;await t.onError(e)}},r;try{r=await Bd()}catch{return n()}let i=r.getStore();if(!i?.isTransactionActive)return n();i.pendingHooks.push(n)},{get:Gd,set:Kd}=zd(()=>null),qd=async()=>await Gd(),{get:Jd,set:Yd}=zd(()=>null),Xd=async e=>{await Yd({...await Jd()??{},...e})},{get:Zd,set:Qd}=zd(()=>!1);function $d(e){return!!e.database||!!e.secondaryStorage}function ef(e){return!!e.database}function tf(e){return ef(e)}var nf=a({id:s(),createdAt:oe().default(()=>new Date),updatedAt:oe().default(()=>new Date)}),rf=nf.extend({userId:we(),expiresAt:oe(),token:s(),ipAddress:s().nullish(),userAgent:s().nullish()}),af=nf.extend({email:s().transform(e=>e.toLowerCase()),emailVerified:F().default(!1),name:s(),image:s().nullish()});function of(e,t){if(!e||!t)return e;let n=Object.entries(t).filter(([,{returned:e}])=>e===!1).map(([e])=>e);return Object.entries(structuredClone(e)).filter(([e])=>!n.includes(e)).reduce((e,[t,n])=>({...e,[t]:n}),{})}var sf=new WeakMap;function cf(e,t,n){let r=`${t}:${n}`;sf.has(e)||sf.set(e,new Map);let i=sf.get(e);if(i.has(r))return i.get(r);let a=n===`output`?R(e)[t]?.fields??{}:{},o=t===`user`||t===`session`||t===`account`?e[t]?.additionalFields:void 0,s={...a,...o??{}};for(let n of e.plugins||[])n.schema&&n.schema[t]&&(s={...s,...n.schema[t].fields});return i.set(r,s),s}function lf(e,t){return of(t,cf(e,`user`,`output`))}function uf(e,t){let n=cf(e,`user`,`output`),r={};for(let e in n){let i=n[e];i.returned!==!1&&(e in t&&t[e]!==void 0?r[e]=t[e]:i.defaultValue===void 0?i.required||(r[e]=null):r[e]=typeof i.defaultValue==`function`?i.defaultValue():i.defaultValue)}return`id`in t&&(r.id=t.id),r}function df(e,t){return of(t,cf(e,`session`,`output`))}function ff(e,t){let{accessToken:n,refreshToken:r,idToken:i,accessTokenExpiresAt:a,refreshTokenExpiresAt:o,password:s,...c}=of(t,cf(e,`account`,`output`));return c}function pf(e,t){let n=t.action||`create`,r=t.fields,i=Object.create(null);for(let t in r)if(t in e){if(r[t].input===!1){if(r[t].defaultValue!==void 0&&n!==`update`){i[t]=r[t].defaultValue;continue}if(e[t])throw M.from(`BAD_REQUEST`,{...ls.FIELD_NOT_ALLOWED,message:`${t} is not allowed to be set`});continue}if(r[t].validator?.input&&e[t]!==void 0){let n=r[t].validator.input[`~standard`].validate(e[t]);if(n instanceof Promise)throw M.from(`INTERNAL_SERVER_ERROR`,ls.ASYNC_VALIDATION_NOT_SUPPORTED);if(`issues`in n&&n.issues)throw M.from(`BAD_REQUEST`,{...ls.VALIDATION_ERROR,message:n.issues[0]?.message||`Validation Error`});i[t]=n.value;continue}if(r[t].transform?.input&&e[t]!==void 0){i[t]=r[t].transform?.input(e[t]);continue}i[t]=e[t]}else if(r[t].defaultValue!==void 0&&n===`create`){if(typeof r[t].defaultValue==`function`){i[t]=r[t].defaultValue();continue}i[t]=r[t].defaultValue}else if(r[t].required&&n===`create`)throw M.from(`BAD_REQUEST`,{...ls.MISSING_FIELD,message:`${t} is required`});return i}function mf(e,t={},n){return pf(t,{fields:cf(e,`user`,`input`),action:n})}function hf(e,t={},n){let r=cf(e,`user`,`input`),i=Object.create(null);for(let e of Object.keys(t))r[e]?.input!==!1&&(i[e]=t[e]);return pf(i,{fields:r,action:n})}function gf(e,t,n){return pf(t,{fields:cf(e,`session`,`input`),action:n})}function _f(e){let t=cf(e,`session`,`input`),n={};for(let e in t)t[e].defaultValue!==void 0&&(n[e]=typeof t[e].defaultValue==`function`?t[e].defaultValue():t[e].defaultValue);return n}function vf(e,t){if(!t)return e;for(let n in t){let r=t[n]?.modelName;r&&(e[n].modelName=r);for(let r in e[n].fields){let i=t[n]?.fields?.[r];i&&(e[n].fields[r].fieldName=i)}}return e}var yf=(e,t=`ms`)=>new Date(Date.now()+(t===`sec`?e*1e3:e));function bf(e){if(e.indexOf(`%`)===-1)return e;try{return decodeURIComponent(e)}catch{return e}}var xf=`__Secure-`;function Sf(e){if(!e)return[];let t=[],n=0,r=0;for(;r<e.length;){if(e[r]===`,`){let i=r+1;for(;i<e.length&&e[i]===` `;)i++;for(;i<e.length&&e[i]!==`=`&&e[i]!==`;`&&e[i]!==`,`;)i++;if(i<e.length&&e[i]===`=`){let i=e.slice(n,r).trim();for(i&&t.push(i),n=r+1;n<e.length&&e[n]===` `;)n++;r=n;continue}}r++}let i=e.slice(n).trim();return i&&t.push(i),t}function Cf(e){let t=new Map;return Sf(e).forEach(e=>{let[n,...r]=e.split(`;`).map(e=>e.trim()),[i,...a]=(n||``).split(`=`),o=Ef(a.join(`=`));if(!i)return;let s={value:bf(o)};r.forEach(e=>{let[t,...n]=e.split(`=`),r=n.join(`=`),i=t.trim().toLowerCase();switch(i){case`max-age`:s[`max-age`]=r?parseInt(r.trim(),10):void 0;break;case`expires`:s.expires=r?new Date(r.trim()):void 0;break;case`domain`:s.domain=r?r.trim():void 0;break;case`path`:s.path=r?r.trim():void 0;break;case`secure`:s.secure=!0;break;case`httponly`:s.httponly=!0;break;case`samesite`:s.samesite=r?r.trim().toLowerCase():void 0;break;case`partitioned`:s.partitioned=!0;break;default:s[i]=!r||r.trim()}}),t.set(i,s)}),t}var wf=/^[\x21\x23-\x27\x2A\x2B\x2D\x2E\x30-\x39\x41-\x5A\x5E\x5F\x60\x61-\x7A\x7C\x7E]+$/,Tf=/^[\x20\x21\x23-\x3A\x3C-\x5B\x5D-\x7E]*$/;function Ef(e){return e.length<2||!e.startsWith(`"`)||!e.endsWith(`"`)?e:e.slice(1,-1)}function Df(e){let t=0,n=e.length;for(;t<n;){let n=e.charCodeAt(t);if(n!==32&&n!==9)break;t++}for(;n>t;){let t=e.charCodeAt(n-1);if(t!==32&&t!==9)break;n--}return t===0&&n===e.length?e:e.slice(t,n)}function Of(e){let t=new Map;if(e.length<2)return t;for(let n of e.split(`;`)){let e=n.indexOf(`=`);if(e===-1)continue;let r=Df(n.slice(0,e)),i=Ef(Df(n.slice(e+1)));wf.test(r)&&Tf.test(i)&&t.set(r,bf(i))}return t}var kf=4050,Af=100;function jf(e,t){return kf-po(e,``,{...t}).length}function Mf(e,t){let n=`${e}.`;if(!t.startsWith(n))return null;let r=t.slice(n.length),i=Number(r);return!Number.isSafeInteger(i)||i<0||String(i)!==r?null:i}function Nf(e,t){let n={},r=Of(t.headers?.get(`cookie`)||``);for(let[t,i]of r)(t===e||Mf(e,t)!==null)&&(n[t]=i);return n}function Pf(e,t,n,r){let i=jf(`${t.name}.99`,t.attributes),a=i>0?Math.ceil(t.value.length/i):1/0;if(a<=1)return n[t.name]=t.value,[t];if(a>Af)return r.warn(`${e} cookie is too large to store even after chunking, so the cookie cache was skipped. Reduce the cached data size or avoid storing this data in cookies.`),[];let o=[];for(let e=0;e<a;e++){let r=`${t.name}.${e}`,a=e*i,s=t.value.substring(a,a+i);o.push({...t,name:r,value:s}),n[r]=s}return r.debug(`CHUNKING_${e.toUpperCase()}_COOKIE`,{message:`${e} cookie exceeds the ${kf} byte limit and was split into ${a} chunks.`,valueSize:t.value.length,chunkCount:a,chunkSizes:o.map(e=>e.value.length)}),o}function Ff(e,t){let n={};for(let r in e)n[r]={name:r,value:``,attributes:{...t,maxAge:0}};return n}var If=e=>(t,n,r)=>{let i=Nf(t,r),a=r.context.logger,o=()=>{let e=Ff(i,n);for(let e in i)delete i[e];return e};return{chunk(r,s){let c=o(),l=Pf(e,{name:t,value:r,attributes:{...n,...s}},i,a);for(let e of l)c[e.name]=e;return Object.values(c)},clean(){return Object.values(o())},setCookies(e){for(let t of e)r.setCookie(t.name,t.value,t.attributes)}}},Lf=If(`Session`),Rf=If(`Account`);function zf(e,t){let n=e.getCookie(t);if(n)return n;let r=[],i=e.headers?.get(`cookie`);if(!i)return null;for(let[e,n]of Of(i)){let i=Mf(t,e);i!==null&&r.push({index:i,value:n})}return r.length>0?(r.sort((e,t)=>e.index-t.index),r.map(e=>e.value).join(``)):null}async function Bf(e,t){let n=e.context.authCookies.accountData,r={maxAge:300,...n.attributes},i=await Fi(t,e.context.secretConfig,`better-auth-account`,r.maxAge),a=Rf(n.name,r,e);a.setCookies(a.chunk(i,r))}async function Vf(e){let t=zf(e,e.context.authCookies.accountData.name);if(t){let n=ae(await Li(t,e.context.secretConfig,`better-auth-account`));if(n)return n}return null}var Hf=ye(a({disableCookieCache:Te().meta({description:`Disable cookie cache and fetch session from database`}).optional(),disableRefresh:Te().meta({description:`Disable session refresh. Useful for checking session status, without updating the session`}).optional()}));function Uf(e){return!!e&&(typeof e==`object`||typeof e==`function`)&&typeof e.then==`function`}var Wf=1e3,Gf=Wf*60,Kf=Gf*60,qf=Kf*24,Jf=qf*7,Yf=qf*30,Xf=qf*365.25,Zf=/^(\+|\-)? ?(\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;function Qf(e){let t=Zf.exec(e);if(!t||t[4]&&t[1])throw TypeError(`Invalid time string format: "${e}". Use formats like "7d", "30m", "1 hour", etc.`);let n=parseFloat(t[2]),r=t[3].toLowerCase(),i;switch(r){case`years`:case`year`:case`yrs`:case`yr`:case`y`:i=n*Xf;break;case`months`:case`month`:case`mo`:i=n*Yf;break;case`weeks`:case`week`:case`w`:i=n*Jf;break;case`days`:case`day`:case`d`:i=n*qf;break;case`hours`:case`hour`:case`hrs`:case`hr`:case`h`:i=n*Kf;break;case`minutes`:case`minute`:case`mins`:case`min`:case`m`:i=n*Gf;break;case`seconds`:case`second`:case`secs`:case`sec`:case`s`:i=n*Wf;break;default:throw TypeError(`Unknown time unit: "${r}"`)}return t[1]===`-`||t[4]===`ago`?-i:i}function $f(e){return Qf(e)}function ep(e){return Math.round(Qf(e)/1e3)}var tp=N({session:rf.loose(),user:af.loose(),updatedAt:b(),version:s().optional()}),np=a({session:S(s(),r()),expiresAt:b(),signature:s()});function rp(e){let t=ae(e);if(t===null)return null;let n=tp.safeParse(t);return n.success?n.data:(ve.warn(`Cookie cache payload failed schema validation`,{issues:n.error.issues.map(({code:e,path:t})=>({code:e,path:t}))}),null)}function ip(e){let t=np.safeParse(e);return t.success?t.data:null}var ap=new Map,op=new TextEncoder,sp={decode:(e,t=`utf-8`)=>(ap.has(t)||ap.set(t,new TextDecoder(t)),ap.get(t).decode(e)),encode:e=>op.encode(e)},cp=(e=`SHA-256`,t=`none`)=>{let n={importKey:async(t,n)=>Bi().importKey(`raw`,C(t),{name:`HMAC`,hash:{name:e}},!1,[n]),sign:async(e,r)=>{typeof e==`string`&&(e=await n.importKey(e,`sign`));let i=await Bi().sign(`HMAC`,e,C(r));return t===`hex`?ue.encode(i):t===`base64`?w.encode(i):t===`base64url`||t===`base64urlnopad`?d.encode(i,{padding:t!==`base64urlnopad`}):i},verify:async(e,r,i)=>(typeof e==`string`&&(e=await n.importKey(e,`verify`)),t===`hex`&&(i=typeof i==`string`?ue.toBytes(i):i),(t===`base64`||t===`base64url`||t===`base64urlnopad`)&&(i=await w.decode(i)),Bi().verify(`HMAC`,e,C(i),C(r)))};return n};function lp(e){let t=typeof e.baseURL==`string`?e.baseURL:void 0,n=typeof e.baseURL==`object`&&e.baseURL!==null?e.baseURL.protocol:void 0,r=(e.advanced?.useSecureCookies===void 0?n===`https`||n!==`http`&&(t?t.startsWith(`https://`):l):e.advanced?.useSecureCookies)?xf:``,i=!!e.advanced?.crossSubDomainCookies?.enabled,a=i?e.advanced?.crossSubDomainCookies?.domain||(t?new URL(t).hostname:void 0):void 0;if(i&&!a&&!ad(e.baseURL))throw new B(`baseURL is required when crossSubdomainCookies are enabled.`);function o(t,n={}){let o=e.advanced?.cookiePrefix||`better-auth`,s=e.advanced?.cookies?.[t]?.name||`${o}.${t}`,c=e.advanced?.cookies?.[t]?.attributes??{};return{name:`${r}${s}`,attributes:{secure:!!r,sameSite:`lax`,path:`/`,httpOnly:!0,...i?{domain:a}:{},...e.advanced?.defaultCookieAttributes,...n,...c}}}return o}function up(e){let t=lp(e),n=t(`session_token`,{maxAge:e.session?.expiresIn||ep(`7d`)}),r=t(`session_data`,{maxAge:e.session?.cookieCache?.maxAge||300}),i=t(`account_data`,{maxAge:e.session?.cookieCache?.maxAge||300}),a=t(`dont_remember`);return{sessionToken:{name:n.name,attributes:n.attributes},sessionData:{name:r.name,attributes:r.attributes},dontRememberToken:{name:a.name,attributes:a.attributes},accountData:{name:i.name,attributes:i.attributes}}}async function dp(e,t,n){if(!e.context.options.session?.cookieCache?.enabled)return;let r=of(t.session,e.context.options.session?.additionalFields),i=lf(e.context.options,t.user),a=e.context.options.session?.cookieCache?.version,o=`1`;if(a){if(typeof a==`string`)o=a;else if(typeof a==`function`){let e=a(t.session,t.user);o=Uf(e)?await e:e}}let s={session:r,user:i,updatedAt:Date.now(),version:o},c={...e.context.authCookies.sessionData.attributes,maxAge:n?void 0:e.context.authCookies.sessionData.attributes.maxAge},l=yf(c.maxAge||60,`sec`).getTime(),u=e.context.options.session?.cookieCache?.strategy||`compact`,f;if(u===`jwe`)f=await Fi(s,e.context.secretConfig,`better-auth-session`,c.maxAge||300);else if(u===`jwt`){let t=e.context.sessionConfig.cookieCacheSigner;f=t?await t.sign(e,s,c.maxAge||300):await Ei(s,e.context.secret,c.maxAge||300)}else f=d.encode(JSON.stringify({session:s,expiresAt:l,signature:await cp(`SHA-256`,`base64urlnopad`).sign(e.context.secret,JSON.stringify({...s,expiresAt:l}))}),{padding:!1});let p=Lf(e.context.authCookies.sessionData.name,c,e);if(p.setCookies(p.chunk(f,c)),e.context.options.account?.storeAccountCookie&&!hp(e,e.context.authCookies.accountData.name)){let n=await Vf(e);if(n){if(!tf(e.context.options)||n.userId===t.user.id)await Bf(e,n);else{gp(e,e.context.authCookies.accountData);let t=Rf(e.context.authCookies.accountData.name,e.context.authCookies.accountData.attributes,e);t.setCookies(t.clean())}}}}async function fp(e,t){let n=e.context.options.session?.cookieCache?.strategy||`compact`;if(n===`jwe`){let n=await Li(t,e.context.secretConfig,`better-auth-session`),r=rp(n);return r?{session:r,expiresAt:n?.exp?n.exp*1e3:Date.now()}:null}if(n===`jwt`){let n=e.context.sessionConfig.cookieCacheSigner;if(n){let r=await n.verify(e,t);return r?{session:r.payload,expiresAt:r.expiresAt}:null}let r=await Di(t,e.context.secret),i=rp(r);return i?{session:i,expiresAt:r?.exp?r.exp*1e3:Date.now()}:null}let r=ip(ae(sp.decode(d.decode(t))));if(!r||!await cp(`SHA-256`,`base64urlnopad`).verify(e.context.secret,JSON.stringify({...r.session,expiresAt:r.expiresAt}),r.signature))return null;let i=rp(r.session);return i?{session:i,expiresAt:r.expiresAt}:null}async function pp(e,t,n,r){let i=await e.getSignedCookie(e.context.authCookies.dontRememberToken.name,e.context.secret);n=n===void 0?!!i:n;let a=e.context.authCookies.sessionToken.attributes,o=n?void 0:e.context.sessionConfig.expiresIn;await e.setSignedCookie(e.context.authCookies.sessionToken.name,t.session.token,e.context.secret,{...a,maxAge:o,...r}),n&&await e.setSignedCookie(e.context.authCookies.dontRememberToken.name,`true`,e.context.secret,e.context.authCookies.dontRememberToken.attributes),await dp(e,t,n),e.context.setNewSession(t)}function mp(e,t){let n=e,r=new Set;n.responseHeaders&&r.add(n.responseHeaders),n.context?.responseHeaders&&r.add(n.context.responseHeaders);let i=`${t}=`,a=`${t}.`;for(let e of r){let t=typeof e.getSetCookie==`function`?e.getSetCookie():Sf(e.get(`set-cookie`)||``);if(!t.length)continue;let n=t.filter(e=>!e.startsWith(i)&&!e.startsWith(a));if(n.length!==t.length){e.delete(`set-cookie`);for(let t of n)e.append(`set-cookie`,t)}}}function hp(e,t){let n=e,r=new Set;n.responseHeaders&&r.add(n.responseHeaders),n.context?.responseHeaders&&r.add(n.context.responseHeaders);let i=`${t}=`,a=`${t}.`;for(let e of r)if((typeof e.getSetCookie==`function`?e.getSetCookie():Sf(e.get(`set-cookie`)||``)).some(e=>e.startsWith(i)||e.startsWith(a)))return!0;return!1}function gp(e,t){mp(e,t.name),e.setCookie(t.name,``,{...t.attributes,maxAge:0})}function _p(e,t){if(gp(e,e.context.authCookies.sessionToken),gp(e,e.context.authCookies.sessionData),e.context.options.account?.storeAccountCookie){gp(e,e.context.authCookies.accountData);let t=Rf(e.context.authCookies.accountData.name,e.context.authCookies.accountData.attributes,e),n=t.clean();t.setCookies(n)}e.context.oauthConfig.storeStateStrategy===`cookie`&&gp(e,e.context.createAuthCookie(`oauth_state`));let n=Lf(e.context.authCookies.sessionData.name,e.context.authCookies.sessionData.attributes,e),r=n.clean();n.setCookies(r),t||gp(e,e.context.authCookies.dontRememberToken)}var vp=()=>X(`/get-session`,{method:[`GET`,`POST`],operationId:`getSession`,query:Hf,requireHeaders:!0,metadata:{openapi:{operationId:`getSession`,description:`Get the current session`,responses:{200:{description:`Success`,content:{"application/json":{schema:{type:[`object`,`null`],properties:{session:{$ref:`#/components/schemas/Session`},user:{$ref:`#/components/schemas/User`}},required:[`session`,`user`]}}}}}}}},async e=>{e.setHeader(`cache-control`,`no-store`),e.setHeader(`pragma`,`no-cache`);let t=e.context.options.session?.deferSessionRefresh,n=e.method===`POST`;if(n&&!t)throw M.from(`METHOD_NOT_ALLOWED`,ls.METHOD_NOT_ALLOWED_DEFER_SESSION_REQUIRED);try{let r=e.context.options.session?.cookieCache?.enabled===!0,i=await e.getSignedCookie(e.context.authCookies.sessionToken.name,e.context.secret);if(!i&&r)return null;let a=zf(e,e.context.authCookies.sessionData.name);if(a&&!r){let t=Lf(e.context.authCookies.sessionData.name,e.context.authCookies.sessionData.attributes,e);t.setCookies(t.clean())}if(!i)return null;let o=r&&!e.query?.disableCookieCache,s=o&&a?await fp(e,a):null;o&&a&&!s&&gp(e,e.context.authCookies.sessionData);let c=await e.getSignedCookie(e.context.authCookies.dontRememberToken.name,e.context.secret);if(s?.session){let t=s.session,n=t.session.token!==i;if(!n){let r=e.context.options.session?.cookieCache?.version,i=`1`;if(r){if(typeof r==`string`)i=r;else if(typeof r==`function`){let e=r(t.session,t.user);i=e instanceof Promise?await e:e}}n=(t.version||`1`)!==i}if(!n){let e=Date.now(),r=new Date(t.session.expiresAt).getTime();n=s.expiresAt<e||!Number.isFinite(r)||r<e}if(n)gp(e,e.context.authCookies.sessionData);else{let n=e.context.sessionConfig.cookieRefreshCache;if(n===!1){e.context.session=t;let n=df(e.context.options,{...t.session,expiresAt:new Date(t.session.expiresAt),createdAt:new Date(t.session.createdAt),updatedAt:new Date(t.session.updatedAt)}),r=lf(e.context.options,{...t.user,createdAt:new Date(t.user.createdAt),updatedAt:new Date(t.user.updatedAt)});return e.json({session:n,user:r})}let r=s.expiresAt-Date.now(),i=n.updateAge*1e3,a=await Zd();if(r<i&&!a){let n={session:{...t.session},user:t.user,updatedAt:Date.now()};await dp(e,n,!1);let r=e.context.authCookies.sessionToken.attributes,i=c?void 0:e.context.sessionConfig.expiresIn;await e.setSignedCookie(e.context.authCookies.sessionToken.name,t.session.token,e.context.secret,{...r,maxAge:i});let a=df(e.context.options,{...n.session,expiresAt:new Date(n.session.expiresAt),createdAt:new Date(n.session.createdAt),updatedAt:new Date(n.session.updatedAt)}),o=lf(e.context.options,{...n.user,createdAt:new Date(n.user.createdAt),updatedAt:new Date(n.user.updatedAt)});return e.context.session={session:a,user:o},e.json({session:a,user:o})}let o=df(e.context.options,{...t.session,expiresAt:new Date(t.session.expiresAt),createdAt:new Date(t.session.createdAt),updatedAt:new Date(t.session.updatedAt)}),l=lf(e.context.options,{...t.user,createdAt:new Date(t.user.createdAt),updatedAt:new Date(t.user.updatedAt)});return e.context.session={session:o,user:l},e.json({session:o,user:l})}}let l=await e.context.internalAdapter.findSession(i);if(e.context.session=l,!l||l.session.expiresAt<new Date)return _p(e),l&&(!t||n)&&await e.context.internalAdapter.deleteSession(l.session.token),e.json(null);if(c||e.query?.disableRefresh){let t=df(e.context.options,l.session),n=lf(e.context.options,l.user);return e.json({session:t,user:n})}let u=e.context.sessionConfig.expiresIn,d=e.context.sessionConfig.updateAge,f=l.session.expiresAt.valueOf()-u*1e3+d*1e3<=Date.now(),p=e.query?.disableRefresh||e.context.options.session?.disableSessionRefresh,m=await Zd(),h=f&&!p&&!m;if(t&&!n){await dp(e,l,!!c);let t=df(e.context.options,l.session),n=lf(e.context.options,l.user);return e.json({session:t,user:n,needsRefresh:h})}if(h){let t=await e.context.internalAdapter.updateSession(l.session.token,{expiresAt:yf(e.context.sessionConfig.expiresIn,`sec`),updatedAt:new Date});if(!t)throw _p(e),M.from(`UNAUTHORIZED`,ls.FAILED_TO_GET_SESSION);let n=e.context.sessionConfig.expiresIn;await pp(e,{session:t,user:l.user},!1,{maxAge:n});let r=df(e.context.options,t),i=lf(e.context.options,l.user);return e.json({session:r,user:i})}await dp(e,l,!!c);let g=df(e.context.options,l.session),_=lf(e.context.options,l.user);return e.json({session:g,user:_})}catch(t){throw Eu(t)?t:(e.context.logger.error(`INTERNAL_SERVER_ERROR`,t),M.from(`INTERNAL_SERVER_ERROR`,ls.FAILED_TO_GET_SESSION,{cause:t}))}}),yp=e=>$d(e.context.options),Z=async(e,t)=>{if(e.context.session)return e.context.session;let n=await vp()({...e,method:`GET`,asResponse:!1,headers:e.headers,returnHeaders:!0,returnStatus:!1,query:{...t,...e.query,disableCookieCache:t?.disableCookieCache||e.query?.disableCookieCache,disableRefresh:t?.disableRefresh||e.query?.disableRefresh}}).catch(()=>null);return n?(n.headers&&n.headers.forEach((t,n)=>{let r=n.toLowerCase();r!==`cache-control`&&r!==`pragma`&&(r===`set-cookie`?e.responseHeaders.append(n,t):e.responseHeaders.set(n,t))}),e.context.session=n.response,n.response):(e.context.session=null,null)},bp=async e=>yp(e)?(e.context.session=null,Z(e,{disableCookieCache:!0})):Z(e),xp=zu(async e=>{let t=await Z(e);if(!t?.session)throw M.from(`UNAUTHORIZED`,{message:`Unauthorized`,code:`UNAUTHORIZED`});return{session:t}}),Sp=zu(async e=>{let t=await bp(e);if(!t?.session)throw M.from(`UNAUTHORIZED`,{message:`Unauthorized`,code:`UNAUTHORIZED`});return{session:t}});zu(async e=>{let t=await Z(e);if(!t?.session&&(e.request||e.headers))throw M.from(`UNAUTHORIZED`,{message:`Unauthorized`,code:`UNAUTHORIZED`});return{session:t}});var Cp=zu(async e=>{let t=await Z(e);if(!t?.session)throw M.from(`UNAUTHORIZED`,{message:`Unauthorized`,code:`UNAUTHORIZED`});if(e.context.sessionConfig.freshAge!==0){let n=new Date(t.session.createdAt).getTime(),r=e.context.sessionConfig.freshAge*1e3;if(Date.now()-n>=r)throw M.from(`FORBIDDEN`,ls.SESSION_NOT_FRESH)}return{session:t}}),wp=()=>X(`/list-sessions`,{method:`GET`,operationId:`listUserSessions`,use:[Cp],requireHeaders:!0,metadata:{openapi:{operationId:`listUserSessions`,description:`List all active sessions for the user`,responses:{200:{description:`Success`,content:{"application/json":{schema:{type:`array`,items:{$ref:`#/components/schemas/Session`}}}}}}}}},async e=>{try{let t=(await e.context.internalAdapter.listSessions(e.context.session.user.id,{onlyActiveSessions:!0})).filter(e=>e.expiresAt>new Date);return e.json(t.map(t=>df(e.context.options,t)))}catch(t){throw e.context.logger.error(t),e.error(`INTERNAL_SERVER_ERROR`)}}),Tp=X(`/revoke-session`,{method:`POST`,body:a({token:s().meta({description:`The token to revoke`})}),use:[Sp],requireHeaders:!0,metadata:{openapi:{description:`Revoke a single session`,requestBody:{content:{"application/json":{schema:{type:`object`,properties:{token:{type:`string`,description:`The token to revoke`}},required:[`token`]}}}},responses:{200:{description:`Success`,content:{"application/json":{schema:{type:`object`,properties:{status:{type:`boolean`,description:`Indicates if the session was revoked successfully`}},required:[`status`]}}}}}}}},async e=>{let t=e.body.token;if((await e.context.internalAdapter.findSession(t))?.session.userId===e.context.session.user.id)try{await e.context.internalAdapter.deleteSession(t)}catch(t){throw e.context.logger.error(t&&typeof t==`object`&&`name`in t?t.name:``,t),M.from(`INTERNAL_SERVER_ERROR`,{message:`Internal Server Error`,code:`INTERNAL_SERVER_ERROR`})}return e.json({status:!0})}),Ep=X(`/revoke-sessions`,{method:`POST`,use:[Sp],requireHeaders:!0,metadata:{openapi:{description:`Revoke all sessions for the user`,responses:{200:{description:`Success`,content:{"application/json":{schema:{type:`object`,properties:{status:{type:`boolean`,description:`Indicates if all sessions were revoked successfully`}},required:[`status`]}}}}}}}},async e=>{try{await e.context.internalAdapter.deleteUserSessions(e.context.session.user.id)}catch(t){throw e.context.logger.error(t&&typeof t==`object`&&`name`in t?t.name:``,t),M.from(`INTERNAL_SERVER_ERROR`,{message:`Internal Server Error`,code:`INTERNAL_SERVER_ERROR`})}return e.json({status:!0})}),Dp=X(`/revoke-other-sessions`,{method:`POST`,requireHeaders:!0,use:[Sp],metadata:{openapi:{description:`Revoke all other sessions for the user except the current one`,responses:{200:{description:`Success`,content:{"application/json":{schema:{type:`object`,properties:{status:{type:`boolean`,description:`Indicates if all other sessions were revoked successfully`}},required:[`status`]}}}}}}}},async e=>{let t=e.context.session;if(!t.user)throw M.from(`UNAUTHORIZED`,{message:`Unauthorized`,code:`UNAUTHORIZED`});let n=(await e.context.internalAdapter.listSessions(t.user.id)).filter(e=>e.expiresAt>new Date).filter(t=>t.token!==e.context.session.session.token);return await Promise.all(n.map(t=>e.context.internalAdapter.deleteSession(t.token))),e.json({status:!0})});function Op(e){if(typeof e!=`object`||!e)return!1;let t=Object.getPrototypeOf(e);return t!==null&&t!==Object.prototype&&Object.getPrototypeOf(t)!==null||Symbol.iterator in e?!1:Symbol.toStringTag in e?Object.prototype.toString.call(e)===`[object Module]`:!0}function kp(e,t,n=`.`,r){if(!Op(t))return kp(e,{},n,r);let i={...t};for(let t of Object.keys(e)){if(t===`__proto__`||t===`constructor`)continue;let a=e[t];a!=null&&(r&&r(i,t,a,n)||(i[t]=Array.isArray(a)&&Array.isArray(i[t])?[...a,...i[t]]:Op(a)&&Op(i[t])?kp(a,i[t],(n?`${n}.`:``)+t.toString(),r):a))}return i}function Ap(e){return(...t)=>t.reduce((t,n)=>kp(t,n,``,e),{})}var jp=Ap(),Mp=new Set([`metadata.google.internal`,`metadata.goog`,`metadata`,`instance-data`,`instance-data.ec2.internal`]);function Np(e){return e.length>=2&&e.startsWith(`[`)&&e.endsWith(`]`)?e.slice(1,-1):e}function Pp(e){if(e.startsWith(`[`)){let t=e.indexOf(`]`);return t===-1?e:e.slice(0,t+1)}let t=e.indexOf(`:`);return t===-1||e.indexOf(`:`,t+1)!==-1?e:e.slice(0,t)}function Fp(e){let t=e.indexOf(`%`);return t===-1?e:e.slice(0,t)}function Ip(e){return e.replace(/\.+$/,``)}function Lp(e){return/^\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}$/.test(e)}function Rp(e){let t=e.split(`.`);return(Number(t[0])<<24|Number(t[1])<<16|Number(t[2])<<8|Number(t[3]))>>>0}function zp(e,t,n){if(n===0)return!0;let r=n===32?4294967295:-1<<32-n>>>0;return(e&r)===(t&r)}function Bp(e){if(e===`0.0.0.0`)return`unspecified`;if(e===`255.255.255.255`)return`broadcast`;let t=Rp(e);return zp(t,Rp(`127.0.0.0`),8)?`loopback`:zp(t,Rp(`10.0.0.0`),8)||zp(t,Rp(`172.16.0.0`),12)||zp(t,Rp(`192.168.0.0`),16)?`private`:zp(t,Rp(`169.254.0.0`),16)?`linkLocal`:zp(t,Rp(`100.64.0.0`),10)?`sharedAddressSpace`:zp(t,Rp(`192.0.2.0`),24)||zp(t,Rp(`198.51.100.0`),24)||zp(t,Rp(`203.0.113.0`),24)?`documentation`:zp(t,Rp(`198.18.0.0`),15)?`benchmarking`:zp(t,Rp(`224.0.0.0`),4)?`multicast`:zp(t,Rp(`0.0.0.0`),8)||zp(t,Rp(`192.0.0.0`),24)||zp(t,Rp(`192.88.99.0`),24)||zp(t,Rp(`240.0.0.0`),4)?`reserved`:`public`}function Vp(e,t,n={}){let r=t*5,i=Number.parseInt(e.slice(r,r+4),16),a=Number.parseInt(e.slice(r+5,r+9),16);if(!Number.isFinite(i)||!Number.isFinite(a))return null;let o=(i<<16|a)>>>0;return n.xor&&(o=(o^4294967295)>>>0),`${o>>>24&255}.${o>>>16&255}.${o>>>8&255}.${o&255}`}function Hp(e){if(e===`0000:0000:0000:0000:0000:0000:0000:0000`)return`unspecified`;if(e===`0000:0000:0000:0000:0000:0000:0000:0001`)return`loopback`;let t=Number.parseInt(e.slice(0,2),16),n=Number.parseInt(e.slice(2,4),16);if(t===255)return`multicast`;if(t===254&&(n&192)==128)return`linkLocal`;if(t===254&&(n&192)==192)return`reserved`;if((t&254)==252)return`private`;if(e.startsWith(`2001:0db8:`))return`documentation`;if(e.startsWith(`2001:0002:0000:`))return`benchmarking`;if(e.startsWith(`2002:`)){let t=Vp(e,1);return t&&Bp(t)!==`public`?`reserved`:`public`}if(e.startsWith(`0064:ff9b:0000:0000:0000:0000:`)){let t=Vp(e,6);return t&&Bp(t),`reserved`}if(e.startsWith(`0064:ff9b:0001:`))return`reserved`;if(e.startsWith(`2001:0000:`)){let t=Vp(e,6,{xor:!0});return t&&Bp(t),`reserved`}return e.startsWith(`0100:0000:0000:0000:`)?`reserved`:e.startsWith(`3fff:0`)?`documentation`:e.startsWith(`5f00:`)||e.startsWith(`0000:0000:0000:0000:0000:0000:`)?`reserved`:`public`}function Up(e){let t=Ip(Fp(Np(Pp(e.trim())))).toLowerCase();if(t===``)return{kind:`reserved`,literal:`fqdn`,canonical:``};if(!vd(t))return t===`localhost`||t.endsWith(`.localhost`)?{kind:`localhost`,literal:`fqdn`,canonical:t}:Mp.has(t)?{kind:`cloudMetadata`,literal:`fqdn`,canonical:t}:{kind:`public`,literal:`fqdn`,canonical:t};if(Lp(t))return{kind:Bp(t),literal:`ipv4`,canonical:t};let n=wd(t,{ipv6Subnet:128});return Lp(n)?{kind:Bp(n),literal:`ipv4`,canonical:n}:{kind:Hp(n),literal:`ipv6`,canonical:n}}function Wp(e){return Up(e).kind===`loopback`}function Gp(e){let t=Up(e).kind;return t===`loopback`||t===`localhost`}function Kp(e){return Up(e).kind===`public`}var qp=Ap((e,t,n)=>{if(Array.isArray(e[t])&&Array.isArray(n))return e[t]=n,!0}),Jp=new WeakMap;function Yp(e,t){let n=e.options;return n?.operationId??n?.metadata?.openapi?.operationId??t??e.path??`/:virtual`}function Xp(e,t){t&&t.forEach((t,n)=>{e.responseHeaders?n.toLowerCase()===`set-cookie`?e.responseHeaders.append(n,t):e.responseHeaders.set(n,t):e.responseHeaders=new Headers({[n]:t})})}function Zp(e){let t=e[i],n=e.headers&&e.headers!==t?new Headers(e.headers):null;if(!t&&!n)return null;let r=new Headers;return t?.forEach((e,t)=>{r.append(t,e)}),n?.forEach((e,t)=>{t.toLowerCase()===`set-cookie`?r.append(t,e):r.set(t,e)}),r}async function Qp(e,t,n,r){let i=A(e.context.options),a={};for(let o of t){let t=!1;try{t=o.matcher(e)}catch(t){let n=Jp.get(o.handler)??`unknown`;throw e.context.logger.error(`An error occurred during ${n} hook matcher execution:`,t),new M(`INTERNAL_SERVER_ERROR`,{message:`An error occurred during hook matcher execution. Check the logs for more details.`})}if(!t)continue;let s=Jp.get(o.handler)??`unknown`,c=n.path??`/:virtual`,l=await i(`hook before ${c} ${s}`,{[ie]:`before`,[P]:c,[se]:s,[L]:r},()=>o.handler({...e,returnHeaders:!0})).catch(t=>{throw Eu(t)&&x(e.context.logger.level,`debug`)&&(t.stack=t.errorStack),t});Xp(e.context,l?.headers);let u=l?.response;if(u&&typeof u==`object`){if(`context`in u&&typeof u.context==`object`){let{headers:e,...t}=u.context;e instanceof Headers&&(a.headers?e.forEach((e,t)=>{a.headers?.set(t,e)}):a.headers=e),a=qp(t,a);continue}return u}}return{context:a}}async function $p(e,t,n,r){let i=A(e.context.options);for(let a of t){if(!a.matcher(e))continue;let t=Jp.get(a.handler)??`unknown`,o=n.path??`/:virtual`,s=await i(`hook after ${o} ${t}`,{[ie]:`after`,[P]:o,[se]:t,[L]:r},()=>a.handler(e)).catch(t=>{if(Eu(t))return x(e.context.logger.level,`debug`)&&(t.stack=t.errorStack),{response:t,headers:Zp(t)};throw t});Xp(e.context,s.headers),s.response!==void 0&&(e.context.returned=s.response)}return{response:e.context.returned,headers:e.context.responseHeaders}}function em(e){let t=e.options.plugins||[],n=[],r=[],i=e.options.hooks?.before;i&&(Jp.set(i,`user`),n.push({matcher:()=>!0,handler:i}));let a=e.options.hooks?.after;a&&(Jp.set(a,`user`),r.push({matcher:()=>!0,handler:a}));let o=t.flatMap(e=>(e.hooks?.before??[]).map(t=>(Jp.set(t.handler,`plugin:${e.id}`),t))),s=t.flatMap(e=>(e.hooks?.after??[]).map(t=>(Jp.set(t.handler,`plugin:${e.id}`),t)));return o.length&&n.push(...o),s.length&&r.push(...s),{beforeHooks:n,afterHooks:r}}async function tm(e,t){let n=A(t.context.options),r=t.operationId??Yp(e),a=e.path??`/:virtual`,o=e.options?.method,s=Array.isArray(o)?o[0]:o,c=t.method??t.request?.method??s??`?`,l=t.asResponse??od(t.request),u={...t,context:{...t.context,returned:void 0,responseHeaders:void 0,session:t.context.session??null},path:e.path,headers:t.headers?new Headers(t.headers):void 0};return n(`${c} ${a}`,{[P]:a,[L]:r},async()=>Fu(u,async()=>{let{beforeHooks:o,afterHooks:s}=em(u.context),c=await Qp(u,o,e,r);if(`context`in c&&c.context&&typeof c.context==`object`){let{headers:e,...t}=c.context;if(e){u.headers||(u.headers=new Headers);let t=u.headers;e.forEach((e,n)=>{t.set(n,e)})}u=qp(t,u)}else if(c){let e=u.context.responseHeaders;return l?wo(c,{headers:e}):t.returnHeaders?{headers:e,response:c}:c}u.asResponse=!1,u.returnHeaders=!0,u.returnStatus=!0;let d=await Fu(u,()=>n(`handler ${a}`,{[P]:a,[L]:r},()=>e(u))).catch(e=>{if(Eu(e))return{response:e,status:e.statusCode,headers:Zp(e)};throw e});if(d instanceof Response)return d;u.context.returned=d.response,u.context.responseHeaders=d.headers??void 0;let f=await $p(u,s,e,r);if(f.response!==void 0&&(d.response=f.response),d.headers=f.headers??d.headers,Eu(d.response)&&x(u.context.logger.level,`debug`)&&(d.response.stack=d.response.errorStack),Eu(d.response)&&!l)throw d.headers&&Object.defineProperty(d.response,i,{enumerable:!1,configurable:!0,writable:!1,value:d.headers}),d.response;return l?wo(d.response,{headers:d.headers??void 0,status:d.status}):t.returnHeaders?t.returnStatus?{headers:d.headers,response:d.response,status:d.status}:{headers:d.headers,response:d.response}:t.returnStatus?{response:d.response,status:d.status}:d.response}))}var nm=/^[a-z](?:[a-z0-9-]*[a-z0-9])?(?:\.[a-z0-9](?:[a-z0-9-]*[a-z0-9])?)+$/i,rm=new Set([`http:`,`https:`,`ws:`,`wss:`,`file:`,`ftp:`,`mailto:`,`javascript:`,`data:`,`vbscript:`,`blob:`,`about:`,`view-source:`]);function im(e){let t=e.protocol.slice(0,-1),n=e.href.slice(e.protocol.length);return e.protocol!==`http:`&&e.protocol!==`https:`&&e.host.length===0&&n.startsWith(`/`)&&!n.startsWith(`//`)&&nm.test(t)}function am(e){return rm.has(e.protocol)||e.host.length===0?!1:e.pathname.startsWith(`/`)}function om(e){return im(e)||am(e)}var Q=ne().superRefine((e,n)=>{let r;try{r=new URL(e)}catch{return n.addIssue({code:`custom`,message:`URL must be parseable`,fatal:!0}),t}hd.includes(r.protocol)?n.addIssue({code:`custom`,message:`URL cannot use javascript:, data:, or vbscript: scheme`}):(e.includes(`#`)&&n.addIssue({code:`custom`,message:`Redirect URI must not contain a fragment component`}),r.protocol===`http:`&&!Gp(r.host)&&n.addIssue({code:`custom`,message:`Redirect URI must use HTTPS (HTTP allowed only for loopback hosts)`}))});function sm(e){return e?.jwks?.keyPairConfig?.alg??`EdDSA`}var cm=(e,t)=>({getAllKeys:async n=>t?.adapter?.getJwks?await t.adapter.getJwks(n):await(await Vd(e)).findMany({model:`jwks`}),getLatestKey:async n=>{let r=new Date,i=e=>!e.expiresAt||e.expiresAt>r;return t?.adapter?.getJwks?(await t.adapter.getJwks(n))?.filter(i).sort((e,t)=>t.createdAt.getTime()-e.createdAt.getTime())[0]:(await(await Vd(e)).findMany({model:`jwks`}))?.filter(i).sort((e,t)=>t.createdAt.getTime()-e.createdAt.getTime())[0]},getKeyById:async(n,r)=>t?.adapter?.getJwks?(await t.adapter.getJwks(n))?.find(e=>e.id===r):await(await Vd(e)).findOne({model:`jwks`,where:[{field:`id`,value:r}]})??void 0,getLatestKeyByAlg:async(n,r)=>{let i=t?.adapter?.getJwks?await t.adapter.getJwks(n):await(await Vd(e)).findMany({model:`jwks`});if(!i)return;let a=sm(t),o=new Date;return i.filter(e=>e.alg===r||e.alg==null&&a===r).filter(e=>!e.expiresAt||e.expiresAt>o).sort((e,t)=>t.createdAt.getTime()-e.createdAt.getTime())[0]},createJwk:async(n,r)=>t?.adapter?.createJwk?await t.adapter.createJwk(r,n):await(await Vd(e)).create({model:`jwks`,data:{...r,createdAt:new Date}})});function lm(e,t){return typeof e==`number`?e:e instanceof Date?Math.floor(e.getTime()/1e3):t+ep(e)}async function um(e){let{alg:t,...n}=e?.jwks?.keyPairConfig??{alg:`EdDSA`,crv:`Ed25519`},{publicKey:r,privateKey:i}=await Ti(t,{...n,extractable:!0});return{publicWebKey:await mi(r),privateWebKey:await mi(i),alg:t,cfg:n}}async function dm(e,t){let{publicWebKey:n,privateWebKey:r,alg:i,cfg:a}=await um(t),o=a&&`crv`in a?a.crv:void 0,s=typeof n.crv==`string`?n.crv:void 0,c=o??s,l=JSON.stringify(r),u=!t?.jwks?.disablePrivateKeyEncryption,d={alg:i,...c?{crv:c}:{},publicKey:JSON.stringify(n),privateKey:u?JSON.stringify(await Ka({key:e.context.secretConfig,data:l})):l,createdAt:new Date,...t?.jwks?.rotationInterval?{expiresAt:new Date(Date.now()+t.jwks.rotationInterval*1e3)}:{}};return await cm(e.context.adapter,t).createJwk(e,d)}async function fm(e,t,n){if(t?.jwt?.sign)return null;let r=cm(e.context.adapter,t),i;if(n?.signingKeyId!==void 0){if(i=await r.getKeyById(e,n.signingKeyId),!i)throw new B(`signJWT: signingKeyId "${n.signingKeyId}" not found in JWKS. The key must be provisioned before it can be referenced.`);if(n.signingAlgorithm!==void 0){let e=sm(t);if((i.alg??e)!==n.signingAlgorithm)throw new B(`signJWT: signingKeyId "${n.signingKeyId}" has alg "${i.alg??`unset (inherits keyPairConfig.alg "${e}")`}" but signingAlgorithm was set to "${n.signingAlgorithm}".`)}}else if(n?.signingAlgorithm!==void 0){if(i=await r.getLatestKeyByAlg(e,n.signingAlgorithm),!i){let r=sm(t),a=t?.jwks?.keyPairConfigs?.find(e=>e.alg===n.signingAlgorithm),o=r===n.signingAlgorithm;if(a||o)i=await dm(e,{...t,jwks:{...t?.jwks,keyPairConfig:a??t?.jwks?.keyPairConfig}});else{let e=t?.jwks?.keyPairConfigs?.map(e=>e.alg).join(`, `)||`none`;throw new B(`signJWT: no key with alg "${n.signingAlgorithm}" found in JWKS. The plugin auto-mints only one key matching keyPairConfig.alg="${r}"; additional algs configured via keyPairConfigs: ${e}. Add "${n.signingAlgorithm}" to jwks.keyPairConfigs so the plugin provisions it on first use, or mint the key explicitly via createJwk().`)}}}else{let n=sm(t);i=await r.getLatestKeyByAlg(e,n)??await r.getLatestKey(e)}if(!i||i.expiresAt&&i.expiresAt<new Date){if(n?.signingKeyId!==void 0||n?.signingAlgorithm!==void 0)throw new B(`signJWT: requested signing key is expired and an explicit kid/alg was provided; not auto-minting a replacement. Rotate the key explicitly.`);i=await dm(e,t)}let a=t?.jwks?.disablePrivateKeyEncryption?i.privateKey:await qa({key:e.context.secretConfig,data:JSON.parse(i.privateKey)}).catch(()=>{throw new B(`Failed to decrypt private key. Make sure the secret currently in use is the same as the one used to encrypt the private key. If you are using a different secret, either clean up your JWKS or disable private key encryption.`)}),o=i.alg??sm(t),s=await xi(JSON.parse(a),o);return{alg:o,kid:i.id,privateKey:s}}async function pm(e,t){let{options:n}=t,r=t.payload,i=Math.floor(Date.now()/1e3),a=r.iat,o=r.exp,s=lm(n?.jwt?.expirationTime??`15m`,a??i);o??=s;let c=r.nbf,l=typeof e.context.options.baseURL==`string`?e.context.options.baseURL:``,u=r.iss,d=n?.jwt?.issuer??l,f=r.aud,p=n?.jwt?.audience??l;if((!(u??d)||!(f??p))&&e.context.logger.warn("[better-auth] The JWT plugin signed a JWT without an issuer or audience because no base URL was resolved for this call. Set `baseURL`, or `jwt.issuer` and `jwt.audience` in the JWT plugin options."),n?.jwt?.sign){let e={...r,iat:a,exp:o,nbf:c,iss:u??d,aud:f??p};return n.jwt.sign(e,t.header,{signingKeyId:t.signingKeyId,signingAlgorithm:t.signingAlgorithm})}let{alg:m,kid:h,privateKey:g}=t.resolvedKey??await fm(e,n,{signingKeyId:t.signingKeyId,signingAlgorithm:t.signingAlgorithm}),_=new Xr(r).setProtectedHeader({...t.header,alg:m,kid:h}).setExpirationTime(o).setIssuer(u??d).setAudience(f??p);return a&&_.setIssuedAt(a),r.sub&&_.setSubject(r.sub),r.nbf&&_.setNotBefore(r.nbf),r.jti&&_.setJti(r.jti),await _.sign(g)}async function mm(e,t){let n=t?.jwt?.definePayload?await t.jwt.definePayload(e.context.session):e.context.session.user;return await pm(e,{options:t,payload:{iat:Math.floor(Date.now()/1e3),...n,sub:await t?.jwt?.getSubject?.(e.context.session)??e.context.session.user.id}})}var hm=S(s(),r()).nullable(),gm=N({essential:F().optional(),value:s().optional(),values:z(s()).optional()}).nullable(),_m=a({acr:gm.optional()}).catchall(hm),vm=N({userinfo:S(s(),hm).optional(),id_token:_m.optional()});function ym(e){if(typeof e==`string`)try{return JSON.parse(e)}catch{return}return e}function bm(e){let t=ym(e),n=vm.safeParse(t);return n.success?n.data:void 0}var xm=re([s(),S(s(),r())]),Sm=xm,Cm=xm.refine(e=>bm(e)!==void 0,{error:`claims must be a valid Claims request object`});function wm(e){return e===void 0||bm(e)!==void 0}function Tm(e,t){let n=bm(e)?.userinfo;if(!n)return[];let r=Object.keys(n);if(!t)return r;let i=new Set(t);return r.filter(e=>i.has(e))}function Em(e,t){let n=bm(e);if(!n)return e===void 0;let r=n.id_token?.acr;if(!r||r.essential!==!0)return!0;let i=r.value===void 0||r.value===t,a=r.values===void 0||r.values.includes(t);return i&&a}function Dm(e,t){let n=bm(e)?.id_token?.acr;return Array.from(new Set([...n?.value===void 0?[]:[n.value],...n?.values??[],...t?.split(` `).filter(Boolean)??[]]))}function Om(e,t){let n=bm(e);if(!n)return;let r=new Set(t),i=Object.fromEntries(Object.entries(n.userinfo??{}).filter(([e])=>r.has(e))),a=Object.keys(i).length?{...n,userinfo:i}:Object.fromEntries(Object.entries(n).filter(([e])=>e!==`userinfo`));return Object.keys(a).length?a:void 0}function km(e){return e.authenticationContext?.acrValuesSupported??[`0`]}function Am(e){throw new g(`INTERNAL_SERVER_ERROR`,{error:`server_error`,error_description:`authenticationContext.resolve ${e}`})}async function jm(e,t){let n=e.authenticationContext?.resolve;if(!n||!t.scopes.includes(`openid`))return{};let{query:r,...i}=t,a=await n({...i,requestedAcrValues:Dm(r.claims,r.acr_values)});a!==void 0&&(typeof a!=`object`||!a)&&Am(`returned a value that is not an object`);let{acr:o=`0`,amr:s}=a??{};return typeof o!=`string`&&Am(`returned a non-string acr`),km(e).includes(o)||Am(`returned acr "${o}", which is not in acrValuesSupported`),s===void 0?{acr:o}:((!Array.isArray(s)||!Array.from(s).every(e=>typeof e==`string`))&&Am(`returned an amr that is not a string array`),{acr:o,amr:s.length?s:void 0})}var Mm=new Set([`iss`,`sub`,`aud`,`exp`,`nbf`,`iat`,`jti`,`auth_time`,`nonce`,`acr`,`amr`,`azp`,`sid`,`at_hash`,`c_hash`,`s_hash`]);function Nm(e){if(!e)return{};let t=[],n=Object.create(null);for(let[r,i]of Object.entries(e))Mm.has(r)?t.push(r):n[r]=i;return t.length>0&&ve.warn(`oauth-provider: stripped reserved id-token claim name(s): ${t.join(`, `)}. The AS owns these claim values.`),n}function Pm(e){let t=e.split(` `).filter(e=>e!==``);return t.length<=1?{}:{given:t.slice(0,-1).join(` `),family:t.at(-1)}}var Fm={name:{scope:`profile`,resolve:e=>e.name??void 0},picture:{scope:`profile`,resolve:e=>e.image??void 0},given_name:{scope:`profile`,resolve:e=>Pm(e.name).given},family_name:{scope:`profile`,resolve:e=>Pm(e.name).family},email:{scope:`email`,resolve:e=>e.email??void 0},email_verified:{scope:`email`,resolve:e=>e.emailVerified??!1}},Im=Object.keys(Fm);function Lm(e){return e.advertisedMetadata?.claims_supported??e.claims??[]}var Rm=new Set([`iss`,`sub`,`aud`,`exp`,`iat`,`jti`,`client_id`,`scope`,`auth_time`,`acr`,`amr`,`cnf`,`reference_id`]);function zm(e){if(!e)return{};let t=[],n={};for(let[r,i]of Object.entries(e))Rm.has(r)?t.push(r):n[r]=i;return t.length>0&&ve.warn(`oauth-provider: stripped reserved access-token claim name(s): ${t.join(`, `)}. The AS owns these claim values.`),n}async function Bm(e){let{ctx:t,opts:n,user:r,client:i,scopes:a,resources:o,referenceId:s,metadata:c,grantType:l,sessionId:u,perRequestClaims:d,resourcePolicyClaims:f}=e,p=await Sl(n,{ctx:t,opts:n,user:r,client:i,scopes:a,grantType:l,referenceId:s,sessionId:u,resources:o,metadata:c}),m=n.customAccessTokenClaims?await n.customAccessTokenClaims({user:r,scopes:a,resources:o,referenceId:s,metadata:c}):{};return zm({...p,...d??{},...m,...f})}var Vm=[`javascript:`,`data:`,`vbscript:`],Hm=s().superRefine((e,n)=>{if(!URL.canParse(e))return n.addIssue({code:`custom`,message:`resource must be an absolute URI`,fatal:!0}),t;e.includes(`#`)?n.addIssue({code:`custom`,message:`resource must not contain a fragment`}):Vm.includes(new URL(e).protocol)&&n.addIssue({code:`custom`,message:`resource cannot use javascript:, data:, or vbscript: scheme`})}),Um=pe([`none`,`consent`,`login`,`create`,`select_account`]),Wm=s().superRefine((e,t)=>{let n=e.split(` `).map(e=>e.trim()).filter(Boolean),r=new Set;if(!n.length)t.addIssue({code:`custom`,message:`prompt must include at least one value`});else{for(let e of n){let n=Um.safeParse(e);n.success?r.add(n.data):t.addIssue({code:`custom`,message:`unsupported prompt value: ${e}`})}r.has(`none`)&&r.size>1&&t.addIssue({code:`custom`,message:`prompt=none cannot be combined with other prompt values`})}}),Gm=a({keys:z(S(s(),r())).min(1)}),Km=re([b(),s().trim().min(1)]).transform((e,n)=>{let r=typeof e==`number`?e:Number(e);return!Number.isInteger(r)||r<0?(n.addIssue({code:`custom`,message:`max_age must be a non-negative integer`}),t):r}),qm=s().regex(/^[A-Za-z0-9_-]{43}$/,`dpop_jkt must be a base64url-encoded SHA-256 JWK thumbprint`),Jm=a({response_type:s().pipe(pe([`code`])).optional(),request:s().optional(),request_uri:s().optional(),redirect_uri:Q.optional(),scope:s().optional(),state:s().optional(),client_id:s().min(1,`client_id is required`),prompt:Wm.optional(),display:s().optional(),ui_locales:s().optional(),max_age:Km.optional(),acr_values:s().optional(),login_hint:s().optional(),id_token_hint:s().optional(),code_challenge:s().optional(),code_challenge_method:s().pipe(pe([`S256`])).optional(),nonce:s().optional(),claims:Sm.optional(),dpop_jkt:qm.optional(),resource:re([Hm,z(Hm).min(1)]).optional()}).passthrough(),Ym=Jm.extend({redirect_uri:Q.optional(),claims:Cm.optional()}),Xm=a({type:xe(`authorization_code`),query:Ym,sessionId:s(),userId:s(),referenceId:s().optional(),authTime:b().optional(),acr:s().optional(),amr:z(s()).optional(),resource:z(s()).optional()}).passthrough(),Zm=a({redirect_uris:z(Q).min(1).optional(),scope:s().optional(),client_name:s().refine(e=>e.trim().length>0,`client_name cannot be empty`).optional(),client_uri:s().optional(),logo_uri:s().optional(),contacts:z(s().min(1)).min(1).optional(),tos_uri:s().optional(),policy_uri:s().optional(),software_id:s().optional(),software_version:s().optional(),software_statement:s().optional(),post_logout_redirect_uris:z(Q).min(1).optional(),backchannel_logout_uri:Q.optional(),backchannel_logout_session_required:F().optional(),frontchannel_logout_uri:Q.optional(),frontchannel_logout_session_required:F().optional(),token_endpoint_auth_method:s().trim().min(1).optional(),jwks:Gm.optional(),jwks_uri:s().optional(),grant_types:z(s().trim().min(1)).min(1).optional(),response_types:z(pe([`code`])).optional(),application_type:pe([`web`,`native`]).optional(),subject_type:pe([`public`,`pairwise`]).optional(),dpop_bound_access_tokens:F().optional(),resources:z(Hm).optional(),skip_consent:be({error:`skip_consent cannot be set during dynamic client registration`}).optional()}),Qm=Zm.omit({skip_consent:!0}).extend({client_id:s().refine(e=>e.trim().length>0,`client_id cannot be empty`),client_secret:s().optional(),client_secret_expires_at:b().int().nonnegative().optional(),client_id_issued_at:b().int().nonnegative().optional()}).loose(),$m=[`EdDSA`,`ES256`,`ES512`,`PS256`,`RS256`],eh=new Set($m),th=64;async function nh(e,t){let n=e.identifierValidator;if(n)return await n(t)?{ok:!0}:{ok:!1,reason:`resource identifier ${t} failed validation`};let r=Hm.safeParse(t);return r.success?{ok:!0}:{ok:!1,reason:`resource identifier ${t} is invalid: ${r.error.issues[0]?.message??`not an absolute URI`}`}}async function rh(e,t){let n=await nh(e,t);if(!n.ok)throw new M(`BAD_REQUEST`,{error:`invalid_target`,error_description:n.reason})}var ih=e=>`${e}/oauth2/userinfo`;function ah(e){if(e!=null){if(typeof e==`string`)return[e];if(Array.isArray(e)){let t=e.filter(e=>typeof e==`string`&&e.length>0);return t.length>0?t:void 0}}}async function oh(e,t,n,r=[]){if(n===void 0)return!0;let i=Array.isArray(n)?n:[n];if(i.length>th)return!1;let a=new Set(r),o=new Set;for(let e of i)a.has(e)||o.add(e);return o.size===0||(await Promise.all(Array.from(o,n=>mh(e,t,n)))).every(Boolean)}async function sh(e,t,n){let r=ah(n.resource),i=n.requestedScopes.includes(`openid`),a=ih(e.context.baseURL??``);if(!r)return{audienceClaim:void 0,accessTokenTtl:null,refreshTokenTtl:null,signingAlgorithm:null,signingKeyId:null,rawCustomClaims:{},dpopBoundAccessTokensRequired:!1,effectiveScopes:[...n.requestedScopes]};let o=[...new Set(r)],s=[];for(let n of o){if(n===a)continue;let r=await mh(e,t,n);if(r){if(r.disabled)throw new M(`BAD_REQUEST`,{error:`invalid_target`,error_description:`requested resource ${n} is disabled`});s.push(r)}else throw new M(`BAD_REQUEST`,{error:`invalid_target`,error_description:`requested resource ${n} is not configured`})}let{value:c}=dh(t);c&&s.length>0&&await ch(e,t,n.clientId,s);let l=[...n.requestedScopes];for(let e of s){if(e.allowedScopes===null||e.allowedScopes===void 0)continue;let t=new Set(e.allowedScopes),n=l.filter(e=>t.has(e));if(n.length===0)throw new M(`BAD_REQUEST`,{error:`invalid_scope`,error_description:`none of the requested scopes are allowed for resource ${e.identifier}`});l=n}let u=null,d=null;for(let e of s)e.accessTokenTtl!=null&&(u=u===null?e.accessTokenTtl:Math.min(u,e.accessTokenTtl)),e.refreshTokenTtl!=null&&(d=d===null?e.refreshTokenTtl:Math.min(d,e.refreshTokenTtl));let f=new Set,p=new Set;for(let e of s)e.signingAlgorithm&&f.add(e.signingAlgorithm),e.signingKeyId&&p.add(e.signingKeyId);if(f.size>1)throw new M(`BAD_REQUEST`,{error:`invalid_request`,error_description:`multi-resource request has conflicting signingAlgorithm pins; a single JWS signature cannot satisfy multiple algorithms`});if(p.size>1)throw new M(`BAD_REQUEST`,{error:`invalid_request`,error_description:`multi-resource request has conflicting signingKeyId pins; a single JWS signature cannot satisfy multiple key ids`});let m=f.values().next().value??null,h=p.values().next().value??null,g={};for(let e of s)e.customClaims&&typeof e.customClaims==`object`&&Object.assign(g,e.customClaims);let _=s.some(e=>e.dpopBoundAccessTokensRequired===!0),v=i?[...o,a]:o,y=[...new Set(v)];return{audienceClaim:y.length===1?y[0]:y,accessTokenTtl:u,refreshTokenTtl:d,signingAlgorithm:m,signingKeyId:h,rawCustomClaims:g,dpopBoundAccessTokensRequired:_,effectiveScopes:l}}async function ch(e,t,n,r){if(r.length===0)return;let i=t.schema?.oauthClientResource?.modelName??`oauthClientResource`,a=await e.context.adapter.findMany({model:i,where:[{field:`clientId`,value:n}]}),o=new Set(a?.map(e=>e.resourceId)??[]),s=r.filter(e=>!o.has(e.identifier));if(s.length>0)throw new M(`BAD_REQUEST`,{error:`invalid_target`,error_description:`client ${n} is not linked to resource(s) ${s.map(e=>e.identifier).join(`, `)}`})}async function lh(e,t,n,r){if(r.length===0)return!1;let i=t.schema?.oauthClientResource?.modelName??`oauthClientResource`;return((await e.context.adapter.findMany({model:i,where:[{field:`clientId`,value:n},{field:`resourceId`,operator:`in`,value:r}],limit:1}))?.length??0)>0}async function uh(e,t,n){if(n.length===0)return{};let r=await e.context.adapter.findMany({model:t.schema?.oauthResource?.modelName??`oauthResource`,where:[{field:`identifier`,operator:`in`,value:n}]}),i=new Map(r.map(e=>[e.identifier,e])),a={};for(let e of n){let t=i.get(e);t?.customClaims&&typeof t.customClaims==`object`&&Object.assign(a,t.customClaims)}return a}function dh(e){return e.enforcePerClientResources===void 0?{value:!0,source:`default`}:{value:e.enforcePerClientResources,source:`explicit`}}var fh=new Map;function ph(e){e===void 0?fh.clear():fh.delete(e)}async function mh(e,t,n){if(await wh(e.context,t),t.cachedResources?.has(n)){let e=fh.get(n);if(e)return Object.assign({},e)}let r=await e.context.adapter.findOne({model:t.schema?.oauthResource?.modelName??`oauthResource`,where:[{field:`identifier`,value:n}]});return r&&t.cachedResources?.has(n)&&fh.set(n,Object.assign({},r)),r}function hh(e){return e.name??e.identifier}function gh(e){let t=[];if(e.resources?.length)for(let n of e.resources)t.push(typeof n==`string`?{identifier:n}:n);return t}function _h(e,t){return{identifier:e.identifier,name:hh(e),accessTokenTtl:e.accessTokenTtl??null,refreshTokenTtl:e.refreshTokenTtl??null,signingAlgorithm:e.signingAlgorithm??null,signingKeyId:e.signingKeyId??null,allowedScopes:e.allowedScopes??null,customClaims:e.customClaims??null,dpopBoundAccessTokensRequired:e.dpopBoundAccessTokensRequired??!1,disabled:e.disabled??!1,policyVersion:1,metadata:e.metadata??null,createdAt:t,updatedAt:t}}function vh(e,t,n){if(t===`overwrite`){let{identifier:t,createdAt:r,...i}=_h(e,n);return i}let r={updatedAt:n};return e.name!==void 0&&(r.name=e.name),e.accessTokenTtl!==void 0&&(r.accessTokenTtl=e.accessTokenTtl),e.refreshTokenTtl!==void 0&&(r.refreshTokenTtl=e.refreshTokenTtl),e.signingAlgorithm!==void 0&&(r.signingAlgorithm=e.signingAlgorithm),e.signingKeyId!==void 0&&(r.signingKeyId=e.signingKeyId),e.allowedScopes!==void 0&&(r.allowedScopes=e.allowedScopes),e.customClaims!==void 0&&(r.customClaims=e.customClaims),e.dpopBoundAccessTokensRequired!==void 0&&(r.dpopBoundAccessTokensRequired=e.dpopBoundAccessTokensRequired),e.disabled!==void 0&&(r.disabled=e.disabled),e.metadata!==void 0&&(r.metadata=e.metadata),r}var yh=/no such table|relation.*does not exist|table.*does(?: not|n'?t) exist|model.*(?:does not exist|was not found in the schema)/i;function bh(e,t){let n=!1,r=t;for(let e=0;r&&!n&&e<5;e++)n=yh.test(r instanceof Error?r.message:String(r)),r=r instanceof Error?r.cause:void 0;n?e.logger.debug(`oauth-provider: oauthResource table not yet created; deferring resource seed to first access.`):e.logger.error("oauth-provider: could not seed `resources` at startup; retrying on first resource access.",t)}var xh=new WeakMap;function Sh(e,t){let n=e.adapter,r=xh.get(n);r||(r=new WeakMap,xh.set(n,r));let i=r.get(t);if(i)return i;let a={completed:!1,promise:null};return r.set(t,a),a}async function Ch(e,t){let n=gh(t);if(n.length===0)return;let r=t.resourceSeedMode??`insertOnly`,i=t.schema?.oauthResource?.modelName??`oauthResource`;for(let a of n){let n=await nh(t,a.identifier);if(!n.ok){ve.warn(`oauth-provider: skipping resource seed for ${a.identifier} — ${n.reason}`);continue}let o=a;if(o.signingAlgorithm!=null&&!eh.has(o.signingAlgorithm)){ve.warn(`oauth-provider: dropping unsupported signingAlgorithm "${o.signingAlgorithm}" for resource ${o.identifier} — must be one of ${$m.join(`, `)}. Continuing without an algorithm override.`);let{signingAlgorithm:e,...t}=o;o=t}let s=[{field:`identifier`,value:o.identifier}],c=await e.adapter.findOne({model:i,where:s}),l=new Date;if(!c)try{await e.adapter.create({model:i,data:_h(o,l)});continue}catch(t){if(!await e.adapter.findOne({model:i,where:s}).catch(()=>null))throw t}r!==`insertOnly`&&await e.adapter.update({model:i,where:s,update:vh(o,r,l)})}}async function wh(e,t){let n=Sh(e,t);if(n.completed!==!0)return n.promise===null&&(n.promise=Ch(e,t).then(()=>{n.completed=!0}).catch(e=>{throw n.promise=null,e})),n.promise}function Th(e){let t=dh(e);ve.info(`oauth-provider: enforcePerClientResources resolved to ${t.value} (${t.source})`)}function Eh(e){return e.headers?.get(`dpop`)??void 0}function Dh(e,t){let{baseURL:n}=e.context,r=n.length;for(;r>0&&n[r-1]===`/`;)r--;let i=n.slice(0,r);if(!e.request||!i)return`${i}${t}`;let a=new URL(i).pathname.replace(/\/$/,``),o=new URL(e.request.url).pathname;return`${i}${o.startsWith(`${a}/`)?o.slice(a.length):t}`}var Oh=new Set([`openid`,`profile`,`email`,`offline_access`]);function kh(e){return Oh.has(e)}function Ah(e){return[...new Set(e.map(e=>e.trim()).filter(Boolean))]}function jh(e,t,n,r){if(e.length===0)return;if(!t.includes(`client_credentials`))throw new M(`BAD_REQUEST`,{error:`invalid_client_metadata`,error_description:`client_credentials_scopes requires the client_credentials grant`});if(n===`none`)throw new M(`BAD_REQUEST`,{error:`invalid_client_metadata`,error_description:`public clients cannot be assigned client_credentials scopes`});let i=new Set(r.scopes??[]),a=e.filter(e=>!i.has(e)||kh(e));if(a.length>0)throw new M(`BAD_REQUEST`,{error:`invalid_scope`,error_description:`The following client_credentials scopes are invalid: ${a.join(`, `)}`})}var Mh=new Set([xt.code,vt.code,bt.code]);async function Nh(e,t,n){if(t.disableJwtPlugin||n.split(`.`).length!==3)return null;try{Si(n)}catch{return null}let r=Ml(e.context),i=r.options,a=await Hc(n,{jwksFetch:i?.jwks?.remoteUrl?i.jwks.remoteUrl:async()=>(await r.endpoints.getJwks(e))?.response,jwksCacheKey:r}),o;try{({payload:o}=await Gr(n,yi(a),{issuer:i?.jwt?.issuer??e.context.baseURL}))}catch(e){if(e instanceof pt||e instanceof ft)return Ph(e.payload)?`inactive`:null;if(e instanceof V&&!Mh.has(e.code))return null;throw e}return Ph(o)?o:null}function Ph(e){return typeof e.azp==`string`&&e.azp.length>0}async function Fh(e,t,n){let r=t.prefix?.opaqueAccessToken;return r&&!n.startsWith(r)?null:e.context.adapter.findOne({model:`oauthAccessToken`,where:[{field:`token`,value:await Jl(t.storeTokens,r?n.slice(r.length):n,`access_token`)}]})}async function Ih(e,t,n){let r=t.prefix?.refreshToken;if(r&&!n.startsWith(r))return null;let i=r?n.slice(r.length):n,a;try{a=t.formatRefreshToken?.decrypt?await t.formatRefreshToken.decrypt(i):{token:i}}catch(e){if(e instanceof g&&e.statusCode===400||e instanceof V)return null;throw e}return e.context.adapter.findOne({model:`oauthRefreshToken`,where:[{field:`token`,value:await Jl(t.storeTokens,a.token,`refresh_token`)}]})}async function Lh(e,t,n){let r=await Nh(e,t,n);if(r===`inactive`)return r;if(r)return{type:`jwt`,payload:r};let i=await Fh(e,t,n);return i?{type:`opaque`,record:i}:null}async function Rh(e,t,n){let r=await Lh(e,t,n);return r===`inactive`?null:r}async function zh(e,t,n,r){let i=async()=>{let r=await Ih(e,t,n);return r?{type:`refresh`,record:r}:null};if(r===`refresh_token`)return await i()??Rh(e,t,n);let a=await Lh(e,t,n);return a===`inactive`?null:a??i()}function Bh(e,t,n=[]){let r=new Set(n),i={sub:e.id??void 0};for(let[n,a]of Object.entries(Fm))(t.includes(a.scope)||r.has(n))&&(i[n]=a.resolve(e));return i}function Vh(e,t){let n={};for(let[r,i]of Object.entries(e??{}))i!==void 0&&(t&&r in t||(n[r]=i));return n}function Hh(e){let t=e.headers?.get(`authorization`),n=hc(t),r=e.request?.method===`POST`?e.body?.access_token??void 0:void 0;if(n&&r)throw new M(`BAD_REQUEST`,{error_description:`Multiple access token transport methods are not allowed`,error:`invalid_request`});let i=n??(r?{scheme:`Bearer`,token:r}:void 0);return{authorization:i,token:i?.token}}async function Uh(e,t){let{authorization:n}=Hh(e);if(!n?.token)throw new M(`UNAUTHORIZED`,{error_description:`access token not found`,error:`invalid_request`});let{payload:r,requestedUserInfoClaims:i}=await Ug(e,t,n.token);if(xc(r)&&!e.request)throw new M(`UNAUTHORIZED`,{error_description:`DPoP-bound access token requires an HTTP request context`,error:`invalid_token`});try{await jc({payload:r,authorization:n,proofJwt:Eh(e),method:e.request?.method??`GET`,url:Dh(e,`/oauth2/userinfo`),proofMaxAgeSeconds:t.dpop?.proofMaxAgeSeconds,signingAlgorithms:t.dpop?.signingAlgorithms,replayStore:pc(e.context.internalAdapter)})}catch(e){throw Ac(e)?new M(`UNAUTHORIZED`,{error_description:e.message,error:e.code}):e}let a=r.scope?.split(` `);if(!a?.includes(`openid`))throw new M(`BAD_REQUEST`,{error_description:`Missing required scope`,error:`invalid_scope`});if(!r.sub)throw new M(`BAD_REQUEST`,{error_description:`user not found`,error:`invalid_request`});let o=await e.context.internalAdapter.findUserById(r.sub);if(!o)throw new M(`BAD_REQUEST`,{error_description:`user not found`,error:`invalid_request`});let s=Bh(o,a??[],i),c=r.client_id??r.azp,l=c&&(t.pairwiseSecret||Ol(t))?await Vl(e,t,c):void 0;t.pairwiseSecret&&l&&(s.sub=await vu(o.id,l,t));let u=a?.length?await wl(t,{ctx:e,opts:t,user:o,scopes:a,jwt:r,client:l??void 0,requestedClaims:i}):{},d=t.customUserInfoClaims&&a?.length?await t.customUserInfoClaims({user:o,scopes:a,jwt:r,requestedClaims:i}):{};return{...s,...Vh(u,s),...Vh(d),sub:s.sub}}var Wh=Object.fromEntries(Im.map(e=>[e,void 0]));function Gh(e){return bc(e)?`DPoP`:`Bearer`}var Kh=`at+jwt`;async function qh(e,t){let n=e.body.grant_type;if(!pl(t).includes(n))throw new M(`BAD_REQUEST`,{error_description:`unsupported grant_type ${n}`,error:`unsupported_grant_type`});switch(n){case`authorization_code`:return Eg(e,t);case`client_credentials`:return Dg(e,t);case`refresh_token`:return Og(e,t);default:{let r=hl(t,n);if(r)return r({ctx:e,opts:t,grantType:n,provider:Jh(e,t,n)});throw new M(`BAD_REQUEST`,{error_description:`unsupported grant_type ${n}`,error:`unsupported_grant_type`})}}}function Jh(e,t,n){return{getClient:n=>Vl(e,t,n),authenticateClient:async r=>{let{clientId:i,clientSecret:a,preVerified:o,authMethod:s,confirmation:c}=fu(await pu(e,t,`${e.context.baseURL}${e.path??`/oauth2/token`}`));if(!i)throw new M(`BAD_REQUEST`,{error_description:`Missing required client_id`,error:`invalid_request`});if(r?.requireCredentials!==!1&&!a&&!o)throw new M(`BAD_REQUEST`,{error_description:`Missing required client credentials`,error:`invalid_client`});return{clientId:i,client:await uu(e,t,i,a,r?.scopes,o,n,s),method:s,confirmation:c}},issueTokens:r=>{if(!n)throw new M(`INTERNAL_SERVER_ERROR`,{error_description:`issueTokens requires a grant type; pass it to getOAuthProviderApi(ctx, opts, grantType).`,error:`server_error`});return wg(e,t,{...r,grantType:n})},resolveConfirmation:async n=>{if(n.confirmation)return n.confirmation;let r=await sh(e,t,{resource:n.resources,clientId:n.client.clientId,requestedScopes:n.scopes});return og(e,t,{client:n.client,grantIssuance:{dpopBoundAccessTokensRequired:r.dpopBoundAccessTokensRequired}})},hashToken:(e,n)=>ql(t.storeTokens,e,n),validateAccessToken:async(n,r)=>{let{validateAccessToken:i}=await Promise.resolve().then(()=>kg);return i(e,t,n,r)},requireActiveAccessToken:async(n,r)=>{let{requireActiveAccessToken:i}=await Promise.resolve().then(()=>kg);return i(e,t,n,r)}}}async function Yh(e,t,n,r,i,a,o){let s=o?.iat??Math.floor(Date.now()/1e3),c=o?.exp??s+(t.accessTokenExpiresIn??3600),l=Ml(e.context).options,u=n?.id??r.clientId;return pm(e,{options:l,header:{typ:Kh},signingKeyId:o?.signingKeyId??void 0,signingAlgorithm:o?.signingAlgorithm??void 0,payload:{...o?.accessTokenClaims??{},sub:u,aud:Il(i),client_id:r.clientId,azp:r.clientId,scope:a.join(` `),sid:o?.sid,reference_id:o?.referenceId,iss:l?.jwt?.issuer??e.context.baseURL,iat:s,exp:c,jti:zi(32),...o?.confirmation?{cnf:o.confirmation}:{}}})}async function Xh(e,t){let n;n=t===`EdDSA`?`SHA-512`:t.endsWith(`384`)?`SHA-384`:t.endsWith(`512`)?`SHA-512`:`SHA-256`;let r=new Uint8Array(await crypto.subtle.digest(n,new TextEncoder().encode(e)));return G(r.slice(0,r.length/2))}async function Zh(e,t,n,r,i,a,o,s,c,l,u){let d=Math.floor(Date.now()/1e3),f=d+(t.idTokenExpiresIn??36e3),p=await vu(n.id,r,t),m=s==null?void 0:Math.floor(s.getTime()/1e3),h=Nm(t.customIdTokenClaims?await t.customIdTokenClaims({user:n,scopes:i,metadata:du(r.metadata)}):void 0),g=t.disableJwtPlugin?void 0:Ml(e.context).options,_=!t.disableJwtPlugin&&!g?.jwt?.sign?await fm(e,g):void 0,v=t.disableJwtPlugin?`HS256`:_?.alg??g?.jwks?.keyPairConfig?.alg,y=c?await Xh(c,v):void 0,b=!!(r.enableEndSession||r.backchannelLogoutUri||r.frontchannelLogoutUri),x={...Wh,auth_time:m,acr:u?.acr??`0`,amr:u?.amr,...h,at_hash:y,iss:g?.jwt?.issuer??e.context.baseURL,sub:p,aud:r.clientId,nonce:a,iat:d,exp:f,sid:b?o:void 0},S=Nm(l);if(Object.assign(x,Vh(S,x)),t.disableJwtPlugin&&!r.clientSecret)return;let C=t.disableJwtPlugin?await new Xr(x).setProtectedHeader({alg:`HS256`}).sign(new TextEncoder().encode(await Wl(e,t.storeClientSecret,r.clientSecret))):await pm(e,{options:g,payload:x,resolvedKey:_??void 0});if(C&&y&&g?.jwt?.sign){let e=Si(C);if(e.alg!==v)throw new M(`INTERNAL_SERVER_ERROR`,{error_description:`ID token signed with "${e.alg}" but at_hash was computed for "${v}". Ensure jwt.sign uses the algorithm declared in keyPairConfig.alg.`,error:`server_error`})}return C}async function Qh(e,t,n){return(e.prefix?.refreshToken??``)+(e.formatRefreshToken?.encrypt?await e.formatRefreshToken.encrypt(t,n):t)}async function $h(e,t,n,r,i,a,o,s,c,l,u,d){let f=a.iat??Math.floor(Date.now()/1e3),p=a?.exp??f+(t.accessTokenExpiresIn??3600),m=t.generateOpaqueAccessToken?await t.generateOpaqueAccessToken():zi(32,`A-Z`,`a-z`);return await e.context.adapter.create({model:`oauthAccessToken`,data:{token:await ql(t.storeTokens,m,`access_token`),clientId:r.clientId,sessionId:a?.sid,userId:n?.id,referenceId:s,authorizationCodeId:c,resources:o,refreshId:l,confirmation:u,requestedUserInfoClaims:d?.length?d:void 0,scopes:i,createdAt:new Date(f*1e3),expiresAt:new Date(p*1e3)}}),(t.prefix?.opaqueAccessToken??``)+m}async function eg(e,t,n){let r=await e.context.adapter.findMany({model:`oauthRefreshToken`,where:[{field:`clientId`,value:t},{field:`userId`,value:n}]});r.length&&await e.context.adapter.deleteMany({model:`oauthAccessToken`,where:[{field:`refreshId`,operator:`in`,value:r.map(e=>e.id)}]}),await e.context.adapter.deleteMany({model:`oauthRefreshToken`,where:[{field:`clientId`,value:t},{field:`userId`,value:n}]})}async function tg(e,t){let n=async n=>{try{await e.context.adapter.deleteMany({model:n,where:[{field:`authorizationCodeId`,value:t}]})}catch(t){e.context.logger.error(`authorization code replay cleanup failed`,t)}};await n(`oauthAccessToken`),await n(`oauthRefreshToken`)}async function ng(e,t,n,r,i,a,o,s,c,l,u,d,f,p){let m=s.iat??Math.floor(Date.now()/1e3),h=s?.exp??m+(t.refreshTokenExpiresIn??2592e3),g=t.generateRefreshToken?await t.generateRefreshToken():zi(32,`A-Z`,`a-z`),_=s?.sid,v={token:await ql(t.storeTokens,g,`refresh_token`),clientId:a.clientId,sessionId:_,userId:n.id,referenceId:r,authorizationCodeId:i,authTime:l,acr:p?.acr,amr:p?.amr,confirmation:d,requestedUserInfoClaims:f?.length?f:void 0,scopes:o,resources:u,createdAt:new Date(m*1e3),expiresAt:new Date(h*1e3)};if(!c?.id)return{id:(await e.context.adapter.create({model:`oauthRefreshToken`,data:v})).id,token:await Qh(t,g,_)};let y=new Date(m*1e3),b={revoked:y,rotatedAt:y},x=t.refreshTokenReuseInterval??0;if(x>0&&(b.rotationReplayExpiresAt=new Date((m+x)*1e3)),!await e.context.adapter.incrementOne({model:`oauthRefreshToken`,where:[{field:`id`,value:c.id},{field:`revoked`,operator:`eq`,value:null}],increment:{},set:b}))throw new M(`BAD_REQUEST`,{error_description:`invalid refresh token`,error:`invalid_grant`});return{id:(await e.context.adapter.create({model:`oauthRefreshToken`,data:v})).id,token:await Qh(t,g,_)}}async function rg(e,t,n){let r=await sh(e,t,{resource:n.resources,clientId:n.clientId,requestedScopes:n.requestedScopes}),i=r.accessTokenTtl===null?n.scopeExpiresAtSeconds:n.iat+r.accessTokenTtl,a=t.refreshTokenExpiresIn??2592e3,o=r.refreshTokenTtl===null?a:Math.min(r.refreshTokenTtl,a);return{audienceClaim:r.audienceClaim,effectiveScopes:r.effectiveScopes,accessTokenExpiresAtSeconds:Math.min(n.scopeExpiresAtSeconds,i),refreshTokenExpiresAtSeconds:n.iat+o,refreshResources:n.refreshToken?.resources??n.originalResources??n.resources,signingAlgorithm:r.signingAlgorithm,signingKeyId:r.signingKeyId,resourceCustomClaims:r.rawCustomClaims,dpopBoundAccessTokensRequired:r.dpopBoundAccessTokensRequired}}function ig(e){throw new M(`BAD_REQUEST`,{error:`invalid_dpop_proof`,error_description:e})}function ag(e){let t=du(e.metadata)??{};return e.dpopBoundAccessTokens===!0||t.dpop_bound_access_tokens===!0}async function og(e,t,n){let r=n.verificationValue?.query.dpop_jkt,i=bc(n.refreshToken?.confirmation),a=i??r,o=Eh(e),s=ag(n.client)||n.grantIssuance.dpopBoundAccessTokensRequired||!!r||!!i;if(!o)s&&ig(`DPoP proof header is required`);else try{return{jkt:(await Oc({proofJwt:o,method:`POST`,url:Dh(e,e.path??`/oauth2/token`),expectedJkt:a,proofMaxAgeSeconds:t.dpop?.proofMaxAgeSeconds,signingAlgorithms:t.dpop?.signingAlgorithms,replayStore:pc(e.context.internalAdapter)})).jkt}}catch(e){throw mc(e)&&ig(e.message),e}}function sg(e){return e?[...new Set(e)].sort():void 0}function cg(e,t){let n=sg(e),r=sg(t);return n===void 0||r===void 0?n===r:n.length===r.length&&n.every((e,t)=>e===r[t])}function lg(e){if(e)return`jkt`in e?`jkt:${e.jkt}`:`x5t#S256:${e[`x5t#S256`]}`}function ug(e,t){return lg(e)===lg(t)}function dg(e){if(!e||typeof e!=`object`)return!1;let t=e;return typeof t.jkt==`string`&&t[`x5t#S256`]===void 0||typeof t[`x5t#S256`]==`string`&&t.jkt===void 0}function fg(e){return e===`Bearer`||e===`DPoP`}function pg(e){if(!e||typeof e!=`object`)return!1;let t=e;return typeof t.access_token==`string`&&typeof t.expires_in==`number`&&typeof t.expires_at==`number`&&fg(t.token_type)&&typeof t.scope==`string`&&(t.refresh_token===void 0||typeof t.refresh_token==`string`)&&(t.id_token===void 0||typeof t.id_token==`string`)}function mg(e){if(!e||typeof e!=`object`)return!1;let t=e,n=t.request;return!!n&&Array.isArray(n.effectiveScopes)&&n.effectiveScopes.every(e=>typeof e==`string`)&&(n.requestedResources===void 0||Array.isArray(n.requestedResources)&&n.requestedResources.every(e=>typeof e==`string`))&&(n.confirmation===void 0||dg(n.confirmation))&&pg(t.response)}function hg(e){let t=sg(e.requestedResources);return{effectiveScopes:sg(e.effectiveScopes)??[],...t?{requestedResources:t}:{},...e.confirmation?{confirmation:e.confirmation}:{}}}function gg(e,t){return cg(e.effectiveScopes,t.effectiveScopes)&&cg(e.requestedResources,t.requestedResources)&&ug(e.confirmation,t.confirmation)}async function _g(e,t){return Ka({key:e.context.secretConfig,data:JSON.stringify(t)})}async function vg(e,t){let n=await qa({key:e.context.secretConfig,data:t}),r=JSON.parse(n);if(mg(r))return r}function yg(e){return!!e.rotatedAt&&!!e.rotationReplayExpiresAt&&e.rotationReplayExpiresAt>=new Date}async function bg(e,t,n,r,i){(t.refreshTokenReuseInterval??0)<=0||await e.context.adapter.update({model:`oauthRefreshToken`,where:[{field:`id`,value:n.id}],update:{rotationReplayResponse:await _g(e,{request:r,response:i})}})}async function xg(e,t,n){if(yg(t)&&t.rotationReplayResponse)try{let r=await vg(e,t.rotationReplayResponse);return!r||!gg(r.request,n)?void 0:r.response}catch(t){e.context.logger.error(`refresh token rotation replay failed`,t);return}}async function Sg(e,t,n){let r=Math.floor(Date.now()/1e3),i=await rg(e,t,{clientId:n.client.clientId,requestedScopes:n.scopes,resources:n.resources,refreshToken:n.refreshToken,iat:r,scopeExpiresAtSeconds:r+(t.accessTokenExpiresIn??3600)}),a=await og(e,t,{client:n.client,grantIssuance:i,refreshToken:n.refreshToken});return hg({effectiveScopes:i.effectiveScopes,requestedResources:n.resources,confirmation:a})}function Cg(e,t){let n=Math.floor(Date.now()/1e3);return e.json({...t,expires_in:Math.max(0,t.expires_at-n)})}async function wg(e,t,n){let{client:r,scopes:i,user:a,grantType:o,referenceId:s,sessionId:c,nonce:l,refreshToken:u,authTime:d,acr:f,amr:p,verificationValue:m}=n,h={acr:f,amr:p},g=Math.floor(Date.now()/1e3),_=a?t.accessTokenExpiresIn??3600:t.m2mAccessTokenExpiresIn??3600,v=Math.min(g+_,n.maxExpiresAt?Math.floor(n.maxExpiresAt.getTime()/1e3):1/0);if(v<=g)throw new M(`BAD_REQUEST`,{error:`invalid_request`,error_description:`the token this grant derives from has expired`});let y=t.scopeExpirations?i.map(e=>t.scopeExpirations?.[e]?lm(t.scopeExpirations[e],g):v).reduce((e,t)=>e<t?e:t,v):v,b=await rg(e,t,{clientId:r.clientId,requestedScopes:i,resources:n.resources,originalResources:n.originalResources,refreshToken:n.refreshToken,iat:g,scopeExpiresAtSeconds:y}),x=b.audienceClaim,S=b.effectiveScopes,C=b.accessTokenExpiresAtSeconds,w=b.refreshTokenExpiresAtSeconds,T=a&&iu(r,`refresh_token`)&&(u?.scopes?.includes(`offline_access`)||i.includes(`offline_access`)),E=x&&!t.disableJwtPlugin,D=a&&S.includes(`openid`),O=du(r.metadata),k=D&&a?{...await Cl(t,{ctx:e,opts:t,user:a,client:r,scopes:S,grantType:o,referenceId:s,sessionId:c,resources:n.resources,metadata:O}),...n.idTokenClaims??{}}:void 0,A=t.customTokenResponseFields?await t.customTokenResponseFields({grantType:o,user:a,scopes:S,metadata:O,verificationValue:m}):void 0,j=b.refreshResources,N=n.confirmation??await og(e,t,{client:r,grantIssuance:b,verificationValue:m,refreshToken:u}),P=n.requestedUserInfoClaims??u?.requestedUserInfoClaims??[],F=T&&a&&!E?await ng(e,t,a,s,n.authorizationCodeId,r,S,{iat:g,exp:w,sid:c},u,d,j,N,P,h):void 0,I=E?await Bm({ctx:e,opts:t,user:a,client:r,scopes:S,grantType:o,sessionId:c,resources:n.resources,referenceId:s,metadata:O,perRequestClaims:n.accessTokenClaims,resourcePolicyClaims:b.resourceCustomClaims}):void 0,[L,R]=await Promise.all([E?Yh(e,t,a,r,x,S,{iat:g,exp:C,sid:c,referenceId:s,signingAlgorithm:b.signingAlgorithm,signingKeyId:b.signingKeyId,accessTokenClaims:I,confirmation:N}):$h(e,t,a,r,S,{iat:g,exp:C,sid:c},n?.resources,s,n.authorizationCodeId,F?.id,N,P),F||(T&&a?ng(e,t,a,s,n.authorizationCodeId,r,S,{iat:g,exp:w,sid:c},u,d,j,N,P,h):void 0)]),ee=D?await Zh(e,t,a,r,S,l,c,d,L,k,h):void 0,te={...A,...n.tokenResponse??{},access_token:L,expires_in:C-g,expires_at:C,token_type:Gh(N),refresh_token:R?.token,scope:S.join(` `),id_token:ee};if(u?.id&&R?.id)try{await bg(e,t,u,hg({effectiveScopes:S,requestedResources:n.resources,confirmation:N}),te)}catch(t){e.context.logger.error(`failed to store refresh token rotation replay`,t)}return e.json(te)}async function Tg(e,t,n,r,i,a){let o=await ql(t.storeTokens,n,`authorization_code`),s=await e.context.internalAdapter.consumeVerificationValue(o);if(!s)throw await tg(e,o),new M(`BAD_REQUEST`,{error_description:`invalid code`,error:`invalid_grant`});let c;try{c=JSON.parse(s.value)}catch{throw new M(`BAD_REQUEST`,{error_description:`malformed verification value`,error:`invalid_grant`})}let l=Xm.safeParse(c);if(!l.success)throw new M(`BAD_REQUEST`,{error_description:`malformed verification value`,error:`invalid_grant`});let u=l.data;if(u.query.client_id!==r)throw new M(`BAD_REQUEST`,{error_description:`invalid client_id`,error:`invalid_grant`});let d=u.query.redirect_uri;if(d){if(!i)throw new M(`BAD_REQUEST`,{error_description:`redirect_uri is required`,error:`invalid_request`});if(d!==i)throw new M(`BAD_REQUEST`,{error_description:`redirect_uri mismatch`,error:`invalid_grant`})}else if(i)throw new M(`BAD_REQUEST`,{error_description:`redirect_uri mismatch`,error:`invalid_grant`});let f=Fl(u.resource)??Fl(u.query.resource),p=a??f;if(a&&f){let e=new Set(a),t=new Set(f);for(let n of e)if(!t.has(n))throw new M(`BAD_REQUEST`,{error_description:`requested resource not authorized`,error:`invalid_target`})}return{verificationValue:u,effectiveResources:p,authorizedResources:f,authorizationCodeId:o}}async function Eg(e,t){let{clientId:n,clientSecret:r,preVerified:i,authMethod:a}=fu(await pu(e,t,`${e.context.baseURL}/oauth2/token`)),{code:o,code_verifier:s,redirect_uri:c,resource:l}=e.body,u=Fl(l);if(!n)throw new M(`BAD_REQUEST`,{error_description:`client_id is required`,error:`invalid_request`});if(!o)throw new M(`BAD_REQUEST`,{error_description:`code is required`,error:`invalid_request`});let d=n&&r,f=n&&o&&s;if(!d&&!f&&!i)throw new M(`BAD_REQUEST`,{error_description:`Either code_verifier or client_secret is required`,error:`invalid_request`});let p=await uu(e,t,n,r,void 0,i,`authorization_code`,a),{verificationValue:m,effectiveResources:h,authorizedResources:g,authorizationCodeId:_}=await Tg(e,t,o,n,c,u),v=m.query.scope?.split(` `);if(!v)throw new M(`INTERNAL_SERVER_ERROR`,{error_description:`verification scope unset`,error:`invalid_scope`});if(cu(p,v),Tu(p,{scopes:(m.query?.scope)?.split(` `)||[],nonce:m.query?.nonce})){if(!f)throw new M(`BAD_REQUEST`,{error_description:`PKCE is required for this client`,error:`invalid_request`})}else if(!(f||d||i))throw new M(`BAD_REQUEST`,{error_description:`Either PKCE (code_verifier) or client authentication (client_secret or client_assertion) is required`,error:`invalid_request`});let y=!!m.query?.code_challenge,b=!!s;if(y||b){if(y&&!b)throw new M(`BAD_REQUEST`,{error_description:`code_verifier required because PKCE was used in authorization`,error:`invalid_request`});if(!y&&b)throw new M(`BAD_REQUEST`,{error_description:`code_verifier provided but PKCE was not used in authorization`,error:`invalid_request`});if((m.query?.code_challenge_method===`S256`?await ms(s):void 0)!==m.query?.code_challenge)throw new M(`BAD_REQUEST`,{error_description:`code verification failed`,error:`invalid_grant`})}if(!m.userId)throw new M(`BAD_REQUEST`,{error_description:`missing user, user may have been deleted`,error:`invalid_user`});let x=await e.context.internalAdapter.findUserById(m.userId);if(!x)throw new M(`BAD_REQUEST`,{error_description:`missing user, user may have been deleted`,error:`invalid_user`});let S=await e.context.adapter.findOne({model:`session`,where:[{field:`id`,value:m.sessionId}]});if(!S||S.expiresAt<new Date)throw new M(`BAD_REQUEST`,{error_description:`session no longer exists`,error:`invalid_request`});let C=m.authTime==null?Pl(S):Nl(m.authTime),w=Tm(m.query.claims,Lm(t));return wg(e,t,{client:p,scopes:m.query.scope?.split(` `)??[],user:x,grantType:`authorization_code`,referenceId:m.referenceId,sessionId:S.id,nonce:m.query?.nonce,authTime:C,acr:m.acr,amr:m.amr,verificationValue:m,authorizationCodeId:_,requestedUserInfoClaims:w,resources:h,originalResources:g})}async function Dg(e,t){let{clientId:n,clientSecret:r,preVerified:i,authMethod:a}=fu(await pu(e,t,`${e.context.baseURL}/oauth2/token`)),{scope:o,resource:s}=e.body,c=Fl(s);if(!n)throw new M(`BAD_REQUEST`,{error_description:`Missing required client_id`,error:`invalid_request`});let l=await uu(e,t,n,r,void 0,i,`client_credentials`,a);if(l.tokenEndpointAuthMethod===`none`)throw new M(`BAD_REQUEST`,{error_description:`public clients cannot use the client_credentials grant`,error:`unauthorized_client`});let u=l.clientCredentialsScopes;if(!u?.length)throw new M(`BAD_REQUEST`,{error_description:`client has no authorized client_credentials scopes`,error:`unauthorized_client`});let d=o?.split(` `);if(d){let e=new Set(u),t=d.filter(t=>!e.has(t)||kh(t));if(t.length)throw new M(`BAD_REQUEST`,{error_description:`The following scopes are invalid: ${t.join(`, `)}`,error:`invalid_scope`})}return d||=[...u],wg(e,t,{client:l,scopes:d,grantType:`client_credentials`,resources:c})}async function Og(e,t){let{clientId:n,clientSecret:r,preVerified:i,authMethod:a}=fu(await pu(e,t,`${e.context.baseURL}/oauth2/token`)),{refresh_token:o,scope:s,resource:c}=e.body,l=Fl(c);if(!n)throw new M(`BAD_REQUEST`,{error_description:`Missing required client_id`,error:`invalid_request`});if(!o)throw new M(`BAD_REQUEST`,{error_description:`Missing a required refresh_token for refresh_token grant`,error:`invalid_request`});let u=await uu(e,t,n,r,void 0,i,`refresh_token`,a),d=await Ih(e,t,o);if(!d)throw new M(`BAD_REQUEST`,{error_description:`session not found`,error:`invalid_grant`});if(d.clientId!==n||d.expiresAt<new Date)throw new M(`BAD_REQUEST`,{error_description:`invalid refresh token`,error:`invalid_grant`});if(l&&d.resources&&!l.every(e=>d.resources?.includes(e)))throw new M(`BAD_REQUEST`,{error_description:`requested resource invalid`,error:`invalid_target`});let f=d?.scopes,p=s?.split(` `);if(p){let e=new Set(f);for(let t of p)if(!e.has(t))throw new M(`BAD_REQUEST`,{error_description:`unable to issue scope ${t}`,error:`invalid_scope`})}if(cu(u,p??f),d.revoked){if(yg(d)){let n=await xg(e,d,await Sg(e,t,{client:u,refreshToken:d,scopes:p??f,resources:l??d.resources}));if(n)return Cg(e,n);throw new M(`BAD_REQUEST`,{error_description:`invalid refresh token`,error:`invalid_grant`})}throw await eg(e,n,d.userId),new M(`BAD_REQUEST`,{error_description:`invalid refresh token`,error:`invalid_grant`})}let m=await e.context.internalAdapter.findUserById(d.userId);if(!m)throw new M(`BAD_REQUEST`,{error_description:`user not found`,error:`invalid_request`});let h=d.authTime==null?void 0:Nl(d.authTime);return wg(e,t,{client:u,scopes:p??f,user:m,grantType:`refresh_token`,referenceId:d.referenceId,authorizationCodeId:d.authorizationCodeId,sessionId:d.sessionId,refreshToken:d,resources:l??d.resources,authTime:h,acr:d.acr??void 0,amr:d.amr??void 0,requestedUserInfoClaims:d.requestedUserInfoClaims})}var kg=De({introspectEndpoint:()=>Gg,requireActiveAccessToken:()=>Hg,requireActiveAccessTokenWithClaims:()=>Ug,validateAccessToken:()=>Vg}),Ag=`Invalid access token`,jg=`Bearer error="invalid_token", error_description="${Ag}"`;function Mg(){return{payload:{active:!1},requestedUserInfoClaims:[]}}function Ng(e,t){return e==null?[]:(Array.isArray(e)?e:[e]).filter(e=>typeof e==`string`&&e!==t)}async function Pg(e,t,n){let{introspectingClientId:r,issuerClientId:i,audienceResources:a}=n;return!r||r===i||a.length!==0&&lh(e,t,r,a)}async function Fg(e,t,n,r){let i=ih(e.context.baseURL??``),a=n.aud;if(!await oh(e,t,a,[i]))return{active:!1};let o=await Vl(e,t,n.azp);if(!o||o?.disabled||!await Pg(e,t,{introspectingClientId:r,issuerClientId:n.azp,audienceResources:Ng(a,i)}))return{active:!1};let s=n.sid;if(s){let t=await e.context.adapter.findOne({model:`session`,where:[{field:`id`,value:s}]});if(!t||t.expiresAt<new Date)return{active:!1}}return n.client_id=n.azp,n.active=!0,n.token_type=Gh(n.cnf),n}async function Ig(e,t,n,r){if(!n.expiresAt||n.expiresAt<new Date||n.revoked)return Mg();let i=Array.isArray(n.resources)?n.resources:void 0,a;if(n.clientId&&(a=await Vl(e,t,n.clientId),!a||a?.disabled||!await Pg(e,t,{introspectingClientId:r,issuerClientId:n.clientId,audienceResources:i??[]})))return Mg();let o=n.sessionId??void 0;if(o){let t=await e.context.adapter.findOne({model:`session`,where:[{field:`id`,value:o}]});if(!t||t.expiresAt<new Date)return Mg()}let s;n.userId&&(s=await e.context.internalAdapter.findUserById(n?.userId));let c=`${e.context.baseURL}/oauth2/userinfo`;if(i?.length&&!await oh(e,t,i,[c]))return Mg();let l=i?[...i]:void 0;l?.length&&n.scopes?.includes(`openid`)&&(l.includes(c)||l.push(c));let u=i?.length?await uh(e,t,i):{},d=a?await Bm({ctx:e,opts:t,user:s,client:a,scopes:n.scopes??[],grantType:void 0,sessionId:void 0,resources:i,referenceId:n.referenceId,metadata:du(a.metadata),perRequestClaims:void 0,resourcePolicyClaims:u}):{},f=(t.disableJwtPlugin?void 0:Ml(e.context))?.options;return{payload:{...d,active:!0,iss:f?.jwt?.issuer??e.context.baseURL,aud:Il(l),client_id:n.clientId,azp:n.clientId,sub:s?.id,sid:o,reference_id:n.referenceId??void 0,exp:Math.floor(new Date(n.expiresAt).getTime()/1e3),iat:Math.floor(new Date(n.createdAt).getTime()/1e3),scope:n.scopes?.join(` `),token_type:Gh(n.confirmation),...n.confirmation?{cnf:n.confirmation}:{}},requestedUserInfoClaims:n.requestedUserInfoClaims??[]}}async function Lg(e,t,n,r){if(!n.clientId||n.clientId!==r||!n.expiresAt||n.expiresAt<new Date||n.revoked)return{active:!1};let i=n.sessionId??void 0;if(i){let t=await e.context.adapter.findOne({model:`session`,where:[{field:`id`,value:i}]});(!t||t.expiresAt<new Date)&&(i=void 0)}let a;return n.userId&&(a=await e.context.internalAdapter.findUserById(n?.userId)??void 0),{active:!0,client_id:r,iss:((t.disableJwtPlugin?void 0:Ml(e.context))?.options)?.jwt?.issuer??e.context.baseURL,sub:a?.id,sid:i,reference_id:n.referenceId??void 0,exp:Math.floor(new Date(n.expiresAt).getTime()/1e3),iat:Math.floor(new Date(n.createdAt).getTime()/1e3),scope:n.scopes?.join(` `),token_type:Gh(n.confirmation),...n.confirmation?{cnf:n.confirmation}:{}}}function Rg(){return new g(`UNAUTHORIZED`,{error_description:Ag,error:`invalid_token`},{"WWW-Authenticate":jg})}async function zg(e,t,n,r){return n.type===`opaque`?Ig(e,t,n.record,r):{payload:await Fg(e,t,n.payload,r),requestedUserInfoClaims:[]}}async function Bg(e,t,n,r){let i=await Rh(e,t,n);return i?zg(e,t,i,r):Mg()}async function Vg(e,t,n,r){return(await Bg(e,t,n,r)).payload}async function Hg(e,t,n,r){let i=await Vg(e,t,n,r);if(i.active)return i;throw Rg()}async function Ug(e,t,n,r){let{payload:i,requestedUserInfoClaims:a}=await Bg(e,t,n,r);if(i.active)return{payload:i,requestedUserInfoClaims:a};throw Rg()}async function Wg(e,t,n,r){if(!n.active||!n.sub)return n;let i=n.client_id??n.azp;if(!i)return n;let a=i===r.clientId?r:await Vl(e,t,i);if(!a)return n;let o=await vu(n.sub,a,t);return{...n,sub:o}}async function Gg(e,t){let{token:n,token_type_hint:r}=e.body,{clientId:i,clientSecret:a,preVerified:o,authMethod:s}=fu(await pu(e,t,`${e.context.baseURL}/oauth2/introspect`));if(!i||!a&&!o)throw new g(`UNAUTHORIZED`,{error_description:`missing required credentials`,error:`invalid_client`});if(n&&typeof n==`string`&&(n=gc(n)),!n?.length)throw new g(`BAD_REQUEST`,{error_description:`missing a required token for introspection`,error:`invalid_request`});let c=await uu(e,t,i,a,void 0,o,void 0,s);try{let i=await zh(e,t,n,r);if(!i)return{active:!1};if(i.type===`refresh`)return Wg(e,t,await Lg(e,t,i.record,c.clientId),c);let{payload:a}=await zg(e,t,i,c.clientId);return Wg(e,t,a,c)}catch(e){throw e instanceof g?e:(ve.error(`Introspection error:`,e),new g(`INTERNAL_SERVER_ERROR`))}}var Kg=`1.8.0-beta.2`;function qg(e){return e?.get(`sec-fetch-mode`)===`cors`}var Jg=e({a:()=>ay,c:()=>Bv,d:()=>Y_,f:()=>ev,g:()=>Q_,i:()=>Nb,l:()=>_v,n:()=>Eb,o:()=>by,p:()=>Z_,r:()=>kb,s:()=>xv,t:()=>Gb,u:()=>tv});async function Yg(e,t,n){let r=await Ob.get(),i=r?.query;if(!i)throw new M(`BAD_REQUEST`,{error_description:`missing oauth query`,error:`invalid_request`});let a=new URLSearchParams(i),o=a.get(`scope`)?.split(` `).filter(e=>e)??[],s=Lm(t),c=Tm(a.get(`claims`),s),l=a.get(`client_id`);if(!l)throw new M(`BAD_REQUEST`,{error_description:`client_id is required`,error:`invalid_client`});let u=e.body.scope?.split(` `).filter(e=>e);if(u&&!u.every(e=>o?.includes(e)))throw new M(`BAD_REQUEST`,{error_description:`Scope not originally requested`,error:`invalid_request`});let d=e.body.claims,f=d===void 0?c:Tm(d,s);if(d!==void 0&&!f.every(e=>c.includes(e)))throw new M(`BAD_REQUEST`,{error_description:`Claim not originally requested`,error:`invalid_request`});let p=await Z(e);if(e.body.accept!==!0){let n=ml(t,xu(a));return n?{redirect:!0,url:await n.handler.deny({ctx:e,value:n.value,userId:p?.user.id}).catch(t=>Ub(e,t,n.handler.errorPage?.({ctx:e,value:n.value})))}:{redirect:!0,url:Ib(a.get(`redirect_uri`)??``,`access_denied`,`User denied access`,a.get(`state`)??void 0,Gb(e,t))}}let m=e.body.reference_id;if(m!==void 0&&!t.postLogin?.consentReferenceId)throw new M(`BAD_REQUEST`,{error_description:`reference_id requires postLogin.consentReferenceId`,error:`invalid_request`});let h=mu(a.get(`prompt`)??``).has(`login`),g=h&&Su(p?.session.createdAt,r?.signedQueryIssuedAt);if(h&&!g)return e?.headers?.set(`accept`,`application/json`),e.query=xu(a),await n(e);let _=await yu(t,{user:p?.user,session:p?.session,scopes:u??o,query:new URLSearchParams(a),consent:{referenceId:m}}),v=await bu(e,l,p?.user.id,_),y=Math.floor(Date.now()/1e3),b=a.getAll(`resource`),x={clientId:l,userId:p?.user.id,scopes:u??o,requestedUserInfoClaims:f,createdAt:new Date(y*1e3),updatedAt:new Date(y*1e3),resources:b.length?b:void 0,referenceId:_};if(v?.id?await e.context.adapter.update({model:`oauthConsent`,where:[{field:`id`,value:v.id}],update:{resources:x.resources,scopes:x.scopes,requestedUserInfoClaims:x.requestedUserInfoClaims,updatedAt:new Date(y*1e3)}}):await e.context.adapter.create({model:`oauthConsent`,data:{...x,scopes:x.scopes}}),u&&a.set(`scope`,x.scopes.join(` `)),d!==void 0){let e=Om(a.get(`claims`),f);e?a.set(`claims`,JSON.stringify(e)):a.delete(`claims`)}e?.headers?.set(`accept`,`application/json`);let S=Cu(a,`consent`);return g&&(S=Cu(S,`login`),S=wu(S)),e.query=xu(S),await n(e,{postLogin:r?.postLoginClearedForSession!==void 0&&r.postLoginClearedForSession===p?.session.id,acceptedConsent:{referenceId:_}})}async function Xg(e,t){if(e.body.selected===!0)return await Zg(e,t);if(e.body.created===!0)return await Qg(e,t);if(e.body.postLogin===!0)return await $g(e,t);throw new M(`BAD_REQUEST`,{error_description:`Missing parameters`,error:`invalid_request`})}async function Zg(e,t){let n=(await Ob.get())?.query;if(!n)throw new M(`BAD_REQUEST`,{error_description:`missing oauth query`,error:`invalid_request`});return e.headers?.set(`accept`,`application/json`),e.query=xu(Cu(new URLSearchParams(n),`select_account`)),await t(e)}async function Qg(e,t){let n=(await Ob.get())?.query;if(!n)throw new M(`BAD_REQUEST`,{error_description:`missing oauth query`,error:`invalid_request`});let r=new URLSearchParams(n);return e.headers?.set(`accept`,`application/json`),e.query=xu(Cu(r,`create`)),await t(e)}async function $g(e,t){let n=await Ob.get(),r=n?.query;if(!r)throw new M(`BAD_REQUEST`,{error_description:`missing oauth query`,error:`invalid_request`});let i=new URLSearchParams(r);e.headers?.set(`accept`,`application/json`),e.query=xu(i);let a=await Z(e);return await t(e,{postLogin:n?.postLoginClearedForSession!==void 0&&n.postLoginClearedForSession===a?.session.id,isPostLoginContinuation:!0})}var e_=`http://schemas.openid.net/event/backchannel-logout`,t_=`logout+jwt`,n_=120,r_=5e3,i_=3e3;async function a_(e,t,n,r){return pm(e,{options:t,payload:{...r,events:{[e_]:{}}},header:{typ:t_},resolvedKey:n??void 0})}async function o_(e,t,n){let{sessionId:r,userId:i}=n;if(!i)return null;let a=e.context.logger;try{let n=await Vd(e.context.adapter),o=[{field:`sessionId`,value:r}],[s,c]=await Promise.all([n.findMany({model:`oauthAccessToken`,where:o}),n.findMany({model:`oauthRefreshToken`,where:o})]),l=new Set;for(let e of s)l.add(e.clientId);for(let e of c)l.add(e.clientId);if(l.size===0)return null;let u=await n.findMany({model:`oauthClient`,where:[{field:`clientId`,operator:`in`,value:Array.from(l)}]}),d=s.filter(e=>!e.revoked).map(e=>e.id),f=c.filter(e=>!e.revoked&&!e.scopes?.includes(`offline_access`)).map(e=>e.id),p=t.disableJwtPlugin?[]:u.filter(e=>!!e.backchannelLogoutUri&&!e.disabled),m=(await Promise.all(p.map(async e=>{try{return{client:e,sub:await vu(i,e,t)}}catch(t){return a.warn(`back-channel logout: unable to resolve subject for client ${e.clientId}`,t),null}}))).filter(e=>e!==null),h=Gb(e,t);return{accessTokenIds:d,refreshTokenIds:f,sessionId:r,backchannelTargets:m,frontchannelLogoutUris:u.flatMap(e=>{if(!e.frontchannelLogoutUri||e.disabled)return[];try{let t=new URL(e.frontchannelLogoutUri);return t.searchParams.set(`iss`,h),t.searchParams.set(`sid`,r),[t.toString()]}catch(t){return a.warn(`front-channel logout: invalid frontchannel_logout_uri for client ${e.clientId}`,t),[]}})}}catch(e){return a.error(`logout planning failed`,e),null}}async function s_(e,t){let n=new Date,r=await Vd(e.context.adapter),i=await Promise.allSettled([t.accessTokenIds.length>0?r.updateMany({model:`oauthAccessToken`,where:[{field:`id`,operator:`in`,value:t.accessTokenIds}],update:{revoked:n}}):Promise.resolve(),t.refreshTokenIds.length>0?r.updateMany({model:`oauthRefreshToken`,where:[{field:`id`,operator:`in`,value:t.refreshTokenIds}],update:{revoked:n}}):Promise.resolve()]);for(let t of i)t.status===`rejected`&&e.context.logger.error(`back-channel logout: token revocation update failed`,t.reason);t.backchannelTargets.length>0&&await c_(e,t)}async function c_(e,t){let n=e.context.logger,r=Ml(e.context)?.options,i=r?.jwt?.issuer??e.context.baseURL,a=Math.floor(Date.now()/1e3),o=a+n_,s=r?.jwt?.sign?null:await fm(e,r);await Promise.allSettled(t.backchannelTargets.map(async({client:c,sub:l})=>{try{let u=zi(32,`a-z`,`A-Z`,`0-9`),d=await a_(e,r,s,{iss:i,aud:c.clientId,sub:l,sid:t.sessionId,iat:a,exp:o,jti:u}),f=await fetch(c.backchannelLogoutUri,{method:`POST`,headers:{"Content-Type":`application/x-www-form-urlencoded`,Accept:`application/json`},body:new URLSearchParams({logout_token:d}),signal:AbortSignal.timeout(r_),redirect:`error`});f.status!==200&&f.status!==204&&n.warn(`back-channel logout to client ${c.clientId} returned ${f.status}`)}catch(e){n.warn(`back-channel logout to client ${c.clientId} failed`,e)}}))}var l_=zd(()=>[]);async function u_(e){if(e.length===0||!await Id())return;let t=await l_.get();await l_.set([...t,...e])}async function d_(){let e=await l_.get();return await l_.set([]),e}var f_=300,p_=`.oauth_logout_confirmation`;function m_(e){return e.replace(/[&<>"']/g,e=>{switch(e){case`&`:return`&`;case`<`:return`<`;case`>`:return`>`;case`"`:return`"`;case`'`:return`'`;default:return e}})}function h_(e){let t=e.request?.headers??e.headers;if(!t||qg(t))return!1;let n=t.get(`accept`)??``;return t.get(`sec-fetch-mode`)===`navigate`||n.includes(`text/html`)||n.includes(`application/xhtml+xml`)}var g_=`default-src 'none'; form-action 'self'; base-uri 'none'; frame-ancestors 'none'`;function __(e,t,n=200,r={}){return new Response(`<!doctype html><html><head><meta charset="utf-8"><title>${m_(e)}</title>${r.head??``}</head><body>${t}</body></html>`,{status:n,headers:{"cache-control":`no-store`,"content-security-policy":r.contentSecurityPolicy??g_,"content-type":`text/html; charset=utf-8`,pragma:`no-cache`,"referrer-policy":`no-referrer`,"x-content-type-options":`nosniff`}})}function v_(e){return`${e.context.baseURL.replace(/\/$/,``)}/oauth2/end-session/confirm`}function y_(e){try{return new URL(v_(e)).pathname}catch{return`/oauth2/end-session/confirm`}}function b_(e){return __(`Confirm logout`,`<main><h1>Confirm logout</h1><p>Do you want to log out of this account?</p><form method="post" data-oidc-logout-confirmation action="${m_(v_(e))}"><button type="submit" name="action" value="confirm">Confirm logout</button></form></main>`)}function x_(e){return __(`Logged out`,`<main><p data-oidc-logout-state="logged-out">${e?`Logged out. ${m_(e)}`:`Logged out.`}</p></main>`)}var S_=`(function () {
|
|
31
|
-
var status = document.querySelector("[data-oidc-logout-state]");
|
|
32
|
-
var redirectUri = status.getAttribute("data-post-logout-redirect-uri");
|
|
33
|
-
var frames = document.querySelectorAll("iframe");
|
|
34
|
-
var pending = frames.length;
|
|
35
|
-
var finished = false;
|
|
36
|
-
function finish() {
|
|
37
|
-
if (finished) return;
|
|
38
|
-
finished = true;
|
|
39
|
-
if (redirectUri) {
|
|
40
|
-
window.location.replace(redirectUri);
|
|
41
|
-
return;
|
|
42
|
-
}
|
|
43
|
-
status.setAttribute("data-oidc-logout-state", "logged-out");
|
|
44
|
-
status.textContent = status.getAttribute("data-logged-out-message");
|
|
45
|
-
}
|
|
46
|
-
function settle() {
|
|
47
|
-
pending -= 1;
|
|
48
|
-
if (pending <= 0) finish();
|
|
49
|
-
}
|
|
50
|
-
for (var i = 0; i < frames.length; i++) {
|
|
51
|
-
frames[i].addEventListener("load", settle);
|
|
52
|
-
frames[i].addEventListener("error", settle);
|
|
53
|
-
}
|
|
54
|
-
setTimeout(finish, ${i_});
|
|
55
|
-
})();`,C_;async function w_(e,t){C_??=Vi(`SHA-256`,`base64`).digest(S_);let n=await C_,r=[...new Set(e.map(e=>new URL(e).origin))],i=t.note?`Logged out. ${t.note}`:`Logged out.`,a=e.map(e=>`<iframe hidden src="${m_(e)}"></iframe>`).join(``),o=t.uri?` data-post-logout-redirect-uri="${m_(t.uri)}"`:``,s=t.uri?`<noscript><a href="${m_(t.uri)}">Continue</a></noscript>`:`<noscript><p>${m_(i)}</p></noscript>`;return __(`Signing out`,`<main><p data-oidc-logout-state="pending" data-logged-out-message="${m_(i)}"${o}>Signing out of connected applications…</p>${s}</main>${a}<script>${S_}<\/script>`,200,{head:t.uri?`<noscript><meta http-equiv="refresh" content="${Math.ceil(i_/1e3)};url=${m_(t.uri)}"></noscript>`:void 0,contentSecurityPolicy:`${g_}; frame-src ${r.join(` `)}; script-src 'sha256-${n}'`})}function T_(e,t){return __(`Logout error`,`<main><h1>Logout error</h1><p data-oidc-logout-state="error">${m_(e)}</p></main>`,t)}function E_(e,t,n,r){if(h_(e))return T_(r,t===`BAD_REQUEST`?400:t===`UNAUTHORIZED`?401:500);throw new g(t,{error:n,error_description:r})}function D_(e){return`${e.context.authCookies.sessionToken.name}${p_}`}function O_(e,t){return{...e.context.authCookies.sessionToken.attributes,httpOnly:!0,maxAge:t,path:y_(e),sameSite:`lax`}}async function k_(e,t,n={}){let r={...t?{sessionId:t}:{},...n,expiresAt:Date.now()+f_*1e3};await e.setSignedCookie(D_(e),JSON.stringify(r),e.context.secret,O_(e,f_))}async function A_(e){let t=await e.getSignedCookie(D_(e),e.context.secret);if(typeof t!=`string`)return null;try{let e=JSON.parse(t);if(typeof e!=`object`||!e)return null;let n=e;return n.sessionId!==void 0&&(typeof n.sessionId!=`string`||n.sessionId.length===0)||n.clientId!==void 0&&(typeof n.clientId!=`string`||n.clientId.length===0)||n.postLogoutRedirectUri!==void 0&&(typeof n.postLogoutRedirectUri!=`string`||n.postLogoutRedirectUri.length===0)||n.state!==void 0&&typeof n.state!=`string`||n.redirectInvalid!==void 0&&typeof n.redirectInvalid!=`boolean`||n.postLogoutRedirectUri!==void 0&&n.clientId===void 0||typeof n.expiresAt!=`number`||!Number.isFinite(n.expiresAt)?null:{...typeof n.sessionId==`string`?{sessionId:n.sessionId}:{},...typeof n.clientId==`string`?{clientId:n.clientId}:{},...typeof n.postLogoutRedirectUri==`string`?{postLogoutRedirectUri:n.postLogoutRedirectUri}:{},...typeof n.state==`string`?{state:n.state}:{},...typeof n.redirectInvalid==`boolean`?{redirectInvalid:n.redirectInvalid}:{},expiresAt:n.expiresAt}}catch{return null}}function j_(e){e.setCookie(D_(e),``,O_(e,0))}async function M_(e){let t=await e.getSignedCookie(e.context.authCookies.sessionToken.name,e.context.secret);if(typeof t!=`string`||t.length===0)return null;try{let n=await e.context.internalAdapter.findSession(t);return n?{session:n.session}:null}catch(t){throw e.context.logger.error(`Failed to read the current logout session`,t),new g(`INTERNAL_SERVER_ERROR`,{error:`server_error`,error_description:`Unable to read the current session`})}}async function N_(e,t){try{return await e.context.adapter.findOne({model:`session`,where:[{field:`id`,value:t}]})}catch(t){throw e.context.logger.error(`Failed to read the hinted logout session`,t),new g(`INTERNAL_SERVER_ERROR`,{error:`server_error`,error_description:`Unable to read the hinted session`})}}async function P_(e,t){if(typeof t.token!=`string`||t.token.length===0)throw new g(`INTERNAL_SERVER_ERROR`,{error:`server_error`,error_description:`Unable to complete logout`});try{await e.context.internalAdapter.deleteSession(t.token)}catch(t){throw e.context.logger.error(`Failed to delete the logout session`,t),new g(`INTERNAL_SERVER_ERROR`,{error:`server_error`,error_description:`Unable to complete logout`})}}async function F_(e,t,n){try{return await Vl(e,t,n)}catch(t){throw e.context.logger.error(`Failed to resolve the logout client`,t),new g(`INTERNAL_SERVER_ERROR`,{error:`server_error`,error_description:`Unable to resolve the logout client`})}}function I_(e){return(Array.isArray(e)?e:[e]).filter(e=>typeof e==`string`)}function L_(e){if(typeof e.aud==`string`&&e.aud.length>0)return e.aud;if(typeof e.azp==`string`&&e.azp.length>0)return e.azp;let t=I_(e.aud);return t.length===1?t[0]:null}async function R_(e,t,n,r){if(r)return F_(e,t,r);let i;try{i=Ci(n)}catch{return null}let a=L_(i);return a?F_(e,t,a):null}async function z_(e,t,n,r){try{let i;if(t.disableJwtPlugin){if(!r.clientSecret)return null;let a=await Wl(e,t.storeClientSecret,r.clientSecret),{payload:o}=await wr(n,new TextEncoder().encode(a));i=JSON.parse(new TextDecoder().decode(o))}else{let t=Ml(e.context).options,{payload:r}=await wr(n,yi(await Hc(n,{jwksFetch:t?.jwks?.remoteUrl??`${e.context.baseURL}${t?.jwks?.jwksPath??`/jwks`}`})));i=JSON.parse(new TextDecoder().decode(r))}return i.iss!==Gb(e,t)||!I_(i.aud).includes(r.clientId)||typeof i.sid!=`string`||i.sid.length===0||typeof i.sub!=`string`||i.sub.length===0?null:i}catch{return null}}function B_(e,t,n){if(!t)return{invalid:!1};if(!e.postLogoutRedirectUris?.includes(t))return{invalid:!0};if(!n)return{uri:t,invalid:!1};try{let e=new URL(t);return e.searchParams.set(`state`,n),{uri:e.toString(),invalid:!1}}catch{return{invalid:!0}}}function V_(e,t){return t.post_logout_redirect_uri?B_(e,t.post_logout_redirect_uri,t.state).invalid?{redirectInvalid:!0}:{clientId:e.clientId,postLogoutRedirectUri:t.post_logout_redirect_uri,...t.state===void 0?{}:{state:t.state}}:{}}async function H_(e,t,n){if(n.redirectInvalid)return{invalid:!0};if(!n.clientId||!n.postLogoutRedirectUri)return{invalid:!1};let r=await F_(e,t,n.clientId);return!r||r.disabled||!r.enableEndSession?{invalid:!0}:B_(r,n.postLogoutRedirectUri,n.state)}async function U_(e,t,n={}){return t?h_(e)?(await k_(e,t.session.id,n),b_(e)):E_(e,`BAD_REQUEST`,`invalid_request`,`User confirmation is required to complete logout`):h_(e)?(await k_(e,void 0,n),b_(e)):E_(e,`BAD_REQUEST`,`invalid_request`,`No active session is available for logout`)}var W_=`The requested post-logout redirect was not registered.`;async function G_(e,t){let n=t.invalid?W_:void 0,r=await d_();return r.length>0&&h_(e)?w_(r,{uri:t.uri,note:n}):t.uri?$(e,t.uri):h_(e)?x_(n):null}async function K_(e,t){let n=await A_(e),r=await M_(e);if(!n||n.expiresAt<=Date.now())return E_(e,`BAD_REQUEST`,`invalid_request`,`The logout confirmation is invalid or expired`);let i=await H_(e,t,n);return r?n.sessionId&&n.sessionId!==r.session.id?E_(e,`BAD_REQUEST`,`invalid_request`,`The logout confirmation is invalid or expired`):(await P_(e,r.session),_p(e),j_(e),G_(e,i)):(j_(e),i.uri?$(e,i.uri):h_(e)?x_(i.invalid?W_:void 0):E_(e,`BAD_REQUEST`,`invalid_request`,`No active session is available for logout`))}async function q_(e,t){let n=e.query??{},r=e.body??{},i={...n,...r},a=await M_(e);if(i.id_token_hint===void 0){let n={};if(i.client_id){let r=await F_(e,t,i.client_id);if(!r)return E_(e,`BAD_REQUEST`,`invalid_client`,`The logout client does not exist`);if(r.disabled)return E_(e,`BAD_REQUEST`,`invalid_client`,`The logout client is disabled`);if(!r.enableEndSession)return E_(e,`UNAUTHORIZED`,`invalid_client`,`The client is not allowed to initiate logout`);n=V_(r,i)}return U_(e,a,n)}let o=await R_(e,t,i.id_token_hint,i.client_id);if(!o)return a&&h_(e)?U_(e,a):E_(e,`BAD_REQUEST`,`invalid_client`,`The logout client does not exist`);if(o.disabled)return E_(e,`BAD_REQUEST`,`invalid_client`,`The logout client is disabled`);if(!o.enableEndSession)return E_(e,`UNAUTHORIZED`,`invalid_client`,`The client is not allowed to initiate logout`);let s=await z_(e,t,i.id_token_hint,o);if(!s)return a&&h_(e)?U_(e,a,i.client_id?V_(o,i):{}):E_(e,`UNAUTHORIZED`,`invalid_token`,`The id_token_hint is invalid`);let c=s.sid,l=await N_(e,c),u=a?.session.id===c;if(a&&!u)return U_(e,a,V_(o,i));let d=B_(o,i.post_logout_redirect_uri,i.state),f=l??(u?a?.session:null);return f&&await P_(e,f),u&&_p(e),j_(e),G_(e,d)}async function J_(e,t){return K_(e,t)}function Y_(e,t,n){let r=e.context.baseURL,i=!n?.jwt_disabled;return{scopes_supported:n?.scopes_supported,issuer:Wb(t?.jwt?.issuer??r),authorization_endpoint:`${r}/oauth2/authorize`,token_endpoint:`${r}/oauth2/token`,jwks_uri:n?.jwt_disabled?void 0:t?.jwks?.remoteUrl??`${r}${t?.jwks?.jwksPath??`/jwks`}`,registration_endpoint:n?.dynamic_client_registration_supported?`${r}/oauth2/register`:void 0,introspection_endpoint:`${r}/oauth2/introspect`,revocation_endpoint:`${r}/oauth2/revoke`,response_types_supported:n?.grant_types_supported&&!n.grant_types_supported.includes(`authorization_code`)?[]:[`code`],response_modes_supported:[`query`],grant_types_supported:n?.grant_types_supported??[`authorization_code`,`client_credentials`,`refresh_token`],token_endpoint_auth_methods_supported:n?.token_endpoint_auth_methods_supported??[...n?.public_client_supported?[`none`]:[],`client_secret_basic`,`client_secret_post`,`private_key_jwt`],token_endpoint_auth_signing_alg_values_supported:[...bs],introspection_endpoint_auth_methods_supported:n?.endpoint_auth_methods_supported??[`client_secret_basic`,`client_secret_post`,`private_key_jwt`],introspection_endpoint_auth_signing_alg_values_supported:[...bs],revocation_endpoint_auth_methods_supported:n?.endpoint_auth_methods_supported??[`client_secret_basic`,`client_secret_post`,`private_key_jwt`],revocation_endpoint_auth_signing_alg_values_supported:[...bs],code_challenge_methods_supported:[`S256`],authorization_response_iss_parameter_supported:!0,dpop_signing_alg_values_supported:n?.dpop_signing_alg_values_supported??[...lc],backchannel_logout_supported:i,backchannel_logout_session_supported:i,frontchannel_logout_supported:!0,frontchannel_logout_session_supported:!0}}function X_(e,t){let n=t.disableJwtPlugin?void 0:Ml(e.context).options,r=ul(t),i=t.allowUnauthenticatedClientRegistration||r.length>0;return{jwtPluginOptions:n,clientDiscoveries:r,authMetadata:Y_(e,n,{scopes_supported:t.advertisedMetadata?.scopes_supported??t.scopes,dynamic_client_registration_supported:t.allowDynamicClientRegistration,public_client_supported:i,grant_types_supported:pl(t),token_endpoint_auth_methods_supported:_l(t,{includeNone:i}),endpoint_auth_methods_supported:_l(t),jwt_disabled:t.disableJwtPlugin,dpop_signing_alg_values_supported:t.dpop?.signingAlgorithms})}}function Z_(e,t){let{clientDiscoveries:n,authMetadata:r}=X_(e,t);return bl(e,t,`oauth-authorization-server`,{...Hl(n),...r})}function Q_(e,t){let n=e.context.baseURL,{jwtPluginOptions:r,clientDiscoveries:i,authMetadata:a}=X_(e,t),o={...a,claims_supported:Lm(t),claims_parameter_supported:!0,userinfo_endpoint:`${n}/oauth2/userinfo`,subject_types_supported:t.pairwiseSecret?[`public`,`pairwise`]:[`public`],acr_values_supported:km(t),id_token_signing_alg_values_supported:(()=>{if(t.disableJwtPlugin)return[`HS256`];let e=r?.jwks?.keyPairConfig?.alg??`EdDSA`,n=r?.jwks?.keyPairConfigs?.map(e=>e.alg)??[];return Array.from(new Set([e,...n]))})(),end_session_endpoint:`${n}/oauth2/end-session`,request_parameter_supported:!1,request_uri_parameter_supported:!1,prompt_values_supported:[`login`,`consent`,`create`,`select_account`,`none`]};return bl(e,t,`openid-configuration`,{...Hl(i),...o})}var $_=`public, max-age=15, stale-while-revalidate=15, stale-if-error=86400`;function ev(e,t){let n=new Headers(t);return n.has(`Cache-Control`)||n.set(`Cache-Control`,$_),n.set(`Content-Type`,`application/json`),new Response(JSON.stringify(e),{status:200,headers:n})}function tv(e,t,n){let{redirectOnError:r,onValidationError:i,errorCodesByField:a,defaultError:o=`invalid_request`,formParams:s,...c}=t;if(!r&&!s){let t=c.metadata?.noStore===!0;return X(e,{...c,onValidationError:async e=>{throw i&&await i(e),new g(`BAD_REQUEST`,nv(e.issues,a,o),t?Iu:void 0)}},n)}let{body:l,query:u,...d}=c;s&&(d.cloneRequest=!0);async function f(e,t,n){if(!n)return{ok:!0};let s=await n.safeParseAsync(e[t]??{});if(s.success)return e[t]=s.data,{ok:!0};i&&await i({message:s.error.message,issues:s.error.issues});let c=nv(s.error.issues,a,o);if(!r)throw new g(`BAD_REQUEST`,c);return{ok:!1,response:r({...c,ctx:e})}}return X(e,d,async e=>{let t=s&&e.request?await eu(e.request):void 0;t&&(e.body=tu(t,e.body??{},s?.repeatable));let r=await f(e,`body`,l);if(!r.ok)return r.response;let i=await f(e,`query`,u);return i.ok?n(e):i.response})}function nv(e,t,n=`invalid_request`){let r=e[0];if(!r)return{error:n,error_description:`Invalid request.`};let i=r.path?.[0],a=typeof i==`string`?i:void 0,o=a?t?.[a]:void 0,s=r.path?.length?ce(r.path):``,c=iv(r);return{error:rv(r,c,o,n),error_description:ov(c??r,s)}}function rv(e,t,n,r){return typeof n==`string`?n:av(e)?n?.missing??r:t?n?.invalid??r:r}function iv(e){if(e.code===`invalid_value`||e.code===`custom`)return e;if(e.code===`invalid_union`)for(let t of e.errors){let e=t.find(e=>e.code===`custom`);if(e)return e}}function av(e){return e.code===`invalid_type`&&e.message.endsWith(`received undefined`)}function ov(e,t){if(!t)return e.message;if(e.code===`invalid_type`)return e.message.endsWith(`received undefined`)?`${t} is required`:e.message.endsWith(`received array`)?`${t} must not appear more than once`:`${t} must be a ${e.expected??`valid value`}`;if(e.code===`invalid_value`){let n=e.values;if(Array.isArray(n)&&n.length>0)return`${t} must be one of: ${n.join(`, `)}`}return`${t}: ${e.message}`}var sv=e=>zu(async t=>{if(!e.allowPublicClientPrelogin)throw new M(`BAD_REQUEST`);let n=t.body.oauth_query;if(!await zl(n,t.context.secret))throw new M(`UNAUTHORIZED`,{error:`invalid_signature`})}),cv={"P-256":`ES256`,"P-384":`ES384`,"P-521":`ES512`},lv=[`Ed25519`],uv=[`d`,`p`,`q`,`dp`,`dq`,`qi`,`oth`];function dv(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function fv(e,t){return typeof e[t]==`string`&&e[t].length>0}function pv(e){return typeof e==`string`&&Object.prototype.hasOwnProperty.call(cv,e)}function mv(e){return lv.some(t=>t===e)}function hv(e){switch(e.kty){case`RSA`:return fv(e,`n`)&&fv(e,`e`);case`EC`:return pv(e.crv)&&fv(e,`x`)&&fv(e,`y`);case`OKP`:return mv(e.crv)&&fv(e,`x`);default:return!1}}function gv(e){if(e.alg===void 0)return!0;if(typeof e.alg!=`string`||!bs.some(t=>t===e.alg))return!1;switch(e.kty){case`RSA`:return e.alg.startsWith(`RS`)||e.alg.startsWith(`PS`);case`EC`:return pv(e.crv)&&cv[e.crv]===e.alg;case`OKP`:return mv(e.crv)&&e.alg===`EdDSA`;default:return!1}}function _v(e){let t=dv(e)&&Array.isArray(e.keys)?e.keys:void 0;if(!t?.length)return{valid:!1,error:`jwks must be an RFC 7517 JWK Set object with a non-empty keys array`};for(let e of t){if(!dv(e))return{valid:!1,error:`jwks keys must be supported public JWKs with required key parameters`};if(e.kty===`oct`||`k`in e||uv.some(t=>t in e))return{valid:!1,error:`jwks must contain only public asymmetric keys`};if(!hv(e))return{valid:!1,error:`jwks keys must be supported public JWKs with required key parameters`};if(!gv(e))return{valid:!1,error:`jwks key alg must be supported for private_key_jwt and compatible with its key type and signing curve`}}return{valid:!0,jwks:{keys:t}}}function vv(e){let t=_v(e);if(!t.valid)throw new M(`BAD_REQUEST`,{error:`invalid_client_metadata`,error_description:t.error})}async function yv(e,t,n,r,i){if(!t)throw new M(`UNAUTHORIZED`);if(!e.headers)throw new M(`BAD_REQUEST`);if(r===`configure-client-credentials-scopes`&&!n.clientPrivileges||n.clientPrivileges&&!await n.clientPrivileges({headers:e.headers,action:r,session:t.session,user:t.user,clientId:i}))throw new M(`UNAUTHORIZED`)}async function bv(e,t,n,r,i){if(!t)throw new M(`UNAUTHORIZED`);if(!e.headers)throw new M(`BAD_REQUEST`);if(n.resourcePrivileges&&!await n.resourcePrivileges({headers:e.headers,action:r,session:t.session,user:t.user,resourceId:i}))throw new M(`UNAUTHORIZED`)}var xv=De({consumeClientAssertion:()=>Bv,isPrivateHostname:()=>Mv,verifyClientAssertion:()=>Vv}),Sv=new WeakMap,Cv=3e5,wv=500,Tv=5e3,Ev=65536,Dv=/^application\/(?:[-\w.]+\+)?json\s*(?:;|$)/i;function Ov(e,t,n,r){if(e.set(t,{jwks:n,fetchedAt:r}),e.size>wv){let t=e.keys().next().value;t!==void 0&&e.delete(t)}}function kv(e){let t=Sv.get(e);if(t)return t;let n=new Map;return Sv.set(e,n),n}function Av(e){return`${e.clientDiscoveryId??`managed`}:${e.jwksUri??``}`}var jv=[...bs];function Mv(e){return!Kp(e)}function Nv(e,t,n){let r=new URL(t);if(r.protocol!==`https:`)throw new g(`BAD_REQUEST`,{error_description:`jwks_uri must use HTTPS`,error:`invalid_client`});if(r.username||r.password)throw new g(`BAD_REQUEST`,{error_description:`jwks_uri must not contain credentials`,error:`invalid_client`});if(t.includes(`#`))throw new g(`BAD_REQUEST`,{error_description:`jwks_uri must not include a fragment component`,error:`invalid_client`});if(Mv(r.hostname))throw new g(`BAD_REQUEST`,{error_description:`jwks_uri must not point to a private or reserved address`,error:`invalid_client`});if(!(n&&r.origin===n)&&!e.context.isTrustedOrigin(r.href))throw new g(`BAD_REQUEST`,{error_description:`client jwks_uri is not trusted`,error:`invalid_client`})}function Pv(e){try{let t=new URL(e);return t.protocol!==`https:`&&t.protocol!==`http:`?void 0:t.origin}catch{return}}async function Fv(e){let t=e.headers.get(`content-length`);if(t!==null&&Number.isFinite(Number(t))&&Number(t)>Ev)throw await e.body?.cancel(),Error(`JWKS response exceeds 64 KiB`);if(!e.body)return``;let n=e.body.getReader(),r=[],i=0;for(;;){let{done:e,value:t}=await n.read();if(e)break;if(i+=t.byteLength,i>Ev)throw await n.cancel(),Error(`JWKS response exceeds 64 KiB`);r.push(t)}let a=new Uint8Array(i),o=0;for(let e of r)a.set(e,o),o+=e.byteLength;return new TextDecoder().decode(a)}async function Iv(e,t=globalThis.fetch){let n=new AbortController,r=setTimeout(()=>n.abort(),Tv);try{let r=await t(e,{signal:n.signal,headers:{accept:`application/json`},redirect:`error`});if(r.redirected)throw Error(`JWKS fetch redirected`);if(r.status!==200)throw Error(`JWKS fetch returned ${r.status}`);let i=r.headers.get(`content-type`);if(!i||!Dv.test(i))throw Error(`JWKS response must use a JSON media type`);let a=await Fv(r),o;try{o=JSON.parse(a)}catch{return{valid:!1}}let s=_v(o);return s.valid?{valid:!0,jwks:s.jwks}:{valid:!1}}finally{clearTimeout(r)}}function Lv(){return new g(`BAD_REQUEST`,{error_description:`failed to fetch client JWKS`,error:`invalid_client`})}async function Rv(e,t,n){if(n.jwks)return JSON.parse(n.jwks);if(!n.jwksUri)throw new g(`BAD_REQUEST`,{error_description:`client has no JWKS configured`,error:`invalid_client`});let r=n.clientDiscoveryId?ul(t).find(e=>e.id===n.clientDiscoveryId):void 0;if(n.clientDiscoveryId&&!r?.fetchClientMetadataResource)throw new g(`BAD_REQUEST`,{error_description:`client discovery does not provide a metadata resource transport`,error:`invalid_client`});Nv(e,n.jwksUri,n.clientDiscoveryId?Pv(n.clientId):void 0);let i=Date.now(),a=Av(n),o=kv(t),s=o.get(a);if(s&&i-s.fetchedAt<Cv)return s.jwks;let c;try{c=await Iv(n.jwksUri,r?.fetchClientMetadataResource)}catch{let e=Cv*2;if(s&&i-s.fetchedAt<e)return s.jwks;throw Lv()}if(!c.valid)throw Lv();return Ov(o,a,c.jwks,i),c.jwks}async function zv(e,t){if(!t.jwksUri)return null;let n=t.clientDiscoveryId?ul(e).find(e=>e.id===t.clientDiscoveryId):void 0;if(t.clientDiscoveryId&&!n?.fetchClientMetadataResource)return null;try{let r=await Iv(t.jwksUri,n?.fetchClientMetadataResource);return r.valid?(Ov(kv(e),Av(t),r.jwks,Date.now()),r.jwks):null}catch{return null}}async function Bv(e,t,n){let{namespace:r,payload:i,expectedAudience:a}=n;if(!(Array.isArray(i.aud)?i.aud:i.aud==null?[]:[i.aud]).includes(a))throw new g(`BAD_REQUEST`,{error_description:`client assertion aud does not match the endpoint`,error:`invalid_client`});let o=t.assertionMaxLifetime??300,s=Math.floor(Date.now()/1e3);if(typeof i.exp!=`number`)throw new g(`BAD_REQUEST`,{error_description:`client assertion must include exp claim`,error:`invalid_client`});if(i.exp<=s)throw new g(`BAD_REQUEST`,{error_description:`client assertion has expired`,error:`invalid_client`});if(i.exp-s>o)throw new g(`BAD_REQUEST`,{error_description:`client assertion exp is too far in the future (max ${o}s)`,error:`invalid_client`});if(typeof i.iat==`number`&&s-i.iat>o)throw new g(`BAD_REQUEST`,{error_description:`client assertion iat is too far in the past (max ${o}s)`,error:`invalid_client`});if(typeof i.jti!=`string`||i.jti.length===0)throw new g(`BAD_REQUEST`,{error_description:`client assertion must include jti claim`,error:`invalid_client`});let c=await Vi(`SHA-256`).digest(new TextEncoder().encode(`${r}:${i.jti}`)),l=me(new Uint8Array(c).slice(0,24),e.context.options);try{await e.context.adapter.create({model:`oauthClientAssertion`,data:{id:l,expiresAt:new Date(i.exp*1e3)},forceAllowId:!0})}catch(t){let n=!1;try{n=!!await e.context.adapter.findOne({model:`oauthClientAssertion`,where:[{field:`id`,value:l}]})}catch{}throw n?new g(`BAD_REQUEST`,{error_description:`client assertion jti has already been used`,error:`invalid_client`}):t}}async function Vv(e,t,n,r,i,a,o){if(r!==`urn:ietf:params:oauth:client-assertion-type:jwt-bearer`)throw new g(`BAD_REQUEST`,{error_description:`unsupported client_assertion_type`,error:`invalid_client`});let s;try{s=Si(n)}catch{throw new g(`BAD_REQUEST`,{error_description:`malformed client assertion: invalid JWT header`,error:`invalid_client`})}if(!s.alg||!jv.includes(s.alg))throw new g(`BAD_REQUEST`,{error_description:`unsupported assertion signing algorithm: ${s.alg}`,error:`invalid_client`});let c;try{c=Ci(n)}catch{throw new g(`BAD_REQUEST`,{error_description:`malformed client assertion: invalid JWT payload`,error:`invalid_client`})}let l=c.sub??c.iss;if(!l)throw new g(`BAD_REQUEST`,{error_description:`client assertion must contain sub or iss claim identifying the client`,error:`invalid_client`});if(i&&i!==l)throw new g(`BAD_REQUEST`,{error_description:`client_id in body does not match assertion sub/iss`,error:`invalid_client`});let u=await Vl(e,t,l);if(!u)throw new g(`BAD_REQUEST`,{error_description:`client not found`,error:`invalid_client`});if(u.disabled)throw new g(`BAD_REQUEST`,{error_description:`client is disabled`,error:`invalid_client`});if(u.tokenEndpointAuthMethod!==`private_key_jwt`)throw new g(`BAD_REQUEST`,{error_description:`client is not registered for private_key_jwt authentication`,error:`invalid_client`});o?.assertClient?.(u);let d=await Rv(e,t,u),f=a??`${e.context.baseURL}/oauth2/token`,p=Gb(e,t),m=o?.endpointAudienceOnly?[f]:[...new Set([f,p])],h={issuer:l,subject:l,audience:m,algorithms:jv},_;try{({payload:_}=await Gr(n,yi(d),h))}catch(e){if(e instanceof Error&&/no matching key|no applicable key/i.test(e.message)){let e=await zv(t,u);if(e)try{({payload:_}=await Gr(n,yi(e),h))}catch{throw new g(`UNAUTHORIZED`,{error_description:`client assertion signature verification failed`,error:`invalid_client`})}else throw new g(`UNAUTHORIZED`,{error_description:`client assertion signature verification failed`,error:`invalid_client`})}else throw new g(`UNAUTHORIZED`,{error_description:`client assertion signature verification failed`,error:`invalid_client`})}let v=(Array.isArray(_.aud)?_.aud:[_.aud]).find(e=>typeof e==`string`&&m.includes(e));return await Bv(e,t,{namespace:`private_key_jwt:${l}`,payload:_,expectedAudience:v}),{clientId:l,client:u}}function Hv(e,t,n){return new g(e,{error:t,error_description:n},{"WWW-Authenticate":`Bearer error="${t}"`,...Iu})}async function Uv(e,t,n){let r=e.headers,i;try{i=kl(r?.get(`authorization`))}catch{throw Hv(`BAD_REQUEST`,`invalid_request`,`Malformed initial access token Authorization header`)}if(!i||!r)return;if(!t.validateInitialAccessToken)throw Hv(`UNAUTHORIZED`,`invalid_token`,`Invalid initial access token`);let a;try{a=await t.validateInitialAccessToken({initialAccessToken:i,headers:r,clientMetadata:n})}catch(e){throw e instanceof g?e:new g(`INTERNAL_SERVER_ERROR`,{error:`server_error`,error_description:`Initial access token validation failed`})}if(!a)throw Hv(`UNAUTHORIZED`,`invalid_token`,`Invalid initial access token`);return a}var Wv=[`authorization_code`];function Gv(e){return[...new Set([...e.clientRegistrationDefaultScopes??e.scopes??[],...e.clientRegistrationAllowedScopes??[]])]}function Kv(e){let t=e.grant_types??[...Wv];if(t.length>0)return t;throw new M(`BAD_REQUEST`,{error:`invalid_client_metadata`,error_description:`grant_types must contain at least one grant type`})}function qv(e,t){return e.response_types?e.response_types:t.includes(`authorization_code`)?[`code`]:void 0}function Jv(e,t){let n=new Set(pl(e)),r=t.filter(e=>n.has(e));if(r.length===0)throw new M(`BAD_REQUEST`,{error:`invalid_client_metadata`,error_description:`no mutually supported grant_type among ${t.join(`, `)}`});return r}function Yv(e,t=`web`){let n=Kv(e);return{...e,token_endpoint_auth_method:e.token_endpoint_auth_method??`client_secret_basic`,application_type:e.application_type??(t===null?void 0:t),grant_types:n,response_types:qv(e,n)}}function Xv(e){let t=new URL(e);return t.protocol!==`http:`&&t.protocol!==`https:`&&t.host!==``}function Zv(e){try{let t=new URL(e).protocol;return t!==`http:`&&t!==`https:`}catch{return!1}}function Qv(e,t){let n=e.clientRegistrationDefaultApplicationType??`web`;return n===`infer`?(t.redirect_uris??[]).some(e=>Zv(e)||ty(e))?`native`:`web`:n}function $v(e){throw new M(`BAD_REQUEST`,{error:`invalid_redirect_uri`,error_description:e})}function ey(e){let t=/^http:\/\/([^/?#]*)/i.exec(e)?.[1];if(!t)return null;let n=t.slice(t.lastIndexOf(`@`)+1);if(n.startsWith(`[`)){let e=n.indexOf(`]`);return e<0?null:n.slice(0,e+1).toLowerCase()}return(n.split(`:`)[0]??``).toLowerCase()}function ty(e){let t=ey(e);return t===`localhost`||t===`127.0.0.1`||t===`[::1]`}function ny(e,t){let n=new Set([...e.clientRegistrationDefaultResources??[],...e.clientRegistrationAllowedResources??[]]);for(let e of t)if(!n.has(e))throw new M(`BAD_REQUEST`,{error:`invalid_target`,error_description:`requested resource ${e} is not allowed for client registration`})}async function ry(e,t,n){let r=t.clientRegistrationDefaultResources??[],i=[...new Set([...r,...n])];for(let n of i){let r=await mh(e,t,n);if(!r)throw new M(`BAD_REQUEST`,{error:`invalid_target`,error_description:`requested resource ${n} does not exist`});if(r.disabled)throw new M(`BAD_REQUEST`,{error:`invalid_target`,error_description:`requested resource ${n} is disabled`})}return i}function iy(e,t){let n;try{n=new URL(e)}catch{$v(`redirect URI must be an absolute URI: ${e}`)}(e.includes(`#`)||n.username.length>0||n.password.length>0)&&$v(`redirect URI must not include credentials or a fragment: ${e}`);let r=n.protocol===`http:`,i=n.protocol===`https:`;/^localhost\.+$/i.test(n.hostname)&&$v(`redirect URI localhost must not include trailing dots: ${e}`);let a=Wp(n.hostname)||n.hostname===`localhost`;t===`web`?(!i||a)&&$v(`web clients require https redirect URIs on non-loopback hosts: ${e}`):i?a&&$v(`native clients must not use https loopback redirect URIs: ${e}`):r?ty(e)||$v(`native clients may use http only on the exact loopback hosts localhost, 127.0.0.1, or [::1]: ${e}`):om(n)||$v(`native private-use redirect URI schemes must not use a reserved scheme; they must be an authority-free reverse-domain URI or a custom-scheme URI with a host and a path: ${e}`)}function ay(e,t){let n=t=>{throw new M(`BAD_REQUEST`,{error:`invalid_client_metadata`,error_description:`${e} ${t}`})},r;try{r=new URL(t)}catch{return n(`must be an absolute URL`)}t.includes(`#`)&&n(`must not include a fragment component`),r.protocol!==`https:`&&n(`must use https`),(r.username||r.password)&&n(`must not contain credentials`),Mv(r.hostname)&&n(`must not point to a private or reserved address`)}var oy=new Set(Object.keys(Zm.shape));function sy(e,t){return{body:Object.fromEntries(Object.entries(e).filter(([e])=>oy.has(e))),metadata:cy(e,t)}}function cy(e,t){let n=El(t),r=Object.fromEntries(Object.entries(e).filter(([e])=>n.has(e)));return Object.keys(r).length?r:void 0}async function ly(e,t){let{body:n,metadata:r}=sy(e.body,t);if(!t.allowDynamicClientRegistration)throw new M(`FORBIDDEN`,{error:`access_denied`,error_description:`Client registration is disabled`});let i=await Z(e),a=i?void 0:await Uv(e,t,n),o=!!a;if(!(i||o||t.allowUnauthenticatedClientRegistration))throw new M(`UNAUTHORIZED`,{error_description:`Authentication required for client registration`},{"WWW-Authenticate":`Bearer`,...Iu});let s=n.grant_types?.length?Jv(t,n.grant_types):n.grant_types,c=n.grant_types?.includes(`authorization_code`)&&!s?.includes(`authorization_code`),l={...n,grant_types:s,response_types:c?void 0:n.response_types};if(!i&&!o&&l.grant_types?.includes(`client_credentials`))throw new M(`BAD_REQUEST`,{error:`invalid_client_metadata`,error_description:`client_credentials grant requires authenticated registration`});let u=Array.isArray(n.resources)?n.resources.filter(e=>typeof e==`string`&&e.length>0):[];i&&await yv(e,i,t,`create`);let d=a?.referenceId??(i&&t.clientReference?await t.clientReference({user:i.user,session:i.session}):void 0),f=Ah(a?.clientCredentialsScopes??[]);jh(f,Kv(l),l.token_endpoint_auth_method,t);let p=await gy(e,t,{metadata:{...l,metadata:r},registrationSource:`dynamic`,userId:d?void 0:i?.session.userId,referenceId:d,requestedResources:u,clientCredentialsScopes:f});return e.setStatus(201),e.json(p)}async function uy(e,t,n){let r=n?.registrationSource===`clientMetadataDocument`,i=Yv(e,r?null:n?.registrationSource===`dynamic`?Qv(t,e):`web`),a=i.token_endpoint_auth_method??`client_secret_basic`;if(!new Set(_l(t,{includeNone:!0})).has(a))throw new M(`BAD_REQUEST`,{error:`invalid_client_metadata`,error_description:`unsupported token_endpoint_auth_method ${a}`});if(i.dpop_bound_access_tokens!==void 0&&typeof i.dpop_bound_access_tokens!=`boolean`)throw new M(`BAD_REQUEST`,{error:`invalid_client_metadata`,error_description:`dpop_bound_access_tokens must be a boolean`});let o=i.grant_types??[],s=i.response_types,c=i.application_type;if(c!==void 0&&c!==`web`&&c!==`native`)throw new M(`BAD_REQUEST`,{error:`invalid_client_metadata`,error_description:`application_type must be web or native`});if(o.includes(`authorization_code`)&&(!i.redirect_uris||i.redirect_uris.length===0))throw new M(`BAD_REQUEST`,{error:`invalid_redirect_uri`,error_description:`Redirect URIs are required for authorization_code and implicit grant types`});for(let e of i.redirect_uris??[])iy(e,c??(r?`native`:`web`));if(r)Jv(t,o);else{let e=new Set(pl(t));for(let t of o)if(!e.has(t))throw new M(`BAD_REQUEST`,{error:`invalid_client_metadata`,error_description:`unsupported grant_type ${t}`})}if(o.includes(`authorization_code`)&&!s?.includes(`code`))throw new M(`BAD_REQUEST`,{error:`invalid_client_metadata`,error_description:`When 'authorization_code' grant type is used, 'code' response type must be included`});if(!o.includes(`authorization_code`)&&s?.includes(`code`))throw new M(`BAD_REQUEST`,{error:`invalid_client_metadata`,error_description:`When 'code' response type is used, 'authorization_code' grant type must be included`});if(i.subject_type!==void 0){if(i.subject_type!==`public`&&i.subject_type!==`pairwise`)throw new M(`BAD_REQUEST`,{error:`invalid_client_metadata`,error_description:`subject_type must be "public" or "pairwise"`});if(i.subject_type===`pairwise`&&!t.pairwiseSecret)throw new M(`BAD_REQUEST`,{error:`invalid_client_metadata`,error_description:`pairwise subject_type requires server pairwiseSecret configuration`});if(i.subject_type===`pairwise`&&i.redirect_uris?.some(Xv))throw new M(`BAD_REQUEST`,{error:`invalid_client_metadata`,error_description:`pairwise clients cannot use custom-scheme redirect URIs that include a host`});if(i.subject_type===`pairwise`&&i.redirect_uris&&i.redirect_uris.length>1&&new Set(i.redirect_uris.map(e=>new URL(e).host)).size>1)throw new M(`BAD_REQUEST`,{error:`invalid_client_metadata`,error_description:`pairwise clients with redirect_uris on different hosts require a sector_identifier_uri, which is not yet supported. All redirect_uris must share the same host.`})}let l=(i?.scope)?.split(` `).filter(e=>e.length),u=n?.registrationSource===`dynamic`||n?.registrationSource===`clientMetadataDocument`,d=u?Gv(t):t.scopes;if(d){let e=new Set(d);for(let t of l??[])if(!e?.has(t))throw new M(`BAD_REQUEST`,{error:`invalid_scope`,error_description:`cannot request scope ${t}`})}if(u&&i.require_pkce===!1)throw new M(`BAD_REQUEST`,{error:`invalid_client_metadata`,error_description:`pkce is required for registered clients.`});if(i.jwks||i.jwks_uri){if(i.jwks&&i.jwks_uri)throw new M(`BAD_REQUEST`,{error:`invalid_client_metadata`,error_description:`jwks and jwks_uri are mutually exclusive`});if(i.jwks_uri)try{let e=new URL(i.jwks_uri);if(e.protocol!==`https:`)throw new M(`BAD_REQUEST`,{error:`invalid_client_metadata`,error_description:`jwks_uri must use HTTPS`});if(e.username||e.password)throw new M(`BAD_REQUEST`,{error:`invalid_client_metadata`,error_description:`jwks_uri must not contain credentials`});if(i.jwks_uri.includes(`#`))throw new M(`BAD_REQUEST`,{error:`invalid_client_metadata`,error_description:`jwks_uri must not include a fragment component`});if(Mv(e.hostname))throw new M(`BAD_REQUEST`,{error:`invalid_client_metadata`,error_description:`jwks_uri must not point to a private or reserved address`});if(n?.ctx&&!n.ctx.context.isTrustedOrigin(e.href)){let t=typeof i.client_id==`string`?i.client_id:void 0;if(!(r&&t!==void 0&&URL.canParse(t)&&new URL(t).origin===e.origin))throw new M(`BAD_REQUEST`,{error:`invalid_client_metadata`,error_description:`jwks_uri must belong to a trusted origin or the Client ID Metadata Document origin`})}}catch(e){throw e instanceof M?e:new M(`BAD_REQUEST`,{error:`invalid_client_metadata`,error_description:`jwks_uri must be a valid URL`})}i.jwks&&vv(i.jwks)}if(a===`private_key_jwt`&&!i.jwks&&!i.jwks_uri)throw new M(`BAD_REQUEST`,{error:`invalid_client_metadata`,error_description:`private_key_jwt requires either jwks or jwks_uri`});if(i.backchannel_logout_uri!==void 0){if(t.disableJwtPlugin)throw new M(`BAD_REQUEST`,{error:`invalid_client_metadata`,error_description:`backchannel_logout_uri requires the jwt plugin (disableJwtPlugin must be false)`});ay(`backchannel_logout_uri`,i.backchannel_logout_uri)}if(i.frontchannel_logout_uri!==void 0){let e;try{e=new URL(i.frontchannel_logout_uri)}catch{throw new M(`BAD_REQUEST`,{error:`invalid_client_metadata`,error_description:`frontchannel_logout_uri must be an absolute URL`})}if(i.frontchannel_logout_uri.includes(`#`))throw new M(`BAD_REQUEST`,{error:`invalid_client_metadata`,error_description:`frontchannel_logout_uri must not include a fragment component`});if(e.username||e.password)throw new M(`BAD_REQUEST`,{error:`invalid_client_metadata`,error_description:`frontchannel_logout_uri must not contain credentials`});let t=e.protocol===`https:`||e.protocol===`http:`,n=(i.redirect_uris??[]).some(t=>{try{return new URL(t).origin===e.origin}catch{return!1}});if(!t||!n)throw new M(`BAD_REQUEST`,{error:`invalid_client_metadata`,error_description:`frontchannel_logout_uri must use the scheme, host, and port of a registered redirect_uri`})}n?.skipExtensionValidation||await Dl(t,i,e.metadata)}var dy=Symbol(`client-registration-collision`);function fy(e){if(!e||typeof e!=`object`)return!1;let t=e;return t[dy]===!0&&(t.kind===`oauth-client-row-unique`||t.kind===`oauth-client-resource-link-unique`)&&`cause`in t}async function py(e,t,n){let r=n.registrationSource===`dynamic`&&!n.metadata.scope?{...n.metadata,scope:(t.clientRegistrationDefaultScopes??t.scopes)?.join(` `)}:n.metadata,i=Yv(r,n.registrationSource===`clientMetadataDocument`?null:n.registrationSource===`dynamic`?Qv(t,r):`web`),a=i.token_endpoint_auth_method===`none`,o=i.token_endpoint_auth_method===`private_key_jwt`,s=vl(t,i.token_endpoint_auth_method);await uy(i,t,{registrationSource:n.registrationSource,ctx:e,skipExtensionValidation:n.registrationSource===`clientMetadataDocument`&&!!n.existingClient});let c=n.clientId??t.generateClientId?.()??zi(32,`a-z`,`A-Z`),l=a||o||s?void 0:t.generateClientSecret?.()||zi(32,`a-z`,`A-Z`),u=l?await Kl(e,t,l):void 0,d=n.registrationSource===`dynamic`&&!a&&t.clientRegistrationRequirePKCE===!1,f=i.require_pkce??(!d&&void 0),p=Math.floor(Date.now()/1e3),{resources:m,...h}=n.registrationSource===`dynamic`||n.registrationSource===`clientMetadataDocument`?{...i,scope:Gv(t).join(` `)}:i,g=n.registrationSource===`clientMetadataDocument`?void 0:{userId:n.userId,referenceId:n.referenceId},_=Cy({...h,redirect_uris:i.redirect_uris??[],disabled:void 0,client_secret_expires_at:u?n.registrationSource===`dynamic`&&t.clientRegistrationClientSecretExpiration?lm(t.clientRegistrationClientSecretExpiration,p):0:void 0,client_id:c,client_secret:u,client_id_issued_at:p,require_pkce:f,user_id:g?.referenceId?void 0:g?.userId,reference_id:g?.referenceId});_.clientCredentialsScopes=n.registrationSource===`clientMetadataDocument`?[]:n.clientCredentialsScopes??[],_.clientDiscoveryId=n.registrationSource===`clientMetadataDocument`?n.clientDiscoveryId:null,_.sectorIdentifier=hu(c,i.redirect_uris),n.registrationSource===`clientMetadataDocument`&&i.application_type===void 0&&(_.applicationType=null);let v=n.registrationSource===`clientMetadataDocument`?[]:n.requestedResources??[];n.registrationSource===`dynamic`&&ny(t,v);let y=await ry(e,t,v),b=t.schema?.oauthClient?.modelName??`oauthClient`,x=t.schema?.oauthClientResource?.modelName??`oauthClientResource`,S=n.registrationSource===`clientMetadataDocument`?n.existingClient:void 0,C=n.registrationSource===`clientMetadataDocument`?n.clientDiscoveryId:null,w=await Ud(e.context.adapter,async()=>{let r=await Vd(e.context.adapter),a,o=!1;if(S){let e;if(Tl(t)){let n=El(t),a=Xc(yy(n,(await r.findOne({model:b,where:[{field:`clientId`,value:c}]}))?.metadata,i.metadata));await Dl(t,i,a),n.size>0&&(e=a&&Object.keys(a).length>0?JSON.stringify(a):null)}let{clientCredentialsScopes:n,disabled:o,skipConsent:s,enableEndSession:l,...u}=_,d=await r.update({model:b,where:[{field:`clientId`,value:c},{field:`clientDiscoveryId`,value:C}],update:{...u,metadata:e,sectorIdentifier:S.sectorIdentifier?_.sectorIdentifier:null,createdAt:S.createdAt,updatedAt:new Date(p*1e3)}});if(!d)throw new M(`BAD_REQUEST`,{error:`invalid_client`,error_description:`client no longer exists`});a=d}else{try{a=await r.create({model:b,data:{..._,createdAt:new Date(p*1e3),updatedAt:new Date(p*1e3)}})}catch(e){throw n.registrationSource===`clientMetadataDocument`&&xy(e)?{[dy]:!0,kind:`oauth-client-row-unique`,clientId:c,cause:e}:e}o=!0}let s=y.length===0?[]:await r.findMany({model:x,where:[{field:`clientId`,value:c}]}),l=new Set(s.map(e=>e.resourceId)),u=new Date;for(let e of y)if(!l.has(e))try{await r.create({model:x,data:{clientId:c,resourceId:e,createdAt:u}})}catch(t){throw n.registrationSource===`clientMetadataDocument`&&xy(t)?{[dy]:!0,kind:`oauth-client-resource-link-unique`,clientId:c,resourceId:e,cause:t}:t}return{client:a,created:o}});return{client:w.client,clientSecret:l,resources:y,created:w.created}}function my(e,t){let n=wy({...e.client,clientSecret:e.clientSecret?(t.prefix?.clientSecret??``)+e.clientSecret:void 0});return e.resources.length>0&&(n.resources=e.resources),n}function hy(e,t){return{...my(e,t),client_credentials_scopes:[...e.client.clientCredentialsScopes??[]]}}async function gy(e,t,n){return my(await py(e,t,n),t)}async function _y(e,t,n){return hy(await py(e,t,n),t)}function vy(e,t){if(e&&e.clientDiscoveryId!==t)throw new M(`BAD_REQUEST`,{error:`invalid_client`,error_description:`client_id is already owned by a different registration source`})}function yy(e,t,n){let r=([t])=>e.has(t),i={...Object.fromEntries(Object.entries(du(t)??{}).filter(e=>!r(e))),...Object.fromEntries(Object.entries(n??{}).filter(r))};return Object.keys(i).length?i:void 0}async function by(e,t,n){if(vy(n.existingClient,n.clientDiscoveryId),n.metadata.backchannel_logout_uri!==void 0||n.metadata.backchannel_logout_session_required!==void 0)throw new M(`BAD_REQUEST`,{error:`invalid_client_metadata`,error_description:`Client ID Metadata Documents cannot register a back-channel logout target`});if((n.metadata.token_endpoint_auth_method??`none`)!==`none`&&n.metadata.token_endpoint_auth_method!==`private_key_jwt`)throw new M(`BAD_REQUEST`,{error:`invalid_client_metadata`,error_description:`Client ID Metadata Document clients cannot use a shared secret`});let r=e=>({...n,existingClient:e,metadata:{...n.metadata,metadata:cy(n.metadata,t),token_endpoint_auth_method:n.metadata.token_endpoint_auth_method??`none`,client_secret:void 0,client_secret_expires_at:void 0},registrationSource:`clientMetadataDocument`});try{return await py(e,t,r(n.existingClient))}catch(i){if(!fy(i))throw i;let a=t.schema?.oauthClient?.modelName??`oauthClient`,o=t.schema?.oauthClientResource?.modelName??`oauthClientResource`,s=await e.context.adapter.findOne({model:a,where:[{field:`clientId`,value:n.clientId}]});if(i.clientId!==n.clientId||!s||s.clientDiscoveryId!==n.clientDiscoveryId||i.kind===`oauth-client-resource-link-unique`&&!await e.context.adapter.findOne({model:o,where:[{field:`clientId`,value:i.clientId},{field:`resourceId`,value:i.resourceId}]}))throw i.cause;try{return await py(e,t,r(s))}catch(e){throw fy(e)?e.cause:e}}}function xy(e){if(!e||typeof e!=`object`)return!1;let t=e,n=String(t.code??t.errno??``);return[`1062`,`11000`,`23505`,`ER_DUP_ENTRY`,`P2002`,`SQLITE_CONSTRAINT_UNIQUE`].includes(n)||t.name===`MongoServerError`&&t.code===11e3?!0:typeof t.message==`string`&&/(?:duplicate|unique constraint|unique key)/i.test(t.message)}async function Sy(e,t,n){let r=await Z(e);if(await yv(e,r,t,`create`),!r)throw new M(`UNAUTHORIZED`);let i=t.clientReference?await t.clientReference({user:r.user,session:r.session}):void 0,{client_credentials_scopes:a,...o}=e.body,s=n?.admin?Ah(a??[]):[];jh(s,Kv(o),o.token_endpoint_auth_method,t),s.length>0&&await yv(e,r,t,`configure-client-credentials-scopes`);let c=n?.admin?o.resources:void 0;for(let n of new Set(c??[]))await bv(e,r,t,`link`,n);let l={metadata:o,registrationSource:`managed`,userId:i?void 0:r.session.userId,referenceId:i,clientCredentialsScopes:s,...c?{requestedResources:c}:{}},u=n?.admin?await _y(e,t,l):await gy(e,t,l);return e.setStatus(201),e.json(u)}function Cy(e){let{client_id:t,client_secret:n,client_secret_expires_at:r,scope:i,user_id:a,client_id_issued_at:o,client_name:s,client_uri:c,logo_uri:l,contacts:u,tos_uri:d,policy_uri:f,jwks:p,jwks_uri:m,software_id:h,software_version:g,software_statement:_,redirect_uris:v,post_logout_redirect_uris:y,backchannel_logout_uri:b,backchannel_logout_session_required:x,frontchannel_logout_uri:S,frontchannel_logout_session_required:C,token_endpoint_auth_method:w,grant_types:T,response_types:E,application_type:D,disabled:O,skip_consent:k,enable_end_session:A,require_pkce:j,dpop_bound_access_tokens:M,subject_type:N,reference_id:P,metadata:F}=e,I=r?new Date(Number(r)*1e3):void 0,L=o?new Date(o*1e3):void 0,R=i?.split(` `),ee=Xc(F??{}),te=ee&&Object.keys(ee).length?JSON.stringify(ee):void 0;return{clientId:t,clientSecret:n,disabled:O,scopes:R,userId:a,createdAt:L,expiresAt:I,name:s,uri:c,icon:l,contacts:u,tos:d,policy:f,softwareId:h,softwareVersion:g,softwareStatement:_,redirectUris:v,postLogoutRedirectUris:y,backchannelLogoutUri:b,backchannelLogoutSessionRequired:x,frontchannelLogoutUri:S,frontchannelLogoutSessionRequired:C,tokenEndpointAuthMethod:w,grantTypes:T,responseTypes:E,jwks:p?JSON.stringify(p):void 0,jwksUri:m,applicationType:D,skipConsent:k,enableEndSession:A,requirePKCE:j,dpopBoundAccessTokens:M,subjectType:N,referenceId:P,metadata:te}}function wy(e){let{clientId:t,clientSecret:n,disabled:r,scopes:i,userId:a,createdAt:o,updatedAt:s,expiresAt:c,name:l,uri:u,icon:d,contacts:f,tos:p,policy:m,softwareId:h,softwareVersion:g,softwareStatement:_,redirectUris:v,postLogoutRedirectUris:y,backchannelLogoutUri:b,backchannelLogoutSessionRequired:x,frontchannelLogoutUri:S,frontchannelLogoutSessionRequired:C,tokenEndpointAuthMethod:w,grantTypes:T,responseTypes:E,applicationType:D,jwks:O,jwksUri:k,skipConsent:A,enableEndSession:j,requirePKCE:M,dpopBoundAccessTokens:N,subjectType:P,referenceId:F,metadata:I}=e,L=c?Math.round(new Date(c).getTime()/1e3):void 0,R=o?Math.round(new Date(o).getTime()/1e3):void 0,ee=i?.join(` `);return{...Xc(du(I)),client_id:t,client_secret:n??void 0,client_secret_expires_at:n?L??0:void 0,scope:ee??void 0,user_id:a??void 0,client_id_issued_at:R??void 0,client_name:l??void 0,client_uri:u??void 0,logo_uri:d??void 0,contacts:f??void 0,tos_uri:p??void 0,policy_uri:m??void 0,jwks:O?JSON.parse(O):void 0,jwks_uri:k??void 0,software_id:h??void 0,software_version:g??void 0,software_statement:_??void 0,redirect_uris:v??[],post_logout_redirect_uris:y??void 0,backchannel_logout_uri:b??void 0,backchannel_logout_session_required:x??void 0,frontchannel_logout_uri:S??void 0,frontchannel_logout_session_required:C??void 0,token_endpoint_auth_method:w??void 0,grant_types:T??void 0,response_types:E??void 0,application_type:D??void 0,disabled:r??void 0,skip_consent:A??void 0,enable_end_session:j??void 0,require_pkce:M??void 0,dpop_bound_access_tokens:N??void 0,subject_type:P??void 0,reference_id:F??void 0}}async function Ty(e,t){let n=await Z(e);if(await yv(e,n,t,`read`,e.query.client_id),!n)throw new M(`UNAUTHORIZED`);let r=await Vl(e,t,e.query.client_id);if(!r)throw new M(`NOT_FOUND`,{error_description:`client not found`,error:`not_found`});if(r.userId){if(r.userId!==n.user.id)throw new M(`UNAUTHORIZED`)}else if(r.referenceId&&t.clientReference){if(r.referenceId!==await t.clientReference(n))throw new M(`UNAUTHORIZED`)}else throw new M(`UNAUTHORIZED`);let i=wy(r);return i.client_secret=void 0,i}async function Ey(e,t,n){let r=await Vl(e,t,n);if(!r||r.disabled)throw new M(`NOT_FOUND`,{error_description:`client not found`,error:`not_found`});return wy({clientId:r.clientId,name:r.name,uri:r.uri,contacts:r.contacts,icon:r.icon,tos:r.tos,policy:r.policy})}async function Dy(e,t){let n=await Z(e);if(await yv(e,n,t,`list`),!n)throw new M(`UNAUTHORIZED`);let r=await t.clientReference?.(n);if(r)return await e.context.adapter.findMany({model:`oauthClient`,where:[{field:`referenceId`,value:r}]}).then(e=>e?e.map(e=>{let t=wy(e);return t.client_secret=void 0,t}):null);if(n.user.id)return await e.context.adapter.findMany({model:`oauthClient`,where:[{field:`userId`,value:n.user.id}]}).then(e=>e?e.map(e=>{let t=wy(e);return t.client_secret=void 0,t}):null);throw new M(`BAD_REQUEST`,{message:`either user_id or reference_id must be provided`})}async function Oy(e,t){let n=await Z(e);if(await yv(e,n,t,`delete`,e.body.client_id),!n)throw new M(`UNAUTHORIZED`);let r=e.body.client_id;Bl(t,r);let i=await Vl(e,t,r);if(!i)throw new M(`NOT_FOUND`,{error_description:`client not found`,error:`not_found`});if(i.userId){if(i.userId!==n.user.id)throw new M(`UNAUTHORIZED`)}else if(i.referenceId&&t.clientReference){if(i.referenceId!==await t.clientReference(n))throw new M(`UNAUTHORIZED`)}else throw new M(`UNAUTHORIZED`);await e.context.adapter.delete({model:`oauthClient`,where:[{field:`clientId`,value:r}]})}async function ky(e,t,n){let r=await Z(e);if(await yv(e,r,t,`update`,e.body.client_id),!r)throw new M(`UNAUTHORIZED`);let i=e.body.client_id;Bl(t,i);let a=await Vl(e,t,i);if(!a)throw new M(`NOT_FOUND`,{error_description:`client not found`,error:`not_found`});let{client_credentials_scopes:o,backchannel_logout_uri:s,frontchannel_logout_uri:c,...l}=e.body.update,u=s===null,d=c===null,f={...l,...s==null?{}:{backchannel_logout_uri:s},...c==null?{}:{frontchannel_logout_uri:c}},p=Object.keys(f).length>0||u||d,m=a.userId?a.userId===r.user.id:a.referenceId&&t.clientReference?a.referenceId===await t.clientReference(r):!1,h=!m&&n?.admin&&o!==void 0&&!p;if(!m&&!h)throw new M(`UNAUTHORIZED`);if(h&&await yv(e,r,t,`configure-client-credentials-scopes`,i),!p&&o===void 0){let e=wy(a);return e.client_secret=void 0,n?.admin?{...e,client_credentials_scopes:[...a.clientCredentialsScopes??[]]}:e}let g=f.grant_types??a.grantTypes??[],_=f.token_endpoint_auth_method??a.tokenEndpointAuthMethod,v=o===void 0?void 0:Ah(o);v!==void 0&&(jh(v,g,_,t),v.length>0&&!h&&await yv(e,r,t,`configure-client-credentials-scopes`,i));let y={...wy({...a,metadata:void 0}),...f,metadata:f.metadata??du(a.metadata)};u&&(y.backchannel_logout_uri=void 0,y.backchannel_logout_session_required=void 0),d&&(y.frontchannel_logout_uri=void 0,y.frontchannel_logout_session_required=void 0),await uy(y,t,{ctx:e});let b={...Cy(f)};f.redirect_uris&&a.sectorIdentifier&&(b.sectorIdentifier=hu(a.clientId,f.redirect_uris)),u&&(b.backchannelLogoutUri=null,b.backchannelLogoutSessionRequired=null),d&&(b.frontchannelLogoutUri=null,b.frontchannelLogoutSessionRequired=null),f.metadata!==void 0&&b.metadata===void 0&&(b.metadata=null),!g.includes(`client_credentials`)||_===`none`?b.clientCredentialsScopes=[]:v!==void 0&&(b.clientCredentialsScopes=v),f.token_endpoint_auth_method&&(f.token_endpoint_auth_method===`private_key_jwt`?b.clientSecret=null:(b.jwks=null,b.jwksUri=null,b.clientSecret||=await Kl(e,t,t.generateClientSecret?.()||zi(32,`a-z`,`A-Z`))));let x=await e.context.adapter.update({model:`oauthClient`,where:[{field:`clientId`,value:i}],update:{...b,updatedAt:new Date(Math.floor(Date.now()/1e3)*1e3)}});if(!x)throw new M(`INTERNAL_SERVER_ERROR`,{error_description:`unable to update client`,error:`invalid_client`});let S=wy(x);return S.client_secret=void 0,n?.admin?{...S,client_credentials_scopes:[...x.clientCredentialsScopes??[]]}:S}async function Ay(e,t){let n=await Z(e);if(await yv(e,n,t,`rotate`,e.body.client_id),!n)throw new M(`UNAUTHORIZED`);let r=e.body.client_id;Bl(t,r);let i=await Vl(e,t,r);if(!i)throw new M(`NOT_FOUND`,{error_description:`client not found`,error:`not_found`});if(i.userId){if(i.userId!==n.user.id)throw new M(`UNAUTHORIZED`)}else if(i.referenceId&&t.clientReference){if(i.referenceId!==await t.clientReference(n))throw new M(`UNAUTHORIZED`)}else throw new M(`UNAUTHORIZED`);if(i.tokenEndpointAuthMethod===`none`||!i.clientSecret)throw new M(`BAD_REQUEST`,{error_description:`secret rotation is only available for clients using client_secret authentication`,error:`invalid_client`});let a=t.generateClientSecret?.()||zi(32,`a-z`,`A-Z`),o=a?await Kl(e,t,a):void 0,s=await e.context.adapter.update({model:`oauthClient`,where:[{field:`clientId`,value:r}],update:{clientSecret:o,updatedAt:new Date(Math.floor(Date.now()/1e3)*1e3)}});if(!s)throw new M(`INTERNAL_SERVER_ERROR`,{error_description:`unable to update client`,error:`invalid_client`});return wy({...s,clientSecret:(t.prefix?.clientSecret??``)+a})}async function jy(e,t){if(!t.allowClientKeyRotation)throw new M(`FORBIDDEN`,{error:`access_denied`,error_description:`Client key rotation is disabled`});let{body:n}=e;vv(n.jwks);let{client:r}=await Vv(e,t,n.client_assertion,n.client_assertion_type,void 0,Dh({context:e.context,request:void 0},`/oauth2/client/rotate-keys`),{endpointAudienceOnly:!0,assertClient:e=>My(t,e)});if(!await e.context.adapter.incrementOne({model:`oauthClient`,where:[{field:`clientId`,value:r.clientId},{field:`jwks`,value:r.jwks}],increment:{},set:{jwks:JSON.stringify(n.jwks),updatedAt:new Date}}))throw new M(`CONFLICT`,{error:`invalid_request`,error_description:`client keys changed while rotating; retry with a fresh client assertion`});return{client_id:r.clientId,jwks:n.jwks}}function My(e,t){if(Bl(e,t.clientId),t.clientDiscoveryId||t.jwksUri||!t.jwks)throw new M(`BAD_REQUEST`,{error:`invalid_client`,error_description:`client keys are not stored inline; rotate them where the client publishes them`})}var Ny=s().trim().min(1),Py=z(s().trim().min(1)).min(1),Fy=e=>X(`/admin/oauth2/create-client`,{method:`POST`,body:a({redirect_uris:z(Q).min(1).optional(),scope:s().optional(),client_name:s().optional(),client_uri:s().optional(),logo_uri:s().optional(),contacts:z(s().min(1)).min(1).optional(),tos_uri:s().optional(),policy_uri:s().optional(),software_id:s().optional(),software_version:s().optional(),software_statement:s().optional(),post_logout_redirect_uris:z(Q).min(1).optional(),backchannel_logout_uri:Q.optional(),backchannel_logout_session_required:F().optional(),frontchannel_logout_uri:Q.optional(),frontchannel_logout_session_required:F().optional(),token_endpoint_auth_method:Ny.optional(),application_type:pe([`web`,`native`]).optional(),jwks:Gm.optional(),jwks_uri:s().optional(),grant_types:Py.optional(),client_credentials_scopes:z(s().trim().min(1)).optional(),resources:z(Hm).optional(),response_types:z(pe([`code`])).optional(),client_secret_expires_at:re([s(),b()]).optional().default(0),skip_consent:F().optional(),enable_end_session:F().optional(),require_pkce:F().optional(),dpop_bound_access_tokens:F().optional(),subject_type:pe([`public`,`pairwise`]).optional(),metadata:S(s(),r()).optional()}),metadata:{noStore:!0,SERVER_ONLY:!0,openapi:{description:`Register an OAuth2 application`,responses:{201:{description:`OAuth2 application registered successfully`,content:{"application/json":{schema:{type:`object`,properties:{client_id:{type:`string`,description:`Unique identifier for the client`},client_secret:{type:`string`,description:`Secret key for the client`},client_secret_expires_at:{type:`number`,description:`Time the client secret will expire. If 0, the client secret will never expire.`},scope:{type:`string`,description:`Space-separated scopes allowed by the client`},client_credentials_scopes:{type:`array`,items:{type:`string`},description:`Server-authorized scope ceiling for client_credentials tokens`},user_id:{type:`string`,description:`ID of the user who registered the client, null if registered anonymously`},client_id_issued_at:{type:`number`,description:`Creation timestamp of this client`},client_name:{type:`string`,description:`Name of the OAuth2 application`},client_uri:{type:`string`,description:`URI of the OAuth2 application`},logo_uri:{type:`string`,description:`Icon URI for the application`},contacts:{type:`array`,items:{type:`string`},description:`List representing ways to contact people responsible for this client, typically email addresses`},tos_uri:{type:`string`,description:`Client's terms of service uri`},policy_uri:{type:`string`,description:`Client's policy uri`},software_id:{type:`string`,description:`Unique identifier assigned by the developer to help in the dynamic registration process`},software_version:{type:`string`,description:`Version identifier for the software_id`},software_statement:{type:`string`,description:`JWT containing metadata values about the client software as claims`},redirect_uris:{type:`array`,items:{type:`string`,format:`uri`},description:`List of allowed redirect uris`},token_endpoint_auth_method:{type:`string`,description:`Requested authentication method for the token endpoint`},grant_types:{type:`array`,items:{type:`string`},description:`Grant types the client may use at the token endpoint`},response_types:{type:`array`,items:{type:`string`,enum:[`code`]},description:`Response types the client may use at the authorization endpoint`},application_type:{type:`string`,description:`OIDC application type used to classify redirect URI policy`,enum:[`web`,`native`]},resources:{type:`array`,items:{type:`string`,format:`uri`},description:`Final server-owned resources linked to the client`},disabled:{type:`boolean`,description:`Whether the client is disabled`},require_pkce:{type:`boolean`,description:`Whether the client requires PKCE`,default:!0},metadata:{type:`object`,additionalProperties:!0,nullable:!0,description:`Additional metadata for the application`}},required:[`client_id`]}}}}}}}},async t=>Sy(t,e,{admin:!0})),Iy=e=>X(`/oauth2/create-client`,{method:`POST`,use:[xp],body:a({redirect_uris:z(Q).min(1).optional(),scope:s().optional(),client_name:s().optional(),client_uri:s().optional(),logo_uri:s().optional(),contacts:z(s().min(1)).min(1).optional(),tos_uri:s().optional(),policy_uri:s().optional(),software_id:s().optional(),software_version:s().optional(),software_statement:s().optional(),post_logout_redirect_uris:z(Q).min(1).optional(),backchannel_logout_uri:Q.optional(),backchannel_logout_session_required:F().optional(),frontchannel_logout_uri:Q.optional(),frontchannel_logout_session_required:F().optional(),token_endpoint_auth_method:Ny.optional(),application_type:pe([`web`,`native`]).optional(),jwks:Gm.optional(),jwks_uri:s().optional(),grant_types:Py.optional(),response_types:z(pe([`code`])).optional(),dpop_bound_access_tokens:F().optional()}),metadata:{noStore:!0,openapi:{description:`Register an OAuth2 application`,responses:{201:{description:`OAuth2 application registered successfully`,content:{"application/json":{schema:{type:`object`,properties:{client_id:{type:`string`,description:`Unique identifier for the client`},client_secret:{type:`string`,description:`Secret key for the client`},client_secret_expires_at:{type:`number`,description:`Time the client secret will expire. If 0, the client secret will never expire.`},scope:{type:`string`,description:`Space-separated scopes allowed by the client`},user_id:{type:`string`,description:`ID of the user who registered the client, null if registered anonymously`},client_id_issued_at:{type:`number`,description:`Creation timestamp of this client`},client_name:{type:`string`,description:`Name of the OAuth2 application`},client_uri:{type:`string`,description:`URI of the OAuth2 application`},logo_uri:{type:`string`,description:`Icon URI for the application`},contacts:{type:`array`,items:{type:`string`},description:`List representing ways to contact people responsible for this client, typically email addresses`},tos_uri:{type:`string`,description:`Client's terms of service uri`},policy_uri:{type:`string`,description:`Client's policy uri`},software_id:{type:`string`,description:`Unique identifier assigned by the developer to help in the dynamic registration process`},software_version:{type:`string`,description:`Version identifier for the software_id`},software_statement:{type:`string`,description:`JWT containing metadata values about the client software as claims`},redirect_uris:{type:`array`,items:{type:`string`,format:`uri`},description:`List of allowed redirect uris`},token_endpoint_auth_method:{type:`string`,description:`Requested authentication method for the token endpoint`},grant_types:{type:`array`,items:{type:`string`},description:`Grant types the client may use at the token endpoint`},response_types:{type:`array`,items:{type:`string`,enum:[`code`]},description:`Response types the client may use at the authorization endpoint`},application_type:{type:`string`,description:`OIDC application type used to classify redirect URI policy`,enum:[`web`,`native`]},resources:{type:`array`,items:{type:`string`,format:`uri`},description:`Final server-owned resources linked to the client`},disabled:{type:`boolean`,description:`Whether the client is disabled`},metadata:{type:`object`,additionalProperties:!0,nullable:!0,description:`Additional metadata for the application`}},required:[`client_id`]}}}}}}}},async t=>Sy(t,e)),Ly=e=>X(`/oauth2/get-client`,{method:`GET`,use:[xp],query:a({client_id:s()}),metadata:{openapi:{description:`Get OAuth2 formatted client details`}}},async t=>Ty(t,e)),Ry=e=>X(`/oauth2/public-client`,{method:`GET`,use:[xp],query:a({client_id:s()}),metadata:{openapi:{description:`Gets publicly available client fields`}}},async t=>{let n=t.query.client_id;return Ey(t,e,n)}),zy=e=>X(`/oauth2/public-client-prelogin`,{method:`POST`,use:[sv(e)],body:a({client_id:s(),oauth_query:s().optional()}),metadata:{openapi:{description:`Gets publicly available client fields (prior to login)`}}},async t=>{let n=t.body.client_id;return Ey(t,e,n)}),By=e=>X(`/oauth2/get-clients`,{method:`GET`,use:[xp],metadata:{openapi:{description:`Get OAuth2 formatted client details for a user or organization`}}},async t=>Dy(t,e)),Vy=e=>X(`/admin/oauth2/update-client`,{method:`PATCH`,body:a({client_id:s(),update:a({redirect_uris:z(Q).min(1).optional(),scope:s().optional(),client_name:s().optional(),client_uri:s().optional(),logo_uri:s().optional(),contacts:z(s().min(1)).min(1).optional(),tos_uri:s().optional(),policy_uri:s().optional(),software_id:s().optional(),software_version:s().optional(),software_statement:s().optional(),post_logout_redirect_uris:z(Q).min(1).optional(),backchannel_logout_uri:Q.nullable().optional(),backchannel_logout_session_required:F().optional(),frontchannel_logout_uri:Q.nullable().optional(),frontchannel_logout_session_required:F().optional(),application_type:pe([`web`,`native`]).optional(),grant_types:Py.optional(),client_credentials_scopes:z(s().trim().min(1)).optional(),response_types:z(pe([`code`])).optional(),client_secret_expires_at:re([s(),b()]).optional(),skip_consent:F().optional(),enable_end_session:F().optional(),disabled:F().optional(),dpop_bound_access_tokens:F().optional(),metadata:S(s(),r()).optional()})}),metadata:{SERVER_ONLY:!0,openapi:{description:`Updates OAuth2 formatted client details.`}}},async t=>ky(t,e,{admin:!0})),Hy=e=>X(`/oauth2/update-client`,{method:`POST`,use:[xp],body:a({client_id:s(),update:a({redirect_uris:z(Q).min(1).optional(),scope:s().optional(),client_name:s().optional(),client_uri:s().optional(),logo_uri:s().optional(),contacts:z(s().min(1)).min(1).optional(),tos_uri:s().optional(),policy_uri:s().optional(),software_id:s().optional(),software_version:s().optional(),software_statement:s().optional(),post_logout_redirect_uris:z(Q).min(1).optional(),backchannel_logout_uri:Q.nullable().optional(),backchannel_logout_session_required:F().optional(),frontchannel_logout_uri:Q.nullable().optional(),frontchannel_logout_session_required:F().optional(),application_type:pe([`web`,`native`]).optional(),grant_types:Py.optional(),response_types:z(pe([`code`])).optional()})}),metadata:{openapi:{description:`Updates OAuth2 formatted client details.`}}},async t=>ky(t,e)),Uy=e=>X(`/oauth2/client/rotate-secret`,{method:`POST`,use:[xp],body:a({client_id:s()}),metadata:{noStore:!0,openapi:{description:`Rotates a confidential client's secret`}}},async t=>Ay(t,e)),Wy=e=>tv(`/oauth2/client/rotate-keys`,{method:`POST`,body:a({client_assertion:s(),client_assertion_type:s(),jwks:Gm}),errorCodesByField:{client_assertion:`invalid_client`,client_assertion_type:`invalid_client`,jwks:`invalid_client_metadata`},metadata:{noStore:!0,openapi:{description:`Replaces the signing keys of a private_key_jwt client. The request is authenticated by a client assertion signed with one of the client's current keys and addressed to this endpoint. Keys left out of the new set stop verifying at once.`}}},async t=>jy(t,e)),Gy=e=>X(`/oauth2/delete-client`,{method:`POST`,use:[xp],body:a({client_id:s()}),metadata:{openapi:{description:`Deletes an oauth client`}}},async t=>Oy(t,e));async function Ky(e,t,n){return await e.context.adapter.findOne({model:`oauthConsent`,where:[{field:`id`,value:n}]})}async function qy(e,t){let n=await Z(e);if(!n)throw new M(`UNAUTHORIZED`);let{id:r}=e.query;if(!r)throw new M(`NOT_FOUND`,{error_description:`missing id parameter`,error:`not_found`});let i=await Ky(e,t,r);if(!i)throw new M(`NOT_FOUND`,{error_description:`no consent`,error:`not_found`});if(i.userId!==n.user.id)throw new M(`UNAUTHORIZED`);return i}async function Jy(e,t){let n=await Z(e);if(!n)throw new M(`UNAUTHORIZED`);return await e.context.adapter.findMany({model:`oauthConsent`,where:[{field:`userId`,value:n.user.id}]})}async function Yy(e,t){let n=await Z(e);if(!n)throw new M(`UNAUTHORIZED`);let{id:r}=e.body;if(!r)throw new M(`NOT_FOUND`,{error_description:`missing id parameter`,error:`not_found`});let i=await Ky(e,t,r);if(!i)throw new M(`NOT_FOUND`,{error_description:`no consent`,error:`not_found`});if(i.userId!==n.user.id)throw new M(`UNAUTHORIZED`);await e.context.adapter.delete({model:`oauthConsent`,where:[{field:`id`,value:r}]})}async function Xy(e,t){let n=await Z(e);if(!n)throw new M(`UNAUTHORIZED`);let{id:r}=e.body;if(!r)throw new M(`NOT_FOUND`,{error_description:`missing id parameter`,error:`not_found`});let i=await Ky(e,t,r);if(!i)throw new M(`NOT_FOUND`,{error_description:`no consent`,error:`not_found`});if(i.userId!==n.user.id)throw new M(`UNAUTHORIZED`);let a=await Vl(e,t,i.clientId);if(!a)throw new M(`NOT_FOUND`,{error_description:`client not found`,error:`not_found`});let o=a?.scopes??t.scopes??[],s=e.body.update,c=s.scopes;if(c&&!c.every(e=>o?.includes(e)))throw new M(`BAD_REQUEST`,{error_description:`unable to provide scopes to ${a?.referenceId??a?.userId}`,error:`invalid_request`});let l=Math.floor(Date.now()/1e3);return await e.context.adapter.update({model:`oauthConsent`,where:[{field:`id`,value:r}],update:{...s,updatedAt:new Date(l*1e3)}})}var Zy=e=>X(`/oauth2/get-consent`,{method:`GET`,query:a({id:s()}),use:[xp],metadata:{openapi:{description:`Gets details of a specific OAuth2 consent for a user`}}},async t=>qy(t,e)),Qy=e=>X(`/oauth2/get-consents`,{method:`GET`,use:[xp],metadata:{openapi:{description:`Gets all available OAuth2 consents for a user`}}},async t=>Jy(t,e)),$y=e=>X(`/oauth2/update-consent`,{method:`POST`,use:[xp],body:a({id:s(),update:a({scopes:z(s())})}),metadata:{openapi:{description:`Updates consent granted to a client.`}}},async t=>Xy(t,e)),eb=e=>X(`/oauth2/delete-consent`,{method:`POST`,use:[xp],body:a({id:s()}),metadata:{openapi:{description:`Deletes consent granted to a client`}}},async t=>Yy(t,e)),tb=e=>e.schema?.oauthResource?.modelName??`oauthResource`,nb=e=>e.schema?.oauthClientResource?.modelName??`oauthClientResource`,rb=e=>e.schema?.oauthClient?.modelName??`oauthClient`;function ib(e){try{return decodeURIComponent(e)}catch{return e}}function ab(e,t){return{identifier:e.identifier,name:e.name??e.identifier,accessTokenTtl:e.accessTokenTtl??null,refreshTokenTtl:e.refreshTokenTtl??null,signingAlgorithm:e.signingAlgorithm??null,signingKeyId:e.signingKeyId??null,allowedScopes:e.allowedScopes??null,customClaims:e.customClaims??null,dpopBoundAccessTokensRequired:e.dpopBoundAccessTokensRequired??!1,disabled:e.disabled??!1,policyVersion:1,metadata:e.metadata??null,createdAt:t,updatedAt:t}}async function ob(e,t){await bv(e,await Z(e),t,`create`);let n=e.body;if(!n?.identifier)throw new M(`BAD_REQUEST`,{error:`invalid_request`,error_description:`identifier is required`});await rh(t,n.identifier);let r=new Date,i;try{i=await e.context.adapter.create({model:tb(t),data:ab(n,r)})}catch(e){let t=e instanceof Error?e.message:String(e);throw/unique|duplicate|UNIQUE/i.test(t)?new M(`BAD_REQUEST`,{error:`invalid_request`,error_description:`resource ${n.identifier} already exists`}):e}if(!i)throw new M(`BAD_REQUEST`,{error:`invalid_request`,error_description:`resource ${n.identifier} could not be created`});return ph(i.identifier),e.json(i,{status:201})}async function sb(e,t){await bv(e,await Z(e),t,`list`);let n=await e.context.adapter.findMany({model:tb(t)});return e.json(n??[])}async function cb(e,t){let n=ib(e.params.identifier);await bv(e,await Z(e),t,`read`,n);let r=await e.context.adapter.findOne({model:tb(t),where:[{field:`identifier`,value:n}]});if(!r)throw new M(`NOT_FOUND`,{error:`not_found`,error_description:`resource ${n} not found`});return e.json(r)}async function lb(e,t){let n=ib(e.params.identifier);if(await bv(e,await Z(e),t,`update`,n),!await e.context.adapter.findOne({model:tb(t),where:[{field:`identifier`,value:n}]}))throw new M(`NOT_FOUND`,{error:`not_found`,error_description:`resource ${n} not found`});let r={updatedAt:new Date};for(let t of[`name`,`accessTokenTtl`,`refreshTokenTtl`,`signingAlgorithm`,`signingKeyId`,`allowedScopes`,`customClaims`,`dpopBoundAccessTokensRequired`,`disabled`,`metadata`])Object.prototype.hasOwnProperty.call(e.body,t)&&(r[t]=e.body[t]);await e.context.adapter.update({model:tb(t),where:[{field:`identifier`,value:n}],update:r}),ph(n);let i=await e.context.adapter.findOne({model:tb(t),where:[{field:`identifier`,value:n}]});if(!i)throw new M(`NOT_FOUND`,{error:`not_found`,error_description:`resource ${n} not found`});return e.json(i)}async function ub(e,t){let n=ib(e.params.identifier);if(await bv(e,await Z(e),t,`delete`,n),!await e.context.adapter.findOne({model:tb(t),where:[{field:`identifier`,value:n}]}))throw new M(`NOT_FOUND`,{error:`not_found`,error_description:`resource ${n} not found`});return await e.context.adapter.delete({model:tb(t),where:[{field:`identifier`,value:n}]}),ph(n),e.json({deleted:!0})}async function db(e,t){let n=await Z(e),r=ib(e.params.identifier),i=ib(e.params.client_id);if(await bv(e,n,t,`link`,r),!await e.context.adapter.findOne({model:tb(t),where:[{field:`identifier`,value:r}]}))throw new M(`NOT_FOUND`,{error:`not_found`,error_description:`resource ${r} not found`});if(!await e.context.adapter.findOne({model:rb(t),where:[{field:`clientId`,value:i}]}))throw new M(`NOT_FOUND`,{error:`not_found`,error_description:`client ${i} not found`});try{await e.context.adapter.create({model:nb(t),data:{clientId:i,resourceId:r,createdAt:new Date}})}catch(t){let n=t instanceof Error?t.message:String(t);if(/unique|duplicate|UNIQUE/i.test(n))return e.json({linked:!0,alreadyLinked:!0});throw t}return e.json({linked:!0})}async function fb(e,t){let n=await Z(e),r=ib(e.params.identifier),i=ib(e.params.client_id);return await bv(e,n,t,`unlink`,r),await e.context.adapter.deleteMany({model:nb(t),where:[{field:`clientId`,value:i},{field:`resourceId`,value:r}]}),e.json({unlinked:!0})}var pb=a({identifier:s().min(1).optional(),name:s().optional(),accessTokenTtl:b().int().positive().nullable().optional(),refreshTokenTtl:b().int().positive().nullable().optional(),signingAlgorithm:pe($m).nullable().optional(),signingKeyId:s().nullable().optional(),allowedScopes:z(s()).nullable().optional(),customClaims:S(s(),r()).nullable().optional(),dpopBoundAccessTokensRequired:F().optional(),disabled:F().optional(),metadata:S(s(),r()).nullable().optional()}),mb=e=>X(`/admin/oauth2/resources`,{method:`POST`,body:pb.required({identifier:!0}),metadata:{SERVER_ONLY:!0}},async t=>ob(t,e)),hb=e=>X(`/admin/oauth2/resources`,{method:`GET`,metadata:{SERVER_ONLY:!0}},async t=>sb(t,e)),gb=e=>X(`/admin/oauth2/resources/:identifier`,{method:`GET`,metadata:{SERVER_ONLY:!0}},async t=>cb(t,e)),_b=e=>X(`/admin/oauth2/resources/:identifier`,{method:`PATCH`,body:pb,metadata:{SERVER_ONLY:!0}},async t=>lb(t,e)),vb=e=>X(`/admin/oauth2/resources/:identifier`,{method:`DELETE`,metadata:{SERVER_ONLY:!0}},async t=>ub(t,e)),yb=e=>X(`/admin/oauth2/resources/:identifier/clients/:client_id`,{method:`POST`,metadata:{SERVER_ONLY:!0}},async t=>db(t,e)),bb=e=>X(`/admin/oauth2/resources/:identifier/clients/:client_id`,{method:`DELETE`,metadata:{SERVER_ONLY:!0}},async t=>fb(t,e));async function xb(e,t,n){if(!await oh(e,t,n.aud,[ih(e.context.baseURL)]))return null;throw new g(`BAD_REQUEST`,{error_description:`JWT access tokens are self-contained and cannot be revoked server-side`,error:`unsupported_token_type`})}async function Sb(e,t){await e.context.adapter.delete({model:`oauthAccessToken`,where:t.id?[{field:`id`,value:t.id}]:[{field:`token`,value:t.token}]})}async function Cb(e,t,n){let{userId:r}=t;if(t.revoked){await eg(e,n,r);return}let i=Math.floor(Date.now()/1e3);await e.context.adapter.incrementOne({model:`oauthRefreshToken`,where:[{field:`id`,value:t.id},{field:`revoked`,operator:`eq`,value:null}],increment:{},set:{revoked:new Date(i*1e3)}})?await e.context.adapter.deleteMany({model:`oauthAccessToken`,where:[{field:`refreshId`,value:t.id}]}):await eg(e,n,r)}async function wb(e,t){let{token:n,token_type_hint:r}=e.body,{clientId:i,clientSecret:a,preVerified:o,authMethod:s}=fu(await pu(e,t,`${e.context.baseURL}/oauth2/revoke`));if(!i)throw new g(`UNAUTHORIZED`,{error_description:`missing required credentials`,error:`invalid_client`});if(typeof n==`string`&&(n=gc(n)),!n?.length)throw new g(`BAD_REQUEST`,{error_description:`missing a required token for introspection`,error:`invalid_request`});let c=await uu(e,t,i,a,void 0,o,void 0,s);try{let i=await zh(e,t,n,r);if(!i)return null;if((i.type===`jwt`?i.payload.azp:i.record.clientId)!==c.clientId){if(c.tokenEndpointAuthMethod===`none`)return null;throw new g(`BAD_REQUEST`,{error_description:`client is not authorized to revoke the presented token`,error:`invalid_request`})}return i.type===`jwt`?await xb(e,t,i.payload):(i.type===`opaque`?await Sb(e,i.record):await Cb(e,i.record,c.clientId),null)}catch(e){throw e instanceof g?e:(ve.error(`Revocation error:`,e),new g(`INTERNAL_SERVER_ERROR`))}}var Tb={oauthClient:{modelName:`oauthClient`,fields:{clientId:{type:`string`,unique:!0,required:!0},clientSecret:{type:`string`,required:!1},clientDiscoveryId:{type:`string`,required:!1},disabled:{type:`boolean`,defaultValue:!1,required:!1},skipConsent:{type:`boolean`,required:!1},enableEndSession:{type:`boolean`,required:!1},subjectType:{type:`string`,required:!1},sectorIdentifier:{type:`string`,required:!1},scopes:{type:`string[]`,required:!1},clientCredentialsScopes:{type:`string[]`,required:!1,defaultValue:[]},userId:{type:`string`,required:!1,references:{model:`user`,field:`id`},index:!0},createdAt:{type:`date`,required:!1},updatedAt:{type:`date`,required:!1},name:{type:`string`,required:!1},uri:{type:`string`,required:!1},icon:{type:`string`,required:!1},contacts:{type:`string[]`,required:!1},tos:{type:`string`,required:!1},policy:{type:`string`,required:!1},softwareId:{type:`string`,required:!1},softwareVersion:{type:`string`,required:!1},softwareStatement:{type:`string`,required:!1},redirectUris:{type:`string[]`,required:!0},postLogoutRedirectUris:{type:`string[]`,required:!1},backchannelLogoutUri:{type:`string`,required:!1},backchannelLogoutSessionRequired:{type:`boolean`,required:!1},frontchannelLogoutUri:{type:`string`,required:!1},frontchannelLogoutSessionRequired:{type:`boolean`,required:!1},tokenEndpointAuthMethod:{type:`string`,required:!1},applicationType:{type:`string`,required:!1},jwks:{type:`string`,required:!1},jwksUri:{type:`string`,required:!1},grantTypes:{type:`string[]`,required:!1},responseTypes:{type:`string[]`,required:!1},requirePKCE:{type:`boolean`,required:!1},dpopBoundAccessTokens:{type:`boolean`,required:!1,defaultValue:!1},referenceId:{type:`string`,required:!1},metadata:{type:`json`,required:!1}}},oauthResource:{modelName:`oauthResource`,fields:{identifier:{type:`string`,required:!0,unique:!0},name:{type:`string`,required:!0},accessTokenTtl:{type:`number`,required:!1},refreshTokenTtl:{type:`number`,required:!1},signingAlgorithm:{type:`string`,required:!1},signingKeyId:{type:`string`,required:!1},allowedScopes:{type:`string[]`,required:!1},customClaims:{type:`json`,required:!1},dpopBoundAccessTokensRequired:{type:`boolean`,required:!1,defaultValue:!1},disabled:{type:`boolean`,required:!1,defaultValue:!1},createdAt:{type:`date`,required:!1},updatedAt:{type:`date`,required:!1},policyVersion:{type:`number`,required:!1,defaultValue:1},metadata:{type:`json`,required:!1}}},oauthClientResource:{modelName:`oauthClientResource`,fields:{clientId:{type:`string`,required:!0,references:{model:`oauthClient`,field:`clientId`,onDelete:`cascade`},index:!0},resourceId:{type:`string`,required:!0,references:{model:`oauthResource`,field:`identifier`,onDelete:`cascade`},index:!0},metadata:{type:`json`,required:!1},createdAt:{type:`date`,required:!1}},indexes:[{fields:[`clientId`,`resourceId`],unique:!0}]},oauthRefreshToken:{fields:{token:{type:`string`,required:!0,unique:!0},clientId:{type:`string`,required:!0,references:{model:`oauthClient`,field:`clientId`},index:!0},sessionId:{type:`string`,required:!1,references:{model:`session`,field:`id`,onDelete:`set null`},index:!0},userId:{type:`string`,required:!0,references:{model:`user`,field:`id`},index:!0},referenceId:{type:`string`,required:!1},authorizationCodeId:{type:`string`,required:!1,index:!0},resources:{type:`string[]`,required:!1},requestedUserInfoClaims:{type:`string[]`,required:!1},expiresAt:{type:`date`},createdAt:{type:`date`},revoked:{type:`date`,required:!1},rotatedAt:{type:`date`,required:!1},rotationReplayResponse:{type:`string`,required:!1},rotationReplayExpiresAt:{type:`date`,required:!1},authTime:{type:`date`,required:!1},acr:{type:`string`,required:!1},amr:{type:`string[]`,required:!1},confirmation:{type:`json`,required:!1},scopes:{type:`string[]`,required:!0}}},oauthAccessToken:{modelName:`oauthAccessToken`,fields:{token:{type:`string`,unique:!0},clientId:{type:`string`,required:!0,references:{model:`oauthClient`,field:`clientId`},index:!0},sessionId:{type:`string`,required:!1,references:{model:`session`,field:`id`,onDelete:`set null`},index:!0},userId:{type:`string`,required:!1,references:{model:`user`,field:`id`},index:!0},referenceId:{type:`string`,required:!1},authorizationCodeId:{type:`string`,required:!1,index:!0},resources:{type:`string[]`,required:!1},requestedUserInfoClaims:{type:`string[]`,required:!1},refreshId:{type:`string`,required:!1,references:{model:`oauthRefreshToken`,field:`id`},index:!0},expiresAt:{type:`date`},createdAt:{type:`date`},revoked:{type:`date`,required:!1},confirmation:{type:`json`,required:!1},scopes:{type:`string[]`,required:!0}}},oauthConsent:{modelName:`oauthConsent`,fields:{clientId:{type:`string`,required:!0,references:{model:`oauthClient`,field:`clientId`},index:!0},userId:{type:`string`,required:!1,references:{model:`user`,field:`id`},index:!0},referenceId:{type:`string`,required:!1},resources:{type:`string[]`,required:!1},requestedUserInfoClaims:{type:`string[]`,required:!1},scopes:{type:`string[]`,required:!0},createdAt:{type:`date`},updatedAt:{type:`date`}}},oauthClientAssertion:{modelName:`oauthClientAssertion`,fields:{expiresAt:{type:`date`,required:!0}}}},Eb=[`openid`,`profile`,`email`,`offline_access`],Db=a({id_token_hint:s().optional(),client_id:s().optional(),post_logout_redirect_uri:Q.optional(),state:s().optional()}),Ob=zd(()=>null),kb=Ob.get,Ab=new WeakMap,jb=`signedQueryIssuedAtMs`;function Mb(e){let t=typeof e==`number`?e:typeof e==`string`?Number(e):void 0;if(!(!t||!Number.isFinite(t)||t<=0))return new Date(t)}var Nb=e=>{let t=e.clientRegistrationAllowedScopes;if(e.clientRegistrationDefaultScopes){let n=t?new Set([...t,...e.clientRegistrationDefaultScopes]):new Set([...e.clientRegistrationDefaultScopes]);t=Array.from(n)}let n=new Set((e.scopes??Eb).filter(e=>e.length));if(t){for(let e of t)if(!n.has(e))throw new B(`clientRegistrationAllowedScope ${e} not found in scopes`)}let r=e.authenticationContext?.acrValuesSupported;if(r&&(r.length===0||r.includes(``)))throw new B(`authenticationContext.acrValuesSupported must list at least one non-empty acr value`);for(let t of e.advertisedMetadata?.scopes_supported??[])if(!n?.has(t))throw new B(`advertisedMetadata.scopes_supported ${t} not found in scopes`);let i=new Set((e.resources??[]).map(e=>typeof e==`string`?e:e.identifier));for(let[t,n]of[[`clientRegistrationDefaultResources`,e.clientRegistrationDefaultResources],[`clientRegistrationAllowedResources`,e.clientRegistrationAllowedResources]])for(let e of n??[])if(!i.has(e))throw new B(`${t} resource ${e} not found in resources`);let o=new Set([`sub`,`iss`,`aud`,`exp`,`iat`,`sid`,`scope`,`azp`,...Im.filter(e=>n.has(Fm[e].scope))]),c={codeExpiresIn:600,accessTokenExpiresIn:3600,m2mAccessTokenExpiresIn:3600,refreshTokenExpiresIn:2592e3,refreshTokenReuseInterval:0,allowUnauthenticatedClientRegistration:!1,allowDynamicClientRegistration:!1,disableJwtPlugin:!1,storeClientSecret:e.disableJwtPlugin?`encrypted`:`hashed`,storeTokens:`hashed`,grantTypes:[`authorization_code`,`client_credentials`,`refresh_token`],...e,scopes:Array.from(n),claims:Array.from(o),clientRegistrationAllowedScopes:t};if(cl(c.extensions),c.pairwiseSecret&&c.pairwiseSecret.length<32)throw new B(`pairwiseSecret must be at least 32 characters long for adequate HMAC-SHA256 security`);if(c.grantTypes&&c.grantTypes.includes(`refresh_token`)&&!c.grantTypes.includes(`authorization_code`))throw new B(`refresh_token grant requires authorization_code grant`);if(c.disableJwtPlugin&&(c.storeClientSecret===`hashed`||typeof c.storeClientSecret==`object`&&`hash`in c.storeClientSecret))throw new B(`unable to store hashed secrets because id tokens will be signed with secret`);if(!c.disableJwtPlugin&&(c.storeClientSecret===`encrypted`||typeof c.storeClientSecret==`object`&&(`encrypt`in c.storeClientSecret||`decrypt`in c.storeClientSecret)))throw new B(`encryption method not recommended, please use 'hashed' or the 'hash' function`);let l=async(e,t)=>{let n=new URL(e.url).pathname,r=t.options.advanced?.skipTrailingSlashes?n.replace(/\/+$/,``)||`/`:n,i=c.disableJwtPlugin?t.baseURL:Ml(t)?.options?.jwt?.issuer??t.baseURL,a=`/`;try{a=new URL(i).pathname.replace(/\/$/,``)||``}catch{a=new URL(t.baseURL).pathname.replace(/\/$/,``)||``}let o={context:t},s=new Set([`/.well-known/oauth-authorization-server${a}`,`${a}/.well-known/oauth-authorization-server`]),l=`${a}/.well-known/openid-configuration`,u=s.has(r),d=c.scopes?.includes(`openid`)&&r===l,f=t=>{let n=ev(t);return e.method===`HEAD`?new Response(null,{status:n.status,headers:n.headers}):n};if((u||d)&&e.method!==`GET`&&e.method!==`HEAD`)return{response:new Response(null,{status:405,headers:{Allow:`GET, HEAD`}})};if(u)return c.scopes?.includes(`openid`)?{response:f(Q_(o,c))}:{response:f(Z_(o,c))};if(d)return{response:f(Q_(o,c))}},u=tv(`/oauth2/authorize`,{method:[`GET`,`POST`],body:a({}).passthrough(),redirectOnError:Zb(c),metadata:{allowedMediaTypes:[`application/x-www-form-urlencoded`],openapi:{description:`Authorize an OAuth 2.1 request from query parameters or an application/x-www-form-urlencoded POST body`,parameters:[{name:`response_type`,in:`query`,required:!1,schema:{type:`string`},description:`OAuth 2.1 response type (e.g., 'code')`},{name:`user_code`,in:`query`,required:!1,schema:{type:`string`},description:`Device user code to approve instead of an authorization request (requires oauthDeviceAuthorization())`},{name:`client_id`,in:`query`,required:!1,schema:{type:`string`},description:`OAuth 2.1 client ID, required for authorization requests (not for user_code)`},{name:`redirect_uri`,in:`query`,required:!1,schema:{type:`string`,format:`uri`},description:`OAuth 2.1 redirect URI`},{name:`scope`,in:`query`,required:!1,schema:{type:`string`},description:`OAuth 2.1 scopes (space-separated)`},{name:`state`,in:`query`,required:!1,schema:{type:`string`},description:`OAuth 2.1 state parameter`},{name:`request_uri`,in:`query`,required:!1,schema:{type:`string`},description:`Pushed Authorization Request URI referencing stored parameters`},{name:`code_challenge`,in:`query`,required:!1,schema:{type:`string`},description:`PKCE code challenge`},{name:`code_challenge_method`,in:`query`,required:!1,schema:{type:`string`},description:`PKCE code challenge method`},{name:`nonce`,in:`query`,required:!1,schema:{type:`string`},description:`OpenID Connect nonce`},{name:`max_age`,in:`query`,required:!1,schema:{type:`integer`,minimum:0},description:`Maximum authentication age in seconds; forces re-authentication when exceeded`},{name:`resource`,in:`query`,required:!1,schema:{type:`array`,items:{type:`string`}},description:`Requested protected resource(s) for the access token. May be supplied multiple times as repeated 'resource' query parameters (RFC 8707) or as an array of strings.`},{name:`prompt`,in:`query`,required:!1,schema:{type:`string`},description:`OAuth2 prompt parameter`}],responses:{302:{description:`Redirect to client with code or error`,headers:{Location:{description:`Redirect URI with code or error`,schema:{type:`string`,format:`uri`}}}},400:{description:`Invalid request`,content:{"application/json":{schema:{type:`object`,properties:{error:{type:`string`},error_description:{type:`string`},state:{type:`string`}},required:[`error`]}}}}}}}},async e=>Qb(e,c,e.authorizeSettings??{isAuthorize:!0})),d=(e,t)=>tm(u,{...e,asResponse:!1,returnHeaders:!1,returnStatus:!1,authorizeSettings:t??{}});return{id:`oauth-provider`,version:Kg,options:c,onRequest:l,init:async e=>{if(e.options.secondaryStorage&&e.options.session?.storeSessionInDatabase!==!0)throw new B("OAuth Provider requires `session.storeSessionInDatabase: true` when using secondaryStorage");if(c.allowClientKeyRotation){let t=e.adapter.id===`memory`?`the memory adapter`:e.options.advanced?.database?.generateId===`serial`?'`advanced.database.generateId: "serial"`':void 0;if(t)throw new B(`\`allowClientKeyRotation\` requires single-use client assertions, which ${t} does not enforce`)}if(await wh(e,c).catch(t=>bh(e,t)),Th(c),!c.disableJwtPlugin){let t=Ml(e)?.options,n=t?.jwt?.issuer??e.baseURL,r=t?.jwt?.issuer==null&&typeof e.options.baseURL==`object`&&e.options.baseURL!==null&&`allowedHosts`in e.options.baseURL;try{new URL(n)}catch(e){if(!r||n!==``)throw e}}return{options:{databaseHooks:{session:{delete:{async before(e,t){if(!t)return;let n=await o_(t,c,{sessionId:e.id,userId:e.userId});if(!n)return;let r=Ab.get(t)??new Map;r.set(e.id,n),Ab.set(t,r)},async after(e,t){if(!t)return;let n=Ab.get(t);if(!n)return;let r=n.get(e.id);if(n.delete(e.id),n.size===0&&Ab.delete(t),!r)return;await u_(r.frontchannelLogoutUris);let i=s_(t,r).catch(e=>{t.context.logger.error(`Logout notification failed after session deletion`,e)});await t.context.runInBackgroundOrAwait(i)}}}}}}},hooks:{before:[{matcher(e){return e.body?.oauth_query},handler:zu(async e=>{let t=e.body.oauth_query;if(!await zl(t,e.context.secret))throw new M(`BAD_REQUEST`,{error:`invalid_signature`});let n=Pe(t);await Ob.set(n),e.path===`/sign-in/social`&&await Xd({query:n.query,...n.signedQueryIssuedAt?{[jb]:n.signedQueryIssuedAt.getTime()}:{}})})}],after:[{matcher(e){return Cf(e.context.responseHeaders?.get(`set-cookie`)||``).has(e.context.authCookies.sessionToken.name)},handler:zu(async e=>{let t=Cf(e.context.responseHeaders?.get(`set-cookie`)||``).get(e.context.authCookies.sessionToken.name)?.value.split(`.`)[0];if(!t)return;let n=await Ob.get(),r=(await qd())?.serverContext,i=n?.query??r?.query;if(!i)return;let a=new URLSearchParams(i),o=await e.context.internalAdapter.findSession(t);if(!o)return;e.context.session=o;let s=e.request?.headers?.get(`sec-fetch-mode`)?.toLowerCase(),c=e.request?.headers?.get(`accept`)?.toLowerCase()??``;s===`navigate`||!s&&(c.includes(`text/html`)||c.includes(`application/xhtml+xml`))||e.headers?.set(`accept`,`application/json`);let l=n?.signedQueryIssuedAt??Mb(r?.[jb]),u=Cu(a,`login`);return Su(o.session.createdAt,l)&&(u=wu(u)),e.query=xu(u),await d(e)})}]},endpoints:{getOAuthServerConfig:X(`/.well-known/oauth-authorization-server`,{method:`GET`,metadata:{SERVER_ONLY:!0}},async e=>c.scopes&&c.scopes.includes(`openid`)?Q_(e,c):Z_(e,c)),getOpenIdConfig:X(`/.well-known/openid-configuration`,{method:`GET`,metadata:{SERVER_ONLY:!0}},async e=>{if(c.scopes&&!c.scopes.includes(`openid`))throw new M(`NOT_FOUND`);return Q_(e,c)}),oauth2Authorize:u,oauth2Consent:X(`/oauth2/consent`,{method:`POST`,body:a({accept:F().meta({description:`Accept or deny user consent for a set of scopes`}),scope:s().optional().meta({description:`List of accept of accepted space-separated scopes. If none is provided, then all originally requested scopes are accepted.`}),claims:Cm.optional().meta({description:`Accepted OIDC claims request object. If none is provided, then all originally requested claims are accepted.`}),reference_id:s().min(1).optional().meta({description:`The reference the user chose for this consent, such as an organization ID. postLogin.consentReferenceId receives it and decides whether to accept it.`}),oauth_query:s().optional().meta({description:`The redirected page's query parameters`})}),use:[xp],metadata:{openapi:{description:`Handle OAuth2 consent`,responses:{200:{description:`Consent processed successfully`,content:{"application/json":{schema:{type:`object`,properties:{redirect:{type:`boolean`,description:"Always true. Indicates the caller should redirect to `url`.",enum:[!0]},url:{type:`string`,format:`uri-reference`,description:`The absolute or relative URI to redirect to next.`}},required:[`redirect`,`url`]}}}}}}}},async e=>Yg(e,c,d)),oauth2Continue:X(`/oauth2/continue`,{method:`POST`,body:a({selected:F().optional().meta({description:`Confirms an account has been selected and authorization can proceed.`}),created:F().optional().meta({description:`Confirms an account was registered`}),postLogin:F().optional().meta({description:`Resumes after the post login page. postLogin.shouldRedirect runs again with isContinuation: true.`}),oauth_query:s().optional().meta({description:`The redirected page's query parameters`})}),use:[xp],metadata:{openapi:{description:`Continues OAuth2 authorization flow`,responses:{200:{description:`Authorization flow continued successfully`,content:{"application/json":{schema:{type:`object`,properties:{redirect:{type:`boolean`,description:"Always true. Indicates the caller should redirect to `url`.",enum:[!0]},url:{type:`string`,format:`uri-reference`,description:`The absolute or relative URI to redirect to next.`}},required:[`redirect`,`url`]}}}}}}}},async e=>Xg(e,d)),oauth2Token:tv(`/oauth2/token`,{method:`POST`,formParams:{repeatable:[`resource`,`audience`]},body:a({grant_type:s().trim().min(1),client_id:s().optional(),client_secret:s().optional(),client_assertion:s().optional(),client_assertion_type:s().optional(),code:s().optional(),code_verifier:s().optional(),redirect_uri:Q.optional(),refresh_token:s().optional(),resource:re([Hm,z(Hm).min(1)]).optional(),scope:s().optional()}).passthrough(),errorCodesByField:{grant_type:{missing:`invalid_request`,invalid:`unsupported_grant_type`},resource:{invalid:`invalid_target`}},metadata:{noStore:!0,allowedMediaTypes:[`application/x-www-form-urlencoded`],openapi:{description:`Obtain an OAuth2.1 access token`,parameters:[{name:`DPoP`,in:`header`,required:!1,schema:{type:`string`},description:`RFC 9449 DPoP proof JWT for issuing DPoP-bound tokens`}],requestBody:{required:!0,content:{"application/json":{schema:{type:`object`,properties:{grant_type:{type:`string`,description:`OAuth2 grant type`},client_id:{type:`string`,description:`OAuth2 client ID`},client_secret:{type:`string`,description:`OAuth2 client secret`},code:{type:`string`,description:`Authorization code (for authorization_code grant)`},code_verifier:{type:`string`,description:`PKCE code verifier (for authorization_code grant)`},redirect_uri:{type:`string`,format:`uri`,description:`Redirect URI (for authorization_code grant)`},refresh_token:{type:`string`,description:`Refresh token (for refresh_token grant)`},resource:{oneOf:[{type:`string`,description:`Single resource (URL)`},{type:`array`,items:{type:`string`},description:`Multiple resources (URLs)`}],description:`Requested protected resource(s) for the access token`},scope:{type:`string`,description:`Requested scopes (for client_credentials grant)`}},required:[`grant_type`]}}}},responses:{200:{description:`Access token response`,content:{"application/json":{schema:{type:`object`,properties:{access_token:{type:`string`,description:`The access token issued by the authorization server`},token_type:{type:`string`,description:`The type of the token issued`,enum:[`Bearer`,`DPoP`]},expires_in:{type:`number`,description:`Lifetime in seconds of the access token`},refresh_token:{type:`string`,description:`Refresh token, if issued`},scope:{type:`string`,description:`Scopes granted by the access token`},id_token:{type:`string`,description:`ID Token (if OpenID Connect)`}},required:[`access_token`,`token_type`,`expires_in`]}}}},400:{description:`Invalid request or error response`,content:{"application/json":{schema:{type:`object`,properties:{error:{type:`string`},error_description:{type:`string`},error_uri:{type:`string`}},required:[`error`]}}}}}}}},async e=>qh(e,c)),oauth2Introspect:tv(`/oauth2/introspect`,{method:`POST`,formParams:{},body:a({client_id:s().optional(),client_secret:s().optional(),client_assertion:s().optional(),client_assertion_type:s().optional(),token:s(),token_type_hint:s().optional()}),metadata:{noStore:!0,allowedMediaTypes:[`application/x-www-form-urlencoded`],openapi:{description:`Introspect an OAuth2 access or refresh token`,requestBody:{required:!0,content:{"application/json":{schema:{type:`object`,properties:{client_id:{type:`string`,description:`OAuth2 client ID`},client_secret:{type:`string`,description:`OAuth2 client secret`},token:{type:`string`,description:`The token to introspect (access or refresh token)`},token_type_hint:{type:`string`,description:"Hint about the token type. Recognized values: `access_token`, `refresh_token`."}},required:[`token`]}}}},responses:{200:{description:`Token introspection response`,content:{"application/json":{schema:{type:`object`,properties:{active:{type:`boolean`,description:`Whether the token is active`},scope:{type:`string`,description:`Scopes associated with the token`},client_id:{type:`string`,description:`Client ID associated with the token`},username:{type:`string`,description:`Username associated with the token`},token_type:{type:`string`,description:`Type of the token`},exp:{type:`number`,description:`Expiration time of the token (seconds since epoch)`},iat:{type:`number`,description:`Issued at time (seconds since epoch)`},nbf:{type:`number`,description:`Not before time (seconds since epoch)`},sub:{type:`string`,description:`Subject of the token`},aud:{type:`string`,description:`Audience of the token`},iss:{type:`string`,description:`Issuer of the token`},jti:{type:`string`,description:`JWT ID`}},required:[`active`]}}}},400:{description:`Invalid request or error response`,content:{"application/json":{schema:{type:`object`,properties:{error:{type:`string`},error_description:{type:`string`},error_uri:{type:`string`}},required:[`error`]}}}}}}}},async e=>Gg(e,c)),oauth2Revoke:tv(`/oauth2/revoke`,{method:`POST`,formParams:{},body:a({client_id:s().optional(),client_secret:s().optional(),client_assertion:s().optional(),client_assertion_type:s().optional(),token:s(),token_type_hint:s().optional()}),metadata:{allowedMediaTypes:[`application/x-www-form-urlencoded`],openapi:{description:`Revoke an OAuth2 access or refresh token`,requestBody:{required:!0,content:{"application/json":{schema:{type:`object`,properties:{client_id:{type:`string`,description:`OAuth2 client ID`},client_secret:{type:`string`,description:`OAuth2 client secret`},token:{type:`string`,description:`The token to revoke (access or refresh token)`},token_type_hint:{type:`string`,description:"Hint about the token type. Recognized values: `access_token`, `refresh_token`."}},required:[`token`]}}}},responses:{200:{description:`Token revoked successfully. The response body is empty.`,content:{"application/json":{schema:{type:`object`,description:`Empty object on success`}}}},400:{description:`Invalid request or error response`,content:{"application/json":{schema:{type:`object`,properties:{error:{type:`string`},error_description:{type:`string`},error_uri:{type:`string`}},required:[`error`]}}}}}}}},async e=>wb(e,c)),oauth2UserInfo:X(`/oauth2/userinfo`,{method:[`GET`,`POST`],body:a({access_token:s().optional()}).passthrough().optional(),metadata:{noStore:!0,allowedMediaTypes:[`application/x-www-form-urlencoded`],openapi:{description:`Get OpenID Connect user information (UserInfo endpoint)`,security:[{bearerAuth:[]},{OAuth2:[`openid`,`profile`,`email`]}],parameters:[{name:`Authorization`,in:`header`,required:!1,schema:{type:`string`},description:`Bearer or DPoP access token`},{name:`DPoP`,in:`header`,required:!1,schema:{type:`string`},description:`RFC 9449 DPoP proof JWT when using a DPoP-bound access token`}],responses:{200:{description:`User information retrieved successfully`,content:{"application/json":{schema:{type:`object`,properties:{sub:{type:`string`,description:`Subject identifier (user ID)`},email:{type:`string`,format:`email`,nullable:!0,description:`User's email address, included if 'email' scope is granted`},name:{type:`string`,nullable:!0,description:`User's full name, included if 'profile' scope is granted`},picture:{type:`string`,format:`uri`,nullable:!0,description:`User's profile picture URL, included if 'profile' scope is granted`},given_name:{type:`string`,nullable:!0,description:`User's given name, included if 'profile' scope is granted`},family_name:{type:`string`,nullable:!0,description:`User's family name, included if 'profile' scope is granted`},email_verified:{type:`boolean`,nullable:!0,description:`Whether the email is verified, included if 'email' scope is granted`}},required:[`sub`]}}}},401:{description:`Unauthorized - invalid or missing access token`,content:{"application/json":{schema:{type:`object`,properties:{error:{type:`string`},error_description:{type:`string`}},required:[`error`]}}}},403:{description:`Forbidden - insufficient scope`,content:{"application/json":{schema:{type:`object`,properties:{error:{type:`string`},error_description:{type:`string`}},required:[`error`]}}}}}}}},async e=>Uh(e,c)),oauth2EndSession:tv(`/oauth2/end-session`,{method:[`GET`,`POST`],body:Db.optional(),query:Db.optional(),metadata:{noStore:!0,allowedMediaTypes:[`application/x-www-form-urlencoded`,`application/json`],$Infer:{body:{},query:{}},openapi:{description:`RP-Initiated Logout endpoint. Accepts standard logout parameters through GET or an application/x-www-form-urlencoded POST body, plus JSON for Better Auth generated-client calls. Requests without a usable id_token_hint may require explicit OP confirmation.`,responses:{200:{description:`Logout completed, or an HTML page was returned for browser navigation — a confirmation page, or the OIDC front-channel logout page when clients with a registered frontchannel_logout_uri hold tokens on the session. A redirect is used only for an exact registered post_logout_redirect_uri.`,content:{"application/json":{schema:{type:`object`,properties:{redirect_uri:{type:`string`,format:`uri`,description:`URI to redirect to after logout (if post_logout_redirect_uri was provided)`},message:{type:`string`,description:`Success message`}}}},"text/html":{schema:{type:`string`,description:`Logout confirmation page, or the OIDC Front-Channel Logout page with one hidden iframe per registered RP`}}}}}}}},async e=>q_(e,c)),oauth2EndSessionConfirmation:tv(`/oauth2/end-session/confirm`,{method:`POST`,body:a({action:xe(`confirm`)}),metadata:{noStore:!0,allowedMediaTypes:[`application/x-www-form-urlencoded`],scope:`http`}},async e=>J_(e,c)),registerOAuthClient:tv(`/oauth2/register`,{method:`POST`,body:Zm.loose(),errorCodesByField:{redirect_uris:`invalid_redirect_uri`,post_logout_redirect_uris:`invalid_redirect_uri`,software_statement:`invalid_software_statement`,resources:`invalid_target`},defaultError:`invalid_client_metadata`,metadata:{noStore:!0,openapi:{description:`Register an OAuth2 application`,responses:{201:{description:`OAuth2 application registered successfully`,content:{"application/json":{schema:{type:`object`,properties:{client_id:{type:`string`,description:`Unique identifier for the client`},client_secret:{type:`string`,description:`Secret key for the client`},client_secret_expires_at:{type:`number`,description:`Time the client secret will expire. If 0, the client secret will never expire.`},scope:{type:`string`,description:`Space-separated scopes allowed by the client`},user_id:{type:`string`,description:`ID of the user who registered the client, null if registered anonymously`},client_id_issued_at:{type:`number`,description:`Creation timestamp of this client`},client_name:{type:`string`,description:`Name of the OAuth2 application`},client_uri:{type:`string`,description:`Name of the OAuth2 application`},logo_uri:{type:`string`,description:`Icon URL for the application`},contacts:{type:`array`,items:{type:`string`},description:`List representing ways to contact people responsible for this client, typically email addresses`},tos_uri:{type:`string`,description:`Client's terms of service uri`},policy_uri:{type:`string`,description:`Client's policy uri`},software_id:{type:`string`,description:`Unique identifier assigned by the developer to help in the dynamic registration process`},software_version:{type:`string`,description:`Version identifier for the software_id`},software_statement:{type:`string`,description:`JWT containing metadata values about the client software as claims`},redirect_uris:{type:`array`,items:{type:`string`,format:`uri`},description:`List of allowed redirect uris`},post_logout_redirect_uris:{type:`array`,items:{type:`string`,format:`uri`},description:`List of allowed logout redirect uris`},backchannel_logout_uri:{type:`string`,format:`uri`,description:`RP URL to receive signed Logout Tokens when the end-user's OP session terminates`},backchannel_logout_session_required:{type:`boolean`,description:"Whether the RP requires a `sid` claim in every Logout Token"},frontchannel_logout_uri:{type:`string`,format:`uri`,description:`RP URL rendered in a hidden iframe on the OP's logout page when the end-user's OP session terminates`},frontchannel_logout_session_required:{type:`boolean`,description:"Whether the RP requires `iss` and `sid` query parameters on its front-channel logout URI. The OP always sends both."},token_endpoint_auth_method:{type:`string`,description:`Requested authentication method for the token endpoint`},grant_types:{type:`array`,items:{type:`string`},description:`Grant types the client may use at the token endpoint`},response_types:{type:`array`,items:{type:`string`,enum:[`code`]},description:`Response types the client may use at the authorization endpoint`},application_type:{type:`string`,description:`OIDC application type used to classify redirect URI policy`,enum:[`web`,`native`]},resources:{type:`array`,items:{type:`string`,format:`uri`},description:`Final resource identifiers linked to the registered client`},disabled:{type:`boolean`,description:`Whether the client is disabled`}},required:[`client_id`]}}}}}}}},async e=>ly(e,c)),adminCreateOAuthClient:Fy(c),createOAuthClient:Iy(c),getOAuthClient:Ly(c),getOAuthClientPublic:Ry(c),getOAuthClientPublicPrelogin:zy(c),getOAuthClients:By(c),adminUpdateOAuthClient:Vy(c),updateOAuthClient:Hy(c),rotateClientSecret:Uy(c),rotateClientKeys:Wy(c),deleteOAuthClient:Gy(c),getOAuthConsent:Zy(c),getOAuthConsents:Qy(c),updateOAuthConsent:$y(c),deleteOAuthConsent:eb(c),adminCreateOAuthResource:mb(c),adminListOAuthResources:hb(c),adminGetOAuthResource:gb(c),adminUpdateOAuthResource:_b(c),adminDeleteOAuthResource:vb(c),adminLinkClientResource:yb(c),adminUnlinkClientResource:bb(c)},schema:vf(structuredClone(Tb),c?.schema),rateLimit:[...c.rateLimit?.token===!1?[]:[{pathMatcher:e=>e===`/oauth2/token`,window:c.rateLimit?.token?.window??60,max:c.rateLimit?.token?.max??20}],...c.rateLimit?.authorize===!1?[]:[{pathMatcher:e=>e===`/oauth2/authorize`,window:c.rateLimit?.authorize?.window??60,max:c.rateLimit?.authorize?.max??30}],...c.rateLimit?.introspect===!1?[]:[{pathMatcher:e=>e===`/oauth2/introspect`,window:c.rateLimit?.introspect?.window??60,max:c.rateLimit?.introspect?.max??100}],...c.rateLimit?.revoke===!1?[]:[{pathMatcher:e=>e===`/oauth2/revoke`,window:c.rateLimit?.revoke?.window??60,max:c.rateLimit?.revoke?.max??30}],...c.rateLimit?.register===!1?[]:[{pathMatcher:e=>e===`/oauth2/register`,window:c.rateLimit?.register?.window??60,max:c.rateLimit?.register?.max??5}],...c.rateLimit?.rotateClientKeys===!1?[]:[{pathMatcher:e=>e===`/oauth2/client/rotate-keys`,window:c.rateLimit?.rotateClientKeys?.window??60,max:c.rateLimit?.rotateClientKeys?.max??5}],...c.rateLimit?.userinfo===!1?[]:[{pathMatcher:e=>e===`/oauth2/userinfo`,window:c.rateLimit?.userinfo?.window??60,max:c.rateLimit?.userinfo?.max??60}]]}};function Pb(e,t,n){return t!==0&&n.getTime()-e.getTime()<=t*1e3}function Fb(e){let{max_age:t,...n}=e;return n}function Ib(e,t,n,r,i,a=`query`){let o=new URLSearchParams({error:t,error_description:n});return r&&o.append(`state`,r),i&&o.append(`iss`,i),a===`fragment`?`${e}#${o.toString()}`:md(e,o)}function Lb(e){let t=typeof e.response_mode==`string`?e.response_mode:void 0;if(t===`fragment`)return`fragment`;if(t===`query`)return`query`;let n=typeof e.response_type==`string`?e.response_type:void 0;return n&&/\b(token|id_token)\b/.test(n)?`fragment`:`query`}var Rb={response_type:{invalid:`unsupported_response_type`},resource:{invalid:`invalid_target`}};function zb(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function Bb(e){return typeof e==`string`?e:void 0}function Vb(e,t){let n=e.method===`POST`&&t?.isAuthorize===!0?e.body:e.query;return{...zb(n)?n:{}}}var $=(e,t)=>{let n=qg(e.request?.headers),r=e.headers?.get(`accept`)?.includes(`application/json`);if(n||r)return{redirect:!0,url:t.toString()};throw e.redirect(t)};function Hb(e,t,n,r,i){return $(e,n.redirect_uri?Ib(n.redirect_uri,r,i,n.state,Gb(e,t)):Kb(e,r,i))}function Ub(e,t,n){if(!(t instanceof g))throw t;let r=t.body,i=r?.error??`invalid_request`,a=r?.error_description??`invalid request`;return n?Ib(n,i,a):Kb(e,i,a)}function Wb(e){try{let t=new URL(e);return t.protocol!==`https:`&&!Gp(t.host)&&(t.protocol=`https:`),t.search=``,t.hash=``,t.toString().replace(/\/$/,``)}catch{return e}}function Gb(e,t){let n;if(t.disableJwtPlugin)n=e.context.baseURL;else try{n=Ml(e.context).options?.jwt?.issuer??e.context.baseURL}catch{n=e.context.baseURL}return Wb(n)}function Kb(e,t,n){return Ib(e.context.options.onAPIError?.errorURL||`${e.context.baseURL}/error`,t,n)}function qb(e){let t;try{t=new URL(e)}catch{return}let n=Wp(t.hostname)||t.hostname===`localhost`;if(t.protocol!==`http:`||!n)return;let r=e.indexOf(`://`);if(r<0)return;let i=r+3,a=e.slice(i).search(/[/?#]/u),o=e.length;a>=0&&(o=i+a);let s=e.slice(i,o),c;if(s.startsWith(`[`)){let t=s.indexOf(`]`);if(t<0)return;if(s[t+1]!==`:`)return e;c=t+1}else if(c=s.lastIndexOf(`:`),c<0)return e;let l=s.slice(c+1);if(!/^\d*$/u.test(l))return;let u=i+c;return`${e.slice(0,u)}${e.slice(o)}`}function Jb(e,t){if(!e||!t)return;let n;try{n=new URL(t)}catch{return}let r=t.includes(`#`),i=n.username.length>0||n.password.length>0;if(r||i)return;let a=qb(t);return e.find(e=>e===t?!0:a?qb(e)===a:!1)}function Yb(e){if(!Q.safeParse(e).success)return!1;let t=new URL(e);return t.username.length===0&&t.password.length===0}async function Xb(e,t,n,r){if(!n||!r)return null;let i;try{i=await Vl(e,t,n)}catch{return null}if(!i||i.disabled)return null;let a=i.redirectUris??[],o=Jb(a,r);if(t.validateRedirectUri){if(!Yb(r))return null;try{return await t.validateRedirectUri(r,a,!!o)?r:null}catch{return null}}return o?r:null}function Zb(e){return async({error:t,error_description:n,ctx:r})=>{let i=r.query??{},a=await Xb(r,e,typeof i.client_id==`string`?i.client_id:void 0,typeof i.redirect_uri==`string`?i.redirect_uri:void 0);return a?$(r,Ib(a,t,n,typeof i.state==`string`?i.state:void 0,Gb(r,e),Lb(i))):$(r,Kb(r,t,n))}}async function Qb(e,t,n){if(!e.request)throw new g(`UNAUTHORIZED`,{error_description:`request not found`,error:`invalid_request`});let r=e.request,i=Vb(e,n),a=ml(t,i);if(a){if(n?.isAuthorize===!0&&!await Z(e))return e.query={[a.parameter]:a.value},nx(e,t,`login`);let o=a.handler.errorPage?.({ctx:e,value:a.value}),s=t=>Ub(e,t,o),c;try{if(c=await a.handler.load({ctx:e,opts:t,value:a.value,signedQuery:n?.isAuthorize===!0?void 0:i}),c.client.disabled)throw new g(`BAD_REQUEST`,{error:`client_disabled`,error_description:`client is disabled`})}catch(t){return $(e,s(t))}return $b(e,t,r.headers,n,{...c,approve:e=>c.approve(e).catch(s),errorURL:s})}if(t.grantTypes&&!t.grantTypes.includes(`authorization_code`))throw new g(`NOT_FOUND`);e.query=i;let o=Bb(i.request),s=Bb(i.request_uri);if(o!==void 0&&s!==void 0)return Zb(t)({error:`invalid_request`,error_description:`request and request_uri cannot be used together`,ctx:e});if(o!==void 0)return Zb(t)({error:`request_not_supported`,error_description:`request object not supported`,ctx:e});if(s!==void 0){let n=Bb(i.client_id);if(!n)return Zb(t)({error:`invalid_request`,error_description:`client_id is required`,ctx:e});if(!t.requestUriResolver)return Zb(t)({error:`request_uri_not_supported`,error_description:`request_uri not supported`,ctx:e});let r=await t.requestUriResolver({requestUri:s,clientId:n,ctx:e});if(!r)return Zb(t)({error:`invalid_request_uri`,error_description:`request_uri is invalid or expired`,ctx:e});let a=i.client_id;i=r,a&&(i.client_id=a)}e.query=i;let c=Jm.safeParse(i);if(!c.success){let n=nv(c.error.issues,Rb);return Zb(t)({...n,ctx:e})}if(i=c.data,e.query=i,await Ob.set({query:ex(i).toString()}),!i.response_type)return Zb(t)({error:`invalid_request`,error_description:`response_type is required`,ctx:e});if((e.query?.prompt?mu(e.query?.prompt):void 0)?.has(`select_account`)&&!t.selectAccount?.page)return $(e,Kb(e,`unsupported_prompt_select_account`,`unsupported prompt type`));if(i.response_type!==`code`)return $(e,Kb(e,`unsupported_response_type`,`unsupported response type`));let l=await Vl(e,t,i.client_id);if(!l)return $(e,Kb(e,`invalid_client`,`client not found`));if(l.disabled)return $(e,Kb(e,`client_disabled`,`client is disabled`));if(!iu(l,`authorization_code`))return $(e,Kb(e,`unauthorized_client`,`client is not authorized to use the authorization_code grant`));let u=l.redirectUris??[],d=!1;if(i.redirect_uri){let e=!!Jb(u,i.redirect_uri);if(t.validateRedirectUri&&Yb(i.redirect_uri))try{d=await t.validateRedirectUri(i.redirect_uri,u,e)}catch{d=!1}else t.validateRedirectUri||(d=e)}if(!d)return $(e,Kb(e,`invalid_redirect`,`invalid redirect uri`));let f=i.scope?.split(` `).filter(e=>e);if(f){let n=new Set(l.scopes??t.scopes),r=f.filter(e=>!n?.has(e));if(r.length)return $(e,Ib(i.redirect_uri,`invalid_scope`,`The following scopes are invalid: ${r.join(`, `)}`,i.state,Gb(e,t)))}f||(f=l.scopes??t.scopes??[],i.scope=f.join(` `));let p=f.includes(`openid`);if(i.claims!==void 0&&!p)return $(e,Ib(i.redirect_uri,`invalid_request`,`openid scope must be requested when using the claims parameter`,i.state,Gb(e,t)));if(p&&!wm(i.claims))return $(e,Ib(i.redirect_uri,`invalid_request`,`claims must be a valid Claims request object`,i.state,Gb(e,t)));if(p&&!km(t).some(e=>Em(i.claims,e)))return $(e,Ib(i.redirect_uri,`access_denied`,`essential acr requirement cannot be met`,i.state,Gb(e,t)));if(i.resource!==void 0)try{await sh(e,t,{resource:i.resource,clientId:l.clientId,requestedScopes:f})}catch(n){if(n instanceof g){let r=n.body?.error??`invalid_target`,a=n.body?.error_description??`requested resource invalid`;return $(e,Ib(i.redirect_uri,r,a,i.state,Gb(e,t)))}throw n}let m=Tu(l,{scopes:f,nonce:i.nonce});if(m&&(!i.code_challenge||!i.code_challenge_method))return $(e,Ib(i.redirect_uri,`invalid_request`,m.valueOf(),i.state,Gb(e,t)));if(i.code_challenge||i.code_challenge_method){if(!i.code_challenge||!i.code_challenge_method)return $(e,Ib(i.redirect_uri,`invalid_request`,`code_challenge and code_challenge_method must both be provided`,i.state,Gb(e,t)));if(![`S256`].includes(i.code_challenge_method))return $(e,Ib(i.redirect_uri,`invalid_request`,`invalid code_challenge method, only S256 is supported`,i.state,Gb(e,t)))}return $b(e,t,r.headers,n,{query:i,client:l,approve:n=>tx(e,t,{...n,query:n.query,clientId:l.clientId,resource:Fl(n.query.resource)??[]})})}async function $b(e,t,n,r,i){let{query:a}=i,{client:o}=i;e.query=a;let s=a.scope?.split(` `).filter(e=>e)??[],c=Tm(a.claims,Lm(t)),l=Fl(a.resource)??[],u=a.prompt?mu(a.prompt):void 0,d=u?.has(`none`)??!1,f=await Z(e),p=a.max_age,m=f!=null&&p!==void 0&&Pb(new Date(f.session.createdAt),p,new Date);if(!f||f!=null&&p!==void 0&&!m||u?.has(`login`)||u?.has(`create`))return d?Hb(e,t,a,`login_required`,`authentication required`):nx(e,t,u?.has(`create`)?`create`:`login`);m&&(a=Fb(a),e.query=a);let h=()=>({user:f.user,session:f.session,scopes:s,query:ex(a)});if(r?.isAuthorize&&u?.has(`select_account`))return nx(e,t,`select_account`);if(r?.isAuthorize&&t.selectAccount&&await t.selectAccount.shouldRedirect({headers:n,...h()}))return d?Hb(e,t,a,`account_selection_required`,`End-User account selection is required`):nx(e,t,`select_account`);if(t.signup?.shouldRedirect){let r=await t.signup.shouldRedirect({headers:n,...h()});if(r)return d?Hb(e,t,a,`interaction_required`,`End-User interaction is required`):nx(e,t,`create`,{page:typeof r==`string`?r:void 0})}if(!r?.postLogin&&t.postLogin&&await t.postLogin.shouldRedirect({headers:n,...h(),isContinuation:r?.isPostLoginContinuation??!1}))return d?Hb(e,t,a,`interaction_required`,`End-User interaction is required`):nx(e,t,`post_login`);if(u?.has(`consent`)||i.requireConsent&&!r?.acceptedConsent)return nx(e,t,`consent`,{sessionId:f.session.id});let _=r?.acceptedConsent?r.acceptedConsent.referenceId:await yu(t,h()),v=async()=>{let r;try{r=await jm(t,{user:f.user,session:f.session,client:o,scopes:s,headers:n,query:a})}catch(n){if(!(n instanceof g))throw n;if(i.errorURL)return $(e,i.errorURL(n));let r=n.body;return Hb(e,t,a,r?.error??`server_error`,r?.error_description??`authentication context unavailable`)}return Em(a.claims,r.acr??`0`)?$(e,await i.approve({query:a,userId:f.user.id,sessionId:f.session.id,authTime:new Date(f.session.createdAt).getTime(),...r,referenceId:_})):Hb(e,t,a,`access_denied`,`essential acr requirement cannot be met`)};if(o.skipConsent)return v();let y=await bu(e,o.clientId,f.user.id,_);return!y||!su(y,s,l)||!c.every(e=>(y.requestedUserInfoClaims??[]).includes(e))?d?Hb(e,t,a,`consent_required`,`End-User consent is required`):nx(e,t,`consent`,{sessionId:f.session.id}):v()}function ex(e){let t=new URLSearchParams;for(let[n,r]of Object.entries(e))if(r!=null){if(Array.isArray(r))for(let e of r)t.append(n,String(e));else n===`claims`&&typeof r==`object`?t.set(n,JSON.stringify(r)):t.set(n,String(r))}return t}async function tx(e,t,n){let r=zi(32,`a-z`,`A-Z`,`0-9`),i=Math.floor(Date.now()/1e3),a=i+(t.codeExpiresIn??600),o={identifier:await ql(t.storeTokens,r,`authorization_code`),updatedAt:new Date(i*1e3),expiresAt:new Date(a*1e3),value:JSON.stringify({type:`authorization_code`,query:n.query,userId:n.userId,sessionId:n?.sessionId,referenceId:n.referenceId,authTime:n.authTime,acr:n.acr,amr:n.amr,resource:n.resource})};await e.context.internalAdapter.createVerificationValue({...o,createdAt:new Date(i*1e3)});let s=new URL(n.query.redirect_uri);return s.searchParams.set(`code`,r),n.query.state&&s.searchParams.set(`state`,n.query.state),s.searchParams.set(`iss`,Gb(e,t)),s.toString()}async function nx(e,t,n,r){let i=await rx(e,t,{postLoginClearedForSession:n===`consent`&&t.postLogin?r?.sessionId:void 0}),a=t.loginPage;if(n===`select_account`)a=t.selectAccount?.page??t.loginPage;else if(n===`post_login`){if(!t.postLogin?.page)throw new g(`INTERNAL_SERVER_ERROR`,{error_description:`postLogin should have been defined`});a=t.postLogin?.page}else n===`consent`?a=t.consentPage:n===`create`&&(a=t.signup?.page??t.loginPage);return $(e,`${r?.page??a}?${i}`)}async function rx(e,t,n){let r=Date.now(),i=Math.floor(r/1e3)+(t.codeExpiresIn??600),a=ex(e.query);a.set(`exp`,String(i)),a.set(Oe,String(r)),a.delete(`sig`),a.delete(ke),n?.postLoginClearedForSession&&a.set(ke,n.postLoginClearedForSession),Me(a);let o=await Ya(je(a).toString(),e.context.secret);return a.set(`sig`,o),a.toString()}export{lf as $,cs as $t,Ep as A,Vl as At,$f as B,cu as Bt,Cp as C,Be as Cn,qu as Ct,wp as D,Nu as Dt,yp as E,Pu as Et,gp as F,Nl as Ft,uf as G,ys as Gt,Vf as H,sc as Ht,up as I,ou as It,ff as J,ds as Jt,_f as K,vs as Kt,dp as L,eu as Lt,xp as M,jl as Mt,lp as N,Jc as Nt,Dp as O,Eu as Ot,_p as P,nu as Pt,mf as Q,ls as Qt,pp as R,Fl as Rt,jp as S,Qe as Sn,dd as St,Z as T,zu as Tt,Bf as U,rc as Ut,Uf as V,zl as Vt,yf as W,Ss as Wt,gf as X,fs as Xt,hf as Y,ps as Yt,df as Z,us as Zt,im as _,yt as _n,id as _t,Hm as a,Ri as an,Vd as at,Gp as b,pt as bn,ad as bt,sh as c,Si as cn,Ud as ct,pm as d,yi as dn,Pd as dt,ss as en,$d as et,dm as f,Xr as fn,kd as ft,om as g,V as gn,td as gt,cm as h,Dt as hn,fd as ht,_v as i,zi as in,Kd as it,Sp as j,El as jt,Tp as k,dl as kt,mm as l,xi as ln,Id as lt,sm as m,wr as mn,md as mt,Nb as n,Ka as nn,Qd as nt,Jh as o,Ei as on,Wd as ot,lm as p,Gr as pn,Nd as pt,vf as q,ms as qt,by as r,Vi as rn,Jd as rt,Qm as s,Ci as sn,Hd as st,kb as t,qa as tn,tf as tt,fm as u,bi as un,Rd as ut,tm as v,xt as vn,nd as vt,vp as w,we as wn,X as wt,Kp as x,gt as xn,od as xt,Yp as y,ft as yn,rd as yt,rp as z,au as zt};
|
|
56
|
-
//# sourceMappingURL=authorize-DXYo-K2n-rmQQ42x1.js.map
|