@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.
Files changed (120) hide show
  1. package/dist/app/server/.vite/manifest.json +65 -65
  2. package/dist/app/server/assets/Grant-D_tun0mF.js.map +1 -1
  3. package/dist/app/server/assets/authorize-DXYo-K2n-B-6vqhvc.js +56 -0
  4. package/dist/app/server/assets/authorize-DXYo-K2n-B-6vqhvc.js.map +1 -0
  5. package/dist/app/server/assets/core-FSS9-r35.js +56 -0
  6. package/dist/app/server/assets/core-FSS9-r35.js.map +1 -0
  7. package/dist/app/server/assets/default-u_dwuiYb-Bby14ucv.js +2 -0
  8. package/dist/app/server/assets/{default-u_dwuiYb-DOrMMcg9.js.map → default-u_dwuiYb-Bby14ucv.js.map} +1 -1
  9. package/dist/app/server/assets/{dist-CoH0hD1s.js → dist-B9KiBJYw.js} +2 -2
  10. package/dist/app/server/assets/{dist-CoH0hD1s.js.map → dist-B9KiBJYw.js.map} +1 -1
  11. package/dist/app/server/assets/{dist-DcICI3fd.js → dist-CU1NXSiz.js} +2 -2
  12. package/dist/app/server/assets/{dist-DcICI3fd.js.map → dist-CU1NXSiz.js.map} +1 -1
  13. package/dist/app/server/assets/dist-CetH4JSY.js +1 -0
  14. package/dist/app/server/assets/{effect-QlVUlMFu-mXPkuQTb.js → effect-QlVUlMFu-Cm-eTtaO.js} +2 -2
  15. package/dist/app/server/assets/{effect-QlVUlMFu-mXPkuQTb.js.map → effect-QlVUlMFu-Cm-eTtaO.js.map} +1 -1
  16. package/dist/app/server/assets/factory-g3i_Ffi5.js +5 -0
  17. package/dist/app/server/assets/{factory-dvoOlKer.js.map → factory-g3i_Ffi5.js.map} +1 -1
  18. package/dist/app/server/assets/get-id-field-BpOAoqqI.js +6 -0
  19. package/dist/app/server/assets/get-id-field-BpOAoqqI.js.map +1 -0
  20. package/dist/app/server/assets/{index-CLddUTqr-CC33CMvS.js → index-CLddUTqr-CmgkbWi9.js} +2 -2
  21. package/dist/app/server/assets/{index-CLddUTqr-CC33CMvS.js.map → index-CLddUTqr-CmgkbWi9.js.map} +1 -1
  22. package/dist/app/server/assets/{index-DZEfthgZ-Ec2MMQ_e.js → index-DZEfthgZ-BnPmps9O.js} +2 -2
  23. package/dist/app/server/assets/{index-DZEfthgZ-Ec2MMQ_e.js.map → index-DZEfthgZ-BnPmps9O.js.map} +1 -1
  24. package/dist/app/server/assets/kysely-adapter-B8VoPArC.js +1 -0
  25. package/dist/app/server/assets/{schema-check-oLqvHR8y.js → schema-check-Bgwl1v0_.js} +2 -2
  26. package/dist/app/server/assets/{schema-check-oLqvHR8y.js.map → schema-check-Bgwl1v0_.js.map} +1 -1
  27. package/dist/app/server/assets/{sury-CWZTCd75-CDaOS2oM.js → sury-CWZTCd75-Bd_PzqCV.js} +2 -2
  28. package/dist/app/server/assets/{sury-CWZTCd75-CDaOS2oM.js.map → sury-CWZTCd75-Bd_PzqCV.js.map} +1 -1
  29. package/dist/app/server/assets/{valibot--1zFm7rT-CIKoH3MS.js → valibot--1zFm7rT-Dd2aEhWG.js} +2 -2
  30. package/dist/app/server/assets/{valibot--1zFm7rT-CIKoH3MS.js.map → valibot--1zFm7rT-Dd2aEhWG.js.map} +1 -1
  31. package/dist/app/server/assets/{valibot-D_HTw1Gn-BdPyLkXt.js → valibot-D_HTw1Gn-C1l3va6F.js} +2 -2
  32. package/dist/app/server/assets/{valibot-D_HTw1Gn-BdPyLkXt.js.map → valibot-D_HTw1Gn-C1l3va6F.js.map} +1 -1
  33. package/dist/app/server/assets/{zod-Bwrt9trS-BezI5Gi1.js → zod-Bwrt9trS-Dry2w0in.js} +2 -2
  34. package/dist/app/server/assets/{zod-Bwrt9trS-BezI5Gi1.js.map → zod-Bwrt9trS-Dry2w0in.js.map} +1 -1
  35. package/dist/app/server/assets/{zod-DSgpEGAE-DZ7M_Q33.js → zod-DSgpEGAE-BZMP86UA.js} +2 -2
  36. package/dist/app/server/assets/{zod-DSgpEGAE-DZ7M_Q33.js.map → zod-DSgpEGAE-BZMP86UA.js.map} +1 -1
  37. package/dist/app/server/index.js +35 -35
  38. package/dist/app/server/index.js.map +1 -1
  39. package/dist/client/Auth.d.ts +1 -1
  40. package/dist/client/Auth.d.ts.map +1 -1
  41. package/dist/client/Auth.js.map +1 -1
  42. package/dist/client/Decorator.d.ts +3 -1
  43. package/dist/client/Decorator.d.ts.map +1 -1
  44. package/dist/client/Decorator.js +1 -0
  45. package/dist/client/Decorator.js.map +1 -1
  46. package/dist/client/actions/passkey.d.ts +63 -2
  47. package/dist/client/actions/passkey.d.ts.map +1 -1
  48. package/dist/client/actions/passkey.js +121 -3
  49. package/dist/client/actions/passkey.js.map +1 -1
  50. package/dist/internal/Apps.d.ts +14 -0
  51. package/dist/internal/Apps.d.ts.map +1 -1
  52. package/dist/internal/Apps.js +14 -2
  53. package/dist/internal/Apps.js.map +1 -1
  54. package/dist/internal/Auth.d.ts +7 -0
  55. package/dist/internal/Auth.d.ts.map +1 -1
  56. package/dist/internal/Auth.js +2 -1
  57. package/dist/internal/Auth.js.map +1 -1
  58. package/dist/internal/Authorize.d.ts.map +1 -1
  59. package/dist/internal/Authorize.js +13 -13
  60. package/dist/internal/Authorize.js.map +1 -1
  61. package/dist/internal/ErrorResponse.d.ts +5 -0
  62. package/dist/internal/ErrorResponse.d.ts.map +1 -1
  63. package/dist/internal/ErrorResponse.js +8 -0
  64. package/dist/internal/ErrorResponse.js.map +1 -1
  65. package/dist/internal/KeyAuthorization.d.ts.map +1 -1
  66. package/dist/internal/KeyAuthorization.js +28 -28
  67. package/dist/internal/KeyAuthorization.js.map +1 -1
  68. package/dist/internal/Owner.d.ts +16 -0
  69. package/dist/internal/Owner.d.ts.map +1 -1
  70. package/dist/internal/Owner.js.map +1 -1
  71. package/dist/internal/Passkey.d.ts +66 -4
  72. package/dist/internal/Passkey.d.ts.map +1 -1
  73. package/dist/internal/Passkey.js +66 -30
  74. package/dist/internal/Passkey.js.map +1 -1
  75. package/dist/internal/Privy.d.ts +27 -0
  76. package/dist/internal/Privy.d.ts.map +1 -1
  77. package/dist/internal/Privy.js +82 -0
  78. package/dist/internal/Privy.js.map +1 -1
  79. package/dist/internal/TempoAccount.d.ts +57 -0
  80. package/dist/internal/TempoAccount.d.ts.map +1 -1
  81. package/dist/internal/TempoAccount.js +118 -5
  82. package/dist/internal/TempoAccount.js.map +1 -1
  83. package/dist/internal/owners/Privy.d.ts.map +1 -1
  84. package/dist/internal/owners/Privy.js +11 -2
  85. package/dist/internal/owners/Privy.js.map +1 -1
  86. package/package.json +1 -1
  87. package/src/api/account.ts +140 -103
  88. package/src/api/authenticate.ts +48 -51
  89. package/src/api/authorize.ts +35 -36
  90. package/src/api/device.ts +20 -23
  91. package/src/api/health.ts +1 -2
  92. package/src/api/lib/AccountStep.ts +75 -0
  93. package/src/api/lib/Auth.ts +6 -0
  94. package/src/api/lib/Cors.ts +3 -0
  95. package/src/api/lib/KeySigner.ts +1 -1
  96. package/src/api/oauth.ts +23 -22
  97. package/src/client/Auth.ts +1 -0
  98. package/src/client/Decorator.ts +6 -1
  99. package/src/client/actions/passkey.ts +197 -3
  100. package/src/internal/Apps.ts +26 -2
  101. package/src/internal/Auth.ts +4 -0
  102. package/src/internal/Authorize.ts +13 -15
  103. package/src/internal/ErrorResponse.ts +10 -0
  104. package/src/internal/KeyAuthorization.ts +28 -31
  105. package/src/internal/OpenApi.ts +35 -0
  106. package/src/internal/Owner.ts +16 -0
  107. package/src/internal/Passkey.ts +99 -34
  108. package/src/internal/Privy.ts +128 -0
  109. package/src/internal/TempoAccount.ts +221 -7
  110. package/src/internal/owners/Privy.ts +19 -6
  111. package/dist/app/server/assets/authorize-DXYo-K2n-rmQQ42x1.js +0 -56
  112. package/dist/app/server/assets/authorize-DXYo-K2n-rmQQ42x1.js.map +0 -1
  113. package/dist/app/server/assets/core-BBrZXfrB.js +0 -56
  114. package/dist/app/server/assets/core-BBrZXfrB.js.map +0 -1
  115. package/dist/app/server/assets/default-u_dwuiYb-DOrMMcg9.js +0 -2
  116. package/dist/app/server/assets/dist-CR6FW-yS.js +0 -1
  117. package/dist/app/server/assets/factory-dvoOlKer.js +0 -5
  118. package/dist/app/server/assets/get-id-field-OwLpfjj2.js +0 -6
  119. package/dist/app/server/assets/get-id-field-OwLpfjj2.js.map +0 -1
  120. package/dist/app/server/assets/kysely-adapter-B8tQwTcu.js +0 -1
@@ -0,0 +1,56 @@
1
+ import{r as e}from"./rolldown-runtime-BWaJ3C7D.js";import{Zt as t}from"./core-FSS9-r35.js";import{$ as n,At as r,B as i,Ct as a,D as o,E as s,Et 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,Mt as _,Ot as v,P as y,Q as b,R as x,St as S,T as C,Tt as w,U as T,Ut as E,V as D,W as O,Wt as k,Y as A,Z as j,a as M,at as N,b as P,bt as F,cr as I,ct as L,d as R,et as ee,f as te,ft as z,h as ne,ht as re,it as ie,j as ae,jt as oe,l as se,m as ce,o as le,ot as ue,p as de,q as fe,rr as pe,rt as me,st as he,t as ge,tt as _e,ut as B,vt as ve,w as ye,wt as V,x as H,xt as be,yt as xe,z as Se}from"./get-id-field-BpOAoqqI.js";import{a as Ce}from"./schema-check-Bgwl1v0_.js";function we(e){return k(he,e)}function Te(e){return f(me,e)}function Ee(e){return E(ie,e)}var De=Object.defineProperty,Oe=(e,t)=>{let n={};for(var r in e)De(n,r,{get:e[r],enumerable:!0});return t||De(n,Symbol.toStringTag,{value:`Module`}),n},ke=`ba_iat`,Ae=`ba_pl`,je=`ba_param`;function Me(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 Ne(e){e.delete(je);let t=[...new Set([...e.keys(),je])].sort();for(let n of t)e.append(je,n)}function Pe(e){let t=new URLSearchParams(e).get(ke);if(!t)return null;let n=Number(t);return!Number.isFinite(n)||n<=0?null:new Date(n)}function Fe(e){let t=new URLSearchParams(e),n=t.get(`ba_pl`)??void 0;for(let e of[`sig`,`exp`,ke,je,Ae])t.delete(e);return{query:t.toString(),signedQueryIssuedAt:Pe(e)??void 0,postLoginClearedForSession:n}}var Ie=class{oHash;iHash;blockLen;outputLen;canXOF=!1;finished=!1;destroyed=!1;constructor(e,t){if(fe(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),j(r)}update(e){return h(this),this.iHash.update(e),this}digestInto(e){h(this),A(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()}},Le=(()=>{let e=((e,t,n)=>new Ie(e,t).update(n).digest());return e.create=(e,t)=>new Ie(e,t),e})(),Re=Uint8Array.of(0),ze=Uint8Array.of();function Be(e,t,n,r=32,i){fe(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=ze:u(n,void 0,`info`),!o)return i&&j(t),new Uint8Array;let s=i&&o===1?t:new Uint8Array(o*a),{iHash:c,oHash:l}=Le.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++){Re[0]=e+1;let t=c._cloneInto(f);e&&t.update(d),t.update(n).update(Re).digestInto(d),l._cloneInto(f).update(d).digestInto(d),s.set(d,a*e)}if(Re[0]=o,o>1&&c.update(d),c.update(n).update(Re).digestInto(d),l.update(d).digestInto(d),s.set(d,a*(o-1)),c.destroy(),l.destroy(),f?.destroy(),d!==s&&j(d),j(Re),r===s.length)return s;let p=s.slice(0,r);return j(s),p}var Ve=(e,t,n,r,i)=>{fe(e),n===void 0&&(n=new Uint8Array(e.outputLen));let a=Le.create(e,n).update(t);return Be(e,a.digest(),r,i,a)},He=e=>e/2**32|0,Ue=e=>e>>>0;function We(e,t,n,r){let i=He(n),a=Ue(n);e.setUint32(t,r?a:i,r),e.setUint32(t+4,r?i:a,r)}function Ge(e,t,n){return e&t^~e&n}function Ke(e,t,n){return e&t^e&n^t&n}var qe=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),A(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)),We(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()}},Je=Uint32Array.from([1779033703,3144134277,1013904242,2773480762,1359893119,2600822924,528734635,1541459225]),Ye=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]),Xe=new Uint32Array(64),Ze=class extends qe{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)Xe[n]=e.getUint32(t,!1);for(let e=16;e<64;e++){let t=Xe[e-15],n=Xe[e-2],r=_e(t,7)^_e(t,18)^t>>>3,i=_e(n,17)^_e(n,19)^n>>>10;Xe[e]=i+Xe[e-7]+r+Xe[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=_e(o,6)^_e(o,11)^_e(o,25),u=l+t+Ge(o,s,c)+Ye[e]+Xe[e]|0,d=(_e(n,2)^_e(n,13)^_e(n,22))+Ke(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(){j(Xe)}destroy(){this.destroyed=!0,this.set(0,0,0,0,0,0,0,0),j(this.buffer)}},Qe=class extends Ze{constructor(){super(32,Je)}},$e=b(()=>new Qe,ee(1)),et=new TextEncoder,tt=new TextDecoder,nt=new TextDecoder(`utf-8`,{fatal:!0}),rt=2**32;function it(...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 at(e,t,n){if(t<0||t>=rt)throw RangeError(`value must be >= 0 and <= ${rt-1}. Received ${t}`);e.set([t>>>24,t>>>16,t>>>8,t&255],n)}function ot(e){let t=Math.floor(e/rt),n=e%rt,r=new Uint8Array(8);return at(r,t,0),at(r,n,4),r}function st(e){let t=new Uint8Array(4);return at(t,e),t}var ct=/[^\x00-\x7f]/;function lt(e){if(typeof e==`string`&&e.length>=128){if(ct.test(e))throw TypeError(`non-ASCII string encountered in encode()`);return et.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 ut(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 dt(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 ft(e,t){let n=`SHA-${e.slice(-3)}`;return new Uint8Array(await crypto.subtle.digest(n,t))}var pt=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)}},mt=class extends pt{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}},ht=class extends pt{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}},gt=class extends pt{static code=`ERR_JOSE_ALG_NOT_ALLOWED`;code=`ERR_JOSE_ALG_NOT_ALLOWED`},U=class extends pt{static code=`ERR_JOSE_NOT_SUPPORTED`;code=`ERR_JOSE_NOT_SUPPORTED`},_t=class extends pt{static code=`ERR_JWE_DECRYPTION_FAILED`;code=`ERR_JWE_DECRYPTION_FAILED`;constructor(e=`decryption operation failed`,t){super(e,t)}},W=class extends pt{static code=`ERR_JWE_INVALID`;code=`ERR_JWE_INVALID`},G=class extends pt{static code=`ERR_JWS_INVALID`;code=`ERR_JWS_INVALID`},vt=class extends pt{static code=`ERR_JWT_INVALID`;code=`ERR_JWT_INVALID`},yt=class extends pt{static code=`ERR_JWK_INVALID`;code=`ERR_JWK_INVALID`},bt=class extends pt{static code=`ERR_JWKS_INVALID`;code=`ERR_JWKS_INVALID`},xt=class extends pt{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)}},St=class extends pt{[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)}},Ct=class extends pt{static code=`ERR_JWKS_TIMEOUT`;code=`ERR_JWKS_TIMEOUT`;constructor(e=`request timed out`,t){super(e,t)}},wt=class extends pt{static code=`ERR_JWS_SIGNATURE_VERIFICATION_FAILED`;code=`ERR_JWS_SIGNATURE_VERIFICATION_FAILED`;constructor(e=`signature verification failed`,t){super(e,t)}},Tt=`The input to be decoded is not correctly encoded.`;function Et(e){try{return dt(typeof e==`string`?e:tt.decode(e),!0)}catch(e){throw TypeError(Tt,{cause:e})}}function K(e){return ut(typeof e==`string`?et.encode(e):e,!0)}function Dt(e,t){if(!(e instanceof Uint8Array))throw TypeError(`${t} must be an instance of Uint8Array`)}function Ot(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 kt(e){return Ot(e)&&Array.isArray(e.keys)&&Array.from(e.keys).every(Ot)}function At(...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 jt(e,t){if(e!==void 0)throw TypeError(`${t} can only be called once`)}function Mt(e,t,n){try{return Et(e)}catch{throw new n(`Failed to base64url decode the ${t}`)}}function Nt(e,t,n){try{return lt(e)}catch{throw new n(`The ${t} is not a valid base64url string`)}}function Pt(e,t,n){let r;try{r=JSON.parse(nt.decode(Et(e)))}catch{throw new t(n)}if(!Ot(r))throw new t(n);return r}var Ft={__proto__:null,b64:!0},It={__proto__:null};function Lt(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 Rt(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 zt(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 U(`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 Bt(e,t){if(t.includes(`b64`)){let t=e.b64;if(typeof t!=`boolean`)throw new G(`The "b64" (base64url-encode payload) Header Parameter must be a boolean`);return t}return!0}function Vt(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(!Ot(r))throw new e(`JOSE Header is not a JSON object`);return[r,n]}var Ht=e=>e[Symbol.toStringTag],Ut=(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 Wt(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(Ot(t)){if(o=on(t),typeof o.kty!=`string`)throw $t(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(Ut(e,o,n),o.kty===`oct`)return Et(o.k);if(!Object.isFrozen(t)){let{key_ops:e}=t;Array.isArray(e)&&Object.freeze(e),Object.freeze(t)}}else{if(!Xt(t))throw $t(r,t,i);let e=i?`secret`:a?`private`:`public`;if(t.type!==e&&(i||[`secret`,`public`,`private`].includes(t.type)))throw TypeError(`${Ht(t)} instances must be of type "${e}" for the ${r} algorithm`);if(Jt(t))return t;if(s=t,s.type===`secret`)return s.export()}Gt||=new WeakMap;let c=t,l=Gt.get(c);if(l?.[r])return l[r];if(l||Gt.set(c,l={}),s&&typeof s.toCryptoKey==`function`){let t=s.type===`public`,n=Kt[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 cn(e,o)}var Gt,Kt={__proto__:null,prime256v1:`P-256`,secp384r1:`P-384`,secp521r1:`P-521`};function qt(e){if(!Jt(e))throw Error(`CryptoKey instance expected`)}var Jt=e=>{if(e?.[Symbol.toStringTag]===`CryptoKey`)return!0;try{return e instanceof CryptoKey}catch{return!1}},Yt=e=>e?.[Symbol.toStringTag]===`KeyObject`,Xt=e=>Jt(e)||Yt(e);function Zt(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 Qt=(e,...t)=>Zt(`Key must be `,e,...t);function $t(e,t,n){let r=[`CryptoKey`,`KeyObject`,`JSON Web Key`];return n&&r.push(`Uint8Array`),TypeError(Zt(`Key for the ${e} algorithm must be `,t,...r))}var en=(e,t=`algorithm.name`)=>TypeError(`CryptoKey does not support this operation, its ${t} must be ${e}`);function tn(e,t){if(t&&!e.usages.includes(t))throw TypeError(`CryptoKey does not support this operation, its usages must include ${t}.`)}function nn(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 rn(e,t,n){let r=e.algorithm;if(r.name!==t.name)throw en(t.name);if(t.hash&&r.hash?.name!==t.hash)throw en(t.hash,`algorithm.hash`);if(t.namedCurve&&r.namedCurve!==t.namedCurve)throw en(t.namedCurve,`algorithm.namedCurve`);if(t.length!==void 0&&r.length!==t.length)throw en(t.length,`algorithm.length`);tn(e,n)}function an(e){return{__proto__:null,...e}}function on(e){let t=an(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 sn(e){if(e!==void 0&&typeof e!=`boolean`)throw TypeError(`"extractable" option must be a boolean`);return e}async function cn(e,t,n){if(!e.kty.includes(t.kty))throw new U(`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 ln(e,t,n,r=!1){return e instanceof Uint8Array&&(e=await crypto.subtle.importKey(`raw`,e,t,r,[n])),rn(e,t,n),e}var un=e=>crypto.getRandomValues(new Uint8Array(e.cekBits>>3));function dn(e,t){let n=e.byteLength<<3;if(n!==t)throw new W(`Invalid Content Encryption Key length. Expected ${t} bits, got ${n} bits`)}var fn=e=>crypto.getRandomValues(new Uint8Array(e.ivBits>>3));function pn(e,t){if(t.length<<3!==e.ivBits)throw new W(`Invalid Initialization Vector length`)}async function mn(e,t,n){if(!(t instanceof Uint8Array))throw TypeError(Qt(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 hn(e,t,n){return new Uint8Array((await crypto.subtle.sign(`HMAC`,e,t)).slice(0,n>>3))}async function gn(e,t,n,r,i){let[a,o,s]=await mn(e,n,`encrypt`),c=new Uint8Array(await crypto.subtle.encrypt({iv:r,name:`AES-CBC`},a,t));return{ciphertext:c,tag:await hn(o,it(i,r,c,ot(i.length*8)),s),iv:r}}async function _n(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 vn(e,t,n,r,i,a){let[o,s,c]=await mn(e,t,`decrypt`),l=await hn(s,it(a,r,n,ot(a.length*8)),c);try{if(await _n(i,l))return new Uint8Array(await crypto.subtle.decrypt({iv:r,name:`AES-CBC`},o,n))}catch{}throw new _t}async function yn(e,t,n,r,i){if(!Jt(n)&&!(n instanceof Uint8Array))throw TypeError(Qt(n,`CryptoKey`,`KeyObject`,`Uint8Array`,`JSON Web Key`));if(r?pn(e,r):r=fn(e),n instanceof Uint8Array&&dn(n,e.cekBits),e.cbc)return gn(e,t,n,r,i);let a=await ln(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 bn(e,t,n,r,i,a){if(!Jt(t)&&!(t instanceof Uint8Array))throw TypeError(Qt(t,`CryptoKey`,`KeyObject`,`Uint8Array`,`JSON Web Key`));if(!r)throw new W(`JWE Initialization Vector missing`);if(!i)throw new W(`JWE Authentication Tag missing`);if(!e.cbc&&i.length!==16)throw new W(`Invalid Authentication Tag length`);if(pn(e,r),t instanceof Uint8Array&&dn(t,e.cekBits),e.cbc)return vn(e,t,n,r,i,a);let o=await ln(t,e.subtle,`decrypt`);try{return new Uint8Array(await crypto.subtle.decrypt({additionalData:a,iv:r,name:`AES-GCM`,tagLength:128},o,it(n,i)))}catch{throw new _t}}function xn(e){let t={__proto__:null};for(let n in e)t[n]={...e[n],alg:n};return t}var Sn=[[`encrypt`,`wrapKey`],[`decrypt`,`unwrapKey`]],Cn=[[],[`deriveBits`]],wn=[[],[]];function Tn(e){return{kty:[`RSA`],mode:`key-encryption`,subtle:{name:`RSA-OAEP`,hash:`SHA-${e}`},usages:Sn,ops:[`wrapKey`,`unwrapKey`]}}function En(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 U(`Invalid or unsupported JWK "alg" (Algorithm) Parameter value`);return{name:`ECDH`,namedCurve:t}},usages:Cn,ops:[void 0,`deriveBits`]}}function Dn(e,t=!1){return{kty:[`oct`],mode:`key-wrapping`,secret:!0,subtle:{name:t?`AES-GCM`:`AES-KW`,length:e},usages:wn,ops:t?[`encrypt`,`decrypt`]:[`wrapKey`,`unwrapKey`]}}function On(){return{kty:[`oct`],mode:`key-wrapping`,secret:!0,subtle:{name:`PBKDF2`},usages:wn,ops:[`deriveBits`,`deriveBits`]}}var kn=xn({dir:{kty:[`oct`],mode:`direct-encryption`,secret:!0,subtle:{name:`AES-GCM`},usages:wn,ops:[`encrypt`,`decrypt`]},"RSA-OAEP":Tn(1),"RSA-OAEP-256":Tn(256),"RSA-OAEP-384":Tn(384),"RSA-OAEP-512":Tn(512),"ECDH-ES":En(`direct-key-agreement`),"ECDH-ES+A128KW":En(`key-agreement-with-key-wrapping`),"ECDH-ES+A192KW":En(`key-agreement-with-key-wrapping`),"ECDH-ES+A256KW":En(`key-agreement-with-key-wrapping`),A128KW:Dn(128),A192KW:Dn(192),A256KW:Dn(256),A128GCMKW:Dn(128,!0),A192GCMKW:Dn(192,!0),A256GCMKW:Dn(256,!0),"PBES2-HS256+A128KW":On(),"PBES2-HS384+A192KW":On(),"PBES2-HS512+A256KW":On()}),An=[`encrypt`,`decrypt`];function jn(e,t=!1){return{kty:[`oct`],secret:!0,subtle:{name:t?`AES-CBC`:`AES-GCM`,length:e},usages:wn,ops:An,cekBits:e,ivBits:t?128:96,cbc:t}}var Mn=xn({A128GCM:jn(128),A192GCM:jn(192),A256GCM:jn(256),"A128CBC-HS256":jn(256,!0),"A192CBC-HS384":jn(384,!0),"A256CBC-HS512":jn(512,!0)});function Nn(e,t){throw new U(`Invalid or unsupported "${e}" (JWE ${t}) header value`)}function Pn(e){return(typeof e==`string`?kn[e]:void 0)??Nn(`alg`,`Algorithm`)}function Fn(e){return e.mode===`key-wrapping`||e.mode===`key-encryption`||e.mode===`key-agreement-with-key-wrapping`}function In(e){return(typeof e==`string`?Mn[e]:void 0)??Nn(`enc`,`Encryption Algorithm`)}function Ln(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`);tn(e,t)}async function Rn(e,t,n){let r=await ln(t,Pn(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 zn(e,t,n){let r=await ln(t,Pn(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 Bn(e,t,n){rn(t,Pn(e).subtle,n),nn(e,t)}async function Vn(e,t,n,r){if(!(e instanceof Uint8Array)||e.length<8)throw new W(`PBES2 Salt Input must be 8 or more octets`);if(!Number.isSafeInteger(n)||Math.sign(n)!==1)throw new W(`PBES2 Count Input must be a positive integer`);let i=it(lt(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 ln(r,Pn(t).subtle,`deriveBits`);return new Uint8Array(await crypto.subtle.deriveBits(o,s,a))}function Hn(e){return it(st(e.length),e)}async function Un(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 ft(`sha256`,it(st(t),e,n));a.set(r,(t-1)*32)}return a.slice(0,r)}async function Wn(e,t,n,r,i=new Uint8Array,a=new Uint8Array){Ln(e),Ln(t,`deriveBits`);let o=it(Hn(lt(n)),Hn(i),Hn(a),st(r));return Un(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 Gn(e){qt(e);let t=e.algorithm.namedCurve;if(t!==`P-256`&&t!==`P-384`&&t!==`P-521`&&e.algorithm.name!==`X25519`)throw new U(`ECDH with the provided key is not allowed or not supported by your javascript runtime`)}function Kn(e,t){let n=e[t];if(n!==void 0){if(typeof n!=`string`)throw new W(`JOSE Header "${t}" (Agreement Party${t===`apu`?`U`:`V`}Info) invalid`);return Mt(n,t,W)}}function qn(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 W(`JOSE Header "apu" and "apv" values must be distinct`)}}function Jn(e){if(e===void 0)throw new W(`JWE Encrypted Key missing`)}function Yn(e){if(e!==void 0)throw new W(`Encountered unexpected JWE Encrypted Key`)}function Xn(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 Zn(e,t,n,r,i,a){let{alg:o}=e,s=e.mode;if(s===`direct-encryption`)return Yn(r),n;let c=s===`direct-key-agreement`;switch(c?Yn(r):Jn(r),e.subtle.name){case`ECDH`:{let{epk:r}=i;if(!Ot(r)||[`d`,`k`,`p`,`q`,`dp`,`dq`,`qi`,`oth`,`priv`].some(e=>Object.hasOwn(r,e)))throw new W(`JOSE Header "epk" (Ephemeral Public Key) missing or invalid`);Gn(n);let a=await cn(e,r),s=Kn(i,`apu`),l=Kn(i,`apv`);qn(s,l);let u=await Wn(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 qt(n),Bn(o,n,`decrypt`),new Uint8Array(await crypto.subtle.decrypt(`RSA-OAEP`,n,r));case`PBKDF2`:{if(typeof i.p2c!=`number`)throw new W(`JOSE Header "p2c" (PBES2 Count) missing or invalid`);Xn(a);let e=a??1e4;if(i.p2c>e)throw new W(`JOSE Header "p2c" (PBES2 Count) out is of acceptable bounds`);if(typeof i.p2s!=`string`)throw new W(`JOSE Header "p2s" (PBES2 Salt) missing or invalid`);n=await Vn(Mt(i.p2s,`p2s`,W),o,i.p2c,n);break}case`AES-GCM`:{if(typeof i.iv!=`string`)throw new W(`JOSE Header "iv" (Initialization Vector) missing or invalid`);if(typeof i.tag!=`string`)throw new W(`JOSE Header "tag" (Authentication Tag) missing or invalid`);let e=Mt(i.iv,`iv`,W),t=Mt(i.tag,`tag`,W);if(e.byteLength!==12)throw new W(`Invalid Initialization Vector length`);if(t.byteLength!==16)throw new W(`Invalid Authentication Tag length`);return bn(In(o.slice(0,-2)),n,r,e,t,new Uint8Array)}}return zn(o.slice(-6),n,r)}async function Qn(e,t,n,r,i,a={}){let{alg:o,mode:s}=e,c=Fn(e);if(i!==void 0&&!c)throw TypeError(`setContentEncryptionKey cannot be called with JWE "alg" (Algorithm) Header ${o}`);let l=await Wt(s===`direct-encryption`?t:e,n,`encrypt`);if(s===`direct-encryption`)return[l,void 0,void 0];let u=c?i??un(t):void 0;u&&dn(u,t.cekBits);let d,f;switch(e.subtle.name){case`ECDH`:{Gn(l);let{apu:n,apv:i}=a;n!==void 0&&Dt(n,`"apu"`),i!==void 0&&Dt(i,`"apv"`);let c=n??Kn(r,`apu`),u=i??Kn(r,`apv`);qn(c,u);let d;d=a.epk===void 0?(await crypto.subtle.generateKey(l.algorithm,!0,[`deriveBits`])).privateKey:await Wt(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 Wn(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=K(n)),i!==void 0&&(f.apv=K(i)),y)return[b,void 0,f];l=b;break}case`RSA-OAEP`:qt(l),Bn(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 Vn(t,o,e,l),f={p2c:e,p2s:K(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 yn(In(o.slice(0,-2)),u,l,e,new Uint8Array);d=t.ciphertext,f={iv:K(t.iv),tag:K(t.tag)}}}if(d??=await Rn(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 $n(e,t){if(e.zip!==void 0&&e.zip!==`DEF`)throw new U(`Unsupported JWE "zip" (Compression Algorithm) Header Parameter value.`);if(e.zip!==void 0&&!t?.zip)throw new W(`JWE "zip" (Compression Algorithm) Header Parameter MUST be in a protected header.`)}function er(e){if(typeof globalThis[e]>`u`)throw new U(`JWE "zip" (Compression Algorithm) Header Parameter requires the ${e} API.`)}async function tr(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 W(`Decompressed plaintext exceeded the configured limit`)}return it(...i)}async function nr(e){return er(`CompressionStream`),tr(new CompressionStream(`deflate-raw`),e)}async function rr(e,t){return er(`DecompressionStream`),tr(new DecompressionStream(`deflate-raw`),e,t)}function ir(e){let{protected:t,ciphertext:n,iv:r,tag:i,aad:a}=e,o;return t!==void 0&&(o=Pt(t,W,`JWE Protected Header is invalid`)),[o,Mt(n,`ciphertext`,W),r===void 0?void 0:Mt(r,`iv`,W),i===void 0?void 0:Mt(i,`tag`,W),Nt((t??``)+(a===void 0?``:`.${a}`),`aad`,W)]}function ar(e){return[e&&Lt(`keyManagementAlgorithms`,e.keyManagementAlgorithms),e&&Lt(`contentEncryptionAlgorithms`,e.contentEncryptionAlgorithms),e?.crit,e?.maxPBES2Count,e?.maxDecompressedLength]}async function or(e,t,n,r=ir(e)){let[i,a,o,s,c]=r,{header:l,unprotected:u,aad:d}=e,f;if(l!==void 0||u!==void 0){if(!At(i,l,u))throw new W(`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;zt(W,It,h,i,f),$n(f,i);let{alg:y,enc:b}=f;if(typeof y!=`string`||!y)throw new W(`missing JWE Algorithm (alg) in JWE Header`);let x=kn[y];if(v===``&&(!x||!Fn(x)))throw new W(`JWE Encrypted Key incorrect type`);let S=x?.mode===`integrated-encryption`;if(!S&&(typeof b!=`string`||!b))throw new W(`missing JWE Encryption Algorithm (enc) in JWE Header`);if(p&&!p.has(y)||!p&&y.startsWith(`PBES2`))throw new gt(`"alg" (Algorithm) Header Parameter value not allowed`);let C;if(S){if(b!==void 0)throw new W(`JWE "enc" (Encryption Algorithm) Header Parameter must not be present for integrated encryption`);if(o?.byteLength)throw new W(`JWE Initialization Vector must be empty for integrated encryption`);if(s?.byteLength)throw new W(`JWE Authentication Tag must be empty for integrated encryption`)}else{if(m&&!m.has(b))throw new gt(`"enc" (Encryption Algorithm) Header Parameter value not allowed`);C=In(b)}let w;if(v!==void 0)try{w=Mt(v,`encrypted_key`,W)}catch(e){if(!x||!Fn(x))throw e;w=new Uint8Array}let T=!1;typeof n==`function`&&(n=await n(i,e),T=!0);let E=x??Pn(y);Fn(E)&&w===void 0&&(w=new Uint8Array);let D=await Wt(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 Zn(E,e,D,w,f,g),Fn(E)&&t instanceof Uint8Array&&t.byteLength<<3!==e.cekBits&&(t=un(e))}catch(n){if(n instanceof TypeError||n instanceof W||n instanceof U)throw n;t=un(e)}O=await bn(e,t,a,o,s,c)}if(f.zip===`DEF`){let e=_??25e4;if(e===0)throw new U(`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 rr(O,e).catch(e=>{throw e instanceof W?e:new W(`Failed to decompress plaintext`,{cause:e})})}return{plaintext:O,...i&&{protectedHeader:i},...d!==void 0&&{additionalAuthenticatedData:Mt(d,`aad`,W)},...u&&{sharedUnprotectedHeader:u},...l&&{unprotectedHeader:l},...T&&{key:D}}}async function sr(e,t,n){if(e instanceof Uint8Array&&(e=tt.decode(e)),typeof e!=`string`)throw new W(`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 W(`Invalid Compact JWE`);return or({ciphertext:o,iv:a||void 0,protected:r,tag:s||void 0,encrypted_key:i||void 0},t,n)}function cr(e,t,n){if(!At(e,t,n))throw new W(`JWE Protected, JWE Shared Unprotected and JWE Per-Recipient Header Parameter names must be disjoint`)}function lr(e,t,n=!1){if(!e[1]&&!e[2]&&!e[3])throw new W(`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&&Dt(o,`JWE Additional Authenticated Data`),s!==void 0&&Dt(s,`JWE Content Encryption Key`),c!==void 0&&Dt(c,`JWE Initialization Vector`),!n&&r!==void 0&&(r=Vt(W,r)[0],e[1]=r),i!==void 0&&(i=Vt(W,i)[0],e[2]=i),!n&&a!==void 0&&(a=Vt(W,a)[0],e[3]=a),l!==void 0&&!Ot(l))throw TypeError(`JWE Key Management Parameters must be an object`);cr(r,i,a);let d={...r,...i,...a};Rt(W,r),zt(W,It,u,r,d),$n(d,r);let{alg:f,enc:p}=d;if(typeof f!=`string`||!f)throw new W(`JWE "alg" (Algorithm) Header Parameter missing or invalid`);let m=kn[f];if(m?.mode===`integrated-encryption`){if(p!==void 0)throw new W(`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 W(`JWE "enc" (Encryption Algorithm) Header Parameter missing or invalid`);return[d,In(p),m]}async function ur(e,t,n){let[r,i,a]=t,[o,s,c,l,u,d,f,p,,m]=e,h=s,g=c,_=a??Pn(r.alg),v,y,b;_.mode===`integrated-encryption`?b=await Wt(_,n,`encrypt`):[b,v,y]=await Qn(_,i,n,r,d,p),y&&(m?g=g?{...g,...y}:y:h=h?{...h,...y}:y,cr(h,g,l));let x=h?K(JSON.stringify(h)):``,S=u?.byteLength?K(u):void 0,C=lt(S?`${x}.${S}`:x),w=o;r.zip===`DEF`&&(w=await nr(w).catch(e=>{throw new W(`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 yn(i,w,b,f,C);let O={ciphertext:K(T)};return D&&(O.iv=K(D)),E&&(O.tag=K(E)),v?.byteLength&&(O.encrypted_key=K(v)),S&&(O.aad=S),h&&(O.protected=x),l&&(O.unprotected=l),g&&(O.header=g),O}async function dr(e,t,n){return ur(e,lr(e,n),t)}function fr(e){return[e.protected,e.encrypted_key,e.iv,e.ciphertext,e.tag].join(`.`)}var pr=[[`verify`],[`sign`]];function mr(e){let t={name:`HMAC`,hash:`SHA-${e}`};return{kty:[`oct`],secret:!0,subtle:t,signing:t,usages:pr}}function hr(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:pr,minRsaBits:2048}}function gr(e,t){return{kty:[`EC`],crv:e,subtle:{name:`ECDSA`,namedCurve:e},signing:{name:`ECDSA`,hash:`SHA-${t}`},usages:pr}}function _r(){let e={name:`Ed25519`};return{kty:[`OKP`],crv:`Ed25519`,subtle:e,signing:e,usages:pr}}function vr(e){let t={name:`ML-DSA-${e}`};return{kty:[`AKP`],subtle:t,signing:t,usages:pr}}var yr=xn({HS256:mr(256),HS384:mr(384),HS512:mr(512),RS256:hr(256),RS384:hr(384),RS512:hr(512),PS256:hr(256,32),PS384:hr(384,48),PS512:hr(512,64),ES256:gr(`P-256`,256),ES384:gr(`P-384`,384),ES512:gr(`P-521`,512),EdDSA:_r(),Ed25519:_r(),"ML-DSA-44":vr(44),"ML-DSA-65":vr(65),"ML-DSA-87":vr(87)});function br(e){let t=typeof e==`string`?yr[e]:void 0;if(!t)throw new U(`alg ${e} is not supported either by JOSE or your javascript runtime`);return t}function xr(e){return[e&&Lt(`algorithms`,e.algorithms),e?.crit]}function Sr(e){return e===void 0?{}:Pt(e,G,`JWS Protected Header is invalid`)}function Cr(e){try{return lt(e)}catch{throw new G(`JWS Compact Serialization payload must use only ASCII characters`)}}async function wr(e,t,n,r,i){let{protected:a,header:o,payload:s}=e,c=i??Sr(a);if(!At(c,o))throw new G(`JWS Protected and JWS Unprotected Header Parameter names must be disjoint`);let l={...c,...o},u=Bt(c,zt(G,Ft,t[1],c,l)),{alg:d}=l;if(typeof d!=`string`||!d)throw new G(`JWS "alg" (Algorithm) Header Parameter missing or invalid`);if(t[0]&&!t[0].has(d))throw new gt(`"alg" (Algorithm) Header Parameter value not allowed`);if(u){if(typeof s!=`string`)throw new G(`JWS Payload must be a string`)}else if(typeof s!=`string`&&!(s instanceof Uint8Array))throw new G(`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=br(d),h=it(a===void 0?new Uint8Array:lt(a),lt(`.`),typeof f==`string`?t[2]??=Nt(f,`payload`,G):f),g=Mt(e.signature,`signature`,G),_=await Wt(m,n,`verify`),v=await ln(_,m.subtle,`verify`);m.minRsaBits&&nn(m.alg,v);let y=!1;try{y=await crypto.subtle.verify(m.signing,v,g,h)}catch{}if(!y)throw new wt;let b={payload:typeof f==`string`?Mt(f,`payload`,G):f};return a!==void 0&&(b.protectedHeader=c),o!==void 0&&(b.unprotectedHeader=o),p?[{...b,key:_},u]:[b,u]}async function Tr(e,t,n){if(e instanceof Uint8Array&&(e=tt.decode(e)),typeof e!=`string`)throw new G(`Compact JWS must be a string or Uint8Array`);let{0:r,1:i,2:a,length:o}=e.split(`.`);if(o!==3)throw new G(`Invalid Compact JWS`);return wr({payload:i,protected:r,signature:a},t,n,Cr)}async function Er(e,t,n){let[r]=await Tr(e,xr(n),t);return r}var Dr=e=>Math.floor(e.getTime()/1e3),Or={s:1,m:60,h:3600,d:86400,w:604800,y:31557600},kr=/^(\+|\-)? ?(\d+|\d+\.\d+) ?(seconds?|secs?|s|minutes?|mins?|m|hours?|hrs?|h|days?|d|weeks?|w|years?|yrs?|y)(?: (ago|from now))?$/i,Ar=`check_failed`;function jr(){throw TypeError(`Invalid time period format`)}function Mr(e){typeof e!=`string`&&jr();let t=kr.exec(e);(!t||t[4]&&t[1])&&jr();let n=parseFloat(t[2]),r=Math.round(n*Or[t[3][0].toLowerCase()]);return Number.isFinite(r)||jr(),t[1]===`-`||t[4]===`ago`?-r:r}function Nr(e,t){if(!Number.isFinite(t))throw TypeError(`Invalid ${e} input`);return t}function Pr(e,t){if(typeof t!=`string`)throw TypeError(`"${e}" claim must be a string`)}function Fr(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 Ir(e,t){return typeof e==`number`?Nr(t,e):e instanceof Date?Nr(t,Dr(e)):Dr(new Date)+Mr(e)}var Lr=e=>{let t=e.toLowerCase();return e.includes(`/`)?t:`application/${t}`},Rr=(e,t)=>typeof e==`string`?t.includes(e):Array.isArray(e)?t.some(t=>e.includes(t)):!1;function zr(e,t,n=!1){let r=e[t];if(r!==void 0||n){if(typeof r!=`number`)throw new mt(`"${t}" claim must be a number`,e,t,`invalid`);return r}}function Br(e,t){throw new mt(`unexpected "${t}" claim value`,e,t,Ar)}function Vr(e,t,n={}){let r;try{r=JSON.parse(nt.decode(t))}catch{}if(!Ot(r))throw new vt(`JWT Claims Set must be a top-level JSON object`);let{typ:i}=n;if(i!==void 0&&(typeof e.typ!=`string`||Lr(e.typ)!==Lr(i)))throw new mt(`unexpected "typ" JWT header value`,r,`typ`,Ar);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 mt(`missing required "${e}" claim`,r,e,`missing`);o!==void 0&&!(Array.isArray(o)?o:[o]).includes(r.iss)&&Br(r,`iss`),s!==void 0&&r.sub!==s&&Br(r,`sub`),c!==void 0&&!Rr(r.aud,typeof c==`string`?[c]:c)&&Br(r,`aud`);let{clockTolerance:d}=n,f=0;if(typeof d==`string`)f=Mr(d);else if(d!==void 0){if(typeof d!=`number`)throw TypeError(`Invalid clockTolerance option type`);f=d}Nr(`clockTolerance option`,f);let{currentDate:p}=n,m=Nr(`currentDate option`,Dr(p===void 0?new Date:p)),h=zr(r,`iat`,l!==void 0),g=zr(r,`nbf`);if(g!==void 0&&g>m+f)throw new mt(`"nbf" claim timestamp check failed`,r,`nbf`,Ar);let _=zr(r,`exp`);if(_!==void 0&&_<=m-f)throw new ht(`"exp" claim timestamp check failed`,r,`exp`,Ar);if(l!==void 0){let e=m-h,t=Nr(`maxTokenAge option`,typeof l==`number`?l:Mr(l));if(e-f>t)throw new ht(`"iat" claim timestamp check failed (too far in the past)`,r,`iat`,Ar);if(e<-f)throw new mt(`"iat" claim timestamp check failed (it should be in the past)`,r,`iat`,Ar)}return r}var Hr;function Ur(e){return Hr.get(e)}function Wr(e){let t=Ur(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 et.encode(JSON.stringify(t))}function Gr(e,t){return Ur(e)[t]}var Kr=class{constructor(e={}){if(!Ot(e))throw TypeError(`JWT Claims Set MUST be an object`);(Hr||=new WeakMap).set(this,structuredClone(e))}setIssuer(e){return Pr(`iss`,e),Ur(this).iss=e,this}setSubject(e){return Pr(`sub`,e),Ur(this).sub=e,this}setAudience(e){return Fr(e),Ur(this).aud=e,this}setJti(e){return Pr(`jti`,e),Ur(this).jti=e,this}setNotBefore(e){return Ur(this).nbf=Ir(e,`setNotBefore`),this}setExpirationTime(e){return Ur(this).exp=Ir(e,`setExpirationTime`),this}setIssuedAt(e){let t=Ur(this);return t.iat=e===void 0?Dr(new Date):typeof e==`string`?Nr(`setIssuedAt`,Dr(new Date)+Mr(e)):Ir(e,`setIssuedAt`),this}};async function qr(e,t,n){let[r,i]=await Tr(e,xr(n),t);if(!i)throw new vt(`JWTs MUST NOT use unencoded payload`);let a=Vr(r.protectedHeader,r.payload,n);return{...r,payload:a}}async function Jr(e,t,n){let{plaintext:r,...i}=await sr(e,ar(n),t),{protectedHeader:a}=i,o=Vr(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 mt(`replicated "${e}" claim header parameter mismatch`,o,e,`mismatch`);return{payload:o,...i}}async function Yr(e,t,n){let[r,i,a,o]=e,s=``;if(i!==void 0){let e=Vt(G,i);i=e[0],s=K(e[1])}if(a!==void 0&&(a=Vt(G,a)[0]),!i&&!a)throw new G(`either setProtectedHeader or setUnprotectedHeader must be called before #sign()`);if(!At(i,a))throw new G(`JWS Protected and JWS Unprotected Header Parameter names must be disjoint`);let c={...i,...a};Rt(G,i);let l=Bt(i,zt(G,Ft,o,i,c));l||n?.();let{alg:u}=c;if(typeof u!=`string`||!u)throw new G(`JWS "alg" (Algorithm) Header Parameter missing or invalid`);let d=br(u),f=``,p=r,m;if(l){let t=e[4];t?(f=t[0]??=K(r),p=t[1]??=lt(f)):(f=K(r),m=et.encode(`${s}.${f}`))}m??=it(lt(s),lt(`.`),p);let h=await ln(await Wt(d,t,`sign`),d.subtle,`sign`);d.minRsaBits&&nn(d.alg,h);let g={signature:K(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 Xr(e,t,n,r,i){let[a]=await Yr([e,t,void 0,n],r,i);return`${a.protected}.${a.payload}.${a.signature}`}var Zr=Kr,Qr=class extends Zr{#e;setProtectedHeader(e){return jt(this.#e,`setProtectedHeader`),this.#e=e,this}async sign(e,t){return Xr(Wr(this),this.#e,t?.crit,e,()=>{throw new vt(`JWTs MUST NOT use unencoded payload`)})}},$r=Kr,ei=class extends $r{#e=[void 0];#t;#n;#r;setProtectedHeader(e){return jt(this.#e[1],`setProtectedHeader`),this.#e[1]=e,this}setKeyManagementParameters(e){return jt(this.#e[7],`setKeyManagementParameters`),this.#e[7]=e,this}setContentEncryptionKey(e){return jt(this.#e[5],`setContentEncryptionKey`),this.#e[5]=e,this}setInitializationVector(e){return jt(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=Wr(this);this.#e[1]&&(this.#t||this.#n||this.#r)&&(this.#e[1]={...this.#e[1],iss:this.#t?Gr(this,`iss`):void 0,sub:this.#n?Gr(this,`sub`):void 0,aud:this.#r?Gr(this,`aud`):void 0});let r=[...this.#e];return r[0]=n,fr(await dr(r,e,t))}},ti=`"alg" (Algorithm)`;function ni(e=`JWK "alg" (Algorithm) Parameter`){throw new U(`Invalid or unsupported ${e} value`)}function ri(e,t){return(typeof e==`string`?yr[e]??kn[e]:void 0)??ni(t)}var ii=(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},ai=e=>({data:e,pos:0}),oi=e=>{let t=e.data[e.pos++];if(t===void 0)throw Error(`Unexpected end of ASN.1 input`);return t},si=e=>{let t=oi(e);if(t&128){let n=t&127,r=0;for(let t=0;t<n;t++)r=r<<8|oi(e);return r}return t},ci=(e,t,n)=>{if(oi(e)!==t)throw Error(n)},li=(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},ui=e=>(ci(e,6,`Expected algorithm OID`),li(e,si(e)));function di(e,t){if(ci(e,48,`Invalid ${t===`spki`?`SPKI`:`PKCS#8`} structure`),si(e),t===`pkcs8`){ci(e,2,`Expected version field`);let t=si(e);e.pos+=t}ci(e,48,`Expected algorithm identifier`),si(e)}var fi=e=>{let t=ui(e);if(ii(t,[43,101,110]))return`X25519`;if(!ii(t,[42,134,72,206,61,2,1]))throw Error(`Unsupported key algorithm`);ci(e,6,`Expected curve OID`);let n=li(e,si(e));if(ii(n,[42,134,72,206,61,3,1,7]))return`P-256`;if(ii(n,[43,129,4,0,34]))return`P-384`;if(ii(n,[43,129,4,0,35]))return`P-521`;throw Error(`Unsupported named curve`)},pi=async(e,t,n,r)=>{let i=sn(r?.extractable),a=ri(n,ti);a.secret&&ni(`"alg" (Algorithm)`);let o=e===`spki`,s;if(a.resolve)try{let n=ai(t);di(n,e),s=a.resolve({crv:fi(n)})}catch{throw new U(`Invalid or unsupported key format`)}else s=a.subtle;return crypto.subtle.importKey(e,t,s,i??o,a.usages[+!o])},mi=(e,t)=>dt(e.replace(t,``)),hi=(e,t,n)=>pi(`spki`,mi(e,/(?:-----(?:BEGIN|END) PUBLIC KEY-----|\s)/g),t,n);async function gi(e){if(Yt(e)){if(e.type===`secret`)e=e.export();else return e.export({format:`jwk`})}if(e instanceof Uint8Array)return{kty:`oct`,k:K(e)};if(!Jt(e))throw TypeError(Qt(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 _i=(e,t)=>{if(typeof e!=`string`||!e)throw new yt(`${t} missing or invalid`)};async function vi(e,t){let n;if(Ot(e)){if(n=an(e),typeof n.kty!=`string`)throw TypeError(Qt(e,`CryptoKey`,`KeyObject`,`JSON Web Key`))}else if(Xt(e))n=an(await gi(e));else throw TypeError(Qt(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`:_i(n.alg,`"alg" (Algorithm) Parameter`),_i(n.pub,`"pub" (Public key) Parameter`),r={alg:n.alg,kty:n.kty,pub:n.pub};break;case`EC`:_i(n.crv,`"crv" (Curve) Parameter`),_i(n.x,`"x" (X Coordinate) Parameter`),_i(n.y,`"y" (Y Coordinate) Parameter`),r={crv:n.crv,kty:n.kty,x:n.x,y:n.y};break;case`OKP`:_i(n.crv,`"crv" (Subtype of Key Pair) Parameter`),_i(n.x,`"x" (Public Key) Parameter`),r={crv:n.crv,kty:n.kty,x:n.x};break;case`RSA`:_i(n.e,`"e" (Exponent) Parameter`),_i(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 yt(`"k" (Key Value) Parameter missing or invalid`);r={k:n.k,kty:n.kty};break;default:throw new U(`"kty" (Key Type) Parameter missing or unsupported`)}let i=lt(JSON.stringify(r));return K(await ft(t,i))}function yi(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 bi(e,t,n){let r=e.get(t)||e.set(t,{}).get(t),{alg:i}=n;if(r[i]===void 0){let e=cn(n,t,!0).then(e=>{if(e.type!==`public`)throw new bt(`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 xi(e){let t;try{t=structuredClone(e)}catch{}if(!kt(t))throw new bt(`JSON Web Key Set malformed`);let n=t.keys.map(e=>{let t=an(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`?yr[a]:void 0;if(!s||s.secret)throw new U(`Unsupported "alg" value for a JSON Web Key Set`);let c=t.keys.filter((e,t)=>yi(n[t],s,a,o)),{0:l,length:u}=c;if(!u)throw new xt;if(u!==1){let e=new St;throw e[Symbol.asyncIterator]=async function*(){for(let e of c)try{yield await bi(r,e,s)}catch{}},e}return bi(r,l,s)},"jwks",{value:()=>structuredClone(t)})}async function Si(e,t,n){if(typeof e!=`string`||e.indexOf(`-----BEGIN PUBLIC KEY-----`)!==0)throw TypeError(`"spki" must be SPKI formatted string`);return hi(e,t,n)}async function Ci(e,t,n){if(!Ot(e))throw TypeError(`JWK must be an object`);let r=on(e),i=sn(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 Et(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 cn(ri(t),r,i);case`RSA`:case`EC`:case`OKP`:return cn(ri(t),r,i);default:throw new U(`Unsupported "kty" (Key Type) Parameter value`)}}function wi(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 Pt(t,TypeError,n)}function Ti(e){if(typeof e!=`string`)throw new vt(`JWTs must use Compact JWS serialization, JWT must be a string`);let{1:t,length:n}=e.split(`.`);if(n===5)throw new vt(`Only JWTs using Compact JWS serialization can be decoded`);if(n!==3)throw new vt(`Invalid JWT`);if(!t)throw new vt(`JWTs must contain a payload`);let r;try{r=Et(t)}catch{throw new vt(`Failed to base64url decode the payload`)}let i;try{i=JSON.parse(nt.decode(r))}catch{throw new vt(`Failed to parse the decoded payload as JSON`)}if(!Ot(i))throw new vt(`Invalid JWT Claims Set`);return i}function Ei(e){let t=e?.modulusLength??2048;if(typeof t!=`number`||!Number.isInteger(t)||t<2048)throw new U(`Invalid or unsupported modulusLength option provided, 2048 bits or larger keys must be used`);return t}async function Di(e,t){let n=sn(t?.extractable),r=ri(e,ti);r.secret&&ni(`"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 U(`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 U(`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:Ei(t)}:r.subtle}return crypto.subtle.generateKey(i,n??!1,[...r.usages[1],...r.usages[0]])}async function Oi(e,t,n=3600){return await new Qr(e).setProtectedHeader({alg:`HS256`}).setIssuedAt().setExpirationTime(Math.floor(Date.now()/1e3)+n).sign(new TextEncoder().encode(t))}async function ki(e,t){try{return(await qr(e,new TextEncoder().encode(t))).payload}catch{return null}}var Ai=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]),ji=()=>Date.now()/1e3|0,Mi=`dir`,Ni=`A256CBC-HS512`;function Pi(e,t){return Ve($e,new TextEncoder().encode(e),new TextEncoder().encode(t),Ai,64)}function Fi(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 Ii(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 Li(e,t,n,r=3600){let i=Pi(Fi(t),n),a=await vi({kty:`oct`,k:K(i)},`sha256`);return await new ei(e).setProtectedHeader({alg:Mi,enc:Ni,kid:a}).setIssuedAt().setExpirationTime(ji()+r).setJti(crypto.randomUUID()).encrypt(i)}var Ri={clockTolerance:15,keyManagementAlgorithms:[Mi],contentEncryptionAlgorithms:[Ni,`A256GCM`]};async function zi(e,t,n){if(!e)return null;let r=!1;try{r=wi(e).kid!==void 0}catch{return null}try{let r=Ii(t),{payload:i}=await Jr(e,async e=>{let t=e.kid;if(t!==void 0){for(let e of r){let r=Pi(e.value,n);if(t===await vi({kty:`oct`,k:K(r)},`sha256`))return r}throw Error(`no matching decryption secret`)}return r.length,Pi(r[0].value,n)},Ri);return i}catch{if(r)return null;let i=Ii(t);if(i.length<=1)return null;for(let t=1;t<i.length;t++)try{let r=i[t],{payload:a}=await Jr(e,Pi(r.value,n),Ri);return a}catch{continue}return null}}function Bi(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 Vi=O(`a-z`,`0-9`,`A-Z`,`-_`);function Hi(){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 Ui(e,t){return{digest:async n=>{let r=T(n),i=await Hi().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`}):D.encode(i):i}}}function Wi(e){return e instanceof Uint8Array||ArrayBuffer.isView(e)&&e.constructor.name===`Uint8Array`&&`BYTES_PER_ELEMENT`in e&&e.BYTES_PER_ELEMENT===1}var Gi=e=>e?`"${e}" `:``;function Ki(e,t=``){if(typeof e!=`boolean`)throw TypeError(Gi(t)+`expected boolean, got type=`+typeof e);return e}function qi(e,t=``){if(typeof e!=`number`)throw TypeError(Gi(t)+`expected number, got `+typeof e);if(!Number.isSafeInteger(e)||e<0)throw RangeError(Gi(t)+`expected integer >= 0, got `+e);return e}function q(e,t,n=``){if(Wi(e)&&(t===void 0||e.length===t))return e;t!==void 0&&qi(t,`length`);let r=Wi(e),i=t===void 0?``:` of length ${t}`,a=r?`length=${e.length}`:`type=${typeof e}`,o=Gi(n)+`expected Uint8Array`+i+`, got `+a;throw r?RangeError(o):TypeError(o)}var Ji=(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 Yi(e,t=!0){if(e.destroyed)throw Error(`hash was destroyed`);if(t&&e.finished)throw Error(`digest() was already called`)}function Xi(e,t){q(e,void 0,`output`);let n=t.outputLen;if(!(e.length>=n))throw RangeError(`"output" expected length >= `+n)}function Zi(e){return new Uint32Array(e.buffer,e.byteOffset,Math.floor(e.byteLength/4))}function Qi(...e){for(let t=0;t<e.length;t++)e[t].fill(0)}function $i(e){return new DataView(e.buffer,e.byteOffset,e.byteLength)}var ea=new Uint8Array(new Uint32Array([287454020]).buffer)[0]===68;function ta(e){return e<<24&4278190080|e<<8&16711680|e>>>8&65280|e>>>24&255}function na(e){for(let t=0;t<e.length;t++)e[t]=ta(e[t]);return e}var ra=ea?e=>e:na,ia=typeof Uint8Array.from([]).toHex==`function`&&typeof Uint8Array.fromHex==`function`,aa=Array.from({length:256},(e,t)=>t.toString(16).padStart(2,`0`));function oa(e){if(q(e),ia)return e.toHex();let t=``;for(let n=0;n<e.length;n++)t+=aa[e[n]];return t}function sa(e){return e>=48&&e<=57?e-48:e>=65&&e<=70?e-55:e>=97&&e<=102?e-87:void 0}function ca(e){if(typeof e!=`string`)throw TypeError(`hex string expected, got `+typeof e);if(ia)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=sa(e.charCodeAt(i)),a=sa(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 la(e){if(typeof e!=`string`)throw TypeError(`string expected`);return new Uint8Array(new TextEncoder().encode(e))}function ua(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 da(e,t){if(ua(e,t)&&e.byteOffset<t.byteOffset)throw Error(`complex overlap of input and output is not supported`)}function fa(...e){let t=0;for(let n=0;n<e.length;n++){let r=e[n];q(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 pa(e,t){return Ji(e,`defaults`),Ji(t,`opts`),Object.assign(e,t)}function ma(e,t){if(e=q(e),t=q(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 ha(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 ga=(e,t)=>{function n(n,...r){if(q(n,void 0,`key`),e.nonceLength!==void 0){let t=r[0];q(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(Wi(r[e]))throw Error(`AAD not supported`)}e.withAAD&&r[a]!==void 0&&q(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`);q(t,void 0,`output`)}},c=!1;return{encrypt(e,t){if(c)throw Error(`cannot encrypt() twice with same key + nonce`);return c=!0,q(e,void 0,`data`),s(o.encrypt.length,t),o.encrypt(e,t)},decrypt(e,t){if(q(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 _a(e,t,n=!0){if(t===void 0)return new Uint8Array(e);if(q(t,e,`output`),n&&!ya(t))throw Error(`invalid output, must be aligned`);return t}function va(e,t,n){qi(e),qi(t),Ki(n);let r=new Uint8Array(16),i=$i(r);return i.setBigUint64(0,BigInt(t),n),i.setBigUint64(8,BigInt(e),n),r}function ya(e){return e.byteOffset%4==0}function ba(e){return Uint8Array.from(q(e))}function xa(e=32){qi(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 Sa(e,t=xa){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;qi(n,`fn.nonceLength`);let r=(e,t,n)=>{let r=fa(e,t);return ua(n,t)||t.fill(0),r},i=((i,...a)=>({encrypt(o){q(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){q(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 Ca=e=>Uint8Array.from(e.split(``),e=>e.charCodeAt(0)),wa=ra(Zi(Ca(`expand 16-byte k`))),Ta=ra(Zi(Ca(`expand 32-byte k`)));function J(e,t){return e<<t|e>>>32-t}var Ea=64,Da=16,Oa=2**32-1,ka=Uint32Array.of();function Aa(e,t,n,r,i,a,o,s){let c=i.length,l=new Uint8Array(Ea),u=Zi(l),d=ea&&ya(i)&&ya(a),f=d?Zi(i):ka,p=d?Zi(a):ka;if(ea)for(let m=0;m<c;o++){if(e(t,n,r,u,o,s),o>=Oa)throw Error(`arx: counter overflow`);let h=Math.min(Ea,c-m);if(d&&h===Ea){let e=m/4;if(m%4!=0)throw Error(`arx: invalid block position`);for(let t=0,n;t<Da;t++)n=e+t,p[n]=f[n]^u[t];m+=Ea}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),ra(u),o>=Oa)throw Error(`arx: counter overflow`);let f=Math.min(Ea,c-d);for(let e=0,t;e<f;e++)t=d+e,a[t]=i[t]^l[e];d+=f}}function ja(e,t){let{allowShortKeys:n,extendNonceFn:r,counterLength:i,counterRight:a,rounds:o}=pa({allowShortKeys:!1,counterLength:8,counterRight:!1,rounds:20},t);if(typeof e!=`function`)throw Error(`core must be a function`);return qi(i),qi(o),Ki(a),Ki(n),(t,s,c,l,u=0)=>{q(t,void 0,`key`),q(s,void 0,`nonce`),q(c,void 0,`data`);let d=c.length,f=l!==void 0;if(l=_a(d,l,!1),f&&da(c,l),qi(u),u<0||u>=Oa)throw Error(`arx: counter overflow`);let p=[],m=t.length,h,g;if(m===32)p.push(h=ba(t)),g=Ta;else if(m===16&&n)h=new Uint8Array(32),h.set(t),h.set(t,16),g=wa,p.push(h);else throw q(t,32,`arx key`),Error(`invalid key size`);(!ea||!ya(s))&&p.push(s=ba(s));let _=Zi(h);if(r){if(s.length!==24)throw Error(`arx: extended nonce must be 24 bytes`);let e=s.subarray(0,16);if(ea)r(g,_,Zi(e),_);else{let t=ra(Uint32Array.from(g));r(t,_,Zi(e),_),Qi(t),ra(_)}s=s.subarray(16)}else ea||ra(_);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=ra(Zi(s));try{return Aa(e,g,_,y,c,l,u,o),l}finally{Qi(...p)}}}function Ma(e,t){return e[t++]&255|(e[t++]&255)<<8}var Na=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=ba(q(e,32,`key`));let t=Ma(e,0),n=Ma(e,2),r=Ma(e,4),i=Ma(e,6),a=Ma(e,8),o=Ma(e,10),s=Ma(e,12),c=Ma(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]=Ma(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=Ma(e,t+0),_=Ma(e,t+2),v=Ma(e,t+4),y=Ma(e,t+6),b=Ma(e,t+8),x=Ma(e,t+10),S=Ma(e,t+12),C=Ma(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 z=P+w*f+T*d+E*u+D*l+O*c;P=z>>>13,z&=8191,z+=k*s+A*o+5*h*j+5*m*M+5*p*N,P+=z>>>13,z&=8191;let ne=P+w*p+T*f+E*d+D*u+O*l;P=ne>>>13,ne&=8191,ne+=k*c+A*s+j*o+5*h*M+5*m*N,P+=ne>>>13,ne&=8191;let re=P+w*m+T*p+E*f+D*d+O*u;P=re>>>13,re&=8191,re+=k*l+A*c+j*s+M*o+5*h*N,P+=re>>>13,re&=8191;let ie=P+w*h+T*m+E*p+D*f+O*d;P=ie>>>13,ie&=8191,ie+=k*u+A*l+j*c+M*s+N*o,P+=ie>>>13,ie&=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]=z,i[7]=ne,i[8]=re,i[9]=ie}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;Qi(n)}update(e){Yi(this),q(e),e=ba(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,Qi(this.h,this.r,this.buffer,this.pad)}digestInto(e){Yi(this),Xi(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}},Pa=ha(32,e=>new Na(e));function Fa(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=J(P^S,16),A=A+P|0,E=J(E^A,12),S=S+E|0,P=J(P^S,8),A=A+P|0,E=J(E^A,7),C=C+D|0,F=J(F^C,16),j=j+F|0,D=J(D^j,12),C=C+D|0,F=J(F^C,8),j=j+F|0,D=J(D^j,7),w=w+O|0,I=J(I^w,16),M=M+I|0,O=J(O^M,12),w=w+O|0,I=J(I^w,8),M=M+I|0,O=J(O^M,7),T=T+k|0,L=J(L^T,16),N=N+L|0,k=J(k^N,12),T=T+k|0,L=J(L^T,8),N=N+L|0,k=J(k^N,7),S=S+D|0,L=J(L^S,16),M=M+L|0,D=J(D^M,12),S=S+D|0,L=J(L^S,8),M=M+L|0,D=J(D^M,7),C=C+O|0,P=J(P^C,16),N=N+P|0,O=J(O^N,12),C=C+O|0,P=J(P^C,8),N=N+P|0,O=J(O^N,7),w=w+k|0,F=J(F^w,16),A=A+F|0,k=J(k^A,12),w=w+k|0,F=J(F^w,8),A=A+F|0,k=J(k^A,7),T=T+E|0,I=J(I^T,16),j=j+I|0,E=J(E^j,12),T=T+E|0,I=J(I^T,8),j=j+I|0,E=J(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 Ia(e,t,n,r){let i=ea?e:ra(e.slice(0,4)),a=ea?t:ra(t.slice(0,8)),o=ea?n:ra(n.slice(0,4)),s=new Uint32Array(16);Fa(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,ra(r),ea||Qi(i,a,o),Qi(s)}var La=ja(Fa,{counterRight:!1,counterLength:8,extendNonceFn:Ia,allowShortKeys:!1}),Ra=new Uint8Array(16),za=(e,t)=>{e.update(t);let n=t.length%16;n&&e.update(Ra.subarray(n))},Ba=new Uint8Array(32);function Va(e,t,n,r,i){i!==void 0&&q(i,void 0,`AAD`);let a=e(t,n,Ba),o=va(r.length,i?i.length:0,!0),s=Pa.create(a);i&&za(s,i),za(s,r),s.update(o);let c=s.digest();return Qi(a,o),c}var Ha=ga({blockSize:64,nonceLength:24,tagLength:16,withAAD:!0},(e=>(t,n,r)=>({encrypt(i,a){let o=i.length;a=_a(o+16,a,!1),a.set(i);let s=a.subarray(0,-16);e(t,n,s,s,1);let c=Va(e,t,n,s,r);return a.set(c,o),Qi(c),a},decrypt(i,a){a=_a(i.length-16,a,!1);let o=i.subarray(0,-16),s=i.subarray(-16),c=Va(e,t,n,o,r);if(!ma(s,c))throw Qi(c),Error(`invalid tag`);return a.set(i.subarray(0,-16)),e(t,n,a,a,1),Qi(c),a}}))(La)),Ua={name:`HMAC`,hash:`SHA-256`},Wa=`$ba$`;function Ga(e){if(!e.startsWith(Wa))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 Ka(e,t){return`${Wa}${e}$${t}`}async function qa(e,t){let n=await Ui(`SHA-256`).digest(e),r=la(t);return oa(Sa(Ha)(new Uint8Array(n)).encrypt(r))}async function Ja(e,t){let n=await Ui(`SHA-256`).digest(e),r=ca(t),i=Sa(Ha)(new Uint8Array(n));return new TextDecoder().decode(i.decrypt(r))}var Ya=async({key:e,data:t})=>{if(typeof e==`string`)return qa(e,t);let n=e.keys.get(e.currentVersion);if(!n)throw Error(`Secret version ${e.currentVersion} not found in keys`);let r=await qa(n,t);return Ka(e.currentVersion,r)},Xa=async({key:e,data:t})=>{if(typeof e==`string`)return Ja(e,t);let n=Ga(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 Ja(t,n.ciphertext)}if(e.legacySecret)return Ja(e.legacySecret,t);throw Error(`Cannot decrypt legacy bare-hex payload: no legacy secret available. Set BETTER_AUTH_SECRET for backwards compatibility.`)},Za=async e=>{let t=typeof e==`string`?new TextEncoder().encode(e):e;return await Hi().importKey(`raw`,t,Ua,!1,[`sign`,`verify`])},Qa=async(e,t)=>{let n=await Za(t),r=await Hi().sign(Ua.name,n,new TextEncoder().encode(e));return btoa(String.fromCharCode(...new Uint8Array(r)))},$a={name:`HMAC`,hash:`SHA-256`},eo=async e=>{let t=typeof e==`string`?new TextEncoder().encode(e):e;return await Hi().importKey(`raw`,t,$a,!1,[`sign`,`verify`])},to=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 Hi().verify($a,n,i,new TextEncoder().encode(t))}catch{return!1}},no=async(e,t)=>{let n=await eo(t),r=await Hi().sign($a.name,n,new TextEncoder().encode(e));return btoa(String.fromCharCode(...new Uint8Array(r)))},ro=async(e,t)=>{let n=await no(e,t);return e=`${e}.${n}`,e=encodeURIComponent(e),e},io=/^application\/([a-z0-9.+-]*\+)?json/i;async function ao(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(io.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 oo(e){return e instanceof g||e?.name===`APIError`}function so(e){try{return e.includes(`%`)?decodeURIComponent(e):e}catch{return e}}async function co(e){try{return{data:await e,error:null}}catch(e){return{data:null,error:e}}}function lo(e){return e instanceof Request||Object.prototype.toString.call(e)===`[object Request]`}var uo={secure:`__Secure-`,host:`__Host-`},fo=(e,t)=>{if(!t)return e;if(t===`secure`||t===`host`)return uo[t]+e};function po(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,so(n))}n=i+1}return t}function mo(e,t,n={}){let r=fo(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 ho({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 go=(e,t,n)=>(t=encodeURIComponent(t),ho(mo(e,t,n))),_o=async(e,t,n,r)=>(t=await ro(t,n),ho(mo(e,t,r)));async function vo(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:yo(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:yo(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 yo(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 bo=async(e,{options:t,path:n})=>{let r=new Headers,i,{data:a,error:o}=await vo(t,e);if(o)throw new Se(o.message,o.issues);let s=e.headers===void 0?`request`in e&&lo(e.request)?e.request.headers:null:e.headers instanceof Headers?e.headers:new Headers(e.headers),c=s?.get(`cookie`),l=c?po(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=fo(e,t);return n&&l?.get(n)||null},getSignedCookie:async(e,t,n)=>{let r=fo(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 to(s,o,await eo(t))?o:!1},setCookie:(e,t,n)=>{let i=go(e,t,n);return r.append(`set-cookie`,i),i},setSignedCookie:async(e,t,n,i)=>{let a=await _o(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 xo(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 So(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 Co(e){return!e||typeof e!=`object`?!1:`_flag`in e&&e._flag===`json`}var wo=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 To(e){for(let t of wo)e.delete(t)}function Eo(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 Do(e,t){if(e instanceof Response){if(t?.headers){let n=new Headers(t.headers);To(n),Eo(e.headers,n)}return e}if(Co(e)){let n=e.body,r=e.routerResponse;if(r instanceof Response)return r;let i=new Headers;if(Eo(i,r?.headers),Eo(i,e.headers),t?.headers){let e=new Headers(t.headers);To(e),Eo(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(oo(e))return Do(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 To(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`)):xo(e)&&(n=So(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 Oo(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 x(`Body is not allowed with GET or HEAD methods`);if(r&&/\/{2,}/.test(r))throw new x(`Path cannot contain consecutive slashes`);let o=async(...e)=>{let t=e[0]||{},{data:n,error:o}=await co(bo(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(oo(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?Do(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 ko(e,t){return[...e??[],...t??[]]}Oo.create=e=>{function t(...t){if(t.length===3){let[n,r,i]=t;return Oo(n,{...r,use:ko(r.use,e?.use)},i)}let[n,r]=t;return Oo({...n,use:ko(n.use,e?.use)},r)}return t};function Ao(e,t){let n=async n=>{let r=n,a=typeof e==`function`?e:t,o=await bo(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 oo(e)&&Object.defineProperty(e,i,{enumerable:!1,configurable:!0,get(){return o.responseHeaders}}),e}};return n.options=typeof e==`function`?{}:e,n}Ao.create=e=>{function t(t,n){if(typeof t==`function`)return Ao({use:e?.use},t);if(!n)throw Error(`Middleware handler is required`);return Ao({...t,method:`*`,use:[...e?.use||[],...t.use||[]]},n)}return t};var jo={};function Mo(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 No(e){let t=[];return e.metadata?.openapi?.parameters?(t.push(...e.metadata.openapi.parameters),t):(e.query instanceof N&&Object.entries(e.query.shape).forEach(([e,n])=>{n instanceof N&&t.push({name:e,in:`query`,schema:{type:Mo(n),...`minLength`in n&&n.minLength?{minLength:n.minLength}:{},description:n.description}})}),t)}function Po(e){if(e.metadata?.openapi?.requestBody)return e.metadata.openapi.requestBody;if(e.body&&(e.body instanceof N||e.body instanceof ue)){let t=e.body.shape;if(!t)return;let n={},r=[];return Object.entries(t).forEach(([e,t])=>{t instanceof N&&(n[e]={type:Mo(t),description:t.description},t instanceof ue||r.push(e))}),{required:e.body instanceof ue?!1:!!e.body,content:{"application/json":{schema:{type:`object`,properties:n,required:r}}}}}}function Fo(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 Io(e,t){return Object.entries(e).forEach(([e,t])=>{let n=t.options;if(t.path&&!n.metadata?.SERVER_ONLY&&(n.method===`GET`&&(jo[t.path]={get:{tags:[`Default`,...n.metadata?.openapi?.tags||[]],description:n.metadata?.openapi?.description,operationId:n.metadata?.openapi?.operationId,security:[{bearerAuth:[]}],parameters:No(n),responses:Fo(n.metadata?.openapi?.responses)}}),n.method===`POST`)){let e=Po(n);jo[t.path]={post:{tags:[`Default`,...n.metadata?.openapi?.tags||[]],description:n.metadata?.openapi?.description,operationId:n.metadata?.openapi?.operationId,security:[{bearerAuth:[]}],parameters:No(n),...e?{requestBody:e}:{requestBody:{content:{"application/json":{schema:{type:`object`,properties:{}}}}}},responses:Fo(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:jo}}var Lo=(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>`,Ro=(()=>{let e=function(){};return e.prototype=Object.create(null),Object.freeze(e.prototype),e})();function zo(){return{root:{key:``},static:new Ro}}function Bo(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 Vo(e){if(!e.includes(`{`))return;let t=Bo(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 Ho=`__rou3_unnamed_`,Uo=`__rou3_esc_`;function Wo(e){return`${Ho}${e}`}function Go(e){return/^(?!__rou3_|_\d)[A-Za-z_]\w*$/.test(e)?e:Uo+e.replace(/[_-]/g,e=>e===`_`?`__`:`_h`)}function Ko(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 qo(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 Jo(e,t,n=Wo){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 Yo(e){return e.includes(`\\`)?e.replace(/\\([:(){}])/g,(e,t)=>`�`+`ABCDE`[`:(){}`.indexOf(t)]):e}function Xo(e){return e.startsWith(`**`)?2:e===`*`||e.includes(`:`)||e.includes(`(`)||qo(e)?1:e===`\\*`?`*`:e===`\\*\\*`?`**`:e.includes(`�`)?e.replace(/\uFFFD([A-E])/g,(e,t)=>t===`A`?`:`:t===`B`?`(`:t===`C`?`)`:t===`D`?`{`:`}`):e}function Zo(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 Qo(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 $o(e){let t=e.split(`/`);return t.shift(),t[t.length-1]===``&&t.pop(),t}function es(e){let t=$o(e);for(;t[t.length-1]===``;)t.pop();return t}function ts(e,t){let n=new Ro;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[Ko(t)]=e.groups[t]}}return n}function ns(e,t=``,n,r){t=t.toUpperCase(),n.charCodeAt(0)!==47&&(n=`/${n}`);let i=Vo(n);if(i){for(let n of i)ns(e,t,n,r);return}n=Yo(n);let a=es(n),o=Zo(a);if(o){for(let n of o)ns(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=Xo(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]=rs(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 Ro),s.static[t]=e,s=e}}let d=l.length>0,f=s.methods??=new Ro;(f[t]??=[]).push({data:r||null,paramsRegexp:u,paramsMap:d?l:void 0}),d||(e.static[`/`+a.join(`/`)]=s)}function rs(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]=Jo(r,n);let a=r.replace(/:([\w-]+)(?:\(([^)]*)\))?/g,(e,t,n)=>`(?<${Go(t)}>${n||`[^/]+`})`).replace(/\((?![?<])/g,()=>`(?<${Wo(n++)}>`).replace(/\uFFFE(.)/g,(e,t)=>/[.*+?^${}()|[\]\\]/.test(t)?`\\${t}`:t);return[RegExp(`^${a}$`),n]}function is(e,t=``,n,r){r?.normalize&&(n=Qo(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=$o(n),o=as(e.root,t,a,0);if(o!==void 0)return r?.params===!1?o:{data:o.data,params:o.paramsMap?ts(a,o.paramsMap):void 0}}function as(e,t,n,r){if(r===n.length){if(e.methods){let r=os(e.methods,t,n,e.key===`*`,!1);if(r)return r}return e.param?.methods&&os(e.param.methods,t,n,!0,!0)||e.wildcard?.methods&&os(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=as(a,t,n,r+1);if(e)return e}}if(e.param){let i=as(e.param,t,n,r+1);if(i)return i}if(e.wildcard&&e.wildcard.methods)return os(e.wildcard.methods,t,n,!0,!1)}function os(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 ss(e,t=``,n,r){r?.normalize&&(n=Qo(n)),n.charCodeAt(n.length-1)===47&&(n=n.slice(0,-1));let i=$o(n),a=cs(e.root,t,i,0);return r?.params===!1?a:a.map(e=>({data:e.data,params:e.paramsMap?ts(i,e.paramsMap):void 0}))}function cs(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)ls(i,a,!0);else{let e=[];for(let t of a){let n=t.paramsMap;n?.[n.length-1]?.[2]&&e.push(t)}ls(i,e,!0)}}}if(e.param){if(r<n.length){let o=i.length;if(cs(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)}ls(i,e,!0)}}}if(r<n.length){let o=e.static?.[a];o&&cs(o,t,n,r+1,i)}if(r===n.length&&e.methods){let n=e.methods[t]||e.methods[``];n&&ls(i,n,e.key===`*`)}return i}function ls(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 us=(e,t)=>{if(!t?.openapi?.disabled){let n={path:`/api/reference`,...t?.openapi};e.openapi=Oo(n.path,{method:`GET`},async t=>{let r=await Io(e);return new Response(Lo(r,n.scalar),{headers:{"Content-Type":`text/html`}})})}let n=zo(),r=zo();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)ns(n,r,t.path,t)}if(t?.routerMiddleware?.length)for(let{path:e,middleware:n}of t.routerMiddleware)ns(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=is(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 ao(u.options.cloneRequest?e.clone():e,n),query:l,_flag:`router`,asResponse:!0,context:t?.routerContext},a=ss(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 Do(r)}catch(e){if(oo(e))return Do(e);throw e}if(t?.throwError)throw n;return oo(n)?Do(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=lo(n)?n:e,i=await a(r),o=await t?.onResponse?.(i,r);return o instanceof Response?o:i},endpoints:e}};function ds(e){return Object.fromEntries(Object.entries(e).map(([e,t])=>[e,{code:e,message:t,toString:()=>e}]))}var fs=ds({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 ps(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 ms(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:ps(e.scope),idToken:e.id_token,raw:e}}function hs(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 gs(e){let t=Array.isArray(e)?e[0]:e;return typeof t==`string`&&t.length>0?t:void 0}async function _s(e){let t=new TextEncoder().encode(e),n=await crypto.subtle.digest(`SHA-256`,t);return d.encode(new Uint8Array(n),{padding:!1})}var vs=/^Basic +(.*)$/i;function ys(e){return new URLSearchParams({v:e}).toString().slice(2)}function bs(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 xs(e,t){let n=`${ys(e)}:${ys(t)}`;return`Basic ${D.encode(n)}`}function Ss(e){let t=e.match(vs);if(!t)throw Error(`Authorization header is not a Basic credential`);let n=t[1]??``,r=new TextDecoder().decode(D.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:bs(a),clientSecret:bs(o)}}var Cs=[`RS256`,`RS384`,`RS512`,`PS256`,`PS384`,`PS512`,`ES256`,`ES384`,`ES512`,`EdDSA`],ws=`urn:ietf:params:oauth:client-assertion-type:jwt-bearer`;async function Ts({getClientAssertion:e,context:t}){return{client_assertion:await e(t),client_assertion_type:ws}}var Es=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)}},Ds=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}},Os=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}},ks=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 As(e){if(typeof e==`number`)return new Os({type:`linear`,attempts:e,delay:1e3});switch(e.type){case`linear`:return new Os(e);case`exponential`:return new ks(e);default:throw Error(`Invalid retry strategy`)}}var js=[`get`,`post`,`put`,`patch`,`delete`];function Ms(e){if(!e.startsWith(`@`))return{method:void 0,path:e};let t=e.indexOf(`/`),n=e.slice(1,t===-1?void 0:t);return js.includes(n)?{method:n,path:t===-1?e:e.slice(t+1)}:{method:void 0,path:e}}var Ns=e=>e===`.`||e===`..`,Ps=e=>e.split(`:`).map(e=>encodeURIComponent(e)).join(`:`);function Fs(e,t){let n=t.get(e);if(n===void 0)return Ps(e);if(Ns(n))throw TypeError(`Path parameters cannot be reserved path segments`);return encodeURIComponent(n)}function Is(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}=Ms(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=>Fs(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 Ls=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},Rs=/^application\/(?:[\w!#$%&*.^`~-]*\+)?json(;.+)?$/i;function zs(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 Rs.test(r)?`json`:n.has(r)||r.startsWith(`text/`)?`text`:`blob`}function Bs(e){try{return JSON.parse(e),!0}catch{return!1}}function Vs(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 Hs(e){try{return JSON.parse(e)}catch{return e}}function Us(e){return typeof e==`function`}function Ws(e){if(e?.customFetchImpl)return e.customFetchImpl;if(typeof globalThis<`u`&&Us(globalThis.fetch))return globalThis.fetch;if(typeof window<`u`&&Us(window.fetch))return window.fetch;throw Error(`No fetch implementation found`)}function Gs(...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 Ks(e){let t=new Headers(Gs(e?.headers,await Ls(e)));if(!t.has(`content-type`)){let n=qs(e?.body);n&&t.set(`content-type`,n)}return t}function qs(e){return Vs(e)?`application/json`:null}function Js(e){let t=e.get(`content-type`);return t?t.split(`;`)[0].trim().toLowerCase():null}function Ys(e,t){let{body:n}=e;return n?!Vs(n)||typeof n==`string`?n:Js(t)===`application/x-www-form-urlencoded`?new URLSearchParams(n).toString():JSON.stringify(n):null}function Xs(e,t){if(t?.method)return t.method.toUpperCase();let{method:n}=Ms(e);return n?n.toUpperCase():t?.body?`POST`:`GET`}function Zs(e,t){let n;return!e?.signal&&e?.timeout&&(n=setTimeout(()=>t?.abort(),e?.timeout)),{abortTimeout:n,clearTimeout:()=>{n&&clearTimeout(n)}}}var Qs=class e extends Error{constructor(t,n){super(n||JSON.stringify(t,null,2)),this.issues=t,Object.setPrototypeOf(this,e.prototype)}};async function $s(e,t){let n=await e[`~standard`].validate(t);if(n.issues)throw new Qs(n.issues);return n.value}function ec(e){"@babel/helpers - typeof";return ec=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},ec(e)}function tc(e,t){if(ec(e)!=`object`||!e)return e;var n=e[Symbol.toPrimitive];if(n!==void 0){var r=n.call(e,t||`default`);if(ec(r)!=`object`)return r;throw TypeError(`@@toPrimitive must return a primitive value.`)}return(t===`string`?String:Number)(e)}function nc(e){var t=tc(e,`string`);return ec(t)==`symbol`?t:t+``}function rc(e,t,n){return(t=nc(t))in e?Object.defineProperty(e,t,{value:n,enumerable:!0,configurable:!0,writable:!0}):e[t]=n,e}function ic(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 ac(e){for(var t=1;t<arguments.length;t++){var n=arguments[t]==null?{}:arguments[t];t%2?ic(Object(n),!0).forEach(function(t){rc(e,t,n[t])}):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(n)):ic(Object(n)).forEach(function(t){Object.defineProperty(e,t,Object.getOwnPropertyDescriptor(n,t))})}return e}var oc=async(e,t)=>{var n;let{hooks:r,url:i,options:a}=await Ds(e,t),o=Ws(a),s=new AbortController,c=a.signal??s.signal,l=Is(i,a),u=await Ks(a),d=Ys(a,u),f=Xs(i,a),p=ac(ac({},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}=Zs(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(ac(ac({},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=zs(h),n={data:null,response:h,request:p};if(e===`json`||e===`text`){let e=await h.text();n.data=await(p.jsonParser??Hs)(e)}else n.data=await h[e]();p?.output&&p.output&&!p.disableValidation&&(n.data=await $s(p.output,n.data));for(let e of r.onSuccess)if(e){var v;await e(ac(ac({},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??Hs,b=await h.text(),x=Bs(b),S=x?await y(b):null,C={response:h,responseText:b,request:p,error:ac(ac({},S),{},{status:h.status,statusText:h.statusText})};for(let e of r.onError)if(e){var w;await e(ac(ac({},C),{},{response:t!=null&&(w=t.hookOptions)!=null&&w.cloneResponse?h.clone():h}))}if(t?.retry){let n=As(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 oc(e,ac(ac({},t),{},{retryAttempt:i+1}))}}if(t?.throw)throw new Es(h.status,h.statusText,x?S:b);return{data:null,error:ac(ac({},S),{},{status:h.status,statusText:h.statusText})}},sc=new Set([301,302,303,307,308]);function cc(e){return e.type===`opaqueredirect`||sc.has(e.status)}function lc(e){return new H(`The OAuth endpoint "${e}" returned an HTTP redirect. Server-side OAuth fetches refuse redirects to prevent SSRF; configure the final endpoint URL.`)}async function uc(e,t){let n=!1,r=t?.onError,i=await oc(e,{...t,redirect:`manual`,async onError(e){cc(e.response)&&(n=!0),await r?.(e)}}).catch(t=>{throw n?lc(e):t});if(n)throw lc(e);return i}var dc=`dpop+jwt`,fc=[`EdDSA`,`ES256`,`ES512`,`PS256`,`RS256`],pc=300,mc=512,hc=new Set([`d`,`p`,`q`,`dp`,`dq`,`qi`,`oth`,`k`]);function gc(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 _c(e){return e instanceof Error&&`code`in e&&e.code===`invalid_dpop_proof`}function vc(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 yc(e){return vc(e)?.token??e}function bc(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 xc(e){let t=await crypto.subtle.digest(`SHA-256`,new TextEncoder().encode(e));return K(new Uint8Array(t))}async function Sc(e){return vi(e,`sha256`)}function Cc(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 wc(e){return Cc(e.cnf)}function Tc(e,t){let n=e[t];return typeof n==`string`&&n.length>0?n:void 0}function Ec(e,t){let n=e[t];return typeof n==`number`&&Number.isFinite(n)?n:void 0}function Dc(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 Oc(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 hc)if(t in e)throw Y(`invalid_dpop_proof`,`DPoP proof jwk must not contain private key material`)}async function kc(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 K(new Uint8Array(n))}async function Ac(e,t){if(e&&!await e.reserve(t))throw Y(`invalid_dpop_proof`,`DPoP proof jti has already been used`)}async function jc({proofJwt:e,method:t,url:n,accessToken:r,expectedJkt:i,requireAth:a=!1,nowSeconds:o=Math.floor(Date.now()/1e3),proofMaxAgeSeconds:s=pc,signingAlgorithms:c=fc,replayStore:l}){if(!e||e.split(`.`).length!==3)throw Y(`invalid_dpop_proof`,`DPoP proof must be a compact JWT`);let u;try{u=wi(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"`);Dc(u.alg,c),Oc(u.jwk);let d;try{d=(await qr(e,await Ci(u.jwk,u.alg),{typ:dc})).payload}catch(e){throw Y(`invalid_dpop_proof`,e instanceof Error?e.message:`DPoP proof signature is invalid`)}let f=Tc(d,`htm`),p=Tc(d,`htu`),m=Tc(d,`jti`),h=Ec(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>mc)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=bc(n),_=bc(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=Tc(d,`ath`);if(a&&!v)throw Y(`invalid_dpop_proof`,`DPoP proof must include an ath claim`);if(r!==void 0&&v!==await xc(r))throw Y(`invalid_dpop_proof`,`DPoP proof ath does not match the access token`);let y=await Sc(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 kc({jkt:y,htm:f.toUpperCase(),htu:g,jti:m}),x=new Date((h+s)*1e3);return await Ac(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 Mc(e,t){return Object.assign(Error(t),{code:e})}function Nc(e){return e instanceof Error&&`code`in e&&(e.code===`invalid_token`||e.code===`invalid_dpop_proof`)}async function Pc({payload:e,authorization:t,proofJwt:n,method:r,url:i,replayStore:a,proofMaxAgeSeconds:o,signingAlgorithms:s}){let c=wc(e);if(c){if(t.scheme!==`DPoP`)throw Mc(`invalid_token`,`DPoP-bound access token requires the DPoP authorization scheme`);if(!n)throw Mc(`invalid_dpop_proof`,`DPoP proof header is required`);try{await jc({proofJwt:n,method:r,url:i,accessToken:t.token,expectedJkt:c,requireAth:!0,proofMaxAgeSeconds:o,signingAlgorithms:s,replayStore:a})}catch(e){throw _c(e)?Mc(`invalid_dpop_proof`,e.message):e}}else if(t.scheme===`DPoP`)throw Mc(`invalid_token`,`DPoP authorization requires a DPoP-bound access token`)}Ct.code,bt.code,St.code;var Fc=new Map,Ic=new WeakMap,Lc=3e5,Rc=3e4,zc=5e3;function Bc(e,t){let n=e.get(t);return n||(n={fetchedAt:0,refetchedAt:0},e.set(t,n)),n}function Vc(e,t){return e.pending!==void 0&&t-e.pending.startedAt<zc}async function Hc(e,t){let n=Date.now();if(!e.pending||!Vc(e,n)){let r={startedAt:n,promise:Wc(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 Ct),i+zc-n)})])}finally{clearTimeout(a)}}async function Uc(e,t,n){if(e.jwks!==t)return e.jwks;let r=Date.now();if(!Vc(e,r)){if(r-e.refetchedAt<Rc)return;e.refetchedAt=r}return Hc(e,n)}async function Wc(e){try{let t=typeof e==`string`?await uc(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{ye.error(`JWKS fetch failed:`,e)}catch{}throw Error(`JWKS fetch failed`)}throw e}}async function Gc(e,t){return(await Kc(e,t)).jwks}async function Kc(e,t){let n;try{n=wi(e)}catch(e){throw e instanceof Error?e:Error(e)}let r=n.kid,i=typeof t.jwksFetch==`string`?Bc(Fc,t.jwksFetch):t.jwksCacheKey?Bc(Ic,t.jwksCacheKey):{fetchedAt:0,refetchedAt:0},a=Date.now()-i.fetchedAt<Lc?i.jwks:void 0;if(!a)return{jwks:await Hc(i,t.jwksFetch),kid:r};let o=e=>Uc(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 qc=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})),Jc=`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(`.`),Yc=new Set([...qc,...Jc,`public`,`type`,`resources`,`client_credentials_scopes`]),Xc=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 Zc(e){return Xc.has(e)}function Qc(e){return Yc.has(e)}function $c(e){if(e)return Object.fromEntries(Object.entries(e).filter(([e])=>!Yc.has(e)))}var el=[`authorization_code`,`client_credentials`,`refresh_token`],tl=[`client_secret_basic`,`client_secret_post`,`private_key_jwt`],nl=[`none`,...tl],rl=new Set(nl);function il(e,t){if(!(t.trim().length>0))throw new H(`OAuth Provider extension ${e} cannot be empty`)}function al(e,t){il(e,t);let n;try{n=new URL(t)}catch{n=void 0}if(!n?.protocol)throw new H(`OAuth Provider extension ${e} must be an absolute URI: ${t}`)}function ol(e){al(`grant type`,e)}function sl(e){if(il(`token_endpoint_auth_method`,e),rl.has(e))throw new H(`OAuth Provider extension token_endpoint_auth_method is reserved: ${e}`)}function cl(e){if(al(`client_assertion_type`,e),e===`urn:ietf:params:oauth:client-assertion-type:jwt-bearer`)throw new H(`OAuth Provider extension client_assertion_type is reserved: ${e}`)}function ll(e){let t=Object.keys(e.grants??{});for(let e of t)ol(e);let n=[],r=[];for(let[t,i]of Object.entries(e.clientAuthentication??{})){sl(t),n.push(t);let e=i.assertionTypes??[t];if(e.length===0)throw new H(`OAuth Provider extension client_assertion_type list cannot be empty for ${t}`);for(let t of e)cl(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)il(`client discovery id`,e);for(let t of e.clientMetadata?.fields??[])if(il(`client metadata field`,t),Qc(t))throw new H(`OAuth Provider extension client metadata field is reserved: ${t}`);return{grantTypes:t,authMethods:n,assertionTypes:r,clientDiscoveryIds:i,interactionRequestParameters:Object.keys(e.interactionRequests??{})}}function ul(e,t){let n=new Set;for(let r of t){if(n.has(r))throw new H(`OAuth Provider extensions register ${e} "${r}" more than once. Extension contributions must be disjoint.`);n.add(r)}}function dl(e){let t=(e??[]).map(ll);ul(`grant type`,t.flatMap(e=>e.grantTypes)),ul(`token_endpoint_auth_method`,t.flatMap(e=>e.authMethods)),ul(`client_assertion_type`,t.flatMap(e=>e.assertionTypes)),ul(`client discovery id`,t.flatMap(e=>e.clientDiscoveryIds)),ul(`interaction request parameter`,t.flatMap(e=>e.interactionRequestParameters))}function fl(e){return e.extensions??[]}function pl(e){return fl(e).flatMap(e=>{let t=e.clientDiscovery;return t?Array.isArray(t)?t:[t]:[]})}function ml(e,t){let n=e.getPlugin(`oauth-provider`);if(!n)throw new H(`extendOAuthProvider requires the oauth-provider plugin.`);let r=n.options.extensions??[];if(r.includes(t))return;let i=[...r,t];dl(i),n.options.extensions=i}function hl(e){return fl(e).flatMap(e=>Object.keys(e.grants??{}))}function gl(e){return Array.from(new Set([...e.grantTypes??el,...hl(e)]))}function _l(e,t){let n=t;if(n.response_type===void 0&&n.request_uri===void 0)for(let t of fl(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 vl(e,t){for(let n of fl(e)){let e=n.grants?.[t];if(e)return e}}function yl(e){return fl(e).flatMap(e=>Object.keys(e.clientAuthentication??{}))}function bl(e,t){return Array.from(new Set([...t?.includeNone?[`none`]:[],...tl,...yl(e)]))}function xl(e,t){return t?yl(e).includes(t):!1}function Sl(e,t){if(t!==`urn:ietf:params:oauth:client-assertion-type:jwt-bearer`)for(let n of fl(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 Cl(e,t,n,r){let i={...r};for(let a of fl(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 wl(e,t){let n={};for(let r of fl(e)){let e=await t(r)??{};for(let[t,r]of Object.entries(e))t in n?ye.warn(`oauth-provider: two extensions contributed the claim "${t}"; keeping the first-registered value.`):n[t]=r}return n}function Tl(e,t){return wl(e,e=>e.claims?.accessToken?.(t))}function El(e,t){return wl(e,e=>e.claims?.idToken?.(t))}function Dl(e,t){return wl(e,e=>e.claims?.userInfo?.(t))}function Ol(e){return fl(e).some(e=>e.clientMetadata)}function kl(e){return new Set(fl(e).flatMap(e=>e.clientMetadata?.fields??[]))}async function Al(e,t,n){let{metadata:r,...i}=t,a=kl(e),o={client:Object.fromEntries(Object.entries(i).filter(([e])=>!a.has(e))),metadata:$c(n)??{}};for(let t of fl(e))await t.clientMetadata?.validate?.(o)}function jl(e){return fl(e).some(e=>e.claims?.userInfo)}function Ml(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 Nl(){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 Pl=e=>e.getPlugin(`oauth-provider`),Fl=e=>{let t=e.getPlugin(`jwt`);if(!t)throw new H(`jwt_config`);return t};function Il(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 Ll(e){if(e instanceof Date||!e||typeof e!=`object`)return Il(e);let t=Il(e.createdAt)??Il(e.created_at);if(t)return t;let n=e.session;if(n&&typeof n==`object`)return Il(n.createdAt)??Il(n.created_at)}function Rl(e){if(typeof e==`string`)return[e];if(e?.length)return e}function zl(e){if(typeof e==`string`)return e;if(e?.length)return e.length===1?e.at(0):e}var Bl=new WeakMap;function Vl(e){let t=Bl.get(e);if(t)return t;let n=Nl();return Bl.set(e,n),n}async function Hl(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 Qa(Me(n).toString(),t);return i.length===1&&!!r&&Bi(r,o)&&new Date(a*1e3)>=new Date}function Ul(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 Wl(e,t,n){let r=Vl(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=pl(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 Gl(e){return e.reduce((e,t)=>({...e,...t.discoveryMetadata??{}}),{})}var Kl=async e=>{let t=await Ui(`SHA-256`).digest(new TextEncoder().encode(e));return d.encode(new Uint8Array(t),{padding:!1})};async function ql(e,t,n){if(t===`encrypted`)return await Xa({key:e.context.secretConfig,data:n});if(typeof t==`object`&&`decrypt`in t)return await t.decrypt(n);throw new H(`Unsupported decryption storageMethod type '${t}'`)}async function Jl(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 Kl(r):void 0;return!!e&&Bi(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&&Bi(e,n)}}if(i===`encrypted`)try{let t=await ql(e,i,n);return!!r&&Bi(t,r)}catch{return!1}if(typeof i==`object`&&`decrypt`in i){let t=await ql(e,i,n);return!!r&&Bi(t,r)}throw new H(`Unsupported verify storageMethod type '${i}'`)}async function Yl(e,t,n){let r=t.storeClientSecret??(t.disableJwtPlugin?`encrypted`:`hashed`);if(r===`encrypted`)return await Ya({key:e.context.secretConfig,data:n});if(r===`hashed`)return await Kl(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 H(`Unsupported storeClientSecret type '${r}'`)}async function Xl(e=`hashed`,t,n){if(e===`hashed`)return await Kl(t);if(typeof e==`object`&&`hash`in e)return await e.hash(t,n);throw new H(`storeToken: unsupported storageMethod type '${e}'`)}async function Zl(e=`hashed`,t,n){if(e===`hashed`)return await Kl(t);if(typeof e==`object`&&`hash`in e)return await e.hash(t,n);throw new H(`getStoredToken: unsupported storageMethod type '${e}'`)}var Ql=/^Basic +/i,$l=/^([!#$%&'*+\-.^_`|~0-9A-Za-z]+)(?=\s|$)/;function eu(e){return e.match($l)?.[1]}var tu=[`client_secret`,`client_assertion`,`client_assertion_type`];function nu(e){throw new g(`BAD_REQUEST`,{error:`invalid_request`,error_description:e})}async function ru(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 iu(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 au(e,t={}){let n;t.client_id!==void 0&&t.client_id!==``&&(typeof t.client_id!=`string`&&nu(`client_id must be a string`),n=t.client_id);let r={},i=(e,t)=>{t!==void 0&&t!==``&&(typeof t!=`string`&&nu(`${e} must be a string`),r[e]=t)};for(let e of tu)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&&nu(`client_id must not be repeated`),n=r[0];for(let e of tu){let n=t.getAll(e).filter(e=>e.length>0);n.length>1&&nu(`${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)&&nu(`A request must use only one client authentication method`),t.client_id=n;for(let e of tu)t[e]=r[e];return{detected:a||Object.keys(r).length>0}}function ou(e){if(Ql.test(e))try{let{clientId:t,clientSecret:n}=Ss(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 su(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 cu(e,t,n){throw new g(e,{error:t,error_description:n})}function lu(e){let t=e?.trim();return t?t.split(/\s+/):[]}function uu(e,t,n){let r=e.resources??[];return t.every(t=>e.scopes.includes(t))&&n.every(e=>r.includes(e))}function du(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 fu(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 pu(e,t,n,r,i,a,o,s){let c=await Wl(e,t,n);c||fu(`client not found`,{method:s}),c.disabled&&fu(`client is disabled`,{method:s});let l=c.tokenEndpointAuthMethod??`client_secret_basic`;if(s&&l!==s&&fu(`client registered for ${l} cannot use ${s}`,{method:s}),(c.tokenEndpointAuthMethod===`private_key_jwt`||xl(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&&fu(`client secret must be provided`,{method:s}),r&&!c.clientSecret&&fu(`public client, client secret should not be received`,{method:s}),r&&!await Jl(e,t,c.clientSecret,r)&&fu(`invalid client_secret`,{method:s})),du(c,i),o&&!su(c,o))throw new g(`BAD_REQUEST`,{error_description:`client is not authorized to use grant type ${o}`,error:`unauthorized_client`});return c}function mu(e){if(e)return typeof e==`string`?JSON.parse(e):e}function hu(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 gu(e,t,n){let r={...e.body??{}};await au(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=Sl(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(()=>Zg).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&&!Ql.test(i)){let e=eu(i);if(!e)throw new g(`BAD_REQUEST`,{error:`invalid_request`,error_description:`Invalid authorization header format`});fu(`unsupported authorization scheme`,{scheme:e})}if(i&&Ql.test(i)){let e=ou(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 _u(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 vu(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 yu(e){if(e.sectorIdentifier)return e.sectorIdentifier;let t=e.redirectUris?.[0];if(!t)throw new H(`Client has no redirect URIs for sector identifier`);return new URL(t).host}async function bu(e,t,n){return Qa(`${yu(t)}.${e}`,n)}async function xu(e,t,n){return t.subjectType===`pairwise`&&n.pairwiseSecret?bu(e,t,n.pairwiseSecret):e}async function Su(e,t){return await e.postLogin?.consentReferenceId?.(t)||void 0}async function Cu(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 wu(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 Tu(e,t){if(!t)return!1;let n=Il(e);return n?n.getTime()>=t.getTime():!1}function Eu(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 Du(e){let t=new URLSearchParams(e);return t.delete(`max_age`),t}function Ou(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 ku(e){return e instanceof g||e instanceof P||e?.name===`APIError`}var Au,ju=!1;function Mu(){try{return globalThis.process?.getBuiltinModule?.(`node:async_hooks`)?.AsyncLocalStorage}catch{return}}async function Nu(){if(Au)return Au;let e=Mu();if(e)return Au??=e,Au;try{let{AsyncLocalStorage:e}=await import(`node:async_hooks`);return Au??=e,Au}catch(e){let t=globalThis.AsyncLocalStorage;if(typeof t==`function`)return Au??=t,Au;throw typeof window<`u`?Error(`getAsyncLocalStorage is only available in server code`):(ju||(ju=!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 Pu=()=>s().context.endpointContextAsyncStorage,Fu=async()=>{let e=Pu();if(e)return e;let t=await Nu(),n=s().context;return n.endpointContextAsyncStorage??=new t};function Iu(){return o()}function Lu(){let e=Iu();if(!e)throw Error("No auth context found. Please make sure you are calling this function within a `runWithEndpointContext` callback.");return e}async function Ru(e,t){return(await Fu()).run(e,t)}var zu={"Cache-Control":`no-store`,Pragma:`no-cache`};function Bu(e,t){ku(t)&&e&&Object.defineProperty(t,i,{enumerable:!1,configurable:!0,value:e,writable:!1})}var Vu=Ao(async()=>({})),Hu=Ao.create({use:[Vu,Ao(async()=>({}))]}),Uu=Oo.create({use:[Vu]});function Wu(e,t){let n=t.metadata?.noStore===!0;return async t=>{if(n)for(let[e,n]of Object.entries(zu))t.setHeader(e,n);try{return await Ru(t,()=>e(t))}catch(e){throw Bu(t.responseHeaders,e),e}}}function X(...e){if(e.length===3){let[t,n,r]=e;return Uu(t,n,Wu(r,n))}let[t,n]=e;return Uu(t,Wu(n,t))}function Gu(e){return{...e,metadata:{...e.metadata,SERVER_ONLY:!0}}}X.serverOnly=(e,t)=>X(Gu(e),t);function Ku(e){return e===`-`||e===`^`||e===`$`||e===`+`||e===`.`||e===`(`||e===`)`||e===`|`||e===`[`||e===`]`||e===`{`||e===`}`||e===`*`||e===`?`||e===`\\`?`\\${e}`:e}function qu(e){let t=``;for(let n=0;n<e.length;n++)t+=Ku(e[n]);return t}function Ju(e,t=!0){if(Array.isArray(e))return`(?:${e.map(e=>`^${Ju(e,t)}$`).join(`|`)})`;let n=``,r=``,i=`.`;t===!0?(n=`/`,r=`[/\\\\]`,i=`[^/\\\\]`):t&&(n=t,r=qu(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+=Ku(n[e+1]),e++):c+=t===`?`?i:t===`*`?`${i}*?`:Ku(t)}c+=l}}}return c}function Yu(e,t){if(typeof t!=`string`)throw TypeError(`Sample must be a string, but ${typeof t} given`);return e.test(t)}function Xu(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=Ju(e,t.separator),r=RegExp(`^${n}$`,t.flags),i=Yu.bind(null,r);return i.options=t,i.pattern=e,i.regexp=r,i}var Zu=47;function Qu(e){let t=e.replace(/:\d+$/,``).replace(/^\[|\]$/g,``).toLowerCase();return t===`localhost`||t.endsWith(`.localhost`)||t===`::1`||t.startsWith(`127.`)}function $u(e){let t=e.length;for(;t>0&&e.charCodeAt(t-1)===Zu;)t--;return t===e.length?e:e.slice(0,t)}function ed(e){try{return($u(new URL(e).pathname)||`/`)!==`/`}catch{throw new H(`Invalid base URL: ${e}. Please provide a valid base URL.`)}}function td(e){try{let t=new URL(e);if(t.protocol!==`http:`&&t.protocol!==`https:`)throw new H(`Invalid base URL: ${e}. URL must include 'http://' or 'https://'`)}catch(t){throw t instanceof H?t:new H(`Invalid base URL: ${e}. Please provide a valid base URL.`,{cause:t})}}function nd(e,t=`/api/auth`){if(td(e),ed(e))return e;let n=$u(e);return!t||t===`/`?n:(t=t.startsWith(`/`)?t:`/${t}`,`${n}${t}`)}function rd(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 id(e,t,n,r,i){if(e)return nd(e,t);if(r!==!1){let e=ae.BETTER_AUTH_URL||ae.NEXT_PUBLIC_BETTER_AUTH_URL||ae.PUBLIC_BETTER_AUTH_URL||ae.NUXT_PUBLIC_BETTER_AUTH_URL||ae.NUXT_PUBLIC_AUTH_URL||(ae.BASE_URL===`/`?void 0:ae.BASE_URL);if(e)return nd(e,t)}let a=n?.headers.get(`x-forwarded-host`),o=n?.headers.get(`x-forwarded-proto`);if(a&&o&&i&&rd(o,`proto`)&&rd(a,`host`))try{return nd(`${o}://${a}`,t)}catch{}if(n){let e=ad(n.url);if(!e)throw new H(`Could not get origin from request. Please provide a valid base URL.`);return nd(e,t)}if(typeof window<`u`&&window.location)return nd(window.location.origin,t)}function ad(e){try{let t=new URL(e);return t.origin===`null`?null:t.origin}catch{return null}}function od(e){try{return new URL(e).protocol}catch{return null}}function sd(e){try{return new URL(e).host}catch{return null}}function cd(e){return typeof e==`object`&&!!e&&`allowedHosts`in e&&Array.isArray(e.allowedHosts)}function ld(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 ud(e,t){let n=ld(e)?e.headers:e;if(t){let e=n.get(`x-forwarded-host`);if(e&&rd(e,`host`))return e}let r=n.get(`host`);if(r&&rd(r,`host`))return r;if(ld(e))try{return new URL(e.url).host}catch{return null}return null}function dd(e,t,n){if(t===`http`||t===`https`)return t;let r=ld(e)?e.headers:e;if(n){let e=r.get(`x-forwarded-proto`);if(e&&rd(e,`proto`))return e}if(ld(e))try{let t=new URL(e.url);if(t.protocol===`http:`||t.protocol===`https:`)return t.protocol.slice(0,-1)}catch{}let i=ud(e,n);return i&&Qu(i)?`http`:`https`}var fd=(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(`?`)?Xu(r)(n):n.toLowerCase()===r.toLowerCase()};function pd(e,t,n,r){let i=ud(t,r);if(!i){if(e.fallback)return nd(e.fallback,n);throw new H(`Could not determine host from request headers. Please provide a fallback URL in your baseURL config.`)}if(e.allowedHosts.some(e=>fd(i,e)))return nd(`${dd(t,e.protocol,r)}://${i}`,n);if(e.fallback)return nd(e.fallback,n);throw new H(`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 md(e,t,n,r,i){if(cd(e))return n?pd(e,n,t,i):e.fallback?nd(e.fallback,t):id(void 0,t,void 0,r,i);let a=ld(n)?n:void 0;return id(typeof e==`string`?e:void 0,t,a,r,i)}function hd(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 gd=`https://better-auth.invalid`;function _d(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,gd):new URL(e);if(n&&r.origin!==gd)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 vd=[`javascript:`,`data:`,`vbscript:`],yd=ve(),bd=xe();function xd(e){return Sd(e)||Cd(e)}function Sd(e){return pe(yd,e)}function Cd(e){return pe(bd,e)}function wd(e){let t=e.toLowerCase();if(t.startsWith(`::ffff:`)){let e=t.substring(7);if(Sd(e))return e}let n=e.split(`:`);if(n.length===7&&n[5]?.toLowerCase()===`ffff`){let e=n[6];if(e&&Sd(e))return e}if(t.includes(`::ffff:`)||t.includes(`:ffff:`)){let t=Td(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 Td(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 Ed(e,t){let n=Td(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 Dd(e,t={}){if(Sd(e)||!Cd(e))return e.toLowerCase();let n=wd(e);return n?n.toLowerCase():Ed(e,t.ipv6Subnet??64)}function Od(e){if(Sd(e))return Uint8Array.from(e.split(`.`).map(e=>Number(e)));if(!Cd(e))return null;let t=wd(e);if(t)return Uint8Array.from(t.split(`.`).map(e=>Number(e)));let n=Td(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 kd=/^\d+$/;function Ad(e){let t=e.lastIndexOf(`/`),n=Od(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(!kd.test(i))return null;let a=Number(i);return a<=r?{bytes:n,prefix:a}:null}function jd(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 Md(e){return e.filter(e=>Ad(e)===null)}function Nd(e,t={}){let n=e.split(`,`).map(e=>e.trim()).filter(Boolean);if(n.length===0)return null;let r=(t.trustedProxies??[]).map(Ad).filter(e=>e!==null);if(r.length>0){for(let e=n.length-1;e>=0;e--){let i=n[e],a=i?Od(i):null;if(!i||!a)return null;if(!r.some(e=>jd(a,e)))return Dd(i,{ipv6Subnet:t.ipv6Subnet})}return null}if(n.length!==1)return null;let i=n[0];return!i||!xd(i)?null:Dd(i,{ipv6Subnet:t.ipv6Subnet})}var Pd=`127.0.0.1`,Fd=[`x-forwarded-for`];function Id(e,t){if(t.advanced?.ipAddress?.disableIpTracking)return null;let n=`headers`in e?e.headers:e,r=t.advanced?.ipAddress?.ipAddressHeaders||Fd;for(let e of r){let r=`get`in n?n.get(e):n[e];if(typeof r==`string`){let e=Nd(r,{ipv6Subnet:t.advanced?.ipAddress?.ipv6Subnet,trustedProxies:t.advanced?.ipAddress?.trustedProxies});if(e)return e}}return p()||y()?Pd:null}function Ld(e,t){return`${e}|${t}`}var Rd=async()=>{let e=s(),t=e.context.requestStateAsyncStorage;if(t)return t;let n=await Nu();return e.context.requestStateAsyncStorage??=new n,e.context.requestStateAsyncStorage};async function zd(){return(await Rd()).getStore()!==void 0}async function Bd(){let e=(await Rd()).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 Vd(e,t){return(await Rd()).run(e,t)}function Hd(e){let t=Object.freeze({});return{get ref(){return t},async get(){let n=await Bd();if(!n.has(t)){let r=await e();return n.set(t,r),r}return n.get(t)},async set(e){(await Bd()).set(t,e)}}}var Ud=async()=>{let e=s(),t=e.context.adapterAsyncStorage;if(t)return t;let n=await Nu();return e.context.adapterAsyncStorage??=new n,e.context.adapterAsyncStorage},Wd=async e=>Ud().then(t=>t.getStore()?.adapter||e).catch(()=>e),Gd=async(e,t)=>{let n=!1;return Ud().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})},Kd=async(e,t,n)=>{let r=!1;return Ud().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{ye.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})},qd=async(e,t)=>{let n=async()=>{try{await e()}catch(e){if(!t?.onError)throw e;await t.onError(e)}},r;try{r=await Ud()}catch{return n()}let i=r.getStore();if(!i?.isTransactionActive)return n();i.pendingHooks.push(n)},{get:Jd,set:Yd}=Hd(()=>null),Xd=async()=>await Jd(),{get:Zd,set:Qd}=Hd(()=>null),$d=async e=>{await Qd({...await Zd()??{},...e})},{get:ef,set:tf}=Hd(()=>!1);function nf(e){return!!e.database||!!e.secondaryStorage}function rf(e){return!!e.database}function af(e){return rf(e)}var of=V({id:v(),createdAt:re().default(()=>new Date),updatedAt:re().default(()=>new Date)}),sf=of.extend({userId:we(),expiresAt:re(),token:v(),ipAddress:v().nullish(),userAgent:v().nullish()}),cf=of.extend({email:v().transform(e=>e.toLowerCase()),emailVerified:z().default(!1),name:v(),image:v().nullish()});function lf(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 uf=new WeakMap;function df(e,t,n){let r=`${t}:${n}`;uf.has(e)||uf.set(e,new Map);let i=uf.get(e);if(i.has(r))return i.get(r);let a=n===`output`?ne(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 ff(e,t){return lf(t,df(e,`user`,`output`))}function pf(e,t){let n=df(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 mf(e,t){return lf(t,df(e,`session`,`output`))}function hf(e,t){let{accessToken:n,refreshToken:r,idToken:i,accessTokenExpiresAt:a,refreshTokenExpiresAt:o,password:s,...c}=lf(t,df(e,`account`,`output`));return c}function gf(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 P.from(`BAD_REQUEST`,{...fs.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 P.from(`INTERNAL_SERVER_ERROR`,fs.ASYNC_VALIDATION_NOT_SUPPORTED);if(`issues`in n&&n.issues)throw P.from(`BAD_REQUEST`,{...fs.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 P.from(`BAD_REQUEST`,{...fs.MISSING_FIELD,message:`${t} is required`});return i}function _f(e,t={},n){return gf(t,{fields:df(e,`user`,`input`),action:n})}function vf(e,t={},n){let r=df(e,`user`,`input`),i=Object.create(null);for(let e of Object.keys(t))r[e]?.input!==!1&&(i[e]=t[e]);return gf(i,{fields:r,action:n})}function yf(e,t,n){return gf(t,{fields:df(e,`session`,`input`),action:n})}function bf(e){let t=df(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 xf(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 Sf=(e,t=`ms`)=>new Date(Date.now()+(t===`sec`?e*1e3:e));function Cf(e){if(e.indexOf(`%`)===-1)return e;try{return decodeURIComponent(e)}catch{return e}}var wf=`__Secure-`;function Tf(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 Ef(e){let t=new Map;return Tf(e).forEach(e=>{let[n,...r]=e.split(`;`).map(e=>e.trim()),[i,...a]=(n||``).split(`=`),o=kf(a.join(`=`));if(!i)return;let s={value:Cf(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 Df=/^[\x21\x23-\x27\x2A\x2B\x2D\x2E\x30-\x39\x41-\x5A\x5E\x5F\x60\x61-\x7A\x7C\x7E]+$/,Of=/^[\x20\x21\x23-\x3A\x3C-\x5B\x5D-\x7E]*$/;function kf(e){return e.length<2||!e.startsWith(`"`)||!e.endsWith(`"`)?e:e.slice(1,-1)}function Af(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 jf(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=Af(n.slice(0,e)),i=kf(Af(n.slice(e+1)));Df.test(r)&&Of.test(i)&&t.set(r,Cf(i))}return t}var Mf=4050,Nf=100;function Pf(e,t){return Mf-go(e,``,{...t}).length}function Ff(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 If(e,t){let n={},r=jf(t.headers?.get(`cookie`)||``);for(let[t,i]of r)(t===e||Ff(e,t)!==null)&&(n[t]=i);return n}function Lf(e,t,n,r){let i=Pf(`${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>Nf)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 ${Mf} byte limit and was split into ${a} chunks.`,valueSize:t.value.length,chunkCount:a,chunkSizes:o.map(e=>e.value.length)}),o}function Rf(e,t){let n={};for(let r in e)n[r]={name:r,value:``,attributes:{...t,maxAge:0}};return n}var zf=e=>(t,n,r)=>{let i=If(t,r),a=r.context.logger,o=()=>{let e=Rf(i,n);for(let e in i)delete i[e];return e};return{chunk(r,s){let c=o(),l=Lf(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)}}},Bf=zf(`Session`),Vf=zf(`Account`);function Hf(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 jf(i)){let i=Ff(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 Uf(e,t){let n=e.context.authCookies.accountData,r={maxAge:300,...n.attributes},i=await Li(t,e.context.secretConfig,`better-auth-account`,r.maxAge),a=Vf(n.name,r,e);a.setCookies(a.chunk(i,r))}async function Wf(e){let t=Hf(e,e.context.authCookies.accountData.name);if(t){let n=ce(await zi(t,e.context.secretConfig,`better-auth-account`));if(n)return n}return null}var Gf=w(V({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 Kf(e){return!!e&&(typeof e==`object`||typeof e==`function`)&&typeof e.then==`function`}var qf=1e3,Jf=qf*60,Yf=Jf*60,Xf=Yf*24,Zf=Xf*7,Qf=Xf*30,$f=Xf*365.25,ep=/^(\+|\-)? ?(\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 tp(e){let t=ep.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*$f;break;case`months`:case`month`:case`mo`:i=n*Qf;break;case`weeks`:case`week`:case`w`:i=n*Zf;break;case`days`:case`day`:case`d`:i=n*Xf;break;case`hours`:case`hour`:case`hrs`:case`hr`:case`h`:i=n*Yf;break;case`minutes`:case`minute`:case`mins`:case`min`:case`m`:i=n*Jf;break;case`seconds`:case`second`:case`secs`:case`sec`:case`s`:i=n*qf;break;default:throw TypeError(`Unknown time unit: "${r}"`)}return t[1]===`-`||t[4]===`ago`?-i:i}function np(e){return tp(e)}function rp(e){return Math.round(tp(e)/1e3)}var ip=be({session:sf.loose(),user:cf.loose(),updatedAt:a(),version:v().optional()}),ap=V({session:c(v(),oe()),expiresAt:a(),signature:v()});function op(e){let t=ce(e);if(t===null)return null;let n=ip.safeParse(t);return n.success?n.data:(ye.warn(`Cookie cache payload failed schema validation`,{issues:n.error.issues.map(({code:e,path:t})=>({code:e,path:t}))}),null)}function sp(e){let t=ap.safeParse(e);return t.success?t.data:null}var cp=new Map,lp=new TextEncoder,up={decode:(e,t=`utf-8`)=>(cp.has(t)||cp.set(t,new TextDecoder(t)),cp.get(t).decode(e)),encode:e=>lp.encode(e)},dp=(e=`SHA-256`,t=`none`)=>{let n={importKey:async(t,n)=>Hi().importKey(`raw`,T(t),{name:`HMAC`,hash:{name:e}},!1,[n]),sign:async(e,r)=>{typeof e==`string`&&(e=await n.importKey(e,`sign`));let i=await Hi().sign(`HMAC`,e,T(r));return t===`hex`?de.encode(i):t===`base64`?D.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`?de.toBytes(i):i),(t===`base64`||t===`base64url`||t===`base64urlnopad`)&&(i=await D.decode(i)),Hi().verify(`HMAC`,e,T(i),T(r)))};return n};function fp(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)?wf:``,i=!!e.advanced?.crossSubDomainCookies?.enabled,a=i?e.advanced?.crossSubDomainCookies?.domain||(t?new URL(t).hostname:void 0):void 0;if(i&&!a&&!cd(e.baseURL))throw new H(`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 pp(e){let t=fp(e),n=t(`session_token`,{maxAge:e.session?.expiresIn||rp(`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 mp(e,t,n){if(!e.context.options.session?.cookieCache?.enabled)return;let r=lf(t.session,e.context.options.session?.additionalFields),i=ff(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=Kf(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=Sf(c.maxAge||60,`sec`).getTime(),u=e.context.options.session?.cookieCache?.strategy||`compact`,f;if(u===`jwe`)f=await Li(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 Oi(s,e.context.secret,c.maxAge||300)}else f=d.encode(JSON.stringify({session:s,expiresAt:l,signature:await dp(`SHA-256`,`base64urlnopad`).sign(e.context.secret,JSON.stringify({...s,expiresAt:l}))}),{padding:!1});let p=Bf(e.context.authCookies.sessionData.name,c,e);if(p.setCookies(p.chunk(f,c)),e.context.options.account?.storeAccountCookie&&!vp(e,e.context.authCookies.accountData.name)){let n=await Wf(e);if(n){if(!af(e.context.options)||n.userId===t.user.id)await Uf(e,n);else{yp(e,e.context.authCookies.accountData);let t=Vf(e.context.authCookies.accountData.name,e.context.authCookies.accountData.attributes,e);t.setCookies(t.clean())}}}}async function hp(e,t){let n=e.context.options.session?.cookieCache?.strategy||`compact`;if(n===`jwe`){let n=await zi(t,e.context.secretConfig,`better-auth-session`),r=op(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 ki(t,e.context.secret),i=op(r);return i?{session:i,expiresAt:r?.exp?r.exp*1e3:Date.now()}:null}let r=sp(ce(up.decode(d.decode(t))));if(!r||!await dp(`SHA-256`,`base64urlnopad`).verify(e.context.secret,JSON.stringify({...r.session,expiresAt:r.expiresAt}),r.signature))return null;let i=op(r.session);return i?{session:i,expiresAt:r.expiresAt}:null}async function gp(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 mp(e,t,n),e.context.setNewSession(t)}function _p(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():Tf(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 vp(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():Tf(e.get(`set-cookie`)||``)).some(e=>e.startsWith(i)||e.startsWith(a)))return!0;return!1}function yp(e,t){_p(e,t.name),e.setCookie(t.name,``,{...t.attributes,maxAge:0})}function bp(e,t){if(yp(e,e.context.authCookies.sessionToken),yp(e,e.context.authCookies.sessionData),e.context.options.account?.storeAccountCookie){yp(e,e.context.authCookies.accountData);let t=Vf(e.context.authCookies.accountData.name,e.context.authCookies.accountData.attributes,e),n=t.clean();t.setCookies(n)}e.context.oauthConfig.storeStateStrategy===`cookie`&&yp(e,e.context.createAuthCookie(`oauth_state`));let n=Bf(e.context.authCookies.sessionData.name,e.context.authCookies.sessionData.attributes,e),r=n.clean();n.setCookies(r),t||yp(e,e.context.authCookies.dontRememberToken)}var xp=()=>X(`/get-session`,{method:[`GET`,`POST`],operationId:`getSession`,query:Gf,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 P.from(`METHOD_NOT_ALLOWED`,fs.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=Hf(e,e.context.authCookies.sessionData.name);if(a&&!r){let t=Bf(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 hp(e,a):null;o&&a&&!s&&yp(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)yp(e,e.context.authCookies.sessionData);else{let n=e.context.sessionConfig.cookieRefreshCache;if(n===!1){e.context.session=t;let n=mf(e.context.options,{...t.session,expiresAt:new Date(t.session.expiresAt),createdAt:new Date(t.session.createdAt),updatedAt:new Date(t.session.updatedAt)}),r=ff(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 ef();if(r<i&&!a){let n={session:{...t.session},user:t.user,updatedAt:Date.now()};await mp(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=mf(e.context.options,{...n.session,expiresAt:new Date(n.session.expiresAt),createdAt:new Date(n.session.createdAt),updatedAt:new Date(n.session.updatedAt)}),o=ff(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=mf(e.context.options,{...t.session,expiresAt:new Date(t.session.expiresAt),createdAt:new Date(t.session.createdAt),updatedAt:new Date(t.session.updatedAt)}),l=ff(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 bp(e),l&&(!t||n)&&await e.context.internalAdapter.deleteSession(l.session.token),e.json(null);if(c||e.query?.disableRefresh){let t=mf(e.context.options,l.session),n=ff(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 ef(),h=f&&!p&&!m;if(t&&!n){await mp(e,l,!!c);let t=mf(e.context.options,l.session),n=ff(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:Sf(e.context.sessionConfig.expiresIn,`sec`),updatedAt:new Date});if(!t)throw bp(e),P.from(`UNAUTHORIZED`,fs.FAILED_TO_GET_SESSION);let n=e.context.sessionConfig.expiresIn;await gp(e,{session:t,user:l.user},!1,{maxAge:n});let r=mf(e.context.options,t),i=ff(e.context.options,l.user);return e.json({session:r,user:i})}await mp(e,l,!!c);let g=mf(e.context.options,l.session),_=ff(e.context.options,l.user);return e.json({session:g,user:_})}catch(t){throw ku(t)?t:(e.context.logger.error(`INTERNAL_SERVER_ERROR`,t),P.from(`INTERNAL_SERVER_ERROR`,fs.FAILED_TO_GET_SESSION,{cause:t}))}}),Sp=e=>nf(e.context.options),Z=async(e,t)=>{if(e.context.session)return e.context.session;let n=await xp()({...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)},Cp=async e=>Sp(e)?(e.context.session=null,Z(e,{disableCookieCache:!0})):Z(e),wp=Hu(async e=>{let t=await Z(e);if(!t?.session)throw P.from(`UNAUTHORIZED`,{message:`Unauthorized`,code:`UNAUTHORIZED`});return{session:t}}),Tp=Hu(async e=>{let t=await Cp(e);if(!t?.session)throw P.from(`UNAUTHORIZED`,{message:`Unauthorized`,code:`UNAUTHORIZED`});return{session:t}});Hu(async e=>{let t=await Z(e);if(!t?.session&&(e.request||e.headers))throw P.from(`UNAUTHORIZED`,{message:`Unauthorized`,code:`UNAUTHORIZED`});return{session:t}});var Ep=Hu(async e=>{let t=await Z(e);if(!t?.session)throw P.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 P.from(`FORBIDDEN`,fs.SESSION_NOT_FRESH)}return{session:t}}),Dp=()=>X(`/list-sessions`,{method:`GET`,operationId:`listUserSessions`,use:[Ep],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=>mf(e.context.options,t)))}catch(t){throw e.context.logger.error(t),e.error(`INTERNAL_SERVER_ERROR`)}}),Op=X(`/revoke-session`,{method:`POST`,body:V({token:v().meta({description:`The token to revoke`})}),use:[Tp],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),P.from(`INTERNAL_SERVER_ERROR`,{message:`Internal Server Error`,code:`INTERNAL_SERVER_ERROR`})}return e.json({status:!0})}),kp=X(`/revoke-sessions`,{method:`POST`,use:[Tp],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),P.from(`INTERNAL_SERVER_ERROR`,{message:`Internal Server Error`,code:`INTERNAL_SERVER_ERROR`})}return e.json({status:!0})}),Ap=X(`/revoke-other-sessions`,{method:`POST`,requireHeaders:!0,use:[Tp],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 P.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 jp(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 Mp(e,t,n=`.`,r){if(!jp(t))return Mp(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]]:jp(a)&&jp(i[t])?Mp(a,i[t],(n?`${n}.`:``)+t.toString(),r):a))}return i}function Np(e){return(...t)=>t.reduce((t,n)=>Mp(t,n,``,e),{})}var Pp=Np(),Fp=new Set([`metadata.google.internal`,`metadata.goog`,`metadata`,`instance-data`,`instance-data.ec2.internal`]);function Ip(e){return e.length>=2&&e.startsWith(`[`)&&e.endsWith(`]`)?e.slice(1,-1):e}function Lp(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 Rp(e){let t=e.indexOf(`%`);return t===-1?e:e.slice(0,t)}function zp(e){return e.replace(/\.+$/,``)}function Bp(e){return/^\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}$/.test(e)}function Vp(e){let t=e.split(`.`);return(Number(t[0])<<24|Number(t[1])<<16|Number(t[2])<<8|Number(t[3]))>>>0}function Hp(e,t,n){if(n===0)return!0;let r=n===32?4294967295:-1<<32-n>>>0;return(e&r)===(t&r)}function Up(e){if(e===`0.0.0.0`)return`unspecified`;if(e===`255.255.255.255`)return`broadcast`;let t=Vp(e);return Hp(t,Vp(`127.0.0.0`),8)?`loopback`:Hp(t,Vp(`10.0.0.0`),8)||Hp(t,Vp(`172.16.0.0`),12)||Hp(t,Vp(`192.168.0.0`),16)?`private`:Hp(t,Vp(`169.254.0.0`),16)?`linkLocal`:Hp(t,Vp(`100.64.0.0`),10)?`sharedAddressSpace`:Hp(t,Vp(`192.0.2.0`),24)||Hp(t,Vp(`198.51.100.0`),24)||Hp(t,Vp(`203.0.113.0`),24)?`documentation`:Hp(t,Vp(`198.18.0.0`),15)?`benchmarking`:Hp(t,Vp(`224.0.0.0`),4)?`multicast`:Hp(t,Vp(`0.0.0.0`),8)||Hp(t,Vp(`192.0.0.0`),24)||Hp(t,Vp(`192.88.99.0`),24)||Hp(t,Vp(`240.0.0.0`),4)?`reserved`:`public`}function Wp(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 Gp(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=Wp(e,1);return t&&Up(t)!==`public`?`reserved`:`public`}if(e.startsWith(`0064:ff9b:0000:0000:0000:0000:`)){let t=Wp(e,6);return t&&Up(t),`reserved`}if(e.startsWith(`0064:ff9b:0001:`))return`reserved`;if(e.startsWith(`2001:0000:`)){let t=Wp(e,6,{xor:!0});return t&&Up(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 Kp(e){let t=zp(Rp(Ip(Lp(e.trim())))).toLowerCase();if(t===``)return{kind:`reserved`,literal:`fqdn`,canonical:``};if(!xd(t))return t===`localhost`||t.endsWith(`.localhost`)?{kind:`localhost`,literal:`fqdn`,canonical:t}:Fp.has(t)?{kind:`cloudMetadata`,literal:`fqdn`,canonical:t}:{kind:`public`,literal:`fqdn`,canonical:t};if(Bp(t))return{kind:Up(t),literal:`ipv4`,canonical:t};let n=Dd(t,{ipv6Subnet:128});return Bp(n)?{kind:Up(n),literal:`ipv4`,canonical:n}:{kind:Gp(n),literal:`ipv6`,canonical:n}}function qp(e){return Kp(e).kind===`loopback`}function Jp(e){let t=Kp(e).kind;return t===`loopback`||t===`localhost`}function Yp(e){return Kp(e).kind===`public`}var Xp=Np((e,t,n)=>{if(Array.isArray(e[t])&&Array.isArray(n))return e[t]=n,!0}),Zp=new WeakMap;function Qp(e,t){let n=e.options;return n?.operationId??n?.metadata?.openapi?.operationId??t??e.path??`/:virtual`}function $p(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 em(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 tm(e,t,n,r){let i=M(e.context.options),a={};for(let o of t){let t=!1;try{t=o.matcher(e)}catch(t){let n=Zp.get(o.handler)??`unknown`;throw e.context.logger.error(`An error occurred during ${n} hook matcher execution:`,t),new P(`INTERNAL_SERVER_ERROR`,{message:`An error occurred during hook matcher execution. Check the logs for more details.`})}if(!t)continue;let s=Zp.get(o.handler)??`unknown`,c=n.path??`/:virtual`,l=await i(`hook before ${c} ${s}`,{[se]:`before`,[R]:c,[le]:s,[te]:r},()=>o.handler({...e,returnHeaders:!0})).catch(t=>{throw ku(t)&&C(e.context.logger.level,`debug`)&&(t.stack=t.errorStack),t});$p(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=Xp(t,a);continue}return u}}return{context:a}}async function nm(e,t,n,r){let i=M(e.context.options);for(let a of t){if(!a.matcher(e))continue;let t=Zp.get(a.handler)??`unknown`,o=n.path??`/:virtual`,s=await i(`hook after ${o} ${t}`,{[se]:`after`,[R]:o,[le]:t,[te]:r},()=>a.handler(e)).catch(t=>{if(ku(t))return C(e.context.logger.level,`debug`)&&(t.stack=t.errorStack),{response:t,headers:em(t)};throw t});$p(e.context,s.headers),s.response!==void 0&&(e.context.returned=s.response)}return{response:e.context.returned,headers:e.context.responseHeaders}}function rm(e){let t=e.options.plugins||[],n=[],r=[],i=e.options.hooks?.before;i&&(Zp.set(i,`user`),n.push({matcher:()=>!0,handler:i}));let a=e.options.hooks?.after;a&&(Zp.set(a,`user`),r.push({matcher:()=>!0,handler:a}));let o=t.flatMap(e=>(e.hooks?.before??[]).map(t=>(Zp.set(t.handler,`plugin:${e.id}`),t))),s=t.flatMap(e=>(e.hooks?.after??[]).map(t=>(Zp.set(t.handler,`plugin:${e.id}`),t)));return o.length&&n.push(...o),s.length&&r.push(...s),{beforeHooks:n,afterHooks:r}}async function im(e,t){let n=M(t.context.options),r=t.operationId??Qp(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??ld(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}`,{[R]:a,[te]:r},async()=>Ru(u,async()=>{let{beforeHooks:o,afterHooks:s}=rm(u.context),c=await tm(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=Xp(t,u)}else if(c){let e=u.context.responseHeaders;return l?Do(c,{headers:e}):t.returnHeaders?{headers:e,response:c}:c}u.asResponse=!1,u.returnHeaders=!0,u.returnStatus=!0;let d=await Ru(u,()=>n(`handler ${a}`,{[R]:a,[te]:r},()=>e(u))).catch(e=>{if(ku(e))return{response:e,status:e.statusCode,headers:em(e)};throw e});if(d instanceof Response)return d;u.context.returned=d.response,u.context.responseHeaders=d.headers??void 0;let f=await nm(u,s,e,r);if(f.response!==void 0&&(d.response=f.response),d.headers=f.headers??d.headers,ku(d.response)&&C(u.context.logger.level,`debug`)&&(d.response.stack=d.response.errorStack),ku(d.response)&&!l)throw d.headers&&Object.defineProperty(d.response,i,{enumerable:!1,configurable:!0,writable:!1,value:d.headers}),d.response;return l?Do(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 am=/^[a-z](?:[a-z0-9-]*[a-z0-9])?(?:\.[a-z0-9](?:[a-z0-9-]*[a-z0-9])?)+$/i,om=new Set([`http:`,`https:`,`ws:`,`wss:`,`file:`,`ftp:`,`mailto:`,`javascript:`,`data:`,`vbscript:`,`blob:`,`about:`,`view-source:`]);function sm(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(`//`)&&am.test(t)}function cm(e){return om.has(e.protocol)||e.host.length===0?!1:e.pathname.startsWith(`/`)}function lm(e){return sm(e)||cm(e)}var Q=_().superRefine((e,n)=>{let r;try{r=new URL(e)}catch{return n.addIssue({code:`custom`,message:`URL must be parseable`,fatal:!0}),t}vd.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:`&&!Jp(r.host)&&n.addIssue({code:`custom`,message:`Redirect URI must use HTTPS (HTTP allowed only for loopback hosts)`}))});function um(e){return e?.jwks?.keyPairConfig?.alg??`EdDSA`}var dm=(e,t)=>({getAllKeys:async n=>t?.adapter?.getJwks?await t.adapter.getJwks(n):await(await Wd(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 Wd(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 Wd(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 Wd(e)).findMany({model:`jwks`});if(!i)return;let a=um(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 Wd(e)).create({model:`jwks`,data:{...r,createdAt:new Date}})});function fm(e,t){return typeof e==`number`?e:e instanceof Date?Math.floor(e.getTime()/1e3):t+rp(e)}async function pm(e){let{alg:t,...n}=e?.jwks?.keyPairConfig??{alg:`EdDSA`,crv:`Ed25519`},{publicKey:r,privateKey:i}=await Di(t,{...n,extractable:!0});return{publicWebKey:await gi(r),privateWebKey:await gi(i),alg:t,cfg:n}}async function mm(e,t){let{publicWebKey:n,privateWebKey:r,alg:i,cfg:a}=await pm(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 Ya({key:e.context.secretConfig,data:l})):l,createdAt:new Date,...t?.jwks?.rotationInterval?{expiresAt:new Date(Date.now()+t.jwks.rotationInterval*1e3)}:{}};return await dm(e.context.adapter,t).createJwk(e,d)}async function hm(e,t,n){if(t?.jwt?.sign)return null;let r=dm(e.context.adapter,t),i;if(n?.signingKeyId!==void 0){if(i=await r.getKeyById(e,n.signingKeyId),!i)throw new H(`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=um(t);if((i.alg??e)!==n.signingAlgorithm)throw new H(`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=um(t),a=t?.jwks?.keyPairConfigs?.find(e=>e.alg===n.signingAlgorithm),o=r===n.signingAlgorithm;if(a||o)i=await mm(e,{...t,jwks:{...t?.jwks,keyPairConfig:a??t?.jwks?.keyPairConfig}});else{let e=t?.jwks?.keyPairConfigs?.map(e=>e.alg).join(`, `)||`none`;throw new H(`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=um(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 H(`signJWT: requested signing key is expired and an explicit kid/alg was provided; not auto-minting a replacement. Rotate the key explicitly.`);i=await mm(e,t)}let a=t?.jwks?.disablePrivateKeyEncryption?i.privateKey:await Xa({key:e.context.secretConfig,data:JSON.parse(i.privateKey)}).catch(()=>{throw new H(`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??um(t),s=await Ci(JSON.parse(a),o);return{alg:o,kid:i.id,privateKey:s}}async function gm(e,t){let{options:n}=t,r=t.payload,i=Math.floor(Date.now()/1e3),a=r.iat,o=r.exp,s=fm(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 hm(e,n,{signingKeyId:t.signingKeyId,signingAlgorithm:t.signingAlgorithm}),_=new Qr(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 _m(e,t){let n=t?.jwt?.definePayload?await t.jwt.definePayload(e.context.session):e.context.session.user;return await gm(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 vm=c(v(),oe()).nullable(),ym=be({essential:z().optional(),value:v().optional(),values:B(v()).optional()}).nullable(),bm=V({acr:ym.optional()}).catchall(vm),xm=be({userinfo:c(v(),vm).optional(),id_token:bm.optional()});function Sm(e){if(typeof e==`string`)try{return JSON.parse(e)}catch{return}return e}function Cm(e){let t=Sm(e),n=xm.safeParse(t);return n.success?n.data:void 0}var wm=r([v(),c(v(),oe())]),Tm=wm,Em=wm.refine(e=>Cm(e)!==void 0,{error:`claims must be a valid Claims request object`});function Dm(e){return e===void 0||Cm(e)!==void 0}function Om(e,t){let n=Cm(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 km(e,t){let n=Cm(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 Am(e,t){let n=Cm(e)?.id_token?.acr;return Array.from(new Set([...n?.value===void 0?[]:[n.value],...n?.values??[],...t?.split(` `).filter(Boolean)??[]]))}function jm(e,t){let n=Cm(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 Mm(e){return e.authenticationContext?.acrValuesSupported??[`0`]}function Nm(e){throw new g(`INTERNAL_SERVER_ERROR`,{error:`server_error`,error_description:`authenticationContext.resolve ${e}`})}async function Pm(e,t){let n=e.authenticationContext?.resolve;if(!n||!t.scopes.includes(`openid`))return{};let{query:r,...i}=t,a=await n({...i,requestedAcrValues:Am(r.claims,r.acr_values)});a!==void 0&&(typeof a!=`object`||!a)&&Nm(`returned a value that is not an object`);let{acr:o=`0`,amr:s}=a??{};return typeof o!=`string`&&Nm(`returned a non-string acr`),Mm(e).includes(o)||Nm(`returned acr "${o}", which is not in acrValuesSupported`),s===void 0?{acr:o}:((!Array.isArray(s)||!Array.from(s).every(e=>typeof e==`string`))&&Nm(`returned an amr that is not a string array`),{acr:o,amr:s.length?s:void 0})}var Fm=new Set([`iss`,`sub`,`aud`,`exp`,`nbf`,`iat`,`jti`,`auth_time`,`nonce`,`acr`,`amr`,`azp`,`sid`,`at_hash`,`c_hash`,`s_hash`]);function Im(e){if(!e)return{};let t=[],n=Object.create(null);for(let[r,i]of Object.entries(e))Fm.has(r)?t.push(r):n[r]=i;return t.length>0&&ye.warn(`oauth-provider: stripped reserved id-token claim name(s): ${t.join(`, `)}. The AS owns these claim values.`),n}function Lm(e){let t=e.split(` `).filter(e=>e!==``);return t.length<=1?{}:{given:t.slice(0,-1).join(` `),family:t.at(-1)}}var Rm={name:{scope:`profile`,resolve:e=>e.name??void 0},picture:{scope:`profile`,resolve:e=>e.image??void 0},given_name:{scope:`profile`,resolve:e=>Lm(e.name).given},family_name:{scope:`profile`,resolve:e=>Lm(e.name).family},email:{scope:`email`,resolve:e=>e.email??void 0},email_verified:{scope:`email`,resolve:e=>e.emailVerified??!1}},zm=Object.keys(Rm);function Bm(e){return e.advertisedMetadata?.claims_supported??e.claims??[]}var Vm=new Set([`iss`,`sub`,`aud`,`exp`,`iat`,`jti`,`client_id`,`scope`,`auth_time`,`acr`,`amr`,`cnf`,`reference_id`]);function Hm(e){if(!e)return{};let t=[],n={};for(let[r,i]of Object.entries(e))Vm.has(r)?t.push(r):n[r]=i;return t.length>0&&ye.warn(`oauth-provider: stripped reserved access-token claim name(s): ${t.join(`, `)}. The AS owns these claim values.`),n}async function Um(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 Tl(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 Hm({...p,...d??{},...m,...f})}var Wm=[`javascript:`,`data:`,`vbscript:`],Gm=v().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`}):Wm.includes(new URL(e).protocol)&&n.addIssue({code:`custom`,message:`resource cannot use javascript:, data:, or vbscript: scheme`})}),Km=L([`none`,`consent`,`login`,`create`,`select_account`]),qm=v().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=Km.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`})}}),Jm=V({keys:B(c(v(),oe())).min(1)}),Ym=r([a(),v().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}),Xm=v().regex(/^[A-Za-z0-9_-]{43}$/,`dpop_jkt must be a base64url-encoded SHA-256 JWK thumbprint`),Zm=V({response_type:v().pipe(L([`code`])).optional(),request:v().optional(),request_uri:v().optional(),redirect_uri:Q.optional(),scope:v().optional(),state:v().optional(),client_id:v().min(1,`client_id is required`),prompt:qm.optional(),display:v().optional(),ui_locales:v().optional(),max_age:Ym.optional(),acr_values:v().optional(),login_hint:v().optional(),id_token_hint:v().optional(),code_challenge:v().optional(),code_challenge_method:v().pipe(L([`S256`])).optional(),nonce:v().optional(),claims:Tm.optional(),dpop_jkt:Xm.optional(),resource:r([Gm,B(Gm).min(1)]).optional()}).passthrough(),Qm=Zm.extend({redirect_uri:Q.optional(),claims:Em.optional()}),$m=V({type:F(`authorization_code`),query:Qm,sessionId:v(),userId:v(),referenceId:v().optional(),authTime:a().optional(),acr:v().optional(),amr:B(v()).optional(),resource:B(v()).optional()}).passthrough(),eh=V({redirect_uris:B(Q).min(1).optional(),scope:v().optional(),client_name:v().refine(e=>e.trim().length>0,`client_name cannot be empty`).optional(),client_uri:v().optional(),logo_uri:v().optional(),contacts:B(v().min(1)).min(1).optional(),tos_uri:v().optional(),policy_uri:v().optional(),software_id:v().optional(),software_version:v().optional(),software_statement:v().optional(),post_logout_redirect_uris:B(Q).min(1).optional(),backchannel_logout_uri:Q.optional(),backchannel_logout_session_required:z().optional(),frontchannel_logout_uri:Q.optional(),frontchannel_logout_session_required:z().optional(),token_endpoint_auth_method:v().trim().min(1).optional(),jwks:Jm.optional(),jwks_uri:v().optional(),grant_types:B(v().trim().min(1)).min(1).optional(),response_types:B(L([`code`])).optional(),application_type:L([`web`,`native`]).optional(),subject_type:L([`public`,`pairwise`]).optional(),dpop_bound_access_tokens:z().optional(),resources:B(Gm).optional(),skip_consent:S({error:`skip_consent cannot be set during dynamic client registration`}).optional()}),th=eh.omit({skip_consent:!0}).extend({client_id:v().refine(e=>e.trim().length>0,`client_id cannot be empty`),client_secret:v().optional(),client_secret_expires_at:a().int().nonnegative().optional(),client_id_issued_at:a().int().nonnegative().optional()}).loose(),nh=[`EdDSA`,`ES256`,`ES512`,`PS256`,`RS256`],rh=new Set(nh),ih=64;async function ah(e,t){let n=e.identifierValidator;if(n)return await n(t)?{ok:!0}:{ok:!1,reason:`resource identifier ${t} failed validation`};let r=Gm.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 oh(e,t){let n=await ah(e,t);if(!n.ok)throw new P(`BAD_REQUEST`,{error:`invalid_target`,error_description:n.reason})}var sh=e=>`${e}/oauth2/userinfo`;function ch(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 lh(e,t,n,r=[]){if(n===void 0)return!0;let i=Array.isArray(n)?n:[n];if(i.length>ih)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=>_h(e,t,n)))).every(Boolean)}async function uh(e,t,n){let r=ch(n.resource),i=n.requestedScopes.includes(`openid`),a=sh(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 _h(e,t,n);if(r){if(r.disabled)throw new P(`BAD_REQUEST`,{error:`invalid_target`,error_description:`requested resource ${n} is disabled`});s.push(r)}else throw new P(`BAD_REQUEST`,{error:`invalid_target`,error_description:`requested resource ${n} is not configured`})}let{value:c}=mh(t);c&&s.length>0&&await dh(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 P(`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 P(`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 P(`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 dh(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 P(`BAD_REQUEST`,{error:`invalid_target`,error_description:`client ${n} is not linked to resource(s) ${s.map(e=>e.identifier).join(`, `)}`})}async function fh(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 ph(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 mh(e){return e.enforcePerClientResources===void 0?{value:!0,source:`default`}:{value:e.enforcePerClientResources,source:`explicit`}}var hh=new Map;function gh(e){e===void 0?hh.clear():hh.delete(e)}async function _h(e,t,n){if(await Dh(e.context,t),t.cachedResources?.has(n)){let e=hh.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)&&hh.set(n,Object.assign({},r)),r}function vh(e){return e.name??e.identifier}function yh(e){let t=[];if(e.resources?.length)for(let n of e.resources)t.push(typeof n==`string`?{identifier:n}:n);return t}function bh(e,t){return{identifier:e.identifier,name:vh(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 xh(e,t,n){if(t===`overwrite`){let{identifier:t,createdAt:r,...i}=bh(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 Sh=/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 Ch(e,t){let n=!1,r=t;for(let e=0;r&&!n&&e<5;e++)n=Sh.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 wh=new WeakMap;function Th(e,t){let n=e.adapter,r=wh.get(n);r||(r=new WeakMap,wh.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 Eh(e,t){let n=yh(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 ah(t,a.identifier);if(!n.ok){ye.warn(`oauth-provider: skipping resource seed for ${a.identifier} — ${n.reason}`);continue}let o=a;if(o.signingAlgorithm!=null&&!rh.has(o.signingAlgorithm)){ye.warn(`oauth-provider: dropping unsupported signingAlgorithm "${o.signingAlgorithm}" for resource ${o.identifier} — must be one of ${nh.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:bh(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:xh(o,r,l)})}}async function Dh(e,t){let n=Th(e,t);if(n.completed!==!0)return n.promise===null&&(n.promise=Eh(e,t).then(()=>{n.completed=!0}).catch(e=>{throw n.promise=null,e})),n.promise}function Oh(e){let t=mh(e);ye.info(`oauth-provider: enforcePerClientResources resolved to ${t.value} (${t.source})`)}function kh(e){return e.headers?.get(`dpop`)??void 0}function Ah(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 jh=new Set([`openid`,`profile`,`email`,`offline_access`]);function Mh(e){return jh.has(e)}function Nh(e){return[...new Set(e.map(e=>e.trim()).filter(Boolean))]}function Ph(e,t,n,r){if(e.length===0)return;if(!t.includes(`client_credentials`))throw new P(`BAD_REQUEST`,{error:`invalid_client_metadata`,error_description:`client_credentials_scopes requires the client_credentials grant`});if(n===`none`)throw new P(`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)||Mh(e));if(a.length>0)throw new P(`BAD_REQUEST`,{error:`invalid_scope`,error_description:`The following client_credentials scopes are invalid: ${a.join(`, `)}`})}var Fh=new Set([Ct.code,bt.code,St.code]);async function Ih(e,t,n){if(t.disableJwtPlugin||n.split(`.`).length!==3)return null;try{wi(n)}catch{return null}let r=Fl(e.context),i=r.options,a=await Gc(n,{jwksFetch:i?.jwks?.remoteUrl?i.jwks.remoteUrl:async()=>(await r.endpoints.getJwks(e))?.response,jwksCacheKey:r}),o;try{({payload:o}=await qr(n,xi(a),{issuer:i?.jwt?.issuer??e.context.baseURL}))}catch(e){if(e instanceof ht||e instanceof mt)return Lh(e.payload)?`inactive`:null;if(e instanceof pt&&!Fh.has(e.code))return null;throw e}return Lh(o)?o:null}function Lh(e){return typeof e.azp==`string`&&e.azp.length>0}async function Rh(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 Zl(t.storeTokens,r?n.slice(r.length):n,`access_token`)}]})}async function zh(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 pt)return null;throw e}return e.context.adapter.findOne({model:`oauthRefreshToken`,where:[{field:`token`,value:await Zl(t.storeTokens,a.token,`refresh_token`)}]})}async function Bh(e,t,n){let r=await Ih(e,t,n);if(r===`inactive`)return r;if(r)return{type:`jwt`,payload:r};let i=await Rh(e,t,n);return i?{type:`opaque`,record:i}:null}async function Vh(e,t,n){let r=await Bh(e,t,n);return r===`inactive`?null:r}async function Hh(e,t,n,r){let i=async()=>{let r=await zh(e,t,n);return r?{type:`refresh`,record:r}:null};if(r===`refresh_token`)return await i()??Vh(e,t,n);let a=await Bh(e,t,n);return a===`inactive`?null:a??i()}function Uh(e,t,n=[]){let r=new Set(n),i={sub:e.id??void 0};for(let[n,a]of Object.entries(Rm))(t.includes(a.scope)||r.has(n))&&(i[n]=a.resolve(e));return i}function Wh(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 Gh(e){let t=e.headers?.get(`authorization`),n=vc(t),r=e.request?.method===`POST`?e.body?.access_token??void 0:void 0;if(n&&r)throw new P(`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 Kh(e,t){let{authorization:n}=Gh(e);if(!n?.token)throw new P(`UNAUTHORIZED`,{error_description:`access token not found`,error:`invalid_request`});let{payload:r,requestedUserInfoClaims:i}=await Kg(e,t,n.token);if(wc(r)&&!e.request)throw new P(`UNAUTHORIZED`,{error_description:`DPoP-bound access token requires an HTTP request context`,error:`invalid_token`});try{await Pc({payload:r,authorization:n,proofJwt:kh(e),method:e.request?.method??`GET`,url:Ah(e,`/oauth2/userinfo`),proofMaxAgeSeconds:t.dpop?.proofMaxAgeSeconds,signingAlgorithms:t.dpop?.signingAlgorithms,replayStore:gc(e.context.internalAdapter)})}catch(e){throw Nc(e)?new P(`UNAUTHORIZED`,{error_description:e.message,error:e.code}):e}let a=r.scope?.split(` `);if(!a?.includes(`openid`))throw new P(`BAD_REQUEST`,{error_description:`Missing required scope`,error:`invalid_scope`});if(!r.sub)throw new P(`BAD_REQUEST`,{error_description:`user not found`,error:`invalid_request`});let o=await e.context.internalAdapter.findUserById(r.sub);if(!o)throw new P(`BAD_REQUEST`,{error_description:`user not found`,error:`invalid_request`});let s=Uh(o,a??[],i),c=r.client_id??r.azp,l=c&&(t.pairwiseSecret||jl(t))?await Wl(e,t,c):void 0;t.pairwiseSecret&&l&&(s.sub=await xu(o.id,l,t));let u=a?.length?await Dl(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,...Wh(u,s),...Wh(d),sub:s.sub}}var qh=Object.fromEntries(zm.map(e=>[e,void 0]));function Jh(e){return Cc(e)?`DPoP`:`Bearer`}var Yh=`at+jwt`;async function Xh(e,t){let n=e.body.grant_type;if(!gl(t).includes(n))throw new P(`BAD_REQUEST`,{error_description:`unsupported grant_type ${n}`,error:`unsupported_grant_type`});switch(n){case`authorization_code`:return kg(e,t);case`client_credentials`:return Ag(e,t);case`refresh_token`:return jg(e,t);default:{let r=vl(t,n);if(r)return r({ctx:e,opts:t,grantType:n,provider:Zh(e,t,n)});throw new P(`BAD_REQUEST`,{error_description:`unsupported grant_type ${n}`,error:`unsupported_grant_type`})}}}function Zh(e,t,n){return{getClient:n=>Wl(e,t,n),authenticateClient:async r=>{let{clientId:i,clientSecret:a,preVerified:o,authMethod:s,confirmation:c}=hu(await gu(e,t,`${e.context.baseURL}${e.path??`/oauth2/token`}`));if(!i)throw new P(`BAD_REQUEST`,{error_description:`Missing required client_id`,error:`invalid_request`});if(r?.requireCredentials!==!1&&!a&&!o)throw new P(`BAD_REQUEST`,{error_description:`Missing required client credentials`,error:`invalid_client`});return{clientId:i,client:await pu(e,t,i,a,r?.scopes,o,n,s),method:s,confirmation:c}},issueTokens:r=>{if(!n)throw new P(`INTERNAL_SERVER_ERROR`,{error_description:`issueTokens requires a grant type; pass it to getOAuthProviderApi(ctx, opts, grantType).`,error:`server_error`});return Dg(e,t,{...r,grantType:n})},resolveConfirmation:async n=>{if(n.confirmation)return n.confirmation;let r=await uh(e,t,{resource:n.resources,clientId:n.client.clientId,requestedScopes:n.scopes});return lg(e,t,{client:n.client,grantIssuance:{dpopBoundAccessTokensRequired:r.dpopBoundAccessTokensRequired}})},hashToken:(e,n)=>Xl(t.storeTokens,e,n),validateAccessToken:async(n,r)=>{let{validateAccessToken:i}=await Promise.resolve().then(()=>Mg);return i(e,t,n,r)},requireActiveAccessToken:async(n,r)=>{let{requireActiveAccessToken:i}=await Promise.resolve().then(()=>Mg);return i(e,t,n,r)}}}async function Qh(e,t,n,r,i,a,o){let s=o?.iat??Math.floor(Date.now()/1e3),c=o?.exp??s+(t.accessTokenExpiresIn??3600),l=Fl(e.context).options,u=n?.id??r.clientId;return gm(e,{options:l,header:{typ:Yh},signingKeyId:o?.signingKeyId??void 0,signingAlgorithm:o?.signingAlgorithm??void 0,payload:{...o?.accessTokenClaims??{},sub:u,aud:zl(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:Vi(32),...o?.confirmation?{cnf:o.confirmation}:{}}})}async function $h(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 K(r.slice(0,r.length/2))}async function eg(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 xu(n.id,r,t),m=s==null?void 0:Math.floor(s.getTime()/1e3),h=Im(t.customIdTokenClaims?await t.customIdTokenClaims({user:n,scopes:i,metadata:mu(r.metadata)}):void 0),g=t.disableJwtPlugin?void 0:Fl(e.context).options,_=!t.disableJwtPlugin&&!g?.jwt?.sign?await hm(e,g):void 0,v=t.disableJwtPlugin?`HS256`:_?.alg??g?.jwks?.keyPairConfig?.alg,y=c?await $h(c,v):void 0,b=!!(r.enableEndSession||r.backchannelLogoutUri||r.frontchannelLogoutUri),x={...qh,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=Im(l);if(Object.assign(x,Wh(S,x)),t.disableJwtPlugin&&!r.clientSecret)return;let C=t.disableJwtPlugin?await new Qr(x).setProtectedHeader({alg:`HS256`}).sign(new TextEncoder().encode(await ql(e,t.storeClientSecret,r.clientSecret))):await gm(e,{options:g,payload:x,resolvedKey:_??void 0});if(C&&y&&g?.jwt?.sign){let e=wi(C);if(e.alg!==v)throw new P(`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 tg(e,t,n){return(e.prefix?.refreshToken??``)+(e.formatRefreshToken?.encrypt?await e.formatRefreshToken.encrypt(t,n):t)}async function ng(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():Vi(32,`A-Z`,`a-z`);return await e.context.adapter.create({model:`oauthAccessToken`,data:{token:await Xl(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 rg(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 ig(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 ag(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():Vi(32,`A-Z`,`a-z`),_=s?.sid,v={token:await Xl(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 tg(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 P(`BAD_REQUEST`,{error_description:`invalid refresh token`,error:`invalid_grant`});return{id:(await e.context.adapter.create({model:`oauthRefreshToken`,data:v})).id,token:await tg(t,g,_)}}async function og(e,t,n){let r=await uh(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 sg(e){throw new P(`BAD_REQUEST`,{error:`invalid_dpop_proof`,error_description:e})}function cg(e){let t=mu(e.metadata)??{};return e.dpopBoundAccessTokens===!0||t.dpop_bound_access_tokens===!0}async function lg(e,t,n){let r=n.verificationValue?.query.dpop_jkt,i=Cc(n.refreshToken?.confirmation),a=i??r,o=kh(e),s=cg(n.client)||n.grantIssuance.dpopBoundAccessTokensRequired||!!r||!!i;if(!o)s&&sg(`DPoP proof header is required`);else try{return{jkt:(await jc({proofJwt:o,method:`POST`,url:Ah(e,e.path??`/oauth2/token`),expectedJkt:a,proofMaxAgeSeconds:t.dpop?.proofMaxAgeSeconds,signingAlgorithms:t.dpop?.signingAlgorithms,replayStore:gc(e.context.internalAdapter)})).jkt}}catch(e){throw _c(e)&&sg(e.message),e}}function ug(e){return e?[...new Set(e)].sort():void 0}function dg(e,t){let n=ug(e),r=ug(t);return n===void 0||r===void 0?n===r:n.length===r.length&&n.every((e,t)=>e===r[t])}function fg(e){if(e)return`jkt`in e?`jkt:${e.jkt}`:`x5t#S256:${e[`x5t#S256`]}`}function pg(e,t){return fg(e)===fg(t)}function mg(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 hg(e){return e===`Bearer`||e===`DPoP`}function gg(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`&&hg(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 _g(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||mg(n.confirmation))&&gg(t.response)}function vg(e){let t=ug(e.requestedResources);return{effectiveScopes:ug(e.effectiveScopes)??[],...t?{requestedResources:t}:{},...e.confirmation?{confirmation:e.confirmation}:{}}}function yg(e,t){return dg(e.effectiveScopes,t.effectiveScopes)&&dg(e.requestedResources,t.requestedResources)&&pg(e.confirmation,t.confirmation)}async function bg(e,t){return Ya({key:e.context.secretConfig,data:JSON.stringify(t)})}async function xg(e,t){let n=await Xa({key:e.context.secretConfig,data:t}),r=JSON.parse(n);if(_g(r))return r}function Sg(e){return!!e.rotatedAt&&!!e.rotationReplayExpiresAt&&e.rotationReplayExpiresAt>=new Date}async function Cg(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 bg(e,{request:r,response:i})}})}async function wg(e,t,n){if(Sg(t)&&t.rotationReplayResponse)try{let r=await xg(e,t.rotationReplayResponse);return!r||!yg(r.request,n)?void 0:r.response}catch(t){e.context.logger.error(`refresh token rotation replay failed`,t);return}}async function Tg(e,t,n){let r=Math.floor(Date.now()/1e3),i=await og(e,t,{clientId:n.client.clientId,requestedScopes:n.scopes,resources:n.resources,refreshToken:n.refreshToken,iat:r,scopeExpiresAtSeconds:r+(t.accessTokenExpiresIn??3600)}),a=await lg(e,t,{client:n.client,grantIssuance:i,refreshToken:n.refreshToken});return vg({effectiveScopes:i.effectiveScopes,requestedResources:n.resources,confirmation:a})}function Eg(e,t){let n=Math.floor(Date.now()/1e3);return e.json({...t,expires_in:Math.max(0,t.expires_at-n)})}async function Dg(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 P(`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]?fm(t.scopeExpirations[e],g):v).reduce((e,t)=>e<t?e:t,v):v,b=await og(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&&su(r,`refresh_token`)&&(u?.scopes?.includes(`offline_access`)||i.includes(`offline_access`)),E=x&&!t.disableJwtPlugin,D=a&&S.includes(`openid`),O=mu(r.metadata),k=D&&a?{...await El(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,M=n.confirmation??await lg(e,t,{client:r,grantIssuance:b,verificationValue:m,refreshToken:u}),N=n.requestedUserInfoClaims??u?.requestedUserInfoClaims??[],F=T&&a&&!E?await ag(e,t,a,s,n.authorizationCodeId,r,S,{iat:g,exp:w,sid:c},u,d,j,M,N,h):void 0,I=E?await Um({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?Qh(e,t,a,r,x,S,{iat:g,exp:C,sid:c,referenceId:s,signingAlgorithm:b.signingAlgorithm,signingKeyId:b.signingKeyId,accessTokenClaims:I,confirmation:M}):ng(e,t,a,r,S,{iat:g,exp:C,sid:c},n?.resources,s,n.authorizationCodeId,F?.id,M,N),F||(T&&a?ag(e,t,a,s,n.authorizationCodeId,r,S,{iat:g,exp:w,sid:c},u,d,j,M,N,h):void 0)]),ee=D?await eg(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:Jh(M),refresh_token:R?.token,scope:S.join(` `),id_token:ee};if(u?.id&&R?.id)try{await Cg(e,t,u,vg({effectiveScopes:S,requestedResources:n.resources,confirmation:M}),te)}catch(t){e.context.logger.error(`failed to store refresh token rotation replay`,t)}return e.json(te)}async function Og(e,t,n,r,i,a){let o=await Xl(t.storeTokens,n,`authorization_code`),s=await e.context.internalAdapter.consumeVerificationValue(o);if(!s)throw await ig(e,o),new P(`BAD_REQUEST`,{error_description:`invalid code`,error:`invalid_grant`});let c;try{c=JSON.parse(s.value)}catch{throw new P(`BAD_REQUEST`,{error_description:`malformed verification value`,error:`invalid_grant`})}let l=$m.safeParse(c);if(!l.success)throw new P(`BAD_REQUEST`,{error_description:`malformed verification value`,error:`invalid_grant`});let u=l.data;if(u.query.client_id!==r)throw new P(`BAD_REQUEST`,{error_description:`invalid client_id`,error:`invalid_grant`});let d=u.query.redirect_uri;if(d){if(!i)throw new P(`BAD_REQUEST`,{error_description:`redirect_uri is required`,error:`invalid_request`});if(d!==i)throw new P(`BAD_REQUEST`,{error_description:`redirect_uri mismatch`,error:`invalid_grant`})}else if(i)throw new P(`BAD_REQUEST`,{error_description:`redirect_uri mismatch`,error:`invalid_grant`});let f=Rl(u.resource)??Rl(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 P(`BAD_REQUEST`,{error_description:`requested resource not authorized`,error:`invalid_target`})}return{verificationValue:u,effectiveResources:p,authorizedResources:f,authorizationCodeId:o}}async function kg(e,t){let{clientId:n,clientSecret:r,preVerified:i,authMethod:a}=hu(await gu(e,t,`${e.context.baseURL}/oauth2/token`)),{code:o,code_verifier:s,redirect_uri:c,resource:l}=e.body,u=Rl(l);if(!n)throw new P(`BAD_REQUEST`,{error_description:`client_id is required`,error:`invalid_request`});if(!o)throw new P(`BAD_REQUEST`,{error_description:`code is required`,error:`invalid_request`});let d=n&&r,f=n&&o&&s;if(!d&&!f&&!i)throw new P(`BAD_REQUEST`,{error_description:`Either code_verifier or client_secret is required`,error:`invalid_request`});let p=await pu(e,t,n,r,void 0,i,`authorization_code`,a),{verificationValue:m,effectiveResources:h,authorizedResources:g,authorizationCodeId:_}=await Og(e,t,o,n,c,u),v=m.query.scope?.split(` `);if(!v)throw new P(`INTERNAL_SERVER_ERROR`,{error_description:`verification scope unset`,error:`invalid_scope`});if(du(p,v),Ou(p,{scopes:(m.query?.scope)?.split(` `)||[],nonce:m.query?.nonce})){if(!f)throw new P(`BAD_REQUEST`,{error_description:`PKCE is required for this client`,error:`invalid_request`})}else if(!(f||d||i))throw new P(`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 P(`BAD_REQUEST`,{error_description:`code_verifier required because PKCE was used in authorization`,error:`invalid_request`});if(!y&&b)throw new P(`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 _s(s):void 0)!==m.query?.code_challenge)throw new P(`BAD_REQUEST`,{error_description:`code verification failed`,error:`invalid_grant`})}if(!m.userId)throw new P(`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 P(`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 P(`BAD_REQUEST`,{error_description:`session no longer exists`,error:`invalid_request`});let C=m.authTime==null?Ll(S):Il(m.authTime),w=Om(m.query.claims,Bm(t));return Dg(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 Ag(e,t){let{clientId:n,clientSecret:r,preVerified:i,authMethod:a}=hu(await gu(e,t,`${e.context.baseURL}/oauth2/token`)),{scope:o,resource:s}=e.body,c=Rl(s);if(!n)throw new P(`BAD_REQUEST`,{error_description:`Missing required client_id`,error:`invalid_request`});let l=await pu(e,t,n,r,void 0,i,`client_credentials`,a);if(l.tokenEndpointAuthMethod===`none`)throw new P(`BAD_REQUEST`,{error_description:`public clients cannot use the client_credentials grant`,error:`unauthorized_client`});let u=l.clientCredentialsScopes;if(!u?.length)throw new P(`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)||Mh(t));if(t.length)throw new P(`BAD_REQUEST`,{error_description:`The following scopes are invalid: ${t.join(`, `)}`,error:`invalid_scope`})}return d||=[...u],Dg(e,t,{client:l,scopes:d,grantType:`client_credentials`,resources:c})}async function jg(e,t){let{clientId:n,clientSecret:r,preVerified:i,authMethod:a}=hu(await gu(e,t,`${e.context.baseURL}/oauth2/token`)),{refresh_token:o,scope:s,resource:c}=e.body,l=Rl(c);if(!n)throw new P(`BAD_REQUEST`,{error_description:`Missing required client_id`,error:`invalid_request`});if(!o)throw new P(`BAD_REQUEST`,{error_description:`Missing a required refresh_token for refresh_token grant`,error:`invalid_request`});let u=await pu(e,t,n,r,void 0,i,`refresh_token`,a),d=await zh(e,t,o);if(!d)throw new P(`BAD_REQUEST`,{error_description:`session not found`,error:`invalid_grant`});if(d.clientId!==n||d.expiresAt<new Date)throw new P(`BAD_REQUEST`,{error_description:`invalid refresh token`,error:`invalid_grant`});if(l&&d.resources&&!l.every(e=>d.resources?.includes(e)))throw new P(`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 P(`BAD_REQUEST`,{error_description:`unable to issue scope ${t}`,error:`invalid_scope`})}if(du(u,p??f),d.revoked){if(Sg(d)){let n=await wg(e,d,await Tg(e,t,{client:u,refreshToken:d,scopes:p??f,resources:l??d.resources}));if(n)return Eg(e,n);throw new P(`BAD_REQUEST`,{error_description:`invalid refresh token`,error:`invalid_grant`})}throw await rg(e,n,d.userId),new P(`BAD_REQUEST`,{error_description:`invalid refresh token`,error:`invalid_grant`})}let m=await e.context.internalAdapter.findUserById(d.userId);if(!m)throw new P(`BAD_REQUEST`,{error_description:`user not found`,error:`invalid_request`});let h=d.authTime==null?void 0:Il(d.authTime);return Dg(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 Mg=Oe({introspectEndpoint:()=>Jg,requireActiveAccessToken:()=>Gg,requireActiveAccessTokenWithClaims:()=>Kg,validateAccessToken:()=>Wg}),Ng=`Invalid access token`,Pg=`Bearer error="invalid_token", error_description="${Ng}"`;function Fg(){return{payload:{active:!1},requestedUserInfoClaims:[]}}function Ig(e,t){return e==null?[]:(Array.isArray(e)?e:[e]).filter(e=>typeof e==`string`&&e!==t)}async function Lg(e,t,n){let{introspectingClientId:r,issuerClientId:i,audienceResources:a}=n;return!r||r===i||a.length!==0&&fh(e,t,r,a)}async function Rg(e,t,n,r){let i=sh(e.context.baseURL??``),a=n.aud;if(!await lh(e,t,a,[i]))return{active:!1};let o=await Wl(e,t,n.azp);if(!o||o?.disabled||!await Lg(e,t,{introspectingClientId:r,issuerClientId:n.azp,audienceResources:Ig(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=Jh(n.cnf),n}async function zg(e,t,n,r){if(!n.expiresAt||n.expiresAt<new Date||n.revoked)return Fg();let i=Array.isArray(n.resources)?n.resources:void 0,a;if(n.clientId&&(a=await Wl(e,t,n.clientId),!a||a?.disabled||!await Lg(e,t,{introspectingClientId:r,issuerClientId:n.clientId,audienceResources:i??[]})))return Fg();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 Fg()}let s;n.userId&&(s=await e.context.internalAdapter.findUserById(n?.userId));let c=`${e.context.baseURL}/oauth2/userinfo`;if(i?.length&&!await lh(e,t,i,[c]))return Fg();let l=i?[...i]:void 0;l?.length&&n.scopes?.includes(`openid`)&&(l.includes(c)||l.push(c));let u=i?.length?await ph(e,t,i):{},d=a?await Um({ctx:e,opts:t,user:s,client:a,scopes:n.scopes??[],grantType:void 0,sessionId:void 0,resources:i,referenceId:n.referenceId,metadata:mu(a.metadata),perRequestClaims:void 0,resourcePolicyClaims:u}):{},f=(t.disableJwtPlugin?void 0:Fl(e.context))?.options;return{payload:{...d,active:!0,iss:f?.jwt?.issuer??e.context.baseURL,aud:zl(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:Jh(n.confirmation),...n.confirmation?{cnf:n.confirmation}:{}},requestedUserInfoClaims:n.requestedUserInfoClaims??[]}}async function Bg(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:Fl(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:Jh(n.confirmation),...n.confirmation?{cnf:n.confirmation}:{}}}function Vg(){return new g(`UNAUTHORIZED`,{error_description:Ng,error:`invalid_token`},{"WWW-Authenticate":Pg})}async function Hg(e,t,n,r){return n.type===`opaque`?zg(e,t,n.record,r):{payload:await Rg(e,t,n.payload,r),requestedUserInfoClaims:[]}}async function Ug(e,t,n,r){let i=await Vh(e,t,n);return i?Hg(e,t,i,r):Fg()}async function Wg(e,t,n,r){return(await Ug(e,t,n,r)).payload}async function Gg(e,t,n,r){let i=await Wg(e,t,n,r);if(i.active)return i;throw Vg()}async function Kg(e,t,n,r){let{payload:i,requestedUserInfoClaims:a}=await Ug(e,t,n,r);if(i.active)return{payload:i,requestedUserInfoClaims:a};throw Vg()}async function qg(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 Wl(e,t,i);if(!a)return n;let o=await xu(n.sub,a,t);return{...n,sub:o}}async function Jg(e,t){let{token:n,token_type_hint:r}=e.body,{clientId:i,clientSecret:a,preVerified:o,authMethod:s}=hu(await gu(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=yc(n)),!n?.length)throw new g(`BAD_REQUEST`,{error_description:`missing a required token for introspection`,error:`invalid_request`});let c=await pu(e,t,i,a,void 0,o,void 0,s);try{let i=await Hh(e,t,n,r);if(!i)return{active:!1};if(i.type===`refresh`)return qg(e,t,await Bg(e,t,i.record,c.clientId),c);let{payload:a}=await Hg(e,t,i,c.clientId);return qg(e,t,a,c)}catch(e){throw e instanceof g?e:(ye.error(`Introspection error:`,e),new g(`INTERNAL_SERVER_ERROR`))}}var Yg=`1.8.0-beta.2`;function Xg(e){return e?.get(`sec-fetch-mode`)===`cors`}var Zg=e({a:()=>cy,c:()=>Uv,d:()=>Q_,f:()=>rv,g:()=>tv,i:()=>Ib,l:()=>bv,n:()=>kb,o:()=>Cy,p:()=>ev,r:()=>Mb,s:()=>wv,t:()=>Jb,u:()=>iv});async function Qg(e,t,n){let r=await jb.get(),i=r?.query;if(!i)throw new P(`BAD_REQUEST`,{error_description:`missing oauth query`,error:`invalid_request`});let a=new URLSearchParams(i),o=a.get(`scope`)?.split(` `).filter(e=>e)??[],s=Bm(t),c=Om(a.get(`claims`),s),l=a.get(`client_id`);if(!l)throw new P(`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 P(`BAD_REQUEST`,{error_description:`Scope not originally requested`,error:`invalid_request`});let d=e.body.claims,f=d===void 0?c:Om(d,s);if(d!==void 0&&!f.every(e=>c.includes(e)))throw new P(`BAD_REQUEST`,{error_description:`Claim not originally requested`,error:`invalid_request`});let p=await Z(e);if(e.body.accept!==!0){let n=_l(t,wu(a));return n?{redirect:!0,url:await n.handler.deny({ctx:e,value:n.value,userId:p?.user.id}).catch(t=>Kb(e,t,n.handler.errorPage?.({ctx:e,value:n.value})))}:{redirect:!0,url:zb(a.get(`redirect_uri`)??``,`access_denied`,`User denied access`,a.get(`state`)??void 0,Jb(e,t))}}let m=e.body.reference_id;if(m!==void 0&&!t.postLogin?.consentReferenceId)throw new P(`BAD_REQUEST`,{error_description:`reference_id requires postLogin.consentReferenceId`,error:`invalid_request`});let h=_u(a.get(`prompt`)??``).has(`login`),g=h&&Tu(p?.session.createdAt,r?.signedQueryIssuedAt);if(h&&!g)return e?.headers?.set(`accept`,`application/json`),e.query=wu(a),await n(e);let _=await Su(t,{user:p?.user,session:p?.session,scopes:u??o,query:new URLSearchParams(a),consent:{referenceId:m}}),v=await Cu(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=jm(a.get(`claims`),f);e?a.set(`claims`,JSON.stringify(e)):a.delete(`claims`)}e?.headers?.set(`accept`,`application/json`);let S=Eu(a,`consent`);return g&&(S=Eu(S,`login`),S=Du(S)),e.query=wu(S),await n(e,{postLogin:r?.postLoginClearedForSession!==void 0&&r.postLoginClearedForSession===p?.session.id,acceptedConsent:{referenceId:_}})}async function $g(e,t){if(e.body.selected===!0)return await e_(e,t);if(e.body.created===!0)return await t_(e,t);if(e.body.postLogin===!0)return await n_(e,t);throw new P(`BAD_REQUEST`,{error_description:`Missing parameters`,error:`invalid_request`})}async function e_(e,t){let n=(await jb.get())?.query;if(!n)throw new P(`BAD_REQUEST`,{error_description:`missing oauth query`,error:`invalid_request`});return e.headers?.set(`accept`,`application/json`),e.query=wu(Eu(new URLSearchParams(n),`select_account`)),await t(e)}async function t_(e,t){let n=(await jb.get())?.query;if(!n)throw new P(`BAD_REQUEST`,{error_description:`missing oauth query`,error:`invalid_request`});let r=new URLSearchParams(n);return e.headers?.set(`accept`,`application/json`),e.query=wu(Eu(r,`create`)),await t(e)}async function n_(e,t){let n=await jb.get(),r=n?.query;if(!r)throw new P(`BAD_REQUEST`,{error_description:`missing oauth query`,error:`invalid_request`});let i=new URLSearchParams(r);e.headers?.set(`accept`,`application/json`),e.query=wu(i);let a=await Z(e);return await t(e,{postLogin:n?.postLoginClearedForSession!==void 0&&n.postLoginClearedForSession===a?.session.id,isPostLoginContinuation:!0})}var r_=`http://schemas.openid.net/event/backchannel-logout`,i_=`logout+jwt`,a_=120,o_=5e3,s_=3e3;async function c_(e,t,n,r){return gm(e,{options:t,payload:{...r,events:{[r_]:{}}},header:{typ:i_},resolvedKey:n??void 0})}async function l_(e,t,n){let{sessionId:r,userId:i}=n;if(!i)return null;let a=e.context.logger;try{let n=await Wd(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 xu(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=Jb(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 u_(e,t){let n=new Date,r=await Wd(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 d_(e,t)}async function d_(e,t){let n=e.context.logger,r=Fl(e.context)?.options,i=r?.jwt?.issuer??e.context.baseURL,a=Math.floor(Date.now()/1e3),o=a+a_,s=r?.jwt?.sign?null:await hm(e,r);await Promise.allSettled(t.backchannelTargets.map(async({client:c,sub:l})=>{try{let u=Vi(32,`a-z`,`A-Z`,`0-9`),d=await c_(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(o_),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 f_=Hd(()=>[]);async function p_(e){if(e.length===0||!await zd())return;let t=await f_.get();await f_.set([...t,...e])}async function m_(){let e=await f_.get();return await f_.set([]),e}var h_=300,g_=`.oauth_logout_confirmation`;function __(e){return e.replace(/[&<>"']/g,e=>{switch(e){case`&`:return`&amp;`;case`<`:return`&lt;`;case`>`:return`&gt;`;case`"`:return`&quot;`;case`'`:return`&#39;`;default:return e}})}function v_(e){let t=e.request?.headers??e.headers;if(!t||Xg(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 y_=`default-src 'none'; form-action 'self'; base-uri 'none'; frame-ancestors 'none'`;function b_(e,t,n=200,r={}){return new Response(`<!doctype html><html><head><meta charset="utf-8"><title>${__(e)}</title>${r.head??``}</head><body>${t}</body></html>`,{status:n,headers:{"cache-control":`no-store`,"content-security-policy":r.contentSecurityPolicy??y_,"content-type":`text/html; charset=utf-8`,pragma:`no-cache`,"referrer-policy":`no-referrer`,"x-content-type-options":`nosniff`}})}function x_(e){return`${e.context.baseURL.replace(/\/$/,``)}/oauth2/end-session/confirm`}function S_(e){try{return new URL(x_(e)).pathname}catch{return`/oauth2/end-session/confirm`}}function C_(e){return b_(`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="${__(x_(e))}"><button type="submit" name="action" value="confirm">Confirm logout</button></form></main>`)}function w_(e){return b_(`Logged out`,`<main><p data-oidc-logout-state="logged-out">${e?`Logged out. ${__(e)}`:`Logged out.`}</p></main>`)}var T_=`(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, ${s_});
55
+ })();`,E_;async function D_(e,t){E_??=Ui(`SHA-256`,`base64`).digest(T_);let n=await E_,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="${__(e)}"></iframe>`).join(``),o=t.uri?` data-post-logout-redirect-uri="${__(t.uri)}"`:``,s=t.uri?`<noscript><a href="${__(t.uri)}">Continue</a></noscript>`:`<noscript><p>${__(i)}</p></noscript>`;return b_(`Signing out`,`<main><p data-oidc-logout-state="pending" data-logged-out-message="${__(i)}"${o}>Signing out of connected applications&hellip;</p>${s}</main>${a}<script>${T_}<\/script>`,200,{head:t.uri?`<noscript><meta http-equiv="refresh" content="${Math.ceil(s_/1e3)};url=${__(t.uri)}"></noscript>`:void 0,contentSecurityPolicy:`${y_}; frame-src ${r.join(` `)}; script-src 'sha256-${n}'`})}function O_(e,t){return b_(`Logout error`,`<main><h1>Logout error</h1><p data-oidc-logout-state="error">${__(e)}</p></main>`,t)}function k_(e,t,n,r){if(v_(e))return O_(r,t===`BAD_REQUEST`?400:t===`UNAUTHORIZED`?401:500);throw new g(t,{error:n,error_description:r})}function A_(e){return`${e.context.authCookies.sessionToken.name}${g_}`}function j_(e,t){return{...e.context.authCookies.sessionToken.attributes,httpOnly:!0,maxAge:t,path:S_(e),sameSite:`lax`}}async function M_(e,t,n={}){let r={...t?{sessionId:t}:{},...n,expiresAt:Date.now()+h_*1e3};await e.setSignedCookie(A_(e),JSON.stringify(r),e.context.secret,j_(e,h_))}async function N_(e){let t=await e.getSignedCookie(A_(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 P_(e){e.setCookie(A_(e),``,j_(e,0))}async function F_(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 I_(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 L_(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 R_(e,t,n){try{return await Wl(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 z_(e){return(Array.isArray(e)?e:[e]).filter(e=>typeof e==`string`)}function B_(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=z_(e.aud);return t.length===1?t[0]:null}async function V_(e,t,n,r){if(r)return R_(e,t,r);let i;try{i=Ti(n)}catch{return null}let a=B_(i);return a?R_(e,t,a):null}async function H_(e,t,n,r){try{let i;if(t.disableJwtPlugin){if(!r.clientSecret)return null;let a=await ql(e,t.storeClientSecret,r.clientSecret),{payload:o}=await Er(n,new TextEncoder().encode(a));i=JSON.parse(new TextDecoder().decode(o))}else{let t=Fl(e.context).options,{payload:r}=await Er(n,xi(await Gc(n,{jwksFetch:t?.jwks?.remoteUrl??`${e.context.baseURL}${t?.jwks?.jwksPath??`/jwks`}`})));i=JSON.parse(new TextDecoder().decode(r))}return i.iss!==Jb(e,t)||!z_(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 U_(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 W_(e,t){return t.post_logout_redirect_uri?U_(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 G_(e,t,n){if(n.redirectInvalid)return{invalid:!0};if(!n.clientId||!n.postLogoutRedirectUri)return{invalid:!1};let r=await R_(e,t,n.clientId);return!r||r.disabled||!r.enableEndSession?{invalid:!0}:U_(r,n.postLogoutRedirectUri,n.state)}async function K_(e,t,n={}){return t?v_(e)?(await M_(e,t.session.id,n),C_(e)):k_(e,`BAD_REQUEST`,`invalid_request`,`User confirmation is required to complete logout`):v_(e)?(await M_(e,void 0,n),C_(e)):k_(e,`BAD_REQUEST`,`invalid_request`,`No active session is available for logout`)}var q_=`The requested post-logout redirect was not registered.`;async function J_(e,t){let n=t.invalid?q_:void 0,r=await m_();return r.length>0&&v_(e)?D_(r,{uri:t.uri,note:n}):t.uri?$(e,t.uri):v_(e)?w_(n):null}async function Y_(e,t){let n=await N_(e),r=await F_(e);if(!n||n.expiresAt<=Date.now())return k_(e,`BAD_REQUEST`,`invalid_request`,`The logout confirmation is invalid or expired`);let i=await G_(e,t,n);return r?n.sessionId&&n.sessionId!==r.session.id?k_(e,`BAD_REQUEST`,`invalid_request`,`The logout confirmation is invalid or expired`):(await L_(e,r.session),bp(e),P_(e),J_(e,i)):(P_(e),i.uri?$(e,i.uri):v_(e)?w_(i.invalid?q_:void 0):k_(e,`BAD_REQUEST`,`invalid_request`,`No active session is available for logout`))}async function X_(e,t){let n=e.query??{},r=e.body??{},i={...n,...r},a=await F_(e);if(i.id_token_hint===void 0){let n={};if(i.client_id){let r=await R_(e,t,i.client_id);if(!r)return k_(e,`BAD_REQUEST`,`invalid_client`,`The logout client does not exist`);if(r.disabled)return k_(e,`BAD_REQUEST`,`invalid_client`,`The logout client is disabled`);if(!r.enableEndSession)return k_(e,`UNAUTHORIZED`,`invalid_client`,`The client is not allowed to initiate logout`);n=W_(r,i)}return K_(e,a,n)}let o=await V_(e,t,i.id_token_hint,i.client_id);if(!o)return a&&v_(e)?K_(e,a):k_(e,`BAD_REQUEST`,`invalid_client`,`The logout client does not exist`);if(o.disabled)return k_(e,`BAD_REQUEST`,`invalid_client`,`The logout client is disabled`);if(!o.enableEndSession)return k_(e,`UNAUTHORIZED`,`invalid_client`,`The client is not allowed to initiate logout`);let s=await H_(e,t,i.id_token_hint,o);if(!s)return a&&v_(e)?K_(e,a,i.client_id?W_(o,i):{}):k_(e,`UNAUTHORIZED`,`invalid_token`,`The id_token_hint is invalid`);let c=s.sid,l=await I_(e,c),u=a?.session.id===c;if(a&&!u)return K_(e,a,W_(o,i));let d=U_(o,i.post_logout_redirect_uri,i.state),f=l??(u?a?.session:null);return f&&await L_(e,f),u&&bp(e),P_(e),J_(e,d)}async function Z_(e,t){return Y_(e,t)}function Q_(e,t,n){let r=e.context.baseURL,i=!n?.jwt_disabled;return{scopes_supported:n?.scopes_supported,issuer:qb(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:[...Cs],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:[...Cs],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:[...Cs],code_challenge_methods_supported:[`S256`],authorization_response_iss_parameter_supported:!0,dpop_signing_alg_values_supported:n?.dpop_signing_alg_values_supported??[...fc],backchannel_logout_supported:i,backchannel_logout_session_supported:i,frontchannel_logout_supported:!0,frontchannel_logout_session_supported:!0}}function $_(e,t){let n=t.disableJwtPlugin?void 0:Fl(e.context).options,r=pl(t),i=t.allowUnauthenticatedClientRegistration||r.length>0;return{jwtPluginOptions:n,clientDiscoveries:r,authMetadata:Q_(e,n,{scopes_supported:t.advertisedMetadata?.scopes_supported??t.scopes,dynamic_client_registration_supported:t.allowDynamicClientRegistration,public_client_supported:i,grant_types_supported:gl(t),token_endpoint_auth_methods_supported:bl(t,{includeNone:i}),endpoint_auth_methods_supported:bl(t),jwt_disabled:t.disableJwtPlugin,dpop_signing_alg_values_supported:t.dpop?.signingAlgorithms})}}function ev(e,t){let{clientDiscoveries:n,authMetadata:r}=$_(e,t);return Cl(e,t,`oauth-authorization-server`,{...Gl(n),...r})}function tv(e,t){let n=e.context.baseURL,{jwtPluginOptions:r,clientDiscoveries:i,authMetadata:a}=$_(e,t),o={...a,claims_supported:Bm(t),claims_parameter_supported:!0,userinfo_endpoint:`${n}/oauth2/userinfo`,subject_types_supported:t.pairwiseSecret?[`public`,`pairwise`]:[`public`],acr_values_supported:Mm(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 Cl(e,t,`openid-configuration`,{...Gl(i),...o})}var nv=`public, max-age=15, stale-while-revalidate=15, stale-if-error=86400`;function rv(e,t){let n=new Headers(t);return n.has(`Cache-Control`)||n.set(`Cache-Control`,nv),n.set(`Content-Type`,`application/json`),new Response(JSON.stringify(e),{status:200,headers:n})}function iv(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`,av(e.issues,a,o),t?zu: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=av(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 ru(e.request):void 0;t&&(e.body=iu(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 av(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?I(r.path):``,c=sv(r);return{error:ov(r,c,o,n),error_description:lv(c??r,s)}}function ov(e,t,n,r){return typeof n==`string`?n:cv(e)?n?.missing??r:t?n?.invalid??r:r}function sv(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 cv(e){return e.code===`invalid_type`&&e.message.endsWith(`received undefined`)}function lv(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 uv=e=>Hu(async t=>{if(!e.allowPublicClientPrelogin)throw new P(`BAD_REQUEST`);let n=t.body.oauth_query;if(!await Hl(n,t.context.secret))throw new P(`UNAUTHORIZED`,{error:`invalid_signature`})}),dv={"P-256":`ES256`,"P-384":`ES384`,"P-521":`ES512`},fv=[`Ed25519`],pv=[`d`,`p`,`q`,`dp`,`dq`,`qi`,`oth`];function mv(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function hv(e,t){return typeof e[t]==`string`&&e[t].length>0}function gv(e){return typeof e==`string`&&Object.prototype.hasOwnProperty.call(dv,e)}function _v(e){return fv.some(t=>t===e)}function vv(e){switch(e.kty){case`RSA`:return hv(e,`n`)&&hv(e,`e`);case`EC`:return gv(e.crv)&&hv(e,`x`)&&hv(e,`y`);case`OKP`:return _v(e.crv)&&hv(e,`x`);default:return!1}}function yv(e){if(e.alg===void 0)return!0;if(typeof e.alg!=`string`||!Cs.some(t=>t===e.alg))return!1;switch(e.kty){case`RSA`:return e.alg.startsWith(`RS`)||e.alg.startsWith(`PS`);case`EC`:return gv(e.crv)&&dv[e.crv]===e.alg;case`OKP`:return _v(e.crv)&&e.alg===`EdDSA`;default:return!1}}function bv(e){let t=mv(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(!mv(e))return{valid:!1,error:`jwks keys must be supported public JWKs with required key parameters`};if(e.kty===`oct`||`k`in e||pv.some(t=>t in e))return{valid:!1,error:`jwks must contain only public asymmetric keys`};if(!vv(e))return{valid:!1,error:`jwks keys must be supported public JWKs with required key parameters`};if(!yv(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 xv(e){let t=bv(e);if(!t.valid)throw new P(`BAD_REQUEST`,{error:`invalid_client_metadata`,error_description:t.error})}async function Sv(e,t,n,r,i){if(!t)throw new P(`UNAUTHORIZED`);if(!e.headers)throw new P(`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 P(`UNAUTHORIZED`)}async function Cv(e,t,n,r,i){if(!t)throw new P(`UNAUTHORIZED`);if(!e.headers)throw new P(`BAD_REQUEST`);if(n.resourcePrivileges&&!await n.resourcePrivileges({headers:e.headers,action:r,session:t.session,user:t.user,resourceId:i}))throw new P(`UNAUTHORIZED`)}var wv=Oe({consumeClientAssertion:()=>Uv,isPrivateHostname:()=>Fv,verifyClientAssertion:()=>Wv}),Tv=new WeakMap,Ev=3e5,Dv=500,Ov=5e3,kv=65536,Av=/^application\/(?:[-\w.]+\+)?json\s*(?:;|$)/i;function jv(e,t,n,r){if(e.set(t,{jwks:n,fetchedAt:r}),e.size>Dv){let t=e.keys().next().value;t!==void 0&&e.delete(t)}}function Mv(e){let t=Tv.get(e);if(t)return t;let n=new Map;return Tv.set(e,n),n}function Nv(e){return`${e.clientDiscoveryId??`managed`}:${e.jwksUri??``}`}var Pv=[...Cs];function Fv(e){return!Yp(e)}function Iv(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(Fv(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 Lv(e){try{let t=new URL(e);return t.protocol!==`https:`&&t.protocol!==`http:`?void 0:t.origin}catch{return}}async function Rv(e){let t=e.headers.get(`content-length`);if(t!==null&&Number.isFinite(Number(t))&&Number(t)>kv)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>kv)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 zv(e,t=globalThis.fetch){let n=new AbortController,r=setTimeout(()=>n.abort(),Ov);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||!Av.test(i))throw Error(`JWKS response must use a JSON media type`);let a=await Rv(r),o;try{o=JSON.parse(a)}catch{return{valid:!1}}let s=bv(o);return s.valid?{valid:!0,jwks:s.jwks}:{valid:!1}}finally{clearTimeout(r)}}function Bv(){return new g(`BAD_REQUEST`,{error_description:`failed to fetch client JWKS`,error:`invalid_client`})}async function Vv(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?pl(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`});Iv(e,n.jwksUri,n.clientDiscoveryId?Lv(n.clientId):void 0);let i=Date.now(),a=Nv(n),o=Mv(t),s=o.get(a);if(s&&i-s.fetchedAt<Ev)return s.jwks;let c;try{c=await zv(n.jwksUri,r?.fetchClientMetadataResource)}catch{let e=Ev*2;if(s&&i-s.fetchedAt<e)return s.jwks;throw Bv()}if(!c.valid)throw Bv();return jv(o,a,c.jwks,i),c.jwks}async function Hv(e,t){if(!t.jwksUri)return null;let n=t.clientDiscoveryId?pl(e).find(e=>e.id===t.clientDiscoveryId):void 0;if(t.clientDiscoveryId&&!n?.fetchClientMetadataResource)return null;try{let r=await zv(t.jwksUri,n?.fetchClientMetadataResource);return r.valid?(jv(Mv(e),Nv(t),r.jwks,Date.now()),r.jwks):null}catch{return null}}async function Uv(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 Ui(`SHA-256`).digest(new TextEncoder().encode(`${r}:${i.jti}`)),l=ge(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 Wv(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=wi(n)}catch{throw new g(`BAD_REQUEST`,{error_description:`malformed client assertion: invalid JWT header`,error:`invalid_client`})}if(!s.alg||!Pv.includes(s.alg))throw new g(`BAD_REQUEST`,{error_description:`unsupported assertion signing algorithm: ${s.alg}`,error:`invalid_client`});let c;try{c=Ti(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 Wl(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 Vv(e,t,u),f=a??`${e.context.baseURL}/oauth2/token`,p=Jb(e,t),m=o?.endpointAudienceOnly?[f]:[...new Set([f,p])],h={issuer:l,subject:l,audience:m,algorithms:Pv},_;try{({payload:_}=await qr(n,xi(d),h))}catch(e){if(e instanceof Error&&/no matching key|no applicable key/i.test(e.message)){let e=await Hv(t,u);if(e)try{({payload:_}=await qr(n,xi(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 Uv(e,t,{namespace:`private_key_jwt:${l}`,payload:_,expectedAudience:v}),{clientId:l,client:u}}function Gv(e,t,n){return new g(e,{error:t,error_description:n},{"WWW-Authenticate":`Bearer error="${t}"`,...zu})}async function Kv(e,t,n){let r=e.headers,i;try{i=Ml(r?.get(`authorization`))}catch{throw Gv(`BAD_REQUEST`,`invalid_request`,`Malformed initial access token Authorization header`)}if(!i||!r)return;if(!t.validateInitialAccessToken)throw Gv(`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 Gv(`UNAUTHORIZED`,`invalid_token`,`Invalid initial access token`);return a}var qv=[`authorization_code`];function Jv(e){return[...new Set([...e.clientRegistrationDefaultScopes??e.scopes??[],...e.clientRegistrationAllowedScopes??[]])]}function Yv(e){let t=e.grant_types??[...qv];if(t.length>0)return t;throw new P(`BAD_REQUEST`,{error:`invalid_client_metadata`,error_description:`grant_types must contain at least one grant type`})}function Xv(e,t){return e.response_types?e.response_types:t.includes(`authorization_code`)?[`code`]:void 0}function Zv(e,t){let n=new Set(gl(e)),r=t.filter(e=>n.has(e));if(r.length===0)throw new P(`BAD_REQUEST`,{error:`invalid_client_metadata`,error_description:`no mutually supported grant_type among ${t.join(`, `)}`});return r}function Qv(e,t=`web`){let n=Yv(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:Xv(e,n)}}function $v(e){let t=new URL(e);return t.protocol!==`http:`&&t.protocol!==`https:`&&t.host!==``}function ey(e){try{let t=new URL(e).protocol;return t!==`http:`&&t!==`https:`}catch{return!1}}function ty(e,t){let n=e.clientRegistrationDefaultApplicationType??`web`;return n===`infer`?(t.redirect_uris??[]).some(e=>ey(e)||iy(e))?`native`:`web`:n}function ny(e){throw new P(`BAD_REQUEST`,{error:`invalid_redirect_uri`,error_description:e})}function ry(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 iy(e){let t=ry(e);return t===`localhost`||t===`127.0.0.1`||t===`[::1]`}function ay(e,t){let n=new Set([...e.clientRegistrationDefaultResources??[],...e.clientRegistrationAllowedResources??[]]);for(let e of t)if(!n.has(e))throw new P(`BAD_REQUEST`,{error:`invalid_target`,error_description:`requested resource ${e} is not allowed for client registration`})}async function oy(e,t,n){let r=t.clientRegistrationDefaultResources??[],i=[...new Set([...r,...n])];for(let n of i){let r=await _h(e,t,n);if(!r)throw new P(`BAD_REQUEST`,{error:`invalid_target`,error_description:`requested resource ${n} does not exist`});if(r.disabled)throw new P(`BAD_REQUEST`,{error:`invalid_target`,error_description:`requested resource ${n} is disabled`})}return i}function sy(e,t){let n;try{n=new URL(e)}catch{ny(`redirect URI must be an absolute URI: ${e}`)}(e.includes(`#`)||n.username.length>0||n.password.length>0)&&ny(`redirect URI must not include credentials or a fragment: ${e}`);let r=n.protocol===`http:`,i=n.protocol===`https:`;/^localhost\.+$/i.test(n.hostname)&&ny(`redirect URI localhost must not include trailing dots: ${e}`);let a=qp(n.hostname)||n.hostname===`localhost`;t===`web`?(!i||a)&&ny(`web clients require https redirect URIs on non-loopback hosts: ${e}`):i?a&&ny(`native clients must not use https loopback redirect URIs: ${e}`):r?iy(e)||ny(`native clients may use http only on the exact loopback hosts localhost, 127.0.0.1, or [::1]: ${e}`):lm(n)||ny(`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 cy(e,t){let n=t=>{throw new P(`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`),Fv(r.hostname)&&n(`must not point to a private or reserved address`)}var ly=new Set(Object.keys(eh.shape));function uy(e,t){return{body:Object.fromEntries(Object.entries(e).filter(([e])=>ly.has(e))),metadata:dy(e,t)}}function dy(e,t){let n=kl(t),r=Object.fromEntries(Object.entries(e).filter(([e])=>n.has(e)));return Object.keys(r).length?r:void 0}async function fy(e,t){let{body:n,metadata:r}=uy(e.body,t);if(!t.allowDynamicClientRegistration)throw new P(`FORBIDDEN`,{error:`access_denied`,error_description:`Client registration is disabled`});let i=await Z(e),a=i?void 0:await Kv(e,t,n),o=!!a;if(!(i||o||t.allowUnauthenticatedClientRegistration))throw new P(`UNAUTHORIZED`,{error_description:`Authentication required for client registration`},{"WWW-Authenticate":`Bearer`,...zu});let s=n.grant_types?.length?Zv(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 P(`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 Sv(e,i,t,`create`);let d=a?.referenceId??(i&&t.clientReference?await t.clientReference({user:i.user,session:i.session}):void 0),f=Nh(a?.clientCredentialsScopes??[]);Ph(f,Yv(l),l.token_endpoint_auth_method,t);let p=await yy(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 py(e,t,n){let r=n?.registrationSource===`clientMetadataDocument`,i=Qv(e,r?null:n?.registrationSource===`dynamic`?ty(t,e):`web`),a=i.token_endpoint_auth_method??`client_secret_basic`;if(!new Set(bl(t,{includeNone:!0})).has(a))throw new P(`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 P(`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 P(`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 P(`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??[])sy(e,c??(r?`native`:`web`));if(r)Zv(t,o);else{let e=new Set(gl(t));for(let t of o)if(!e.has(t))throw new P(`BAD_REQUEST`,{error:`invalid_client_metadata`,error_description:`unsupported grant_type ${t}`})}if(o.includes(`authorization_code`)&&!s?.includes(`code`))throw new P(`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 P(`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 P(`BAD_REQUEST`,{error:`invalid_client_metadata`,error_description:`subject_type must be "public" or "pairwise"`});if(i.subject_type===`pairwise`&&!t.pairwiseSecret)throw new P(`BAD_REQUEST`,{error:`invalid_client_metadata`,error_description:`pairwise subject_type requires server pairwiseSecret configuration`});if(i.subject_type===`pairwise`&&i.redirect_uris?.some($v))throw new P(`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 P(`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?Jv(t):t.scopes;if(d){let e=new Set(d);for(let t of l??[])if(!e?.has(t))throw new P(`BAD_REQUEST`,{error:`invalid_scope`,error_description:`cannot request scope ${t}`})}if(u&&i.require_pkce===!1)throw new P(`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 P(`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 P(`BAD_REQUEST`,{error:`invalid_client_metadata`,error_description:`jwks_uri must use HTTPS`});if(e.username||e.password)throw new P(`BAD_REQUEST`,{error:`invalid_client_metadata`,error_description:`jwks_uri must not contain credentials`});if(i.jwks_uri.includes(`#`))throw new P(`BAD_REQUEST`,{error:`invalid_client_metadata`,error_description:`jwks_uri must not include a fragment component`});if(Fv(e.hostname))throw new P(`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 P(`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 P?e:new P(`BAD_REQUEST`,{error:`invalid_client_metadata`,error_description:`jwks_uri must be a valid URL`})}i.jwks&&xv(i.jwks)}if(a===`private_key_jwt`&&!i.jwks&&!i.jwks_uri)throw new P(`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 P(`BAD_REQUEST`,{error:`invalid_client_metadata`,error_description:`backchannel_logout_uri requires the jwt plugin (disableJwtPlugin must be false)`});cy(`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 P(`BAD_REQUEST`,{error:`invalid_client_metadata`,error_description:`frontchannel_logout_uri must be an absolute URL`})}if(i.frontchannel_logout_uri.includes(`#`))throw new P(`BAD_REQUEST`,{error:`invalid_client_metadata`,error_description:`frontchannel_logout_uri must not include a fragment component`});if(e.username||e.password)throw new P(`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 P(`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 Al(t,i,e.metadata)}var my=Symbol(`client-registration-collision`);function hy(e){if(!e||typeof e!=`object`)return!1;let t=e;return t[my]===!0&&(t.kind===`oauth-client-row-unique`||t.kind===`oauth-client-resource-link-unique`)&&`cause`in t}async function gy(e,t,n){let r=n.registrationSource===`dynamic`&&!n.metadata.scope?{...n.metadata,scope:(t.clientRegistrationDefaultScopes??t.scopes)?.join(` `)}:n.metadata,i=Qv(r,n.registrationSource===`clientMetadataDocument`?null:n.registrationSource===`dynamic`?ty(t,r):`web`),a=i.token_endpoint_auth_method===`none`,o=i.token_endpoint_auth_method===`private_key_jwt`,s=xl(t,i.token_endpoint_auth_method);await py(i,t,{registrationSource:n.registrationSource,ctx:e,skipExtensionValidation:n.registrationSource===`clientMetadataDocument`&&!!n.existingClient});let c=n.clientId??t.generateClientId?.()??Vi(32,`a-z`,`A-Z`),l=a||o||s?void 0:t.generateClientSecret?.()||Vi(32,`a-z`,`A-Z`),u=l?await Yl(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:Jv(t).join(` `)}:i,g=n.registrationSource===`clientMetadataDocument`?void 0:{userId:n.userId,referenceId:n.referenceId},_=Ey({...h,redirect_uris:i.redirect_uris??[],disabled:void 0,client_secret_expires_at:u?n.registrationSource===`dynamic`&&t.clientRegistrationClientSecretExpiration?fm(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=vu(c,i.redirect_uris),n.registrationSource===`clientMetadataDocument`&&i.application_type===void 0&&(_.applicationType=null);let v=n.registrationSource===`clientMetadataDocument`?[]:n.requestedResources??[];n.registrationSource===`dynamic`&&ay(t,v);let y=await oy(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 Kd(e.context.adapter,async()=>{let r=await Wd(e.context.adapter),a,o=!1;if(S){let e;if(Ol(t)){let n=kl(t),a=$c(Sy(n,(await r.findOne({model:b,where:[{field:`clientId`,value:c}]}))?.metadata,i.metadata));await Al(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 P(`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`&&wy(e)?{[my]:!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`&&wy(t)?{[my]:!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 _y(e,t){let n=Dy({...e.client,clientSecret:e.clientSecret?(t.prefix?.clientSecret??``)+e.clientSecret:void 0});return e.resources.length>0&&(n.resources=e.resources),n}function vy(e,t){return{..._y(e,t),client_credentials_scopes:[...e.client.clientCredentialsScopes??[]]}}async function yy(e,t,n){return _y(await gy(e,t,n),t)}async function by(e,t,n){return vy(await gy(e,t,n),t)}function xy(e,t){if(e&&e.clientDiscoveryId!==t)throw new P(`BAD_REQUEST`,{error:`invalid_client`,error_description:`client_id is already owned by a different registration source`})}function Sy(e,t,n){let r=([t])=>e.has(t),i={...Object.fromEntries(Object.entries(mu(t)??{}).filter(e=>!r(e))),...Object.fromEntries(Object.entries(n??{}).filter(r))};return Object.keys(i).length?i:void 0}async function Cy(e,t,n){if(xy(n.existingClient,n.clientDiscoveryId),n.metadata.backchannel_logout_uri!==void 0||n.metadata.backchannel_logout_session_required!==void 0)throw new P(`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 P(`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:dy(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 gy(e,t,r(n.existingClient))}catch(i){if(!hy(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 gy(e,t,r(s))}catch(e){throw hy(e)?e.cause:e}}}function wy(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 Ty(e,t,n){let r=await Z(e);if(await Sv(e,r,t,`create`),!r)throw new P(`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?Nh(a??[]):[];Ph(s,Yv(o),o.token_endpoint_auth_method,t),s.length>0&&await Sv(e,r,t,`configure-client-credentials-scopes`);let c=n?.admin?o.resources:void 0;for(let n of new Set(c??[]))await Cv(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 by(e,t,l):await yy(e,t,l);return e.setStatus(201),e.json(u)}function Ey(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=$c(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 Dy(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{...$c(mu(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 Oy(e,t){let n=await Z(e);if(await Sv(e,n,t,`read`,e.query.client_id),!n)throw new P(`UNAUTHORIZED`);let r=await Wl(e,t,e.query.client_id);if(!r)throw new P(`NOT_FOUND`,{error_description:`client not found`,error:`not_found`});if(r.userId){if(r.userId!==n.user.id)throw new P(`UNAUTHORIZED`)}else if(r.referenceId&&t.clientReference){if(r.referenceId!==await t.clientReference(n))throw new P(`UNAUTHORIZED`)}else throw new P(`UNAUTHORIZED`);let i=Dy(r);return i.client_secret=void 0,i}async function ky(e,t,n){let r=await Wl(e,t,n);if(!r||r.disabled)throw new P(`NOT_FOUND`,{error_description:`client not found`,error:`not_found`});return Dy({clientId:r.clientId,name:r.name,uri:r.uri,contacts:r.contacts,icon:r.icon,tos:r.tos,policy:r.policy})}async function Ay(e,t){let n=await Z(e);if(await Sv(e,n,t,`list`),!n)throw new P(`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=Dy(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=Dy(e);return t.client_secret=void 0,t}):null);throw new P(`BAD_REQUEST`,{message:`either user_id or reference_id must be provided`})}async function jy(e,t){let n=await Z(e);if(await Sv(e,n,t,`delete`,e.body.client_id),!n)throw new P(`UNAUTHORIZED`);let r=e.body.client_id;Ul(t,r);let i=await Wl(e,t,r);if(!i)throw new P(`NOT_FOUND`,{error_description:`client not found`,error:`not_found`});if(i.userId){if(i.userId!==n.user.id)throw new P(`UNAUTHORIZED`)}else if(i.referenceId&&t.clientReference){if(i.referenceId!==await t.clientReference(n))throw new P(`UNAUTHORIZED`)}else throw new P(`UNAUTHORIZED`);await e.context.adapter.delete({model:`oauthClient`,where:[{field:`clientId`,value:r}]})}async function My(e,t,n){let r=await Z(e);if(await Sv(e,r,t,`update`,e.body.client_id),!r)throw new P(`UNAUTHORIZED`);let i=e.body.client_id;Ul(t,i);let a=await Wl(e,t,i);if(!a)throw new P(`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 P(`UNAUTHORIZED`);if(h&&await Sv(e,r,t,`configure-client-credentials-scopes`,i),!p&&o===void 0){let e=Dy(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:Nh(o);v!==void 0&&(Ph(v,g,_,t),v.length>0&&!h&&await Sv(e,r,t,`configure-client-credentials-scopes`,i));let y={...Dy({...a,metadata:void 0}),...f,metadata:f.metadata??mu(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 py(y,t,{ctx:e});let b={...Ey(f)};f.redirect_uris&&a.sectorIdentifier&&(b.sectorIdentifier=vu(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 Yl(e,t,t.generateClientSecret?.()||Vi(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 P(`INTERNAL_SERVER_ERROR`,{error_description:`unable to update client`,error:`invalid_client`});let S=Dy(x);return S.client_secret=void 0,n?.admin?{...S,client_credentials_scopes:[...x.clientCredentialsScopes??[]]}:S}async function Ny(e,t){let n=await Z(e);if(await Sv(e,n,t,`rotate`,e.body.client_id),!n)throw new P(`UNAUTHORIZED`);let r=e.body.client_id;Ul(t,r);let i=await Wl(e,t,r);if(!i)throw new P(`NOT_FOUND`,{error_description:`client not found`,error:`not_found`});if(i.userId){if(i.userId!==n.user.id)throw new P(`UNAUTHORIZED`)}else if(i.referenceId&&t.clientReference){if(i.referenceId!==await t.clientReference(n))throw new P(`UNAUTHORIZED`)}else throw new P(`UNAUTHORIZED`);if(i.tokenEndpointAuthMethod===`none`||!i.clientSecret)throw new P(`BAD_REQUEST`,{error_description:`secret rotation is only available for clients using client_secret authentication`,error:`invalid_client`});let a=t.generateClientSecret?.()||Vi(32,`a-z`,`A-Z`),o=a?await Yl(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 P(`INTERNAL_SERVER_ERROR`,{error_description:`unable to update client`,error:`invalid_client`});return Dy({...s,clientSecret:(t.prefix?.clientSecret??``)+a})}async function Py(e,t){if(!t.allowClientKeyRotation)throw new P(`FORBIDDEN`,{error:`access_denied`,error_description:`Client key rotation is disabled`});let{body:n}=e;xv(n.jwks);let{client:r}=await Wv(e,t,n.client_assertion,n.client_assertion_type,void 0,Ah({context:e.context,request:void 0},`/oauth2/client/rotate-keys`),{endpointAudienceOnly:!0,assertClient:e=>Fy(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 P(`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 Fy(e,t){if(Ul(e,t.clientId),t.clientDiscoveryId||t.jwksUri||!t.jwks)throw new P(`BAD_REQUEST`,{error:`invalid_client`,error_description:`client keys are not stored inline; rotate them where the client publishes them`})}var Iy=v().trim().min(1),Ly=B(v().trim().min(1)).min(1),Ry=e=>X(`/admin/oauth2/create-client`,{method:`POST`,body:V({redirect_uris:B(Q).min(1).optional(),scope:v().optional(),client_name:v().optional(),client_uri:v().optional(),logo_uri:v().optional(),contacts:B(v().min(1)).min(1).optional(),tos_uri:v().optional(),policy_uri:v().optional(),software_id:v().optional(),software_version:v().optional(),software_statement:v().optional(),post_logout_redirect_uris:B(Q).min(1).optional(),backchannel_logout_uri:Q.optional(),backchannel_logout_session_required:z().optional(),frontchannel_logout_uri:Q.optional(),frontchannel_logout_session_required:z().optional(),token_endpoint_auth_method:Iy.optional(),application_type:L([`web`,`native`]).optional(),jwks:Jm.optional(),jwks_uri:v().optional(),grant_types:Ly.optional(),client_credentials_scopes:B(v().trim().min(1)).optional(),resources:B(Gm).optional(),response_types:B(L([`code`])).optional(),client_secret_expires_at:r([v(),a()]).optional().default(0),skip_consent:z().optional(),enable_end_session:z().optional(),require_pkce:z().optional(),dpop_bound_access_tokens:z().optional(),subject_type:L([`public`,`pairwise`]).optional(),metadata:c(v(),oe()).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=>Ty(t,e,{admin:!0})),zy=e=>X(`/oauth2/create-client`,{method:`POST`,use:[wp],body:V({redirect_uris:B(Q).min(1).optional(),scope:v().optional(),client_name:v().optional(),client_uri:v().optional(),logo_uri:v().optional(),contacts:B(v().min(1)).min(1).optional(),tos_uri:v().optional(),policy_uri:v().optional(),software_id:v().optional(),software_version:v().optional(),software_statement:v().optional(),post_logout_redirect_uris:B(Q).min(1).optional(),backchannel_logout_uri:Q.optional(),backchannel_logout_session_required:z().optional(),frontchannel_logout_uri:Q.optional(),frontchannel_logout_session_required:z().optional(),token_endpoint_auth_method:Iy.optional(),application_type:L([`web`,`native`]).optional(),jwks:Jm.optional(),jwks_uri:v().optional(),grant_types:Ly.optional(),response_types:B(L([`code`])).optional(),dpop_bound_access_tokens:z().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=>Ty(t,e)),By=e=>X(`/oauth2/get-client`,{method:`GET`,use:[wp],query:V({client_id:v()}),metadata:{openapi:{description:`Get OAuth2 formatted client details`}}},async t=>Oy(t,e)),Vy=e=>X(`/oauth2/public-client`,{method:`GET`,use:[wp],query:V({client_id:v()}),metadata:{openapi:{description:`Gets publicly available client fields`}}},async t=>{let n=t.query.client_id;return ky(t,e,n)}),Hy=e=>X(`/oauth2/public-client-prelogin`,{method:`POST`,use:[uv(e)],body:V({client_id:v(),oauth_query:v().optional()}),metadata:{openapi:{description:`Gets publicly available client fields (prior to login)`}}},async t=>{let n=t.body.client_id;return ky(t,e,n)}),Uy=e=>X(`/oauth2/get-clients`,{method:`GET`,use:[wp],metadata:{openapi:{description:`Get OAuth2 formatted client details for a user or organization`}}},async t=>Ay(t,e)),Wy=e=>X(`/admin/oauth2/update-client`,{method:`PATCH`,body:V({client_id:v(),update:V({redirect_uris:B(Q).min(1).optional(),scope:v().optional(),client_name:v().optional(),client_uri:v().optional(),logo_uri:v().optional(),contacts:B(v().min(1)).min(1).optional(),tos_uri:v().optional(),policy_uri:v().optional(),software_id:v().optional(),software_version:v().optional(),software_statement:v().optional(),post_logout_redirect_uris:B(Q).min(1).optional(),backchannel_logout_uri:Q.nullable().optional(),backchannel_logout_session_required:z().optional(),frontchannel_logout_uri:Q.nullable().optional(),frontchannel_logout_session_required:z().optional(),application_type:L([`web`,`native`]).optional(),grant_types:Ly.optional(),client_credentials_scopes:B(v().trim().min(1)).optional(),response_types:B(L([`code`])).optional(),client_secret_expires_at:r([v(),a()]).optional(),skip_consent:z().optional(),enable_end_session:z().optional(),disabled:z().optional(),dpop_bound_access_tokens:z().optional(),metadata:c(v(),oe()).optional()})}),metadata:{SERVER_ONLY:!0,openapi:{description:`Updates OAuth2 formatted client details.`}}},async t=>My(t,e,{admin:!0})),Gy=e=>X(`/oauth2/update-client`,{method:`POST`,use:[wp],body:V({client_id:v(),update:V({redirect_uris:B(Q).min(1).optional(),scope:v().optional(),client_name:v().optional(),client_uri:v().optional(),logo_uri:v().optional(),contacts:B(v().min(1)).min(1).optional(),tos_uri:v().optional(),policy_uri:v().optional(),software_id:v().optional(),software_version:v().optional(),software_statement:v().optional(),post_logout_redirect_uris:B(Q).min(1).optional(),backchannel_logout_uri:Q.nullable().optional(),backchannel_logout_session_required:z().optional(),frontchannel_logout_uri:Q.nullable().optional(),frontchannel_logout_session_required:z().optional(),application_type:L([`web`,`native`]).optional(),grant_types:Ly.optional(),response_types:B(L([`code`])).optional()})}),metadata:{openapi:{description:`Updates OAuth2 formatted client details.`}}},async t=>My(t,e)),Ky=e=>X(`/oauth2/client/rotate-secret`,{method:`POST`,use:[wp],body:V({client_id:v()}),metadata:{noStore:!0,openapi:{description:`Rotates a confidential client's secret`}}},async t=>Ny(t,e)),qy=e=>iv(`/oauth2/client/rotate-keys`,{method:`POST`,body:V({client_assertion:v(),client_assertion_type:v(),jwks:Jm}),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=>Py(t,e)),Jy=e=>X(`/oauth2/delete-client`,{method:`POST`,use:[wp],body:V({client_id:v()}),metadata:{openapi:{description:`Deletes an oauth client`}}},async t=>jy(t,e));async function Yy(e,t,n){return await e.context.adapter.findOne({model:`oauthConsent`,where:[{field:`id`,value:n}]})}async function Xy(e,t){let n=await Z(e);if(!n)throw new P(`UNAUTHORIZED`);let{id:r}=e.query;if(!r)throw new P(`NOT_FOUND`,{error_description:`missing id parameter`,error:`not_found`});let i=await Yy(e,t,r);if(!i)throw new P(`NOT_FOUND`,{error_description:`no consent`,error:`not_found`});if(i.userId!==n.user.id)throw new P(`UNAUTHORIZED`);return i}async function Zy(e,t){let n=await Z(e);if(!n)throw new P(`UNAUTHORIZED`);return await e.context.adapter.findMany({model:`oauthConsent`,where:[{field:`userId`,value:n.user.id}]})}async function Qy(e,t){let n=await Z(e);if(!n)throw new P(`UNAUTHORIZED`);let{id:r}=e.body;if(!r)throw new P(`NOT_FOUND`,{error_description:`missing id parameter`,error:`not_found`});let i=await Yy(e,t,r);if(!i)throw new P(`NOT_FOUND`,{error_description:`no consent`,error:`not_found`});if(i.userId!==n.user.id)throw new P(`UNAUTHORIZED`);await e.context.adapter.delete({model:`oauthConsent`,where:[{field:`id`,value:r}]})}async function $y(e,t){let n=await Z(e);if(!n)throw new P(`UNAUTHORIZED`);let{id:r}=e.body;if(!r)throw new P(`NOT_FOUND`,{error_description:`missing id parameter`,error:`not_found`});let i=await Yy(e,t,r);if(!i)throw new P(`NOT_FOUND`,{error_description:`no consent`,error:`not_found`});if(i.userId!==n.user.id)throw new P(`UNAUTHORIZED`);let a=await Wl(e,t,i.clientId);if(!a)throw new P(`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 P(`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 eb=e=>X(`/oauth2/get-consent`,{method:`GET`,query:V({id:v()}),use:[wp],metadata:{openapi:{description:`Gets details of a specific OAuth2 consent for a user`}}},async t=>Xy(t,e)),tb=e=>X(`/oauth2/get-consents`,{method:`GET`,use:[wp],metadata:{openapi:{description:`Gets all available OAuth2 consents for a user`}}},async t=>Zy(t,e)),nb=e=>X(`/oauth2/update-consent`,{method:`POST`,use:[wp],body:V({id:v(),update:V({scopes:B(v())})}),metadata:{openapi:{description:`Updates consent granted to a client.`}}},async t=>$y(t,e)),rb=e=>X(`/oauth2/delete-consent`,{method:`POST`,use:[wp],body:V({id:v()}),metadata:{openapi:{description:`Deletes consent granted to a client`}}},async t=>Qy(t,e)),ib=e=>e.schema?.oauthResource?.modelName??`oauthResource`,ab=e=>e.schema?.oauthClientResource?.modelName??`oauthClientResource`,ob=e=>e.schema?.oauthClient?.modelName??`oauthClient`;function sb(e){try{return decodeURIComponent(e)}catch{return e}}function cb(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 lb(e,t){await Cv(e,await Z(e),t,`create`);let n=e.body;if(!n?.identifier)throw new P(`BAD_REQUEST`,{error:`invalid_request`,error_description:`identifier is required`});await oh(t,n.identifier);let r=new Date,i;try{i=await e.context.adapter.create({model:ib(t),data:cb(n,r)})}catch(e){let t=e instanceof Error?e.message:String(e);throw/unique|duplicate|UNIQUE/i.test(t)?new P(`BAD_REQUEST`,{error:`invalid_request`,error_description:`resource ${n.identifier} already exists`}):e}if(!i)throw new P(`BAD_REQUEST`,{error:`invalid_request`,error_description:`resource ${n.identifier} could not be created`});return gh(i.identifier),e.json(i,{status:201})}async function ub(e,t){await Cv(e,await Z(e),t,`list`);let n=await e.context.adapter.findMany({model:ib(t)});return e.json(n??[])}async function db(e,t){let n=sb(e.params.identifier);await Cv(e,await Z(e),t,`read`,n);let r=await e.context.adapter.findOne({model:ib(t),where:[{field:`identifier`,value:n}]});if(!r)throw new P(`NOT_FOUND`,{error:`not_found`,error_description:`resource ${n} not found`});return e.json(r)}async function fb(e,t){let n=sb(e.params.identifier);if(await Cv(e,await Z(e),t,`update`,n),!await e.context.adapter.findOne({model:ib(t),where:[{field:`identifier`,value:n}]}))throw new P(`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:ib(t),where:[{field:`identifier`,value:n}],update:r}),gh(n);let i=await e.context.adapter.findOne({model:ib(t),where:[{field:`identifier`,value:n}]});if(!i)throw new P(`NOT_FOUND`,{error:`not_found`,error_description:`resource ${n} not found`});return e.json(i)}async function pb(e,t){let n=sb(e.params.identifier);if(await Cv(e,await Z(e),t,`delete`,n),!await e.context.adapter.findOne({model:ib(t),where:[{field:`identifier`,value:n}]}))throw new P(`NOT_FOUND`,{error:`not_found`,error_description:`resource ${n} not found`});return await e.context.adapter.delete({model:ib(t),where:[{field:`identifier`,value:n}]}),gh(n),e.json({deleted:!0})}async function mb(e,t){let n=await Z(e),r=sb(e.params.identifier),i=sb(e.params.client_id);if(await Cv(e,n,t,`link`,r),!await e.context.adapter.findOne({model:ib(t),where:[{field:`identifier`,value:r}]}))throw new P(`NOT_FOUND`,{error:`not_found`,error_description:`resource ${r} not found`});if(!await e.context.adapter.findOne({model:ob(t),where:[{field:`clientId`,value:i}]}))throw new P(`NOT_FOUND`,{error:`not_found`,error_description:`client ${i} not found`});try{await e.context.adapter.create({model:ab(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 hb(e,t){let n=await Z(e),r=sb(e.params.identifier),i=sb(e.params.client_id);return await Cv(e,n,t,`unlink`,r),await e.context.adapter.deleteMany({model:ab(t),where:[{field:`clientId`,value:i},{field:`resourceId`,value:r}]}),e.json({unlinked:!0})}var gb=V({identifier:v().min(1).optional(),name:v().optional(),accessTokenTtl:a().int().positive().nullable().optional(),refreshTokenTtl:a().int().positive().nullable().optional(),signingAlgorithm:L(nh).nullable().optional(),signingKeyId:v().nullable().optional(),allowedScopes:B(v()).nullable().optional(),customClaims:c(v(),oe()).nullable().optional(),dpopBoundAccessTokensRequired:z().optional(),disabled:z().optional(),metadata:c(v(),oe()).nullable().optional()}),_b=e=>X(`/admin/oauth2/resources`,{method:`POST`,body:gb.required({identifier:!0}),metadata:{SERVER_ONLY:!0}},async t=>lb(t,e)),vb=e=>X(`/admin/oauth2/resources`,{method:`GET`,metadata:{SERVER_ONLY:!0}},async t=>ub(t,e)),yb=e=>X(`/admin/oauth2/resources/:identifier`,{method:`GET`,metadata:{SERVER_ONLY:!0}},async t=>db(t,e)),bb=e=>X(`/admin/oauth2/resources/:identifier`,{method:`PATCH`,body:gb,metadata:{SERVER_ONLY:!0}},async t=>fb(t,e)),xb=e=>X(`/admin/oauth2/resources/:identifier`,{method:`DELETE`,metadata:{SERVER_ONLY:!0}},async t=>pb(t,e)),Sb=e=>X(`/admin/oauth2/resources/:identifier/clients/:client_id`,{method:`POST`,metadata:{SERVER_ONLY:!0}},async t=>mb(t,e)),Cb=e=>X(`/admin/oauth2/resources/:identifier/clients/:client_id`,{method:`DELETE`,metadata:{SERVER_ONLY:!0}},async t=>hb(t,e));async function wb(e,t,n){if(!await lh(e,t,n.aud,[sh(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 Tb(e,t){await e.context.adapter.delete({model:`oauthAccessToken`,where:t.id?[{field:`id`,value:t.id}]:[{field:`token`,value:t.token}]})}async function Eb(e,t,n){let{userId:r}=t;if(t.revoked){await rg(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 rg(e,n,r)}async function Db(e,t){let{token:n,token_type_hint:r}=e.body,{clientId:i,clientSecret:a,preVerified:o,authMethod:s}=hu(await gu(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=yc(n)),!n?.length)throw new g(`BAD_REQUEST`,{error_description:`missing a required token for introspection`,error:`invalid_request`});let c=await pu(e,t,i,a,void 0,o,void 0,s);try{let i=await Hh(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 wb(e,t,i.payload):(i.type===`opaque`?await Tb(e,i.record):await Eb(e,i.record,c.clientId),null)}catch(e){throw e instanceof g?e:(ye.error(`Revocation error:`,e),new g(`INTERNAL_SERVER_ERROR`))}}var Ob={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}}}},kb=[`openid`,`profile`,`email`,`offline_access`],Ab=V({id_token_hint:v().optional(),client_id:v().optional(),post_logout_redirect_uri:Q.optional(),state:v().optional()}),jb=Hd(()=>null),Mb=jb.get,Nb=new WeakMap,Pb=`signedQueryIssuedAtMs`;function Fb(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 Ib=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??kb).filter(e=>e.length));if(t){for(let e of t)if(!n.has(e))throw new H(`clientRegistrationAllowedScope ${e} not found in scopes`)}let i=e.authenticationContext?.acrValuesSupported;if(i&&(i.length===0||i.includes(``)))throw new H(`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 H(`advertisedMetadata.scopes_supported ${t} not found in scopes`);let a=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(!a.has(e))throw new H(`${t} resource ${e} not found in resources`);let o=new Set([`sub`,`iss`,`aud`,`exp`,`iat`,`sid`,`scope`,`azp`,...zm.filter(e=>n.has(Rm[e].scope))]),s={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(dl(s.extensions),s.pairwiseSecret&&s.pairwiseSecret.length<32)throw new H(`pairwiseSecret must be at least 32 characters long for adequate HMAC-SHA256 security`);if(s.grantTypes&&s.grantTypes.includes(`refresh_token`)&&!s.grantTypes.includes(`authorization_code`))throw new H(`refresh_token grant requires authorization_code grant`);if(s.disableJwtPlugin&&(s.storeClientSecret===`hashed`||typeof s.storeClientSecret==`object`&&`hash`in s.storeClientSecret))throw new H(`unable to store hashed secrets because id tokens will be signed with secret`);if(!s.disableJwtPlugin&&(s.storeClientSecret===`encrypted`||typeof s.storeClientSecret==`object`&&(`encrypt`in s.storeClientSecret||`decrypt`in s.storeClientSecret)))throw new H(`encryption method not recommended, please use 'hashed' or the 'hash' function`);let c=async(e,t)=>{let n=new URL(e.url).pathname,r=t.options.advanced?.skipTrailingSlashes?n.replace(/\/+$/,``)||`/`:n,i=s.disableJwtPlugin?t.baseURL:Fl(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},c=new Set([`/.well-known/oauth-authorization-server${a}`,`${a}/.well-known/oauth-authorization-server`]),l=`${a}/.well-known/openid-configuration`,u=c.has(r),d=s.scopes?.includes(`openid`)&&r===l,f=t=>{let n=rv(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 s.scopes?.includes(`openid`)?{response:f(tv(o,s))}:{response:f(ev(o,s))};if(d)return{response:f(tv(o,s))}},l=iv(`/oauth2/authorize`,{method:[`GET`,`POST`],body:V({}).passthrough(),redirectOnError:ex(s),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=>tx(e,s,e.authorizeSettings??{isAuthorize:!0})),u=(e,t)=>im(l,{...e,asResponse:!1,returnHeaders:!1,returnStatus:!1,authorizeSettings:t??{}});return{id:`oauth-provider`,version:Yg,options:s,onRequest:c,init:async e=>{if(e.options.secondaryStorage&&e.options.session?.storeSessionInDatabase!==!0)throw new H("OAuth Provider requires `session.storeSessionInDatabase: true` when using secondaryStorage");if(s.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 H(`\`allowClientKeyRotation\` requires single-use client assertions, which ${t} does not enforce`)}if(await Dh(e,s).catch(t=>Ch(e,t)),Oh(s),!s.disableJwtPlugin){let t=Fl(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 l_(t,s,{sessionId:e.id,userId:e.userId});if(!n)return;let r=Nb.get(t)??new Map;r.set(e.id,n),Nb.set(t,r)},async after(e,t){if(!t)return;let n=Nb.get(t);if(!n)return;let r=n.get(e.id);if(n.delete(e.id),n.size===0&&Nb.delete(t),!r)return;await p_(r.frontchannelLogoutUris);let i=u_(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:Hu(async e=>{let t=e.body.oauth_query;if(!await Hl(t,e.context.secret))throw new P(`BAD_REQUEST`,{error:`invalid_signature`});let n=Fe(t);await jb.set(n),e.path===`/sign-in/social`&&await $d({query:n.query,...n.signedQueryIssuedAt?{[Pb]:n.signedQueryIssuedAt.getTime()}:{}})})}],after:[{matcher(e){return Ef(e.context.responseHeaders?.get(`set-cookie`)||``).has(e.context.authCookies.sessionToken.name)},handler:Hu(async e=>{let t=Ef(e.context.responseHeaders?.get(`set-cookie`)||``).get(e.context.authCookies.sessionToken.name)?.value.split(`.`)[0];if(!t)return;let n=await jb.get(),r=(await Xd())?.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??Fb(r?.[Pb]),d=Eu(a,`login`);return Tu(o.session.createdAt,l)&&(d=Du(d)),e.query=wu(d),await u(e)})}]},endpoints:{getOAuthServerConfig:X(`/.well-known/oauth-authorization-server`,{method:`GET`,metadata:{SERVER_ONLY:!0}},async e=>s.scopes&&s.scopes.includes(`openid`)?tv(e,s):ev(e,s)),getOpenIdConfig:X(`/.well-known/openid-configuration`,{method:`GET`,metadata:{SERVER_ONLY:!0}},async e=>{if(s.scopes&&!s.scopes.includes(`openid`))throw new P(`NOT_FOUND`);return tv(e,s)}),oauth2Authorize:l,oauth2Consent:X(`/oauth2/consent`,{method:`POST`,body:V({accept:z().meta({description:`Accept or deny user consent for a set of scopes`}),scope:v().optional().meta({description:`List of accept of accepted space-separated scopes. If none is provided, then all originally requested scopes are accepted.`}),claims:Em.optional().meta({description:`Accepted OIDC claims request object. If none is provided, then all originally requested claims are accepted.`}),reference_id:v().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:v().optional().meta({description:`The redirected page's query parameters`})}),use:[wp],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=>Qg(e,s,u)),oauth2Continue:X(`/oauth2/continue`,{method:`POST`,body:V({selected:z().optional().meta({description:`Confirms an account has been selected and authorization can proceed.`}),created:z().optional().meta({description:`Confirms an account was registered`}),postLogin:z().optional().meta({description:`Resumes after the post login page. postLogin.shouldRedirect runs again with isContinuation: true.`}),oauth_query:v().optional().meta({description:`The redirected page's query parameters`})}),use:[wp],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=>$g(e,u)),oauth2Token:iv(`/oauth2/token`,{method:`POST`,formParams:{repeatable:[`resource`,`audience`]},body:V({grant_type:v().trim().min(1),client_id:v().optional(),client_secret:v().optional(),client_assertion:v().optional(),client_assertion_type:v().optional(),code:v().optional(),code_verifier:v().optional(),redirect_uri:Q.optional(),refresh_token:v().optional(),resource:r([Gm,B(Gm).min(1)]).optional(),scope:v().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=>Xh(e,s)),oauth2Introspect:iv(`/oauth2/introspect`,{method:`POST`,formParams:{},body:V({client_id:v().optional(),client_secret:v().optional(),client_assertion:v().optional(),client_assertion_type:v().optional(),token:v(),token_type_hint:v().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=>Jg(e,s)),oauth2Revoke:iv(`/oauth2/revoke`,{method:`POST`,formParams:{},body:V({client_id:v().optional(),client_secret:v().optional(),client_assertion:v().optional(),client_assertion_type:v().optional(),token:v(),token_type_hint:v().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=>Db(e,s)),oauth2UserInfo:X(`/oauth2/userinfo`,{method:[`GET`,`POST`],body:V({access_token:v().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=>Kh(e,s)),oauth2EndSession:iv(`/oauth2/end-session`,{method:[`GET`,`POST`],body:Ab.optional(),query:Ab.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=>X_(e,s)),oauth2EndSessionConfirmation:iv(`/oauth2/end-session/confirm`,{method:`POST`,body:V({action:F(`confirm`)}),metadata:{noStore:!0,allowedMediaTypes:[`application/x-www-form-urlencoded`],scope:`http`}},async e=>Z_(e,s)),registerOAuthClient:iv(`/oauth2/register`,{method:`POST`,body:eh.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=>fy(e,s)),adminCreateOAuthClient:Ry(s),createOAuthClient:zy(s),getOAuthClient:By(s),getOAuthClientPublic:Vy(s),getOAuthClientPublicPrelogin:Hy(s),getOAuthClients:Uy(s),adminUpdateOAuthClient:Wy(s),updateOAuthClient:Gy(s),rotateClientSecret:Ky(s),rotateClientKeys:qy(s),deleteOAuthClient:Jy(s),getOAuthConsent:eb(s),getOAuthConsents:tb(s),updateOAuthConsent:nb(s),deleteOAuthConsent:rb(s),adminCreateOAuthResource:_b(s),adminListOAuthResources:vb(s),adminGetOAuthResource:yb(s),adminUpdateOAuthResource:bb(s),adminDeleteOAuthResource:xb(s),adminLinkClientResource:Sb(s),adminUnlinkClientResource:Cb(s)},schema:xf(structuredClone(Ob),s?.schema),rateLimit:[...s.rateLimit?.token===!1?[]:[{pathMatcher:e=>e===`/oauth2/token`,window:s.rateLimit?.token?.window??60,max:s.rateLimit?.token?.max??20}],...s.rateLimit?.authorize===!1?[]:[{pathMatcher:e=>e===`/oauth2/authorize`,window:s.rateLimit?.authorize?.window??60,max:s.rateLimit?.authorize?.max??30}],...s.rateLimit?.introspect===!1?[]:[{pathMatcher:e=>e===`/oauth2/introspect`,window:s.rateLimit?.introspect?.window??60,max:s.rateLimit?.introspect?.max??100}],...s.rateLimit?.revoke===!1?[]:[{pathMatcher:e=>e===`/oauth2/revoke`,window:s.rateLimit?.revoke?.window??60,max:s.rateLimit?.revoke?.max??30}],...s.rateLimit?.register===!1?[]:[{pathMatcher:e=>e===`/oauth2/register`,window:s.rateLimit?.register?.window??60,max:s.rateLimit?.register?.max??5}],...s.rateLimit?.rotateClientKeys===!1?[]:[{pathMatcher:e=>e===`/oauth2/client/rotate-keys`,window:s.rateLimit?.rotateClientKeys?.window??60,max:s.rateLimit?.rotateClientKeys?.max??5}],...s.rateLimit?.userinfo===!1?[]:[{pathMatcher:e=>e===`/oauth2/userinfo`,window:s.rateLimit?.userinfo?.window??60,max:s.rateLimit?.userinfo?.max??60}]]}};function Lb(e,t,n){return t!==0&&n.getTime()-e.getTime()<=t*1e3}function Rb(e){let{max_age:t,...n}=e;return n}function zb(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()}`:_d(e,o)}function Bb(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 Vb={response_type:{invalid:`unsupported_response_type`},resource:{invalid:`invalid_target`}};function Hb(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function Ub(e){return typeof e==`string`?e:void 0}function Wb(e,t){let n=e.method===`POST`&&t?.isAuthorize===!0?e.body:e.query;return{...Hb(n)?n:{}}}var $=(e,t)=>{let n=Xg(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 Gb(e,t,n,r,i){return $(e,n.redirect_uri?zb(n.redirect_uri,r,i,n.state,Jb(e,t)):Yb(e,r,i))}function Kb(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?zb(n,i,a):Yb(e,i,a)}function qb(e){try{let t=new URL(e);return t.protocol!==`https:`&&!Jp(t.host)&&(t.protocol=`https:`),t.search=``,t.hash=``,t.toString().replace(/\/$/,``)}catch{return e}}function Jb(e,t){let n;if(t.disableJwtPlugin)n=e.context.baseURL;else try{n=Fl(e.context).options?.jwt?.issuer??e.context.baseURL}catch{n=e.context.baseURL}return qb(n)}function Yb(e,t,n){return zb(e.context.options.onAPIError?.errorURL||`${e.context.baseURL}/error`,t,n)}function Xb(e){let t;try{t=new URL(e)}catch{return}let n=qp(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 Zb(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=Xb(t);return e.find(e=>e===t?!0:a?Xb(e)===a:!1)}function Qb(e){if(!Q.safeParse(e).success)return!1;let t=new URL(e);return t.username.length===0&&t.password.length===0}async function $b(e,t,n,r){if(!n||!r)return null;let i;try{i=await Wl(e,t,n)}catch{return null}if(!i||i.disabled)return null;let a=i.redirectUris??[],o=Zb(a,r);if(t.validateRedirectUri){if(!Qb(r))return null;try{return await t.validateRedirectUri(r,a,!!o)?r:null}catch{return null}}return o?r:null}function ex(e){return async({error:t,error_description:n,ctx:r})=>{let i=r.query??{},a=await $b(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,zb(a,t,n,typeof i.state==`string`?i.state:void 0,Jb(r,e),Bb(i))):$(r,Yb(r,t,n))}}async function tx(e,t,n){if(!e.request)throw new g(`UNAUTHORIZED`,{error_description:`request not found`,error:`invalid_request`});let r=e.request,i=Wb(e,n),a=_l(t,i);if(a){if(n?.isAuthorize===!0&&!await Z(e))return e.query={[a.parameter]:a.value},ax(e,t,`login`);let o=a.handler.errorPage?.({ctx:e,value:a.value}),s=t=>Kb(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 nx(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=Ub(i.request),s=Ub(i.request_uri);if(o!==void 0&&s!==void 0)return ex(t)({error:`invalid_request`,error_description:`request and request_uri cannot be used together`,ctx:e});if(o!==void 0)return ex(t)({error:`request_not_supported`,error_description:`request object not supported`,ctx:e});if(s!==void 0){let n=Ub(i.client_id);if(!n)return ex(t)({error:`invalid_request`,error_description:`client_id is required`,ctx:e});if(!t.requestUriResolver)return ex(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 ex(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=Zm.safeParse(i);if(!c.success){let n=av(c.error.issues,Vb);return ex(t)({...n,ctx:e})}if(i=c.data,e.query=i,await jb.set({query:rx(i).toString()}),!i.response_type)return ex(t)({error:`invalid_request`,error_description:`response_type is required`,ctx:e});if((e.query?.prompt?_u(e.query?.prompt):void 0)?.has(`select_account`)&&!t.selectAccount?.page)return $(e,Yb(e,`unsupported_prompt_select_account`,`unsupported prompt type`));if(i.response_type!==`code`)return $(e,Yb(e,`unsupported_response_type`,`unsupported response type`));let l=await Wl(e,t,i.client_id);if(!l)return $(e,Yb(e,`invalid_client`,`client not found`));if(l.disabled)return $(e,Yb(e,`client_disabled`,`client is disabled`));if(!su(l,`authorization_code`))return $(e,Yb(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=!!Zb(u,i.redirect_uri);if(t.validateRedirectUri&&Qb(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,Yb(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,zb(i.redirect_uri,`invalid_scope`,`The following scopes are invalid: ${r.join(`, `)}`,i.state,Jb(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,zb(i.redirect_uri,`invalid_request`,`openid scope must be requested when using the claims parameter`,i.state,Jb(e,t)));if(p&&!Dm(i.claims))return $(e,zb(i.redirect_uri,`invalid_request`,`claims must be a valid Claims request object`,i.state,Jb(e,t)));if(p&&!Mm(t).some(e=>km(i.claims,e)))return $(e,zb(i.redirect_uri,`access_denied`,`essential acr requirement cannot be met`,i.state,Jb(e,t)));if(i.resource!==void 0)try{await uh(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,zb(i.redirect_uri,r,a,i.state,Jb(e,t)))}throw n}let m=Ou(l,{scopes:f,nonce:i.nonce});if(m&&(!i.code_challenge||!i.code_challenge_method))return $(e,zb(i.redirect_uri,`invalid_request`,m.valueOf(),i.state,Jb(e,t)));if(i.code_challenge||i.code_challenge_method){if(!i.code_challenge||!i.code_challenge_method)return $(e,zb(i.redirect_uri,`invalid_request`,`code_challenge and code_challenge_method must both be provided`,i.state,Jb(e,t)));if(![`S256`].includes(i.code_challenge_method))return $(e,zb(i.redirect_uri,`invalid_request`,`invalid code_challenge method, only S256 is supported`,i.state,Jb(e,t)))}return nx(e,t,r.headers,n,{query:i,client:l,approve:n=>ix(e,t,{...n,query:n.query,clientId:l.clientId,resource:Rl(n.query.resource)??[]})})}async function nx(e,t,n,r,i){let{query:a}=i,{client:o}=i;e.query=a;let s=a.scope?.split(` `).filter(e=>e)??[],c=Om(a.claims,Bm(t)),l=Rl(a.resource)??[],u=a.prompt?_u(a.prompt):void 0,d=u?.has(`none`)??!1,f=await Z(e),p=a.max_age,m=f!=null&&p!==void 0&&Lb(new Date(f.session.createdAt),p,new Date);if(!f||f!=null&&p!==void 0&&!m||u?.has(`login`)||u?.has(`create`))return d?Gb(e,t,a,`login_required`,`authentication required`):ax(e,t,u?.has(`create`)?`create`:`login`);m&&(a=Rb(a),e.query=a);let h=()=>({user:f.user,session:f.session,scopes:s,query:rx(a)});if(r?.isAuthorize&&u?.has(`select_account`))return ax(e,t,`select_account`);if(r?.isAuthorize&&t.selectAccount&&await t.selectAccount.shouldRedirect({headers:n,...h()}))return d?Gb(e,t,a,`account_selection_required`,`End-User account selection is required`):ax(e,t,`select_account`);if(t.signup?.shouldRedirect){let r=await t.signup.shouldRedirect({headers:n,...h()});if(r)return d?Gb(e,t,a,`interaction_required`,`End-User interaction is required`):ax(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?Gb(e,t,a,`interaction_required`,`End-User interaction is required`):ax(e,t,`post_login`);if(u?.has(`consent`)||i.requireConsent&&!r?.acceptedConsent)return ax(e,t,`consent`,{sessionId:f.session.id});let _=r?.acceptedConsent?r.acceptedConsent.referenceId:await Su(t,h()),v=async()=>{let r;try{r=await Pm(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 Gb(e,t,a,r?.error??`server_error`,r?.error_description??`authentication context unavailable`)}return km(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:_})):Gb(e,t,a,`access_denied`,`essential acr requirement cannot be met`)};if(o.skipConsent)return v();let y=await Cu(e,o.clientId,f.user.id,_);return!y||!uu(y,s,l)||!c.every(e=>(y.requestedUserInfoClaims??[]).includes(e))?d?Gb(e,t,a,`consent_required`,`End-User consent is required`):ax(e,t,`consent`,{sessionId:f.session.id}):v()}function rx(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 ix(e,t,n){let r=Vi(32,`a-z`,`A-Z`,`0-9`),i=Math.floor(Date.now()/1e3),a=i+(t.codeExpiresIn??600),o={identifier:await Xl(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`,Jb(e,t)),s.toString()}async function ax(e,t,n,r){let i=await ox(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 ox(e,t,n){let r=Date.now(),i=Math.floor(r/1e3)+(t.codeExpiresIn??600),a=rx(e.query);a.set(`exp`,String(i)),a.set(ke,String(r)),a.delete(`sig`),a.delete(Ae),n?.postLoginClearedForSession&&a.set(Ae,n.postLoginClearedForSession),Ne(a);let o=await Qa(Me(a).toString(),e.context.secret);return a.set(`sig`,o),a.toString()}export{ff as $,ds as $t,kp as A,Wl as At,np as B,du as Bt,Ep as C,Ve as Cn,Xu as Ct,Dp as D,Iu as Dt,Sp as E,Lu as Et,yp as F,Il as Ft,pf as G,Ss as Gt,Wf as H,uc as Ht,pp as I,lu as It,hf as J,ms as Jt,bf as K,xs as Kt,mp as L,ru as Lt,wp as M,Pl as Mt,fp as N,Zc as Nt,Ap as O,ku as Ot,bp as P,au as Pt,_f as Q,fs as Qt,gp as R,Rl as Rt,Pp as S,$e as Sn,md as St,Z as T,we as Tn,Hu as Tt,Uf as U,oc as Ut,Kf as V,Hl as Vt,Sf as W,Ts as Wt,yf as X,hs as Xt,vf as Y,gs as Yt,mf as Z,ps as Zt,sm as _,xt as _n,sd as _t,Gm as a,Bi as an,Wd as at,Jp as b,ht as bn,cd as bt,uh as c,wi as cn,Kd as ct,gm as d,xi as dn,Ld as dt,us as en,nf as et,mm as f,Qr as fn,Md as ft,lm as g,pt as gn,id as gt,dm as h,kt as hn,hd as ht,bv as i,Vi as in,Yd as it,Tp as j,kl as jt,Op as k,ml as kt,_m as l,Ci as ln,zd as lt,um as m,Er as mn,_d as mt,Ib as n,Ya as nn,tf as nt,Zh as o,Oi as on,qd as ot,fm as p,qr as pn,Id as pt,xf as q,_s as qt,Cy as r,Ui as rn,Zd as rt,th as s,Ti as sn,Gd as st,Mb as t,Xa as tn,af as tt,hm as u,Si as un,Vd as ut,im as v,Ct as vn,ad as vt,xp as w,Ee as wn,X as wt,Yp as x,vt as xn,ld as xt,Qp as y,mt as yn,od as yt,op as z,cu as zt};
56
+ //# sourceMappingURL=authorize-DXYo-K2n-B-6vqhvc.js.map