@shumai-one/shumai 0.6.2 → 0.6.3

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 (165) hide show
  1. package/bin/chunk-02b5bcmc.js +1 -0
  2. package/bin/{chunk-m0q2cgfg.js → chunk-09mj32d7.js} +1 -1
  3. package/bin/{chunk-b7bnp021.js → chunk-09mpcg9x.js} +2 -2
  4. package/bin/{chunk-257dcd2f.js → chunk-0a298n62.js} +2 -2
  5. package/bin/{chunk-cz13a82m.js → chunk-0rgbxp24.js} +2 -2
  6. package/bin/{chunk-mwktrwtx.js → chunk-19zbh4fr.js} +1 -1
  7. package/bin/{chunk-v05rrxp5.js → chunk-1e1q1hyg.js} +2 -2
  8. package/bin/{chunk-fatmqnp1.js → chunk-1ja2zw4w.js} +1 -1
  9. package/bin/chunk-1tar0x8s.js +7 -0
  10. package/bin/{chunk-1nvd90g2.js → chunk-1y6h4vge.js} +1 -1
  11. package/bin/{chunk-tekwpkjf.js → chunk-20bamhwa.js} +2 -2
  12. package/bin/{chunk-8mqbztj8.js → chunk-20w1w9x7.js} +2 -2
  13. package/bin/{chunk-qwpkcp8d.js → chunk-25npafhz.js} +2 -2
  14. package/bin/{chunk-km4gn6b6.js → chunk-2qgagdb7.js} +1 -1
  15. package/bin/chunk-2t6g3pny.js +3 -0
  16. package/bin/{chunk-ns33grgx.js → chunk-34f64q0q.js} +1 -1
  17. package/bin/{chunk-1wfg56z3.js → chunk-3hgrw1m0.js} +4 -4
  18. package/bin/{chunk-p3f5aevs.js → chunk-3s2ga6mt.js} +1 -1
  19. package/bin/{chunk-hzkjgcre.js → chunk-3vpz5nat.js} +1 -1
  20. package/bin/{chunk-2jj4j8cn.js → chunk-4p31kxjh.js} +2 -2
  21. package/bin/{chunk-9t3p4xp6.js → chunk-4vjgdj0h.js} +1 -1
  22. package/bin/{chunk-96qpjght.js → chunk-50pfmxt1.js} +2 -2
  23. package/bin/{chunk-2cdxm1cp.js → chunk-5ddg5ezb.js} +9 -9
  24. package/bin/chunk-5ngftxjb.js +218 -0
  25. package/bin/{chunk-r1xer8gn.js → chunk-6f3zhq64.js} +3 -3
  26. package/bin/chunk-6nqqe7w9.js +1 -0
  27. package/bin/{chunk-h1n7jqnw.js → chunk-6t525bmg.js} +1 -1
  28. package/bin/{chunk-01052ssf.js → chunk-7546ptwg.js} +11 -11
  29. package/bin/{chunk-82tps5n1.js → chunk-7jz3cmq6.js} +1 -1
  30. package/bin/{chunk-v5cn90cf.js → chunk-7kah3zb5.js} +2 -2
  31. package/bin/{chunk-73yncv54.js → chunk-7mawxsk3.js} +2 -2
  32. package/bin/chunk-8ww98y1m.js +2 -0
  33. package/bin/{chunk-55h9ze53.js → chunk-9405hzv2.js} +2 -2
  34. package/bin/{chunk-cgmebxx6.js → chunk-95b4mwyq.js} +1 -1
  35. package/bin/chunk-9vxmgvc8.js +2 -0
  36. package/bin/{chunk-knj2s8mg.js → chunk-9x42vgeq.js} +5 -5
  37. package/bin/{chunk-7sgrtxbt.js → chunk-a859y4e1.js} +2 -2
  38. package/bin/{chunk-y241cxff.js → chunk-addssm8d.js} +1 -1
  39. package/bin/{chunk-f6avg5qe.js → chunk-ajq9sxg0.js} +33 -33
  40. package/bin/chunk-amp9h878.js +2 -0
  41. package/bin/{chunk-yk12hydf.js → chunk-atdfqdkj.js} +4 -4
  42. package/bin/{chunk-5wapd171.js → chunk-atpt99h4.js} +10 -10
  43. package/bin/chunk-awshe30f.js +1 -0
  44. package/bin/chunk-b3t7gbhm.js +2 -0
  45. package/bin/{chunk-e4f56spj.js → chunk-bbxwyhz3.js} +3 -3
  46. package/bin/{chunk-a411xhmm.js → chunk-bd3v8mp1.js} +4 -4
  47. package/bin/{chunk-167z646e.js → chunk-brgns7hv.js} +1 -1
  48. package/bin/{chunk-576nj64j.js → chunk-c02727j9.js} +2 -2
  49. package/bin/{chunk-8yjsmr7g.js → chunk-c1wvs81k.js} +1 -1
  50. package/bin/chunk-c8frmqsk.js +2 -0
  51. package/bin/{chunk-xc54vhfz.js → chunk-cagzye3j.js} +1 -1
  52. package/bin/{chunk-s9ksftq2.js → chunk-cp96e9pq.js} +1 -1
  53. package/bin/{chunk-q5vkxee3.js → chunk-d55138xx.js} +2 -2
  54. package/bin/{chunk-7v7mypc6.js → chunk-ddmf9gqv.js} +2 -2
  55. package/bin/chunk-djb65frk.js +1 -0
  56. package/bin/{chunk-q83h0hkx.js → chunk-dkhdn92k.js} +2 -2
  57. package/bin/chunk-dx9f5wab.js +1 -0
  58. package/bin/{chunk-f25fe9th.js → chunk-dygj751y.js} +11 -11
  59. package/bin/{chunk-m9adtgzk.js → chunk-e55sgg8t.js} +1 -1
  60. package/bin/{chunk-q8w4mbw4.js → chunk-enax4303.js} +2 -2
  61. package/bin/{chunk-vcrmjtcz.js → chunk-erfkd3z9.js} +2 -2
  62. package/bin/{chunk-8cjet7pp.js → chunk-esj0kwe5.js} +5 -5
  63. package/bin/{chunk-atfz7g7e.js → chunk-etrm28sy.js} +1 -1
  64. package/bin/chunk-ex3174e3.js +2 -0
  65. package/bin/{chunk-9n1w5dw1.js → chunk-ezjxx44x.js} +3 -3
  66. package/bin/{chunk-cf5axr8c.js → chunk-f4xnx4n6.js} +1 -1
  67. package/bin/{chunk-7naa7tpn.js → chunk-f8hgy69t.js} +2 -2
  68. package/bin/chunk-fakph5jp.js +1 -0
  69. package/bin/{chunk-kvhf12b4.js → chunk-femnbfkj.js} +1 -1
  70. package/bin/{chunk-ah8fjb6f.js → chunk-ffjdkdcv.js} +2 -2
  71. package/bin/{chunk-vkzasgxw.js → chunk-gd016e9p.js} +2 -2
  72. package/bin/{chunk-ympbfzz4.js → chunk-gyv3yrhj.js} +1 -1
  73. package/bin/{chunk-jzgbxqdg.js → chunk-h2bphev9.js} +2 -2
  74. package/bin/chunk-h3atwgx2.js +1 -0
  75. package/bin/chunk-h7xny3de.js +2 -0
  76. package/bin/{chunk-m82tkhaa.js → chunk-hg3rkp41.js} +5 -5
  77. package/bin/{chunk-3z85zxkn.js → chunk-hpzk9k55.js} +1 -1
  78. package/bin/{chunk-9zsv6d2f.js → chunk-hsyfrzdd.js} +1 -1
  79. package/bin/chunk-hvyy8vct.js +3 -0
  80. package/bin/{chunk-b5rhvzv9.js → chunk-j2txsbxz.js} +2 -2
  81. package/bin/chunk-j6x53e33.js +1 -0
  82. package/bin/chunk-jacanzp7.js +1 -0
  83. package/bin/{chunk-g6sdezec.js → chunk-jc7dycy6.js} +1 -1
  84. package/bin/{chunk-cwat1jwx.js → chunk-k7vbk8v4.js} +1 -1
  85. package/bin/{chunk-zrszykjf.js → chunk-mn0kt3p6.js} +1 -1
  86. package/bin/chunk-mn71dffh.js +4 -0
  87. package/bin/{chunk-vp3czaeh.js → chunk-npeapp7e.js} +2 -2
  88. package/bin/{chunk-2nhgdqdg.js → chunk-p2vsdnd1.js} +2 -2
  89. package/bin/chunk-pdw77q09.js +2 -0
  90. package/bin/{chunk-zezje74z.js → chunk-pq6kdp83.js} +3 -3
  91. package/bin/chunk-ptcz4ed3.js +2 -0
  92. package/bin/{chunk-z1p13dnc.js → chunk-q1fzgqsv.js} +2 -2
  93. package/bin/chunk-q4ny4hpt.js +2 -0
  94. package/bin/{chunk-mzsw9var.js → chunk-q5x0yywj.js} +2 -2
  95. package/bin/{chunk-g22wmpk1.js → chunk-q8xr1a8j.js} +2 -2
  96. package/bin/chunk-q8ysc5ex.js +1 -0
  97. package/bin/{chunk-1ktk6764.js → chunk-qm50g4n5.js} +4 -4
  98. package/bin/{chunk-q2bew2vc.js → chunk-qvp24w0q.js} +2 -2
  99. package/bin/{chunk-9xhjy897.js → chunk-r6t0j0jx.js} +3 -3
  100. package/bin/chunk-s1j4v33x.js +2 -0
  101. package/bin/{chunk-yq32evnn.js → chunk-s6pk2zyg.js} +5 -5
  102. package/bin/{chunk-hnkcgvcj.js → chunk-s74g9vsk.js} +1 -1
  103. package/bin/{chunk-gxepkvt2.js → chunk-sz19nn1x.js} +1 -1
  104. package/bin/{chunk-hpbn0k9n.js → chunk-sz5zawfw.js} +1 -1
  105. package/bin/chunk-t68y25gf.js +1 -0
  106. package/bin/{chunk-mcw198kg.js → chunk-te484xtb.js} +8 -8
  107. package/bin/{chunk-jt0ykktx.js → chunk-tfrevef9.js} +1 -1
  108. package/bin/chunk-thpw6tcj.js +2 -0
  109. package/bin/{chunk-02fvcrej.js → chunk-v0yevesp.js} +7 -7
  110. package/bin/chunk-vj4gamdn.js +2 -0
  111. package/bin/{chunk-p4s95471.js → chunk-vmwys2ch.js} +1 -1
  112. package/bin/{chunk-e4yscwen.js → chunk-vnmggrd6.js} +7 -7
  113. package/bin/{chunk-hpwv4am3.js → chunk-vv0m0m2f.js} +4 -4
  114. package/bin/{chunk-x03jwaga.js → chunk-w6g84d59.js} +4 -4
  115. package/bin/{chunk-3ckkwdjx.js → chunk-wgvgtttc.js} +3 -3
  116. package/bin/chunk-xy9qpn6b.js +1 -0
  117. package/bin/{chunk-mcj1xpcc.js → chunk-y3haqtr8.js} +2 -2
  118. package/bin/chunk-y5dv67mg.js +2 -0
  119. package/bin/{chunk-4mws03es.js → chunk-yb4mzqrd.js} +2 -2
  120. package/bin/{chunk-x8mjh387.js → chunk-z0de127n.js} +4 -4
  121. package/bin/chunk-z8t6e0ee.js +1 -0
  122. package/bin/chunk-zfg4yy3c.js +2 -0
  123. package/bin/{chunk-hw6czrya.js → chunk-zkvezz89.js} +1 -1
  124. package/bin/chunk-zrrnvdxq.js +3 -0
  125. package/bin/{chunk-srxp5jav.js → chunk-zx1c4vm5.js} +30 -30
  126. package/bin/chunk-zzqse5qc.js +2 -0
  127. package/bin/shumai-app.html +1 -1
  128. package/bin/shumai-app.js +328 -328
  129. package/package.json +7 -7
  130. package/bin/chunk-0bj887zm.js +0 -2
  131. package/bin/chunk-26qn7fek.js +0 -2
  132. package/bin/chunk-2ne2b54t.js +0 -2
  133. package/bin/chunk-2vbeqczj.js +0 -1
  134. package/bin/chunk-37p6bcx2.js +0 -1
  135. package/bin/chunk-3knfx6dm.js +0 -1
  136. package/bin/chunk-54tbfvya.js +0 -2
  137. package/bin/chunk-56kh5fxc.js +0 -1
  138. package/bin/chunk-6cnqjngz.js +0 -1
  139. package/bin/chunk-7g46e1wy.js +0 -3
  140. package/bin/chunk-84x8p7v5.js +0 -1
  141. package/bin/chunk-8fyg9dy4.js +0 -2
  142. package/bin/chunk-8gtfgkrn.js +0 -2
  143. package/bin/chunk-8xb6yz11.js +0 -2
  144. package/bin/chunk-91rb0jpb.js +0 -2
  145. package/bin/chunk-9f1xk1nt.js +0 -1
  146. package/bin/chunk-9mk9cvbk.js +0 -1
  147. package/bin/chunk-9nw5w8vh.js +0 -1
  148. package/bin/chunk-dk42gf7v.js +0 -2
  149. package/bin/chunk-eb7mzbfm.js +0 -1
  150. package/bin/chunk-er14d498.js +0 -3
  151. package/bin/chunk-fvx9k1dc.js +0 -2
  152. package/bin/chunk-gtf19jc1.js +0 -2
  153. package/bin/chunk-hfm82066.js +0 -2
  154. package/bin/chunk-kj6h5j5a.js +0 -4
  155. package/bin/chunk-ny1kbmxt.js +0 -2
  156. package/bin/chunk-p3j6ydk1.js +0 -1
  157. package/bin/chunk-pk406dgy.js +0 -2
  158. package/bin/chunk-s1e4qy3q.js +0 -14
  159. package/bin/chunk-swtwaaqe.js +0 -1
  160. package/bin/chunk-tagdrg7p.js +0 -1
  161. package/bin/chunk-twtxnzbv.js +0 -2
  162. package/bin/chunk-v5mcjwxy.js +0 -2
  163. package/bin/chunk-x342vzdx.js +0 -2
  164. package/bin/chunk-xvkwbczx.js +0 -3
  165. package/bin/chunk-zarz3sqn.js +0 -211
@@ -1,5 +1,5 @@
1
1
  // @bun
2
- import{ed,yf,qa,ce,te,U,Rm,go,Jt,Xi,El,vi,ea,Ef,Ic,Ee,xl,us,Cl,To,ko,td,ta,rd,Tc,xf,Vs,Cf,Ks,rA,Sf,nA,oA,nd,If,Mr,vr,od,$a,kc,pn,mn,ds}from"./chunk-yk12hydf.js";import{dn,yi,Ur,zr,Al,_l,yc,yl,$u,pr,Hu,Hr,Qu,bs,Gu,vl,bl,Qo,gf,vc,Sn,so,Xr,Af}from"./chunk-gxepkvt2.js";import{_f,Vu}from"./chunk-8gtfgkrn.js";import{xc}from"./chunk-3ckkwdjx.js";import{Pr,sA,kf,e,In,Vo,dA,fA,_,E,N,W,Sl,ue,A,wi,l,Lm,oe,D,k,T,v,na,ye,Cs}from"./chunk-2cdxm1cp.js";import{Ye}from"./chunk-2jj4j8cn.js";var ai={};Ye(ai,{accountSchema:()=>xa,coreSchema:()=>Ze,getAuthTables:()=>go,rateLimitSchema:()=>Na,sessionSchema:()=>zn,userSchema:()=>Nn,verificationSchema:()=>ja});function Pa(t){return Object.fromEntries(Object.entries(t).map(([r,n])=>[r,{code:r,message:n,toString:()=>r}]))}var Ae=Pa({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"});var Ze=l({id:e(),createdAt:ue().default(()=>new Date),updatedAt:ue().default(()=>new Date)});var xa=Ze.extend({providerId:e(),accountId:e(),userId:_f(),accessToken:e().nullish(),refreshToken:e().nullish(),idToken:e().nullish(),accessTokenExpiresAt:ue().nullish(),refreshTokenExpiresAt:ue().nullish(),scope:e().nullish(),password:e().nullish()});var Na=l({key:e(),count:_(),lastRequest:_()});var zn=Ze.extend({userId:_f(),expiresAt:ue(),token:e(),ipAddress:e().nullish(),userAgent:e().nullish()});var Nn=Ze.extend({email:e().transform((t)=>t.toLowerCase()),emailVerified:E().default(!1),name:e(),image:e().nullish()});var ja=Ze.extend({value:e(),expiresAt:ue(),identifier:e()});function Ba(t){return ym(t).schema}function ym(t){let{indexesByTable:r,tables:n}=Rm(t),o=new Map,i={};for(let s in n){let a=n[s],c=a.fields,d={};if(Object.entries(c).forEach(([u,f])=>{let p=f.references,h=p?n[p.model]:void 0,m=p&&h?{...f,references:{...p,model:h.modelName}}:f;if(d[f.fieldName||u]=m,p)o.set(m,{modelKey:p.model,fieldKey:p.field})}),i[a.modelName]){if(i[a.modelName].fields={...i[a.modelName].fields,...d},a.disableMigrations)i[a.modelName].disableMigrations=!0;continue}i[a.modelName]={fields:d,order:a.order||1/0,disableMigrations:a.disableMigrations}}for(let[s,a]of r)if(i[s])i[s].indexes=a;return{schema:i,tables:n,referenceKeys:o}}function ci(t){if(t==="-"||t==="^"||t==="$"||t==="+"||t==="."||t==="("||t===")"||t==="|"||t==="["||t==="]"||t==="{"||t==="}"||t==="*"||t==="?"||t==="\\")return`\\${t}`;else return t}function Zh(t){let r="";for(let n=0;n<t.length;n++)r+=ci(t[n]);return r}function Ma(t,r=!0){if(Array.isArray(t))return`(?:${t.map((u)=>`^${Ma(u,r)}$`).join("|")})`;let n="",o="",i=".";if(r===!0)n="/",o="[/\\\\]",i="[^/\\\\]";else if(r)if(n=r,o=Zh(n),o.length>1)o=`(?:${o})`,i=`((?!${o}).)`;else i=`[^${o}]`;let s=r?`${o}+?`:"",a=r?`${o}*?`:"",c=r?t.split(n):[t],d="";for(let u=0;u<c.length;u++){let f=c[u],p=c[u+1],h="";if(!f&&u>0)continue;if(r)if(u===c.length-1)h=a;else if(p!=="**")h=s;else h="";if(r&&f==="**"){if(h)d+=u===0?"":h,d+=`(?:${i}*?${h})*?`;continue}for(let m=0;m<f.length;m++){let w=f[m];if(w==="\\"){if(m<f.length-1)d+=ci(f[m+1]),m++}else if(w==="?")d+=i;else if(w==="*")d+=`${i}*?`;else d+=ci(w)}d+=h}return d}function Yh(t,r){if(typeof r!=="string")throw TypeError(`Sample must be a string, but ${typeof r} given`);return t.test(r)}function jt(t,r){if(typeof t!=="string"&&!Array.isArray(t))throw TypeError(`The first argument must be a single pattern string or an array of patterns, but ${typeof t} given`);if(typeof r==="string"||typeof r==="boolean")r={separator:r};if(arguments.length===2&&!(typeof r>"u"||typeof r==="object"&&r!==null&&!Array.isArray(r)))throw TypeError(`The second argument must be an options object or a string/boolean separator, but ${typeof r} given`);if(r=r||{},r.separator==="\\")throw Error("\\ is not a valid separator because it is used for escaping. Try setting the separator to `true` instead");let n=Ma(t,r.separator),o=new RegExp(`^${n}$`,r.flags),i=Yh.bind(null,o);return i.options=r,i.pattern=t,i.regexp=o,i}var Xh=47;function em(t){let r=t.replace(/:\d+$/,"").replace(/^\[|\]$/g,"").toLowerCase();return r==="localhost"||r.endsWith(".localhost")||r==="::1"||r.startsWith("127.")}function Ha(t){let r=t.length;while(r>0&&t.charCodeAt(r-1)===Xh)r--;return r===t.length?t:t.slice(0,r)}function tm(t){try{return(Ha(new URL(t).pathname)||"/")!=="/"}catch{throw new te(`Invalid base URL: ${t}. Please provide a valid base URL.`)}}function rm(t){try{let r=new URL(t);if(r.protocol!=="http:"&&r.protocol!=="https:")throw new te(`Invalid base URL: ${t}. URL must include 'http://' or 'https://'`)}catch(r){if(r instanceof te)throw r;throw new te(`Invalid base URL: ${t}. Please provide a valid base URL.`,{cause:r})}}function dt(t,r="/api/auth"){if(rm(t),tm(t))return t;let n=Ha(t);if(!r||r==="/")return n;return r=r.startsWith("/")?r:`/${r}`,`${n}${r}`}function Dr(t,r){if(!t||t.trim()==="")return!1;if(r==="proto")return t==="http"||t==="https";if(r==="host"){if([/\.\./,/\0/,/[\s]/,/^[.]/,/[<>'"]/,/javascript:/i,/file:/i,/data:/i].some((n)=>n.test(t)))return!1;return/^[a-zA-Z0-9]([a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?(\.[a-zA-Z0-9]([a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?)*(:[0-9]{1,5})?$/.test(t)||/^(\d{1,3}\.){3}\d{1,3}(:[0-9]{1,5})?$/.test(t)||/^\[[0-9a-fA-F:]+\](:[0-9]{1,5})?$/.test(t)||/^localhost(:[0-9]{1,5})?$/i.test(t)}return!1}function Hs(t,r,n,o,i){if(t)return dt(t,r);if(o!==!1){let c=Jt.BETTER_AUTH_URL||Jt.NEXT_PUBLIC_BETTER_AUTH_URL||Jt.PUBLIC_BETTER_AUTH_URL||Jt.NUXT_PUBLIC_BETTER_AUTH_URL||Jt.NUXT_PUBLIC_AUTH_URL||(Jt.BASE_URL!=="/"?Jt.BASE_URL:void 0);if(c)return dt(c,r)}let s=n?.headers.get("x-forwarded-host"),a=n?.headers.get("x-forwarded-proto");if(s&&a&&i){if(Dr(a,"proto")&&Dr(s,"host"))try{return dt(`${a}://${s}`,r)}catch(c){}}if(n){let c=Ai(n.url);if(!c)throw new te("Could not get origin from request. Please provide a valid base URL.");return dt(c,r)}if(typeof window<"u"&&window.location)return dt(window.location.origin,r)}function Ai(t){try{let r=new URL(t);return r.origin==="null"?null:r.origin}catch{return null}}function Va(t){try{return new URL(t).protocol}catch{return null}}function Fa(t){try{return new URL(t).host}catch{return null}}function ls(t){return typeof t==="object"&&t!==null&&"allowedHosts"in t&&Array.isArray(t.allowedHosts)}function je(t){if(t instanceof Request)return!0;if(typeof t!=="object"||t===null||Object.prototype.toString.call(t)!=="[object Request]")return!1;let r=t;return typeof r.url==="string"&&typeof r.headers==="object"&&r.headers!==null&&typeof r.headers.get==="function"}function Ka(t,r){let n=je(t)?t.headers:t;if(r){let i=n.get("x-forwarded-host");if(i&&Dr(i,"host"))return i}let o=n.get("host");if(o&&Dr(o,"host"))return o;if(je(t))try{return new URL(t.url).host}catch{return null}return null}function nm(t,r,n){if(r==="http"||r==="https")return r;let o=je(t)?t.headers:t;if(n){let s=o.get("x-forwarded-proto");if(s&&Dr(s,"proto"))return s}if(je(t))try{let s=new URL(t.url);if(s.protocol==="http:"||s.protocol==="https:")return s.protocol.slice(0,-1)}catch{}let i=Ka(t,n);if(i&&em(i))return"http";return"https"}var om=(t,r)=>{if(!t||!r)return!1;let n=t.replace(/^https?:\/\//,"").split("/")[0].toLowerCase(),o=r.replace(/^https?:\/\//,"").split("/")[0].toLowerCase();if(o.includes("*")||o.includes("?"))return jt(o)(n);return n.toLowerCase()===o.toLowerCase()};function im(t,r,n,o){let i=Ka(r,o);if(!i){if(t.fallback)return dt(t.fallback,n);throw new te("Could not determine host from request headers. Please provide a fallback URL in your baseURL config.")}if(t.allowedHosts.some((s)=>om(i,s)))return dt(`${nm(r,t.protocol,o)}://${i}`,n);if(t.fallback)return dt(t.fallback,n);throw new te(`Host "${i}" is not in the allowed hosts list. Allowed hosts: ${t.allowedHosts.join(", ")}. Add this host to your allowedHosts config or provide a fallback URL.`)}function Wa(t,r,n,o,i){if(ls(t)){if(n)return im(t,n,r,i);if(t.fallback)return dt(t.fallback,r);return Hs(void 0,r,void 0,o,i)}let s=je(n)?n:void 0;if(typeof t==="string")return Hs(t,r,s,o,i);return Hs(void 0,r,s,o,i)}var Ga=/[\u0000-\u001f\u007f-\u009f]/,Ja="https://better-auth.invalid",sm=/%2[fF]|%5[cC]/,am=(t)=>{let r=t;try{r=decodeURIComponent(t)}catch{}let n=[];for(let o of r.split("/"))if(o==="..")n.pop();else if(o!=="."&&o!=="")n.push(o);return n.length>0?`/${n.join("/")}`:""},Qa=(t)=>{if(Ga.test(t))return null;let r=t.indexOf(":");if(r<=0)return null;let n=t.slice(0,r).toLowerCase(),o=t.slice(r+1),i="";if(o.startsWith("//")){o=o.slice(2);let c=o.search(/[/?#]/);if(c===-1)i=o,o="";else i=o.slice(0,c),o=o.slice(c)}let s=o.search(/[?#]/),a=am(s===-1?o:o.slice(0,s));return{scheme:n,authority:i.toLowerCase(),path:a}},cm=(t)=>{if(!t.startsWith("/")||t.startsWith("//")||t.includes("\\")||Ga.test(t))return!1;let r=t.search(/[?#]/),n=r===-1?t:t.slice(0,r);if(sm.test(n))return!1;try{return new URL(t,Ja).origin===Ja}catch{return!1}},lf=(t,r,n)=>{if(t.startsWith("/"))return n?.allowRelativePaths===!0&&cm(t);if(r.includes("*")||r.includes("?")){if(r.includes("://"))return jt(r)(Ai(t)||t);let a=Fa(t);if(!a)return!1;return jt(r)(a)}let o=Va(t);if(o==="http:"||o==="https:"||!o)return r===Ai(t);let i=Qa(t),s=Qa(r);if(!i||!s||i.scheme!==s.scheme)return!1;if(s.authority&&i.authority!==s.authority)return!1;if(!s.path)return!0;return i.path===s.path||i.path.startsWith(`${s.path}/`)};function cf(t){return!!t.database||!!t.secondaryStorage}function dm(t){return!!t.database}function qn(t){return dm(t)}function pc(t){return!!t&&(typeof t==="object"||typeof t==="function")&&typeof t.then==="function"}class di{oHash;iHash;blockLen;outputLen;canXOF=!1;finished=!1;destroyed=!1;constructor(t,r){if(rd(t),ta(r,void 0,"key"),this.iHash=t.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,o=new Uint8Array(n);o.set(r.length>n?t.create().update(r).digest():r);for(let i=0;i<o.length;i++)o[i]^=54;this.iHash.update(o),this.oHash=t.create();for(let i=0;i<o.length;i++)o[i]^=106;this.oHash.update(o),Vs(o)}update(t){return Tc(this),this.iHash.update(t),this}digestInto(t){Tc(this),xf(t,this),this.finished=!0;let r=t.subarray(0,this.outputLen);this.iHash.digestInto(r),this.oHash.update(r),this.oHash.digestInto(r),this.destroy()}digest(){let t=new Uint8Array(this.oHash.outputLen);return this.digestInto(t),t}_cloneInto(t){t||=Object.create(Object.getPrototypeOf(this),{});let{oHash:r,iHash:n,finished:o,destroyed:i,blockLen:s,outputLen:a,canXOF:c}=this;return t=t,t.finished=o,t.destroyed=i,t.blockLen=s,t.outputLen=a,t.canXOF=c,t.oHash=r._cloneInto(t.oHash),t.iHash=n._cloneInto(t.iHash),t}clone(){return this._cloneInto()}destroy(){this.destroyed=!0,this.oHash.destroy(),this.iHash.destroy()}}var ui=(()=>{let t=(r,n,o)=>new di(r,n).update(o).digest();return t.create=(r,n)=>new di(r,n),t})();var Lr=Uint8Array.of(0),um=Uint8Array.of();function lm(t,r,n,o=32,i){rd(t),td(o,"length"),ta(r,void 0,"prk");let s=t.outputLen;if(r.length<s)throw Error('"prk" must be at least HashLen octets');if(o>255*s)throw Error("Length must be <= 255*HashLen");let a=Math.ceil(o/s);if(n===void 0)n=um;else ta(n,void 0,"info");if(!a){if(i)Vs(r);return new Uint8Array}let c=i&&a===1?r:new Uint8Array(a*s),{iHash:d,oHash:u}=ui.create(t,r),f=i?r:new Uint8Array(s),p=a>1?i?.iHash||t.create():void 0;for(let m=0;m<a-1;m++){Lr[0]=m+1;let w=d._cloneInto(p);if(m)w.update(f);w.update(n).update(Lr).digestInto(f),u._cloneInto(p).update(f).digestInto(f),c.set(f,s*m)}if(Lr[0]=a,a>1)d.update(f);if(d.update(n).update(Lr).digestInto(f),u.update(f).digestInto(f),c.set(f,s*(a-1)),d.destroy(),u.destroy(),p?.destroy(),f!==c)Vs(f);if(Vs(Lr),o===c.length)return c;let h=c.slice(0,o);return Vs(c),h}var jn=(t,r,n,o,i)=>{if(rd(t),n===void 0)n=new Uint8Array(t.outputLen);let s=ui.create(t,n).update(r);return lm(t,s.digest(),o,i,s)};var fm=(t)=>t/4294967296|0,pm=(t)=>t>>>0;function Za(t,r,n,o){let i=fm(n),s=pm(n);t.setUint32(r,o?s:i,o),t.setUint32(r+4,o?i:s,o)}function Ya(t,r,n){return t&r^~t&n}function Xa(t,r,n){return t&r^t&n^r&n}class li{blockLen;outputLen;canXOF=!1;padOffset;isLE;buffer;view;finished=!1;length=0;pos=0;destroyed=!1;constructor(t,r,n,o){this.blockLen=t,this.outputLen=r,this.padOffset=n,this.isLE=o,this.buffer=new Uint8Array(t),this.view=Cf(this.buffer)}update(t){Tc(this),ta(t);let{view:r,buffer:n,blockLen:o}=this,i=t.length,s=!1;for(let a=0;a<i;){let c=Math.min(o-this.pos,i-a);if(c===o){let d=Cf(t);for(;o<=i-a;a+=o)this.process(d,a);s=!0;continue}if(n.set(a===0&&c===i?t:t.subarray(a,a+c),this.pos),this.pos+=c,a+=c,this.pos===o)this.process(r,0),this.pos=0,s=!0}if(this.length+=t.length,s)this.roundClean();return this}digestInto(t){Tc(this),xf(t,this),this.finished=!0;let{buffer:r,view:n,blockLen:o,isLE:i}=this,{pos:s}=this;if(r[s++]=128,r.fill(0,s),this.padOffset>o-s)this.process(n,0),r.fill(0);Za(n,o-8,this.length*8,i),this.process(n,0),this.roundClean();let a=t===r?n:Cf(t),c=this.outputLen,d=c/4,u=this.get();if(c%4||d>u.length)throw Error("invalid outputLen");for(let f=0;f<d;f++)a.setUint32(4*f,u[f],i)}digest(){let{buffer:t,outputLen:r}=this;this.digestInto(t);let n=t.slice(0,r);return this.destroy(),n}_cloneIntoMeta(t){let{buffer:r,length:n,finished:o,destroyed:i,pos:s}=this;if(t.destroyed=i,t.finished=o,t.length=n,t.pos=s,s)t.buffer.set(r);return t}clone(){return this._cloneInto()}}var ec=Uint32Array.from([1779033703,3144134277,1013904242,2773480762,1359893119,2600822924,528734635,1541459225]);var hm=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]),yt=new Uint32Array(64);class tc extends li{A=0;B=0;C=0;D=0;E=0;F=0;G=0;H=0;constructor(t,r){super(64,t,8,!1);this.A=r[0]|0,this.B=r[1]|0,this.C=r[2]|0,this.D=r[3]|0,this.E=r[4]|0,this.F=r[5]|0,this.G=r[6]|0,this.H=r[7]|0}get(){let{A:t,B:r,C:n,D:o,E:i,F:s,G:a,H:c}=this;return[t,r,n,o,i,s,a,c]}set(t,r,n,o,i,s,a,c){this.A=t|0,this.B=r|0,this.C=n|0,this.D=o|0,this.E=i|0,this.F=s|0,this.G=a|0,this.H=c|0}_cloneInto(t){return(t||=new this.constructor).set(...this.get()),this._cloneIntoMeta(t)}process(t,r){for(let f=0;f<16;f++,r+=4)yt[f]=t.getUint32(r,!1);for(let f=16;f<64;f++){let p=yt[f-15],h=yt[f-2],m=Ks(p,7)^Ks(p,18)^p>>>3,w=Ks(h,17)^Ks(h,19)^h>>>10;yt[f]=w+yt[f-7]+m+yt[f-16]|0}let{A:n,B:o,C:i,D:s,E:a,F:c,G:d,H:u}=this;for(let f=0;f<64;f++){let p=Ks(a,6)^Ks(a,11)^Ks(a,25),h=u+p+Ya(a,c,d)+hm[f]+yt[f]|0,w=(Ks(n,2)^Ks(n,13)^Ks(n,22))+Xa(n,o,i)|0;u=d,d=c,c=a,a=s+h|0,s=i,i=o,o=n,n=h+w|0}n=n+this.A|0,o=o+this.B|0,i=i+this.C|0,s=s+this.D|0,a=a+this.E|0,c=c+this.F|0,d=d+this.G|0,u=u+this.H|0,this.set(n,o,i,s,a,c,d,u)}roundClean(){Vs(yt)}destroy(){this.destroyed=!0,this.set(0,0,0,0,0,0,0,0),Vs(this.buffer)}}class rc extends tc{constructor(){super(32,ec)}}var Bn=nA(()=>new rc,oA(1));async function $n(t,r,n=3600){return await new bs(t).setProtectedHeader({alg:"HS256"}).setIssuedAt().setExpirationTime(Math.floor(Date.now()/1000)+n).sign(new TextEncoder().encode(r))}async function sc(t,r){try{return(await Hr(t,new TextEncoder().encode(r))).payload}catch{return null}}var mm=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]),gm=()=>Date.now()/1000|0,ac="dir",cc="A256CBC-HS512";function xr(t,r){return jn(Bn,new TextEncoder().encode(t),new TextEncoder().encode(r),mm,64)}function _m(t){if(typeof t==="string")return t;let r=t.keys.get(t.currentVersion);if(!r)throw Error(`Secret version ${t.currentVersion} not found in keys`);return r}function nc(t){if(typeof t==="string")return[{version:0,value:t}];let r=[];for(let[n,o]of t.keys)r.push({version:n,value:o});if(t.legacySecret&&!r.some((n)=>n.value===t.legacySecret))r.push({version:-1,value:t.legacySecret});return r}async function Mn(t,r,n,o=3600){let i=xr(_m(r),n),s=await bl({kty:"oct",k:pr(i)},"sha256");return await new Gu(t).setProtectedHeader({alg:ac,enc:cc,kid:s}).setIssuedAt().setExpirationTime(gm()+o).setJti(crypto.randomUUID()).encrypt(i)}var oc={clockTolerance:15,keyManagementAlgorithms:[ac],contentEncryptionAlgorithms:[cc,"A256GCM"]};async function Hn(t,r,n){if(!t)return null;let o=!1;try{o=so(t).kid!==void 0}catch{return null}try{let i=nc(r),{payload:s}=await Qu(t,async(a)=>{let c=a.kid;if(c!==void 0){for(let d of i){let u=xr(d.value,n);if(c===await bl({kty:"oct",k:pr(u)},"sha256"))return u}throw Error("no matching decryption secret")}if(i.length===1)return xr(i[0].value,n);return xr(i[0].value,n)},oc);return s}catch{if(o)return null;let i=nc(r);if(i.length<=1)return null;for(let s=1;s<i.length;s++)try{let a=i[s],{payload:c}=await Qu(t,xr(a.value,n),oc);return c}catch{continue}return null}}function cr(t,r){if(!t||!r)return t;let n=Object.entries(r).filter(([,{returned:o}])=>o===!1).map(([o])=>o);return Object.entries(structuredClone(t)).filter(([o])=>!n.includes(o)).reduce((o,[i,s])=>({...o,[i]:s}),{})}var fi=new WeakMap;function Xe(t,r,n){let o=`${r}:${n}`;if(!fi.has(t))fi.set(t,new Map);let i=fi.get(t);if(i.has(o))return i.get(o);let s=n==="output"?go(t)[r]?.fields??{}:{},a=r==="user"||r==="session"||r==="account"?t[r]?.additionalFields:void 0,c={...s,...a??{}};for(let d of t.plugins||[])if(d.schema&&d.schema[r])c={...c,...d.schema[r].fields};return i.set(o,c),c}function se(t,r){return cr(r,Xe(t,"user","output"))}function Nr(t,r){let n=Xe(t,"user","output"),o={};for(let i in n){let s=n[i];if(s.returned===!1)continue;if(i in r&&r[i]!==void 0)o[i]=r[i];else if(s.defaultValue!==void 0)o[i]=typeof s.defaultValue==="function"?s.defaultValue():s.defaultValue;else if(!s.required)o[i]=null}if("id"in r)o.id=r.id;return o}function we(t,r){return cr(r,Xe(t,"session","output"))}function Vn(t,r){let{accessToken:n,refreshToken:o,idToken:i,accessTokenExpiresAt:s,refreshTokenExpiresAt:a,password:c,...d}=cr(r,Xe(t,"account","output"));return d}function Bt(t,r){let n=r.action||"create",o=r.fields,i=Object.create(null);for(let s in o){if(s in t){if(o[s].input===!1){if(o[s].defaultValue!==void 0){if(n!=="update"){i[s]=o[s].defaultValue;continue}}if(t[s])throw U.from("BAD_REQUEST",{...Ae.FIELD_NOT_ALLOWED,message:`${s} is not allowed to be set`});continue}if(o[s].validator?.input&&t[s]!==void 0){let a=o[s].validator.input["~standard"].validate(t[s]);if(a instanceof Promise)throw U.from("INTERNAL_SERVER_ERROR",Ae.ASYNC_VALIDATION_NOT_SUPPORTED);if("issues"in a&&a.issues)throw U.from("BAD_REQUEST",{...Ae.VALIDATION_ERROR,message:a.issues[0]?.message||"Validation Error"});i[s]=a.value;continue}if(o[s].transform?.input&&t[s]!==void 0){i[s]=o[s].transform?.input(t[s]);continue}i[s]=t[s];continue}if(o[s].defaultValue!==void 0&&n==="create"){if(typeof o[s].defaultValue==="function"){i[s]=o[s].defaultValue();continue}i[s]=o[s].defaultValue;continue}if(o[s].required&&n==="create")throw U.from("BAD_REQUEST",{...Ae.MISSING_FIELD,message:`${s} is required`})}return i}function dr(t,r={},n){return Bt(r,{fields:Xe(t,"user","input"),action:n})}function ur(t,r={},n){let o=Xe(t,"user","input"),i=Object.create(null);for(let s of Object.keys(r)){if(o[s]?.input===!1)continue;i[s]=r[s]}return Bt(i,{fields:o,action:n})}function dc(t,r){let n=Xe(t,"user","input");return Bt(r||{},{fields:n})}function uc(t,r){return Bt(r,{fields:Xe(t,"account","input")})}function Fn(t,r,n){return Bt(r,{fields:Xe(t,"session","input"),action:n})}function Kn(t){let r=Xe(t,"session","input"),n={};for(let o in r)if(r[o].defaultValue!==void 0)n[o]=typeof r[o].defaultValue==="function"?r[o].defaultValue():r[o].defaultValue;return n}function mc(t,r){if(!r)return t;for(let n in r){let o=r[n]?.modelName;if(o)t[n].modelName=o;for(let i in t[n].fields){let s=r[n]?.fields?.[i];if(!s)continue;t[n].fields[i].fieldName=s}}return t}var ut=(t,r="ms")=>new Date(Date.now()+(r==="sec"?t*1000:t));var Am=/^(\+|\-)? ?(\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 km(t){let r=Am.exec(t);if(!r||r[4]&&r[1])throw TypeError(`Invalid time string format: "${t}". Use formats like "7d", "30m", "1 hour", etc.`);let n=parseFloat(r[2]),o=r[3].toLowerCase(),i;switch(o){case"years":case"year":case"yrs":case"yr":case"y":i=n*31557600000;break;case"months":case"month":case"mo":i=n*2592000000;break;case"weeks":case"week":case"w":i=n*604800000;break;case"days":case"day":case"d":i=n*86400000;break;case"hours":case"hour":case"hrs":case"hr":case"h":i=n*3600000;break;case"minutes":case"minute":case"mins":case"min":case"m":i=n*60000;break;case"seconds":case"second":case"secs":case"sec":case"s":i=n*1000;break;default:throw TypeError(`Unknown time unit: "${o}"`)}if(r[1]==="-"||r[4]==="ago")return-i;return i}function Wn(t){return Math.round(km(t)/1000)}var Sm=oe({session:zn.loose(),user:Nn.loose(),updatedAt:_(),version:e().optional()}),Tm=l({session:k(e(),W()),expiresAt:_(),signature:e()});function hc(t){let r=Mr(t);if(r===null)return null;let n=Sm.safeParse(r);if(n.success)return n.data;return Ee.warn("Cookie cache payload failed schema validation",{issues:n.error.issues.map(({code:o,path:i})=>({code:o,path:i}))}),null}function lc(t){let r=Tm.safeParse(t);return r.success?r.data:null}function wc(t){if(t.indexOf("%")===-1)return t;try{return decodeURIComponent(t)}catch{return t}}var Ec="__Secure-";function Jn(t){if(!t)return[];let r=[],n=0,o=0;while(o<t.length){if(t[o]===","){let s=o+1;while(s<t.length&&t[s]===" ")s++;while(s<t.length&&t[s]!=="="&&t[s]!==";"&&t[s]!==",")s++;if(s<t.length&&t[s]==="="){let a=t.slice(n,o).trim();if(a)r.push(a);n=o+1;while(n<t.length&&t[n]===" ")n++;o=n;continue}}o++}let i=t.slice(n).trim();if(i)r.push(i);return r}function Gn(t){let r=new Map;return Jn(t).forEach((n)=>{let[o,...i]=n.split(";").map((u)=>u.trim()),[s,...a]=(o||"").split("="),c=Sc(a.join("="));if(!s)return;let d={value:wc(c)};i.forEach((u)=>{let[f,...p]=u.split("="),h=p.join("="),m=f.trim().toLowerCase();switch(m){case"max-age":d["max-age"]=h?parseInt(h.trim(),10):void 0;break;case"expires":d.expires=h?new Date(h.trim()):void 0;break;case"domain":d.domain=h?h.trim():void 0;break;case"path":d.path=h?h.trim():void 0;break;case"secure":d.secure=!0;break;case"httponly":d.httponly=!0;break;case"samesite":d.samesite=h?h.trim().toLowerCase():void 0;break;case"partitioned":d.partitioned=!0;break;default:d[m]=h?h.trim():!0;break}}),r.set(s,d)}),r}var bc=/^[\x21\x23-\x27\x2A\x2B\x2D\x2E\x30-\x39\x41-\x5A\x5E\x5F\x60\x61-\x7A\x7C\x7E]+$/,Im=/^[\x20\x21\x23-\x3A\x3C-\x5B\x5D-\x7E]*$/;function Sc(t){if(t.length<2||!t.startsWith('"')||!t.endsWith('"'))return t;return t.slice(1,-1)}function fc(t){let r=0,n=t.length;while(r<n){let o=t.charCodeAt(r);if(o!==32&&o!==9)break;r++}while(n>r){let o=t.charCodeAt(n-1);if(o!==32&&o!==9)break;n--}return r===0&&n===t.length?t:t.slice(r,n)}function Zn(t){let r=new Map;if(t.length<2)return r;for(let n of t.split(";")){let o=n.indexOf("=");if(o===-1)continue;let i=fc(n.slice(0,o)),s=Sc(fc(n.slice(o+1)));if(bc.test(i)&&Im.test(s))r.set(i,wc(s))}return r}function De(){let t=typeof globalThis<"u"&&globalThis.crypto;if(t&&typeof t.subtle==="object"&&t.subtle!=null)return t.subtle;throw Error("crypto.subtle must be defined")}var pi={name:"HMAC",hash:"SHA-256"},hi=async(t)=>{let r=typeof t==="string"?new TextEncoder().encode(t):t;return await De().importKey("raw",r,pi,!1,["sign","verify"])},Rc=async(t,r,n)=>{try{let o=atob(t),i=new Uint8Array(o.length);for(let s=0,a=o.length;s<a;s++)i[s]=o.charCodeAt(s);return await De().verify(pi,n,i,new TextEncoder().encode(r))}catch{return!1}},Um=async(t,r)=>{let n=await hi(r),o=await De().sign(pi.name,n,new TextEncoder().encode(t));return btoa(String.fromCharCode(...new Uint8Array(o)))},Uc=async(t,r)=>{let n=await Um(t,r);return t=`${t}.${n}`,t=encodeURIComponent(t),t};var Cm=/^application\/([a-z0-9.+-]*\+)?json/i;async function Cc(t,r){let n=t.headers.get("content-type")||"",o=n.toLowerCase();if(!t.body)return;if(r&&r.length>0){if(!r.some((i)=>{let s=o.split(";")[0].trim(),a=i.toLowerCase().trim();return s===a||s.includes(a)})){if(!o)throw new ce(415,{message:`Content-Type is required. Allowed types: ${r.join(", ")}`,code:"UNSUPPORTED_MEDIA_TYPE"});throw new ce(415,{message:`Content-Type "${n}" is not allowed. Allowed types: ${r.join(", ")}`,code:"UNSUPPORTED_MEDIA_TYPE"})}}if(Cm.test(o))try{return await t.json()}catch(i){if(i instanceof SyntaxError)throw new ce(400,{message:"Invalid JSON in request body",code:"BAD_REQUEST"});throw i}if(o.includes("application/x-www-form-urlencoded")){let i=await t.formData(),s={};return i.forEach((a,c)=>{s[c]=a.toString()}),s}if(o.includes("multipart/form-data")){let i=await t.formData(),s={};return i.forEach((a,c)=>{s[c]=a}),s}if(o.includes("text/plain"))return await t.text();if(o.includes("application/octet-stream"))return await t.arrayBuffer();if(o.includes("application/pdf")||o.includes("image/")||o.includes("video/"))return await t.blob();if(o.includes("application/stream")||t.body instanceof ReadableStream)return t.body;return await t.text()}function lt(t){return t instanceof ce||t?.name==="APIError"}function Oc(t){try{return t.includes("%")?decodeURIComponent(t):t}catch{return t}}async function Dc(t){try{return{data:await t,error:null}}catch(r){return{data:null,error:r}}}function Yn(t){return t instanceof Request||Object.prototype.toString.call(t)==="[object Request]"}var Om={secure:"__Secure-",host:"__Host-"},qr=(t,r)=>{if(!r)return t;if(r!=="secure"&&r!=="host")return;return Om[r]+t};function mi(t){if(typeof t!=="string")throw TypeError("argument str must be a string");let r=new Map,n=0;while(n<t.length){let o=t.indexOf("=",n);if(o===-1)break;let i=t.indexOf(";",n);if(i===-1)i=t.length;else if(i<o){n=t.lastIndexOf(";",o-1)+1;continue}let s=t.slice(n,o).trim();if(!r.has(s)){let a=t.slice(o+1,i).trim();if(a.codePointAt(0)===34)a=a.slice(1,-1);r.set(s,Oc(a))}n=i+1}return r}function Lc(t,r,n={}){let o=qr(t,n.prefix)??t,i={...n},s=o.toLowerCase();if(s.startsWith("__host-"))i.secure=!0,i.path="/",i.domain=void 0;else if(s.startsWith("__secure-"))i.secure=!0;if(i.partitioned===!0||i.sameSite?.toLowerCase()==="none")i.secure=!0;return{name:o,value:r,options:i}}function Pc({name:t,value:r,options:n}){let o=`${t}=${r}`;if(typeof n.maxAge==="number"&&n.maxAge>=0){if(n.maxAge>34560000)throw Error("Cookies Max-Age SHOULD NOT be greater than 400 days (34560000 seconds) in duration.");o+=`; Max-Age=${Math.floor(n.maxAge)}`}if(n.domain)o+=`; Domain=${n.domain}`;if(n.path)o+=`; Path=${n.path}`;if(n.expires){if(n.expires.getTime()-Date.now()>34560000000)throw Error("Cookies Expires SHOULD NOT be greater than 400 days (34560000 seconds) in the future.");o+=`; Expires=${n.expires.toUTCString()}`}if(n.httpOnly)o+="; HttpOnly";if(n.secure)o+="; Secure";if(n.sameSite)o+=`; SameSite=${n.sameSite.charAt(0).toUpperCase()+n.sameSite.slice(1)}`;if(n.partitioned)o+="; Partitioned";return o}var jr=(t,r,n)=>(r=encodeURIComponent(r),Pc(Lc(t,r,n))),gi=async(t,r,n,o)=>(r=await Uc(r,n),Pc(Lc(t,r,o)));async function Nc(t,r={}){let n={body:r.body,query:r.query};if(t.body){let o=await t.body["~standard"].validate(r.body);if(o.issues)return{data:null,error:zc(o.issues,"body")};n.body=o.value}if(t.query){let o=await t.query["~standard"].validate(r.query);if(o.issues)return{data:null,error:zc(o.issues,"query")};n.query=o.value}if(t.requireHeaders&&!r.headers)return{data:null,error:{message:"Headers is required",issues:[]}};if(t.requireRequest&&!r.request)return{data:null,error:{message:"Request is required",issues:[]}};return{data:n,error:null}}function zc(t,r){return{message:t.map((n)=>`[${n.path?.length?`${r}.`+n.path.map((o)=>typeof o==="object"?o.key:o).join("."):r}] ${n.message}`).join("; "),issues:t}}var Vr=async(t,{options:r,path:n})=>{let o=new Headers,i=void 0,{data:s,error:a}=await Nc(r,t);if(a)throw new ed(a.message,a.issues);let c=t.headers!==void 0?t.headers instanceof Headers?t.headers:new Headers(t.headers):("request"in t)&&Yn(t.request)?t.request.headers:null,d=c?.get("cookie"),u=d?mi(d):void 0,f={...t,body:s.body,query:s.query,path:t.path||n||"virtual:",context:"context"in t&&t.context?t.context:{},returned:void 0,headers:t?.headers,request:t?.request,params:"params"in t?t.params:void 0,method:t.method??(Array.isArray(r.method)?r.method[0]:r.method==="*"?"GET":r.method),setHeader:(p,h)=>{o.set(p,h)},getHeader:(p)=>{if(!c)return null;return c.get(p)},getCookie:(p,h)=>{let m=qr(p,h);if(!m)return null;return u?.get(m)||null},getSignedCookie:async(p,h,m)=>{let w=qr(p,m);if(!w)return null;let y=u?.get(w);if(!y)return null;let I=y.lastIndexOf(".");if(I<1)return null;let R=y.substring(0,I),b=y.substring(I+1);if(b.length!==44||!b.endsWith("="))return null;return await Rc(b,R,await hi(h))?R:!1},setCookie:(p,h,m)=>{let w=jr(p,h,m);return o.append("set-cookie",w),w},setSignedCookie:async(p,h,m,w)=>{let y=await gi(p,h,m,w);return o.append("set-cookie",y),y},redirect:(p)=>(o.set("location",p),new ce("FOUND",void 0,o)),error:(p,h,m)=>new ce(p,h,m),setStatus:(p)=>{i=p},json:(p,h)=>{if(!t.asResponse)return p;return{body:h?.body||p,routerResponse:h,_flag:"json"}},responseHeaders:o,get responseStatus(){return i}};for(let p of r.use||[]){let h=await p({...f,returnHeaders:!0,asResponse:!1});if(h.response)Object.assign(f.context,h.response);if(h.headers)h.headers.forEach((m,w)=>{f.responseHeaders.set(w,m)})}return f};function Dm(t){if(t===void 0)return!1;let r=typeof t;if(r==="string"||r==="number"||r==="boolean"||r===null)return!0;if(r!=="object")return!1;if(Array.isArray(t))return!0;if(t.buffer)return!1;return t.constructor&&t.constructor.name==="Object"||typeof t.toJSON==="function"}function Pm(t){let r=new WeakMap,n=new WeakMap,o=0,i=(s,a)=>{let c=a;while(c){if(c===s)return!0;c=r.get(c)}return!1};return JSON.stringify(t,function(s,a){if(typeof a==="bigint")return a.toString();if(typeof a==="object"&&a!==null){if(i(a,this))return`[Circular ref-${n.get(a)}]`;if(r.set(a,this),!n.has(a))n.set(a,o++)}return a})}function zm(t){if(!t||typeof t!=="object")return!1;return"_flag"in t&&t._flag==="json"}var Nm=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"]);function ki(t){for(let r of Nm)t.delete(r)}function Xn(t,r){if(!r)return;for(let[n,o]of new Headers(r).entries())if(n.toLowerCase()==="set-cookie")t.append(n,o);else t.set(n,o)}function We(t,r){if(t instanceof Response){if(r?.headers){let i=new Headers(r.headers);ki(i),Xn(t.headers,i)}return t}if(zm(t)){let{body:i,routerResponse:s}=t;if(s instanceof Response)return s;let a=new Headers;if(Xn(a,s?.headers),Xn(a,t.headers),r?.headers){let u=new Headers(r.headers);ki(u),Xn(a,u)}a.set("Content-Type","application/json");let c=t.status??r?.status??s?.status,d=r?.statusText??s?.statusText;return new Response(JSON.stringify(i),{...s,headers:a,...c===void 0?{}:{status:c},...d===void 0?{}:{statusText:d}})}if(lt(t))return We(t.body,{status:r?.status??t.statusCode,statusText:t.status.toString(),headers:r?.headers||t.headers});let n=t,o=new Headers(r?.headers);if(ki(o),!t){if(t===null)n=JSON.stringify(null);o.set("content-type","application/json")}else if(typeof t==="string")n=t,o.set("Content-Type","text/plain");else if(t instanceof ArrayBuffer||ArrayBuffer.isView(t))n=t,o.set("Content-Type","application/octet-stream");else if(t instanceof Blob)n=t,o.set("Content-Type",t.type||"application/octet-stream");else if(t instanceof FormData)n=t;else if(t instanceof URLSearchParams)n=t,o.set("Content-Type","application/x-www-form-urlencoded");else if(t instanceof ReadableStream)n=t,o.set("Content-Type","application/octet-stream");else if(Dm(t))n=Pm(t),o.set("Content-Type","application/json");return new Response(n,{...r,headers:o})}function _t(t,r,n){let o=typeof t==="string"?t:void 0,i=typeof r==="object"?r:t,s=typeof r==="function"?r:n;if((i.method==="GET"||i.method==="HEAD")&&i.body)throw new yf("Body is not allowed with GET or HEAD methods");if(o&&/\/{2,}/.test(o))throw new yf("Path cannot contain consecutive slashes");let a=async(...c)=>{let d=c[0]||{},{data:u,error:f}=await Dc(Vr(d,{options:i,path:o}));if(f){if(!(f instanceof ed))throw f;if(i.onValidationError)await i.onValidationError({message:f.message,issues:f.issues});throw new ce(400,{message:f.message,code:"VALIDATION_ERROR"})}let p=await s(u).catch(async(w)=>{if(lt(w)){let y=i.onAPIError;if(y)await y(w);if(d.asResponse)return w}throw w}),{responseHeaders:h,responseStatus:m}=u;return d.asResponse?We(p,m===void 0?{headers:h}:{headers:h,status:m}):d.returnHeaders?d.returnStatus?{headers:h,response:p,status:m}:{headers:h,response:p}:d.returnStatus?{response:p,status:m}:p};return a.options=i,a.path=o,a}function qc(t,r){return[...t??[],...r??[]]}_t.create=(t)=>{function r(...n){if(n.length===3){let[s,a,c]=n;return _t(s,{...a,use:qc(a.use,t?.use)},c)}let[o,i]=n;return _t({...o,use:qc(o.use,t?.use)},i)}return r};function At(t,r){let n=async(o)=>{let i=o,s=typeof t==="function"?t:r,a=await Vr(i,{options:typeof t==="function"?{}:t,path:"/"});if(!s)throw Error("handler must be defined");try{let c=await s(a),d=a.responseHeaders;return i.returnHeaders?{headers:d,response:c}:c}catch(c){if(lt(c))Object.defineProperty(c,qa,{enumerable:!1,configurable:!0,get(){return a.responseHeaders}});throw c}};return n.options=typeof t==="function"?{}:t,n}At.create=(t)=>{function r(n,o){if(typeof n==="function")return At({use:t?.use},n);if(!o)throw Error("Middleware handler is required");return At({...n,method:"*",use:[...t?.use||[],...n.use||[]]},o)}return r};var Ei={};function $c(t){switch(t.constructor.name){case"ZodString":return"string";case"ZodNumber":return"number";case"ZodBoolean":return"boolean";case"ZodObject":return"object";case"ZodArray":return"array";default:return"string"}}function jc(t){let r=[];if(t.metadata?.openapi?.parameters)return r.push(...t.metadata.openapi.parameters),r;if(t.query instanceof wi)Object.entries(t.query.shape).forEach(([n,o])=>{if(o instanceof wi)r.push({name:n,in:"query",schema:{type:$c(o),..."minLength"in o&&o.minLength?{minLength:o.minLength}:{},description:o.description}})});return r}function qm(t){if(t.metadata?.openapi?.requestBody)return t.metadata.openapi.requestBody;if(!t.body)return;if(t.body instanceof wi||t.body instanceof na){let r=t.body.shape;if(!r)return;let n={},o=[];return Object.entries(r).forEach(([i,s])=>{if(s instanceof wi){if(n[i]={type:$c(s),description:s.description},!(s instanceof na))o.push(i)}}),{required:t.body instanceof na?!1:t.body?!0:!1,content:{"application/json":{schema:{type:"object",properties:n,required:o}}}}}}function Bc(t){return{"400":{content:{"application/json":{schema:{type:"object",properties:{message:{type:"string"}},required:["message"]}}},description:"Bad Request. Usually due to missing parameters, or invalid parameters."},"401":{content:{"application/json":{schema:{type:"object",properties:{message:{type:"string"}},required:["message"]}}},description:"Unauthorized. Due to missing or invalid authentication."},"403":{content:{"application/json":{schema:{type:"object",properties:{message:{type:"string"}}}}},description:"Forbidden. You do not have permission to access this resource or to perform this action."},"404":{content:{"application/json":{schema:{type:"object",properties:{message:{type:"string"}}}}},description:"Not Found. The requested resource was not found."},"429":{content:{"application/json":{schema:{type:"object",properties:{message:{type:"string"}}}}},description:"Too Many Requests. You have exceeded the rate limit. Try again later."},"500":{content:{"application/json":{schema:{type:"object",properties:{message:{type:"string"}}}}},description:"Internal Server Error. This is a problem with the server that you cannot fix."},...t}}async function bi(t,r){let n={schemas:{}};return Object.entries(t).forEach(([o,i])=>{let s=i.options;if(!i.path||s.metadata?.SERVER_ONLY)return;if(s.method==="GET")Ei[i.path]={get:{tags:["Default",...s.metadata?.openapi?.tags||[]],description:s.metadata?.openapi?.description,operationId:s.metadata?.openapi?.operationId,security:[{bearerAuth:[]}],parameters:jc(s),responses:Bc(s.metadata?.openapi?.responses)}};if(s.method==="POST"){let a=qm(s);Ei[i.path]={post:{tags:["Default",...s.metadata?.openapi?.tags||[]],description:s.metadata?.openapi?.description,operationId:s.metadata?.openapi?.operationId,security:[{bearerAuth:[]}],parameters:jc(s),...a?{requestBody:a}:{requestBody:{content:{"application/json":{schema:{type:"object",properties:{}}}}}},responses:Bc(s.metadata?.openapi?.responses)}}}}),{openapi:"3.1.1",info:{title:"Better Auth",description:"API Reference for your Better Auth Instance",version:"1.1.0"},components:n,security:[{apiKeyCookie:[]}],servers:[{url:r?.url}],tags:[{name:"Default",description:"Default endpoints that are included with Better Auth by default. These endpoints are not part of any plugin."}],paths:Ei}}var Si=(t,r)=>`<!doctype html>
2
+ import{rd,vf,$a,ce,te,U,Om,go,Jt,Xi,xl,vi,ea,xf,Tc,Ee,Cl,us,Sl,To,ko,nd,ta,od,kc,Cf,Vs,Sf,Ks,oA,If,sA,iA,sd,Tf,Mr,vr,id,Ha,Rc,pn,mn,ds}from"./chunk-atdfqdkj.js";import{dn,yi,zr,jr,_l,yl,vc,vl,Qu,mr,Gu,Qr,Vu,bs,Ku,bl,wl,Qo,Af,bc,In,so,en,_f}from"./chunk-sz19nn1x.js";import{yf,Wu}from"./chunk-vj4gamdn.js";import{Cc}from"./chunk-wgvgtttc.js";import{Pr,aA,Rf,e,Tn,Vo,pA,mA,_,E,N,J,Il,ue,A,wi,l,Bm,oe,D,k,T,v,na,ye,Cs}from"./chunk-5ddg5ezb.js";import{Ye}from"./chunk-4p31kxjh.js";var ai={};Ye(ai,{accountSchema:()=>xa,coreSchema:()=>Ze,getAuthTables:()=>go,rateLimitSchema:()=>za,sessionSchema:()=>zn,userSchema:()=>Nn,verificationSchema:()=>Na});function Pa(t){return Object.fromEntries(Object.entries(t).map(([r,n])=>[r,{code:r,message:n,toString:()=>r}]))}var Ae=Pa({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"});var Ze=l({id:e(),createdAt:ue().default(()=>new Date),updatedAt:ue().default(()=>new Date)});var xa=Ze.extend({providerId:e(),accountId:e(),userId:yf(),accessToken:e().nullish(),refreshToken:e().nullish(),idToken:e().nullish(),accessTokenExpiresAt:ue().nullish(),refreshTokenExpiresAt:ue().nullish(),scope:e().nullish(),password:e().nullish()});var za=l({key:e(),count:_(),lastRequest:_()});var zn=Ze.extend({userId:yf(),expiresAt:ue(),token:e(),ipAddress:e().nullish(),userAgent:e().nullish()});var Nn=Ze.extend({email:e().transform((t)=>t.toLowerCase()),emailVerified:E().default(!1),name:e(),image:e().nullish()});var Na=Ze.extend({value:e(),expiresAt:ue(),identifier:e()});function qa(t){return bm(t).schema}function bm(t){let{indexesByTable:r,tables:n}=Om(t),o=new Map,i={};for(let s in n){let a=n[s],c=a.fields,d={};if(Object.entries(c).forEach(([u,f])=>{let p=f.references,h=p?n[p.model]:void 0,m=p&&h?{...f,references:{...p,model:h.modelName}}:f;if(d[f.fieldName||u]=m,p)o.set(m,{modelKey:p.model,fieldKey:p.field})}),i[a.modelName]){if(i[a.modelName].fields={...i[a.modelName].fields,...d},a.disableMigrations)i[a.modelName].disableMigrations=!0;continue}i[a.modelName]={fields:d,order:a.order||1/0,disableMigrations:a.disableMigrations}}for(let[s,a]of r)if(i[s])i[s].indexes=a;return{schema:i,tables:n,referenceKeys:o}}function ci(t){if(t==="-"||t==="^"||t==="$"||t==="+"||t==="."||t==="("||t===")"||t==="|"||t==="["||t==="]"||t==="{"||t==="}"||t==="*"||t==="?"||t==="\\")return`\\${t}`;else return t}function Zh(t){let r="";for(let n=0;n<t.length;n++)r+=ci(t[n]);return r}function Ba(t,r=!0){if(Array.isArray(t))return`(?:${t.map((u)=>`^${Ba(u,r)}$`).join("|")})`;let n="",o="",i=".";if(r===!0)n="/",o="[/\\\\]",i="[^/\\\\]";else if(r)if(n=r,o=Zh(n),o.length>1)o=`(?:${o})`,i=`((?!${o}).)`;else i=`[^${o}]`;let s=r?`${o}+?`:"",a=r?`${o}*?`:"",c=r?t.split(n):[t],d="";for(let u=0;u<c.length;u++){let f=c[u],p=c[u+1],h="";if(!f&&u>0)continue;if(r)if(u===c.length-1)h=a;else if(p!=="**")h=s;else h="";if(r&&f==="**"){if(h)d+=u===0?"":h,d+=`(?:${i}*?${h})*?`;continue}for(let m=0;m<f.length;m++){let w=f[m];if(w==="\\"){if(m<f.length-1)d+=ci(f[m+1]),m++}else if(w==="?")d+=i;else if(w==="*")d+=`${i}*?`;else d+=ci(w)}d+=h}return d}function Yh(t,r){if(typeof r!=="string")throw TypeError(`Sample must be a string, but ${typeof r} given`);return t.test(r)}function jt(t,r){if(typeof t!=="string"&&!Array.isArray(t))throw TypeError(`The first argument must be a single pattern string or an array of patterns, but ${typeof t} given`);if(typeof r==="string"||typeof r==="boolean")r={separator:r};if(arguments.length===2&&!(typeof r>"u"||typeof r==="object"&&r!==null&&!Array.isArray(r)))throw TypeError(`The second argument must be an options object or a string/boolean separator, but ${typeof r} given`);if(r=r||{},r.separator==="\\")throw Error("\\ is not a valid separator because it is used for escaping. Try setting the separator to `true` instead");let n=Ba(t,r.separator),o=new RegExp(`^${n}$`,r.flags),i=Yh.bind(null,o);return i.options=r,i.pattern=t,i.regexp=o,i}var Xh=47;function em(t){let r=t.replace(/:\d+$/,"").replace(/^\[|\]$/g,"").toLowerCase();return r==="localhost"||r.endsWith(".localhost")||r==="::1"||r.startsWith("127.")}function Ma(t){let r=t.length;while(r>0&&t.charCodeAt(r-1)===Xh)r--;return r===t.length?t:t.slice(0,r)}function tm(t){try{return(Ma(new URL(t).pathname)||"/")!=="/"}catch{throw new te(`Invalid base URL: ${t}. Please provide a valid base URL.`)}}function rm(t){try{let r=new URL(t);if(r.protocol!=="http:"&&r.protocol!=="https:")throw new te(`Invalid base URL: ${t}. URL must include 'http://' or 'https://'`)}catch(r){if(r instanceof te)throw r;throw new te(`Invalid base URL: ${t}. Please provide a valid base URL.`,{cause:r})}}function dt(t,r="/api/auth"){if(rm(t),tm(t))return t;let n=Ma(t);if(!r||r==="/")return n;return r=r.startsWith("/")?r:`/${r}`,`${n}${r}`}function Dr(t,r){if(!t||t.trim()==="")return!1;if(r==="proto")return t==="http"||t==="https";if(r==="host"){if([/\.\./,/\0/,/[\s]/,/^[.]/,/[<>'"]/,/javascript:/i,/file:/i,/data:/i].some((n)=>n.test(t)))return!1;return/^[a-zA-Z0-9]([a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?(\.[a-zA-Z0-9]([a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?)*(:[0-9]{1,5})?$/.test(t)||/^(\d{1,3}\.){3}\d{1,3}(:[0-9]{1,5})?$/.test(t)||/^\[[0-9a-fA-F:]+\](:[0-9]{1,5})?$/.test(t)||/^localhost(:[0-9]{1,5})?$/i.test(t)}return!1}function Hs(t,r,n,o,i){if(t)return dt(t,r);if(o!==!1){let c=Jt.BETTER_AUTH_URL||Jt.NEXT_PUBLIC_BETTER_AUTH_URL||Jt.PUBLIC_BETTER_AUTH_URL||Jt.NUXT_PUBLIC_BETTER_AUTH_URL||Jt.NUXT_PUBLIC_AUTH_URL||(Jt.BASE_URL!=="/"?Jt.BASE_URL:void 0);if(c)return dt(c,r)}let s=n?.headers.get("x-forwarded-host"),a=n?.headers.get("x-forwarded-proto");if(s&&a&&i){if(Dr(a,"proto")&&Dr(s,"host"))try{return dt(`${a}://${s}`,r)}catch(c){}}if(n){let c=Ai(n.url);if(!c)throw new te("Could not get origin from request. Please provide a valid base URL.");return dt(c,r)}if(typeof window<"u"&&window.location)return dt(window.location.origin,r)}function Ai(t){try{let r=new URL(t);return r.origin==="null"?null:r.origin}catch{return null}}function Va(t){try{return new URL(t).protocol}catch{return null}}function Fa(t){try{return new URL(t).host}catch{return null}}function ls(t){return typeof t==="object"&&t!==null&&"allowedHosts"in t&&Array.isArray(t.allowedHosts)}function je(t){if(t instanceof Request)return!0;if(typeof t!=="object"||t===null||Object.prototype.toString.call(t)!=="[object Request]")return!1;let r=t;return typeof r.url==="string"&&typeof r.headers==="object"&&r.headers!==null&&typeof r.headers.get==="function"}function Ka(t,r){let n=je(t)?t.headers:t;if(r){let i=n.get("x-forwarded-host");if(i&&Dr(i,"host"))return i}let o=n.get("host");if(o&&Dr(o,"host"))return o;if(je(t))try{return new URL(t.url).host}catch{return null}return null}function nm(t,r,n){if(r==="http"||r==="https")return r;let o=je(t)?t.headers:t;if(n){let s=o.get("x-forwarded-proto");if(s&&Dr(s,"proto"))return s}if(je(t))try{let s=new URL(t.url);if(s.protocol==="http:"||s.protocol==="https:")return s.protocol.slice(0,-1)}catch{}let i=Ka(t,n);if(i&&em(i))return"http";return"https"}var om=(t,r)=>{if(!t||!r)return!1;let n=t.replace(/^https?:\/\//,"").split("/")[0].toLowerCase(),o=r.replace(/^https?:\/\//,"").split("/")[0].toLowerCase();if(o.includes("*")||o.includes("?"))return jt(o)(n);return n.toLowerCase()===o.toLowerCase()};function im(t,r,n,o){let i=Ka(r,o);if(!i){if(t.fallback)return dt(t.fallback,n);throw new te("Could not determine host from request headers. Please provide a fallback URL in your baseURL config.")}if(t.allowedHosts.some((s)=>om(i,s)))return dt(`${nm(r,t.protocol,o)}://${i}`,n);if(t.fallback)return dt(t.fallback,n);throw new te(`Host "${i}" is not in the allowed hosts list. Allowed hosts: ${t.allowedHosts.join(", ")}. Add this host to your allowedHosts config or provide a fallback URL.`)}function Wa(t,r,n,o,i){if(ls(t)){if(n)return im(t,n,r,i);if(t.fallback)return dt(t.fallback,r);return Hs(void 0,r,void 0,o,i)}let s=je(n)?n:void 0;if(typeof t==="string")return Hs(t,r,s,o,i);return Hs(void 0,r,s,o,i)}var Ga=/[\u0000-\u001f\u007f-\u009f]/,Ja="https://better-auth.invalid",sm=/%2[fF]|%5[cC]/,am=(t)=>{let r=t;try{r=decodeURIComponent(t)}catch{}let n=[];for(let o of r.split("/"))if(o==="..")n.pop();else if(o!=="."&&o!=="")n.push(o);return n.length>0?`/${n.join("/")}`:""},Qa=(t)=>{if(Ga.test(t))return null;let r=t.indexOf(":");if(r<=0)return null;let n=t.slice(0,r).toLowerCase(),o=t.slice(r+1),i="";if(o.startsWith("//")){o=o.slice(2);let c=o.search(/[/?#]/);if(c===-1)i=o,o="";else i=o.slice(0,c),o=o.slice(c)}let s=o.search(/[?#]/),a=am(s===-1?o:o.slice(0,s));return{scheme:n,authority:i.toLowerCase(),path:a}},cm=(t)=>{if(!t.startsWith("/")||t.startsWith("//")||t.includes("\\")||Ga.test(t))return!1;let r=t.search(/[?#]/),n=r===-1?t:t.slice(0,r);if(sm.test(n))return!1;try{return new URL(t,Ja).origin===Ja}catch{return!1}},cf=(t,r,n)=>{if(t.startsWith("/"))return n?.allowRelativePaths===!0&&cm(t);if(r.includes("*")||r.includes("?")){if(r.includes("://"))return jt(r)(Ai(t)||t);let a=Fa(t);if(!a)return!1;return jt(r)(a)}let o=Va(t);if(o==="http:"||o==="https:"||!o)return r===Ai(t);let i=Qa(t),s=Qa(r);if(!i||!s||i.scheme!==s.scheme)return!1;if(s.authority&&i.authority!==s.authority)return!1;if(!s.path)return!0;return i.path===s.path||i.path.startsWith(`${s.path}/`)};function uf(t){return!!t.database||!!t.secondaryStorage}function dm(t){return!!t.database}function qn(t){return dm(t)}function mc(t){return!!t&&(typeof t==="object"||typeof t==="function")&&typeof t.then==="function"}class di{oHash;iHash;blockLen;outputLen;canXOF=!1;finished=!1;destroyed=!1;constructor(t,r){if(od(t),ta(r,void 0,"key"),this.iHash=t.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,o=new Uint8Array(n);o.set(r.length>n?t.create().update(r).digest():r);for(let i=0;i<o.length;i++)o[i]^=54;this.iHash.update(o),this.oHash=t.create();for(let i=0;i<o.length;i++)o[i]^=106;this.oHash.update(o),Vs(o)}update(t){return kc(this),this.iHash.update(t),this}digestInto(t){kc(this),Cf(t,this),this.finished=!0;let r=t.subarray(0,this.outputLen);this.iHash.digestInto(r),this.oHash.update(r),this.oHash.digestInto(r),this.destroy()}digest(){let t=new Uint8Array(this.oHash.outputLen);return this.digestInto(t),t}_cloneInto(t){t||=Object.create(Object.getPrototypeOf(this),{});let{oHash:r,iHash:n,finished:o,destroyed:i,blockLen:s,outputLen:a,canXOF:c}=this;return t=t,t.finished=o,t.destroyed=i,t.blockLen=s,t.outputLen=a,t.canXOF=c,t.oHash=r._cloneInto(t.oHash),t.iHash=n._cloneInto(t.iHash),t}clone(){return this._cloneInto()}destroy(){this.destroyed=!0,this.oHash.destroy(),this.iHash.destroy()}}var ui=(()=>{let t=(r,n,o)=>new di(r,n).update(o).digest();return t.create=(r,n)=>new di(r,n),t})();var Lr=Uint8Array.of(0),um=Uint8Array.of();function lm(t,r,n,o=32,i){od(t),nd(o,"length"),ta(r,void 0,"prk");let s=t.outputLen;if(r.length<s)throw Error('"prk" must be at least HashLen octets');if(o>255*s)throw Error("Length must be <= 255*HashLen");let a=Math.ceil(o/s);if(n===void 0)n=um;else ta(n,void 0,"info");if(!a){if(i)Vs(r);return new Uint8Array}let c=i&&a===1?r:new Uint8Array(a*s),{iHash:d,oHash:u}=ui.create(t,r),f=i?r:new Uint8Array(s),p=a>1?i?.iHash||t.create():void 0;for(let m=0;m<a-1;m++){Lr[0]=m+1;let w=d._cloneInto(p);if(m)w.update(f);w.update(n).update(Lr).digestInto(f),u._cloneInto(p).update(f).digestInto(f),c.set(f,s*m)}if(Lr[0]=a,a>1)d.update(f);if(d.update(n).update(Lr).digestInto(f),u.update(f).digestInto(f),c.set(f,s*(a-1)),d.destroy(),u.destroy(),p?.destroy(),f!==c)Vs(f);if(Vs(Lr),o===c.length)return c;let h=c.slice(0,o);return Vs(c),h}var jn=(t,r,n,o,i)=>{if(od(t),n===void 0)n=new Uint8Array(t.outputLen);let s=ui.create(t,n).update(r);return lm(t,s.digest(),o,i,s)};var fm=(t)=>t/4294967296|0,pm=(t)=>t>>>0;function Za(t,r,n,o){let i=fm(n),s=pm(n);t.setUint32(r,o?s:i,o),t.setUint32(r+4,o?i:s,o)}function Ya(t,r,n){return t&r^~t&n}function Xa(t,r,n){return t&r^t&n^r&n}class li{blockLen;outputLen;canXOF=!1;padOffset;isLE;buffer;view;finished=!1;length=0;pos=0;destroyed=!1;constructor(t,r,n,o){this.blockLen=t,this.outputLen=r,this.padOffset=n,this.isLE=o,this.buffer=new Uint8Array(t),this.view=Sf(this.buffer)}update(t){kc(this),ta(t);let{view:r,buffer:n,blockLen:o}=this,i=t.length,s=!1;for(let a=0;a<i;){let c=Math.min(o-this.pos,i-a);if(c===o){let d=Sf(t);for(;o<=i-a;a+=o)this.process(d,a);s=!0;continue}if(n.set(a===0&&c===i?t:t.subarray(a,a+c),this.pos),this.pos+=c,a+=c,this.pos===o)this.process(r,0),this.pos=0,s=!0}if(this.length+=t.length,s)this.roundClean();return this}digestInto(t){kc(this),Cf(t,this),this.finished=!0;let{buffer:r,view:n,blockLen:o,isLE:i}=this,{pos:s}=this;if(r[s++]=128,r.fill(0,s),this.padOffset>o-s)this.process(n,0),r.fill(0);Za(n,o-8,this.length*8,i),this.process(n,0),this.roundClean();let a=t===r?n:Sf(t),c=this.outputLen,d=c/4,u=this.get();if(c%4||d>u.length)throw Error("invalid outputLen");for(let f=0;f<d;f++)a.setUint32(4*f,u[f],i)}digest(){let{buffer:t,outputLen:r}=this;this.digestInto(t);let n=t.slice(0,r);return this.destroy(),n}_cloneIntoMeta(t){let{buffer:r,length:n,finished:o,destroyed:i,pos:s}=this;if(t.destroyed=i,t.finished=o,t.length=n,t.pos=s,s)t.buffer.set(r);return t}clone(){return this._cloneInto()}}var ec=Uint32Array.from([1779033703,3144134277,1013904242,2773480762,1359893119,2600822924,528734635,1541459225]);var hm=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]),yt=new Uint32Array(64);class tc extends li{A=0;B=0;C=0;D=0;E=0;F=0;G=0;H=0;constructor(t,r){super(64,t,8,!1);this.A=r[0]|0,this.B=r[1]|0,this.C=r[2]|0,this.D=r[3]|0,this.E=r[4]|0,this.F=r[5]|0,this.G=r[6]|0,this.H=r[7]|0}get(){let{A:t,B:r,C:n,D:o,E:i,F:s,G:a,H:c}=this;return[t,r,n,o,i,s,a,c]}set(t,r,n,o,i,s,a,c){this.A=t|0,this.B=r|0,this.C=n|0,this.D=o|0,this.E=i|0,this.F=s|0,this.G=a|0,this.H=c|0}_cloneInto(t){return(t||=new this.constructor).set(...this.get()),this._cloneIntoMeta(t)}process(t,r){for(let f=0;f<16;f++,r+=4)yt[f]=t.getUint32(r,!1);for(let f=16;f<64;f++){let p=yt[f-15],h=yt[f-2],m=Ks(p,7)^Ks(p,18)^p>>>3,w=Ks(h,17)^Ks(h,19)^h>>>10;yt[f]=w+yt[f-7]+m+yt[f-16]|0}let{A:n,B:o,C:i,D:s,E:a,F:c,G:d,H:u}=this;for(let f=0;f<64;f++){let p=Ks(a,6)^Ks(a,11)^Ks(a,25),h=u+p+Ya(a,c,d)+hm[f]+yt[f]|0,w=(Ks(n,2)^Ks(n,13)^Ks(n,22))+Xa(n,o,i)|0;u=d,d=c,c=a,a=s+h|0,s=i,i=o,o=n,n=h+w|0}n=n+this.A|0,o=o+this.B|0,i=i+this.C|0,s=s+this.D|0,a=a+this.E|0,c=c+this.F|0,d=d+this.G|0,u=u+this.H|0,this.set(n,o,i,s,a,c,d,u)}roundClean(){Vs(yt)}destroy(){this.destroyed=!0,this.set(0,0,0,0,0,0,0,0),Vs(this.buffer)}}class rc extends tc{constructor(){super(32,ec)}}var Bn=sA(()=>new rc,iA(1));async function $n(t,r,n=3600){return await new bs(t).setProtectedHeader({alg:"HS256"}).setIssuedAt().setExpirationTime(Math.floor(Date.now()/1000)+n).sign(new TextEncoder().encode(r))}async function sc(t,r){try{return(await Qr(t,new TextEncoder().encode(r))).payload}catch{return null}}var mm=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]),gm=()=>Date.now()/1000|0,ac="dir",cc="A256CBC-HS512";function xr(t,r){return jn(Bn,new TextEncoder().encode(t),new TextEncoder().encode(r),mm,64)}function ym(t){if(typeof t==="string")return t;let r=t.keys.get(t.currentVersion);if(!r)throw Error(`Secret version ${t.currentVersion} not found in keys`);return r}function nc(t){if(typeof t==="string")return[{version:0,value:t}];let r=[];for(let[n,o]of t.keys)r.push({version:n,value:o});if(t.legacySecret&&!r.some((n)=>n.value===t.legacySecret))r.push({version:-1,value:t.legacySecret});return r}async function Mn(t,r,n,o=3600){let i=xr(ym(r),n),s=await wl({kty:"oct",k:mr(i)},"sha256");return await new Ku(t).setProtectedHeader({alg:ac,enc:cc,kid:s}).setIssuedAt().setExpirationTime(gm()+o).setJti(crypto.randomUUID()).encrypt(i)}var oc={clockTolerance:15,keyManagementAlgorithms:[ac],contentEncryptionAlgorithms:[cc,"A256GCM"]};async function Hn(t,r,n){if(!t)return null;let o=!1;try{o=so(t).kid!==void 0}catch{return null}try{let i=nc(r),{payload:s}=await Vu(t,async(a)=>{let c=a.kid;if(c!==void 0){for(let d of i){let u=xr(d.value,n);if(c===await wl({kty:"oct",k:mr(u)},"sha256"))return u}throw Error("no matching decryption secret")}if(i.length===1)return xr(i[0].value,n);return xr(i[0].value,n)},oc);return s}catch{if(o)return null;let i=nc(r);if(i.length<=1)return null;for(let s=1;s<i.length;s++)try{let a=i[s],{payload:c}=await Vu(t,xr(a.value,n),oc);return c}catch{continue}return null}}function cr(t,r){if(!t||!r)return t;let n=Object.entries(r).filter(([,{returned:o}])=>o===!1).map(([o])=>o);return Object.entries(structuredClone(t)).filter(([o])=>!n.includes(o)).reduce((o,[i,s])=>({...o,[i]:s}),{})}var fi=new WeakMap;function Xe(t,r,n){let o=`${r}:${n}`;if(!fi.has(t))fi.set(t,new Map);let i=fi.get(t);if(i.has(o))return i.get(o);let s=n==="output"?go(t)[r]?.fields??{}:{},a=r==="user"||r==="session"||r==="account"?t[r]?.additionalFields:void 0,c={...s,...a??{}};for(let d of t.plugins||[])if(d.schema&&d.schema[r])c={...c,...d.schema[r].fields};return i.set(o,c),c}function se(t,r){return cr(r,Xe(t,"user","output"))}function Nr(t,r){let n=Xe(t,"user","output"),o={};for(let i in n){let s=n[i];if(s.returned===!1)continue;if(i in r&&r[i]!==void 0)o[i]=r[i];else if(s.defaultValue!==void 0)o[i]=typeof s.defaultValue==="function"?s.defaultValue():s.defaultValue;else if(!s.required)o[i]=null}if("id"in r)o.id=r.id;return o}function we(t,r){return cr(r,Xe(t,"session","output"))}function Vn(t,r){let{accessToken:n,refreshToken:o,idToken:i,accessTokenExpiresAt:s,refreshTokenExpiresAt:a,password:c,...d}=cr(r,Xe(t,"account","output"));return d}function Bt(t,r){let n=r.action||"create",o=r.fields,i=Object.create(null);for(let s in o){if(s in t){if(o[s].input===!1){if(o[s].defaultValue!==void 0){if(n!=="update"){i[s]=o[s].defaultValue;continue}}if(t[s])throw U.from("BAD_REQUEST",{...Ae.FIELD_NOT_ALLOWED,message:`${s} is not allowed to be set`});continue}if(o[s].validator?.input&&t[s]!==void 0){let a=o[s].validator.input["~standard"].validate(t[s]);if(a instanceof Promise)throw U.from("INTERNAL_SERVER_ERROR",Ae.ASYNC_VALIDATION_NOT_SUPPORTED);if("issues"in a&&a.issues)throw U.from("BAD_REQUEST",{...Ae.VALIDATION_ERROR,message:a.issues[0]?.message||"Validation Error"});i[s]=a.value;continue}if(o[s].transform?.input&&t[s]!==void 0){i[s]=o[s].transform?.input(t[s]);continue}i[s]=t[s];continue}if(o[s].defaultValue!==void 0&&n==="create"){if(typeof o[s].defaultValue==="function"){i[s]=o[s].defaultValue();continue}i[s]=o[s].defaultValue;continue}if(o[s].required&&n==="create")throw U.from("BAD_REQUEST",{...Ae.MISSING_FIELD,message:`${s} is required`})}return i}function dr(t,r={},n){return Bt(r,{fields:Xe(t,"user","input"),action:n})}function ur(t,r={},n){let o=Xe(t,"user","input"),i=Object.create(null);for(let s of Object.keys(r)){if(o[s]?.input===!1)continue;i[s]=r[s]}return Bt(i,{fields:o,action:n})}function dc(t,r){let n=Xe(t,"user","input");return Bt(r||{},{fields:n})}function uc(t,r){return Bt(r,{fields:Xe(t,"account","input")})}function Fn(t,r,n){return Bt(r,{fields:Xe(t,"session","input"),action:n})}function Kn(t){let r=Xe(t,"session","input"),n={};for(let o in r)if(r[o].defaultValue!==void 0)n[o]=typeof r[o].defaultValue==="function"?r[o].defaultValue():r[o].defaultValue;return n}function hc(t,r){if(!r)return t;for(let n in r){let o=r[n]?.modelName;if(o)t[n].modelName=o;for(let i in t[n].fields){let s=r[n]?.fields?.[i];if(!s)continue;t[n].fields[i].fieldName=s}}return t}var ut=(t,r="ms")=>new Date(Date.now()+(r==="sec"?t*1000:t));var _m=/^(\+|\-)? ?(\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 Am(t){let r=_m.exec(t);if(!r||r[4]&&r[1])throw TypeError(`Invalid time string format: "${t}". Use formats like "7d", "30m", "1 hour", etc.`);let n=parseFloat(r[2]),o=r[3].toLowerCase(),i;switch(o){case"years":case"year":case"yrs":case"yr":case"y":i=n*31557600000;break;case"months":case"month":case"mo":i=n*2592000000;break;case"weeks":case"week":case"w":i=n*604800000;break;case"days":case"day":case"d":i=n*86400000;break;case"hours":case"hour":case"hrs":case"hr":case"h":i=n*3600000;break;case"minutes":case"minute":case"mins":case"min":case"m":i=n*60000;break;case"seconds":case"second":case"secs":case"sec":case"s":i=n*1000;break;default:throw TypeError(`Unknown time unit: "${o}"`)}if(r[1]==="-"||r[4]==="ago")return-i;return i}function Wn(t){return Math.round(Am(t)/1000)}var km=oe({session:zn.loose(),user:Nn.loose(),updatedAt:_(),version:e().optional()}),vm=l({session:k(e(),J()),expiresAt:_(),signature:e()});function gc(t){let r=Mr(t);if(r===null)return null;let n=km.safeParse(r);if(n.success)return n.data;return Ee.warn("Cookie cache payload failed schema validation",{issues:n.error.issues.map(({code:o,path:i})=>({code:o,path:i}))}),null}function lc(t){let r=vm.safeParse(t);return r.success?r.data:null}function pc(t){if(t.indexOf("%")===-1)return t;try{return decodeURIComponent(t)}catch{return t}}var wc="__Secure-";function Jn(t){if(!t)return[];let r=[],n=0,o=0;while(o<t.length){if(t[o]===","){let s=o+1;while(s<t.length&&t[s]===" ")s++;while(s<t.length&&t[s]!=="="&&t[s]!==";"&&t[s]!==",")s++;if(s<t.length&&t[s]==="="){let a=t.slice(n,o).trim();if(a)r.push(a);n=o+1;while(n<t.length&&t[n]===" ")n++;o=n;continue}}o++}let i=t.slice(n).trim();if(i)r.push(i);return r}function Qn(t){let r=new Map;return Jn(t).forEach((n)=>{let[o,...i]=n.split(";").map((u)=>u.trim()),[s,...a]=(o||"").split("="),c=Sc(a.join("="));if(!s)return;let d={value:pc(c)};i.forEach((u)=>{let[f,...p]=u.split("="),h=p.join("="),m=f.trim().toLowerCase();switch(m){case"max-age":d["max-age"]=h?parseInt(h.trim(),10):void 0;break;case"expires":d.expires=h?new Date(h.trim()):void 0;break;case"domain":d.domain=h?h.trim():void 0;break;case"path":d.path=h?h.trim():void 0;break;case"secure":d.secure=!0;break;case"httponly":d.httponly=!0;break;case"samesite":d.samesite=h?h.trim().toLowerCase():void 0;break;case"partitioned":d.partitioned=!0;break;default:d[m]=h?h.trim():!0;break}}),r.set(s,d)}),r}var Ec=/^[\x21\x23-\x27\x2A\x2B\x2D\x2E\x30-\x39\x41-\x5A\x5E\x5F\x60\x61-\x7A\x7C\x7E]+$/,Rm=/^[\x20\x21\x23-\x3A\x3C-\x5B\x5D-\x7E]*$/;function Sc(t){if(t.length<2||!t.startsWith('"')||!t.endsWith('"'))return t;return t.slice(1,-1)}function fc(t){let r=0,n=t.length;while(r<n){let o=t.charCodeAt(r);if(o!==32&&o!==9)break;r++}while(n>r){let o=t.charCodeAt(n-1);if(o!==32&&o!==9)break;n--}return r===0&&n===t.length?t:t.slice(r,n)}function Zn(t){let r=new Map;if(t.length<2)return r;for(let n of t.split(";")){let o=n.indexOf("=");if(o===-1)continue;let i=fc(n.slice(0,o)),s=Sc(fc(n.slice(o+1)));if(Ec.test(i)&&Rm.test(s))r.set(i,pc(s))}return r}function De(){let t=typeof globalThis<"u"&&globalThis.crypto;if(t&&typeof t.subtle==="object"&&t.subtle!=null)return t.subtle;throw Error("crypto.subtle must be defined")}var pi={name:"HMAC",hash:"SHA-256"},hi=async(t)=>{let r=typeof t==="string"?new TextEncoder().encode(t):t;return await De().importKey("raw",r,pi,!1,["sign","verify"])},Ic=async(t,r,n)=>{try{let o=atob(t),i=new Uint8Array(o.length);for(let s=0,a=o.length;s<a;s++)i[s]=o.charCodeAt(s);return await De().verify(pi,n,i,new TextEncoder().encode(r))}catch{return!1}},Tm=async(t,r)=>{let n=await hi(r),o=await De().sign(pi.name,n,new TextEncoder().encode(t));return btoa(String.fromCharCode(...new Uint8Array(o)))},Uc=async(t,r)=>{let n=await Tm(t,r);return t=`${t}.${n}`,t=encodeURIComponent(t),t};var Im=/^application\/([a-z0-9.+-]*\+)?json/i;async function Oc(t,r){let n=t.headers.get("content-type")||"",o=n.toLowerCase();if(!t.body)return;if(r&&r.length>0){if(!r.some((i)=>{let s=o.split(";")[0].trim(),a=i.toLowerCase().trim();return s===a||s.includes(a)})){if(!o)throw new ce(415,{message:`Content-Type is required. Allowed types: ${r.join(", ")}`,code:"UNSUPPORTED_MEDIA_TYPE"});throw new ce(415,{message:`Content-Type "${n}" is not allowed. Allowed types: ${r.join(", ")}`,code:"UNSUPPORTED_MEDIA_TYPE"})}}if(Im.test(o))try{return await t.json()}catch(i){if(i instanceof SyntaxError)throw new ce(400,{message:"Invalid JSON in request body",code:"BAD_REQUEST"});throw i}if(o.includes("application/x-www-form-urlencoded")){let i=await t.formData(),s={};return i.forEach((a,c)=>{s[c]=a.toString()}),s}if(o.includes("multipart/form-data")){let i=await t.formData(),s={};return i.forEach((a,c)=>{s[c]=a}),s}if(o.includes("text/plain"))return await t.text();if(o.includes("application/octet-stream"))return await t.arrayBuffer();if(o.includes("application/pdf")||o.includes("image/")||o.includes("video/"))return await t.blob();if(o.includes("application/stream")||t.body instanceof ReadableStream)return t.body;return await t.text()}function lt(t){return t instanceof ce||t?.name==="APIError"}function Dc(t){try{return t.includes("%")?decodeURIComponent(t):t}catch{return t}}async function Lc(t){try{return{data:await t,error:null}}catch(r){return{data:null,error:r}}}function Yn(t){return t instanceof Request||Object.prototype.toString.call(t)==="[object Request]"}var Um={secure:"__Secure-",host:"__Host-"},qr=(t,r)=>{if(!r)return t;if(r!=="secure"&&r!=="host")return;return Um[r]+t};function mi(t){if(typeof t!=="string")throw TypeError("argument str must be a string");let r=new Map,n=0;while(n<t.length){let o=t.indexOf("=",n);if(o===-1)break;let i=t.indexOf(";",n);if(i===-1)i=t.length;else if(i<o){n=t.lastIndexOf(";",o-1)+1;continue}let s=t.slice(n,o).trim();if(!r.has(s)){let a=t.slice(o+1,i).trim();if(a.codePointAt(0)===34)a=a.slice(1,-1);r.set(s,Dc(a))}n=i+1}return r}function Pc(t,r,n={}){let o=qr(t,n.prefix)??t,i={...n},s=o.toLowerCase();if(s.startsWith("__host-"))i.secure=!0,i.path="/",i.domain=void 0;else if(s.startsWith("__secure-"))i.secure=!0;if(i.partitioned===!0||i.sameSite?.toLowerCase()==="none")i.secure=!0;return{name:o,value:r,options:i}}function xc({name:t,value:r,options:n}){let o=`${t}=${r}`;if(typeof n.maxAge==="number"&&n.maxAge>=0){if(n.maxAge>34560000)throw Error("Cookies Max-Age SHOULD NOT be greater than 400 days (34560000 seconds) in duration.");o+=`; Max-Age=${Math.floor(n.maxAge)}`}if(n.domain)o+=`; Domain=${n.domain}`;if(n.path)o+=`; Path=${n.path}`;if(n.expires){if(n.expires.getTime()-Date.now()>34560000000)throw Error("Cookies Expires SHOULD NOT be greater than 400 days (34560000 seconds) in the future.");o+=`; Expires=${n.expires.toUTCString()}`}if(n.httpOnly)o+="; HttpOnly";if(n.secure)o+="; Secure";if(n.sameSite)o+=`; SameSite=${n.sameSite.charAt(0).toUpperCase()+n.sameSite.slice(1)}`;if(n.partitioned)o+="; Partitioned";return o}var Br=(t,r,n)=>(r=encodeURIComponent(r),xc(Pc(t,r,n))),gi=async(t,r,n,o)=>(r=await Uc(r,n),xc(Pc(t,r,o)));async function Nc(t,r={}){let n={body:r.body,query:r.query};if(t.body){let o=await t.body["~standard"].validate(r.body);if(o.issues)return{data:null,error:zc(o.issues,"body")};n.body=o.value}if(t.query){let o=await t.query["~standard"].validate(r.query);if(o.issues)return{data:null,error:zc(o.issues,"query")};n.query=o.value}if(t.requireHeaders&&!r.headers)return{data:null,error:{message:"Headers is required",issues:[]}};if(t.requireRequest&&!r.request)return{data:null,error:{message:"Request is required",issues:[]}};return{data:n,error:null}}function zc(t,r){return{message:t.map((n)=>`[${n.path?.length?`${r}.`+n.path.map((o)=>typeof o==="object"?o.key:o).join("."):r}] ${n.message}`).join("; "),issues:t}}var $r=async(t,{options:r,path:n})=>{let o=new Headers,i=void 0,{data:s,error:a}=await Nc(r,t);if(a)throw new rd(a.message,a.issues);let c=t.headers!==void 0?t.headers instanceof Headers?t.headers:new Headers(t.headers):("request"in t)&&Yn(t.request)?t.request.headers:null,d=c?.get("cookie"),u=d?mi(d):void 0,f={...t,body:s.body,query:s.query,path:t.path||n||"virtual:",context:"context"in t&&t.context?t.context:{},returned:void 0,headers:t?.headers,request:t?.request,params:"params"in t?t.params:void 0,method:t.method??(Array.isArray(r.method)?r.method[0]:r.method==="*"?"GET":r.method),setHeader:(p,h)=>{o.set(p,h)},getHeader:(p)=>{if(!c)return null;return c.get(p)},getCookie:(p,h)=>{let m=qr(p,h);if(!m)return null;return u?.get(m)||null},getSignedCookie:async(p,h,m)=>{let w=qr(p,m);if(!w)return null;let y=u?.get(w);if(!y)return null;let I=y.lastIndexOf(".");if(I<1)return null;let R=y.substring(0,I),b=y.substring(I+1);if(b.length!==44||!b.endsWith("="))return null;return await Ic(b,R,await hi(h))?R:!1},setCookie:(p,h,m)=>{let w=Br(p,h,m);return o.append("set-cookie",w),w},setSignedCookie:async(p,h,m,w)=>{let y=await gi(p,h,m,w);return o.append("set-cookie",y),y},redirect:(p)=>(o.set("location",p),new ce("FOUND",void 0,o)),error:(p,h,m)=>new ce(p,h,m),setStatus:(p)=>{i=p},json:(p,h)=>{if(!t.asResponse)return p;return{body:h?.body||p,routerResponse:h,_flag:"json"}},responseHeaders:o,get responseStatus(){return i}};for(let p of r.use||[]){let h=await p({...f,returnHeaders:!0,asResponse:!1});if(h.response)Object.assign(f.context,h.response);if(h.headers)h.headers.forEach((m,w)=>{f.responseHeaders.set(w,m)})}return f};function Dm(t){if(t===void 0)return!1;let r=typeof t;if(r==="string"||r==="number"||r==="boolean"||r===null)return!0;if(r!=="object")return!1;if(Array.isArray(t))return!0;if(t.buffer)return!1;return t.constructor&&t.constructor.name==="Object"||typeof t.toJSON==="function"}function Lm(t){let r=new WeakMap,n=new WeakMap,o=0,i=(s,a)=>{let c=a;while(c){if(c===s)return!0;c=r.get(c)}return!1};return JSON.stringify(t,function(s,a){if(typeof a==="bigint")return a.toString();if(typeof a==="object"&&a!==null){if(i(a,this))return`[Circular ref-${n.get(a)}]`;if(r.set(a,this),!n.has(a))n.set(a,o++)}return a})}function Pm(t){if(!t||typeof t!=="object")return!1;return"_flag"in t&&t._flag==="json"}var zm=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"]);function ki(t){for(let r of zm)t.delete(r)}function Xn(t,r){if(!r)return;for(let[n,o]of new Headers(r).entries())if(n.toLowerCase()==="set-cookie")t.append(n,o);else t.set(n,o)}function We(t,r){if(t instanceof Response){if(r?.headers){let i=new Headers(r.headers);ki(i),Xn(t.headers,i)}return t}if(Pm(t)){let{body:i,routerResponse:s}=t;if(s instanceof Response)return s;let a=new Headers;if(Xn(a,s?.headers),Xn(a,t.headers),r?.headers){let u=new Headers(r.headers);ki(u),Xn(a,u)}a.set("Content-Type","application/json");let c=t.status??r?.status??s?.status,d=r?.statusText??s?.statusText;return new Response(JSON.stringify(i),{...s,headers:a,...c===void 0?{}:{status:c},...d===void 0?{}:{statusText:d}})}if(lt(t))return We(t.body,{status:r?.status??t.statusCode,statusText:t.status.toString(),headers:r?.headers||t.headers});let n=t,o=new Headers(r?.headers);if(ki(o),!t){if(t===null)n=JSON.stringify(null);o.set("content-type","application/json")}else if(typeof t==="string")n=t,o.set("Content-Type","text/plain");else if(t instanceof ArrayBuffer||ArrayBuffer.isView(t))n=t,o.set("Content-Type","application/octet-stream");else if(t instanceof Blob)n=t,o.set("Content-Type",t.type||"application/octet-stream");else if(t instanceof FormData)n=t;else if(t instanceof URLSearchParams)n=t,o.set("Content-Type","application/x-www-form-urlencoded");else if(t instanceof ReadableStream)n=t,o.set("Content-Type","application/octet-stream");else if(Dm(t))n=Lm(t),o.set("Content-Type","application/json");return new Response(n,{...r,headers:o})}function _t(t,r,n){let o=typeof t==="string"?t:void 0,i=typeof r==="object"?r:t,s=typeof r==="function"?r:n;if((i.method==="GET"||i.method==="HEAD")&&i.body)throw new vf("Body is not allowed with GET or HEAD methods");if(o&&/\/{2,}/.test(o))throw new vf("Path cannot contain consecutive slashes");let a=async(...c)=>{let d=c[0]||{},{data:u,error:f}=await Lc($r(d,{options:i,path:o}));if(f){if(!(f instanceof rd))throw f;if(i.onValidationError)await i.onValidationError({message:f.message,issues:f.issues});throw new ce(400,{message:f.message,code:"VALIDATION_ERROR"})}let p=await s(u).catch(async(w)=>{if(lt(w)){let y=i.onAPIError;if(y)await y(w);if(d.asResponse)return w}throw w}),{responseHeaders:h,responseStatus:m}=u;return d.asResponse?We(p,m===void 0?{headers:h}:{headers:h,status:m}):d.returnHeaders?d.returnStatus?{headers:h,response:p,status:m}:{headers:h,response:p}:d.returnStatus?{response:p,status:m}:p};return a.options=i,a.path=o,a}function qc(t,r){return[...t??[],...r??[]]}_t.create=(t)=>{function r(...n){if(n.length===3){let[s,a,c]=n;return _t(s,{...a,use:qc(a.use,t?.use)},c)}let[o,i]=n;return _t({...o,use:qc(o.use,t?.use)},i)}return r};function At(t,r){let n=async(o)=>{let i=o,s=typeof t==="function"?t:r,a=await $r(i,{options:typeof t==="function"?{}:t,path:"/"});if(!s)throw Error("handler must be defined");try{let c=await s(a),d=a.responseHeaders;return i.returnHeaders?{headers:d,response:c}:c}catch(c){if(lt(c))Object.defineProperty(c,$a,{enumerable:!1,configurable:!0,get(){return a.responseHeaders}});throw c}};return n.options=typeof t==="function"?{}:t,n}At.create=(t)=>{function r(n,o){if(typeof n==="function")return At({use:t?.use},n);if(!o)throw Error("Middleware handler is required");return At({...n,method:"*",use:[...t?.use||[],...n.use||[]]},o)}return r};var Ei={};function $c(t){switch(t.constructor.name){case"ZodString":return"string";case"ZodNumber":return"number";case"ZodBoolean":return"boolean";case"ZodObject":return"object";case"ZodArray":return"array";default:return"string"}}function jc(t){let r=[];if(t.metadata?.openapi?.parameters)return r.push(...t.metadata.openapi.parameters),r;if(t.query instanceof wi)Object.entries(t.query.shape).forEach(([n,o])=>{if(o instanceof wi)r.push({name:n,in:"query",schema:{type:$c(o),..."minLength"in o&&o.minLength?{minLength:o.minLength}:{},description:o.description}})});return r}function Nm(t){if(t.metadata?.openapi?.requestBody)return t.metadata.openapi.requestBody;if(!t.body)return;if(t.body instanceof wi||t.body instanceof na){let r=t.body.shape;if(!r)return;let n={},o=[];return Object.entries(r).forEach(([i,s])=>{if(s instanceof wi){if(n[i]={type:$c(s),description:s.description},!(s instanceof na))o.push(i)}}),{required:t.body instanceof na?!1:t.body?!0:!1,content:{"application/json":{schema:{type:"object",properties:n,required:o}}}}}}function Bc(t){return{"400":{content:{"application/json":{schema:{type:"object",properties:{message:{type:"string"}},required:["message"]}}},description:"Bad Request. Usually due to missing parameters, or invalid parameters."},"401":{content:{"application/json":{schema:{type:"object",properties:{message:{type:"string"}},required:["message"]}}},description:"Unauthorized. Due to missing or invalid authentication."},"403":{content:{"application/json":{schema:{type:"object",properties:{message:{type:"string"}}}}},description:"Forbidden. You do not have permission to access this resource or to perform this action."},"404":{content:{"application/json":{schema:{type:"object",properties:{message:{type:"string"}}}}},description:"Not Found. The requested resource was not found."},"429":{content:{"application/json":{schema:{type:"object",properties:{message:{type:"string"}}}}},description:"Too Many Requests. You have exceeded the rate limit. Try again later."},"500":{content:{"application/json":{schema:{type:"object",properties:{message:{type:"string"}}}}},description:"Internal Server Error. This is a problem with the server that you cannot fix."},...t}}async function bi(t,r){let n={schemas:{}};return Object.entries(t).forEach(([o,i])=>{let s=i.options;if(!i.path||s.metadata?.SERVER_ONLY)return;if(s.method==="GET")Ei[i.path]={get:{tags:["Default",...s.metadata?.openapi?.tags||[]],description:s.metadata?.openapi?.description,operationId:s.metadata?.openapi?.operationId,security:[{bearerAuth:[]}],parameters:jc(s),responses:Bc(s.metadata?.openapi?.responses)}};if(s.method==="POST"){let a=Nm(s);Ei[i.path]={post:{tags:["Default",...s.metadata?.openapi?.tags||[]],description:s.metadata?.openapi?.description,operationId:s.metadata?.openapi?.operationId,security:[{bearerAuth:[]}],parameters:jc(s),...a?{requestBody:a}:{requestBody:{content:{"application/json":{schema:{type:"object",properties:{}}}}}},responses:Bc(s.metadata?.openapi?.responses)}}}}),{openapi:"3.1.1",info:{title:"Better Auth",description:"API Reference for your Better Auth Instance",version:"1.1.0"},components:n,security:[{apiKeyCookie:[]}],servers:[{url:r?.url}],tags:[{name:"Default",description:"Default endpoints that are included with Better Auth by default. These endpoints are not part of any plugin."}],paths:Ei}}var Si=(t,r)=>`<!doctype html>
3
3
  <html>
4
4
  <head>
5
5
  <title>Scalar API Reference</title>
@@ -28,15 +28,15 @@ import{ed,yf,qa,ce,te,U,Rm,go,Jt,Xi,El,vi,ea,Ef,Ic,Ee,xl,us,Cl,To,ko,td,ta,rd,Tc
28
28
  </script>
29
29
  <script src="https://cdn.jsdelivr.net/npm/@scalar/api-reference"></script>
30
30
  </body>
31
- </html>`;var ro=(()=>{let t=function(){};return t.prototype=Object.create(null),Object.freeze(t.prototype),t})();function Ii(){return{root:{key:""},static:new ro}}function jm(t){let r=0,n=0;for(;r<t.length;r++){let a=t.charCodeAt(r);if(a===92)r++;else if(a===40)n++;else if(a===41&&n>0)n--;else if(a===123&&n===0)break}if(r>=t.length)return;let o=r+1;n=0;for(;o<t.length;o++){let a=t.charCodeAt(o);if(a===92)o++;else if(a===40)n++;else if(a===41&&n>0)n--;else if(a===125&&n===0)break}if(o>=t.length)return;let i=t[o+1],s=i==="?"||i==="+"||i==="*";return[t.slice(0,r),t.slice(r+1,o),t.slice(o+(s?2:1)),s?i:void 0]}function Bm(t){if(!t.includes("{"))return;let r=jm(t);if(!r)return;let[n,o,i,s]=r;if(!s)return[n+o+i];if(s==="?")return[n+o+i,n+i];if(o.includes("/"))throw Error("unsupported group repetition across segments");return[`${n}(?:${o})${s}${i}`]}var $m="__rou3_unnamed_",Mm="__rou3_esc_";function Mc(t){return`${$m}${t}`}function Hm(t){return/^(?!__rou3_|_\d)[A-Za-z_]\w*$/.test(t)?t:Mm+t.replace(/[_-]/g,(r)=>r==="_"?"__":"_h")}function Vm(t){if(t.charCodeAt(0)!==95)return t;if(t.startsWith("__rou3_esc_"))return t.slice(11).replace(/__|_h/g,(r)=>r==="__"?"_":"-");return t.startsWith("__rou3_unnamed_")?t.slice(15):t}function Fm(t){let r=0;for(let n=0;n<t.length;n++){let o=t.charCodeAt(n);if(o===92){n++;continue}if(o===40){r++;continue}if(o===41&&r>0){r--;continue}if(o===42&&r===0)return!0}return!1}function Km(t,r,n=Mc){let o=0,i=r,s="";for(let a=0;a<t.length;a++){let c=t.charCodeAt(a);if(c===92){if(s+=t[a],a+1<t.length)s+=t[++a];continue}if(c===40){o++,s+=t[a];continue}if(c===41&&o>0){o--,s+=t[a];continue}if(c===42&&o===0){s+=`(?<${n(i++)}>[^/]*)`;continue}s+=t[a]}return[s,i]}function Wm(t){if(!t.includes("\\"))return t;return t.replace(/\\([:(){}])/g,(r,n)=>"\uFFFD"+"ABCDE"[":(){}".indexOf(n)])}function Jm(t){if(t.startsWith("**"))return 2;if(t==="*"||t.includes(":")||t.includes("(")||Fm(t))return 1;if(t==="\\*")return"*";if(t==="\\*\\*")return"**";if(!t.includes("\uFFFD"))return t;return t.replace(/\uFFFD([A-E])/g,(r,n)=>n==="A"?":":n==="B"?"(":n==="C"?")":n==="D"?"{":"}")}function Qm(t){for(let r=0;r<t.length;r++){let n=t[r].charCodeAt(t[r].length-1);if(n!==63&&n!==43&&n!==42)continue;let o=t[r].match(/^(.*:[\w-]+(?:\([^)]*\))?)([?+*])$/);if(!o)continue;let i=t.slice(0,r),s=t.slice(r+1);if(o[2]==="?")return["/"+i.concat(o[1]).concat(s).join("/"),"/"+i.concat(s).join("/")];let a=o[1].match(/:([\w-]+)/)?.[1]||"_",c="/"+[...i,`**:${a}`,...s].join("/"),d="/"+[...i,...s].join("/");return o[2]==="+"?[c]:[c,d]}}function Hc(t){if(!t.includes("/."))return t;let r=[];for(let n of t.split("/"))if(n===".")continue;else if(n===".."&&r.length>1)r.pop();else r.push(n);return r.join("/")||"/"}function Ui(t){let r=t.split("/");if(r.shift(),r[r.length-1]==="")r.pop();return r}function Gm(t){let r=Ui(t);while(r[r.length-1]==="")r.pop();return r}function Vc(t,r){let n=new ro;for(let[o,i]of r){let s=o<0?t.slice(-(o+1)).join("/"):t[o];if(typeof i==="string")n[i]=s;else{let a=s.match(i);if(a)for(let c in a.groups)n[Vm(c)]=a.groups[c]}}return n}function Fr(t,r="",n,o){if(r=r.toUpperCase(),n.charCodeAt(0)!==47)n=`/${n}`;let i=Bm(n);if(i){for(let m of i)Fr(t,r,m,o);return}n=Wm(n);let s=Gm(n),a=Qm(s);if(a){for(let m of a)Fr(t,r,m,o);return}let c=t.root,d=0,u=[],f=[];for(let m=0;m<s.length;m++){let w=s[m],y=Jm(w);if(y===2){if(!c.wildcard)c.wildcard={key:"**"};c=c.wildcard,u.push([-(m+1),w.split(":")[1]||"_",w.length===2]);break}if(y===1){if(!c.param)c.param={key:"*"};if(c=c.param,w==="*")u.push([m,String(d++),!0]);else if(w.includes("(")||w.includes(":",1)||!/^:[\w-]+$/.test(w)){let[R,b]=Zm(w,d);d=b,f[m]=R,c.hasRegexParam=!0,u.push([m,R,!1])}else u.push([m,w.slice(1),!1]);continue}w=s[m]=y;let I=c.static?.[w];if(I)c=I;else{let R={key:w};if(!c.static)c.static=new ro;c.static[w]=R,c=R}}let p=u.length>0,h=c.methods??=new ro;if((h[r]??=[]).push({data:o||null,paramsRegexp:f,paramsMap:p?u:void 0}),!p)t.static["/"+s.join("/")]=c}function Zm(t,r=0){let n=r,o="",i=0;for(let a=0;a<t.length;a++){let c=t.charCodeAt(a);if(c===40)i++;else if(c===41&&i>0)i--;else if(c===92&&i===0&&a+1<t.length){let d=t[a+1];if(d!==":"&&d!=="("&&d!=="*"&&d!=="\\"){o+="\uFFFE"+d,a++;continue}}else if(c===46&&i===0){o+="\\.";continue}o+=t[a]}[o,n]=Km(o,n);let s=o.replace(/:([\w-]+)(?:\(([^)]*)\))?/g,(a,c,d)=>`(?<${Hm(c)}>${d||"[^/]+"})`).replace(/\((?![?<])/g,()=>`(?<${Mc(n++)}>`).replace(/\uFFFE(.)/g,(a,c)=>/[.*+?^${}()|[\]\\]/.test(c)?`\\${c}`:c);return[new RegExp(`^${s}$`),n]}function Fc(t,r="",n,o){if(o?.normalize)n=Hc(n);if(n.charCodeAt(n.length-1)===47)n=n.slice(0,-1);let i=t.static[n];if(i&&i.methods){let c=i.methods[r]||i.methods[""];if(c!==void 0)return c[0]}let s=Ui(n),a=Ri(t.root,r,s,0);if(a===void 0)return;if(o?.params===!1)return a;return{data:a.data,params:a.paramsMap?Vc(s,a.paramsMap):void 0}}function Ri(t,r,n,o){if(o===n.length){if(t.methods){let s=eo(t.methods,r,n,t.key==="*",!1);if(s)return s}return t.param?.methods&&eo(t.param.methods,r,n,!0,!0)||t.wildcard?.methods&&eo(t.wildcard.methods,r,n,!0,!0)||void 0}let i=n[o];if(t.static){let s=t.static[i];if(s){let a=Ri(s,r,n,o+1);if(a)return a}}if(t.param){let s=Ri(t.param,r,n,o+1);if(s)return s}if(t.wildcard&&t.wildcard.methods)return eo(t.wildcard.methods,r,n,!0,!1)}function eo(t,r,n,o,i){let s=t[r]||t[""];if(!s)return;let a=s[0];if(s.length===1&&a.paramsRegexp.length===0){if(!i)return a;let u=a.paramsMap;return u?.[u.length-1]?.[2]?a:void 0}let c,d=-1;for(let u of s){let f=u.paramsMap,p=f?.[f.length-1]?.[2];if(i&&!p)continue;let h=o&&f&&!p?1:0,m=u.paramsRegexp;for(let w=0;w<m.length;w++)if(m[w]){if(!m[w].test(n[w])){h=-1;break}h++}if(h>d)c=u,d=h}return c}function Kc(t,r="",n,o){if(o?.normalize)n=Hc(n);if(n.charCodeAt(n.length-1)===47)n=n.slice(0,-1);let i=Ui(n),s=Ti(t.root,r,i,0);if(o?.params===!1)return s;return s.map((a)=>({data:a.data,params:a.paramsMap?Vc(i,a.paramsMap):void 0}))}function Ti(t,r,n,o,i=[]){let s=n[o];if(t.wildcard&&t.wildcard.methods){let a=t.wildcard.methods[r]||t.wildcard.methods[""];if(a)if(o<n.length)to(i,a,!0);else{let c=[];for(let d of a){let u=d.paramsMap;if(u?.[u.length-1]?.[2])c.push(d)}to(i,c,!0)}}if(t.param){if(o<n.length){let a=i.length;if(Ti(t.param,r,n,o+1,i),t.param.hasRegexParam){for(let c=i.length-1;c>=a;c--)if(i[c].paramsRegexp[o]?.test(s)===!1)i.splice(c,1)}}else if(t.param.methods){let a=t.param.methods[r]||t.param.methods[""];if(a){let c=[];for(let d of a){let u=d.paramsMap;if(u?.[u.length-1]?.[2])c.push(d)}to(i,c,!0)}}}if(o<n.length){let a=t.static?.[s];if(a)Ti(a,r,n,o+1,i)}if(o===n.length&&t.methods){let a=t.methods[r]||t.methods[""];if(a)to(i,a,t.key==="*")}return i}function to(t,r,n){if(r.length>1)r=r.map((o)=>{let i=0,{paramsRegexp:s,paramsMap:a}=o;for(let c=0;c<s.length;c++)if(s[c])i++;if(n&&a&&!a[a.length-1][2])i++;return[o,i]}).sort((o,i)=>o[1]-i[1]).map((o)=>o[0]);for(let o of r)t.push(o)}var Ci=(t,r)=>{if(!r?.openapi?.disabled){let a={path:"/api/reference",...r?.openapi};t.openapi=_t(a.path,{method:"GET"},async(c)=>{let d=await bi(t);return new Response(Si(d,a.scalar),{headers:{"Content-Type":"text/html"}})})}let n=Ii(),o=Ii();for(let a of Object.values(t)){if(!a.options||!a.path)continue;if(a.options?.metadata?.SERVER_ONLY)continue;let c=Array.isArray(a.options?.method)?a.options.method:[a.options?.method];for(let d of c)Fr(n,d,a.path,a)}if(r?.routerMiddleware?.length)for(let{path:a,middleware:c}of r.routerMiddleware)Fr(o,"*",a,c);let i=r?.basePath&&r.basePath!=="/"?r.basePath.replace(/\/+$/,""):"",s=async(a)=>{let c=new URL(a.url),d=c.pathname,u;if(i){if(!d.startsWith(`${i}/`))return new Response(null,{status:404,statusText:"Not Found"});u=d.slice(i.length)}else u=d;if(u.length===0||/\/{2,}/.test(u))return new Response(null,{status:404,statusText:"Not Found"});let f=Fc(n,a.method,u);if(u.endsWith("/")!==f?.data?.path?.endsWith("/")&&!r?.skipTrailingSlashes)return new Response(null,{status:404,statusText:"Not Found"});if(!f?.data)return new Response(null,{status:404,statusText:"Not Found"});let p={};c.searchParams.forEach((m,w)=>{if(w in p)if(Array.isArray(p[w]))p[w].push(m);else p[w]=[p[w],m];else p[w]=m});let h=f.data;try{let m=h.options.metadata?.allowedMediaTypes||r?.allowedMediaTypes,w={path:u,method:a.method,headers:a.headers,params:f.params?{...f.params}:{},request:a,body:h.options.disableBody?void 0:await Cc(h.options.cloneRequest?a.clone():a,m),query:p,_flag:"router",asResponse:!0,context:r?.routerContext},y=Kc(o,"*",u);if(y?.length)for(let{data:I,params:R}of y){let b=await I({...w,params:R?{...R}:{},asResponse:!1});if(b instanceof Response)return b}return await h(w)}catch(m){if(r?.onError)try{let w=await r.onError(m,a);if(w instanceof Response)return We(w)}catch(w){if(lt(w))return We(w);throw w}if(r?.throwError)throw m;if(lt(m))return We(m);return console.error("# SERVER_ERROR: ",m),new Response(null,{status:500,statusText:"Internal Server Error"})}};return{handler:async(a)=>{let c=await r?.onRequest?.(a);if(c instanceof Response)return c;let d=Yn(c)?c:a,u=await s(d),f=await r?.onResponse?.(u,d);if(f instanceof Response)return f;return u},endpoints:t}};var Jc=4050,Wc=100;function Ym(t,r){return Jc-jr(t,"",{...r}).length}function Qc(t,r){let n=`${t}.`;if(!r.startsWith(n))return null;let o=r.slice(n.length),i=Number(o);if(!Number.isSafeInteger(i)||i<0||String(i)!==o)return null;return i}function Xm(t,r){let n={},o=Zn(r.headers?.get("cookie")||"");for(let[i,s]of o){if(i!==t&&Qc(t,i)===null)continue;n[i]=s}return n}function eg(t,r,n,o){let i=Ym(`${r.name}.${Wc-1}`,r.attributes),s=i>0?Math.ceil(r.value.length/i):1/0;if(s<=1)return n[r.name]=r.value,[r];if(s>Wc)return o.warn(`${t} 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 a=[];for(let c=0;c<s;c++){let d=`${r.name}.${c}`,u=c*i,f=r.value.substring(u,u+i);a.push({...r,name:d,value:f}),n[d]=f}return o.debug(`CHUNKING_${t.toUpperCase()}_COOKIE`,{message:`${t} cookie exceeds the ${Jc} byte limit and was split into ${s} chunks.`,valueSize:r.value.length,chunkCount:s,chunkSizes:a.map((c)=>c.value.length)}),a}function tg(t,r){let n={};for(let o in t)n[o]={name:o,value:"",attributes:{...r,maxAge:0}};return n}var Gc=(t)=>(r,n,o)=>{let i=Xm(r,o),s=o.context.logger,a=()=>{let c=tg(i,n);for(let d in i)delete i[d];return c};return{chunk(c,d){let u=a(),f=eg(t,{name:r,value:c,attributes:{...n,...d}},i,s);for(let p of f)u[p.name]=p;return Object.values(u)},clean(){return Object.values(a())},setCookies(c){for(let d of c)o.setCookie(d.name,d.value,d.attributes)}}},Kr=Gc("Session"),no=Gc("Account");function oo(t,r){let n=t.getCookie(r);if(n)return n;let o=[],i=t.headers?.get("cookie");if(!i)return null;for(let[s,a]of Zn(i)){let c=Qc(r,s);if(c===null)continue;o.push({index:c,value:a})}if(o.length>0)return o.sort((s,a)=>s.index-a.index),o.map((s)=>s.value).join("");return null}async function ft(t,r){let n=t.context.authCookies.accountData,o={maxAge:300,...n.attributes},i=await Mn(r,t.context.secretConfig,"better-auth-account",o.maxAge),s=no(n.name,o,t);s.setCookies(s.chunk(i,o))}async function io(t){let r=oo(t,t.context.authCookies.accountData.name);if(r){let n=Mr(await Hn(r,t.context.secretConfig,"better-auth-account"));if(n)return n}return null}var Zc=ye(l({disableCookieCache:Vu().meta({description:"Disable cookie cache and fetch session from database"}).optional(),disableRefresh:Vu().meta({description:"Disable session refresh. Useful for checking session status, without updating the session"}).optional()}));var Oi=new Map,rg=new TextEncoder,Yc={decode:(t,r="utf-8")=>{if(!Oi.has(r))Oi.set(r,new TextDecoder(r));return Oi.get(r).decode(t)},encode:(t)=>rg.encode(t)};var Di=(t="SHA-256",r="none")=>{let n={importKey:async(o,i)=>De().importKey("raw",Cl(o),{name:"HMAC",hash:{name:t}},!1,[i]),sign:async(o,i)=>{if(typeof o==="string")o=await n.importKey(o,"sign");let s=await De().sign("HMAC",o,Cl(i));if(r==="hex")return nd.encode(s);if(r==="base64")return To.encode(s);if(r==="base64url"||r==="base64urlnopad")return ko.encode(s,{padding:r!=="base64urlnopad"});return s},verify:async(o,i,s)=>{if(typeof o==="string")o=await n.importKey(o,"verify");if(r==="hex")s=typeof s==="string"?nd.toBytes(s):s;if(r==="base64"||r==="base64url"||r==="base64urlnopad")s=await To.decode(s);return De().verify("HMAC",o,Cl(s),Cl(i))}};return n};function Zu(t){let r=typeof t.baseURL==="string"?t.baseURL:void 0,n=typeof t.baseURL==="object"&&t.baseURL!==null?t.baseURL.protocol:void 0,o=(t.advanced?.useSecureCookies!==void 0?t.advanced?.useSecureCookies:n==="https"?!0:n==="http"?!1:r?r.startsWith("https://"):Xi)?Ec:"",i=!!t.advanced?.crossSubDomainCookies?.enabled,s=i?t.advanced?.crossSubDomainCookies?.domain||(r?new URL(r).hostname:void 0):void 0;if(i&&!s&&!ls(t.baseURL))throw new te("baseURL is required when crossSubdomainCookies are enabled.");function a(c,d={}){let u=t.advanced?.cookiePrefix||"better-auth",f=t.advanced?.cookies?.[c]?.name||`${u}.${c}`,p=t.advanced?.cookies?.[c]?.attributes??{};return{name:`${o}${f}`,attributes:{secure:!!o,sameSite:"lax",path:"/",httpOnly:!0,...i?{domain:s}:{},...t.advanced?.defaultCookieAttributes,...d,...p}}}return a}function uf(t){let r=Zu(t),n=r("session_token",{maxAge:t.session?.expiresIn||Wn("7d")}),o=r("session_data",{maxAge:t.session?.cookieCache?.maxAge||300}),i=r("account_data",{maxAge:t.session?.cookieCache?.maxAge||300}),s=r("dont_remember");return{sessionToken:{name:n.name,attributes:n.attributes},sessionData:{name:o.name,attributes:o.attributes},dontRememberToken:{name:s.name,attributes:s.attributes},accountData:{name:i.name,attributes:i.attributes}}}async function Wr(t,r,n){if(!t.context.options.session?.cookieCache?.enabled)return;let o=cr(r.session,t.context.options.session?.additionalFields),i=se(t.context.options,r.user),s=t.context.options.session?.cookieCache?.version,a="1";if(s){if(typeof s==="string")a=s;else if(typeof s==="function"){let m=s(r.session,r.user);a=pc(m)?await m:m}}let c={session:o,user:i,updatedAt:Date.now(),version:a},d={...t.context.authCookies.sessionData.attributes,maxAge:n?void 0:t.context.authCookies.sessionData.attributes.maxAge},u=ut(d.maxAge||60,"sec").getTime(),f=t.context.options.session?.cookieCache?.strategy||"compact",p;if(f==="jwe")p=await Mn(c,t.context.secretConfig,"better-auth-session",d.maxAge||300);else if(f==="jwt"){let m=t.context.sessionConfig.cookieCacheSigner;p=m?await m.sign(t,c,d.maxAge||300):await $n(c,t.context.secret,d.maxAge||300)}else p=ko.encode(JSON.stringify({session:c,expiresAt:u,signature:await Di("SHA-256","base64urlnopad").sign(t.context.secret,JSON.stringify({...c,expiresAt:u}))}),{padding:!1});let h=Kr(t.context.authCookies.sessionData.name,d,t);if(h.setCookies(h.chunk(p,d)),t.context.options.account?.storeAccountCookie&&!og(t,t.context.authCookies.accountData.name)){let m=await io(t);if(m)if(!qn(t.context.options)||m.userId===r.user.id)await ft(t,m);else{Be(t,t.context.authCookies.accountData);let w=no(t.context.authCookies.accountData.name,t.context.authCookies.accountData.attributes,t);w.setCookies(w.clean())}}}async function Xc(t,r){let n=t.context.options.session?.cookieCache?.strategy||"compact";if(n==="jwe"){let s=await Hn(r,t.context.secretConfig,"better-auth-session"),a=hc(s);if(!a)return null;return{session:a,expiresAt:s?.exp?s.exp*1000:Date.now()}}if(n==="jwt"){let s=t.context.sessionConfig.cookieCacheSigner;if(s){let d=await s.verify(t,r);if(!d)return null;return{session:d.payload,expiresAt:d.expiresAt}}let a=await sc(r,t.context.secret),c=hc(a);if(!c)return null;return{session:c,expiresAt:a?.exp?a.exp*1000:Date.now()}}let o=lc(Mr(Yc.decode(ko.decode(r))));if(!o)return null;if(!await Di("SHA-256","base64urlnopad").verify(t.context.secret,JSON.stringify({...o.session,expiresAt:o.expiresAt}),o.signature))return null;let i=hc(o.session);return i?{session:i,expiresAt:o.expiresAt}:null}async function pe(t,r,n,o){let i=await t.getSignedCookie(t.context.authCookies.dontRememberToken.name,t.context.secret);n=n!==void 0?n:!!i;let s=t.context.authCookies.sessionToken.attributes,a=n?void 0:t.context.sessionConfig.expiresIn;if(await t.setSignedCookie(t.context.authCookies.sessionToken.name,r.session.token,t.context.secret,{...s,maxAge:a,...o}),n)await t.setSignedCookie(t.context.authCookies.dontRememberToken.name,"true",t.context.secret,t.context.authCookies.dontRememberToken.attributes);await Wr(t,r,n),t.context.setNewSession(r)}function ng(t,r){let n=t,o=new Set;if(n.responseHeaders)o.add(n.responseHeaders);if(n.context?.responseHeaders)o.add(n.context.responseHeaders);let i=`${r}=`,s=`${r}.`;for(let a of o){let c=typeof a.getSetCookie==="function"?a.getSetCookie():Jn(a.get("set-cookie")||"");if(!c.length)continue;let d=c.filter((u)=>!u.startsWith(i)&&!u.startsWith(s));if(d.length===c.length)continue;a.delete("set-cookie");for(let u of d)a.append("set-cookie",u)}}function og(t,r){let n=t,o=new Set;if(n.responseHeaders)o.add(n.responseHeaders);if(n.context?.responseHeaders)o.add(n.context.responseHeaders);let i=`${r}=`,s=`${r}.`;for(let a of o)if((typeof a.getSetCookie==="function"?a.getSetCookie():Jn(a.get("set-cookie")||"")).some((c)=>c.startsWith(i)||c.startsWith(s)))return!0;return!1}function Be(t,r){ng(t,r.name),t.setCookie(r.name,"",{...r.attributes,maxAge:0})}function Le(t,r){if(Be(t,t.context.authCookies.sessionToken),Be(t,t.context.authCookies.sessionData),t.context.options.account?.storeAccountCookie){Be(t,t.context.authCookies.accountData);let i=no(t.context.authCookies.accountData.name,t.context.authCookies.accountData.attributes,t),s=i.clean();i.setCookies(s)}if(t.context.oauthConfig.storeStateStrategy==="cookie")Be(t,t.context.createAuthCookie("oauth_state"));let n=Kr(t.context.authCookies.sessionData.name,t.context.authCookies.sessionData.attributes,t),o=n.clean();if(n.setCookies(o),!r)Be(t,t.context.authCookies.dontRememberToken)}function Li(t){if(!t?.method)throw new U("FORBIDDEN",{code:"validation_source_missing",message:"User validation source is required"});if(t.method==="oauth"&&!t.oauth?.providerId)throw new U("FORBIDDEN",{code:"validation_source_missing",message:"OAuth user validation source requires oauth.providerId"});if((t.method==="sso-oidc"||t.method==="sso-saml")&&!t.sso?.providerId)throw new U("FORBIDDEN",{code:"validation_source_missing",message:"SSO user validation source requires sso.providerId"})}async function lr(t,r){let n=t.context.options.user?.validateUserInfo;if(!n)return;Li(r.source);let o;try{o=await n(r,t)}catch(i){throw t.context.logger.error("validateUserInfo callback threw",i),new U("FORBIDDEN",{code:"validation_failed",message:"User validation failed"})}if(o?.error)throw new U("FORBIDDEN",{code:o.error,message:o.errorDescription||o.error})}function cs(t,r){return{digest:async(n)=>{let o=Cl(n),i=await De().digest(t,o);if(r==="hex")return Array.from(new Uint8Array(i)).map((s)=>s.toString(16).padStart(2,"0")).join("");if(r==="base64"||r==="base64url"||r==="base64urlnopad"){if(r.includes("url"))return ko.encode(i,{padding:r!=="base64urlnopad"});return To.encode(i)}return i}}}var ig=async(t)=>{let r=await cs("SHA-256").digest(new TextEncoder().encode(t));return ko.encode(new Uint8Array(r),{padding:!1})};async function $t(t,r){if(!r||r==="plain")return t;if(r==="hashed")return ig(t);if(typeof r==="object"&&"hash"in r)return r.hash(t);return t}function Mt(t,r){if(!r)return;if(typeof r==="object"&&"default"in r){if(r.overrides){for(let[n,o]of Object.entries(r.overrides))if(t.startsWith(n))return o}return r.default}return r}var kt,id=!1;function sg(){try{return globalThis.process?.getBuiltinModule?.("node:async_hooks")?.AsyncLocalStorage}catch{return}}async function fr(){if(kt)return kt;let t=sg();if(t)return kt??=t,kt;try{let{AsyncLocalStorage:r}=await import("async_hooks");return kt??=r,kt}catch(r){let n=globalThis.AsyncLocalStorage;if(typeof n==="function")return kt??=n,kt;if(typeof window<"u")throw Error("getAsyncLocalStorage is only available in server code");if(!id)id=!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");throw r}}var ag=()=>ea().context.endpointContextAsyncStorage,cg=async()=>{let t=ag();if(t)return t;let r=await fr(),n=ea().context;return n.endpointContextAsyncStorage??=new r};function Je(){return Ef()}function Bu(){let t=Je();if(!t)throw Error("No auth context found. Please make sure you are calling this function within a `runWithEndpointContext` callback.");return t}async function hr(t,r){return(await cg()).run(t,r)}var xi=async()=>{let t=ea(),r=t.context.requestStateAsyncStorage;if(r)return r;let n=await fr();return t.context.requestStateAsyncStorage??=new n,t.context.requestStateAsyncStorage};async function zi(){return(await xi()).getStore()!==void 0}async function Pi(){let t=(await xi()).getStore();if(!t)throw Error("No request state found. Please make sure you are calling this function within a `runWithRequestState` callback.");return t}async function Ni(t,r){return(await xi()).run(t,r)}function Et(t){let r=Object.freeze({});return{get ref(){return r},async get(){let n=await Pi();if(!n.has(r)){let o=await t();return n.set(r,o),o}return n.get(r)},async set(n){(await Pi()).set(r,n)}}}var ao=async()=>{let t=ea(),r=t.context.adapterAsyncStorage;if(r)return r;let n=await fr();return t.context.adapterAsyncStorage??=new n,t.context.adapterAsyncStorage};var X=async(t)=>ao().then((r)=>r.getStore()?.adapter||t).catch(()=>t),vm=async(t,r)=>{let n=!1;return ao().then(async(o)=>{n=!0;let i=[],s,a,c=!1;try{s=await o.run({adapter:t,pendingHooks:i,isTransactionActive:!1},r)}catch(d){a=d,c=!0}for(let d of i)await d();if(c)throw a;return s}).catch((o)=>{if(!n)return r();throw o})},Ue=async(t,r,n)=>{let o=!1;return ao().then(async(i)=>{if(o=!0,i.getStore()?.isTransactionActive)return r();let s=xc(t)?.();if(s)await s;let a=[],c,d,u=!1;try{c=await t.transaction(async(p)=>(a=[],i.run({adapter:p,pendingHooks:a,isTransactionActive:!0},r)))}catch(p){u=!0,d=p}let f=async(p)=>{for(let h of a)try{await h()}catch(m){if(!n?.onAfterCommitHookError){if(p==="throw")throw m;try{Ee.error("Failed to run an after-commit hook for work that could not roll back",m)}catch{}continue}try{await n.onAfterCommitHookError(m)}catch{}}};if(u){if(t.options?.adapterConfig.transaction===!1)await f("log");throw d}return await f("throw"),c}).catch((i)=>{if(!o)return r();throw i})},Te=async(t,r)=>{let n=async()=>{try{await t()}catch(s){if(!r?.onError)throw s;await r.onError(s)}},o;try{o=await ao()}catch{return n()}let i=o.getStore();if(!i?.isTransactionActive)return n();i.pendingHooks.push(n)};function co(t,r){let n=ds(r.options),o=r.hooks;async function i(f,p,h){let m=Je(),w=f;for(let{source:I,hooks:R}of o){let b=R[p]?.create?.before;if(b){let O=await n(`db create.before ${p}`,{[pn]:"create.before",[vr]:p,[mn]:I},()=>b(w,m));if(O===!1)return null;if(typeof O==="object"&&"data"in O)w={...w,...O.data}}}let y=null;if(!h||h.executeMainFn)y=await(await X(t)).create({model:p,data:w,forceAllowId:!0});if(h?.fn)y=await h.fn(y??w);for(let{source:I,hooks:R}of o){let b=R[p]?.create?.after;if(b)await Te(async()=>{await n(`db create.after ${p}`,{[pn]:"create.after",[vr]:p,[mn]:I},()=>b(y,m))})}return y}async function s(f,p,h,m){let w=Je(),y=f;for(let{source:b,hooks:O}of o){let g=O[h]?.update?.before;if(g){let S=await n(`db update.before ${h}`,{[pn]:"update.before",[vr]:h,[mn]:b},()=>g(f,w));if(S===!1)return null;if(typeof S==="object"&&"data"in S)y={...y,...S.data}}}let I=m?await m.fn(y):null,R=!m||m.executeMainFn?await(await X(t)).update({model:h,update:y,where:p}):I;for(let{source:b,hooks:O}of o){let g=O[h]?.update?.after;if(g)await Te(async()=>{await n(`db update.after ${h}`,{[pn]:"update.after",[vr]:h,[mn]:b},()=>g(R,w))})}return R}async function a(f,p,h,m){let w=Je(),y=f;for(let{source:b,hooks:O}of o){let g=O[h]?.update?.before;if(g){let S=await n(`db updateMany.before ${h}`,{[pn]:"updateMany.before",[vr]:h,[mn]:b},()=>g(f,w));if(S===!1)return null;if(typeof S==="object"&&"data"in S)y={...y,...S.data}}}let I=m?await m.fn(y):null,R=!m||m.executeMainFn?await(await X(t)).updateMany({model:h,update:y,where:p}):I;for(let{source:b,hooks:O}of o){let g=O[h]?.update?.after;if(g)await Te(async()=>{await n(`db updateMany.after ${h}`,{[pn]:"updateMany.after",[vr]:h,[mn]:b},()=>g(R,w))})}return R}async function c(f,p,h){let m=Je(),w=null;try{w=(await(await X(t)).findMany({model:p,where:f,limit:1}))[0]||null}catch{}if(w)for(let{source:R,hooks:b}of o){let O=b[p]?.delete?.before;if(O){if(await n(`db delete.before ${p}`,{[pn]:"delete.before",[vr]:p,[mn]:R},()=>O(w,m))===!1)return null}}let y=h?await h.fn(f):null,I=(!h||h.executeMainFn)&&w?await(await X(t)).delete({model:p,where:f}):y;if(w)for(let{source:R,hooks:b}of o){let O=b[p]?.delete?.after;if(O)await Te(async()=>{await n(`db delete.after ${p}`,{[pn]:"delete.after",[vr]:p,[mn]:R},()=>O(w,m))})}return I}async function d(f,p,h){let m=Je(),w=[];try{w=await(await X(t)).findMany({model:p,where:f})}catch{}for(let R of w)for(let{source:b,hooks:O}of o){let g=O[p]?.delete?.before;if(g){if(await n(`db delete.before ${p}`,{[pn]:"delete.before",[vr]:p,[mn]:b},()=>g(R,m))===!1)return null}}let y=h?await h.fn(f):null,I=!h||h.executeMainFn?await(await X(t)).deleteMany({model:p,where:f}):y;for(let R of w)for(let{source:b,hooks:O}of o){let g=O[p]?.delete?.after;if(g)await Te(async()=>{await n(`db delete.after ${p}`,{[pn]:"delete.after",[vr]:p,[mn]:b},()=>g(R,m))})}return I}async function u(f,p,h,m){let w=Je(),y=o.flatMap(({source:b,hooks:O})=>{let g=O[f]?.delete?.before;return g?[{source:b,fn:g}]:[]}),I=m??null;if(y.length){if(!I)try{I=(await(await X(t)).findMany({model:f,where:p,limit:1}))[0]||null}catch{}if(I){for(let{source:b,fn:O}of y)if(await n(`db delete.before ${f}`,{[pn]:"delete.before",[vr]:f,[mn]:b},()=>O(I,w))===!1)return null}}let R=await h();if(!R)return null;for(let{source:b,hooks:O}of o){let g=O[f]?.delete?.after;if(g)await Te(async()=>{await n(`db delete.after ${f}`,{[pn]:"delete.after",[vr]:f,[mn]:b},()=>g(R,w))})}return R}return{createWithHooks:i,updateWithHooks:s,updateManyWithHooks:a,deleteWithHooks:c,deleteManyWithHooks:d,consumeOneWithHooks:u}}var dg=dA(),ug=fA();function qi(t){return Jr(t)||ji(t)}function Jr(t){return kf(dg,t)}function ji(t){return kf(ug,t)}function sd(t){let r=t.toLowerCase();if(r.startsWith("::ffff:")){let o=r.substring(7);if(Jr(o))return o}let n=t.split(":");if(n.length===7&&n[5]?.toLowerCase()==="ffff"){let o=n[6];if(o&&Jr(o))return o}if(r.includes("::ffff:")||r.includes(":ffff:")){let o=Bi(t);if(o.length===8&&o[0]==="0000"&&o[1]==="0000"&&o[2]==="0000"&&o[3]==="0000"&&o[4]==="0000"&&o[5]==="ffff"&&o[6]&&o[7])return`${Number.parseInt(o[6].substring(0,2),16)}.${Number.parseInt(o[6].substring(2,4),16)}.${Number.parseInt(o[7].substring(0,2),16)}.${Number.parseInt(o[7].substring(2,4),16)}`}return null}function Bi(t){if(t.includes("::")){let r=t.split("::"),n=r[0]?r[0].split(":"):[],o=r[1]?r[1].split(":"):[],i=8-n.length-o.length,s=Array(i).fill("0000"),a=n.map((d)=>d.padStart(4,"0")),c=o.map((d)=>d.padStart(4,"0"));return[...a,...s,...c]}return t.split(":").map((r)=>r.padStart(4,"0"))}function lg(t,r){let n=Bi(t);if(r!==void 0&&r<128){let o=Math.max(0,Math.floor(r));return n.map((i)=>{if(o<=0)return"0000";if(o>=16)return o-=16,i;let s=Number.parseInt(i,16)&(65535<<16-o&65535);return o=0,s.toString(16).padStart(4,"0")}).join(":").toLowerCase()}return n.join(":").toLowerCase()}function uo(t,r={}){if(Jr(t))return t.toLowerCase();if(!ji(t))return t.toLowerCase();let n=sd(t);if(n)return n.toLowerCase();return lg(t,r.ipv6Subnet??64)}function ad(t){if(Jr(t))return Uint8Array.from(t.split(".").map((i)=>Number(i)));if(!ji(t))return null;let r=sd(t);if(r)return Uint8Array.from(r.split(".").map((i)=>Number(i)));let n=Bi(t),o=new Uint8Array(16);for(let i=0;i<8;i++){let s=Number.parseInt(n[i]??"0",16);o[i*2]=s>>8&255,o[i*2+1]=s&255}return o}var fg=/^\d+$/;function cd(t){let r=t.lastIndexOf("/"),n=ad(r===-1?t:t.slice(0,r));if(!n)return null;let o=n.length*8;if(r===-1)return{bytes:n,prefix:o};let i=t.slice(r+1);if(!fg.test(i))return null;let s=Number(i);return s<=o?{bytes:n,prefix:s}:null}function pg(t,r){if(t.length!==r.bytes.length)return!1;let n=r.prefix;for(let o=0;o<t.length&&n>0;o++){let i=n>=8?8:n,s=i===8?255:255<<8-i&255;if(((t[o]??0)&s)!==((r.bytes[o]??0)&s))return!1;n-=8}return!0}function $g(t){return t.filter((r)=>cd(r)===null)}function hg(t,r={}){let n=t.split(",").map((s)=>s.trim()).filter(Boolean);if(n.length===0)return null;let o=(r.trustedProxies??[]).map(cd).filter((s)=>s!==null);if(o.length>0){for(let s=n.length-1;s>=0;s--){let a=n[s],c=a?ad(a):null;if(!a||!c)return null;if(o.some((d)=>pg(c,d)))continue;return uo(a,{ipv6Subnet:r.ipv6Subnet})}return null}if(n.length!==1)return null;let i=n[0];if(!i||!qi(i))return null;return uo(i,{ipv6Subnet:r.ipv6Subnet})}var mg="127.0.0.1",gg=["x-forwarded-for"];function lo(t,r){if(r.advanced?.ipAddress?.disableIpTracking)return null;let n="headers"in t?t.headers:t,o=r.advanced?.ipAddress?.ipAddressHeaders||gg;for(let i of o){let s="get"in n?n.get(i):n[i];if(typeof s==="string"){let a=hg(s,{ipv6Subnet:r.advanced?.ipAddress?.ipv6Subnet,trustedProxies:r.advanced?.ipAddress?.trustedProxies});if(a)return a}}if(vi()||El())return mg;return null}function dd(t,r){return`${t}|${r}`}function et(t,r=Date.now()){let n=typeof t==="number"?t:t.getTime();return Math.max(Math.floor((n-r)/1000),0)}var gc=(t,r)=>{let{logger:n,options:o}=r,i=o.secondaryStorage,s=new Map,a=o.session?.expiresIn||604800,c=!!i&&o.session?.storeSessionInDatabase===!0&&o.session?.preserveSessionInDatabase!==!0,{createWithHooks:d,updateWithHooks:u,updateManyWithHooks:f,deleteWithHooks:p,deleteManyWithHooks:h,consumeOneWithHooks:m}=co(t,r),w=(g)=>{let S=[...g,{field:"expiresAt",value:new Date,operator:"gt"}];return h(S,"session",{fn:async()=>{await(await X(t)).updateMany({model:"session",where:S,update:{expiresAt:new Date}})},executeMainFn:!1})};async function y(g){if(!i)return;let S=await i.get(`active-sessions-${g.id}`);if(!S)return;let C=Date.now(),z=(Mr(S)||[]).filter((L)=>L.expiresAt>C);await Promise.all(z.map(async({token:L})=>{let x=await i.get(L);if(!x)return;let P=Mr(x);if(!P)return;let j=et(P.session.expiresAt,C);await i.set(L,JSON.stringify({session:P.session,user:g}),Math.floor(j))}))}async function I(g){if(!i)return[];let S=await i.get(`active-sessions-${g}`);return S?Mr(S)||[]:[]}async function R(g,S){if(!i)return;let C=new Set(S.map((B)=>B.token));for(let{token:B}of S)await i.delete(B);let z=`active-sessions-${g}`,L=await I(g),x=Date.now(),P=L.filter((B)=>B.expiresAt>x&&!C.has(B.token));P.sort((B,H)=>B.expiresAt-H.expiresAt);let j=P.at(-1)?.expiresAt;if(j){await i.set(z,JSON.stringify(P),et(j,x));return}await i.delete(z)}async function b(g,S){if(!i)return;let C=S??await I(g);await Te(()=>R(g,C),{onError(z){n.error("Failed to delete committed user sessions from secondary storage",z)}})}async function O(g,S){let C=s.get(g)??Promise.resolve(),z,L=new Promise((P)=>{z=P}),x=C.catch(()=>{}).then(()=>L);s.set(g,x),await C.catch(()=>{});try{return await S()}finally{if(z(),s.get(g)===x)s.delete(g)}}return{createOAuthUser:async(g,S)=>Ue(t,async()=>{let C=await d({createdAt:new Date,updatedAt:new Date,...g,email:g.email?.toLowerCase()},"user",void 0);if(!C)throw new U("BAD_REQUEST",{message:"Failed to create user"});return{user:C,account:await d({...S,userId:C.id,createdAt:new Date,updatedAt:new Date},"account",void 0)}}),createUser:async(g,S)=>{let C={createdAt:new Date,updatedAt:new Date,...g,email:g.email?.toLowerCase()};if(o.user?.validateUserInfo){let z={...S,action:"create-user"};Li(z);let L;try{L=Bu()}catch(x){throw n.error("Unable to run validateUserInfo: missing endpoint context",x),new U("FORBIDDEN",{code:"validation_context_missing",message:"User validation requires an endpoint context"})}await lr(L,{user:C,source:z})}return await d(C,"user",void 0)},createAccount:async(g)=>await d({createdAt:new Date,updatedAt:new Date,...g},"account",void 0),listSessions:async(g,S)=>{if(c)return(await(await X(t)).findMany({model:"session",where:[{field:"userId",value:g},{field:"expiresAt",value:new Date,operator:"gt"}]})).map((C)=>we(r.options,C));if(i){let C=await i.get(`active-sessions-${g}`);if(!C)return[];let z=Mr(C)||[],L=Date.now(),x=new Set,P=[];for(let{token:j,expiresAt:B}of z){if(B<=L||x.has(j))continue;x.add(j);let H=await i.get(j);if(!H)continue;try{let q=typeof H==="string"?JSON.parse(H):H;if(!q?.session)continue;P.push(we(r.options,{...q.session,expiresAt:new Date(q.session.expiresAt)}))}catch{continue}}return P}return await(await X(t)).findMany({model:"session",where:[{field:"userId",value:g},...S?.onlyActiveSessions?[{field:"expiresAt",value:new Date,operator:"gt"}]:[]]})},listUsers:async(g,S,C,z)=>await(await X(t)).findMany({model:"user",limit:g,offset:S,sortBy:C,where:z}),countTotalUsers:async(g)=>{let S=await(await X(t)).count({model:"user",where:g});if(typeof S==="string")return parseInt(S);return S},deleteUser:async(g)=>{let S=await I(g);if(!i||o.session?.storeSessionInDatabase)await h([{field:"userId",value:g}],"session",void 0);if(await h([{field:"userId",value:g}],"account",void 0),await p([{field:"id",value:g}],"user",void 0)!==null)await b(g,S)},createSession:async(g,S,C,z,L)=>{let x=await(async()=>{let M=Je();return M?.headers||M?.request?.headers})(),P=o.session?.storeSessionInDatabase,j=L?.deferSecondaryStorageWrites===!0&&c,{id:B,...H}=C||{},q;if(i&&!P){let M=r.generateId({model:"session"});q=M!==!1?M:us()}let J=Kn(o),Q={...q?{id:q}:{},ipAddress:x?lo(x,o)||"":"",userAgent:x?.get("user-agent")||"",...H,expiresAt:S?ut(86400,"sec"):ut(a,"sec"),userId:g,token:us(32),createdAt:new Date,updatedAt:new Date,...J,...z?H:{}},G=async(M)=>{if(!i)return M;let Y=await i.get(`active-sessions-${g}`),Z=[],re=Date.now();if(Y)Z=Mr(Y)||[],Z=Z.filter((Ke)=>Ke.expiresAt>re&&Ke.token!==Q.token);let ie=[...Z,{token:Q.token,expiresAt:Q.expiresAt.getTime()}].sort((Ke,wt)=>Ke.expiresAt-wt.expiresAt),qe=et(ie.at(-1)?.expiresAt??Q.expiresAt.getTime(),re);if(qe>0)await i.set(`active-sessions-${g}`,JSON.stringify(ie),qe);let gt=await(await X(t)).findOne({model:"user",where:[{field:"id",value:g}]}),ct=et(Q.expiresAt,re);if(ct>0)await i.set(Q.token,JSON.stringify({session:M,user:gt}),ct);return M};return await d(Q,"session",i?{fn:async(M)=>{if(!j)return G(M);return await Te(async()=>{await G(M)},{onError(Y){n.error("Failed to mirror committed session to secondary storage",Y)}}),M},executeMainFn:P}:void 0)},findSession:async(g)=>{if(i){let L=await i.get(g);if(!L&&(!o.session?.storeSessionInDatabase||r.options.session?.preserveSessionInDatabase))return null;if(L){let x=Mr(L);if(!x)return null;return{session:we(r.options,{...x.session,expiresAt:new Date(x.session.expiresAt),createdAt:new Date(x.session.createdAt),updatedAt:new Date(x.session.updatedAt)}),user:se(r.options,{...x.user,createdAt:new Date(x.user.createdAt),updatedAt:new Date(x.user.updatedAt)})}}}let S=await(await X(t)).findOne({model:"session",where:[{value:g,field:"token"}],join:{user:!0}});if(!S)return null;let{user:C,...z}=S;if(!C)return null;return{session:we(r.options,z),user:se(r.options,C)}},findSessions:async(g,S)=>{let C=[...new Set(g)],z=new Map,L=[];if(i)for(let P of C){let j=await i.get(P);if(j)try{let B=typeof j==="string"?JSON.parse(j):j;if(!B)continue;let H=new Date(B.session.expiresAt);if(S?.onlyActiveSessions&&H<=new Date)continue;let q={session:{...B.session,expiresAt:new Date(B.session.expiresAt)},user:{...B.user,createdAt:new Date(B.user.createdAt),updatedAt:new Date(B.user.updatedAt)}};z.set(P,q)}catch{continue}else L.push(P)}let x=i?L:C;if(x.length>0&&(!i||c)){let P=await(await X(t)).findMany({model:"session",limit:x.length,where:[{field:"token",value:x,operator:"in"},...S?.onlyActiveSessions?[{field:"expiresAt",value:new Date,operator:"gt"}]:[]],join:{user:!0}});for(let{user:j,...B}of P)if(j)z.set(B.token,{session:B,user:j})}return C.flatMap((P)=>{let j=z.get(P);return j?[j]:[]})},updateSession:async(g,S)=>await u(S,[{field:"token",value:g}],"session",i?{async fn(C){let z=await i.get(g);if(!z)return null;let L=Mr(z);if(!L)return null;let x={...L.session,...C,expiresAt:new Date(C.expiresAt??L.session.expiresAt),createdAt:new Date(L.session.createdAt),updatedAt:new Date(C.updatedAt??L.session.updatedAt)},P=we(r.options,x),j=Date.now(),B=new Date(P.expiresAt).getTime(),H=et(B,j);if(H>0){await i.set(g,JSON.stringify({session:P,user:L.user}),H);let q=`active-sessions-${P.userId}`,J=await i.get(q),Q=(J?Mr(J)||[]:[]).filter((M)=>M.token!==g&&M.expiresAt>j).concat([{token:g,expiresAt:B}]).sort((M,Y)=>M.expiresAt-Y.expiresAt),G=Q.at(-1)?.expiresAt;if(G&&G>j)await i.set(q,JSON.stringify(Q),et(G,j));else await i.delete(q)}return P},executeMainFn:o.session?.storeSessionInDatabase}:void 0),deleteSession:async(g)=>{if(i){let S=await i.get(g);if(S){let{session:C}=Mr(S)??{};if(!C){n.error("Session not found in secondary storage");return}let z=C.userId,L=await i.get(`active-sessions-${z}`);if(L){let x=Mr(L)||[],P=Date.now(),j=x.filter((H)=>H.expiresAt>P&&H.token!==g),B=j.sort((H,q)=>H.expiresAt-q.expiresAt).at(-1)?.expiresAt;if(j.length>0&&B&&B>Date.now())await i.set(`active-sessions-${z}`,JSON.stringify(j),et(B,P));else await i.delete(`active-sessions-${z}`)}else n.error("Active sessions list not found in secondary storage")}if(await i.delete(g),!o.session?.storeSessionInDatabase)return;if(r.options.session?.preserveSessionInDatabase){await w([{field:"token",value:g}]);return}}await p([{field:"token",value:g}],"session",void 0)},deleteAccounts:async(g)=>{await h([{field:"userId",value:g}],"account",void 0)},deleteAccount:async(g)=>{await p([{field:"id",value:g}],"account",void 0)},deleteUserSessions:async(g)=>{let S=await I(g);if(i){if(!o.session?.storeSessionInDatabase){await b(g,S);return}if(r.options.session?.preserveSessionInDatabase){if(await w([{field:"userId",value:g}])!==null)await b(g,S);return}}if(await h([{field:"userId",value:g}],"session",void 0)!==null)await b(g,S)},deleteSessions:async(g)=>{if(i){if(await Promise.all(g.map((S)=>i.delete(S))),!o.session?.storeSessionInDatabase)return;if(r.options.session?.preserveSessionInDatabase){await w([{field:"token",value:g,operator:"in"}]);return}}await h([{field:"token",value:g,operator:"in"}],"session",void 0)},findAccountOwnerByKey:async({providerId:g,accountId:S})=>{let C=await(await X(t)).findMany({model:"account",where:[{field:"providerId",value:g},{field:"accountId",value:S}],limit:2,join:{user:!0}});if(C.length>1)throw new te(`Multiple accounts match the same accountId for provider ${JSON.stringify(g)}. Resolve duplicate account identities before continuing.`);let z=C[0];if(!z)return null;let{user:L,...x}=z;return L?{kind:"owned",user:L,account:x}:{kind:"orphaned",account:x}},findUserByEmail:async(g,S)=>{let C=await(await X(t)).findOne({model:"user",where:[{value:g.toLowerCase(),field:"email"}],join:{...S?.includeAccounts?{account:!0}:{}}});if(!C)return null;let{account:z,...L}=C;return{user:L,accounts:z??[]}},findUserById:async(g)=>{if(!g)return null;return await(await X(t)).findOne({model:"user",where:[{field:"id",value:g}]})},linkAccount:async(g)=>await d({createdAt:new Date,updatedAt:new Date,...g},"account",void 0),updateUser:async(g,S)=>{let C=await u({...S,...S.email?{email:S.email.toLowerCase()}:{}},[{field:"id",value:g}],"user",void 0);return await Te(()=>y(C),{onError(z){n.error("Failed to refresh committed user sessions in secondary storage",z)}}),C},updateUserByEmail:async(g,S)=>{let C=await u({...S,...S.email?{email:S.email.toLowerCase()}:{}},[{field:"email",value:g.toLowerCase()}],"user",void 0);return await Te(()=>y(C),{onError(z){n.error("Failed to refresh committed user sessions in secondary storage",z)}}),C},updatePassword:async(g,S)=>{await f({password:S},[{field:"userId",value:g},{field:"providerId",value:"credential"},{field:"accountId",value:g}],"account",void 0)},findAccounts:async(g)=>await(await X(t)).findMany({model:"account",where:[{field:"userId",value:g}]}),findCredentialAccount:async(g)=>(await X(t)).findOne({model:"account",where:[{field:"userId",value:g},{field:"providerId",value:"credential"},{field:"accountId",value:g}]}),findAccountByKey:async({providerId:g,accountId:S})=>{let C=await(await X(t)).findMany({model:"account",limit:2,where:[{field:"providerId",value:g},{field:"accountId",value:S}]});if(C.length>1)throw new te(`Multiple accounts match the same accountId for provider ${JSON.stringify(g)}. Resolve duplicate account identities before continuing.`);return C[0]??null},findAccountByUserId:async(g)=>await(await X(t)).findMany({model:"account",where:[{field:"userId",value:g}]}),updateAccount:async(g,S)=>await u(S,[{field:"id",value:g}],"account",void 0),createVerificationValue:async(g)=>{let S=Mt(g.identifier,o.verification?.storeIdentifier),C=await $t(g.identifier,S);return await d({createdAt:new Date,updatedAt:new Date,...g,identifier:C},"verification",i?{async fn(z){let L=et(z.expiresAt);if(L>0)await i.set(`verification:${C}`,JSON.stringify(z),L);return z},executeMainFn:o.verification?.storeInDatabase}:void 0)},findVerificationValue:async(g)=>{let S=Mt(g,o.verification?.storeIdentifier),C=await $t(g,S);if(i){let P=await i.get(`verification:${C}`);if(P){let j=Mr(P);if(j)return j}if(S&&S!=="plain"){let j=await i.get(`verification:${g}`);if(j){let B=Mr(j);if(B)return B}}if(!o.verification?.storeInDatabase)return null}let z=await X(t);async function L(P){return z.findMany({model:"verification",where:[{field:"identifier",value:P}],sortBy:{field:"createdAt",direction:"desc"},limit:1})}let x=await L(C);if(!x.length&&S&&S!=="plain")x=await L(g);if(!o.verification?.disableCleanup)await h([{field:"expiresAt",value:new Date,operator:"lt"}],"verification",void 0);return x[0]||null},deleteVerificationByIdentifier:async(g)=>{let S=await $t(g,Mt(g,o.verification?.storeIdentifier));if(i)await i.delete(`verification:${S}`);if(!i||o.verification?.storeInDatabase)await p([{field:"identifier",value:S}],"verification",void 0)},consumeVerificationValue:async(g)=>{let S=Mt(g,o.verification?.storeIdentifier),C=await $t(g,S),z=S&&S!=="plain"?[C,g]:[C],L=(P)=>{if(!P)return null;let j=typeof P==="string"?Mr(P):typeof P==="object"?P:null;if(!j)return null;let B=new Date(j.expiresAt);if(!Number.isFinite(B.getTime()))return null;return{...j,expiresAt:B}},x=null;if(i&&!o.verification?.storeInDatabase){let P=async(j)=>L(await i.getAndDelete(j));for(let j of z){let B=await P(`verification:${j}`);if(!B)continue;await Promise.all(z.filter((H)=>H!==j).map((H)=>i.delete(`verification:${H}`))),x=B;break}}else{let P=async(j)=>O(`verification:${j}`,()=>Ue(t,async()=>{let B=await X(t),H=[{field:"identifier",value:j}],q=(await B.findMany({model:"verification",where:H,sortBy:{field:"createdAt",direction:"desc"},limit:1}))[0]??null;if(!q)return null;return m("verification",[{field:"id",value:q.id}],async()=>{let J=await B.consumeOne({model:"verification",where:[{field:"id",value:q.id}]});if(!J)return null;return await B.deleteMany({model:"verification",where:H}),J},q)}));for(let j of z)if(x=await P(j),x)break;if(x&&i)await Promise.all(z.map((j)=>i.delete(`verification:${j}`)))}if(!x||x.expiresAt<new Date)return null;return x},reserveVerificationValue:async(g)=>{let S=If(new Uint8Array(await cs("SHA-256").digest(new TextEncoder().encode("reserve:"+g.identifier))),o),C=Mt(g.identifier,o.verification?.storeIdentifier),z=await $t(g.identifier,C);if(i&&!o.verification?.storeInDatabase)throw new te("reserveVerificationValue requires database-backed verification storage. Set verification.storeInDatabase to true for flows that reserve verification values.");try{await t.create({model:"verification",data:{id:S,identifier:z,value:g.value,expiresAt:g.expiresAt,createdAt:new Date,updatedAt:new Date},forceAllowId:!0})}catch(L){if(await t.findOne({model:"verification",where:[{field:"id",value:S}]}))return!1;throw L}if(i){let L=et(g.expiresAt);if(L>0)await i.set(`verification:${z}`,JSON.stringify({id:S,identifier:z,value:g.value,expiresAt:g.expiresAt}),L)}return!0},updateVerificationByIdentifier:async(g,S)=>{let C=await $t(g,Mt(g,o.verification?.storeIdentifier));if(i){let z=await i.get(`verification:${C}`);if(z){let L=Mr(z);if(L){let x={...L,...S},P=x.expiresAt??L.expiresAt,j=et(P instanceof Date?P:new Date(P));if(j>0)await i.set(`verification:${C}`,JSON.stringify(x),j);if(!o.verification?.storeInDatabase)return x}}}if(!i||o.verification?.storeInDatabase)return await u(S,[{field:"identifier",value:C}],"verification",void 0);return S},refreshUserSessions:y}};function $i(t){if(t===null||typeof t!=="object")return!1;let r=Object.getPrototypeOf(t);if(r!==null&&r!==Object.prototype&&Object.getPrototypeOf(r)!==null)return!1;if(Symbol.iterator in t)return!1;if(Symbol.toStringTag in t)return Object.prototype.toString.call(t)==="[object Module]";return!0}function Mi(t,r,n=".",o){if(!$i(r))return Mi(t,{},n,o);let i={...r};for(let s of Object.keys(t)){if(s==="__proto__"||s==="constructor")continue;let a=t[s];if(a===null||a===void 0)continue;if(o&&o(i,s,a,n))continue;if(Array.isArray(a)&&Array.isArray(i[s]))i[s]=[...a,...i[s]];else if($i(a)&&$i(i[s]))i[s]=Mi(a,i[s],(n?`${n}.`:"")+s.toString(),o);else i[s]=a}return i}function Qr(t){return(...r)=>r.reduce((n,o)=>Mi(n,o,"",t),{})}var Uu=Qr(),RR=Qr((t,r,n)=>{if(t[r]!==void 0&&typeof n==="function")return t[r]=n(t[r]),!0}),TR=Qr((t,r,n)=>{if(Array.isArray(t[r])&&typeof n==="function")return t[r]=n(t[r]),!0});var wg=new Set(["metadata.google.internal","metadata.goog","metadata","instance-data","instance-data.ec2.internal"]);function yg(t){if(t.length>=2&&t.startsWith("[")&&t.endsWith("]"))return t.slice(1,-1);return t}function _g(t){if(t.startsWith("[")){let n=t.indexOf("]");if(n===-1)return t;return t.slice(0,n+1)}let r=t.indexOf(":");if(r===-1)return t;if(t.indexOf(":",r+1)!==-1)return t;return t.slice(0,r)}function Ag(t){let r=t.indexOf("%");if(r===-1)return t;return t.slice(0,r)}function kg(t){return t.replace(/\.+$/,"")}function ud(t){return/^\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}$/.test(t)}function ve(t){let r=t.split(".");return(Number(r[0])<<24|Number(r[1])<<16|Number(r[2])<<8|Number(r[3]))>>>0}function Ie(t,r,n){if(n===0)return!0;let o=n===32?4294967295:-1<<32-n>>>0;return(t&o)===(r&o)}function Gr(t){if(t==="0.0.0.0")return"unspecified";if(t==="255.255.255.255")return"broadcast";let r=ve(t);if(Ie(r,ve("127.0.0.0"),8))return"loopback";if(Ie(r,ve("10.0.0.0"),8))return"private";if(Ie(r,ve("172.16.0.0"),12))return"private";if(Ie(r,ve("192.168.0.0"),16))return"private";if(Ie(r,ve("169.254.0.0"),16))return"linkLocal";if(Ie(r,ve("100.64.0.0"),10))return"sharedAddressSpace";if(Ie(r,ve("192.0.2.0"),24))return"documentation";if(Ie(r,ve("198.51.100.0"),24))return"documentation";if(Ie(r,ve("203.0.113.0"),24))return"documentation";if(Ie(r,ve("198.18.0.0"),15))return"benchmarking";if(Ie(r,ve("224.0.0.0"),4))return"multicast";if(Ie(r,ve("0.0.0.0"),8))return"reserved";if(Ie(r,ve("192.0.0.0"),24))return"reserved";if(Ie(r,ve("192.88.99.0"),24))return"reserved";if(Ie(r,ve("240.0.0.0"),4))return"reserved";return"public"}function Hi(t,r,n={}){let o=r*5,i=Number.parseInt(t.slice(o,o+4),16),s=Number.parseInt(t.slice(o+5,o+9),16);if(!Number.isFinite(i)||!Number.isFinite(s))return null;let a=(i<<16|s)>>>0;if(n.xor)a=(a^4294967295)>>>0;return`${a>>>24&255}.${a>>>16&255}.${a>>>8&255}.${a&255}`}function Eg(t){if(t==="0000:0000:0000:0000:0000:0000:0000:0000")return"unspecified";if(t==="0000:0000:0000:0000:0000:0000:0000:0001")return"loopback";let r=Number.parseInt(t.slice(0,2),16),n=Number.parseInt(t.slice(2,4),16);if(r===255)return"multicast";if(r===254&&(n&192)===128)return"linkLocal";if(r===254&&(n&192)===192)return"reserved";if((r&254)===252)return"private";if(t.startsWith("2001:0db8:"))return"documentation";if(t.startsWith("2001:0002:0000:"))return"benchmarking";if(t.startsWith("2002:")){let o=Hi(t,1);if(o&&Gr(o)!=="public")return"reserved";return"public"}if(t.startsWith("0064:ff9b:0000:0000:0000:0000:")){let o=Hi(t,6);if(o&&Gr(o)!=="public")return"reserved";return"reserved"}if(t.startsWith("0064:ff9b:0001:"))return"reserved";if(t.startsWith("2001:0000:")){let o=Hi(t,6,{xor:!0});if(o&&Gr(o)!=="public")return"reserved";return"reserved"}if(t.startsWith("0100:0000:0000:0000:"))return"reserved";if(t.startsWith("3fff:0"))return"documentation";if(t.startsWith("5f00:"))return"reserved";if(t.startsWith("0000:0000:0000:0000:0000:0000:"))return"reserved";return"public"}function Vi(t){let r=kg(Ag(yg(_g(t.trim())))).toLowerCase();if(r==="")return{kind:"reserved",literal:"fqdn",canonical:""};if(!qi(r)){if(r==="localhost"||r.endsWith(".localhost"))return{kind:"localhost",literal:"fqdn",canonical:r};if(wg.has(r))return{kind:"cloudMetadata",literal:"fqdn",canonical:r};return{kind:"public",literal:"fqdn",canonical:r}}if(ud(r))return{kind:Gr(r),literal:"ipv4",canonical:r};let n=uo(r,{ipv6Subnet:128});if(ud(n))return{kind:Gr(n),literal:"ipv4",canonical:n};return{kind:Eg(n),literal:"ipv6",canonical:n}}function Fi(t){return Vi(t).kind==="loopback"}function mr(t){let r=Vi(t).kind;return r==="loopback"||r==="localhost"}function ld(t){return Vi(t).kind==="public"}async function Hg(t){let r=t.options,n=r.plugins||[],o=[],i=[];for(let s of n)if(s.init){let a=s.init(t),c;if(pc(a))c=await a;else c=a;if(typeof c==="object"){if(c.options){let{databaseHooks:d,trustedOrigins:u,...f}=c.options;if(d)i.push({source:`plugin:${s.id}`,hooks:d});if(u)o.push(u);r=Uu(r,f)}if(c.context)Object.assign(t,c.context)}}if(o.length>0){let s=[...r.trustedOrigins?[r.trustedOrigins]:[],...o],a=s.filter(Array.isArray).flat(),c=s.filter((d)=>typeof d==="function");if(c.length>0)r.trustedOrigins=async(d)=>{let u=await Promise.all(c.map((f)=>f(d)));return[...a,...u.flat()].filter((f)=>typeof f==="string"&&f!=="")};else r.trustedOrigins=a}if(r.databaseHooks)i.push({source:"user",hooks:r.databaseHooks});t.internalAdapter=gc(t.adapter,{options:r,logger:t.logger,hooks:i,generateId:t.generateId}),t.options=r}function Qg(t){let r=[];if(t.advanced?.crossSubDomainCookies?.enabled);return r}async function zu(t,r){let n=[];if(ls(t.baseURL)){let i=t.baseURL.allowedHosts,s=t.baseURL.protocol;for(let a of i)if(!a.includes("://")){if(!s||s==="https"||s==="auto")n.push(`https://${a}`);if(s==="http"||s==="auto"||mr(a))n.push(`http://${a}`)}else n.push(a);if(t.baseURL.fallback)try{n.push(new URL(t.baseURL.fallback).origin)}catch{}}else{let i=Hs(typeof t.baseURL==="string"?t.baseURL:void 0,t.basePath,r);if(i)n.push(new URL(i).origin)}if(t.trustedOrigins){if(Array.isArray(t.trustedOrigins))n.push(...t.trustedOrigins);if(typeof t.trustedOrigins==="function"){let i=await t.trustedOrigins(r);n.push(...i)}}let o=Jt.BETTER_AUTH_TRUSTED_ORIGINS;if(o)n.push(...o.split(","));return n.filter((i)=>Boolean(i))}function fd(t){if(je(t?.request))return t.request;if(!t?.headers)return;let r=t.headers instanceof Headers?t.headers:new Headers(t.headers);if(!r.has("host")&&!r.has("x-forwarded-host"))return;return r}function df(t){return t.advanced?.trustedProxyHeaders??!1}async function ff(t,r,n){let o=t.options.baseURL,i=Wa(o,t.options.basePath||"/api/auth",r,void 0,n);if(!i)throw new te("Could not resolve base URL from request. Check your allowedHosts config.");let s=Object.create(Object.getPrototypeOf(t),Object.getOwnPropertyDescriptors(t));s.baseURL=i,s.options={...t.options,baseURL:Ai(i)||void 0};let a={...s.options,baseURL:o},c=typeof t.options.trustedOrigins==="function"||typeof t.options.account?.accountLinking?.trustedProviders==="function",d;if(c)if(je(r))d=r;else if(r)d=new Request(i,{headers:r});else d=void 0;else d=void 0;if(s.trustedOrigins=await zu(a,d),s.trustedProviders=await ju(s.options,d),t.options.advanced?.crossSubDomainCookies?.enabled)s.authCookies=uf(s.options),s.createAuthCookie=Zu(s.options);return s}async function tt(t,r){if(!t)return;for(let n of t){let o=typeof n==="function"?await n():n;if(o[r.field??"id"]===r.value)return o}}async function ju(t,r){let n=t.account?.accountLinking?.trustedProviders;if(!n)return[];if(Array.isArray(n))return n.filter((o)=>Boolean(o));return(await n(r)??[]).filter((o)=>Boolean(o))}function Ht(t,r){if(r.length<t.context.password.config.minPasswordLength)throw t.context.logger.warn("Password is too short"),U.from("BAD_REQUEST",Ae.PASSWORD_TOO_SHORT)}function xe(t,r){if(r.length>t.context.password.config.maxPasswordLength)throw t.context.logger.warn("Password is too long"),U.from("BAD_REQUEST",Ae.PASSWORD_TOO_LONG)}async function pd(t,r,n,o){await Ue(t.context.adapter,async()=>{if(await o?.(),t.context.options.emailAndPassword?.revokeSessionsOnPasswordReset)await t.context.internalAdapter.deleteUserSessions(r);if(!await t.context.internalAdapter.findCredentialAccount(r)){await t.context.internalAdapter.createAccount({userId:r,providerId:"credential",accountId:r,password:n});return}await t.context.internalAdapter.updatePassword(r,n)})}async function hd(t,r){xe(t,r.password);let n=await t.context.internalAdapter.findCredentialAccount(r.userId),o=n?.password;if(!n||!o)return!1;return await t.context.password.verify({hash:o,password:r.password})}async function Gg(t,r){let n=r.body.password;if(typeof n==="string")xe(r,n);let o=await r.context.internalAdapter.findCredentialAccount(t),i=o?.password;if(!o||!i||!n){if(n)await r.context.password.hash(n);throw U.from("BAD_REQUEST",Ae.INVALID_PASSWORD)}if(!await r.context.password.verify({hash:i,password:n}))throw U.from("BAD_REQUEST",Ae.INVALID_PASSWORD);return!0}function Br(t){return t instanceof ce||t instanceof U||t?.name==="APIError"}var Zr={"Cache-Control":"no-store",Pragma:"no-cache"};function bg(t,r){if(!Br(r)||!t)return;Object.defineProperty(r,qa,{enumerable:!1,configurable:!0,value:t,writable:!1})}var Ji=At(async()=>({})),Cn=At.create({use:[Ji,At(async()=>({}))]}),md=_t.create({use:[Ji]});function gd(t,r){let n=r.metadata?.noStore===!0;return async(o)=>{if(n)for(let[i,s]of Object.entries(Zr))o.setHeader(i,s);try{return await hr(o,()=>t(o))}catch(i){throw bg(o.responseHeaders,i),i}}}function Pe(...t){if(t.length===3){let[o,i,s]=t;return md(o,i,gd(s,i))}let[r,n]=t;return md(r,gd(n,r))}function vg(t){return{...t,metadata:{...t.metadata,SERVER_ONLY:!0}}}Pe.serverOnly=(t,r)=>Pe(vg(t),r);function gr(t,r){let n;try{n=new URL(t).pathname.replace(/\/+$/,"")||"/"}catch{return"/"}let o=r.replace(/\/+$/,"");if(o==="")return n;if(n===o)return"/";if(n.startsWith(o+"/"))return n.slice(o.length).replace(/\/+$/,"")||"/";return n}var wd="https://better-auth.invalid";function $e(t,r){let n=t.startsWith("/");if(t.startsWith("//")||t.startsWith("/\\"))throw TypeError("Expected an absolute or root-relative URL");let o=n?new URL(t,wd):new URL(t);if(n&&o.origin!==wd)throw TypeError("Expected an absolute or root-relative URL");let i=r.toString();if(!i)return t;let s=o.search.endsWith("&")?"":"&";return o.search=o.search?`${o.search}${s}${i}`:i,n?o.href.slice(o.origin.length):o.href}var yd=["javascript:","data:","vbscript:"];function _d(t,r,n){let o=!1;return function(...i){if(!o)(n?.warn??console.warn)(`[Deprecation] ${r}`),o=!0;return t.apply(this,i)}}function Ad(t){return t.context.skipOriginCheck===!0&&t.context.options.advanced?.disableCSRFCheck===void 0}function Qi(t){let r=t.context.skipOriginCheck;if(r===!0)return!0;if(Array.isArray(r)&&t.request)try{let n=new URL(t.context.baseURL).pathname,o=gr(t.request.url,n);return r.some((i)=>{let s=i.replace(/\/+$/,"");return o===s||o.startsWith(`${s}/`)})}catch{}return!1}var Sg=_d(function(){},"disableOriginCheck: true currently also disables CSRF checks. In a future version, disableOriginCheck will ONLY disable URL validation. To keep CSRF disabled, add disableCSRFCheck: true to your config."),kd=Cn(async(t)=>{if(t.request?.method==="GET"||t.request?.method==="OPTIONS"||t.request?.method==="HEAD"||!t.request)return;if(await fo(t),Qi(t))return;let{body:r,query:n}=t,o=r?.callbackURL||n?.callbackURL,i=r?.redirectTo,s=r?.errorCallbackURL,a=r?.newUserCallbackURL,c=(d,u)=>{if(!d)return;if(typeof d!=="string")throw U.fromStatus("BAD_REQUEST",{message:`Invalid ${u}: expected a string`});if(!t.context.isTrustedOrigin(d,{allowRelativePaths:u!=="origin"})){if(t.context.logger.error(`Invalid ${u}: ${d}`),t.context.logger.info(`If it's a valid URL, please add ${d} to trustedOrigins in your auth config
32
- `,`Current list of trustedOrigins: ${t.context.trustedOrigins}`),u==="origin")throw U.from("FORBIDDEN",Ae.INVALID_ORIGIN);if(u==="callbackURL")throw U.from("FORBIDDEN",Ae.INVALID_CALLBACK_URL);if(u==="redirectURL")throw U.from("FORBIDDEN",Ae.INVALID_REDIRECT_URL);if(u==="errorCallbackURL")throw U.from("FORBIDDEN",Ae.INVALID_ERROR_CALLBACK_URL);if(u==="newUserCallbackURL")throw U.from("FORBIDDEN",Ae.INVALID_NEW_USER_CALLBACK_URL);throw U.fromStatus("FORBIDDEN",{message:`Invalid ${u}`})}};o&&c(o,"callbackURL"),i&&c(i,"redirectURL"),s&&c(s,"errorCallbackURL"),a&&c(a,"newUserCallbackURL")}),bt=(t)=>Cn(async(r)=>{if(!r.request)return;if(Qi(r))return;let n=t(r),o=(s,a)=>{if(!s)return;if(!r.context.isTrustedOrigin(s,{allowRelativePaths:a!=="origin"})){if(r.context.logger.error(`Invalid ${a}: ${s}`),r.context.logger.info(`If it's a valid URL, please add ${s} to trustedOrigins in your auth config
33
- `,`Current list of trustedOrigins: ${r.context.trustedOrigins}`),a==="origin")throw U.from("FORBIDDEN",Ae.INVALID_ORIGIN);if(a==="callbackURL")throw U.from("FORBIDDEN",Ae.INVALID_CALLBACK_URL);if(a==="redirectURL")throw U.from("FORBIDDEN",Ae.INVALID_REDIRECT_URL);if(a==="errorCallbackURL")throw U.from("FORBIDDEN",Ae.INVALID_ERROR_CALLBACK_URL);if(a==="newUserCallbackURL")throw U.from("FORBIDDEN",Ae.INVALID_NEW_USER_CALLBACK_URL);throw U.fromStatus("FORBIDDEN",{message:`Invalid ${a}`})}},i=Array.isArray(n)?n:[n];for(let s of i)o(s,"callbackURL")});async function fo(t,r=!1){let n=t.request?.headers;if(!n||!t.request)return;let o=n.get("origin"),i=o||n.get("referer")||"",s=n.has("cookie");if(t.context.skipCSRFCheck)return;if(Ad(t)){t.context.options.advanced?.disableOriginCheck===!0&&Sg();return}if(Qi(t))return;if(!(r||s))return;let a=o==="null"&&n.get("sec-fetch-site")==="same-origin"?Hs(void 0,t.context.options.basePath,t.request,!1,t.context.options.advanced?.trustedProxyHeaders):void 0,c=(a?Ai(a):void 0)??i;if(!c||c==="null")throw U.from("FORBIDDEN",Ae.MISSING_OR_NULL_ORIGIN);let d=Array.isArray(t.context.options.trustedOrigins)?t.context.trustedOrigins:[...t.context.trustedOrigins,...(await t.context.options.trustedOrigins?.(t.request))?.filter((u)=>Boolean(u))||[]];if(!d.some((u)=>lf(c,u)))throw t.context.logger.error(`Invalid origin: ${c}`),t.context.logger.info(`If it's a valid URL, please add ${c} to trustedOrigins in your auth config
34
- `,`Current list of trustedOrigins: ${d}`),U.from("FORBIDDEN",Ae.INVALID_ORIGIN)}var Yr=Cn(async(t)=>{if(!t.request)return;await Rg(t)});async function Rg(t){let r=t.request;if(!r)return;if(t.context.skipCSRFCheck)return;if(Ad(t))return;let n=r.headers;if(n.has("cookie"))return await fo(t);let o=n.get("Sec-Fetch-Site"),i=n.get("Sec-Fetch-Mode"),s=n.get("Sec-Fetch-Dest");if(Boolean(o&&o.trim()||i&&i.trim()||s&&s.trim())){if(o==="cross-site"&&i==="navigate")throw t.context.logger.error("Blocked cross-site navigation login attempt (CSRF protection)",{secFetchSite:o,secFetchMode:i,secFetchDest:s}),U.from("FORBIDDEN",Ae.CROSS_SITE_NAVIGATION_LOGIN_BLOCKED);return await fo(t,!0)}if(n.get("origin")||n.get("referer"))return await fo(t,!0)}var vt=new Map,Ed=1e5;function Tg(){let t=Date.now();for(let[o,i]of vt)if(t>=i.expiresAt)vt.delete(o);if(vt.size<=Ed)return;let r=vt.size-Ed,n=0;for(let o of vt.keys())if(vt.delete(o),++n>=r)break}function Ig(t,r,n){let o=r.window*1000;if(!t)return{next:{key:"",count:1,lastRequest:n},update:!1,allowed:!0,retryAfter:null};if(n-t.lastRequest>=o)return{next:{...t,count:1,lastRequest:n},update:!0,allowed:!0,retryAfter:null};if(t.count>=r.max)return{next:t,update:!0,allowed:!1,retryAfter:vd(t.lastRequest,r.window)};return{next:{...t,count:t.count+1,lastRequest:n},update:!0,allowed:!0,retryAfter:null}}function Ug(t){return new Response(JSON.stringify({message:"Too many requests. Please try again later."}),{status:429,statusText:"Too Many Requests",headers:{"Content-Type":"application/json","X-Retry-After":t.toString()}})}function vd(t,r){let n=Date.now(),o=r*1000;return Math.ceil((t+o-n)/1000)}function Cg(t){let n=t.adapter,o=Math.max(...Og(t)),i=async(c)=>{let d=(await n.findMany({model:"rateLimit",where:[{field:"key",value:c}]}))[0];if(d)d.lastRequest=Number(d.lastRequest);return d},s=async(c,d)=>{if(d.window>o)o=d.window;let u=d.window*1000,f=await i(c),p=Date.now();if(!f)try{return await n.create({model:"rateLimit",data:{key:c,count:1,lastRequest:p}}),{allowed:!0,retryAfter:null}}catch(w){if(!await i(c))throw w;return s(c,d)}if(p-f.lastRequest>=u){if(await n.incrementOne({model:"rateLimit",where:[{field:"key",value:c},{field:"lastRequest",operator:"lte",value:f.lastRequest}],increment:{},set:{count:1,lastRequest:p}}))return await a(p),{allowed:!0,retryAfter:null};return s(c,d)}let h=p-u;if(await n.incrementOne({model:"rateLimit",where:[{field:"key",value:c},{field:"lastRequest",operator:"gt",value:h},{field:"count",operator:"lt",value:d.max}],increment:{count:1},set:{lastRequest:p}}))return{allowed:!0,retryAfter:null};let m=await i(c);if(!m)return s(c,d);if(p-m.lastRequest>=u)return s(c,d);return{allowed:!1,retryAfter:vd(m.lastRequest,d.window)}},a=async(c)=>{let d=c-o*1000;await t.runInBackgroundOrAwait(n.deleteMany({model:"rateLimit",where:[{field:"lastRequest",operator:"lt",value:d}]}).then(()=>{return}).catch((u)=>t.logger.error("Error pruning rate limit rows",u)))};return{consume:s}}function Og(t){let r=[t.rateLimit.window,...Rd().map((o)=>o.window)];for(let o of t.options.plugins||[])if(o.rateLimit)r.push(...o.rateLimit.map((i)=>i.window));if(t.rateLimit.customRules){for(let o of Object.values(t.rateLimit.customRules))if(o&&typeof o!=="function")r.push(o.window)}let n=r.filter((o)=>Number.isFinite(o)&&o>0);return n.length>0?n:[t.rateLimit.window]}function Dg(t,r){if(t.options.rateLimit?.customStorage)return t.options.rateLimit.customStorage;let n=t.rateLimit.storage;if(n==="secondary-storage"){let o=(s)=>s??t.options.rateLimit?.window??10,i=t.options.secondaryStorage?.increment;if(!i)throw new te("Secondary-storage rate limiting requires SecondaryStorage.increment.");return{consume:async(s,a)=>{if(await i(s,o(a.window))<=a.max)return{allowed:!0,retryAfter:null};return{allowed:!1,retryAfter:a.window}}}}else if(n==="memory"){let o=(i)=>i??t.options.rateLimit?.window??10;return{async consume(i,s){Tg();let a=Date.now(),c=vt.get(i),d=Ig(c&&a<c.expiresAt?c.data:void 0,s,a);if(d.allowed)vt.set(i,{data:{...d.next,key:i},expiresAt:a+o(s.window)*1000});return{allowed:d.allowed,retryAfter:d.retryAfter}}}}return Cg(t)}var bd=!1,Lg="no-trusted-ip";async function Pg(t,r){let n=new URL(r.baseURL).pathname,o=gr(t.url,n),i=r.rateLimit.window,s=r.rateLimit.max,a=lo(t,r.options);if(!a&&r.options.advanced?.ipAddress?.disableIpTracking)return null;if(!a&&!bd)r.logger.warn("Rate limiting could not determine a client IP and is falling back to a single shared per-path bucket. Ensure your runtime forwards a trusted client IP header, then set `advanced.ipAddress.ipAddressHeaders` or `advanced.ipAddress.trustedProxies` so the address can be resolved."),bd=!0;let c=dd(a??Lg,o),d=Rd().find((u)=>u.pathMatcher(o));if(d)i=d.window,s=d.max;for(let u of r.options.plugins||[])if(u.rateLimit){let f=u.rateLimit.find((p)=>p.pathMatcher(o));if(f){i=f.window,s=f.max;break}}if(r.rateLimit.customRules){let u=Object.keys(r.rateLimit.customRules).find((f)=>{if(f.includes("*"))return jt(f)(o);return f===o});if(u){let f=r.rateLimit.customRules[u],p=typeof f==="function"?await f(t,{window:i,max:s}):f;if(p)i=p.window,s=p.max;if(p===!1)return null}}return{key:c,currentWindow:i,currentMax:s}}async function Sd(t,r){if(!r.rateLimit.enabled)return;let n=await Pg(t,r);if(!n)return;let{key:o,currentWindow:i,currentMax:s}=n,a=Dg(r,{window:i}),c={window:i,max:s},{allowed:d,retryAfter:u}=await a.consume(o,c);if(!d)return Ug(u??i)}function Rd(){return[{pathMatcher(t){return t.startsWith("/sign-in")||t.startsWith("/sign-up")||t.startsWith("/change-password")||t.startsWith("/change-email")},window:10,max:3},{pathMatcher(t){return t==="/request-password-reset"||t==="/send-verification-email"||t.startsWith("/forget-password")||t==="/email-otp/send-verification-otp"||t==="/email-otp/request-password-reset"},window:60,max:3}]}var{get:xg,set:Gi}=Et(()=>null),Zi=async()=>await xg(),{get:Yi,set:zg}=Et(()=>null),es=async(t)=>{await zg({...await Yi()??{},...t})};var{get:ts,set:mT}=Et(()=>!1);var rs=()=>Pe("/get-session",{method:["GET","POST"],operationId:"getSession",query:Zc,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(t)=>{t.setHeader("cache-control","no-store"),t.setHeader("pragma","no-cache");let r=t.context.options.session?.deferSessionRefresh,n=t.method==="POST";if(n&&!r)throw U.from("METHOD_NOT_ALLOWED",Ae.METHOD_NOT_ALLOWED_DEFER_SESSION_REQUIRED);try{let o=t.context.options.session?.cookieCache?.enabled===!0,i=await t.getSignedCookie(t.context.authCookies.sessionToken.name,t.context.secret);if(!i&&o)return null;let s=oo(t,t.context.authCookies.sessionData.name);if(s&&!o){let b=Kr(t.context.authCookies.sessionData.name,t.context.authCookies.sessionData.attributes,t);b.setCookies(b.clean())}if(!i)return null;let a=o&&!t.query?.disableCookieCache,c=a&&s?await Xc(t,s):null;if(a&&s&&!c)Be(t,t.context.authCookies.sessionData);let d=await t.getSignedCookie(t.context.authCookies.dontRememberToken.name,t.context.secret);if(c?.session){let b=c.session,O=b.session.token!==i;if(!O){let g=t.context.options.session?.cookieCache?.version,S="1";if(g){if(typeof g==="string")S=g;else if(typeof g==="function"){let C=g(b.session,b.user);S=C instanceof Promise?await C:C}}O=(b.version||"1")!==S}if(!O){let g=Date.now(),S=new Date(b.session.expiresAt).getTime();O=c.expiresAt<g||!Number.isFinite(S)||S<g}if(O)Be(t,t.context.authCookies.sessionData);else{let g=t.context.sessionConfig.cookieRefreshCache;if(g===!1){t.context.session=b;let P=we(t.context.options,{...b.session,expiresAt:new Date(b.session.expiresAt),createdAt:new Date(b.session.createdAt),updatedAt:new Date(b.session.updatedAt)}),j=se(t.context.options,{...b.user,createdAt:new Date(b.user.createdAt),updatedAt:new Date(b.user.updatedAt)});return t.json({session:P,user:j})}let S=c.expiresAt-Date.now(),C=g.updateAge*1000,z=await ts();if(S<C&&!z){let P={session:{...b.session},user:b.user,updatedAt:Date.now()};await Wr(t,P,!1);let j=t.context.authCookies.sessionToken.attributes,B=d?void 0:t.context.sessionConfig.expiresIn;await t.setSignedCookie(t.context.authCookies.sessionToken.name,b.session.token,t.context.secret,{...j,maxAge:B});let H=we(t.context.options,{...P.session,expiresAt:new Date(P.session.expiresAt),createdAt:new Date(P.session.createdAt),updatedAt:new Date(P.session.updatedAt)}),q=se(t.context.options,{...P.user,createdAt:new Date(P.user.createdAt),updatedAt:new Date(P.user.updatedAt)});return t.context.session={session:H,user:q},t.json({session:H,user:q})}let L=we(t.context.options,{...b.session,expiresAt:new Date(b.session.expiresAt),createdAt:new Date(b.session.createdAt),updatedAt:new Date(b.session.updatedAt)}),x=se(t.context.options,{...b.user,createdAt:new Date(b.user.createdAt),updatedAt:new Date(b.user.updatedAt)});return t.context.session={session:L,user:x},t.json({session:L,user:x})}}let u=await t.context.internalAdapter.findSession(i);if(t.context.session=u,!u||u.session.expiresAt<new Date){if(Le(t),u){if(!r||n)await t.context.internalAdapter.deleteSession(u.session.token)}return t.json(null)}if(d||t.query?.disableRefresh){let b=we(t.context.options,u.session),O=se(t.context.options,u.user);return t.json({session:b,user:O})}let f=t.context.sessionConfig.expiresIn,p=t.context.sessionConfig.updateAge,h=u.session.expiresAt.valueOf()-f*1000+p*1000<=Date.now(),m=t.query?.disableRefresh||t.context.options.session?.disableSessionRefresh,w=await ts(),y=h&&!m&&!w;if(r&&!n){await Wr(t,u,!!d);let b=we(t.context.options,u.session),O=se(t.context.options,u.user);return t.json({session:b,user:O,needsRefresh:y})}if(y){let b=await t.context.internalAdapter.updateSession(u.session.token,{expiresAt:ut(t.context.sessionConfig.expiresIn,"sec"),updatedAt:new Date});if(!b)throw Le(t),U.from("UNAUTHORIZED",Ae.FAILED_TO_GET_SESSION);let O=t.context.sessionConfig.expiresIn;await pe(t,{session:b,user:u.user},!1,{maxAge:O});let g=we(t.context.options,b),S=se(t.context.options,u.user);return t.json({session:g,user:S})}await Wr(t,u,!!d);let I=we(t.context.options,u.session),R=se(t.context.options,u.user);return t.json({session:I,user:R})}catch(o){if(Br(o))throw o;throw t.context.logger.error("INTERNAL_SERVER_ERROR",o),U.from("INTERNAL_SERVER_ERROR",Ae.FAILED_TO_GET_SESSION,{cause:o})}}),St=(t)=>cf(t.context.options),ee=async(t,r)=>{if(t.context.session)return t.context.session;let n=await rs()({...t,method:"GET",asResponse:!1,headers:t.headers,returnHeaders:!0,returnStatus:!1,query:{...r,...t.query,disableCookieCache:r?.disableCookieCache||t.query?.disableCookieCache,disableRefresh:r?.disableRefresh||t.query?.disableRefresh}}).catch(()=>null);if(!n)return t.context.session=null,null;if(n.headers)n.headers.forEach((o,i)=>{let s=i.toLowerCase();if(s==="cache-control"||s==="pragma")return;if(s==="set-cookie")t.responseHeaders.append(i,o);else t.responseHeaders.set(i,o)});return t.context.session=n.response,n.response},Td=async(t)=>{if(!St(t))return ee(t);return t.context.session=null,ee(t,{disableCookieCache:!0})},$r=Cn(async(t)=>{let r=await ee(t);if(!r?.session)throw U.from("UNAUTHORIZED",{message:"Unauthorized",code:"UNAUTHORIZED"});return{session:r}}),Qe=Cn(async(t)=>{let r=await Td(t);if(!r?.session)throw U.from("UNAUTHORIZED",{message:"Unauthorized",code:"UNAUTHORIZED"});return{session:r}}),Ng=Cn(async(t)=>{let r=await ee(t);if(!r?.session&&(t.request||t.headers))throw U.from("UNAUTHORIZED",{message:"Unauthorized",code:"UNAUTHORIZED"});return{session:r}}),po=Cn(async(t)=>{let r=await ee(t);if(!r?.session)throw U.from("UNAUTHORIZED",{message:"Unauthorized",code:"UNAUTHORIZED"});if(t.context.sessionConfig.freshAge!==0){let n=new Date(r.session.createdAt).getTime(),o=t.context.sessionConfig.freshAge*1000;if(Date.now()-n>=o)throw U.from("FORBIDDEN",Ae.SESSION_NOT_FRESH)}return{session:r}}),Id=()=>Pe("/list-sessions",{method:"GET",operationId:"listUserSessions",use:[po],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(t)=>{try{let r=(await t.context.internalAdapter.listSessions(t.context.session.user.id,{onlyActiveSessions:!0})).filter((n)=>n.expiresAt>new Date);return t.json(r.map((n)=>we(t.context.options,n)))}catch(r){throw t.context.logger.error(r),t.error("INTERNAL_SERVER_ERROR")}}),Ud=Pe("/revoke-session",{method:"POST",body:l({token:e().meta({description:"The token to revoke"})}),use:[Qe],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(t)=>{let r=t.body.token;if((await t.context.internalAdapter.findSession(r))?.session.userId===t.context.session.user.id)try{await t.context.internalAdapter.deleteSession(r)}catch(n){throw t.context.logger.error(n&&typeof n==="object"&&"name"in n?n.name:"",n),U.from("INTERNAL_SERVER_ERROR",{message:"Internal Server Error",code:"INTERNAL_SERVER_ERROR"})}return t.json({status:!0})}),Cd=Pe("/revoke-sessions",{method:"POST",use:[Qe],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(t)=>{try{await t.context.internalAdapter.deleteUserSessions(t.context.session.user.id)}catch(r){throw t.context.logger.error(r&&typeof r==="object"&&"name"in r?r.name:"",r),U.from("INTERNAL_SERVER_ERROR",{message:"Internal Server Error",code:"INTERNAL_SERVER_ERROR"})}return t.json({status:!0})}),Od=Pe("/revoke-other-sessions",{method:"POST",requireHeaders:!0,use:[Qe],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(t)=>{let r=t.context.session;if(!r.user)throw U.from("UNAUTHORIZED",{message:"Unauthorized",code:"UNAUTHORIZED"});let n=(await t.context.internalAdapter.listSessions(r.user.id)).filter((o)=>o.expiresAt>new Date).filter((o)=>o.token!==t.context.session.session.token);return await Promise.all(n.map((o)=>t.context.internalAdapter.deleteSession(o.token))),t.json({status:!0})});function ho(t){return t}async function ns(t,r,n){let o={tokens:r,profile:n},i=t.accountSubject,s=await i(o),a=String(s);if(typeof s==="number"&&!Number.isFinite(s)||a.trim().length===0||a==="undefined"||a==="null")throw new te("OAUTH_ACCOUNT_SUBJECT_INVALID");return{providerId:t.id,accountId:a}}async function mo(t,r,n){try{return await ns(t,r,n)}catch{throw U.from("UNAUTHORIZED",Ae.FAILED_TO_GET_USER_INFO)}}var he={NO_CODE:"no_code",PROVIDER_NOT_FOUND:"oauth_provider_not_found",ISSUER_MISSING:"issuer_missing",ISSUER_MISMATCH:"issuer_mismatch",INVALID_CODE:"invalid_code",NONCE_BINDING_MISSING:"nonce_binding_missing",UNABLE_TO_GET_USER_INFO:"unable_to_get_user_info",NO_CALLBACK_URL:"no_callback_url",UNABLE_TO_LINK_ACCOUNT:"unable_to_link_account",EMAIL_DOES_NOT_MATCH:"email_does_not_match",ACCOUNT_ALREADY_LINKED_TO_DIFFERENT_USER:"account_already_linked_to_different_user",EMAIL_NOT_FOUND:"email_not_found",EMAIL_NOT_VERIFIED:"email_not_verified"},qg="https://www.better-auth.com/docs/concepts/oauth#handling-providers-without-email";function en(t,r,n,o){let i=new URLSearchParams({error:n});if(o)i.set("error_description",o);let s=$e(r,i);throw t.redirect(s)}function wr(t,r){return`${r?.source==="generic"?`Generic OAuth provider "${t}"`:`Provider "${t}"`} did not return an email${r?.source==="id_token"?" in the id token":""}. Either request the provider's email scope, or create a placeholder via \`mapProfileToUser\`. See ${qg}`}function Vt(t,r){if(typeof t==="string")t=new TextEncoder().encode(t);if(typeof r==="string")r=new TextEncoder().encode(r);let n=new Uint8Array(t),o=new Uint8Array(r),i=n.length^o.length,s=Math.max(n.length,o.length);for(let a=0;a<s;a++)i|=(a<n.length?n[a]:0)^(a<o.length?o[a]:0);return i===0}var _e=xl("a-z","0-9","A-Z","-_");/*! noble-ciphers - MIT License (c) 2023 Paul Miller (paulmillr.com) */function os(t){return t instanceof Uint8Array||ArrayBuffer.isView(t)&&t.constructor.name==="Uint8Array"&&"BYTES_PER_ELEMENT"in t&&t.BYTES_PER_ELEMENT===1}var wo=(t)=>t?`"${t}" `:"";function yo(t,r=""){if(typeof t!=="boolean")throw TypeError(wo(r)+"expected boolean, got type="+typeof t);return t}function pt(t,r=""){if(typeof t!=="number")throw TypeError(wo(r)+"expected number, got "+typeof t);if(!Number.isSafeInteger(t)||t<0)throw RangeError(wo(r)+"expected integer >= 0, got "+t);return t}function de(t,r,n=""){if(os(t)&&(r===void 0||t.length===r))return t;if(r!==void 0)pt(r,"length");let o=os(t),i=r!==void 0?` of length ${r}`:"",s=o?`length=${t.length}`:`type=${typeof t}`,a=wo(n)+"expected Uint8Array"+i+", got "+s;if(!o)throw TypeError(a);throw RangeError(a)}var Dd=(t,r)=>{if(t===null||typeof t!=="object"||Array.isArray(t))throw TypeError(r==="object"?"expected valid options object":`"${r}" expected object, got type=${typeof t}`)};function is(t,r=!0){if(t.destroyed)throw Error("hash was destroyed");if(r&&t.finished)throw Error("digest() was already called")}function Pd(t,r){de(t,void 0,"output");let n=r.outputLen;if(!(t.length>=n))throw RangeError('"output" expected length >= '+n)}function rt(t){return new Uint32Array(t.buffer,t.byteOffset,Math.floor(t.byteLength/4))}function ze(...t){for(let r=0;r<t.length;r++)t[r].fill(0)}function jg(t){return new DataView(t.buffer,t.byteOffset,t.byteLength)}var He=(()=>new Uint8Array(new Uint32Array([287454020]).buffer)[0]===68)();function Bg(t){return t<<24&4278190080|t<<8&16711680|t>>>8&65280|t>>>24&255}function Mg(t){for(let r=0;r<t.length;r++)t[r]=Bg(t[r]);return t}var Ne=He?(t)=>t:Mg,xd=(()=>typeof Uint8Array.from([]).toHex==="function"&&typeof Uint8Array.fromHex==="function")(),Fg=Array.from({length:256},(t,r)=>r.toString(16).padStart(2,"0"));function zd(t){if(de(t),xd)return t.toHex();let r="";for(let n=0;n<t.length;n++)r+=Fg[t[n]];return r}function Ld(t){return t>=48&&t<=57?t-48:t>=65&&t<=70?t-55:t>=97&&t<=102?t-87:void 0}function Nd(t){if(typeof t!=="string")throw TypeError("hex string expected, got "+typeof t);if(xd)try{return Uint8Array.fromHex(t)}catch(i){if(i instanceof SyntaxError)throw RangeError(i.message);throw i}let r=t.length,n=r/2;if(r%2)throw RangeError("hex string expected, got unpadded hex of length "+r);let o=new Uint8Array(n);for(let i=0,s=0;i<n;i++,s+=2){let a=Ld(t.charCodeAt(s)),c=Ld(t.charCodeAt(s+1));if(a===void 0||c===void 0){let d=t[s]+t[s+1];throw RangeError('hex string expected, got non-hex character "'+d+'" at index '+s)}o[i]=a*16+c}return o}function qd(t){if(typeof t!=="string")throw TypeError("string expected");return new Uint8Array(new TextEncoder().encode(t))}function jd(t,r){if(!t.byteLength||!r.byteLength)return!1;return t.buffer===r.buffer&&t.byteOffset<r.byteOffset+r.byteLength&&r.byteOffset<t.byteOffset+t.byteLength}function Bd(t,r){if(jd(t,r)&&t.byteOffset<r.byteOffset)throw Error("complex overlap of input and output is not supported")}function Zg(...t){let r=0;for(let o=0;o<t.length;o++){let i=t[o];de(i),r+=i.length}let n=new Uint8Array(r);for(let o=0,i=0;o<t.length;o++){let s=t[o];n.set(s,i),i+=s.length}return n}function $d(t,r){return Dd(t,"defaults"),Dd(r,"opts"),Object.assign(t,r)}function Md(t,r){if(t=de(t),r=de(r),t.length!==r.length)return!1;let n=0;for(let o=0;o<t.length;o++)n|=t[o]^r[o];return n===0}function Hd(t,r,n){let o=r,i=n||(()=>[]),s=(c,d)=>o(d,...i(c)).update(c).digest(),a=o(new Uint8Array(t),...i(new Uint8Array(0)));return s.outputLen=a.outputLen,s.blockLen=a.blockLen,s.create=(c,...d)=>o(c,...d),s}var Vd=(t,r)=>{function n(o,...i){if(de(o,void 0,"key"),t.nonceLength!==void 0){let p=i[0];de(p,t.varSizeNonce?void 0:t.nonceLength,"nonce")}let s=t.tagLength,a=t.nonceLength!==void 0?1:0;if(!t.withAAD){for(let p=a;p<i.length;p++)if(os(i[p]))throw Error("AAD not supported")}if(t.withAAD&&i[a]!==void 0)de(i[a],void 0,"AAD");let c=r(o,...i),d=(p,h)=>{if(h!==void 0){if(p!==2)throw Error("cipher output not supported");de(h,void 0,"output")}},u=!1;return{encrypt(p,h){if(u)throw Error("cannot encrypt() twice with same key + nonce");return u=!0,de(p,void 0,"data"),d(c.encrypt.length,h),c.encrypt(p,h)},decrypt(p,h){if(de(p,void 0,"data"),s&&p.length<s)throw Error('"ciphertext" expected length >= tagLength='+s);return d(c.decrypt.length,h),c.decrypt(p,h)}}}return Object.assign(n,t),n};function tn(t,r,n=!0){if(r===void 0)return new Uint8Array(t);if(de(r,t,"output"),n&&!rn(r))throw Error("invalid output, must be aligned");return r}function Fd(t,r,n){pt(t),pt(r),yo(n);let o=new Uint8Array(16),i=jg(o);return i.setBigUint64(0,BigInt(r),n),i.setBigUint64(8,BigInt(t),n),o}function rn(t){return t.byteOffset%4===0}function yr(t){return Uint8Array.from(de(t))}function Kd(t=32){pt(t,"bytesLength");let r=typeof globalThis==="object"?globalThis.crypto:null;if(typeof r?.getRandomValues!=="function")throw Error("crypto.getRandomValues must be defined");if(t>65536)throw RangeError(`"bytesLength" expected <= 65536, got ${t}`);return r.getRandomValues(new Uint8Array(t))}function ss(t,r=Kd){if(typeof t!=="function")throw TypeError('"fn" expected cipher constructor, got type='+typeof t);if(typeof r!=="function")throw TypeError('"randomBytes_" expected function, got type='+typeof r);let{nonceLength:n}=t;pt(n,"fn.nonceLength");let o=(s,a,c)=>{let d=Zg(s,a);if(!jd(c,a))a.fill(0);return d},i=(s,...a)=>({encrypt(c){de(c,void 0,"data");let d=r(n),u=t(s,d,...a).encrypt(c);if(u instanceof Promise)return u.then((f)=>o(d,f,c));return o(d,u,c)},decrypt(c){de(c,void 0,"data");let d=c.subarray(0,n),u=c.subarray(n);return t(s,d,...a).decrypt(u)}});if("blockSize"in t)i.blockSize=t.blockSize;if("tagLength"in t)i.tagLength=t.tagLength;if("withAAD"in t)i.withAAD=t.withAAD;return i}var Jd=(t)=>Uint8Array.from(t.split(""),(r)=>r.charCodeAt(0)),Yg=(()=>Ne(rt(Jd("expand 16-byte k"))))(),Xg=(()=>Ne(rt(Jd("expand 32-byte k"))))();function ne(t,r){return t<<r|t>>>32-r}var nn=64,ew=16,as=(()=>4294967295)(),Wd=Uint32Array.of();function tw(t,r,n,o,i,s,a,c){let d=i.length,u=new Uint8Array(nn),f=rt(u),p=He&&rn(i)&&rn(s),h=p?rt(i):Wd,m=p?rt(s):Wd;if(!He){for(let w=0;w<d;a++){if(t(r,n,o,f,a,c),Ne(f),a>=as)throw Error("arx: counter overflow");let y=Math.min(nn,d-w);for(let I=0,R;I<y;I++)R=w+I,s[R]=i[R]^u[I];w+=y}return}for(let w=0;w<d;a++){if(t(r,n,o,f,a,c),a>=as)throw Error("arx: counter overflow");let y=Math.min(nn,d-w);if(p&&y===nn){let I=w/4;if(w%4!==0)throw Error("arx: invalid block position");for(let R=0,b;R<ew;R++)b=I+R,m[b]=h[b]^f[R];w+=nn;continue}for(let I=0,R;I<y;I++)R=w+I,s[R]=i[R]^u[I];w+=y}}function Qd(t,r){let{allowShortKeys:n,extendNonceFn:o,counterLength:i,counterRight:s,rounds:a}=$d({allowShortKeys:!1,counterLength:8,counterRight:!1,rounds:20},r);if(typeof t!=="function")throw Error("core must be a function");return pt(i),pt(a),yo(s),yo(n),(c,d,u,f,p=0)=>{de(c,void 0,"key"),de(d,void 0,"nonce"),de(u,void 0,"data");let h=u.length,m=f!==void 0;if(f=tn(h,f,!1),m)Bd(u,f);if(pt(p),p<0||p>=as)throw Error("arx: counter overflow");let w=[],y=c.length,I,R;if(y===32)w.push(I=yr(c)),R=Xg;else if(y===16&&n)I=new Uint8Array(32),I.set(c),I.set(c,16),R=Yg,w.push(I);else throw de(c,32,"arx key"),Error("invalid key size");if(!He||!rn(d))w.push(d=yr(d));let b=rt(I);if(o){if(d.length!==24)throw Error("arx: extended nonce must be 24 bytes");let S=d.subarray(0,16);if(He)o(R,b,rt(S),b);else{let C=Ne(Uint32Array.from(R));o(C,b,rt(S),b),ze(C),Ne(b)}d=d.subarray(16)}else if(!He)Ne(b);let O=16-i;if(O!==d.length)throw Error(`arx: nonce must be ${O} or 16 bytes`);if(O!==12){let S=new Uint8Array(12);S.set(d,s?0:12-d.length),d=S,w.push(d)}let g=Ne(rt(d));try{return tw(t,R,b,g,u,f,p,a),f}finally{ze(...w)}}}function be(t,r){return t[r++]&255|(t[r++]&255)<<8}class Gd{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(t){t=yr(de(t,32,"key"));let r=be(t,0),n=be(t,2),o=be(t,4),i=be(t,6),s=be(t,8),a=be(t,10),c=be(t,12),d=be(t,14);this.r[0]=r&8191,this.r[1]=(r>>>13|n<<3)&8191,this.r[2]=(n>>>10|o<<6)&7939,this.r[3]=(o>>>7|i<<9)&8191,this.r[4]=(i>>>4|s<<12)&255,this.r[5]=s>>>1&8190,this.r[6]=(s>>>14|a<<2)&8191,this.r[7]=(a>>>11|c<<5)&8065,this.r[8]=(c>>>8|d<<8)&8191,this.r[9]=d>>>5&127;for(let u=0;u<8;u++)this.pad[u]=be(t,16+2*u)}process(t,r,n=!1){let o=n?0:2048,{h:i,r:s}=this,a=s[0],c=s[1],d=s[2],u=s[3],f=s[4],p=s[5],h=s[6],m=s[7],w=s[8],y=s[9],I=be(t,r+0),R=be(t,r+2),b=be(t,r+4),O=be(t,r+6),g=be(t,r+8),S=be(t,r+10),C=be(t,r+12),z=be(t,r+14),L=i[0]+(I&8191),x=i[1]+((I>>>13|R<<3)&8191),P=i[2]+((R>>>10|b<<6)&8191),j=i[3]+((b>>>7|O<<9)&8191),B=i[4]+((O>>>4|g<<12)&8191),H=i[5]+(g>>>1&8191),q=i[6]+((g>>>14|S<<2)&8191),J=i[7]+((S>>>11|C<<5)&8191),Q=i[8]+((C>>>8|z<<8)&8191),G=i[9]+(z>>>5|o),M=0,Y=M+L*a+x*(5*y)+P*(5*w)+j*(5*m)+B*(5*h);M=Y>>>13,Y&=8191,Y+=H*(5*p)+q*(5*f)+J*(5*u)+Q*(5*d)+G*(5*c),M+=Y>>>13,Y&=8191;let Z=M+L*c+x*a+P*(5*y)+j*(5*w)+B*(5*m);M=Z>>>13,Z&=8191,Z+=H*(5*h)+q*(5*p)+J*(5*f)+Q*(5*u)+G*(5*d),M+=Z>>>13,Z&=8191;let re=M+L*d+x*c+P*a+j*(5*y)+B*(5*w);M=re>>>13,re&=8191,re+=H*(5*m)+q*(5*h)+J*(5*p)+Q*(5*f)+G*(5*u),M+=re>>>13,re&=8191;let ie=M+L*u+x*d+P*c+j*a+B*(5*y);M=ie>>>13,ie&=8191,ie+=H*(5*w)+q*(5*m)+J*(5*h)+Q*(5*p)+G*(5*f),M+=ie>>>13,ie&=8191;let qe=M+L*f+x*u+P*d+j*c+B*a;M=qe>>>13,qe&=8191,qe+=H*(5*y)+q*(5*w)+J*(5*m)+Q*(5*h)+G*(5*p),M+=qe>>>13,qe&=8191;let gt=M+L*p+x*f+P*u+j*d+B*c;M=gt>>>13,gt&=8191,gt+=H*a+q*(5*y)+J*(5*w)+Q*(5*m)+G*(5*h),M+=gt>>>13,gt&=8191;let ct=M+L*h+x*p+P*f+j*u+B*d;M=ct>>>13,ct&=8191,ct+=H*c+q*a+J*(5*y)+Q*(5*w)+G*(5*m),M+=ct>>>13,ct&=8191;let Ke=M+L*m+x*h+P*p+j*f+B*u;M=Ke>>>13,Ke&=8191,Ke+=H*d+q*c+J*a+Q*(5*y)+G*(5*w),M+=Ke>>>13,Ke&=8191;let wt=M+L*w+x*m+P*h+j*p+B*f;M=wt>>>13,wt&=8191,wt+=H*u+q*d+J*c+Q*a+G*(5*y),M+=wt>>>13,wt&=8191;let ar=M+L*y+x*w+P*m+j*h+B*p;M=ar>>>13,ar&=8191,ar+=H*f+q*u+J*d+Q*c+G*a,M+=ar>>>13,ar&=8191,M=(M<<2)+M|0,M=M+Y|0,Y=M&8191,M=M>>>13,Z+=M,i[0]=Y,i[1]=Z,i[2]=re,i[3]=ie,i[4]=qe,i[5]=gt,i[6]=ct,i[7]=Ke,i[8]=wt,i[9]=ar}finalize(){let{h:t,pad:r}=this,n=new Uint16Array(10),o=t[1]>>>13;t[1]&=8191;for(let a=2;a<10;a++)t[a]+=o,o=t[a]>>>13,t[a]&=8191;t[0]+=o*5,o=t[0]>>>13,t[0]&=8191,t[1]+=o,o=t[1]>>>13,t[1]&=8191,t[2]+=o,n[0]=t[0]+5,o=n[0]>>>13,n[0]&=8191;for(let a=1;a<10;a++)n[a]=t[a]+o,o=n[a]>>>13,n[a]&=8191;n[9]-=8192;let i=(o^1)-1;for(let a=0;a<10;a++)n[a]&=i;i=~i;for(let a=0;a<10;a++)t[a]=t[a]&i|n[a];t[0]=(t[0]|t[1]<<13)&65535,t[1]=(t[1]>>>3|t[2]<<10)&65535,t[2]=(t[2]>>>6|t[3]<<7)&65535,t[3]=(t[3]>>>9|t[4]<<4)&65535,t[4]=(t[4]>>>12|t[5]<<1|t[6]<<14)&65535,t[5]=(t[6]>>>2|t[7]<<11)&65535,t[6]=(t[7]>>>5|t[8]<<8)&65535,t[7]=(t[8]>>>8|t[9]<<5)&65535;let s=t[0]+r[0];t[0]=s&65535;for(let a=1;a<8;a++)s=(t[a]+r[a]|0)+(s>>>16)|0,t[a]=s&65535;ze(n)}update(t){is(this),de(t),t=yr(t);let{buffer:r,blockLen:n}=this,o=t.length;for(let i=0;i<o;){let s=Math.min(n-this.pos,o-i);if(s===n){for(;n<=o-i;i+=n)this.process(t,i);continue}if(r.set(t.subarray(i,i+s),this.pos),this.pos+=s,i+=s,this.pos===n)this.process(r,0,!1),this.pos=0}return this}destroy(){this.destroyed=!0,ze(this.h,this.r,this.buffer,this.pad)}digestInto(t){is(this),Pd(t,this),this.finished=!0;let{buffer:r,h:n}=this,{pos:o}=this;if(o){r[o++]=1;for(;o<16;o++)r[o]=0;this.process(r,0,!0)}this.finalize();let i=0;for(let s=0;s<8;s++)t[i++]=n[s]>>>0,t[i++]=n[s]>>>8}digest(){let{buffer:t,outputLen:r}=this;this.digestInto(t);let n=t.slice(0,r);return this.destroy(),n}}var Zd=Hd(32,(t)=>new Gd(t));function eu(t,r,n,o,i,s=20){let a=t[0],c=t[1],d=t[2],u=t[3],f=r[0],p=r[1],h=r[2],m=r[3],w=r[4],y=r[5],I=r[6],R=r[7],b=i,O=n[0],g=n[1],S=n[2],C=a,z=c,L=d,x=u,P=f,j=p,B=h,H=m,q=w,J=y,Q=I,G=R,M=b,Y=O,Z=g,re=S;for(let qe=0;qe<s;qe+=2)C=C+P|0,M=ne(M^C,16),q=q+M|0,P=ne(P^q,12),C=C+P|0,M=ne(M^C,8),q=q+M|0,P=ne(P^q,7),z=z+j|0,Y=ne(Y^z,16),J=J+Y|0,j=ne(j^J,12),z=z+j|0,Y=ne(Y^z,8),J=J+Y|0,j=ne(j^J,7),L=L+B|0,Z=ne(Z^L,16),Q=Q+Z|0,B=ne(B^Q,12),L=L+B|0,Z=ne(Z^L,8),Q=Q+Z|0,B=ne(B^Q,7),x=x+H|0,re=ne(re^x,16),G=G+re|0,H=ne(H^G,12),x=x+H|0,re=ne(re^x,8),G=G+re|0,H=ne(H^G,7),C=C+j|0,re=ne(re^C,16),Q=Q+re|0,j=ne(j^Q,12),C=C+j|0,re=ne(re^C,8),Q=Q+re|0,j=ne(j^Q,7),z=z+B|0,M=ne(M^z,16),G=G+M|0,B=ne(B^G,12),z=z+B|0,M=ne(M^z,8),G=G+M|0,B=ne(B^G,7),L=L+H|0,Y=ne(Y^L,16),q=q+Y|0,H=ne(H^q,12),L=L+H|0,Y=ne(Y^L,8),q=q+Y|0,H=ne(H^q,7),x=x+P|0,Z=ne(Z^x,16),J=J+Z|0,P=ne(P^J,12),x=x+P|0,Z=ne(Z^x,8),J=J+Z|0,P=ne(P^J,7);let ie=0;o[ie++]=a+C|0,o[ie++]=c+z|0,o[ie++]=d+L|0,o[ie++]=u+x|0,o[ie++]=f+P|0,o[ie++]=p+j|0,o[ie++]=h+B|0,o[ie++]=m+H|0,o[ie++]=w+q|0,o[ie++]=y+J|0,o[ie++]=I+Q|0,o[ie++]=R+G|0,o[ie++]=b+M|0,o[ie++]=O+Y|0,o[ie++]=g+Z|0,o[ie++]=S+re|0}function rw(t,r,n,o){let i=He?t:Ne(t.slice(0,4)),s=He?r:Ne(r.slice(0,8)),a=He?n:Ne(n.slice(0,4)),c=new Uint32Array(16);eu(i,s,a.subarray(1),c,a[0]);let d=0;if(o[d++]=c[0]-i[0]|0,o[d++]=c[1]-i[1]|0,o[d++]=c[2]-i[2]|0,o[d++]=c[3]-i[3]|0,o[d++]=c[12]-a[0]|0,o[d++]=c[13]-a[1]|0,o[d++]=c[14]-a[2]|0,o[d++]=c[15]-a[3]|0,Ne(o),!He)ze(i,s,a);ze(c)}var nw=Qd(eu,{counterRight:!1,counterLength:8,extendNonceFn:rw,allowShortKeys:!1});var ow=new Uint8Array(16),Yd=(t,r)=>{t.update(r);let n=r.length%16;if(n)t.update(ow.subarray(n))},iw=new Uint8Array(32);function Xd(t,r,n,o,i){if(i!==void 0)de(i,void 0,"AAD");let s=t(r,n,iw),a=Fd(o.length,i?i.length:0,!0),c=Zd.create(s);if(i)Yd(c,i);Yd(c,o),c.update(a);let d=c.digest();return ze(s,a),d}var sw=(t)=>(r,n,o)=>({encrypt(s,a){let c=s.length;a=tn(c+16,a,!1),a.set(s);let d=a.subarray(0,-16);t(r,n,d,d,1);let u=Xd(t,r,n,d,o);return a.set(u,c),ze(u),a},decrypt(s,a){a=tn(s.length-16,a,!1);let c=s.subarray(0,-16),d=s.subarray(-16),u=Xd(t,r,n,c,o);if(!Md(d,u))throw ze(u),Error("invalid tag");return a.set(s.subarray(0,-16)),t(r,n,a,a,1),ze(u),a}});var fs=Vd({blockSize:64,nonceLength:24,tagLength:16,withAAD:!0},sw(nw));var ru={name:"HMAC",hash:"SHA-256"},nu="$ba$";function aw(t){if(!t.startsWith(nu))return null;let r=4,n=t.indexOf("$",r);if(n===-1)return null;let o=parseInt(t.slice(r,n),10);if(!Number.isInteger(o)||o<0)return null;return{version:o,ciphertext:t.slice(n+1)}}function cw(t,r){return`${nu}${t}$${r}`}async function tu(t,r){let n=await cs("SHA-256").digest(t),o=qd(r);return zd(ss(fs)(new Uint8Array(n)).encrypt(o))}async function ps(t,r){let n=await cs("SHA-256").digest(t),o=Nd(r),i=ss(fs)(new Uint8Array(n));return new TextDecoder().decode(i.decrypt(o))}var nt=async({key:t,data:r})=>{if(typeof t==="string")return tu(t,r);let n=t.keys.get(t.currentVersion);if(!n)throw Error(`Secret version ${t.currentVersion} not found in keys`);let o=await tu(n,r);return cw(t.currentVersion,o)},ot=async({key:t,data:r})=>{if(typeof t==="string")return ps(t,r);let n=aw(r);if(n){let o=t.keys.get(n.version);if(!o)throw Error(`Secret version ${n.version} not found in keys (key may have been retired)`);return ps(o,n.ciphertext)}if(t.legacySecret)return ps(t.legacySecret,r);throw Error("Cannot decrypt legacy bare-hex payload: no legacy secret available. Set BETTER_AUTH_SECRET for backwards compatibility.")},dw=async(t)=>{let r=typeof t==="string"?new TextEncoder().encode(t):t;return await De().importKey("raw",r,ru,!1,["sign","verify"])},on=async(t,r)=>{let n=await dw(r),o=await De().sign(ru.name,n,new TextEncoder().encode(t));return btoa(String.fromCharCode(...new Uint8Array(o)))};function uw(t){if(t.startsWith("$ba$"))return!0;return t.length%2===0&&/^[0-9a-f]+$/i.test(t)}function _o(t,r){if(!t)return t;if(r.options.account?.encryptOAuthTokens){if(!uw(t))return t;return ot({key:r.secretConfig,data:t})}return t}function me(t,r){if(r.options.account?.encryptOAuthTokens&&t)return nt({key:r.secretConfig,data:t});return t}function Rt(t){if(!t.callbackPath)return`/callback/${t.id}`;return t.callbackPath.startsWith("/")?t.callbackPath:`/${t.callbackPath}`}function Tt(t){if(!t)return;try{return t.clone()}catch{return new Request(t.url,{cache:t.cache,credentials:t.credentials,headers:t.headers,integrity:t.integrity,keepalive:t.keepalive,method:t.method,mode:t.mode,redirect:t.redirect,referrer:t.referrer,referrerPolicy:t.referrerPolicy,signal:t.signal})}}async function Se(t,r,n,o=3600,i){return await $n({email:r.toLowerCase(),updateTo:n?.toLowerCase(),...i},t,o)}async function hs(t,r){if(!t.context.options.emailVerification?.sendVerificationEmail)throw t.context.logger.error("Verification email isn't enabled."),U.from("BAD_REQUEST",Ae.VERIFICATION_EMAIL_NOT_ENABLED);let n=await Se(t.context.secret,r.email,void 0,t.context.options.emailVerification?.expiresIn),o=t.body.callbackURL?encodeURIComponent(t.body.callbackURL):encodeURIComponent("/"),i=`${t.context.baseURL}/verify-email?token=${n}&callbackURL=${o}`;await t.context.options.emailVerification.sendVerificationEmail({user:r,url:i,token:n},t.request)}var ou=Pe("/send-verification-email",{method:"POST",operationId:"sendVerificationEmail",cloneRequest:!0,body:l({email:In().meta({description:"The email to send the verification email to"}),callbackURL:e().meta({description:"The URL to use for email verification callback"}).optional()}),metadata:{openapi:{operationId:"sendVerificationEmail",description:"Send a verification email to the user",requestBody:{content:{"application/json":{schema:{type:"object",properties:{email:{type:"string",description:"The email to send the verification email to",example:"user@example.com"},callbackURL:{type:"string",description:"The URL to use for email verification callback",example:"https://example.com/callback",nullable:!0}},required:["email"]}}}},responses:{"200":{description:"Success",content:{"application/json":{schema:{type:"object",properties:{status:{type:"boolean",description:"Indicates if the email was sent successfully",example:!0}}}}}},"400":{description:"Bad Request",content:{"application/json":{schema:{type:"object",properties:{message:{type:"string",description:"Error message",example:"Verification email isn't enabled"}}}}}}}}}},async(t)=>{if(!t.context.options.emailVerification?.sendVerificationEmail)throw t.context.logger.error("Verification email isn't enabled."),U.from("BAD_REQUEST",Ae.VERIFICATION_EMAIL_NOT_ENABLED);let{email:r}=t.body,n=await ee(t);if(!n){let i=Date.now(),s=await t.context.internalAdapter.findUserByEmail(r),a;if(!s||s.user.emailVerified)await Se(t.context.secret,r,void 0,t.context.options.emailVerification?.expiresIn);else try{await hs(t,s.user)}catch(d){a=d}let c=500-(Date.now()-i);if(c>0)await new Promise((d)=>setTimeout(d,c));if(a)throw a;return t.json({status:!0})}if(n?.user.email.toLowerCase()!==r.toLowerCase())throw U.from("BAD_REQUEST",Ae.EMAIL_MISMATCH);if(n?.user.emailVerified)throw U.from("BAD_REQUEST",Ae.EMAIL_ALREADY_VERIFIED);return await hs(t,n.user),t.json({status:!0})}),iu=Pe("/verify-email",{method:"GET",operationId:"verifyEmail",query:l({token:e().meta({description:"The token to verify the email"}),callbackURL:e().meta({description:"The URL to redirect to after email verification"}).optional()}),use:[bt((t)=>t.query.callbackURL)],metadata:{openapi:{description:"Verify the email of the user",parameters:[{name:"token",in:"query",description:"The token to verify the email",required:!0,schema:{type:"string"}},{name:"callbackURL",in:"query",description:"The URL to redirect to after email verification",required:!1,schema:{type:"string"}}],responses:{"200":{description:"Success",content:{"application/json":{schema:{type:"object",properties:{user:{type:"object",$ref:"#/components/schemas/User"},status:{type:"boolean",description:"Indicates if the email was verified successfully"}},required:["user","status"]}}}}}}}},async(t)=>{function r(c){if(t.query.callbackURL){let d=new URLSearchParams({error:c.code}),u=$e(t.query.callbackURL,d);throw t.redirect(u)}throw U.from("UNAUTHORIZED",c)}let{token:n}=t.query,o;try{o=await Hr(n,new TextEncoder().encode(t.context.secret),{algorithms:["HS256"]})}catch(c){if(c instanceof yi)return r(Ae.TOKEN_EXPIRED);return r(Ae.INVALID_TOKEN)}let i=l({email:In(),updateTo:e().optional(),requestType:e().optional()}).parse(o.payload),s=await t.context.internalAdapter.findUserByEmail(i.email);if(!s)return r(Ae.USER_NOT_FOUND);if(i.updateTo){let c=await ee(t);if(c&&c.user.email!==i.email)return r(Ae.INVALID_USER);switch(i.requestType){case"change-email-confirmation":{let d=await Se(t.context.secret,i.email,i.updateTo,t.context.options.emailVerification?.expiresIn,{requestType:"change-email-verification"}),u=t.query.callbackURL?encodeURIComponent(t.query.callbackURL):encodeURIComponent("/"),f=`${t.context.baseURL}/verify-email?token=${d}&callbackURL=${u}`;if(t.context.options.emailVerification?.sendVerificationEmail)await t.context.runInBackgroundOrAwait(t.context.options.emailVerification.sendVerificationEmail({user:{...s.user,email:i.updateTo},url:f,token:d},Tt(t.request)));if(t.query.callbackURL)throw t.redirect(t.query.callbackURL);return t.json({status:!0})}case"change-email-verification":{let d=c;if(!d){let f=await t.context.internalAdapter.createSession(s.user.id);if(!f)throw U.from("INTERNAL_SERVER_ERROR",Ae.FAILED_TO_CREATE_SESSION);d={session:f,user:s.user}}let u=await t.context.internalAdapter.updateUserByEmail(i.email,{email:i.updateTo,emailVerified:!0});if(t.context.options.emailVerification?.afterEmailVerification)await t.context.options.emailVerification.afterEmailVerification(u,t.request);if(await pe(t,{session:d.session,user:{...d.user,email:i.updateTo,emailVerified:!0}}),t.query.callbackURL)throw t.redirect(t.query.callbackURL);return t.json({status:!0,user:se(t.context.options,u)})}default:{let d=c;if(!d){let h=await t.context.internalAdapter.createSession(s.user.id);if(!h)throw U.from("INTERNAL_SERVER_ERROR",Ae.FAILED_TO_CREATE_SESSION);d={session:h,user:s.user}}let u=await t.context.internalAdapter.updateUserByEmail(i.email,{email:i.updateTo,emailVerified:!1}),f=await Se(t.context.secret,i.updateTo),p=t.query.callbackURL?encodeURIComponent(t.query.callbackURL):encodeURIComponent("/");if(t.context.options.emailVerification?.sendVerificationEmail)await t.context.runInBackgroundOrAwait(t.context.options.emailVerification.sendVerificationEmail({user:u,url:`${t.context.baseURL}/verify-email?token=${f}&callbackURL=${p}`,token:f},Tt(t.request)));if(await pe(t,{session:d.session,user:{...d.user,email:i.updateTo,emailVerified:!1}}),t.query.callbackURL)throw t.redirect(t.query.callbackURL);return t.json({status:!0,user:se(t.context.options,u)})}}}if(s.user.emailVerified){if(t.query.callbackURL)throw t.redirect(t.query.callbackURL);return t.json({status:!0,user:null})}if(t.context.options.emailVerification?.beforeEmailVerification)await t.context.options.emailVerification.beforeEmailVerification(s.user,t.request);let a=await t.context.internalAdapter.updateUserByEmail(i.email,{emailVerified:!0});if(t.context.options.emailVerification?.afterEmailVerification)await t.context.options.emailVerification.afterEmailVerification(a,t.request);if(t.context.options.emailVerification?.autoSignInAfterVerification){let c=await ee(t);if(!c||c.user.email!==i.email){let d=await t.context.internalAdapter.createSession(s.user.id);if(!d)throw U.from("INTERNAL_SERVER_ERROR",Ae.FAILED_TO_CREATE_SESSION);await pe(t,{session:d,user:{...s.user,emailVerified:!0}})}else await pe(t,{session:c.session,user:{...c.user,emailVerified:!0}})}if(t.query.callbackURL)throw t.redirect(t.query.callbackURL);return t.json({status:!0,user:null})});function ms(t){if(Array.isArray(t))return t.map((r)=>typeof r==="string"?r.trim():"").filter(Boolean);if(typeof t==="string")return t.trim().split(/\s+/).filter(Boolean);return[]}function sn(t){let r=(n)=>new Date(new Date().getTime()+n*1000);return{tokenType:t.token_type,accessToken:t.access_token,refreshToken:t.refresh_token,accessTokenExpiresAt:t.expires_in?r(t.expires_in):void 0,refreshTokenExpiresAt:t.refresh_token_expires_in?r(t.refresh_token_expires_in):void 0,scopes:ms(t.scope),idToken:t.id_token,raw:t}}function gs(t,r){let n=t?t.split(",").map((i)=>i.trim()).filter(Boolean):[],o=(r??[]).map((i)=>i.trim()).filter(Boolean);return[...new Set([...n,...o])].join(",")}function Re(t){let r=Array.isArray(t)?t[0]:t;return typeof r==="string"&&r.length>0?r:void 0}async function an(t){let r=new TextEncoder().encode(t),n=await crypto.subtle.digest("SHA-256",r);return ko.encode(new Uint8Array(n),{padding:!1})}var ws=["state","client_id","redirect_uri","response_type","code_challenge","code_challenge_method","nonce","scope"],Ft=new Set(ws);async function V({id:t,options:r,authorizationEndpoint:n,state:o,codeVerifier:i,scopes:s,claims:a,redirectURI:c,duration:d,prompt:u,accessType:f,responseType:p,display:h,loginHint:m,nonce:w,hd:y,responseMode:I,additionalParams:R,scopeJoiner:b}){r=typeof r==="function"?await r():r;let O=new URL(r.authorizationEndpoint||n);O.searchParams.set("response_type",p||"code");let g=Re(r.clientId);if(!g)throw Error("OAuth provider requires clientId");if(O.searchParams.set("client_id",g),O.searchParams.set("state",o),s?.length)O.searchParams.set("scope",s.join(b||" "));if(O.searchParams.set("redirect_uri",r.redirectURI||c),d&&O.searchParams.set("duration",d),h&&O.searchParams.set("display",h),m&&O.searchParams.set("login_hint",m),w&&O.searchParams.set("nonce",w),u&&O.searchParams.set("prompt",u),y&&O.searchParams.set("hd",y),f&&O.searchParams.set("access_type",f),I&&O.searchParams.set("response_mode",I),i){let S=await an(i);O.searchParams.set("code_challenge_method","S256"),O.searchParams.set("code_challenge",S)}if(a){let S=a.reduce((C,z)=>(C[z]=null,C),{});O.searchParams.set("claims",JSON.stringify({id_token:{email:null,email_verified:null,...S}}))}if(R)for(let[S,C]of Object.entries(R)){if(Ft.has(S))continue;O.searchParams.set(S,C)}return O}var cn=k(e(),e()).refine((t)=>!Object.keys(t).some((r)=>Ft.has(r)),{message:`additionalParams cannot include reserved OAuth parameters: ${ws.join(", ")}`}).meta({description:"Extra query parameters to append to the provider authorization URL (e.g. Cognito identity_provider, Google hd)."}).optional();var lw=/^Basic +(.*)$/i;function su(t){return new URLSearchParams({v:t}).toString().slice(2)}function au(t){let r=new URLSearchParams(`v=${t}`).get("v");if(r===null)throw Error("form-url-encoded value could not be decoded");return r}function ys(t,r){let n=`${su(t)}:${su(r)}`;return`Basic ${To.encode(n)}`}function _s(t){let r=t.match(lw);if(!r)throw Error("Authorization header is not a Basic credential");let n=r[1]??"",o=new TextDecoder().decode(To.decode(n)),i=o.indexOf(":");if(i===-1)throw Error("Basic credential is missing the client id/secret separator");let s=o.slice(0,i),a=o.slice(i+1);if(!s||!a)throw Error("Basic credential client id and secret must both be non-empty");return{clientId:au(s),clientSecret:au(a)}}var Kt=["RS256","RS384","RS512","PS256","PS384","PS512","ES256","ES384","ES512","EdDSA"];var Wt="urn:ietf:params:oauth:client-assertion-type:jwt-bearer";async function As({getClientAssertion:t,context:r}){return{client_assertion:await t(r),client_assertion_type:Wt}}var fw=class extends Error{constructor(t,r,n){super(r||t.toString(),{cause:n});this.status=t,this.statusText=r,this.error=n,Error.captureStackTrace(this,this.constructor)}},pw=async(t,r)=>{let n=r||{},o={onRequest:[r===null||r===void 0?void 0:r.onRequest],onResponse:[r===null||r===void 0?void 0:r.onResponse],onSuccess:[r===null||r===void 0?void 0:r.onSuccess],onError:[r===null||r===void 0?void 0:r.onError],onRetry:[r===null||r===void 0?void 0:r.onRetry]};if(!r||!(r===null||r===void 0?void 0:r.plugins))return{url:t,options:n,hooks:o};for(let f of(r===null||r===void 0?void 0:r.plugins)||[]){var i,s,a,c,d;if(f.init){var u;let p=await((u=f.init)===null||u===void 0?void 0:u.call(f,t.toString(),n));n=p.options||n,t=p.url}o.onRequest.push((i=f.hooks)===null||i===void 0?void 0:i.onRequest),o.onResponse.push((s=f.hooks)===null||s===void 0?void 0:s.onResponse),o.onSuccess.push((a=f.hooks)===null||a===void 0?void 0:a.onSuccess),o.onError.push((c=f.hooks)===null||c===void 0?void 0:c.onError),o.onRetry.push((d=f.hooks)===null||d===void 0?void 0:d.onRetry)}return{url:t,options:n,hooks:o}},cu=class{constructor(t){this.options=t}shouldAttemptRetry(t,r){if(this.options.shouldRetry)return Promise.resolve(t<this.options.attempts&&this.options.shouldRetry(r));return Promise.resolve(t<this.options.attempts)}getDelay(){return this.options.delay}},hw=class{constructor(t){this.options=t}shouldAttemptRetry(t,r){if(this.options.shouldRetry)return Promise.resolve(t<this.options.attempts&&this.options.shouldRetry(r));return Promise.resolve(t<this.options.attempts)}getDelay(t){return Math.min(this.options.maxDelay,this.options.baseDelay*2**t)}};function mw(t){if(typeof t==="number")return new cu({type:"linear",attempts:t,delay:1000});switch(t.type){case"linear":return new cu(t);case"exponential":return new hw(t);default:throw Error("Invalid retry strategy")}}var gw=["get","post","put","patch","delete"];function fu(t){if(!t.startsWith("@"))return{method:void 0,path:t};let r=t.indexOf("/"),n=t.slice(1,r===-1?void 0:r);if(!gw.includes(n))return{method:void 0,path:t};return{method:n,path:r===-1?t:t.slice(r+1)}}var ww=(t)=>t==="."||t==="..",yw=(t)=>t.split(":").map((r)=>encodeURIComponent(r)).join(":");function _w(t,r){let n=r.get(t);if(n===void 0)return yw(t);if(ww(n))throw TypeError("Path parameters cannot be reserved path segments");return encodeURIComponent(n)}function Aw(t,r){let{baseURL:n,params:o,query:i}=r||{query:{},params:{},baseURL:""},s=t.startsWith("http")?t.split("/").slice(0,3).join("/"):n||"",{path:a}=fu(t);if(a!==t)t=`/${a}`;if(!s.endsWith("/"))s+="/";let[c,d]=t.replace(s,"").split("?"),u=new URLSearchParams(d);for(let[h,m]of Object.entries(i||{})){if(m==null)continue;let w;if(typeof m==="string")w=m;else if(Array.isArray(m)){for(let y of m)u.append(h,y);continue}else w=JSON.stringify(m);u.set(h,w)}let f=new Map;if(o)if(Array.isArray(o)){let h=c.split("/").filter((m)=>m.startsWith(":"));for(let[m,w]of h.entries()){let y=o[m];f.set(w,String(y))}}else for(let[h,m]of Object.entries(o))f.set(`:${h}`,String(m));c=c.split("/").map((h)=>_w(h,f)).join("/"),c=c.replace(/^\/+/,"");let p=u.toString();if(p=p.length>0?`?${p}`.replace(/\+/g,"%20"):"",!s.startsWith("http"))return`${s}${c}${p}`;return new URL(`${c}${p}`,s)}var kw=async(t)=>{let r={},n=async(o)=>typeof o==="function"?await o():o;if(t===null||t===void 0?void 0:t.auth){if(t.auth.type==="Bearer"){let o=await n(t.auth.token);if(!o)return r;r.authorization=`Bearer ${o}`}else if(t.auth.type==="Basic"){let[o,i]=await Promise.all([n(t.auth.username),n(t.auth.password)]);if(!o||!i)return r;r.authorization=`Basic ${btoa(`${o}:${i}`)}`}else if(t.auth.type==="Custom"){let[o,i]=await Promise.all([n(t.auth.prefix),n(t.auth.value)]);if(!i)return r;r.authorization=`${o!==null&&o!==void 0?o:""} ${i}`}}return r},Ew=/^application\/(?:[\w!#$%&*.^`~-]*\+)?json(;.+)?$/i;function bw(t){let r=t.headers.get("content-type"),n=new Set(["image/svg","application/xml","application/xhtml","application/html"]);if(!r)return"json";let o=r.split(";").shift()||"";if(Ew.test(o))return"json";if(n.has(o)||o.startsWith("text/"))return"text";return"blob"}function vw(t){try{return JSON.parse(t),!0}catch(r){return!1}}function pu(t){if(t===void 0)return!1;let r=typeof t;if(r==="string"||r==="number"||r==="boolean"||r===null)return!0;if(r!=="object")return!1;if(Array.isArray(t))return!0;if(t.buffer)return!1;return t.constructor&&t.constructor.name==="Object"||typeof t.toJSON==="function"}function du(t){try{return JSON.parse(t)}catch(r){return t}}function uu(t){return typeof t==="function"}function Sw(t){if(t===null||t===void 0?void 0:t.customFetchImpl)return t.customFetchImpl;if(typeof globalThis<"u"&&uu(globalThis.fetch))return globalThis.fetch;if(typeof window<"u"&&uu(window.fetch))return window.fetch;throw Error("No fetch implementation found")}function Rw(...t){let r={};for(let n of t){if(!n)continue;if(n instanceof Headers)n.forEach((o,i)=>{r[i]=o});else{let o=Array.isArray(n)?n:Object.entries(n);for(let[i,s]of o)if(s!==null&&s!==void 0)r[i]=s}}return r}async function Tw(t){let r=new Headers(Rw(t===null||t===void 0?void 0:t.headers,await kw(t)));if(!r.has("content-type")){let n=Iw(t===null||t===void 0?void 0:t.body);if(n)r.set("content-type",n)}return r}function Iw(t){if(pu(t))return"application/json";return null}function Uw(t){let r=t.get("content-type");return r?r.split(";")[0].trim().toLowerCase():null}function Cw(t,r){let{body:n}=t;if(!n)return null;if(!pu(n))return n;if(typeof n==="string")return n;if(Uw(r)==="application/x-www-form-urlencoded")return new URLSearchParams(n).toString();return JSON.stringify(n)}function Ow(t,r){if(r===null||r===void 0?void 0:r.method)return r.method.toUpperCase();let{method:n}=fu(t);if(n)return n.toUpperCase();return(r===null||r===void 0?void 0:r.body)?"POST":"GET"}function Dw(t,r){let n;if(!(t===null||t===void 0?void 0:t.signal)&&(t===null||t===void 0?void 0:t.timeout))n=setTimeout(()=>r===null||r===void 0?void 0:r.abort(),t===null||t===void 0?void 0:t.timeout);return{abortTimeout:n,clearTimeout:()=>{if(n)clearTimeout(n)}}}var Lw=class t extends Error{constructor(r,n){super(n||JSON.stringify(r,null,2));this.issues=r,Object.setPrototypeOf(this,t.prototype)}};async function Pw(t,r){let n=await t["~standard"].validate(r);if(n.issues)throw new Lw(n.issues);return n.value}function un(t){return un=typeof Symbol=="function"&&typeof Symbol.iterator=="symbol"?function(r){return typeof r}:function(r){return r&&typeof Symbol=="function"&&r.constructor===Symbol&&r!==Symbol.prototype?"symbol":typeof r},un(t)}function xw(t,r){if(un(t)!="object"||!t)return t;var n=t[Symbol.toPrimitive];if(n!==void 0){var o=n.call(t,r||"default");if(un(o)!="object")return o;throw TypeError("@@toPrimitive must return a primitive value.")}return(r==="string"?String:Number)(t)}function zw(t){var r=xw(t,"string");return un(r)=="symbol"?r:r+""}function Nw(t,r,n){return(r=zw(r))in t?Object.defineProperty(t,r,{value:n,enumerable:!0,configurable:!0,writable:!0}):t[r]=n,t}function lu(t,r){var n=Object.keys(t);if(Object.getOwnPropertySymbols){var o=Object.getOwnPropertySymbols(t);r&&(o=o.filter(function(i){return Object.getOwnPropertyDescriptor(t,i).enumerable})),n.push.apply(n,o)}return n}function Ce(t){for(var r=1;r<arguments.length;r++){var n=arguments[r]!=null?arguments[r]:{};r%2?lu(Object(n),!0).forEach(function(o){Nw(t,o,n[o])}):Object.getOwnPropertyDescriptors?Object.defineProperties(t,Object.getOwnPropertyDescriptors(n)):lu(Object(n)).forEach(function(o){Object.defineProperty(t,o,Object.getOwnPropertyDescriptor(n,o))})}return t}var Me=async(t,r)=>{var n,o,i;let{hooks:s,url:a,options:c}=await pw(t,r),d=Sw(c),u=new AbortController,f=(n=c.signal)!==null&&n!==void 0?n:u.signal,p=Aw(a,c),h=await Tw(c),m=Cw(c,h),w=Ow(a,c),y=Ce(Ce({},c),{},{url:p,headers:h,body:m,method:w,signal:f});for(let H of s.onRequest)if(H){let q=await H(y);if(typeof q==="object"&&q!==null)Object.assign(y,q)}if("pipeTo"in y&&typeof y.pipeTo==="function"||typeof(r===null||r===void 0||(o=r.body)===null||o===void 0?void 0:o.pipe)==="function"){if(!("duplex"in y))y.duplex="half"}let{clearTimeout:I}=Dw(c,u),R=await d(y.url,y);I();let b={response:R,request:y};for(let H of s.onResponse)if(H){var O;let q=await H(Ce(Ce({},b),{},{response:(r===null||r===void 0||(O=r.hookOptions)===null||O===void 0?void 0:O.cloneResponse)?R.clone():R}));if(q instanceof Response)R=q;else if(typeof q==="object"&&q!==null)R=q.response}if(R.ok){if(y.method==="HEAD")return{data:"",error:null};let H=bw(R),q={data:null,response:R,request:y};if(H==="json"||H==="text"){var g;let J=await R.text();q.data=await((g=y.jsonParser)!==null&&g!==void 0?g:du)(J)}else q.data=await R[H]();if(y===null||y===void 0?void 0:y.output){if(y.output&&!y.disableValidation)q.data=await Pw(y.output,q.data)}for(let J of s.onSuccess)if(J){var S;await J(Ce(Ce({},q),{},{response:(r===null||r===void 0||(S=r.hookOptions)===null||S===void 0?void 0:S.cloneResponse)?R.clone():R}))}if(r===null||r===void 0?void 0:r.throw)return q.data;return{data:q.data,error:null}}let C=(i=r===null||r===void 0?void 0:r.jsonParser)!==null&&i!==void 0?i:du,z=await R.text(),L=vw(z),x=L?await C(z):null,P={response:R,responseText:z,request:y,error:Ce(Ce({},x),{},{status:R.status,statusText:R.statusText})};for(let H of s.onError)if(H){var j;await H(Ce(Ce({},P),{},{response:(r===null||r===void 0||(j=r.hookOptions)===null||j===void 0?void 0:j.cloneResponse)?R.clone():R}))}if(r===null||r===void 0?void 0:r.retry){var B;let H=mw(r.retry),q=(B=r.retryAttempt)!==null&&B!==void 0?B:0;if(await H.shouldAttemptRetry(q,R)){for(let Q of s.onRetry)if(Q)await Q(b);let J=H.getDelay(q);return await new Promise((Q)=>setTimeout(Q,J)),await Me(t,Ce(Ce({},r),{},{retryAttempt:q+1}))}}if(r===null||r===void 0?void 0:r.throw)throw new fw(R.status,R.statusText,L?x:z);return{data:null,error:Ce(Ce({},x),{},{status:R.status,statusText:R.statusText})}};var qw=new Set([301,302,303,307,308]);function jw(t){return t.type==="opaqueredirect"||qw.has(t.status)}function hu(t){return new te(`The OAuth endpoint "${t}" returned an HTTP redirect. Server-side OAuth fetches refuse redirects to prevent SSRF; configure the final endpoint URL.`)}async function Qt(t,r){let n=!1,o=r?.onError,i=await Me(t,{...r,redirect:"manual",async onError(s){if(jw(s.response))n=!0;await o?.(s)}}).catch((s)=>{if(n)throw hu(t);throw s});if(n)throw hu(t);return i}function Bw(t,r){if(r==="basic")return{method:"client_secret_basic"};if(t.clientSecret)return{method:"client_secret_post"};return{method:"none"}}function ks(t,r,n){if(r.clientSecret||n.has("client_secret"))throw Error(`${t} token endpoint authentication cannot be combined with clientSecret`)}function Ao(t,r){if(r)t.set("client_id",r)}function gu(t,r){if(!r.clientSecret)throw Error(`${t} token endpoint authentication requires clientSecret`)}function Eo(t,r){if(!r)throw Error(`${t} token endpoint authentication requires clientId`)}function $w({body:t,options:r,clientId:n,requireClientSecret:o}){if(o)gu("client_secret_post",r);if(r.clientSecret)Eo("client_secret_post",n),Ao(t,n),t.set("client_secret",r.clientSecret)}function Mw({headers:t,options:r,clientId:n,body:o}){if(o.has("client_secret"))throw Error("client_secret_basic token endpoint authentication cannot be combined with client_secret body parameters");gu("client_secret_basic",r),Eo("client_secret_basic",n),t.authorization=ys(n,r.clientSecret)}function mu(t){if(t.has("client_assertion")!==t.has("client_assertion_type"))throw Error("client_assertion and client_assertion_type must both be provided")}async function bo({body:t,headers:r,options:n,tokenEndpoint:o,grantType:i,tokenEndpointAuth:s,authentication:a}){mu(t);let c=Re(n.clientId);if(t.has("client_assertion")){if(s)throw Error("client_assertion body parameters cannot be combined with tokenEndpointAuth");ks("private_key_jwt",n,t),Ao(t,c);return}let d=s??Bw(n,a);if(d.method==="custom"){await d.customizeRequest({body:t,headers:r,options:n,tokenEndpoint:o,grantType:i}),mu(t);return}if(d.method==="private_key_jwt"){if(ks(d.method,n,t),Eo(d.method,c),!o)throw Error("private_key_jwt token endpoint authentication requires tokenEndpoint");let u=await As({getClientAssertion:d.getClientAssertion,context:{clientId:c,tokenEndpoint:o,grantType:i}});Ao(t,c);for(let[f,p]of Object.entries(u))t.set(f,p);return}if(d.method==="none"){if(ks(d.method,n,t),i==="client_credentials")throw Error("none token endpoint authentication cannot be used with client_credentials grant");Eo(d.method,c),Ao(t,c);return}if(d.method==="client_secret_basic"){Mw({headers:r,options:n,clientId:c,body:t});return}$w({body:t,options:n,clientId:c,requireClientSecret:s?.method==="client_secret_post"})}var wu="dpop+jwt",za=["EdDSA","ES256","ES512","PS256","RS256"],Hw=300,Vw=512,Fw=new Set(["d","p","q","dp","dq","qi","oth","k"]);function Ss(){let t=new Map;return{reserve({key:r,expiresAt:n,now:o}){let i=o.getTime();for(let[s,a]of t)if(a<=i)t.delete(s);if(t.has(r))return!1;return t.set(r,n.getTime()),!0}}}function Ac(t){return{reserve:({key:r,expiresAt:n})=>t.reserveVerificationValue({identifier:`dpop-proof:${r}`,value:r,expiresAt:n})}}function ge(t,r){return Object.assign(Error(r),{code:t})}function So(t){return t instanceof Error&&"code"in t&&t.code==="invalid_dpop_proof"}function _r(t){if(!t)return;let r=t.trim();if(!r)return;let n=/^([A-Za-z][A-Za-z0-9!#$%&'*+.^_`|~-]*)\s+(.+)$/.exec(r);if(!n)return{scheme:"Unknown",token:r};let o=n[1]??"",i=n[2]?.trim()??"";if(o.toLowerCase()==="bearer")return{scheme:"Bearer",token:i};if(o.toLowerCase()==="dpop")return{scheme:"DPoP",token:i};return{scheme:"Unknown",token:r}}function fn(t){return _r(t)?.token??t}function Es(t){let r=new URL(t);if(r.hash)throw Error("DPoP proof htu must not contain a fragment");return`${r.origin}${r.pathname}`}async function yu(t){let r=await crypto.subtle.digest("SHA-256",new TextEncoder().encode(t));return pr(new Uint8Array(r))}async function _u(t){return bl(t,"sha256")}function hn(t){if(!t||typeof t!=="object"||Array.isArray(t))return;let r=t.jkt;return typeof r==="string"&&r.length>0?r:void 0}function gn(t){return hn(t.cnf)}function vo(t,r){let n=t[r];return typeof n==="string"&&n.length>0?n:void 0}function Kw(t,r){let n=t[r];return typeof n==="number"&&Number.isFinite(n)?n:void 0}function Ww(t,r){if(!t||t==="none"||t.startsWith("HS"))throw ge("invalid_dpop_proof","DPoP proof must use an asymmetric JWS algorithm");if(!r.includes(t))throw ge("invalid_dpop_proof","DPoP proof uses an unsupported JWS algorithm")}function Jw(t){if(!t||typeof t!=="object"||Array.isArray(t))throw ge("invalid_dpop_proof","DPoP proof header must include a public jwk");if(t.kty==="oct")throw ge("invalid_dpop_proof","DPoP proof jwk must be asymmetric");for(let r of Fw)if(r in t)throw ge("invalid_dpop_proof","DPoP proof jwk must not contain private key material")}async function Qw(t){let r=`${t.jkt}
31
+ </html>`;var ro=(()=>{let t=function(){};return t.prototype=Object.create(null),Object.freeze(t.prototype),t})();function Ii(){return{root:{key:""},static:new ro}}function qm(t){let r=0,n=0;for(;r<t.length;r++){let a=t.charCodeAt(r);if(a===92)r++;else if(a===40)n++;else if(a===41&&n>0)n--;else if(a===123&&n===0)break}if(r>=t.length)return;let o=r+1;n=0;for(;o<t.length;o++){let a=t.charCodeAt(o);if(a===92)o++;else if(a===40)n++;else if(a===41&&n>0)n--;else if(a===125&&n===0)break}if(o>=t.length)return;let i=t[o+1],s=i==="?"||i==="+"||i==="*";return[t.slice(0,r),t.slice(r+1,o),t.slice(o+(s?2:1)),s?i:void 0]}function jm(t){if(!t.includes("{"))return;let r=qm(t);if(!r)return;let[n,o,i,s]=r;if(!s)return[n+o+i];if(s==="?")return[n+o+i,n+i];if(o.includes("/"))throw Error("unsupported group repetition across segments");return[`${n}(?:${o})${s}${i}`]}var $m="__rou3_unnamed_",Mm="__rou3_esc_";function Mc(t){return`${$m}${t}`}function Hm(t){return/^(?!__rou3_|_\d)[A-Za-z_]\w*$/.test(t)?t:Mm+t.replace(/[_-]/g,(r)=>r==="_"?"__":"_h")}function Vm(t){if(t.charCodeAt(0)!==95)return t;if(t.startsWith("__rou3_esc_"))return t.slice(11).replace(/__|_h/g,(r)=>r==="__"?"_":"-");return t.startsWith("__rou3_unnamed_")?t.slice(15):t}function Fm(t){let r=0;for(let n=0;n<t.length;n++){let o=t.charCodeAt(n);if(o===92){n++;continue}if(o===40){r++;continue}if(o===41&&r>0){r--;continue}if(o===42&&r===0)return!0}return!1}function Km(t,r,n=Mc){let o=0,i=r,s="";for(let a=0;a<t.length;a++){let c=t.charCodeAt(a);if(c===92){if(s+=t[a],a+1<t.length)s+=t[++a];continue}if(c===40){o++,s+=t[a];continue}if(c===41&&o>0){o--,s+=t[a];continue}if(c===42&&o===0){s+=`(?<${n(i++)}>[^/]*)`;continue}s+=t[a]}return[s,i]}function Wm(t){if(!t.includes("\\"))return t;return t.replace(/\\([:(){}])/g,(r,n)=>"\uFFFD"+"ABCDE"[":(){}".indexOf(n)])}function Jm(t){if(t.startsWith("**"))return 2;if(t==="*"||t.includes(":")||t.includes("(")||Fm(t))return 1;if(t==="\\*")return"*";if(t==="\\*\\*")return"**";if(!t.includes("\uFFFD"))return t;return t.replace(/\uFFFD([A-E])/g,(r,n)=>n==="A"?":":n==="B"?"(":n==="C"?")":n==="D"?"{":"}")}function Qm(t){for(let r=0;r<t.length;r++){let n=t[r].charCodeAt(t[r].length-1);if(n!==63&&n!==43&&n!==42)continue;let o=t[r].match(/^(.*:[\w-]+(?:\([^)]*\))?)([?+*])$/);if(!o)continue;let i=t.slice(0,r),s=t.slice(r+1);if(o[2]==="?")return["/"+i.concat(o[1]).concat(s).join("/"),"/"+i.concat(s).join("/")];let a=o[1].match(/:([\w-]+)/)?.[1]||"_",c="/"+[...i,`**:${a}`,...s].join("/"),d="/"+[...i,...s].join("/");return o[2]==="+"?[c]:[c,d]}}function Hc(t){if(!t.includes("/."))return t;let r=[];for(let n of t.split("/"))if(n===".")continue;else if(n===".."&&r.length>1)r.pop();else r.push(n);return r.join("/")||"/"}function Ui(t){let r=t.split("/");if(r.shift(),r[r.length-1]==="")r.pop();return r}function Gm(t){let r=Ui(t);while(r[r.length-1]==="")r.pop();return r}function Vc(t,r){let n=new ro;for(let[o,i]of r){let s=o<0?t.slice(-(o+1)).join("/"):t[o];if(typeof i==="string")n[i]=s;else{let a=s.match(i);if(a)for(let c in a.groups)n[Vm(c)]=a.groups[c]}}return n}function Vr(t,r="",n,o){if(r=r.toUpperCase(),n.charCodeAt(0)!==47)n=`/${n}`;let i=jm(n);if(i){for(let m of i)Vr(t,r,m,o);return}n=Wm(n);let s=Gm(n),a=Qm(s);if(a){for(let m of a)Vr(t,r,m,o);return}let c=t.root,d=0,u=[],f=[];for(let m=0;m<s.length;m++){let w=s[m],y=Jm(w);if(y===2){if(!c.wildcard)c.wildcard={key:"**"};c=c.wildcard,u.push([-(m+1),w.split(":")[1]||"_",w.length===2]);break}if(y===1){if(!c.param)c.param={key:"*"};if(c=c.param,w==="*")u.push([m,String(d++),!0]);else if(w.includes("(")||w.includes(":",1)||!/^:[\w-]+$/.test(w)){let[R,b]=Zm(w,d);d=b,f[m]=R,c.hasRegexParam=!0,u.push([m,R,!1])}else u.push([m,w.slice(1),!1]);continue}w=s[m]=y;let I=c.static?.[w];if(I)c=I;else{let R={key:w};if(!c.static)c.static=new ro;c.static[w]=R,c=R}}let p=u.length>0,h=c.methods??=new ro;if((h[r]??=[]).push({data:o||null,paramsRegexp:f,paramsMap:p?u:void 0}),!p)t.static["/"+s.join("/")]=c}function Zm(t,r=0){let n=r,o="",i=0;for(let a=0;a<t.length;a++){let c=t.charCodeAt(a);if(c===40)i++;else if(c===41&&i>0)i--;else if(c===92&&i===0&&a+1<t.length){let d=t[a+1];if(d!==":"&&d!=="("&&d!=="*"&&d!=="\\"){o+="\uFFFE"+d,a++;continue}}else if(c===46&&i===0){o+="\\.";continue}o+=t[a]}[o,n]=Km(o,n);let s=o.replace(/:([\w-]+)(?:\(([^)]*)\))?/g,(a,c,d)=>`(?<${Hm(c)}>${d||"[^/]+"})`).replace(/\((?![?<])/g,()=>`(?<${Mc(n++)}>`).replace(/\uFFFE(.)/g,(a,c)=>/[.*+?^${}()|[\]\\]/.test(c)?`\\${c}`:c);return[new RegExp(`^${s}$`),n]}function Fc(t,r="",n,o){if(o?.normalize)n=Hc(n);if(n.charCodeAt(n.length-1)===47)n=n.slice(0,-1);let i=t.static[n];if(i&&i.methods){let c=i.methods[r]||i.methods[""];if(c!==void 0)return c[0]}let s=Ui(n),a=Ri(t.root,r,s,0);if(a===void 0)return;if(o?.params===!1)return a;return{data:a.data,params:a.paramsMap?Vc(s,a.paramsMap):void 0}}function Ri(t,r,n,o){if(o===n.length){if(t.methods){let s=eo(t.methods,r,n,t.key==="*",!1);if(s)return s}return t.param?.methods&&eo(t.param.methods,r,n,!0,!0)||t.wildcard?.methods&&eo(t.wildcard.methods,r,n,!0,!0)||void 0}let i=n[o];if(t.static){let s=t.static[i];if(s){let a=Ri(s,r,n,o+1);if(a)return a}}if(t.param){let s=Ri(t.param,r,n,o+1);if(s)return s}if(t.wildcard&&t.wildcard.methods)return eo(t.wildcard.methods,r,n,!0,!1)}function eo(t,r,n,o,i){let s=t[r]||t[""];if(!s)return;let a=s[0];if(s.length===1&&a.paramsRegexp.length===0){if(!i)return a;let u=a.paramsMap;return u?.[u.length-1]?.[2]?a:void 0}let c,d=-1;for(let u of s){let f=u.paramsMap,p=f?.[f.length-1]?.[2];if(i&&!p)continue;let h=o&&f&&!p?1:0,m=u.paramsRegexp;for(let w=0;w<m.length;w++)if(m[w]){if(!m[w].test(n[w])){h=-1;break}h++}if(h>d)c=u,d=h}return c}function Kc(t,r="",n,o){if(o?.normalize)n=Hc(n);if(n.charCodeAt(n.length-1)===47)n=n.slice(0,-1);let i=Ui(n),s=Ti(t.root,r,i,0);if(o?.params===!1)return s;return s.map((a)=>({data:a.data,params:a.paramsMap?Vc(i,a.paramsMap):void 0}))}function Ti(t,r,n,o,i=[]){let s=n[o];if(t.wildcard&&t.wildcard.methods){let a=t.wildcard.methods[r]||t.wildcard.methods[""];if(a)if(o<n.length)to(i,a,!0);else{let c=[];for(let d of a){let u=d.paramsMap;if(u?.[u.length-1]?.[2])c.push(d)}to(i,c,!0)}}if(t.param){if(o<n.length){let a=i.length;if(Ti(t.param,r,n,o+1,i),t.param.hasRegexParam){for(let c=i.length-1;c>=a;c--)if(i[c].paramsRegexp[o]?.test(s)===!1)i.splice(c,1)}}else if(t.param.methods){let a=t.param.methods[r]||t.param.methods[""];if(a){let c=[];for(let d of a){let u=d.paramsMap;if(u?.[u.length-1]?.[2])c.push(d)}to(i,c,!0)}}}if(o<n.length){let a=t.static?.[s];if(a)Ti(a,r,n,o+1,i)}if(o===n.length&&t.methods){let a=t.methods[r]||t.methods[""];if(a)to(i,a,t.key==="*")}return i}function to(t,r,n){if(r.length>1)r=r.map((o)=>{let i=0,{paramsRegexp:s,paramsMap:a}=o;for(let c=0;c<s.length;c++)if(s[c])i++;if(n&&a&&!a[a.length-1][2])i++;return[o,i]}).sort((o,i)=>o[1]-i[1]).map((o)=>o[0]);for(let o of r)t.push(o)}var Ci=(t,r)=>{if(!r?.openapi?.disabled){let a={path:"/api/reference",...r?.openapi};t.openapi=_t(a.path,{method:"GET"},async(c)=>{let d=await bi(t);return new Response(Si(d,a.scalar),{headers:{"Content-Type":"text/html"}})})}let n=Ii(),o=Ii();for(let a of Object.values(t)){if(!a.options||!a.path)continue;if(a.options?.metadata?.SERVER_ONLY)continue;let c=Array.isArray(a.options?.method)?a.options.method:[a.options?.method];for(let d of c)Vr(n,d,a.path,a)}if(r?.routerMiddleware?.length)for(let{path:a,middleware:c}of r.routerMiddleware)Vr(o,"*",a,c);let i=r?.basePath&&r.basePath!=="/"?r.basePath.replace(/\/+$/,""):"",s=async(a)=>{let c=new URL(a.url),d=c.pathname,u;if(i){if(!d.startsWith(`${i}/`))return new Response(null,{status:404,statusText:"Not Found"});u=d.slice(i.length)}else u=d;if(u.length===0||/\/{2,}/.test(u))return new Response(null,{status:404,statusText:"Not Found"});let f=Fc(n,a.method,u);if(u.endsWith("/")!==f?.data?.path?.endsWith("/")&&!r?.skipTrailingSlashes)return new Response(null,{status:404,statusText:"Not Found"});if(!f?.data)return new Response(null,{status:404,statusText:"Not Found"});let p={};c.searchParams.forEach((m,w)=>{if(w in p)if(Array.isArray(p[w]))p[w].push(m);else p[w]=[p[w],m];else p[w]=m});let h=f.data;try{let m=h.options.metadata?.allowedMediaTypes||r?.allowedMediaTypes,w={path:u,method:a.method,headers:a.headers,params:f.params?{...f.params}:{},request:a,body:h.options.disableBody?void 0:await Oc(h.options.cloneRequest?a.clone():a,m),query:p,_flag:"router",asResponse:!0,context:r?.routerContext},y=Kc(o,"*",u);if(y?.length)for(let{data:I,params:R}of y){let b=await I({...w,params:R?{...R}:{},asResponse:!1});if(b instanceof Response)return b}return await h(w)}catch(m){if(r?.onError)try{let w=await r.onError(m,a);if(w instanceof Response)return We(w)}catch(w){if(lt(w))return We(w);throw w}if(r?.throwError)throw m;if(lt(m))return We(m);return console.error("# SERVER_ERROR: ",m),new Response(null,{status:500,statusText:"Internal Server Error"})}};return{handler:async(a)=>{let c=await r?.onRequest?.(a);if(c instanceof Response)return c;let d=Yn(c)?c:a,u=await s(d),f=await r?.onResponse?.(u,d);if(f instanceof Response)return f;return u},endpoints:t}};var Jc=4050,Wc=100;function Ym(t,r){return Jc-Br(t,"",{...r}).length}function Qc(t,r){let n=`${t}.`;if(!r.startsWith(n))return null;let o=r.slice(n.length),i=Number(o);if(!Number.isSafeInteger(i)||i<0||String(i)!==o)return null;return i}function Xm(t,r){let n={},o=Zn(r.headers?.get("cookie")||"");for(let[i,s]of o){if(i!==t&&Qc(t,i)===null)continue;n[i]=s}return n}function eg(t,r,n,o){let i=Ym(`${r.name}.${Wc-1}`,r.attributes),s=i>0?Math.ceil(r.value.length/i):1/0;if(s<=1)return n[r.name]=r.value,[r];if(s>Wc)return o.warn(`${t} 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 a=[];for(let c=0;c<s;c++){let d=`${r.name}.${c}`,u=c*i,f=r.value.substring(u,u+i);a.push({...r,name:d,value:f}),n[d]=f}return o.debug(`CHUNKING_${t.toUpperCase()}_COOKIE`,{message:`${t} cookie exceeds the ${Jc} byte limit and was split into ${s} chunks.`,valueSize:r.value.length,chunkCount:s,chunkSizes:a.map((c)=>c.value.length)}),a}function tg(t,r){let n={};for(let o in t)n[o]={name:o,value:"",attributes:{...r,maxAge:0}};return n}var Gc=(t)=>(r,n,o)=>{let i=Xm(r,o),s=o.context.logger,a=()=>{let c=tg(i,n);for(let d in i)delete i[d];return c};return{chunk(c,d){let u=a(),f=eg(t,{name:r,value:c,attributes:{...n,...d}},i,s);for(let p of f)u[p.name]=p;return Object.values(u)},clean(){return Object.values(a())},setCookies(c){for(let d of c)o.setCookie(d.name,d.value,d.attributes)}}},Fr=Gc("Session"),no=Gc("Account");function oo(t,r){let n=t.getCookie(r);if(n)return n;let o=[],i=t.headers?.get("cookie");if(!i)return null;for(let[s,a]of Zn(i)){let c=Qc(r,s);if(c===null)continue;o.push({index:c,value:a})}if(o.length>0)return o.sort((s,a)=>s.index-a.index),o.map((s)=>s.value).join("");return null}async function ft(t,r){let n=t.context.authCookies.accountData,o={maxAge:300,...n.attributes},i=await Mn(r,t.context.secretConfig,"better-auth-account",o.maxAge),s=no(n.name,o,t);s.setCookies(s.chunk(i,o))}async function io(t){let r=oo(t,t.context.authCookies.accountData.name);if(r){let n=Mr(await Hn(r,t.context.secretConfig,"better-auth-account"));if(n)return n}return null}var Zc=ye(l({disableCookieCache:Wu().meta({description:"Disable cookie cache and fetch session from database"}).optional(),disableRefresh:Wu().meta({description:"Disable session refresh. Useful for checking session status, without updating the session"}).optional()}));var Oi=new Map,rg=new TextEncoder,Yc={decode:(t,r="utf-8")=>{if(!Oi.has(r))Oi.set(r,new TextDecoder(r));return Oi.get(r).decode(t)},encode:(t)=>rg.encode(t)};var Di=(t="SHA-256",r="none")=>{let n={importKey:async(o,i)=>De().importKey("raw",Sl(o),{name:"HMAC",hash:{name:t}},!1,[i]),sign:async(o,i)=>{if(typeof o==="string")o=await n.importKey(o,"sign");let s=await De().sign("HMAC",o,Sl(i));if(r==="hex")return sd.encode(s);if(r==="base64")return To.encode(s);if(r==="base64url"||r==="base64urlnopad")return ko.encode(s,{padding:r!=="base64urlnopad"});return s},verify:async(o,i,s)=>{if(typeof o==="string")o=await n.importKey(o,"verify");if(r==="hex")s=typeof s==="string"?sd.toBytes(s):s;if(r==="base64"||r==="base64url"||r==="base64urlnopad")s=await To.decode(s);return De().verify("HMAC",o,Sl(s),Sl(i))}};return n};function Uu(t){let r=typeof t.baseURL==="string"?t.baseURL:void 0,n=typeof t.baseURL==="object"&&t.baseURL!==null?t.baseURL.protocol:void 0,o=(t.advanced?.useSecureCookies!==void 0?t.advanced?.useSecureCookies:n==="https"?!0:n==="http"?!1:r?r.startsWith("https://"):Xi)?wc:"",i=!!t.advanced?.crossSubDomainCookies?.enabled,s=i?t.advanced?.crossSubDomainCookies?.domain||(r?new URL(r).hostname:void 0):void 0;if(i&&!s&&!ls(t.baseURL))throw new te("baseURL is required when crossSubdomainCookies are enabled.");function a(c,d={}){let u=t.advanced?.cookiePrefix||"better-auth",f=t.advanced?.cookies?.[c]?.name||`${u}.${c}`,p=t.advanced?.cookies?.[c]?.attributes??{};return{name:`${o}${f}`,attributes:{secure:!!o,sameSite:"lax",path:"/",httpOnly:!0,...i?{domain:s}:{},...t.advanced?.defaultCookieAttributes,...d,...p}}}return a}function df(t){let r=Uu(t),n=r("session_token",{maxAge:t.session?.expiresIn||Wn("7d")}),o=r("session_data",{maxAge:t.session?.cookieCache?.maxAge||300}),i=r("account_data",{maxAge:t.session?.cookieCache?.maxAge||300}),s=r("dont_remember");return{sessionToken:{name:n.name,attributes:n.attributes},sessionData:{name:o.name,attributes:o.attributes},dontRememberToken:{name:s.name,attributes:s.attributes},accountData:{name:i.name,attributes:i.attributes}}}async function Kr(t,r,n){if(!t.context.options.session?.cookieCache?.enabled)return;let o=cr(r.session,t.context.options.session?.additionalFields),i=se(t.context.options,r.user),s=t.context.options.session?.cookieCache?.version,a="1";if(s){if(typeof s==="string")a=s;else if(typeof s==="function"){let m=s(r.session,r.user);a=mc(m)?await m:m}}let c={session:o,user:i,updatedAt:Date.now(),version:a},d={...t.context.authCookies.sessionData.attributes,maxAge:n?void 0:t.context.authCookies.sessionData.attributes.maxAge},u=ut(d.maxAge||60,"sec").getTime(),f=t.context.options.session?.cookieCache?.strategy||"compact",p;if(f==="jwe")p=await Mn(c,t.context.secretConfig,"better-auth-session",d.maxAge||300);else if(f==="jwt"){let m=t.context.sessionConfig.cookieCacheSigner;p=m?await m.sign(t,c,d.maxAge||300):await $n(c,t.context.secret,d.maxAge||300)}else p=ko.encode(JSON.stringify({session:c,expiresAt:u,signature:await Di("SHA-256","base64urlnopad").sign(t.context.secret,JSON.stringify({...c,expiresAt:u}))}),{padding:!1});let h=Fr(t.context.authCookies.sessionData.name,d,t);if(h.setCookies(h.chunk(p,d)),t.context.options.account?.storeAccountCookie&&!og(t,t.context.authCookies.accountData.name)){let m=await io(t);if(m)if(!qn(t.context.options)||m.userId===r.user.id)await ft(t,m);else{Be(t,t.context.authCookies.accountData);let w=no(t.context.authCookies.accountData.name,t.context.authCookies.accountData.attributes,t);w.setCookies(w.clean())}}}async function Xc(t,r){let n=t.context.options.session?.cookieCache?.strategy||"compact";if(n==="jwe"){let s=await Hn(r,t.context.secretConfig,"better-auth-session"),a=gc(s);if(!a)return null;return{session:a,expiresAt:s?.exp?s.exp*1000:Date.now()}}if(n==="jwt"){let s=t.context.sessionConfig.cookieCacheSigner;if(s){let d=await s.verify(t,r);if(!d)return null;return{session:d.payload,expiresAt:d.expiresAt}}let a=await sc(r,t.context.secret),c=gc(a);if(!c)return null;return{session:c,expiresAt:a?.exp?a.exp*1000:Date.now()}}let o=lc(Mr(Yc.decode(ko.decode(r))));if(!o)return null;if(!await Di("SHA-256","base64urlnopad").verify(t.context.secret,JSON.stringify({...o.session,expiresAt:o.expiresAt}),o.signature))return null;let i=gc(o.session);return i?{session:i,expiresAt:o.expiresAt}:null}async function pe(t,r,n,o){let i=await t.getSignedCookie(t.context.authCookies.dontRememberToken.name,t.context.secret);n=n!==void 0?n:!!i;let s=t.context.authCookies.sessionToken.attributes,a=n?void 0:t.context.sessionConfig.expiresIn;if(await t.setSignedCookie(t.context.authCookies.sessionToken.name,r.session.token,t.context.secret,{...s,maxAge:a,...o}),n)await t.setSignedCookie(t.context.authCookies.dontRememberToken.name,"true",t.context.secret,t.context.authCookies.dontRememberToken.attributes);await Kr(t,r,n),t.context.setNewSession(r)}function ng(t,r){let n=t,o=new Set;if(n.responseHeaders)o.add(n.responseHeaders);if(n.context?.responseHeaders)o.add(n.context.responseHeaders);let i=`${r}=`,s=`${r}.`;for(let a of o){let c=typeof a.getSetCookie==="function"?a.getSetCookie():Jn(a.get("set-cookie")||"");if(!c.length)continue;let d=c.filter((u)=>!u.startsWith(i)&&!u.startsWith(s));if(d.length===c.length)continue;a.delete("set-cookie");for(let u of d)a.append("set-cookie",u)}}function og(t,r){let n=t,o=new Set;if(n.responseHeaders)o.add(n.responseHeaders);if(n.context?.responseHeaders)o.add(n.context.responseHeaders);let i=`${r}=`,s=`${r}.`;for(let a of o)if((typeof a.getSetCookie==="function"?a.getSetCookie():Jn(a.get("set-cookie")||"")).some((c)=>c.startsWith(i)||c.startsWith(s)))return!0;return!1}function Be(t,r){ng(t,r.name),t.setCookie(r.name,"",{...r.attributes,maxAge:0})}function Le(t,r){if(Be(t,t.context.authCookies.sessionToken),Be(t,t.context.authCookies.sessionData),t.context.options.account?.storeAccountCookie){Be(t,t.context.authCookies.accountData);let i=no(t.context.authCookies.accountData.name,t.context.authCookies.accountData.attributes,t),s=i.clean();i.setCookies(s)}if(t.context.oauthConfig.storeStateStrategy==="cookie")Be(t,t.context.createAuthCookie("oauth_state"));let n=Fr(t.context.authCookies.sessionData.name,t.context.authCookies.sessionData.attributes,t),o=n.clean();if(n.setCookies(o),!r)Be(t,t.context.authCookies.dontRememberToken)}function Li(t){if(!t?.method)throw new U("FORBIDDEN",{code:"validation_source_missing",message:"User validation source is required"});if(t.method==="oauth"&&!t.oauth?.providerId)throw new U("FORBIDDEN",{code:"validation_source_missing",message:"OAuth user validation source requires oauth.providerId"});if((t.method==="sso-oidc"||t.method==="sso-saml")&&!t.sso?.providerId)throw new U("FORBIDDEN",{code:"validation_source_missing",message:"SSO user validation source requires sso.providerId"})}async function lr(t,r){let n=t.context.options.user?.validateUserInfo;if(!n)return;Li(r.source);let o;try{o=await n(r,t)}catch(i){throw t.context.logger.error("validateUserInfo callback threw",i),new U("FORBIDDEN",{code:"validation_failed",message:"User validation failed"})}if(o?.error)throw new U("FORBIDDEN",{code:o.error,message:o.errorDescription||o.error})}function cs(t,r){return{digest:async(n)=>{let o=Sl(n),i=await De().digest(t,o);if(r==="hex")return Array.from(new Uint8Array(i)).map((s)=>s.toString(16).padStart(2,"0")).join("");if(r==="base64"||r==="base64url"||r==="base64urlnopad"){if(r.includes("url"))return ko.encode(i,{padding:r!=="base64urlnopad"});return To.encode(i)}return i}}}var ig=async(t)=>{let r=await cs("SHA-256").digest(new TextEncoder().encode(t));return ko.encode(new Uint8Array(r),{padding:!1})};async function $t(t,r){if(!r||r==="plain")return t;if(r==="hashed")return ig(t);if(typeof r==="object"&&"hash"in r)return r.hash(t);return t}function Mt(t,r){if(!r)return;if(typeof r==="object"&&"default"in r){if(r.overrides){for(let[n,o]of Object.entries(r.overrides))if(t.startsWith(n))return o}return r.default}return r}var kt,ed=!1;function sg(){try{return globalThis.process?.getBuiltinModule?.("node:async_hooks")?.AsyncLocalStorage}catch{return}}async function fr(){if(kt)return kt;let t=sg();if(t)return kt??=t,kt;try{let{AsyncLocalStorage:r}=await import("async_hooks");return kt??=r,kt}catch(r){let n=globalThis.AsyncLocalStorage;if(typeof n==="function")return kt??=n,kt;if(typeof window<"u")throw Error("getAsyncLocalStorage is only available in server code");if(!ed)ed=!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");throw r}}var ag=()=>ea().context.endpointContextAsyncStorage,cg=async()=>{let t=ag();if(t)return t;let r=await fr(),n=ea().context;return n.endpointContextAsyncStorage??=new r};function Je(){return xf()}function zu(){let t=Je();if(!t)throw Error("No auth context found. Please make sure you are calling this function within a `runWithEndpointContext` callback.");return t}async function pr(t,r){return(await cg()).run(t,r)}var xi=async()=>{let t=ea(),r=t.context.requestStateAsyncStorage;if(r)return r;let n=await fr();return t.context.requestStateAsyncStorage??=new n,t.context.requestStateAsyncStorage};async function zi(){return(await xi()).getStore()!==void 0}async function Pi(){let t=(await xi()).getStore();if(!t)throw Error("No request state found. Please make sure you are calling this function within a `runWithRequestState` callback.");return t}async function Ni(t,r){return(await xi()).run(t,r)}function Et(t){let r=Object.freeze({});return{get ref(){return r},async get(){let n=await Pi();if(!n.has(r)){let o=await t();return n.set(r,o),o}return n.get(r)},async set(n){(await Pi()).set(r,n)}}}var ao=async()=>{let t=ea(),r=t.context.adapterAsyncStorage;if(r)return r;let n=await fr();return t.context.adapterAsyncStorage??=new n,t.context.adapterAsyncStorage};var X=async(t)=>ao().then((r)=>r.getStore()?.adapter||t).catch(()=>t),wm=async(t,r)=>{let n=!1;return ao().then(async(o)=>{n=!0;let i=[],s,a,c=!1;try{s=await o.run({adapter:t,pendingHooks:i,isTransactionActive:!1},r)}catch(d){a=d,c=!0}for(let d of i)await d();if(c)throw a;return s}).catch((o)=>{if(!n)return r();throw o})},Ue=async(t,r,n)=>{let o=!1;return ao().then(async(i)=>{if(o=!0,i.getStore()?.isTransactionActive)return r();let s=Cc(t)?.();if(s)await s;let a=[],c,d,u=!1;try{c=await t.transaction(async(p)=>(a=[],i.run({adapter:p,pendingHooks:a,isTransactionActive:!0},r)))}catch(p){u=!0,d=p}let f=async(p)=>{for(let h of a)try{await h()}catch(m){if(!n?.onAfterCommitHookError){if(p==="throw")throw m;try{Ee.error("Failed to run an after-commit hook for work that could not roll back",m)}catch{}continue}try{await n.onAfterCommitHookError(m)}catch{}}};if(u){if(t.options?.adapterConfig.transaction===!1)await f("log");throw d}return await f("throw"),c}).catch((i)=>{if(!o)return r();throw i})},Te=async(t,r)=>{let n=async()=>{try{await t()}catch(s){if(!r?.onError)throw s;await r.onError(s)}},o;try{o=await ao()}catch{return n()}let i=o.getStore();if(!i?.isTransactionActive)return n();i.pendingHooks.push(n)};function co(t,r){let n=ds(r.options),o=r.hooks;async function i(f,p,h){let m=Je(),w=f;for(let{source:I,hooks:R}of o){let b=R[p]?.create?.before;if(b){let O=await n(`db create.before ${p}`,{[pn]:"create.before",[vr]:p,[mn]:I},()=>b(w,m));if(O===!1)return null;if(typeof O==="object"&&"data"in O)w={...w,...O.data}}}let y=null;if(!h||h.executeMainFn)y=await(await X(t)).create({model:p,data:w,forceAllowId:!0});if(h?.fn)y=await h.fn(y??w);for(let{source:I,hooks:R}of o){let b=R[p]?.create?.after;if(b)await Te(async()=>{await n(`db create.after ${p}`,{[pn]:"create.after",[vr]:p,[mn]:I},()=>b(y,m))})}return y}async function s(f,p,h,m){let w=Je(),y=f;for(let{source:b,hooks:O}of o){let g=O[h]?.update?.before;if(g){let S=await n(`db update.before ${h}`,{[pn]:"update.before",[vr]:h,[mn]:b},()=>g(f,w));if(S===!1)return null;if(typeof S==="object"&&"data"in S)y={...y,...S.data}}}let I=m?await m.fn(y):null,R=!m||m.executeMainFn?await(await X(t)).update({model:h,update:y,where:p}):I;for(let{source:b,hooks:O}of o){let g=O[h]?.update?.after;if(g)await Te(async()=>{await n(`db update.after ${h}`,{[pn]:"update.after",[vr]:h,[mn]:b},()=>g(R,w))})}return R}async function a(f,p,h,m){let w=Je(),y=f;for(let{source:b,hooks:O}of o){let g=O[h]?.update?.before;if(g){let S=await n(`db updateMany.before ${h}`,{[pn]:"updateMany.before",[vr]:h,[mn]:b},()=>g(f,w));if(S===!1)return null;if(typeof S==="object"&&"data"in S)y={...y,...S.data}}}let I=m?await m.fn(y):null,R=!m||m.executeMainFn?await(await X(t)).updateMany({model:h,update:y,where:p}):I;for(let{source:b,hooks:O}of o){let g=O[h]?.update?.after;if(g)await Te(async()=>{await n(`db updateMany.after ${h}`,{[pn]:"updateMany.after",[vr]:h,[mn]:b},()=>g(R,w))})}return R}async function c(f,p,h){let m=Je(),w=null;try{w=(await(await X(t)).findMany({model:p,where:f,limit:1}))[0]||null}catch{}if(w)for(let{source:R,hooks:b}of o){let O=b[p]?.delete?.before;if(O){if(await n(`db delete.before ${p}`,{[pn]:"delete.before",[vr]:p,[mn]:R},()=>O(w,m))===!1)return null}}let y=h?await h.fn(f):null,I=(!h||h.executeMainFn)&&w?await(await X(t)).delete({model:p,where:f}):y;if(w)for(let{source:R,hooks:b}of o){let O=b[p]?.delete?.after;if(O)await Te(async()=>{await n(`db delete.after ${p}`,{[pn]:"delete.after",[vr]:p,[mn]:R},()=>O(w,m))})}return I}async function d(f,p,h){let m=Je(),w=[];try{w=await(await X(t)).findMany({model:p,where:f})}catch{}for(let R of w)for(let{source:b,hooks:O}of o){let g=O[p]?.delete?.before;if(g){if(await n(`db delete.before ${p}`,{[pn]:"delete.before",[vr]:p,[mn]:b},()=>g(R,m))===!1)return null}}let y=h?await h.fn(f):null,I=!h||h.executeMainFn?await(await X(t)).deleteMany({model:p,where:f}):y;for(let R of w)for(let{source:b,hooks:O}of o){let g=O[p]?.delete?.after;if(g)await Te(async()=>{await n(`db delete.after ${p}`,{[pn]:"delete.after",[vr]:p,[mn]:b},()=>g(R,m))})}return I}async function u(f,p,h,m){let w=Je(),y=o.flatMap(({source:b,hooks:O})=>{let g=O[f]?.delete?.before;return g?[{source:b,fn:g}]:[]}),I=m??null;if(y.length){if(!I)try{I=(await(await X(t)).findMany({model:f,where:p,limit:1}))[0]||null}catch{}if(I){for(let{source:b,fn:O}of y)if(await n(`db delete.before ${f}`,{[pn]:"delete.before",[vr]:f,[mn]:b},()=>O(I,w))===!1)return null}}let R=await h();if(!R)return null;for(let{source:b,hooks:O}of o){let g=O[f]?.delete?.after;if(g)await Te(async()=>{await n(`db delete.after ${f}`,{[pn]:"delete.after",[vr]:f,[mn]:b},()=>g(R,w))})}return R}return{createWithHooks:i,updateWithHooks:s,updateManyWithHooks:a,deleteWithHooks:c,deleteManyWithHooks:d,consumeOneWithHooks:u}}var dg=pA(),ug=mA();function qi(t){return Wr(t)||ji(t)}function Wr(t){return Rf(dg,t)}function ji(t){return Rf(ug,t)}function td(t){let r=t.toLowerCase();if(r.startsWith("::ffff:")){let o=r.substring(7);if(Wr(o))return o}let n=t.split(":");if(n.length===7&&n[5]?.toLowerCase()==="ffff"){let o=n[6];if(o&&Wr(o))return o}if(r.includes("::ffff:")||r.includes(":ffff:")){let o=Bi(t);if(o.length===8&&o[0]==="0000"&&o[1]==="0000"&&o[2]==="0000"&&o[3]==="0000"&&o[4]==="0000"&&o[5]==="ffff"&&o[6]&&o[7])return`${Number.parseInt(o[6].substring(0,2),16)}.${Number.parseInt(o[6].substring(2,4),16)}.${Number.parseInt(o[7].substring(0,2),16)}.${Number.parseInt(o[7].substring(2,4),16)}`}return null}function Bi(t){if(t.includes("::")){let r=t.split("::"),n=r[0]?r[0].split(":"):[],o=r[1]?r[1].split(":"):[],i=8-n.length-o.length,s=Array(i).fill("0000"),a=n.map((d)=>d.padStart(4,"0")),c=o.map((d)=>d.padStart(4,"0"));return[...a,...s,...c]}return t.split(":").map((r)=>r.padStart(4,"0"))}function lg(t,r){let n=Bi(t);if(r!==void 0&&r<128){let o=Math.max(0,Math.floor(r));return n.map((i)=>{if(o<=0)return"0000";if(o>=16)return o-=16,i;let s=Number.parseInt(i,16)&(65535<<16-o&65535);return o=0,s.toString(16).padStart(4,"0")}).join(":").toLowerCase()}return n.join(":").toLowerCase()}function uo(t,r={}){if(Wr(t))return t.toLowerCase();if(!ji(t))return t.toLowerCase();let n=td(t);if(n)return n.toLowerCase();return lg(t,r.ipv6Subnet??64)}function ad(t){if(Wr(t))return Uint8Array.from(t.split(".").map((i)=>Number(i)));if(!ji(t))return null;let r=td(t);if(r)return Uint8Array.from(r.split(".").map((i)=>Number(i)));let n=Bi(t),o=new Uint8Array(16);for(let i=0;i<8;i++){let s=Number.parseInt(n[i]??"0",16);o[i*2]=s>>8&255,o[i*2+1]=s&255}return o}var fg=/^\d+$/;function cd(t){let r=t.lastIndexOf("/"),n=ad(r===-1?t:t.slice(0,r));if(!n)return null;let o=n.length*8;if(r===-1)return{bytes:n,prefix:o};let i=t.slice(r+1);if(!fg.test(i))return null;let s=Number(i);return s<=o?{bytes:n,prefix:s}:null}function pg(t,r){if(t.length!==r.bytes.length)return!1;let n=r.prefix;for(let o=0;o<t.length&&n>0;o++){let i=n>=8?8:n,s=i===8?255:255<<8-i&255;if(((t[o]??0)&s)!==((r.bytes[o]??0)&s))return!1;n-=8}return!0}function Qg(t){return t.filter((r)=>cd(r)===null)}function hg(t,r={}){let n=t.split(",").map((s)=>s.trim()).filter(Boolean);if(n.length===0)return null;let o=(r.trustedProxies??[]).map(cd).filter((s)=>s!==null);if(o.length>0){for(let s=n.length-1;s>=0;s--){let a=n[s],c=a?ad(a):null;if(!a||!c)return null;if(o.some((d)=>pg(c,d)))continue;return uo(a,{ipv6Subnet:r.ipv6Subnet})}return null}if(n.length!==1)return null;let i=n[0];if(!i||!qi(i))return null;return uo(i,{ipv6Subnet:r.ipv6Subnet})}var mg="127.0.0.1",gg=["x-forwarded-for"];function lo(t,r){if(r.advanced?.ipAddress?.disableIpTracking)return null;let n="headers"in t?t.headers:t,o=r.advanced?.ipAddress?.ipAddressHeaders||gg;for(let i of o){let s="get"in n?n.get(i):n[i];if(typeof s==="string"){let a=hg(s,{ipv6Subnet:r.advanced?.ipAddress?.ipv6Subnet,trustedProxies:r.advanced?.ipAddress?.trustedProxies});if(a)return a}}if(vi()||xl())return mg;return null}function dd(t,r){return`${t}|${r}`}function et(t,r=Date.now()){let n=typeof t==="number"?t:t.getTime();return Math.max(Math.floor((n-r)/1000),0)}var Ac=(t,r)=>{let{logger:n,options:o}=r,i=o.secondaryStorage,s=new Map,a=o.session?.expiresIn||604800,c=!!i&&o.session?.storeSessionInDatabase===!0&&o.session?.preserveSessionInDatabase!==!0,{createWithHooks:d,updateWithHooks:u,updateManyWithHooks:f,deleteWithHooks:p,deleteManyWithHooks:h,consumeOneWithHooks:m}=co(t,r),w=(g)=>{let S=[...g,{field:"expiresAt",value:new Date,operator:"gt"}];return h(S,"session",{fn:async()=>{await(await X(t)).updateMany({model:"session",where:S,update:{expiresAt:new Date}})},executeMainFn:!1})};async function y(g){if(!i)return;let S=await i.get(`active-sessions-${g.id}`);if(!S)return;let C=Date.now(),z=(Mr(S)||[]).filter((L)=>L.expiresAt>C);await Promise.all(z.map(async({token:L})=>{let x=await i.get(L);if(!x)return;let P=Mr(x);if(!P)return;let j=et(P.session.expiresAt,C);await i.set(L,JSON.stringify({session:P.session,user:g}),Math.floor(j))}))}async function I(g){if(!i)return[];let S=await i.get(`active-sessions-${g}`);return S?Mr(S)||[]:[]}async function R(g,S){if(!i)return;let C=new Set(S.map((B)=>B.token));for(let{token:B}of S)await i.delete(B);let z=`active-sessions-${g}`,L=await I(g),x=Date.now(),P=L.filter((B)=>B.expiresAt>x&&!C.has(B.token));P.sort((B,H)=>B.expiresAt-H.expiresAt);let j=P.at(-1)?.expiresAt;if(j){await i.set(z,JSON.stringify(P),et(j,x));return}await i.delete(z)}async function b(g,S){if(!i)return;let C=S??await I(g);await Te(()=>R(g,C),{onError(z){n.error("Failed to delete committed user sessions from secondary storage",z)}})}async function O(g,S){let C=s.get(g)??Promise.resolve(),z,L=new Promise((P)=>{z=P}),x=C.catch(()=>{}).then(()=>L);s.set(g,x),await C.catch(()=>{});try{return await S()}finally{if(z(),s.get(g)===x)s.delete(g)}}return{createOAuthUser:async(g,S)=>Ue(t,async()=>{let C=await d({createdAt:new Date,updatedAt:new Date,...g,email:g.email?.toLowerCase()},"user",void 0);if(!C)throw new U("BAD_REQUEST",{message:"Failed to create user"});return{user:C,account:await d({...S,userId:C.id,createdAt:new Date,updatedAt:new Date},"account",void 0)}}),createUser:async(g,S)=>{let C={createdAt:new Date,updatedAt:new Date,...g,email:g.email?.toLowerCase()};if(o.user?.validateUserInfo){let z={...S,action:"create-user"};Li(z);let L;try{L=zu()}catch(x){throw n.error("Unable to run validateUserInfo: missing endpoint context",x),new U("FORBIDDEN",{code:"validation_context_missing",message:"User validation requires an endpoint context"})}await lr(L,{user:C,source:z})}return await d(C,"user",void 0)},createAccount:async(g)=>await d({createdAt:new Date,updatedAt:new Date,...g},"account",void 0),listSessions:async(g,S)=>{if(c)return(await(await X(t)).findMany({model:"session",where:[{field:"userId",value:g},{field:"expiresAt",value:new Date,operator:"gt"}]})).map((C)=>we(r.options,C));if(i){let C=await i.get(`active-sessions-${g}`);if(!C)return[];let z=Mr(C)||[],L=Date.now(),x=new Set,P=[];for(let{token:j,expiresAt:B}of z){if(B<=L||x.has(j))continue;x.add(j);let H=await i.get(j);if(!H)continue;try{let q=typeof H==="string"?JSON.parse(H):H;if(!q?.session)continue;P.push(we(r.options,{...q.session,expiresAt:new Date(q.session.expiresAt)}))}catch{continue}}return P}return await(await X(t)).findMany({model:"session",where:[{field:"userId",value:g},...S?.onlyActiveSessions?[{field:"expiresAt",value:new Date,operator:"gt"}]:[]]})},listUsers:async(g,S,C,z)=>await(await X(t)).findMany({model:"user",limit:g,offset:S,sortBy:C,where:z}),countTotalUsers:async(g)=>{let S=await(await X(t)).count({model:"user",where:g});if(typeof S==="string")return parseInt(S);return S},deleteUser:async(g)=>{let S=await I(g);if(!i||o.session?.storeSessionInDatabase)await h([{field:"userId",value:g}],"session",void 0);if(await h([{field:"userId",value:g}],"account",void 0),await p([{field:"id",value:g}],"user",void 0)!==null)await b(g,S)},createSession:async(g,S,C,z,L)=>{let x=await(async()=>{let M=Je();return M?.headers||M?.request?.headers})(),P=o.session?.storeSessionInDatabase,j=L?.deferSecondaryStorageWrites===!0&&c,{id:B,...H}=C||{},q;if(i&&!P){let M=r.generateId({model:"session"});q=M!==!1?M:us()}let W=Kn(o),Q={...q?{id:q}:{},ipAddress:x?lo(x,o)||"":"",userAgent:x?.get("user-agent")||"",...H,expiresAt:S?ut(86400,"sec"):ut(a,"sec"),userId:g,token:us(32),createdAt:new Date,updatedAt:new Date,...W,...z?H:{}},G=async(M)=>{if(!i)return M;let Y=await i.get(`active-sessions-${g}`),Z=[],re=Date.now();if(Y)Z=Mr(Y)||[],Z=Z.filter((Ke)=>Ke.expiresAt>re&&Ke.token!==Q.token);let ie=[...Z,{token:Q.token,expiresAt:Q.expiresAt.getTime()}].sort((Ke,wt)=>Ke.expiresAt-wt.expiresAt),qe=et(ie.at(-1)?.expiresAt??Q.expiresAt.getTime(),re);if(qe>0)await i.set(`active-sessions-${g}`,JSON.stringify(ie),qe);let gt=await(await X(t)).findOne({model:"user",where:[{field:"id",value:g}]}),ct=et(Q.expiresAt,re);if(ct>0)await i.set(Q.token,JSON.stringify({session:M,user:gt}),ct);return M};return await d(Q,"session",i?{fn:async(M)=>{if(!j)return G(M);return await Te(async()=>{await G(M)},{onError(Y){n.error("Failed to mirror committed session to secondary storage",Y)}}),M},executeMainFn:P}:void 0)},findSession:async(g)=>{if(i){let L=await i.get(g);if(!L&&(!o.session?.storeSessionInDatabase||r.options.session?.preserveSessionInDatabase))return null;if(L){let x=Mr(L);if(!x)return null;return{session:we(r.options,{...x.session,expiresAt:new Date(x.session.expiresAt),createdAt:new Date(x.session.createdAt),updatedAt:new Date(x.session.updatedAt)}),user:se(r.options,{...x.user,createdAt:new Date(x.user.createdAt),updatedAt:new Date(x.user.updatedAt)})}}}let S=await(await X(t)).findOne({model:"session",where:[{value:g,field:"token"}],join:{user:!0}});if(!S)return null;let{user:C,...z}=S;if(!C)return null;return{session:we(r.options,z),user:se(r.options,C)}},findSessions:async(g,S)=>{let C=[...new Set(g)],z=new Map,L=[];if(i)for(let P of C){let j=await i.get(P);if(j)try{let B=typeof j==="string"?JSON.parse(j):j;if(!B)continue;let H=new Date(B.session.expiresAt);if(S?.onlyActiveSessions&&H<=new Date)continue;let q={session:{...B.session,expiresAt:new Date(B.session.expiresAt)},user:{...B.user,createdAt:new Date(B.user.createdAt),updatedAt:new Date(B.user.updatedAt)}};z.set(P,q)}catch{continue}else L.push(P)}let x=i?L:C;if(x.length>0&&(!i||c)){let P=await(await X(t)).findMany({model:"session",limit:x.length,where:[{field:"token",value:x,operator:"in"},...S?.onlyActiveSessions?[{field:"expiresAt",value:new Date,operator:"gt"}]:[]],join:{user:!0}});for(let{user:j,...B}of P)if(j)z.set(B.token,{session:B,user:j})}return C.flatMap((P)=>{let j=z.get(P);return j?[j]:[]})},updateSession:async(g,S)=>await u(S,[{field:"token",value:g}],"session",i?{async fn(C){let z=await i.get(g);if(!z)return null;let L=Mr(z);if(!L)return null;let x={...L.session,...C,expiresAt:new Date(C.expiresAt??L.session.expiresAt),createdAt:new Date(L.session.createdAt),updatedAt:new Date(C.updatedAt??L.session.updatedAt)},P=we(r.options,x),j=Date.now(),B=new Date(P.expiresAt).getTime(),H=et(B,j);if(H>0){await i.set(g,JSON.stringify({session:P,user:L.user}),H);let q=`active-sessions-${P.userId}`,W=await i.get(q),Q=(W?Mr(W)||[]:[]).filter((M)=>M.token!==g&&M.expiresAt>j).concat([{token:g,expiresAt:B}]).sort((M,Y)=>M.expiresAt-Y.expiresAt),G=Q.at(-1)?.expiresAt;if(G&&G>j)await i.set(q,JSON.stringify(Q),et(G,j));else await i.delete(q)}return P},executeMainFn:o.session?.storeSessionInDatabase}:void 0),deleteSession:async(g)=>{if(i){let S=await i.get(g);if(S){let{session:C}=Mr(S)??{};if(!C){n.error("Session not found in secondary storage");return}let z=C.userId,L=await i.get(`active-sessions-${z}`);if(L){let x=Mr(L)||[],P=Date.now(),j=x.filter((H)=>H.expiresAt>P&&H.token!==g),B=j.sort((H,q)=>H.expiresAt-q.expiresAt).at(-1)?.expiresAt;if(j.length>0&&B&&B>Date.now())await i.set(`active-sessions-${z}`,JSON.stringify(j),et(B,P));else await i.delete(`active-sessions-${z}`)}else n.error("Active sessions list not found in secondary storage")}if(await i.delete(g),!o.session?.storeSessionInDatabase)return;if(r.options.session?.preserveSessionInDatabase){await w([{field:"token",value:g}]);return}}await p([{field:"token",value:g}],"session",void 0)},deleteAccounts:async(g)=>{await h([{field:"userId",value:g}],"account",void 0)},deleteAccount:async(g)=>{await p([{field:"id",value:g}],"account",void 0)},deleteUserSessions:async(g)=>{let S=await I(g);if(i){if(!o.session?.storeSessionInDatabase){await b(g,S);return}if(r.options.session?.preserveSessionInDatabase){if(await w([{field:"userId",value:g}])!==null)await b(g,S);return}}if(await h([{field:"userId",value:g}],"session",void 0)!==null)await b(g,S)},deleteSessions:async(g)=>{if(i){if(await Promise.all(g.map((S)=>i.delete(S))),!o.session?.storeSessionInDatabase)return;if(r.options.session?.preserveSessionInDatabase){await w([{field:"token",value:g,operator:"in"}]);return}}await h([{field:"token",value:g,operator:"in"}],"session",void 0)},findAccountOwnerByKey:async({providerId:g,accountId:S})=>{let C=await(await X(t)).findMany({model:"account",where:[{field:"providerId",value:g},{field:"accountId",value:S}],limit:2,join:{user:!0}});if(C.length>1)throw new te(`Multiple accounts match the same accountId for provider ${JSON.stringify(g)}. Resolve duplicate account identities before continuing.`);let z=C[0];if(!z)return null;let{user:L,...x}=z;return L?{kind:"owned",user:L,account:x}:{kind:"orphaned",account:x}},findUserByEmail:async(g,S)=>{let C=await(await X(t)).findOne({model:"user",where:[{value:g.toLowerCase(),field:"email"}],join:{...S?.includeAccounts?{account:!0}:{}}});if(!C)return null;let{account:z,...L}=C;return{user:L,accounts:z??[]}},findUserById:async(g)=>{if(!g)return null;return await(await X(t)).findOne({model:"user",where:[{field:"id",value:g}]})},linkAccount:async(g)=>await d({createdAt:new Date,updatedAt:new Date,...g},"account",void 0),updateUser:async(g,S)=>{let C=await u({...S,...S.email?{email:S.email.toLowerCase()}:{}},[{field:"id",value:g}],"user",void 0);return await Te(()=>y(C),{onError(z){n.error("Failed to refresh committed user sessions in secondary storage",z)}}),C},updateUserByEmail:async(g,S)=>{let C=await u({...S,...S.email?{email:S.email.toLowerCase()}:{}},[{field:"email",value:g.toLowerCase()}],"user",void 0);return await Te(()=>y(C),{onError(z){n.error("Failed to refresh committed user sessions in secondary storage",z)}}),C},updatePassword:async(g,S)=>{await f({password:S},[{field:"userId",value:g},{field:"providerId",value:"credential"},{field:"accountId",value:g}],"account",void 0)},findAccounts:async(g)=>await(await X(t)).findMany({model:"account",where:[{field:"userId",value:g}]}),findCredentialAccount:async(g)=>(await X(t)).findOne({model:"account",where:[{field:"userId",value:g},{field:"providerId",value:"credential"},{field:"accountId",value:g}]}),findAccountByKey:async({providerId:g,accountId:S})=>{let C=await(await X(t)).findMany({model:"account",limit:2,where:[{field:"providerId",value:g},{field:"accountId",value:S}]});if(C.length>1)throw new te(`Multiple accounts match the same accountId for provider ${JSON.stringify(g)}. Resolve duplicate account identities before continuing.`);return C[0]??null},findAccountByUserId:async(g)=>await(await X(t)).findMany({model:"account",where:[{field:"userId",value:g}]}),updateAccount:async(g,S)=>await u(S,[{field:"id",value:g}],"account",void 0),createVerificationValue:async(g)=>{let S=Mt(g.identifier,o.verification?.storeIdentifier),C=await $t(g.identifier,S);return await d({createdAt:new Date,updatedAt:new Date,...g,identifier:C},"verification",i?{async fn(z){let L=et(z.expiresAt);if(L>0)await i.set(`verification:${C}`,JSON.stringify(z),L);return z},executeMainFn:o.verification?.storeInDatabase}:void 0)},findVerificationValue:async(g)=>{let S=Mt(g,o.verification?.storeIdentifier),C=await $t(g,S);if(i){let P=await i.get(`verification:${C}`);if(P){let j=Mr(P);if(j)return j}if(S&&S!=="plain"){let j=await i.get(`verification:${g}`);if(j){let B=Mr(j);if(B)return B}}if(!o.verification?.storeInDatabase)return null}let z=await X(t);async function L(P){return z.findMany({model:"verification",where:[{field:"identifier",value:P}],sortBy:{field:"createdAt",direction:"desc"},limit:1})}let x=await L(C);if(!x.length&&S&&S!=="plain")x=await L(g);if(!o.verification?.disableCleanup)await h([{field:"expiresAt",value:new Date,operator:"lt"}],"verification",void 0);return x[0]||null},deleteVerificationByIdentifier:async(g)=>{let S=await $t(g,Mt(g,o.verification?.storeIdentifier));if(i)await i.delete(`verification:${S}`);if(!i||o.verification?.storeInDatabase)await p([{field:"identifier",value:S}],"verification",void 0)},consumeVerificationValue:async(g)=>{let S=Mt(g,o.verification?.storeIdentifier),C=await $t(g,S),z=S&&S!=="plain"?[C,g]:[C],L=(P)=>{if(!P)return null;let j=typeof P==="string"?Mr(P):typeof P==="object"?P:null;if(!j)return null;let B=new Date(j.expiresAt);if(!Number.isFinite(B.getTime()))return null;return{...j,expiresAt:B}},x=null;if(i&&!o.verification?.storeInDatabase){let P=async(j)=>L(await i.getAndDelete(j));for(let j of z){let B=await P(`verification:${j}`);if(!B)continue;await Promise.all(z.filter((H)=>H!==j).map((H)=>i.delete(`verification:${H}`))),x=B;break}}else{let P=async(j)=>O(`verification:${j}`,()=>Ue(t,async()=>{let B=await X(t),H=[{field:"identifier",value:j}],q=(await B.findMany({model:"verification",where:H,sortBy:{field:"createdAt",direction:"desc"},limit:1}))[0]??null;if(!q)return null;return m("verification",[{field:"id",value:q.id}],async()=>{let W=await B.consumeOne({model:"verification",where:[{field:"id",value:q.id}]});if(!W)return null;return await B.deleteMany({model:"verification",where:H}),W},q)}));for(let j of z)if(x=await P(j),x)break;if(x&&i)await Promise.all(z.map((j)=>i.delete(`verification:${j}`)))}if(!x||x.expiresAt<new Date)return null;return x},reserveVerificationValue:async(g)=>{let S=Tf(new Uint8Array(await cs("SHA-256").digest(new TextEncoder().encode("reserve:"+g.identifier))),o),C=Mt(g.identifier,o.verification?.storeIdentifier),z=await $t(g.identifier,C);if(i&&!o.verification?.storeInDatabase)throw new te("reserveVerificationValue requires database-backed verification storage. Set verification.storeInDatabase to true for flows that reserve verification values.");try{await t.create({model:"verification",data:{id:S,identifier:z,value:g.value,expiresAt:g.expiresAt,createdAt:new Date,updatedAt:new Date},forceAllowId:!0})}catch(L){if(await t.findOne({model:"verification",where:[{field:"id",value:S}]}))return!1;throw L}if(i){let L=et(g.expiresAt);if(L>0)await i.set(`verification:${z}`,JSON.stringify({id:S,identifier:z,value:g.value,expiresAt:g.expiresAt}),L)}return!0},updateVerificationByIdentifier:async(g,S)=>{let C=await $t(g,Mt(g,o.verification?.storeIdentifier));if(i){let z=await i.get(`verification:${C}`);if(z){let L=Mr(z);if(L){let x={...L,...S},P=x.expiresAt??L.expiresAt,j=et(P instanceof Date?P:new Date(P));if(j>0)await i.set(`verification:${C}`,JSON.stringify(x),j);if(!o.verification?.storeInDatabase)return x}}}if(!i||o.verification?.storeInDatabase)return await u(S,[{field:"identifier",value:C}],"verification",void 0);return S},refreshUserSessions:y}};function $i(t){if(t===null||typeof t!=="object")return!1;let r=Object.getPrototypeOf(t);if(r!==null&&r!==Object.prototype&&Object.getPrototypeOf(r)!==null)return!1;if(Symbol.iterator in t)return!1;if(Symbol.toStringTag in t)return Object.prototype.toString.call(t)==="[object Module]";return!0}function Mi(t,r,n=".",o){if(!$i(r))return Mi(t,{},n,o);let i={...r};for(let s of Object.keys(t)){if(s==="__proto__"||s==="constructor")continue;let a=t[s];if(a===null||a===void 0)continue;if(o&&o(i,s,a,n))continue;if(Array.isArray(a)&&Array.isArray(i[s]))i[s]=[...a,...i[s]];else if($i(a)&&$i(i[s]))i[s]=Mi(a,i[s],(n?`${n}.`:"")+s.toString(),o);else i[s]=a}return i}function Jr(t){return(...r)=>r.reduce((n,o)=>Mi(n,o,"",t),{})}var ju=Jr(),RR=Jr((t,r,n)=>{if(t[r]!==void 0&&typeof n==="function")return t[r]=n(t[r]),!0}),TR=Jr((t,r,n)=>{if(Array.isArray(t[r])&&typeof n==="function")return t[r]=n(t[r]),!0});var wg=new Set(["metadata.google.internal","metadata.goog","metadata","instance-data","instance-data.ec2.internal"]);function yg(t){if(t.length>=2&&t.startsWith("[")&&t.endsWith("]"))return t.slice(1,-1);return t}function _g(t){if(t.startsWith("[")){let n=t.indexOf("]");if(n===-1)return t;return t.slice(0,n+1)}let r=t.indexOf(":");if(r===-1)return t;if(t.indexOf(":",r+1)!==-1)return t;return t.slice(0,r)}function Ag(t){let r=t.indexOf("%");if(r===-1)return t;return t.slice(0,r)}function kg(t){return t.replace(/\.+$/,"")}function ud(t){return/^\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}$/.test(t)}function ve(t){let r=t.split(".");return(Number(r[0])<<24|Number(r[1])<<16|Number(r[2])<<8|Number(r[3]))>>>0}function Ie(t,r,n){if(n===0)return!0;let o=n===32?4294967295:-1<<32-n>>>0;return(t&o)===(r&o)}function Gr(t){if(t==="0.0.0.0")return"unspecified";if(t==="255.255.255.255")return"broadcast";let r=ve(t);if(Ie(r,ve("127.0.0.0"),8))return"loopback";if(Ie(r,ve("10.0.0.0"),8))return"private";if(Ie(r,ve("172.16.0.0"),12))return"private";if(Ie(r,ve("192.168.0.0"),16))return"private";if(Ie(r,ve("169.254.0.0"),16))return"linkLocal";if(Ie(r,ve("100.64.0.0"),10))return"sharedAddressSpace";if(Ie(r,ve("192.0.2.0"),24))return"documentation";if(Ie(r,ve("198.51.100.0"),24))return"documentation";if(Ie(r,ve("203.0.113.0"),24))return"documentation";if(Ie(r,ve("198.18.0.0"),15))return"benchmarking";if(Ie(r,ve("224.0.0.0"),4))return"multicast";if(Ie(r,ve("0.0.0.0"),8))return"reserved";if(Ie(r,ve("192.0.0.0"),24))return"reserved";if(Ie(r,ve("192.88.99.0"),24))return"reserved";if(Ie(r,ve("240.0.0.0"),4))return"reserved";return"public"}function Hi(t,r,n={}){let o=r*5,i=Number.parseInt(t.slice(o,o+4),16),s=Number.parseInt(t.slice(o+5,o+9),16);if(!Number.isFinite(i)||!Number.isFinite(s))return null;let a=(i<<16|s)>>>0;if(n.xor)a=(a^4294967295)>>>0;return`${a>>>24&255}.${a>>>16&255}.${a>>>8&255}.${a&255}`}function Eg(t){if(t==="0000:0000:0000:0000:0000:0000:0000:0000")return"unspecified";if(t==="0000:0000:0000:0000:0000:0000:0000:0001")return"loopback";let r=Number.parseInt(t.slice(0,2),16),n=Number.parseInt(t.slice(2,4),16);if(r===255)return"multicast";if(r===254&&(n&192)===128)return"linkLocal";if(r===254&&(n&192)===192)return"reserved";if((r&254)===252)return"private";if(t.startsWith("2001:0db8:"))return"documentation";if(t.startsWith("2001:0002:0000:"))return"benchmarking";if(t.startsWith("2002:")){let o=Hi(t,1);if(o&&Gr(o)!=="public")return"reserved";return"public"}if(t.startsWith("0064:ff9b:0000:0000:0000:0000:")){let o=Hi(t,6);if(o&&Gr(o)!=="public")return"reserved";return"reserved"}if(t.startsWith("0064:ff9b:0001:"))return"reserved";if(t.startsWith("2001:0000:")){let o=Hi(t,6,{xor:!0});if(o&&Gr(o)!=="public")return"reserved";return"reserved"}if(t.startsWith("0100:0000:0000:0000:"))return"reserved";if(t.startsWith("3fff:0"))return"documentation";if(t.startsWith("5f00:"))return"reserved";if(t.startsWith("0000:0000:0000:0000:0000:0000:"))return"reserved";return"public"}function Vi(t){let r=kg(Ag(yg(_g(t.trim())))).toLowerCase();if(r==="")return{kind:"reserved",literal:"fqdn",canonical:""};if(!qi(r)){if(r==="localhost"||r.endsWith(".localhost"))return{kind:"localhost",literal:"fqdn",canonical:r};if(wg.has(r))return{kind:"cloudMetadata",literal:"fqdn",canonical:r};return{kind:"public",literal:"fqdn",canonical:r}}if(ud(r))return{kind:Gr(r),literal:"ipv4",canonical:r};let n=uo(r,{ipv6Subnet:128});if(ud(n))return{kind:Gr(n),literal:"ipv4",canonical:n};return{kind:Eg(n),literal:"ipv6",canonical:n}}function Fi(t){return Vi(t).kind==="loopback"}function hr(t){let r=Vi(t).kind;return r==="loopback"||r==="localhost"}function ld(t){return Vi(t).kind==="public"}async function Gg(t){let r=t.options,n=r.plugins||[],o=[],i=[];for(let s of n)if(s.init){let a=s.init(t),c;if(mc(a))c=await a;else c=a;if(typeof c==="object"){if(c.options){let{databaseHooks:d,trustedOrigins:u,...f}=c.options;if(d)i.push({source:`plugin:${s.id}`,hooks:d});if(u)o.push(u);r=ju(r,f)}if(c.context)Object.assign(t,c.context)}}if(o.length>0){let s=[...r.trustedOrigins?[r.trustedOrigins]:[],...o],a=s.filter(Array.isArray).flat(),c=s.filter((d)=>typeof d==="function");if(c.length>0)r.trustedOrigins=async(d)=>{let u=await Promise.all(c.map((f)=>f(d)));return[...a,...u.flat()].filter((f)=>typeof f==="string"&&f!=="")};else r.trustedOrigins=a}if(r.databaseHooks)i.push({source:"user",hooks:r.databaseHooks});t.internalAdapter=Ac(t.adapter,{options:r,logger:t.logger,hooks:i,generateId:t.generateId}),t.options=r}function Vg(t){let r=[];if(t.advanced?.crossSubDomainCookies?.enabled);return r}async function qu(t,r){let n=[];if(ls(t.baseURL)){let i=t.baseURL.allowedHosts,s=t.baseURL.protocol;for(let a of i)if(!a.includes("://")){if(!s||s==="https"||s==="auto")n.push(`https://${a}`);if(s==="http"||s==="auto"||hr(a))n.push(`http://${a}`)}else n.push(a);if(t.baseURL.fallback)try{n.push(new URL(t.baseURL.fallback).origin)}catch{}}else{let i=Hs(typeof t.baseURL==="string"?t.baseURL:void 0,t.basePath,r);if(i)n.push(new URL(i).origin)}if(t.trustedOrigins){if(Array.isArray(t.trustedOrigins))n.push(...t.trustedOrigins);if(typeof t.trustedOrigins==="function"){let i=await t.trustedOrigins(r);n.push(...i)}}let o=Jt.BETTER_AUTH_TRUSTED_ORIGINS;if(o)n.push(...o.split(","));return n.filter((i)=>Boolean(i))}function fd(t){if(je(t?.request))return t.request;if(!t?.headers)return;let r=t.headers instanceof Headers?t.headers:new Headers(t.headers);if(!r.has("host")&&!r.has("x-forwarded-host"))return;return r}function ff(t){return t.advanced?.trustedProxyHeaders??!1}async function pf(t,r,n){let o=t.options.baseURL,i=Wa(o,t.options.basePath||"/api/auth",r,void 0,n);if(!i)throw new te("Could not resolve base URL from request. Check your allowedHosts config.");let s=Object.create(Object.getPrototypeOf(t),Object.getOwnPropertyDescriptors(t));s.baseURL=i,s.options={...t.options,baseURL:Ai(i)||void 0};let a={...s.options,baseURL:o},c=typeof t.options.trustedOrigins==="function"||typeof t.options.account?.accountLinking?.trustedProviders==="function",d;if(c)if(je(r))d=r;else if(r)d=new Request(i,{headers:r});else d=void 0;else d=void 0;if(s.trustedOrigins=await qu(a,d),s.trustedProviders=await $u(s.options,d),t.options.advanced?.crossSubDomainCookies?.enabled)s.authCookies=df(s.options),s.createAuthCookie=Uu(s.options);return s}async function tt(t,r){if(!t)return;for(let n of t){let o=typeof n==="function"?await n():n;if(o[r.field??"id"]===r.value)return o}}async function $u(t,r){let n=t.account?.accountLinking?.trustedProviders;if(!n)return[];if(Array.isArray(n))return n.filter((o)=>Boolean(o));return(await n(r)??[]).filter((o)=>Boolean(o))}function Ht(t,r){if(r.length<t.context.password.config.minPasswordLength)throw t.context.logger.warn("Password is too short"),U.from("BAD_REQUEST",Ae.PASSWORD_TOO_SHORT)}function xe(t,r){if(r.length>t.context.password.config.maxPasswordLength)throw t.context.logger.warn("Password is too long"),U.from("BAD_REQUEST",Ae.PASSWORD_TOO_LONG)}async function pd(t,r,n,o){await Ue(t.context.adapter,async()=>{if(await o?.(),t.context.options.emailAndPassword?.revokeSessionsOnPasswordReset)await t.context.internalAdapter.deleteUserSessions(r);if(!await t.context.internalAdapter.findCredentialAccount(r)){await t.context.internalAdapter.createAccount({userId:r,providerId:"credential",accountId:r,password:n});return}await t.context.internalAdapter.updatePassword(r,n)})}async function hd(t,r){xe(t,r.password);let n=await t.context.internalAdapter.findCredentialAccount(r.userId),o=n?.password;if(!n||!o)return!1;return await t.context.password.verify({hash:o,password:r.password})}async function Kg(t,r){let n=r.body.password;if(typeof n==="string")xe(r,n);let o=await r.context.internalAdapter.findCredentialAccount(t),i=o?.password;if(!o||!i||!n){if(n)await r.context.password.hash(n);throw U.from("BAD_REQUEST",Ae.INVALID_PASSWORD)}if(!await r.context.password.verify({hash:i,password:n}))throw U.from("BAD_REQUEST",Ae.INVALID_PASSWORD);return!0}function Ur(t){return t instanceof ce||t instanceof U||t?.name==="APIError"}var Zr={"Cache-Control":"no-store",Pragma:"no-cache"};function bg(t,r){if(!Ur(r)||!t)return;Object.defineProperty(r,$a,{enumerable:!1,configurable:!0,value:t,writable:!1})}var Ji=At(async()=>({})),Sn=At.create({use:[Ji,At(async()=>({}))]}),md=_t.create({use:[Ji]});function gd(t,r){let n=r.metadata?.noStore===!0;return async(o)=>{if(n)for(let[i,s]of Object.entries(Zr))o.setHeader(i,s);try{return await pr(o,()=>t(o))}catch(i){throw bg(o.responseHeaders,i),i}}}function Pe(...t){if(t.length===3){let[o,i,s]=t;return md(o,i,gd(s,i))}let[r,n]=t;return md(r,gd(n,r))}function vg(t){return{...t,metadata:{...t.metadata,SERVER_ONLY:!0}}}Pe.serverOnly=(t,r)=>Pe(vg(t),r);function gr(t,r){let n;try{n=new URL(t).pathname.replace(/\/+$/,"")||"/"}catch{return"/"}let o=r.replace(/\/+$/,"");if(o==="")return n;if(n===o)return"/";if(n.startsWith(o+"/"))return n.slice(o.length).replace(/\/+$/,"")||"/";return n}var wd="https://better-auth.invalid";function $e(t,r){let n=t.startsWith("/");if(t.startsWith("//")||t.startsWith("/\\"))throw TypeError("Expected an absolute or root-relative URL");let o=n?new URL(t,wd):new URL(t);if(n&&o.origin!==wd)throw TypeError("Expected an absolute or root-relative URL");let i=r.toString();if(!i)return t;let s=o.search.endsWith("&")?"":"&";return o.search=o.search?`${o.search}${s}${i}`:i,n?o.href.slice(o.origin.length):o.href}var yd=["javascript:","data:","vbscript:"];function _d(t,r,n){let o=!1;return function(...i){if(!o)(n?.warn??console.warn)(`[Deprecation] ${r}`),o=!0;return t.apply(this,i)}}function Ad(t){return t.context.skipOriginCheck===!0&&t.context.options.advanced?.disableCSRFCheck===void 0}function Qi(t){let r=t.context.skipOriginCheck;if(r===!0)return!0;if(Array.isArray(r)&&t.request)try{let n=new URL(t.context.baseURL).pathname,o=gr(t.request.url,n);return r.some((i)=>{let s=i.replace(/\/+$/,"");return o===s||o.startsWith(`${s}/`)})}catch{}return!1}var Sg=_d(function(){},"disableOriginCheck: true currently also disables CSRF checks. In a future version, disableOriginCheck will ONLY disable URL validation. To keep CSRF disabled, add disableCSRFCheck: true to your config."),kd=Sn(async(t)=>{if(t.request?.method==="GET"||t.request?.method==="OPTIONS"||t.request?.method==="HEAD"||!t.request)return;if(await fo(t),Qi(t))return;let{body:r,query:n}=t,o=r?.callbackURL||n?.callbackURL,i=r?.redirectTo,s=r?.errorCallbackURL,a=r?.newUserCallbackURL,c=(d,u)=>{if(!d)return;if(typeof d!=="string")throw U.fromStatus("BAD_REQUEST",{message:`Invalid ${u}: expected a string`});if(!t.context.isTrustedOrigin(d,{allowRelativePaths:u!=="origin"})){if(t.context.logger.error(`Invalid ${u}: ${d}`),t.context.logger.info(`If it's a valid URL, please add ${d} to trustedOrigins in your auth config
32
+ `,`Current list of trustedOrigins: ${t.context.trustedOrigins}`),u==="origin")throw U.from("FORBIDDEN",Ae.INVALID_ORIGIN);if(u==="callbackURL")throw U.from("FORBIDDEN",Ae.INVALID_CALLBACK_URL);if(u==="redirectURL")throw U.from("FORBIDDEN",Ae.INVALID_REDIRECT_URL);if(u==="errorCallbackURL")throw U.from("FORBIDDEN",Ae.INVALID_ERROR_CALLBACK_URL);if(u==="newUserCallbackURL")throw U.from("FORBIDDEN",Ae.INVALID_NEW_USER_CALLBACK_URL);throw U.fromStatus("FORBIDDEN",{message:`Invalid ${u}`})}};o&&c(o,"callbackURL"),i&&c(i,"redirectURL"),s&&c(s,"errorCallbackURL"),a&&c(a,"newUserCallbackURL")}),bt=(t)=>Sn(async(r)=>{if(!r.request)return;if(Qi(r))return;let n=t(r),o=(s,a)=>{if(!s)return;if(!r.context.isTrustedOrigin(s,{allowRelativePaths:a!=="origin"})){if(r.context.logger.error(`Invalid ${a}: ${s}`),r.context.logger.info(`If it's a valid URL, please add ${s} to trustedOrigins in your auth config
33
+ `,`Current list of trustedOrigins: ${r.context.trustedOrigins}`),a==="origin")throw U.from("FORBIDDEN",Ae.INVALID_ORIGIN);if(a==="callbackURL")throw U.from("FORBIDDEN",Ae.INVALID_CALLBACK_URL);if(a==="redirectURL")throw U.from("FORBIDDEN",Ae.INVALID_REDIRECT_URL);if(a==="errorCallbackURL")throw U.from("FORBIDDEN",Ae.INVALID_ERROR_CALLBACK_URL);if(a==="newUserCallbackURL")throw U.from("FORBIDDEN",Ae.INVALID_NEW_USER_CALLBACK_URL);throw U.fromStatus("FORBIDDEN",{message:`Invalid ${a}`})}},i=Array.isArray(n)?n:[n];for(let s of i)o(s,"callbackURL")});async function fo(t,r=!1){let n=t.request?.headers;if(!n||!t.request)return;let o=n.get("origin"),i=o||n.get("referer")||"",s=n.has("cookie");if(t.context.skipCSRFCheck)return;if(Ad(t)){t.context.options.advanced?.disableOriginCheck===!0&&Sg();return}if(Qi(t))return;if(!(r||s))return;let a=o==="null"&&n.get("sec-fetch-site")==="same-origin"?Hs(void 0,t.context.options.basePath,t.request,!1,t.context.options.advanced?.trustedProxyHeaders):void 0,c=(a?Ai(a):void 0)??i;if(!c||c==="null")throw U.from("FORBIDDEN",Ae.MISSING_OR_NULL_ORIGIN);let d=Array.isArray(t.context.options.trustedOrigins)?t.context.trustedOrigins:[...t.context.trustedOrigins,...(await t.context.options.trustedOrigins?.(t.request))?.filter((u)=>Boolean(u))||[]];if(!d.some((u)=>cf(c,u)))throw t.context.logger.error(`Invalid origin: ${c}`),t.context.logger.info(`If it's a valid URL, please add ${c} to trustedOrigins in your auth config
34
+ `,`Current list of trustedOrigins: ${d}`),U.from("FORBIDDEN",Ae.INVALID_ORIGIN)}var Yr=Sn(async(t)=>{if(!t.request)return;await Rg(t)});async function Rg(t){let r=t.request;if(!r)return;if(t.context.skipCSRFCheck)return;if(Ad(t))return;let n=r.headers;if(n.has("cookie"))return await fo(t);let o=n.get("Sec-Fetch-Site"),i=n.get("Sec-Fetch-Mode"),s=n.get("Sec-Fetch-Dest");if(Boolean(o&&o.trim()||i&&i.trim()||s&&s.trim())){if(o==="cross-site"&&i==="navigate")throw t.context.logger.error("Blocked cross-site navigation login attempt (CSRF protection)",{secFetchSite:o,secFetchMode:i,secFetchDest:s}),U.from("FORBIDDEN",Ae.CROSS_SITE_NAVIGATION_LOGIN_BLOCKED);return await fo(t,!0)}if(n.get("origin")||n.get("referer"))return await fo(t,!0)}var vt=new Map,Ed=1e5;function Tg(){let t=Date.now();for(let[o,i]of vt)if(t>=i.expiresAt)vt.delete(o);if(vt.size<=Ed)return;let r=vt.size-Ed,n=0;for(let o of vt.keys())if(vt.delete(o),++n>=r)break}function Ig(t,r,n){let o=r.window*1000;if(!t)return{next:{key:"",count:1,lastRequest:n},update:!1,allowed:!0,retryAfter:null};if(n-t.lastRequest>=o)return{next:{...t,count:1,lastRequest:n},update:!0,allowed:!0,retryAfter:null};if(t.count>=r.max)return{next:t,update:!0,allowed:!1,retryAfter:vd(t.lastRequest,r.window)};return{next:{...t,count:t.count+1,lastRequest:n},update:!0,allowed:!0,retryAfter:null}}function Ug(t){return new Response(JSON.stringify({message:"Too many requests. Please try again later."}),{status:429,statusText:"Too Many Requests",headers:{"Content-Type":"application/json","X-Retry-After":t.toString()}})}function vd(t,r){let n=Date.now(),o=r*1000;return Math.ceil((t+o-n)/1000)}function Cg(t){let n=t.adapter,o=Math.max(...Og(t)),i=async(c)=>{let d=(await n.findMany({model:"rateLimit",where:[{field:"key",value:c}]}))[0];if(d)d.lastRequest=Number(d.lastRequest);return d},s=async(c,d)=>{if(d.window>o)o=d.window;let u=d.window*1000,f=await i(c),p=Date.now();if(!f)try{return await n.create({model:"rateLimit",data:{key:c,count:1,lastRequest:p}}),{allowed:!0,retryAfter:null}}catch(w){if(!await i(c))throw w;return s(c,d)}if(p-f.lastRequest>=u){if(await n.incrementOne({model:"rateLimit",where:[{field:"key",value:c},{field:"lastRequest",operator:"lte",value:f.lastRequest}],increment:{},set:{count:1,lastRequest:p}}))return await a(p),{allowed:!0,retryAfter:null};return s(c,d)}let h=p-u;if(await n.incrementOne({model:"rateLimit",where:[{field:"key",value:c},{field:"lastRequest",operator:"gt",value:h},{field:"count",operator:"lt",value:d.max}],increment:{count:1},set:{lastRequest:p}}))return{allowed:!0,retryAfter:null};let m=await i(c);if(!m)return s(c,d);if(p-m.lastRequest>=u)return s(c,d);return{allowed:!1,retryAfter:vd(m.lastRequest,d.window)}},a=async(c)=>{let d=c-o*1000;await t.runInBackgroundOrAwait(n.deleteMany({model:"rateLimit",where:[{field:"lastRequest",operator:"lt",value:d}]}).then(()=>{return}).catch((u)=>t.logger.error("Error pruning rate limit rows",u)))};return{consume:s}}function Og(t){let r=[t.rateLimit.window,...Rd().map((o)=>o.window)];for(let o of t.options.plugins||[])if(o.rateLimit)r.push(...o.rateLimit.map((i)=>i.window));if(t.rateLimit.customRules){for(let o of Object.values(t.rateLimit.customRules))if(o&&typeof o!=="function")r.push(o.window)}let n=r.filter((o)=>Number.isFinite(o)&&o>0);return n.length>0?n:[t.rateLimit.window]}function Dg(t,r){if(t.options.rateLimit?.customStorage)return t.options.rateLimit.customStorage;let n=t.rateLimit.storage;if(n==="secondary-storage"){let o=(s)=>s??t.options.rateLimit?.window??10,i=t.options.secondaryStorage?.increment;if(!i)throw new te("Secondary-storage rate limiting requires SecondaryStorage.increment.");return{consume:async(s,a)=>{if(await i(s,o(a.window))<=a.max)return{allowed:!0,retryAfter:null};return{allowed:!1,retryAfter:a.window}}}}else if(n==="memory"){let o=(i)=>i??t.options.rateLimit?.window??10;return{async consume(i,s){Tg();let a=Date.now(),c=vt.get(i),d=Ig(c&&a<c.expiresAt?c.data:void 0,s,a);if(d.allowed)vt.set(i,{data:{...d.next,key:i},expiresAt:a+o(s.window)*1000});return{allowed:d.allowed,retryAfter:d.retryAfter}}}}return Cg(t)}var bd=!1,Lg="no-trusted-ip";async function Pg(t,r){let n=new URL(r.baseURL).pathname,o=gr(t.url,n),i=r.rateLimit.window,s=r.rateLimit.max,a=lo(t,r.options);if(!a&&r.options.advanced?.ipAddress?.disableIpTracking)return null;if(!a&&!bd)r.logger.warn("Rate limiting could not determine a client IP and is falling back to a single shared per-path bucket. Ensure your runtime forwards a trusted client IP header, then set `advanced.ipAddress.ipAddressHeaders` or `advanced.ipAddress.trustedProxies` so the address can be resolved."),bd=!0;let c=dd(a??Lg,o),d=Rd().find((u)=>u.pathMatcher(o));if(d)i=d.window,s=d.max;for(let u of r.options.plugins||[])if(u.rateLimit){let f=u.rateLimit.find((p)=>p.pathMatcher(o));if(f){i=f.window,s=f.max;break}}if(r.rateLimit.customRules){let u=Object.keys(r.rateLimit.customRules).find((f)=>{if(f.includes("*"))return jt(f)(o);return f===o});if(u){let f=r.rateLimit.customRules[u],p=typeof f==="function"?await f(t,{window:i,max:s}):f;if(p)i=p.window,s=p.max;if(p===!1)return null}}return{key:c,currentWindow:i,currentMax:s}}async function Sd(t,r){if(!r.rateLimit.enabled)return;let n=await Pg(t,r);if(!n)return;let{key:o,currentWindow:i,currentMax:s}=n,a=Dg(r,{window:i}),c={window:i,max:s},{allowed:d,retryAfter:u}=await a.consume(o,c);if(!d)return Ug(u??i)}function Rd(){return[{pathMatcher(t){return t.startsWith("/sign-in")||t.startsWith("/sign-up")||t.startsWith("/change-password")||t.startsWith("/change-email")},window:10,max:3},{pathMatcher(t){return t==="/request-password-reset"||t==="/send-verification-email"||t.startsWith("/forget-password")||t==="/email-otp/send-verification-otp"||t==="/email-otp/request-password-reset"},window:60,max:3}]}var{get:xg,set:Gi}=Et(()=>null),Zi=async()=>await xg(),{get:Yi,set:zg}=Et(()=>null),es=async(t)=>{await zg({...await Yi()??{},...t})};var{get:ts,set:mT}=Et(()=>!1);var rs=()=>Pe("/get-session",{method:["GET","POST"],operationId:"getSession",query:Zc,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(t)=>{t.setHeader("cache-control","no-store"),t.setHeader("pragma","no-cache");let r=t.context.options.session?.deferSessionRefresh,n=t.method==="POST";if(n&&!r)throw U.from("METHOD_NOT_ALLOWED",Ae.METHOD_NOT_ALLOWED_DEFER_SESSION_REQUIRED);try{let o=t.context.options.session?.cookieCache?.enabled===!0,i=await t.getSignedCookie(t.context.authCookies.sessionToken.name,t.context.secret);if(!i&&o)return null;let s=oo(t,t.context.authCookies.sessionData.name);if(s&&!o){let b=Fr(t.context.authCookies.sessionData.name,t.context.authCookies.sessionData.attributes,t);b.setCookies(b.clean())}if(!i)return null;let a=o&&!t.query?.disableCookieCache,c=a&&s?await Xc(t,s):null;if(a&&s&&!c)Be(t,t.context.authCookies.sessionData);let d=await t.getSignedCookie(t.context.authCookies.dontRememberToken.name,t.context.secret);if(c?.session){let b=c.session,O=b.session.token!==i;if(!O){let g=t.context.options.session?.cookieCache?.version,S="1";if(g){if(typeof g==="string")S=g;else if(typeof g==="function"){let C=g(b.session,b.user);S=C instanceof Promise?await C:C}}O=(b.version||"1")!==S}if(!O){let g=Date.now(),S=new Date(b.session.expiresAt).getTime();O=c.expiresAt<g||!Number.isFinite(S)||S<g}if(O)Be(t,t.context.authCookies.sessionData);else{let g=t.context.sessionConfig.cookieRefreshCache;if(g===!1){t.context.session=b;let P=we(t.context.options,{...b.session,expiresAt:new Date(b.session.expiresAt),createdAt:new Date(b.session.createdAt),updatedAt:new Date(b.session.updatedAt)}),j=se(t.context.options,{...b.user,createdAt:new Date(b.user.createdAt),updatedAt:new Date(b.user.updatedAt)});return t.json({session:P,user:j})}let S=c.expiresAt-Date.now(),C=g.updateAge*1000,z=await ts();if(S<C&&!z){let P={session:{...b.session},user:b.user,updatedAt:Date.now()};await Kr(t,P,!1);let j=t.context.authCookies.sessionToken.attributes,B=d?void 0:t.context.sessionConfig.expiresIn;await t.setSignedCookie(t.context.authCookies.sessionToken.name,b.session.token,t.context.secret,{...j,maxAge:B});let H=we(t.context.options,{...P.session,expiresAt:new Date(P.session.expiresAt),createdAt:new Date(P.session.createdAt),updatedAt:new Date(P.session.updatedAt)}),q=se(t.context.options,{...P.user,createdAt:new Date(P.user.createdAt),updatedAt:new Date(P.user.updatedAt)});return t.context.session={session:H,user:q},t.json({session:H,user:q})}let L=we(t.context.options,{...b.session,expiresAt:new Date(b.session.expiresAt),createdAt:new Date(b.session.createdAt),updatedAt:new Date(b.session.updatedAt)}),x=se(t.context.options,{...b.user,createdAt:new Date(b.user.createdAt),updatedAt:new Date(b.user.updatedAt)});return t.context.session={session:L,user:x},t.json({session:L,user:x})}}let u=await t.context.internalAdapter.findSession(i);if(t.context.session=u,!u||u.session.expiresAt<new Date){if(Le(t),u){if(!r||n)await t.context.internalAdapter.deleteSession(u.session.token)}return t.json(null)}if(d||t.query?.disableRefresh){let b=we(t.context.options,u.session),O=se(t.context.options,u.user);return t.json({session:b,user:O})}let f=t.context.sessionConfig.expiresIn,p=t.context.sessionConfig.updateAge,h=u.session.expiresAt.valueOf()-f*1000+p*1000<=Date.now(),m=t.query?.disableRefresh||t.context.options.session?.disableSessionRefresh,w=await ts(),y=h&&!m&&!w;if(r&&!n){await Kr(t,u,!!d);let b=we(t.context.options,u.session),O=se(t.context.options,u.user);return t.json({session:b,user:O,needsRefresh:y})}if(y){let b=await t.context.internalAdapter.updateSession(u.session.token,{expiresAt:ut(t.context.sessionConfig.expiresIn,"sec"),updatedAt:new Date});if(!b)throw Le(t),U.from("UNAUTHORIZED",Ae.FAILED_TO_GET_SESSION);let O=t.context.sessionConfig.expiresIn;await pe(t,{session:b,user:u.user},!1,{maxAge:O});let g=we(t.context.options,b),S=se(t.context.options,u.user);return t.json({session:g,user:S})}await Kr(t,u,!!d);let I=we(t.context.options,u.session),R=se(t.context.options,u.user);return t.json({session:I,user:R})}catch(o){if(Ur(o))throw o;throw t.context.logger.error("INTERNAL_SERVER_ERROR",o),U.from("INTERNAL_SERVER_ERROR",Ae.FAILED_TO_GET_SESSION,{cause:o})}}),St=(t)=>uf(t.context.options),ee=async(t,r)=>{if(t.context.session)return t.context.session;let n=await rs()({...t,method:"GET",asResponse:!1,headers:t.headers,returnHeaders:!0,returnStatus:!1,query:{...r,...t.query,disableCookieCache:r?.disableCookieCache||t.query?.disableCookieCache,disableRefresh:r?.disableRefresh||t.query?.disableRefresh}}).catch(()=>null);if(!n)return t.context.session=null,null;if(n.headers)n.headers.forEach((o,i)=>{let s=i.toLowerCase();if(s==="cache-control"||s==="pragma")return;if(s==="set-cookie")t.responseHeaders.append(i,o);else t.responseHeaders.set(i,o)});return t.context.session=n.response,n.response},Td=async(t)=>{if(!St(t))return ee(t);return t.context.session=null,ee(t,{disableCookieCache:!0})},Hr=Sn(async(t)=>{let r=await ee(t);if(!r?.session)throw U.from("UNAUTHORIZED",{message:"Unauthorized",code:"UNAUTHORIZED"});return{session:r}}),Qe=Sn(async(t)=>{let r=await Td(t);if(!r?.session)throw U.from("UNAUTHORIZED",{message:"Unauthorized",code:"UNAUTHORIZED"});return{session:r}}),Ng=Sn(async(t)=>{let r=await ee(t);if(!r?.session&&(t.request||t.headers))throw U.from("UNAUTHORIZED",{message:"Unauthorized",code:"UNAUTHORIZED"});return{session:r}}),po=Sn(async(t)=>{let r=await ee(t);if(!r?.session)throw U.from("UNAUTHORIZED",{message:"Unauthorized",code:"UNAUTHORIZED"});if(t.context.sessionConfig.freshAge!==0){let n=new Date(r.session.createdAt).getTime(),o=t.context.sessionConfig.freshAge*1000;if(Date.now()-n>=o)throw U.from("FORBIDDEN",Ae.SESSION_NOT_FRESH)}return{session:r}}),Id=()=>Pe("/list-sessions",{method:"GET",operationId:"listUserSessions",use:[po],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(t)=>{try{let r=(await t.context.internalAdapter.listSessions(t.context.session.user.id,{onlyActiveSessions:!0})).filter((n)=>n.expiresAt>new Date);return t.json(r.map((n)=>we(t.context.options,n)))}catch(r){throw t.context.logger.error(r),t.error("INTERNAL_SERVER_ERROR")}}),Ud=Pe("/revoke-session",{method:"POST",body:l({token:e().meta({description:"The token to revoke"})}),use:[Qe],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(t)=>{let r=t.body.token;if((await t.context.internalAdapter.findSession(r))?.session.userId===t.context.session.user.id)try{await t.context.internalAdapter.deleteSession(r)}catch(n){throw t.context.logger.error(n&&typeof n==="object"&&"name"in n?n.name:"",n),U.from("INTERNAL_SERVER_ERROR",{message:"Internal Server Error",code:"INTERNAL_SERVER_ERROR"})}return t.json({status:!0})}),Cd=Pe("/revoke-sessions",{method:"POST",use:[Qe],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(t)=>{try{await t.context.internalAdapter.deleteUserSessions(t.context.session.user.id)}catch(r){throw t.context.logger.error(r&&typeof r==="object"&&"name"in r?r.name:"",r),U.from("INTERNAL_SERVER_ERROR",{message:"Internal Server Error",code:"INTERNAL_SERVER_ERROR"})}return t.json({status:!0})}),Od=Pe("/revoke-other-sessions",{method:"POST",requireHeaders:!0,use:[Qe],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(t)=>{let r=t.context.session;if(!r.user)throw U.from("UNAUTHORIZED",{message:"Unauthorized",code:"UNAUTHORIZED"});let n=(await t.context.internalAdapter.listSessions(r.user.id)).filter((o)=>o.expiresAt>new Date).filter((o)=>o.token!==t.context.session.session.token);return await Promise.all(n.map((o)=>t.context.internalAdapter.deleteSession(o.token))),t.json({status:!0})});function ho(t){return t}async function ns(t,r,n){let o={tokens:r,profile:n},i=t.accountSubject,s=await i(o),a=String(s);if(typeof s==="number"&&!Number.isFinite(s)||a.trim().length===0||a==="undefined"||a==="null")throw new te("OAUTH_ACCOUNT_SUBJECT_INVALID");return{providerId:t.id,accountId:a}}async function mo(t,r,n){try{return await ns(t,r,n)}catch{throw U.from("UNAUTHORIZED",Ae.FAILED_TO_GET_USER_INFO)}}var he={NO_CODE:"no_code",PROVIDER_NOT_FOUND:"oauth_provider_not_found",ISSUER_MISSING:"issuer_missing",ISSUER_MISMATCH:"issuer_mismatch",INVALID_CODE:"invalid_code",NONCE_BINDING_MISSING:"nonce_binding_missing",UNABLE_TO_GET_USER_INFO:"unable_to_get_user_info",NO_CALLBACK_URL:"no_callback_url",UNABLE_TO_LINK_ACCOUNT:"unable_to_link_account",EMAIL_DOES_NOT_MATCH:"email_does_not_match",ACCOUNT_ALREADY_LINKED_TO_DIFFERENT_USER:"account_already_linked_to_different_user",EMAIL_NOT_FOUND:"email_not_found",EMAIL_NOT_VERIFIED:"email_not_verified"},qg="https://www.better-auth.com/docs/concepts/oauth#handling-providers-without-email";function Xr(t,r,n,o){let i=new URLSearchParams({error:n});if(o)i.set("error_description",o);let s=$e(r,i);throw t.redirect(s)}function wr(t,r){return`${r?.source==="generic"?`Generic OAuth provider "${t}"`:`Provider "${t}"`} did not return an email${r?.source==="id_token"?" in the id token":""}. Either request the provider's email scope, or create a placeholder via \`mapProfileToUser\`. See ${qg}`}function Vt(t,r){if(typeof t==="string")t=new TextEncoder().encode(t);if(typeof r==="string")r=new TextEncoder().encode(r);let n=new Uint8Array(t),o=new Uint8Array(r),i=n.length^o.length,s=Math.max(n.length,o.length);for(let a=0;a<s;a++)i|=(a<n.length?n[a]:0)^(a<o.length?o[a]:0);return i===0}var _e=Cl("a-z","0-9","A-Z","-_");/*! noble-ciphers - MIT License (c) 2023 Paul Miller (paulmillr.com) */function os(t){return t instanceof Uint8Array||ArrayBuffer.isView(t)&&t.constructor.name==="Uint8Array"&&"BYTES_PER_ELEMENT"in t&&t.BYTES_PER_ELEMENT===1}var wo=(t)=>t?`"${t}" `:"";function yo(t,r=""){if(typeof t!=="boolean")throw TypeError(wo(r)+"expected boolean, got type="+typeof t);return t}function pt(t,r=""){if(typeof t!=="number")throw TypeError(wo(r)+"expected number, got "+typeof t);if(!Number.isSafeInteger(t)||t<0)throw RangeError(wo(r)+"expected integer >= 0, got "+t);return t}function de(t,r,n=""){if(os(t)&&(r===void 0||t.length===r))return t;if(r!==void 0)pt(r,"length");let o=os(t),i=r!==void 0?` of length ${r}`:"",s=o?`length=${t.length}`:`type=${typeof t}`,a=wo(n)+"expected Uint8Array"+i+", got "+s;if(!o)throw TypeError(a);throw RangeError(a)}var Dd=(t,r)=>{if(t===null||typeof t!=="object"||Array.isArray(t))throw TypeError(r==="object"?"expected valid options object":`"${r}" expected object, got type=${typeof t}`)};function is(t,r=!0){if(t.destroyed)throw Error("hash was destroyed");if(r&&t.finished)throw Error("digest() was already called")}function Pd(t,r){de(t,void 0,"output");let n=r.outputLen;if(!(t.length>=n))throw RangeError('"output" expected length >= '+n)}function rt(t){return new Uint32Array(t.buffer,t.byteOffset,Math.floor(t.byteLength/4))}function ze(...t){for(let r=0;r<t.length;r++)t[r].fill(0)}function jg(t){return new DataView(t.buffer,t.byteOffset,t.byteLength)}var He=(()=>new Uint8Array(new Uint32Array([287454020]).buffer)[0]===68)();function Bg(t){return t<<24&4278190080|t<<8&16711680|t>>>8&65280|t>>>24&255}function $g(t){for(let r=0;r<t.length;r++)t[r]=Bg(t[r]);return t}var Ne=He?(t)=>t:$g,xd=(()=>typeof Uint8Array.from([]).toHex==="function"&&typeof Uint8Array.fromHex==="function")(),Mg=Array.from({length:256},(t,r)=>r.toString(16).padStart(2,"0"));function zd(t){if(de(t),xd)return t.toHex();let r="";for(let n=0;n<t.length;n++)r+=Mg[t[n]];return r}function Ld(t){return t>=48&&t<=57?t-48:t>=65&&t<=70?t-55:t>=97&&t<=102?t-87:void 0}function Nd(t){if(typeof t!=="string")throw TypeError("hex string expected, got "+typeof t);if(xd)try{return Uint8Array.fromHex(t)}catch(i){if(i instanceof SyntaxError)throw RangeError(i.message);throw i}let r=t.length,n=r/2;if(r%2)throw RangeError("hex string expected, got unpadded hex of length "+r);let o=new Uint8Array(n);for(let i=0,s=0;i<n;i++,s+=2){let a=Ld(t.charCodeAt(s)),c=Ld(t.charCodeAt(s+1));if(a===void 0||c===void 0){let d=t[s]+t[s+1];throw RangeError('hex string expected, got non-hex character "'+d+'" at index '+s)}o[i]=a*16+c}return o}function qd(t){if(typeof t!=="string")throw TypeError("string expected");return new Uint8Array(new TextEncoder().encode(t))}function jd(t,r){if(!t.byteLength||!r.byteLength)return!1;return t.buffer===r.buffer&&t.byteOffset<r.byteOffset+r.byteLength&&r.byteOffset<t.byteOffset+t.byteLength}function Bd(t,r){if(jd(t,r)&&t.byteOffset<r.byteOffset)throw Error("complex overlap of input and output is not supported")}function Hg(...t){let r=0;for(let o=0;o<t.length;o++){let i=t[o];de(i),r+=i.length}let n=new Uint8Array(r);for(let o=0,i=0;o<t.length;o++){let s=t[o];n.set(s,i),i+=s.length}return n}function $d(t,r){return Dd(t,"defaults"),Dd(r,"opts"),Object.assign(t,r)}function Md(t,r){if(t=de(t),r=de(r),t.length!==r.length)return!1;let n=0;for(let o=0;o<t.length;o++)n|=t[o]^r[o];return n===0}function Hd(t,r,n){let o=r,i=n||(()=>[]),s=(c,d)=>o(d,...i(c)).update(c).digest(),a=o(new Uint8Array(t),...i(new Uint8Array(0)));return s.outputLen=a.outputLen,s.blockLen=a.blockLen,s.create=(c,...d)=>o(c,...d),s}var Vd=(t,r)=>{function n(o,...i){if(de(o,void 0,"key"),t.nonceLength!==void 0){let p=i[0];de(p,t.varSizeNonce?void 0:t.nonceLength,"nonce")}let s=t.tagLength,a=t.nonceLength!==void 0?1:0;if(!t.withAAD){for(let p=a;p<i.length;p++)if(os(i[p]))throw Error("AAD not supported")}if(t.withAAD&&i[a]!==void 0)de(i[a],void 0,"AAD");let c=r(o,...i),d=(p,h)=>{if(h!==void 0){if(p!==2)throw Error("cipher output not supported");de(h,void 0,"output")}},u=!1;return{encrypt(p,h){if(u)throw Error("cannot encrypt() twice with same key + nonce");return u=!0,de(p,void 0,"data"),d(c.encrypt.length,h),c.encrypt(p,h)},decrypt(p,h){if(de(p,void 0,"data"),s&&p.length<s)throw Error('"ciphertext" expected length >= tagLength='+s);return d(c.decrypt.length,h),c.decrypt(p,h)}}}return Object.assign(n,t),n};function tn(t,r,n=!0){if(r===void 0)return new Uint8Array(t);if(de(r,t,"output"),n&&!rn(r))throw Error("invalid output, must be aligned");return r}function Fd(t,r,n){pt(t),pt(r),yo(n);let o=new Uint8Array(16),i=jg(o);return i.setBigUint64(0,BigInt(r),n),i.setBigUint64(8,BigInt(t),n),o}function rn(t){return t.byteOffset%4===0}function yr(t){return Uint8Array.from(de(t))}function Kd(t=32){pt(t,"bytesLength");let r=typeof globalThis==="object"?globalThis.crypto:null;if(typeof r?.getRandomValues!=="function")throw Error("crypto.getRandomValues must be defined");if(t>65536)throw RangeError(`"bytesLength" expected <= 65536, got ${t}`);return r.getRandomValues(new Uint8Array(t))}function ss(t,r=Kd){if(typeof t!=="function")throw TypeError('"fn" expected cipher constructor, got type='+typeof t);if(typeof r!=="function")throw TypeError('"randomBytes_" expected function, got type='+typeof r);let{nonceLength:n}=t;pt(n,"fn.nonceLength");let o=(s,a,c)=>{let d=Hg(s,a);if(!jd(c,a))a.fill(0);return d},i=(s,...a)=>({encrypt(c){de(c,void 0,"data");let d=r(n),u=t(s,d,...a).encrypt(c);if(u instanceof Promise)return u.then((f)=>o(d,f,c));return o(d,u,c)},decrypt(c){de(c,void 0,"data");let d=c.subarray(0,n),u=c.subarray(n);return t(s,d,...a).decrypt(u)}});if("blockSize"in t)i.blockSize=t.blockSize;if("tagLength"in t)i.tagLength=t.tagLength;if("withAAD"in t)i.withAAD=t.withAAD;return i}var Jd=(t)=>Uint8Array.from(t.split(""),(r)=>r.charCodeAt(0)),Fg=(()=>Ne(rt(Jd("expand 16-byte k"))))(),Zg=(()=>Ne(rt(Jd("expand 32-byte k"))))();function ne(t,r){return t<<r|t>>>32-r}var nn=64,ew=16,as=(()=>4294967295)(),Wd=Uint32Array.of();function tw(t,r,n,o,i,s,a,c){let d=i.length,u=new Uint8Array(nn),f=rt(u),p=He&&rn(i)&&rn(s),h=p?rt(i):Wd,m=p?rt(s):Wd;if(!He){for(let w=0;w<d;a++){if(t(r,n,o,f,a,c),Ne(f),a>=as)throw Error("arx: counter overflow");let y=Math.min(nn,d-w);for(let I=0,R;I<y;I++)R=w+I,s[R]=i[R]^u[I];w+=y}return}for(let w=0;w<d;a++){if(t(r,n,o,f,a,c),a>=as)throw Error("arx: counter overflow");let y=Math.min(nn,d-w);if(p&&y===nn){let I=w/4;if(w%4!==0)throw Error("arx: invalid block position");for(let R=0,b;R<ew;R++)b=I+R,m[b]=h[b]^f[R];w+=nn;continue}for(let I=0,R;I<y;I++)R=w+I,s[R]=i[R]^u[I];w+=y}}function Qd(t,r){let{allowShortKeys:n,extendNonceFn:o,counterLength:i,counterRight:s,rounds:a}=$d({allowShortKeys:!1,counterLength:8,counterRight:!1,rounds:20},r);if(typeof t!=="function")throw Error("core must be a function");return pt(i),pt(a),yo(s),yo(n),(c,d,u,f,p=0)=>{de(c,void 0,"key"),de(d,void 0,"nonce"),de(u,void 0,"data");let h=u.length,m=f!==void 0;if(f=tn(h,f,!1),m)Bd(u,f);if(pt(p),p<0||p>=as)throw Error("arx: counter overflow");let w=[],y=c.length,I,R;if(y===32)w.push(I=yr(c)),R=Zg;else if(y===16&&n)I=new Uint8Array(32),I.set(c),I.set(c,16),R=Fg,w.push(I);else throw de(c,32,"arx key"),Error("invalid key size");if(!He||!rn(d))w.push(d=yr(d));let b=rt(I);if(o){if(d.length!==24)throw Error("arx: extended nonce must be 24 bytes");let S=d.subarray(0,16);if(He)o(R,b,rt(S),b);else{let C=Ne(Uint32Array.from(R));o(C,b,rt(S),b),ze(C),Ne(b)}d=d.subarray(16)}else if(!He)Ne(b);let O=16-i;if(O!==d.length)throw Error(`arx: nonce must be ${O} or 16 bytes`);if(O!==12){let S=new Uint8Array(12);S.set(d,s?0:12-d.length),d=S,w.push(d)}let g=Ne(rt(d));try{return tw(t,R,b,g,u,f,p,a),f}finally{ze(...w)}}}function be(t,r){return t[r++]&255|(t[r++]&255)<<8}class Gd{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(t){t=yr(de(t,32,"key"));let r=be(t,0),n=be(t,2),o=be(t,4),i=be(t,6),s=be(t,8),a=be(t,10),c=be(t,12),d=be(t,14);this.r[0]=r&8191,this.r[1]=(r>>>13|n<<3)&8191,this.r[2]=(n>>>10|o<<6)&7939,this.r[3]=(o>>>7|i<<9)&8191,this.r[4]=(i>>>4|s<<12)&255,this.r[5]=s>>>1&8190,this.r[6]=(s>>>14|a<<2)&8191,this.r[7]=(a>>>11|c<<5)&8065,this.r[8]=(c>>>8|d<<8)&8191,this.r[9]=d>>>5&127;for(let u=0;u<8;u++)this.pad[u]=be(t,16+2*u)}process(t,r,n=!1){let o=n?0:2048,{h:i,r:s}=this,a=s[0],c=s[1],d=s[2],u=s[3],f=s[4],p=s[5],h=s[6],m=s[7],w=s[8],y=s[9],I=be(t,r+0),R=be(t,r+2),b=be(t,r+4),O=be(t,r+6),g=be(t,r+8),S=be(t,r+10),C=be(t,r+12),z=be(t,r+14),L=i[0]+(I&8191),x=i[1]+((I>>>13|R<<3)&8191),P=i[2]+((R>>>10|b<<6)&8191),j=i[3]+((b>>>7|O<<9)&8191),B=i[4]+((O>>>4|g<<12)&8191),H=i[5]+(g>>>1&8191),q=i[6]+((g>>>14|S<<2)&8191),W=i[7]+((S>>>11|C<<5)&8191),Q=i[8]+((C>>>8|z<<8)&8191),G=i[9]+(z>>>5|o),M=0,Y=M+L*a+x*(5*y)+P*(5*w)+j*(5*m)+B*(5*h);M=Y>>>13,Y&=8191,Y+=H*(5*p)+q*(5*f)+W*(5*u)+Q*(5*d)+G*(5*c),M+=Y>>>13,Y&=8191;let Z=M+L*c+x*a+P*(5*y)+j*(5*w)+B*(5*m);M=Z>>>13,Z&=8191,Z+=H*(5*h)+q*(5*p)+W*(5*f)+Q*(5*u)+G*(5*d),M+=Z>>>13,Z&=8191;let re=M+L*d+x*c+P*a+j*(5*y)+B*(5*w);M=re>>>13,re&=8191,re+=H*(5*m)+q*(5*h)+W*(5*p)+Q*(5*f)+G*(5*u),M+=re>>>13,re&=8191;let ie=M+L*u+x*d+P*c+j*a+B*(5*y);M=ie>>>13,ie&=8191,ie+=H*(5*w)+q*(5*m)+W*(5*h)+Q*(5*p)+G*(5*f),M+=ie>>>13,ie&=8191;let qe=M+L*f+x*u+P*d+j*c+B*a;M=qe>>>13,qe&=8191,qe+=H*(5*y)+q*(5*w)+W*(5*m)+Q*(5*h)+G*(5*p),M+=qe>>>13,qe&=8191;let gt=M+L*p+x*f+P*u+j*d+B*c;M=gt>>>13,gt&=8191,gt+=H*a+q*(5*y)+W*(5*w)+Q*(5*m)+G*(5*h),M+=gt>>>13,gt&=8191;let ct=M+L*h+x*p+P*f+j*u+B*d;M=ct>>>13,ct&=8191,ct+=H*c+q*a+W*(5*y)+Q*(5*w)+G*(5*m),M+=ct>>>13,ct&=8191;let Ke=M+L*m+x*h+P*p+j*f+B*u;M=Ke>>>13,Ke&=8191,Ke+=H*d+q*c+W*a+Q*(5*y)+G*(5*w),M+=Ke>>>13,Ke&=8191;let wt=M+L*w+x*m+P*h+j*p+B*f;M=wt>>>13,wt&=8191,wt+=H*u+q*d+W*c+Q*a+G*(5*y),M+=wt>>>13,wt&=8191;let ar=M+L*y+x*w+P*m+j*h+B*p;M=ar>>>13,ar&=8191,ar+=H*f+q*u+W*d+Q*c+G*a,M+=ar>>>13,ar&=8191,M=(M<<2)+M|0,M=M+Y|0,Y=M&8191,M=M>>>13,Z+=M,i[0]=Y,i[1]=Z,i[2]=re,i[3]=ie,i[4]=qe,i[5]=gt,i[6]=ct,i[7]=Ke,i[8]=wt,i[9]=ar}finalize(){let{h:t,pad:r}=this,n=new Uint16Array(10),o=t[1]>>>13;t[1]&=8191;for(let a=2;a<10;a++)t[a]+=o,o=t[a]>>>13,t[a]&=8191;t[0]+=o*5,o=t[0]>>>13,t[0]&=8191,t[1]+=o,o=t[1]>>>13,t[1]&=8191,t[2]+=o,n[0]=t[0]+5,o=n[0]>>>13,n[0]&=8191;for(let a=1;a<10;a++)n[a]=t[a]+o,o=n[a]>>>13,n[a]&=8191;n[9]-=8192;let i=(o^1)-1;for(let a=0;a<10;a++)n[a]&=i;i=~i;for(let a=0;a<10;a++)t[a]=t[a]&i|n[a];t[0]=(t[0]|t[1]<<13)&65535,t[1]=(t[1]>>>3|t[2]<<10)&65535,t[2]=(t[2]>>>6|t[3]<<7)&65535,t[3]=(t[3]>>>9|t[4]<<4)&65535,t[4]=(t[4]>>>12|t[5]<<1|t[6]<<14)&65535,t[5]=(t[6]>>>2|t[7]<<11)&65535,t[6]=(t[7]>>>5|t[8]<<8)&65535,t[7]=(t[8]>>>8|t[9]<<5)&65535;let s=t[0]+r[0];t[0]=s&65535;for(let a=1;a<8;a++)s=(t[a]+r[a]|0)+(s>>>16)|0,t[a]=s&65535;ze(n)}update(t){is(this),de(t),t=yr(t);let{buffer:r,blockLen:n}=this,o=t.length;for(let i=0;i<o;){let s=Math.min(n-this.pos,o-i);if(s===n){for(;n<=o-i;i+=n)this.process(t,i);continue}if(r.set(t.subarray(i,i+s),this.pos),this.pos+=s,i+=s,this.pos===n)this.process(r,0,!1),this.pos=0}return this}destroy(){this.destroyed=!0,ze(this.h,this.r,this.buffer,this.pad)}digestInto(t){is(this),Pd(t,this),this.finished=!0;let{buffer:r,h:n}=this,{pos:o}=this;if(o){r[o++]=1;for(;o<16;o++)r[o]=0;this.process(r,0,!0)}this.finalize();let i=0;for(let s=0;s<8;s++)t[i++]=n[s]>>>0,t[i++]=n[s]>>>8}digest(){let{buffer:t,outputLen:r}=this;this.digestInto(t);let n=t.slice(0,r);return this.destroy(),n}}var Zd=Hd(32,(t)=>new Gd(t));function eu(t,r,n,o,i,s=20){let a=t[0],c=t[1],d=t[2],u=t[3],f=r[0],p=r[1],h=r[2],m=r[3],w=r[4],y=r[5],I=r[6],R=r[7],b=i,O=n[0],g=n[1],S=n[2],C=a,z=c,L=d,x=u,P=f,j=p,B=h,H=m,q=w,W=y,Q=I,G=R,M=b,Y=O,Z=g,re=S;for(let qe=0;qe<s;qe+=2)C=C+P|0,M=ne(M^C,16),q=q+M|0,P=ne(P^q,12),C=C+P|0,M=ne(M^C,8),q=q+M|0,P=ne(P^q,7),z=z+j|0,Y=ne(Y^z,16),W=W+Y|0,j=ne(j^W,12),z=z+j|0,Y=ne(Y^z,8),W=W+Y|0,j=ne(j^W,7),L=L+B|0,Z=ne(Z^L,16),Q=Q+Z|0,B=ne(B^Q,12),L=L+B|0,Z=ne(Z^L,8),Q=Q+Z|0,B=ne(B^Q,7),x=x+H|0,re=ne(re^x,16),G=G+re|0,H=ne(H^G,12),x=x+H|0,re=ne(re^x,8),G=G+re|0,H=ne(H^G,7),C=C+j|0,re=ne(re^C,16),Q=Q+re|0,j=ne(j^Q,12),C=C+j|0,re=ne(re^C,8),Q=Q+re|0,j=ne(j^Q,7),z=z+B|0,M=ne(M^z,16),G=G+M|0,B=ne(B^G,12),z=z+B|0,M=ne(M^z,8),G=G+M|0,B=ne(B^G,7),L=L+H|0,Y=ne(Y^L,16),q=q+Y|0,H=ne(H^q,12),L=L+H|0,Y=ne(Y^L,8),q=q+Y|0,H=ne(H^q,7),x=x+P|0,Z=ne(Z^x,16),W=W+Z|0,P=ne(P^W,12),x=x+P|0,Z=ne(Z^x,8),W=W+Z|0,P=ne(P^W,7);let ie=0;o[ie++]=a+C|0,o[ie++]=c+z|0,o[ie++]=d+L|0,o[ie++]=u+x|0,o[ie++]=f+P|0,o[ie++]=p+j|0,o[ie++]=h+B|0,o[ie++]=m+H|0,o[ie++]=w+q|0,o[ie++]=y+W|0,o[ie++]=I+Q|0,o[ie++]=R+G|0,o[ie++]=b+M|0,o[ie++]=O+Y|0,o[ie++]=g+Z|0,o[ie++]=S+re|0}function rw(t,r,n,o){let i=He?t:Ne(t.slice(0,4)),s=He?r:Ne(r.slice(0,8)),a=He?n:Ne(n.slice(0,4)),c=new Uint32Array(16);eu(i,s,a.subarray(1),c,a[0]);let d=0;if(o[d++]=c[0]-i[0]|0,o[d++]=c[1]-i[1]|0,o[d++]=c[2]-i[2]|0,o[d++]=c[3]-i[3]|0,o[d++]=c[12]-a[0]|0,o[d++]=c[13]-a[1]|0,o[d++]=c[14]-a[2]|0,o[d++]=c[15]-a[3]|0,Ne(o),!He)ze(i,s,a);ze(c)}var nw=Qd(eu,{counterRight:!1,counterLength:8,extendNonceFn:rw,allowShortKeys:!1});var ow=new Uint8Array(16),Yd=(t,r)=>{t.update(r);let n=r.length%16;if(n)t.update(ow.subarray(n))},iw=new Uint8Array(32);function Xd(t,r,n,o,i){if(i!==void 0)de(i,void 0,"AAD");let s=t(r,n,iw),a=Fd(o.length,i?i.length:0,!0),c=Zd.create(s);if(i)Yd(c,i);Yd(c,o),c.update(a);let d=c.digest();return ze(s,a),d}var sw=(t)=>(r,n,o)=>({encrypt(s,a){let c=s.length;a=tn(c+16,a,!1),a.set(s);let d=a.subarray(0,-16);t(r,n,d,d,1);let u=Xd(t,r,n,d,o);return a.set(u,c),ze(u),a},decrypt(s,a){a=tn(s.length-16,a,!1);let c=s.subarray(0,-16),d=s.subarray(-16),u=Xd(t,r,n,c,o);if(!Md(d,u))throw ze(u),Error("invalid tag");return a.set(s.subarray(0,-16)),t(r,n,a,a,1),ze(u),a}});var fs=Vd({blockSize:64,nonceLength:24,tagLength:16,withAAD:!0},sw(nw));var ru={name:"HMAC",hash:"SHA-256"},nu="$ba$";function aw(t){if(!t.startsWith(nu))return null;let r=4,n=t.indexOf("$",r);if(n===-1)return null;let o=parseInt(t.slice(r,n),10);if(!Number.isInteger(o)||o<0)return null;return{version:o,ciphertext:t.slice(n+1)}}function cw(t,r){return`${nu}${t}$${r}`}async function tu(t,r){let n=await cs("SHA-256").digest(t),o=qd(r);return zd(ss(fs)(new Uint8Array(n)).encrypt(o))}async function ps(t,r){let n=await cs("SHA-256").digest(t),o=Nd(r),i=ss(fs)(new Uint8Array(n));return new TextDecoder().decode(i.decrypt(o))}var nt=async({key:t,data:r})=>{if(typeof t==="string")return tu(t,r);let n=t.keys.get(t.currentVersion);if(!n)throw Error(`Secret version ${t.currentVersion} not found in keys`);let o=await tu(n,r);return cw(t.currentVersion,o)},ot=async({key:t,data:r})=>{if(typeof t==="string")return ps(t,r);let n=aw(r);if(n){let o=t.keys.get(n.version);if(!o)throw Error(`Secret version ${n.version} not found in keys (key may have been retired)`);return ps(o,n.ciphertext)}if(t.legacySecret)return ps(t.legacySecret,r);throw Error("Cannot decrypt legacy bare-hex payload: no legacy secret available. Set BETTER_AUTH_SECRET for backwards compatibility.")},dw=async(t)=>{let r=typeof t==="string"?new TextEncoder().encode(t):t;return await De().importKey("raw",r,ru,!1,["sign","verify"])},on=async(t,r)=>{let n=await dw(r),o=await De().sign(ru.name,n,new TextEncoder().encode(t));return btoa(String.fromCharCode(...new Uint8Array(o)))};function uw(t){if(t.startsWith("$ba$"))return!0;return t.length%2===0&&/^[0-9a-f]+$/i.test(t)}function _o(t,r){if(!t)return t;if(r.options.account?.encryptOAuthTokens){if(!uw(t))return t;return ot({key:r.secretConfig,data:t})}return t}function me(t,r){if(r.options.account?.encryptOAuthTokens&&t)return nt({key:r.secretConfig,data:t});return t}function Rt(t){if(!t.callbackPath)return`/callback/${t.id}`;return t.callbackPath.startsWith("/")?t.callbackPath:`/${t.callbackPath}`}function Tt(t){if(!t)return;try{return t.clone()}catch{return new Request(t.url,{cache:t.cache,credentials:t.credentials,headers:t.headers,integrity:t.integrity,keepalive:t.keepalive,method:t.method,mode:t.mode,redirect:t.redirect,referrer:t.referrer,referrerPolicy:t.referrerPolicy,signal:t.signal})}}async function Se(t,r,n,o=3600,i){return await $n({email:r.toLowerCase(),updateTo:n?.toLowerCase(),...i},t,o)}async function hs(t,r){if(!t.context.options.emailVerification?.sendVerificationEmail)throw t.context.logger.error("Verification email isn't enabled."),U.from("BAD_REQUEST",Ae.VERIFICATION_EMAIL_NOT_ENABLED);let n=await Se(t.context.secret,r.email,void 0,t.context.options.emailVerification?.expiresIn),o=t.body.callbackURL?encodeURIComponent(t.body.callbackURL):encodeURIComponent("/"),i=`${t.context.baseURL}/verify-email?token=${n}&callbackURL=${o}`;await t.context.options.emailVerification.sendVerificationEmail({user:r,url:i,token:n},t.request)}var ou=Pe("/send-verification-email",{method:"POST",operationId:"sendVerificationEmail",cloneRequest:!0,body:l({email:Tn().meta({description:"The email to send the verification email to"}),callbackURL:e().meta({description:"The URL to use for email verification callback"}).optional()}),metadata:{openapi:{operationId:"sendVerificationEmail",description:"Send a verification email to the user",requestBody:{content:{"application/json":{schema:{type:"object",properties:{email:{type:"string",description:"The email to send the verification email to",example:"user@example.com"},callbackURL:{type:"string",description:"The URL to use for email verification callback",example:"https://example.com/callback",nullable:!0}},required:["email"]}}}},responses:{"200":{description:"Success",content:{"application/json":{schema:{type:"object",properties:{status:{type:"boolean",description:"Indicates if the email was sent successfully",example:!0}}}}}},"400":{description:"Bad Request",content:{"application/json":{schema:{type:"object",properties:{message:{type:"string",description:"Error message",example:"Verification email isn't enabled"}}}}}}}}}},async(t)=>{if(!t.context.options.emailVerification?.sendVerificationEmail)throw t.context.logger.error("Verification email isn't enabled."),U.from("BAD_REQUEST",Ae.VERIFICATION_EMAIL_NOT_ENABLED);let{email:r}=t.body,n=await ee(t);if(!n){let i=Date.now(),s=await t.context.internalAdapter.findUserByEmail(r),a;if(!s||s.user.emailVerified)await Se(t.context.secret,r,void 0,t.context.options.emailVerification?.expiresIn);else try{await hs(t,s.user)}catch(d){a=d}let c=500-(Date.now()-i);if(c>0)await new Promise((d)=>setTimeout(d,c));if(a)throw a;return t.json({status:!0})}if(n?.user.email.toLowerCase()!==r.toLowerCase())throw U.from("BAD_REQUEST",Ae.EMAIL_MISMATCH);if(n?.user.emailVerified)throw U.from("BAD_REQUEST",Ae.EMAIL_ALREADY_VERIFIED);return await hs(t,n.user),t.json({status:!0})}),iu=Pe("/verify-email",{method:"GET",operationId:"verifyEmail",query:l({token:e().meta({description:"The token to verify the email"}),callbackURL:e().meta({description:"The URL to redirect to after email verification"}).optional()}),use:[bt((t)=>t.query.callbackURL)],metadata:{openapi:{description:"Verify the email of the user",parameters:[{name:"token",in:"query",description:"The token to verify the email",required:!0,schema:{type:"string"}},{name:"callbackURL",in:"query",description:"The URL to redirect to after email verification",required:!1,schema:{type:"string"}}],responses:{"200":{description:"Success",content:{"application/json":{schema:{type:"object",properties:{user:{type:"object",$ref:"#/components/schemas/User"},status:{type:"boolean",description:"Indicates if the email was verified successfully"}},required:["user","status"]}}}}}}}},async(t)=>{function r(c){if(t.query.callbackURL){let d=new URLSearchParams({error:c.code}),u=$e(t.query.callbackURL,d);throw t.redirect(u)}throw U.from("UNAUTHORIZED",c)}let{token:n}=t.query,o;try{o=await Qr(n,new TextEncoder().encode(t.context.secret),{algorithms:["HS256"]})}catch(c){if(c instanceof yi)return r(Ae.TOKEN_EXPIRED);return r(Ae.INVALID_TOKEN)}let i=l({email:Tn(),updateTo:e().optional(),requestType:e().optional()}).parse(o.payload),s=await t.context.internalAdapter.findUserByEmail(i.email);if(!s)return r(Ae.USER_NOT_FOUND);if(i.updateTo){let c=await ee(t);if(c&&c.user.email!==i.email)return r(Ae.INVALID_USER);switch(i.requestType){case"change-email-confirmation":{let d=await Se(t.context.secret,i.email,i.updateTo,t.context.options.emailVerification?.expiresIn,{requestType:"change-email-verification"}),u=t.query.callbackURL?encodeURIComponent(t.query.callbackURL):encodeURIComponent("/"),f=`${t.context.baseURL}/verify-email?token=${d}&callbackURL=${u}`;if(t.context.options.emailVerification?.sendVerificationEmail)await t.context.runInBackgroundOrAwait(t.context.options.emailVerification.sendVerificationEmail({user:{...s.user,email:i.updateTo},url:f,token:d},Tt(t.request)));if(t.query.callbackURL)throw t.redirect(t.query.callbackURL);return t.json({status:!0})}case"change-email-verification":{let d=c;if(!d){let f=await t.context.internalAdapter.createSession(s.user.id);if(!f)throw U.from("INTERNAL_SERVER_ERROR",Ae.FAILED_TO_CREATE_SESSION);d={session:f,user:s.user}}let u=await t.context.internalAdapter.updateUserByEmail(i.email,{email:i.updateTo,emailVerified:!0});if(t.context.options.emailVerification?.afterEmailVerification)await t.context.options.emailVerification.afterEmailVerification(u,t.request);if(await pe(t,{session:d.session,user:{...d.user,email:i.updateTo,emailVerified:!0}}),t.query.callbackURL)throw t.redirect(t.query.callbackURL);return t.json({status:!0,user:se(t.context.options,u)})}default:{let d=c;if(!d){let h=await t.context.internalAdapter.createSession(s.user.id);if(!h)throw U.from("INTERNAL_SERVER_ERROR",Ae.FAILED_TO_CREATE_SESSION);d={session:h,user:s.user}}let u=await t.context.internalAdapter.updateUserByEmail(i.email,{email:i.updateTo,emailVerified:!1}),f=await Se(t.context.secret,i.updateTo),p=t.query.callbackURL?encodeURIComponent(t.query.callbackURL):encodeURIComponent("/");if(t.context.options.emailVerification?.sendVerificationEmail)await t.context.runInBackgroundOrAwait(t.context.options.emailVerification.sendVerificationEmail({user:u,url:`${t.context.baseURL}/verify-email?token=${f}&callbackURL=${p}`,token:f},Tt(t.request)));if(await pe(t,{session:d.session,user:{...d.user,email:i.updateTo,emailVerified:!1}}),t.query.callbackURL)throw t.redirect(t.query.callbackURL);return t.json({status:!0,user:se(t.context.options,u)})}}}if(s.user.emailVerified){if(t.query.callbackURL)throw t.redirect(t.query.callbackURL);return t.json({status:!0,user:null})}if(t.context.options.emailVerification?.beforeEmailVerification)await t.context.options.emailVerification.beforeEmailVerification(s.user,t.request);let a=await t.context.internalAdapter.updateUserByEmail(i.email,{emailVerified:!0});if(t.context.options.emailVerification?.afterEmailVerification)await t.context.options.emailVerification.afterEmailVerification(a,t.request);if(t.context.options.emailVerification?.autoSignInAfterVerification){let c=await ee(t);if(!c||c.user.email!==i.email){let d=await t.context.internalAdapter.createSession(s.user.id);if(!d)throw U.from("INTERNAL_SERVER_ERROR",Ae.FAILED_TO_CREATE_SESSION);await pe(t,{session:d,user:{...s.user,emailVerified:!0}})}else await pe(t,{session:c.session,user:{...c.user,emailVerified:!0}})}if(t.query.callbackURL)throw t.redirect(t.query.callbackURL);return t.json({status:!0,user:null})});function ms(t){if(Array.isArray(t))return t.map((r)=>typeof r==="string"?r.trim():"").filter(Boolean);if(typeof t==="string")return t.trim().split(/\s+/).filter(Boolean);return[]}function sn(t){let r=(n)=>new Date(new Date().getTime()+n*1000);return{tokenType:t.token_type,accessToken:t.access_token,refreshToken:t.refresh_token,accessTokenExpiresAt:t.expires_in?r(t.expires_in):void 0,refreshTokenExpiresAt:t.refresh_token_expires_in?r(t.refresh_token_expires_in):void 0,scopes:ms(t.scope),idToken:t.id_token,raw:t}}function gs(t,r){let n=t?t.split(",").map((i)=>i.trim()).filter(Boolean):[],o=(r??[]).map((i)=>i.trim()).filter(Boolean);return[...new Set([...n,...o])].join(",")}function Re(t){let r=Array.isArray(t)?t[0]:t;return typeof r==="string"&&r.length>0?r:void 0}async function an(t){let r=new TextEncoder().encode(t),n=await crypto.subtle.digest("SHA-256",r);return ko.encode(new Uint8Array(n),{padding:!1})}var ws=["state","client_id","redirect_uri","response_type","code_challenge","code_challenge_method","nonce","scope"],Ft=new Set(ws);async function V({id:t,options:r,authorizationEndpoint:n,state:o,codeVerifier:i,scopes:s,claims:a,redirectURI:c,duration:d,prompt:u,accessType:f,responseType:p,display:h,loginHint:m,nonce:w,hd:y,responseMode:I,additionalParams:R,scopeJoiner:b}){r=typeof r==="function"?await r():r;let O=new URL(r.authorizationEndpoint||n);O.searchParams.set("response_type",p||"code");let g=Re(r.clientId);if(!g)throw Error("OAuth provider requires clientId");if(O.searchParams.set("client_id",g),O.searchParams.set("state",o),s?.length)O.searchParams.set("scope",s.join(b||" "));if(O.searchParams.set("redirect_uri",r.redirectURI||c),d&&O.searchParams.set("duration",d),h&&O.searchParams.set("display",h),m&&O.searchParams.set("login_hint",m),w&&O.searchParams.set("nonce",w),u&&O.searchParams.set("prompt",u),y&&O.searchParams.set("hd",y),f&&O.searchParams.set("access_type",f),I&&O.searchParams.set("response_mode",I),i){let S=await an(i);O.searchParams.set("code_challenge_method","S256"),O.searchParams.set("code_challenge",S)}if(a){let S=a.reduce((C,z)=>(C[z]=null,C),{});O.searchParams.set("claims",JSON.stringify({id_token:{email:null,email_verified:null,...S}}))}if(R)for(let[S,C]of Object.entries(R)){if(Ft.has(S))continue;O.searchParams.set(S,C)}return O}var cn=k(e(),e()).refine((t)=>!Object.keys(t).some((r)=>Ft.has(r)),{message:`additionalParams cannot include reserved OAuth parameters: ${ws.join(", ")}`}).meta({description:"Extra query parameters to append to the provider authorization URL (e.g. Cognito identity_provider, Google hd)."}).optional();var lw=/^Basic +(.*)$/i;function su(t){return new URLSearchParams({v:t}).toString().slice(2)}function au(t){let r=new URLSearchParams(`v=${t}`).get("v");if(r===null)throw Error("form-url-encoded value could not be decoded");return r}function ys(t,r){let n=`${su(t)}:${su(r)}`;return`Basic ${To.encode(n)}`}function _s(t){let r=t.match(lw);if(!r)throw Error("Authorization header is not a Basic credential");let n=r[1]??"",o=new TextDecoder().decode(To.decode(n)),i=o.indexOf(":");if(i===-1)throw Error("Basic credential is missing the client id/secret separator");let s=o.slice(0,i),a=o.slice(i+1);if(!s||!a)throw Error("Basic credential client id and secret must both be non-empty");return{clientId:au(s),clientSecret:au(a)}}var Kt=["RS256","RS384","RS512","PS256","PS384","PS512","ES256","ES384","ES512","EdDSA"];var Wt="urn:ietf:params:oauth:client-assertion-type:jwt-bearer";async function As({getClientAssertion:t,context:r}){return{client_assertion:await t(r),client_assertion_type:Wt}}var fw=class extends Error{constructor(t,r,n){super(r||t.toString(),{cause:n});this.status=t,this.statusText=r,this.error=n,Error.captureStackTrace(this,this.constructor)}},pw=async(t,r)=>{let n=r||{},o={onRequest:[r===null||r===void 0?void 0:r.onRequest],onResponse:[r===null||r===void 0?void 0:r.onResponse],onSuccess:[r===null||r===void 0?void 0:r.onSuccess],onError:[r===null||r===void 0?void 0:r.onError],onRetry:[r===null||r===void 0?void 0:r.onRetry]};if(!r||!(r===null||r===void 0?void 0:r.plugins))return{url:t,options:n,hooks:o};for(let f of(r===null||r===void 0?void 0:r.plugins)||[]){var i,s,a,c,d;if(f.init){var u;let p=await((u=f.init)===null||u===void 0?void 0:u.call(f,t.toString(),n));n=p.options||n,t=p.url}o.onRequest.push((i=f.hooks)===null||i===void 0?void 0:i.onRequest),o.onResponse.push((s=f.hooks)===null||s===void 0?void 0:s.onResponse),o.onSuccess.push((a=f.hooks)===null||a===void 0?void 0:a.onSuccess),o.onError.push((c=f.hooks)===null||c===void 0?void 0:c.onError),o.onRetry.push((d=f.hooks)===null||d===void 0?void 0:d.onRetry)}return{url:t,options:n,hooks:o}},cu=class{constructor(t){this.options=t}shouldAttemptRetry(t,r){if(this.options.shouldRetry)return Promise.resolve(t<this.options.attempts&&this.options.shouldRetry(r));return Promise.resolve(t<this.options.attempts)}getDelay(){return this.options.delay}},hw=class{constructor(t){this.options=t}shouldAttemptRetry(t,r){if(this.options.shouldRetry)return Promise.resolve(t<this.options.attempts&&this.options.shouldRetry(r));return Promise.resolve(t<this.options.attempts)}getDelay(t){return Math.min(this.options.maxDelay,this.options.baseDelay*2**t)}};function mw(t){if(typeof t==="number")return new cu({type:"linear",attempts:t,delay:1000});switch(t.type){case"linear":return new cu(t);case"exponential":return new hw(t);default:throw Error("Invalid retry strategy")}}var gw=["get","post","put","patch","delete"];function fu(t){if(!t.startsWith("@"))return{method:void 0,path:t};let r=t.indexOf("/"),n=t.slice(1,r===-1?void 0:r);if(!gw.includes(n))return{method:void 0,path:t};return{method:n,path:r===-1?t:t.slice(r+1)}}var ww=(t)=>t==="."||t==="..",yw=(t)=>t.split(":").map((r)=>encodeURIComponent(r)).join(":");function _w(t,r){let n=r.get(t);if(n===void 0)return yw(t);if(ww(n))throw TypeError("Path parameters cannot be reserved path segments");return encodeURIComponent(n)}function Aw(t,r){let{baseURL:n,params:o,query:i}=r||{query:{},params:{},baseURL:""},s=t.startsWith("http")?t.split("/").slice(0,3).join("/"):n||"",{path:a}=fu(t);if(a!==t)t=`/${a}`;if(!s.endsWith("/"))s+="/";let[c,d]=t.replace(s,"").split("?"),u=new URLSearchParams(d);for(let[h,m]of Object.entries(i||{})){if(m==null)continue;let w;if(typeof m==="string")w=m;else if(Array.isArray(m)){for(let y of m)u.append(h,y);continue}else w=JSON.stringify(m);u.set(h,w)}let f=new Map;if(o)if(Array.isArray(o)){let h=c.split("/").filter((m)=>m.startsWith(":"));for(let[m,w]of h.entries()){let y=o[m];f.set(w,String(y))}}else for(let[h,m]of Object.entries(o))f.set(`:${h}`,String(m));c=c.split("/").map((h)=>_w(h,f)).join("/"),c=c.replace(/^\/+/,"");let p=u.toString();if(p=p.length>0?`?${p}`.replace(/\+/g,"%20"):"",!s.startsWith("http"))return`${s}${c}${p}`;return new URL(`${c}${p}`,s)}var kw=async(t)=>{let r={},n=async(o)=>typeof o==="function"?await o():o;if(t===null||t===void 0?void 0:t.auth){if(t.auth.type==="Bearer"){let o=await n(t.auth.token);if(!o)return r;r.authorization=`Bearer ${o}`}else if(t.auth.type==="Basic"){let[o,i]=await Promise.all([n(t.auth.username),n(t.auth.password)]);if(!o||!i)return r;r.authorization=`Basic ${btoa(`${o}:${i}`)}`}else if(t.auth.type==="Custom"){let[o,i]=await Promise.all([n(t.auth.prefix),n(t.auth.value)]);if(!i)return r;r.authorization=`${o!==null&&o!==void 0?o:""} ${i}`}}return r},Ew=/^application\/(?:[\w!#$%&*.^`~-]*\+)?json(;.+)?$/i;function bw(t){let r=t.headers.get("content-type"),n=new Set(["image/svg","application/xml","application/xhtml","application/html"]);if(!r)return"json";let o=r.split(";").shift()||"";if(Ew.test(o))return"json";if(n.has(o)||o.startsWith("text/"))return"text";return"blob"}function vw(t){try{return JSON.parse(t),!0}catch(r){return!1}}function pu(t){if(t===void 0)return!1;let r=typeof t;if(r==="string"||r==="number"||r==="boolean"||r===null)return!0;if(r!=="object")return!1;if(Array.isArray(t))return!0;if(t.buffer)return!1;return t.constructor&&t.constructor.name==="Object"||typeof t.toJSON==="function"}function du(t){try{return JSON.parse(t)}catch(r){return t}}function uu(t){return typeof t==="function"}function Sw(t){if(t===null||t===void 0?void 0:t.customFetchImpl)return t.customFetchImpl;if(typeof globalThis<"u"&&uu(globalThis.fetch))return globalThis.fetch;if(typeof window<"u"&&uu(window.fetch))return window.fetch;throw Error("No fetch implementation found")}function Rw(...t){let r={};for(let n of t){if(!n)continue;if(n instanceof Headers)n.forEach((o,i)=>{r[i]=o});else{let o=Array.isArray(n)?n:Object.entries(n);for(let[i,s]of o)if(s!==null&&s!==void 0)r[i]=s}}return r}async function Tw(t){let r=new Headers(Rw(t===null||t===void 0?void 0:t.headers,await kw(t)));if(!r.has("content-type")){let n=Iw(t===null||t===void 0?void 0:t.body);if(n)r.set("content-type",n)}return r}function Iw(t){if(pu(t))return"application/json";return null}function Uw(t){let r=t.get("content-type");return r?r.split(";")[0].trim().toLowerCase():null}function Cw(t,r){let{body:n}=t;if(!n)return null;if(!pu(n))return n;if(typeof n==="string")return n;if(Uw(r)==="application/x-www-form-urlencoded")return new URLSearchParams(n).toString();return JSON.stringify(n)}function Ow(t,r){if(r===null||r===void 0?void 0:r.method)return r.method.toUpperCase();let{method:n}=fu(t);if(n)return n.toUpperCase();return(r===null||r===void 0?void 0:r.body)?"POST":"GET"}function Dw(t,r){let n;if(!(t===null||t===void 0?void 0:t.signal)&&(t===null||t===void 0?void 0:t.timeout))n=setTimeout(()=>r===null||r===void 0?void 0:r.abort(),t===null||t===void 0?void 0:t.timeout);return{abortTimeout:n,clearTimeout:()=>{if(n)clearTimeout(n)}}}var Lw=class t extends Error{constructor(r,n){super(n||JSON.stringify(r,null,2));this.issues=r,Object.setPrototypeOf(this,t.prototype)}};async function Pw(t,r){let n=await t["~standard"].validate(r);if(n.issues)throw new Lw(n.issues);return n.value}function un(t){return un=typeof Symbol=="function"&&typeof Symbol.iterator=="symbol"?function(r){return typeof r}:function(r){return r&&typeof Symbol=="function"&&r.constructor===Symbol&&r!==Symbol.prototype?"symbol":typeof r},un(t)}function xw(t,r){if(un(t)!="object"||!t)return t;var n=t[Symbol.toPrimitive];if(n!==void 0){var o=n.call(t,r||"default");if(un(o)!="object")return o;throw TypeError("@@toPrimitive must return a primitive value.")}return(r==="string"?String:Number)(t)}function zw(t){var r=xw(t,"string");return un(r)=="symbol"?r:r+""}function Nw(t,r,n){return(r=zw(r))in t?Object.defineProperty(t,r,{value:n,enumerable:!0,configurable:!0,writable:!0}):t[r]=n,t}function lu(t,r){var n=Object.keys(t);if(Object.getOwnPropertySymbols){var o=Object.getOwnPropertySymbols(t);r&&(o=o.filter(function(i){return Object.getOwnPropertyDescriptor(t,i).enumerable})),n.push.apply(n,o)}return n}function Ce(t){for(var r=1;r<arguments.length;r++){var n=arguments[r]!=null?arguments[r]:{};r%2?lu(Object(n),!0).forEach(function(o){Nw(t,o,n[o])}):Object.getOwnPropertyDescriptors?Object.defineProperties(t,Object.getOwnPropertyDescriptors(n)):lu(Object(n)).forEach(function(o){Object.defineProperty(t,o,Object.getOwnPropertyDescriptor(n,o))})}return t}var Me=async(t,r)=>{var n,o,i;let{hooks:s,url:a,options:c}=await pw(t,r),d=Sw(c),u=new AbortController,f=(n=c.signal)!==null&&n!==void 0?n:u.signal,p=Aw(a,c),h=await Tw(c),m=Cw(c,h),w=Ow(a,c),y=Ce(Ce({},c),{},{url:p,headers:h,body:m,method:w,signal:f});for(let H of s.onRequest)if(H){let q=await H(y);if(typeof q==="object"&&q!==null)Object.assign(y,q)}if("pipeTo"in y&&typeof y.pipeTo==="function"||typeof(r===null||r===void 0||(o=r.body)===null||o===void 0?void 0:o.pipe)==="function"){if(!("duplex"in y))y.duplex="half"}let{clearTimeout:I}=Dw(c,u),R=await d(y.url,y);I();let b={response:R,request:y};for(let H of s.onResponse)if(H){var O;let q=await H(Ce(Ce({},b),{},{response:(r===null||r===void 0||(O=r.hookOptions)===null||O===void 0?void 0:O.cloneResponse)?R.clone():R}));if(q instanceof Response)R=q;else if(typeof q==="object"&&q!==null)R=q.response}if(R.ok){if(y.method==="HEAD")return{data:"",error:null};let H=bw(R),q={data:null,response:R,request:y};if(H==="json"||H==="text"){var g;let W=await R.text();q.data=await((g=y.jsonParser)!==null&&g!==void 0?g:du)(W)}else q.data=await R[H]();if(y===null||y===void 0?void 0:y.output){if(y.output&&!y.disableValidation)q.data=await Pw(y.output,q.data)}for(let W of s.onSuccess)if(W){var S;await W(Ce(Ce({},q),{},{response:(r===null||r===void 0||(S=r.hookOptions)===null||S===void 0?void 0:S.cloneResponse)?R.clone():R}))}if(r===null||r===void 0?void 0:r.throw)return q.data;return{data:q.data,error:null}}let C=(i=r===null||r===void 0?void 0:r.jsonParser)!==null&&i!==void 0?i:du,z=await R.text(),L=vw(z),x=L?await C(z):null,P={response:R,responseText:z,request:y,error:Ce(Ce({},x),{},{status:R.status,statusText:R.statusText})};for(let H of s.onError)if(H){var j;await H(Ce(Ce({},P),{},{response:(r===null||r===void 0||(j=r.hookOptions)===null||j===void 0?void 0:j.cloneResponse)?R.clone():R}))}if(r===null||r===void 0?void 0:r.retry){var B;let H=mw(r.retry),q=(B=r.retryAttempt)!==null&&B!==void 0?B:0;if(await H.shouldAttemptRetry(q,R)){for(let Q of s.onRetry)if(Q)await Q(b);let W=H.getDelay(q);return await new Promise((Q)=>setTimeout(Q,W)),await Me(t,Ce(Ce({},r),{},{retryAttempt:q+1}))}}if(r===null||r===void 0?void 0:r.throw)throw new fw(R.status,R.statusText,L?x:z);return{data:null,error:Ce(Ce({},x),{},{status:R.status,statusText:R.statusText})}};var qw=new Set([301,302,303,307,308]);function jw(t){return t.type==="opaqueredirect"||qw.has(t.status)}function hu(t){return new te(`The OAuth endpoint "${t}" returned an HTTP redirect. Server-side OAuth fetches refuse redirects to prevent SSRF; configure the final endpoint URL.`)}async function Qt(t,r){let n=!1,o=r?.onError,i=await Me(t,{...r,redirect:"manual",async onError(s){if(jw(s.response))n=!0;await o?.(s)}}).catch((s)=>{if(n)throw hu(t);throw s});if(n)throw hu(t);return i}function Bw(t,r){if(r==="basic")return{method:"client_secret_basic"};if(t.clientSecret)return{method:"client_secret_post"};return{method:"none"}}function ks(t,r,n){if(r.clientSecret||n.has("client_secret"))throw Error(`${t} token endpoint authentication cannot be combined with clientSecret`)}function Ao(t,r){if(r)t.set("client_id",r)}function gu(t,r){if(!r.clientSecret)throw Error(`${t} token endpoint authentication requires clientSecret`)}function Eo(t,r){if(!r)throw Error(`${t} token endpoint authentication requires clientId`)}function $w({body:t,options:r,clientId:n,requireClientSecret:o}){if(o)gu("client_secret_post",r);if(r.clientSecret)Eo("client_secret_post",n),Ao(t,n),t.set("client_secret",r.clientSecret)}function Mw({headers:t,options:r,clientId:n,body:o}){if(o.has("client_secret"))throw Error("client_secret_basic token endpoint authentication cannot be combined with client_secret body parameters");gu("client_secret_basic",r),Eo("client_secret_basic",n),t.authorization=ys(n,r.clientSecret)}function mu(t){if(t.has("client_assertion")!==t.has("client_assertion_type"))throw Error("client_assertion and client_assertion_type must both be provided")}async function bo({body:t,headers:r,options:n,tokenEndpoint:o,grantType:i,tokenEndpointAuth:s,authentication:a}){mu(t);let c=Re(n.clientId);if(t.has("client_assertion")){if(s)throw Error("client_assertion body parameters cannot be combined with tokenEndpointAuth");ks("private_key_jwt",n,t),Ao(t,c);return}let d=s??Bw(n,a);if(d.method==="custom"){await d.customizeRequest({body:t,headers:r,options:n,tokenEndpoint:o,grantType:i}),mu(t);return}if(d.method==="private_key_jwt"){if(ks(d.method,n,t),Eo(d.method,c),!o)throw Error("private_key_jwt token endpoint authentication requires tokenEndpoint");let u=await As({getClientAssertion:d.getClientAssertion,context:{clientId:c,tokenEndpoint:o,grantType:i}});Ao(t,c);for(let[f,p]of Object.entries(u))t.set(f,p);return}if(d.method==="none"){if(ks(d.method,n,t),i==="client_credentials")throw Error("none token endpoint authentication cannot be used with client_credentials grant");Eo(d.method,c),Ao(t,c);return}if(d.method==="client_secret_basic"){Mw({headers:r,options:n,clientId:c,body:t});return}$w({body:t,options:n,clientId:c,requireClientSecret:s?.method==="client_secret_post"})}var wu="dpop+jwt",ja=["EdDSA","ES256","ES512","PS256","RS256"],Hw=300,Vw=512,Fw=new Set(["d","p","q","dp","dq","qi","oth","k"]);function Ss(){let t=new Map;return{reserve({key:r,expiresAt:n,now:o}){let i=o.getTime();for(let[s,a]of t)if(a<=i)t.delete(s);if(t.has(r))return!1;return t.set(r,n.getTime()),!0}}}function _c(t){return{reserve:({key:r,expiresAt:n})=>t.reserveVerificationValue({identifier:`dpop-proof:${r}`,value:r,expiresAt:n})}}function ge(t,r){return Object.assign(Error(r),{code:t})}function So(t){return t instanceof Error&&"code"in t&&t.code==="invalid_dpop_proof"}function _r(t){if(!t)return;let r=t.trim();if(!r)return;let n=/^([A-Za-z][A-Za-z0-9!#$%&'*+.^_`|~-]*)\s+(.+)$/.exec(r);if(!n)return{scheme:"Unknown",token:r};let o=n[1]??"",i=n[2]?.trim()??"";if(o.toLowerCase()==="bearer")return{scheme:"Bearer",token:i};if(o.toLowerCase()==="dpop")return{scheme:"DPoP",token:i};return{scheme:"Unknown",token:r}}function fn(t){return _r(t)?.token??t}function Es(t){let r=new URL(t);if(r.hash)throw Error("DPoP proof htu must not contain a fragment");return`${r.origin}${r.pathname}`}async function yu(t){let r=await crypto.subtle.digest("SHA-256",new TextEncoder().encode(t));return mr(new Uint8Array(r))}async function _u(t){return wl(t,"sha256")}function hn(t){if(!t||typeof t!=="object"||Array.isArray(t))return;let r=t.jkt;return typeof r==="string"&&r.length>0?r:void 0}function gn(t){return hn(t.cnf)}function vo(t,r){let n=t[r];return typeof n==="string"&&n.length>0?n:void 0}function Kw(t,r){let n=t[r];return typeof n==="number"&&Number.isFinite(n)?n:void 0}function Ww(t,r){if(!t||t==="none"||t.startsWith("HS"))throw ge("invalid_dpop_proof","DPoP proof must use an asymmetric JWS algorithm");if(!r.includes(t))throw ge("invalid_dpop_proof","DPoP proof uses an unsupported JWS algorithm")}function Jw(t){if(!t||typeof t!=="object"||Array.isArray(t))throw ge("invalid_dpop_proof","DPoP proof header must include a public jwk");if(t.kty==="oct")throw ge("invalid_dpop_proof","DPoP proof jwk must be asymmetric");for(let r of Fw)if(r in t)throw ge("invalid_dpop_proof","DPoP proof jwk must not contain private key material")}async function Qw(t){let r=`${t.jkt}
35
35
  ${t.htm}
36
36
  ${t.htu}
37
- ${t.jti}`,n=await crypto.subtle.digest("SHA-256",new TextEncoder().encode(r));return pr(new Uint8Array(n))}async function Gw(t,r){if(!t)return;if(!await t.reserve(r))throw ge("invalid_dpop_proof","DPoP proof jti has already been used")}async function Ro({proofJwt:t,method:r,url:n,accessToken:o,expectedJkt:i,requireAth:s=!1,nowSeconds:a=Math.floor(Date.now()/1000),proofMaxAgeSeconds:c=Hw,signingAlgorithms:d=za,replayStore:u}){if(!t||t.split(".").length!==3)throw ge("invalid_dpop_proof","DPoP proof must be a compact JWT");let f;try{f=so(t)}catch(C){throw ge("invalid_dpop_proof",C instanceof Error?C.message:"DPoP proof header is invalid")}if(f.typ!=="dpop+jwt")throw ge("invalid_dpop_proof",'DPoP proof typ must be "dpop+jwt"');Ww(f.alg,d),Jw(f.jwk);let p;try{p=(await Hr(t,await Sn(f.jwk,f.alg),{typ:wu})).payload}catch(C){throw ge("invalid_dpop_proof",C instanceof Error?C.message:"DPoP proof signature is invalid")}let h=vo(p,"htm"),m=vo(p,"htu"),w=vo(p,"jti"),y=Kw(p,"iat");if(!h||!m||!w||y===void 0)throw ge("invalid_dpop_proof","DPoP proof must include htm, htu, jti, and iat claims");if(w.length>Vw)throw ge("invalid_dpop_proof","DPoP proof jti is too large");if(h.toUpperCase()!==r.toUpperCase())throw ge("invalid_dpop_proof","DPoP proof htm does not match the request method");let I,R;try{I=Es(n),R=Es(m)}catch(C){throw ge("invalid_dpop_proof",C instanceof Error?C.message:"DPoP proof htu is invalid")}if(R!==I)throw ge("invalid_dpop_proof","DPoP proof htu does not match the request URL");if(y>a+5||a-y>c)throw ge("invalid_dpop_proof","DPoP proof iat is outside the accepted window");let b=vo(p,"ath");if(s&&!b)throw ge("invalid_dpop_proof","DPoP proof must include an ath claim");if(o!==void 0){if(b!==await yu(o))throw ge("invalid_dpop_proof","DPoP proof ath does not match the access token")}let O=await _u(f.jwk);if(i!==void 0&&O!==i)throw ge("invalid_dpop_proof","DPoP proof key does not match the bound token");let g=await Qw({jkt:O,htm:h.toUpperCase(),htu:I,jti:w}),S=new Date((y+c)*1000);return await Gw(u,{key:g,expiresAt:S,now:new Date(a*1000)}),{jwk:f.jwk,jkt:O,jti:w,htm:h,htu:I,iat:y,ath:b,replayKey:g,expiresAt:S}}function ln(t,r){return Object.assign(Error(r),{code:t})}function wn(t){return t instanceof Error&&"code"in t&&(t.code==="invalid_token"||t.code==="invalid_dpop_proof")}async function yn({payload:t,authorization:r,proofJwt:n,method:o,url:i,replayStore:s,proofMaxAgeSeconds:a,signingAlgorithms:c}){let d=gn(t);if(!d){if(r.scheme==="DPoP")throw ln("invalid_token","DPoP authorization requires a DPoP-bound access token");return}if(r.scheme!=="DPoP")throw ln("invalid_token","DPoP-bound access token requires the DPoP authorization scheme");if(!n)throw ln("invalid_dpop_proof","DPoP proof header is required");try{await Ro({proofJwt:n,method:o,url:i,accessToken:r.token,expectedJkt:d,requireAth:!0,proofMaxAgeSeconds:a,signingAlgorithms:c,replayStore:s})}catch(u){if(So(u))throw ln("invalid_dpop_proof",u.message);throw u}}var Zw=new Set(["grant_type","refresh_token","__proto__","constructor","prototype"]);async function Yw({refreshToken:t,options:r,authentication:n,tokenEndpointAuth:o,tokenEndpoint:i,extraParams:s,resource:a}){r=typeof r==="function"?await r():r;let c=ey({refreshToken:t,options:r,extraParams:s,resource:a});return await bo({body:c.body,headers:c.headers,options:r,tokenEndpoint:i??"",grantType:"refresh_token",tokenEndpointAuth:o,authentication:n}),c}function Xw(t,r){if(!r)return;for(let[n,o]of Object.entries(r)){if(Zw.has(n))continue;t.set(n,o)}}function ey({refreshToken:t,options:r,extraParams:n,resource:o}){let i=new URLSearchParams,s={"content-type":"application/x-www-form-urlencoded",accept:"application/json"};if(i.set("grant_type","refresh_token"),i.set("refresh_token",t),o)if(typeof o==="string")i.append("resource",o);else for(let a of o)i.append("resource",a);if(n)Xw(i,n);return{body:i,headers:s}}async function F({refreshToken:t,options:r,tokenEndpoint:n,authentication:o,tokenEndpointAuth:i,extraParams:s,resource:a}){let{body:c,headers:d}=await Yw({refreshToken:t,options:r,authentication:o,tokenEndpointAuth:i,tokenEndpoint:n,extraParams:s,resource:a}),{data:u,error:f}=await Qt(n,{method:"POST",body:c,headers:d});if(f)throw f;let p={accessToken:u.access_token,refreshToken:u.refresh_token,tokenType:u.token_type,scopes:ms(u.scope),idToken:u.id_token};if(u.expires_in)p.accessTokenExpiresAt=new Date(new Date().getTime()+u.expires_in*1000);if(u.refresh_token_expires_in)p.refreshTokenExpiresAt=new Date(new Date().getTime()+u.refresh_token_expires_in*1000);return p}var ty=new Set([yl.code,Al.code,yc.code]);function ry(t){return ty.has(t.code)}var ny=new Map,oy=new WeakMap,iy=300000,sy=30000,ku=5000;function Au(t,r){let n=t.get(r);if(!n)n={fetchedAt:0,refetchedAt:0},t.set(r,n);return n}function Eu(t,r){return t.pending!==void 0&&r-t.pending.startedAt<ku}async function bu(t,r){let n=Date.now();if(!t.pending||!Eu(t,n)){let a={startedAt:n,promise:dy(r).then((c)=>{if(n>=t.fetchedAt)t.jwks=c,t.fetchedAt=n;return c}).finally(()=>{if(t.pending===a)t.pending=void 0})};t.pending=a}let{promise:o,startedAt:i}=t.pending,s;try{return await Promise.race([o,new Promise((a,c)=>{s=setTimeout(()=>c(new yl),i+ku-n)})])}finally{clearTimeout(s)}}async function ay(t,r,n){if(t.jwks!==r)return t.jwks;let o=Date.now();if(!Eu(t,o)){if(o-t.refetchedAt<sy)return;t.refetchedAt=o}return bu(t,n)}function cy(t,r){return!r.kid&&(t instanceof _l||t instanceof $u)}async function dy(t){try{let r=typeof t==="string"?await Qt(t,{headers:{Accept:"application/json"}}).then(async(n)=>{if(n.error)throw Error(`Jwks failed: ${n.error.message??n.error.statusText}`);return n.data}):await t();if(!r)throw Error("No jwks found");return r}catch(r){if(r instanceof TypeError){try{Ee.error("JWKS fetch failed:",r)}catch{}throw Error("JWKS fetch failed")}throw r}}function bm(t){return{authorizationHeader:t.headers.get("authorization"),dpopProofJwt:t.headers.get("dpop"),method:t.method,url:t.url}}var uy=Ss();async function ly(t,r){if(t.split(".").length!==3)throw new Ur("Invalid Compact JWS");let n=await Su(t,r),o=n.jwks;for(let i=0;;i++)try{return await Hr(t,Qo(o),r.verifyOptions)}catch(s){let a=i<2&&cy(s,n)?await n.refresh?.(o):void 0;if(!a)throw s;o=a}}async function vu(t,r){try{let n=await ly(t,r);if(n.payload.azp)n.payload.client_id=n.payload.azp;return n.payload}catch(n){if(n instanceof Error)throw n;throw Error(n)}}async function Ar(t,r){return(await Su(t,r)).jwks}async function Su(t,r){let n;try{n=so(t)}catch(c){if(c instanceof Error)throw c;throw Error(c)}let o=n.kid,i=typeof r.jwksFetch==="string"?Au(ny,r.jwksFetch):r.jwksCacheKey?Au(oy,r.jwksCacheKey):{fetchedAt:0,refetchedAt:0},s=Date.now()-i.fetchedAt<iy?i.jwks:void 0;if(!s)return{jwks:await bu(i,r.jwksFetch),kid:o};let a=(c)=>ay(i,c,r.jwksFetch);if(!o||s.keys.some((c)=>c.kid===o))return{jwks:s,kid:o,refresh:a};return{jwks:await a(s)??s,kid:o}}async function fy(t,r){let n;if(r.jwksUrl&&!r?.remoteVerify?.force)try{n=await vu(t,{jwksFetch:r.jwksUrl,verifyOptions:r.verifyOptions})}catch(i){if(i instanceof Error)if(i.name==="TypeError"||i.name==="JWSInvalid");else if(i instanceof yi)throw new ce("UNAUTHORIZED",{message:"token expired"});else if(i instanceof dn){if(ry(i))throw i;throw new ce("UNAUTHORIZED",{message:"invalid access token"})}else throw i;else throw Error(i)}if(r?.remoteVerify){let{data:i,error:s}=await Qt(r.remoteVerify.introspectUrl,{method:"POST",headers:{Accept:"application/json","Content-Type":"application/x-www-form-urlencoded"},body:new URLSearchParams({client_id:r.remoteVerify.clientId,client_secret:r.remoteVerify.clientSecret,token:t,token_type_hint:"access_token"}).toString()});if(s)Ee.error(`Introspection failed: ${s.message??s.statusText}`);if(!i)throw new ce("INTERNAL_SERVER_ERROR",{message:"introspection failed"});if(!i.active)throw new ce("UNAUTHORIZED",{message:"token inactive"});try{let a=new vc(i).encode(),{audience:c,...d}=r.verifyOptions,u=!i.aud&&r.remoteVerify.allowMissingAudience===!0;n=vc.decode(a,u?d:r.verifyOptions).payload}catch(a){throw Error(a)}}if(!n)throw new ce("UNAUTHORIZED",{message:"no token payload"});let o=gy(n.scope);if(r.requiredScopes){let i=r.isScopeSatisfied??((a,c)=>c.has(a)),s=r.requiredScopes.filter((a)=>!i(a,o));if(s.length>0)throw Iu(s)}return n}var py=/^[\x21\x23-\x5b\x5d-\x7e]+$/,hy=/^[\x20-\x21\x23-\x5b\x5d-\x7e]+$/,Ru=new WeakSet;function Is(t){return py.test(t)}function Tu(t,r){for(let n of t)if(!Is(n))throw TypeError(`invalid ${r}: ${JSON.stringify(n)}`)}function my(t){if(t.requiredScopes)Tu(t.requiredScopes,"required scope")}function gy(t){if(t===void 0)return new Set;if(typeof t!=="string"||t.length===0||t.split(" ").some((r)=>!Is(r)))throw new ce("UNAUTHORIZED",{message:"access token scope claim is invalid",error:"invalid_token",error_description:"access token scope claim is invalid"});return new Set(t.split(" "))}function Iu(t,r=`access token is missing required scope: ${t.join(" ")}`){if(t.length===0)throw TypeError("requiredScopes must contain at least one scope");if(Tu(t,"required scope"),typeof r!=="string"||!hy.test(r))throw TypeError("invalid error_description");let n=new ce("FORBIDDEN",{message:r,error:"insufficient_scope",error_description:r,scope:[...new Set(t)].join(" ")});return Ru.add(n),n}function qu(t){if(!(t instanceof ce)||!Ru.has(t)||t.status!=="FORBIDDEN")return!1;let r=t.body;if(r?.error!=="insufficient_scope"||typeof r.scope!=="string")return!1;let n=r.scope.split(" ");return n.length>0&&n.every(Is)}function Rs(t,r){throw new ce("UNAUTHORIZED",r?{message:t,error:r,error_description:t}:{message:t})}async function wm(t,r){my(r);let n=_r(t.authorizationHeader);if(!n?.token)Rs("missing authorization header");if(n.scheme==="Unknown")Rs("authorization scheme must be Bearer or DPoP","invalid_token");let o=await fy(n.token,r);try{await yn({payload:o,authorization:n,proofJwt:t.dpopProofJwt,method:t.method,url:t.url,replayStore:r.dpop?.replayStore??uy,proofMaxAgeSeconds:r.dpop?.proofMaxAgeSeconds,signingAlgorithms:r.dpop?.signingAlgorithms})}catch(i){if(wn(i))Rs(i.message,i.code);throw i}return o}async function Us({code:t,codeVerifier:r,redirectURI:n,options:o,authentication:i,tokenEndpointAuth:s,tokenEndpoint:a,deviceId:c,headers:d,additionalParams:u={},resource:f}){o=typeof o==="function"?await o():o;let p=wy({code:t,codeVerifier:r,redirectURI:n,options:o,deviceId:c,headers:d,additionalParams:u,resource:f});return await bo({body:p.body,headers:p.headers,options:o,tokenEndpoint:a??"",grantType:"authorization_code",tokenEndpointAuth:s,authentication:i}),p}function wy({code:t,codeVerifier:r,redirectURI:n,options:o,deviceId:i,headers:s,additionalParams:a={},resource:c}){let d=new URLSearchParams,u={"content-type":"application/x-www-form-urlencoded",accept:"application/json",...s};if(d.set("grant_type","authorization_code"),d.set("code",t),r&&d.set("code_verifier",r),o.clientKey&&d.set("client_key",o.clientKey),i&&d.set("device_id",i),d.set("redirect_uri",o.redirectURI||n),c)if(typeof c==="string")d.append("resource",c);else for(let f of c)d.append("resource",f);for(let[f,p]of Object.entries(a))if(!d.has(f))d.append(f,p);return{body:d,headers:u}}async function K({code:t,codeVerifier:r,redirectURI:n,options:o,tokenEndpoint:i,authentication:s,tokenEndpointAuth:a,deviceId:c,headers:d,additionalParams:u={},resource:f}){let{body:p,headers:h}=await Us({code:t,codeVerifier:r,redirectURI:n,options:o,authentication:s,tokenEndpointAuth:a,tokenEndpoint:i,deviceId:c,headers:d,additionalParams:u,resource:f}),{data:m,error:w}=await Qt(i,{method:"POST",body:p,headers:h});if(w)throw w;return sn(m)}var yy=30,_y=["iss","sub","aud","exp","iat"];function Ay(t){return{issuer:t.issuer,audience:t.audience,algorithms:t.algorithms,maxTokenAge:t.maxTokenAge,requiredClaims:_y,clockTolerance:yy}}async function ky(t){let r=new TextEncoder().encode(t),n=await crypto.subtle.digest("SHA-256",r);return Array.from(new Uint8Array(n)).map((o)=>o.toString(16).padStart(2,"0")).join("")}async function Ey(t,r,n="exact"){if(typeof t!=="string")return!1;if(t===r)return!0;if(n==="exact-or-sha256")return t===await ky(r);return!1}async function by(t,r,n){if(![r.audience].flat().some(Boolean))throw Error("ID token audience is not configured");let o=await Hr(t,r.jwks,Ay(r));if(n&&!await Ey(o.payload.nonce,n,r.nonceComparison))throw Error("ID token nonce does not match");if(r.verifyClaims&&!r.verifyClaims(o.payload))throw Error("ID token claims were rejected");return o}function _n(t){let r=t.options??{};if(r.disableIdTokenSignIn)return!1;return Boolean(t.idToken||r.verifyIdToken)}async function An(t,r,n,o){let i=t.options??{};if(i.disableIdTokenSignIn)return!1;try{if(i.verifyIdToken)return await i.verifyIdToken(r,n,o);let s=t.idToken;if(!s)return!1;if("verify"in s)return await s.verify(r,n,o);if(r.split(".").length!==3)return s.allowOpaqueToken===!0;return await by(r,s,n),!0}catch{return!1}}function kn(t,r){return{linked:!1,error:{code:t,message:r}}}async function Ou(t,{link:r,userInfo:n,account:o,profile:i,scopes:s}){try{await lr(t,{user:{...n,id:r.userId,email:n.email??void 0},source:{action:"link-account",method:"oauth",oauth:{providerId:o.providerId,profile:i}}})}catch(c){if(!Br(c)||!c.body?.code)throw c;return kn(c.body.code,c.body.message)}if(!t.context.trustedProviders.includes(o.providerId)&&!n.emailVerified||t.context.options.account?.accountLinking?.enabled===!1)return t.context.logger.error("Unable to link account - untrusted provider"),kn(he.UNABLE_TO_LINK_ACCOUNT);if(n.email?.toLowerCase()!==r.email.toLowerCase()&&t.context.options.account?.accountLinking?.allowDifferentEmails!==!0)return kn(he.EMAIL_DOES_NOT_MATCH);let a=await t.context.internalAdapter.findAccountByKey(o);if(a){if(a.userId.toString()!==r.userId.toString())return kn(he.ACCOUNT_ALREADY_LINKED_TO_DIFFERENT_USER);let c=gs(a.scope,s),d=Object.fromEntries(Object.entries({providerId:o.providerId,accessToken:await me(o.accessToken,t.context),refreshToken:await me(o.refreshToken,t.context),idToken:o.idToken,accessTokenExpiresAt:o.accessTokenExpiresAt,refreshTokenExpiresAt:o.refreshTokenExpiresAt,scope:c||void 0}).filter(([u,f])=>f!==void 0));await t.context.internalAdapter.updateAccount(a.id,d)}else if(!await t.context.internalAdapter.createAccount({userId:r.userId,...o,accessToken:await me(o.accessToken,t.context),refreshToken:await me(o.refreshToken,t.context),scope:s?.join(",")??o.scope}))return kn(he.UNABLE_TO_LINK_ACCOUNT);return await En(t,r.userId,n),{linked:!0}}async function Io(t,r){let{userInfo:n,account:o,callbackURL:i,disableSignUp:s,overrideUserInfo:a}=r,c=r.source??{method:"oauth",oauth:{providerId:o.providerId}},d=!!r.selectedUser||r.requireExactAccountBinding===!0,u=null,f=await t.context.internalAdapter.findAccountOwnerByKey({providerId:o.providerId,accountId:o.accountId}).catch((I)=>{t.context.logger.error(`Better auth was unable to query your database.
38
- Error: `,I),en(t,t.context.options.onAPIError?.errorURL||`${t.context.baseURL}/error`,"internal_server_error")});if(f?.kind==="orphaned")return t.context.logger.error("OAuth account references a missing user. Repair the account before retrying authentication."),{error:"unable to link account",data:null,isRegister:!1};let p=await(async()=>{if(f?.kind==="owned"){if(r.selectedUser&&f.user.id!==r.selectedUser.userId)throw new U("CONFLICT",{code:"account_ownership_conflict",message:"Account is already linked to another user"});return{user:f.user,linkedAccount:f.account,accounts:[f.account]}}if(r.selectedUser){let R=await t.context.internalAdapter.findUserById(r.selectedUser.userId);if(!R)throw new U("NOT_FOUND",{code:"user_not_found",message:"User not found"});return{user:R,linkedAccount:null,accounts:[]}}let I=await t.context.internalAdapter.findUserByEmail(n.email.toLowerCase(),{includeAccounts:!0});if(!I)return null;return{user:I.user,linkedAccount:null,accounts:I.accounts}})().catch((I)=>{if(Br(I))throw I;t.context.logger.error(`Better auth was unable to query your database.
39
- Error: `,I),en(t,t.context.options.onAPIError?.errorURL||`${t.context.baseURL}/error`,"internal_server_error")}),h=p?.user,m=!h;if(p){let I=p.linkedAccount??p.accounts.find((R)=>R.providerId===o.providerId&&R.accountId===o.accountId);if(!I){let R=t.context.options.account?.accountLinking,b=r.isTrustedProvider||r.trustProviderByName!==!1&&t.context.trustedProviders.includes(o.providerId),O=R?.requireLocalEmailVerified??!0;if(!r.selectedUser&&(!b&&!n.emailVerified||O&&!p.user.emailVerified||R?.enabled===!1||R?.disableImplicitLinking===!0)){if(El())t.context.logger.warn(`User already exist but account isn't linked to ${o.providerId}. To read more about how account linking works in Better Auth see https://www.better-auth.com/docs/concepts/users-accounts#account-linking.`);return{error:"account not linked",data:null}}try{let{id:g,...S}=n;await lr(t,{user:{...S,id:p.user.id,email:n.email.toLowerCase()},source:{...c,action:"link-account"}});let C=await t.context.internalAdapter.linkAccount({providerId:o.providerId,accountId:o.accountId,userId:p.user.id,accessToken:await me(o.accessToken,t.context),refreshToken:await me(o.refreshToken,t.context),idToken:o.idToken,accessTokenExpiresAt:o.accessTokenExpiresAt,refreshTokenExpiresAt:o.refreshTokenExpiresAt,scope:o.scope});if(!C)return{error:"unable to link account",data:null};if(d&&(C.accountId!==o.accountId||C.providerId!==o.providerId||C.userId!==p.user.id))throw new U("CONFLICT",{code:"account_hook_binding_conflict",message:"Account hook changed the selected authentication binding"});if(t.context.options.account?.storeAccountCookie)if(r.deferNonDatabaseWrites)u=C;else await ft(t,C)}catch(g){if(Br(g))throw g;return t.context.logger.error("Unable to link account",g),{error:"unable to link account",data:null}}if(!r.selectedUser&&n.emailVerified&&!p.user.emailVerified&&n.email.toLowerCase()===p.user.email)await t.context.internalAdapter.updateUser(p.user.id,{emailVerified:!0});if(!r.selectedUser)h=await En(t,p.user.id,n)??h}else{let{id:R,...b}=n;await lr(t,{user:{...b,id:p.user.id,email:n.email.toLowerCase()},source:{...c,action:"sign-in"}});let O=t.context.options.account?.updateAccountOnSignIn!==!1?Object.fromEntries(Object.entries({providerId:o.providerId,idToken:o.idToken,accessToken:await me(o.accessToken,t.context),refreshToken:await me(o.refreshToken,t.context),accessTokenExpiresAt:o.accessTokenExpiresAt,refreshTokenExpiresAt:o.refreshTokenExpiresAt}).filter(([g,S])=>S!==void 0)):{};if(t.context.options.account?.storeAccountCookie){let g={...I,...O};if(r.deferNonDatabaseWrites)u=g;else await ft(t,g)}if(Object.keys(O).length>0){let g=await t.context.internalAdapter.updateAccount(I.id,O);if(!g)return{error:"unable to update account",data:null};if(d&&(g.accountId!==o.accountId||g.providerId!==o.providerId||g.userId!==p.user.id))throw new U("CONFLICT",{code:"account_hook_binding_conflict",message:"Account hook changed the selected authentication binding"});if(r.deferNonDatabaseWrites&&u)u=g}if(!r.selectedUser&&n.emailVerified&&!p.user.emailVerified&&n.email.toLowerCase()===p.user.email)await t.context.internalAdapter.updateUser(p.user.id,{emailVerified:!0})}if(r.selectedUser?r.selectedUser.profile==="update":a){let{id:R,email:b,emailVerified:O,name:g,image:S,...C}=n,z=ur(t.context.options,C,"update"),L=await t.context.internalAdapter.updateUser(p.user.id,{name:g,image:S,...z,email:n.email.toLowerCase(),emailVerified:n.email.toLowerCase()===p.user.email?p.user.emailVerified||n.emailVerified:n.emailVerified});if(L==null)t.context.logger.warn("Could not update user info during OAuth sign in; preserving existing user for session.");if(r.selectedUser&&L&&L.id!==r.selectedUser.userId)throw new U("CONFLICT",{code:"user_hook_selection_conflict",message:"User hook changed the selected user"});h=L??h}}else{if(s)return{error:"signup disabled",data:null,isRegister:!1};try{let{id:I,email:R,emailVerified:b,name:O,image:g,...S}=n,C=ur(t.context.options,S,"create"),z={accessToken:await me(o.accessToken,t.context),refreshToken:await me(o.refreshToken,t.context),idToken:o.idToken,accessTokenExpiresAt:o.accessTokenExpiresAt,refreshTokenExpiresAt:o.refreshTokenExpiresAt,scope:o.scope,providerId:o.providerId,accountId:o.accountId},{createdUser:L,createdAccount:x}=await Ue(t.context.adapter,async()=>{let P=await t.context.internalAdapter.createUser({name:O,image:g,...C,email:n.email.toLowerCase(),emailVerified:n.emailVerified},c);return{createdUser:P,createdAccount:await t.context.internalAdapter.createAccount({...z,userId:P.id})}});if(d&&(x.accountId!==o.accountId||x.providerId!==o.providerId||x.userId!==L.id))throw new U("CONFLICT",{code:"account_hook_binding_conflict",message:"Account hook changed the selected authentication binding"});if(h=L,t.context.options.account?.storeAccountCookie)if(r.deferNonDatabaseWrites)u=x;else await ft(t,x)}catch(I){if(Br(I))throw I;return t.context.logger.error("Unable to create OAuth user",I),{error:"unable to create user",data:null,isRegister:!1}}}if(!h)return{error:"unable to create user",data:null,isRegister:!1};let w=t.context.socialProviders.find((I)=>I.id===o.providerId)?.options?.requireEmailVerification;if(m&&!h.emailVerified&&(t.context.options.emailVerification?.sendOnSignUp??w))await Cu(t,h,i,r.deferNonDatabaseWrites);if(w&&!h.emailVerified){if(!m&&t.context.options.emailVerification?.sendOnSignIn)await Cu(t,h,i,r.deferNonDatabaseWrites);return{error:he.EMAIL_NOT_VERIFIED,data:null,isRegister:m}}let y=await t.context.internalAdapter.createSession(h.id,void 0,void 0,void 0,{deferSecondaryStorageWrites:r.deferNonDatabaseWrites===!0});if(!y)return{error:"unable to create session",data:null,isRegister:!1};if(d&&y.userId!==(r.selectedUser?.userId??h.id))throw new U("CONFLICT",{code:"session_hook_user_conflict",message:"Session hook changed the selected user"});return{data:{session:y,user:h},error:null,isRegister:m,accountCookie:u}}async function Cu(t,r,n,o){let i=t.context.options.emailVerification?.sendVerificationEmail;if(!i)return;let s=async()=>{try{let a=await Se(t.context.secret,r.email,void 0,t.context.options.emailVerification?.expiresIn),c=`${t.context.baseURL}/verify-email?token=${a}&callbackURL=${encodeURIComponent(n||"/")}`;await t.context.runInBackgroundOrAwait(i({user:r,url:c,token:a},t.request))}catch(a){t.context.logger.error("Failed to send OAuth verification email",a)}};if(o)await Te(s);else await s()}async function En(t,r,n){if(t.context.options.account?.accountLinking?.updateUserInfoOnLink!==!0)return;try{let{email:o,emailVerified:i,name:s,image:a,...c}=n,d=ur(t.context.options,c,"update");return await t.context.internalAdapter.updateUser(r,{name:s,image:a,...d})}catch(o){t.context.logger.warn("Could not update user info on account link",o);return}}var vy=Sf("better-auth:oauth-encryption:v1");function Os(t,r){return rA(jn(Bn,Sf(t),vy,Sf(`better-auth:${r}:v1`),32))}function Ds(t,r){if(typeof t==="string")return Os(t,r);return{keys:new Map(Array.from(t.keys,([n,o])=>[n,Os(o,r)])),currentVersion:t.currentVersion,...t.legacySecret&&{legacySecret:Os(t.legacySecret,r)}}}var Ls=oe({callbackURL:e(),codeVerifier:e(),errorURL:e().optional(),newUserURL:e().optional(),expiresAt:_(),oauthState:e().optional(),link:l({email:e(),userId:_f()}).optional(),requestSignUp:E().optional(),idTokenNonce:e().optional(),serverContext:k(e(),W()).optional()}),Ps=(t)=>`auth-state:${t}`,OI=new Set(Object.keys(Ls.shape)),Ge=class extends te{code;details;errorURL;constructor(t,r){super(t,r);this.code=r.code,this.details=r.details,this.errorURL=r.errorURL}};async function Du(t,r,n){let o=_e(32);if(t.context.oauthConfig.storeStateStrategy==="cookie"){let a={...r,oauthState:o},c=await nt({key:Ds(t.context.secretConfig,"oauth-state-cookie"),data:JSON.stringify(a)}),d=t.context.createAuthCookie(n?.cookieName??"oauth_state",{maxAge:600});return t.setCookie(d.name,c,d.attributes),{state:o,codeVerifier:r.codeVerifier}}let i=t.context.createAuthCookie(n?.cookieName??"state",{maxAge:300});await t.setSignedCookie(i.name,o,t.context.secret,i.attributes);let s=new Date;if(s.setMinutes(s.getMinutes()+10),!await t.context.internalAdapter.createVerificationValue({value:JSON.stringify({...r,oauthState:o}),identifier:Ps(o),expiresAt:s}))throw new Ge("Unable to create verification. Make sure the database adapter is properly working and there is a verification table in the database",{code:"state_generation_error"});return{state:o,codeVerifier:r.codeVerifier}}async function Lu(t,r,n){if(!r)throw new Ge("State not found in OAuth callback",{code:"state_not_found"});let o=t.context.oauthConfig.storeStateStrategy,i;if(o==="cookie"){let s=t.context.createAuthCookie(n?.cookieName??"oauth_state"),a=t.getCookie(s.name);if(!a)throw new Ge("State mismatch: auth state cookie not found",{code:"state_mismatch",details:{state:r}});try{let c=await ot({key:Ds(t.context.secretConfig,"oauth-state-cookie"),data:a});i=Ls.parse(JSON.parse(c))}catch(c){throw new Ge("State invalid: Failed to decrypt or parse auth state",{code:"state_invalid",details:{state:r},cause:c})}if(!i.oauthState||i.oauthState!==r)throw new Ge("State mismatch: OAuth state parameter does not match stored state",{code:"state_security_mismatch",details:{state:r},errorURL:i.errorURL});Be(t,s)}else{let s=await t.context.internalAdapter.findVerificationValue(Ps(r));if(!s)throw new Ge("State mismatch: verification not found",{code:"state_mismatch",details:{state:r}});if(i=Ls.parse(JSON.parse(s.value)),i.oauthState!==void 0&&i.oauthState!==r)throw new Ge("State mismatch: OAuth state parameter does not match stored state",{code:"state_security_mismatch",details:{state:r},errorURL:i.errorURL});let a=t.context.createAuthCookie(n?.cookieName??"state"),c=await t.getSignedCookie(a.name,t.context.secret);if(!(n?.skipStateCookieCheck??t.context.oauthConfig.skipStateCookieCheck)&&(!c||c!==r))throw new Ge("State mismatch: State not persisted correctly",{code:"state_security_mismatch",details:{state:r},errorURL:i.errorURL});Be(t,a),await t.context.internalAdapter.deleteVerificationByIdentifier(Ps(r))}if(i.expiresAt<Date.now())throw new Ge("Invalid state: request expired",{code:"state_mismatch",details:{expiresAt:i.expiresAt},errorURL:i.errorURL});return i}function kr(t){return t.requiresIdTokenNonce?_e(32):void 0}async function Er(t,r){let n=t.body?.callbackURL||t.context.options.baseURL;if(!n)throw U.from("BAD_REQUEST",Ae.CALLBACK_URL_REQUIRED);let o=r?.codeVerifier??_e(128),i=await Yi(),s=i&&Object.keys(i).length?i:void 0,a={...r?.additionalData?r.additionalData:{},callbackURL:n,codeVerifier:o,errorURL:t.body?.errorCallbackURL,newUserURL:t.body?.newUserCallbackURL,link:r?.link,serverContext:s,expiresAt:Date.now()+600000,requestSignUp:t.body?.requestSignUp,idTokenNonce:r?.idTokenNonce};await Gi(a);try{return Du(t,a)}catch(c){throw t.context.logger.error("Failed to create verification",c),new U("INTERNAL_SERVER_ERROR",{message:"Unable to create verification",cause:c})}}async function Pu(t){let r=t.query.state||t.body?.state,n=t.context.options.onAPIError?.errorURL||`${t.context.baseURL}/error`,o;try{o=await Lu(t,r)}catch(i){t.context.logger.error("Failed to parse state",i);let s="internal_server_error",a=n;if(i instanceof Ge)s=i.code==="state_security_mismatch"?"state_mismatch":i.code,a=i.errorURL||n;en(t,a,s)}if(!o.errorURL)o.errorURL=n;if(o)await Gi(o);return o}var xu=(t)=>({id:"apple",name:"Apple",accountSubject:({profile:n})=>n.sub,async createAuthorizationURL({state:n,scopes:o,redirectURI:i,additionalParams:s,codeVerifier:a}){if(!Re(t.clientId)||!t.clientSecret)throw Ee.error("Client ID and client secret are required for Apple. Make sure to provide them in the options."),new te("CLIENT_ID_AND_SECRET_REQUIRED");let c=t.disableDefaultScope?[]:["email","name"];if(t.scope)c.push(...t.scope);if(o)c.push(...o);return await V({id:"apple",options:t,authorizationEndpoint:"https://appleid.apple.com/auth/authorize",scopes:c,state:n,redirectURI:i,codeVerifier:a,responseMode:"form_post",responseType:"code id_token",additionalParams:s})},validateAuthorizationCode:async({code:n,codeVerifier:o,redirectURI:i})=>K({code:n,codeVerifier:o,redirectURI:i,options:t,tokenEndpoint:"https://appleid.apple.com/auth/token"}),idToken:{jwks:(n)=>Nu(n.kid),issuer:"https://appleid.apple.com",algorithms:["RS256"],audience:t.audience&&t.audience.length?t.audience:t.appBundleIdentifier?t.appBundleIdentifier:t.clientId,maxTokenAge:"1h",nonceComparison:"exact-or-sha256"},refreshAccessToken:t.refreshAccessToken?t.refreshAccessToken:async(n)=>F({refreshToken:n,options:t,tokenEndpoint:"https://appleid.apple.com/auth/token"}),async getUserInfo(n){if(t.getUserInfo)return t.getUserInfo(n);if(!n.idToken)return null;let o=Xr(n.idToken);if(!o)return null;let i;if(n.user?.name)i=`${n.user.name.firstName||""} ${n.user.name.lastName||""}`.trim();else i=o.name||"";let s=typeof o.email_verified==="boolean"?o.email_verified:o.email_verified==="true",a={...o,name:i},c=await t.mapProfileToUser?.(a);return{user:{name:a.name,emailVerified:s,email:o.email,...c},data:a}},options:t}),Nu=async(t)=>{let{data:r}=await Me("https://appleid.apple.com/auth/keys");if(!r?.keys)throw new U("BAD_REQUEST",{message:"Keys not found"});let n=r.keys.find((o)=>o.kid===t);if(!n)throw Error(`JWK with kid ${t} not found`);return await Sn(n,n.alg)};var Mu=(t)=>({id:"atlassian",name:"Atlassian",accountSubject:({profile:n})=>n.account_id,async createAuthorizationURL({state:n,scopes:o,codeVerifier:i,redirectURI:s,additionalParams:a}){if(!t.clientId||!t.clientSecret)throw Ee.error("Client Id and Secret are required for Atlassian"),new te("CLIENT_ID_AND_SECRET_REQUIRED");if(!i)throw new te("codeVerifier is required for Atlassian");let c=t.disableDefaultScope?[]:["read:jira-user","offline_access"];if(t.scope)c.push(...t.scope);if(o)c.push(...o);return V({id:"atlassian",options:t,authorizationEndpoint:"https://auth.atlassian.com/authorize",scopes:c,state:n,codeVerifier:i,redirectURI:s,additionalParams:{...a??{},audience:"api.atlassian.com"},prompt:t.prompt})},validateAuthorizationCode:async({code:n,codeVerifier:o,redirectURI:i})=>K({code:n,codeVerifier:o,redirectURI:i,options:t,tokenEndpoint:"https://auth.atlassian.com/oauth/token"}),refreshAccessToken:t.refreshAccessToken?t.refreshAccessToken:async(n)=>F({refreshToken:n,options:{clientId:t.clientId,clientSecret:t.clientSecret},tokenEndpoint:"https://auth.atlassian.com/oauth/token"}),async getUserInfo(n){if(t.getUserInfo)return t.getUserInfo(n);if(!n.accessToken)return null;try{let{data:o}=await Me("https://api.atlassian.com/me",{headers:{Authorization:`Bearer ${n.accessToken}`}});if(!o)return null;let i=await t.mapProfileToUser?.(o);return{user:{name:o.name,email:o.email,image:o.picture,emailVerified:!1,...i},data:o}}catch(o){return Ee.error("Failed to fetch user info from Atlassian:",o),null}},options:t});var Sy="https://dash.cloudflare.com/oauth2/auth",Fu="https://dash.cloudflare.com/oauth2/token",Ry="https://api.cloudflare.com/client/v4/user",Ku=(t)=>{let r=t.clientSecret?"client_secret_basic":"none";return{method:t.tokenEndpointAuthMethod??r}},Wu=(t)=>({id:"cloudflare",name:"Cloudflare",accountSubject:({profile:r})=>r.id,createAuthorizationURL({state:r,scopes:n,codeVerifier:o,redirectURI:i}){let s=t.disableDefaultScope?[]:["user-details.read"];if(t.scope?.length)s.push(...t.scope);if(n?.length)s.push(...n);return V({id:"cloudflare",options:t,authorizationEndpoint:Sy,scopes:s.length?[...new Set(s)]:void 0,state:r,codeVerifier:o,redirectURI:i})},validateAuthorizationCode:async({code:r,codeVerifier:n,redirectURI:o})=>K({code:r,codeVerifier:n,redirectURI:o,options:t,tokenEndpoint:Fu,tokenEndpointAuth:Ku(t)}),refreshAccessToken:t.refreshAccessToken?t.refreshAccessToken:async(r)=>F({refreshToken:r,options:{clientId:t.clientId,clientKey:t.clientKey,clientSecret:t.clientSecret},tokenEndpoint:Fu,tokenEndpointAuth:Ku(t)}),async getUserInfo(r){if(t.getUserInfo)return t.getUserInfo(r);let{data:n,error:o}=await Me(Ry,{headers:{authorization:`Bearer ${r.accessToken}`}});if(o||!n?.success||!n.result)return Ee.error("Failed to fetch user info from Cloudflare:",o??n?.errors),null;let i=n.result,s=[i.first_name,i.last_name].filter(Boolean).join(" ")||i.email,a=await t.mapProfileToUser?.(i);return{user:{name:s,email:i.email,emailVerified:!1,...a},data:i}},options:t});var Ju=(t)=>{if(!t.domain||!t.region||!t.userPoolId)throw Ee.error("Domain, region and userPoolId are required for Amazon Cognito. Make sure to provide them in the options."),new te("DOMAIN_AND_REGION_REQUIRED");let r=t.domain.replace(/^https?:\/\//,""),n=`https://${r}/oauth2/authorize`,o=`https://${r}/oauth2/token`,i=`https://${r}/oauth2/userinfo`;return{id:"cognito",name:"Cognito",accountSubject:({profile:s})=>s.sub,async createAuthorizationURL({state:s,scopes:a,codeVerifier:c,redirectURI:d,additionalParams:u}){if(!Re(t.clientId))throw Ee.error("ClientId is required for Amazon Cognito. Make sure to provide them in the options."),new te("CLIENT_ID_AND_SECRET_REQUIRED");if(t.requireClientSecret&&!t.clientSecret)throw Ee.error("Client Secret is required when requireClientSecret is true. Make sure to provide it in the options."),new te("CLIENT_SECRET_REQUIRED");let f=t.disableDefaultScope?[]:["openid","profile","email"];if(t.scope)f.push(...t.scope);if(a)f.push(...a);let p=await V({id:"cognito",options:{...t},authorizationEndpoint:n,scopes:f,state:s,codeVerifier:c,redirectURI:d,prompt:t.prompt,additionalParams:{...t.identityProvider?{identity_provider:t.identityProvider}:{},...u??{}}}),h=p.searchParams.get("scope");if(h){p.searchParams.delete("scope");let m=encodeURIComponent(h),w=p.toString(),y=w.includes("?")?"&":"?";return new URL(`${w}${y}scope=${m}`)}return p},validateAuthorizationCode:async({code:s,codeVerifier:a,redirectURI:c})=>K({code:s,codeVerifier:a,redirectURI:c,options:t,tokenEndpoint:o}),refreshAccessToken:t.refreshAccessToken?t.refreshAccessToken:async(s)=>F({refreshToken:s,options:{clientId:t.clientId,clientKey:t.clientKey,clientSecret:t.clientSecret},tokenEndpoint:o}),idToken:{jwks:(s)=>Yu(s.kid,t.region,t.userPoolId),issuer:`https://cognito-idp.${t.region}.amazonaws.com/${t.userPoolId}`,audience:t.clientId,algorithms:["RS256"],maxTokenAge:"1h"},async getUserInfo(s){if(t.getUserInfo)return t.getUserInfo(s);if(s.idToken)try{let a=Xr(s.idToken);if(!a)return null;let c=a.name||a.given_name||a.username||"",d={...a,name:c},u=await t.mapProfileToUser?.(d);return{user:{name:d.name,email:a.email,image:a.picture,emailVerified:a.email_verified,...u},data:d}}catch(a){Ee.error("Failed to decode ID token:",a)}if(s.accessToken)try{let{data:a}=await Me(i,{headers:{Authorization:`Bearer ${s.accessToken}`}});if(a){let c=await t.mapProfileToUser?.(a);return{user:{name:a.name||a.given_name||a.username||"",email:a.email,image:a.picture,emailVerified:a.email_verified,...c},data:a}}}catch(a){Ee.error("Failed to fetch user info from Cognito:",a)}return null},options:t}},Yu=async(t,r,n)=>{let o=`https://cognito-idp.${r}.amazonaws.com/${n}/.well-known/jwks.json`;try{let{data:i}=await Me(o);if(!i?.keys)throw new U("BAD_REQUEST",{message:"Keys not found"});let s=i.keys.find((a)=>a.kid===t);if(!s)throw Error(`JWK with kid ${t} not found`);return await Sn(s,s.alg)}catch(i){throw Ee.error("Failed to fetch Cognito public key:",i),i}};var Xu=(t)=>({id:"discord",name:"Discord",accountSubject:({profile:n})=>n.id,createAuthorizationURL({state:n,scopes:o,redirectURI:i,additionalParams:s}){let a=t.disableDefaultScope?[]:["identify","email"];if(o)a.push(...o);if(t.scope)a.push(...t.scope);let c=a.includes("bot");return V({id:"discord",options:t,authorizationEndpoint:"https://discord.com/api/oauth2/authorize",scopes:a,state:n,redirectURI:i,prompt:t.prompt||"none",additionalParams:{...c&&t.permissions!==void 0?{permissions:String(t.permissions)}:{},...s??{}}})},validateAuthorizationCode:async({code:n,redirectURI:o})=>K({code:n,redirectURI:o,options:t,tokenEndpoint:"https://discord.com/api/oauth2/token"}),refreshAccessToken:t.refreshAccessToken?t.refreshAccessToken:async(n)=>F({refreshToken:n,options:{clientId:t.clientId,clientKey:t.clientKey,clientSecret:t.clientSecret},tokenEndpoint:"https://discord.com/api/oauth2/token"}),async getUserInfo(n){if(t.getUserInfo)return t.getUserInfo(n);let{data:o,error:i}=await Me("https://discord.com/api/users/@me",{headers:{authorization:`Bearer ${n.accessToken}`}});if(i)return null;if(o.avatar===null)o.image_url=`https://cdn.discordapp.com/embed/avatars/${o.discriminator==="0"?Number(BigInt(o.id)>>BigInt(22))%6:parseInt(o.discriminator)%5}.png`;else{let a=o.avatar.startsWith("a_")?"gif":"png";o.image_url=`https://cdn.discordapp.com/avatars/${o.id}/${o.avatar}.${a}`}let s=await t.mapProfileToUser?.(o);return{user:{name:o.global_name||o.username||"",email:o.email,emailVerified:o.verified,image:o.image_url,...s},data:o}},options:t});var el=(t)=>({id:"dropbox",name:"Dropbox",accountSubject:({profile:n})=>n.account_id,createAuthorizationURL:async({state:n,scopes:o,codeVerifier:i,redirectURI:s,additionalParams:a})=>{let c=t.disableDefaultScope?[]:["account_info.read"];if(t.scope)c.push(...t.scope);if(o)c.push(...o);return await V({id:"dropbox",options:t,authorizationEndpoint:"https://www.dropbox.com/oauth2/authorize",scopes:c,state:n,redirectURI:s,codeVerifier:i,additionalParams:{...t.accessType?{token_access_type:t.accessType}:{},...a??{}}})},validateAuthorizationCode:async({code:n,codeVerifier:o,redirectURI:i})=>await K({code:n,codeVerifier:o,redirectURI:i,options:t,tokenEndpoint:"https://api.dropboxapi.com/oauth2/token"}),refreshAccessToken:t.refreshAccessToken?t.refreshAccessToken:async(n)=>F({refreshToken:n,options:{clientId:t.clientId,clientKey:t.clientKey,clientSecret:t.clientSecret},tokenEndpoint:"https://api.dropboxapi.com/oauth2/token"}),async getUserInfo(n){if(t.getUserInfo)return t.getUserInfo(n);let{data:o,error:i}=await Me("https://api.dropboxapi.com/2/users/get_current_account",{method:"POST",headers:{Authorization:`Bearer ${n.accessToken}`}});if(i)return null;let s=await t.mapProfileToUser?.(o);return{user:{name:o.name?.display_name,email:o.email,emailVerified:o.email_verified||!1,image:o.profile_photo_url,...s},data:o}},options:t});async function tl(t,r){let n=Re(r.clientId);if(!n||!r.clientSecret)return null;let o=Array.isArray(r.clientId)?r.clientId:[r.clientId],{data:i,error:s}=await Me("https://graph.facebook.com/debug_token",{query:{input_token:t,access_token:`${n}|${r.clientSecret}`}});if(s||!i?.data)return null;let{is_valid:a,app_id:c,user_id:d}=i.data;if(a!==!0||!c||!o.includes(c)||!d)return null;return d}var rl=(t)=>({id:"facebook",name:"Facebook",accountSubject:({profile:r})=>("sub"in r)?r.sub:r.id,async createAuthorizationURL({state:r,scopes:n,redirectURI:o,loginHint:i,additionalParams:s}){if(!Re(t.clientId)||!t.clientSecret)throw Ee.error("Client ID and client secret are required for Facebook. Make sure to provide them in the options."),new te("CLIENT_ID_AND_SECRET_REQUIRED");let a=t.disableDefaultScope?[]:["email","public_profile"];if(t.scope)a.push(...t.scope);if(n)a.push(...n);return await V({id:"facebook",options:t,authorizationEndpoint:"https://www.facebook.com/v24.0/dialog/oauth",scopes:a,state:r,redirectURI:o,loginHint:i,additionalParams:{...t.configId?{config_id:t.configId}:{},...s??{}}})},validateAuthorizationCode:async({code:r,redirectURI:n})=>K({code:r,redirectURI:n,options:t,tokenEndpoint:"https://graph.facebook.com/v24.0/oauth/access_token"}),idToken:{jwks:gf(new URL("https://limited.facebook.com/.well-known/oauth/openid/jwks/")),issuer:"https://www.facebook.com",audience:t.clientId,algorithms:["RS256"],allowOpaqueToken:!0},refreshAccessToken:t.refreshAccessToken?t.refreshAccessToken:async(r)=>F({refreshToken:r,options:{clientId:t.clientId,clientKey:t.clientKey,clientSecret:t.clientSecret},tokenEndpoint:"https://graph.facebook.com/v24.0/oauth/access_token"}),async getUserInfo(r){if(t.getUserInfo){let c=!!r.idToken&&r.idToken.split(".").length!==3,d=r.accessToken||(c?r.idToken:void 0);if(d&&!await tl(d,t))return null;return t.getUserInfo(r)}if(r.idToken&&r.idToken.split(".").length===3){let c=Xr(r.idToken),d=await t.mapProfileToUser?.(c);return{user:{name:c.name,email:c.email,image:c.picture,emailVerified:!1,...d},data:c}}let n=r.accessToken;if(!n)return null;let o=await tl(n,t);if(!o)return null;let{data:i,error:s}=await Me("https://graph.facebook.com/me?fields="+["id","name","email","picture",...t?.fields||[]].join(","),{auth:{type:"Bearer",token:n}});if(s)return null;if(i.id!==o)return null;let a=await t.mapProfileToUser?.(i);return{user:{name:i.name,email:i.email,image:i.picture.data.url,emailVerified:i.email_verified??!1,...a},data:i}},options:t});var nl=(t)=>({id:"figma",name:"Figma",accountSubject:({profile:n})=>n.id,async createAuthorizationURL({state:n,scopes:o,codeVerifier:i,redirectURI:s,additionalParams:a}){if(!t.clientId||!t.clientSecret)throw Ee.error("Client Id and Client Secret are required for Figma. Make sure to provide them in the options."),new te("CLIENT_ID_AND_SECRET_REQUIRED");if(!i)throw new te("codeVerifier is required for Figma");let c=t.disableDefaultScope?[]:["current_user:read"];if(t.scope)c.push(...t.scope);if(o)c.push(...o);return await V({id:"figma",options:t,authorizationEndpoint:"https://www.figma.com/oauth",scopes:c,state:n,codeVerifier:i,redirectURI:s,additionalParams:a})},validateAuthorizationCode:async({code:n,codeVerifier:o,redirectURI:i})=>K({code:n,codeVerifier:o,redirectURI:i,options:t,tokenEndpoint:"https://api.figma.com/v1/oauth/token",authentication:"basic"}),refreshAccessToken:t.refreshAccessToken?t.refreshAccessToken:async(n)=>F({refreshToken:n,options:{clientId:t.clientId,clientKey:t.clientKey,clientSecret:t.clientSecret},tokenEndpoint:"https://api.figma.com/v1/oauth/token",authentication:"basic"}),async getUserInfo(n){if(t.getUserInfo)return t.getUserInfo(n);try{let{data:o}=await Me("https://api.figma.com/v1/me",{headers:{Authorization:`Bearer ${n.accessToken}`}});if(!o)return Ee.error("Failed to fetch user from Figma"),null;let i=await t.mapProfileToUser?.(o);return{user:{name:o.handle,email:o.email,image:o.img_url,emailVerified:!1,...i},data:o}}catch(o){return Ee.error("Failed to fetch user info from Figma:",o),null}},options:t});var ol=(t)=>({id:"github",name:"GitHub",accountSubject:({profile:n})=>n.id,createAuthorizationURL({state:n,scopes:o,loginHint:i,codeVerifier:s,redirectURI:a,additionalParams:c}){let d=t.disableDefaultScope?[]:["read:user","user:email"];if(t.scope)d.push(...t.scope);if(o)d.push(...o);return V({id:"github",options:t,authorizationEndpoint:"https://github.com/login/oauth/authorize",scopes:d,state:n,codeVerifier:s,redirectURI:a,loginHint:i,prompt:t.prompt,additionalParams:c})},validateAuthorizationCode:async({code:n,codeVerifier:o,redirectURI:i})=>{let{body:s,headers:a}=await Us({code:n,codeVerifier:o,redirectURI:i,options:t}),{data:c,error:d}=await Me("https://github.com/login/oauth/access_token",{method:"POST",body:s,headers:a});if(d)return Ee.error("GitHub OAuth token exchange failed:",d),null;if("error"in c)return Ee.error("GitHub OAuth token exchange failed:",c),null;return sn(c)},refreshAccessToken:t.refreshAccessToken?t.refreshAccessToken:async(n)=>F({refreshToken:n,options:{clientId:t.clientId,clientKey:t.clientKey,clientSecret:t.clientSecret},tokenEndpoint:"https://github.com/login/oauth/access_token"}),async getUserInfo(n){if(t.getUserInfo)return t.getUserInfo(n);let{data:o,error:i}=await Me("https://api.github.com/user",{headers:{"User-Agent":"better-auth",authorization:`Bearer ${n.accessToken}`}});if(i)return null;let{data:s}=await Me("https://api.github.com/user/emails",{headers:{Authorization:`Bearer ${n.accessToken}`,"User-Agent":"better-auth"}});if(!o.email&&s)o.email=(s.find((d)=>d.primary)??s[0])?.email;let a=s?.find((d)=>d.email===o.email)?.verified??!1,c=await t.mapProfileToUser?.(o);return{user:{name:o.name||o.login||"",email:o.email,image:o.avatar_url,emailVerified:a,...c},data:o}},options:t});var xs=(t="")=>t.split("://").map((r)=>r.replace(/\/{2,}/g,"/")).join("://"),Ty=(t)=>{let r=t||"https://gitlab.com";return{authorizationEndpoint:xs(`${r}/oauth/authorize`),tokenEndpoint:xs(`${r}/oauth/token`),userinfoEndpoint:xs(`${r}/api/v4/user`)}},il=(t)=>{let{authorizationEndpoint:r,tokenEndpoint:n,userinfoEndpoint:o}=Ty(t.issuer),i="gitlab";return{id:"gitlab",name:"Gitlab",accountSubject:({profile:s})=>s.id,createAuthorizationURL:async({state:s,scopes:a,codeVerifier:c,loginHint:d,redirectURI:u,additionalParams:f})=>{let p=t.disableDefaultScope?[]:["read_user"];if(t.scope)p.push(...t.scope);if(a)p.push(...a);return await V({id:"gitlab",options:t,authorizationEndpoint:r,scopes:p,state:s,redirectURI:u,codeVerifier:c,loginHint:d,additionalParams:f})},validateAuthorizationCode:async({code:s,redirectURI:a,codeVerifier:c})=>K({code:s,redirectURI:a,options:t,codeVerifier:c,tokenEndpoint:n}),refreshAccessToken:t.refreshAccessToken?t.refreshAccessToken:async(s)=>F({refreshToken:s,options:{clientId:t.clientId,clientKey:t.clientKey,clientSecret:t.clientSecret},tokenEndpoint:n}),async getUserInfo(s){if(t.getUserInfo)return t.getUserInfo(s);let{data:a,error:c}=await Me(o,{headers:{authorization:`Bearer ${s.accessToken}`}});if(c||a.state!=="active"||a.locked)return null;let d=await t.mapProfileToUser?.(a);return{user:{name:a.name??a.username??"",email:a.email,image:a.avatar_url,emailVerified:a.email_verified??!1,...d},data:a}},options:t}};var Iy="1h",sl="RS256",Uy=[sl];var zs=(t,r)=>{if(!t)return!0;if(typeof r!=="string"||!r)return!1;if(t==="*")return!0;return r===t},al=(t)=>({id:"google",name:"Google",accountSubject:({profile:r})=>r.sub,async createAuthorizationURL({state:r,scopes:n,codeVerifier:o,redirectURI:i,loginHint:s,display:a,additionalParams:c}){if(!Re(t.clientId)||!t.clientSecret)throw Ee.error("Client Id and Client Secret is required for Google. Make sure to provide them in the options."),new te("CLIENT_ID_AND_SECRET_REQUIRED");if(!o)throw new te("codeVerifier is required for Google");let d=t.disableDefaultScope?[]:["email","profile","openid"];if(t.scope)d.push(...t.scope);if(n)d.push(...n);return await V({id:"google",options:t,authorizationEndpoint:"https://accounts.google.com/o/oauth2/v2/auth",scopes:d,state:r,codeVerifier:o,redirectURI:i,prompt:t.prompt,accessType:t.accessType,display:a||t.display,loginHint:s,hd:t.hd,additionalParams:{...t.includeGrantedScopes===!1?{}:{include_granted_scopes:"true"},...c??{}}})},validateAuthorizationCode:async({code:r,codeVerifier:n,redirectURI:o})=>K({code:r,codeVerifier:n,redirectURI:o,options:t,tokenEndpoint:"https://oauth2.googleapis.com/token"}),refreshAccessToken:t.refreshAccessToken?t.refreshAccessToken:async(r)=>F({refreshToken:r,options:{clientId:t.clientId,clientKey:t.clientKey,clientSecret:t.clientSecret},tokenEndpoint:"https://oauth2.googleapis.com/token"}),idToken:{jwks:(r)=>cl(r.kid),issuer:["https://accounts.google.com","accounts.google.com"],audience:t.clientId,algorithms:Uy,maxTokenAge:Iy,verifyClaims:t.hd?(r)=>zs(t.hd,r.hd):void 0},async getUserInfo(r){if(t.getUserInfo)return t.getUserInfo(r);if(!r.idToken)return null;let n=Xr(r.idToken);if(!zs(t.hd,n.hd))return Ee.error(`Google sign-in rejected: id token hosted domain (hd) "${n.hd??"<missing>"}" does not satisfy the configured "hd" option "${t.hd}".`),null;let o=await t.mapProfileToUser?.(n);return{user:{name:n.name,email:n.email,image:n.picture,emailVerified:n.email_verified,...o},data:n}},options:t}),cl=async(t)=>{let[r]=await Cy(t);if(!r)throw Error(`JWK with kid ${t} not found`);return r},Cy=async(t)=>{let{data:r}=await Me("https://www.googleapis.com/oauth2/v3/certs");if(!r?.keys)throw new U("BAD_REQUEST",{message:"Keys not found"});let n=t?r.keys.filter((o)=>o.kid===t):r.keys;if(!n.length)throw Error(`JWK with kid ${t} not found`);return Promise.all(n.map((o)=>Sn(o,sl)))};var dl=(t)=>({id:"huggingface",name:"Hugging Face",accountSubject:({profile:n})=>n.sub,createAuthorizationURL({state:n,scopes:o,codeVerifier:i,redirectURI:s,additionalParams:a}){let c=t.disableDefaultScope?[]:["openid","profile","email"];if(t.scope)c.push(...t.scope);if(o)c.push(...o);return V({id:"huggingface",options:t,authorizationEndpoint:"https://huggingface.co/oauth/authorize",scopes:c,state:n,codeVerifier:i,redirectURI:s,additionalParams:a})},validateAuthorizationCode:async({code:n,codeVerifier:o,redirectURI:i})=>K({code:n,codeVerifier:o,redirectURI:i,options:t,tokenEndpoint:"https://huggingface.co/oauth/token"}),refreshAccessToken:t.refreshAccessToken?t.refreshAccessToken:async(n)=>F({refreshToken:n,options:{clientId:t.clientId,clientKey:t.clientKey,clientSecret:t.clientSecret},tokenEndpoint:"https://huggingface.co/oauth/token"}),async getUserInfo(n){if(t.getUserInfo)return t.getUserInfo(n);let{data:o,error:i}=await Me("https://huggingface.co/oauth/userinfo",{method:"GET",headers:{Authorization:`Bearer ${n.accessToken}`}});if(i)return null;let s=await t.mapProfileToUser?.(o);return{user:{name:o.name||o.preferred_username||"",email:o.email,image:o.picture,emailVerified:o.email_verified??!1,...s},data:o}},options:t});var ul=(t)=>({id:"kakao",name:"Kakao",accountSubject:({profile:n})=>n.id,createAuthorizationURL({state:n,scopes:o,redirectURI:i,additionalParams:s}){let a=t.disableDefaultScope?[]:["account_email","profile_image","profile_nickname"];if(t.scope)a.push(...t.scope);if(o)a.push(...o);return V({id:"kakao",options:t,authorizationEndpoint:"https://kauth.kakao.com/oauth/authorize",scopes:a,state:n,redirectURI:i,additionalParams:s})},validateAuthorizationCode:async({code:n,redirectURI:o})=>K({code:n,redirectURI:o,options:t,tokenEndpoint:"https://kauth.kakao.com/oauth/token"}),refreshAccessToken:t.refreshAccessToken?t.refreshAccessToken:async(n)=>F({refreshToken:n,options:{clientId:t.clientId,clientKey:t.clientKey,clientSecret:t.clientSecret},tokenEndpoint:"https://kauth.kakao.com/oauth/token"}),async getUserInfo(n){if(t.getUserInfo)return t.getUserInfo(n);let{data:o,error:i}=await Me("https://kapi.kakao.com/v2/user/me",{headers:{Authorization:`Bearer ${n.accessToken}`}});if(i||!o)return null;let s=await t.mapProfileToUser?.(o),a=o.kakao_account||{},c=a.profile||{};return{user:{name:c.nickname||a.name||"",email:a.email,image:c.profile_image_url||c.thumbnail_image_url,emailVerified:!!a.is_email_valid&&!!a.is_email_verified,...s},data:o}},options:t});var ll=(t)=>({id:"kick",name:"Kick",accountSubject:({profile:r})=>r.user_id,createAuthorizationURL({state:r,scopes:n,redirectURI:o,codeVerifier:i,additionalParams:s}){let a=t.disableDefaultScope?[]:["user:read"];if(t.scope)a.push(...t.scope);if(n)a.push(...n);return V({id:"kick",redirectURI:o,options:t,authorizationEndpoint:"https://id.kick.com/oauth/authorize",scopes:a,codeVerifier:i,state:r,additionalParams:s})},async validateAuthorizationCode({code:r,redirectURI:n,codeVerifier:o}){return K({code:r,redirectURI:n,options:t,tokenEndpoint:"https://id.kick.com/oauth/token",codeVerifier:o})},refreshAccessToken:t.refreshAccessToken?t.refreshAccessToken:async(r)=>F({refreshToken:r,options:{clientId:t.clientId,clientSecret:t.clientSecret},tokenEndpoint:"https://id.kick.com/oauth/token"}),async getUserInfo(r){if(t.getUserInfo)return t.getUserInfo(r);let{data:n,error:o}=await Me("https://api.kick.com/public/v1/users",{method:"GET",headers:{Authorization:`Bearer ${r.accessToken}`}});if(o)return null;let i=n.data[0],s=await t.mapProfileToUser?.(i);return{user:{name:i.name,email:i.email,image:i.profile_picture,emailVerified:!1,...s},data:i}},options:t});var fl=(t)=>({id:"line",name:"LINE",accountSubject:({profile:s})=>s.sub,async createAuthorizationURL({state:s,scopes:a,codeVerifier:c,redirectURI:d,loginHint:u,additionalParams:f}){let p=t.disableDefaultScope?[]:["openid","profile","email"];if(t.scope)p.push(...t.scope);if(a)p.push(...a);return await V({id:"line",options:t,authorizationEndpoint:"https://access.line.me/oauth2/v2.1/authorize",scopes:p,state:s,codeVerifier:c,redirectURI:d,loginHint:u,additionalParams:f})},validateAuthorizationCode:async({code:s,codeVerifier:a,redirectURI:c})=>K({code:s,codeVerifier:a,redirectURI:c,options:t,tokenEndpoint:"https://api.line.me/oauth2/v2.1/token"}),refreshAccessToken:t.refreshAccessToken?t.refreshAccessToken:async(s)=>F({refreshToken:s,options:{clientId:t.clientId,clientSecret:t.clientSecret},tokenEndpoint:"https://api.line.me/oauth2/v2.1/token"}),idToken:{verify:async(s,a)=>{let c=new URLSearchParams;if(c.set("id_token",s),c.set("client_id",t.clientId),a)c.set("nonce",a);let{data:d,error:u}=await Me("https://api.line.me/oauth2/v2.1/verify",{method:"POST",headers:{"content-type":"application/x-www-form-urlencoded"},body:c});if(u||!d)return!1;if(d.aud!==t.clientId)return!1;if(d.nonce&&d.nonce!==a)return!1;return!0}},async getUserInfo(s){if(t.getUserInfo)return t.getUserInfo(s);let a=null;if(s.idToken)try{a=Xr(s.idToken)}catch{}if(!a){let{data:d}=await Me("https://api.line.me/oauth2/v2.1/userinfo",{headers:{authorization:`Bearer ${s.accessToken}`}});a=d||null}if(!a)return null;let c=await t.mapProfileToUser?.(a);return{user:{name:a.name||"",email:a.email,image:a.picture,emailVerified:!1,...c},data:a}},options:t});var pl=(t)=>({id:"linear",name:"Linear",accountSubject:({profile:n})=>n.id,createAuthorizationURL({state:n,scopes:o,loginHint:i,redirectURI:s,additionalParams:a}){let c=t.disableDefaultScope?[]:["read"];if(t.scope)c.push(...t.scope);if(o)c.push(...o);return V({id:"linear",options:t,authorizationEndpoint:"https://linear.app/oauth/authorize",scopes:c,state:n,redirectURI:s,loginHint:i,additionalParams:a})},validateAuthorizationCode:async({code:n,redirectURI:o})=>K({code:n,redirectURI:o,options:t,tokenEndpoint:"https://api.linear.app/oauth/token"}),refreshAccessToken:t.refreshAccessToken?t.refreshAccessToken:async(n)=>F({refreshToken:n,options:{clientId:t.clientId,clientKey:t.clientKey,clientSecret:t.clientSecret},tokenEndpoint:"https://api.linear.app/oauth/token"}),async getUserInfo(n){if(t.getUserInfo)return t.getUserInfo(n);let{data:o,error:i}=await Me("https://api.linear.app/graphql",{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${n.accessToken}`},body:JSON.stringify({query:`
37
+ ${t.jti}`,n=await crypto.subtle.digest("SHA-256",new TextEncoder().encode(r));return mr(new Uint8Array(n))}async function Gw(t,r){if(!t)return;if(!await t.reserve(r))throw ge("invalid_dpop_proof","DPoP proof jti has already been used")}async function Ro({proofJwt:t,method:r,url:n,accessToken:o,expectedJkt:i,requireAth:s=!1,nowSeconds:a=Math.floor(Date.now()/1000),proofMaxAgeSeconds:c=Hw,signingAlgorithms:d=ja,replayStore:u}){if(!t||t.split(".").length!==3)throw ge("invalid_dpop_proof","DPoP proof must be a compact JWT");let f;try{f=so(t)}catch(C){throw ge("invalid_dpop_proof",C instanceof Error?C.message:"DPoP proof header is invalid")}if(f.typ!=="dpop+jwt")throw ge("invalid_dpop_proof",'DPoP proof typ must be "dpop+jwt"');Ww(f.alg,d),Jw(f.jwk);let p;try{p=(await Qr(t,await In(f.jwk,f.alg),{typ:wu})).payload}catch(C){throw ge("invalid_dpop_proof",C instanceof Error?C.message:"DPoP proof signature is invalid")}let h=vo(p,"htm"),m=vo(p,"htu"),w=vo(p,"jti"),y=Kw(p,"iat");if(!h||!m||!w||y===void 0)throw ge("invalid_dpop_proof","DPoP proof must include htm, htu, jti, and iat claims");if(w.length>Vw)throw ge("invalid_dpop_proof","DPoP proof jti is too large");if(h.toUpperCase()!==r.toUpperCase())throw ge("invalid_dpop_proof","DPoP proof htm does not match the request method");let I,R;try{I=Es(n),R=Es(m)}catch(C){throw ge("invalid_dpop_proof",C instanceof Error?C.message:"DPoP proof htu is invalid")}if(R!==I)throw ge("invalid_dpop_proof","DPoP proof htu does not match the request URL");if(y>a+5||a-y>c)throw ge("invalid_dpop_proof","DPoP proof iat is outside the accepted window");let b=vo(p,"ath");if(s&&!b)throw ge("invalid_dpop_proof","DPoP proof must include an ath claim");if(o!==void 0){if(b!==await yu(o))throw ge("invalid_dpop_proof","DPoP proof ath does not match the access token")}let O=await _u(f.jwk);if(i!==void 0&&O!==i)throw ge("invalid_dpop_proof","DPoP proof key does not match the bound token");let g=await Qw({jkt:O,htm:h.toUpperCase(),htu:I,jti:w}),S=new Date((y+c)*1000);return await Gw(u,{key:g,expiresAt:S,now:new Date(a*1000)}),{jwk:f.jwk,jkt:O,jti:w,htm:h,htu:I,iat:y,ath:b,replayKey:g,expiresAt:S}}function ln(t,r){return Object.assign(Error(r),{code:t})}function wn(t){return t instanceof Error&&"code"in t&&(t.code==="invalid_token"||t.code==="invalid_dpop_proof")}async function yn({payload:t,authorization:r,proofJwt:n,method:o,url:i,replayStore:s,proofMaxAgeSeconds:a,signingAlgorithms:c}){let d=gn(t);if(!d){if(r.scheme==="DPoP")throw ln("invalid_token","DPoP authorization requires a DPoP-bound access token");return}if(r.scheme!=="DPoP")throw ln("invalid_token","DPoP-bound access token requires the DPoP authorization scheme");if(!n)throw ln("invalid_dpop_proof","DPoP proof header is required");try{await Ro({proofJwt:n,method:o,url:i,accessToken:r.token,expectedJkt:d,requireAth:!0,proofMaxAgeSeconds:a,signingAlgorithms:c,replayStore:s})}catch(u){if(So(u))throw ln("invalid_dpop_proof",u.message);throw u}}var Zw=new Set(["grant_type","refresh_token","__proto__","constructor","prototype"]);async function Yw({refreshToken:t,options:r,authentication:n,tokenEndpointAuth:o,tokenEndpoint:i,extraParams:s,resource:a}){r=typeof r==="function"?await r():r;let c=ey({refreshToken:t,options:r,extraParams:s,resource:a});return await bo({body:c.body,headers:c.headers,options:r,tokenEndpoint:i??"",grantType:"refresh_token",tokenEndpointAuth:o,authentication:n}),c}function Xw(t,r){if(!r)return;for(let[n,o]of Object.entries(r)){if(Zw.has(n))continue;t.set(n,o)}}function ey({refreshToken:t,options:r,extraParams:n,resource:o}){let i=new URLSearchParams,s={"content-type":"application/x-www-form-urlencoded",accept:"application/json"};if(i.set("grant_type","refresh_token"),i.set("refresh_token",t),o)if(typeof o==="string")i.append("resource",o);else for(let a of o)i.append("resource",a);if(n)Xw(i,n);return{body:i,headers:s}}async function F({refreshToken:t,options:r,tokenEndpoint:n,authentication:o,tokenEndpointAuth:i,extraParams:s,resource:a}){let{body:c,headers:d}=await Yw({refreshToken:t,options:r,authentication:o,tokenEndpointAuth:i,tokenEndpoint:n,extraParams:s,resource:a}),{data:u,error:f}=await Qt(n,{method:"POST",body:c,headers:d});if(f)throw f;let p={accessToken:u.access_token,refreshToken:u.refresh_token,tokenType:u.token_type,scopes:ms(u.scope),idToken:u.id_token};if(u.expires_in)p.accessTokenExpiresAt=new Date(new Date().getTime()+u.expires_in*1000);if(u.refresh_token_expires_in)p.refreshTokenExpiresAt=new Date(new Date().getTime()+u.refresh_token_expires_in*1000);return p}var ty=new Set([vl.code,_l.code,vc.code]);function ry(t){return ty.has(t.code)}var ny=new Map,oy=new WeakMap,iy=300000,sy=30000,ku=5000;function Au(t,r){let n=t.get(r);if(!n)n={fetchedAt:0,refetchedAt:0},t.set(r,n);return n}function Eu(t,r){return t.pending!==void 0&&r-t.pending.startedAt<ku}async function bu(t,r){let n=Date.now();if(!t.pending||!Eu(t,n)){let a={startedAt:n,promise:dy(r).then((c)=>{if(n>=t.fetchedAt)t.jwks=c,t.fetchedAt=n;return c}).finally(()=>{if(t.pending===a)t.pending=void 0})};t.pending=a}let{promise:o,startedAt:i}=t.pending,s;try{return await Promise.race([o,new Promise((a,c)=>{s=setTimeout(()=>c(new vl),i+ku-n)})])}finally{clearTimeout(s)}}async function ay(t,r,n){if(t.jwks!==r)return t.jwks;let o=Date.now();if(!Eu(t,o)){if(o-t.refetchedAt<sy)return;t.refetchedAt=o}return bu(t,n)}function cy(t,r){return!r.kid&&(t instanceof yl||t instanceof Qu)}async function dy(t){try{let r=typeof t==="string"?await Qt(t,{headers:{Accept:"application/json"}}).then(async(n)=>{if(n.error)throw Error(`Jwks failed: ${n.error.message??n.error.statusText}`);return n.data}):await t();if(!r)throw Error("No jwks found");return r}catch(r){if(r instanceof TypeError){try{Ee.error("JWKS fetch failed:",r)}catch{}throw Error("JWKS fetch failed")}throw r}}function Em(t){return{authorizationHeader:t.headers.get("authorization"),dpopProofJwt:t.headers.get("dpop"),method:t.method,url:t.url}}var uy=Ss();async function ly(t,r){if(t.split(".").length!==3)throw new zr("Invalid Compact JWS");let n=await Su(t,r),o=n.jwks;for(let i=0;;i++)try{return await Qr(t,Qo(o),r.verifyOptions)}catch(s){let a=i<2&&cy(s,n)?await n.refresh?.(o):void 0;if(!a)throw s;o=a}}async function vu(t,r){try{let n=await ly(t,r);if(n.payload.azp)n.payload.client_id=n.payload.azp;return n.payload}catch(n){if(n instanceof Error)throw n;throw Error(n)}}async function Ar(t,r){return(await Su(t,r)).jwks}async function Su(t,r){let n;try{n=so(t)}catch(c){if(c instanceof Error)throw c;throw Error(c)}let o=n.kid,i=typeof r.jwksFetch==="string"?Au(ny,r.jwksFetch):r.jwksCacheKey?Au(oy,r.jwksCacheKey):{fetchedAt:0,refetchedAt:0},s=Date.now()-i.fetchedAt<iy?i.jwks:void 0;if(!s)return{jwks:await bu(i,r.jwksFetch),kid:o};let a=(c)=>ay(i,c,r.jwksFetch);if(!o||s.keys.some((c)=>c.kid===o))return{jwks:s,kid:o,refresh:a};return{jwks:await a(s)??s,kid:o}}async function fy(t,r){let n;if(r.jwksUrl&&!r?.remoteVerify?.force)try{n=await vu(t,{jwksFetch:r.jwksUrl,verifyOptions:r.verifyOptions})}catch(i){if(i instanceof Error)if(i.name==="TypeError"||i.name==="JWSInvalid");else if(i instanceof yi)throw new ce("UNAUTHORIZED",{message:"token expired"});else if(i instanceof dn){if(ry(i))throw i;throw new ce("UNAUTHORIZED",{message:"invalid access token"})}else throw i;else throw Error(i)}if(r?.remoteVerify){let{data:i,error:s}=await Qt(r.remoteVerify.introspectUrl,{method:"POST",headers:{Accept:"application/json","Content-Type":"application/x-www-form-urlencoded"},body:new URLSearchParams({client_id:r.remoteVerify.clientId,client_secret:r.remoteVerify.clientSecret,token:t,token_type_hint:"access_token"}).toString()});if(s)Ee.error(`Introspection failed: ${s.message??s.statusText}`);if(!i)throw new ce("INTERNAL_SERVER_ERROR",{message:"introspection failed"});if(!i.active)throw new ce("UNAUTHORIZED",{message:"token inactive"});try{let a=new bc(i).encode(),{audience:c,...d}=r.verifyOptions,u=!i.aud&&r.remoteVerify.allowMissingAudience===!0;n=bc.decode(a,u?d:r.verifyOptions).payload}catch(a){throw Error(a)}}if(!n)throw new ce("UNAUTHORIZED",{message:"no token payload"});let o=gy(n.scope);if(r.requiredScopes){let i=r.isScopeSatisfied??((a,c)=>c.has(a)),s=r.requiredScopes.filter((a)=>!i(a,o));if(s.length>0)throw Iu(s)}return n}var py=/^[\x21\x23-\x5b\x5d-\x7e]+$/,hy=/^[\x20-\x21\x23-\x5b\x5d-\x7e]+$/,Ru=new WeakSet;function Is(t){return py.test(t)}function Tu(t,r){for(let n of t)if(!Is(n))throw TypeError(`invalid ${r}: ${JSON.stringify(n)}`)}function my(t){if(t.requiredScopes)Tu(t.requiredScopes,"required scope")}function gy(t){if(t===void 0)return new Set;if(typeof t!=="string"||t.length===0||t.split(" ").some((r)=>!Is(r)))throw new ce("UNAUTHORIZED",{message:"access token scope claim is invalid",error:"invalid_token",error_description:"access token scope claim is invalid"});return new Set(t.split(" "))}function Iu(t,r=`access token is missing required scope: ${t.join(" ")}`){if(t.length===0)throw TypeError("requiredScopes must contain at least one scope");if(Tu(t,"required scope"),typeof r!=="string"||!hy.test(r))throw TypeError("invalid error_description");let n=new ce("FORBIDDEN",{message:r,error:"insufficient_scope",error_description:r,scope:[...new Set(t)].join(" ")});return Ru.add(n),n}function Hu(t){if(!(t instanceof ce)||!Ru.has(t)||t.status!=="FORBIDDEN")return!1;let r=t.body;if(r?.error!=="insufficient_scope"||typeof r.scope!=="string")return!1;let n=r.scope.split(" ");return n.length>0&&n.every(Is)}function Rs(t,r){throw new ce("UNAUTHORIZED",r?{message:t,error:r,error_description:t}:{message:t})}async function xm(t,r){my(r);let n=_r(t.authorizationHeader);if(!n?.token)Rs("missing authorization header");if(n.scheme==="Unknown")Rs("authorization scheme must be Bearer or DPoP","invalid_token");let o=await fy(n.token,r);try{await yn({payload:o,authorization:n,proofJwt:t.dpopProofJwt,method:t.method,url:t.url,replayStore:r.dpop?.replayStore??uy,proofMaxAgeSeconds:r.dpop?.proofMaxAgeSeconds,signingAlgorithms:r.dpop?.signingAlgorithms})}catch(i){if(wn(i))Rs(i.message,i.code);throw i}return o}async function Us({code:t,codeVerifier:r,redirectURI:n,options:o,authentication:i,tokenEndpointAuth:s,tokenEndpoint:a,deviceId:c,headers:d,additionalParams:u={},resource:f}){o=typeof o==="function"?await o():o;let p=wy({code:t,codeVerifier:r,redirectURI:n,options:o,deviceId:c,headers:d,additionalParams:u,resource:f});return await bo({body:p.body,headers:p.headers,options:o,tokenEndpoint:a??"",grantType:"authorization_code",tokenEndpointAuth:s,authentication:i}),p}function wy({code:t,codeVerifier:r,redirectURI:n,options:o,deviceId:i,headers:s,additionalParams:a={},resource:c}){let d=new URLSearchParams,u={"content-type":"application/x-www-form-urlencoded",accept:"application/json",...s};if(d.set("grant_type","authorization_code"),d.set("code",t),r&&d.set("code_verifier",r),o.clientKey&&d.set("client_key",o.clientKey),i&&d.set("device_id",i),d.set("redirect_uri",o.redirectURI||n),c)if(typeof c==="string")d.append("resource",c);else for(let f of c)d.append("resource",f);for(let[f,p]of Object.entries(a))if(!d.has(f))d.append(f,p);return{body:d,headers:u}}async function K({code:t,codeVerifier:r,redirectURI:n,options:o,tokenEndpoint:i,authentication:s,tokenEndpointAuth:a,deviceId:c,headers:d,additionalParams:u={},resource:f}){let{body:p,headers:h}=await Us({code:t,codeVerifier:r,redirectURI:n,options:o,authentication:s,tokenEndpointAuth:a,tokenEndpoint:i,deviceId:c,headers:d,additionalParams:u,resource:f}),{data:m,error:w}=await Qt(i,{method:"POST",body:p,headers:h});if(w)throw w;return sn(m)}var yy=30,_y=["iss","sub","aud","exp","iat"];function Ay(t){return{issuer:t.issuer,audience:t.audience,algorithms:t.algorithms,maxTokenAge:t.maxTokenAge,requiredClaims:_y,clockTolerance:yy}}async function ky(t){let r=new TextEncoder().encode(t),n=await crypto.subtle.digest("SHA-256",r);return Array.from(new Uint8Array(n)).map((o)=>o.toString(16).padStart(2,"0")).join("")}async function Ey(t,r,n="exact"){if(typeof t!=="string")return!1;if(t===r)return!0;if(n==="exact-or-sha256")return t===await ky(r);return!1}async function by(t,r,n){if(![r.audience].flat().some(Boolean))throw Error("ID token audience is not configured");let o=await Qr(t,r.jwks,Ay(r));if(n&&!await Ey(o.payload.nonce,n,r.nonceComparison))throw Error("ID token nonce does not match");if(r.verifyClaims&&!r.verifyClaims(o.payload))throw Error("ID token claims were rejected");return o}function _n(t){let r=t.options??{};if(r.disableIdTokenSignIn)return!1;return Boolean(t.idToken||r.verifyIdToken)}async function An(t,r,n,o){let i=t.options??{};if(i.disableIdTokenSignIn)return!1;try{if(i.verifyIdToken)return await i.verifyIdToken(r,n,o);let s=t.idToken;if(!s)return!1;if("verify"in s)return await s.verify(r,n,o);if(r.split(".").length!==3)return s.allowOpaqueToken===!0;return await by(r,s,n),!0}catch{return!1}}function kn(t,r){return{linked:!1,error:{code:t,message:r}}}async function Ou(t,{link:r,userInfo:n,account:o,profile:i,scopes:s}){try{await lr(t,{user:{...n,id:r.userId,email:n.email??void 0},source:{action:"link-account",method:"oauth",oauth:{providerId:o.providerId,profile:i}}})}catch(c){if(!Ur(c)||!c.body?.code)throw c;return kn(c.body.code,c.body.message)}if(!t.context.trustedProviders.includes(o.providerId)&&!n.emailVerified||t.context.options.account?.accountLinking?.enabled===!1)return t.context.logger.error("Unable to link account - untrusted provider"),kn(he.UNABLE_TO_LINK_ACCOUNT);if(n.email?.toLowerCase()!==r.email.toLowerCase()&&t.context.options.account?.accountLinking?.allowDifferentEmails!==!0)return kn(he.EMAIL_DOES_NOT_MATCH);let a=await t.context.internalAdapter.findAccountByKey(o);if(a){if(a.userId.toString()!==r.userId.toString())return kn(he.ACCOUNT_ALREADY_LINKED_TO_DIFFERENT_USER);let c=gs(a.scope,s),d=Object.fromEntries(Object.entries({providerId:o.providerId,accessToken:await me(o.accessToken,t.context),refreshToken:await me(o.refreshToken,t.context),idToken:o.idToken,accessTokenExpiresAt:o.accessTokenExpiresAt,refreshTokenExpiresAt:o.refreshTokenExpiresAt,scope:c||void 0}).filter(([u,f])=>f!==void 0));await t.context.internalAdapter.updateAccount(a.id,d)}else if(!await t.context.internalAdapter.createAccount({userId:r.userId,...o,accessToken:await me(o.accessToken,t.context),refreshToken:await me(o.refreshToken,t.context),scope:s?.join(",")??o.scope}))return kn(he.UNABLE_TO_LINK_ACCOUNT);return await En(t,r.userId,n),{linked:!0}}async function Io(t,r){let{userInfo:n,account:o,callbackURL:i,disableSignUp:s,overrideUserInfo:a}=r,c=r.source??{method:"oauth",oauth:{providerId:o.providerId}},d=!!r.selectedUser||r.requireExactAccountBinding===!0,u=null,f=await t.context.internalAdapter.findAccountOwnerByKey({providerId:o.providerId,accountId:o.accountId}).catch((I)=>{t.context.logger.error(`Better auth was unable to query your database.
38
+ Error: `,I),Xr(t,t.context.options.onAPIError?.errorURL||`${t.context.baseURL}/error`,"internal_server_error")});if(f?.kind==="orphaned")return t.context.logger.error("OAuth account references a missing user. Repair the account before retrying authentication."),{error:"unable to link account",data:null,isRegister:!1};let p=await(async()=>{if(f?.kind==="owned"){if(r.selectedUser&&f.user.id!==r.selectedUser.userId)throw new U("CONFLICT",{code:"account_ownership_conflict",message:"Account is already linked to another user"});return{user:f.user,linkedAccount:f.account,accounts:[f.account]}}if(r.selectedUser){let R=await t.context.internalAdapter.findUserById(r.selectedUser.userId);if(!R)throw new U("NOT_FOUND",{code:"user_not_found",message:"User not found"});return{user:R,linkedAccount:null,accounts:[]}}let I=await t.context.internalAdapter.findUserByEmail(n.email.toLowerCase(),{includeAccounts:!0});if(!I)return null;return{user:I.user,linkedAccount:null,accounts:I.accounts}})().catch((I)=>{if(Ur(I))throw I;t.context.logger.error(`Better auth was unable to query your database.
39
+ Error: `,I),Xr(t,t.context.options.onAPIError?.errorURL||`${t.context.baseURL}/error`,"internal_server_error")}),h=p?.user,m=!h;if(p){let I=p.linkedAccount??p.accounts.find((R)=>R.providerId===o.providerId&&R.accountId===o.accountId);if(!I){let R=t.context.options.account?.accountLinking,b=r.isTrustedProvider||r.trustProviderByName!==!1&&t.context.trustedProviders.includes(o.providerId),O=R?.requireLocalEmailVerified??!0;if(!r.selectedUser&&(!b&&!n.emailVerified||O&&!p.user.emailVerified||R?.enabled===!1||R?.disableImplicitLinking===!0)){if(xl())t.context.logger.warn(`User already exist but account isn't linked to ${o.providerId}. To read more about how account linking works in Better Auth see https://www.better-auth.com/docs/concepts/users-accounts#account-linking.`);return{error:"account not linked",data:null}}try{let{id:g,...S}=n;await lr(t,{user:{...S,id:p.user.id,email:n.email.toLowerCase()},source:{...c,action:"link-account"}});let C=await t.context.internalAdapter.linkAccount({providerId:o.providerId,accountId:o.accountId,userId:p.user.id,accessToken:await me(o.accessToken,t.context),refreshToken:await me(o.refreshToken,t.context),idToken:o.idToken,accessTokenExpiresAt:o.accessTokenExpiresAt,refreshTokenExpiresAt:o.refreshTokenExpiresAt,scope:o.scope});if(!C)return{error:"unable to link account",data:null};if(d&&(C.accountId!==o.accountId||C.providerId!==o.providerId||C.userId!==p.user.id))throw new U("CONFLICT",{code:"account_hook_binding_conflict",message:"Account hook changed the selected authentication binding"});if(t.context.options.account?.storeAccountCookie)if(r.deferNonDatabaseWrites)u=C;else await ft(t,C)}catch(g){if(Ur(g))throw g;return t.context.logger.error("Unable to link account",g),{error:"unable to link account",data:null}}if(!r.selectedUser&&n.emailVerified&&!p.user.emailVerified&&n.email.toLowerCase()===p.user.email)await t.context.internalAdapter.updateUser(p.user.id,{emailVerified:!0});if(!r.selectedUser)h=await En(t,p.user.id,n)??h}else{let{id:R,...b}=n;await lr(t,{user:{...b,id:p.user.id,email:n.email.toLowerCase()},source:{...c,action:"sign-in"}});let O=t.context.options.account?.updateAccountOnSignIn!==!1?Object.fromEntries(Object.entries({providerId:o.providerId,idToken:o.idToken,accessToken:await me(o.accessToken,t.context),refreshToken:await me(o.refreshToken,t.context),accessTokenExpiresAt:o.accessTokenExpiresAt,refreshTokenExpiresAt:o.refreshTokenExpiresAt}).filter(([g,S])=>S!==void 0)):{};if(t.context.options.account?.storeAccountCookie){let g={...I,...O};if(r.deferNonDatabaseWrites)u=g;else await ft(t,g)}if(Object.keys(O).length>0){let g=await t.context.internalAdapter.updateAccount(I.id,O);if(!g)return{error:"unable to update account",data:null};if(d&&(g.accountId!==o.accountId||g.providerId!==o.providerId||g.userId!==p.user.id))throw new U("CONFLICT",{code:"account_hook_binding_conflict",message:"Account hook changed the selected authentication binding"});if(r.deferNonDatabaseWrites&&u)u=g}if(!r.selectedUser&&n.emailVerified&&!p.user.emailVerified&&n.email.toLowerCase()===p.user.email)await t.context.internalAdapter.updateUser(p.user.id,{emailVerified:!0})}if(r.selectedUser?r.selectedUser.profile==="update":a){let{id:R,email:b,emailVerified:O,name:g,image:S,...C}=n,z=ur(t.context.options,C,"update"),L=await t.context.internalAdapter.updateUser(p.user.id,{name:g,image:S,...z,email:n.email.toLowerCase(),emailVerified:n.email.toLowerCase()===p.user.email?p.user.emailVerified||n.emailVerified:n.emailVerified});if(L==null)t.context.logger.warn("Could not update user info during OAuth sign in; preserving existing user for session.");if(r.selectedUser&&L&&L.id!==r.selectedUser.userId)throw new U("CONFLICT",{code:"user_hook_selection_conflict",message:"User hook changed the selected user"});h=L??h}}else{if(s)return{error:"signup disabled",data:null,isRegister:!1};try{let{id:I,email:R,emailVerified:b,name:O,image:g,...S}=n,C=ur(t.context.options,S,"create"),z={accessToken:await me(o.accessToken,t.context),refreshToken:await me(o.refreshToken,t.context),idToken:o.idToken,accessTokenExpiresAt:o.accessTokenExpiresAt,refreshTokenExpiresAt:o.refreshTokenExpiresAt,scope:o.scope,providerId:o.providerId,accountId:o.accountId},{createdUser:L,createdAccount:x}=await Ue(t.context.adapter,async()=>{let P=await t.context.internalAdapter.createUser({name:O,image:g,...C,email:n.email.toLowerCase(),emailVerified:n.emailVerified},c);return{createdUser:P,createdAccount:await t.context.internalAdapter.createAccount({...z,userId:P.id})}});if(d&&(x.accountId!==o.accountId||x.providerId!==o.providerId||x.userId!==L.id))throw new U("CONFLICT",{code:"account_hook_binding_conflict",message:"Account hook changed the selected authentication binding"});if(h=L,t.context.options.account?.storeAccountCookie)if(r.deferNonDatabaseWrites)u=x;else await ft(t,x)}catch(I){if(Ur(I))throw I;return t.context.logger.error("Unable to create OAuth user",I),{error:"unable to create user",data:null,isRegister:!1}}}if(!h)return{error:"unable to create user",data:null,isRegister:!1};let w=t.context.socialProviders.find((I)=>I.id===o.providerId)?.options?.requireEmailVerification;if(m&&!h.emailVerified&&(t.context.options.emailVerification?.sendOnSignUp??w))await Cu(t,h,i,r.deferNonDatabaseWrites);if(w&&!h.emailVerified){if(!m&&t.context.options.emailVerification?.sendOnSignIn)await Cu(t,h,i,r.deferNonDatabaseWrites);return{error:he.EMAIL_NOT_VERIFIED,data:null,isRegister:m}}let y=await t.context.internalAdapter.createSession(h.id,void 0,void 0,void 0,{deferSecondaryStorageWrites:r.deferNonDatabaseWrites===!0});if(!y)return{error:"unable to create session",data:null,isRegister:!1};if(d&&y.userId!==(r.selectedUser?.userId??h.id))throw new U("CONFLICT",{code:"session_hook_user_conflict",message:"Session hook changed the selected user"});return{data:{session:y,user:h},error:null,isRegister:m,accountCookie:u}}async function Cu(t,r,n,o){let i=t.context.options.emailVerification?.sendVerificationEmail;if(!i)return;let s=async()=>{try{let a=await Se(t.context.secret,r.email,void 0,t.context.options.emailVerification?.expiresIn),c=`${t.context.baseURL}/verify-email?token=${a}&callbackURL=${encodeURIComponent(n||"/")}`;await t.context.runInBackgroundOrAwait(i({user:r,url:c,token:a},t.request))}catch(a){t.context.logger.error("Failed to send OAuth verification email",a)}};if(o)await Te(s);else await s()}async function En(t,r,n){if(t.context.options.account?.accountLinking?.updateUserInfoOnLink!==!0)return;try{let{email:o,emailVerified:i,name:s,image:a,...c}=n,d=ur(t.context.options,c,"update");return await t.context.internalAdapter.updateUser(r,{name:s,image:a,...d})}catch(o){t.context.logger.warn("Could not update user info on account link",o);return}}var vy=If("better-auth:oauth-encryption:v1");function Os(t,r){return oA(jn(Bn,If(t),vy,If(`better-auth:${r}:v1`),32))}function Ds(t,r){if(typeof t==="string")return Os(t,r);return{keys:new Map(Array.from(t.keys,([n,o])=>[n,Os(o,r)])),currentVersion:t.currentVersion,...t.legacySecret&&{legacySecret:Os(t.legacySecret,r)}}}var Ls=oe({callbackURL:e(),codeVerifier:e(),errorURL:e().optional(),newUserURL:e().optional(),expiresAt:_(),oauthState:e().optional(),link:l({email:e(),userId:yf()}).optional(),requestSignUp:E().optional(),idTokenNonce:e().optional(),serverContext:k(e(),J()).optional()}),Ps=(t)=>`auth-state:${t}`,OI=new Set(Object.keys(Ls.shape)),Ge=class extends te{code;details;errorURL;constructor(t,r){super(t,r);this.code=r.code,this.details=r.details,this.errorURL=r.errorURL}};async function Du(t,r,n){let o=_e(32);if(t.context.oauthConfig.storeStateStrategy==="cookie"){let a={...r,oauthState:o},c=await nt({key:Ds(t.context.secretConfig,"oauth-state-cookie"),data:JSON.stringify(a)}),d=t.context.createAuthCookie(n?.cookieName??"oauth_state",{maxAge:600});return t.setCookie(d.name,c,d.attributes),{state:o,codeVerifier:r.codeVerifier}}let i=t.context.createAuthCookie(n?.cookieName??"state",{maxAge:300});await t.setSignedCookie(i.name,o,t.context.secret,i.attributes);let s=new Date;if(s.setMinutes(s.getMinutes()+10),!await t.context.internalAdapter.createVerificationValue({value:JSON.stringify({...r,oauthState:o}),identifier:Ps(o),expiresAt:s}))throw new Ge("Unable to create verification. Make sure the database adapter is properly working and there is a verification table in the database",{code:"state_generation_error"});return{state:o,codeVerifier:r.codeVerifier}}async function Lu(t,r,n){if(!r)throw new Ge("State not found in OAuth callback",{code:"state_not_found"});let o=t.context.oauthConfig.storeStateStrategy,i;if(o==="cookie"){let s=t.context.createAuthCookie(n?.cookieName??"oauth_state"),a=t.getCookie(s.name);if(!a)throw new Ge("State mismatch: auth state cookie not found",{code:"state_mismatch",details:{state:r}});try{let c=await ot({key:Ds(t.context.secretConfig,"oauth-state-cookie"),data:a});i=Ls.parse(JSON.parse(c))}catch(c){throw new Ge("State invalid: Failed to decrypt or parse auth state",{code:"state_invalid",details:{state:r},cause:c})}if(!i.oauthState||i.oauthState!==r)throw new Ge("State mismatch: OAuth state parameter does not match stored state",{code:"state_security_mismatch",details:{state:r},errorURL:i.errorURL});Be(t,s)}else{let s=await t.context.internalAdapter.findVerificationValue(Ps(r));if(!s)throw new Ge("State mismatch: verification not found",{code:"state_mismatch",details:{state:r}});if(i=Ls.parse(JSON.parse(s.value)),i.oauthState!==void 0&&i.oauthState!==r)throw new Ge("State mismatch: OAuth state parameter does not match stored state",{code:"state_security_mismatch",details:{state:r},errorURL:i.errorURL});let a=t.context.createAuthCookie(n?.cookieName??"state"),c=await t.getSignedCookie(a.name,t.context.secret);if(!(n?.skipStateCookieCheck??t.context.oauthConfig.skipStateCookieCheck)&&(!c||c!==r))throw new Ge("State mismatch: State not persisted correctly",{code:"state_security_mismatch",details:{state:r},errorURL:i.errorURL});Be(t,a),await t.context.internalAdapter.deleteVerificationByIdentifier(Ps(r))}if(i.expiresAt<Date.now())throw new Ge("Invalid state: request expired",{code:"state_mismatch",details:{expiresAt:i.expiresAt},errorURL:i.errorURL});return i}function kr(t){return t.requiresIdTokenNonce?_e(32):void 0}async function Er(t,r){let n=t.body?.callbackURL||t.context.options.baseURL;if(!n)throw U.from("BAD_REQUEST",Ae.CALLBACK_URL_REQUIRED);let o=r?.codeVerifier??_e(128),i=await Yi(),s=i&&Object.keys(i).length?i:void 0,a={...r?.additionalData?r.additionalData:{},callbackURL:n,codeVerifier:o,errorURL:t.body?.errorCallbackURL,newUserURL:t.body?.newUserCallbackURL,link:r?.link,serverContext:s,expiresAt:Date.now()+600000,requestSignUp:t.body?.requestSignUp,idTokenNonce:r?.idTokenNonce};await Gi(a);try{return Du(t,a)}catch(c){throw t.context.logger.error("Failed to create verification",c),new U("INTERNAL_SERVER_ERROR",{message:"Unable to create verification",cause:c})}}async function Pu(t){let r=t.query.state||t.body?.state,n=t.context.options.onAPIError?.errorURL||`${t.context.baseURL}/error`,o;try{o=await Lu(t,r)}catch(i){t.context.logger.error("Failed to parse state",i);let s="internal_server_error",a=n;if(i instanceof Ge)s=i.code==="state_security_mismatch"?"state_mismatch":i.code,a=i.errorURL||n;Xr(t,a,s)}if(!o.errorURL)o.errorURL=n;if(o)await Gi(o);return o}var xu=(t)=>({id:"apple",name:"Apple",accountSubject:({profile:n})=>n.sub,async createAuthorizationURL({state:n,scopes:o,redirectURI:i,additionalParams:s,codeVerifier:a}){if(!Re(t.clientId)||!t.clientSecret)throw Ee.error("Client ID and client secret are required for Apple. Make sure to provide them in the options."),new te("CLIENT_ID_AND_SECRET_REQUIRED");let c=t.disableDefaultScope?[]:["email","name"];if(t.scope)c.push(...t.scope);if(o)c.push(...o);return await V({id:"apple",options:t,authorizationEndpoint:"https://appleid.apple.com/auth/authorize",scopes:c,state:n,redirectURI:i,codeVerifier:a,responseMode:"form_post",responseType:"code id_token",additionalParams:s})},validateAuthorizationCode:async({code:n,codeVerifier:o,redirectURI:i})=>K({code:n,codeVerifier:o,redirectURI:i,options:t,tokenEndpoint:"https://appleid.apple.com/auth/token"}),idToken:{jwks:(n)=>Nu(n.kid),issuer:"https://appleid.apple.com",algorithms:["RS256"],audience:t.audience&&t.audience.length?t.audience:t.appBundleIdentifier?t.appBundleIdentifier:t.clientId,maxTokenAge:"1h",nonceComparison:"exact-or-sha256"},refreshAccessToken:t.refreshAccessToken?t.refreshAccessToken:async(n)=>F({refreshToken:n,options:t,tokenEndpoint:"https://appleid.apple.com/auth/token"}),async getUserInfo(n){if(t.getUserInfo)return t.getUserInfo(n);if(!n.idToken)return null;let o=en(n.idToken);if(!o)return null;let i;if(n.user?.name)i=`${n.user.name.firstName||""} ${n.user.name.lastName||""}`.trim();else i=o.name||"";let s=typeof o.email_verified==="boolean"?o.email_verified:o.email_verified==="true",a={...o,name:i},c=await t.mapProfileToUser?.(a);return{user:{name:a.name,emailVerified:s,email:o.email,...c},data:a}},options:t}),Nu=async(t)=>{let{data:r}=await Me("https://appleid.apple.com/auth/keys");if(!r?.keys)throw new U("BAD_REQUEST",{message:"Keys not found"});let n=r.keys.find((o)=>o.kid===t);if(!n)throw Error(`JWK with kid ${t} not found`);return await In(n,n.alg)};var Bu=(t)=>({id:"atlassian",name:"Atlassian",accountSubject:({profile:n})=>n.account_id,async createAuthorizationURL({state:n,scopes:o,codeVerifier:i,redirectURI:s,additionalParams:a}){if(!t.clientId||!t.clientSecret)throw Ee.error("Client Id and Secret are required for Atlassian"),new te("CLIENT_ID_AND_SECRET_REQUIRED");if(!i)throw new te("codeVerifier is required for Atlassian");let c=t.disableDefaultScope?[]:["read:jira-user","offline_access"];if(t.scope)c.push(...t.scope);if(o)c.push(...o);return V({id:"atlassian",options:t,authorizationEndpoint:"https://auth.atlassian.com/authorize",scopes:c,state:n,codeVerifier:i,redirectURI:s,additionalParams:{...a??{},audience:"api.atlassian.com"},prompt:t.prompt})},validateAuthorizationCode:async({code:n,codeVerifier:o,redirectURI:i})=>K({code:n,codeVerifier:o,redirectURI:i,options:t,tokenEndpoint:"https://auth.atlassian.com/oauth/token"}),refreshAccessToken:t.refreshAccessToken?t.refreshAccessToken:async(n)=>F({refreshToken:n,options:{clientId:t.clientId,clientSecret:t.clientSecret},tokenEndpoint:"https://auth.atlassian.com/oauth/token"}),async getUserInfo(n){if(t.getUserInfo)return t.getUserInfo(n);if(!n.accessToken)return null;try{let{data:o}=await Me("https://api.atlassian.com/me",{headers:{Authorization:`Bearer ${n.accessToken}`}});if(!o)return null;let i=await t.mapProfileToUser?.(o);return{user:{name:o.name,email:o.email,image:o.picture,emailVerified:!1,...i},data:o}}catch(o){return Ee.error("Failed to fetch user info from Atlassian:",o),null}},options:t});var Sy="https://dash.cloudflare.com/oauth2/auth",Mu="https://dash.cloudflare.com/oauth2/token",Ry="https://api.cloudflare.com/client/v4/user",Fu=(t)=>{let r=t.clientSecret?"client_secret_basic":"none";return{method:t.tokenEndpointAuthMethod??r}},Ju=(t)=>({id:"cloudflare",name:"Cloudflare",accountSubject:({profile:r})=>r.id,createAuthorizationURL({state:r,scopes:n,codeVerifier:o,redirectURI:i}){let s=t.disableDefaultScope?[]:["user-details.read"];if(t.scope?.length)s.push(...t.scope);if(n?.length)s.push(...n);return V({id:"cloudflare",options:t,authorizationEndpoint:Sy,scopes:s.length?[...new Set(s)]:void 0,state:r,codeVerifier:o,redirectURI:i})},validateAuthorizationCode:async({code:r,codeVerifier:n,redirectURI:o})=>K({code:r,codeVerifier:n,redirectURI:o,options:t,tokenEndpoint:Mu,tokenEndpointAuth:Fu(t)}),refreshAccessToken:t.refreshAccessToken?t.refreshAccessToken:async(r)=>F({refreshToken:r,options:{clientId:t.clientId,clientKey:t.clientKey,clientSecret:t.clientSecret},tokenEndpoint:Mu,tokenEndpointAuth:Fu(t)}),async getUserInfo(r){if(t.getUserInfo)return t.getUserInfo(r);let{data:n,error:o}=await Me(Ry,{headers:{authorization:`Bearer ${r.accessToken}`}});if(o||!n?.success||!n.result)return Ee.error("Failed to fetch user info from Cloudflare:",o??n?.errors),null;let i=n.result,s=[i.first_name,i.last_name].filter(Boolean).join(" ")||i.email,a=await t.mapProfileToUser?.(i);return{user:{name:s,email:i.email,emailVerified:!1,...a},data:i}},options:t});var Zu=(t)=>{if(!t.domain||!t.region||!t.userPoolId)throw Ee.error("Domain, region and userPoolId are required for Amazon Cognito. Make sure to provide them in the options."),new te("DOMAIN_AND_REGION_REQUIRED");let r=t.domain.replace(/^https?:\/\//,""),n=`https://${r}/oauth2/authorize`,o=`https://${r}/oauth2/token`,i=`https://${r}/oauth2/userinfo`;return{id:"cognito",name:"Cognito",accountSubject:({profile:s})=>s.sub,async createAuthorizationURL({state:s,scopes:a,codeVerifier:c,redirectURI:d,additionalParams:u}){if(!Re(t.clientId))throw Ee.error("ClientId is required for Amazon Cognito. Make sure to provide them in the options."),new te("CLIENT_ID_AND_SECRET_REQUIRED");if(t.requireClientSecret&&!t.clientSecret)throw Ee.error("Client Secret is required when requireClientSecret is true. Make sure to provide it in the options."),new te("CLIENT_SECRET_REQUIRED");let f=t.disableDefaultScope?[]:["openid","profile","email"];if(t.scope)f.push(...t.scope);if(a)f.push(...a);let p=await V({id:"cognito",options:{...t},authorizationEndpoint:n,scopes:f,state:s,codeVerifier:c,redirectURI:d,prompt:t.prompt,additionalParams:{...t.identityProvider?{identity_provider:t.identityProvider}:{},...u??{}}}),h=p.searchParams.get("scope");if(h){p.searchParams.delete("scope");let m=encodeURIComponent(h),w=p.toString(),y=w.includes("?")?"&":"?";return new URL(`${w}${y}scope=${m}`)}return p},validateAuthorizationCode:async({code:s,codeVerifier:a,redirectURI:c})=>K({code:s,codeVerifier:a,redirectURI:c,options:t,tokenEndpoint:o}),refreshAccessToken:t.refreshAccessToken?t.refreshAccessToken:async(s)=>F({refreshToken:s,options:{clientId:t.clientId,clientKey:t.clientKey,clientSecret:t.clientSecret},tokenEndpoint:o}),idToken:{jwks:(s)=>Yu(s.kid,t.region,t.userPoolId),issuer:`https://cognito-idp.${t.region}.amazonaws.com/${t.userPoolId}`,audience:t.clientId,algorithms:["RS256"],maxTokenAge:"1h"},async getUserInfo(s){if(t.getUserInfo)return t.getUserInfo(s);if(s.idToken)try{let a=en(s.idToken);if(!a)return null;let c=a.name||a.given_name||a.username||"",d={...a,name:c},u=await t.mapProfileToUser?.(d);return{user:{name:d.name,email:a.email,image:a.picture,emailVerified:a.email_verified,...u},data:d}}catch(a){Ee.error("Failed to decode ID token:",a)}if(s.accessToken)try{let{data:a}=await Me(i,{headers:{Authorization:`Bearer ${s.accessToken}`}});if(a){let c=await t.mapProfileToUser?.(a);return{user:{name:a.name||a.given_name||a.username||"",email:a.email,image:a.picture,emailVerified:a.email_verified,...c},data:a}}}catch(a){Ee.error("Failed to fetch user info from Cognito:",a)}return null},options:t}},Yu=async(t,r,n)=>{let o=`https://cognito-idp.${r}.amazonaws.com/${n}/.well-known/jwks.json`;try{let{data:i}=await Me(o);if(!i?.keys)throw new U("BAD_REQUEST",{message:"Keys not found"});let s=i.keys.find((a)=>a.kid===t);if(!s)throw Error(`JWK with kid ${t} not found`);return await In(s,s.alg)}catch(i){throw Ee.error("Failed to fetch Cognito public key:",i),i}};var Xu=(t)=>({id:"discord",name:"Discord",accountSubject:({profile:n})=>n.id,createAuthorizationURL({state:n,scopes:o,redirectURI:i,additionalParams:s}){let a=t.disableDefaultScope?[]:["identify","email"];if(o)a.push(...o);if(t.scope)a.push(...t.scope);let c=a.includes("bot");return V({id:"discord",options:t,authorizationEndpoint:"https://discord.com/api/oauth2/authorize",scopes:a,state:n,redirectURI:i,prompt:t.prompt||"none",additionalParams:{...c&&t.permissions!==void 0?{permissions:String(t.permissions)}:{},...s??{}}})},validateAuthorizationCode:async({code:n,redirectURI:o})=>K({code:n,redirectURI:o,options:t,tokenEndpoint:"https://discord.com/api/oauth2/token"}),refreshAccessToken:t.refreshAccessToken?t.refreshAccessToken:async(n)=>F({refreshToken:n,options:{clientId:t.clientId,clientKey:t.clientKey,clientSecret:t.clientSecret},tokenEndpoint:"https://discord.com/api/oauth2/token"}),async getUserInfo(n){if(t.getUserInfo)return t.getUserInfo(n);let{data:o,error:i}=await Me("https://discord.com/api/users/@me",{headers:{authorization:`Bearer ${n.accessToken}`}});if(i)return null;if(o.avatar===null)o.image_url=`https://cdn.discordapp.com/embed/avatars/${o.discriminator==="0"?Number(BigInt(o.id)>>BigInt(22))%6:parseInt(o.discriminator)%5}.png`;else{let a=o.avatar.startsWith("a_")?"gif":"png";o.image_url=`https://cdn.discordapp.com/avatars/${o.id}/${o.avatar}.${a}`}let s=await t.mapProfileToUser?.(o);return{user:{name:o.global_name||o.username||"",email:o.email,emailVerified:o.verified,image:o.image_url,...s},data:o}},options:t});var el=(t)=>({id:"dropbox",name:"Dropbox",accountSubject:({profile:n})=>n.account_id,createAuthorizationURL:async({state:n,scopes:o,codeVerifier:i,redirectURI:s,additionalParams:a})=>{let c=t.disableDefaultScope?[]:["account_info.read"];if(t.scope)c.push(...t.scope);if(o)c.push(...o);return await V({id:"dropbox",options:t,authorizationEndpoint:"https://www.dropbox.com/oauth2/authorize",scopes:c,state:n,redirectURI:s,codeVerifier:i,additionalParams:{...t.accessType?{token_access_type:t.accessType}:{},...a??{}}})},validateAuthorizationCode:async({code:n,codeVerifier:o,redirectURI:i})=>await K({code:n,codeVerifier:o,redirectURI:i,options:t,tokenEndpoint:"https://api.dropboxapi.com/oauth2/token"}),refreshAccessToken:t.refreshAccessToken?t.refreshAccessToken:async(n)=>F({refreshToken:n,options:{clientId:t.clientId,clientKey:t.clientKey,clientSecret:t.clientSecret},tokenEndpoint:"https://api.dropboxapi.com/oauth2/token"}),async getUserInfo(n){if(t.getUserInfo)return t.getUserInfo(n);let{data:o,error:i}=await Me("https://api.dropboxapi.com/2/users/get_current_account",{method:"POST",headers:{Authorization:`Bearer ${n.accessToken}`}});if(i)return null;let s=await t.mapProfileToUser?.(o);return{user:{name:o.name?.display_name,email:o.email,emailVerified:o.email_verified||!1,image:o.profile_photo_url,...s},data:o}},options:t});async function tl(t,r){let n=Re(r.clientId);if(!n||!r.clientSecret)return null;let o=Array.isArray(r.clientId)?r.clientId:[r.clientId],{data:i,error:s}=await Me("https://graph.facebook.com/debug_token",{query:{input_token:t,access_token:`${n}|${r.clientSecret}`}});if(s||!i?.data)return null;let{is_valid:a,app_id:c,user_id:d}=i.data;if(a!==!0||!c||!o.includes(c)||!d)return null;return d}var rl=(t)=>({id:"facebook",name:"Facebook",accountSubject:({profile:r})=>("sub"in r)?r.sub:r.id,async createAuthorizationURL({state:r,scopes:n,redirectURI:o,loginHint:i,additionalParams:s}){if(!Re(t.clientId)||!t.clientSecret)throw Ee.error("Client ID and client secret are required for Facebook. Make sure to provide them in the options."),new te("CLIENT_ID_AND_SECRET_REQUIRED");let a=t.disableDefaultScope?[]:["email","public_profile"];if(t.scope)a.push(...t.scope);if(n)a.push(...n);return await V({id:"facebook",options:t,authorizationEndpoint:"https://www.facebook.com/v24.0/dialog/oauth",scopes:a,state:r,redirectURI:o,loginHint:i,additionalParams:{...t.configId?{config_id:t.configId}:{},...s??{}}})},validateAuthorizationCode:async({code:r,redirectURI:n})=>K({code:r,redirectURI:n,options:t,tokenEndpoint:"https://graph.facebook.com/v24.0/oauth/access_token"}),idToken:{jwks:Af(new URL("https://limited.facebook.com/.well-known/oauth/openid/jwks/")),issuer:"https://www.facebook.com",audience:t.clientId,algorithms:["RS256"],allowOpaqueToken:!0},refreshAccessToken:t.refreshAccessToken?t.refreshAccessToken:async(r)=>F({refreshToken:r,options:{clientId:t.clientId,clientKey:t.clientKey,clientSecret:t.clientSecret},tokenEndpoint:"https://graph.facebook.com/v24.0/oauth/access_token"}),async getUserInfo(r){if(t.getUserInfo){let c=!!r.idToken&&r.idToken.split(".").length!==3,d=r.accessToken||(c?r.idToken:void 0);if(d&&!await tl(d,t))return null;return t.getUserInfo(r)}if(r.idToken&&r.idToken.split(".").length===3){let c=en(r.idToken),d=await t.mapProfileToUser?.(c);return{user:{name:c.name,email:c.email,image:c.picture,emailVerified:!1,...d},data:c}}let n=r.accessToken;if(!n)return null;let o=await tl(n,t);if(!o)return null;let{data:i,error:s}=await Me("https://graph.facebook.com/me?fields="+["id","name","email","picture",...t?.fields||[]].join(","),{auth:{type:"Bearer",token:n}});if(s)return null;if(i.id!==o)return null;let a=await t.mapProfileToUser?.(i);return{user:{name:i.name,email:i.email,image:i.picture.data.url,emailVerified:i.email_verified??!1,...a},data:i}},options:t});var nl=(t)=>({id:"figma",name:"Figma",accountSubject:({profile:n})=>n.id,async createAuthorizationURL({state:n,scopes:o,codeVerifier:i,redirectURI:s,additionalParams:a}){if(!t.clientId||!t.clientSecret)throw Ee.error("Client Id and Client Secret are required for Figma. Make sure to provide them in the options."),new te("CLIENT_ID_AND_SECRET_REQUIRED");if(!i)throw new te("codeVerifier is required for Figma");let c=t.disableDefaultScope?[]:["current_user:read"];if(t.scope)c.push(...t.scope);if(o)c.push(...o);return await V({id:"figma",options:t,authorizationEndpoint:"https://www.figma.com/oauth",scopes:c,state:n,codeVerifier:i,redirectURI:s,additionalParams:a})},validateAuthorizationCode:async({code:n,codeVerifier:o,redirectURI:i})=>K({code:n,codeVerifier:o,redirectURI:i,options:t,tokenEndpoint:"https://api.figma.com/v1/oauth/token",authentication:"basic"}),refreshAccessToken:t.refreshAccessToken?t.refreshAccessToken:async(n)=>F({refreshToken:n,options:{clientId:t.clientId,clientKey:t.clientKey,clientSecret:t.clientSecret},tokenEndpoint:"https://api.figma.com/v1/oauth/token",authentication:"basic"}),async getUserInfo(n){if(t.getUserInfo)return t.getUserInfo(n);try{let{data:o}=await Me("https://api.figma.com/v1/me",{headers:{Authorization:`Bearer ${n.accessToken}`}});if(!o)return Ee.error("Failed to fetch user from Figma"),null;let i=await t.mapProfileToUser?.(o);return{user:{name:o.handle,email:o.email,image:o.img_url,emailVerified:!1,...i},data:o}}catch(o){return Ee.error("Failed to fetch user info from Figma:",o),null}},options:t});var ol=(t)=>({id:"github",name:"GitHub",accountSubject:({profile:n})=>n.id,createAuthorizationURL({state:n,scopes:o,loginHint:i,codeVerifier:s,redirectURI:a,additionalParams:c}){let d=t.disableDefaultScope?[]:["read:user","user:email"];if(t.scope)d.push(...t.scope);if(o)d.push(...o);return V({id:"github",options:t,authorizationEndpoint:"https://github.com/login/oauth/authorize",scopes:d,state:n,codeVerifier:s,redirectURI:a,loginHint:i,prompt:t.prompt,additionalParams:c})},validateAuthorizationCode:async({code:n,codeVerifier:o,redirectURI:i})=>{let{body:s,headers:a}=await Us({code:n,codeVerifier:o,redirectURI:i,options:t}),{data:c,error:d}=await Me("https://github.com/login/oauth/access_token",{method:"POST",body:s,headers:a});if(d)return Ee.error("GitHub OAuth token exchange failed:",d),null;if("error"in c)return Ee.error("GitHub OAuth token exchange failed:",c),null;return sn(c)},refreshAccessToken:t.refreshAccessToken?t.refreshAccessToken:async(n)=>F({refreshToken:n,options:{clientId:t.clientId,clientKey:t.clientKey,clientSecret:t.clientSecret},tokenEndpoint:"https://github.com/login/oauth/access_token"}),async getUserInfo(n){if(t.getUserInfo)return t.getUserInfo(n);let{data:o,error:i}=await Me("https://api.github.com/user",{headers:{"User-Agent":"better-auth",authorization:`Bearer ${n.accessToken}`}});if(i)return null;let{data:s}=await Me("https://api.github.com/user/emails",{headers:{Authorization:`Bearer ${n.accessToken}`,"User-Agent":"better-auth"}});if(!o.email&&s)o.email=(s.find((d)=>d.primary)??s[0])?.email;let a=s?.find((d)=>d.email===o.email)?.verified??!1,c=await t.mapProfileToUser?.(o);return{user:{name:o.name||o.login||"",email:o.email,image:o.avatar_url,emailVerified:a,...c},data:o}},options:t});var xs=(t="")=>t.split("://").map((r)=>r.replace(/\/{2,}/g,"/")).join("://"),Ty=(t)=>{let r=t||"https://gitlab.com";return{authorizationEndpoint:xs(`${r}/oauth/authorize`),tokenEndpoint:xs(`${r}/oauth/token`),userinfoEndpoint:xs(`${r}/api/v4/user`)}},il=(t)=>{let{authorizationEndpoint:r,tokenEndpoint:n,userinfoEndpoint:o}=Ty(t.issuer),i="gitlab";return{id:"gitlab",name:"Gitlab",accountSubject:({profile:s})=>s.id,createAuthorizationURL:async({state:s,scopes:a,codeVerifier:c,loginHint:d,redirectURI:u,additionalParams:f})=>{let p=t.disableDefaultScope?[]:["read_user"];if(t.scope)p.push(...t.scope);if(a)p.push(...a);return await V({id:"gitlab",options:t,authorizationEndpoint:r,scopes:p,state:s,redirectURI:u,codeVerifier:c,loginHint:d,additionalParams:f})},validateAuthorizationCode:async({code:s,redirectURI:a,codeVerifier:c})=>K({code:s,redirectURI:a,options:t,codeVerifier:c,tokenEndpoint:n}),refreshAccessToken:t.refreshAccessToken?t.refreshAccessToken:async(s)=>F({refreshToken:s,options:{clientId:t.clientId,clientKey:t.clientKey,clientSecret:t.clientSecret},tokenEndpoint:n}),async getUserInfo(s){if(t.getUserInfo)return t.getUserInfo(s);let{data:a,error:c}=await Me(o,{headers:{authorization:`Bearer ${s.accessToken}`}});if(c||a.state!=="active"||a.locked)return null;let d=await t.mapProfileToUser?.(a);return{user:{name:a.name??a.username??"",email:a.email,image:a.avatar_url,emailVerified:a.email_verified??!1,...d},data:a}},options:t}};var Iy="1h",sl="RS256",Uy=[sl];var zs=(t,r)=>{if(!t)return!0;if(typeof r!=="string"||!r)return!1;if(t==="*")return!0;return r===t},al=(t)=>({id:"google",name:"Google",accountSubject:({profile:r})=>r.sub,async createAuthorizationURL({state:r,scopes:n,codeVerifier:o,redirectURI:i,loginHint:s,display:a,additionalParams:c}){if(!Re(t.clientId)||!t.clientSecret)throw Ee.error("Client Id and Client Secret is required for Google. Make sure to provide them in the options."),new te("CLIENT_ID_AND_SECRET_REQUIRED");if(!o)throw new te("codeVerifier is required for Google");let d=t.disableDefaultScope?[]:["email","profile","openid"];if(t.scope)d.push(...t.scope);if(n)d.push(...n);return await V({id:"google",options:t,authorizationEndpoint:"https://accounts.google.com/o/oauth2/v2/auth",scopes:d,state:r,codeVerifier:o,redirectURI:i,prompt:t.prompt,accessType:t.accessType,display:a||t.display,loginHint:s,hd:t.hd,additionalParams:{...t.includeGrantedScopes===!1?{}:{include_granted_scopes:"true"},...c??{}}})},validateAuthorizationCode:async({code:r,codeVerifier:n,redirectURI:o})=>K({code:r,codeVerifier:n,redirectURI:o,options:t,tokenEndpoint:"https://oauth2.googleapis.com/token"}),refreshAccessToken:t.refreshAccessToken?t.refreshAccessToken:async(r)=>F({refreshToken:r,options:{clientId:t.clientId,clientKey:t.clientKey,clientSecret:t.clientSecret},tokenEndpoint:"https://oauth2.googleapis.com/token"}),idToken:{jwks:(r)=>cl(r.kid),issuer:["https://accounts.google.com","accounts.google.com"],audience:t.clientId,algorithms:Uy,maxTokenAge:Iy,verifyClaims:t.hd?(r)=>zs(t.hd,r.hd):void 0},async getUserInfo(r){if(t.getUserInfo)return t.getUserInfo(r);if(!r.idToken)return null;let n=en(r.idToken);if(!zs(t.hd,n.hd))return Ee.error(`Google sign-in rejected: id token hosted domain (hd) "${n.hd??"<missing>"}" does not satisfy the configured "hd" option "${t.hd}".`),null;let o=await t.mapProfileToUser?.(n);return{user:{name:n.name,email:n.email,image:n.picture,emailVerified:n.email_verified,...o},data:n}},options:t}),cl=async(t)=>{let[r]=await Cy(t);if(!r)throw Error(`JWK with kid ${t} not found`);return r},Cy=async(t)=>{let{data:r}=await Me("https://www.googleapis.com/oauth2/v3/certs");if(!r?.keys)throw new U("BAD_REQUEST",{message:"Keys not found"});let n=t?r.keys.filter((o)=>o.kid===t):r.keys;if(!n.length)throw Error(`JWK with kid ${t} not found`);return Promise.all(n.map((o)=>In(o,sl)))};var dl=(t)=>({id:"huggingface",name:"Hugging Face",accountSubject:({profile:n})=>n.sub,createAuthorizationURL({state:n,scopes:o,codeVerifier:i,redirectURI:s,additionalParams:a}){let c=t.disableDefaultScope?[]:["openid","profile","email"];if(t.scope)c.push(...t.scope);if(o)c.push(...o);return V({id:"huggingface",options:t,authorizationEndpoint:"https://huggingface.co/oauth/authorize",scopes:c,state:n,codeVerifier:i,redirectURI:s,additionalParams:a})},validateAuthorizationCode:async({code:n,codeVerifier:o,redirectURI:i})=>K({code:n,codeVerifier:o,redirectURI:i,options:t,tokenEndpoint:"https://huggingface.co/oauth/token"}),refreshAccessToken:t.refreshAccessToken?t.refreshAccessToken:async(n)=>F({refreshToken:n,options:{clientId:t.clientId,clientKey:t.clientKey,clientSecret:t.clientSecret},tokenEndpoint:"https://huggingface.co/oauth/token"}),async getUserInfo(n){if(t.getUserInfo)return t.getUserInfo(n);let{data:o,error:i}=await Me("https://huggingface.co/oauth/userinfo",{method:"GET",headers:{Authorization:`Bearer ${n.accessToken}`}});if(i)return null;let s=await t.mapProfileToUser?.(o);return{user:{name:o.name||o.preferred_username||"",email:o.email,image:o.picture,emailVerified:o.email_verified??!1,...s},data:o}},options:t});var ul=(t)=>({id:"kakao",name:"Kakao",accountSubject:({profile:n})=>n.id,createAuthorizationURL({state:n,scopes:o,redirectURI:i,additionalParams:s}){let a=t.disableDefaultScope?[]:["account_email","profile_image","profile_nickname"];if(t.scope)a.push(...t.scope);if(o)a.push(...o);return V({id:"kakao",options:t,authorizationEndpoint:"https://kauth.kakao.com/oauth/authorize",scopes:a,state:n,redirectURI:i,additionalParams:s})},validateAuthorizationCode:async({code:n,redirectURI:o})=>K({code:n,redirectURI:o,options:t,tokenEndpoint:"https://kauth.kakao.com/oauth/token"}),refreshAccessToken:t.refreshAccessToken?t.refreshAccessToken:async(n)=>F({refreshToken:n,options:{clientId:t.clientId,clientKey:t.clientKey,clientSecret:t.clientSecret},tokenEndpoint:"https://kauth.kakao.com/oauth/token"}),async getUserInfo(n){if(t.getUserInfo)return t.getUserInfo(n);let{data:o,error:i}=await Me("https://kapi.kakao.com/v2/user/me",{headers:{Authorization:`Bearer ${n.accessToken}`}});if(i||!o)return null;let s=await t.mapProfileToUser?.(o),a=o.kakao_account||{},c=a.profile||{};return{user:{name:c.nickname||a.name||"",email:a.email,image:c.profile_image_url||c.thumbnail_image_url,emailVerified:!!a.is_email_valid&&!!a.is_email_verified,...s},data:o}},options:t});var ll=(t)=>({id:"kick",name:"Kick",accountSubject:({profile:r})=>r.user_id,createAuthorizationURL({state:r,scopes:n,redirectURI:o,codeVerifier:i,additionalParams:s}){let a=t.disableDefaultScope?[]:["user:read"];if(t.scope)a.push(...t.scope);if(n)a.push(...n);return V({id:"kick",redirectURI:o,options:t,authorizationEndpoint:"https://id.kick.com/oauth/authorize",scopes:a,codeVerifier:i,state:r,additionalParams:s})},async validateAuthorizationCode({code:r,redirectURI:n,codeVerifier:o}){return K({code:r,redirectURI:n,options:t,tokenEndpoint:"https://id.kick.com/oauth/token",codeVerifier:o})},refreshAccessToken:t.refreshAccessToken?t.refreshAccessToken:async(r)=>F({refreshToken:r,options:{clientId:t.clientId,clientSecret:t.clientSecret},tokenEndpoint:"https://id.kick.com/oauth/token"}),async getUserInfo(r){if(t.getUserInfo)return t.getUserInfo(r);let{data:n,error:o}=await Me("https://api.kick.com/public/v1/users",{method:"GET",headers:{Authorization:`Bearer ${r.accessToken}`}});if(o)return null;let i=n.data[0],s=await t.mapProfileToUser?.(i);return{user:{name:i.name,email:i.email,image:i.profile_picture,emailVerified:!1,...s},data:i}},options:t});var fl=(t)=>({id:"line",name:"LINE",accountSubject:({profile:s})=>s.sub,async createAuthorizationURL({state:s,scopes:a,codeVerifier:c,redirectURI:d,loginHint:u,additionalParams:f}){let p=t.disableDefaultScope?[]:["openid","profile","email"];if(t.scope)p.push(...t.scope);if(a)p.push(...a);return await V({id:"line",options:t,authorizationEndpoint:"https://access.line.me/oauth2/v2.1/authorize",scopes:p,state:s,codeVerifier:c,redirectURI:d,loginHint:u,additionalParams:f})},validateAuthorizationCode:async({code:s,codeVerifier:a,redirectURI:c})=>K({code:s,codeVerifier:a,redirectURI:c,options:t,tokenEndpoint:"https://api.line.me/oauth2/v2.1/token"}),refreshAccessToken:t.refreshAccessToken?t.refreshAccessToken:async(s)=>F({refreshToken:s,options:{clientId:t.clientId,clientSecret:t.clientSecret},tokenEndpoint:"https://api.line.me/oauth2/v2.1/token"}),idToken:{verify:async(s,a)=>{let c=new URLSearchParams;if(c.set("id_token",s),c.set("client_id",t.clientId),a)c.set("nonce",a);let{data:d,error:u}=await Me("https://api.line.me/oauth2/v2.1/verify",{method:"POST",headers:{"content-type":"application/x-www-form-urlencoded"},body:c});if(u||!d)return!1;if(d.aud!==t.clientId)return!1;if(d.nonce&&d.nonce!==a)return!1;return!0}},async getUserInfo(s){if(t.getUserInfo)return t.getUserInfo(s);let a=null;if(s.idToken)try{a=en(s.idToken)}catch{}if(!a){let{data:d}=await Me("https://api.line.me/oauth2/v2.1/userinfo",{headers:{authorization:`Bearer ${s.accessToken}`}});a=d||null}if(!a)return null;let c=await t.mapProfileToUser?.(a);return{user:{name:a.name||"",email:a.email,image:a.picture,emailVerified:!1,...c},data:a}},options:t});var pl=(t)=>({id:"linear",name:"Linear",accountSubject:({profile:n})=>n.id,createAuthorizationURL({state:n,scopes:o,loginHint:i,redirectURI:s,additionalParams:a}){let c=t.disableDefaultScope?[]:["read"];if(t.scope)c.push(...t.scope);if(o)c.push(...o);return V({id:"linear",options:t,authorizationEndpoint:"https://linear.app/oauth/authorize",scopes:c,state:n,redirectURI:s,loginHint:i,additionalParams:a})},validateAuthorizationCode:async({code:n,redirectURI:o})=>K({code:n,redirectURI:o,options:t,tokenEndpoint:"https://api.linear.app/oauth/token"}),refreshAccessToken:t.refreshAccessToken?t.refreshAccessToken:async(n)=>F({refreshToken:n,options:{clientId:t.clientId,clientKey:t.clientKey,clientSecret:t.clientSecret},tokenEndpoint:"https://api.linear.app/oauth/token"}),async getUserInfo(n){if(t.getUserInfo)return t.getUserInfo(n);let{data:o,error:i}=await Me("https://api.linear.app/graphql",{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${n.accessToken}`},body:JSON.stringify({query:`
40
40
  query {
41
41
  viewer {
42
42
  id
@@ -48,7 +48,7 @@ Error: `,I),en(t,t.context.options.onAPIError?.errorURL||`${t.context.baseURL}/e
48
48
  updatedAt
49
49
  }
50
50
  }
51
- `})});if(i||!o?.data?.viewer)return null;let s=o.data.viewer,a=await t.mapProfileToUser?.(s);return{user:{name:o.data.viewer.name,email:o.data.viewer.email,image:o.data.viewer.avatarUrl,emailVerified:!1,...a},data:s}},options:t});var hl=(t)=>({id:"linkedin",name:"Linkedin",accountSubject:({profile:o})=>o.sub,createAuthorizationURL:async({state:o,scopes:i,redirectURI:s,loginHint:a,additionalParams:c})=>{let d=t.disableDefaultScope?[]:["profile","email","openid"];if(t.scope)d.push(...t.scope);if(i)d.push(...i);return await V({id:"linkedin",options:t,authorizationEndpoint:"https://www.linkedin.com/oauth/v2/authorization",scopes:d,state:o,loginHint:a,redirectURI:s,additionalParams:c})},validateAuthorizationCode:async({code:o,redirectURI:i})=>await K({code:o,redirectURI:i,options:t,tokenEndpoint:"https://www.linkedin.com/oauth/v2/accessToken"}),refreshAccessToken:t.refreshAccessToken?t.refreshAccessToken:async(o)=>F({refreshToken:o,options:{clientId:t.clientId,clientKey:t.clientKey,clientSecret:t.clientSecret},tokenEndpoint:"https://www.linkedin.com/oauth/v2/accessToken"}),async getUserInfo(o){if(t.getUserInfo)return t.getUserInfo(o);let{data:i,error:s}=await Me("https://api.linkedin.com/v2/userinfo",{method:"GET",headers:{Authorization:`Bearer ${o.accessToken}`}});if(s)return null;let a=await t.mapProfileToUser?.(i);return{user:{name:i.name,email:i.email,emailVerified:i.email_verified??!1,image:i.picture,...a},data:i}},options:t});var ml="9188040d-6c67-4c5b-b112-36a304b66dad",wl=(t)=>{let r=t.tenantId||"common",n=t.authority||"https://login.microsoftonline.com";while(n.endsWith("/"))n=n.slice(0,-1);let o=`${n}/${r}/oauth2/v2.0/authorize`,i=`${n}/${r}/oauth2/v2.0/token`;if(t.clientSecret&&t.clientAssertion)throw new te("Microsoft Entra ID clientAssertion cannot be combined with clientSecret");let s=t.clientAssertion?{method:"private_key_jwt",getClientAssertion:t.clientAssertion}:void 0;return{id:"microsoft",name:"Microsoft EntraID",accountSubject:({profile:a})=>a.oid,createAuthorizationURL(a){if(!Re(t.clientId))throw Ee.error("Client Id is required for Microsoft Entra ID. Make sure to provide it in the options."),new te("CLIENT_ID_AND_SECRET_REQUIRED");let c=t.disableDefaultScope?[]:["openid","profile","email","User.Read","offline_access"];if(t.scope)c.push(...t.scope);if(a.scopes)c.push(...a.scopes);return V({id:"microsoft",options:t,authorizationEndpoint:o,state:a.state,codeVerifier:a.codeVerifier,scopes:c,redirectURI:a.redirectURI,prompt:t.prompt,loginHint:a.loginHint,additionalParams:a.additionalParams})},validateAuthorizationCode({code:a,codeVerifier:c,redirectURI:d}){return K({code:a,codeVerifier:c,redirectURI:d,options:t,tokenEndpoint:i,tokenEndpointAuth:s})},idToken:{jwks:(a)=>kl(a.kid,r,n),algorithms:["RS256"],audience:t.clientId,maxTokenAge:"1h",issuer:r!=="common"&&r!=="organizations"&&r!=="consumers"?`${n}/${r}/v2.0`:void 0,verifyClaims:(a)=>{let c=a.tid;if(typeof c!=="string"||a.iss!==`${n}/${c}/v2.0`)return!1;if(r==="organizations"&&c===ml)return!1;if(r==="consumers"&&c!==ml)return!1;return!0}},async getUserInfo(a){if(t.getUserInfo)return t.getUserInfo(a);if(!a.idToken)return null;let c=Xr(a.idToken);if(typeof c.oid!=="string"||c.oid.trim().length===0)return Ee.error("Microsoft Entra ID token did not include a valid oid claim; unable to resolve a stable account identifier."),null;let d=t.profilePhotoSize||48;if(!t.disableProfilePhoto&&a.accessToken)await Me(`https://graph.microsoft.com/v1.0/me/photos/${d}x${d}/$value`,{headers:{Authorization:`Bearer ${a.accessToken}`},async onResponse(p){if(!p.response.ok)return;try{let h=await p.response.clone().arrayBuffer();c.picture=`data:image/jpeg;base64, ${To.encode(h)}`}catch(h){Ee.error(h&&typeof h==="object"&&"name"in h?h.name:"",h)}}});let u=await t.mapProfileToUser?.(c),f=c.email_verified!==void 0?c.email_verified:c.email&&(c.verified_primary_email?.includes(c.email)||c.verified_secondary_email?.includes(c.email))?!0:!1;return{user:{name:c.name,email:c.email,image:c.picture,emailVerified:f,...u},data:c}},refreshAccessToken:t.refreshAccessToken?t.refreshAccessToken:async(a)=>{let c=t.disableDefaultScope?[]:["openid","profile","email","User.Read","offline_access"];if(t.scope)c.push(...t.scope);return F({refreshToken:a,options:{clientId:t.clientId,clientSecret:t.clientSecret},extraParams:{scope:c.join(" ")},tokenEndpoint:i,tokenEndpointAuth:s})},options:t}},kl=async(t,r,n)=>{let{data:o}=await Me(`${n}/${r}/discovery/v2.0/keys`);if(!o?.keys)throw new U("BAD_REQUEST",{message:"Keys not found"});let i=o.keys.find((s)=>s.kid===t);if(!i)throw Error(`JWK with kid ${t} not found`);return await Sn(i,i.alg??"RS256")};var Rl=(t)=>({id:"naver",name:"Naver",accountSubject:({profile:n})=>n.response.id,createAuthorizationURL({state:n,scopes:o,redirectURI:i,additionalParams:s}){let a=t.disableDefaultScope?[]:["profile","email"];if(t.scope)a.push(...t.scope);if(o)a.push(...o);return V({id:"naver",options:t,authorizationEndpoint:"https://nid.naver.com/oauth2.0/authorize",scopes:a,state:n,redirectURI:i,additionalParams:s})},validateAuthorizationCode:async({code:n,redirectURI:o})=>K({code:n,redirectURI:o,options:t,tokenEndpoint:"https://nid.naver.com/oauth2.0/token"}),refreshAccessToken:t.refreshAccessToken?t.refreshAccessToken:async(n)=>F({refreshToken:n,options:{clientId:t.clientId,clientKey:t.clientKey,clientSecret:t.clientSecret},tokenEndpoint:"https://nid.naver.com/oauth2.0/token"}),async getUserInfo(n){if(t.getUserInfo)return t.getUserInfo(n);let{data:o,error:i}=await Me("https://openapi.naver.com/v1/nid/me",{headers:{Authorization:`Bearer ${n.accessToken}`}});if(i||!o||o.resultcode!=="00")return null;let s=await t.mapProfileToUser?.(o),a=o.response||{};return{user:{name:a.name||a.nickname||"",email:a.email,image:a.profile_image,emailVerified:!1,...s},data:o}},options:t});var Tl=(t)=>({id:"notion",name:"Notion",accountSubject:({profile:n})=>n.id,createAuthorizationURL({state:n,scopes:o,loginHint:i,redirectURI:s,additionalParams:a}){let c=t.disableDefaultScope?[]:[];if(t.scope)c.push(...t.scope);if(o)c.push(...o);return V({id:"notion",options:t,authorizationEndpoint:"https://api.notion.com/v1/oauth/authorize",scopes:c,state:n,redirectURI:s,loginHint:i,additionalParams:{...a??{},owner:"user"}})},validateAuthorizationCode:async({code:n,redirectURI:o})=>K({code:n,redirectURI:o,options:t,tokenEndpoint:"https://api.notion.com/v1/oauth/token",authentication:"basic"}),refreshAccessToken:t.refreshAccessToken?t.refreshAccessToken:async(n)=>F({refreshToken:n,options:{clientId:t.clientId,clientKey:t.clientKey,clientSecret:t.clientSecret},tokenEndpoint:"https://api.notion.com/v1/oauth/token"}),async getUserInfo(n){if(t.getUserInfo)return t.getUserInfo(n);let{data:o,error:i}=await Me("https://api.notion.com/v1/users/me",{headers:{Authorization:`Bearer ${n.accessToken}`,"Notion-Version":"2022-06-28"}});if(i||!o)return null;let s=o.bot?.owner?.user;if(!s)return null;let a=await t.mapProfileToUser?.(s);return{user:{name:s.name||"",email:s.person?.email||null,image:s.avatar_url,emailVerified:!1,...a},data:s}},options:t});var Il=(t)=>{let r=t.issuer||"https://idp.paybin.io",n=`${r}/oauth2/authorize`,o=`${r}/oauth2/token`;return{id:"paybin",name:"Paybin",accountSubject:({profile:i})=>i.sub,async createAuthorizationURL({state:i,scopes:s,codeVerifier:a,redirectURI:c,loginHint:d,additionalParams:u}){if(!t.clientId||!t.clientSecret)throw Ee.error("Client Id and Client Secret is required for Paybin. Make sure to provide them in the options."),new te("CLIENT_ID_AND_SECRET_REQUIRED");if(!a)throw new te("codeVerifier is required for Paybin");let f=t.disableDefaultScope?[]:["openid","email","profile"];if(t.scope)f.push(...t.scope);if(s)f.push(...s);return await V({id:"paybin",options:t,authorizationEndpoint:n,scopes:f,state:i,codeVerifier:a,redirectURI:c,prompt:t.prompt,loginHint:d,additionalParams:u})},validateAuthorizationCode:async({code:i,codeVerifier:s,redirectURI:a})=>K({code:i,codeVerifier:s,redirectURI:a,options:t,tokenEndpoint:o}),refreshAccessToken:t.refreshAccessToken?t.refreshAccessToken:async(i)=>F({refreshToken:i,options:{clientId:t.clientId,clientKey:t.clientKey,clientSecret:t.clientSecret},tokenEndpoint:o}),async getUserInfo(i){if(t.getUserInfo)return t.getUserInfo(i);if(!i.idToken)return null;let s=Xr(i.idToken),a=await t.mapProfileToUser?.(s);return{user:{name:s.name||s.preferred_username||"",email:s.email,image:s.picture,emailVerified:s.email_verified||!1,...a},data:s}},options:t}};var Ul=(t)=>{let r=(t.environment||"sandbox")==="sandbox",n=r?"https://www.sandbox.paypal.com/signin/authorize":"https://www.paypal.com/signin/authorize",o=r?"https://api-m.sandbox.paypal.com/v1/oauth2/token":"https://api-m.paypal.com/v1/oauth2/token",i=r?"https://api-m.sandbox.paypal.com/v1/identity/oauth2/userinfo":"https://api-m.paypal.com/v1/identity/oauth2/userinfo",s={clientId:t.clientId,clientSecret:t.clientSecret},a={method:"client_secret_basic"};return{id:"paypal",name:"PayPal",accountSubject:({profile:c})=>c.user_id,async createAuthorizationURL({state:c,codeVerifier:d,redirectURI:u,additionalParams:f}){if(!t.clientId||!t.clientSecret)throw Ee.error("Client Id and Client Secret is required for PayPal. Make sure to provide them in the options."),new te("CLIENT_ID_AND_SECRET_REQUIRED");return await V({id:"paypal",options:t,authorizationEndpoint:n,scopes:[],state:c,codeVerifier:d,redirectURI:u,prompt:t.prompt,additionalParams:f})},validateAuthorizationCode:async({code:c,codeVerifier:d,redirectURI:u})=>{try{return await K({code:c,codeVerifier:d,redirectURI:t.redirectURI||u,options:s,tokenEndpoint:o,tokenEndpointAuth:a})}catch(f){throw Ee.error("PayPal token exchange failed:",f),new te("FAILED_TO_GET_ACCESS_TOKEN")}},refreshAccessToken:t.refreshAccessToken?t.refreshAccessToken:async(c)=>{try{return await F({refreshToken:c,options:s,tokenEndpoint:o,tokenEndpointAuth:a})}catch(d){throw Ee.error("PayPal token refresh failed:",d),new te("FAILED_TO_REFRESH_ACCESS_TOKEN")}},async getUserInfo(c){if(t.getUserInfo)return t.getUserInfo(c);if(!c.accessToken)return Ee.error("Access token is required to fetch PayPal user info"),null;try{let d=await Me(`${i}?schema=paypalv1.1`,{headers:{Authorization:`Bearer ${c.accessToken}`,Accept:"application/json"}});if(!d.data)return Ee.error("Failed to fetch user info from PayPal"),null;let u=d.data;if(c.idToken){let p;try{p=Xr(c.idToken).sub}catch(m){return Ee.error("Failed to decode PayPal ID token:",m),null}let h=u.sub??u.user_id;if(!p||h!==p)return Ee.error("PayPal user info subject does not match ID token subject"),null}let f=await t.mapProfileToUser?.(u);return{user:{name:u.name,email:u.email,image:u.picture,emailVerified:u.email_verified,...f},data:u}}catch(d){return Ee.error("Failed to fetch user info from PayPal:",d),null}},options:t}};var Ol=(t)=>({id:"polar",name:"Polar",accountSubject:({profile:n})=>n.id,createAuthorizationURL({state:n,scopes:o,codeVerifier:i,redirectURI:s,additionalParams:a}){let c=t.disableDefaultScope?[]:["openid","profile","email"];if(t.scope)c.push(...t.scope);if(o)c.push(...o);return V({id:"polar",options:t,authorizationEndpoint:"https://polar.sh/oauth2/authorize",scopes:c,state:n,codeVerifier:i,redirectURI:s,prompt:t.prompt,additionalParams:a})},validateAuthorizationCode:async({code:n,codeVerifier:o,redirectURI:i})=>K({code:n,codeVerifier:o,redirectURI:i,options:t,tokenEndpoint:"https://api.polar.sh/v1/oauth2/token"}),refreshAccessToken:t.refreshAccessToken?t.refreshAccessToken:async(n)=>F({refreshToken:n,options:{clientId:t.clientId,clientKey:t.clientKey,clientSecret:t.clientSecret},tokenEndpoint:"https://api.polar.sh/v1/oauth2/token"}),async getUserInfo(n){if(t.getUserInfo)return t.getUserInfo(n);let{data:o,error:i}=await Me("https://api.polar.sh/v1/oauth2/userinfo",{headers:{Authorization:`Bearer ${n.accessToken}`}});if(i)return null;let s=await t.mapProfileToUser?.(o);return{user:{name:o.public_name||o.username||"",email:o.email,image:o.avatar_url,emailVerified:o.email_verified??!1,...s},data:o}},options:t});var Oy="https://backboard.railway.com/oauth/auth",Dl="https://backboard.railway.com/oauth/token",Dy="https://backboard.railway.com/oauth/me",Ll=(t)=>({id:"railway",name:"Railway",accountSubject:({profile:r})=>r.sub,createAuthorizationURL({state:r,scopes:n,codeVerifier:o,redirectURI:i,additionalParams:s}){let a=t.disableDefaultScope?[]:["openid","email","profile"];if(t.scope)a.push(...t.scope);if(n)a.push(...n);return V({id:"railway",options:t,authorizationEndpoint:Oy,scopes:a,state:r,codeVerifier:o,redirectURI:i,additionalParams:s})},validateAuthorizationCode:async({code:r,codeVerifier:n,redirectURI:o})=>K({code:r,codeVerifier:n,redirectURI:o,options:t,tokenEndpoint:Dl,authentication:"basic"}),refreshAccessToken:t.refreshAccessToken?t.refreshAccessToken:async(r)=>F({refreshToken:r,options:{clientId:t.clientId,clientKey:t.clientKey,clientSecret:t.clientSecret},tokenEndpoint:Dl,authentication:"basic"}),async getUserInfo(r){if(t.getUserInfo)return t.getUserInfo(r);let{data:n,error:o}=await Me(Dy,{headers:{authorization:`Bearer ${r.accessToken}`}});if(o||!n)return null;let i=await t.mapProfileToUser?.(n);return{user:{name:n.name,email:n.email,image:n.picture,emailVerified:!1,...i},data:n}},options:t});var Ly="placeholder.invalid";function it({identifier:t,namespace:r}){let n=In().safeParse(`${t}@${r}.${Ly}`);if(!n.success)throw TypeError("Invalid placeholder email");return n.data}var Pl=(t)=>{let n={clientId:t.clientId,clientSecret:t.clientSecret},o={method:"client_secret_basic"};return{id:"reddit",name:"Reddit",accountSubject:({profile:i})=>i.id,createAuthorizationURL({state:i,scopes:s,redirectURI:a,additionalParams:c}){let d=t.disableDefaultScope?[]:["identity"];if(t.scope)d.push(...t.scope);if(s)d.push(...s);return V({id:"reddit",options:t,authorizationEndpoint:"https://www.reddit.com/api/v1/authorize",scopes:d,state:i,redirectURI:a,duration:t.duration,additionalParams:c})},validateAuthorizationCode:async({code:i,redirectURI:s})=>K({code:i,redirectURI:t.redirectURI||s,options:n,tokenEndpoint:"https://www.reddit.com/api/v1/access_token",tokenEndpointAuth:o,headers:{accept:"text/plain","user-agent":"better-auth"}}),refreshAccessToken:t.refreshAccessToken?t.refreshAccessToken:async(i)=>F({refreshToken:i,options:n,tokenEndpoint:"https://www.reddit.com/api/v1/access_token",tokenEndpointAuth:o}),async getUserInfo(i){if(t.getUserInfo)return t.getUserInfo(i);let{data:s,error:a}=await Me("https://oauth.reddit.com/api/v1/me",{headers:{Authorization:`Bearer ${i.accessToken}`,"User-Agent":"better-auth"}});if(a)return null;let c=await t.mapProfileToUser?.(s),d=c?.email||it({identifier:s.id,namespace:"reddit"});return{user:{name:s.name,image:s.icon_img?.split("?")[0],...c,email:d,emailVerified:c?.emailVerified??!1},data:s}},options:t}};var zl=(t)=>({id:"roblox",name:"Roblox",accountSubject:({profile:n})=>n.sub,createAuthorizationURL({state:n,scopes:o,redirectURI:i,additionalParams:s}){let a=t.disableDefaultScope?[]:["openid","profile"];if(t.scope)a.push(...t.scope);if(o)a.push(...o);return V({id:"roblox",options:t,authorizationEndpoint:"https://apis.roblox.com/oauth/v1/authorize",scopes:a,state:n,redirectURI:i,prompt:t.prompt||"select_account consent",additionalParams:s})},validateAuthorizationCode:async({code:n,redirectURI:o})=>K({code:n,redirectURI:t.redirectURI||o,options:t,tokenEndpoint:"https://apis.roblox.com/oauth/v1/token",authentication:"post"}),refreshAccessToken:t.refreshAccessToken?t.refreshAccessToken:async(n)=>F({refreshToken:n,options:{clientId:t.clientId,clientKey:t.clientKey,clientSecret:t.clientSecret},tokenEndpoint:"https://apis.roblox.com/oauth/v1/token"}),async getUserInfo(n){if(t.getUserInfo)return t.getUserInfo(n);let{data:o,error:i}=await Me("https://apis.roblox.com/oauth/v1/userinfo",{headers:{authorization:`Bearer ${n.accessToken}`}});if(i)return null;let s=await t.mapProfileToUser?.(o);return{user:{name:o.nickname||o.preferred_username||"",image:o.picture,email:it({identifier:o.sub,namespace:"roblox"}),emailVerified:!1,...s},data:{...o}}},options:t});var Nl=(t)=>{let r=(t.environment??"production")==="sandbox",n=t.loginUrl?`https://${t.loginUrl}/services/oauth2/authorize`:r?"https://test.salesforce.com/services/oauth2/authorize":"https://login.salesforce.com/services/oauth2/authorize",o=t.loginUrl?`https://${t.loginUrl}/services/oauth2/token`:r?"https://test.salesforce.com/services/oauth2/token":"https://login.salesforce.com/services/oauth2/token",i=t.loginUrl?`https://${t.loginUrl}/services/oauth2/userinfo`:r?"https://test.salesforce.com/services/oauth2/userinfo":"https://login.salesforce.com/services/oauth2/userinfo";return{id:"salesforce",name:"Salesforce",accountSubject:({profile:s})=>s.user_id,async createAuthorizationURL({state:s,scopes:a,codeVerifier:c,redirectURI:d,additionalParams:u}){if(!t.clientId||!t.clientSecret)throw Ee.error("Client Id and Client Secret are required for Salesforce. Make sure to provide them in the options."),new te("CLIENT_ID_AND_SECRET_REQUIRED");if(!c)throw new te("codeVerifier is required for Salesforce");let f=t.disableDefaultScope?[]:["openid","email","profile"];if(t.scope)f.push(...t.scope);if(a)f.push(...a);return V({id:"salesforce",options:t,authorizationEndpoint:n,scopes:f,state:s,codeVerifier:c,redirectURI:t.redirectURI||d,additionalParams:u})},validateAuthorizationCode:async({code:s,codeVerifier:a,redirectURI:c})=>K({code:s,codeVerifier:a,redirectURI:t.redirectURI||c,options:t,tokenEndpoint:o}),refreshAccessToken:t.refreshAccessToken?t.refreshAccessToken:async(s)=>F({refreshToken:s,options:{clientId:t.clientId,clientSecret:t.clientSecret},tokenEndpoint:o}),async getUserInfo(s){if(t.getUserInfo)return t.getUserInfo(s);try{let{data:a}=await Me(i,{headers:{Authorization:`Bearer ${s.accessToken}`}});if(!a)return Ee.error("Failed to fetch user info from Salesforce"),null;let c=await t.mapProfileToUser?.(a);return{user:{name:a.name,email:a.email,image:a.photos?.picture||a.photos?.thumbnail,emailVerified:a.email_verified??!1,...c},data:a}}catch(a){return Ee.error("Failed to fetch user info from Salesforce:",a),null}},options:t}};var ql=(t)=>({id:"slack",name:"Slack",accountSubject:({profile:n})=>n["https://slack.com/user_id"],createAuthorizationURL({state:n,scopes:o,redirectURI:i,additionalParams:s}){let a=t.disableDefaultScope?[]:["openid","profile","email"];if(o)a.push(...o);if(t.scope)a.push(...t.scope);return V({id:"slack",options:t,authorizationEndpoint:"https://slack.com/openid/connect/authorize",scopes:a,state:n,redirectURI:i,additionalParams:s})},validateAuthorizationCode:async({code:n,redirectURI:o})=>K({code:n,redirectURI:o,options:t,tokenEndpoint:"https://slack.com/api/openid.connect.token"}),refreshAccessToken:t.refreshAccessToken?t.refreshAccessToken:async(n)=>F({refreshToken:n,options:{clientId:t.clientId,clientKey:t.clientKey,clientSecret:t.clientSecret},tokenEndpoint:"https://slack.com/api/openid.connect.token"}),async getUserInfo(n){if(t.getUserInfo)return t.getUserInfo(n);let{data:o,error:i}=await Me("https://slack.com/api/openid.connect.userInfo",{headers:{authorization:`Bearer ${n.accessToken}`}});if(i)return null;let s=await t.mapProfileToUser?.(o);return{user:{name:o.name||"",email:o.email,emailVerified:o.email_verified,image:o.picture||o["https://slack.com/user_image_512"],...s},data:o}},options:t});var jl=(t)=>({id:"spotify",name:"Spotify",accountSubject:({profile:n})=>n.id,createAuthorizationURL({state:n,scopes:o,codeVerifier:i,redirectURI:s,additionalParams:a}){let c=t.disableDefaultScope?[]:["user-read-email"];if(t.scope)c.push(...t.scope);if(o)c.push(...o);return V({id:"spotify",options:t,authorizationEndpoint:"https://accounts.spotify.com/authorize",scopes:c,state:n,codeVerifier:i,redirectURI:s,additionalParams:a})},validateAuthorizationCode:async({code:n,codeVerifier:o,redirectURI:i})=>K({code:n,codeVerifier:o,redirectURI:i,options:t,tokenEndpoint:"https://accounts.spotify.com/api/token"}),refreshAccessToken:t.refreshAccessToken?t.refreshAccessToken:async(n)=>F({refreshToken:n,options:{clientId:t.clientId,clientKey:t.clientKey,clientSecret:t.clientSecret},tokenEndpoint:"https://accounts.spotify.com/api/token"}),async getUserInfo(n){if(t.getUserInfo)return t.getUserInfo(n);let{data:o,error:i}=await Me("https://api.spotify.com/v1/me",{method:"GET",headers:{Authorization:`Bearer ${n.accessToken}`}});if(i)return null;let s=await t.mapProfileToUser?.(o);return{user:{name:o.display_name,email:o.email,image:o.images[0]?.url,emailVerified:!1,...s},data:o}},options:t});var Bl=(t)=>{let n={method:"custom",customizeRequest({body:o}){o.set("client_key",t.clientKey),o.set("client_secret",t.clientSecret)}};return{id:"tiktok",name:"TikTok",accountSubject:({profile:o})=>o.data.user.open_id,createAuthorizationURL({state:o,scopes:i,redirectURI:s,additionalParams:a}){let c=t.disableDefaultScope?[]:["user.info.profile"];if(t.scope)c.push(...t.scope);if(i)c.push(...i);let d=new URL("https://www.tiktok.com/v2/auth/authorize");if(d.searchParams.set("scope",c.join(",")),d.searchParams.set("response_type","code"),d.searchParams.set("client_key",t.clientKey),d.searchParams.set("redirect_uri",t.redirectURI||s),d.searchParams.set("state",o),a)for(let[u,f]of Object.entries(a)){if(Ft.has(u))continue;if(u==="client_key")continue;d.searchParams.set(u,f)}return d},validateAuthorizationCode:async({code:o,codeVerifier:i,redirectURI:s})=>K({code:o,codeVerifier:i,redirectURI:t.redirectURI||s,options:{},tokenEndpoint:"https://open.tiktokapis.com/v2/oauth/token/",tokenEndpointAuth:n}),refreshAccessToken:t.refreshAccessToken?t.refreshAccessToken:async(o)=>F({refreshToken:o,options:{},tokenEndpoint:"https://open.tiktokapis.com/v2/oauth/token/",tokenEndpointAuth:n}),async getUserInfo(o){if(t.getUserInfo)return t.getUserInfo(o);let{data:i,error:s}=await Me(`https://open.tiktokapis.com/v2/user/info/?fields=${["open_id","avatar_large_url","display_name","username"].join(",")}`,{headers:{authorization:`Bearer ${o.accessToken}`}});if(s)return null;return{user:{email:i.data.user.email||it({identifier:i.data.user.open_id,namespace:"tiktok"}),name:i.data.user.display_name||i.data.user.username||"",image:i.data.user.avatar_large_url,emailVerified:!1},data:i}},options:t}};var $l=(t)=>({id:"twitch",name:"Twitch",accountSubject:({profile:n})=>n.sub,createAuthorizationURL({state:n,scopes:o,redirectURI:i,additionalParams:s}){let a=t.disableDefaultScope?[]:["user:read:email","openid"];if(t.scope)a.push(...t.scope);if(o)a.push(...o);return V({id:"twitch",redirectURI:i,options:t,authorizationEndpoint:"https://id.twitch.tv/oauth2/authorize",scopes:a,state:n,claims:t.claims||["email","email_verified","preferred_username","picture"],additionalParams:s})},validateAuthorizationCode:async({code:n,redirectURI:o})=>K({code:n,redirectURI:o,options:t,tokenEndpoint:"https://id.twitch.tv/oauth2/token"}),refreshAccessToken:t.refreshAccessToken?t.refreshAccessToken:async(n)=>F({refreshToken:n,options:{clientId:t.clientId,clientKey:t.clientKey,clientSecret:t.clientSecret},tokenEndpoint:"https://id.twitch.tv/oauth2/token"}),async getUserInfo(n){if(t.getUserInfo)return t.getUserInfo(n);let o=n.idToken;if(!o)return Ee.error("No idToken found in token"),null;let i=Xr(o),s=await t.mapProfileToUser?.(i);return{user:{name:i.preferred_username,email:i.email,image:i.picture,emailVerified:i.email_verified,...s},data:i}},options:t});var Ml=(t)=>({id:"twitter",name:"Twitter",accountSubject:({profile:n})=>n.data.id,createAuthorizationURL(n){let o=t.disableDefaultScope?[]:["users.read","tweet.read","offline.access","users.email"];if(t.scope)o.push(...t.scope);if(n.scopes)o.push(...n.scopes);return V({id:"twitter",options:t,authorizationEndpoint:"https://x.com/i/oauth2/authorize",scopes:o,state:n.state,codeVerifier:n.codeVerifier,redirectURI:n.redirectURI,additionalParams:n.additionalParams})},validateAuthorizationCode:async({code:n,codeVerifier:o,redirectURI:i})=>K({code:n,codeVerifier:o,authentication:"basic",redirectURI:i,options:t,tokenEndpoint:"https://api.x.com/2/oauth2/token"}),refreshAccessToken:t.refreshAccessToken?t.refreshAccessToken:async(n)=>F({refreshToken:n,options:{clientId:t.clientId,clientKey:t.clientKey,clientSecret:t.clientSecret},authentication:"basic",tokenEndpoint:"https://api.x.com/2/oauth2/token"}),async getUserInfo(n){if(t.getUserInfo)return t.getUserInfo(n);let{data:o,error:i}=await Me("https://api.x.com/2/users/me?user.fields=profile_image_url",{method:"GET",headers:{Authorization:`Bearer ${n.accessToken}`}});if(i)return null;let{data:s,error:a}=await Me("https://api.x.com/2/users/me?user.fields=confirmed_email",{method:"GET",headers:{Authorization:`Bearer ${n.accessToken}`}}),c=!1;if(!a&&s?.data?.confirmed_email)o.data.email=s.data.confirmed_email,c=!0;let d=await t.mapProfileToUser?.(o);return{user:{name:o.data.name,email:o.data.email||it({identifier:o.data.id,namespace:"twitter"}),image:o.data.profile_image_url,emailVerified:c,...d},data:o}},options:t});var Hl=(t)=>({id:"vercel",name:"Vercel",accountSubject:({profile:r})=>r.sub,createAuthorizationURL({state:r,scopes:n,codeVerifier:o,redirectURI:i,additionalParams:s}){if(!o)throw new te("codeVerifier is required for Vercel");let a=void 0;if(t.scope!==void 0||n!==void 0){if(a=[],t.scope)a.push(...t.scope);if(n)a.push(...n)}return V({id:"vercel",options:t,authorizationEndpoint:"https://vercel.com/oauth/authorize",scopes:a,state:r,codeVerifier:o,redirectURI:i,additionalParams:s})},validateAuthorizationCode:async({code:r,codeVerifier:n,redirectURI:o})=>K({code:r,codeVerifier:n,redirectURI:o,options:t,tokenEndpoint:"https://api.vercel.com/login/oauth/token"}),async getUserInfo(r){if(t.getUserInfo)return t.getUserInfo(r);let{data:n,error:o}=await Me("https://api.vercel.com/login/oauth/userinfo",{headers:{Authorization:`Bearer ${r.accessToken}`}});if(o||!n)return null;let i=await t.mapProfileToUser?.(n);return{user:{name:n.name??n.preferred_username??"",email:n.email,image:n.picture,emailVerified:n.email_verified??!1,...i},data:n}},options:t});var Vl=(t)=>({id:"vk",name:"VK",accountSubject:({profile:n})=>n.user.user_id,async createAuthorizationURL({state:n,scopes:o,codeVerifier:i,redirectURI:s,additionalParams:a}){let c=t.disableDefaultScope?[]:["email","phone"];if(t.scope)c.push(...t.scope);if(o)c.push(...o);return V({id:"vk",options:t,authorizationEndpoint:"https://id.vk.com/authorize",scopes:c,state:n,redirectURI:s,codeVerifier:i,additionalParams:a})},validateAuthorizationCode:async({code:n,codeVerifier:o,redirectURI:i,deviceId:s})=>K({code:n,codeVerifier:o,redirectURI:t.redirectURI||i,options:t,deviceId:s,tokenEndpoint:"https://id.vk.com/oauth2/auth"}),refreshAccessToken:t.refreshAccessToken?t.refreshAccessToken:async(n)=>F({refreshToken:n,options:{clientId:t.clientId,clientKey:t.clientKey,clientSecret:t.clientSecret},tokenEndpoint:"https://id.vk.com/oauth2/auth"}),async getUserInfo(n){if(t.getUserInfo)return t.getUserInfo(n);if(!n.accessToken)return null;let{data:o,error:i}=await Me("https://id.vk.com/oauth2/user_info",{method:"POST",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:new URLSearchParams({access_token:n.accessToken,client_id:t.clientId}).toString()});if(i)return null;let s=await t.mapProfileToUser?.(o);if(!o.user.email&&!s?.email)return null;return{user:{first_name:o.user.first_name,last_name:o.user.last_name,email:o.user.email,image:o.user.avatar,emailVerified:!1,birthday:o.user.birthday,sex:o.user.sex,name:`${o.user.first_name} ${o.user.last_name}`,...s},data:o}},options:t});var Fl=(t)=>({id:"wechat",name:"WeChat",accountSubject:({profile:r})=>r.unionid||r.openid,createAuthorizationURL({state:r,scopes:n,redirectURI:o,additionalParams:i}){let s=t.disableDefaultScope?[]:["snsapi_login"];t.scope&&s.push(...t.scope),n&&s.push(...n);let a=new URL("https://open.weixin.qq.com/connect/qrconnect");if(a.searchParams.set("scope",s.join(",")),a.searchParams.set("response_type","code"),a.searchParams.set("appid",t.clientId),a.searchParams.set("redirect_uri",t.redirectURI||o),a.searchParams.set("state",r),a.searchParams.set("lang",t.lang||"cn"),i)for(let[c,d]of Object.entries(i)){if(Ft.has(c))continue;if(c==="appid")continue;a.searchParams.set(c,d)}return a.hash="wechat_redirect",a},validateAuthorizationCode:async({code:r})=>{let{data:n,error:o}=await Me("https://api.weixin.qq.com/sns/oauth2/access_token?"+new URLSearchParams({appid:t.clientId,secret:t.clientSecret,code:r,grant_type:"authorization_code"}).toString(),{method:"GET"});if(o||!n||n.errcode)throw Error(`Failed to validate authorization code: ${n?.errmsg||o?.message||"Unknown error"}`);return{tokenType:"Bearer",accessToken:n.access_token,refreshToken:n.refresh_token,accessTokenExpiresAt:new Date(Date.now()+n.expires_in*1000),scopes:n.scope.split(","),openid:n.openid,unionid:n.unionid}},refreshAccessToken:t.refreshAccessToken?t.refreshAccessToken:async(r)=>{let{data:n,error:o}=await Me("https://api.weixin.qq.com/sns/oauth2/refresh_token?"+new URLSearchParams({appid:t.clientId,grant_type:"refresh_token",refresh_token:r}).toString(),{method:"GET"});if(o||!n||n.errcode)throw Error(`Failed to refresh access token: ${n?.errmsg||o?.message||"Unknown error"}`);return{tokenType:"Bearer",accessToken:n.access_token,refreshToken:n.refresh_token,accessTokenExpiresAt:new Date(Date.now()+n.expires_in*1000),scopes:n.scope.split(",")}},async getUserInfo(r){if(t.getUserInfo)return t.getUserInfo(r);let n=r.openid;if(!n)return null;let{data:o,error:i}=await Me("https://api.weixin.qq.com/sns/userinfo?"+new URLSearchParams({access_token:r.accessToken||"",openid:n,lang:"zh_CN"}).toString(),{method:"GET"});if(i||!o||o.errcode)return null;let s=await t.mapProfileToUser?.(o),a=o.unionid||o.openid||n;return{user:{name:o.nickname,email:o.email||it({identifier:a,namespace:"wechat"}),image:o.headimgurl,emailVerified:!1,...s},data:o}},options:t});var Kl=(t)=>{let r={pkce:!0,...t};return{id:"zoom",name:"Zoom",accountSubject:({profile:n})=>n.id,createAuthorizationURL:async({state:n,redirectURI:o,codeVerifier:i,additionalParams:s})=>V({id:"zoom",options:r,authorizationEndpoint:"https://zoom.us/oauth/authorize",state:n,redirectURI:o,codeVerifier:r.pkce?i:void 0,additionalParams:s}),validateAuthorizationCode:async({code:n,redirectURI:o,codeVerifier:i})=>K({code:n,redirectURI:r.redirectURI||o,codeVerifier:i,options:r,tokenEndpoint:"https://zoom.us/oauth/token",authentication:"post"}),refreshAccessToken:r.refreshAccessToken?r.refreshAccessToken:async(n)=>F({refreshToken:n,options:{clientId:r.clientId,clientKey:r.clientKey,clientSecret:r.clientSecret},tokenEndpoint:"https://zoom.us/oauth/token"}),async getUserInfo(n){if(r.getUserInfo)return r.getUserInfo(n);let{data:o,error:i}=await Me("https://api.zoom.us/v2/users/me",{headers:{authorization:`Bearer ${n.accessToken}`}});if(i)return null;let s=await r.mapProfileToUser?.(o);return{user:{name:o.display_name,image:o.pic_url,email:o.email,emailVerified:Boolean(o.verified),...s},data:{...o}}}}};var Em={apple:xu,atlassian:Mu,cloudflare:Wu,cognito:Ju,discord:Xu,facebook:rl,figma:nl,github:ol,microsoft:wl,google:al,huggingface:dl,slack:ql,spotify:jl,twitch:$l,twitter:Ml,dropbox:el,kick:ll,linear:pl,linkedin:hl,gitlab:il,tiktok:Bl,reddit:Pl,roblox:zl,salesforce:Nl,vk:Vl,zoom:Kl,notion:Tl,kakao:ul,naver:Rl,line:fl,paybin:Il,paypal:Ul,polar:Ol,railway:Ll,vercel:Hl,wechat:Fl},Py=Object.keys(Em),Uo=T(Py).or(e());function Wl(t){if(!t)return[];return t.split(",").map((r)=>r.trim()).filter(Boolean)}var Jl=Pe("/list-accounts",{method:"GET",use:[$r],metadata:{openapi:{operationId:"listUserAccounts",description:"List all accounts linked to the user",responses:{"200":{description:"Success",content:{"application/json":{schema:{type:"array",items:{type:"object",properties:{id:{type:"string"},providerId:{type:"string"},createdAt:{type:"string",format:"date-time"},updatedAt:{type:"string",format:"date-time"},accountId:{type:"string"},userId:{type:"string"},scopes:{type:"array",items:{type:"string"}}},required:["id","providerId","createdAt","updatedAt","accountId","userId","scopes"]}}}}}}}}},async(t)=>{let r=t.context.session,n=await t.context.internalAdapter.findAccounts(r.user.id);return t.json(n.map((o)=>{let{scope:i,...s}=Vn(t.context.options,o);return{...s,scopes:Wl(i)}}))}),Ql=Pe("/link-social",{method:"POST",requireHeaders:!0,body:l({callbackURL:e().meta({description:"The URL to redirect to after the user has signed in"}).optional(),provider:Uo,idToken:l({token:e(),nonce:e().optional(),accessToken:e().optional(),refreshToken:e().optional()}).optional(),requestSignUp:E().optional(),scopes:A(e()).meta({description:"Additional scopes to request from the provider"}).optional(),errorCallbackURL:e().meta({description:"The URL to redirect to if there is an error during the link process"}).optional(),disableRedirect:E().meta({description:"Disable automatic redirection to the provider. Useful for handling the redirection yourself"}).optional(),loginHint:e().meta({description:"The login hint to use for the authorization code request"}).optional(),additionalParams:cn,additionalData:k(e(),N()).optional()}),use:[$r],metadata:{openapi:{description:"Link a social account to the user",operationId:"linkSocialAccount",responses:{"200":{description:"Success",content:{"application/json":{schema:{type:"object",properties:{url:{type:"string",description:"The authorization URL to redirect the user to"},redirect:{type:"boolean",description:"Indicates if the user should be redirected to the authorization URL"},status:{type:"boolean"}},required:["redirect"]}}}}}}}},async(t)=>{let r=t.context.session,n=await tt(t.context.socialProviders,{value:t.body.provider});if(!n)throw t.context.logger.error("Provider not found. Make sure to add the provider in your auth config",{provider:t.body.provider}),U.from("NOT_FOUND",Ae.PROVIDER_NOT_FOUND);if(t.body.idToken){if(!_n(n))throw t.context.logger.error("Provider does not support id token verification",{provider:t.body.provider}),U.from("NOT_FOUND",Ae.ID_TOKEN_NOT_SUPPORTED);let{token:a,nonce:c}=t.body.idToken;if(!await An(n,a,c,t))throw t.context.logger.warn("Invalid id token",{provider:t.body.provider}),U.from("UNAUTHORIZED",Ae.INVALID_TOKEN);let d=await n.getUserInfo({idToken:a,accessToken:t.body.idToken.accessToken,refreshToken:t.body.idToken.refreshToken});if(!d||!d?.user)throw t.context.logger.error("Failed to get user info",{provider:t.body.provider}),U.from("UNAUTHORIZED",Ae.FAILED_TO_GET_USER_INFO);if(!d.user.email)throw t.context.logger.error(wr(t.body.provider,{source:"id_token"}),{provider:t.body.provider}),U.from("UNAUTHORIZED",Ae.USER_EMAIL_NOT_FOUND);let u=await mo(n,{idToken:a,accessToken:t.body.idToken.accessToken,refreshToken:t.body.idToken.refreshToken},d.data),f=await t.context.internalAdapter.findAccountByKey(u);if(f?.userId===r.user.id){let p=Object.fromEntries(Object.entries({providerId:n.id,accessToken:await me(t.body.idToken.accessToken,t.context),idToken:a,refreshToken:await me(t.body.idToken.refreshToken,t.context)}).filter(([h,m])=>m!==void 0));return await t.context.internalAdapter.updateAccount(f.id,p),await En(t,r.user.id,d.user),t.json({url:"",status:!0,redirect:!1})}if(f)throw U.from("CONFLICT",Ae.SOCIAL_ACCOUNT_ALREADY_LINKED);if(!t.context.trustedProviders.includes(n.id)&&!d.user.emailVerified||t.context.options.account?.accountLinking?.enabled===!1)throw U.from("UNAUTHORIZED",{message:"Account not linked - linking not allowed",code:"LINKING_NOT_ALLOWED"});if(d.user.email?.toLowerCase()!==r.user.email.toLowerCase()&&t.context.options.account?.accountLinking?.allowDifferentEmails!==!0)throw U.from("UNAUTHORIZED",{message:"Account not linked - different emails not allowed",code:"LINKING_DIFFERENT_EMAILS_NOT_ALLOWED"});try{await t.context.internalAdapter.createAccount({userId:r.user.id,...u,accessToken:await me(t.body.idToken.accessToken,t.context),idToken:a,refreshToken:await me(t.body.idToken.refreshToken,t.context)})}catch{throw U.from("EXPECTATION_FAILED",{message:"Account not linked - unable to create account",code:"LINKING_FAILED"})}return await En(t,r.user.id,d.user),t.json({url:"",status:!0,redirect:!1})}let o=kr(n),i=await Er(t,{link:{userId:r.user.id,email:r.user.email},additionalData:t.body.additionalData,idTokenNonce:o}),s=await n.createAuthorizationURL({state:i.state,codeVerifier:i.codeVerifier,idTokenNonce:o,redirectURI:`${t.context.baseURL}${Rt(n)}`,scopes:t.body.scopes,loginHint:t.body.loginHint,additionalParams:t.body.additionalParams});if(!t.body.disableRedirect)t.setHeader("Location",s.toString());return t.json({url:s.toString(),redirect:!t.body.disableRedirect})}),Gl=Pe("/unlink-account",{method:"POST",body:l({accountId:e().meta({description:"The Better Auth account ID to unlink"})}),use:[po],metadata:{openapi:{description:"Unlink an account",responses:{"200":{description:"Success",content:{"application/json":{schema:{type:"object",properties:{status:{type:"boolean"}}}}}}}}}},async(t)=>{let{accountId:r}=t.body,n=await t.context.internalAdapter.findAccounts(t.context.session.user.id);if(n.length===1&&!t.context.options.account?.accountLinking?.allowUnlinkingAll)throw U.from("BAD_REQUEST",Ae.FAILED_TO_UNLINK_LAST_ACCOUNT);let o=n.find((i)=>i.id===r);if(!o)throw U.from("BAD_REQUEST",Ae.ACCOUNT_NOT_FOUND);return await t.context.internalAdapter.deleteAccount(o.id),t.json({status:!0})});async function Ns(t,r){let n=await ee(t,{disableCookieCache:St(t)});if(!n&&(t.request||t.headers))throw t.error("UNAUTHORIZED");let o=n?.user?.id||r;if(!o)throw U.from("BAD_REQUEST",{message:"Either userId or session is required",code:"USER_ID_OR_SESSION_REQUIRED"});return o}var qs=D([Lm({accountId:e().meta({description:"The Better Auth account ID"}),userId:e().meta({description:"The user ID associated with the account"}).optional()}),Lm({useAccountCookie:v(!0).meta({description:"Select the current OAuth account from its signed cookie"}),userId:e().meta({description:"The user ID associated with the account"}).optional()})]);function Zl(t,r,{resolvedUserId:n,selection:o}){return(!qn(t.context.options)||r.userId===n)&&("accountId"in o?r.id===o.accountId:!0)}async function js(t,{resolvedUserId:r,selection:n}){if("accountId"in n){let o=(await t.context.internalAdapter.findAccounts(r)).find((i)=>i.id===n.accountId);if(o)return{account:o,accountCookie:null}}else if(t.context.options.account?.storeAccountCookie){let o=await io(t);if(o&&Zl(t,o,{resolvedUserId:r,selection:n}))return{account:o,accountCookie:o}}throw U.from("BAD_REQUEST",Ae.ACCOUNT_NOT_FOUND)}async function Yl(t,{resolvedUserId:r,selection:n,account:o}){let i=o??(await js(t,{resolvedUserId:r,selection:n})).account;if(!Zl(t,i,{resolvedUserId:r,selection:n}))throw U.from("BAD_REQUEST",Ae.ACCOUNT_NOT_FOUND);let s=await tt(t.context.socialProviders,{value:i.providerId});if(!s)throw U.from("BAD_REQUEST",{message:`Provider ${i.providerId} is not supported.`,code:"PROVIDER_NOT_SUPPORTED"});try{let a=null,c=i.accessTokenExpiresAt&&new Date(i.accessTokenExpiresAt).getTime()-Date.now()<5000;if(i.refreshToken&&c&&s.refreshAccessToken){let u=await _o(i.refreshToken,t.context);a=await s.refreshAccessToken(u,t);let f={accessToken:await me(a?.accessToken,t.context),accessTokenExpiresAt:a?.accessTokenExpiresAt,refreshToken:a?.refreshToken?await me(a.refreshToken,t.context):i.refreshToken,refreshTokenExpiresAt:a?.refreshTokenExpiresAt??i.refreshTokenExpiresAt,idToken:a?.idToken||i.idToken},p=null;if(i.id)p=await t.context.internalAdapter.updateAccount(i.id,f);if(t.context.options.account?.storeAccountCookie)await ft(t,{...i,...p??f})}let d=(()=>{if(a?.accessTokenExpiresAt){if(typeof a.accessTokenExpiresAt==="string")return new Date(a.accessTokenExpiresAt);return a.accessTokenExpiresAt}if(i.accessTokenExpiresAt){if(typeof i.accessTokenExpiresAt==="string")return new Date(i.accessTokenExpiresAt);return i.accessTokenExpiresAt}})();return{accessToken:a?.accessToken??await _o(i.accessToken??"",t.context),accessTokenExpiresAt:d,scopes:Wl(i.scope),idToken:a?.idToken??i.idToken??void 0}}catch(a){throw U.from("BAD_REQUEST",{message:"Failed to get a valid access token",code:"FAILED_TO_GET_ACCESS_TOKEN"})}}var Xl=Pe("/get-access-token",{method:"POST",body:qs,metadata:{openapi:{description:"Get a valid access token, doing a refresh if needed",responses:{200:{description:"A Valid access token",content:{"application/json":{schema:{type:"object",properties:{tokenType:{type:"string"},idToken:{type:"string"},accessToken:{type:"string"},accessTokenExpiresAt:{type:"string",format:"date-time"}}}}}},400:{description:"Invalid refresh token or provider configuration"}}}}},async(t)=>{let{userId:r}=t.body,n=await Yl(t,{resolvedUserId:await Ns(t,r),selection:t.body});return t.json(n)}),ef=Pe("/refresh-token",{method:"POST",body:qs,metadata:{openapi:{description:"Refresh the access token using a refresh token",responses:{200:{description:"Access token refreshed successfully",content:{"application/json":{schema:{type:"object",properties:{tokenType:{type:"string"},idToken:{type:"string"},accessToken:{type:"string"},refreshToken:{type:"string"},accessTokenExpiresAt:{type:"string",format:"date-time"},refreshTokenExpiresAt:{type:"string",format:"date-time"}}}}}},400:{description:"Invalid refresh token or provider configuration"}}}}},async(t)=>{let{userId:r}=t.body,{account:n,accountCookie:o}=await js(t,{resolvedUserId:await Ns(t,r),selection:t.body}),i=await tt(t.context.socialProviders,{value:n.providerId});if(!i)throw U.from("BAD_REQUEST",{message:`Provider ${n.providerId} is not supported.`,code:"PROVIDER_NOT_SUPPORTED"});if(!i.refreshAccessToken)throw U.from("BAD_REQUEST",{message:`Provider ${n.providerId} does not support token refreshing.`,code:"TOKEN_REFRESH_NOT_SUPPORTED"});let s=n.refreshToken??void 0;if(!s)throw U.from("BAD_REQUEST",{message:"Refresh token not found",code:"REFRESH_TOKEN_NOT_FOUND"});try{let a=await _o(s,t.context),c=await i.refreshAccessToken(a,t),d=c.refreshToken?await me(c.refreshToken,t.context):s,u=c.refreshTokenExpiresAt??n.refreshTokenExpiresAt,f={accessToken:await me(c.accessToken,t.context),refreshToken:d,accessTokenExpiresAt:c.accessTokenExpiresAt,refreshTokenExpiresAt:u,idToken:c.idToken||n.idToken},p=null;if(n.id)p=await t.context.internalAdapter.updateAccount(n.id,f);if(o?.id===n.id&&t.context.options.account?.storeAccountCookie)await ft(t,{...o,...p??f});let h=p?.scope??n.scope;return t.json({accessToken:c.accessToken,refreshToken:c.refreshToken??a,accessTokenExpiresAt:c.accessTokenExpiresAt,refreshTokenExpiresAt:u,scope:h,idToken:c.idToken||n.idToken,providerId:n.providerId,accountId:n.id})}catch(a){throw U.from("BAD_REQUEST",{message:"Failed to refresh access token",code:"FAILED_TO_REFRESH_ACCESS_TOKEN"})}}),tf=Pe("/account-info",{method:"GET",metadata:{openapi:{description:"Get the account info provided by the provider",responses:{"200":{description:"Success",content:{"application/json":{schema:{type:"object",properties:{user:{type:"object",properties:{name:{type:"string"},email:{type:"string",nullable:!0},image:{type:"string"},emailVerified:{type:"boolean"}},required:["emailVerified"]},account:{type:"object",properties:{id:{type:"string"},providerId:{type:"string"},accountId:{type:"string"}},required:["id","providerId","accountId"],additionalProperties:!1},data:{type:"object",properties:{},additionalProperties:!0}},required:["user","data","account"],additionalProperties:!1}}}}}}},query:qs},async(t)=>{let{userId:r}=t.query,n=await Ns(t,r),{account:o}=await js(t,{resolvedUserId:n,selection:t.query}),i=await tt(t.context.socialProviders,{value:o.providerId});if(!i)throw U.from("BAD_REQUEST",{message:"Account is not associated with a configured social provider.",code:"PROVIDER_NOT_CONFIGURED"});let s=await Yl(t,{resolvedUserId:n,selection:t.query,account:o});if(!s.accessToken)throw U.from("BAD_REQUEST",{message:"Access token not found",code:"ACCESS_TOKEN_NOT_FOUND"});let a=await i.getUserInfo({...s,accessToken:s.accessToken});if(!a)throw U.from("UNAUTHORIZED",Ae.FAILED_TO_GET_USER_INFO);return t.json({...a,account:{id:o.id,providerId:o.providerId,accountId:o.accountId}})});async function rf(t,r,n){if(n.iss&&r.issuer&&n.iss!==r.issuer)return t.context.logger.error("OAuth issuer mismatch",{expected:r.issuer,received:n.iss}),{error:he.ISSUER_MISMATCH};if(r.requiresIdTokenNonce&&!n.idTokenNonce)return t.context.logger.error("OAuth id_token nonce binding required but no expected nonce was found in state",{providerId:r.id}),{error:he.NONCE_BINDING_MISSING};let o;try{o=await r.validateAuthorizationCode({code:n.code,codeVerifier:n.codeVerifier,deviceId:n.deviceId,redirectURI:`${t.context.baseURL}${Rt(r)}`})}catch(a){return t.context.logger.error("Failed to validate authorization code",a),{error:he.INVALID_CODE}}if(!o)return{error:he.INVALID_CODE};let i=await r.getUserInfo({...o,expectedIdTokenNonce:n.idTokenNonce,user:Mr(n.user)??void 0});if(!i?.user)return t.context.logger.error("Unable to get user info"),{error:he.UNABLE_TO_GET_USER_INFO};let s=await ns(r,o,i.data).catch((a)=>(t.context.logger.error("Unable to derive provider account identity",{providerId:r.id,error:a}),null));if(!s)return{error:he.UNABLE_TO_GET_USER_INFO};return{tokens:o,userInfo:i.user,providerProfile:ho(i.data),accountKey:s}}var br={scope:"server"};var Gt=l({code:e().optional(),error:e().optional(),device_id:e().optional(),error_description:e().optional(),state:e().optional(),user:e().optional(),iss:e().optional()}),nf=Pe("/callback/:id",{method:["GET","POST"],operationId:"handleOAuthCallback",body:Gt.optional(),query:Gt.optional(),metadata:{...br,allowedMediaTypes:["application/x-www-form-urlencoded","application/json"]}},async(t)=>{let r,n=t.context.options.onAPIError?.errorURL||`${t.context.baseURL}/error`;if(t.method==="POST"){let q=t.body?Gt.parse(t.body):{},J=t.query?Gt.parse(t.query):{},Q=Gt.parse({...q,...J}),G=new URLSearchParams;for(let[Y,Z]of Object.entries(Q))if(Z!==void 0&&Z!==null)G.set(Y,String(Z));let M=`${t.context.baseURL}/callback/${t.params.id}?${G.toString()}`;throw t.redirect(M)}try{if(t.method==="GET")r=Gt.parse(t.query);else if(t.method==="POST")r=Gt.parse(t.body);else throw Error("Unsupported method")}catch(q){t.context.logger.error("INVALID_CALLBACK_REQUEST",q);let J=$e(n,new URLSearchParams({error:"invalid_callback_request"}));throw t.redirect(J)}let{code:o,error:i,state:s,error_description:a,device_id:c,user:d,iss:u}=r;if(s===void 0&&o){let q=await tt(t.context.socialProviders,{value:t.params.id});if(q?.allowIdpInitiated){let J=kr(q),{state:Q,codeVerifier:G}=await Er(t,{idTokenNonce:J}),M=await q.createAuthorizationURL({state:Q,codeVerifier:G,idTokenNonce:J,redirectURI:`${t.context.baseURL}${Rt(q)}`});throw t.redirect(M.toString())}}if(!s){t.context.logger.error("State not found",i);let q=$e(n,new URLSearchParams({error:"state_not_found"}));throw t.redirect(q)}let{codeVerifier:f,callbackURL:p,link:h,errorURL:m,newUserURL:w,requestSignUp:y,idTokenNonce:I}=await Pu(t);function R(q,J){let Q=m??n,G=new URLSearchParams({error:q});if(J)G.set("error_description",J);let M=$e(Q,G);throw t.redirect(M)}if(i)R(i,a);if(!o)throw t.context.logger.warn("Code not found"),R(he.NO_CODE);let b=await tt(t.context.socialProviders,{value:t.params.id});if(!b)throw t.context.logger.warn("OAuth provider not found",{providerId:t.params.id}),R(he.PROVIDER_NOT_FOUND);let O=await rf(t,b,{code:o,codeVerifier:f,iss:u,deviceId:c,user:d,idTokenNonce:I});if(O.error)throw R(O.error);let{tokens:g,userInfo:S,providerProfile:C,accountKey:z}=O,{accountId:L}=z;if(!p)throw t.context.logger.error("No callback URL found"),R(he.NO_CALLBACK_URL);let x={...z,...g,scope:g.scopes?.join(",")};if(h){let q=await Ou(t,{link:h,userInfo:S,account:x,profile:C,scopes:g.scopes});if(!q.linked)return R(q.error.code,q.error.message);throw t.redirect(p)}if(!S.email)return t.context.logger.error(wr(b.id)),R(he.EMAIL_NOT_FOUND);let P;try{P=await Io(t,{userInfo:{...S,id:L,email:S.email,name:S.name||""},account:x,callbackURL:p,disableSignUp:b.disableImplicitSignUp&&!y||b.options?.disableSignUp,overrideUserInfo:b.options?.overrideUserInfoOnSignIn,source:{method:"oauth",oauth:{providerId:b.id,profile:C}}})}catch(q){if(Br(q)&&q.body?.code)R(q.body.code,q.body.message);throw q}if(P.error)return t.context.logger.error(P.error.split(" ").join("_")),R(P.error.split(" ").join("_"));let{session:j,user:B}=P.data;await pe(t,{session:j,user:B});let H;try{H=(P.isRegister?w||p:p).toString()}catch{H=P.isRegister?w||p:p}throw t.redirect(H)});function of(t){return t.replace(/</g,"&lt;").replace(/>/g,"&gt;").replace(/"/g,"&quot;").replace(/'/g,"&#39;").replace(/&(?!amp;|lt;|gt;|quot;|#39;|#x[0-9a-fA-F]+;|#[0-9]+;)/g,"&amp;")}var xy=(t,r="Unknown",n=null)=>{let o=t.onAPIError?.customizeDefaultErrorPage;return`<!DOCTYPE html>
51
+ `})});if(i||!o?.data?.viewer)return null;let s=o.data.viewer,a=await t.mapProfileToUser?.(s);return{user:{name:o.data.viewer.name,email:o.data.viewer.email,image:o.data.viewer.avatarUrl,emailVerified:!1,...a},data:s}},options:t});var hl=(t)=>({id:"linkedin",name:"Linkedin",accountSubject:({profile:o})=>o.sub,createAuthorizationURL:async({state:o,scopes:i,redirectURI:s,loginHint:a,additionalParams:c})=>{let d=t.disableDefaultScope?[]:["profile","email","openid"];if(t.scope)d.push(...t.scope);if(i)d.push(...i);return await V({id:"linkedin",options:t,authorizationEndpoint:"https://www.linkedin.com/oauth/v2/authorization",scopes:d,state:o,loginHint:a,redirectURI:s,additionalParams:c})},validateAuthorizationCode:async({code:o,redirectURI:i})=>await K({code:o,redirectURI:i,options:t,tokenEndpoint:"https://www.linkedin.com/oauth/v2/accessToken"}),refreshAccessToken:t.refreshAccessToken?t.refreshAccessToken:async(o)=>F({refreshToken:o,options:{clientId:t.clientId,clientKey:t.clientKey,clientSecret:t.clientSecret},tokenEndpoint:"https://www.linkedin.com/oauth/v2/accessToken"}),async getUserInfo(o){if(t.getUserInfo)return t.getUserInfo(o);let{data:i,error:s}=await Me("https://api.linkedin.com/v2/userinfo",{method:"GET",headers:{Authorization:`Bearer ${o.accessToken}`}});if(s)return null;let a=await t.mapProfileToUser?.(i);return{user:{name:i.name,email:i.email,emailVerified:i.email_verified??!1,image:i.picture,...a},data:i}},options:t});var ml="9188040d-6c67-4c5b-b112-36a304b66dad",gl=(t)=>{let r=t.tenantId||"common",n=t.authority||"https://login.microsoftonline.com";while(n.endsWith("/"))n=n.slice(0,-1);let o=`${n}/${r}/oauth2/v2.0/authorize`,i=`${n}/${r}/oauth2/v2.0/token`;if(t.clientSecret&&t.clientAssertion)throw new te("Microsoft Entra ID clientAssertion cannot be combined with clientSecret");let s=t.clientAssertion?{method:"private_key_jwt",getClientAssertion:t.clientAssertion}:void 0;return{id:"microsoft",name:"Microsoft EntraID",accountSubject:({profile:a})=>a.oid,createAuthorizationURL(a){if(!Re(t.clientId))throw Ee.error("Client Id is required for Microsoft Entra ID. Make sure to provide it in the options."),new te("CLIENT_ID_AND_SECRET_REQUIRED");let c=t.disableDefaultScope?[]:["openid","profile","email","User.Read","offline_access"];if(t.scope)c.push(...t.scope);if(a.scopes)c.push(...a.scopes);return V({id:"microsoft",options:t,authorizationEndpoint:o,state:a.state,codeVerifier:a.codeVerifier,scopes:c,redirectURI:a.redirectURI,prompt:t.prompt,loginHint:a.loginHint,additionalParams:a.additionalParams})},validateAuthorizationCode({code:a,codeVerifier:c,redirectURI:d}){return K({code:a,codeVerifier:c,redirectURI:d,options:t,tokenEndpoint:i,tokenEndpointAuth:s})},idToken:{jwks:(a)=>kl(a.kid,r,n),algorithms:["RS256"],audience:t.clientId,maxTokenAge:"1h",issuer:r!=="common"&&r!=="organizations"&&r!=="consumers"?`${n}/${r}/v2.0`:void 0,verifyClaims:(a)=>{let c=a.tid;if(typeof c!=="string"||a.iss!==`${n}/${c}/v2.0`)return!1;if(r==="organizations"&&c===ml)return!1;if(r==="consumers"&&c!==ml)return!1;return!0}},async getUserInfo(a){if(t.getUserInfo)return t.getUserInfo(a);if(!a.idToken)return null;let c=en(a.idToken);if(typeof c.oid!=="string"||c.oid.trim().length===0)return Ee.error("Microsoft Entra ID token did not include a valid oid claim; unable to resolve a stable account identifier."),null;let d=t.profilePhotoSize||48;if(!t.disableProfilePhoto&&a.accessToken)await Me(`https://graph.microsoft.com/v1.0/me/photos/${d}x${d}/$value`,{headers:{Authorization:`Bearer ${a.accessToken}`},async onResponse(p){if(!p.response.ok)return;try{let h=await p.response.clone().arrayBuffer();c.picture=`data:image/jpeg;base64, ${To.encode(h)}`}catch(h){Ee.error(h&&typeof h==="object"&&"name"in h?h.name:"",h)}}});let u=await t.mapProfileToUser?.(c),f=c.email_verified!==void 0?c.email_verified:c.email&&(c.verified_primary_email?.includes(c.email)||c.verified_secondary_email?.includes(c.email))?!0:!1;return{user:{name:c.name,email:c.email,image:c.picture,emailVerified:f,...u},data:c}},refreshAccessToken:t.refreshAccessToken?t.refreshAccessToken:async(a)=>{let c=t.disableDefaultScope?[]:["openid","profile","email","User.Read","offline_access"];if(t.scope)c.push(...t.scope);return F({refreshToken:a,options:{clientId:t.clientId,clientSecret:t.clientSecret},extraParams:{scope:c.join(" ")},tokenEndpoint:i,tokenEndpointAuth:s})},options:t}},kl=async(t,r,n)=>{let{data:o}=await Me(`${n}/${r}/discovery/v2.0/keys`);if(!o?.keys)throw new U("BAD_REQUEST",{message:"Keys not found"});let i=o.keys.find((s)=>s.kid===t);if(!i)throw Error(`JWK with kid ${t} not found`);return await In(i,i.alg??"RS256")};var El=(t)=>({id:"naver",name:"Naver",accountSubject:({profile:n})=>n.response.id,createAuthorizationURL({state:n,scopes:o,redirectURI:i,additionalParams:s}){let a=t.disableDefaultScope?[]:["profile","email"];if(t.scope)a.push(...t.scope);if(o)a.push(...o);return V({id:"naver",options:t,authorizationEndpoint:"https://nid.naver.com/oauth2.0/authorize",scopes:a,state:n,redirectURI:i,additionalParams:s})},validateAuthorizationCode:async({code:n,redirectURI:o})=>K({code:n,redirectURI:o,options:t,tokenEndpoint:"https://nid.naver.com/oauth2.0/token"}),refreshAccessToken:t.refreshAccessToken?t.refreshAccessToken:async(n)=>F({refreshToken:n,options:{clientId:t.clientId,clientKey:t.clientKey,clientSecret:t.clientSecret},tokenEndpoint:"https://nid.naver.com/oauth2.0/token"}),async getUserInfo(n){if(t.getUserInfo)return t.getUserInfo(n);let{data:o,error:i}=await Me("https://openapi.naver.com/v1/nid/me",{headers:{Authorization:`Bearer ${n.accessToken}`}});if(i||!o||o.resultcode!=="00")return null;let s=await t.mapProfileToUser?.(o),a=o.response||{};return{user:{name:a.name||a.nickname||"",email:a.email,image:a.profile_image,emailVerified:!1,...s},data:o}},options:t});var Rl=(t)=>({id:"notion",name:"Notion",accountSubject:({profile:n})=>n.id,createAuthorizationURL({state:n,scopes:o,loginHint:i,redirectURI:s,additionalParams:a}){let c=t.disableDefaultScope?[]:[];if(t.scope)c.push(...t.scope);if(o)c.push(...o);return V({id:"notion",options:t,authorizationEndpoint:"https://api.notion.com/v1/oauth/authorize",scopes:c,state:n,redirectURI:s,loginHint:i,additionalParams:{...a??{},owner:"user"}})},validateAuthorizationCode:async({code:n,redirectURI:o})=>K({code:n,redirectURI:o,options:t,tokenEndpoint:"https://api.notion.com/v1/oauth/token",authentication:"basic"}),refreshAccessToken:t.refreshAccessToken?t.refreshAccessToken:async(n)=>F({refreshToken:n,options:{clientId:t.clientId,clientKey:t.clientKey,clientSecret:t.clientSecret},tokenEndpoint:"https://api.notion.com/v1/oauth/token"}),async getUserInfo(n){if(t.getUserInfo)return t.getUserInfo(n);let{data:o,error:i}=await Me("https://api.notion.com/v1/users/me",{headers:{Authorization:`Bearer ${n.accessToken}`,"Notion-Version":"2022-06-28"}});if(i||!o)return null;let s=o.bot?.owner?.user;if(!s)return null;let a=await t.mapProfileToUser?.(s);return{user:{name:s.name||"",email:s.person?.email||null,image:s.avatar_url,emailVerified:!1,...a},data:s}},options:t});var Tl=(t)=>{let r=t.issuer||"https://idp.paybin.io",n=`${r}/oauth2/authorize`,o=`${r}/oauth2/token`;return{id:"paybin",name:"Paybin",accountSubject:({profile:i})=>i.sub,async createAuthorizationURL({state:i,scopes:s,codeVerifier:a,redirectURI:c,loginHint:d,additionalParams:u}){if(!t.clientId||!t.clientSecret)throw Ee.error("Client Id and Client Secret is required for Paybin. Make sure to provide them in the options."),new te("CLIENT_ID_AND_SECRET_REQUIRED");if(!a)throw new te("codeVerifier is required for Paybin");let f=t.disableDefaultScope?[]:["openid","email","profile"];if(t.scope)f.push(...t.scope);if(s)f.push(...s);return await V({id:"paybin",options:t,authorizationEndpoint:n,scopes:f,state:i,codeVerifier:a,redirectURI:c,prompt:t.prompt,loginHint:d,additionalParams:u})},validateAuthorizationCode:async({code:i,codeVerifier:s,redirectURI:a})=>K({code:i,codeVerifier:s,redirectURI:a,options:t,tokenEndpoint:o}),refreshAccessToken:t.refreshAccessToken?t.refreshAccessToken:async(i)=>F({refreshToken:i,options:{clientId:t.clientId,clientKey:t.clientKey,clientSecret:t.clientSecret},tokenEndpoint:o}),async getUserInfo(i){if(t.getUserInfo)return t.getUserInfo(i);if(!i.idToken)return null;let s=en(i.idToken),a=await t.mapProfileToUser?.(s);return{user:{name:s.name||s.preferred_username||"",email:s.email,image:s.picture,emailVerified:s.email_verified||!1,...a},data:s}},options:t}};var Ul=(t)=>{let r=(t.environment||"sandbox")==="sandbox",n=r?"https://www.sandbox.paypal.com/signin/authorize":"https://www.paypal.com/signin/authorize",o=r?"https://api-m.sandbox.paypal.com/v1/oauth2/token":"https://api-m.paypal.com/v1/oauth2/token",i=r?"https://api-m.sandbox.paypal.com/v1/identity/oauth2/userinfo":"https://api-m.paypal.com/v1/identity/oauth2/userinfo",s={clientId:t.clientId,clientSecret:t.clientSecret},a={method:"client_secret_basic"};return{id:"paypal",name:"PayPal",accountSubject:({profile:c})=>c.user_id,async createAuthorizationURL({state:c,codeVerifier:d,redirectURI:u,additionalParams:f}){if(!t.clientId||!t.clientSecret)throw Ee.error("Client Id and Client Secret is required for PayPal. Make sure to provide them in the options."),new te("CLIENT_ID_AND_SECRET_REQUIRED");return await V({id:"paypal",options:t,authorizationEndpoint:n,scopes:[],state:c,codeVerifier:d,redirectURI:u,prompt:t.prompt,additionalParams:f})},validateAuthorizationCode:async({code:c,codeVerifier:d,redirectURI:u})=>{try{return await K({code:c,codeVerifier:d,redirectURI:t.redirectURI||u,options:s,tokenEndpoint:o,tokenEndpointAuth:a})}catch(f){throw Ee.error("PayPal token exchange failed:",f),new te("FAILED_TO_GET_ACCESS_TOKEN")}},refreshAccessToken:t.refreshAccessToken?t.refreshAccessToken:async(c)=>{try{return await F({refreshToken:c,options:s,tokenEndpoint:o,tokenEndpointAuth:a})}catch(d){throw Ee.error("PayPal token refresh failed:",d),new te("FAILED_TO_REFRESH_ACCESS_TOKEN")}},async getUserInfo(c){if(t.getUserInfo)return t.getUserInfo(c);if(!c.accessToken)return Ee.error("Access token is required to fetch PayPal user info"),null;try{let d=await Me(`${i}?schema=paypalv1.1`,{headers:{Authorization:`Bearer ${c.accessToken}`,Accept:"application/json"}});if(!d.data)return Ee.error("Failed to fetch user info from PayPal"),null;let u=d.data;if(c.idToken){let p;try{p=en(c.idToken).sub}catch(m){return Ee.error("Failed to decode PayPal ID token:",m),null}let h=u.sub??u.user_id;if(!p||h!==p)return Ee.error("PayPal user info subject does not match ID token subject"),null}let f=await t.mapProfileToUser?.(u);return{user:{name:u.name,email:u.email,image:u.picture,emailVerified:u.email_verified,...f},data:u}}catch(d){return Ee.error("Failed to fetch user info from PayPal:",d),null}},options:t}};var Ol=(t)=>({id:"polar",name:"Polar",accountSubject:({profile:n})=>n.id,createAuthorizationURL({state:n,scopes:o,codeVerifier:i,redirectURI:s,additionalParams:a}){let c=t.disableDefaultScope?[]:["openid","profile","email"];if(t.scope)c.push(...t.scope);if(o)c.push(...o);return V({id:"polar",options:t,authorizationEndpoint:"https://polar.sh/oauth2/authorize",scopes:c,state:n,codeVerifier:i,redirectURI:s,prompt:t.prompt,additionalParams:a})},validateAuthorizationCode:async({code:n,codeVerifier:o,redirectURI:i})=>K({code:n,codeVerifier:o,redirectURI:i,options:t,tokenEndpoint:"https://api.polar.sh/v1/oauth2/token"}),refreshAccessToken:t.refreshAccessToken?t.refreshAccessToken:async(n)=>F({refreshToken:n,options:{clientId:t.clientId,clientKey:t.clientKey,clientSecret:t.clientSecret},tokenEndpoint:"https://api.polar.sh/v1/oauth2/token"}),async getUserInfo(n){if(t.getUserInfo)return t.getUserInfo(n);let{data:o,error:i}=await Me("https://api.polar.sh/v1/oauth2/userinfo",{headers:{Authorization:`Bearer ${n.accessToken}`}});if(i)return null;let s=await t.mapProfileToUser?.(o);return{user:{name:o.public_name||o.username||"",email:o.email,image:o.avatar_url,emailVerified:o.email_verified??!1,...s},data:o}},options:t});var Oy="https://backboard.railway.com/oauth/auth",Dl="https://backboard.railway.com/oauth/token",Dy="https://backboard.railway.com/oauth/me",Ll=(t)=>({id:"railway",name:"Railway",accountSubject:({profile:r})=>r.sub,createAuthorizationURL({state:r,scopes:n,codeVerifier:o,redirectURI:i,additionalParams:s}){let a=t.disableDefaultScope?[]:["openid","email","profile"];if(t.scope)a.push(...t.scope);if(n)a.push(...n);return V({id:"railway",options:t,authorizationEndpoint:Oy,scopes:a,state:r,codeVerifier:o,redirectURI:i,additionalParams:s})},validateAuthorizationCode:async({code:r,codeVerifier:n,redirectURI:o})=>K({code:r,codeVerifier:n,redirectURI:o,options:t,tokenEndpoint:Dl,authentication:"basic"}),refreshAccessToken:t.refreshAccessToken?t.refreshAccessToken:async(r)=>F({refreshToken:r,options:{clientId:t.clientId,clientKey:t.clientKey,clientSecret:t.clientSecret},tokenEndpoint:Dl,authentication:"basic"}),async getUserInfo(r){if(t.getUserInfo)return t.getUserInfo(r);let{data:n,error:o}=await Me(Dy,{headers:{authorization:`Bearer ${r.accessToken}`}});if(o||!n)return null;let i=await t.mapProfileToUser?.(n);return{user:{name:n.name,email:n.email,image:n.picture,emailVerified:!1,...i},data:n}},options:t});var Ly="placeholder.invalid";function it({identifier:t,namespace:r}){let n=Tn().safeParse(`${t}@${r}.${Ly}`);if(!n.success)throw TypeError("Invalid placeholder email");return n.data}var Pl=(t)=>{let n={clientId:t.clientId,clientSecret:t.clientSecret},o={method:"client_secret_basic"};return{id:"reddit",name:"Reddit",accountSubject:({profile:i})=>i.id,createAuthorizationURL({state:i,scopes:s,redirectURI:a,additionalParams:c}){let d=t.disableDefaultScope?[]:["identity"];if(t.scope)d.push(...t.scope);if(s)d.push(...s);return V({id:"reddit",options:t,authorizationEndpoint:"https://www.reddit.com/api/v1/authorize",scopes:d,state:i,redirectURI:a,duration:t.duration,additionalParams:c})},validateAuthorizationCode:async({code:i,redirectURI:s})=>K({code:i,redirectURI:t.redirectURI||s,options:n,tokenEndpoint:"https://www.reddit.com/api/v1/access_token",tokenEndpointAuth:o,headers:{accept:"text/plain","user-agent":"better-auth"}}),refreshAccessToken:t.refreshAccessToken?t.refreshAccessToken:async(i)=>F({refreshToken:i,options:n,tokenEndpoint:"https://www.reddit.com/api/v1/access_token",tokenEndpointAuth:o}),async getUserInfo(i){if(t.getUserInfo)return t.getUserInfo(i);let{data:s,error:a}=await Me("https://oauth.reddit.com/api/v1/me",{headers:{Authorization:`Bearer ${i.accessToken}`,"User-Agent":"better-auth"}});if(a)return null;let c=await t.mapProfileToUser?.(s),d=c?.email||it({identifier:s.id,namespace:"reddit"});return{user:{name:s.name,image:s.icon_img?.split("?")[0],...c,email:d,emailVerified:c?.emailVerified??!1},data:s}},options:t}};var zl=(t)=>({id:"roblox",name:"Roblox",accountSubject:({profile:n})=>n.sub,createAuthorizationURL({state:n,scopes:o,redirectURI:i,additionalParams:s}){let a=t.disableDefaultScope?[]:["openid","profile"];if(t.scope)a.push(...t.scope);if(o)a.push(...o);return V({id:"roblox",options:t,authorizationEndpoint:"https://apis.roblox.com/oauth/v1/authorize",scopes:a,state:n,redirectURI:i,prompt:t.prompt||"select_account consent",additionalParams:s})},validateAuthorizationCode:async({code:n,redirectURI:o})=>K({code:n,redirectURI:t.redirectURI||o,options:t,tokenEndpoint:"https://apis.roblox.com/oauth/v1/token",authentication:"post"}),refreshAccessToken:t.refreshAccessToken?t.refreshAccessToken:async(n)=>F({refreshToken:n,options:{clientId:t.clientId,clientKey:t.clientKey,clientSecret:t.clientSecret},tokenEndpoint:"https://apis.roblox.com/oauth/v1/token"}),async getUserInfo(n){if(t.getUserInfo)return t.getUserInfo(n);let{data:o,error:i}=await Me("https://apis.roblox.com/oauth/v1/userinfo",{headers:{authorization:`Bearer ${n.accessToken}`}});if(i)return null;let s=await t.mapProfileToUser?.(o);return{user:{name:o.nickname||o.preferred_username||"",image:o.picture,email:it({identifier:o.sub,namespace:"roblox"}),emailVerified:!1,...s},data:{...o}}},options:t});var Nl=(t)=>{let r=(t.environment??"production")==="sandbox",n=t.loginUrl?`https://${t.loginUrl}/services/oauth2/authorize`:r?"https://test.salesforce.com/services/oauth2/authorize":"https://login.salesforce.com/services/oauth2/authorize",o=t.loginUrl?`https://${t.loginUrl}/services/oauth2/token`:r?"https://test.salesforce.com/services/oauth2/token":"https://login.salesforce.com/services/oauth2/token",i=t.loginUrl?`https://${t.loginUrl}/services/oauth2/userinfo`:r?"https://test.salesforce.com/services/oauth2/userinfo":"https://login.salesforce.com/services/oauth2/userinfo";return{id:"salesforce",name:"Salesforce",accountSubject:({profile:s})=>s.user_id,async createAuthorizationURL({state:s,scopes:a,codeVerifier:c,redirectURI:d,additionalParams:u}){if(!t.clientId||!t.clientSecret)throw Ee.error("Client Id and Client Secret are required for Salesforce. Make sure to provide them in the options."),new te("CLIENT_ID_AND_SECRET_REQUIRED");if(!c)throw new te("codeVerifier is required for Salesforce");let f=t.disableDefaultScope?[]:["openid","email","profile"];if(t.scope)f.push(...t.scope);if(a)f.push(...a);return V({id:"salesforce",options:t,authorizationEndpoint:n,scopes:f,state:s,codeVerifier:c,redirectURI:t.redirectURI||d,additionalParams:u})},validateAuthorizationCode:async({code:s,codeVerifier:a,redirectURI:c})=>K({code:s,codeVerifier:a,redirectURI:t.redirectURI||c,options:t,tokenEndpoint:o}),refreshAccessToken:t.refreshAccessToken?t.refreshAccessToken:async(s)=>F({refreshToken:s,options:{clientId:t.clientId,clientSecret:t.clientSecret},tokenEndpoint:o}),async getUserInfo(s){if(t.getUserInfo)return t.getUserInfo(s);try{let{data:a}=await Me(i,{headers:{Authorization:`Bearer ${s.accessToken}`}});if(!a)return Ee.error("Failed to fetch user info from Salesforce"),null;let c=await t.mapProfileToUser?.(a);return{user:{name:a.name,email:a.email,image:a.photos?.picture||a.photos?.thumbnail,emailVerified:a.email_verified??!1,...c},data:a}}catch(a){return Ee.error("Failed to fetch user info from Salesforce:",a),null}},options:t}};var ql=(t)=>({id:"slack",name:"Slack",accountSubject:({profile:n})=>n["https://slack.com/user_id"],createAuthorizationURL({state:n,scopes:o,redirectURI:i,additionalParams:s}){let a=t.disableDefaultScope?[]:["openid","profile","email"];if(o)a.push(...o);if(t.scope)a.push(...t.scope);return V({id:"slack",options:t,authorizationEndpoint:"https://slack.com/openid/connect/authorize",scopes:a,state:n,redirectURI:i,additionalParams:s})},validateAuthorizationCode:async({code:n,redirectURI:o})=>K({code:n,redirectURI:o,options:t,tokenEndpoint:"https://slack.com/api/openid.connect.token"}),refreshAccessToken:t.refreshAccessToken?t.refreshAccessToken:async(n)=>F({refreshToken:n,options:{clientId:t.clientId,clientKey:t.clientKey,clientSecret:t.clientSecret},tokenEndpoint:"https://slack.com/api/openid.connect.token"}),async getUserInfo(n){if(t.getUserInfo)return t.getUserInfo(n);let{data:o,error:i}=await Me("https://slack.com/api/openid.connect.userInfo",{headers:{authorization:`Bearer ${n.accessToken}`}});if(i)return null;let s=await t.mapProfileToUser?.(o);return{user:{name:o.name||"",email:o.email,emailVerified:o.email_verified,image:o.picture||o["https://slack.com/user_image_512"],...s},data:o}},options:t});var jl=(t)=>({id:"spotify",name:"Spotify",accountSubject:({profile:n})=>n.id,createAuthorizationURL({state:n,scopes:o,codeVerifier:i,redirectURI:s,additionalParams:a}){let c=t.disableDefaultScope?[]:["user-read-email"];if(t.scope)c.push(...t.scope);if(o)c.push(...o);return V({id:"spotify",options:t,authorizationEndpoint:"https://accounts.spotify.com/authorize",scopes:c,state:n,codeVerifier:i,redirectURI:s,additionalParams:a})},validateAuthorizationCode:async({code:n,codeVerifier:o,redirectURI:i})=>K({code:n,codeVerifier:o,redirectURI:i,options:t,tokenEndpoint:"https://accounts.spotify.com/api/token"}),refreshAccessToken:t.refreshAccessToken?t.refreshAccessToken:async(n)=>F({refreshToken:n,options:{clientId:t.clientId,clientKey:t.clientKey,clientSecret:t.clientSecret},tokenEndpoint:"https://accounts.spotify.com/api/token"}),async getUserInfo(n){if(t.getUserInfo)return t.getUserInfo(n);let{data:o,error:i}=await Me("https://api.spotify.com/v1/me",{method:"GET",headers:{Authorization:`Bearer ${n.accessToken}`}});if(i)return null;let s=await t.mapProfileToUser?.(o);return{user:{name:o.display_name,email:o.email,image:o.images[0]?.url,emailVerified:!1,...s},data:o}},options:t});var Bl=(t)=>{let n={method:"custom",customizeRequest({body:o}){o.set("client_key",t.clientKey),o.set("client_secret",t.clientSecret)}};return{id:"tiktok",name:"TikTok",accountSubject:({profile:o})=>o.data.user.open_id,createAuthorizationURL({state:o,scopes:i,redirectURI:s,additionalParams:a}){let c=t.disableDefaultScope?[]:["user.info.profile"];if(t.scope)c.push(...t.scope);if(i)c.push(...i);let d=new URL("https://www.tiktok.com/v2/auth/authorize");if(d.searchParams.set("scope",c.join(",")),d.searchParams.set("response_type","code"),d.searchParams.set("client_key",t.clientKey),d.searchParams.set("redirect_uri",t.redirectURI||s),d.searchParams.set("state",o),a)for(let[u,f]of Object.entries(a)){if(Ft.has(u))continue;if(u==="client_key")continue;d.searchParams.set(u,f)}return d},validateAuthorizationCode:async({code:o,codeVerifier:i,redirectURI:s})=>K({code:o,codeVerifier:i,redirectURI:t.redirectURI||s,options:{},tokenEndpoint:"https://open.tiktokapis.com/v2/oauth/token/",tokenEndpointAuth:n}),refreshAccessToken:t.refreshAccessToken?t.refreshAccessToken:async(o)=>F({refreshToken:o,options:{},tokenEndpoint:"https://open.tiktokapis.com/v2/oauth/token/",tokenEndpointAuth:n}),async getUserInfo(o){if(t.getUserInfo)return t.getUserInfo(o);let{data:i,error:s}=await Me(`https://open.tiktokapis.com/v2/user/info/?fields=${["open_id","avatar_large_url","display_name","username"].join(",")}`,{headers:{authorization:`Bearer ${o.accessToken}`}});if(s)return null;return{user:{email:i.data.user.email||it({identifier:i.data.user.open_id,namespace:"tiktok"}),name:i.data.user.display_name||i.data.user.username||"",image:i.data.user.avatar_large_url,emailVerified:!1},data:i}},options:t}};var $l=(t)=>({id:"twitch",name:"Twitch",accountSubject:({profile:n})=>n.sub,createAuthorizationURL({state:n,scopes:o,redirectURI:i,additionalParams:s}){let a=t.disableDefaultScope?[]:["user:read:email","openid"];if(t.scope)a.push(...t.scope);if(o)a.push(...o);return V({id:"twitch",redirectURI:i,options:t,authorizationEndpoint:"https://id.twitch.tv/oauth2/authorize",scopes:a,state:n,claims:t.claims||["email","email_verified","preferred_username","picture"],additionalParams:s})},validateAuthorizationCode:async({code:n,redirectURI:o})=>K({code:n,redirectURI:o,options:t,tokenEndpoint:"https://id.twitch.tv/oauth2/token"}),refreshAccessToken:t.refreshAccessToken?t.refreshAccessToken:async(n)=>F({refreshToken:n,options:{clientId:t.clientId,clientKey:t.clientKey,clientSecret:t.clientSecret},tokenEndpoint:"https://id.twitch.tv/oauth2/token"}),async getUserInfo(n){if(t.getUserInfo)return t.getUserInfo(n);let o=n.idToken;if(!o)return Ee.error("No idToken found in token"),null;let i=en(o),s=await t.mapProfileToUser?.(i);return{user:{name:i.preferred_username,email:i.email,image:i.picture,emailVerified:i.email_verified,...s},data:i}},options:t});var Ml=(t)=>({id:"twitter",name:"Twitter",accountSubject:({profile:n})=>n.data.id,createAuthorizationURL(n){let o=t.disableDefaultScope?[]:["users.read","tweet.read","offline.access","users.email"];if(t.scope)o.push(...t.scope);if(n.scopes)o.push(...n.scopes);return V({id:"twitter",options:t,authorizationEndpoint:"https://x.com/i/oauth2/authorize",scopes:o,state:n.state,codeVerifier:n.codeVerifier,redirectURI:n.redirectURI,additionalParams:n.additionalParams})},validateAuthorizationCode:async({code:n,codeVerifier:o,redirectURI:i})=>K({code:n,codeVerifier:o,authentication:"basic",redirectURI:i,options:t,tokenEndpoint:"https://api.x.com/2/oauth2/token"}),refreshAccessToken:t.refreshAccessToken?t.refreshAccessToken:async(n)=>F({refreshToken:n,options:{clientId:t.clientId,clientKey:t.clientKey,clientSecret:t.clientSecret},authentication:"basic",tokenEndpoint:"https://api.x.com/2/oauth2/token"}),async getUserInfo(n){if(t.getUserInfo)return t.getUserInfo(n);let{data:o,error:i}=await Me("https://api.x.com/2/users/me?user.fields=profile_image_url",{method:"GET",headers:{Authorization:`Bearer ${n.accessToken}`}});if(i)return null;let{data:s,error:a}=await Me("https://api.x.com/2/users/me?user.fields=confirmed_email",{method:"GET",headers:{Authorization:`Bearer ${n.accessToken}`}}),c=!1;if(!a&&s?.data?.confirmed_email)o.data.email=s.data.confirmed_email,c=!0;let d=await t.mapProfileToUser?.(o);return{user:{name:o.data.name,email:o.data.email||it({identifier:o.data.id,namespace:"twitter"}),image:o.data.profile_image_url,emailVerified:c,...d},data:o}},options:t});var Hl=(t)=>({id:"vercel",name:"Vercel",accountSubject:({profile:r})=>r.sub,createAuthorizationURL({state:r,scopes:n,codeVerifier:o,redirectURI:i,additionalParams:s}){if(!o)throw new te("codeVerifier is required for Vercel");let a=void 0;if(t.scope!==void 0||n!==void 0){if(a=[],t.scope)a.push(...t.scope);if(n)a.push(...n)}return V({id:"vercel",options:t,authorizationEndpoint:"https://vercel.com/oauth/authorize",scopes:a,state:r,codeVerifier:o,redirectURI:i,additionalParams:s})},validateAuthorizationCode:async({code:r,codeVerifier:n,redirectURI:o})=>K({code:r,codeVerifier:n,redirectURI:o,options:t,tokenEndpoint:"https://api.vercel.com/login/oauth/token"}),async getUserInfo(r){if(t.getUserInfo)return t.getUserInfo(r);let{data:n,error:o}=await Me("https://api.vercel.com/login/oauth/userinfo",{headers:{Authorization:`Bearer ${r.accessToken}`}});if(o||!n)return null;let i=await t.mapProfileToUser?.(n);return{user:{name:n.name??n.preferred_username??"",email:n.email,image:n.picture,emailVerified:n.email_verified??!1,...i},data:n}},options:t});var Vl=(t)=>({id:"vk",name:"VK",accountSubject:({profile:n})=>n.user.user_id,async createAuthorizationURL({state:n,scopes:o,codeVerifier:i,redirectURI:s,additionalParams:a}){let c=t.disableDefaultScope?[]:["email","phone"];if(t.scope)c.push(...t.scope);if(o)c.push(...o);return V({id:"vk",options:t,authorizationEndpoint:"https://id.vk.com/authorize",scopes:c,state:n,redirectURI:s,codeVerifier:i,additionalParams:a})},validateAuthorizationCode:async({code:n,codeVerifier:o,redirectURI:i,deviceId:s})=>K({code:n,codeVerifier:o,redirectURI:t.redirectURI||i,options:t,deviceId:s,tokenEndpoint:"https://id.vk.com/oauth2/auth"}),refreshAccessToken:t.refreshAccessToken?t.refreshAccessToken:async(n)=>F({refreshToken:n,options:{clientId:t.clientId,clientKey:t.clientKey,clientSecret:t.clientSecret},tokenEndpoint:"https://id.vk.com/oauth2/auth"}),async getUserInfo(n){if(t.getUserInfo)return t.getUserInfo(n);if(!n.accessToken)return null;let{data:o,error:i}=await Me("https://id.vk.com/oauth2/user_info",{method:"POST",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:new URLSearchParams({access_token:n.accessToken,client_id:t.clientId}).toString()});if(i)return null;let s=await t.mapProfileToUser?.(o);if(!o.user.email&&!s?.email)return null;return{user:{first_name:o.user.first_name,last_name:o.user.last_name,email:o.user.email,image:o.user.avatar,emailVerified:!1,birthday:o.user.birthday,sex:o.user.sex,name:`${o.user.first_name} ${o.user.last_name}`,...s},data:o}},options:t});var Fl=(t)=>({id:"wechat",name:"WeChat",accountSubject:({profile:r})=>r.unionid||r.openid,createAuthorizationURL({state:r,scopes:n,redirectURI:o,additionalParams:i}){let s=t.disableDefaultScope?[]:["snsapi_login"];t.scope&&s.push(...t.scope),n&&s.push(...n);let a=new URL("https://open.weixin.qq.com/connect/qrconnect");if(a.searchParams.set("scope",s.join(",")),a.searchParams.set("response_type","code"),a.searchParams.set("appid",t.clientId),a.searchParams.set("redirect_uri",t.redirectURI||o),a.searchParams.set("state",r),a.searchParams.set("lang",t.lang||"cn"),i)for(let[c,d]of Object.entries(i)){if(Ft.has(c))continue;if(c==="appid")continue;a.searchParams.set(c,d)}return a.hash="wechat_redirect",a},validateAuthorizationCode:async({code:r})=>{let{data:n,error:o}=await Me("https://api.weixin.qq.com/sns/oauth2/access_token?"+new URLSearchParams({appid:t.clientId,secret:t.clientSecret,code:r,grant_type:"authorization_code"}).toString(),{method:"GET"});if(o||!n||n.errcode)throw Error(`Failed to validate authorization code: ${n?.errmsg||o?.message||"Unknown error"}`);return{tokenType:"Bearer",accessToken:n.access_token,refreshToken:n.refresh_token,accessTokenExpiresAt:new Date(Date.now()+n.expires_in*1000),scopes:n.scope.split(","),openid:n.openid,unionid:n.unionid}},refreshAccessToken:t.refreshAccessToken?t.refreshAccessToken:async(r)=>{let{data:n,error:o}=await Me("https://api.weixin.qq.com/sns/oauth2/refresh_token?"+new URLSearchParams({appid:t.clientId,grant_type:"refresh_token",refresh_token:r}).toString(),{method:"GET"});if(o||!n||n.errcode)throw Error(`Failed to refresh access token: ${n?.errmsg||o?.message||"Unknown error"}`);return{tokenType:"Bearer",accessToken:n.access_token,refreshToken:n.refresh_token,accessTokenExpiresAt:new Date(Date.now()+n.expires_in*1000),scopes:n.scope.split(",")}},async getUserInfo(r){if(t.getUserInfo)return t.getUserInfo(r);let n=r.openid;if(!n)return null;let{data:o,error:i}=await Me("https://api.weixin.qq.com/sns/userinfo?"+new URLSearchParams({access_token:r.accessToken||"",openid:n,lang:"zh_CN"}).toString(),{method:"GET"});if(i||!o||o.errcode)return null;let s=await t.mapProfileToUser?.(o),a=o.unionid||o.openid||n;return{user:{name:o.nickname,email:o.email||it({identifier:a,namespace:"wechat"}),image:o.headimgurl,emailVerified:!1,...s},data:o}},options:t});var Kl=(t)=>{let r={pkce:!0,...t};return{id:"zoom",name:"Zoom",accountSubject:({profile:n})=>n.id,createAuthorizationURL:async({state:n,redirectURI:o,codeVerifier:i,additionalParams:s})=>V({id:"zoom",options:r,authorizationEndpoint:"https://zoom.us/oauth/authorize",state:n,redirectURI:o,codeVerifier:r.pkce?i:void 0,additionalParams:s}),validateAuthorizationCode:async({code:n,redirectURI:o,codeVerifier:i})=>K({code:n,redirectURI:r.redirectURI||o,codeVerifier:i,options:r,tokenEndpoint:"https://zoom.us/oauth/token",authentication:"post"}),refreshAccessToken:r.refreshAccessToken?r.refreshAccessToken:async(n)=>F({refreshToken:n,options:{clientId:r.clientId,clientKey:r.clientKey,clientSecret:r.clientSecret},tokenEndpoint:"https://zoom.us/oauth/token"}),async getUserInfo(n){if(r.getUserInfo)return r.getUserInfo(n);let{data:o,error:i}=await Me("https://api.zoom.us/v2/users/me",{headers:{authorization:`Bearer ${n.accessToken}`}});if(i)return null;let s=await r.mapProfileToUser?.(o);return{user:{name:o.display_name,image:o.pic_url,email:o.email,emailVerified:Boolean(o.verified),...s},data:{...o}}}}};var Cm={apple:xu,atlassian:Bu,cloudflare:Ju,cognito:Zu,discord:Xu,facebook:rl,figma:nl,github:ol,microsoft:gl,google:al,huggingface:dl,slack:ql,spotify:jl,twitch:$l,twitter:Ml,dropbox:el,kick:ll,linear:pl,linkedin:hl,gitlab:il,tiktok:Bl,reddit:Pl,roblox:zl,salesforce:Nl,vk:Vl,zoom:Kl,notion:Rl,kakao:ul,naver:El,line:fl,paybin:Tl,paypal:Ul,polar:Ol,railway:Ll,vercel:Hl,wechat:Fl},Py=Object.keys(Cm),Uo=T(Py).or(e());function Wl(t){if(!t)return[];return t.split(",").map((r)=>r.trim()).filter(Boolean)}var Jl=Pe("/list-accounts",{method:"GET",use:[Hr],metadata:{openapi:{operationId:"listUserAccounts",description:"List all accounts linked to the user",responses:{"200":{description:"Success",content:{"application/json":{schema:{type:"array",items:{type:"object",properties:{id:{type:"string"},providerId:{type:"string"},createdAt:{type:"string",format:"date-time"},updatedAt:{type:"string",format:"date-time"},accountId:{type:"string"},userId:{type:"string"},scopes:{type:"array",items:{type:"string"}}},required:["id","providerId","createdAt","updatedAt","accountId","userId","scopes"]}}}}}}}}},async(t)=>{let r=t.context.session,n=await t.context.internalAdapter.findAccounts(r.user.id);return t.json(n.map((o)=>{let{scope:i,...s}=Vn(t.context.options,o);return{...s,scopes:Wl(i)}}))}),Ql=Pe("/link-social",{method:"POST",requireHeaders:!0,body:l({callbackURL:e().meta({description:"The URL to redirect to after the user has signed in"}).optional(),provider:Uo,idToken:l({token:e(),nonce:e().optional(),accessToken:e().optional(),refreshToken:e().optional()}).optional(),requestSignUp:E().optional(),scopes:A(e()).meta({description:"Additional scopes to request from the provider"}).optional(),errorCallbackURL:e().meta({description:"The URL to redirect to if there is an error during the link process"}).optional(),disableRedirect:E().meta({description:"Disable automatic redirection to the provider. Useful for handling the redirection yourself"}).optional(),loginHint:e().meta({description:"The login hint to use for the authorization code request"}).optional(),additionalParams:cn,additionalData:k(e(),N()).optional()}),use:[Hr],metadata:{openapi:{description:"Link a social account to the user",operationId:"linkSocialAccount",responses:{"200":{description:"Success",content:{"application/json":{schema:{type:"object",properties:{url:{type:"string",description:"The authorization URL to redirect the user to"},redirect:{type:"boolean",description:"Indicates if the user should be redirected to the authorization URL"},status:{type:"boolean"}},required:["redirect"]}}}}}}}},async(t)=>{let r=t.context.session,n=await tt(t.context.socialProviders,{value:t.body.provider});if(!n)throw t.context.logger.error("Provider not found. Make sure to add the provider in your auth config",{provider:t.body.provider}),U.from("NOT_FOUND",Ae.PROVIDER_NOT_FOUND);if(t.body.idToken){if(!_n(n))throw t.context.logger.error("Provider does not support id token verification",{provider:t.body.provider}),U.from("NOT_FOUND",Ae.ID_TOKEN_NOT_SUPPORTED);let{token:a,nonce:c}=t.body.idToken;if(!await An(n,a,c,t))throw t.context.logger.warn("Invalid id token",{provider:t.body.provider}),U.from("UNAUTHORIZED",Ae.INVALID_TOKEN);let d=await n.getUserInfo({idToken:a,accessToken:t.body.idToken.accessToken,refreshToken:t.body.idToken.refreshToken});if(!d||!d?.user)throw t.context.logger.error("Failed to get user info",{provider:t.body.provider}),U.from("UNAUTHORIZED",Ae.FAILED_TO_GET_USER_INFO);if(!d.user.email)throw t.context.logger.error(wr(t.body.provider,{source:"id_token"}),{provider:t.body.provider}),U.from("UNAUTHORIZED",Ae.USER_EMAIL_NOT_FOUND);let u=await mo(n,{idToken:a,accessToken:t.body.idToken.accessToken,refreshToken:t.body.idToken.refreshToken},d.data),f=await t.context.internalAdapter.findAccountByKey(u);if(f?.userId===r.user.id){let p=Object.fromEntries(Object.entries({providerId:n.id,accessToken:await me(t.body.idToken.accessToken,t.context),idToken:a,refreshToken:await me(t.body.idToken.refreshToken,t.context)}).filter(([h,m])=>m!==void 0));return await t.context.internalAdapter.updateAccount(f.id,p),await En(t,r.user.id,d.user),t.json({url:"",status:!0,redirect:!1})}if(f)throw U.from("CONFLICT",Ae.SOCIAL_ACCOUNT_ALREADY_LINKED);if(!t.context.trustedProviders.includes(n.id)&&!d.user.emailVerified||t.context.options.account?.accountLinking?.enabled===!1)throw U.from("UNAUTHORIZED",{message:"Account not linked - linking not allowed",code:"LINKING_NOT_ALLOWED"});if(d.user.email?.toLowerCase()!==r.user.email.toLowerCase()&&t.context.options.account?.accountLinking?.allowDifferentEmails!==!0)throw U.from("UNAUTHORIZED",{message:"Account not linked - different emails not allowed",code:"LINKING_DIFFERENT_EMAILS_NOT_ALLOWED"});try{await t.context.internalAdapter.createAccount({userId:r.user.id,...u,accessToken:await me(t.body.idToken.accessToken,t.context),idToken:a,refreshToken:await me(t.body.idToken.refreshToken,t.context)})}catch{throw U.from("EXPECTATION_FAILED",{message:"Account not linked - unable to create account",code:"LINKING_FAILED"})}return await En(t,r.user.id,d.user),t.json({url:"",status:!0,redirect:!1})}let o=kr(n),i=await Er(t,{link:{userId:r.user.id,email:r.user.email},additionalData:t.body.additionalData,idTokenNonce:o}),s=await n.createAuthorizationURL({state:i.state,codeVerifier:i.codeVerifier,idTokenNonce:o,redirectURI:`${t.context.baseURL}${Rt(n)}`,scopes:t.body.scopes,loginHint:t.body.loginHint,additionalParams:t.body.additionalParams});if(!t.body.disableRedirect)t.setHeader("Location",s.toString());return t.json({url:s.toString(),redirect:!t.body.disableRedirect})}),Gl=Pe("/unlink-account",{method:"POST",body:l({accountId:e().meta({description:"The Better Auth account ID to unlink"})}),use:[po],metadata:{openapi:{description:"Unlink an account",responses:{"200":{description:"Success",content:{"application/json":{schema:{type:"object",properties:{status:{type:"boolean"}}}}}}}}}},async(t)=>{let{accountId:r}=t.body,n=await t.context.internalAdapter.findAccounts(t.context.session.user.id);if(n.length===1&&!t.context.options.account?.accountLinking?.allowUnlinkingAll)throw U.from("BAD_REQUEST",Ae.FAILED_TO_UNLINK_LAST_ACCOUNT);let o=n.find((i)=>i.id===r);if(!o)throw U.from("BAD_REQUEST",Ae.ACCOUNT_NOT_FOUND);return await t.context.internalAdapter.deleteAccount(o.id),t.json({status:!0})});async function Ns(t,r){let n=await ee(t,{disableCookieCache:St(t)});if(!n&&(t.request||t.headers))throw t.error("UNAUTHORIZED");let o=n?.user?.id||r;if(!o)throw U.from("BAD_REQUEST",{message:"Either userId or session is required",code:"USER_ID_OR_SESSION_REQUIRED"});return o}var qs=D([Bm({accountId:e().meta({description:"The Better Auth account ID"}),userId:e().meta({description:"The user ID associated with the account"}).optional()}),Bm({useAccountCookie:v(!0).meta({description:"Select the current OAuth account from its signed cookie"}),userId:e().meta({description:"The user ID associated with the account"}).optional()})]);function Zl(t,r,{resolvedUserId:n,selection:o}){return(!qn(t.context.options)||r.userId===n)&&("accountId"in o?r.id===o.accountId:!0)}async function js(t,{resolvedUserId:r,selection:n}){if("accountId"in n){let o=(await t.context.internalAdapter.findAccounts(r)).find((i)=>i.id===n.accountId);if(o)return{account:o,accountCookie:null}}else if(t.context.options.account?.storeAccountCookie){let o=await io(t);if(o&&Zl(t,o,{resolvedUserId:r,selection:n}))return{account:o,accountCookie:o}}throw U.from("BAD_REQUEST",Ae.ACCOUNT_NOT_FOUND)}async function Yl(t,{resolvedUserId:r,selection:n,account:o}){let i=o??(await js(t,{resolvedUserId:r,selection:n})).account;if(!Zl(t,i,{resolvedUserId:r,selection:n}))throw U.from("BAD_REQUEST",Ae.ACCOUNT_NOT_FOUND);let s=await tt(t.context.socialProviders,{value:i.providerId});if(!s)throw U.from("BAD_REQUEST",{message:`Provider ${i.providerId} is not supported.`,code:"PROVIDER_NOT_SUPPORTED"});try{let a=null,c=i.accessTokenExpiresAt&&new Date(i.accessTokenExpiresAt).getTime()-Date.now()<5000;if(i.refreshToken&&c&&s.refreshAccessToken){let u=await _o(i.refreshToken,t.context);a=await s.refreshAccessToken(u,t);let f={accessToken:await me(a?.accessToken,t.context),accessTokenExpiresAt:a?.accessTokenExpiresAt,refreshToken:a?.refreshToken?await me(a.refreshToken,t.context):i.refreshToken,refreshTokenExpiresAt:a?.refreshTokenExpiresAt??i.refreshTokenExpiresAt,idToken:a?.idToken||i.idToken},p=null;if(i.id)p=await t.context.internalAdapter.updateAccount(i.id,f);if(t.context.options.account?.storeAccountCookie)await ft(t,{...i,...p??f})}let d=(()=>{if(a?.accessTokenExpiresAt){if(typeof a.accessTokenExpiresAt==="string")return new Date(a.accessTokenExpiresAt);return a.accessTokenExpiresAt}if(i.accessTokenExpiresAt){if(typeof i.accessTokenExpiresAt==="string")return new Date(i.accessTokenExpiresAt);return i.accessTokenExpiresAt}})();return{accessToken:a?.accessToken??await _o(i.accessToken??"",t.context),accessTokenExpiresAt:d,scopes:Wl(i.scope),idToken:a?.idToken??i.idToken??void 0}}catch(a){throw U.from("BAD_REQUEST",{message:"Failed to get a valid access token",code:"FAILED_TO_GET_ACCESS_TOKEN"})}}var Xl=Pe("/get-access-token",{method:"POST",body:qs,metadata:{openapi:{description:"Get a valid access token, doing a refresh if needed",responses:{200:{description:"A Valid access token",content:{"application/json":{schema:{type:"object",properties:{tokenType:{type:"string"},idToken:{type:"string"},accessToken:{type:"string"},accessTokenExpiresAt:{type:"string",format:"date-time"}}}}}},400:{description:"Invalid refresh token or provider configuration"}}}}},async(t)=>{let{userId:r}=t.body,n=await Yl(t,{resolvedUserId:await Ns(t,r),selection:t.body});return t.json(n)}),ef=Pe("/refresh-token",{method:"POST",body:qs,metadata:{openapi:{description:"Refresh the access token using a refresh token",responses:{200:{description:"Access token refreshed successfully",content:{"application/json":{schema:{type:"object",properties:{tokenType:{type:"string"},idToken:{type:"string"},accessToken:{type:"string"},refreshToken:{type:"string"},accessTokenExpiresAt:{type:"string",format:"date-time"},refreshTokenExpiresAt:{type:"string",format:"date-time"}}}}}},400:{description:"Invalid refresh token or provider configuration"}}}}},async(t)=>{let{userId:r}=t.body,{account:n,accountCookie:o}=await js(t,{resolvedUserId:await Ns(t,r),selection:t.body}),i=await tt(t.context.socialProviders,{value:n.providerId});if(!i)throw U.from("BAD_REQUEST",{message:`Provider ${n.providerId} is not supported.`,code:"PROVIDER_NOT_SUPPORTED"});if(!i.refreshAccessToken)throw U.from("BAD_REQUEST",{message:`Provider ${n.providerId} does not support token refreshing.`,code:"TOKEN_REFRESH_NOT_SUPPORTED"});let s=n.refreshToken??void 0;if(!s)throw U.from("BAD_REQUEST",{message:"Refresh token not found",code:"REFRESH_TOKEN_NOT_FOUND"});try{let a=await _o(s,t.context),c=await i.refreshAccessToken(a,t),d=c.refreshToken?await me(c.refreshToken,t.context):s,u=c.refreshTokenExpiresAt??n.refreshTokenExpiresAt,f={accessToken:await me(c.accessToken,t.context),refreshToken:d,accessTokenExpiresAt:c.accessTokenExpiresAt,refreshTokenExpiresAt:u,idToken:c.idToken||n.idToken},p=null;if(n.id)p=await t.context.internalAdapter.updateAccount(n.id,f);if(o?.id===n.id&&t.context.options.account?.storeAccountCookie)await ft(t,{...o,...p??f});let h=p?.scope??n.scope;return t.json({accessToken:c.accessToken,refreshToken:c.refreshToken??a,accessTokenExpiresAt:c.accessTokenExpiresAt,refreshTokenExpiresAt:u,scope:h,idToken:c.idToken||n.idToken,providerId:n.providerId,accountId:n.id})}catch(a){throw U.from("BAD_REQUEST",{message:"Failed to refresh access token",code:"FAILED_TO_REFRESH_ACCESS_TOKEN"})}}),tf=Pe("/account-info",{method:"GET",metadata:{openapi:{description:"Get the account info provided by the provider",responses:{"200":{description:"Success",content:{"application/json":{schema:{type:"object",properties:{user:{type:"object",properties:{name:{type:"string"},email:{type:"string",nullable:!0},image:{type:"string"},emailVerified:{type:"boolean"}},required:["emailVerified"]},account:{type:"object",properties:{id:{type:"string"},providerId:{type:"string"},accountId:{type:"string"}},required:["id","providerId","accountId"],additionalProperties:!1},data:{type:"object",properties:{},additionalProperties:!0}},required:["user","data","account"],additionalProperties:!1}}}}}}},query:qs},async(t)=>{let{userId:r}=t.query,n=await Ns(t,r),{account:o}=await js(t,{resolvedUserId:n,selection:t.query}),i=await tt(t.context.socialProviders,{value:o.providerId});if(!i)throw U.from("BAD_REQUEST",{message:"Account is not associated with a configured social provider.",code:"PROVIDER_NOT_CONFIGURED"});let s=await Yl(t,{resolvedUserId:n,selection:t.query,account:o});if(!s.accessToken)throw U.from("BAD_REQUEST",{message:"Access token not found",code:"ACCESS_TOKEN_NOT_FOUND"});let a=await i.getUserInfo({...s,accessToken:s.accessToken});if(!a)throw U.from("UNAUTHORIZED",Ae.FAILED_TO_GET_USER_INFO);return t.json({...a,account:{id:o.id,providerId:o.providerId,accountId:o.accountId}})});async function rf(t,r,n){if(n.iss&&r.issuer&&n.iss!==r.issuer)return t.context.logger.error("OAuth issuer mismatch",{expected:r.issuer,received:n.iss}),{error:he.ISSUER_MISMATCH};if(r.requiresIdTokenNonce&&!n.idTokenNonce)return t.context.logger.error("OAuth id_token nonce binding required but no expected nonce was found in state",{providerId:r.id}),{error:he.NONCE_BINDING_MISSING};let o;try{o=await r.validateAuthorizationCode({code:n.code,codeVerifier:n.codeVerifier,deviceId:n.deviceId,redirectURI:`${t.context.baseURL}${Rt(r)}`})}catch(a){return t.context.logger.error("Failed to validate authorization code",a),{error:he.INVALID_CODE}}if(!o)return{error:he.INVALID_CODE};let i=await r.getUserInfo({...o,expectedIdTokenNonce:n.idTokenNonce,user:Mr(n.user)??void 0});if(!i?.user)return t.context.logger.error("Unable to get user info"),{error:he.UNABLE_TO_GET_USER_INFO};let s=await ns(r,o,i.data).catch((a)=>(t.context.logger.error("Unable to derive provider account identity",{providerId:r.id,error:a}),null));if(!s)return{error:he.UNABLE_TO_GET_USER_INFO};return{tokens:o,userInfo:i.user,providerProfile:ho(i.data),accountKey:s}}var br={scope:"server"};var Gt=l({code:e().optional(),error:e().optional(),device_id:e().optional(),error_description:e().optional(),state:e().optional(),user:e().optional(),iss:e().optional()}),nf=Pe("/callback/:id",{method:["GET","POST"],operationId:"handleOAuthCallback",body:Gt.optional(),query:Gt.optional(),metadata:{...br,allowedMediaTypes:["application/x-www-form-urlencoded","application/json"]}},async(t)=>{let r,n=t.context.options.onAPIError?.errorURL||`${t.context.baseURL}/error`;if(t.method==="POST"){let q=t.body?Gt.parse(t.body):{},W=t.query?Gt.parse(t.query):{},Q=Gt.parse({...q,...W}),G=new URLSearchParams;for(let[Y,Z]of Object.entries(Q))if(Z!==void 0&&Z!==null)G.set(Y,String(Z));let M=`${t.context.baseURL}/callback/${t.params.id}?${G.toString()}`;throw t.redirect(M)}try{if(t.method==="GET")r=Gt.parse(t.query);else if(t.method==="POST")r=Gt.parse(t.body);else throw Error("Unsupported method")}catch(q){t.context.logger.error("INVALID_CALLBACK_REQUEST",q);let W=$e(n,new URLSearchParams({error:"invalid_callback_request"}));throw t.redirect(W)}let{code:o,error:i,state:s,error_description:a,device_id:c,user:d,iss:u}=r;if(s===void 0&&o){let q=await tt(t.context.socialProviders,{value:t.params.id});if(q?.allowIdpInitiated){let W=kr(q),{state:Q,codeVerifier:G}=await Er(t,{idTokenNonce:W}),M=await q.createAuthorizationURL({state:Q,codeVerifier:G,idTokenNonce:W,redirectURI:`${t.context.baseURL}${Rt(q)}`});throw t.redirect(M.toString())}}if(!s){t.context.logger.error("State not found",i);let q=$e(n,new URLSearchParams({error:"state_not_found"}));throw t.redirect(q)}let{codeVerifier:f,callbackURL:p,link:h,errorURL:m,newUserURL:w,requestSignUp:y,idTokenNonce:I}=await Pu(t);function R(q,W){let Q=m??n,G=new URLSearchParams({error:q});if(W)G.set("error_description",W);let M=$e(Q,G);throw t.redirect(M)}if(i)R(i,a);if(!o)throw t.context.logger.warn("Code not found"),R(he.NO_CODE);let b=await tt(t.context.socialProviders,{value:t.params.id});if(!b)throw t.context.logger.warn("OAuth provider not found",{providerId:t.params.id}),R(he.PROVIDER_NOT_FOUND);let O=await rf(t,b,{code:o,codeVerifier:f,iss:u,deviceId:c,user:d,idTokenNonce:I});if(O.error)throw R(O.error);let{tokens:g,userInfo:S,providerProfile:C,accountKey:z}=O,{accountId:L}=z;if(!p)throw t.context.logger.error("No callback URL found"),R(he.NO_CALLBACK_URL);let x={...z,...g,scope:g.scopes?.join(",")};if(h){let q=await Ou(t,{link:h,userInfo:S,account:x,profile:C,scopes:g.scopes});if(!q.linked)return R(q.error.code,q.error.message);throw t.redirect(p)}if(!S.email)return t.context.logger.error(wr(b.id)),R(he.EMAIL_NOT_FOUND);let P;try{P=await Io(t,{userInfo:{...S,id:L,email:S.email,name:S.name||""},account:x,callbackURL:p,disableSignUp:b.disableImplicitSignUp&&!y||b.options?.disableSignUp,overrideUserInfo:b.options?.overrideUserInfoOnSignIn,source:{method:"oauth",oauth:{providerId:b.id,profile:C}}})}catch(q){if(Ur(q)&&q.body?.code)R(q.body.code,q.body.message);throw q}if(P.error)return t.context.logger.error(P.error.split(" ").join("_")),R(P.error.split(" ").join("_"));let{session:j,user:B}=P.data;await pe(t,{session:j,user:B});let H;try{H=(P.isRegister?w||p:p).toString()}catch{H=P.isRegister?w||p:p}throw t.redirect(H)});function of(t){return t.replace(/</g,"&lt;").replace(/>/g,"&gt;").replace(/"/g,"&quot;").replace(/'/g,"&#39;").replace(/&(?!amp;|lt;|gt;|quot;|#39;|#x[0-9a-fA-F]+;|#[0-9]+;)/g,"&amp;")}var xy=(t,r="Unknown",n=null)=>{let o=t.onAPIError?.customizeDefaultErrorPage;return`<!DOCTYPE html>
52
52
  <html lang="en">
53
53
  <head>
54
54
  <meta charset="UTF-8" />
@@ -382,7 +382,7 @@ ${o?.disableBackgroundGrid?"":`
382
382
  </div>
383
383
  </div>
384
384
  </body>
385
- </html>`},sf=Pe("/error",{method:"GET",metadata:{...br,openapi:{description:"Displays an error page",responses:{"200":{description:"Success",content:{"text/html":{schema:{type:"string",description:"The HTML content of the error page"}}}}}}}},async(t)=>{let r=new URL(t.request?.url||""),n=r.searchParams.get("error")||"UNKNOWN",o=r.searchParams.get("error_description")||null,i=/^[\'A-Za-z0-9_-]+$/.test(n||"")?n:"UNKNOWN",s=o?of(o):null,a=new URLSearchParams;if(a.set("error",i),o)a.set("error_description",o);let c=t.context.options,d=c.onAPIError?.errorURL;if(d){let u=$e(d,a);return new Response(null,{status:302,headers:{Location:u}})}if(Xi&&!c.onAPIError?.customizeDefaultErrorPage)return new Response(null,{status:302,headers:{Location:`/?${a.toString()}`}});return new Response(xy(t.context.options,i,s),{headers:{"Content-Type":"text/html"}})});var af=Pe("/ok",{method:"GET",metadata:{...br,openapi:{description:"Check if the API is working",responses:{"200":{description:"API is working",content:{"application/json":{schema:{type:"object",properties:{ok:{type:"boolean",description:"Indicates if the API is working"}},required:["ok"]}}}}}}}},async(t)=>t.json({ok:!0}));function wf(t,r,n){let o=r?new URL(r,t.baseURL):new URL(`${t.baseURL}/error`);if(n)Object.entries(n).forEach(([i,s])=>o.searchParams.set(i,s));return o.href}function Ny(t,r,n){let o=new URL(r,t.baseURL);if(n)Object.entries(n).forEach(([i,s])=>o.searchParams.set(i,s));return o.href}var bf=Pe("/request-password-reset",{method:"POST",body:l({email:In().meta({description:"The email address of the user to send a password reset email to"}),redirectTo:e().meta({description:"The URL to redirect the user to reset their password. If the token isn't valid or expired, it'll be redirected with a query parameter `?error=INVALID_TOKEN`. If the token is valid, it'll be redirected with a query parameter `?token=VALID_TOKEN"}).optional()}),metadata:{openapi:{operationId:"requestPasswordReset",description:"Send a password reset email to the user",responses:{"200":{description:"Success",content:{"application/json":{schema:{type:"object",properties:{status:{type:"boolean"},message:{type:"string"}}}}}}}}},use:[bt((t)=>t.body.redirectTo)]},async(t)=>{if(!t.context.options.emailAndPassword?.sendResetPassword)throw t.context.logger.error("Reset password isn't enabled.Please pass an emailAndPassword.sendResetPassword function in your auth config!"),U.from("BAD_REQUEST",{message:"Reset password isn't enabled",code:"RESET_PASSWORD_DISABLED"});let{email:r,redirectTo:n}=t.body,o=await t.context.internalAdapter.findUserByEmail(r,{includeAccounts:!0});if(!o)return us(24),await t.context.internalAdapter.findVerificationValue("dummy-verification-token"),t.context.logger.warn("Reset Password: User not found"),t.json({status:!0,message:"If this email exists in our system, check your email for the reset link"});let i=ut(t.context.options.emailAndPassword.resetPasswordTokenExpiresIn||3600,"sec"),s=us(24);await t.context.internalAdapter.createVerificationValue({value:o.user.id,identifier:`reset-password:${s}`,expiresAt:i});let a=n?encodeURIComponent(n):"",c=`${t.context.baseURL}/reset-password/${s}?callbackURL=${a}`;return await t.context.runInBackgroundOrAwait(t.context.options.emailAndPassword.sendResetPassword({user:o.user,url:c,token:s},t.request)),t.json({status:!0,message:"If this email exists in our system, check your email for the reset link"})}),vf=Pe("/reset-password/:token",{method:"GET",operationId:"resetPasswordCallback",query:l({callbackURL:e().meta({description:"The URL to redirect the user to reset their password"})}),use:[bt((t)=>t.query.callbackURL)],metadata:{openapi:{operationId:"resetPasswordCallback",description:"Redirects the user to the callback URL with the token",parameters:[{name:"token",in:"path",required:!0,description:"The token to reset the password",schema:{type:"string"}},{name:"callbackURL",in:"query",required:!0,description:"The URL to redirect the user to reset their password",schema:{type:"string"}}],responses:{"200":{description:"Success",content:{"application/json":{schema:{type:"object",properties:{token:{type:"string"}}}}}}}}}},async(t)=>{let{token:r}=t.params,{callbackURL:n}=t.query;if(!r||!n)throw t.redirect(wf(t.context,n,{error:"INVALID_TOKEN"}));let o=await t.context.internalAdapter.findVerificationValue(`reset-password:${r}`);if(!o||o.expiresAt<new Date)throw t.redirect(wf(t.context,n,{error:"INVALID_TOKEN"}));throw t.redirect(Ny(t.context,n,{token:r}))}),Rf=Pe("/reset-password",{method:"POST",operationId:"resetPassword",query:l({token:e().optional()}).optional(),body:l({newPassword:e().meta({description:"The new password to set"}),token:e().meta({description:"The token to reset the password"}).optional()}),metadata:{openapi:{operationId:"resetPassword",description:"Reset the password for a user",responses:{"200":{description:"Success",content:{"application/json":{schema:{type:"object",properties:{status:{type:"boolean"}}}}}}}}}},async(t)=>{let r=t.body.token||t.query?.token;if(!r)throw U.from("BAD_REQUEST",Ae.INVALID_TOKEN);let{newPassword:n}=t.body;Ht(t,n),xe(t,n);let o=`reset-password:${r}`,i=await t.context.internalAdapter.findVerificationValue(o);if(!i||i.expiresAt<new Date)throw U.from("BAD_REQUEST",Ae.INVALID_TOKEN);let s=i.value,a=await t.context.internalAdapter.findUserById(s);if(!a)throw U.from("BAD_REQUEST",Ae.USER_NOT_FOUND);if(await pd(t,s,await t.context.password.hash(n),async()=>{if(!await t.context.internalAdapter.consumeVerificationValue(o))throw U.from("BAD_REQUEST",Ae.INVALID_TOKEN)}),t.context.options.emailAndPassword?.onPasswordReset)await t.context.options.emailAndPassword.onPasswordReset({user:a},t.request);return t.json({status:!0})}),Tf=Pe("/verify-password",{method:"POST",body:l({password:e().meta({description:"The password to verify"})}),metadata:{scope:"server",openapi:{operationId:"verifyPassword",description:"Verify the current user's password",responses:{"200":{description:"Success",content:{"application/json":{schema:{type:"object",properties:{status:{type:"boolean"}}}}}}}}},use:[Qe]},async(t)=>{let{password:r}=t.body,n=t.context.session;if(!await hd(t,{password:r,userId:n.user.id}))throw U.from("BAD_REQUEST",Ae.INVALID_PASSWORD);return t.json({status:!0})});var qy=l({callbackURL:e().meta({description:"Callback URL to redirect to after the user has signed in"}).optional(),newUserCallbackURL:e().optional(),errorCallbackURL:e().meta({description:"Callback URL to redirect to if an error happens"}).optional(),provider:Uo,disableRedirect:E().meta({description:"Disable automatic redirection to the provider. Useful for handling the redirection yourself"}).optional(),idToken:ye(l({token:e().meta({description:"ID token from the provider"}),nonce:e().meta({description:"Nonce used to generate the token"}).optional(),accessToken:e().meta({description:"Access token from the provider"}).optional(),refreshToken:e().meta({description:"Refresh token from the provider"}).optional(),expiresAt:_().meta({description:"Expiry date of the token"}).optional(),user:l({name:l({firstName:e().optional(),lastName:e().optional()}).optional(),email:e().optional()}).meta({description:"The user object from the provider. Only available for some providers like Apple."}).optional()})),scopes:A(e()).meta({description:"Array of scopes to request from the provider. This will override the default scopes passed."}).optional(),requestSignUp:E().meta({description:"Explicitly request sign-up. Useful when disableImplicitSignUp is true for this provider"}).optional(),loginHint:e().meta({description:"The login hint to use for the authorization code request"}).optional(),additionalParams:cn,additionalData:k(e(),N()).optional().meta({description:"Additional data to be passed through the OAuth flow"})}),Uf=()=>Pe("/sign-in/social",{method:"POST",operationId:"socialSignIn",body:qy,metadata:{$Infer:{body:{},returned:{}},openapi:{description:"Sign in with a social provider",operationId:"socialSignIn",responses:{"200":{description:"Success - Returns session details (idToken branch) or an authorize URL (redirect branch)",content:{"application/json":{schema:{type:"object",description:"Returns session details when idToken is provided, or an authorize URL otherwise",properties:{token:{type:"string"},user:{type:"object",$ref:"#/components/schemas/User"},url:{type:"string"},redirect:{type:"boolean"}},required:["redirect"]}}}}}}}},async(t)=>{let r=await tt(t.context.socialProviders,{value:t.body.provider});if(!r)throw t.context.logger.error("Provider not found. Make sure to add the provider in your auth config",{provider:t.body.provider}),U.from("NOT_FOUND",Ae.PROVIDER_NOT_FOUND);if(t.body.idToken){if(!_n(r))throw t.context.logger.error("Provider does not support id token verification",{provider:t.body.provider}),U.from("NOT_FOUND",Ae.ID_TOKEN_NOT_SUPPORTED);let{token:a,nonce:c}=t.body.idToken;if(!await An(r,a,c,t))throw t.context.logger.warn("Invalid id token",{provider:t.body.provider}),U.from("UNAUTHORIZED",Ae.INVALID_TOKEN);let d={idToken:a,accessToken:t.body.idToken.accessToken,refreshToken:t.body.idToken.refreshToken,user:t.body.idToken.user},u=await r.getUserInfo(d);if(!u||!u?.user)throw t.context.logger.error("Failed to get user info",{provider:t.body.provider}),U.from("UNAUTHORIZED",Ae.FAILED_TO_GET_USER_INFO);if(!u.user.email)throw t.context.logger.error(wr(t.body.provider,{source:"id_token"}),{provider:t.body.provider}),U.from("UNAUTHORIZED",Ae.USER_EMAIL_NOT_FOUND);let f=await mo(r,d,u.data),p=ho(u.data),h=await Io(t,{userInfo:{...u.user,email:u.user.email,id:f.accountId,name:u.user.name||"",image:u.user.image,emailVerified:u.user.emailVerified||!1},account:{...f,accessToken:t.body.idToken.accessToken,idToken:a},callbackURL:t.body.callbackURL,disableSignUp:r.disableImplicitSignUp&&!t.body.requestSignUp||r.options?.disableSignUp||r.disableSignUp,source:{method:"oauth",oauth:{providerId:r.id,profile:p}}});if(h.error){if(h.error===he.EMAIL_NOT_VERIFIED)throw U.from("FORBIDDEN",Ae.EMAIL_NOT_VERIFIED);throw U.from("UNAUTHORIZED",{message:h.error,code:"OAUTH_LINK_ERROR"})}return await pe(t,h.data),t.json({redirect:!1,token:h.data.session.token,url:void 0,user:se(t.context.options,h.data.user)})}let n=kr(r),{codeVerifier:o,state:i}=await Er(t,{additionalData:t.body.additionalData,idTokenNonce:n}),s=await r.createAuthorizationURL({state:i,codeVerifier:o,idTokenNonce:n,redirectURI:`${t.context.baseURL}${Rt(r)}`,scopes:t.body.scopes,loginHint:t.body.loginHint,additionalParams:t.body.additionalParams});if(!t.body.disableRedirect)t.setHeader("Location",s.toString());return t.json({url:s.toString(),redirect:!t.body.disableRedirect})}),Of=()=>Pe("/sign-in/email",{method:"POST",operationId:"signInEmail",use:[Yr],cloneRequest:!0,body:l({email:e().meta({description:"Email of the user"}),password:e().meta({description:"Password of the user"}),callbackURL:e().meta({description:"Callback URL to use as a redirect for email verification"}).optional(),rememberMe:E().meta({description:"If this is false, the session will not be remembered. Default is `true`."}).default(!0).optional()}),metadata:{allowedMediaTypes:["application/x-www-form-urlencoded","application/json"],$Infer:{body:{},returned:{}},openapi:{operationId:"signInEmail",description:"Sign in with email and password",responses:{"200":{description:"Success - Returns either session details or redirect URL",content:{"application/json":{schema:{type:"object",description:"Session response when idToken is provided",properties:{redirect:{type:"boolean",enum:[!1]},token:{type:"string",description:"Session token"},url:{type:"string",nullable:!0},user:{type:"object",$ref:"#/components/schemas/User"}},required:["redirect","token","user"]}}}}}}}},async(t)=>{if(!t.context.options?.emailAndPassword?.enabled)throw t.context.logger.error("Email and password is not enabled. Make sure to enable it in the options on you `auth.ts` file. Check `https://better-auth.com/docs/authentication/email-password` for more!"),U.from("BAD_REQUEST",{code:"EMAIL_PASSWORD_DISABLED",message:"Email and password is not enabled"});let{email:r,password:n}=t.body;if(!In().safeParse(r).success)throw U.from("BAD_REQUEST",Ae.INVALID_EMAIL);xe(t,n);let o=await t.context.internalAdapter.findUserByEmail(r.toLowerCase(),{includeAccounts:!0}),i=o?.accounts.find((d)=>d.providerId==="credential"&&d.accountId===o.user.id);if(!o||!i)throw await t.context.password.hash(n),t.context.logger.warn("User not found"),U.from("UNAUTHORIZED",Ae.INVALID_EMAIL_OR_PASSWORD);let s=o.user,a=i.password;if(!a)throw await t.context.password.hash(n),t.context.logger.warn("Password not found"),U.from("UNAUTHORIZED",Ae.INVALID_EMAIL_OR_PASSWORD);if(!await t.context.password.verify({hash:a,password:n}))throw t.context.logger.warn("Invalid password"),U.from("UNAUTHORIZED",Ae.INVALID_EMAIL_OR_PASSWORD);if(t.context.options?.emailAndPassword?.requireEmailVerification&&!s.emailVerified){if(!t.context.options?.emailVerification?.sendVerificationEmail)throw U.from("FORBIDDEN",Ae.EMAIL_NOT_VERIFIED);if(t.context.options?.emailVerification?.sendOnSignIn){let d=await Se(t.context.secret,s.email,void 0,t.context.options.emailVerification?.expiresIn),u=t.body.callbackURL?encodeURIComponent(t.body.callbackURL):encodeURIComponent("/"),f=`${t.context.baseURL}/verify-email?token=${d}&callbackURL=${u}`;await t.context.runInBackgroundOrAwait(t.context.options.emailVerification.sendVerificationEmail({user:s,url:f,token:d},Tt(t.request)))}throw U.from("FORBIDDEN",Ae.EMAIL_NOT_VERIFIED)}let c=await t.context.internalAdapter.createSession(s.id,t.body.rememberMe===!1);if(!c)throw t.context.logger.error("Failed to create session"),U.from("UNAUTHORIZED",Ae.FAILED_TO_CREATE_SESSION);if(await pe(t,{session:c,user:s},t.body.rememberMe===!1),t.body.callbackURL)t.setHeader("Location",t.body.callbackURL);return t.json({redirect:!!t.body.callbackURL,token:c.token,url:t.body.callbackURL,user:se(t.context.options,s)})});var By=l({callbackURL:e().meta({description:"The URL to redirect to after provider logout"}).optional(),disableRedirect:E().meta({description:"Return the provider logout URL without redirecting"}).optional(),state:e().meta({description:"State to pass to the provider logout endpoint"}).optional()}).optional(),Df=(t)=>({success:!0,url:t?.url,redirect:t?.redirect}),Lf=Pe("/sign-out",{method:"POST",body:By,operationId:"signOut",requireHeaders:!0,metadata:{openapi:{operationId:"signOut",description:"Sign out the current user",responses:{"200":{description:"Success",content:{"application/json":{schema:{type:"object",properties:{success:{type:"boolean"},url:{type:"string",description:"Provider logout URL when RP-initiated logout is available"},redirect:{type:"boolean",description:"Whether the client should redirect to the provider logout URL"}}}}}}}}}},async(t)=>{let r=await t.getSignedCookie(t.context.authCookies.sessionToken.name,t.context.secret),n=null;if(r)try{n=await t.context.internalAdapter.findSession(r)}catch(i){t.context.logger.error("Failed to read session from database",i)}if(r)try{await t.context.internalAdapter.deleteSession(r)}catch(i){t.context.logger.error("Failed to delete session from database",i)}Le(t);let o=await(async()=>{try{if(!n)return null;let i=await t.context.internalAdapter.findAccounts(n.user.id),s=new Map(t.context.socialProviders.map((u)=>[u.id,u])),a=i.filter((u)=>Boolean(s.get(u.providerId)?.createEndSessionURL)).sort((u,f)=>f.updatedAt.getTime()-u.updatedAt.getTime());if(a.length===0)return null;let c=new Set,d=t.body?.callbackURL?new URL(t.body.callbackURL,t.context.baseURL).toString():void 0;for(let u of a){if(c.has(u.providerId))continue;c.add(u.providerId);let f=s.get(u.providerId);try{let p=await f?.createEndSessionURL?.({idToken:u.idToken,postLogoutRedirectURI:d,state:t.body?.state});if(p)return p.toString()}catch(p){t.context.logger.error(`Failed to create logout URL for provider "${u.providerId}"`,p)}}return null}catch(i){return t.context.logger.error("Failed to create provider logout URL",i),null}})();if(o){let i=!t.body?.disableRedirect;if(i)t.setHeader("Location",o);return t.json(Df({url:o,redirect:i}))}return t.json(Df())});var $y=l({name:e(),email:In(),password:e().nonempty(),image:e().optional(),callbackURL:e().optional(),rememberMe:E().optional()}).and(k(e(),N())),Pf=()=>Pe("/sign-up/email",{method:"POST",operationId:"signUpWithEmailAndPassword",use:[Yr],body:$y,cloneRequest:!0,metadata:{allowedMediaTypes:["application/x-www-form-urlencoded","application/json"],$Infer:{body:{},returned:{}},openapi:{operationId:"signUpWithEmailAndPassword",description:"Sign up a user using email and password",requestBody:{content:{"application/json":{schema:{type:"object",properties:{name:{type:"string",description:"The name of the user"},email:{type:"string",description:"The email of the user"},password:{type:"string",description:"The password of the user"},image:{type:"string",description:"The profile image URL of the user"},callbackURL:{type:"string",description:"The URL to use for email verification callback"},rememberMe:{type:"boolean",description:"If this is false, the session will not be remembered. Default is `true`."}},required:["name","email","password"]}}}},responses:{"200":{description:"Successfully created user",content:{"application/json":{schema:{type:"object",properties:{token:{type:"string",nullable:!0,description:"Authentication token for the session"},user:{type:"object",properties:{id:{type:"string",description:"The unique identifier of the user"},email:{type:"string",format:"email",description:"The email address of the user"},name:{type:"string",description:"The name of the user"},image:{type:"string",format:"uri",nullable:!0,description:"The profile image URL of the user"},emailVerified:{type:"boolean",description:"Whether the email has been verified"},createdAt:{type:"string",format:"date-time",description:"When the user was created"},updatedAt:{type:"string",format:"date-time",description:"When the user was last updated"}},required:["id","email","name","emailVerified","createdAt","updatedAt"]}},required:["user"]}}}},"422":{description:"Unprocessable Entity. User already exists or failed to create user.",content:{"application/json":{schema:{type:"object",properties:{message:{type:"string"}}}}}}}}}},async(t)=>Ue(t.context.adapter,async()=>{if(!t.context.options.emailAndPassword?.enabled||t.context.options.emailAndPassword?.disableSignUp)throw U.from("BAD_REQUEST",{message:"Email and password sign up is not enabled",code:"EMAIL_PASSWORD_SIGN_UP_DISABLED"});let r=t.body,{name:n,email:o,password:i,image:s,callbackURL:a,rememberMe:c,...d}=r;if(!In().safeParse(o).success)throw U.from("BAD_REQUEST",Ae.INVALID_EMAIL);if(!i||typeof i!=="string")throw U.from("BAD_REQUEST",Ae.INVALID_PASSWORD);Ht(t,i),xe(t,i);let u=t.context.options.emailAndPassword.requireEmailVerification||t.context.options.emailAndPassword.autoSignIn===!1,f=t.context.options.emailAndPassword.autoSignIn===!1||u,p=dr(t.context.options,d,"create"),h=o.toLowerCase(),m=()=>{let b=new Date,O=t.context.generateId({model:"user"})||us(),g={name:n,email:h,emailVerified:!1,image:s??null,createdAt:b,updatedAt:b},S=t.context.options.emailAndPassword?.customSyntheticUser,C;if(S){let z=Object.keys(t.context.options.user?.additionalFields??{}),L={};for(let P of z)if(P in p)L[P]=p[P];let x=S({coreFields:g,additionalFields:L,id:O});C=Nr(t.context.options,x)}else C=Nr(t.context.options,{...g,...p,id:O});return t.json({token:null,user:se(t.context.options,C)})},w=await t.context.internalAdapter.findUserByEmail(h);if(w?.user){if(t.context.logger.info(`Sign-up attempt for existing email: ${o}`),u){if(await t.context.password.hash(i),t.context.options.emailAndPassword?.onExistingUserSignUp)await t.context.runInBackgroundOrAwait(t.context.options.emailAndPassword.onExistingUserSignUp({user:w.user},Tt(t.request)));return m()}throw U.from("UNPROCESSABLE_ENTITY",Ae.USER_ALREADY_EXISTS_USE_ANOTHER_EMAIL)}let y=await t.context.password.hash(i),I;try{if(I=await t.context.internalAdapter.createUser({email:h,name:n,image:s,...p,emailVerified:!1},{method:"email-password"}),!I)throw U.from("BAD_REQUEST",Ae.FAILED_TO_CREATE_USER)}catch(b){if(Br(b)){if(b.statusCode===403&&u)return m();throw b}if(El())t.context.logger.error("Failed to create user",b);throw t.context.logger?.error("Failed to create user",b),U.from("UNPROCESSABLE_ENTITY",Ae.FAILED_TO_CREATE_USER)}if(!I)throw U.from("UNPROCESSABLE_ENTITY",Ae.FAILED_TO_CREATE_USER);if(await t.context.internalAdapter.linkAccount({userId:I.id,providerId:"credential",accountId:I.id,password:y}),t.context.options.emailVerification?.sendOnSignUp??t.context.options.emailAndPassword.requireEmailVerification){let b=await Se(t.context.secret,I.email,void 0,t.context.options.emailVerification?.expiresIn),O=r.callbackURL?encodeURIComponent(r.callbackURL):encodeURIComponent("/"),g=`${t.context.baseURL}/verify-email?token=${b}&callbackURL=${O}`;if(t.context.options.emailVerification?.sendVerificationEmail)await t.context.runInBackgroundOrAwait(t.context.options.emailVerification.sendVerificationEmail({user:I,url:g,token:b},Tt(t.request)))}if(f)return t.json({token:null,user:se(t.context.options,I)});let R=await t.context.internalAdapter.createSession(I.id,c===!1,void 0,void 0,{deferSecondaryStorageWrites:!0});if(!R)throw U.from("BAD_REQUEST",Ae.FAILED_TO_CREATE_SESSION);return await pe(t,{session:R,user:I},c===!1),t.json({token:R.token,user:se(t.context.options,I)})}));var My=k(e().meta({description:"Field name must be a string"}),N()),zf=()=>Pe("/update-session",{method:"POST",operationId:"updateSession",body:My,use:[$r],metadata:{$Infer:{body:{}},openapi:{operationId:"updateSession",description:"Update the current session",responses:{"200":{description:"Success",content:{"application/json":{schema:{type:"object",properties:{session:{type:"object",$ref:"#/components/schemas/Session"}}}}}}}}}},async(t)=>{let r=t.body;if(typeof r!=="object"||Array.isArray(r))throw U.from("BAD_REQUEST",Ae.BODY_MUST_BE_AN_OBJECT);let n=t.context.session,o=Fn(t.context.options,r,"update");if(Object.keys(o).length===0)throw U.fromStatus("BAD_REQUEST",{message:"No fields to update"});let i=await t.context.internalAdapter.updateSession(n.session.token,{...o,updatedAt:new Date});if(!i&&St(t))throw Le(t),U.from("UNAUTHORIZED",Ae.FAILED_TO_GET_SESSION);let s=i??{...n.session,...o,updatedAt:new Date};return await pe(t,{session:s,user:n.user}),t.json({session:we(t.context.options,s)})});var Hy=k(e().meta({description:"Field name must be a string"}),N()),Nf=()=>Pe("/update-user",{method:"POST",operationId:"updateUser",body:Hy,use:[$r],metadata:{$Infer:{body:{}},openapi:{operationId:"updateUser",description:"Update the current user",requestBody:{content:{"application/json":{schema:{type:"object",properties:{name:{type:"string",description:"The name of the user"},image:{type:"string",description:"The image of the user",nullable:!0}}}}}},responses:{"200":{description:"Success",content:{"application/json":{schema:{type:"object",properties:{user:{type:"object",$ref:"#/components/schemas/User"}}}}}}}}}},async(t)=>{let r=t.body;if(typeof r!=="object"||Array.isArray(r))throw U.from("BAD_REQUEST",Ae.BODY_MUST_BE_AN_OBJECT);if(r.email)throw U.from("BAD_REQUEST",Ae.EMAIL_CAN_NOT_BE_UPDATED);let{name:n,image:o,...i}=r,s=t.context.session,a=dr(t.context.options,i,"update");if(o===void 0&&n===void 0&&Object.keys(a).length===0)throw U.fromStatus("BAD_REQUEST",{message:"No fields to update"});let c=await t.context.internalAdapter.updateUser(s.user.id,{name:n,image:o,...a})??{...s.user,...n!==void 0&&{name:n},...o!==void 0&&{image:o},...a};return await pe(t,{session:s.session,user:c}),t.json({status:!0})}),qf=Pe("/change-password",{method:"POST",operationId:"changePassword",body:l({newPassword:e().meta({description:"The new password to set"}),currentPassword:e().meta({description:"The current password is required"}),revokeOtherSessions:E().meta({description:"Must be a boolean value"}).optional()}),use:[Qe],metadata:{openapi:{operationId:"changePassword",description:"Change the password of the user",responses:{"200":{description:"Password successfully changed",content:{"application/json":{schema:{type:"object",properties:{token:{type:"string",nullable:!0,description:"New session token if other sessions were revoked"},user:{type:"object",properties:{id:{type:"string",description:"The unique identifier of the user"},email:{type:"string",format:"email",description:"The email address of the user"},name:{type:"string",description:"The name of the user"},image:{type:"string",format:"uri",nullable:!0,description:"The profile image URL of the user"},emailVerified:{type:"boolean",description:"Whether the email has been verified"},createdAt:{type:"string",format:"date-time",description:"When the user was created"},updatedAt:{type:"string",format:"date-time",description:"When the user was last updated"}},required:["id","email","name","emailVerified","createdAt","updatedAt"]}},required:["user"]}}}}}}}},async(t)=>{let{newPassword:r,currentPassword:n,revokeOtherSessions:o}=t.body,i=t.context.session;Ht(t,r),xe(t,r),xe(t,n);let s=await t.context.internalAdapter.findCredentialAccount(i.user.id);if(!s||!s.password)throw U.from("BAD_REQUEST",Ae.CREDENTIAL_ACCOUNT_NOT_FOUND);let a=await t.context.password.hash(r);if(!await t.context.password.verify({hash:s.password,password:n}))throw U.from("BAD_REQUEST",Ae.INVALID_PASSWORD);let c=await Ue(t.context.adapter,async()=>{if(o)await t.context.internalAdapter.deleteUserSessions(i.user.id);if(await t.context.internalAdapter.updateAccount(s.id,{password:a}),!o)return null;let u=await t.context.internalAdapter.createSession(i.user.id,void 0,void 0,void 0,{deferSecondaryStorageWrites:!0});if(!u)throw U.from("INTERNAL_SERVER_ERROR",Ae.FAILED_TO_GET_SESSION);return u}),d=null;if(c)await pe(t,{session:c,user:i.user}),d=c.token;return t.json({token:d,user:se(t.context.options,i.user)})}),jf=Pe.serverOnly({method:"POST",body:l({newPassword:e().meta({description:"The new password to set is required"})}),use:[Qe]},async(t)=>{let{newPassword:r}=t.body,n=t.context.session;Ht(t,r),xe(t,r);let o=await t.context.internalAdapter.findCredentialAccount(n.user.id),i=await t.context.password.hash(r);if(!o)return await t.context.internalAdapter.linkAccount({userId:n.user.id,providerId:"credential",accountId:n.user.id,password:i}),t.json({status:!0});if(!o.password)return await t.context.internalAdapter.updateAccount(o.id,{password:i}),t.json({status:!0});throw U.from("BAD_REQUEST",Ae.PASSWORD_ALREADY_SET)}),Bf=Pe("/delete-user",{method:"POST",use:[Qe],body:l({callbackURL:e().meta({description:"The callback URL to redirect to after the user is deleted"}).optional(),password:e().meta({description:"The password of the user is required to delete the user"}).optional(),token:e().meta({description:"The token to delete the user is required"}).optional()}),metadata:{openapi:{operationId:"deleteUser",description:"Delete the user",requestBody:{content:{"application/json":{schema:{type:"object",properties:{callbackURL:{type:"string",description:"The callback URL to redirect to after the user is deleted"},password:{type:"string",description:"The user's password. Required if session is not fresh"},token:{type:"string",description:"The deletion verification token"}}}}}},responses:{"200":{description:"User deletion processed successfully",content:{"application/json":{schema:{type:"object",properties:{success:{type:"boolean",description:"Indicates if the operation was successful"},message:{type:"string",enum:["User deleted","Verification email sent"],description:"Status message of the deletion process"}},required:["success","message"]}}}}}}}},async(t)=>{if(!t.context.options.user?.deleteUser?.enabled)throw t.context.logger.error("Delete user is disabled. Enable it in the options"),U.fromStatus("NOT_FOUND");let r=t.context.session;if(t.body.password){xe(t,t.body.password);let i=await t.context.internalAdapter.findCredentialAccount(r.user.id);if(!i||!i.password)throw U.from("BAD_REQUEST",Ae.CREDENTIAL_ACCOUNT_NOT_FOUND);if(!await t.context.password.verify({hash:i.password,password:t.body.password}))throw U.from("BAD_REQUEST",Ae.INVALID_PASSWORD)}if(t.body.token)return await Bs({...t,query:{token:t.body.token}}),t.json({success:!0,message:"User deleted"});if(t.context.options.user.deleteUser?.sendDeleteAccountVerification){let i=_e(32,"0-9","a-z");await t.context.internalAdapter.createVerificationValue({value:r.user.id,identifier:`delete-account-${i}`,expiresAt:new Date(Date.now()+(t.context.options.user.deleteUser?.deleteTokenExpiresIn||86400)*1000)});let s=`${t.context.baseURL}/delete-user/callback?token=${i}&callbackURL=${encodeURIComponent(t.body.callbackURL||"/")}`;return await t.context.runInBackgroundOrAwait(t.context.options.user.deleteUser.sendDeleteAccountVerification({user:r.user,url:s,token:i},t.request)),t.json({success:!0,message:"Verification email sent"})}if(!t.body.password&&t.context.sessionConfig.freshAge!==0){let i=new Date(r.session.createdAt).getTime(),s=t.context.sessionConfig.freshAge*1000;if(Date.now()-i>=s)throw U.from("BAD_REQUEST",Ae.SESSION_EXPIRED)}let n=t.context.options.user.deleteUser?.beforeDelete;if(n)await n(r.user,t.request);await t.context.internalAdapter.deleteUser(r.user.id),await t.context.internalAdapter.deleteUserSessions(r.user.id),Le(t);let o=t.context.options.user.deleteUser?.afterDelete;if(o)await o(r.user,t.request);return t.json({success:!0,message:"User deleted"})}),Bs=Pe("/delete-user/callback",{method:"GET",query:l({token:e().meta({description:"The token to verify the deletion request"}),callbackURL:e().meta({description:"The URL to redirect to after deletion"}).optional()}),use:[bt((t)=>t.query.callbackURL)],metadata:{openapi:{description:"Callback to complete user deletion with verification token",responses:{"200":{description:"User successfully deleted",content:{"application/json":{schema:{type:"object",properties:{success:{type:"boolean",description:"Indicates if the deletion was successful"},message:{type:"string",enum:["User deleted"],description:"Confirmation message"}},required:["success","message"]}}}}}}}},async(t)=>{if(!t.context.options.user?.deleteUser?.enabled)throw t.context.logger.error("Delete user is disabled. Enable it in the options"),U.from("NOT_FOUND",{message:"Not found",code:"NOT_FOUND"});let r=await ee(t,{disableCookieCache:St(t)});if(!r)throw U.from("NOT_FOUND",Ae.FAILED_TO_GET_USER_INFO);let n=await t.context.internalAdapter.consumeVerificationValue(`delete-account-${t.query.token}`);if(!n||n.value!==r.user.id)throw U.from("NOT_FOUND",Ae.INVALID_TOKEN);let o=t.context.options.user.deleteUser?.beforeDelete;if(o)await o(r.user,t.request);await t.context.internalAdapter.deleteUser(r.user.id),await t.context.internalAdapter.deleteUserSessions(r.user.id),await t.context.internalAdapter.deleteAccounts(r.user.id),Le(t);let i=t.context.options.user.deleteUser?.afterDelete;if(i)await i(r.user,t.request);if(t.query.callbackURL)throw t.redirect(t.query.callbackURL||"/");return t.json({success:!0,message:"User deleted"})}),$f=Pe("/change-email",{method:"POST",body:l({newEmail:In().meta({description:"The new email address to set must be a valid email address"}),callbackURL:e().meta({description:"The URL to redirect to after email verification"}).optional()}),use:[Qe],metadata:{openapi:{operationId:"changeEmail",responses:{"200":{description:"Email change request processed successfully",content:{"application/json":{schema:{type:"object",properties:{user:{type:"object",$ref:"#/components/schemas/User"},status:{type:"boolean",description:"Indicates if the request was successful"},message:{type:"string",enum:["Email updated","Verification email sent"],description:"Status message of the email change process",nullable:!0}},required:["status"]}}}}}}}},async(t)=>{if(!t.context.options.user?.changeEmail?.enabled)throw t.context.logger.error("Change email is disabled."),U.from("BAD_REQUEST",Ae.CHANGE_EMAIL_DISABLED);let r=t.body.newEmail.toLowerCase();if(r===t.context.session.user.email)throw t.context.logger.warn("Email is the same"),U.fromStatus("BAD_REQUEST",{message:"Email is the same"});let n=t.context.session.user.emailVerified!==!0&&t.context.options.user.changeEmail.updateEmailWithoutVerification,o=t.context.options.emailVerification?.sendVerificationEmail,i=o&&t.context.session.user.emailVerified&&t.context.options.user.changeEmail.sendChangeEmailConfirmation;if(!n&&!i&&!o)throw t.context.logger.error("Verification email isn't enabled."),U.fromStatus("BAD_REQUEST",{message:"Verification email isn't enabled"});if(await t.context.internalAdapter.findUserByEmail(r))return await Se(t.context.secret,t.context.session.user.email,r,t.context.options.emailVerification?.expiresIn),t.context.logger.info("Change email attempt for existing email"),t.json({status:!0});if(n){if(await t.context.internalAdapter.updateUser(t.context.session.user.id,{email:r}),await pe(t,{session:t.context.session.session,user:{...t.context.session.user,email:r}}),o){let c=await Se(t.context.secret,r,void 0,t.context.options.emailVerification?.expiresIn),d=`${t.context.baseURL}/verify-email?token=${c}&callbackURL=${encodeURIComponent(t.body.callbackURL||"/")}`;await t.context.runInBackgroundOrAwait(o({user:{...t.context.session.user,email:r},url:d,token:c},t.request))}return t.json({status:!0})}if(i){let c=await Se(t.context.secret,t.context.session.user.email,r,t.context.options.emailVerification?.expiresIn,{requestType:"change-email-confirmation"}),d=`${t.context.baseURL}/verify-email?token=${c}&callbackURL=${encodeURIComponent(t.body.callbackURL||"/")}`;return await t.context.runInBackgroundOrAwait(i({user:t.context.session.user,newEmail:r,url:d,token:c},t.request)),t.json({status:!0})}if(!o)throw t.context.logger.error("Verification email isn't enabled."),U.fromStatus("BAD_REQUEST",{message:"Verification email isn't enabled"});let s=await Se(t.context.secret,t.context.session.user.email,r,t.context.options.emailVerification?.expiresIn,{requestType:"change-email-verification"}),a=`${t.context.baseURL}/verify-email?token=${s}&callbackURL=${encodeURIComponent(t.body.callbackURL||"/")}`;return await t.context.runInBackgroundOrAwait(o({user:{...t.context.session.user,email:r},url:a,token:s},t.request)),t.json({status:!0})});var Mf=Qr((t,r,n)=>{if(Array.isArray(t[r])&&Array.isArray(n))return t[r]=n,!0}),Zt=new WeakMap;function $s(t,r){let n=t.options;return n?.operationId??n?.metadata?.openapi?.operationId??r??t.path??"/:virtual"}function Hf(t,r){if(!r)return;r.forEach((n,o)=>{if(!t.responseHeaders)t.responseHeaders=new Headers({[o]:n});else if(o.toLowerCase()==="set-cookie")t.responseHeaders.append(o,n);else t.responseHeaders.set(o,n)})}function Vf(t){let r=t[qa],n=t.headers&&t.headers!==r?new Headers(t.headers):null;if(!r&&!n)return null;let o=new Headers;return r?.forEach((i,s)=>{o.append(s,i)}),n?.forEach((i,s)=>{if(s.toLowerCase()==="set-cookie")o.append(s,i);else o.set(s,i)}),o}async function Vy(t,r,n,o){let i=ds(t.context.options),s={};for(let a of r){let c=!1;try{c=a.matcher(t)}catch(h){let m=Zt.get(a.handler)??"unknown";throw t.context.logger.error(`An error occurred during ${m} hook matcher execution:`,h),new U("INTERNAL_SERVER_ERROR",{message:"An error occurred during hook matcher execution. Check the logs for more details."})}if(!c)continue;let d=Zt.get(a.handler)??"unknown",u=n.path??"/:virtual",f=await i(`hook before ${u} ${d}`,{[pn]:"before",[$a]:u,[mn]:d,[kc]:o},()=>a.handler({...t,returnHeaders:!0})).catch((h)=>{if(Br(h)&&Ic(t.context.logger.level,"debug"))h.stack=h.errorStack;throw h});Hf(t.context,f?.headers);let p=f?.response;if(p&&typeof p==="object"){if("context"in p&&typeof p.context==="object"){let{headers:h,...m}=p.context;if(h instanceof Headers)if(s.headers)h.forEach((w,y)=>{s.headers?.set(y,w)});else s.headers=h;s=Mf(m,s);continue}return p}}return{context:s}}async function Fy(t,r,n,o){let i=ds(t.context.options);for(let s of r){if(!s.matcher(t))continue;let a=Zt.get(s.handler)??"unknown",c=n.path??"/:virtual",d=await i(`hook after ${c} ${a}`,{[pn]:"after",[$a]:c,[mn]:a,[kc]:o},()=>s.handler(t)).catch((u)=>{if(Br(u)){if(Ic(t.context.logger.level,"debug"))u.stack=u.errorStack;return{response:u,headers:Vf(u)}}throw u});if(Hf(t.context,d.headers),d.response!==void 0)t.context.returned=d.response}return{response:t.context.returned,headers:t.context.responseHeaders}}function Ky(t){let r=t.options.plugins||[],n=[],o=[],i=t.options.hooks?.before;if(i)Zt.set(i,"user"),n.push({matcher:()=>!0,handler:i});let s=t.options.hooks?.after;if(s)Zt.set(s,"user"),o.push({matcher:()=>!0,handler:s});let a=r.flatMap((d)=>(d.hooks?.before??[]).map((u)=>(Zt.set(u.handler,`plugin:${d.id}`),u))),c=r.flatMap((d)=>(d.hooks?.after??[]).map((u)=>(Zt.set(u.handler,`plugin:${d.id}`),u)));if(a.length)n.push(...a);if(c.length)o.push(...c);return{beforeHooks:n,afterHooks:o}}async function bn(t,r){let n=ds(r.context.options),o=r.operationId??$s(t),i=t.path??"/:virtual",s=t.options?.method,a=Array.isArray(s)?s[0]:s,c=r.method??r.request?.method??a??"?",d=r.asResponse??je(r.request),u={...r,context:{...r.context,returned:void 0,responseHeaders:void 0,session:r.context.session??null},path:t.path,headers:r.headers?new Headers(r.headers):void 0};return n(`${c} ${i}`,{[$a]:i,[kc]:o},async()=>hr(u,async()=>{let{beforeHooks:f,afterHooks:p}=Ky(u.context),h=await Vy(u,f,t,o);if("context"in h&&h.context&&typeof h.context==="object"){let{headers:y,...I}=h.context;if(y){if(!u.headers)u.headers=new Headers;let R=u.headers;y.forEach((b,O)=>{R.set(O,b)})}u=Mf(I,u)}else if(h){let y=u.context.responseHeaders;return d?We(h,{headers:y}):r.returnHeaders?{headers:y,response:h}:h}u.asResponse=!1,u.returnHeaders=!0,u.returnStatus=!0;let m=await hr(u,()=>n(`handler ${i}`,{[$a]:i,[kc]:o},()=>t(u))).catch((y)=>{if(Br(y))return{response:y,status:y.statusCode,headers:Vf(y)};throw y});if(m instanceof Response)return m;u.context.returned=m.response,u.context.responseHeaders=m.headers??void 0;let w=await Fy(u,p,t,o);if(w.response!==void 0)m.response=w.response;if(m.headers=w.headers??m.headers,Br(m.response)&&Ic(u.context.logger.level,"debug"))m.response.stack=m.response.errorStack;if(Br(m.response)&&!d){if(m.headers)Object.defineProperty(m.response,qa,{enumerable:!1,configurable:!0,writable:!1,value:m.headers});throw m.response}return d?We(m.response,{headers:m.headers??void 0,status:m.status}):r.returnHeaders?r.returnStatus?{headers:m.headers,response:m.response,status:m.status}:{headers:m.headers,response:m.response}:r.returnStatus?{response:m.response,status:m.status}:m.response}))}async function Wy(t,r){if(t.baseURL)return t;let n=fd(r),o=t.options.baseURL,i=ls(o)&&Boolean(o.fallback);if(n===void 0&&!i)throw new U("INTERNAL_SERVER_ERROR",{message:"Dynamic baseURL could not be resolved for this direct auth.api call. Pass `headers: request.headers` (or `request`) to the call, or add `fallback` to your baseURL config."});try{return await ff(t,n,df(t.options))}catch(s){if(s instanceof te)throw new U("INTERNAL_SERVER_ERROR",{message:s.message});throw s}}function Ff(t,r){let n={};for(let[o,i]of Object.entries(t))n[o]=async(s)=>{let a=$s(i,o),c=async()=>{let d=await r,u=d.checkSchema?.();if(u)await u;let f=ls(d.options.baseURL)?await Wy(d,s):d;return bn(i,{...s,context:f,operationId:a,asResponse:s?.asResponse??je(s?.request)})};if(await zi())return c();return Ni(new WeakMap,c)},n[o].path=i.path,n[o].options=i.options;return n}function Vg(t,r){let n=new Map;t.plugins?.forEach((i)=>{if(i.endpoints){for(let[s,a]of Object.entries(i.endpoints))if(a&&"path"in a&&typeof a.path==="string"){let c=a.path,d=[];if(a.options&&"method"in a.options){if(Array.isArray(a.options.method))d=a.options.method;else if(typeof a.options.method==="string")d=[a.options.method]}if(d.length===0)d=["*"];if(!n.has(c))n.set(c,[]);n.get(c).push({pluginId:i.id,endpointKey:s,methods:d})}}});let o=[];for(let[i,s]of n.entries())if(s.length>1){let a=new Map,c=!1;for(let d of s)for(let u of d.methods){if(!a.has(u))a.set(u,[]);if(a.get(u).push(d.pluginId),a.get(u).length>1)c=!0;if(u==="*"&&s.length>1)c=!0;else if(u!=="*"&&a.has("*"))c=!0}if(c){let d=[...new Set(s.map((f)=>f.pluginId))],u=[];for(let[f,p]of a.entries())if(p.length>1||f==="*"&&s.length>1||f!=="*"&&a.has("*"))u.push(f);o.push({path:i,plugins:d,conflictingMethods:u})}}if(o.length>0){let i=o.map((s)=>` - "${s.path}" [${s.conflictingMethods.join(", ")}] used by plugins: ${s.plugins.join(", ")}`).join(`
385
+ </html>`},sf=Pe("/error",{method:"GET",metadata:{...br,openapi:{description:"Displays an error page",responses:{"200":{description:"Success",content:{"text/html":{schema:{type:"string",description:"The HTML content of the error page"}}}}}}}},async(t)=>{let r=new URL(t.request?.url||""),n=r.searchParams.get("error")||"UNKNOWN",o=r.searchParams.get("error_description")||null,i=/^[\'A-Za-z0-9_-]+$/.test(n||"")?n:"UNKNOWN",s=o?of(o):null,a=new URLSearchParams;if(a.set("error",i),o)a.set("error_description",o);let c=t.context.options,d=c.onAPIError?.errorURL;if(d){let u=$e(d,a);return new Response(null,{status:302,headers:{Location:u}})}if(Xi&&!c.onAPIError?.customizeDefaultErrorPage)return new Response(null,{status:302,headers:{Location:`/?${a.toString()}`}});return new Response(xy(t.context.options,i,s),{headers:{"Content-Type":"text/html"}})});var af=Pe("/ok",{method:"GET",metadata:{...br,openapi:{description:"Check if the API is working",responses:{"200":{description:"API is working",content:{"application/json":{schema:{type:"object",properties:{ok:{type:"boolean",description:"Indicates if the API is working"}},required:["ok"]}}}}}}}},async(t)=>t.json({ok:!0}));function lf(t,r,n){let o=r?new URL(r,t.baseURL):new URL(`${t.baseURL}/error`);if(n)Object.entries(n).forEach(([i,s])=>o.searchParams.set(i,s));return o.href}function zy(t,r,n){let o=new URL(r,t.baseURL);if(n)Object.entries(n).forEach(([i,s])=>o.searchParams.set(i,s));return o.href}var wf=Pe("/request-password-reset",{method:"POST",body:l({email:Tn().meta({description:"The email address of the user to send a password reset email to"}),redirectTo:e().meta({description:"The URL to redirect the user to reset their password. If the token isn't valid or expired, it'll be redirected with a query parameter `?error=INVALID_TOKEN`. If the token is valid, it'll be redirected with a query parameter `?token=VALID_TOKEN"}).optional()}),metadata:{openapi:{operationId:"requestPasswordReset",description:"Send a password reset email to the user",responses:{"200":{description:"Success",content:{"application/json":{schema:{type:"object",properties:{status:{type:"boolean"},message:{type:"string"}}}}}}}}},use:[bt((t)=>t.body.redirectTo)]},async(t)=>{if(!t.context.options.emailAndPassword?.sendResetPassword)throw t.context.logger.error("Reset password isn't enabled.Please pass an emailAndPassword.sendResetPassword function in your auth config!"),U.from("BAD_REQUEST",{message:"Reset password isn't enabled",code:"RESET_PASSWORD_DISABLED"});let{email:r,redirectTo:n}=t.body,o=await t.context.internalAdapter.findUserByEmail(r,{includeAccounts:!0});if(!o)return us(24),await t.context.internalAdapter.findVerificationValue("dummy-verification-token"),t.context.logger.warn("Reset Password: User not found"),t.json({status:!0,message:"If this email exists in our system, check your email for the reset link"});let i=ut(t.context.options.emailAndPassword.resetPasswordTokenExpiresIn||3600,"sec"),s=us(24);await t.context.internalAdapter.createVerificationValue({value:o.user.id,identifier:`reset-password:${s}`,expiresAt:i});let a=n?encodeURIComponent(n):"",c=`${t.context.baseURL}/reset-password/${s}?callbackURL=${a}`;return await t.context.runInBackgroundOrAwait(t.context.options.emailAndPassword.sendResetPassword({user:o.user,url:c,token:s},t.request)),t.json({status:!0,message:"If this email exists in our system, check your email for the reset link"})}),kf=Pe("/reset-password/:token",{method:"GET",operationId:"resetPasswordCallback",query:l({callbackURL:e().meta({description:"The URL to redirect the user to reset their password"})}),use:[bt((t)=>t.query.callbackURL)],metadata:{openapi:{operationId:"resetPasswordCallback",description:"Redirects the user to the callback URL with the token",parameters:[{name:"token",in:"path",required:!0,description:"The token to reset the password",schema:{type:"string"}},{name:"callbackURL",in:"query",required:!0,description:"The URL to redirect the user to reset their password",schema:{type:"string"}}],responses:{"200":{description:"Success",content:{"application/json":{schema:{type:"object",properties:{token:{type:"string"}}}}}}}}}},async(t)=>{let{token:r}=t.params,{callbackURL:n}=t.query;if(!r||!n)throw t.redirect(lf(t.context,n,{error:"INVALID_TOKEN"}));let o=await t.context.internalAdapter.findVerificationValue(`reset-password:${r}`);if(!o||o.expiresAt<new Date)throw t.redirect(lf(t.context,n,{error:"INVALID_TOKEN"}));throw t.redirect(zy(t.context,n,{token:r}))}),Ef=Pe("/reset-password",{method:"POST",operationId:"resetPassword",query:l({token:e().optional()}).optional(),body:l({newPassword:e().meta({description:"The new password to set"}),token:e().meta({description:"The token to reset the password"}).optional()}),metadata:{openapi:{operationId:"resetPassword",description:"Reset the password for a user",responses:{"200":{description:"Success",content:{"application/json":{schema:{type:"object",properties:{status:{type:"boolean"}}}}}}}}}},async(t)=>{let r=t.body.token||t.query?.token;if(!r)throw U.from("BAD_REQUEST",Ae.INVALID_TOKEN);let{newPassword:n}=t.body;Ht(t,n),xe(t,n);let o=`reset-password:${r}`,i=await t.context.internalAdapter.findVerificationValue(o);if(!i||i.expiresAt<new Date)throw U.from("BAD_REQUEST",Ae.INVALID_TOKEN);let s=i.value,a=await t.context.internalAdapter.findUserById(s);if(!a)throw U.from("BAD_REQUEST",Ae.USER_NOT_FOUND);if(await pd(t,s,await t.context.password.hash(n),async()=>{if(!await t.context.internalAdapter.consumeVerificationValue(o))throw U.from("BAD_REQUEST",Ae.INVALID_TOKEN)}),t.context.options.emailAndPassword?.onPasswordReset)await t.context.options.emailAndPassword.onPasswordReset({user:a},t.request);return t.json({status:!0})}),bf=Pe("/verify-password",{method:"POST",body:l({password:e().meta({description:"The password to verify"})}),metadata:{scope:"server",openapi:{operationId:"verifyPassword",description:"Verify the current user's password",responses:{"200":{description:"Success",content:{"application/json":{schema:{type:"object",properties:{status:{type:"boolean"}}}}}}}}},use:[Qe]},async(t)=>{let{password:r}=t.body,n=t.context.session;if(!await hd(t,{password:r,userId:n.user.id}))throw U.from("BAD_REQUEST",Ae.INVALID_PASSWORD);return t.json({status:!0})});var Ny=l({callbackURL:e().meta({description:"Callback URL to redirect to after the user has signed in"}).optional(),newUserCallbackURL:e().optional(),errorCallbackURL:e().meta({description:"Callback URL to redirect to if an error happens"}).optional(),provider:Uo,disableRedirect:E().meta({description:"Disable automatic redirection to the provider. Useful for handling the redirection yourself"}).optional(),idToken:ye(l({token:e().meta({description:"ID token from the provider"}),nonce:e().meta({description:"Nonce used to generate the token"}).optional(),accessToken:e().meta({description:"Access token from the provider"}).optional(),refreshToken:e().meta({description:"Refresh token from the provider"}).optional(),expiresAt:_().meta({description:"Expiry date of the token"}).optional(),user:l({name:l({firstName:e().optional(),lastName:e().optional()}).optional(),email:e().optional()}).meta({description:"The user object from the provider. Only available for some providers like Apple."}).optional()})),scopes:A(e()).meta({description:"Array of scopes to request from the provider. This will override the default scopes passed."}).optional(),requestSignUp:E().meta({description:"Explicitly request sign-up. Useful when disableImplicitSignUp is true for this provider"}).optional(),loginHint:e().meta({description:"The login hint to use for the authorization code request"}).optional(),additionalParams:cn,additionalData:k(e(),N()).optional().meta({description:"Additional data to be passed through the OAuth flow"})}),Uf=()=>Pe("/sign-in/social",{method:"POST",operationId:"socialSignIn",body:Ny,metadata:{$Infer:{body:{},returned:{}},openapi:{description:"Sign in with a social provider",operationId:"socialSignIn",responses:{"200":{description:"Success - Returns session details (idToken branch) or an authorize URL (redirect branch)",content:{"application/json":{schema:{type:"object",description:"Returns session details when idToken is provided, or an authorize URL otherwise",properties:{token:{type:"string"},user:{type:"object",$ref:"#/components/schemas/User"},url:{type:"string"},redirect:{type:"boolean"}},required:["redirect"]}}}}}}}},async(t)=>{let r=await tt(t.context.socialProviders,{value:t.body.provider});if(!r)throw t.context.logger.error("Provider not found. Make sure to add the provider in your auth config",{provider:t.body.provider}),U.from("NOT_FOUND",Ae.PROVIDER_NOT_FOUND);if(t.body.idToken){if(!_n(r))throw t.context.logger.error("Provider does not support id token verification",{provider:t.body.provider}),U.from("NOT_FOUND",Ae.ID_TOKEN_NOT_SUPPORTED);let{token:a,nonce:c}=t.body.idToken;if(!await An(r,a,c,t))throw t.context.logger.warn("Invalid id token",{provider:t.body.provider}),U.from("UNAUTHORIZED",Ae.INVALID_TOKEN);let d={idToken:a,accessToken:t.body.idToken.accessToken,refreshToken:t.body.idToken.refreshToken,user:t.body.idToken.user},u=await r.getUserInfo(d);if(!u||!u?.user)throw t.context.logger.error("Failed to get user info",{provider:t.body.provider}),U.from("UNAUTHORIZED",Ae.FAILED_TO_GET_USER_INFO);if(!u.user.email)throw t.context.logger.error(wr(t.body.provider,{source:"id_token"}),{provider:t.body.provider}),U.from("UNAUTHORIZED",Ae.USER_EMAIL_NOT_FOUND);let f=await mo(r,d,u.data),p=ho(u.data),h=await Io(t,{userInfo:{...u.user,email:u.user.email,id:f.accountId,name:u.user.name||"",image:u.user.image,emailVerified:u.user.emailVerified||!1},account:{...f,accessToken:t.body.idToken.accessToken,idToken:a},callbackURL:t.body.callbackURL,disableSignUp:r.disableImplicitSignUp&&!t.body.requestSignUp||r.options?.disableSignUp||r.disableSignUp,source:{method:"oauth",oauth:{providerId:r.id,profile:p}}});if(h.error){if(h.error===he.EMAIL_NOT_VERIFIED)throw U.from("FORBIDDEN",Ae.EMAIL_NOT_VERIFIED);throw U.from("UNAUTHORIZED",{message:h.error,code:"OAUTH_LINK_ERROR"})}return await pe(t,h.data),t.json({redirect:!1,token:h.data.session.token,url:void 0,user:se(t.context.options,h.data.user)})}let n=kr(r),{codeVerifier:o,state:i}=await Er(t,{additionalData:t.body.additionalData,idTokenNonce:n}),s=await r.createAuthorizationURL({state:i,codeVerifier:o,idTokenNonce:n,redirectURI:`${t.context.baseURL}${Rt(r)}`,scopes:t.body.scopes,loginHint:t.body.loginHint,additionalParams:t.body.additionalParams});if(!t.body.disableRedirect)t.setHeader("Location",s.toString());return t.json({url:s.toString(),redirect:!t.body.disableRedirect})}),Of=()=>Pe("/sign-in/email",{method:"POST",operationId:"signInEmail",use:[Yr],cloneRequest:!0,body:l({email:e().meta({description:"Email of the user"}),password:e().meta({description:"Password of the user"}),callbackURL:e().meta({description:"Callback URL to use as a redirect for email verification"}).optional(),rememberMe:E().meta({description:"If this is false, the session will not be remembered. Default is `true`."}).default(!0).optional()}),metadata:{allowedMediaTypes:["application/x-www-form-urlencoded","application/json"],$Infer:{body:{},returned:{}},openapi:{operationId:"signInEmail",description:"Sign in with email and password",responses:{"200":{description:"Success - Returns either session details or redirect URL",content:{"application/json":{schema:{type:"object",description:"Session response when idToken is provided",properties:{redirect:{type:"boolean",enum:[!1]},token:{type:"string",description:"Session token"},url:{type:"string",nullable:!0},user:{type:"object",$ref:"#/components/schemas/User"}},required:["redirect","token","user"]}}}}}}}},async(t)=>{if(!t.context.options?.emailAndPassword?.enabled)throw t.context.logger.error("Email and password is not enabled. Make sure to enable it in the options on you `auth.ts` file. Check `https://better-auth.com/docs/authentication/email-password` for more!"),U.from("BAD_REQUEST",{code:"EMAIL_PASSWORD_DISABLED",message:"Email and password is not enabled"});let{email:r,password:n}=t.body;if(!Tn().safeParse(r).success)throw U.from("BAD_REQUEST",Ae.INVALID_EMAIL);xe(t,n);let o=await t.context.internalAdapter.findUserByEmail(r.toLowerCase(),{includeAccounts:!0}),i=o?.accounts.find((d)=>d.providerId==="credential"&&d.accountId===o.user.id);if(!o||!i)throw await t.context.password.hash(n),t.context.logger.warn("User not found"),U.from("UNAUTHORIZED",Ae.INVALID_EMAIL_OR_PASSWORD);let s=o.user,a=i.password;if(!a)throw await t.context.password.hash(n),t.context.logger.warn("Password not found"),U.from("UNAUTHORIZED",Ae.INVALID_EMAIL_OR_PASSWORD);if(!await t.context.password.verify({hash:a,password:n}))throw t.context.logger.warn("Invalid password"),U.from("UNAUTHORIZED",Ae.INVALID_EMAIL_OR_PASSWORD);if(t.context.options?.emailAndPassword?.requireEmailVerification&&!s.emailVerified){if(!t.context.options?.emailVerification?.sendVerificationEmail)throw U.from("FORBIDDEN",Ae.EMAIL_NOT_VERIFIED);if(t.context.options?.emailVerification?.sendOnSignIn){let d=await Se(t.context.secret,s.email,void 0,t.context.options.emailVerification?.expiresIn),u=t.body.callbackURL?encodeURIComponent(t.body.callbackURL):encodeURIComponent("/"),f=`${t.context.baseURL}/verify-email?token=${d}&callbackURL=${u}`;await t.context.runInBackgroundOrAwait(t.context.options.emailVerification.sendVerificationEmail({user:s,url:f,token:d},Tt(t.request)))}throw U.from("FORBIDDEN",Ae.EMAIL_NOT_VERIFIED)}let c=await t.context.internalAdapter.createSession(s.id,t.body.rememberMe===!1);if(!c)throw t.context.logger.error("Failed to create session"),U.from("UNAUTHORIZED",Ae.FAILED_TO_CREATE_SESSION);if(await pe(t,{session:c,user:s},t.body.rememberMe===!1),t.body.callbackURL)t.setHeader("Location",t.body.callbackURL);return t.json({redirect:!!t.body.callbackURL,token:c.token,url:t.body.callbackURL,user:se(t.context.options,s)})});var qy=l({callbackURL:e().meta({description:"The URL to redirect to after provider logout"}).optional(),disableRedirect:E().meta({description:"Return the provider logout URL without redirecting"}).optional(),state:e().meta({description:"State to pass to the provider logout endpoint"}).optional()}).optional(),Df=(t)=>({success:!0,url:t?.url,redirect:t?.redirect}),Lf=Pe("/sign-out",{method:"POST",body:qy,operationId:"signOut",requireHeaders:!0,metadata:{openapi:{operationId:"signOut",description:"Sign out the current user",responses:{"200":{description:"Success",content:{"application/json":{schema:{type:"object",properties:{success:{type:"boolean"},url:{type:"string",description:"Provider logout URL when RP-initiated logout is available"},redirect:{type:"boolean",description:"Whether the client should redirect to the provider logout URL"}}}}}}}}}},async(t)=>{let r=await t.getSignedCookie(t.context.authCookies.sessionToken.name,t.context.secret),n=null;if(r)try{n=await t.context.internalAdapter.findSession(r)}catch(i){t.context.logger.error("Failed to read session from database",i)}if(r)try{await t.context.internalAdapter.deleteSession(r)}catch(i){t.context.logger.error("Failed to delete session from database",i)}Le(t);let o=await(async()=>{try{if(!n)return null;let i=await t.context.internalAdapter.findAccounts(n.user.id),s=new Map(t.context.socialProviders.map((u)=>[u.id,u])),a=i.filter((u)=>Boolean(s.get(u.providerId)?.createEndSessionURL)).sort((u,f)=>f.updatedAt.getTime()-u.updatedAt.getTime());if(a.length===0)return null;let c=new Set,d=t.body?.callbackURL?new URL(t.body.callbackURL,t.context.baseURL).toString():void 0;for(let u of a){if(c.has(u.providerId))continue;c.add(u.providerId);let f=s.get(u.providerId);try{let p=await f?.createEndSessionURL?.({idToken:u.idToken,postLogoutRedirectURI:d,state:t.body?.state});if(p)return p.toString()}catch(p){t.context.logger.error(`Failed to create logout URL for provider "${u.providerId}"`,p)}}return null}catch(i){return t.context.logger.error("Failed to create provider logout URL",i),null}})();if(o){let i=!t.body?.disableRedirect;if(i)t.setHeader("Location",o);return t.json(Df({url:o,redirect:i}))}return t.json(Df())});var jy=l({name:e(),email:Tn(),password:e().nonempty(),image:e().optional(),callbackURL:e().optional(),rememberMe:E().optional()}).and(k(e(),N())),Pf=()=>Pe("/sign-up/email",{method:"POST",operationId:"signUpWithEmailAndPassword",use:[Yr],body:jy,cloneRequest:!0,metadata:{allowedMediaTypes:["application/x-www-form-urlencoded","application/json"],$Infer:{body:{},returned:{}},openapi:{operationId:"signUpWithEmailAndPassword",description:"Sign up a user using email and password",requestBody:{content:{"application/json":{schema:{type:"object",properties:{name:{type:"string",description:"The name of the user"},email:{type:"string",description:"The email of the user"},password:{type:"string",description:"The password of the user"},image:{type:"string",description:"The profile image URL of the user"},callbackURL:{type:"string",description:"The URL to use for email verification callback"},rememberMe:{type:"boolean",description:"If this is false, the session will not be remembered. Default is `true`."}},required:["name","email","password"]}}}},responses:{"200":{description:"Successfully created user",content:{"application/json":{schema:{type:"object",properties:{token:{type:"string",nullable:!0,description:"Authentication token for the session"},user:{type:"object",properties:{id:{type:"string",description:"The unique identifier of the user"},email:{type:"string",format:"email",description:"The email address of the user"},name:{type:"string",description:"The name of the user"},image:{type:"string",format:"uri",nullable:!0,description:"The profile image URL of the user"},emailVerified:{type:"boolean",description:"Whether the email has been verified"},createdAt:{type:"string",format:"date-time",description:"When the user was created"},updatedAt:{type:"string",format:"date-time",description:"When the user was last updated"}},required:["id","email","name","emailVerified","createdAt","updatedAt"]}},required:["user"]}}}},"422":{description:"Unprocessable Entity. User already exists or failed to create user.",content:{"application/json":{schema:{type:"object",properties:{message:{type:"string"}}}}}}}}}},async(t)=>Ue(t.context.adapter,async()=>{if(!t.context.options.emailAndPassword?.enabled||t.context.options.emailAndPassword?.disableSignUp)throw U.from("BAD_REQUEST",{message:"Email and password sign up is not enabled",code:"EMAIL_PASSWORD_SIGN_UP_DISABLED"});let r=t.body,{name:n,email:o,password:i,image:s,callbackURL:a,rememberMe:c,...d}=r;if(!Tn().safeParse(o).success)throw U.from("BAD_REQUEST",Ae.INVALID_EMAIL);if(!i||typeof i!=="string")throw U.from("BAD_REQUEST",Ae.INVALID_PASSWORD);Ht(t,i),xe(t,i);let u=t.context.options.emailAndPassword.requireEmailVerification||t.context.options.emailAndPassword.autoSignIn===!1,f=t.context.options.emailAndPassword.autoSignIn===!1||u,p=dr(t.context.options,d,"create"),h=o.toLowerCase(),m=()=>{let b=new Date,O=t.context.generateId({model:"user"})||us(),g={name:n,email:h,emailVerified:!1,image:s??null,createdAt:b,updatedAt:b},S=t.context.options.emailAndPassword?.customSyntheticUser,C;if(S){let z=Object.keys(t.context.options.user?.additionalFields??{}),L={};for(let P of z)if(P in p)L[P]=p[P];let x=S({coreFields:g,additionalFields:L,id:O});C=Nr(t.context.options,x)}else C=Nr(t.context.options,{...g,...p,id:O});return t.json({token:null,user:se(t.context.options,C)})},w=await t.context.internalAdapter.findUserByEmail(h);if(w?.user){if(t.context.logger.info(`Sign-up attempt for existing email: ${o}`),u){if(await t.context.password.hash(i),t.context.options.emailAndPassword?.onExistingUserSignUp)await t.context.runInBackgroundOrAwait(t.context.options.emailAndPassword.onExistingUserSignUp({user:w.user},Tt(t.request)));return m()}throw U.from("UNPROCESSABLE_ENTITY",Ae.USER_ALREADY_EXISTS_USE_ANOTHER_EMAIL)}let y=await t.context.password.hash(i),I;try{if(I=await t.context.internalAdapter.createUser({email:h,name:n,image:s,...p,emailVerified:!1},{method:"email-password"}),!I)throw U.from("BAD_REQUEST",Ae.FAILED_TO_CREATE_USER)}catch(b){if(Ur(b)){if(b.statusCode===403&&u)return m();throw b}if(xl())t.context.logger.error("Failed to create user",b);throw t.context.logger?.error("Failed to create user",b),U.from("UNPROCESSABLE_ENTITY",Ae.FAILED_TO_CREATE_USER)}if(!I)throw U.from("UNPROCESSABLE_ENTITY",Ae.FAILED_TO_CREATE_USER);if(await t.context.internalAdapter.linkAccount({userId:I.id,providerId:"credential",accountId:I.id,password:y}),t.context.options.emailVerification?.sendOnSignUp??t.context.options.emailAndPassword.requireEmailVerification){let b=await Se(t.context.secret,I.email,void 0,t.context.options.emailVerification?.expiresIn),O=r.callbackURL?encodeURIComponent(r.callbackURL):encodeURIComponent("/"),g=`${t.context.baseURL}/verify-email?token=${b}&callbackURL=${O}`;if(t.context.options.emailVerification?.sendVerificationEmail)await t.context.runInBackgroundOrAwait(t.context.options.emailVerification.sendVerificationEmail({user:I,url:g,token:b},Tt(t.request)))}if(f)return t.json({token:null,user:se(t.context.options,I)});let R=await t.context.internalAdapter.createSession(I.id,c===!1,void 0,void 0,{deferSecondaryStorageWrites:!0});if(!R)throw U.from("BAD_REQUEST",Ae.FAILED_TO_CREATE_SESSION);return await pe(t,{session:R,user:I},c===!1),t.json({token:R.token,user:se(t.context.options,I)})}));var By=k(e().meta({description:"Field name must be a string"}),N()),zf=()=>Pe("/update-session",{method:"POST",operationId:"updateSession",body:By,use:[Hr],metadata:{$Infer:{body:{}},openapi:{operationId:"updateSession",description:"Update the current session",responses:{"200":{description:"Success",content:{"application/json":{schema:{type:"object",properties:{session:{type:"object",$ref:"#/components/schemas/Session"}}}}}}}}}},async(t)=>{let r=t.body;if(typeof r!=="object"||Array.isArray(r))throw U.from("BAD_REQUEST",Ae.BODY_MUST_BE_AN_OBJECT);let n=t.context.session,o=Fn(t.context.options,r,"update");if(Object.keys(o).length===0)throw U.fromStatus("BAD_REQUEST",{message:"No fields to update"});let i=await t.context.internalAdapter.updateSession(n.session.token,{...o,updatedAt:new Date});if(!i&&St(t))throw Le(t),U.from("UNAUTHORIZED",Ae.FAILED_TO_GET_SESSION);let s=i??{...n.session,...o,updatedAt:new Date};return await pe(t,{session:s,user:n.user}),t.json({session:we(t.context.options,s)})});var $y=k(e().meta({description:"Field name must be a string"}),N()),Nf=()=>Pe("/update-user",{method:"POST",operationId:"updateUser",body:$y,use:[Hr],metadata:{$Infer:{body:{}},openapi:{operationId:"updateUser",description:"Update the current user",requestBody:{content:{"application/json":{schema:{type:"object",properties:{name:{type:"string",description:"The name of the user"},image:{type:"string",description:"The image of the user",nullable:!0}}}}}},responses:{"200":{description:"Success",content:{"application/json":{schema:{type:"object",properties:{user:{type:"object",$ref:"#/components/schemas/User"}}}}}}}}}},async(t)=>{let r=t.body;if(typeof r!=="object"||Array.isArray(r))throw U.from("BAD_REQUEST",Ae.BODY_MUST_BE_AN_OBJECT);if(r.email)throw U.from("BAD_REQUEST",Ae.EMAIL_CAN_NOT_BE_UPDATED);let{name:n,image:o,...i}=r,s=t.context.session,a=dr(t.context.options,i,"update");if(o===void 0&&n===void 0&&Object.keys(a).length===0)throw U.fromStatus("BAD_REQUEST",{message:"No fields to update"});let c=await t.context.internalAdapter.updateUser(s.user.id,{name:n,image:o,...a})??{...s.user,...n!==void 0&&{name:n},...o!==void 0&&{image:o},...a};return await pe(t,{session:s.session,user:c}),t.json({status:!0})}),qf=Pe("/change-password",{method:"POST",operationId:"changePassword",body:l({newPassword:e().meta({description:"The new password to set"}),currentPassword:e().meta({description:"The current password is required"}),revokeOtherSessions:E().meta({description:"Must be a boolean value"}).optional()}),use:[Qe],metadata:{openapi:{operationId:"changePassword",description:"Change the password of the user",responses:{"200":{description:"Password successfully changed",content:{"application/json":{schema:{type:"object",properties:{token:{type:"string",nullable:!0,description:"New session token if other sessions were revoked"},user:{type:"object",properties:{id:{type:"string",description:"The unique identifier of the user"},email:{type:"string",format:"email",description:"The email address of the user"},name:{type:"string",description:"The name of the user"},image:{type:"string",format:"uri",nullable:!0,description:"The profile image URL of the user"},emailVerified:{type:"boolean",description:"Whether the email has been verified"},createdAt:{type:"string",format:"date-time",description:"When the user was created"},updatedAt:{type:"string",format:"date-time",description:"When the user was last updated"}},required:["id","email","name","emailVerified","createdAt","updatedAt"]}},required:["user"]}}}}}}}},async(t)=>{let{newPassword:r,currentPassword:n,revokeOtherSessions:o}=t.body,i=t.context.session;Ht(t,r),xe(t,r),xe(t,n);let s=await t.context.internalAdapter.findCredentialAccount(i.user.id);if(!s||!s.password)throw U.from("BAD_REQUEST",Ae.CREDENTIAL_ACCOUNT_NOT_FOUND);let a=await t.context.password.hash(r);if(!await t.context.password.verify({hash:s.password,password:n}))throw U.from("BAD_REQUEST",Ae.INVALID_PASSWORD);let c=await Ue(t.context.adapter,async()=>{if(o)await t.context.internalAdapter.deleteUserSessions(i.user.id);if(await t.context.internalAdapter.updateAccount(s.id,{password:a}),!o)return null;let u=await t.context.internalAdapter.createSession(i.user.id,void 0,void 0,void 0,{deferSecondaryStorageWrites:!0});if(!u)throw U.from("INTERNAL_SERVER_ERROR",Ae.FAILED_TO_GET_SESSION);return u}),d=null;if(c)await pe(t,{session:c,user:i.user}),d=c.token;return t.json({token:d,user:se(t.context.options,i.user)})}),jf=Pe.serverOnly({method:"POST",body:l({newPassword:e().meta({description:"The new password to set is required"})}),use:[Qe]},async(t)=>{let{newPassword:r}=t.body,n=t.context.session;Ht(t,r),xe(t,r);let o=await t.context.internalAdapter.findCredentialAccount(n.user.id),i=await t.context.password.hash(r);if(!o)return await t.context.internalAdapter.linkAccount({userId:n.user.id,providerId:"credential",accountId:n.user.id,password:i}),t.json({status:!0});if(!o.password)return await t.context.internalAdapter.updateAccount(o.id,{password:i}),t.json({status:!0});throw U.from("BAD_REQUEST",Ae.PASSWORD_ALREADY_SET)}),Bf=Pe("/delete-user",{method:"POST",use:[Qe],body:l({callbackURL:e().meta({description:"The callback URL to redirect to after the user is deleted"}).optional(),password:e().meta({description:"The password of the user is required to delete the user"}).optional(),token:e().meta({description:"The token to delete the user is required"}).optional()}),metadata:{openapi:{operationId:"deleteUser",description:"Delete the user",requestBody:{content:{"application/json":{schema:{type:"object",properties:{callbackURL:{type:"string",description:"The callback URL to redirect to after the user is deleted"},password:{type:"string",description:"The user's password. Required if session is not fresh"},token:{type:"string",description:"The deletion verification token"}}}}}},responses:{"200":{description:"User deletion processed successfully",content:{"application/json":{schema:{type:"object",properties:{success:{type:"boolean",description:"Indicates if the operation was successful"},message:{type:"string",enum:["User deleted","Verification email sent"],description:"Status message of the deletion process"}},required:["success","message"]}}}}}}}},async(t)=>{if(!t.context.options.user?.deleteUser?.enabled)throw t.context.logger.error("Delete user is disabled. Enable it in the options"),U.fromStatus("NOT_FOUND");let r=t.context.session;if(t.body.password){xe(t,t.body.password);let i=await t.context.internalAdapter.findCredentialAccount(r.user.id);if(!i||!i.password)throw U.from("BAD_REQUEST",Ae.CREDENTIAL_ACCOUNT_NOT_FOUND);if(!await t.context.password.verify({hash:i.password,password:t.body.password}))throw U.from("BAD_REQUEST",Ae.INVALID_PASSWORD)}if(t.body.token)return await Bs({...t,query:{token:t.body.token}}),t.json({success:!0,message:"User deleted"});if(t.context.options.user.deleteUser?.sendDeleteAccountVerification){let i=_e(32,"0-9","a-z");await t.context.internalAdapter.createVerificationValue({value:r.user.id,identifier:`delete-account-${i}`,expiresAt:new Date(Date.now()+(t.context.options.user.deleteUser?.deleteTokenExpiresIn||86400)*1000)});let s=`${t.context.baseURL}/delete-user/callback?token=${i}&callbackURL=${encodeURIComponent(t.body.callbackURL||"/")}`;return await t.context.runInBackgroundOrAwait(t.context.options.user.deleteUser.sendDeleteAccountVerification({user:r.user,url:s,token:i},t.request)),t.json({success:!0,message:"Verification email sent"})}if(!t.body.password&&t.context.sessionConfig.freshAge!==0){let i=new Date(r.session.createdAt).getTime(),s=t.context.sessionConfig.freshAge*1000;if(Date.now()-i>=s)throw U.from("BAD_REQUEST",Ae.SESSION_EXPIRED)}let n=t.context.options.user.deleteUser?.beforeDelete;if(n)await n(r.user,t.request);await t.context.internalAdapter.deleteUser(r.user.id),await t.context.internalAdapter.deleteUserSessions(r.user.id),Le(t);let o=t.context.options.user.deleteUser?.afterDelete;if(o)await o(r.user,t.request);return t.json({success:!0,message:"User deleted"})}),Bs=Pe("/delete-user/callback",{method:"GET",query:l({token:e().meta({description:"The token to verify the deletion request"}),callbackURL:e().meta({description:"The URL to redirect to after deletion"}).optional()}),use:[bt((t)=>t.query.callbackURL)],metadata:{openapi:{description:"Callback to complete user deletion with verification token",responses:{"200":{description:"User successfully deleted",content:{"application/json":{schema:{type:"object",properties:{success:{type:"boolean",description:"Indicates if the deletion was successful"},message:{type:"string",enum:["User deleted"],description:"Confirmation message"}},required:["success","message"]}}}}}}}},async(t)=>{if(!t.context.options.user?.deleteUser?.enabled)throw t.context.logger.error("Delete user is disabled. Enable it in the options"),U.from("NOT_FOUND",{message:"Not found",code:"NOT_FOUND"});let r=await ee(t,{disableCookieCache:St(t)});if(!r)throw U.from("NOT_FOUND",Ae.FAILED_TO_GET_USER_INFO);let n=await t.context.internalAdapter.consumeVerificationValue(`delete-account-${t.query.token}`);if(!n||n.value!==r.user.id)throw U.from("NOT_FOUND",Ae.INVALID_TOKEN);let o=t.context.options.user.deleteUser?.beforeDelete;if(o)await o(r.user,t.request);await t.context.internalAdapter.deleteUser(r.user.id),await t.context.internalAdapter.deleteUserSessions(r.user.id),await t.context.internalAdapter.deleteAccounts(r.user.id),Le(t);let i=t.context.options.user.deleteUser?.afterDelete;if(i)await i(r.user,t.request);if(t.query.callbackURL)throw t.redirect(t.query.callbackURL||"/");return t.json({success:!0,message:"User deleted"})}),$f=Pe("/change-email",{method:"POST",body:l({newEmail:Tn().meta({description:"The new email address to set must be a valid email address"}),callbackURL:e().meta({description:"The URL to redirect to after email verification"}).optional()}),use:[Qe],metadata:{openapi:{operationId:"changeEmail",responses:{"200":{description:"Email change request processed successfully",content:{"application/json":{schema:{type:"object",properties:{user:{type:"object",$ref:"#/components/schemas/User"},status:{type:"boolean",description:"Indicates if the request was successful"},message:{type:"string",enum:["Email updated","Verification email sent"],description:"Status message of the email change process",nullable:!0}},required:["status"]}}}}}}}},async(t)=>{if(!t.context.options.user?.changeEmail?.enabled)throw t.context.logger.error("Change email is disabled."),U.from("BAD_REQUEST",Ae.CHANGE_EMAIL_DISABLED);let r=t.body.newEmail.toLowerCase();if(r===t.context.session.user.email)throw t.context.logger.warn("Email is the same"),U.fromStatus("BAD_REQUEST",{message:"Email is the same"});let n=t.context.session.user.emailVerified!==!0&&t.context.options.user.changeEmail.updateEmailWithoutVerification,o=t.context.options.emailVerification?.sendVerificationEmail,i=o&&t.context.session.user.emailVerified&&t.context.options.user.changeEmail.sendChangeEmailConfirmation;if(!n&&!i&&!o)throw t.context.logger.error("Verification email isn't enabled."),U.fromStatus("BAD_REQUEST",{message:"Verification email isn't enabled"});if(await t.context.internalAdapter.findUserByEmail(r))return await Se(t.context.secret,t.context.session.user.email,r,t.context.options.emailVerification?.expiresIn),t.context.logger.info("Change email attempt for existing email"),t.json({status:!0});if(n){if(await t.context.internalAdapter.updateUser(t.context.session.user.id,{email:r}),await pe(t,{session:t.context.session.session,user:{...t.context.session.user,email:r}}),o){let c=await Se(t.context.secret,r,void 0,t.context.options.emailVerification?.expiresIn),d=`${t.context.baseURL}/verify-email?token=${c}&callbackURL=${encodeURIComponent(t.body.callbackURL||"/")}`;await t.context.runInBackgroundOrAwait(o({user:{...t.context.session.user,email:r},url:d,token:c},t.request))}return t.json({status:!0})}if(i){let c=await Se(t.context.secret,t.context.session.user.email,r,t.context.options.emailVerification?.expiresIn,{requestType:"change-email-confirmation"}),d=`${t.context.baseURL}/verify-email?token=${c}&callbackURL=${encodeURIComponent(t.body.callbackURL||"/")}`;return await t.context.runInBackgroundOrAwait(i({user:t.context.session.user,newEmail:r,url:d,token:c},t.request)),t.json({status:!0})}if(!o)throw t.context.logger.error("Verification email isn't enabled."),U.fromStatus("BAD_REQUEST",{message:"Verification email isn't enabled"});let s=await Se(t.context.secret,t.context.session.user.email,r,t.context.options.emailVerification?.expiresIn,{requestType:"change-email-verification"}),a=`${t.context.baseURL}/verify-email?token=${s}&callbackURL=${encodeURIComponent(t.body.callbackURL||"/")}`;return await t.context.runInBackgroundOrAwait(o({user:{...t.context.session.user,email:r},url:a,token:s},t.request)),t.json({status:!0})});var Mf=Jr((t,r,n)=>{if(Array.isArray(t[r])&&Array.isArray(n))return t[r]=n,!0}),Zt=new WeakMap;function $s(t,r){let n=t.options;return n?.operationId??n?.metadata?.openapi?.operationId??r??t.path??"/:virtual"}function Hf(t,r){if(!r)return;r.forEach((n,o)=>{if(!t.responseHeaders)t.responseHeaders=new Headers({[o]:n});else if(o.toLowerCase()==="set-cookie")t.responseHeaders.append(o,n);else t.responseHeaders.set(o,n)})}function Vf(t){let r=t[$a],n=t.headers&&t.headers!==r?new Headers(t.headers):null;if(!r&&!n)return null;let o=new Headers;return r?.forEach((i,s)=>{o.append(s,i)}),n?.forEach((i,s)=>{if(s.toLowerCase()==="set-cookie")o.append(s,i);else o.set(s,i)}),o}async function My(t,r,n,o){let i=ds(t.context.options),s={};for(let a of r){let c=!1;try{c=a.matcher(t)}catch(h){let m=Zt.get(a.handler)??"unknown";throw t.context.logger.error(`An error occurred during ${m} hook matcher execution:`,h),new U("INTERNAL_SERVER_ERROR",{message:"An error occurred during hook matcher execution. Check the logs for more details."})}if(!c)continue;let d=Zt.get(a.handler)??"unknown",u=n.path??"/:virtual",f=await i(`hook before ${u} ${d}`,{[pn]:"before",[Ha]:u,[mn]:d,[Rc]:o},()=>a.handler({...t,returnHeaders:!0})).catch((h)=>{if(Ur(h)&&Tc(t.context.logger.level,"debug"))h.stack=h.errorStack;throw h});Hf(t.context,f?.headers);let p=f?.response;if(p&&typeof p==="object"){if("context"in p&&typeof p.context==="object"){let{headers:h,...m}=p.context;if(h instanceof Headers)if(s.headers)h.forEach((w,y)=>{s.headers?.set(y,w)});else s.headers=h;s=Mf(m,s);continue}return p}}return{context:s}}async function Hy(t,r,n,o){let i=ds(t.context.options);for(let s of r){if(!s.matcher(t))continue;let a=Zt.get(s.handler)??"unknown",c=n.path??"/:virtual",d=await i(`hook after ${c} ${a}`,{[pn]:"after",[Ha]:c,[mn]:a,[Rc]:o},()=>s.handler(t)).catch((u)=>{if(Ur(u)){if(Tc(t.context.logger.level,"debug"))u.stack=u.errorStack;return{response:u,headers:Vf(u)}}throw u});if(Hf(t.context,d.headers),d.response!==void 0)t.context.returned=d.response}return{response:t.context.returned,headers:t.context.responseHeaders}}function Fy(t){let r=t.options.plugins||[],n=[],o=[],i=t.options.hooks?.before;if(i)Zt.set(i,"user"),n.push({matcher:()=>!0,handler:i});let s=t.options.hooks?.after;if(s)Zt.set(s,"user"),o.push({matcher:()=>!0,handler:s});let a=r.flatMap((d)=>(d.hooks?.before??[]).map((u)=>(Zt.set(u.handler,`plugin:${d.id}`),u))),c=r.flatMap((d)=>(d.hooks?.after??[]).map((u)=>(Zt.set(u.handler,`plugin:${d.id}`),u)));if(a.length)n.push(...a);if(c.length)o.push(...c);return{beforeHooks:n,afterHooks:o}}async function bn(t,r){let n=ds(r.context.options),o=r.operationId??$s(t),i=t.path??"/:virtual",s=t.options?.method,a=Array.isArray(s)?s[0]:s,c=r.method??r.request?.method??a??"?",d=r.asResponse??je(r.request),u={...r,context:{...r.context,returned:void 0,responseHeaders:void 0,session:r.context.session??null},path:t.path,headers:r.headers?new Headers(r.headers):void 0};return n(`${c} ${i}`,{[Ha]:i,[Rc]:o},async()=>pr(u,async()=>{let{beforeHooks:f,afterHooks:p}=Fy(u.context),h=await My(u,f,t,o);if("context"in h&&h.context&&typeof h.context==="object"){let{headers:y,...I}=h.context;if(y){if(!u.headers)u.headers=new Headers;let R=u.headers;y.forEach((b,O)=>{R.set(O,b)})}u=Mf(I,u)}else if(h){let y=u.context.responseHeaders;return d?We(h,{headers:y}):r.returnHeaders?{headers:y,response:h}:h}u.asResponse=!1,u.returnHeaders=!0,u.returnStatus=!0;let m=await pr(u,()=>n(`handler ${i}`,{[Ha]:i,[Rc]:o},()=>t(u))).catch((y)=>{if(Ur(y))return{response:y,status:y.statusCode,headers:Vf(y)};throw y});if(m instanceof Response)return m;u.context.returned=m.response,u.context.responseHeaders=m.headers??void 0;let w=await Hy(u,p,t,o);if(w.response!==void 0)m.response=w.response;if(m.headers=w.headers??m.headers,Ur(m.response)&&Tc(u.context.logger.level,"debug"))m.response.stack=m.response.errorStack;if(Ur(m.response)&&!d){if(m.headers)Object.defineProperty(m.response,$a,{enumerable:!1,configurable:!0,writable:!1,value:m.headers});throw m.response}return d?We(m.response,{headers:m.headers??void 0,status:m.status}):r.returnHeaders?r.returnStatus?{headers:m.headers,response:m.response,status:m.status}:{headers:m.headers,response:m.response}:r.returnStatus?{response:m.response,status:m.status}:m.response}))}async function Ky(t,r){if(t.baseURL)return t;let n=fd(r),o=t.options.baseURL,i=ls(o)&&Boolean(o.fallback);if(n===void 0&&!i)throw new U("INTERNAL_SERVER_ERROR",{message:"Dynamic baseURL could not be resolved for this direct auth.api call. Pass `headers: request.headers` (or `request`) to the call, or add `fallback` to your baseURL config."});try{return await pf(t,n,ff(t.options))}catch(s){if(s instanceof te)throw new U("INTERNAL_SERVER_ERROR",{message:s.message});throw s}}function Ff(t,r){let n={};for(let[o,i]of Object.entries(t))n[o]=async(s)=>{let a=$s(i,o),c=async()=>{let d=await r,u=d.checkSchema?.();if(u)await u;let f=ls(d.options.baseURL)?await Ky(d,s):d;return bn(i,{...s,context:f,operationId:a,asResponse:s?.asResponse??je(s?.request)})};if(await zi())return c();return Ni(new WeakMap,c)},n[o].path=i.path,n[o].options=i.options;return n}function Wg(t,r){let n=new Map;t.plugins?.forEach((i)=>{if(i.endpoints){for(let[s,a]of Object.entries(i.endpoints))if(a&&"path"in a&&typeof a.path==="string"){let c=a.path,d=[];if(a.options&&"method"in a.options){if(Array.isArray(a.options.method))d=a.options.method;else if(typeof a.options.method==="string")d=[a.options.method]}if(d.length===0)d=["*"];if(!n.has(c))n.set(c,[]);n.get(c).push({pluginId:i.id,endpointKey:s,methods:d})}}});let o=[];for(let[i,s]of n.entries())if(s.length>1){let a=new Map,c=!1;for(let d of s)for(let u of d.methods){if(!a.has(u))a.set(u,[]);if(a.get(u).push(d.pluginId),a.get(u).length>1)c=!0;if(u==="*"&&s.length>1)c=!0;else if(u!=="*"&&a.has("*"))c=!0}if(c){let d=[...new Set(s.map((f)=>f.pluginId))],u=[];for(let[f,p]of a.entries())if(p.length>1||f==="*"&&s.length>1||f!=="*"&&a.has("*"))u.push(f);o.push({path:i,plugins:d,conflictingMethods:u})}}if(o.length>0){let i=o.map((s)=>` - "${s.path}" [${s.conflictingMethods.join(", ")}] used by plugins: ${s.plugins.join(", ")}`).join(`
386
386
  `);r.error(`Endpoint path conflicts detected! Multiple plugins are trying to use the same endpoint paths with conflicting HTTP methods:
387
387
  ${i}
388
388
 
@@ -390,4 +390,4 @@ To resolve this, you can:
390
390
  1. Use only one of the conflicting plugins
391
391
  2. Configure the plugins to use different paths (if supported)
392
392
  3. Ensure plugins use different HTTP methods for the same path
393
- `)}}function xm(t,r){let n=ds(r),o=r.plugins?.reduce((s,a)=>({...s,...a.endpoints}),{})??{},i=r.plugins?.map((s)=>s.middlewares?.map((a)=>{let c=async(d)=>{let u=await t;return n(`middleware ${a.path} ${s.id}`,{[pn]:"middleware",[$a]:a.path,[mn]:`plugin:${s.id}`},()=>a.middleware({...d,context:{...u,...d.context}}))};return c.options=a.middleware.options,{path:a.path,middleware:c}})).filter((s)=>s!==void 0).flat()||[];return{api:Ff({signInSocial:Uf(),callbackOAuth:nf,getSession:rs(),signOut:Lf,signUpEmail:Pf(),signInEmail:Of(),resetPassword:Rf,verifyPassword:Tf,verifyEmail:iu,sendVerificationEmail:ou,changeEmail:$f,changePassword:qf,setPassword:jf,updateSession:zf(),updateUser:Nf(),deleteUser:Bf,requestPasswordReset:bf,requestPasswordResetCallback:vf,listSessions:Id(),revokeSession:Ud,revokeSessions:Cd,revokeOtherSessions:Od,linkSocialAccount:Ql,listUserAccounts:Jl,deleteUserCallback:Bs,unlinkAccount:Gl,refreshToken:ef,getAccessToken:Xl,accountInfo:tf,...o,ok:af,error:sf},t),middlewares:i}}var Kg=(t,r)=>{let n=ds(r),{api:o,middlewares:i}=xm(t,r),s=new URL(t.baseURL).pathname;return Ci(o,{routerContext:t,openapi:{disabled:!0},basePath:s,routerMiddleware:[{path:"/**",middleware:kd},...i],allowedMediaTypes:["application/json"],skipTrailingSlashes:r.advanced?.skipTrailingSlashes??!1,async onRequest(a){let c=t.options.disabledPaths||[],d=gr(a.url,s);if(c.includes(d))return new Response("Not Found",{status:404});let u=t.checkSchema?.();if(u)await u;let f=a,p=await Sd(f,t);if(p)return p;for(let h of t.options.plugins||[])if(h.onRequest){let m=await n(`onRequest ${h.id}`,{[pn]:"onRequest",[mn]:`plugin:${h.id}`},()=>h.onRequest(f,t));if(m&&"response"in m)return m.response;if(m&&"request"in m)f=m.request}return f},async onResponse(a,c){for(let d of t.options.plugins||[])if(d.onResponse){let u=await n(`onResponse ${d.id}`,{[pn]:"onResponse",[mn]:`plugin:${d.id}`,[od]:a.status},()=>d.onResponse(a,t));if(u)return u.response}return a},async onError(a){if(Br(a)&&a.status==="FOUND")return;if(r.onAPIError?.throw)throw a;if(r.onAPIError?.onError){try{await r.onAPIError.onError(a,t)}catch(u){t.logger.error("onAPIError.onError threw",u)}return}let c=r.logger?.level,d=c==="error"||c==="warn"||c==="debug"?Ee:void 0;if(r.logger?.disabled!==!0){if(a&&typeof a==="object"&&"message"in a&&typeof a.message==="string"){if(a.message.includes("no column")||a.message.includes("column")||a.message.includes("relation")||a.message.includes("table")||a.message.includes("does not exist")){t.logger?.error(a.message);return}}if(Br(a)){if(a.status==="INTERNAL_SERVER_ERROR")t.logger.error(a.status,a);d?.error(a.message)}else t.logger?.error(a&&typeof a==="object"&&"name"in a?a.name:"",a)}}})};function vs(t){return t?.jwks?.keyPairConfig?.alg??"EdDSA"}var _i=(t,r)=>({getAllKeys:async(n)=>{if(r?.adapter?.getJwks)return await r.adapter.getJwks(n);return await(await X(t)).findMany({model:"jwks"})},getLatestKey:async(n)=>{let o=new Date,i=(s)=>!s.expiresAt||s.expiresAt>o;if(r?.adapter?.getJwks)return(await r.adapter.getJwks(n))?.filter(i).sort((s,a)=>a.createdAt.getTime()-s.createdAt.getTime())[0];return(await(await X(t)).findMany({model:"jwks"}))?.filter(i).sort((s,a)=>a.createdAt.getTime()-s.createdAt.getTime())[0]},getKeyById:async(n,o)=>{if(r?.adapter?.getJwks)return(await r.adapter.getJwks(n))?.find((i)=>i.id===o);return await(await X(t)).findOne({model:"jwks",where:[{field:"id",value:o}]})??void 0},getLatestKeyByAlg:async(n,o)=>{let i=r?.adapter?.getJwks?await r.adapter.getJwks(n):await(await X(t)).findMany({model:"jwks"});if(!i)return;let s=vs(r),a=new Date;return i.filter((c)=>c.alg===o||c.alg==null&&s===o).filter((c)=>!c.expiresAt||c.expiresAt>a).sort((c,d)=>d.createdAt.getTime()-c.createdAt.getTime())[0]},createJwk:async(n,o)=>{if(r?.adapter?.createJwk)return await r.adapter.createJwk(o,n);return await(await X(t)).create({model:"jwks",data:{...o,createdAt:new Date}})}});function Yt(t,r){if(typeof t==="number")return t;else if(t instanceof Date)return Math.floor(t.getTime()/1000);else return r+Wn(t)}async function Kf(t){let{alg:r,...n}=t?.jwks?.keyPairConfig??{alg:"EdDSA",crv:"Ed25519"},{publicKey:o,privateKey:i}=await Af(r,{...n,extractable:!0});return{publicWebKey:await vl(o),privateWebKey:await vl(i),alg:r,cfg:n}}async function _c(t,r){let{publicWebKey:n,privateWebKey:o,alg:i,cfg:s}=await Kf(r),a=s&&"crv"in s?s.crv:void 0,c=typeof n.crv==="string"?n.crv:void 0,d=a??c,u=JSON.stringify(o),f=!r?.jwks?.disablePrivateKeyEncryption,p={alg:i,...d?{crv:d}:{},publicKey:JSON.stringify(n),privateKey:f?JSON.stringify(await nt({key:t.context.secretConfig,data:u})):u,createdAt:new Date,...r?.jwks?.rotationInterval?{expiresAt:new Date(Date.now()+r.jwks.rotationInterval*1000)}:{}};return await _i(t.context.adapter,r).createJwk(t,p)}async function Ki(t,r,n){if(r?.jwt?.sign)return null;let o=_i(t.context.adapter,r),i;if(n?.signingKeyId!==void 0){if(i=await o.getKeyById(t,n.signingKeyId),!i)throw new te(`signJWT: signingKeyId "${n.signingKeyId}" not found in JWKS. The key must be provisioned before it can be referenced.`);if(n.signingAlgorithm!==void 0){let d=vs(r);if((i.alg??d)!==n.signingAlgorithm)throw new te(`signJWT: signingKeyId "${n.signingKeyId}" has alg "${i.alg??`unset (inherits keyPairConfig.alg "${d}")`}" but signingAlgorithm was set to "${n.signingAlgorithm}".`)}}else if(n?.signingAlgorithm!==void 0){if(i=await o.getLatestKeyByAlg(t,n.signingAlgorithm),!i){let d=vs(r),u=r?.jwks?.keyPairConfigs?.find((p)=>p.alg===n.signingAlgorithm),f=d===n.signingAlgorithm;if(u||f)i=await _c(t,{...r,jwks:{...r?.jwks,keyPairConfig:u??r?.jwks?.keyPairConfig}});else{let p=r?.jwks?.keyPairConfigs?.map((h)=>h.alg).join(", ")||"none";throw new te(`signJWT: no key with alg "${n.signingAlgorithm}" found in JWKS. The plugin auto-mints only one key matching keyPairConfig.alg="${d}"; additional algs configured via keyPairConfigs: ${p}. Add "${n.signingAlgorithm}" to jwks.keyPairConfigs so the plugin provisions it on first use, or mint the key explicitly via createJwk().`)}}}else{let d=vs(r);i=await o.getLatestKeyByAlg(t,d)??await o.getLatestKey(t)}if(!i||i.expiresAt&&i.expiresAt<new Date){if(n?.signingKeyId!==void 0||n?.signingAlgorithm!==void 0)throw new te("signJWT: requested signing key is expired and an explicit kid/alg was provided; not auto-minting a replacement. Rotate the key explicitly.");i=await _c(t,r)}let s=!r?.jwks?.disablePrivateKeyEncryption?await ot({key:t.context.secretConfig,data:JSON.parse(i.privateKey)}).catch(()=>{throw new te("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.")}):i.privateKey,a=i.alg??vs(r),c=await Sn(JSON.parse(s),a);return{alg:a,kid:i.id,privateKey:c}}async function Wi(t,r){let{options:n}=r,o=r.payload,i=Math.floor(Date.now()/1000),{iat:s,exp:a}=o,c=Yt(n?.jwt?.expirationTime??"15m",s??i);a=a??c;let d=o.nbf,u=typeof t.context.options.baseURL==="string"?t.context.options.baseURL:"",f=o.iss,p=n?.jwt?.issuer??u,h=o.aud,m=n?.jwt?.audience??u;if(!(f??p)||!(h??m))t.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.");if(n?.jwt?.sign){let b={...o,iat:s,exp:a,nbf:d,iss:f??p,aud:h??m};return n.jwt.sign(b,r.header,{signingKeyId:r.signingKeyId,signingAlgorithm:r.signingAlgorithm})}let{alg:w,kid:y,privateKey:I}=r.resolvedKey??await Ki(t,n,{signingKeyId:r.signingKeyId,signingAlgorithm:r.signingAlgorithm}),R=new bs(o).setProtectedHeader({...r.header,alg:w,kid:y}).setExpirationTime(a).setIssuer(f??p).setAudience(h??m);if(s)R.setIssuedAt(s);if(o.sub)R.setSubject(o.sub);if(o.nbf)R.setNotBefore(o.nbf);if(o.jti)R.setJti(o.jti);return await R.sign(I)}async function pf(t,r){let n=!r?.jwt?.definePayload?t.context.session.user:await r.jwt.definePayload(t.context.session);return await Wi(t,{options:r,payload:{iat:Math.floor(Date.now()/1000),...n,sub:await r?.jwt?.getSubject?.(t.context.session)??t.context.session.user.id}})}var Wf=Object.defineProperty,Co=(t,r)=>{let n={};for(var o in t)Wf(n,o,{get:t[o],enumerable:!0});if(!r)Wf(n,Symbol.toStringTag,{value:"Module"});return n};var Ms="ba_iat",Oo="ba_pl";function Do(t){let r=new URLSearchParams,n=[...t.entries()].sort(([o,i],[s,a])=>{if(o<s)return-1;if(o>s)return 1;if(i<a)return-1;if(i>a)return 1;return 0});for(let[o,i]of n)r.append(o,i);return r}function Jf(t){t.delete("ba_param");let r=[...new Set([...t.keys(),"ba_param"])].sort();for(let n of r)t.append("ba_param",n)}function Qf(t){let r=new URLSearchParams(t).get("ba_iat");if(!r)return null;let n=Number(r);if(!Number.isFinite(n)||n<=0)return null;return new Date(n)}var Jy=["authorization_code","client_credentials","refresh_token"],Zf=["client_secret_basic","client_secret_post","private_key_jwt"],Qy=["none",...Zf],Gy=new Set(Qy);function Js(t,r){if(r.trim().length>0)return;throw new te(`OAuth Provider extension ${t} cannot be empty`)}function Yf(t,r){Js(t,r);let n;try{n=new URL(r)}catch{n=void 0}if(n?.protocol)return;throw new te(`OAuth Provider extension ${t} must be an absolute URI: ${r}`)}function Zy(t){Yf("grant type",t)}function Yy(t){if(Js("token_endpoint_auth_method",t),!Gy.has(t))return;throw new te(`OAuth Provider extension token_endpoint_auth_method is reserved: ${t}`)}function Xy(t){if(Yf("client_assertion_type",t),t!==Wt)return;throw new te(`OAuth Provider extension client_assertion_type is reserved: ${t}`)}function e_(t){let r=Object.keys(t.grants??{});for(let s of r)Zy(s);let n=[],o=[];for(let[s,a]of Object.entries(t.clientAuthentication??{})){Yy(s),n.push(s);let c=a.assertionTypes??[s];if(c.length===0)throw new te(`OAuth Provider extension client_assertion_type list cannot be empty for ${s}`);for(let d of c)Xy(d),o.push(d)}let i=(t.clientDiscovery?Array.isArray(t.clientDiscovery)?t.clientDiscovery:[t.clientDiscovery]:[]).map((s)=>s.id);for(let s of i)Js("client discovery id",s);return{grantTypes:r,authMethods:n,assertionTypes:o,clientDiscoveryIds:i}}function Lo(t,r){let n=new Set;for(let o of r){if(n.has(o))throw new te(`OAuth Provider extensions register ${t} "${o}" more than once. Extension contributions must be disjoint.`);n.add(o)}}function Xf(t){let r=(t??[]).map(e_);Lo("grant type",r.flatMap((n)=>n.grantTypes)),Lo("token_endpoint_auth_method",r.flatMap((n)=>n.authMethods)),Lo("client_assertion_type",r.flatMap((n)=>n.assertionTypes)),Lo("client discovery id",r.flatMap((n)=>n.clientDiscoveryIds))}function It(t){return t.extensions??[]}function Rn(t){return It(t).flatMap((r)=>{let n=r.clientDiscovery;if(!n)return[];return Array.isArray(n)?n:[n]})}function t_(t){return It(t).flatMap((r)=>Object.keys(r.grants??{}))}function Rr(t){return Array.from(new Set([...t.grantTypes??Jy,...t_(t)]))}function ep(t,r){for(let n of It(t)){let o=n.grants?.[r];if(o)return o}}function tp(t){return It(t).flatMap((r)=>Object.keys(r.clientAuthentication??{}))}function Po(t,r){return Array.from(new Set([...r?.includeNone?["none"]:[],...Zf,...tp(t)]))}function Gs(t,r){return r?tp(t).includes(r):!1}function r_(t,r){if(r===Wt)return;for(let n of It(t)){let o=n.clientAuthentication??{};for(let[i,s]of Object.entries(o))if((s.assertionTypes??[i]).includes(r))return{method:i,strategy:s}}}function Zs(t,r,n,o){let i={...o};for(let s of It(r)){let a=s.metadata?.({ctx:t,opts:r,type:n,document:o});for(let[c,d]of Object.entries(a??{}))if(!(c in i))i[c]=d}return i}async function Ys(t,r){let n={};for(let o of It(t)){let i=await r(o)??{};for(let[s,a]of Object.entries(i)){if(s in n){Ee.warn(`oauth-provider: two extensions contributed the claim "${s}"; keeping the first-registered value.`);continue}n[s]=a}}return n}function rp(t,r){return Ys(t,(n)=>n.claims?.accessToken?.(r))}function np(t,r){return Ys(t,(n)=>n.claims?.idToken?.(r))}function op(t,r){return Ys(t,(n)=>n.claims?.userInfo?.(r))}function ip(t){return It(t).some((r)=>r.claims?.userInfo)}function sp(t){if(!t)return;let[r,n,...o]=t.trim().split(/\s+/);if(r?.toLowerCase()!=="bearer")return;if(!n||o.length>0)throw new ce("BAD_REQUEST",{error:"invalid_request",error_description:"Malformed Bearer Authorization header"});return n}function n_(){let t=new Map;return{get(r){let n=t.get(r);if(!n)return;if(n.expiresAt&&n.expiresAt<new Date){t.delete(r);return}return n},set(r,n){t.set(r,n)}}}var Oe=(t)=>{let r=t.getPlugin("jwt");if(!r)throw new te("jwt_config");return r},o_=new Set([yl.code,Al.code,yc.code]);function xo(t){return t instanceof dn&&!o_.has(t.code)}function st(t){if(t==null)return;if(t instanceof Date)return Number.isFinite(t.getTime())?t:void 0;if(typeof t==="number"){if(!Number.isFinite(t))return;let r=new Date(t);return Number.isFinite(r.getTime())?r:void 0}if(typeof t==="string"){let r=t.trim();if(!r.length)return;let n=Number(r);if(Number.isFinite(n)){let i=new Date(n);return Number.isFinite(i.getTime())?i:void 0}let o=new Date(r);return Number.isFinite(o.getTime())?o:void 0}}function ap(t){if(t instanceof Date)return st(t);if(!t||typeof t!=="object")return st(t);let r=st(t.createdAt)??st(t.created_at);if(r)return r;let n=t.session;if(!n||typeof n!=="object")return;return st(n.createdAt)??st(n.created_at)}function Ut(t){if(typeof t==="string")return[t];if(!t?.length)return;return t}function Xs(t){if(typeof t==="string")return t;if(!t?.length)return;return t.length===1?t.at(0):t}var Gf=new WeakMap;function i_(t){let r=Gf.get(t);if(r)return r;let n=n_();return Gf.set(t,n),n}async function ra(t,r){let n=new URLSearchParams(t),o=n.get("sig"),i=n.getAll("sig"),s=Number(n.get("exp"));n.delete("sig");let a=await on(Do(n).toString(),r);return i.length===1&&!!o&&Vt(o,a)&&new Date(s*1000)>=new Date}function Tn(t,r){if(t.cachedTrustedClients?.has(r))throw new ce("BAD_REQUEST",{error:"invalid_client",error_description:"trusted clients must be updated manually"})}async function ke(t,r,n){let o=i_(r),i=o.get(n);if(i&&!i.clientDiscoveryId)return Object.assign({},i);let s=await t.context.adapter.findOne({model:r.schema?.oauthClient?.modelName??"oauthClient",where:[{field:"clientId",value:n}]}),a=Rn(r);if(s?.clientDiscoveryId){let c=s.clientDiscoveryId,d=a.find((u)=>u.id===c);if(!d?.matches(n))return null;if(s=await d.resolve(t,n,s),!s)return null}else if(s){if(r.cachedTrustedClients?.has(n))o.set(n,Object.assign({},s));return s}else for(let c of a){if(!c.matches(n))continue;let d=await c.resolve(t,n,null);if(d){s=d;break}}return s}function oa(t){return t.reduce((r,n)=>({...r,...n.discoveryMetadata??{}}),{})}var zo=async(t)=>{let r=await cs("SHA-256").digest(new TextEncoder().encode(t));return ko.encode(new Uint8Array(r),{padding:!1})};async function Sr(t,r,n){if(r==="encrypted")return await ot({key:t.context.secretConfig,data:n});else if(typeof r==="object"&&"decrypt"in r)return await r.decrypt(n);throw new te(`Unsupported decryption storageMethod type '${r}'`)}async function s_(t,r,n,o){let i=r.storeClientSecret??(r.disableJwtPlugin?"encrypted":"hashed");if(o&&r.prefix?.clientSecret)if(o.startsWith(r.prefix?.clientSecret))o=o.replace(r.prefix.clientSecret,"");else throw new ce("UNAUTHORIZED",{error_description:"invalid client_secret",error:"invalid_client"});if(i==="hashed"){let s=o?await zo(o):void 0;return!!s&&Vt(s,n)}else if(typeof i==="object"&&"hash"in i)if(i.verify)return!!o&&await i.verify(o,n);else{let s=o?await i.hash(o):void 0;return!!s&&Vt(s,n)}else if(i==="encrypted")try{let s=await Sr(t,i,n);return!!o&&Vt(s,o)}catch{return!1}else if(typeof i==="object"&&"decrypt"in i){let s=await Sr(t,i,n);return!!o&&Vt(s,o)}throw new te(`Unsupported verify storageMethod type '${i}'`)}async function No(t,r,n){let o=r.storeClientSecret??(r.disableJwtPlugin?"encrypted":"hashed");if(o==="encrypted")return await nt({key:t.context.secretConfig,data:n});else if(o==="hashed")return await zo(n);else if(typeof o==="object"&&"hash"in o)return await o.hash(n);else if(typeof o==="object"&&"encrypt"in o)return await o.encrypt(n);throw new te(`Unsupported storeClientSecret type '${o}'`)}async function er(t="hashed",r,n){if(t==="hashed")return await zo(r);else if(typeof t==="object"&&"hash"in t)return await t.hash(r,n);throw new te(`storeToken: unsupported storageMethod type '${t}'`)}async function tr(t="hashed",r,n){if(t==="hashed")return await zo(r);else if(typeof t==="object"&&"hash"in t)return await t.hash(r,n);throw new te(`getStoredToken: unsupported storageMethod type '${t}'`)}var Ws=/^Basic +/i,a_=/^([!#$%&'*+\-.^_`|~0-9A-Za-z]+)(?=\s|$)/;function c_(t){return t.match(a_)?.[1]}var Fs=["client_secret","client_assertion","client_assertion_type"];function vn(t){throw new ce("BAD_REQUEST",{error:"invalid_request",error_description:t})}async function d_(t,r={}){let n;if(r.client_id!==void 0&&r.client_id!==""){if(typeof r.client_id!=="string")vn("client_id must be a string");n=r.client_id}let o={},i=(u,f)=>{if(f===void 0||f==="")return;if(typeof f!=="string")vn(`${u} must be a string`);o[u]=f};for(let u of Fs)if(Object.hasOwn(r,u))i(u,r[u]);let s=t?.headers.get("authorization"),a=Boolean(s);if(t){if((t.headers.get("content-type")?.toLowerCase()??"").includes("application/x-www-form-urlencoded")){let u=new URLSearchParams(await t.clone().text()),f=u.getAll("client_id").filter((p)=>p.length>0);if(f.length>1)vn("client_id must not be repeated");n=f[0];for(let p of Fs){let h=u.getAll(p).filter((m)=>m.length>0);if(h.length>1)vn(`${p} must not be repeated`);if(h.length===1)i(p,h[0])}}}let c=o.client_secret!==void 0,d=o.client_assertion!==void 0||o.client_assertion_type!==void 0;if(a&&(c||d)||c&&d)vn("A request must use only one client authentication method");r.client_id=n;for(let u of Fs)r[u]=o[u];return{detected:a||Object.keys(o).length>0}}function u_(t){if(!Ws.test(t))return;try{let{clientId:r,clientSecret:n}=_s(t);return{client_id:r,client_secret:n}}catch{throw new ce("UNAUTHORIZED",{error_description:"invalid authorization header format",error:"invalid_client"},{"WWW-Authenticate":"Basic"})}}function Un(t,r){let n=t.grantTypes&&t.grantTypes.length>0?t.grantTypes:["authorization_code"];if(r==="refresh_token"&&n.includes("authorization_code"))return!0;return n.includes(r)}function qo(t,r){if(!r||!t.scopes)return;let n=new Set(t.scopes);for(let o of r)if(!n.has(o))throw new ce("BAD_REQUEST",{error_description:`client does not allow scope ${o}`,error:"invalid_scope"})}function Xt(t,r){let n=r?.method==="client_secret_basic",o=r?.scheme??(n?"Basic":void 0);throw new ce(o?"UNAUTHORIZED":"BAD_REQUEST",{error_description:t,error:"invalid_client"},o?{"WWW-Authenticate":o}:void 0)}async function Ct(t,r,n,o,i,s,a,c){let d=await ke(t,r,n);if(!d)Xt("client not found",{method:c});if(d.disabled)Xt("client is disabled",{method:c});let u=d.tokenEndpointAuthMethod??"client_secret_basic";if(c&&u!==c)Xt(`client registered for ${u} cannot use ${c}`,{method:c});if((d.tokenEndpointAuthMethod==="private_key_jwt"||Gs(r,d.tokenEndpointAuthMethod))&&!s)throw new ce("BAD_REQUEST",{error_description:`client registered for ${d.tokenEndpointAuthMethod} must use client_assertion`,error:"invalid_client"});if(!s){if(d.tokenEndpointAuthMethod!=="none"&&!o)Xt("client secret must be provided",{method:c});if(o&&!d.clientSecret)Xt("public client, client secret should not be received",{method:c});if(o&&!await s_(t,r,d.clientSecret,o))Xt("invalid client_secret",{method:c})}if(qo(d,i),a&&!Un(d,a))throw new ce("BAD_REQUEST",{error_description:`client is not authorized to use grant type ${a}`,error:"unauthorized_client"});return d}function rr(t){if(!t)return;return typeof t==="string"?JSON.parse(t):t}function Ot(t){return{clientId:t?.clientId,clientSecret:t?.kind==="client_secret"?t.clientSecret:void 0,preVerified:t?.kind==="pre_verified",authMethod:t?.method,confirmation:t?.kind==="pre_verified"?t.confirmation:void 0}}async function Dt(t,r,n){let o={...t.body??{}};await d_(t.request,o);let i=t.request?.headers.get("authorization")??void 0;if(o.client_assertion_type||o.client_assertion){if(!o.client_assertion||!o.client_assertion_type)throw new ce("BAD_REQUEST",{error_description:"client_assertion and client_assertion_type must both be provided",error:"invalid_client"});let{client_assertion:s,client_assertion_type:a}=o,c=r_(r,a);if(c){let u=await c.strategy.authenticate({ctx:t,opts:r,assertion:s,assertionType:a,clientId:o.client_id,expectedAudience:n});return{kind:"pre_verified",method:c.method,clientId:u.clientId,confirmation:u.confirmation}}let{verifyClientAssertion:d}=await import("./chunk-54tbfvya.js").then((u)=>u.o);return{kind:"pre_verified",method:"private_key_jwt",clientId:(await d(t,r,s,a,o.client_id,n)).clientId}}if(i&&!Ws.test(i)){let s=c_(i);if(!s)throw new ce("BAD_REQUEST",{error:"invalid_request",error_description:"Invalid authorization header format"});Xt("unsupported authorization scheme",{scheme:s})}if(i&&Ws.test(i)){let s=u_(i);if(s)return{kind:"client_secret",method:"client_secret_basic",clientId:s.client_id,clientSecret:s.client_secret}}if(o.client_id&&o.client_secret)return{kind:"client_secret",method:"client_secret_post",clientId:o.client_id,clientSecret:o.client_secret};if(o.client_id)return{kind:"public",method:"none",clientId:o.client_id};return null}function ia(t){let r=t.split(" ").map((o)=>o.trim()),n=new Set;for(let o of r)if(o==="login"||o==="consent"||o==="create"||o==="select_account"||o==="none")n.add(o);return new Set(n)}function l_(t){let r=t.redirectUris?.[0];if(!r)throw new te("Client has no redirect URIs for sector identifier");return new URL(r).host}async function f_(t,r,n){return on(`${l_(r)}.${t}`,n)}async function Tr(t,r,n){if(r.subjectType==="pairwise"&&n.pairwiseSecret)return f_(t,r,n.pairwiseSecret);return t}async function sa(t,r){return await t.postLogin?.consentReferenceId?.(r)||void 0}async function aa(t,r,n,o){let i=[{field:"clientId",value:r},{field:"userId",value:n}];if(o)return t.context.adapter.findOne({model:"oauthConsent",where:[...i,{field:"referenceId",value:o}]});let s=100;for(let a=0;;a+=s){let c=await t.context.adapter.findMany({model:"oauthConsent",where:i,limit:s,offset:a,sortBy:{field:"id",direction:"asc"}}),d=c.find((u)=>!u.referenceId);if(d||c.length<s)return d??null}}function nr(t){let r=Object.create(null);for(let n of new Set(t.keys())){let o=t.getAll(n);r[n]=o.length===1?o[0]:o}return r}function ca(t,r){if(!r)return!1;let n=st(t);if(!n)return!1;return n.getTime()>=r.getTime()}function Ir(t,r){let n=new URLSearchParams(t),o=n.get("prompt")?.split(" "),i=o?.findIndex((s)=>s===r)??-1;if(i>=0)o?.splice(i,1),o?.length?n.set("prompt",o.join(" ")):n.delete("prompt");return n}function da(t){let r=new URLSearchParams(t);return r.delete("max_age"),r}function jo(t,r){if(t.tokenEndpointAuthMethod==="none")return"pkce is required for public clients";let n=r?.scopes??[],o=n.includes("openid"),i=typeof r?.nonce==="string"&&r.nonce.length>0,s=o&&i;if(n.includes("offline_access")&&!s)return"pkce or OIDC nonce is required when requesting offline_access scope";if(t.requirePKCE??!0)return"pkce is required for this client";return!1}var p_=/^[a-z](?:[a-z0-9-]*[a-z0-9])?(?:\.[a-z0-9](?:[a-z0-9-]*[a-z0-9])?)+$/i,h_=new Set(["http:","https:","ws:","wss:","file:","ftp:","mailto:","javascript:","data:","vbscript:","blob:","about:","view-source:"]);function m_(t){let r=t.protocol.slice(0,-1),n=t.href.slice(t.protocol.length);return t.protocol!=="http:"&&t.protocol!=="https:"&&t.host.length===0&&n.startsWith("/")&&!n.startsWith("//")&&p_.test(r)}function g_(t){if(h_.has(t.protocol))return!1;if(t.host.length===0)return!1;return t.pathname.startsWith("/")}function cp(t){return m_(t)||g_(t)}var le=Vo().superRefine((t,r)=>{let n;try{n=new URL(t)}catch{return r.addIssue({code:"custom",message:"URL must be parseable",fatal:!0}),Pr}if(yd.includes(n.protocol)){r.addIssue({code:"custom",message:"URL cannot use javascript:, data:, or vbscript: scheme"});return}if(t.includes("#"))r.addIssue({code:"custom",message:"Redirect URI must not contain a fragment component"});if(n.protocol==="http:"&&!mr(n.host))r.addIssue({code:"custom",message:"Redirect URI must use HTTPS (HTTP allowed only for loopback hosts)"})});var w_=new Set(["iss","sub","aud","exp","nbf","iat","jti","auth_time","nonce","acr","amr","azp","sid","at_hash","c_hash","s_hash"]);function dp(t){if(!t)return{};let r=[],n=Object.create(null);for(let[o,i]of Object.entries(t)){if(w_.has(o)){r.push(o);continue}n[o]=i}if(r.length>0)Ee.warn(`oauth-provider: stripped reserved id-token claim name(s): ${r.join(", ")}. The AS owns these claim values.`);return n}var _p=k(e(),W()).nullable(),y_=oe({essential:E().optional(),value:e().optional(),values:A(e()).optional()}).nullable(),__=l({acr:y_.optional()}).catchall(_p),A_=oe({userinfo:k(e(),_p).optional(),id_token:__.optional()});function k_(t){if(typeof t==="string")try{return JSON.parse(t)}catch{return}return t}function On(t){let r=k_(t),n=A_.safeParse(r);return n.success?n.data:void 0}var Ap=D([e(),k(e(),W())]),E_=Ap,la=Ap.refine((t)=>On(t)!==void 0,{error:"claims must be a valid Claims request object"});function kp(t){return t===void 0||On(t)!==void 0}function Dn(t,r){let n=On(t)?.userinfo;if(!n)return[];let o=Object.keys(n);if(!r)return o;let i=new Set(r);return o.filter((s)=>i.has(s))}function Ep(t,r){let n=On(t);if(!n)return t===void 0;let o=n.id_token?.acr;if(!o||o.essential!==!0)return!0;let i=o.value===void 0||o.value===r,s=o.values===void 0||o.values.includes(r);return i&&s}function bp(t,r){let n=On(t);if(!n)return;let o=new Set(r),i=Object.fromEntries(Object.entries(n.userinfo??{}).filter(([a])=>o.has(a))),s=Object.keys(i).length?{...n,userinfo:i}:Object.fromEntries(Object.entries(n).filter(([a])=>a!=="userinfo"));return Object.keys(s).length?s:void 0}function up(t){let r=t.split(" ").filter((n)=>n!=="");if(r.length<=1)return{};return{given:r.slice(0,-1).join(" "),family:r.at(-1)}}var Mo={name:{scope:"profile",resolve:(t)=>t.name??void 0},picture:{scope:"profile",resolve:(t)=>t.image??void 0},given_name:{scope:"profile",resolve:(t)=>up(t.name).given},family_name:{scope:"profile",resolve:(t)=>up(t.name).family},email:{scope:"email",resolve:(t)=>t.email??void 0},email_verified:{scope:"email",resolve:(t)=>t.emailVerified??!1}},fa=Object.keys(Mo);function Ln(t){return t.advertisedMetadata?.claims_supported??t.claims??[]}var b_=new Set(["iss","sub","aud","exp","iat","jti","client_id","scope","auth_time","acr","amr","cnf"]);function v_(t){if(!t)return{};let r=[],n={};for(let[o,i]of Object.entries(t)){if(b_.has(o)){r.push(o);continue}n[o]=i}if(r.length>0)Ee.warn(`oauth-provider: stripped reserved access-token claim name(s): ${r.join(", ")}. The AS owns these claim values.`);return n}async function vp(t){let{ctx:r,opts:n,user:o,client:i,scopes:s,resources:a,referenceId:c,metadata:d,grantType:u,sessionId:f,perRequestClaims:p,resourcePolicyClaims:h}=t,m=await rp(n,{ctx:r,opts:n,user:o,client:i,scopes:s,grantType:u,referenceId:c,sessionId:f,resources:a,metadata:d}),w=n.customAccessTokenClaims?await n.customAccessTokenClaims({user:o,scopes:s,resources:a,referenceId:c,metadata:d}):{};return v_({...m,...p??{},...w,...h})}var S_=["javascript:","data:","vbscript:"],Qs=e().superRefine((t,r)=>{if(!URL.canParse(t))return r.addIssue({code:"custom",message:"resource must be an absolute URI",fatal:!0}),Pr;if(t.includes("#")){r.addIssue({code:"custom",message:"resource must not contain a fragment"});return}if(S_.includes(new URL(t).protocol))r.addIssue({code:"custom",message:"resource cannot use javascript:, data:, or vbscript: scheme"})}),R_=T(["none","consent","login","create","select_account"]),T_=e().superRefine((t,r)=>{let n=t.split(" ").map((i)=>i.trim()).filter(Boolean),o=new Set;if(!n.length){r.addIssue({code:"custom",message:"prompt must include at least one value"});return}for(let i of n){let s=R_.safeParse(i);if(!s.success){r.addIssue({code:"custom",message:`unsupported prompt value: ${i}`});continue}o.add(s.data)}if(o.has("none")&&o.size>1)r.addIssue({code:"custom",message:"prompt=none cannot be combined with other prompt values"})}),Pn=l({keys:A(k(e(),W())).min(1)}),I_=D([_(),e().trim().min(1)]).transform((t,r)=>{let n=typeof t==="number"?t:Number(t);if(!Number.isInteger(n)||n<0)return r.addIssue({code:"custom",message:"max_age must be a non-negative integer"}),Pr;return n}),U_=e().regex(/^[A-Za-z0-9_-]{43}$/,"dpop_jkt must be a base64url-encoded SHA-256 JWK thumbprint"),pa=l({response_type:e().pipe(T(["code"])).optional(),request:e().optional(),request_uri:e().optional(),redirect_uri:le.optional(),scope:e().optional(),state:e().optional(),client_id:e().min(1,"client_id is required"),prompt:T_.optional(),display:e().optional(),ui_locales:e().optional(),max_age:I_.optional(),acr_values:e().optional(),login_hint:e().optional(),id_token_hint:e().optional(),code_challenge:e().optional(),code_challenge_method:e().pipe(T(["S256"])).optional(),nonce:e().optional(),claims:E_.optional(),dpop_jkt:U_.optional(),resource:D([Qs,A(Qs).min(1)]).optional()}).passthrough(),C_=pa.extend({redirect_uri:le.optional(),claims:la.optional()}),O_=l({type:v("authorization_code"),query:C_,sessionId:e(),userId:e(),referenceId:e().optional(),authTime:_().optional(),resource:A(e()).optional()}).passthrough(),ha=l({redirect_uris:A(le).min(1).optional(),scope:e().optional(),client_name:e().refine((t)=>t.trim().length>0,"client_name cannot be empty").optional(),client_uri:e().optional(),logo_uri:e().optional(),contacts:A(e().min(1)).min(1).optional(),tos_uri:e().optional(),policy_uri:e().optional(),software_id:e().optional(),software_version:e().optional(),software_statement:e().optional(),post_logout_redirect_uris:A(le).min(1).optional(),backchannel_logout_uri:le.optional(),backchannel_logout_session_required:E().optional(),token_endpoint_auth_method:e().trim().min(1).optional(),jwks:Pn.optional(),jwks_uri:e().optional(),grant_types:A(e().trim().min(1)).min(1).optional(),response_types:A(T(["code"])).optional(),application_type:T(["web","native"]).optional(),subject_type:T(["public","pairwise"]).optional(),dpop_bound_access_tokens:E().optional(),resources:A(Qs).optional(),skip_consent:Sl({error:"skip_consent cannot be set during dynamic client registration"}).optional()}),HN=ha.omit({skip_consent:!0}).extend({client_id:e().refine((t)=>t.trim().length>0,"client_id cannot be empty"),client_secret:e().optional(),client_secret_expires_at:_().int().nonnegative().optional(),client_id_issued_at:_().int().nonnegative().optional()}).loose(),Ho=["EdDSA","ES256","ES512","PS256","RS256"],D_=new Set(Ho),L_=64;async function Sp(t,r){let n=t.identifierValidator;if(n){if(!await n(r))return{ok:!1,reason:`resource identifier ${r} failed validation`};return{ok:!0}}let o=Qs.safeParse(r);if(!o.success)return{ok:!1,reason:`resource identifier ${r} is invalid: ${o.error.issues[0]?.message??"not an absolute URI"}`};return{ok:!0}}async function Rp(t,r){let n=await Sp(t,r);if(!n.ok)throw new U("BAD_REQUEST",{error:"invalid_target",error_description:n.reason})}var P_=(t)=>`${t}/oauth2/userinfo`;async function Tp(t){if(!(t.headers.get("content-type")?.toLowerCase()??"").includes("application/x-www-form-urlencoded"))return;let r;try{r=await t.clone().text()}catch{return}if(!r)return;let n=new URLSearchParams(r).getAll("resource").filter((o)=>o.length>0);return n.length>0?n:void 0}function x_(t){if(t===void 0||t===null)return;if(typeof t==="string")return[t];if(Array.isArray(t)){let r=t.filter((n)=>typeof n==="string"&&n.length>0);return r.length>0?r:void 0}}async function Fo(t,r,n,o=[]){if(n===void 0)return!0;let i=Array.isArray(n)?n:[n];if(i.length>L_)return!1;let s=new Set(o),a=new Set;for(let c of i){if(s.has(c))continue;a.add(c)}if(a.size===0)return!0;return(await Promise.all(Array.from(a,(c)=>Wo(t,r,c)))).every(Boolean)}async function ma(t,r,n){let o=x_(n.resource),i=n.requestedScopes.includes("openid"),s=P_(t.context.baseURL??"");if(!o)return{audienceClaim:void 0,accessTokenTtl:null,refreshTokenTtl:null,signingAlgorithm:null,signingKeyId:null,rawCustomClaims:{},dpopBoundAccessTokensRequired:!1,effectiveScopes:[...n.requestedScopes]};let a=[...new Set(o)],c=[];for(let g of a){if(g===s)continue;let S=await Wo(t,r,g);if(S){if(S.disabled)throw new U("BAD_REQUEST",{error:"invalid_target",error_description:`requested resource ${g} is disabled`});c.push(S);continue}throw new U("BAD_REQUEST",{error:"invalid_target",error_description:`requested resource ${g} is not configured`})}let{value:d}=Ip(r);if(d&&c.length>0)await z_(t,r,n.clientId,c);let u=[...n.requestedScopes];for(let g of c){if(g.allowedScopes===null||g.allowedScopes===void 0)continue;let S=new Set(g.allowedScopes),C=u.filter((z)=>S.has(z));if(C.length===0)throw new U("BAD_REQUEST",{error:"invalid_scope",error_description:`none of the requested scopes are allowed for resource ${g.identifier}`});u=C}let f=null,p=null;for(let g of c){if(g.accessTokenTtl!=null)f=f===null?g.accessTokenTtl:Math.min(f,g.accessTokenTtl);if(g.refreshTokenTtl!=null)p=p===null?g.refreshTokenTtl:Math.min(p,g.refreshTokenTtl)}let h=new Set,m=new Set;for(let g of c){if(g.signingAlgorithm)h.add(g.signingAlgorithm);if(g.signingKeyId)m.add(g.signingKeyId)}if(h.size>1)throw new U("BAD_REQUEST",{error:"invalid_request",error_description:"multi-resource request has conflicting signingAlgorithm pins; a single JWS signature cannot satisfy multiple algorithms"});if(m.size>1)throw new U("BAD_REQUEST",{error:"invalid_request",error_description:"multi-resource request has conflicting signingKeyId pins; a single JWS signature cannot satisfy multiple key ids"});let w=h.values().next().value??null,y=m.values().next().value??null,I={};for(let g of c)if(g.customClaims&&typeof g.customClaims==="object")Object.assign(I,g.customClaims);let R=c.some((g)=>g.dpopBoundAccessTokensRequired===!0),b=i?[...a,s]:a,O=[...new Set(b)];return{audienceClaim:O.length===1?O[0]:O,accessTokenTtl:f,refreshTokenTtl:p,signingAlgorithm:w,signingKeyId:y,rawCustomClaims:I,dpopBoundAccessTokensRequired:R,effectiveScopes:u}}async function z_(t,r,n,o){if(o.length===0)return;let i=r.schema?.oauthClientResource?.modelName??"oauthClientResource",s=await t.context.adapter.findMany({model:i,where:[{field:"clientId",value:n}]}),a=new Set(s?.map((d)=>d.resourceId)??[]),c=o.filter((d)=>!a.has(d.identifier));if(c.length>0)throw new U("BAD_REQUEST",{error:"invalid_target",error_description:`client ${n} is not linked to resource(s) ${c.map((d)=>d.identifier).join(", ")}`})}async function N_(t,r,n,o){if(o.length===0)return!1;let i=r.schema?.oauthClientResource?.modelName??"oauthClientResource";return((await t.context.adapter.findMany({model:i,where:[{field:"clientId",value:n},{field:"resourceId",operator:"in",value:o}],limit:1}))?.length??0)>0}async function q_(t,r,n){if(n.length===0)return{};let o=await t.context.adapter.findMany({model:r.schema?.oauthResource?.modelName??"oauthResource",where:[{field:"identifier",operator:"in",value:n}]}),i=new Map(o.map((a)=>[a.identifier,a])),s={};for(let a of n){let c=i.get(a);if(c?.customClaims&&typeof c.customClaims==="object")Object.assign(s,c.customClaims)}return s}function Ip(t){if(t.enforcePerClientResources!==void 0)return{value:t.enforcePerClientResources,source:"explicit"};return{value:!0,source:"default"}}var Bo=new Map;function Ko(t){if(t===void 0){Bo.clear();return}Bo.delete(t)}async function Wo(t,r,n){if(await ga(t.context,r),r.cachedResources?.has(n)){let i=Bo.get(n);if(i)return Object.assign({},i)}let o=await t.context.adapter.findOne({model:r.schema?.oauthResource?.modelName??"oauthResource",where:[{field:"identifier",value:n}]});if(o&&r.cachedResources?.has(n))Bo.set(n,Object.assign({},o));return o}function j_(t){return t.name??t.identifier}function B_(t){let r=[];if(t.resources?.length)for(let n of t.resources)r.push(typeof n==="string"?{identifier:n}:n);return r}function Up(t,r){return{identifier:t.identifier,name:j_(t),accessTokenTtl:t.accessTokenTtl??null,refreshTokenTtl:t.refreshTokenTtl??null,signingAlgorithm:t.signingAlgorithm??null,signingKeyId:t.signingKeyId??null,allowedScopes:t.allowedScopes??null,customClaims:t.customClaims??null,dpopBoundAccessTokensRequired:t.dpopBoundAccessTokensRequired??!1,disabled:t.disabled??!1,policyVersion:1,metadata:t.metadata??null,createdAt:r,updatedAt:r}}function $_(t,r,n){if(r==="overwrite"){let{identifier:i,createdAt:s,...a}=Up(t,n);return a}let o={updatedAt:n};if(t.name!==void 0)o.name=t.name;if(t.accessTokenTtl!==void 0)o.accessTokenTtl=t.accessTokenTtl;if(t.refreshTokenTtl!==void 0)o.refreshTokenTtl=t.refreshTokenTtl;if(t.signingAlgorithm!==void 0)o.signingAlgorithm=t.signingAlgorithm;if(t.signingKeyId!==void 0)o.signingKeyId=t.signingKeyId;if(t.allowedScopes!==void 0)o.allowedScopes=t.allowedScopes;if(t.customClaims!==void 0)o.customClaims=t.customClaims;if(t.dpopBoundAccessTokensRequired!==void 0)o.dpopBoundAccessTokensRequired=t.dpopBoundAccessTokensRequired;if(t.disabled!==void 0)o.disabled=t.disabled;if(t.metadata!==void 0)o.metadata=t.metadata;return o}var M_=/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 Cp(t,r){let n=!1,o=r;for(let i=0;o&&!n&&i<5;i++)n=M_.test(o instanceof Error?o.message:String(o)),o=o instanceof Error?o.cause:void 0;if(n){t.logger.debug("oauth-provider: oauthResource table not yet created; deferring resource seed to first access.");return}t.logger.error("oauth-provider: could not seed `resources` at startup; retrying on first resource access.",r)}var lp=new WeakMap;function H_(t,r){let n=t.adapter,o=lp.get(n);if(!o)o=new WeakMap,lp.set(n,o);let i=o.get(r);if(i)return i;let s={completed:!1,promise:null};return o.set(r,s),s}async function V_(t,r){let n=B_(r);if(n.length===0)return;let o=r.resourceSeedMode??"insertOnly",i=r.schema?.oauthResource?.modelName??"oauthResource";for(let s of n){let a=await Sp(r,s.identifier);if(!a.ok){Ee.warn(`oauth-provider: skipping resource seed for ${s.identifier} \u2014 ${a.reason}`);continue}let c=s;if(c.signingAlgorithm!=null&&!D_.has(c.signingAlgorithm)){Ee.warn(`oauth-provider: dropping unsupported signingAlgorithm "${c.signingAlgorithm}" for resource ${c.identifier} \u2014 must be one of ${Ho.join(", ")}. Continuing without an algorithm override.`);let{signingAlgorithm:p,...h}=c;c=h}let d=[{field:"identifier",value:c.identifier}],u=await t.adapter.findOne({model:i,where:d}),f=new Date;if(!u)try{await t.adapter.create({model:i,data:Up(c,f)});continue}catch(p){if(!await t.adapter.findOne({model:i,where:d}).catch(()=>null))throw p}if(o==="insertOnly")continue;await t.adapter.update({model:i,where:d,update:$_(c,o,f)})}}async function ga(t,r){let n=H_(t,r);if(n.completed===!0)return;if(n.promise!==null)return n.promise;return n.promise=V_(t,r).then(()=>{n.completed=!0}).catch((o)=>{throw n.promise=null,o}),n.promise}function Op(t){let r=Ip(t);Ee.info(`oauth-provider: enforcePerClientResources resolved to ${r.value} (${r.source})`)}function Dp(t){return t.headers?.get("dpop")??void 0}function Jo(t,r){let{baseURL:n}=t.context,o=n.length;while(o>0&&n[o-1]==="/")o--;let i=n.slice(0,o);if(!t.request||!i)return`${i}${r}`;let s=new URL(i).pathname.replace(/\/$/,""),a=new URL(t.request.url).pathname;return`${i}${a.startsWith(`${s}/`)?a.slice(s.length):r}`}var F_=new Set(["openid","profile","email","offline_access"]);function Lp(t){return F_.has(t)}function wa(t){return[...new Set(t.map((r)=>r.trim()).filter(Boolean))]}function ya(t,r,n,o){if(t.length===0)return;if(!r.includes("client_credentials"))throw new U("BAD_REQUEST",{error:"invalid_client_metadata",error_description:"client_credentials_scopes requires the client_credentials grant"});if(n==="none")throw new U("BAD_REQUEST",{error:"invalid_client_metadata",error_description:"public clients cannot be assigned client_credentials scopes"});let i=new Set(o.scopes??[]),s=t.filter((a)=>!i.has(a)||Lp(a));if(s.length>0)throw new U("BAD_REQUEST",{error:"invalid_scope",error_description:`The following client_credentials scopes are invalid: ${s.join(", ")}`})}function K_(t,r,n=[]){let o=new Set(n),i={sub:t.id??void 0};for(let[s,a]of Object.entries(Mo))if(r.includes(a.scope)||o.has(s))i[s]=a.resolve(t);return i}function ua(t,r){let n={};for(let[o,i]of Object.entries(t??{})){if(i===void 0)continue;if(r&&o in r)continue;n[o]=i}return n}function W_(t){let r=t.headers?.get("authorization"),n=_r(r),o=t.request?.method==="POST"?t.body?.access_token??void 0:void 0;if(n&&o)throw new U("BAD_REQUEST",{error_description:"Multiple access token transport methods are not allowed",error:"invalid_request"});let i=n??(o?{scheme:"Bearer",token:o}:void 0);return{authorization:i,token:i?.token}}async function Pp(t,r){let{authorization:n}=W_(t);if(!n?.token)throw new U("UNAUTHORIZED",{error_description:"access token not found",error:"invalid_request"});let{payload:o,requestedUserInfoClaims:i}=await Hp(t,r,n.token);if(gn(o)&&!t.request)throw new U("UNAUTHORIZED",{error_description:"DPoP-bound access token requires an HTTP request context",error:"invalid_token"});try{await yn({payload:o,authorization:n,proofJwt:Dp(t),method:t.request?.method??"GET",url:Jo(t,"/oauth2/userinfo"),proofMaxAgeSeconds:r.dpop?.proofMaxAgeSeconds,signingAlgorithms:r.dpop?.signingAlgorithms,replayStore:Ac(t.context.internalAdapter)})}catch(h){if(wn(h))throw new U("UNAUTHORIZED",{error_description:h.message,error:h.code});throw h}let s=o.scope?.split(" ");if(!s?.includes("openid"))throw new U("BAD_REQUEST",{error_description:"Missing required scope",error:"invalid_scope"});if(!o.sub)throw new U("BAD_REQUEST",{error_description:"user not found",error:"invalid_request"});let a=await t.context.internalAdapter.findUserById(o.sub);if(!a)throw new U("BAD_REQUEST",{error_description:"user not found",error:"invalid_request"});let c=K_(a,s??[],i),d=o.client_id??o.azp,u=d&&(r.pairwiseSecret||ip(r))?await ke(t,r,d):void 0;if(r.pairwiseSecret&&u)c.sub=await Tr(a.id,u,r);let f=s?.length?await op(r,{ctx:t,opts:r,user:a,scopes:s,jwt:o,client:u??void 0,requestedClaims:i}):{},p=r.customUserInfoClaims&&s?.length?await r.customUserInfoClaims({user:a,scopes:s,jwt:o,requestedClaims:i}):{};return{...c,...ua(f,c),...ua(p),sub:c.sub}}var J_=Object.fromEntries(fa.map((t)=>[t,void 0]));function Go(t){return hn(t)?"DPoP":"Bearer"}var Q_="at+jwt";async function xp(t,r){let n=t.body.grant_type;if(!Rr(r).includes(n))throw new U("BAD_REQUEST",{error_description:`unsupported grant_type ${n}`,error:"unsupported_grant_type"});switch(n){case"authorization_code":return EA(t,r);case"client_credentials":return bA(t,r);case"refresh_token":return vA(t,r);default:{let o=ep(r,n);if(o)return o({ctx:t,opts:r,grantType:n,provider:G_(t,r,n)});throw new U("BAD_REQUEST",{error_description:`unsupported grant_type ${n}`,error:"unsupported_grant_type"})}}}function G_(t,r,n){return{getClient:(o)=>ke(t,r,o),authenticateClient:async(o)=>{let{clientId:i,clientSecret:s,preVerified:a,authMethod:c,confirmation:d}=Ot(await Dt(t,r,`${t.context.baseURL}${t.path??"/oauth2/token"}`));if(!i)throw new U("BAD_REQUEST",{error_description:"Missing required client_id",error:"invalid_request"});if(o?.requireCredentials!==!1&&!s&&!a)throw new U("BAD_REQUEST",{error_description:"Missing required client credentials",error:"invalid_client"});return{clientId:i,client:await Ct(t,r,i,s,o?.scopes,a,n,c),method:c,confirmation:d}},issueTokens:(o)=>{if(!n)throw new U("INTERNAL_SERVER_ERROR",{error_description:"issueTokens requires a grant type; pass it to getOAuthProviderApi(ctx, opts, grantType).",error:"server_error"});return Xo(t,r,{...o,grantType:n})},hashToken:(o,i)=>er(r.storeTokens,o,i),validateAccessToken:async(o,i)=>{let{validateAccessToken:s}=await Promise.resolve().then(()=>wp);return s(t,r,o,i)},requireActiveAccessToken:async(o,i)=>{let{requireActiveAccessToken:s}=await Promise.resolve().then(()=>wp);return s(t,r,o,i)}}}async function Z_(t,r,n,o,i,s,a){let c=a?.iat??Math.floor(Date.now()/1000),d=a?.exp??c+(r.accessTokenExpiresIn??3600),u=Oe(t.context).options,f=n?.id??o.clientId;return Wi(t,{options:u,header:{typ:Q_},signingKeyId:a?.signingKeyId??void 0,signingAlgorithm:a?.signingAlgorithm??void 0,payload:{...a?.accessTokenClaims??{},sub:f,aud:Xs(i),client_id:o.clientId,azp:o.clientId,scope:s.join(" "),sid:a?.sid,iss:u?.jwt?.issuer??t.context.baseURL,iat:c,exp:d,jti:_e(32),...a?.confirmation?{cnf:a.confirmation}:{}}})}async function Y_(t,r){let n;if(r==="EdDSA")n="SHA-512";else if(r.endsWith("384"))n="SHA-384";else if(r.endsWith("512"))n="SHA-512";else n="SHA-256";let o=new Uint8Array(await crypto.subtle.digest(n,new TextEncoder().encode(t)));return pr(o.slice(0,o.length/2))}async function X_(t,r,n,o,i,s,a,c,d,u){let f=Math.floor(Date.now()/1000),p=f+(r.idTokenExpiresIn??36000),h=await Tr(n.id,o,r),m=c!=null?Math.floor(c.getTime()/1000):void 0,w=dp(r.customIdTokenClaims?await r.customIdTokenClaims({user:n,scopes:i,metadata:rr(o.metadata)}):void 0),y=r.disableJwtPlugin?void 0:Oe(t.context).options,I=!r.disableJwtPlugin&&!y?.jwt?.sign?await Ki(t,y):void 0,R=r.disableJwtPlugin?"HS256":I?.alg??y?.jwks?.keyPairConfig?.alg,b=d?await Y_(d,R):void 0,O=Boolean(o.enableEndSession||o.backchannelLogoutUri),g={...J_,auth_time:m,acr:"0",...w,at_hash:b,iss:y?.jwt?.issuer??t.context.baseURL,sub:h,aud:o.clientId,nonce:s,iat:f,exp:p,sid:O?a:void 0},S=dp(u);if(Object.assign(g,ua(S,g)),r.disableJwtPlugin&&!o.clientSecret)return;let C=r.disableJwtPlugin?await new bs(g).setProtectedHeader({alg:"HS256"}).sign(new TextEncoder().encode(await Sr(t,r.storeClientSecret,o.clientSecret))):await Wi(t,{options:y,payload:g,resolvedKey:I??void 0});if(C&&b&&y?.jwt?.sign){let z=so(C);if(z.alg!==R)throw new U("INTERNAL_SERVER_ERROR",{error_description:`ID token signed with "${z.alg}" but at_hash was computed for "${R}". Ensure jwt.sign uses the algorithm declared in keyPairConfig.alg.`,error:"server_error"})}return C}async function fp(t,r,n){return(t.prefix?.refreshToken??"")+(t.formatRefreshToken?.encrypt?t.formatRefreshToken.encrypt(r,n):r)}async function Zo(t,r){if(t.prefix?.refreshToken)if(r.startsWith(t.prefix.refreshToken))r=r.replace(t.prefix.refreshToken,"");else throw new U("BAD_REQUEST",{error_description:"refresh token not found",error:"invalid_token"});return t.formatRefreshToken?.decrypt?t.formatRefreshToken?.decrypt(r):{token:r}}async function eA(t,r,n,o,i,s,a,c,d,u,f,p){let h=s.iat??Math.floor(Date.now()/1000),m=s?.exp??h+(r.accessTokenExpiresIn??3600),w=r.generateOpaqueAccessToken?await r.generateOpaqueAccessToken():_e(32,"A-Z","a-z");return await t.context.adapter.create({model:"oauthAccessToken",data:{token:await er(r.storeTokens,w,"access_token"),clientId:o.clientId,sessionId:s?.sid,userId:n?.id,referenceId:c,authorizationCodeId:d,resources:a,refreshId:u,confirmation:f,requestedUserInfoClaims:p?.length?p:void 0,scopes:i,createdAt:new Date(h*1000),expiresAt:new Date(m*1000)}}),(r.prefix?.opaqueAccessToken??"")+w}async function Yo(t,r,n){let o=await t.context.adapter.findMany({model:"oauthRefreshToken",where:[{field:"clientId",value:r},{field:"userId",value:n}]});if(o.length)await t.context.adapter.deleteMany({model:"oauthAccessToken",where:[{field:"refreshId",operator:"in",value:o.map((i)=>i.id)}]});await t.context.adapter.deleteMany({model:"oauthRefreshToken",where:[{field:"clientId",value:r},{field:"userId",value:n}]})}async function tA(t,r){let n=async(o)=>{try{await t.context.adapter.deleteMany({model:o,where:[{field:"authorizationCodeId",value:r}]})}catch(i){t.context.logger.error("authorization code replay cleanup failed",i)}};await n("oauthAccessToken"),await n("oauthRefreshToken")}async function pp(t,r,n,o,i,s,a,c,d,u,f,p,h){let m=c.iat??Math.floor(Date.now()/1000),w=c?.exp??m+(r.refreshTokenExpiresIn??2592000),y=r.generateRefreshToken?await r.generateRefreshToken():_e(32,"A-Z","a-z"),I=c?.sid,R={token:await er(r.storeTokens,y,"refresh_token"),clientId:s.clientId,sessionId:I,userId:n.id,referenceId:o,authorizationCodeId:i,authTime:u,confirmation:p,requestedUserInfoClaims:h?.length?h:void 0,scopes:a,resources:f,createdAt:new Date(m*1000),expiresAt:new Date(w*1000)};if(!d?.id)return{id:(await t.context.adapter.create({model:"oauthRefreshToken",data:R})).id,token:await fp(r,y,I)};let b=new Date(m*1000),O={revoked:b,rotatedAt:b},g=r.refreshTokenReuseInterval??0;if(g>0)O.rotationReplayExpiresAt=new Date((m+g)*1000);if(!await t.context.adapter.incrementOne({model:"oauthRefreshToken",where:[{field:"id",value:d.id},{field:"revoked",operator:"eq",value:null}],increment:{},set:O}))throw new U("BAD_REQUEST",{error_description:"invalid refresh token",error:"invalid_grant"});return{id:(await t.context.adapter.create({model:"oauthRefreshToken",data:R})).id,token:await fp(r,y,I)}}async function zp(t,r,n){let o=await ma(t,r,{resource:n.resources,clientId:n.clientId,requestedScopes:n.requestedScopes}),i=o.accessTokenTtl!==null?n.iat+o.accessTokenTtl:n.scopeExpiresAtSeconds,s=r.refreshTokenExpiresIn??2592000,a=o.refreshTokenTtl!==null?Math.min(o.refreshTokenTtl,s):s;return{audienceClaim:o.audienceClaim,effectiveScopes:o.effectiveScopes,accessTokenExpiresAtSeconds:Math.min(n.scopeExpiresAtSeconds,i),refreshTokenExpiresAtSeconds:n.iat+a,refreshResources:n.refreshToken?.resources??n.originalResources??n.resources,signingAlgorithm:o.signingAlgorithm,signingKeyId:o.signingKeyId,resourceCustomClaims:o.rawCustomClaims,dpopBoundAccessTokensRequired:o.dpopBoundAccessTokensRequired}}function hp(t){throw new U("BAD_REQUEST",{error:"invalid_dpop_proof",error_description:t})}function iA(t){let r=rr(t.metadata)??{};return t.dpopBoundAccessTokens===!0||r.dpop_bound_access_tokens===!0}async function Np(t,r,n){let o=n.verificationValue?.query.dpop_jkt,i=hn(n.refreshToken?.confirmation),s=i??o,a=Dp(t),c=iA(n.client)||n.grantIssuance.dpopBoundAccessTokensRequired||!!o||!!i;if(!a){if(c)hp("DPoP proof header is required");return}try{return{jkt:(await Ro({proofJwt:a,method:"POST",url:Jo(t,t.path??"/oauth2/token"),expectedJkt:s,proofMaxAgeSeconds:r.dpop?.proofMaxAgeSeconds,signingAlgorithms:r.dpop?.signingAlgorithms,replayStore:Ac(t.context.internalAdapter)})).jkt}}catch(d){if(So(d))hp(d.message);throw d}}function $o(t){return t?[...new Set(t)].sort():void 0}function mp(t,r){let n=$o(t),o=$o(r);if(n===void 0||o===void 0)return n===o;if(n.length!==o.length)return!1;return n.every((i,s)=>i===o[s])}function gp(t){if(!t)return;if("jkt"in t)return`jkt:${t.jkt}`;return`x5t#S256:${t["x5t#S256"]}`}function aA(t,r){return gp(t)===gp(r)}function cA(t){if(!t||typeof t!=="object")return!1;let r=t;return typeof r.jkt==="string"&&r["x5t#S256"]===void 0||typeof r["x5t#S256"]==="string"&&r.jkt===void 0}function uA(t){return t==="Bearer"||t==="DPoP"}function lA(t){if(!t||typeof t!=="object")return!1;let r=t;return typeof r.access_token==="string"&&typeof r.expires_in==="number"&&typeof r.expires_at==="number"&&uA(r.token_type)&&typeof r.scope==="string"&&(r.refresh_token===void 0||typeof r.refresh_token==="string")&&(r.id_token===void 0||typeof r.id_token==="string")}function pA(t){if(!t||typeof t!=="object")return!1;let r=t,n=r.request;return!!n&&Array.isArray(n.effectiveScopes)&&n.effectiveScopes.every((o)=>typeof o==="string")&&(n.requestedResources===void 0||Array.isArray(n.requestedResources)&&n.requestedResources.every((o)=>typeof o==="string"))&&(n.confirmation===void 0||cA(n.confirmation))&&lA(r.response)}function qp(t){let r=$o(t.requestedResources);return{effectiveScopes:$o(t.effectiveScopes)??[],...r?{requestedResources:r}:{},...t.confirmation?{confirmation:t.confirmation}:{}}}function hA(t,r){return mp(t.effectiveScopes,r.effectiveScopes)&&mp(t.requestedResources,r.requestedResources)&&aA(t.confirmation,r.confirmation)}async function mA(t,r){return nt({key:t.context.secretConfig,data:JSON.stringify(r)})}async function gA(t,r){let n=await ot({key:t.context.secretConfig,data:r}),o=JSON.parse(n);if(!pA(o))return;return o}function jp(t){return!!t.rotatedAt&&!!t.rotationReplayExpiresAt&&t.rotationReplayExpiresAt>=new Date}async function wA(t,r,n,o,i){if((r.refreshTokenReuseInterval??0)<=0)return;await t.context.adapter.update({model:"oauthRefreshToken",where:[{field:"id",value:n.id}],update:{rotationReplayResponse:await mA(t,{request:o,response:i})}})}async function yA(t,r,n){if(!jp(r))return;if(!r.rotationReplayResponse)return;try{let o=await gA(t,r.rotationReplayResponse);if(!o||!hA(o.request,n))return;return o.response}catch(o){t.context.logger.error("refresh token rotation replay failed",o);return}}async function _A(t,r,n){let o=Math.floor(Date.now()/1000),i=await zp(t,r,{clientId:n.client.clientId,requestedScopes:n.scopes,resources:n.resources,refreshToken:n.refreshToken,iat:o,scopeExpiresAtSeconds:o+(r.accessTokenExpiresIn??3600)}),s=await Np(t,r,{client:n.client,grantIssuance:i,refreshToken:n.refreshToken});return qp({effectiveScopes:i.effectiveScopes,requestedResources:n.resources,confirmation:s})}function AA(t,r){let n=Math.floor(Date.now()/1000);return t.json({...r,expires_in:Math.max(0,r.expires_at-n)})}async function Xo(t,r,n){let{client:o,scopes:i,user:s,grantType:a,referenceId:c,sessionId:d,nonce:u,refreshToken:f,authTime:p,verificationValue:h}=n,m=Math.floor(Date.now()/1000),w=m+(s?r.accessTokenExpiresIn??3600:r.m2mAccessTokenExpiresIn??3600),y=r.scopeExpirations?i.map((Z)=>r.scopeExpirations?.[Z]?Yt(r.scopeExpirations[Z],m):w).reduce((Z,re)=>Z<re?Z:re,w):w,I=await zp(t,r,{clientId:o.clientId,requestedScopes:i,resources:n.resources,originalResources:n.originalResources,refreshToken:n.refreshToken,iat:m,scopeExpiresAtSeconds:y}),{audienceClaim:R,effectiveScopes:b,accessTokenExpiresAtSeconds:O,refreshTokenExpiresAtSeconds:g}=I,S=s&&Un(o,"refresh_token")&&(f?.scopes?.includes("offline_access")||i.includes("offline_access")),C=R&&!r.disableJwtPlugin,z=s&&b.includes("openid"),L=rr(o.metadata),x=z&&s?{...await np(r,{ctx:t,opts:r,user:s,client:o,scopes:b,grantType:a,referenceId:c,sessionId:d,resources:n.resources,metadata:L}),...n.idTokenClaims??{}}:void 0,P=r.customTokenResponseFields?await r.customTokenResponseFields({grantType:a,user:s,scopes:b,metadata:L,verificationValue:h}):void 0,j=I.refreshResources,B=n.confirmation??await Np(t,r,{client:o,grantIssuance:I,verificationValue:h,refreshToken:f}),H=n.requestedUserInfoClaims??f?.requestedUserInfoClaims??[],q=S&&s&&!C?await pp(t,r,s,c,n.authorizationCodeId,o,b,{iat:m,exp:g,sid:d},f,p,j,B,H):void 0,J=C?await vp({ctx:t,opts:r,user:s,client:o,scopes:b,grantType:a,sessionId:d,resources:n.resources,referenceId:c,metadata:L,perRequestClaims:n.accessTokenClaims,resourcePolicyClaims:I.resourceCustomClaims}):void 0,[Q,G]=await Promise.all([C?Z_(t,r,s,o,R,b,{iat:m,exp:O,sid:d,signingAlgorithm:I.signingAlgorithm,signingKeyId:I.signingKeyId,accessTokenClaims:J,confirmation:B}):eA(t,r,s,o,b,{iat:m,exp:O,sid:d},n?.resources,c,n.authorizationCodeId,q?.id,B,H),q?q:S&&s?pp(t,r,s,c,n.authorizationCodeId,o,b,{iat:m,exp:g,sid:d},f,p,j,B,H):void 0]),M=z?await X_(t,r,s,o,b,u,d,p,Q,x):void 0,Y={...P,...n.tokenResponse??{},access_token:Q,expires_in:O-m,expires_at:O,token_type:Go(B),refresh_token:G?.token,scope:b.join(" "),id_token:M};if(f?.id&&G?.id)try{await wA(t,r,f,qp({effectiveScopes:b,requestedResources:n.resources,confirmation:B}),Y)}catch(Z){t.context.logger.error("failed to store refresh token rotation replay",Z)}return t.json(Y)}async function kA(t,r,n,o,i,s){let a=await er(r.storeTokens,n,"authorization_code"),c=await t.context.internalAdapter.consumeVerificationValue(a);if(!c)throw await tA(t,a),new U("BAD_REQUEST",{error_description:"invalid code",error:"invalid_grant"});let d;try{d=JSON.parse(c.value)}catch{throw new U("BAD_REQUEST",{error_description:"malformed verification value",error:"invalid_grant"})}let u=O_.safeParse(d);if(!u.success)throw new U("BAD_REQUEST",{error_description:"malformed verification value",error:"invalid_grant"});let f=u.data;if(f.query.client_id!==o)throw new U("BAD_REQUEST",{error_description:"invalid client_id",error:"invalid_grant"});let p=f.query.redirect_uri;if(p){if(!i)throw new U("BAD_REQUEST",{error_description:"redirect_uri is required",error:"invalid_request"});if(p!==i)throw new U("BAD_REQUEST",{error_description:"redirect_uri mismatch",error:"invalid_grant"})}else if(i)throw new U("BAD_REQUEST",{error_description:"redirect_uri mismatch",error:"invalid_grant"});let h=Ut(f.resource)??Ut(f.query.resource),m=s??h;if(s&&h){let w=new Set(s),y=new Set(h);for(let I of w)if(!y.has(I))throw new U("BAD_REQUEST",{error_description:"requested resource not authorized",error:"invalid_target"})}return{verificationValue:f,effectiveResources:m,authorizedResources:h,authorizationCodeId:a}}async function EA(t,r){let{clientId:n,clientSecret:o,preVerified:i,authMethod:s}=Ot(await Dt(t,r,`${t.context.baseURL}/oauth2/token`)),{code:a,code_verifier:c,redirect_uri:d,resource:u}=t.body,f=Ut(u);if(!n)throw new U("BAD_REQUEST",{error_description:"client_id is required",error:"invalid_request"});if(!a)throw new U("BAD_REQUEST",{error_description:"code is required",error:"invalid_request"});let p=n&&o,h=n&&a&&c;if(!p&&!h&&!i)throw new U("BAD_REQUEST",{error_description:"Either code_verifier or client_secret is required",error:"invalid_request"});let m=await Ct(t,r,n,o,void 0,i,"authorization_code",s),{verificationValue:w,effectiveResources:y,authorizedResources:I,authorizationCodeId:R}=await kA(t,r,a,n,d,f),b=w.query.scope?.split(" ");if(!b)throw new U("INTERNAL_SERVER_ERROR",{error_description:"verification scope unset",error:"invalid_scope"});if(qo(m,b),jo(m,{scopes:w.query?.scope?.split(" ")||[],nonce:w.query?.nonce})){if(!h)throw new U("BAD_REQUEST",{error_description:"PKCE is required for this client",error:"invalid_request"})}else if(!(h||p||i))throw new U("BAD_REQUEST",{error_description:"Either PKCE (code_verifier) or client authentication (client_secret or client_assertion) is required",error:"invalid_request"});let O=!!w.query?.code_challenge,g=!!c;if(O||g){if(O&&!g)throw new U("BAD_REQUEST",{error_description:"code_verifier required because PKCE was used in authorization",error:"invalid_request"});if(!O&&g)throw new U("BAD_REQUEST",{error_description:"code_verifier provided but PKCE was not used in authorization",error:"invalid_request"});if((w.query?.code_challenge_method==="S256"?await an(c):void 0)!==w.query?.code_challenge)throw new U("BAD_REQUEST",{error_description:"code verification failed",error:"invalid_grant"})}if(!w.userId)throw new U("BAD_REQUEST",{error_description:"missing user, user may have been deleted",error:"invalid_user"});let S=await t.context.internalAdapter.findUserById(w.userId);if(!S)throw new U("BAD_REQUEST",{error_description:"missing user, user may have been deleted",error:"invalid_user"});let C=await t.context.adapter.findOne({model:"session",where:[{field:"id",value:w.sessionId}]});if(!C||C.expiresAt<new Date)throw new U("BAD_REQUEST",{error_description:"session no longer exists",error:"invalid_request"});let z=w.authTime!=null?st(w.authTime):ap(C),L=Dn(w.query.claims,Ln(r));return Xo(t,r,{client:m,scopes:w.query.scope?.split(" ")??[],user:S,grantType:"authorization_code",referenceId:w.referenceId,sessionId:C.id,nonce:w.query?.nonce,authTime:z,verificationValue:w,authorizationCodeId:R,requestedUserInfoClaims:L,resources:y,originalResources:I})}async function bA(t,r){let{clientId:n,clientSecret:o,preVerified:i,authMethod:s}=Ot(await Dt(t,r,`${t.context.baseURL}/oauth2/token`)),{scope:a,resource:c}=t.body,d=Ut(c);if(!n)throw new U("BAD_REQUEST",{error_description:"Missing required client_id",error:"invalid_request"});let u=await Ct(t,r,n,o,void 0,i,"client_credentials",s);if(u.tokenEndpointAuthMethod==="none")throw new U("BAD_REQUEST",{error_description:"public clients cannot use the client_credentials grant",error:"unauthorized_client"});let f=u.clientCredentialsScopes;if(!f?.length)throw new U("BAD_REQUEST",{error_description:"client has no authorized client_credentials scopes",error:"unauthorized_client"});let p=a?.split(" ");if(p){let h=new Set(f),m=p.filter((w)=>!h.has(w)||Lp(w));if(m.length)throw new U("BAD_REQUEST",{error_description:`The following scopes are invalid: ${m.join(", ")}`,error:"invalid_scope"})}if(!p)p=[...f];return Xo(t,r,{client:u,scopes:p,grantType:"client_credentials",resources:d})}async function vA(t,r){let{clientId:n,clientSecret:o,preVerified:i,authMethod:s}=Ot(await Dt(t,r,`${t.context.baseURL}/oauth2/token`)),{refresh_token:a,scope:c,resource:d}=t.body,u=Ut(d);if(!n)throw new U("BAD_REQUEST",{error_description:"Missing required client_id",error:"invalid_request"});if(!a)throw new U("BAD_REQUEST",{error_description:"Missing a required refresh_token for refresh_token grant",error:"invalid_request"});let f=await Ct(t,r,n,o,void 0,i,"refresh_token",s),p=await Zo(r,a),h=await t.context.adapter.findOne({model:"oauthRefreshToken",where:[{field:"token",value:await tr(r.storeTokens,p.token,"refresh_token")}]});if(!h)throw new U("BAD_REQUEST",{error_description:"session not found",error:"invalid_grant"});if(h.clientId!==n)throw new U("BAD_REQUEST",{error_description:"invalid refresh token",error:"invalid_grant"});if(h.expiresAt<new Date)throw new U("BAD_REQUEST",{error_description:"invalid refresh token",error:"invalid_grant"});if(u&&h.resources&&!u.every((R)=>h.resources?.includes(R)))throw new U("BAD_REQUEST",{error_description:"requested resource invalid",error:"invalid_target"});let m=h?.scopes,w=c?.split(" ");if(w){let R=new Set(m);for(let b of w)if(!R.has(b))throw new U("BAD_REQUEST",{error_description:`unable to issue scope ${b}`,error:"invalid_scope"})}if(qo(f,w??m),h.revoked){if(jp(h)){let R=await yA(t,h,await _A(t,r,{client:f,refreshToken:h,scopes:w??m,resources:u??h.resources}));if(R)return AA(t,R);throw new U("BAD_REQUEST",{error_description:"invalid refresh token",error:"invalid_grant"})}throw await Yo(t,n,h.userId),new U("BAD_REQUEST",{error_description:"invalid refresh token",error:"invalid_grant"})}let y=await t.context.internalAdapter.findUserById(h.userId);if(!y)throw new U("BAD_REQUEST",{error_description:"user not found",error:"invalid_request"});let I=h.authTime!=null?st(h.authTime):void 0;return Xo(t,r,{client:f,scopes:w??m,user:y,grantType:"refresh_token",referenceId:h.referenceId,authorizationCodeId:h.authorizationCodeId,sessionId:h.sessionId,refreshToken:h,resources:u??h.resources,authTime:I,requestedUserInfoClaims:h.requestedUserInfoClaims})}var wp=Co({introspectEndpoint:()=>ka,requireActiveAccessToken:()=>OA,requireActiveAccessTokenWithClaims:()=>Hp,validateAccessToken:()=>Aa}),Bp="Invalid access token",SA=`Bearer error="invalid_token", error_description="${Bp}"`;function Cr(){return{payload:{active:!1},requestedUserInfoClaims:[]}}function RA(t,r){if(t==null)return[];return(Array.isArray(t)?t:[t]).filter((n)=>typeof n==="string"&&n!==r)}async function $p(t,r,n){let{introspectingClientId:o,issuerClientId:i,audienceResources:s}=n;if(!o)return!0;if(o===i)return!0;if(s.length===0)return!1;return N_(t,r,o,s)}async function TA(t,r,n,o){if(r.disableJwtPlugin)throw new ce("BAD_REQUEST",{error_description:"JWT access tokens are disabled",error:"invalid_request"});let i=Oe(t.context),s=i.options,a=`${t.context.baseURL??""}/oauth2/userinfo`,c=s?.jwt?.issuer??t.context.baseURL,d;try{d=(await Hr(n,Qo(await Ar(n,{jwksFetch:s?.jwks?.remoteUrl?s.jwks.remoteUrl:async()=>(await i.endpoints.getJwks(t))?.response,jwksCacheKey:i})),{issuer:c})).payload}catch(h){if(h instanceof yi||h instanceof zr)return{active:!1};if(h instanceof TypeError||xo(h))throw new ce("BAD_REQUEST",{error_description:"invalid JWT signature",error:"invalid_request"});throw h}let u=d.aud;if(!await Fo(t,r,u,[a]))return{active:!1};if(!d.azp)return{active:!1};let f=await ke(t,r,d.azp);if(!f||f?.disabled)return{active:!1};if(!await $p(t,r,{introspectingClientId:o,issuerClientId:d.azp,audienceResources:RA(u,a)}))return{active:!1};let p=d.sid;if(p){let h=await t.context.adapter.findOne({model:"session",where:[{field:"id",value:p}]});if(!h||h.expiresAt<new Date)return{active:!1}}return d.client_id=d.azp,d.active=!0,d.token_type=Go(d.cnf),d}async function IA(t,r,n,o){let i=n;if(r.prefix?.opaqueAccessToken)if(i.startsWith(r.prefix.opaqueAccessToken))i=i.replace(r.prefix.opaqueAccessToken,"");else throw new ce("BAD_REQUEST",{error_description:"opaque access token not found",error:"invalid_request"});let s=await t.context.adapter.findOne({model:"oauthAccessToken",where:[{field:"token",value:await tr(r.storeTokens,i,"access_token")}]});if(!s)throw new ce("BAD_REQUEST",{error_description:"opaque access token not found",error:"invalid_token"});if(!s.expiresAt||s.expiresAt<new Date)return Cr();if(s.revoked)return Cr();let a=Array.isArray(s.resources)?s.resources:void 0,c;if(s.clientId){if(c=await ke(t,r,s.clientId),!c||c?.disabled)return Cr();if(!await $p(t,r,{introspectingClientId:o,issuerClientId:s.clientId,audienceResources:a??[]}))return Cr()}let d=s.sessionId??void 0;if(d){let y=await t.context.adapter.findOne({model:"session",where:[{field:"id",value:d}]});if(!y||y.expiresAt<new Date)return Cr()}let u;if(s.userId)u=await t.context.internalAdapter.findUserById(s?.userId);let f=`${t.context.baseURL}/oauth2/userinfo`;if(a?.length&&!await Fo(t,r,a,[f]))return Cr();let p=a?[...a]:void 0;if(p?.length&&s.scopes?.includes("openid")){if(!p.includes(f))p.push(f)}let h=a?.length?await q_(t,r,a):{},m=c?await vp({ctx:t,opts:r,user:u,client:c,scopes:s.scopes??[],grantType:void 0,sessionId:void 0,resources:a,referenceId:s.referenceId,metadata:rr(c.metadata),perRequestClaims:void 0,resourcePolicyClaims:h}):{},w=(r.disableJwtPlugin?void 0:Oe(t.context))?.options;return{payload:{...m,active:!0,iss:w?.jwt?.issuer??t.context.baseURL,aud:Xs(p),client_id:s.clientId,azp:s.clientId,sub:u?.id,sid:d,exp:Math.floor(new Date(s.expiresAt).getTime()/1000),iat:Math.floor(new Date(s.createdAt).getTime()/1000),scope:s.scopes?.join(" "),token_type:Go(s.confirmation),...s.confirmation?{cnf:s.confirmation}:{}},requestedUserInfoClaims:s.requestedUserInfoClaims??[]}}async function UA(t,r,n,o){let i=await t.context.adapter.findOne({model:"oauthRefreshToken",where:[{field:"token",value:await tr(r.storeTokens,n,"refresh_token")}]});if(!i)throw new ce("BAD_REQUEST",{error_description:"token not found",error:"invalid_token"});if(!i.clientId||i.clientId!==o)return{active:!1};if(!i.expiresAt||i.expiresAt<new Date)return{active:!1};if(i.revoked)return{active:!1};let s=i.sessionId??void 0;if(s){let c=await t.context.adapter.findOne({model:"session",where:[{field:"id",value:s}]});if(!c||c.expiresAt<new Date)s=void 0}let a=void 0;if(i.userId)a=await t.context.internalAdapter.findUserById(i?.userId)??void 0;return{active:!0,client_id:o,iss:(r.disableJwtPlugin?void 0:Oe(t.context))?.options?.jwt?.issuer??t.context.baseURL,sub:a?.id,sid:s,exp:Math.floor(new Date(i.expiresAt).getTime()/1000),iat:Math.floor(new Date(i.createdAt).getTime()/1000),scope:i.scopes?.join(" "),token_type:Go(i.confirmation),...i.confirmation?{cnf:i.confirmation}:{}}}function _a(){return new ce("UNAUTHORIZED",{error_description:Bp,error:"invalid_token"},{"WWW-Authenticate":SA})}function CA(t){return t.status==="BAD_REQUEST"||t.body?.error==="invalid_token"}async function Mp(t,r,n,o){try{return{payload:await TA(t,r,n,o),requestedUserInfoClaims:[]}}catch(i){if(i instanceof ce);else if(i instanceof Error)throw i;else throw Error(i)}try{return await IA(t,r,n,o)}catch(i){if(i instanceof ce);else if(i instanceof Error)throw i;else throw Error("Unknown error validating access token")}throw _a()}async function Aa(t,r,n,o){return(await Mp(t,r,n,o)).payload}async function OA(t,r,n,o){let i=await Aa(t,r,n,o);if(i.active)return i;throw _a()}async function Hp(t,r,n,o){let{payload:i,requestedUserInfoClaims:s}=await Mp(t,r,n,o);if(i.active)return{payload:i,requestedUserInfoClaims:s};throw _a()}async function yp(t,r,n,o){if(!n.active||!n.sub)return n;let i=n.client_id??n.azp;if(!i)return n;let s=i===o.clientId?o:await ke(t,r,i);if(!s)return n;let a=await Tr(n.sub,s,r);return{...n,sub:a}}async function ka(t,r){let{token:n,token_type_hint:o}=t.body;if(o!=="access_token"&&o!=="refresh_token")o=void 0;let{clientId:i,clientSecret:s,preVerified:a,authMethod:c}=Ot(await Dt(t,r,`${t.context.baseURL}/oauth2/introspect`));if(!i||!s&&!a)throw new ce("UNAUTHORIZED",{error_description:"missing required credentials",error:"invalid_client"});if(n&&typeof n==="string")n=fn(n);if(!n?.length)throw new ce("BAD_REQUEST",{error_description:"missing a required token for introspection",error:"invalid_request"});let d=await Ct(t,r,i,s,void 0,a,void 0,c);try{if(o===void 0||o==="access_token")try{return yp(t,r,await Aa(t,r,n,d.clientId),d)}catch(u){if(u instanceof ce){if(o==="access_token")throw u}else if(u instanceof Error)throw u;else throw Error(u)}if(o===void 0||o==="refresh_token")try{return yp(t,r,await UA(t,r,(await Zo(r,n)).token,d.clientId),d)}catch(u){if(u instanceof ce){if(o==="refresh_token")throw u}else if(u instanceof Error)throw u;else throw Error(u)}throw new ce("BAD_REQUEST",{error_description:"token not found",error:"invalid_request"})}catch(u){if(u instanceof ce){if(CA(u))return{active:!1};throw u}else if(u instanceof Error)throw Ee.error("Introspection error:",u.message,u.stack),new ce("INTERNAL_SERVER_ERROR");else throw Ee.error("Introspection error:",u),new ce("INTERNAL_SERVER_ERROR")}}var Vp="1.7.12";function Ea(t){return t?.get("sec-fetch-mode")==="cors"}var{defineProperty:ba,getOwnPropertyDescriptor:DA,getOwnPropertyNames:LA}=Object,PA=Object.prototype.hasOwnProperty,Kp=(t,r)=>{let n={};for(var o in t)ba(n,o,{get:t[o],enumerable:!0});if(!r)ba(n,Symbol.toStringTag,{value:"Module"});return n},Fp=(t,r,n,o)=>{if(r&&typeof r==="object"||typeof r==="function"){for(var i=LA(r),s=0,a=i.length,c;s<a;s++)if(c=i[s],!PA.call(t,c)&&c!==n)ba(t,c,{get:((d)=>r[d]).bind(null,c),enumerable:!(o=DA(r,c))||o.enumerable})}return t},Wp=(t,r,n)=>(Fp(t,r,"default"),n&&Fp(n,r,"default"));function Jp(t,r){let n=r.id?{id:r.id}:{};for(let o in t){let i=t[o],s=r[o];if(s===void 0)continue;n[i.fieldName||o]=s}return n}function Qp(t,r){if(!r)return null;let n={id:r.id};for(let[o,i]of Object.entries(t))n[o]=r[i.fieldName||o];return n}var xA=5000,zA=2000,NA=250,qA=(t)=>`revoke-unproven-account-access:${t}`;async function jA(t,r){let n=Date.now()+zA;while(Date.now()<n){let o=await t.context.internalAdapter.findVerificationValue(r);if(!o)return;if(o.expiresAt<=new Date){await t.context.internalAdapter.deleteVerificationByIdentifier(r);return}await new Promise((i)=>setTimeout(i,NA))}}async function Gp(t,r){let n=qA(r);if(!await t.context.internalAdapter.reserveVerificationValue({identifier:n,value:r,expiresAt:new Date(Date.now()+xA)}).catch((o)=>{if(o instanceof te&&o.message.includes("requires database-backed verification storage"))return!0;throw o}))return await jA(t,n),t.context.internalAdapter.findUserById(r);try{let o=await t.context.internalAdapter.findUserById(r);if(!o||o.emailVerified)return o;let i=await t.context.internalAdapter.findAccounts(r);for(let s of i)await t.context.internalAdapter.deleteAccount(s.id);return await t.context.internalAdapter.deleteUserSessions(r),await t.context.internalAdapter.updateUser(r,{emailVerified:!0})}finally{await t.context.internalAdapter.deleteVerificationByIdentifier(n).catch(()=>{})}}var BA={string:e,number:_,boolean:E,date:ue};function Zp({fields:t,isClientSide:r}){let n=Object.keys(t).reduce((o,i)=>{let s=t[i];if(!s)return o;if(r&&s.input===!1)return o;let a;if(s.type==="json")a=Cs();else if(s.type==="string[]"||s.type==="number[]")a=A(s.type==="string[]"?e():_());else if(Array.isArray(s.type))a=N();else a=BA[s.type]();if(s?.required===!1)a=a.nullish();if(!r&&s?.returned===!1)return o;return{...o,[i]:a}},{});return l(n)}var $A=Kp({buildSyntheticUserOutput:()=>Nr,convertFromDB:()=>Qp,convertToDB:()=>Jp,createInternalAdapter:()=>gc,getSchema:()=>Ba,getSessionDefaultFields:()=>Kn,getWithHooks:()=>co,mergeSchema:()=>mc,parseAccountInput:()=>uc,parseAccountOutput:()=>Vn,parseAdditionalUserInput:()=>dc,parseAdditionalUserInputFromProviderProfile:()=>ur,parseInputData:()=>Bt,parseSessionInput:()=>Fn,parseSessionOutput:()=>we,parseUserInput:()=>dr,parseUserOutput:()=>se,revokeUnprovenAccountAccess:()=>Gp,toZodSchema:()=>Zp});Wp($A,ai);async function MA(t,r,n){let o=await Nt.get(),i=o?.query;if(!i)throw new U("BAD_REQUEST",{error_description:"missing oauth query",error:"invalid_request"});let s=new URLSearchParams(i),a=s.get("scope")?.split(" ")??[],c=Ln(r),d=Dn(s.get("claims"),c),u=s.get("client_id");if(!u)throw new U("BAD_REQUEST",{error_description:"client_id is required",error:"invalid_client"});let f=t.body.scope?.split(" ");if(f){if(!f.every((C)=>a?.includes(C)))throw new U("BAD_REQUEST",{error_description:"Scope not originally requested",error:"invalid_request"})}let p=t.body.claims,h=p!==void 0?Dn(p,c):d;if(p!==void 0&&!h.every((C)=>d.includes(C)))throw new U("BAD_REQUEST",{error_description:"Claim not originally requested",error:"invalid_request"});if(t.body.accept!==!0)return{redirect:!0,url:Ve(s.get("redirect_uri")??"","access_denied","User denied access",s.get("state")??void 0,Qn(t,r))};let m=await ee(t),w=ia(s.get("prompt")??"").has("login"),y=w&&ca(m?.session.createdAt,o?.signedQueryIssuedAt);if(w&&!y)return t?.headers?.set("accept","application/json"),t.query=nr(s),await n(t);let I=await sa(r,{user:m?.user,session:m?.session,scopes:f??a}),R=await aa(t,u,m?.user.id,I),b=Math.floor(Date.now()/1000),O=s.getAll("resource"),g={clientId:u,userId:m?.user.id,scopes:f??a,requestedUserInfoClaims:h,createdAt:new Date(b*1000),updatedAt:new Date(b*1000),resources:O.length?O:void 0,referenceId:I};if(R?.id?await t.context.adapter.update({model:"oauthConsent",where:[{field:"id",value:R.id}],update:{resources:g.resources,scopes:g.scopes,requestedUserInfoClaims:g.requestedUserInfoClaims,updatedAt:new Date(b*1000)}}):await t.context.adapter.create({model:"oauthConsent",data:{...g,scopes:g.scopes}}),f)s.set("scope",g.scopes.join(" "));if(p!==void 0){let C=bp(s.get("claims"),h);if(C)s.set("claims",JSON.stringify(C));else s.delete("claims")}t?.headers?.set("accept","application/json");let S=Ir(s,"consent");if(y)S=Ir(S,"login"),S=da(S);return t.query=nr(S),await n(t,{postLogin:o?.postLoginClearedForSession!==void 0&&o.postLoginClearedForSession===m?.session.id})}async function HA(t,r){if(t.body.selected===!0)return await VA(t,r);else if(t.body.created===!0)return await FA(t,r);else if(t.body.postLogin===!0)return await KA(t,r);else throw new U("BAD_REQUEST",{error_description:"Missing parameters",error:"invalid_request"})}async function VA(t,r){let n=(await Nt.get())?.query;if(!n)throw new U("BAD_REQUEST",{error_description:"missing oauth query",error:"invalid_request"});return t.headers?.set("accept","application/json"),t.query=nr(Ir(new URLSearchParams(n),"select_account")),await r(t)}async function FA(t,r){let n=(await Nt.get())?.query;if(!n)throw new U("BAD_REQUEST",{error_description:"missing oauth query",error:"invalid_request"});let o=new URLSearchParams(n);return t.headers?.set("accept","application/json"),t.query=nr(Ir(o,"create")),await r(t)}async function KA(t,r){let n=await Nt.get(),o=n?.query;if(!o)throw new U("BAD_REQUEST",{error_description:"missing oauth query",error:"invalid_request"});let i=new URLSearchParams(o);t.headers?.set("accept","application/json"),t.query=nr(i);let s=await ee(t);return await r(t,{postLogin:n?.postLoginClearedForSession!==void 0&&n.postLoginClearedForSession===s?.session.id,isPostLoginContinuation:!0})}var WA="http://schemas.openid.net/event/backchannel-logout",JA="logout+jwt",QA=120,GA=5000;async function ZA(t,r,n,o){return Wi(t,{options:r,payload:{...o,events:{[WA]:{}}},header:{typ:JA},resolvedKey:n??void 0})}async function YA(t,r,n){let{sessionId:o,userId:i}=n;if(!i)return null;let s=t.context.logger;try{let a=await X(t.context.adapter),c=[{field:"sessionId",value:o}],[d,u]=await Promise.all([a.findMany({model:"oauthAccessToken",where:c}),a.findMany({model:"oauthRefreshToken",where:c})]),f=new Set;for(let y of d)f.add(y.clientId);for(let y of u)f.add(y.clientId);if(f.size===0)return null;let p=await a.findMany({model:"oauthClient",where:[{field:"clientId",operator:"in",value:Array.from(f)}]}),h=d.filter((y)=>!y.revoked).map((y)=>y.id),m=u.filter((y)=>!y.revoked&&!y.scopes?.includes("offline_access")).map((y)=>y.id),w=r.disableJwtPlugin?[]:p.filter((y)=>Boolean(y.backchannelLogoutUri)&&!y.disabled);return{accessTokenIds:h,refreshTokenIds:m,sessionId:o,targets:(await Promise.all(w.map(async(y)=>{try{return{client:y,sub:await Tr(i,y,r)}}catch(I){return s.warn(`back-channel logout: unable to resolve subject for client ${y.clientId}`,I),null}}))).filter((y)=>y!==null)}}catch(a){return s.error("back-channel logout planning failed",a),null}}async function XA(t,r){let n=new Date,o=await X(t.context.adapter),i=await Promise.allSettled([r.accessTokenIds.length>0?o.updateMany({model:"oauthAccessToken",where:[{field:"id",operator:"in",value:r.accessTokenIds}],update:{revoked:n}}):Promise.resolve(),r.refreshTokenIds.length>0?o.updateMany({model:"oauthRefreshToken",where:[{field:"id",operator:"in",value:r.refreshTokenIds}],update:{revoked:n}}):Promise.resolve()]);for(let s of i)if(s.status==="rejected")t.context.logger.error("back-channel logout: token revocation update failed",s.reason);if(r.targets.length>0)await ek(t,r)}async function ek(t,r){let n=t.context.logger,o=Oe(t.context)?.options,i=o?.jwt?.issuer??t.context.baseURL,s=Math.floor(Date.now()/1000),a=s+QA,c=o?.jwt?.sign?null:await Ki(t,o);await Promise.allSettled(r.targets.map(async({client:d,sub:u})=>{try{let f=_e(32,"a-z","A-Z","0-9"),p=await ZA(t,o,c,{iss:i,aud:d.clientId,sub:u,sid:r.sessionId,iat:s,exp:a,jti:f}),h=await fetch(d.backchannelLogoutUri,{method:"POST",headers:{"Content-Type":"application/x-www-form-urlencoded",Accept:"application/json"},body:new URLSearchParams({logout_token:p}),signal:AbortSignal.timeout(GA),redirect:"error"});if(h.status!==200&&h.status!==204)n.warn(`back-channel logout to client ${d.clientId} returned ${h.status}`)}catch(f){n.warn(`back-channel logout to client ${d.clientId} failed`,f)}}))}var Yp=300,tk=".oauth_logout_confirmation";function oi(t){return t.replace(/[&<>"']/g,(r)=>{switch(r){case"&":return"&amp;";case"<":return"&lt;";case">":return"&gt;";case'"':return"&quot;";case"'":return"&#39;";default:return r}})}function zt(t){let r=t.request?.headers??t.headers;if(!r||Ea(r))return!1;let n=r.get("accept")??"";return r.get("sec-fetch-mode")==="navigate"||n.includes("text/html")||n.includes("application/xhtml+xml")}function Ca(t,r,n=200){return new Response(`<!doctype html><html><head><meta charset="utf-8"><title>${oi(t)}</title></head><body>${r}</body></html>`,{status:n,headers:{"cache-control":"no-store","content-security-policy":"default-src 'none'; form-action 'self'; base-uri 'none'; frame-ancestors 'none'","content-type":"text/html; charset=utf-8",pragma:"no-cache","x-content-type-options":"nosniff"}})}function ph(t){return`${t.context.baseURL.replace(/\/$/,"")}/oauth2/end-session/confirm`}function rk(t){try{return new URL(ph(t)).pathname}catch{return"/oauth2/end-session/confirm"}}function Xp(t){return Ca("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="${oi(ph(t))}"><button type="submit" name="action" value="confirm">Confirm logout</button></form></main>`)}function Ta(t){return Ca("Logged out",`<main><p data-oidc-logout-state="logged-out">${t?`Logged out. ${oi(t)}`:"Logged out."}</p></main>`)}function nk(t,r){return Ca("Logout error",`<main><h1>Logout error</h1><p data-oidc-logout-state="error">${oi(t)}</p></main>`,r)}function Fe(t,r,n,o){if(zt(t))return nk(o,r==="BAD_REQUEST"?400:r==="UNAUTHORIZED"?401:500);throw new ce(r,{error:n,error_description:o})}function Oa(t){return`${t.context.authCookies.sessionToken.name}${tk}`}function hh(t,r){return{...t.context.authCookies.sessionToken.attributes,httpOnly:!0,maxAge:r,path:rk(t),sameSite:"lax"}}async function eh(t,r,n={}){let o={...r?{sessionId:r}:{},...n,expiresAt:Date.now()+Yp*1000};await t.setSignedCookie(Oa(t),JSON.stringify(o),t.context.secret,hh(t,Yp))}async function ok(t){let r=await t.getSignedCookie(Oa(t),t.context.secret);if(typeof r!=="string")return null;try{let n=JSON.parse(r);if(typeof n!=="object"||n===null)return null;let o=n;if(o.sessionId!==void 0&&(typeof o.sessionId!=="string"||o.sessionId.length===0)||o.clientId!==void 0&&(typeof o.clientId!=="string"||o.clientId.length===0)||o.postLogoutRedirectUri!==void 0&&(typeof o.postLogoutRedirectUri!=="string"||o.postLogoutRedirectUri.length===0)||o.state!==void 0&&typeof o.state!=="string"||o.redirectInvalid!==void 0&&typeof o.redirectInvalid!=="boolean"||o.postLogoutRedirectUri!==void 0&&o.clientId===void 0||typeof o.expiresAt!=="number"||!Number.isFinite(o.expiresAt))return null;return{...typeof o.sessionId==="string"?{sessionId:o.sessionId}:{},...typeof o.clientId==="string"?{clientId:o.clientId}:{},...typeof o.postLogoutRedirectUri==="string"?{postLogoutRedirectUri:o.postLogoutRedirectUri}:{},...typeof o.state==="string"?{state:o.state}:{},...typeof o.redirectInvalid==="boolean"?{redirectInvalid:o.redirectInvalid}:{},expiresAt:o.expiresAt}}catch{return null}}function Ia(t){t.setCookie(Oa(t),"",hh(t,0))}async function mh(t){let r=await t.getSignedCookie(t.context.authCookies.sessionToken.name,t.context.secret);if(typeof r!=="string"||r.length===0)return null;try{let n=await t.context.internalAdapter.findSession(r);return n?{session:n.session}:null}catch(n){throw t.context.logger.error("Failed to read the current logout session",n),new ce("INTERNAL_SERVER_ERROR",{error:"server_error",error_description:"Unable to read the current session"})}}async function ik(t,r){try{return await t.context.adapter.findOne({model:"session",where:[{field:"id",value:r}]})}catch(n){throw t.context.logger.error("Failed to read the hinted logout session",n),new ce("INTERNAL_SERVER_ERROR",{error:"server_error",error_description:"Unable to read the hinted session"})}}async function gh(t,r){if(typeof r.token!=="string"||r.token.length===0)throw new ce("INTERNAL_SERVER_ERROR",{error:"server_error",error_description:"Unable to complete logout"});try{await t.context.internalAdapter.deleteSession(r.token)}catch(n){throw t.context.logger.error("Failed to delete the logout session",n),new ce("INTERNAL_SERVER_ERROR",{error:"server_error",error_description:"Unable to complete logout"})}}async function ri(t,r,n){try{return await ke(t,r,n)}catch(o){throw t.context.logger.error("Failed to resolve the logout client",o),new ce("INTERNAL_SERVER_ERROR",{error:"server_error",error_description:"Unable to resolve the logout client"})}}function wh(t){return(Array.isArray(t)?t:[t]).filter((r)=>typeof r==="string")}function sk(t){if(typeof t.aud==="string"&&t.aud.length>0)return t.aud;if(typeof t.azp==="string"&&t.azp.length>0)return t.azp;let r=wh(t.aud);return r.length===1?r[0]:null}async function ak(t,r,n,o){if(o)return ri(t,r,o);let i;try{i=Xr(n)}catch{return null}let s=sk(i);return s?ri(t,r,s):null}async function ck(t,r,n,o){try{let i;if(r.disableJwtPlugin){if(!o.clientSecret)return null;let s=await Sr(t,r.storeClientSecret,o.clientSecret),{payload:a}=await Hu(n,new TextEncoder().encode(s));i=JSON.parse(new TextDecoder().decode(a))}else{let s=Oe(t.context).options,{payload:a}=await Hu(n,Qo(await Ar(n,{jwksFetch:s?.jwks?.remoteUrl??`${t.context.baseURL}${s?.jwks?.jwksPath??"/jwks"}`})));i=JSON.parse(new TextDecoder().decode(a))}if(i.iss!==Qn(t,r))return null;if(!wh(i.aud).includes(o.clientId))return null;if(typeof i.sid!=="string"||i.sid.length===0||typeof i.sub!=="string"||i.sub.length===0)return null;return i}catch{return null}}function Da(t,r,n){if(!r)return{invalid:!1};if(!t.postLogoutRedirectUris?.includes(r))return{invalid:!0};if(!n)return{uri:r,invalid:!1};try{let o=new URL(r);return o.searchParams.set("state",n),{uri:o.toString(),invalid:!1}}catch{return{invalid:!0}}}function va(t,r){if(!r.post_logout_redirect_uri)return{};if(Da(t,r.post_logout_redirect_uri,r.state).invalid)return{redirectInvalid:!0};return{clientId:t.clientId,postLogoutRedirectUri:r.post_logout_redirect_uri,...r.state!==void 0?{state:r.state}:{}}}async function dk(t,r,n){if(n.redirectInvalid)return{invalid:!0};if(!n.clientId||!n.postLogoutRedirectUri)return{invalid:!1};let o=await ri(t,r,n.clientId);if(!o||o.disabled||!o.enableEndSession)return{invalid:!0};return Da(o,n.postLogoutRedirectUri,n.state)}async function ei(t,r,n={}){if(!r){if(zt(t))return await eh(t,void 0,n),Xp(t);return Fe(t,"BAD_REQUEST","invalid_request","No active session is available for logout")}if(!zt(t))return Fe(t,"BAD_REQUEST","invalid_request","User confirmation is required to complete logout");return await eh(t,r.session.id,n),Xp(t)}async function uk(t,r){let n=await ok(t),o=await mh(t);if(!n||n.expiresAt<=Date.now())return Fe(t,"BAD_REQUEST","invalid_request","The logout confirmation is invalid or expired");let i=await dk(t,r,n);if(!o){if(Ia(t),i.uri)return fe(t,i.uri);return zt(t)?Ta(i.invalid?"The requested post-logout redirect was not registered.":void 0):Fe(t,"BAD_REQUEST","invalid_request","No active session is available for logout")}if(n.sessionId&&n.sessionId!==o.session.id)return Fe(t,"BAD_REQUEST","invalid_request","The logout confirmation is invalid or expired");if(await gh(t,o.session),Le(t),Ia(t),i.uri)return fe(t,i.uri);return zt(t)?Ta(i.invalid?"The requested post-logout redirect was not registered.":void 0):null}async function lk(t,r){let n=t.query??{},o=t.body??{},i={...n,...o},s=await mh(t);if(i.id_token_hint===void 0){let m={};if(i.client_id){let w=await ri(t,r,i.client_id);if(!w)return Fe(t,"BAD_REQUEST","invalid_client","The logout client does not exist");if(w.disabled)return Fe(t,"BAD_REQUEST","invalid_client","The logout client is disabled");if(!w.enableEndSession)return Fe(t,"UNAUTHORIZED","invalid_client","The client is not allowed to initiate logout");m=va(w,i)}return ei(t,s,m)}let a=await ak(t,r,i.id_token_hint,i.client_id);if(!a){if(s&&zt(t))return ei(t,s);return Fe(t,"BAD_REQUEST","invalid_client","The logout client does not exist")}if(a.disabled)return Fe(t,"BAD_REQUEST","invalid_client","The logout client is disabled");if(!a.enableEndSession)return Fe(t,"UNAUTHORIZED","invalid_client","The client is not allowed to initiate logout");let c=await ck(t,r,i.id_token_hint,a);if(!c){if(s&&zt(t))return ei(t,s,i.client_id?va(a,i):{});return Fe(t,"UNAUTHORIZED","invalid_token","The id_token_hint is invalid")}let d=c.sid,u=await ik(t,d),f=s?.session.id===d;if(s&&!f)return ei(t,s,va(a,i));let p=Da(a,i.post_logout_redirect_uri,i.state),h=u??(f?s?.session:null);if(h)await gh(t,h);if(f)Le(t);if(Ia(t),p.uri)return fe(t,p.uri);return zt(t)?Ta(p.invalid?"The requested post-logout redirect was not registered.":void 0):null}async function fk(t,r){return uk(t,r)}function zy(t,r,n){let o=t.context.baseURL,i=!n?.jwt_disabled;return{scopes_supported:n?.scopes_supported,issuer:Wh(r?.jwt?.issuer??o),authorization_endpoint:`${o}/oauth2/authorize`,token_endpoint:`${o}/oauth2/token`,jwks_uri:n?.jwt_disabled?void 0:r?.jwks?.remoteUrl??`${o}${r?.jwks?.jwksPath??"/jwks"}`,registration_endpoint:n?.dynamic_client_registration_supported?`${o}/oauth2/register`:void 0,introspection_endpoint:`${o}/oauth2/introspect`,revocation_endpoint:`${o}/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:[...Kt],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:[...Kt],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:[...Kt],code_challenge_methods_supported:["S256"],authorization_response_iss_parameter_supported:!0,dpop_signing_alg_values_supported:n?.dpop_signing_alg_values_supported??[...za],backchannel_logout_supported:i,backchannel_logout_session_supported:i}}function yh(t,r){let n=r.disableJwtPlugin?void 0:Oe(t.context).options,o=Rn(r),i=r.allowUnauthenticatedClientRegistration||o.length>0;return{jwtPluginOptions:n,clientDiscoveries:o,authMetadata:zy(t,n,{scopes_supported:r.advertisedMetadata?.scopes_supported??r.scopes,dynamic_client_registration_supported:r.allowDynamicClientRegistration,public_client_supported:i,grant_types_supported:Rr(r),token_endpoint_auth_methods_supported:Po(r,{includeNone:i}),endpoint_auth_methods_supported:Po(r),jwt_disabled:r.disableJwtPlugin,dpop_signing_alg_values_supported:r.dpop?.signingAlgorithms})}}function Wg(t,r){let{clientDiscoveries:n,authMetadata:o}=yh(t,r);return Zs(t,r,"oauth-authorization-server",{...oa(n),...o})}function mf(t,r){let n=t.context.baseURL,{jwtPluginOptions:o,clientDiscoveries:i,authMetadata:s}=yh(t,r),a={...s,claims_supported:Ln(r),claims_parameter_supported:!0,userinfo_endpoint:`${n}/oauth2/userinfo`,subject_types_supported:r.pairwiseSecret?["public","pairwise"]:["public"],acr_values_supported:["0"],id_token_signing_alg_values_supported:(()=>{if(r.disableJwtPlugin)return["HS256"];let c=o?.jwks?.keyPairConfig?.alg??"EdDSA",d=o?.jwks?.keyPairConfigs?.map((u)=>u.alg)??[];return Array.from(new Set([c,...d]))})(),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 Zs(t,r,"openid-configuration",{...oa(i),...a})}var pk="public, max-age=15, stale-while-revalidate=15, stale-if-error=86400";function gl(t,r){let n=new Headers(r);if(!n.has("Cache-Control"))n.set("Cache-Control",pk);return n.set("Content-Type","application/json"),new Response(JSON.stringify(t),{status:200,headers:n})}var nP=(t,r)=>async(n)=>gl(await t.api.getOAuthServerConfig({request:n,asResponse:!1}),r?.headers),oP=(t,r)=>async(n)=>gl(await t.api.getOpenIdConfig({request:n,asResponse:!1}),r?.headers);function Pt(t,r,n){let{redirectOnError:o,onValidationError:i,errorCodesByField:s,defaultError:a="invalid_request",...c}=r;if(!o)return Pe(t,{...c,onValidationError:async(m)=>{if(i)await i(m);throw new ce("BAD_REQUEST",{...Ua(m.issues,s,a)})}},n);let d=o,{body:u,query:f,...p}=c;async function h(m,w,y){if(!y)return{ok:!0};let I=await y.safeParseAsync(m[w]??{});if(I.success)return m[w]=I.data,{ok:!0};if(i)await i({message:I.error.message,issues:I.error.issues});return{ok:!1,response:d({...Ua(I.error.issues,s,a),ctx:m})}}return Pe(t,p,async(m)=>{let w=await h(m,"body",u);if(!w.ok)return w.response;let y=await h(m,"query",f);if(!y.ok)return y.response;return n(m)})}function Ua(t,r,n="invalid_request"){let o=t[0];if(!o)return{error:n,error_description:"Invalid request."};let i=o.path?.[0],s=typeof i==="string"?i:void 0,a=s?r?.[s]:void 0,c=o.path?.length?sA(o.path):"";return{error:hk(o,a,n),error_description:gk(o,c)}}function hk(t,r,n){if(typeof r==="string")return r;if(mk(t))return r?.missing??n;if(t.code==="invalid_value")return r?.invalid??n;return n}function mk(t){return t.code==="invalid_type"&&t.message.endsWith("received undefined")}function gk(t,r){if(!r)return t.message;if(t.code==="invalid_type"){if(t.message.endsWith("received undefined"))return`${r} is required`;if(t.message.endsWith("received array"))return`${r} must not appear more than once`;return`${r} must be a ${t.expected??"valid value"}`}if(t.code==="invalid_value"){let n=t.values;if(Array.isArray(n)&&n.length>0)return`${r} must be one of: ${n.join(", ")}`}return`${r}: ${t.message}`}var wk=(t)=>Cn(async(r)=>{if(!t.allowPublicClientPrelogin)throw new U("BAD_REQUEST");let n=r.body.oauth_query;if(!await ra(n,r.context.secret))throw new U("UNAUTHORIZED",{error:"invalid_signature"})}),_h={"P-256":"ES256","P-384":"ES384","P-521":"ES512"},yk=["Ed25519"],_k=["d","p","q","dp","dq","qi","oth"];function th(t){return typeof t==="object"&&t!==null&&!Array.isArray(t)}function xn(t,r){return typeof t[r]==="string"&&t[r].length>0}function Ah(t){return typeof t==="string"&&Object.prototype.hasOwnProperty.call(_h,t)}function kh(t){return yk.some((r)=>r===t)}function Ak(t){switch(t.kty){case"RSA":return xn(t,"n")&&xn(t,"e");case"EC":return Ah(t.crv)&&xn(t,"x")&&xn(t,"y");case"OKP":return kh(t.crv)&&xn(t,"x");default:return!1}}function kk(t){if(t.alg===void 0)return!0;if(typeof t.alg!=="string"||!Kt.some((r)=>r===t.alg))return!1;switch(t.kty){case"RSA":return t.alg.startsWith("RS")||t.alg.startsWith("PS");case"EC":return Ah(t.crv)&&_h[t.crv]===t.alg;case"OKP":return kh(t.crv)&&t.alg==="EdDSA";default:return!1}}function Eh(t){let r=th(t)&&Array.isArray(t.keys)?t.keys:void 0;if(!r?.length)return{valid:!1,error:"jwks must be an RFC 7517 JWK Set object with a non-empty keys array"};for(let n of r){if(!th(n))return{valid:!1,error:"jwks keys must be supported public JWKs with required key parameters"};if(n.kty==="oct"||"k"in n||_k.some((o)=>(o in n)))return{valid:!1,error:"jwks must contain only public asymmetric keys"};if(!Ak(n))return{valid:!1,error:"jwks keys must be supported public JWKs with required key parameters"};if(!kk(n))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:r}}}function bh(t){let r=Eh(t);if(!r.valid)throw new U("BAD_REQUEST",{error:"invalid_client_metadata",error_description:r.error})}var Ek=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,tokenEndpointAuthMethod:!0,grantTypes:!0,responseTypes:!0,applicationType:!0,jwks:!0,jwksUri:!0,requirePKCE:!0,dpopBoundAccessTokens:!0,skipConsent:!0,enableEndSession:!0,subjectType:!0,referenceId:!0,metadata:!0})),bk=["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","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"],vk=new Set([...Ek,...bk,"public","type","resources","client_credentials_scopes"]);function vh(t){if(!t)return;return Object.fromEntries(Object.entries(t).filter(([r])=>!vk.has(r)))}async function at(t,r,n,o,i){if(!r)throw new U("UNAUTHORIZED");if(!t.headers)throw new U("BAD_REQUEST");if(o==="configure-client-credentials-scopes"&&!n.clientPrivileges)throw new U("UNAUTHORIZED");if(n.clientPrivileges&&!await n.clientPrivileges({headers:t.headers,action:o,session:r.session,user:r.user,clientId:i}))throw new U("UNAUTHORIZED")}async function qt(t,r,n,o,i){if(!r)throw new U("UNAUTHORIZED");if(!t.headers)throw new U("BAD_REQUEST");if(!n.resourcePrivileges)return;if(!await n.resourcePrivileges({headers:t.headers,action:o,session:r.session,user:r.user,resourceId:i}))throw new U("UNAUTHORIZED")}var sP=Co({consumeClientAssertion:()=>Jg,isPrivateHostname:()=>ni,verifyClientAssertion:()=>Uh}),rh=new WeakMap,nh=300000,Sk=500,Rk=5000,oh=65536,Tk=/^application\/(?:[-\w.]+\+)?json\s*(?:;|$)/i;function Sh(t,r,n,o){if(t.set(r,{jwks:n,fetchedAt:o}),t.size>Sk){let i=t.keys().next().value;if(i!==void 0)t.delete(i)}}function Rh(t){let r=rh.get(t);if(r)return r;let n=new Map;return rh.set(t,n),n}function Th(t){return`${t.clientDiscoveryId??"managed"}:${t.jwksUri??""}`}var ih=[...Kt];function ni(t){return!ld(t)}function Ik(t,r,n){let o=new URL(r);if(o.protocol!=="https:")throw new ce("BAD_REQUEST",{error_description:"jwks_uri must use HTTPS",error:"invalid_client"});if(o.username||o.password)throw new ce("BAD_REQUEST",{error_description:"jwks_uri must not contain credentials",error:"invalid_client"});if(r.includes("#"))throw new ce("BAD_REQUEST",{error_description:"jwks_uri must not include a fragment component",error:"invalid_client"});if(ni(o.hostname))throw new ce("BAD_REQUEST",{error_description:"jwks_uri must not point to a private or reserved address",error:"invalid_client"});if(n&&o.origin===n)return;if(!t.context.isTrustedOrigin(o.href))throw new ce("BAD_REQUEST",{error_description:"client jwks_uri is not trusted",error:"invalid_client"})}function Uk(t){try{let r=new URL(t);if(r.protocol!=="https:"&&r.protocol!=="http:")return;return r.origin}catch{return}}async function Ck(t){let r=t.headers.get("content-length");if(r!==null&&Number.isFinite(Number(r))&&Number(r)>oh)throw await t.body?.cancel(),Error("JWKS response exceeds 64 KiB");if(!t.body)return"";let n=t.body.getReader(),o=[],i=0;while(!0){let{done:c,value:d}=await n.read();if(c)break;if(i+=d.byteLength,i>oh)throw await n.cancel(),Error("JWKS response exceeds 64 KiB");o.push(d)}let s=new Uint8Array(i),a=0;for(let c of o)s.set(c,a),a+=c.byteLength;return new TextDecoder().decode(s)}async function Ih(t,r=globalThis.fetch){let n=new AbortController,o=setTimeout(()=>n.abort(),Rk);try{let i=await r(t,{signal:n.signal,headers:{accept:"application/json"},redirect:"error"});if(i.redirected)throw Error("JWKS fetch redirected");if(i.status!==200)throw Error(`JWKS fetch returned ${i.status}`);let s=i.headers.get("content-type");if(!s||!Tk.test(s))throw Error("JWKS response must use a JSON media type");let a=await Ck(i),c;try{c=JSON.parse(a)}catch{return{valid:!1}}let d=Eh(c);if(!d.valid)return{valid:!1};return{valid:!0,jwks:d.jwks}}finally{clearTimeout(o)}}function sh(){return new ce("BAD_REQUEST",{error_description:"failed to fetch client JWKS",error:"invalid_client"})}async function Ok(t,r,n){if(n.jwks)return JSON.parse(n.jwks);if(!n.jwksUri)throw new ce("BAD_REQUEST",{error_description:"client has no JWKS configured",error:"invalid_client"});let o=n.clientDiscoveryId?Rn(r).find((u)=>u.id===n.clientDiscoveryId):void 0;if(n.clientDiscoveryId&&!o?.fetchClientMetadataResource)throw new ce("BAD_REQUEST",{error_description:"client discovery does not provide a metadata resource transport",error:"invalid_client"});Ik(t,n.jwksUri,n.clientDiscoveryId?Uk(n.clientId):void 0);let i=Date.now(),s=Th(n),a=Rh(r),c=a.get(s);if(c&&i-c.fetchedAt<nh)return c.jwks;let d;try{d=await Ih(n.jwksUri,o?.fetchClientMetadataResource)}catch{let u=nh*2;if(c&&i-c.fetchedAt<u)return c.jwks;throw sh()}if(!d.valid)throw sh();return Sh(a,s,d.jwks,i),d.jwks}async function Dk(t,r){if(!r.jwksUri)return null;let n=r.clientDiscoveryId?Rn(t).find((o)=>o.id===r.clientDiscoveryId):void 0;if(r.clientDiscoveryId&&!n?.fetchClientMetadataResource)return null;try{let o=await Ih(r.jwksUri,n?.fetchClientMetadataResource);if(!o.valid)return null;return Sh(Rh(t),Th(r),o.jwks,Date.now()),o.jwks}catch{return null}}async function Jg(t,r,n){let{namespace:o,payload:i,expectedAudience:s}=n;if(!(Array.isArray(i.aud)?i.aud:i.aud!=null?[i.aud]:[]).includes(s))throw new ce("BAD_REQUEST",{error_description:"client assertion aud does not match the endpoint",error:"invalid_client"});let a=r.assertionMaxLifetime??300,c=Math.floor(Date.now()/1000);if(typeof i.exp!=="number")throw new ce("BAD_REQUEST",{error_description:"client assertion must include exp claim",error:"invalid_client"});if(i.exp<=c)throw new ce("BAD_REQUEST",{error_description:"client assertion has expired",error:"invalid_client"});if(i.exp-c>a)throw new ce("BAD_REQUEST",{error_description:`client assertion exp is too far in the future (max ${a}s)`,error:"invalid_client"});if(typeof i.iat==="number"&&c-i.iat>a)throw new ce("BAD_REQUEST",{error_description:`client assertion iat is too far in the past (max ${a}s)`,error:"invalid_client"});if(typeof i.jti!=="string"||i.jti.length===0)throw new ce("BAD_REQUEST",{error_description:"client assertion must include jti claim",error:"invalid_client"});let d=await cs("SHA-256").digest(new TextEncoder().encode(`${o}:${i.jti}`)),u=If(new Uint8Array(d).slice(0,24),t.context.options);try{await t.context.adapter.create({model:"oauthClientAssertion",data:{id:u,expiresAt:new Date(i.exp*1000)},forceAllowId:!0})}catch(f){let p=!1;try{p=Boolean(await t.context.adapter.findOne({model:"oauthClientAssertion",where:[{field:"id",value:u}]}))}catch{}if(p)throw new ce("BAD_REQUEST",{error_description:"client assertion jti has already been used",error:"invalid_client"});throw f}}async function Uh(t,r,n,o,i,s,a){if(o!==Wt)throw new ce("BAD_REQUEST",{error_description:"unsupported client_assertion_type",error:"invalid_client"});let c;try{c=so(n)}catch{throw new ce("BAD_REQUEST",{error_description:"malformed client assertion: invalid JWT header",error:"invalid_client"})}if(!c.alg||!ih.includes(c.alg))throw new ce("BAD_REQUEST",{error_description:`unsupported assertion signing algorithm: ${c.alg}`,error:"invalid_client"});let d;try{d=Xr(n)}catch{throw new ce("BAD_REQUEST",{error_description:"malformed client assertion: invalid JWT payload",error:"invalid_client"})}let u=d.sub??d.iss;if(!u)throw new ce("BAD_REQUEST",{error_description:"client assertion must contain sub or iss claim identifying the client",error:"invalid_client"});if(i&&i!==u)throw new ce("BAD_REQUEST",{error_description:"client_id in body does not match assertion sub/iss",error:"invalid_client"});let f=await ke(t,r,u);if(!f)throw new ce("BAD_REQUEST",{error_description:"client not found",error:"invalid_client"});if(f.disabled)throw new ce("BAD_REQUEST",{error_description:"client is disabled",error:"invalid_client"});if(f.tokenEndpointAuthMethod!=="private_key_jwt")throw new ce("BAD_REQUEST",{error_description:"client is not registered for private_key_jwt authentication",error:"invalid_client"});a?.assertClient?.(f);let p=await Ok(t,r,f),h=s??`${t.context.baseURL}/oauth2/token`,m=Qn(t,r),w=a?.endpointAudienceOnly?[h]:[...new Set([h,m])],y={issuer:u,subject:u,audience:w,algorithms:ih},I;try{({payload:I}=await Hr(n,Qo(p),y))}catch(b){if(b instanceof Error&&/no matching key|no applicable key/i.test(b.message)){let O=await Dk(r,f);if(O)try{({payload:I}=await Hr(n,Qo(O),y))}catch{throw new ce("UNAUTHORIZED",{error_description:"client assertion signature verification failed",error:"invalid_client"})}else throw new ce("UNAUTHORIZED",{error_description:"client assertion signature verification failed",error:"invalid_client"})}else throw new ce("UNAUTHORIZED",{error_description:"client assertion signature verification failed",error:"invalid_client"})}let R=(Array.isArray(I.aud)?I.aud:[I.aud]).find((b)=>typeof b==="string"&&w.includes(b));return await Jg(t,r,{namespace:`private_key_jwt:${u}`,payload:I,expectedAudience:R}),{clientId:u,client:f}}function Sa(t,r,n){return new ce(t,{error:r,error_description:n},{"WWW-Authenticate":`Bearer error="${r}"`,...Zr})}async function Lk(t,r,n){let o=t.headers,i;try{i=sp(o?.get("authorization"))}catch{throw Sa("BAD_REQUEST","invalid_request","Malformed initial access token Authorization header")}if(!i||!o)return;if(!r.validateInitialAccessToken)throw Sa("UNAUTHORIZED","invalid_token","Invalid initial access token");let s;try{s=await r.validateInitialAccessToken({initialAccessToken:i,headers:o,clientMetadata:n})}catch(a){if(a instanceof ce)throw a;throw new ce("INTERNAL_SERVER_ERROR",{error:"server_error",error_description:"Initial access token validation failed"})}if(!s)throw Sa("UNAUTHORIZED","invalid_token","Invalid initial access token");return s}var Pk=["authorization_code"];function Ch(t){return[...new Set([...t.clientRegistrationDefaultScopes??t.scopes??[],...t.clientRegistrationAllowedScopes??[]])]}function Oh(t){let r=t.grant_types??[...Pk];if(r.length>0)return r;throw new U("BAD_REQUEST",{error:"invalid_client_metadata",error_description:"grant_types must contain at least one grant type"})}function xk(t,r){if(t.response_types)return t.response_types;return r.includes("authorization_code")?["code"]:void 0}function Dh(t,r){let n=new Set(Rr(t)),o=r.filter((i)=>n.has(i));if(o.length===0)throw new U("BAD_REQUEST",{error:"invalid_client_metadata",error_description:`no mutually supported grant_type among ${r.join(", ")}`});return o}function Lh(t,r="web"){let n=Oh(t);return{...t,token_endpoint_auth_method:t.token_endpoint_auth_method??"client_secret_basic",application_type:t.application_type??(r===null?void 0:r),grant_types:n,response_types:xk(t,n)}}function zk(t){let r=new URL(t);return r.protocol!=="http:"&&r.protocol!=="https:"&&r.host!==""}function Nk(t){try{let r=new URL(t).protocol;return r!=="http:"&&r!=="https:"}catch{return!1}}function Ph(t,r){let n=t.clientRegistrationDefaultApplicationType??"web";if(n!=="infer")return n;return(r.redirect_uris??[]).some((o)=>Nk(o)||xh(o))?"native":"web"}function or(t){throw new U("BAD_REQUEST",{error:"invalid_redirect_uri",error_description:t})}function qk(t){let r=/^http:\/\/([^/?#]*)/i.exec(t)?.[1];if(!r)return null;let n=r.slice(r.lastIndexOf("@")+1);if(n.startsWith("[")){let o=n.indexOf("]");return o<0?null:n.slice(0,o+1).toLowerCase()}return(n.split(":")[0]??"").toLowerCase()}function xh(t){let r=qk(t);return r==="localhost"||r==="127.0.0.1"||r==="[::1]"}function jk(t,r){let n=new Set([...t.clientRegistrationDefaultResources??[],...t.clientRegistrationAllowedResources??[]]);for(let o of r)if(!n.has(o))throw new U("BAD_REQUEST",{error:"invalid_target",error_description:`requested resource ${o} is not allowed for client registration`})}async function Bk(t,r,n){let o=r.clientRegistrationDefaultResources??[],i=[...new Set([...o,...n])];for(let s of i){let a=await Wo(t,r,s);if(!a)throw new U("BAD_REQUEST",{error:"invalid_target",error_description:`requested resource ${s} does not exist`});if(a.disabled)throw new U("BAD_REQUEST",{error:"invalid_target",error_description:`requested resource ${s} is disabled`})}return i}function $k(t,r){let n;try{n=new URL(t)}catch{or(`redirect URI must be an absolute URI: ${t}`)}if(t.includes("#")||n.username.length>0||n.password.length>0)or(`redirect URI must not include credentials or a fragment: ${t}`);let o=n.protocol==="http:",i=n.protocol==="https:";if(/^localhost\.+$/i.test(n.hostname))or(`redirect URI localhost must not include trailing dots: ${t}`);let s=Fi(n.hostname)||n.hostname==="localhost";if(r==="web"){if(!i||s)or(`web clients require https redirect URIs on non-loopback hosts: ${t}`);return}if(i){if(s)or(`native clients must not use https loopback redirect URIs: ${t}`);return}if(o){if(!xh(t))or(`native clients may use http only on the exact loopback hosts localhost, 127.0.0.1, or [::1]: ${t}`);return}if(!cp(n))or(`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: ${t}`)}async function Mk(t,r){let n=t.body;if(!r.allowDynamicClientRegistration)throw new U("FORBIDDEN",{error:"access_denied",error_description:"Client registration is disabled"});let o=await ee(t),i=o?void 0:await Lk(t,r,n),s=Boolean(i);if(!(o||s||r.allowUnauthenticatedClientRegistration))throw new U("UNAUTHORIZED",{error_description:"Authentication required for client registration"},{"WWW-Authenticate":"Bearer",...Zr});let a=n.grant_types?.length?Dh(r,n.grant_types):n.grant_types,c=n.grant_types?.includes("authorization_code")&&!a?.includes("authorization_code"),d={...n,grant_types:a,response_types:c?void 0:n.response_types};if(!o&&!s){if(d.grant_types?.includes("client_credentials"))throw new U("BAD_REQUEST",{error:"invalid_client_metadata",error_description:"client_credentials grant requires authenticated registration"})}let u=Array.isArray(n.resources)?n.resources.filter((h)=>typeof h==="string"&&h.length>0):[];if(o)await at(t,o,r,"create");let f=i?.referenceId??(o&&r.clientReference?await r.clientReference({user:o.user,session:o.session}):void 0),p=await jh(t,r,{metadata:d,registrationSource:"dynamic",userId:f?void 0:o?.session.userId,referenceId:f,requestedResources:u});return t.setStatus(201),t.json(p)}async function zh(t,r,n){let o=n?.registrationSource==="clientMetadataDocument",i=Lh(t,o?null:n?.registrationSource==="dynamic"?Ph(r,t):"web"),s=i.token_endpoint_auth_method??"client_secret_basic";if(!new Set(Po(r,{includeNone:!0})).has(s))throw new U("BAD_REQUEST",{error:"invalid_client_metadata",error_description:`unsupported token_endpoint_auth_method ${s}`});if(i.dpop_bound_access_tokens!==void 0&&typeof i.dpop_bound_access_tokens!=="boolean")throw new U("BAD_REQUEST",{error:"invalid_client_metadata",error_description:"dpop_bound_access_tokens must be a boolean"});let a=i.grant_types??[],{response_types:c,application_type:d}=i;if(d!==void 0&&d!=="web"&&d!=="native")throw new U("BAD_REQUEST",{error:"invalid_client_metadata",error_description:"application_type must be web or native"});if(a.includes("authorization_code")&&(!i.redirect_uris||i.redirect_uris.length===0))throw new U("BAD_REQUEST",{error:"invalid_redirect_uri",error_description:"Redirect URIs are required for authorization_code and implicit grant types"});for(let h of i.redirect_uris??[])$k(h,d??(o?"native":"web"));if(o)Dh(r,a);else{let h=new Set(Rr(r));for(let m of a)if(!h.has(m))throw new U("BAD_REQUEST",{error:"invalid_client_metadata",error_description:`unsupported grant_type ${m}`})}if(a.includes("authorization_code")&&!c?.includes("code"))throw new U("BAD_REQUEST",{error:"invalid_client_metadata",error_description:"When 'authorization_code' grant type is used, 'code' response type must be included"});if(!a.includes("authorization_code")&&c?.includes("code"))throw new U("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 U("BAD_REQUEST",{error:"invalid_client_metadata",error_description:'subject_type must be "public" or "pairwise"'});if(i.subject_type==="pairwise"&&!r.pairwiseSecret)throw new U("BAD_REQUEST",{error:"invalid_client_metadata",error_description:"pairwise subject_type requires server pairwiseSecret configuration"});if(i.subject_type==="pairwise"&&i.redirect_uris?.some(zk))throw new U("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){if(new Set(i.redirect_uris.map((h)=>new URL(h).host)).size>1)throw new U("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 u=i?.scope?.split(" ").filter((h)=>h.length),f=n?.registrationSource==="dynamic"||n?.registrationSource==="clientMetadataDocument",p=f?Ch(r):r.scopes;if(p){let h=new Set(p);for(let m of u??[])if(!h?.has(m))throw new U("BAD_REQUEST",{error:"invalid_scope",error_description:`cannot request scope ${m}`})}if(f&&i.require_pkce===!1)throw new U("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 U("BAD_REQUEST",{error:"invalid_client_metadata",error_description:"jwks and jwks_uri are mutually exclusive"});if(i.jwks_uri)try{let h=new URL(i.jwks_uri);if(h.protocol!=="https:")throw new U("BAD_REQUEST",{error:"invalid_client_metadata",error_description:"jwks_uri must use HTTPS"});if(h.username||h.password)throw new U("BAD_REQUEST",{error:"invalid_client_metadata",error_description:"jwks_uri must not contain credentials"});if(i.jwks_uri.includes("#"))throw new U("BAD_REQUEST",{error:"invalid_client_metadata",error_description:"jwks_uri must not include a fragment component"});if(ni(h.hostname))throw new U("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(h.href)){let m=typeof i.client_id==="string"?i.client_id:void 0;if(!(o&&m!==void 0&&URL.canParse(m)&&new URL(m).origin===h.origin))throw new U("BAD_REQUEST",{error:"invalid_client_metadata",error_description:"jwks_uri must belong to a trusted origin or the Client ID Metadata Document origin"})}}catch(h){if(h instanceof U)throw h;throw new U("BAD_REQUEST",{error:"invalid_client_metadata",error_description:"jwks_uri must be a valid URL"})}if(i.jwks)bh(i.jwks)}if(s==="private_key_jwt"&&!i.jwks&&!i.jwks_uri)throw new U("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(r.disableJwtPlugin)throw new U("BAD_REQUEST",{error:"invalid_client_metadata",error_description:"backchannel_logout_uri requires the jwt plugin (disableJwtPlugin must be false)"});let h;try{h=new URL(i.backchannel_logout_uri)}catch{throw new U("BAD_REQUEST",{error:"invalid_client_metadata",error_description:"backchannel_logout_uri must be an absolute URL"})}if(i.backchannel_logout_uri.includes("#"))throw new U("BAD_REQUEST",{error:"invalid_client_metadata",error_description:"backchannel_logout_uri must not include a fragment component"});if(h.protocol!=="https:")throw new U("BAD_REQUEST",{error:"invalid_client_metadata",error_description:"backchannel_logout_uri must use https"});if(h.username||h.password)throw new U("BAD_REQUEST",{error:"invalid_client_metadata",error_description:"backchannel_logout_uri must not contain credentials"});if(ni(h.hostname))throw new U("BAD_REQUEST",{error:"invalid_client_metadata",error_description:"backchannel_logout_uri must not point to a private or reserved address"})}}var ah=Symbol("client-registration-collision");async function Nh(t,r,n){let o=n.registrationSource==="dynamic"&&!n.metadata.scope?{...n.metadata,scope:(r.clientRegistrationDefaultScopes??r.scopes)?.join(" ")}:n.metadata,i=Lh(o,n.registrationSource==="clientMetadataDocument"?null:n.registrationSource==="dynamic"?Ph(r,o):"web"),s=i.token_endpoint_auth_method==="none",a=i.token_endpoint_auth_method==="private_key_jwt",c=Gs(r,i.token_endpoint_auth_method);await zh(i,r,{registrationSource:n.registrationSource,ctx:t});let d=n.clientId??r.generateClientId?.()??_e(32,"a-z","A-Z"),u=s||a||c?void 0:r.generateClientSecret?.()||_e(32,"a-z","A-Z"),f=u?await No(t,r,u):void 0,p=n.registrationSource==="dynamic"&&!s&&r.clientRegistrationRequirePKCE===!1,h=i.require_pkce??(p?!1:void 0),m=Math.floor(Date.now()/1000),{resources:w,...y}=n.registrationSource==="dynamic"||n.registrationSource==="clientMetadataDocument"?{...i,scope:Ch(r).join(" ")}:i,I=n.registrationSource==="clientMetadataDocument"?void 0:{userId:n.userId,referenceId:n.referenceId},R=$h({...y,redirect_uris:i.redirect_uris??[],disabled:void 0,client_secret_expires_at:f?n.registrationSource==="dynamic"&&r.clientRegistrationClientSecretExpiration?Yt(r.clientRegistrationClientSecretExpiration,m):0:void 0,client_id:d,client_secret:f,client_id_issued_at:m,require_pkce:h,user_id:I?.referenceId?void 0:I?.userId,reference_id:I?.referenceId});if(R.clientCredentialsScopes=n.registrationSource==="managed"?n.clientCredentialsScopes??[]:[],R.clientDiscoveryId=n.registrationSource==="clientMetadataDocument"?n.clientDiscoveryId:null,n.registrationSource==="clientMetadataDocument"&&i.application_type===void 0)R.applicationType=null;let b=n.registrationSource==="clientMetadataDocument"?[]:n.requestedResources??[];if(n.registrationSource==="dynamic")jk(r,b);let O=await Bk(t,r,b),g=r.schema?.oauthClient?.modelName??"oauthClient",S=r.schema?.oauthClientResource?.modelName??"oauthClientResource",C=n.registrationSource==="clientMetadataDocument"?n.existingClient:void 0,z=n.registrationSource==="clientMetadataDocument"?n.clientDiscoveryId:null,L=await Ue(t.context.adapter,async()=>{let x=await X(t.context.adapter),P,j=!1;if(C){let{clientCredentialsScopes:J,disabled:Q,skipConsent:G,enableEndSession:M,...Y}=R,Z=await x.update({model:g,where:[{field:"clientId",value:d},{field:"clientDiscoveryId",value:z}],update:{...Y,createdAt:C.createdAt,updatedAt:new Date(m*1000)}});if(!Z)throw new U("BAD_REQUEST",{error:"invalid_client",error_description:"client no longer exists"});P=Z}else{try{P=await x.create({model:g,data:{...R,createdAt:new Date(m*1000),updatedAt:new Date(m*1000)}})}catch(J){if(n.registrationSource==="clientMetadataDocument"&&ch(J))throw{[ah]:!0,kind:"oauth-client-row-unique",clientId:d,cause:J};throw J}j=!0}let B=O.length===0?[]:await x.findMany({model:S,where:[{field:"clientId",value:d}]}),H=new Set(B.map((J)=>J.resourceId)),q=new Date;for(let J of O){if(H.has(J))continue;try{await x.create({model:S,data:{clientId:d,resourceId:J,createdAt:q}})}catch(Q){if(n.registrationSource==="clientMetadataDocument"&&ch(Q))throw{[ah]:!0,kind:"oauth-client-resource-link-unique",clientId:d,resourceId:J,cause:Q};throw Q}}return{client:P,created:j}});return{client:L.client,clientSecret:u,resources:O,created:L.created}}function qh(t,r){let n=ht({...t.client,clientSecret:t.clientSecret?(r.prefix?.clientSecret??"")+t.clientSecret:void 0});if(t.resources.length>0)n.resources=t.resources;return n}function Hk(t,r){return{...qh(t,r),client_credentials_scopes:[...t.client.clientCredentialsScopes??[]]}}async function jh(t,r,n){return qh(await Nh(t,r,n),r)}async function Vk(t,r,n){return Hk(await Nh(t,r,n),r)}function ch(t){if(!t||typeof t!=="object")return!1;let r=t,n=String(r.code??r.errno??"");if(["1062","11000","23505","ER_DUP_ENTRY","P2002","SQLITE_CONSTRAINT_UNIQUE"].includes(n))return!0;if(r.name==="MongoServerError"&&r.code===11000)return!0;return typeof r.message==="string"&&/(?:duplicate|unique constraint|unique key)/i.test(r.message)}async function Bh(t,r,n){let o=await ee(t);if(await at(t,o,r,"create"),!o)throw new U("UNAUTHORIZED");let i=r.clientReference?await r.clientReference({user:o.user,session:o.session}):void 0,{client_credentials_scopes:s,...a}=t.body,c=n?.admin?wa(s??[]):[];if(ya(c,Oh(a),a.token_endpoint_auth_method,r),c.length>0)await at(t,o,r,"configure-client-credentials-scopes");let d=n?.admin?a.resources:void 0;for(let p of new Set(d??[]))await qt(t,o,r,"link",p);let u={metadata:a,registrationSource:"managed",userId:i?void 0:o.session.userId,referenceId:i,clientCredentialsScopes:c,...d?{requestedResources:d}:{}},f=n?.admin?await Vk(t,r,u):await jh(t,r,u);return t.setStatus(201),t.json(f)}function $h(t){let{client_id:r,client_secret:n,client_secret_expires_at:o,scope:i,user_id:s,client_id_issued_at:a,client_name:c,client_uri:d,logo_uri:u,contacts:f,tos_uri:p,policy_uri:h,jwks:m,jwks_uri:w,software_id:y,software_version:I,software_statement:R,redirect_uris:b,post_logout_redirect_uris:O,backchannel_logout_uri:g,backchannel_logout_session_required:S,token_endpoint_auth_method:C,grant_types:z,response_types:L,application_type:x,disabled:P,skip_consent:j,enable_end_session:B,require_pkce:H,dpop_bound_access_tokens:q,subject_type:J,reference_id:Q,metadata:G}=t,M=o?new Date(Number(o)*1000):void 0,Y=a?new Date(a*1000):void 0,Z=i?.split(" "),re=vh(G??{}),ie=re&&Object.keys(re).length?JSON.stringify(re):void 0;return{clientId:r,clientSecret:n,disabled:P,scopes:Z,userId:s,createdAt:Y,expiresAt:M,name:c,uri:d,icon:u,contacts:f,tos:p,policy:h,softwareId:y,softwareVersion:I,softwareStatement:R,redirectUris:b,postLogoutRedirectUris:O,backchannelLogoutUri:g,backchannelLogoutSessionRequired:S,tokenEndpointAuthMethod:C,grantTypes:z,responseTypes:L,jwks:m?JSON.stringify(m):void 0,jwksUri:w,applicationType:x,skipConsent:j,enableEndSession:B,requirePKCE:H,dpopBoundAccessTokens:q,subjectType:J,referenceId:Q,metadata:ie}}function ht(t){let{clientId:r,clientSecret:n,disabled:o,scopes:i,userId:s,createdAt:a,updatedAt:c,expiresAt:d,name:u,uri:f,icon:p,contacts:h,tos:m,policy:w,softwareId:y,softwareVersion:I,softwareStatement:R,redirectUris:b,postLogoutRedirectUris:O,backchannelLogoutUri:g,backchannelLogoutSessionRequired:S,tokenEndpointAuthMethod:C,grantTypes:z,responseTypes:L,applicationType:x,jwks:P,jwksUri:j,skipConsent:B,enableEndSession:H,requirePKCE:q,dpopBoundAccessTokens:J,subjectType:Q,referenceId:G,metadata:M}=t,Y=d?Math.round(new Date(d).getTime()/1000):void 0,Z=a?Math.round(new Date(a).getTime()/1000):void 0,re=i?.join(" ");return{...vh(rr(M)),client_id:r,client_secret:n??void 0,client_secret_expires_at:n?Y??0:void 0,scope:re??void 0,user_id:s??void 0,client_id_issued_at:Z??void 0,client_name:u??void 0,client_uri:f??void 0,logo_uri:p??void 0,contacts:h??void 0,tos_uri:m??void 0,policy_uri:w??void 0,jwks:P?JSON.parse(P):void 0,jwks_uri:j??void 0,software_id:y??void 0,software_version:I??void 0,software_statement:R??void 0,redirect_uris:b??[],post_logout_redirect_uris:O??void 0,backchannel_logout_uri:g??void 0,backchannel_logout_session_required:S??void 0,token_endpoint_auth_method:C??void 0,grant_types:z??void 0,response_types:L??void 0,application_type:x??void 0,disabled:o??void 0,skip_consent:B??void 0,enable_end_session:H??void 0,require_pkce:q??void 0,dpop_bound_access_tokens:J??void 0,subject_type:Q??void 0,reference_id:G??void 0}}async function Fk(t,r){let n=await ee(t);if(await at(t,n,r,"read",t.query.client_id),!n)throw new U("UNAUTHORIZED");let o=await ke(t,r,t.query.client_id);if(!o)throw new U("NOT_FOUND",{error_description:"client not found",error:"not_found"});if(o.userId){if(o.userId!==n.user.id)throw new U("UNAUTHORIZED")}else if(o.referenceId&&r.clientReference){if(o.referenceId!==await r.clientReference(n))throw new U("UNAUTHORIZED")}else throw new U("UNAUTHORIZED");let i=ht(o);return i.client_secret=void 0,i}async function Mh(t,r,n){let o=await ke(t,r,n);if(!o)throw new U("NOT_FOUND",{error_description:"client not found",error:"not_found"});if(o.disabled)throw new U("NOT_FOUND",{error_description:"client not found",error:"not_found"});return ht({clientId:o.clientId,name:o.name,uri:o.uri,contacts:o.contacts,icon:o.icon,tos:o.tos,policy:o.policy})}async function Kk(t,r){let n=await ee(t);if(await at(t,n,r,"list"),!n)throw new U("UNAUTHORIZED");let o=await r.clientReference?.(n);if(o)return await t.context.adapter.findMany({model:"oauthClient",where:[{field:"referenceId",value:o}]}).then((i)=>{if(!i)return null;return i.map((s)=>{let a=ht(s);return a.client_secret=void 0,a})});else if(n.user.id)return await t.context.adapter.findMany({model:"oauthClient",where:[{field:"userId",value:n.user.id}]}).then((i)=>{if(!i)return null;return i.map((s)=>{let a=ht(s);return a.client_secret=void 0,a})});else throw new U("BAD_REQUEST",{message:"either user_id or reference_id must be provided"})}async function Wk(t,r){let n=await ee(t);if(await at(t,n,r,"delete",t.body.client_id),!n)throw new U("UNAUTHORIZED");let o=t.body.client_id;Tn(r,o);let i=await ke(t,r,o);if(!i)throw new U("NOT_FOUND",{error_description:"client not found",error:"not_found"});if(i.userId){if(i.userId!==n.user.id)throw new U("UNAUTHORIZED")}else if(i.referenceId&&r.clientReference){if(i.referenceId!==await r.clientReference(n))throw new U("UNAUTHORIZED")}else throw new U("UNAUTHORIZED");await t.context.adapter.delete({model:"oauthClient",where:[{field:"clientId",value:o}]})}async function Hh(t,r,n){let o=await ee(t);if(await at(t,o,r,"update",t.body.client_id),!o)throw new U("UNAUTHORIZED");let i=t.body.client_id;Tn(r,i);let s=await ke(t,r,i);if(!s)throw new U("NOT_FOUND",{error_description:"client not found",error:"not_found"});let{client_credentials_scopes:a,...c}=t.body.update,d=s.userId?s.userId===o.user.id:s.referenceId&&r.clientReference?s.referenceId===await r.clientReference(o):!1,u=!d&&n?.admin&&a!==void 0&&Object.keys(c).length===0;if(!d&&!u)throw new U("UNAUTHORIZED");if(u)await at(t,o,r,"configure-client-credentials-scopes",i);if(Object.keys(c).length===0&&a===void 0){let I=ht(s);if(I.client_secret=void 0,n?.admin)return{...I,client_credentials_scopes:[...s.clientCredentialsScopes??[]]};return I}let f=c.grant_types??s.grantTypes??[],p=c.token_endpoint_auth_method??s.tokenEndpointAuthMethod,h=a===void 0?void 0:wa(a);if(h!==void 0){if(ya(h,f,p,r),h.length>0&&!u)await at(t,o,r,"configure-client-credentials-scopes",i)}await zh({...ht(s),...c},r,{ctx:t});let m={...$h(c)};if(!f.includes("client_credentials")||p==="none")m.clientCredentialsScopes=[];else if(h!==void 0)m.clientCredentialsScopes=h;if(c.token_endpoint_auth_method){if(c.token_endpoint_auth_method==="private_key_jwt")m.clientSecret=null;else if(m.jwks=null,m.jwksUri=null,!m.clientSecret)m.clientSecret=await No(t,r,r.generateClientSecret?.()||_e(32,"a-z","A-Z"))}let w=await t.context.adapter.update({model:"oauthClient",where:[{field:"clientId",value:i}],update:{...m,updatedAt:new Date(Math.floor(Date.now()/1000)*1000)}});if(!w)throw new U("INTERNAL_SERVER_ERROR",{error_description:"unable to update client",error:"invalid_client"});let y=ht(w);if(y.client_secret=void 0,n?.admin)return{...y,client_credentials_scopes:[...w.clientCredentialsScopes??[]]};return y}async function Jk(t,r){let n=await ee(t);if(await at(t,n,r,"rotate",t.body.client_id),!n)throw new U("UNAUTHORIZED");let o=t.body.client_id;Tn(r,o);let i=await ke(t,r,o);if(!i)throw new U("NOT_FOUND",{error_description:"client not found",error:"not_found"});if(i.userId){if(i.userId!==n.user.id)throw new U("UNAUTHORIZED")}else if(i.referenceId&&r.clientReference){if(i.referenceId!==await r.clientReference(n))throw new U("UNAUTHORIZED")}else throw new U("UNAUTHORIZED");if(i.tokenEndpointAuthMethod==="none"||!i.clientSecret)throw new U("BAD_REQUEST",{error_description:"secret rotation is only available for clients using client_secret authentication",error:"invalid_client"});let s=r.generateClientSecret?.()||_e(32,"a-z","A-Z"),a=s?await No(t,r,s):void 0,c=await t.context.adapter.update({model:"oauthClient",where:[{field:"clientId",value:o}],update:{clientSecret:a,updatedAt:new Date(Math.floor(Date.now()/1000)*1000)}});if(!c)throw new U("INTERNAL_SERVER_ERROR",{error_description:"unable to update client",error:"invalid_client"});return ht({...c,clientSecret:(r.prefix?.clientSecret??"")+s})}async function Qk(t,r){if(!r.allowClientKeyRotation)throw new U("FORBIDDEN",{error:"access_denied",error_description:"Client key rotation is disabled"});let{body:n}=t;bh(n.jwks);let{client:o}=await Uh(t,r,n.client_assertion,n.client_assertion_type,void 0,Jo({context:t.context,request:void 0},"/oauth2/client/rotate-keys"),{endpointAudienceOnly:!0,assertClient:(i)=>Gk(r,i)});if(!await t.context.adapter.incrementOne({model:"oauthClient",where:[{field:"clientId",value:o.clientId},{field:"jwks",value:o.jwks}],increment:{},set:{jwks:JSON.stringify(n.jwks),updatedAt:new Date}}))throw new U("CONFLICT",{error:"invalid_request",error_description:"client keys changed while rotating; retry with a fresh client assertion"});return{client_id:o.clientId,jwks:n.jwks}}function Gk(t,r){if(Tn(t,r.clientId),r.clientDiscoveryId||r.jwksUri||!r.jwks)throw new U("BAD_REQUEST",{error:"invalid_client",error_description:"client keys are not stored inline; rotate them where the client publishes them"})}var Vh=e().trim().min(1),ii=A(e().trim().min(1)).min(1),Zk=(t)=>Pe("/admin/oauth2/create-client",{method:"POST",body:l({redirect_uris:A(le).min(1).optional(),scope:e().optional(),client_name:e().optional(),client_uri:e().optional(),logo_uri:e().optional(),contacts:A(e().min(1)).min(1).optional(),tos_uri:e().optional(),policy_uri:e().optional(),software_id:e().optional(),software_version:e().optional(),software_statement:e().optional(),post_logout_redirect_uris:A(le).min(1).optional(),backchannel_logout_uri:le.optional(),backchannel_logout_session_required:E().optional(),token_endpoint_auth_method:Vh.optional(),application_type:T(["web","native"]).optional(),jwks:Pn.optional(),jwks_uri:e().optional(),grant_types:ii.optional(),client_credentials_scopes:A(e().trim().min(1)).optional(),resources:A(Qs).optional(),response_types:A(T(["code"])).optional(),client_secret_expires_at:D([e(),_()]).optional().default(0),skip_consent:E().optional(),enable_end_session:E().optional(),require_pkce:E().optional(),dpop_bound_access_tokens:E().optional(),subject_type:T(["public","pairwise"]).optional(),metadata:k(e(),W()).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(r)=>Bh(r,t,{admin:!0})),Yk=(t)=>Pe("/oauth2/create-client",{method:"POST",use:[$r],body:l({redirect_uris:A(le).min(1).optional(),scope:e().optional(),client_name:e().optional(),client_uri:e().optional(),logo_uri:e().optional(),contacts:A(e().min(1)).min(1).optional(),tos_uri:e().optional(),policy_uri:e().optional(),software_id:e().optional(),software_version:e().optional(),software_statement:e().optional(),post_logout_redirect_uris:A(le).min(1).optional(),backchannel_logout_uri:le.optional(),backchannel_logout_session_required:E().optional(),token_endpoint_auth_method:Vh.optional(),application_type:T(["web","native"]).optional(),jwks:Pn.optional(),jwks_uri:e().optional(),grant_types:ii.optional(),response_types:A(T(["code"])).optional(),dpop_bound_access_tokens:E().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(r)=>Bh(r,t)),Xk=(t)=>Pe("/oauth2/get-client",{method:"GET",use:[$r],query:l({client_id:e()}),metadata:{openapi:{description:"Get OAuth2 formatted client details"}}},async(r)=>Fk(r,t)),eE=(t)=>Pe("/oauth2/public-client",{method:"GET",use:[$r],query:l({client_id:e()}),metadata:{openapi:{description:"Gets publicly available client fields"}}},async(r)=>{let n=r.query.client_id;return Mh(r,t,n)}),tE=(t)=>Pe("/oauth2/public-client-prelogin",{method:"POST",use:[wk(t)],body:l({client_id:e(),oauth_query:e().optional()}),metadata:{openapi:{description:"Gets publicly available client fields (prior to login)"}}},async(r)=>{let n=r.body.client_id;return Mh(r,t,n)}),rE=(t)=>Pe("/oauth2/get-clients",{method:"GET",use:[$r],metadata:{openapi:{description:"Get OAuth2 formatted client details for a user or organization"}}},async(r)=>Kk(r,t)),nE=(t)=>Pe("/admin/oauth2/update-client",{method:"PATCH",body:l({client_id:e(),update:l({redirect_uris:A(le).min(1).optional(),scope:e().optional(),client_name:e().optional(),client_uri:e().optional(),logo_uri:e().optional(),contacts:A(e().min(1)).min(1).optional(),tos_uri:e().optional(),policy_uri:e().optional(),software_id:e().optional(),software_version:e().optional(),software_statement:e().optional(),post_logout_redirect_uris:A(le).min(1).optional(),backchannel_logout_uri:le.optional(),backchannel_logout_session_required:E().optional(),application_type:T(["web","native"]).optional(),grant_types:ii.optional(),client_credentials_scopes:A(e().trim().min(1)).optional(),response_types:A(T(["code"])).optional(),client_secret_expires_at:D([e(),_()]).optional(),skip_consent:E().optional(),enable_end_session:E().optional(),disabled:E().optional(),dpop_bound_access_tokens:E().optional(),metadata:k(e(),W()).optional()})}),metadata:{SERVER_ONLY:!0,openapi:{description:"Updates OAuth2 formatted client details."}}},async(r)=>Hh(r,t,{admin:!0})),oE=(t)=>Pe("/oauth2/update-client",{method:"POST",use:[$r],body:l({client_id:e(),update:l({redirect_uris:A(le).min(1).optional(),scope:e().optional(),client_name:e().optional(),client_uri:e().optional(),logo_uri:e().optional(),contacts:A(e().min(1)).min(1).optional(),tos_uri:e().optional(),policy_uri:e().optional(),software_id:e().optional(),software_version:e().optional(),software_statement:e().optional(),post_logout_redirect_uris:A(le).min(1).optional(),backchannel_logout_uri:le.optional(),backchannel_logout_session_required:E().optional(),application_type:T(["web","native"]).optional(),grant_types:ii.optional(),response_types:A(T(["code"])).optional()})}),metadata:{openapi:{description:"Updates OAuth2 formatted client details."}}},async(r)=>Hh(r,t)),iE=(t)=>Pe("/oauth2/client/rotate-secret",{method:"POST",use:[$r],body:l({client_id:e()}),metadata:{noStore:!0,openapi:{description:"Rotates a confidential client's secret"}}},async(r)=>Jk(r,t)),sE=(t)=>Pt("/oauth2/client/rotate-keys",{method:"POST",body:l({client_assertion:e(),client_assertion_type:e(),jwks:Pn}),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(r)=>Qk(r,t)),aE=(t)=>Pe("/oauth2/delete-client",{method:"POST",use:[$r],body:l({client_id:e()}),metadata:{openapi:{description:"Deletes an oauth client"}}},async(r)=>Wk(r,t));async function La(t,r,n){return await t.context.adapter.findOne({model:"oauthConsent",where:[{field:"id",value:n}]})}async function cE(t,r){let n=await ee(t);if(!n)throw new U("UNAUTHORIZED");let{id:o}=t.query;if(!o)throw new U("NOT_FOUND",{error_description:"missing id parameter",error:"not_found"});let i=await La(t,r,o);if(!i)throw new U("NOT_FOUND",{error_description:"no consent",error:"not_found"});if(i.userId!==n.user.id)throw new U("UNAUTHORIZED");return i}async function dE(t,r){let n=await ee(t);if(!n)throw new U("UNAUTHORIZED");return await t.context.adapter.findMany({model:"oauthConsent",where:[{field:"userId",value:n.user.id}]})}async function uE(t,r){let n=await ee(t);if(!n)throw new U("UNAUTHORIZED");let{id:o}=t.body;if(!o)throw new U("NOT_FOUND",{error_description:"missing id parameter",error:"not_found"});let i=await La(t,r,o);if(!i)throw new U("NOT_FOUND",{error_description:"no consent",error:"not_found"});if(i.userId!==n.user.id)throw new U("UNAUTHORIZED");await t.context.adapter.delete({model:"oauthConsent",where:[{field:"id",value:o}]})}async function lE(t,r){let n=await ee(t);if(!n)throw new U("UNAUTHORIZED");let{id:o}=t.body;if(!o)throw new U("NOT_FOUND",{error_description:"missing id parameter",error:"not_found"});let i=await La(t,r,o);if(!i)throw new U("NOT_FOUND",{error_description:"no consent",error:"not_found"});if(i.userId!==n.user.id)throw new U("UNAUTHORIZED");let s=await ke(t,r,i.clientId);if(!s)throw new U("NOT_FOUND",{error_description:"client not found",error:"not_found"});let a=s?.scopes??r.scopes??[],c=t.body.update,d=c.scopes;if(d&&!d.every((f)=>a?.includes(f)))throw new U("BAD_REQUEST",{error_description:`unable to provide scopes to ${s?.referenceId??s?.userId}`,error:"invalid_request"});let u=Math.floor(Date.now()/1000);return await t.context.adapter.update({model:"oauthConsent",where:[{field:"id",value:o}],update:{...c,updatedAt:new Date(u*1000)}})}var fE=(t)=>Pe("/oauth2/get-consent",{method:"GET",query:l({id:e()}),use:[$r],metadata:{openapi:{description:"Gets details of a specific OAuth2 consent for a user"}}},async(r)=>cE(r,t)),pE=(t)=>Pe("/oauth2/get-consents",{method:"GET",use:[$r],metadata:{openapi:{description:"Gets all available OAuth2 consents for a user"}}},async(r)=>dE(r,t)),hE=(t)=>Pe("/oauth2/update-consent",{method:"POST",use:[$r],body:l({id:e(),update:l({scopes:A(e())})}),metadata:{openapi:{description:"Updates consent granted to a client."}}},async(r)=>lE(r,t)),mE=(t)=>Pe("/oauth2/delete-consent",{method:"POST",use:[$r],body:l({id:e()}),metadata:{openapi:{description:"Deletes consent granted to a client"}}},async(r)=>uE(r,t)),mt=(t)=>t.schema?.oauthResource?.modelName??"oauthResource",Fh=(t)=>t.schema?.oauthClientResource?.modelName??"oauthClientResource",gE=(t)=>t.schema?.oauthClient?.modelName??"oauthClient";function sr(t){try{return decodeURIComponent(t)}catch{return t}}function wE(t,r){return{identifier:t.identifier,name:t.name??t.identifier,accessTokenTtl:t.accessTokenTtl??null,refreshTokenTtl:t.refreshTokenTtl??null,signingAlgorithm:t.signingAlgorithm??null,signingKeyId:t.signingKeyId??null,allowedScopes:t.allowedScopes??null,customClaims:t.customClaims??null,dpopBoundAccessTokensRequired:t.dpopBoundAccessTokensRequired??!1,disabled:t.disabled??!1,policyVersion:1,metadata:t.metadata??null,createdAt:r,updatedAt:r}}async function yE(t,r){await qt(t,await ee(t),r,"create");let n=t.body;if(!n?.identifier)throw new U("BAD_REQUEST",{error:"invalid_request",error_description:"identifier is required"});await Rp(r,n.identifier);let o=new Date,i;try{i=await t.context.adapter.create({model:mt(r),data:wE(n,o)})}catch(s){let a=s instanceof Error?s.message:String(s);if(/unique|duplicate|UNIQUE/i.test(a))throw new U("BAD_REQUEST",{error:"invalid_request",error_description:`resource ${n.identifier} already exists`});throw s}if(!i)throw new U("BAD_REQUEST",{error:"invalid_request",error_description:`resource ${n.identifier} could not be created`});return Ko(i.identifier),t.json(i,{status:201})}async function _E(t,r){await qt(t,await ee(t),r,"list");let n=await t.context.adapter.findMany({model:mt(r)});return t.json(n??[])}async function AE(t,r){let n=sr(t.params.identifier);await qt(t,await ee(t),r,"read",n);let o=await t.context.adapter.findOne({model:mt(r),where:[{field:"identifier",value:n}]});if(!o)throw new U("NOT_FOUND",{error:"not_found",error_description:`resource ${n} not found`});return t.json(o)}async function kE(t,r){let n=sr(t.params.identifier);if(await qt(t,await ee(t),r,"update",n),!await t.context.adapter.findOne({model:mt(r),where:[{field:"identifier",value:n}]}))throw new U("NOT_FOUND",{error:"not_found",error_description:`resource ${n} not found`});let o={updatedAt:new Date};for(let s of["name","accessTokenTtl","refreshTokenTtl","signingAlgorithm","signingKeyId","allowedScopes","customClaims","dpopBoundAccessTokensRequired","disabled","metadata"])if(Object.prototype.hasOwnProperty.call(t.body,s))o[s]=t.body[s];await t.context.adapter.update({model:mt(r),where:[{field:"identifier",value:n}],update:o}),Ko(n);let i=await t.context.adapter.findOne({model:mt(r),where:[{field:"identifier",value:n}]});if(!i)throw new U("NOT_FOUND",{error:"not_found",error_description:`resource ${n} not found`});return t.json(i)}async function EE(t,r){let n=sr(t.params.identifier);if(await qt(t,await ee(t),r,"delete",n),!await t.context.adapter.findOne({model:mt(r),where:[{field:"identifier",value:n}]}))throw new U("NOT_FOUND",{error:"not_found",error_description:`resource ${n} not found`});return await t.context.adapter.delete({model:mt(r),where:[{field:"identifier",value:n}]}),Ko(n),t.json({deleted:!0})}async function bE(t,r){let n=await ee(t),o=sr(t.params.identifier),i=sr(t.params.client_id);if(await qt(t,n,r,"link",o),!await t.context.adapter.findOne({model:mt(r),where:[{field:"identifier",value:o}]}))throw new U("NOT_FOUND",{error:"not_found",error_description:`resource ${o} not found`});if(!await t.context.adapter.findOne({model:gE(r),where:[{field:"clientId",value:i}]}))throw new U("NOT_FOUND",{error:"not_found",error_description:`client ${i} not found`});try{await t.context.adapter.create({model:Fh(r),data:{clientId:i,resourceId:o,createdAt:new Date}})}catch(s){let a=s instanceof Error?s.message:String(s);if(/unique|duplicate|UNIQUE/i.test(a))return t.json({linked:!0,alreadyLinked:!0});throw s}return t.json({linked:!0})}async function vE(t,r){let n=await ee(t),o=sr(t.params.identifier),i=sr(t.params.client_id);return await qt(t,n,r,"unlink",o),await t.context.adapter.deleteMany({model:Fh(r),where:[{field:"clientId",value:i},{field:"resourceId",value:o}]}),t.json({unlinked:!0})}var Kh=l({identifier:e().min(1).optional(),name:e().optional(),accessTokenTtl:_().int().positive().nullable().optional(),refreshTokenTtl:_().int().positive().nullable().optional(),signingAlgorithm:T(Ho).nullable().optional(),signingKeyId:e().nullable().optional(),allowedScopes:A(e()).nullable().optional(),customClaims:k(e(),W()).nullable().optional(),dpopBoundAccessTokensRequired:E().optional(),disabled:E().optional(),metadata:k(e(),W()).nullable().optional()}),SE=(t)=>Pe("/admin/oauth2/resources",{method:"POST",body:Kh.required({identifier:!0}),metadata:{SERVER_ONLY:!0}},async(r)=>yE(r,t)),RE=(t)=>Pe("/admin/oauth2/resources",{method:"GET",metadata:{SERVER_ONLY:!0}},async(r)=>_E(r,t)),TE=(t)=>Pe("/admin/oauth2/resources/:identifier",{method:"GET",metadata:{SERVER_ONLY:!0}},async(r)=>AE(r,t)),IE=(t)=>Pe("/admin/oauth2/resources/:identifier",{method:"PATCH",body:Kh,metadata:{SERVER_ONLY:!0}},async(r)=>kE(r,t)),UE=(t)=>Pe("/admin/oauth2/resources/:identifier",{method:"DELETE",metadata:{SERVER_ONLY:!0}},async(r)=>EE(r,t)),CE=(t)=>Pe("/admin/oauth2/resources/:identifier/clients/:client_id",{method:"POST",metadata:{SERVER_ONLY:!0}},async(r)=>bE(r,t)),OE=(t)=>Pe("/admin/oauth2/resources/:identifier/clients/:client_id",{method:"DELETE",metadata:{SERVER_ONLY:!0}},async(r)=>vE(r,t));async function DE(t,r,n){if(r.disableJwtPlugin)throw new ce("BAD_REQUEST",{error_description:"JWT access tokens are disabled",error:"invalid_request"});let o=Oe(t.context),i=o.options,s;try{s=(await Hr(n,Qo(await Ar(n,{jwksFetch:i?.jwks?.remoteUrl?i.jwks.remoteUrl:async()=>(await o.endpoints.getJwks(t))?.response,jwksCacheKey:o})),{issuer:i?.jwt?.issuer??t.context.baseURL})).payload}catch(c){if(c instanceof yi||c instanceof zr)return null;if(c instanceof TypeError||xo(c))throw new ce("BAD_REQUEST",{error_description:"invalid JWT signature",error:"invalid_request"});throw c}let a=`${t.context.baseURL}/oauth2/userinfo`;if(!s.azp||!await Fo(t,r,s.aud,[a]))return null;throw new ce("BAD_REQUEST",{error_description:"JWT access tokens are self-contained and cannot be revoked server-side",error:"unsupported_token_type"})}async function LE(t,r,n,o){let i=n;if(r.prefix?.opaqueAccessToken)if(i.startsWith(r.prefix.opaqueAccessToken))i=i.replace(r.prefix.opaqueAccessToken,"");else throw new ce("BAD_REQUEST",{error_description:"opaque access token not found",error:"invalid_request"});let s=await t.context.adapter.findOne({model:"oauthAccessToken",where:[{field:"token",value:await tr(r.storeTokens,i,"access_token")}]});if(!s)throw new ce("BAD_REQUEST",{error_description:"opaque access token not found",error:"invalid_request"});if(!s.clientId||s.clientId!==o)return null;s.id?await t.context.adapter.delete({model:"oauthAccessToken",where:[{field:"id",value:s.id}]}):await t.context.adapter.delete({model:"oauthAccessToken",where:[{field:"token",value:s.token}]})}async function PE(t,r,n,o){let i=await t.context.adapter.findOne({model:"oauthRefreshToken",where:[{field:"token",value:await tr(r.storeTokens,n,"refresh_token")}]});if(!i)throw new ce("BAD_REQUEST",{error_description:"token not found",error:"invalid_request"});if(i.revoked)throw await Yo(t,o,i.userId),new ce("BAD_REQUEST",{error_description:"refresh token revoked",error:"invalid_request"});if(!i.clientId||i.clientId!==o)return null;let s=Math.floor(Date.now()/1000);if(!await t.context.adapter.incrementOne({model:"oauthRefreshToken",where:[{field:"id",value:i.id},{field:"revoked",operator:"eq",value:null}],increment:{},set:{revoked:new Date(s*1000)}}))throw await Yo(t,o,i.userId),new ce("BAD_REQUEST",{error_description:"refresh token revoked",error:"invalid_request"});await t.context.adapter.deleteMany({model:"oauthAccessToken",where:[{field:"refreshId",value:i.id}]})}async function xE(t,r,n,o){try{return await DE(t,r,o)}catch(i){if(i instanceof ce){if(i.body?.error==="unsupported_token_type")throw i}else if(i instanceof Error)throw i;else throw Error(i)}try{return await LE(t,r,o,n)}catch(i){if(i instanceof ce);else if(i instanceof Error)throw i;else throw Error("Unknown error validating access token")}throw new ce("BAD_REQUEST",{error_description:"Invalid access token",error:"invalid_request"})}async function zE(t,r){let{token:n,token_type_hint:o}=t.body;if(o!=="access_token"&&o!=="refresh_token")o=void 0;let{clientId:i,clientSecret:s,preVerified:a,authMethod:c}=Ot(await Dt(t,r,`${t.context.baseURL}/oauth2/revoke`));if(!i)throw new ce("UNAUTHORIZED",{error_description:"missing required credentials",error:"invalid_client"});if(typeof n==="string")n=fn(n);if(!n?.length)throw new ce("BAD_REQUEST",{error_description:"missing a required token for introspection",error:"invalid_request"});let d=await Ct(t,r,i,s,void 0,a,void 0,c);try{if(o===void 0||o==="access_token")try{return await xE(t,r,d.clientId,n)}catch(u){if(u instanceof ce){if(o==="access_token"||u.body?.error==="unsupported_token_type")throw u}else if(u instanceof Error)throw u;else throw Error(u)}if(o===void 0||o==="refresh_token")try{return await PE(t,r,(await Zo(r,n)).token,d.clientId)}catch(u){if(u instanceof ce){if(o==="refresh_token")throw u}else if(u instanceof Error)throw u;else throw Error(u)}throw new ce("BAD_REQUEST",{error_description:"token not found",error:"invalid_request"})}catch(u){if(u instanceof ce){if(u.body?.error==="unsupported_token_type")throw u;if(u.name==="BAD_REQUEST")return null;throw u}else if(u instanceof Error)throw Ee.error("Introspection error:",u.message,u.stack),new ce("INTERNAL_SERVER_ERROR");else throw Ee.error("Introspection error:",u),new ce("INTERNAL_SERVER_ERROR")}}var NE={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},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},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},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}}}},jy=["openid","profile","email","offline_access"],dh=l({id_token_hint:e().optional(),client_id:e().optional(),post_logout_redirect_uri:le.optional(),state:e().optional()}),Nt=Et(()=>null),iP=Nt.get,ti=new WeakMap,uh="signedQueryIssuedAtMs";function qE(t){let r=typeof t==="number"?t:typeof t==="string"?Number(t):void 0;if(!r||!Number.isFinite(r)||r<=0)return;return new Date(r)}var hf=(t)=>{let r=t.clientRegistrationAllowedScopes;if(t.clientRegistrationDefaultScopes){let u=r?new Set([...r,...t.clientRegistrationDefaultScopes]):new Set([...t.clientRegistrationDefaultScopes]);r=Array.from(u)}let n=new Set((t.scopes??jy).filter((u)=>u.length));if(r){for(let u of r)if(!n.has(u))throw new te(`clientRegistrationAllowedScope ${u} not found in scopes`)}for(let u of t.advertisedMetadata?.scopes_supported??[])if(!n?.has(u))throw new te(`advertisedMetadata.scopes_supported ${u} not found in scopes`);let o=new Set((t.resources??[]).map((u)=>typeof u==="string"?u:u.identifier));for(let[u,f]of[["clientRegistrationDefaultResources",t.clientRegistrationDefaultResources],["clientRegistrationAllowedResources",t.clientRegistrationAllowedResources]])for(let p of f??[])if(!o.has(p))throw new te(`${u} resource ${p} not found in resources`);let i=new Set(["sub","iss","aud","exp","iat","sid","scope","azp",...fa.filter((u)=>n.has(Mo[u].scope))]),s={codeExpiresIn:600,accessTokenExpiresIn:3600,m2mAccessTokenExpiresIn:3600,refreshTokenExpiresIn:2592000,refreshTokenReuseInterval:0,allowUnauthenticatedClientRegistration:!1,allowDynamicClientRegistration:!1,disableJwtPlugin:!1,storeClientSecret:t.disableJwtPlugin?"encrypted":"hashed",storeTokens:"hashed",grantTypes:["authorization_code","client_credentials","refresh_token"],...t,scopes:Array.from(n),claims:Array.from(i),clientRegistrationAllowedScopes:r};if(Xf(s.extensions),s.pairwiseSecret&&s.pairwiseSecret.length<32)throw new te("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 te("refresh_token grant requires authorization_code grant");if(s.disableJwtPlugin&&(s.storeClientSecret==="hashed"||typeof s.storeClientSecret==="object"&&("hash"in s.storeClientSecret)))throw new te("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 te("encryption method not recommended, please use 'hashed' or the 'hash' function");let a=async(u,f)=>{let p=new URL(u.url).pathname,h=f.options.advanced?.skipTrailingSlashes?p.replace(/\/+$/,"")||"/":p,m=s.disableJwtPlugin?f.baseURL:Oe(f)?.options?.jwt?.issuer??f.baseURL,w="/";try{w=new URL(m).pathname.replace(/\/$/,"")||""}catch{w=new URL(f.baseURL).pathname.replace(/\/$/,"")||""}let y={context:f},I=new Set([`/.well-known/oauth-authorization-server${w}`,`${w}/.well-known/oauth-authorization-server`]),R=`${w}/.well-known/openid-configuration`,b=I.has(h),O=s.scopes?.includes("openid")&&h===R,g=(S)=>{let C=gl(S);if(u.method==="HEAD")return new Response(null,{status:C.status,headers:C.headers});return C};if(b||O){if(u.method!=="GET"&&u.method!=="HEAD")return{response:new Response(null,{status:405,headers:{Allow:"GET, HEAD"}})}}if(b){if(s.scopes?.includes("openid"))return{response:g(mf(y,s))};return{response:g(Wg(y,s))}}if(O)return{response:g(mf(y,s))}},c=Pt("/oauth2/authorize",{method:["GET","POST"],body:l({}).passthrough(),redirectOnError:xt(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:"client_id",in:"query",required:!0,schema:{type:"string"},description:"OAuth 2.1 client ID"},{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(u)=>KE(u,s,u.authorizeSettings??{isAuthorize:!0})),d=(u,f)=>bn(c,{...u,asResponse:!1,returnHeaders:!1,returnStatus:!1,authorizeSettings:f??{}});return{id:"oauth-provider",version:Vp,options:s,onRequest:a,init:async(u)=>{if(u.options.secondaryStorage&&u.options.session?.storeSessionInDatabase!==!0)throw new te("OAuth Provider requires `session.storeSessionInDatabase: true` when using secondaryStorage");if(s.allowClientKeyRotation){let f=u.adapter.id==="memory"?"the memory adapter":u.options.advanced?.database?.generateId==="serial"?'`advanced.database.generateId: "serial"`':void 0;if(f)throw new te(`\`allowClientKeyRotation\` requires single-use client assertions, which ${f} does not enforce`)}if(await ga(u,s).catch((f)=>Cp(u,f)),Op(s),!s.disableJwtPlugin){let f=Oe(u)?.options,p=f?.jwt?.issuer??u.baseURL,h=f?.jwt?.issuer==null&&typeof u.options.baseURL==="object"&&u.options.baseURL!==null&&"allowedHosts"in u.options.baseURL;try{new URL(p)}catch(m){if(!h||p!=="")throw m}}return{options:{databaseHooks:{session:{delete:{async before(f,p){if(!p)return;let h=await YA(p,s,{sessionId:f.id,userId:f.userId});if(!h)return;let m=ti.get(p)??new Map;m.set(f.id,h),ti.set(p,m)},async after(f,p){if(!p)return;let h=ti.get(p);if(!h)return;let m=h.get(f.id);if(h.delete(f.id),h.size===0)ti.delete(p);if(!m)return;let w=XA(p,m).catch((y)=>{p.context.logger.error("Back-channel logout failed after session deletion",y)});await p.context.runInBackgroundOrAwait(w)}}}}}}},hooks:{before:[{matcher(u){return u.body?.oauth_query},handler:Cn(async(u)=>{let f=u.body.oauth_query;if(!await ra(f,u.context.secret))throw new U("BAD_REQUEST",{error:"invalid_signature"});let p=Qf(f),h=new URLSearchParams(f),m=h.get("ba_pl")??void 0;if(h.delete("sig"),h.delete("exp"),h.delete(Ms),h.delete(Oo),await Nt.set({query:h.toString(),signedQueryIssuedAt:p??void 0,postLoginClearedForSession:m}),u.path==="/sign-in/social")await es({query:h.toString(),...p?{[uh]:p.getTime()}:{}})})}],after:[{matcher(u){return Gn(u.context.responseHeaders?.get("set-cookie")||"").has(u.context.authCookies.sessionToken.name)},handler:Cn(async(u)=>{let f=Gn(u.context.responseHeaders?.get("set-cookie")||"").get(u.context.authCookies.sessionToken.name)?.value.split(".")[0];if(!f)return;let p=await Nt.get(),h=(await Zi())?.serverContext,m=p?.query??h?.query;if(!m)return;let w=new URLSearchParams(m),y=await u.context.internalAdapter.findSession(f);if(!y)return;u.context.session=y;let I=u.request?.headers?.get("sec-fetch-mode")?.toLowerCase(),R=u.request?.headers?.get("accept")?.toLowerCase()??"";if(!(I==="navigate"||!I&&(R.includes("text/html")||R.includes("application/xhtml+xml"))))u.headers?.set("accept","application/json");let b=p?.signedQueryIssuedAt??qE(h?.[uh]),O=Ir(w,"login");if(ca(y.session.createdAt,b))O=da(O);return u.query=nr(O),await d(u)})}]},endpoints:{getOAuthServerConfig:Pe("/.well-known/oauth-authorization-server",{method:"GET",metadata:{SERVER_ONLY:!0}},async(u)=>{if(s.scopes&&s.scopes.includes("openid"))return mf(u,s);else return Wg(u,s)}),getOpenIdConfig:Pe("/.well-known/openid-configuration",{method:"GET",metadata:{SERVER_ONLY:!0}},async(u)=>{if(s.scopes&&!s.scopes.includes("openid"))throw new U("NOT_FOUND");return mf(u,s)}),oauth2Authorize:c,oauth2Consent:Pe("/oauth2/consent",{method:"POST",body:l({accept:E().meta({description:"Accept or deny user consent for a set of scopes"}),scope:e().optional().meta({description:"List of accept of accepted space-separated scopes. If none is provided, then all originally requested scopes are accepted."}),claims:la.optional().meta({description:"Accepted OIDC claims request object. If none is provided, then all originally requested claims are accepted."}),oauth_query:e().optional().meta({description:"The redirected page's query parameters"})}),use:[$r],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(u)=>MA(u,s,d)),oauth2Continue:Pe("/oauth2/continue",{method:"POST",body:l({selected:E().optional().meta({description:"Confirms an account has been selected and authorization can proceed."}),created:E().optional().meta({description:"Confirms an account was registered"}),postLogin:E().optional().meta({description:"Resumes after the post login page. postLogin.shouldRedirect runs again with isContinuation: true."}),oauth_query:e().optional().meta({description:"The redirected page's query parameters"})}),use:[$r],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(u)=>HA(u,d)),oauth2Token:Pt("/oauth2/token",{method:"POST",cloneRequest:!0,body:l({grant_type:e().trim().min(1),client_id:e().optional(),client_secret:e().optional(),client_assertion:e().optional(),client_assertion_type:e().optional(),code:e().optional(),code_verifier:e().optional(),redirect_uri:le.optional(),refresh_token:e().optional(),resource:D([Qs,A(Qs).min(1)]).optional(),scope:e().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(u)=>{if(u.request){let f=await Tp(u.request);if(f&&f.length>1)u.body.resource=f}return xp(u,s)}),oauth2Introspect:Pt("/oauth2/introspect",{method:"POST",cloneRequest:!0,body:l({client_id:e().optional(),client_secret:e().optional(),client_assertion:e().optional(),client_assertion_type:e().optional(),token:e(),token_type_hint:e().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(u)=>ka(u,s)),oauth2Revoke:Pt("/oauth2/revoke",{method:"POST",cloneRequest:!0,body:l({client_id:e().optional(),client_secret:e().optional(),client_assertion:e().optional(),client_assertion_type:e().optional(),token:e(),token_type_hint:e().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(u)=>zE(u,s)),oauth2UserInfo:Pe("/oauth2/userinfo",{method:["GET","POST"],body:l({access_token:e().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(u)=>Pp(u,s)),oauth2EndSession:Pt("/oauth2/end-session",{method:["GET","POST"],body:dh.optional(),query:dh.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 confirmation page was returned for browser navigation. 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"}}}}}}}},async(u)=>lk(u,s)),oauth2EndSessionConfirmation:Pt("/oauth2/end-session/confirm",{method:"POST",body:l({action:v("confirm")}),metadata:{noStore:!0,allowedMediaTypes:["application/x-www-form-urlencoded"],scope:"http"}},async(u)=>fk(u,s)),registerOAuthClient:Pt("/oauth2/register",{method:"POST",body:ha,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"},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(u)=>Mk(u,s)),adminCreateOAuthClient:Zk(s),createOAuthClient:Yk(s),getOAuthClient:Xk(s),getOAuthClientPublic:eE(s),getOAuthClientPublicPrelogin:tE(s),getOAuthClients:rE(s),adminUpdateOAuthClient:nE(s),updateOAuthClient:oE(s),rotateClientSecret:iE(s),rotateClientKeys:sE(s),deleteOAuthClient:aE(s),getOAuthConsent:fE(s),getOAuthConsents:pE(s),updateOAuthConsent:hE(s),deleteOAuthConsent:mE(s),adminCreateOAuthResource:SE(s),adminListOAuthResources:RE(s),adminGetOAuthResource:TE(s),adminUpdateOAuthResource:IE(s),adminDeleteOAuthResource:UE(s),adminLinkClientResource:CE(s),adminUnlinkClientResource:OE(s)},schema:mc(structuredClone(NE),s?.schema),rateLimit:[...s.rateLimit?.token!==!1?[{pathMatcher:(u)=>u==="/oauth2/token",window:s.rateLimit?.token?.window??60,max:s.rateLimit?.token?.max??20}]:[],...s.rateLimit?.authorize!==!1?[{pathMatcher:(u)=>u==="/oauth2/authorize",window:s.rateLimit?.authorize?.window??60,max:s.rateLimit?.authorize?.max??30}]:[],...s.rateLimit?.introspect!==!1?[{pathMatcher:(u)=>u==="/oauth2/introspect",window:s.rateLimit?.introspect?.window??60,max:s.rateLimit?.introspect?.max??100}]:[],...s.rateLimit?.revoke!==!1?[{pathMatcher:(u)=>u==="/oauth2/revoke",window:s.rateLimit?.revoke?.window??60,max:s.rateLimit?.revoke?.max??30}]:[],...s.rateLimit?.register!==!1?[{pathMatcher:(u)=>u==="/oauth2/register",window:s.rateLimit?.register?.window??60,max:s.rateLimit?.register?.max??5}]:[],...s.rateLimit?.rotateClientKeys!==!1?[{pathMatcher:(u)=>u==="/oauth2/client/rotate-keys",window:s.rateLimit?.rotateClientKeys?.window??60,max:s.rateLimit?.rotateClientKeys?.max??5}]:[],...s.rateLimit?.userinfo!==!1?[{pathMatcher:(u)=>u==="/oauth2/userinfo",window:s.rateLimit?.userinfo?.window??60,max:s.rateLimit?.userinfo?.max??60}]:[]]}};function jE(t,r,n){if(r===0)return!1;return n.getTime()-t.getTime()<=r*1000}function BE(t){let{max_age:r,...n}=t;return n}function Ve(t,r,n,o,i,s="query"){let a=new URLSearchParams({error:r,error_description:n});if(o&&a.append("state",o),i&&a.append("iss",i),s==="fragment")return`${t}#${a.toString()}`;return $e(t,a)}function $E(t){let r=typeof t.response_mode==="string"?t.response_mode:void 0;if(r==="fragment")return"fragment";if(r==="query")return"query";let n=typeof t.response_type==="string"?t.response_type:void 0;if(n&&/\b(token|id_token)\b/.test(n))return"fragment";return"query"}var ME={response_type:{invalid:"unsupported_response_type"},resource:{invalid:"invalid_target"}};function HE(t){return typeof t==="object"&&t!==null&&!Array.isArray(t)}function Ra(t){return typeof t==="string"?t:void 0}function VE(t,r){let n=t.method==="POST"&&r?.isAuthorize===!0?t.body:t.query;return{...HE(n)?n:{}}}var fe=(t,r)=>{let n=Ea(t.request?.headers),o=t.headers?.get("accept")?.includes("application/json");if(n||o)return{redirect:!0,url:r.toString()};else throw t.redirect(r)};function Or(t,r,n,o,i){return fe(t,Ve(n.redirect_uri,o,i,n.state,Qn(t,r)))}function Wh(t){try{let r=new URL(t);if(r.protocol!=="https:"&&!mr(r.host))r.protocol="https:";return r.search="",r.hash="",r.toString().replace(/\/$/,"")}catch{return t}}function Qn(t,r){let n;if(r.disableJwtPlugin)n=t.context.baseURL;else try{n=Oe(t.context).options?.jwt?.issuer??t.context.baseURL}catch{n=t.context.baseURL}return Wh(n)}function ir(t,r,n){return Ve(t.context.options.onAPIError?.errorURL||`${t.context.baseURL}/error`,r,n)}function lh(t){let r;try{r=new URL(t)}catch{return}let n=Fi(r.hostname)||r.hostname==="localhost";if(r.protocol!=="http:"||!n)return;let o=t.indexOf("://");if(o<0)return;let i=o+3,s=t.slice(i).search(/[/?#]/u),a=t.length;if(s>=0)a=i+s;let c=t.slice(i,a),d;if(c.startsWith("[")){let p=c.indexOf("]");if(p<0)return;if(c[p+1]!==":")return t;d=p+1}else if(d=c.lastIndexOf(":"),d<0)return t;let u=c.slice(d+1);if(!/^\d*$/u.test(u))return;let f=i+d;return`${t.slice(0,f)}${t.slice(a)}`}function Jh(t,r){if(!t||!r)return;let n;try{n=new URL(r)}catch{return}let o=r.includes("#"),i=n.username.length>0||n.password.length>0;if(o||i)return;let s=lh(r);return t.find((a)=>{if(a===r)return!0;if(!s)return!1;return lh(a)===s})}function Qh(t){if(!le.safeParse(t).success)return!1;let r=new URL(t);return r.username.length===0&&r.password.length===0}async function FE(t,r,n,o){if(!n||!o)return null;let i;try{i=await ke(t,r,n)}catch{return null}if(!i||i.disabled)return null;let s=i.redirectUris??[],a=Jh(s,o);if(r.validateRedirectUri){if(!Qh(o))return null;try{return await r.validateRedirectUri(o,s,Boolean(a))?o:null}catch{return null}}return a?o:null}function xt(t){return async({error:r,error_description:n,ctx:o})=>{let i=o.query??{},s=await FE(o,t,typeof i.client_id==="string"?i.client_id:void 0,typeof i.redirect_uri==="string"?i.redirect_uri:void 0);if(s)return fe(o,Ve(s,r,n,typeof i.state==="string"?i.state:void 0,Qn(o,t),$E(i)));return fe(o,ir(o,r,n))}}async function KE(t,r,n){if(r.grantTypes&&!r.grantTypes.includes("authorization_code"))throw new ce("NOT_FOUND");if(!t.request)throw new ce("UNAUTHORIZED",{error_description:"request not found",error:"invalid_request"});let o=t.request,i=VE(t,n);t.query=i;let s=Ra(i.request),a=Ra(i.request_uri);if(s!==void 0&&a!==void 0)return xt(r)({error:"invalid_request",error_description:"request and request_uri cannot be used together",ctx:t});if(s!==void 0)return xt(r)({error:"request_not_supported",error_description:"request object not supported",ctx:t});if(a!==void 0){let L=Ra(i.client_id);if(!L)return xt(r)({error:"invalid_request",error_description:"client_id is required",ctx:t});if(!r.requestUriResolver)return xt(r)({error:"request_uri_not_supported",error_description:"request_uri not supported",ctx:t});let x=await r.requestUriResolver({requestUri:a,clientId:L,ctx:t});if(!x)return xt(r)({error:"invalid_request_uri",error_description:"request_uri is invalid or expired",ctx:t});let P=i.client_id;if(i=x,P)i.client_id=P}t.query=i;let c=pa.safeParse(i);if(!c.success){let L=Ua(c.error.issues,ME);return xt(r)({...L,ctx:t})}if(i=c.data,t.query=i,await Nt.set({query:Gh(i).toString()}),!i.response_type)return xt(r)({error:"invalid_request",error_description:"response_type is required",ctx:t});let d=t.query?.prompt?ia(t.query?.prompt):void 0,u=d?.has("none")??!1;if(d?.has("select_account")&&!r.selectAccount?.page)return fe(t,ir(t,"unsupported_prompt_select_account","unsupported prompt type"));if(i.response_type!=="code")return fe(t,ir(t,"unsupported_response_type","unsupported response type"));let f=await ke(t,r,i.client_id);if(!f)return fe(t,ir(t,"invalid_client","client not found"));if(f.disabled)return fe(t,ir(t,"client_disabled","client is disabled"));if(!Un(f,"authorization_code"))return fe(t,ir(t,"unauthorized_client","client is not authorized to use the authorization_code grant"));let p=f.redirectUris??[],h=!1;if(i.redirect_uri){let L=Boolean(Jh(p,i.redirect_uri));if(r.validateRedirectUri&&Qh(i.redirect_uri))try{h=await r.validateRedirectUri(i.redirect_uri,p,L)}catch{h=!1}else if(!r.validateRedirectUri)h=L}if(!h)return fe(t,ir(t,"invalid_redirect","invalid redirect uri"));let m=i.scope?.split(" ").filter((L)=>L);if(m){let L=new Set(f.scopes??r.scopes),x=m.filter((P)=>!L?.has(P));if(x.length)return fe(t,Ve(i.redirect_uri,"invalid_scope",`The following scopes are invalid: ${x.join(", ")}`,i.state,Qn(t,r)))}if(!m)m=f.scopes??r.scopes??[],i.scope=m.join(" ");let w=m.includes("openid");if(i.claims!==void 0&&!w)return fe(t,Ve(i.redirect_uri,"invalid_request","openid scope must be requested when using the claims parameter",i.state,Qn(t,r)));if(w&&!kp(i.claims))return fe(t,Ve(i.redirect_uri,"invalid_request","claims must be a valid Claims request object",i.state,Qn(t,r)));if(w&&!Ep(i.claims,"0"))return fe(t,Ve(i.redirect_uri,"access_denied","essential acr requirement cannot be met",i.state,Qn(t,r)));let y=Dn(i.claims,Ln(r));if(i.resource!==void 0)try{await ma(t,r,{resource:i.resource,clientId:f.clientId,requestedScopes:m})}catch(L){if(L instanceof ce){let x=L.body?.error??"invalid_target",P=L.body?.error_description??"requested resource invalid";return fe(t,Ve(i.redirect_uri,x,P,i.state,Qn(t,r)))}throw L}let I=jo(f,{scopes:m,nonce:i.nonce});if(I){if(!i.code_challenge||!i.code_challenge_method)return fe(t,Ve(i.redirect_uri,"invalid_request",I.valueOf(),i.state,Qn(t,r)))}if(i.code_challenge||i.code_challenge_method){if(!i.code_challenge||!i.code_challenge_method)return fe(t,Ve(i.redirect_uri,"invalid_request","code_challenge and code_challenge_method must both be provided",i.state,Qn(t,r)));if(!["S256"].includes(i.code_challenge_method))return fe(t,Ve(i.redirect_uri,"invalid_request","invalid code_challenge method, only S256 is supported",i.state,Qn(t,r)))}let R=Ut(i.resource)??[],b=await ee(t),O=i.max_age,g=b!=null&&O!==void 0&&jE(new Date(b.session.createdAt),O,new Date);if(!b||b!=null&&O!==void 0&&!g||d?.has("login")||d?.has("create")){if(u)return Or(t,r,i,"login_required","authentication required");return Lt(t,r,d?.has("create")?"create":"login")}if(g)i=BE(i),t.query=i;if(n?.isAuthorize&&d?.has("select_account"))return Lt(t,r,"select_account");if(n?.isAuthorize&&r.selectAccount){if(await r.selectAccount.shouldRedirect({headers:o.headers,user:b.user,session:b.session,scopes:m})){if(u)return Or(t,r,i,"account_selection_required","End-User account selection is required");return Lt(t,r,"select_account")}}if(r.signup?.shouldRedirect){let L=await r.signup.shouldRedirect({headers:o.headers,user:b.user,session:b.session,scopes:m});if(L){if(u)return Or(t,r,i,"interaction_required","End-User interaction is required");return Lt(t,r,"create",{page:typeof L==="string"?L:void 0})}}if(!n?.postLogin&&r.postLogin){if(await r.postLogin.shouldRedirect({headers:o.headers,user:b.user,session:b.session,scopes:m,isContinuation:n?.isPostLoginContinuation??!1})){if(u)return Or(t,r,i,"interaction_required","End-User interaction is required");return Lt(t,r,"post_login")}}if(d?.has("consent"))return Lt(t,r,"consent",{sessionId:b.session.id});let S=await sa(r,{user:b.user,session:b.session,scopes:m});if(f.skipConsent)return fh(t,r,{query:i,clientId:f.clientId,userId:b.user.id,sessionId:b.session.id,authTime:new Date(b.session.createdAt).getTime(),referenceId:S,resource:R});let C=await aa(t,f.clientId,b.user.id,S);if(!C||!m.every((L)=>C.scopes.includes(L))||!y.every((L)=>(C.requestedUserInfoClaims??[]).includes(L))){if(u)return Or(t,r,i,"consent_required","End-User consent is required");return Lt(t,r,"consent",{sessionId:b.session.id})}let z=C?.resources??[];if(R.some((L)=>!z.includes(L))){if(u)return Or(t,r,i,"consent_required","End-User consent is required");return Lt(t,r,"consent",{sessionId:b.session.id})}return fh(t,r,{query:i,clientId:f.clientId,userId:b.user.id,sessionId:b.session.id,authTime:new Date(b.session.createdAt).getTime(),referenceId:S,resource:R})}function Gh(t){let r=new URLSearchParams;for(let[n,o]of Object.entries(t)){if(o==null)continue;if(Array.isArray(o))for(let i of o)r.append(n,String(i));else if(n==="claims"&&typeof o==="object")r.set(n,JSON.stringify(o));else r.set(n,String(o))}return r}async function fh(t,r,n){let o=_e(32,"a-z","A-Z","0-9"),i=Math.floor(Date.now()/1000),s=i+(r.codeExpiresIn??600),a={identifier:await er(r.storeTokens,o,"authorization_code"),updatedAt:new Date(i*1000),expiresAt:new Date(s*1000),value:JSON.stringify({type:"authorization_code",query:n.query,userId:n.userId,sessionId:n?.sessionId,referenceId:n.referenceId,authTime:n.authTime,resource:n.resource})};await t.context.internalAdapter.createVerificationValue({...a,createdAt:new Date(i*1000)});let c=new URL(n.query.redirect_uri);if(c.searchParams.set("code",o),n.query.state)c.searchParams.set("state",n.query.state);return c.searchParams.set("iss",Qn(t,r)),fe(t,c.toString())}async function Lt(t,r,n,o){let i=await WE(t,r,{postLoginClearedForSession:n==="consent"&&r.postLogin?o?.sessionId:void 0}),s=r.loginPage;if(n==="select_account")s=r.selectAccount?.page??r.loginPage;else if(n==="post_login"){if(!r.postLogin?.page)throw new ce("INTERNAL_SERVER_ERROR",{error_description:"postLogin should have been defined"});s=r.postLogin?.page}else if(n==="consent")s=r.consentPage;else if(n==="create")s=r.signup?.page??r.loginPage;return fe(t,`${o?.page??s}?${i}`)}async function WE(t,r,n){let o=Date.now(),i=Math.floor(o/1000)+(r.codeExpiresIn??600),s=Gh(t.query);if(s.set("exp",String(i)),s.set(Ms,String(o)),s.delete("sig"),s.delete(Oo),n?.postLoginClearedForSession)s.set(Oo,n.postLoginClearedForSession);Jf(s);let a=await on(Do(s).toString(),t.context.secret);return s.set("sig",a),s.toString()}export{Ae,ym,Hs,Ai,ls,lf,cf,pc,mc,hc,Zu,uf,cs,Bu,vm,$g,gc,Uu,Hg,Qg,zu,df,ff,ju,Gg,Br,Cn,Pe,$r,Me,za,Ac,bm,qu,wm,Em,Vg,xm,Kg,vs,_i,_c,Ki,Wi,pf,zy,Wg,mf,gl,nP,oP,sP,Jg,jy,iP,hf,Qn,Qs};
393
+ `)}}function Sm(t,r){let n=ds(r),o=r.plugins?.reduce((s,a)=>({...s,...a.endpoints}),{})??{},i=r.plugins?.map((s)=>s.middlewares?.map((a)=>{let c=async(d)=>{let u=await t;return n(`middleware ${a.path} ${s.id}`,{[pn]:"middleware",[Ha]:a.path,[mn]:`plugin:${s.id}`},()=>a.middleware({...d,context:{...u,...d.context}}))};return c.options=a.middleware.options,{path:a.path,middleware:c}})).filter((s)=>s!==void 0).flat()||[];return{api:Ff({signInSocial:Uf(),callbackOAuth:nf,getSession:rs(),signOut:Lf,signUpEmail:Pf(),signInEmail:Of(),resetPassword:Ef,verifyPassword:bf,verifyEmail:iu,sendVerificationEmail:ou,changeEmail:$f,changePassword:qf,setPassword:jf,updateSession:zf(),updateUser:Nf(),deleteUser:Bf,requestPasswordReset:wf,requestPasswordResetCallback:kf,listSessions:Id(),revokeSession:Ud,revokeSessions:Cd,revokeOtherSessions:Od,linkSocialAccount:Ql,listUserAccounts:Jl,deleteUserCallback:Bs,unlinkAccount:Gl,refreshToken:ef,getAccessToken:Xl,accountInfo:tf,...o,ok:af,error:sf},t),middlewares:i}}var Jg=(t,r)=>{let n=ds(r),{api:o,middlewares:i}=Sm(t,r),s=new URL(t.baseURL).pathname;return Ci(o,{routerContext:t,openapi:{disabled:!0},basePath:s,routerMiddleware:[{path:"/**",middleware:kd},...i],allowedMediaTypes:["application/json"],skipTrailingSlashes:r.advanced?.skipTrailingSlashes??!1,async onRequest(a){let c=t.options.disabledPaths||[],d=gr(a.url,s);if(c.includes(d))return new Response("Not Found",{status:404});let u=t.checkSchema?.();if(u)await u;let f=a,p=await Sd(f,t);if(p)return p;for(let h of t.options.plugins||[])if(h.onRequest){let m=await n(`onRequest ${h.id}`,{[pn]:"onRequest",[mn]:`plugin:${h.id}`},()=>h.onRequest(f,t));if(m&&"response"in m)return m.response;if(m&&"request"in m)f=m.request}return f},async onResponse(a,c){for(let d of t.options.plugins||[])if(d.onResponse){let u=await n(`onResponse ${d.id}`,{[pn]:"onResponse",[mn]:`plugin:${d.id}`,[id]:a.status},()=>d.onResponse(a,t));if(u)return u.response}return a},async onError(a){if(Ur(a)&&a.status==="FOUND")return;if(r.onAPIError?.throw)throw a;if(r.onAPIError?.onError){try{await r.onAPIError.onError(a,t)}catch(u){t.logger.error("onAPIError.onError threw",u)}return}let c=r.logger?.level,d=c==="error"||c==="warn"||c==="debug"?Ee:void 0;if(r.logger?.disabled!==!0){if(a&&typeof a==="object"&&"message"in a&&typeof a.message==="string"){if(a.message.includes("no column")||a.message.includes("column")||a.message.includes("relation")||a.message.includes("table")||a.message.includes("does not exist")){t.logger?.error(a.message);return}}if(Ur(a)){if(a.status==="INTERNAL_SERVER_ERROR")t.logger.error(a.status,a);d?.error(a.message)}else t.logger?.error(a&&typeof a==="object"&&"name"in a?a.name:"",a)}}})};function vs(t){return t?.jwks?.keyPairConfig?.alg??"EdDSA"}var _i=(t,r)=>({getAllKeys:async(n)=>{if(r?.adapter?.getJwks)return await r.adapter.getJwks(n);return await(await X(t)).findMany({model:"jwks"})},getLatestKey:async(n)=>{let o=new Date,i=(s)=>!s.expiresAt||s.expiresAt>o;if(r?.adapter?.getJwks)return(await r.adapter.getJwks(n))?.filter(i).sort((s,a)=>a.createdAt.getTime()-s.createdAt.getTime())[0];return(await(await X(t)).findMany({model:"jwks"}))?.filter(i).sort((s,a)=>a.createdAt.getTime()-s.createdAt.getTime())[0]},getKeyById:async(n,o)=>{if(r?.adapter?.getJwks)return(await r.adapter.getJwks(n))?.find((i)=>i.id===o);return await(await X(t)).findOne({model:"jwks",where:[{field:"id",value:o}]})??void 0},getLatestKeyByAlg:async(n,o)=>{let i=r?.adapter?.getJwks?await r.adapter.getJwks(n):await(await X(t)).findMany({model:"jwks"});if(!i)return;let s=vs(r),a=new Date;return i.filter((c)=>c.alg===o||c.alg==null&&s===o).filter((c)=>!c.expiresAt||c.expiresAt>a).sort((c,d)=>d.createdAt.getTime()-c.createdAt.getTime())[0]},createJwk:async(n,o)=>{if(r?.adapter?.createJwk)return await r.adapter.createJwk(o,n);return await(await X(t)).create({model:"jwks",data:{...o,createdAt:new Date}})}});function Yt(t,r){if(typeof t==="number")return t;else if(t instanceof Date)return Math.floor(t.getTime()/1000);else return r+Wn(t)}async function Kf(t){let{alg:r,...n}=t?.jwks?.keyPairConfig??{alg:"EdDSA",crv:"Ed25519"},{publicKey:o,privateKey:i}=await _f(r,{...n,extractable:!0});return{publicWebKey:await bl(o),privateWebKey:await bl(i),alg:r,cfg:n}}async function yc(t,r){let{publicWebKey:n,privateWebKey:o,alg:i,cfg:s}=await Kf(r),a=s&&"crv"in s?s.crv:void 0,c=typeof n.crv==="string"?n.crv:void 0,d=a??c,u=JSON.stringify(o),f=!r?.jwks?.disablePrivateKeyEncryption,p={alg:i,...d?{crv:d}:{},publicKey:JSON.stringify(n),privateKey:f?JSON.stringify(await nt({key:t.context.secretConfig,data:u})):u,createdAt:new Date,...r?.jwks?.rotationInterval?{expiresAt:new Date(Date.now()+r.jwks.rotationInterval*1000)}:{}};return await _i(t.context.adapter,r).createJwk(t,p)}async function Ki(t,r,n){if(r?.jwt?.sign)return null;let o=_i(t.context.adapter,r),i;if(n?.signingKeyId!==void 0){if(i=await o.getKeyById(t,n.signingKeyId),!i)throw new te(`signJWT: signingKeyId "${n.signingKeyId}" not found in JWKS. The key must be provisioned before it can be referenced.`);if(n.signingAlgorithm!==void 0){let d=vs(r);if((i.alg??d)!==n.signingAlgorithm)throw new te(`signJWT: signingKeyId "${n.signingKeyId}" has alg "${i.alg??`unset (inherits keyPairConfig.alg "${d}")`}" but signingAlgorithm was set to "${n.signingAlgorithm}".`)}}else if(n?.signingAlgorithm!==void 0){if(i=await o.getLatestKeyByAlg(t,n.signingAlgorithm),!i){let d=vs(r),u=r?.jwks?.keyPairConfigs?.find((p)=>p.alg===n.signingAlgorithm),f=d===n.signingAlgorithm;if(u||f)i=await yc(t,{...r,jwks:{...r?.jwks,keyPairConfig:u??r?.jwks?.keyPairConfig}});else{let p=r?.jwks?.keyPairConfigs?.map((h)=>h.alg).join(", ")||"none";throw new te(`signJWT: no key with alg "${n.signingAlgorithm}" found in JWKS. The plugin auto-mints only one key matching keyPairConfig.alg="${d}"; additional algs configured via keyPairConfigs: ${p}. Add "${n.signingAlgorithm}" to jwks.keyPairConfigs so the plugin provisions it on first use, or mint the key explicitly via createJwk().`)}}}else{let d=vs(r);i=await o.getLatestKeyByAlg(t,d)??await o.getLatestKey(t)}if(!i||i.expiresAt&&i.expiresAt<new Date){if(n?.signingKeyId!==void 0||n?.signingAlgorithm!==void 0)throw new te("signJWT: requested signing key is expired and an explicit kid/alg was provided; not auto-minting a replacement. Rotate the key explicitly.");i=await yc(t,r)}let s=!r?.jwks?.disablePrivateKeyEncryption?await ot({key:t.context.secretConfig,data:JSON.parse(i.privateKey)}).catch(()=>{throw new te("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.")}):i.privateKey,a=i.alg??vs(r),c=await In(JSON.parse(s),a);return{alg:a,kid:i.id,privateKey:c}}async function Wi(t,r){let{options:n}=r,o=r.payload,i=Math.floor(Date.now()/1000),{iat:s,exp:a}=o,c=Yt(n?.jwt?.expirationTime??"15m",s??i);a=a??c;let d=o.nbf,u=typeof t.context.options.baseURL==="string"?t.context.options.baseURL:"",f=o.iss,p=n?.jwt?.issuer??u,h=o.aud,m=n?.jwt?.audience??u;if(!(f??p)||!(h??m))t.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.");if(n?.jwt?.sign){let b={...o,iat:s,exp:a,nbf:d,iss:f??p,aud:h??m};return n.jwt.sign(b,r.header,{signingKeyId:r.signingKeyId,signingAlgorithm:r.signingAlgorithm})}let{alg:w,kid:y,privateKey:I}=r.resolvedKey??await Ki(t,n,{signingKeyId:r.signingKeyId,signingAlgorithm:r.signingAlgorithm}),R=new bs(o).setProtectedHeader({...r.header,alg:w,kid:y}).setExpirationTime(a).setIssuer(f??p).setAudience(h??m);if(s)R.setIssuedAt(s);if(o.sub)R.setSubject(o.sub);if(o.nbf)R.setNotBefore(o.nbf);if(o.jti)R.setJti(o.jti);return await R.sign(I)}async function mf(t,r){let n=!r?.jwt?.definePayload?t.context.session.user:await r.jwt.definePayload(t.context.session);return await Wi(t,{options:r,payload:{iat:Math.floor(Date.now()/1000),...n,sub:await r?.jwt?.getSubject?.(t.context.session)??t.context.session.user.id}})}var Wf=Object.defineProperty,Co=(t,r)=>{let n={};for(var o in t)Wf(n,o,{get:t[o],enumerable:!0});if(!r)Wf(n,Symbol.toStringTag,{value:"Module"});return n};var Ms="ba_iat",Oo="ba_pl";function Do(t){let r=new URLSearchParams,n=[...t.entries()].sort(([o,i],[s,a])=>{if(o<s)return-1;if(o>s)return 1;if(i<a)return-1;if(i>a)return 1;return 0});for(let[o,i]of n)r.append(o,i);return r}function Jf(t){t.delete("ba_param");let r=[...new Set([...t.keys(),"ba_param"])].sort();for(let n of r)t.append("ba_param",n)}function Qf(t){let r=new URLSearchParams(t).get("ba_iat");if(!r)return null;let n=Number(r);if(!Number.isFinite(n)||n<=0)return null;return new Date(n)}var Wy=["authorization_code","client_credentials","refresh_token"],Zf=["client_secret_basic","client_secret_post","private_key_jwt"],Jy=["none",...Zf],Qy=new Set(Jy);function Js(t,r){if(r.trim().length>0)return;throw new te(`OAuth Provider extension ${t} cannot be empty`)}function Yf(t,r){Js(t,r);let n;try{n=new URL(r)}catch{n=void 0}if(n?.protocol)return;throw new te(`OAuth Provider extension ${t} must be an absolute URI: ${r}`)}function Zy(t){Yf("grant type",t)}function Yy(t){if(Js("token_endpoint_auth_method",t),!Qy.has(t))return;throw new te(`OAuth Provider extension token_endpoint_auth_method is reserved: ${t}`)}function Xy(t){if(Yf("client_assertion_type",t),t!==Wt)return;throw new te(`OAuth Provider extension client_assertion_type is reserved: ${t}`)}function e_(t){let r=Object.keys(t.grants??{});for(let s of r)Zy(s);let n=[],o=[];for(let[s,a]of Object.entries(t.clientAuthentication??{})){Yy(s),n.push(s);let c=a.assertionTypes??[s];if(c.length===0)throw new te(`OAuth Provider extension client_assertion_type list cannot be empty for ${s}`);for(let d of c)Xy(d),o.push(d)}let i=(t.clientDiscovery?Array.isArray(t.clientDiscovery)?t.clientDiscovery:[t.clientDiscovery]:[]).map((s)=>s.id);for(let s of i)Js("client discovery id",s);return{grantTypes:r,authMethods:n,assertionTypes:o,clientDiscoveryIds:i}}function Lo(t,r){let n=new Set;for(let o of r){if(n.has(o))throw new te(`OAuth Provider extensions register ${t} "${o}" more than once. Extension contributions must be disjoint.`);n.add(o)}}function Xf(t){let r=(t??[]).map(e_);Lo("grant type",r.flatMap((n)=>n.grantTypes)),Lo("token_endpoint_auth_method",r.flatMap((n)=>n.authMethods)),Lo("client_assertion_type",r.flatMap((n)=>n.assertionTypes)),Lo("client discovery id",r.flatMap((n)=>n.clientDiscoveryIds))}function It(t){return t.extensions??[]}function Rn(t){return It(t).flatMap((r)=>{let n=r.clientDiscovery;if(!n)return[];return Array.isArray(n)?n:[n]})}function t_(t){return It(t).flatMap((r)=>Object.keys(r.grants??{}))}function Rr(t){return Array.from(new Set([...t.grantTypes??Wy,...t_(t)]))}function ep(t,r){for(let n of It(t)){let o=n.grants?.[r];if(o)return o}}function tp(t){return It(t).flatMap((r)=>Object.keys(r.clientAuthentication??{}))}function Po(t,r){return Array.from(new Set([...r?.includeNone?["none"]:[],...Zf,...tp(t)]))}function Gs(t,r){return r?tp(t).includes(r):!1}function r_(t,r){if(r===Wt)return;for(let n of It(t)){let o=n.clientAuthentication??{};for(let[i,s]of Object.entries(o))if((s.assertionTypes??[i]).includes(r))return{method:i,strategy:s}}}function Zs(t,r,n,o){let i={...o};for(let s of It(r)){let a=s.metadata?.({ctx:t,opts:r,type:n,document:o});for(let[c,d]of Object.entries(a??{}))if(!(c in i))i[c]=d}return i}async function Ys(t,r){let n={};for(let o of It(t)){let i=await r(o)??{};for(let[s,a]of Object.entries(i)){if(s in n){Ee.warn(`oauth-provider: two extensions contributed the claim "${s}"; keeping the first-registered value.`);continue}n[s]=a}}return n}function rp(t,r){return Ys(t,(n)=>n.claims?.accessToken?.(r))}function np(t,r){return Ys(t,(n)=>n.claims?.idToken?.(r))}function op(t,r){return Ys(t,(n)=>n.claims?.userInfo?.(r))}function ip(t){return It(t).some((r)=>r.claims?.userInfo)}function sp(t){if(!t)return;let[r,n,...o]=t.trim().split(/\s+/);if(r?.toLowerCase()!=="bearer")return;if(!n||o.length>0)throw new ce("BAD_REQUEST",{error:"invalid_request",error_description:"Malformed Bearer Authorization header"});return n}function n_(){let t=new Map;return{get(r){let n=t.get(r);if(!n)return;if(n.expiresAt&&n.expiresAt<new Date){t.delete(r);return}return n},set(r,n){t.set(r,n)}}}var Oe=(t)=>{let r=t.getPlugin("jwt");if(!r)throw new te("jwt_config");return r},o_=new Set([vl.code,_l.code,vc.code]);function xo(t){return t instanceof dn&&!o_.has(t.code)}function st(t){if(t==null)return;if(t instanceof Date)return Number.isFinite(t.getTime())?t:void 0;if(typeof t==="number"){if(!Number.isFinite(t))return;let r=new Date(t);return Number.isFinite(r.getTime())?r:void 0}if(typeof t==="string"){let r=t.trim();if(!r.length)return;let n=Number(r);if(Number.isFinite(n)){let i=new Date(n);return Number.isFinite(i.getTime())?i:void 0}let o=new Date(r);return Number.isFinite(o.getTime())?o:void 0}}function ap(t){if(t instanceof Date)return st(t);if(!t||typeof t!=="object")return st(t);let r=st(t.createdAt)??st(t.created_at);if(r)return r;let n=t.session;if(!n||typeof n!=="object")return;return st(n.createdAt)??st(n.created_at)}function Ut(t){if(typeof t==="string")return[t];if(!t?.length)return;return t}function Xs(t){if(typeof t==="string")return t;if(!t?.length)return;return t.length===1?t.at(0):t}var Gf=new WeakMap;function i_(t){let r=Gf.get(t);if(r)return r;let n=n_();return Gf.set(t,n),n}async function ra(t,r){let n=new URLSearchParams(t),o=n.get("sig"),i=n.getAll("sig"),s=Number(n.get("exp"));n.delete("sig");let a=await on(Do(n).toString(),r);return i.length===1&&!!o&&Vt(o,a)&&new Date(s*1000)>=new Date}function Un(t,r){if(t.cachedTrustedClients?.has(r))throw new ce("BAD_REQUEST",{error:"invalid_client",error_description:"trusted clients must be updated manually"})}async function ke(t,r,n){let o=i_(r),i=o.get(n);if(i&&!i.clientDiscoveryId)return Object.assign({},i);let s=await t.context.adapter.findOne({model:r.schema?.oauthClient?.modelName??"oauthClient",where:[{field:"clientId",value:n}]}),a=Rn(r);if(s?.clientDiscoveryId){let c=s.clientDiscoveryId,d=a.find((u)=>u.id===c);if(!d?.matches(n))return null;if(s=await d.resolve(t,n,s),!s)return null}else if(s){if(r.cachedTrustedClients?.has(n))o.set(n,Object.assign({},s));return s}else for(let c of a){if(!c.matches(n))continue;let d=await c.resolve(t,n,null);if(d){s=d;break}}return s}function oa(t){return t.reduce((r,n)=>({...r,...n.discoveryMetadata??{}}),{})}var zo=async(t)=>{let r=await cs("SHA-256").digest(new TextEncoder().encode(t));return ko.encode(new Uint8Array(r),{padding:!1})};async function Sr(t,r,n){if(r==="encrypted")return await ot({key:t.context.secretConfig,data:n});else if(typeof r==="object"&&"decrypt"in r)return await r.decrypt(n);throw new te(`Unsupported decryption storageMethod type '${r}'`)}async function s_(t,r,n,o){let i=r.storeClientSecret??(r.disableJwtPlugin?"encrypted":"hashed");if(o&&r.prefix?.clientSecret)if(o.startsWith(r.prefix?.clientSecret))o=o.replace(r.prefix.clientSecret,"");else throw new ce("UNAUTHORIZED",{error_description:"invalid client_secret",error:"invalid_client"});if(i==="hashed"){let s=o?await zo(o):void 0;return!!s&&Vt(s,n)}else if(typeof i==="object"&&"hash"in i)if(i.verify)return!!o&&await i.verify(o,n);else{let s=o?await i.hash(o):void 0;return!!s&&Vt(s,n)}else if(i==="encrypted")try{let s=await Sr(t,i,n);return!!o&&Vt(s,o)}catch{return!1}else if(typeof i==="object"&&"decrypt"in i){let s=await Sr(t,i,n);return!!o&&Vt(s,o)}throw new te(`Unsupported verify storageMethod type '${i}'`)}async function No(t,r,n){let o=r.storeClientSecret??(r.disableJwtPlugin?"encrypted":"hashed");if(o==="encrypted")return await nt({key:t.context.secretConfig,data:n});else if(o==="hashed")return await zo(n);else if(typeof o==="object"&&"hash"in o)return await o.hash(n);else if(typeof o==="object"&&"encrypt"in o)return await o.encrypt(n);throw new te(`Unsupported storeClientSecret type '${o}'`)}async function er(t="hashed",r,n){if(t==="hashed")return await zo(r);else if(typeof t==="object"&&"hash"in t)return await t.hash(r,n);throw new te(`storeToken: unsupported storageMethod type '${t}'`)}async function tr(t="hashed",r,n){if(t==="hashed")return await zo(r);else if(typeof t==="object"&&"hash"in t)return await t.hash(r,n);throw new te(`getStoredToken: unsupported storageMethod type '${t}'`)}var Ws=/^Basic +/i,a_=/^([!#$%&'*+\-.^_`|~0-9A-Za-z]+)(?=\s|$)/;function c_(t){return t.match(a_)?.[1]}var Fs=["client_secret","client_assertion","client_assertion_type"];function vn(t){throw new ce("BAD_REQUEST",{error:"invalid_request",error_description:t})}async function d_(t,r={}){let n;if(r.client_id!==void 0&&r.client_id!==""){if(typeof r.client_id!=="string")vn("client_id must be a string");n=r.client_id}let o={},i=(u,f)=>{if(f===void 0||f==="")return;if(typeof f!=="string")vn(`${u} must be a string`);o[u]=f};for(let u of Fs)if(Object.hasOwn(r,u))i(u,r[u]);let s=t?.headers.get("authorization"),a=Boolean(s);if(t){if((t.headers.get("content-type")?.toLowerCase()??"").includes("application/x-www-form-urlencoded")){let u=new URLSearchParams(await t.clone().text()),f=u.getAll("client_id").filter((p)=>p.length>0);if(f.length>1)vn("client_id must not be repeated");n=f[0];for(let p of Fs){let h=u.getAll(p).filter((m)=>m.length>0);if(h.length>1)vn(`${p} must not be repeated`);if(h.length===1)i(p,h[0])}}}let c=o.client_secret!==void 0,d=o.client_assertion!==void 0||o.client_assertion_type!==void 0;if(a&&(c||d)||c&&d)vn("A request must use only one client authentication method");r.client_id=n;for(let u of Fs)r[u]=o[u];return{detected:a||Object.keys(o).length>0}}function u_(t){if(!Ws.test(t))return;try{let{clientId:r,clientSecret:n}=_s(t);return{client_id:r,client_secret:n}}catch{throw new ce("UNAUTHORIZED",{error_description:"invalid authorization header format",error:"invalid_client"},{"WWW-Authenticate":"Basic"})}}function Cn(t,r){let n=t.grantTypes&&t.grantTypes.length>0?t.grantTypes:["authorization_code"];if(r==="refresh_token"&&n.includes("authorization_code"))return!0;return n.includes(r)}function qo(t,r){if(!r||!t.scopes)return;let n=new Set(t.scopes);for(let o of r)if(!n.has(o))throw new ce("BAD_REQUEST",{error_description:`client does not allow scope ${o}`,error:"invalid_scope"})}function Xt(t,r){let n=r?.method==="client_secret_basic",o=r?.scheme??(n?"Basic":void 0);throw new ce(o?"UNAUTHORIZED":"BAD_REQUEST",{error_description:t,error:"invalid_client"},o?{"WWW-Authenticate":o}:void 0)}async function Ct(t,r,n,o,i,s,a,c){let d=await ke(t,r,n);if(!d)Xt("client not found",{method:c});if(d.disabled)Xt("client is disabled",{method:c});let u=d.tokenEndpointAuthMethod??"client_secret_basic";if(c&&u!==c)Xt(`client registered for ${u} cannot use ${c}`,{method:c});if((d.tokenEndpointAuthMethod==="private_key_jwt"||Gs(r,d.tokenEndpointAuthMethod))&&!s)throw new ce("BAD_REQUEST",{error_description:`client registered for ${d.tokenEndpointAuthMethod} must use client_assertion`,error:"invalid_client"});if(!s){if(d.tokenEndpointAuthMethod!=="none"&&!o)Xt("client secret must be provided",{method:c});if(o&&!d.clientSecret)Xt("public client, client secret should not be received",{method:c});if(o&&!await s_(t,r,d.clientSecret,o))Xt("invalid client_secret",{method:c})}if(qo(d,i),a&&!Cn(d,a))throw new ce("BAD_REQUEST",{error_description:`client is not authorized to use grant type ${a}`,error:"unauthorized_client"});return d}function rr(t){if(!t)return;return typeof t==="string"?JSON.parse(t):t}function Ot(t){return{clientId:t?.clientId,clientSecret:t?.kind==="client_secret"?t.clientSecret:void 0,preVerified:t?.kind==="pre_verified",authMethod:t?.method,confirmation:t?.kind==="pre_verified"?t.confirmation:void 0}}async function Dt(t,r,n){let o={...t.body??{}};await d_(t.request,o);let i=t.request?.headers.get("authorization")??void 0;if(o.client_assertion_type||o.client_assertion){if(!o.client_assertion||!o.client_assertion_type)throw new ce("BAD_REQUEST",{error_description:"client_assertion and client_assertion_type must both be provided",error:"invalid_client"});let{client_assertion:s,client_assertion_type:a}=o,c=r_(r,a);if(c){let u=await c.strategy.authenticate({ctx:t,opts:r,assertion:s,assertionType:a,clientId:o.client_id,expectedAudience:n});return{kind:"pre_verified",method:c.method,clientId:u.clientId,confirmation:u.confirmation}}let{verifyClientAssertion:d}=await import("./chunk-8ww98y1m.js").then((u)=>u.o);return{kind:"pre_verified",method:"private_key_jwt",clientId:(await d(t,r,s,a,o.client_id,n)).clientId}}if(i&&!Ws.test(i)){let s=c_(i);if(!s)throw new ce("BAD_REQUEST",{error:"invalid_request",error_description:"Invalid authorization header format"});Xt("unsupported authorization scheme",{scheme:s})}if(i&&Ws.test(i)){let s=u_(i);if(s)return{kind:"client_secret",method:"client_secret_basic",clientId:s.client_id,clientSecret:s.client_secret}}if(o.client_id&&o.client_secret)return{kind:"client_secret",method:"client_secret_post",clientId:o.client_id,clientSecret:o.client_secret};if(o.client_id)return{kind:"public",method:"none",clientId:o.client_id};return null}function ia(t){let r=t.split(" ").map((o)=>o.trim()),n=new Set;for(let o of r)if(o==="login"||o==="consent"||o==="create"||o==="select_account"||o==="none")n.add(o);return new Set(n)}function l_(t){let r=t.redirectUris?.[0];if(!r)throw new te("Client has no redirect URIs for sector identifier");return new URL(r).host}async function f_(t,r,n){return on(`${l_(r)}.${t}`,n)}async function Tr(t,r,n){if(r.subjectType==="pairwise"&&n.pairwiseSecret)return f_(t,r,n.pairwiseSecret);return t}async function sa(t,r){return await t.postLogin?.consentReferenceId?.(r)||void 0}async function aa(t,r,n,o){let i=[{field:"clientId",value:r},{field:"userId",value:n}];if(o)return t.context.adapter.findOne({model:"oauthConsent",where:[...i,{field:"referenceId",value:o}]});let s=100;for(let a=0;;a+=s){let c=await t.context.adapter.findMany({model:"oauthConsent",where:i,limit:s,offset:a,sortBy:{field:"id",direction:"asc"}}),d=c.find((u)=>!u.referenceId);if(d||c.length<s)return d??null}}function nr(t){let r=Object.create(null);for(let n of new Set(t.keys())){let o=t.getAll(n);r[n]=o.length===1?o[0]:o}return r}function ca(t,r){if(!r)return!1;let n=st(t);if(!n)return!1;return n.getTime()>=r.getTime()}function Ir(t,r){let n=new URLSearchParams(t),o=n.get("prompt")?.split(" "),i=o?.findIndex((s)=>s===r)??-1;if(i>=0)o?.splice(i,1),o?.length?n.set("prompt",o.join(" ")):n.delete("prompt");return n}function da(t){let r=new URLSearchParams(t);return r.delete("max_age"),r}function jo(t,r){if(t.tokenEndpointAuthMethod==="none")return"pkce is required for public clients";let n=r?.scopes??[],o=n.includes("openid"),i=typeof r?.nonce==="string"&&r.nonce.length>0,s=o&&i;if(n.includes("offline_access")&&!s)return"pkce or OIDC nonce is required when requesting offline_access scope";if(t.requirePKCE??!0)return"pkce is required for this client";return!1}var p_=/^[a-z](?:[a-z0-9-]*[a-z0-9])?(?:\.[a-z0-9](?:[a-z0-9-]*[a-z0-9])?)+$/i,h_=new Set(["http:","https:","ws:","wss:","file:","ftp:","mailto:","javascript:","data:","vbscript:","blob:","about:","view-source:"]);function m_(t){let r=t.protocol.slice(0,-1),n=t.href.slice(t.protocol.length);return t.protocol!=="http:"&&t.protocol!=="https:"&&t.host.length===0&&n.startsWith("/")&&!n.startsWith("//")&&p_.test(r)}function g_(t){if(h_.has(t.protocol))return!1;if(t.host.length===0)return!1;return t.pathname.startsWith("/")}function cp(t){return m_(t)||g_(t)}var le=Vo().superRefine((t,r)=>{let n;try{n=new URL(t)}catch{return r.addIssue({code:"custom",message:"URL must be parseable",fatal:!0}),Pr}if(yd.includes(n.protocol)){r.addIssue({code:"custom",message:"URL cannot use javascript:, data:, or vbscript: scheme"});return}if(t.includes("#"))r.addIssue({code:"custom",message:"Redirect URI must not contain a fragment component"});if(n.protocol==="http:"&&!hr(n.host))r.addIssue({code:"custom",message:"Redirect URI must use HTTPS (HTTP allowed only for loopback hosts)"})});var w_=new Set(["iss","sub","aud","exp","nbf","iat","jti","auth_time","nonce","acr","amr","azp","sid","at_hash","c_hash","s_hash"]);function dp(t){if(!t)return{};let r=[],n=Object.create(null);for(let[o,i]of Object.entries(t)){if(w_.has(o)){r.push(o);continue}n[o]=i}if(r.length>0)Ee.warn(`oauth-provider: stripped reserved id-token claim name(s): ${r.join(", ")}. The AS owns these claim values.`);return n}var _p=k(e(),J()).nullable(),y_=oe({essential:E().optional(),value:e().optional(),values:A(e()).optional()}).nullable(),__=l({acr:y_.optional()}).catchall(_p),A_=oe({userinfo:k(e(),_p).optional(),id_token:__.optional()});function k_(t){if(typeof t==="string")try{return JSON.parse(t)}catch{return}return t}function On(t){let r=k_(t),n=A_.safeParse(r);return n.success?n.data:void 0}var Ap=D([e(),k(e(),J())]),E_=Ap,la=Ap.refine((t)=>On(t)!==void 0,{error:"claims must be a valid Claims request object"});function kp(t){return t===void 0||On(t)!==void 0}function Dn(t,r){let n=On(t)?.userinfo;if(!n)return[];let o=Object.keys(n);if(!r)return o;let i=new Set(r);return o.filter((s)=>i.has(s))}function Ep(t,r){let n=On(t);if(!n)return t===void 0;let o=n.id_token?.acr;if(!o||o.essential!==!0)return!0;let i=o.value===void 0||o.value===r,s=o.values===void 0||o.values.includes(r);return i&&s}function bp(t,r){let n=On(t);if(!n)return;let o=new Set(r),i=Object.fromEntries(Object.entries(n.userinfo??{}).filter(([a])=>o.has(a))),s=Object.keys(i).length?{...n,userinfo:i}:Object.fromEntries(Object.entries(n).filter(([a])=>a!=="userinfo"));return Object.keys(s).length?s:void 0}function up(t){let r=t.split(" ").filter((n)=>n!=="");if(r.length<=1)return{};return{given:r.slice(0,-1).join(" "),family:r.at(-1)}}var Mo={name:{scope:"profile",resolve:(t)=>t.name??void 0},picture:{scope:"profile",resolve:(t)=>t.image??void 0},given_name:{scope:"profile",resolve:(t)=>up(t.name).given},family_name:{scope:"profile",resolve:(t)=>up(t.name).family},email:{scope:"email",resolve:(t)=>t.email??void 0},email_verified:{scope:"email",resolve:(t)=>t.emailVerified??!1}},fa=Object.keys(Mo);function Ln(t){return t.advertisedMetadata?.claims_supported??t.claims??[]}var b_=new Set(["iss","sub","aud","exp","iat","jti","client_id","scope","auth_time","acr","amr","cnf"]);function v_(t){if(!t)return{};let r=[],n={};for(let[o,i]of Object.entries(t)){if(b_.has(o)){r.push(o);continue}n[o]=i}if(r.length>0)Ee.warn(`oauth-provider: stripped reserved access-token claim name(s): ${r.join(", ")}. The AS owns these claim values.`);return n}async function vp(t){let{ctx:r,opts:n,user:o,client:i,scopes:s,resources:a,referenceId:c,metadata:d,grantType:u,sessionId:f,perRequestClaims:p,resourcePolicyClaims:h}=t,m=await rp(n,{ctx:r,opts:n,user:o,client:i,scopes:s,grantType:u,referenceId:c,sessionId:f,resources:a,metadata:d}),w=n.customAccessTokenClaims?await n.customAccessTokenClaims({user:o,scopes:s,resources:a,referenceId:c,metadata:d}):{};return v_({...m,...p??{},...w,...h})}var S_=["javascript:","data:","vbscript:"],Qs=e().superRefine((t,r)=>{if(!URL.canParse(t))return r.addIssue({code:"custom",message:"resource must be an absolute URI",fatal:!0}),Pr;if(t.includes("#")){r.addIssue({code:"custom",message:"resource must not contain a fragment"});return}if(S_.includes(new URL(t).protocol))r.addIssue({code:"custom",message:"resource cannot use javascript:, data:, or vbscript: scheme"})}),R_=T(["none","consent","login","create","select_account"]),T_=e().superRefine((t,r)=>{let n=t.split(" ").map((i)=>i.trim()).filter(Boolean),o=new Set;if(!n.length){r.addIssue({code:"custom",message:"prompt must include at least one value"});return}for(let i of n){let s=R_.safeParse(i);if(!s.success){r.addIssue({code:"custom",message:`unsupported prompt value: ${i}`});continue}o.add(s.data)}if(o.has("none")&&o.size>1)r.addIssue({code:"custom",message:"prompt=none cannot be combined with other prompt values"})}),Pn=l({keys:A(k(e(),J())).min(1)}),I_=D([_(),e().trim().min(1)]).transform((t,r)=>{let n=typeof t==="number"?t:Number(t);if(!Number.isInteger(n)||n<0)return r.addIssue({code:"custom",message:"max_age must be a non-negative integer"}),Pr;return n}),U_=e().regex(/^[A-Za-z0-9_-]{43}$/,"dpop_jkt must be a base64url-encoded SHA-256 JWK thumbprint"),pa=l({response_type:e().pipe(T(["code"])).optional(),request:e().optional(),request_uri:e().optional(),redirect_uri:le.optional(),scope:e().optional(),state:e().optional(),client_id:e().min(1,"client_id is required"),prompt:T_.optional(),display:e().optional(),ui_locales:e().optional(),max_age:I_.optional(),acr_values:e().optional(),login_hint:e().optional(),id_token_hint:e().optional(),code_challenge:e().optional(),code_challenge_method:e().pipe(T(["S256"])).optional(),nonce:e().optional(),claims:E_.optional(),dpop_jkt:U_.optional(),resource:D([Qs,A(Qs).min(1)]).optional()}).passthrough(),C_=pa.extend({redirect_uri:le.optional(),claims:la.optional()}),O_=l({type:v("authorization_code"),query:C_,sessionId:e(),userId:e(),referenceId:e().optional(),authTime:_().optional(),resource:A(e()).optional()}).passthrough(),ha=l({redirect_uris:A(le).min(1).optional(),scope:e().optional(),client_name:e().refine((t)=>t.trim().length>0,"client_name cannot be empty").optional(),client_uri:e().optional(),logo_uri:e().optional(),contacts:A(e().min(1)).min(1).optional(),tos_uri:e().optional(),policy_uri:e().optional(),software_id:e().optional(),software_version:e().optional(),software_statement:e().optional(),post_logout_redirect_uris:A(le).min(1).optional(),backchannel_logout_uri:le.optional(),backchannel_logout_session_required:E().optional(),token_endpoint_auth_method:e().trim().min(1).optional(),jwks:Pn.optional(),jwks_uri:e().optional(),grant_types:A(e().trim().min(1)).min(1).optional(),response_types:A(T(["code"])).optional(),application_type:T(["web","native"]).optional(),subject_type:T(["public","pairwise"]).optional(),dpop_bound_access_tokens:E().optional(),resources:A(Qs).optional(),skip_consent:Il({error:"skip_consent cannot be set during dynamic client registration"}).optional()}),HN=ha.omit({skip_consent:!0}).extend({client_id:e().refine((t)=>t.trim().length>0,"client_id cannot be empty"),client_secret:e().optional(),client_secret_expires_at:_().int().nonnegative().optional(),client_id_issued_at:_().int().nonnegative().optional()}).loose(),Ho=["EdDSA","ES256","ES512","PS256","RS256"],D_=new Set(Ho),L_=64;async function Sp(t,r){let n=t.identifierValidator;if(n){if(!await n(r))return{ok:!1,reason:`resource identifier ${r} failed validation`};return{ok:!0}}let o=Qs.safeParse(r);if(!o.success)return{ok:!1,reason:`resource identifier ${r} is invalid: ${o.error.issues[0]?.message??"not an absolute URI"}`};return{ok:!0}}async function Rp(t,r){let n=await Sp(t,r);if(!n.ok)throw new U("BAD_REQUEST",{error:"invalid_target",error_description:n.reason})}var P_=(t)=>`${t}/oauth2/userinfo`;async function Tp(t){if(!(t.headers.get("content-type")?.toLowerCase()??"").includes("application/x-www-form-urlencoded"))return;let r;try{r=await t.clone().text()}catch{return}if(!r)return;let n=new URLSearchParams(r).getAll("resource").filter((o)=>o.length>0);return n.length>0?n:void 0}function x_(t){if(t===void 0||t===null)return;if(typeof t==="string")return[t];if(Array.isArray(t)){let r=t.filter((n)=>typeof n==="string"&&n.length>0);return r.length>0?r:void 0}}async function Fo(t,r,n,o=[]){if(n===void 0)return!0;let i=Array.isArray(n)?n:[n];if(i.length>L_)return!1;let s=new Set(o),a=new Set;for(let c of i){if(s.has(c))continue;a.add(c)}if(a.size===0)return!0;return(await Promise.all(Array.from(a,(c)=>Wo(t,r,c)))).every(Boolean)}async function ma(t,r,n){let o=x_(n.resource),i=n.requestedScopes.includes("openid"),s=P_(t.context.baseURL??"");if(!o)return{audienceClaim:void 0,accessTokenTtl:null,refreshTokenTtl:null,signingAlgorithm:null,signingKeyId:null,rawCustomClaims:{},dpopBoundAccessTokensRequired:!1,effectiveScopes:[...n.requestedScopes]};let a=[...new Set(o)],c=[];for(let g of a){if(g===s)continue;let S=await Wo(t,r,g);if(S){if(S.disabled)throw new U("BAD_REQUEST",{error:"invalid_target",error_description:`requested resource ${g} is disabled`});c.push(S);continue}throw new U("BAD_REQUEST",{error:"invalid_target",error_description:`requested resource ${g} is not configured`})}let{value:d}=Ip(r);if(d&&c.length>0)await z_(t,r,n.clientId,c);let u=[...n.requestedScopes];for(let g of c){if(g.allowedScopes===null||g.allowedScopes===void 0)continue;let S=new Set(g.allowedScopes),C=u.filter((z)=>S.has(z));if(C.length===0)throw new U("BAD_REQUEST",{error:"invalid_scope",error_description:`none of the requested scopes are allowed for resource ${g.identifier}`});u=C}let f=null,p=null;for(let g of c){if(g.accessTokenTtl!=null)f=f===null?g.accessTokenTtl:Math.min(f,g.accessTokenTtl);if(g.refreshTokenTtl!=null)p=p===null?g.refreshTokenTtl:Math.min(p,g.refreshTokenTtl)}let h=new Set,m=new Set;for(let g of c){if(g.signingAlgorithm)h.add(g.signingAlgorithm);if(g.signingKeyId)m.add(g.signingKeyId)}if(h.size>1)throw new U("BAD_REQUEST",{error:"invalid_request",error_description:"multi-resource request has conflicting signingAlgorithm pins; a single JWS signature cannot satisfy multiple algorithms"});if(m.size>1)throw new U("BAD_REQUEST",{error:"invalid_request",error_description:"multi-resource request has conflicting signingKeyId pins; a single JWS signature cannot satisfy multiple key ids"});let w=h.values().next().value??null,y=m.values().next().value??null,I={};for(let g of c)if(g.customClaims&&typeof g.customClaims==="object")Object.assign(I,g.customClaims);let R=c.some((g)=>g.dpopBoundAccessTokensRequired===!0),b=i?[...a,s]:a,O=[...new Set(b)];return{audienceClaim:O.length===1?O[0]:O,accessTokenTtl:f,refreshTokenTtl:p,signingAlgorithm:w,signingKeyId:y,rawCustomClaims:I,dpopBoundAccessTokensRequired:R,effectiveScopes:u}}async function z_(t,r,n,o){if(o.length===0)return;let i=r.schema?.oauthClientResource?.modelName??"oauthClientResource",s=await t.context.adapter.findMany({model:i,where:[{field:"clientId",value:n}]}),a=new Set(s?.map((d)=>d.resourceId)??[]),c=o.filter((d)=>!a.has(d.identifier));if(c.length>0)throw new U("BAD_REQUEST",{error:"invalid_target",error_description:`client ${n} is not linked to resource(s) ${c.map((d)=>d.identifier).join(", ")}`})}async function N_(t,r,n,o){if(o.length===0)return!1;let i=r.schema?.oauthClientResource?.modelName??"oauthClientResource";return((await t.context.adapter.findMany({model:i,where:[{field:"clientId",value:n},{field:"resourceId",operator:"in",value:o}],limit:1}))?.length??0)>0}async function q_(t,r,n){if(n.length===0)return{};let o=await t.context.adapter.findMany({model:r.schema?.oauthResource?.modelName??"oauthResource",where:[{field:"identifier",operator:"in",value:n}]}),i=new Map(o.map((a)=>[a.identifier,a])),s={};for(let a of n){let c=i.get(a);if(c?.customClaims&&typeof c.customClaims==="object")Object.assign(s,c.customClaims)}return s}function Ip(t){if(t.enforcePerClientResources!==void 0)return{value:t.enforcePerClientResources,source:"explicit"};return{value:!0,source:"default"}}var Bo=new Map;function Ko(t){if(t===void 0){Bo.clear();return}Bo.delete(t)}async function Wo(t,r,n){if(await ga(t.context,r),r.cachedResources?.has(n)){let i=Bo.get(n);if(i)return Object.assign({},i)}let o=await t.context.adapter.findOne({model:r.schema?.oauthResource?.modelName??"oauthResource",where:[{field:"identifier",value:n}]});if(o&&r.cachedResources?.has(n))Bo.set(n,Object.assign({},o));return o}function j_(t){return t.name??t.identifier}function B_(t){let r=[];if(t.resources?.length)for(let n of t.resources)r.push(typeof n==="string"?{identifier:n}:n);return r}function Up(t,r){return{identifier:t.identifier,name:j_(t),accessTokenTtl:t.accessTokenTtl??null,refreshTokenTtl:t.refreshTokenTtl??null,signingAlgorithm:t.signingAlgorithm??null,signingKeyId:t.signingKeyId??null,allowedScopes:t.allowedScopes??null,customClaims:t.customClaims??null,dpopBoundAccessTokensRequired:t.dpopBoundAccessTokensRequired??!1,disabled:t.disabled??!1,policyVersion:1,metadata:t.metadata??null,createdAt:r,updatedAt:r}}function $_(t,r,n){if(r==="overwrite"){let{identifier:i,createdAt:s,...a}=Up(t,n);return a}let o={updatedAt:n};if(t.name!==void 0)o.name=t.name;if(t.accessTokenTtl!==void 0)o.accessTokenTtl=t.accessTokenTtl;if(t.refreshTokenTtl!==void 0)o.refreshTokenTtl=t.refreshTokenTtl;if(t.signingAlgorithm!==void 0)o.signingAlgorithm=t.signingAlgorithm;if(t.signingKeyId!==void 0)o.signingKeyId=t.signingKeyId;if(t.allowedScopes!==void 0)o.allowedScopes=t.allowedScopes;if(t.customClaims!==void 0)o.customClaims=t.customClaims;if(t.dpopBoundAccessTokensRequired!==void 0)o.dpopBoundAccessTokensRequired=t.dpopBoundAccessTokensRequired;if(t.disabled!==void 0)o.disabled=t.disabled;if(t.metadata!==void 0)o.metadata=t.metadata;return o}var M_=/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 Cp(t,r){let n=!1,o=r;for(let i=0;o&&!n&&i<5;i++)n=M_.test(o instanceof Error?o.message:String(o)),o=o instanceof Error?o.cause:void 0;if(n){t.logger.debug("oauth-provider: oauthResource table not yet created; deferring resource seed to first access.");return}t.logger.error("oauth-provider: could not seed `resources` at startup; retrying on first resource access.",r)}var lp=new WeakMap;function H_(t,r){let n=t.adapter,o=lp.get(n);if(!o)o=new WeakMap,lp.set(n,o);let i=o.get(r);if(i)return i;let s={completed:!1,promise:null};return o.set(r,s),s}async function V_(t,r){let n=B_(r);if(n.length===0)return;let o=r.resourceSeedMode??"insertOnly",i=r.schema?.oauthResource?.modelName??"oauthResource";for(let s of n){let a=await Sp(r,s.identifier);if(!a.ok){Ee.warn(`oauth-provider: skipping resource seed for ${s.identifier} \u2014 ${a.reason}`);continue}let c=s;if(c.signingAlgorithm!=null&&!D_.has(c.signingAlgorithm)){Ee.warn(`oauth-provider: dropping unsupported signingAlgorithm "${c.signingAlgorithm}" for resource ${c.identifier} \u2014 must be one of ${Ho.join(", ")}. Continuing without an algorithm override.`);let{signingAlgorithm:p,...h}=c;c=h}let d=[{field:"identifier",value:c.identifier}],u=await t.adapter.findOne({model:i,where:d}),f=new Date;if(!u)try{await t.adapter.create({model:i,data:Up(c,f)});continue}catch(p){if(!await t.adapter.findOne({model:i,where:d}).catch(()=>null))throw p}if(o==="insertOnly")continue;await t.adapter.update({model:i,where:d,update:$_(c,o,f)})}}async function ga(t,r){let n=H_(t,r);if(n.completed===!0)return;if(n.promise!==null)return n.promise;return n.promise=V_(t,r).then(()=>{n.completed=!0}).catch((o)=>{throw n.promise=null,o}),n.promise}function Op(t){let r=Ip(t);Ee.info(`oauth-provider: enforcePerClientResources resolved to ${r.value} (${r.source})`)}function Dp(t){return t.headers?.get("dpop")??void 0}function Jo(t,r){let{baseURL:n}=t.context,o=n.length;while(o>0&&n[o-1]==="/")o--;let i=n.slice(0,o);if(!t.request||!i)return`${i}${r}`;let s=new URL(i).pathname.replace(/\/$/,""),a=new URL(t.request.url).pathname;return`${i}${a.startsWith(`${s}/`)?a.slice(s.length):r}`}var F_=new Set(["openid","profile","email","offline_access"]);function Lp(t){return F_.has(t)}function wa(t){return[...new Set(t.map((r)=>r.trim()).filter(Boolean))]}function ya(t,r,n,o){if(t.length===0)return;if(!r.includes("client_credentials"))throw new U("BAD_REQUEST",{error:"invalid_client_metadata",error_description:"client_credentials_scopes requires the client_credentials grant"});if(n==="none")throw new U("BAD_REQUEST",{error:"invalid_client_metadata",error_description:"public clients cannot be assigned client_credentials scopes"});let i=new Set(o.scopes??[]),s=t.filter((a)=>!i.has(a)||Lp(a));if(s.length>0)throw new U("BAD_REQUEST",{error:"invalid_scope",error_description:`The following client_credentials scopes are invalid: ${s.join(", ")}`})}function K_(t,r,n=[]){let o=new Set(n),i={sub:t.id??void 0};for(let[s,a]of Object.entries(Mo))if(r.includes(a.scope)||o.has(s))i[s]=a.resolve(t);return i}function ua(t,r){let n={};for(let[o,i]of Object.entries(t??{})){if(i===void 0)continue;if(r&&o in r)continue;n[o]=i}return n}function W_(t){let r=t.headers?.get("authorization"),n=_r(r),o=t.request?.method==="POST"?t.body?.access_token??void 0:void 0;if(n&&o)throw new U("BAD_REQUEST",{error_description:"Multiple access token transport methods are not allowed",error:"invalid_request"});let i=n??(o?{scheme:"Bearer",token:o}:void 0);return{authorization:i,token:i?.token}}async function Pp(t,r){let{authorization:n}=W_(t);if(!n?.token)throw new U("UNAUTHORIZED",{error_description:"access token not found",error:"invalid_request"});let{payload:o,requestedUserInfoClaims:i}=await Hp(t,r,n.token);if(gn(o)&&!t.request)throw new U("UNAUTHORIZED",{error_description:"DPoP-bound access token requires an HTTP request context",error:"invalid_token"});try{await yn({payload:o,authorization:n,proofJwt:Dp(t),method:t.request?.method??"GET",url:Jo(t,"/oauth2/userinfo"),proofMaxAgeSeconds:r.dpop?.proofMaxAgeSeconds,signingAlgorithms:r.dpop?.signingAlgorithms,replayStore:_c(t.context.internalAdapter)})}catch(h){if(wn(h))throw new U("UNAUTHORIZED",{error_description:h.message,error:h.code});throw h}let s=o.scope?.split(" ");if(!s?.includes("openid"))throw new U("BAD_REQUEST",{error_description:"Missing required scope",error:"invalid_scope"});if(!o.sub)throw new U("BAD_REQUEST",{error_description:"user not found",error:"invalid_request"});let a=await t.context.internalAdapter.findUserById(o.sub);if(!a)throw new U("BAD_REQUEST",{error_description:"user not found",error:"invalid_request"});let c=K_(a,s??[],i),d=o.client_id??o.azp,u=d&&(r.pairwiseSecret||ip(r))?await ke(t,r,d):void 0;if(r.pairwiseSecret&&u)c.sub=await Tr(a.id,u,r);let f=s?.length?await op(r,{ctx:t,opts:r,user:a,scopes:s,jwt:o,client:u??void 0,requestedClaims:i}):{},p=r.customUserInfoClaims&&s?.length?await r.customUserInfoClaims({user:a,scopes:s,jwt:o,requestedClaims:i}):{};return{...c,...ua(f,c),...ua(p),sub:c.sub}}var J_=Object.fromEntries(fa.map((t)=>[t,void 0]));function Go(t){return hn(t)?"DPoP":"Bearer"}var Q_="at+jwt";async function xp(t,r){let n=t.body.grant_type;if(!Rr(r).includes(n))throw new U("BAD_REQUEST",{error_description:`unsupported grant_type ${n}`,error:"unsupported_grant_type"});switch(n){case"authorization_code":return EA(t,r);case"client_credentials":return bA(t,r);case"refresh_token":return vA(t,r);default:{let o=ep(r,n);if(o)return o({ctx:t,opts:r,grantType:n,provider:G_(t,r,n)});throw new U("BAD_REQUEST",{error_description:`unsupported grant_type ${n}`,error:"unsupported_grant_type"})}}}function G_(t,r,n){return{getClient:(o)=>ke(t,r,o),authenticateClient:async(o)=>{let{clientId:i,clientSecret:s,preVerified:a,authMethod:c,confirmation:d}=Ot(await Dt(t,r,`${t.context.baseURL}${t.path??"/oauth2/token"}`));if(!i)throw new U("BAD_REQUEST",{error_description:"Missing required client_id",error:"invalid_request"});if(o?.requireCredentials!==!1&&!s&&!a)throw new U("BAD_REQUEST",{error_description:"Missing required client credentials",error:"invalid_client"});return{clientId:i,client:await Ct(t,r,i,s,o?.scopes,a,n,c),method:c,confirmation:d}},issueTokens:(o)=>{if(!n)throw new U("INTERNAL_SERVER_ERROR",{error_description:"issueTokens requires a grant type; pass it to getOAuthProviderApi(ctx, opts, grantType).",error:"server_error"});return Xo(t,r,{...o,grantType:n})},hashToken:(o,i)=>er(r.storeTokens,o,i),validateAccessToken:async(o,i)=>{let{validateAccessToken:s}=await Promise.resolve().then(()=>wp);return s(t,r,o,i)},requireActiveAccessToken:async(o,i)=>{let{requireActiveAccessToken:s}=await Promise.resolve().then(()=>wp);return s(t,r,o,i)}}}async function Z_(t,r,n,o,i,s,a){let c=a?.iat??Math.floor(Date.now()/1000),d=a?.exp??c+(r.accessTokenExpiresIn??3600),u=Oe(t.context).options,f=n?.id??o.clientId;return Wi(t,{options:u,header:{typ:Q_},signingKeyId:a?.signingKeyId??void 0,signingAlgorithm:a?.signingAlgorithm??void 0,payload:{...a?.accessTokenClaims??{},sub:f,aud:Xs(i),client_id:o.clientId,azp:o.clientId,scope:s.join(" "),sid:a?.sid,iss:u?.jwt?.issuer??t.context.baseURL,iat:c,exp:d,jti:_e(32),...a?.confirmation?{cnf:a.confirmation}:{}}})}async function Y_(t,r){let n;if(r==="EdDSA")n="SHA-512";else if(r.endsWith("384"))n="SHA-384";else if(r.endsWith("512"))n="SHA-512";else n="SHA-256";let o=new Uint8Array(await crypto.subtle.digest(n,new TextEncoder().encode(t)));return mr(o.slice(0,o.length/2))}async function X_(t,r,n,o,i,s,a,c,d,u){let f=Math.floor(Date.now()/1000),p=f+(r.idTokenExpiresIn??36000),h=await Tr(n.id,o,r),m=c!=null?Math.floor(c.getTime()/1000):void 0,w=dp(r.customIdTokenClaims?await r.customIdTokenClaims({user:n,scopes:i,metadata:rr(o.metadata)}):void 0),y=r.disableJwtPlugin?void 0:Oe(t.context).options,I=!r.disableJwtPlugin&&!y?.jwt?.sign?await Ki(t,y):void 0,R=r.disableJwtPlugin?"HS256":I?.alg??y?.jwks?.keyPairConfig?.alg,b=d?await Y_(d,R):void 0,O=Boolean(o.enableEndSession||o.backchannelLogoutUri),g={...J_,auth_time:m,acr:"0",...w,at_hash:b,iss:y?.jwt?.issuer??t.context.baseURL,sub:h,aud:o.clientId,nonce:s,iat:f,exp:p,sid:O?a:void 0},S=dp(u);if(Object.assign(g,ua(S,g)),r.disableJwtPlugin&&!o.clientSecret)return;let C=r.disableJwtPlugin?await new bs(g).setProtectedHeader({alg:"HS256"}).sign(new TextEncoder().encode(await Sr(t,r.storeClientSecret,o.clientSecret))):await Wi(t,{options:y,payload:g,resolvedKey:I??void 0});if(C&&b&&y?.jwt?.sign){let z=so(C);if(z.alg!==R)throw new U("INTERNAL_SERVER_ERROR",{error_description:`ID token signed with "${z.alg}" but at_hash was computed for "${R}". Ensure jwt.sign uses the algorithm declared in keyPairConfig.alg.`,error:"server_error"})}return C}async function fp(t,r,n){return(t.prefix?.refreshToken??"")+(t.formatRefreshToken?.encrypt?t.formatRefreshToken.encrypt(r,n):r)}async function Zo(t,r){if(t.prefix?.refreshToken)if(r.startsWith(t.prefix.refreshToken))r=r.replace(t.prefix.refreshToken,"");else throw new U("BAD_REQUEST",{error_description:"refresh token not found",error:"invalid_token"});return t.formatRefreshToken?.decrypt?t.formatRefreshToken?.decrypt(r):{token:r}}async function eA(t,r,n,o,i,s,a,c,d,u,f,p){let h=s.iat??Math.floor(Date.now()/1000),m=s?.exp??h+(r.accessTokenExpiresIn??3600),w=r.generateOpaqueAccessToken?await r.generateOpaqueAccessToken():_e(32,"A-Z","a-z");return await t.context.adapter.create({model:"oauthAccessToken",data:{token:await er(r.storeTokens,w,"access_token"),clientId:o.clientId,sessionId:s?.sid,userId:n?.id,referenceId:c,authorizationCodeId:d,resources:a,refreshId:u,confirmation:f,requestedUserInfoClaims:p?.length?p:void 0,scopes:i,createdAt:new Date(h*1000),expiresAt:new Date(m*1000)}}),(r.prefix?.opaqueAccessToken??"")+w}async function Yo(t,r,n){let o=await t.context.adapter.findMany({model:"oauthRefreshToken",where:[{field:"clientId",value:r},{field:"userId",value:n}]});if(o.length)await t.context.adapter.deleteMany({model:"oauthAccessToken",where:[{field:"refreshId",operator:"in",value:o.map((i)=>i.id)}]});await t.context.adapter.deleteMany({model:"oauthRefreshToken",where:[{field:"clientId",value:r},{field:"userId",value:n}]})}async function tA(t,r){let n=async(o)=>{try{await t.context.adapter.deleteMany({model:o,where:[{field:"authorizationCodeId",value:r}]})}catch(i){t.context.logger.error("authorization code replay cleanup failed",i)}};await n("oauthAccessToken"),await n("oauthRefreshToken")}async function pp(t,r,n,o,i,s,a,c,d,u,f,p,h){let m=c.iat??Math.floor(Date.now()/1000),w=c?.exp??m+(r.refreshTokenExpiresIn??2592000),y=r.generateRefreshToken?await r.generateRefreshToken():_e(32,"A-Z","a-z"),I=c?.sid,R={token:await er(r.storeTokens,y,"refresh_token"),clientId:s.clientId,sessionId:I,userId:n.id,referenceId:o,authorizationCodeId:i,authTime:u,confirmation:p,requestedUserInfoClaims:h?.length?h:void 0,scopes:a,resources:f,createdAt:new Date(m*1000),expiresAt:new Date(w*1000)};if(!d?.id)return{id:(await t.context.adapter.create({model:"oauthRefreshToken",data:R})).id,token:await fp(r,y,I)};let b=new Date(m*1000),O={revoked:b,rotatedAt:b},g=r.refreshTokenReuseInterval??0;if(g>0)O.rotationReplayExpiresAt=new Date((m+g)*1000);if(!await t.context.adapter.incrementOne({model:"oauthRefreshToken",where:[{field:"id",value:d.id},{field:"revoked",operator:"eq",value:null}],increment:{},set:O}))throw new U("BAD_REQUEST",{error_description:"invalid refresh token",error:"invalid_grant"});return{id:(await t.context.adapter.create({model:"oauthRefreshToken",data:R})).id,token:await fp(r,y,I)}}async function zp(t,r,n){let o=await ma(t,r,{resource:n.resources,clientId:n.clientId,requestedScopes:n.requestedScopes}),i=o.accessTokenTtl!==null?n.iat+o.accessTokenTtl:n.scopeExpiresAtSeconds,s=r.refreshTokenExpiresIn??2592000,a=o.refreshTokenTtl!==null?Math.min(o.refreshTokenTtl,s):s;return{audienceClaim:o.audienceClaim,effectiveScopes:o.effectiveScopes,accessTokenExpiresAtSeconds:Math.min(n.scopeExpiresAtSeconds,i),refreshTokenExpiresAtSeconds:n.iat+a,refreshResources:n.refreshToken?.resources??n.originalResources??n.resources,signingAlgorithm:o.signingAlgorithm,signingKeyId:o.signingKeyId,resourceCustomClaims:o.rawCustomClaims,dpopBoundAccessTokensRequired:o.dpopBoundAccessTokensRequired}}function hp(t){throw new U("BAD_REQUEST",{error:"invalid_dpop_proof",error_description:t})}function rA(t){let r=rr(t.metadata)??{};return t.dpopBoundAccessTokens===!0||r.dpop_bound_access_tokens===!0}async function Np(t,r,n){let o=n.verificationValue?.query.dpop_jkt,i=hn(n.refreshToken?.confirmation),s=i??o,a=Dp(t),c=rA(n.client)||n.grantIssuance.dpopBoundAccessTokensRequired||!!o||!!i;if(!a){if(c)hp("DPoP proof header is required");return}try{return{jkt:(await Ro({proofJwt:a,method:"POST",url:Jo(t,t.path??"/oauth2/token"),expectedJkt:s,proofMaxAgeSeconds:r.dpop?.proofMaxAgeSeconds,signingAlgorithms:r.dpop?.signingAlgorithms,replayStore:_c(t.context.internalAdapter)})).jkt}}catch(d){if(So(d))hp(d.message);throw d}}function $o(t){return t?[...new Set(t)].sort():void 0}function mp(t,r){let n=$o(t),o=$o(r);if(n===void 0||o===void 0)return n===o;if(n.length!==o.length)return!1;return n.every((i,s)=>i===o[s])}function gp(t){if(!t)return;if("jkt"in t)return`jkt:${t.jkt}`;return`x5t#S256:${t["x5t#S256"]}`}function nA(t,r){return gp(t)===gp(r)}function cA(t){if(!t||typeof t!=="object")return!1;let r=t;return typeof r.jkt==="string"&&r["x5t#S256"]===void 0||typeof r["x5t#S256"]==="string"&&r.jkt===void 0}function dA(t){return t==="Bearer"||t==="DPoP"}function uA(t){if(!t||typeof t!=="object")return!1;let r=t;return typeof r.access_token==="string"&&typeof r.expires_in==="number"&&typeof r.expires_at==="number"&&dA(r.token_type)&&typeof r.scope==="string"&&(r.refresh_token===void 0||typeof r.refresh_token==="string")&&(r.id_token===void 0||typeof r.id_token==="string")}function lA(t){if(!t||typeof t!=="object")return!1;let r=t,n=r.request;return!!n&&Array.isArray(n.effectiveScopes)&&n.effectiveScopes.every((o)=>typeof o==="string")&&(n.requestedResources===void 0||Array.isArray(n.requestedResources)&&n.requestedResources.every((o)=>typeof o==="string"))&&(n.confirmation===void 0||cA(n.confirmation))&&uA(r.response)}function qp(t){let r=$o(t.requestedResources);return{effectiveScopes:$o(t.effectiveScopes)??[],...r?{requestedResources:r}:{},...t.confirmation?{confirmation:t.confirmation}:{}}}function fA(t,r){return mp(t.effectiveScopes,r.effectiveScopes)&&mp(t.requestedResources,r.requestedResources)&&nA(t.confirmation,r.confirmation)}async function hA(t,r){return nt({key:t.context.secretConfig,data:JSON.stringify(r)})}async function gA(t,r){let n=await ot({key:t.context.secretConfig,data:r}),o=JSON.parse(n);if(!lA(o))return;return o}function jp(t){return!!t.rotatedAt&&!!t.rotationReplayExpiresAt&&t.rotationReplayExpiresAt>=new Date}async function wA(t,r,n,o,i){if((r.refreshTokenReuseInterval??0)<=0)return;await t.context.adapter.update({model:"oauthRefreshToken",where:[{field:"id",value:n.id}],update:{rotationReplayResponse:await hA(t,{request:o,response:i})}})}async function yA(t,r,n){if(!jp(r))return;if(!r.rotationReplayResponse)return;try{let o=await gA(t,r.rotationReplayResponse);if(!o||!fA(o.request,n))return;return o.response}catch(o){t.context.logger.error("refresh token rotation replay failed",o);return}}async function _A(t,r,n){let o=Math.floor(Date.now()/1000),i=await zp(t,r,{clientId:n.client.clientId,requestedScopes:n.scopes,resources:n.resources,refreshToken:n.refreshToken,iat:o,scopeExpiresAtSeconds:o+(r.accessTokenExpiresIn??3600)}),s=await Np(t,r,{client:n.client,grantIssuance:i,refreshToken:n.refreshToken});return qp({effectiveScopes:i.effectiveScopes,requestedResources:n.resources,confirmation:s})}function AA(t,r){let n=Math.floor(Date.now()/1000);return t.json({...r,expires_in:Math.max(0,r.expires_at-n)})}async function Xo(t,r,n){let{client:o,scopes:i,user:s,grantType:a,referenceId:c,sessionId:d,nonce:u,refreshToken:f,authTime:p,verificationValue:h}=n,m=Math.floor(Date.now()/1000),w=m+(s?r.accessTokenExpiresIn??3600:r.m2mAccessTokenExpiresIn??3600),y=r.scopeExpirations?i.map((Z)=>r.scopeExpirations?.[Z]?Yt(r.scopeExpirations[Z],m):w).reduce((Z,re)=>Z<re?Z:re,w):w,I=await zp(t,r,{clientId:o.clientId,requestedScopes:i,resources:n.resources,originalResources:n.originalResources,refreshToken:n.refreshToken,iat:m,scopeExpiresAtSeconds:y}),{audienceClaim:R,effectiveScopes:b,accessTokenExpiresAtSeconds:O,refreshTokenExpiresAtSeconds:g}=I,S=s&&Cn(o,"refresh_token")&&(f?.scopes?.includes("offline_access")||i.includes("offline_access")),C=R&&!r.disableJwtPlugin,z=s&&b.includes("openid"),L=rr(o.metadata),x=z&&s?{...await np(r,{ctx:t,opts:r,user:s,client:o,scopes:b,grantType:a,referenceId:c,sessionId:d,resources:n.resources,metadata:L}),...n.idTokenClaims??{}}:void 0,P=r.customTokenResponseFields?await r.customTokenResponseFields({grantType:a,user:s,scopes:b,metadata:L,verificationValue:h}):void 0,j=I.refreshResources,B=n.confirmation??await Np(t,r,{client:o,grantIssuance:I,verificationValue:h,refreshToken:f}),H=n.requestedUserInfoClaims??f?.requestedUserInfoClaims??[],q=S&&s&&!C?await pp(t,r,s,c,n.authorizationCodeId,o,b,{iat:m,exp:g,sid:d},f,p,j,B,H):void 0,W=C?await vp({ctx:t,opts:r,user:s,client:o,scopes:b,grantType:a,sessionId:d,resources:n.resources,referenceId:c,metadata:L,perRequestClaims:n.accessTokenClaims,resourcePolicyClaims:I.resourceCustomClaims}):void 0,[Q,G]=await Promise.all([C?Z_(t,r,s,o,R,b,{iat:m,exp:O,sid:d,signingAlgorithm:I.signingAlgorithm,signingKeyId:I.signingKeyId,accessTokenClaims:W,confirmation:B}):eA(t,r,s,o,b,{iat:m,exp:O,sid:d},n?.resources,c,n.authorizationCodeId,q?.id,B,H),q?q:S&&s?pp(t,r,s,c,n.authorizationCodeId,o,b,{iat:m,exp:g,sid:d},f,p,j,B,H):void 0]),M=z?await X_(t,r,s,o,b,u,d,p,Q,x):void 0,Y={...P,...n.tokenResponse??{},access_token:Q,expires_in:O-m,expires_at:O,token_type:Go(B),refresh_token:G?.token,scope:b.join(" "),id_token:M};if(f?.id&&G?.id)try{await wA(t,r,f,qp({effectiveScopes:b,requestedResources:n.resources,confirmation:B}),Y)}catch(Z){t.context.logger.error("failed to store refresh token rotation replay",Z)}return t.json(Y)}async function kA(t,r,n,o,i,s){let a=await er(r.storeTokens,n,"authorization_code"),c=await t.context.internalAdapter.consumeVerificationValue(a);if(!c)throw await tA(t,a),new U("BAD_REQUEST",{error_description:"invalid code",error:"invalid_grant"});let d;try{d=JSON.parse(c.value)}catch{throw new U("BAD_REQUEST",{error_description:"malformed verification value",error:"invalid_grant"})}let u=O_.safeParse(d);if(!u.success)throw new U("BAD_REQUEST",{error_description:"malformed verification value",error:"invalid_grant"});let f=u.data;if(f.query.client_id!==o)throw new U("BAD_REQUEST",{error_description:"invalid client_id",error:"invalid_grant"});let p=f.query.redirect_uri;if(p){if(!i)throw new U("BAD_REQUEST",{error_description:"redirect_uri is required",error:"invalid_request"});if(p!==i)throw new U("BAD_REQUEST",{error_description:"redirect_uri mismatch",error:"invalid_grant"})}else if(i)throw new U("BAD_REQUEST",{error_description:"redirect_uri mismatch",error:"invalid_grant"});let h=Ut(f.resource)??Ut(f.query.resource),m=s??h;if(s&&h){let w=new Set(s),y=new Set(h);for(let I of w)if(!y.has(I))throw new U("BAD_REQUEST",{error_description:"requested resource not authorized",error:"invalid_target"})}return{verificationValue:f,effectiveResources:m,authorizedResources:h,authorizationCodeId:a}}async function EA(t,r){let{clientId:n,clientSecret:o,preVerified:i,authMethod:s}=Ot(await Dt(t,r,`${t.context.baseURL}/oauth2/token`)),{code:a,code_verifier:c,redirect_uri:d,resource:u}=t.body,f=Ut(u);if(!n)throw new U("BAD_REQUEST",{error_description:"client_id is required",error:"invalid_request"});if(!a)throw new U("BAD_REQUEST",{error_description:"code is required",error:"invalid_request"});let p=n&&o,h=n&&a&&c;if(!p&&!h&&!i)throw new U("BAD_REQUEST",{error_description:"Either code_verifier or client_secret is required",error:"invalid_request"});let m=await Ct(t,r,n,o,void 0,i,"authorization_code",s),{verificationValue:w,effectiveResources:y,authorizedResources:I,authorizationCodeId:R}=await kA(t,r,a,n,d,f),b=w.query.scope?.split(" ");if(!b)throw new U("INTERNAL_SERVER_ERROR",{error_description:"verification scope unset",error:"invalid_scope"});if(qo(m,b),jo(m,{scopes:w.query?.scope?.split(" ")||[],nonce:w.query?.nonce})){if(!h)throw new U("BAD_REQUEST",{error_description:"PKCE is required for this client",error:"invalid_request"})}else if(!(h||p||i))throw new U("BAD_REQUEST",{error_description:"Either PKCE (code_verifier) or client authentication (client_secret or client_assertion) is required",error:"invalid_request"});let O=!!w.query?.code_challenge,g=!!c;if(O||g){if(O&&!g)throw new U("BAD_REQUEST",{error_description:"code_verifier required because PKCE was used in authorization",error:"invalid_request"});if(!O&&g)throw new U("BAD_REQUEST",{error_description:"code_verifier provided but PKCE was not used in authorization",error:"invalid_request"});if((w.query?.code_challenge_method==="S256"?await an(c):void 0)!==w.query?.code_challenge)throw new U("BAD_REQUEST",{error_description:"code verification failed",error:"invalid_grant"})}if(!w.userId)throw new U("BAD_REQUEST",{error_description:"missing user, user may have been deleted",error:"invalid_user"});let S=await t.context.internalAdapter.findUserById(w.userId);if(!S)throw new U("BAD_REQUEST",{error_description:"missing user, user may have been deleted",error:"invalid_user"});let C=await t.context.adapter.findOne({model:"session",where:[{field:"id",value:w.sessionId}]});if(!C||C.expiresAt<new Date)throw new U("BAD_REQUEST",{error_description:"session no longer exists",error:"invalid_request"});let z=w.authTime!=null?st(w.authTime):ap(C),L=Dn(w.query.claims,Ln(r));return Xo(t,r,{client:m,scopes:w.query.scope?.split(" ")??[],user:S,grantType:"authorization_code",referenceId:w.referenceId,sessionId:C.id,nonce:w.query?.nonce,authTime:z,verificationValue:w,authorizationCodeId:R,requestedUserInfoClaims:L,resources:y,originalResources:I})}async function bA(t,r){let{clientId:n,clientSecret:o,preVerified:i,authMethod:s}=Ot(await Dt(t,r,`${t.context.baseURL}/oauth2/token`)),{scope:a,resource:c}=t.body,d=Ut(c);if(!n)throw new U("BAD_REQUEST",{error_description:"Missing required client_id",error:"invalid_request"});let u=await Ct(t,r,n,o,void 0,i,"client_credentials",s);if(u.tokenEndpointAuthMethod==="none")throw new U("BAD_REQUEST",{error_description:"public clients cannot use the client_credentials grant",error:"unauthorized_client"});let f=u.clientCredentialsScopes;if(!f?.length)throw new U("BAD_REQUEST",{error_description:"client has no authorized client_credentials scopes",error:"unauthorized_client"});let p=a?.split(" ");if(p){let h=new Set(f),m=p.filter((w)=>!h.has(w)||Lp(w));if(m.length)throw new U("BAD_REQUEST",{error_description:`The following scopes are invalid: ${m.join(", ")}`,error:"invalid_scope"})}if(!p)p=[...f];return Xo(t,r,{client:u,scopes:p,grantType:"client_credentials",resources:d})}async function vA(t,r){let{clientId:n,clientSecret:o,preVerified:i,authMethod:s}=Ot(await Dt(t,r,`${t.context.baseURL}/oauth2/token`)),{refresh_token:a,scope:c,resource:d}=t.body,u=Ut(d);if(!n)throw new U("BAD_REQUEST",{error_description:"Missing required client_id",error:"invalid_request"});if(!a)throw new U("BAD_REQUEST",{error_description:"Missing a required refresh_token for refresh_token grant",error:"invalid_request"});let f=await Ct(t,r,n,o,void 0,i,"refresh_token",s),p=await Zo(r,a),h=await t.context.adapter.findOne({model:"oauthRefreshToken",where:[{field:"token",value:await tr(r.storeTokens,p.token,"refresh_token")}]});if(!h)throw new U("BAD_REQUEST",{error_description:"session not found",error:"invalid_grant"});if(h.clientId!==n)throw new U("BAD_REQUEST",{error_description:"invalid refresh token",error:"invalid_grant"});if(h.expiresAt<new Date)throw new U("BAD_REQUEST",{error_description:"invalid refresh token",error:"invalid_grant"});if(u&&h.resources&&!u.every((R)=>h.resources?.includes(R)))throw new U("BAD_REQUEST",{error_description:"requested resource invalid",error:"invalid_target"});let m=h?.scopes,w=c?.split(" ");if(w){let R=new Set(m);for(let b of w)if(!R.has(b))throw new U("BAD_REQUEST",{error_description:`unable to issue scope ${b}`,error:"invalid_scope"})}if(qo(f,w??m),h.revoked){if(jp(h)){let R=await yA(t,h,await _A(t,r,{client:f,refreshToken:h,scopes:w??m,resources:u??h.resources}));if(R)return AA(t,R);throw new U("BAD_REQUEST",{error_description:"invalid refresh token",error:"invalid_grant"})}throw await Yo(t,n,h.userId),new U("BAD_REQUEST",{error_description:"invalid refresh token",error:"invalid_grant"})}let y=await t.context.internalAdapter.findUserById(h.userId);if(!y)throw new U("BAD_REQUEST",{error_description:"user not found",error:"invalid_request"});let I=h.authTime!=null?st(h.authTime):void 0;return Xo(t,r,{client:f,scopes:w??m,user:y,grantType:"refresh_token",referenceId:h.referenceId,authorizationCodeId:h.authorizationCodeId,sessionId:h.sessionId,refreshToken:h,resources:u??h.resources,authTime:I,requestedUserInfoClaims:h.requestedUserInfoClaims})}var wp=Co({introspectEndpoint:()=>ka,requireActiveAccessToken:()=>OA,requireActiveAccessTokenWithClaims:()=>Hp,validateAccessToken:()=>Aa}),Bp="Invalid access token",SA=`Bearer error="invalid_token", error_description="${Bp}"`;function Cr(){return{payload:{active:!1},requestedUserInfoClaims:[]}}function RA(t,r){if(t==null)return[];return(Array.isArray(t)?t:[t]).filter((n)=>typeof n==="string"&&n!==r)}async function $p(t,r,n){let{introspectingClientId:o,issuerClientId:i,audienceResources:s}=n;if(!o)return!0;if(o===i)return!0;if(s.length===0)return!1;return N_(t,r,o,s)}async function TA(t,r,n,o){if(r.disableJwtPlugin)throw new ce("BAD_REQUEST",{error_description:"JWT access tokens are disabled",error:"invalid_request"});let i=Oe(t.context),s=i.options,a=`${t.context.baseURL??""}/oauth2/userinfo`,c=s?.jwt?.issuer??t.context.baseURL,d;try{d=(await Qr(n,Qo(await Ar(n,{jwksFetch:s?.jwks?.remoteUrl?s.jwks.remoteUrl:async()=>(await i.endpoints.getJwks(t))?.response,jwksCacheKey:i})),{issuer:c})).payload}catch(h){if(h instanceof yi||h instanceof jr)return{active:!1};if(h instanceof TypeError||xo(h))throw new ce("BAD_REQUEST",{error_description:"invalid JWT signature",error:"invalid_request"});throw h}let u=d.aud;if(!await Fo(t,r,u,[a]))return{active:!1};if(!d.azp)return{active:!1};let f=await ke(t,r,d.azp);if(!f||f?.disabled)return{active:!1};if(!await $p(t,r,{introspectingClientId:o,issuerClientId:d.azp,audienceResources:RA(u,a)}))return{active:!1};let p=d.sid;if(p){let h=await t.context.adapter.findOne({model:"session",where:[{field:"id",value:p}]});if(!h||h.expiresAt<new Date)return{active:!1}}return d.client_id=d.azp,d.active=!0,d.token_type=Go(d.cnf),d}async function IA(t,r,n,o){let i=n;if(r.prefix?.opaqueAccessToken)if(i.startsWith(r.prefix.opaqueAccessToken))i=i.replace(r.prefix.opaqueAccessToken,"");else throw new ce("BAD_REQUEST",{error_description:"opaque access token not found",error:"invalid_request"});let s=await t.context.adapter.findOne({model:"oauthAccessToken",where:[{field:"token",value:await tr(r.storeTokens,i,"access_token")}]});if(!s)throw new ce("BAD_REQUEST",{error_description:"opaque access token not found",error:"invalid_token"});if(!s.expiresAt||s.expiresAt<new Date)return Cr();if(s.revoked)return Cr();let a=Array.isArray(s.resources)?s.resources:void 0,c;if(s.clientId){if(c=await ke(t,r,s.clientId),!c||c?.disabled)return Cr();if(!await $p(t,r,{introspectingClientId:o,issuerClientId:s.clientId,audienceResources:a??[]}))return Cr()}let d=s.sessionId??void 0;if(d){let y=await t.context.adapter.findOne({model:"session",where:[{field:"id",value:d}]});if(!y||y.expiresAt<new Date)return Cr()}let u;if(s.userId)u=await t.context.internalAdapter.findUserById(s?.userId);let f=`${t.context.baseURL}/oauth2/userinfo`;if(a?.length&&!await Fo(t,r,a,[f]))return Cr();let p=a?[...a]:void 0;if(p?.length&&s.scopes?.includes("openid")){if(!p.includes(f))p.push(f)}let h=a?.length?await q_(t,r,a):{},m=c?await vp({ctx:t,opts:r,user:u,client:c,scopes:s.scopes??[],grantType:void 0,sessionId:void 0,resources:a,referenceId:s.referenceId,metadata:rr(c.metadata),perRequestClaims:void 0,resourcePolicyClaims:h}):{},w=(r.disableJwtPlugin?void 0:Oe(t.context))?.options;return{payload:{...m,active:!0,iss:w?.jwt?.issuer??t.context.baseURL,aud:Xs(p),client_id:s.clientId,azp:s.clientId,sub:u?.id,sid:d,exp:Math.floor(new Date(s.expiresAt).getTime()/1000),iat:Math.floor(new Date(s.createdAt).getTime()/1000),scope:s.scopes?.join(" "),token_type:Go(s.confirmation),...s.confirmation?{cnf:s.confirmation}:{}},requestedUserInfoClaims:s.requestedUserInfoClaims??[]}}async function UA(t,r,n,o){let i=await t.context.adapter.findOne({model:"oauthRefreshToken",where:[{field:"token",value:await tr(r.storeTokens,n,"refresh_token")}]});if(!i)throw new ce("BAD_REQUEST",{error_description:"token not found",error:"invalid_token"});if(!i.clientId||i.clientId!==o)return{active:!1};if(!i.expiresAt||i.expiresAt<new Date)return{active:!1};if(i.revoked)return{active:!1};let s=i.sessionId??void 0;if(s){let c=await t.context.adapter.findOne({model:"session",where:[{field:"id",value:s}]});if(!c||c.expiresAt<new Date)s=void 0}let a=void 0;if(i.userId)a=await t.context.internalAdapter.findUserById(i?.userId)??void 0;return{active:!0,client_id:o,iss:(r.disableJwtPlugin?void 0:Oe(t.context))?.options?.jwt?.issuer??t.context.baseURL,sub:a?.id,sid:s,exp:Math.floor(new Date(i.expiresAt).getTime()/1000),iat:Math.floor(new Date(i.createdAt).getTime()/1000),scope:i.scopes?.join(" "),token_type:Go(i.confirmation),...i.confirmation?{cnf:i.confirmation}:{}}}function _a(){return new ce("UNAUTHORIZED",{error_description:Bp,error:"invalid_token"},{"WWW-Authenticate":SA})}function CA(t){return t.status==="BAD_REQUEST"||t.body?.error==="invalid_token"}async function Mp(t,r,n,o){try{return{payload:await TA(t,r,n,o),requestedUserInfoClaims:[]}}catch(i){if(i instanceof ce);else if(i instanceof Error)throw i;else throw Error(i)}try{return await IA(t,r,n,o)}catch(i){if(i instanceof ce);else if(i instanceof Error)throw i;else throw Error("Unknown error validating access token")}throw _a()}async function Aa(t,r,n,o){return(await Mp(t,r,n,o)).payload}async function OA(t,r,n,o){let i=await Aa(t,r,n,o);if(i.active)return i;throw _a()}async function Hp(t,r,n,o){let{payload:i,requestedUserInfoClaims:s}=await Mp(t,r,n,o);if(i.active)return{payload:i,requestedUserInfoClaims:s};throw _a()}async function yp(t,r,n,o){if(!n.active||!n.sub)return n;let i=n.client_id??n.azp;if(!i)return n;let s=i===o.clientId?o:await ke(t,r,i);if(!s)return n;let a=await Tr(n.sub,s,r);return{...n,sub:a}}async function ka(t,r){let{token:n,token_type_hint:o}=t.body;if(o!=="access_token"&&o!=="refresh_token")o=void 0;let{clientId:i,clientSecret:s,preVerified:a,authMethod:c}=Ot(await Dt(t,r,`${t.context.baseURL}/oauth2/introspect`));if(!i||!s&&!a)throw new ce("UNAUTHORIZED",{error_description:"missing required credentials",error:"invalid_client"});if(n&&typeof n==="string")n=fn(n);if(!n?.length)throw new ce("BAD_REQUEST",{error_description:"missing a required token for introspection",error:"invalid_request"});let d=await Ct(t,r,i,s,void 0,a,void 0,c);try{if(o===void 0||o==="access_token")try{return yp(t,r,await Aa(t,r,n,d.clientId),d)}catch(u){if(u instanceof ce){if(o==="access_token")throw u}else if(u instanceof Error)throw u;else throw Error(u)}if(o===void 0||o==="refresh_token")try{return yp(t,r,await UA(t,r,(await Zo(r,n)).token,d.clientId),d)}catch(u){if(u instanceof ce){if(o==="refresh_token")throw u}else if(u instanceof Error)throw u;else throw Error(u)}throw new ce("BAD_REQUEST",{error_description:"token not found",error:"invalid_request"})}catch(u){if(u instanceof ce){if(CA(u))return{active:!1};throw u}else if(u instanceof Error)throw Ee.error("Introspection error:",u.message,u.stack),new ce("INTERNAL_SERVER_ERROR");else throw Ee.error("Introspection error:",u),new ce("INTERNAL_SERVER_ERROR")}}var Vp="1.7.12";function Ea(t){return t?.get("sec-fetch-mode")==="cors"}var{defineProperty:ba,getOwnPropertyDescriptor:DA,getOwnPropertyNames:LA}=Object,PA=Object.prototype.hasOwnProperty,Kp=(t,r)=>{let n={};for(var o in t)ba(n,o,{get:t[o],enumerable:!0});if(!r)ba(n,Symbol.toStringTag,{value:"Module"});return n},Fp=(t,r,n,o)=>{if(r&&typeof r==="object"||typeof r==="function"){for(var i=LA(r),s=0,a=i.length,c;s<a;s++)if(c=i[s],!PA.call(t,c)&&c!==n)ba(t,c,{get:((d)=>r[d]).bind(null,c),enumerable:!(o=DA(r,c))||o.enumerable})}return t},Wp=(t,r,n)=>(Fp(t,r,"default"),n&&Fp(n,r,"default"));function Jp(t,r){let n=r.id?{id:r.id}:{};for(let o in t){let i=t[o],s=r[o];if(s===void 0)continue;n[i.fieldName||o]=s}return n}function Qp(t,r){if(!r)return null;let n={id:r.id};for(let[o,i]of Object.entries(t))n[o]=r[i.fieldName||o];return n}var xA=5000,zA=2000,NA=250,qA=(t)=>`revoke-unproven-account-access:${t}`;async function jA(t,r){let n=Date.now()+zA;while(Date.now()<n){let o=await t.context.internalAdapter.findVerificationValue(r);if(!o)return;if(o.expiresAt<=new Date){await t.context.internalAdapter.deleteVerificationByIdentifier(r);return}await new Promise((i)=>setTimeout(i,NA))}}async function Gp(t,r){let n=qA(r);if(!await t.context.internalAdapter.reserveVerificationValue({identifier:n,value:r,expiresAt:new Date(Date.now()+xA)}).catch((o)=>{if(o instanceof te&&o.message.includes("requires database-backed verification storage"))return!0;throw o}))return await jA(t,n),t.context.internalAdapter.findUserById(r);try{let o=await t.context.internalAdapter.findUserById(r);if(!o||o.emailVerified)return o;let i=await t.context.internalAdapter.findAccounts(r);for(let s of i)await t.context.internalAdapter.deleteAccount(s.id);return await t.context.internalAdapter.deleteUserSessions(r),await t.context.internalAdapter.updateUser(r,{emailVerified:!0})}finally{await t.context.internalAdapter.deleteVerificationByIdentifier(n).catch(()=>{})}}var BA={string:e,number:_,boolean:E,date:ue};function Zp({fields:t,isClientSide:r}){let n=Object.keys(t).reduce((o,i)=>{let s=t[i];if(!s)return o;if(r&&s.input===!1)return o;let a;if(s.type==="json")a=Cs();else if(s.type==="string[]"||s.type==="number[]")a=A(s.type==="string[]"?e():_());else if(Array.isArray(s.type))a=N();else a=BA[s.type]();if(s?.required===!1)a=a.nullish();if(!r&&s?.returned===!1)return o;return{...o,[i]:a}},{});return l(n)}var $A=Kp({buildSyntheticUserOutput:()=>Nr,convertFromDB:()=>Qp,convertToDB:()=>Jp,createInternalAdapter:()=>Ac,getSchema:()=>qa,getSessionDefaultFields:()=>Kn,getWithHooks:()=>co,mergeSchema:()=>hc,parseAccountInput:()=>uc,parseAccountOutput:()=>Vn,parseAdditionalUserInput:()=>dc,parseAdditionalUserInputFromProviderProfile:()=>ur,parseInputData:()=>Bt,parseSessionInput:()=>Fn,parseSessionOutput:()=>we,parseUserInput:()=>dr,parseUserOutput:()=>se,revokeUnprovenAccountAccess:()=>Gp,toZodSchema:()=>Zp});Wp($A,ai);async function MA(t,r,n){let o=await Nt.get(),i=o?.query;if(!i)throw new U("BAD_REQUEST",{error_description:"missing oauth query",error:"invalid_request"});let s=new URLSearchParams(i),a=s.get("scope")?.split(" ")??[],c=Ln(r),d=Dn(s.get("claims"),c),u=s.get("client_id");if(!u)throw new U("BAD_REQUEST",{error_description:"client_id is required",error:"invalid_client"});let f=t.body.scope?.split(" ");if(f){if(!f.every((C)=>a?.includes(C)))throw new U("BAD_REQUEST",{error_description:"Scope not originally requested",error:"invalid_request"})}let p=t.body.claims,h=p!==void 0?Dn(p,c):d;if(p!==void 0&&!h.every((C)=>d.includes(C)))throw new U("BAD_REQUEST",{error_description:"Claim not originally requested",error:"invalid_request"});if(t.body.accept!==!0)return{redirect:!0,url:Ve(s.get("redirect_uri")??"","access_denied","User denied access",s.get("state")??void 0,Gn(t,r))};let m=await ee(t),w=ia(s.get("prompt")??"").has("login"),y=w&&ca(m?.session.createdAt,o?.signedQueryIssuedAt);if(w&&!y)return t?.headers?.set("accept","application/json"),t.query=nr(s),await n(t);let I=await sa(r,{user:m?.user,session:m?.session,scopes:f??a}),R=await aa(t,u,m?.user.id,I),b=Math.floor(Date.now()/1000),O=s.getAll("resource"),g={clientId:u,userId:m?.user.id,scopes:f??a,requestedUserInfoClaims:h,createdAt:new Date(b*1000),updatedAt:new Date(b*1000),resources:O.length?O:void 0,referenceId:I};if(R?.id?await t.context.adapter.update({model:"oauthConsent",where:[{field:"id",value:R.id}],update:{resources:g.resources,scopes:g.scopes,requestedUserInfoClaims:g.requestedUserInfoClaims,updatedAt:new Date(b*1000)}}):await t.context.adapter.create({model:"oauthConsent",data:{...g,scopes:g.scopes}}),f)s.set("scope",g.scopes.join(" "));if(p!==void 0){let C=bp(s.get("claims"),h);if(C)s.set("claims",JSON.stringify(C));else s.delete("claims")}t?.headers?.set("accept","application/json");let S=Ir(s,"consent");if(y)S=Ir(S,"login"),S=da(S);return t.query=nr(S),await n(t,{postLogin:o?.postLoginClearedForSession!==void 0&&o.postLoginClearedForSession===m?.session.id})}async function HA(t,r){if(t.body.selected===!0)return await VA(t,r);else if(t.body.created===!0)return await FA(t,r);else if(t.body.postLogin===!0)return await KA(t,r);else throw new U("BAD_REQUEST",{error_description:"Missing parameters",error:"invalid_request"})}async function VA(t,r){let n=(await Nt.get())?.query;if(!n)throw new U("BAD_REQUEST",{error_description:"missing oauth query",error:"invalid_request"});return t.headers?.set("accept","application/json"),t.query=nr(Ir(new URLSearchParams(n),"select_account")),await r(t)}async function FA(t,r){let n=(await Nt.get())?.query;if(!n)throw new U("BAD_REQUEST",{error_description:"missing oauth query",error:"invalid_request"});let o=new URLSearchParams(n);return t.headers?.set("accept","application/json"),t.query=nr(Ir(o,"create")),await r(t)}async function KA(t,r){let n=await Nt.get(),o=n?.query;if(!o)throw new U("BAD_REQUEST",{error_description:"missing oauth query",error:"invalid_request"});let i=new URLSearchParams(o);t.headers?.set("accept","application/json"),t.query=nr(i);let s=await ee(t);return await r(t,{postLogin:n?.postLoginClearedForSession!==void 0&&n.postLoginClearedForSession===s?.session.id,isPostLoginContinuation:!0})}var WA="http://schemas.openid.net/event/backchannel-logout",JA="logout+jwt",QA=120,GA=5000;async function ZA(t,r,n,o){return Wi(t,{options:r,payload:{...o,events:{[WA]:{}}},header:{typ:JA},resolvedKey:n??void 0})}async function YA(t,r,n){let{sessionId:o,userId:i}=n;if(!i)return null;let s=t.context.logger;try{let a=await X(t.context.adapter),c=[{field:"sessionId",value:o}],[d,u]=await Promise.all([a.findMany({model:"oauthAccessToken",where:c}),a.findMany({model:"oauthRefreshToken",where:c})]),f=new Set;for(let y of d)f.add(y.clientId);for(let y of u)f.add(y.clientId);if(f.size===0)return null;let p=await a.findMany({model:"oauthClient",where:[{field:"clientId",operator:"in",value:Array.from(f)}]}),h=d.filter((y)=>!y.revoked).map((y)=>y.id),m=u.filter((y)=>!y.revoked&&!y.scopes?.includes("offline_access")).map((y)=>y.id),w=r.disableJwtPlugin?[]:p.filter((y)=>Boolean(y.backchannelLogoutUri)&&!y.disabled);return{accessTokenIds:h,refreshTokenIds:m,sessionId:o,targets:(await Promise.all(w.map(async(y)=>{try{return{client:y,sub:await Tr(i,y,r)}}catch(I){return s.warn(`back-channel logout: unable to resolve subject for client ${y.clientId}`,I),null}}))).filter((y)=>y!==null)}}catch(a){return s.error("back-channel logout planning failed",a),null}}async function XA(t,r){let n=new Date,o=await X(t.context.adapter),i=await Promise.allSettled([r.accessTokenIds.length>0?o.updateMany({model:"oauthAccessToken",where:[{field:"id",operator:"in",value:r.accessTokenIds}],update:{revoked:n}}):Promise.resolve(),r.refreshTokenIds.length>0?o.updateMany({model:"oauthRefreshToken",where:[{field:"id",operator:"in",value:r.refreshTokenIds}],update:{revoked:n}}):Promise.resolve()]);for(let s of i)if(s.status==="rejected")t.context.logger.error("back-channel logout: token revocation update failed",s.reason);if(r.targets.length>0)await ek(t,r)}async function ek(t,r){let n=t.context.logger,o=Oe(t.context)?.options,i=o?.jwt?.issuer??t.context.baseURL,s=Math.floor(Date.now()/1000),a=s+QA,c=o?.jwt?.sign?null:await Ki(t,o);await Promise.allSettled(r.targets.map(async({client:d,sub:u})=>{try{let f=_e(32,"a-z","A-Z","0-9"),p=await ZA(t,o,c,{iss:i,aud:d.clientId,sub:u,sid:r.sessionId,iat:s,exp:a,jti:f}),h=await fetch(d.backchannelLogoutUri,{method:"POST",headers:{"Content-Type":"application/x-www-form-urlencoded",Accept:"application/json"},body:new URLSearchParams({logout_token:p}),signal:AbortSignal.timeout(GA),redirect:"error"});if(h.status!==200&&h.status!==204)n.warn(`back-channel logout to client ${d.clientId} returned ${h.status}`)}catch(f){n.warn(`back-channel logout to client ${d.clientId} failed`,f)}}))}var Yp=300,tk=".oauth_logout_confirmation";function oi(t){return t.replace(/[&<>"']/g,(r)=>{switch(r){case"&":return"&amp;";case"<":return"&lt;";case">":return"&gt;";case'"':return"&quot;";case"'":return"&#39;";default:return r}})}function zt(t){let r=t.request?.headers??t.headers;if(!r||Ea(r))return!1;let n=r.get("accept")??"";return r.get("sec-fetch-mode")==="navigate"||n.includes("text/html")||n.includes("application/xhtml+xml")}function Ca(t,r,n=200){return new Response(`<!doctype html><html><head><meta charset="utf-8"><title>${oi(t)}</title></head><body>${r}</body></html>`,{status:n,headers:{"cache-control":"no-store","content-security-policy":"default-src 'none'; form-action 'self'; base-uri 'none'; frame-ancestors 'none'","content-type":"text/html; charset=utf-8",pragma:"no-cache","x-content-type-options":"nosniff"}})}function ph(t){return`${t.context.baseURL.replace(/\/$/,"")}/oauth2/end-session/confirm`}function rk(t){try{return new URL(ph(t)).pathname}catch{return"/oauth2/end-session/confirm"}}function Xp(t){return Ca("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="${oi(ph(t))}"><button type="submit" name="action" value="confirm">Confirm logout</button></form></main>`)}function Ta(t){return Ca("Logged out",`<main><p data-oidc-logout-state="logged-out">${t?`Logged out. ${oi(t)}`:"Logged out."}</p></main>`)}function nk(t,r){return Ca("Logout error",`<main><h1>Logout error</h1><p data-oidc-logout-state="error">${oi(t)}</p></main>`,r)}function Fe(t,r,n,o){if(zt(t))return nk(o,r==="BAD_REQUEST"?400:r==="UNAUTHORIZED"?401:500);throw new ce(r,{error:n,error_description:o})}function Oa(t){return`${t.context.authCookies.sessionToken.name}${tk}`}function hh(t,r){return{...t.context.authCookies.sessionToken.attributes,httpOnly:!0,maxAge:r,path:rk(t),sameSite:"lax"}}async function eh(t,r,n={}){let o={...r?{sessionId:r}:{},...n,expiresAt:Date.now()+Yp*1000};await t.setSignedCookie(Oa(t),JSON.stringify(o),t.context.secret,hh(t,Yp))}async function ok(t){let r=await t.getSignedCookie(Oa(t),t.context.secret);if(typeof r!=="string")return null;try{let n=JSON.parse(r);if(typeof n!=="object"||n===null)return null;let o=n;if(o.sessionId!==void 0&&(typeof o.sessionId!=="string"||o.sessionId.length===0)||o.clientId!==void 0&&(typeof o.clientId!=="string"||o.clientId.length===0)||o.postLogoutRedirectUri!==void 0&&(typeof o.postLogoutRedirectUri!=="string"||o.postLogoutRedirectUri.length===0)||o.state!==void 0&&typeof o.state!=="string"||o.redirectInvalid!==void 0&&typeof o.redirectInvalid!=="boolean"||o.postLogoutRedirectUri!==void 0&&o.clientId===void 0||typeof o.expiresAt!=="number"||!Number.isFinite(o.expiresAt))return null;return{...typeof o.sessionId==="string"?{sessionId:o.sessionId}:{},...typeof o.clientId==="string"?{clientId:o.clientId}:{},...typeof o.postLogoutRedirectUri==="string"?{postLogoutRedirectUri:o.postLogoutRedirectUri}:{},...typeof o.state==="string"?{state:o.state}:{},...typeof o.redirectInvalid==="boolean"?{redirectInvalid:o.redirectInvalid}:{},expiresAt:o.expiresAt}}catch{return null}}function Ia(t){t.setCookie(Oa(t),"",hh(t,0))}async function mh(t){let r=await t.getSignedCookie(t.context.authCookies.sessionToken.name,t.context.secret);if(typeof r!=="string"||r.length===0)return null;try{let n=await t.context.internalAdapter.findSession(r);return n?{session:n.session}:null}catch(n){throw t.context.logger.error("Failed to read the current logout session",n),new ce("INTERNAL_SERVER_ERROR",{error:"server_error",error_description:"Unable to read the current session"})}}async function ik(t,r){try{return await t.context.adapter.findOne({model:"session",where:[{field:"id",value:r}]})}catch(n){throw t.context.logger.error("Failed to read the hinted logout session",n),new ce("INTERNAL_SERVER_ERROR",{error:"server_error",error_description:"Unable to read the hinted session"})}}async function gh(t,r){if(typeof r.token!=="string"||r.token.length===0)throw new ce("INTERNAL_SERVER_ERROR",{error:"server_error",error_description:"Unable to complete logout"});try{await t.context.internalAdapter.deleteSession(r.token)}catch(n){throw t.context.logger.error("Failed to delete the logout session",n),new ce("INTERNAL_SERVER_ERROR",{error:"server_error",error_description:"Unable to complete logout"})}}async function ri(t,r,n){try{return await ke(t,r,n)}catch(o){throw t.context.logger.error("Failed to resolve the logout client",o),new ce("INTERNAL_SERVER_ERROR",{error:"server_error",error_description:"Unable to resolve the logout client"})}}function wh(t){return(Array.isArray(t)?t:[t]).filter((r)=>typeof r==="string")}function sk(t){if(typeof t.aud==="string"&&t.aud.length>0)return t.aud;if(typeof t.azp==="string"&&t.azp.length>0)return t.azp;let r=wh(t.aud);return r.length===1?r[0]:null}async function ak(t,r,n,o){if(o)return ri(t,r,o);let i;try{i=en(n)}catch{return null}let s=sk(i);return s?ri(t,r,s):null}async function ck(t,r,n,o){try{let i;if(r.disableJwtPlugin){if(!o.clientSecret)return null;let s=await Sr(t,r.storeClientSecret,o.clientSecret),{payload:a}=await Gu(n,new TextEncoder().encode(s));i=JSON.parse(new TextDecoder().decode(a))}else{let s=Oe(t.context).options,{payload:a}=await Gu(n,Qo(await Ar(n,{jwksFetch:s?.jwks?.remoteUrl??`${t.context.baseURL}${s?.jwks?.jwksPath??"/jwks"}`})));i=JSON.parse(new TextDecoder().decode(a))}if(i.iss!==Gn(t,r))return null;if(!wh(i.aud).includes(o.clientId))return null;if(typeof i.sid!=="string"||i.sid.length===0||typeof i.sub!=="string"||i.sub.length===0)return null;return i}catch{return null}}function Da(t,r,n){if(!r)return{invalid:!1};if(!t.postLogoutRedirectUris?.includes(r))return{invalid:!0};if(!n)return{uri:r,invalid:!1};try{let o=new URL(r);return o.searchParams.set("state",n),{uri:o.toString(),invalid:!1}}catch{return{invalid:!0}}}function va(t,r){if(!r.post_logout_redirect_uri)return{};if(Da(t,r.post_logout_redirect_uri,r.state).invalid)return{redirectInvalid:!0};return{clientId:t.clientId,postLogoutRedirectUri:r.post_logout_redirect_uri,...r.state!==void 0?{state:r.state}:{}}}async function dk(t,r,n){if(n.redirectInvalid)return{invalid:!0};if(!n.clientId||!n.postLogoutRedirectUri)return{invalid:!1};let o=await ri(t,r,n.clientId);if(!o||o.disabled||!o.enableEndSession)return{invalid:!0};return Da(o,n.postLogoutRedirectUri,n.state)}async function ei(t,r,n={}){if(!r){if(zt(t))return await eh(t,void 0,n),Xp(t);return Fe(t,"BAD_REQUEST","invalid_request","No active session is available for logout")}if(!zt(t))return Fe(t,"BAD_REQUEST","invalid_request","User confirmation is required to complete logout");return await eh(t,r.session.id,n),Xp(t)}async function uk(t,r){let n=await ok(t),o=await mh(t);if(!n||n.expiresAt<=Date.now())return Fe(t,"BAD_REQUEST","invalid_request","The logout confirmation is invalid or expired");let i=await dk(t,r,n);if(!o){if(Ia(t),i.uri)return fe(t,i.uri);return zt(t)?Ta(i.invalid?"The requested post-logout redirect was not registered.":void 0):Fe(t,"BAD_REQUEST","invalid_request","No active session is available for logout")}if(n.sessionId&&n.sessionId!==o.session.id)return Fe(t,"BAD_REQUEST","invalid_request","The logout confirmation is invalid or expired");if(await gh(t,o.session),Le(t),Ia(t),i.uri)return fe(t,i.uri);return zt(t)?Ta(i.invalid?"The requested post-logout redirect was not registered.":void 0):null}async function lk(t,r){let n=t.query??{},o=t.body??{},i={...n,...o},s=await mh(t);if(i.id_token_hint===void 0){let m={};if(i.client_id){let w=await ri(t,r,i.client_id);if(!w)return Fe(t,"BAD_REQUEST","invalid_client","The logout client does not exist");if(w.disabled)return Fe(t,"BAD_REQUEST","invalid_client","The logout client is disabled");if(!w.enableEndSession)return Fe(t,"UNAUTHORIZED","invalid_client","The client is not allowed to initiate logout");m=va(w,i)}return ei(t,s,m)}let a=await ak(t,r,i.id_token_hint,i.client_id);if(!a){if(s&&zt(t))return ei(t,s);return Fe(t,"BAD_REQUEST","invalid_client","The logout client does not exist")}if(a.disabled)return Fe(t,"BAD_REQUEST","invalid_client","The logout client is disabled");if(!a.enableEndSession)return Fe(t,"UNAUTHORIZED","invalid_client","The client is not allowed to initiate logout");let c=await ck(t,r,i.id_token_hint,a);if(!c){if(s&&zt(t))return ei(t,s,i.client_id?va(a,i):{});return Fe(t,"UNAUTHORIZED","invalid_token","The id_token_hint is invalid")}let d=c.sid,u=await ik(t,d),f=s?.session.id===d;if(s&&!f)return ei(t,s,va(a,i));let p=Da(a,i.post_logout_redirect_uri,i.state),h=u??(f?s?.session:null);if(h)await gh(t,h);if(f)Le(t);if(Ia(t),p.uri)return fe(t,p.uri);return zt(t)?Ta(p.invalid?"The requested post-logout redirect was not registered.":void 0):null}async function fk(t,r){return uk(t,r)}function Gy(t,r,n){let o=t.context.baseURL,i=!n?.jwt_disabled;return{scopes_supported:n?.scopes_supported,issuer:Wh(r?.jwt?.issuer??o),authorization_endpoint:`${o}/oauth2/authorize`,token_endpoint:`${o}/oauth2/token`,jwks_uri:n?.jwt_disabled?void 0:r?.jwks?.remoteUrl??`${o}${r?.jwks?.jwksPath??"/jwks"}`,registration_endpoint:n?.dynamic_client_registration_supported?`${o}/oauth2/register`:void 0,introspection_endpoint:`${o}/oauth2/introspect`,revocation_endpoint:`${o}/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:[...Kt],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:[...Kt],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:[...Kt],code_challenge_methods_supported:["S256"],authorization_response_iss_parameter_supported:!0,dpop_signing_alg_values_supported:n?.dpop_signing_alg_values_supported??[...ja],backchannel_logout_supported:i,backchannel_logout_session_supported:i}}function yh(t,r){let n=r.disableJwtPlugin?void 0:Oe(t.context).options,o=Rn(r),i=r.allowUnauthenticatedClientRegistration||o.length>0;return{jwtPluginOptions:n,clientDiscoveries:o,authMetadata:Gy(t,n,{scopes_supported:r.advertisedMetadata?.scopes_supported??r.scopes,dynamic_client_registration_supported:r.allowDynamicClientRegistration,public_client_supported:i,grant_types_supported:Rr(r),token_endpoint_auth_methods_supported:Po(r,{includeNone:i}),endpoint_auth_methods_supported:Po(r),jwt_disabled:r.disableJwtPlugin,dpop_signing_alg_values_supported:r.dpop?.signingAlgorithms})}}function Yg(t,r){let{clientDiscoveries:n,authMetadata:o}=yh(t,r);return Zs(t,r,"oauth-authorization-server",{...oa(n),...o})}function hf(t,r){let n=t.context.baseURL,{jwtPluginOptions:o,clientDiscoveries:i,authMetadata:s}=yh(t,r),a={...s,claims_supported:Ln(r),claims_parameter_supported:!0,userinfo_endpoint:`${n}/oauth2/userinfo`,subject_types_supported:r.pairwiseSecret?["public","pairwise"]:["public"],acr_values_supported:["0"],id_token_signing_alg_values_supported:(()=>{if(r.disableJwtPlugin)return["HS256"];let c=o?.jwks?.keyPairConfig?.alg??"EdDSA",d=o?.jwks?.keyPairConfigs?.map((u)=>u.alg)??[];return Array.from(new Set([c,...d]))})(),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 Zs(t,r,"openid-configuration",{...oa(i),...a})}var pk="public, max-age=15, stale-while-revalidate=15, stale-if-error=86400";function Al(t,r){let n=new Headers(r);if(!n.has("Cache-Control"))n.set("Cache-Control",pk);return n.set("Content-Type","application/json"),new Response(JSON.stringify(t),{status:200,headers:n})}var lP=(t,r)=>async(n)=>Al(await t.api.getOAuthServerConfig({request:n,asResponse:!1}),r?.headers),cP=(t,r)=>async(n)=>Al(await t.api.getOpenIdConfig({request:n,asResponse:!1}),r?.headers);function Pt(t,r,n){let{redirectOnError:o,onValidationError:i,errorCodesByField:s,defaultError:a="invalid_request",...c}=r;if(!o)return Pe(t,{...c,onValidationError:async(m)=>{if(i)await i(m);throw new ce("BAD_REQUEST",{...Ua(m.issues,s,a)})}},n);let d=o,{body:u,query:f,...p}=c;async function h(m,w,y){if(!y)return{ok:!0};let I=await y.safeParseAsync(m[w]??{});if(I.success)return m[w]=I.data,{ok:!0};if(i)await i({message:I.error.message,issues:I.error.issues});return{ok:!1,response:d({...Ua(I.error.issues,s,a),ctx:m})}}return Pe(t,p,async(m)=>{let w=await h(m,"body",u);if(!w.ok)return w.response;let y=await h(m,"query",f);if(!y.ok)return y.response;return n(m)})}function Ua(t,r,n="invalid_request"){let o=t[0];if(!o)return{error:n,error_description:"Invalid request."};let i=o.path?.[0],s=typeof i==="string"?i:void 0,a=s?r?.[s]:void 0,c=o.path?.length?aA(o.path):"";return{error:hk(o,a,n),error_description:gk(o,c)}}function hk(t,r,n){if(typeof r==="string")return r;if(mk(t))return r?.missing??n;if(t.code==="invalid_value")return r?.invalid??n;return n}function mk(t){return t.code==="invalid_type"&&t.message.endsWith("received undefined")}function gk(t,r){if(!r)return t.message;if(t.code==="invalid_type"){if(t.message.endsWith("received undefined"))return`${r} is required`;if(t.message.endsWith("received array"))return`${r} must not appear more than once`;return`${r} must be a ${t.expected??"valid value"}`}if(t.code==="invalid_value"){let n=t.values;if(Array.isArray(n)&&n.length>0)return`${r} must be one of: ${n.join(", ")}`}return`${r}: ${t.message}`}var wk=(t)=>Sn(async(r)=>{if(!t.allowPublicClientPrelogin)throw new U("BAD_REQUEST");let n=r.body.oauth_query;if(!await ra(n,r.context.secret))throw new U("UNAUTHORIZED",{error:"invalid_signature"})}),_h={"P-256":"ES256","P-384":"ES384","P-521":"ES512"},yk=["Ed25519"],_k=["d","p","q","dp","dq","qi","oth"];function th(t){return typeof t==="object"&&t!==null&&!Array.isArray(t)}function xn(t,r){return typeof t[r]==="string"&&t[r].length>0}function Ah(t){return typeof t==="string"&&Object.prototype.hasOwnProperty.call(_h,t)}function kh(t){return yk.some((r)=>r===t)}function Ak(t){switch(t.kty){case"RSA":return xn(t,"n")&&xn(t,"e");case"EC":return Ah(t.crv)&&xn(t,"x")&&xn(t,"y");case"OKP":return kh(t.crv)&&xn(t,"x");default:return!1}}function kk(t){if(t.alg===void 0)return!0;if(typeof t.alg!=="string"||!Kt.some((r)=>r===t.alg))return!1;switch(t.kty){case"RSA":return t.alg.startsWith("RS")||t.alg.startsWith("PS");case"EC":return Ah(t.crv)&&_h[t.crv]===t.alg;case"OKP":return kh(t.crv)&&t.alg==="EdDSA";default:return!1}}function Eh(t){let r=th(t)&&Array.isArray(t.keys)?t.keys:void 0;if(!r?.length)return{valid:!1,error:"jwks must be an RFC 7517 JWK Set object with a non-empty keys array"};for(let n of r){if(!th(n))return{valid:!1,error:"jwks keys must be supported public JWKs with required key parameters"};if(n.kty==="oct"||"k"in n||_k.some((o)=>(o in n)))return{valid:!1,error:"jwks must contain only public asymmetric keys"};if(!Ak(n))return{valid:!1,error:"jwks keys must be supported public JWKs with required key parameters"};if(!kk(n))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:r}}}function bh(t){let r=Eh(t);if(!r.valid)throw new U("BAD_REQUEST",{error:"invalid_client_metadata",error_description:r.error})}var Ek=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,tokenEndpointAuthMethod:!0,grantTypes:!0,responseTypes:!0,applicationType:!0,jwks:!0,jwksUri:!0,requirePKCE:!0,dpopBoundAccessTokens:!0,skipConsent:!0,enableEndSession:!0,subjectType:!0,referenceId:!0,metadata:!0})),bk=["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","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"],vk=new Set([...Ek,...bk,"public","type","resources","client_credentials_scopes"]);function vh(t){if(!t)return;return Object.fromEntries(Object.entries(t).filter(([r])=>!vk.has(r)))}async function at(t,r,n,o,i){if(!r)throw new U("UNAUTHORIZED");if(!t.headers)throw new U("BAD_REQUEST");if(o==="configure-client-credentials-scopes"&&!n.clientPrivileges)throw new U("UNAUTHORIZED");if(n.clientPrivileges&&!await n.clientPrivileges({headers:t.headers,action:o,session:r.session,user:r.user,clientId:i}))throw new U("UNAUTHORIZED")}async function qt(t,r,n,o,i){if(!r)throw new U("UNAUTHORIZED");if(!t.headers)throw new U("BAD_REQUEST");if(!n.resourcePrivileges)return;if(!await n.resourcePrivileges({headers:t.headers,action:o,session:r.session,user:r.user,resourceId:i}))throw new U("UNAUTHORIZED")}var uP=Co({consumeClientAssertion:()=>Xg,isPrivateHostname:()=>ni,verifyClientAssertion:()=>Uh}),rh=new WeakMap,nh=300000,Sk=500,Rk=5000,oh=65536,Tk=/^application\/(?:[-\w.]+\+)?json\s*(?:;|$)/i;function Sh(t,r,n,o){if(t.set(r,{jwks:n,fetchedAt:o}),t.size>Sk){let i=t.keys().next().value;if(i!==void 0)t.delete(i)}}function Rh(t){let r=rh.get(t);if(r)return r;let n=new Map;return rh.set(t,n),n}function Th(t){return`${t.clientDiscoveryId??"managed"}:${t.jwksUri??""}`}var ih=[...Kt];function ni(t){return!ld(t)}function Ik(t,r,n){let o=new URL(r);if(o.protocol!=="https:")throw new ce("BAD_REQUEST",{error_description:"jwks_uri must use HTTPS",error:"invalid_client"});if(o.username||o.password)throw new ce("BAD_REQUEST",{error_description:"jwks_uri must not contain credentials",error:"invalid_client"});if(r.includes("#"))throw new ce("BAD_REQUEST",{error_description:"jwks_uri must not include a fragment component",error:"invalid_client"});if(ni(o.hostname))throw new ce("BAD_REQUEST",{error_description:"jwks_uri must not point to a private or reserved address",error:"invalid_client"});if(n&&o.origin===n)return;if(!t.context.isTrustedOrigin(o.href))throw new ce("BAD_REQUEST",{error_description:"client jwks_uri is not trusted",error:"invalid_client"})}function Uk(t){try{let r=new URL(t);if(r.protocol!=="https:"&&r.protocol!=="http:")return;return r.origin}catch{return}}async function Ck(t){let r=t.headers.get("content-length");if(r!==null&&Number.isFinite(Number(r))&&Number(r)>oh)throw await t.body?.cancel(),Error("JWKS response exceeds 64 KiB");if(!t.body)return"";let n=t.body.getReader(),o=[],i=0;while(!0){let{done:c,value:d}=await n.read();if(c)break;if(i+=d.byteLength,i>oh)throw await n.cancel(),Error("JWKS response exceeds 64 KiB");o.push(d)}let s=new Uint8Array(i),a=0;for(let c of o)s.set(c,a),a+=c.byteLength;return new TextDecoder().decode(s)}async function Ih(t,r=globalThis.fetch){let n=new AbortController,o=setTimeout(()=>n.abort(),Rk);try{let i=await r(t,{signal:n.signal,headers:{accept:"application/json"},redirect:"error"});if(i.redirected)throw Error("JWKS fetch redirected");if(i.status!==200)throw Error(`JWKS fetch returned ${i.status}`);let s=i.headers.get("content-type");if(!s||!Tk.test(s))throw Error("JWKS response must use a JSON media type");let a=await Ck(i),c;try{c=JSON.parse(a)}catch{return{valid:!1}}let d=Eh(c);if(!d.valid)return{valid:!1};return{valid:!0,jwks:d.jwks}}finally{clearTimeout(o)}}function sh(){return new ce("BAD_REQUEST",{error_description:"failed to fetch client JWKS",error:"invalid_client"})}async function Ok(t,r,n){if(n.jwks)return JSON.parse(n.jwks);if(!n.jwksUri)throw new ce("BAD_REQUEST",{error_description:"client has no JWKS configured",error:"invalid_client"});let o=n.clientDiscoveryId?Rn(r).find((u)=>u.id===n.clientDiscoveryId):void 0;if(n.clientDiscoveryId&&!o?.fetchClientMetadataResource)throw new ce("BAD_REQUEST",{error_description:"client discovery does not provide a metadata resource transport",error:"invalid_client"});Ik(t,n.jwksUri,n.clientDiscoveryId?Uk(n.clientId):void 0);let i=Date.now(),s=Th(n),a=Rh(r),c=a.get(s);if(c&&i-c.fetchedAt<nh)return c.jwks;let d;try{d=await Ih(n.jwksUri,o?.fetchClientMetadataResource)}catch{let u=nh*2;if(c&&i-c.fetchedAt<u)return c.jwks;throw sh()}if(!d.valid)throw sh();return Sh(a,s,d.jwks,i),d.jwks}async function Dk(t,r){if(!r.jwksUri)return null;let n=r.clientDiscoveryId?Rn(t).find((o)=>o.id===r.clientDiscoveryId):void 0;if(r.clientDiscoveryId&&!n?.fetchClientMetadataResource)return null;try{let o=await Ih(r.jwksUri,n?.fetchClientMetadataResource);if(!o.valid)return null;return Sh(Rh(t),Th(r),o.jwks,Date.now()),o.jwks}catch{return null}}async function Xg(t,r,n){let{namespace:o,payload:i,expectedAudience:s}=n;if(!(Array.isArray(i.aud)?i.aud:i.aud!=null?[i.aud]:[]).includes(s))throw new ce("BAD_REQUEST",{error_description:"client assertion aud does not match the endpoint",error:"invalid_client"});let a=r.assertionMaxLifetime??300,c=Math.floor(Date.now()/1000);if(typeof i.exp!=="number")throw new ce("BAD_REQUEST",{error_description:"client assertion must include exp claim",error:"invalid_client"});if(i.exp<=c)throw new ce("BAD_REQUEST",{error_description:"client assertion has expired",error:"invalid_client"});if(i.exp-c>a)throw new ce("BAD_REQUEST",{error_description:`client assertion exp is too far in the future (max ${a}s)`,error:"invalid_client"});if(typeof i.iat==="number"&&c-i.iat>a)throw new ce("BAD_REQUEST",{error_description:`client assertion iat is too far in the past (max ${a}s)`,error:"invalid_client"});if(typeof i.jti!=="string"||i.jti.length===0)throw new ce("BAD_REQUEST",{error_description:"client assertion must include jti claim",error:"invalid_client"});let d=await cs("SHA-256").digest(new TextEncoder().encode(`${o}:${i.jti}`)),u=Tf(new Uint8Array(d).slice(0,24),t.context.options);try{await t.context.adapter.create({model:"oauthClientAssertion",data:{id:u,expiresAt:new Date(i.exp*1000)},forceAllowId:!0})}catch(f){let p=!1;try{p=Boolean(await t.context.adapter.findOne({model:"oauthClientAssertion",where:[{field:"id",value:u}]}))}catch{}if(p)throw new ce("BAD_REQUEST",{error_description:"client assertion jti has already been used",error:"invalid_client"});throw f}}async function Uh(t,r,n,o,i,s,a){if(o!==Wt)throw new ce("BAD_REQUEST",{error_description:"unsupported client_assertion_type",error:"invalid_client"});let c;try{c=so(n)}catch{throw new ce("BAD_REQUEST",{error_description:"malformed client assertion: invalid JWT header",error:"invalid_client"})}if(!c.alg||!ih.includes(c.alg))throw new ce("BAD_REQUEST",{error_description:`unsupported assertion signing algorithm: ${c.alg}`,error:"invalid_client"});let d;try{d=en(n)}catch{throw new ce("BAD_REQUEST",{error_description:"malformed client assertion: invalid JWT payload",error:"invalid_client"})}let u=d.sub??d.iss;if(!u)throw new ce("BAD_REQUEST",{error_description:"client assertion must contain sub or iss claim identifying the client",error:"invalid_client"});if(i&&i!==u)throw new ce("BAD_REQUEST",{error_description:"client_id in body does not match assertion sub/iss",error:"invalid_client"});let f=await ke(t,r,u);if(!f)throw new ce("BAD_REQUEST",{error_description:"client not found",error:"invalid_client"});if(f.disabled)throw new ce("BAD_REQUEST",{error_description:"client is disabled",error:"invalid_client"});if(f.tokenEndpointAuthMethod!=="private_key_jwt")throw new ce("BAD_REQUEST",{error_description:"client is not registered for private_key_jwt authentication",error:"invalid_client"});a?.assertClient?.(f);let p=await Ok(t,r,f),h=s??`${t.context.baseURL}/oauth2/token`,m=Gn(t,r),w=a?.endpointAudienceOnly?[h]:[...new Set([h,m])],y={issuer:u,subject:u,audience:w,algorithms:ih},I;try{({payload:I}=await Qr(n,Qo(p),y))}catch(b){if(b instanceof Error&&/no matching key|no applicable key/i.test(b.message)){let O=await Dk(r,f);if(O)try{({payload:I}=await Qr(n,Qo(O),y))}catch{throw new ce("UNAUTHORIZED",{error_description:"client assertion signature verification failed",error:"invalid_client"})}else throw new ce("UNAUTHORIZED",{error_description:"client assertion signature verification failed",error:"invalid_client"})}else throw new ce("UNAUTHORIZED",{error_description:"client assertion signature verification failed",error:"invalid_client"})}let R=(Array.isArray(I.aud)?I.aud:[I.aud]).find((b)=>typeof b==="string"&&w.includes(b));return await Xg(t,r,{namespace:`private_key_jwt:${u}`,payload:I,expectedAudience:R}),{clientId:u,client:f}}function Sa(t,r,n){return new ce(t,{error:r,error_description:n},{"WWW-Authenticate":`Bearer error="${r}"`,...Zr})}async function Lk(t,r,n){let o=t.headers,i;try{i=sp(o?.get("authorization"))}catch{throw Sa("BAD_REQUEST","invalid_request","Malformed initial access token Authorization header")}if(!i||!o)return;if(!r.validateInitialAccessToken)throw Sa("UNAUTHORIZED","invalid_token","Invalid initial access token");let s;try{s=await r.validateInitialAccessToken({initialAccessToken:i,headers:o,clientMetadata:n})}catch(a){if(a instanceof ce)throw a;throw new ce("INTERNAL_SERVER_ERROR",{error:"server_error",error_description:"Initial access token validation failed"})}if(!s)throw Sa("UNAUTHORIZED","invalid_token","Invalid initial access token");return s}var Pk=["authorization_code"];function Ch(t){return[...new Set([...t.clientRegistrationDefaultScopes??t.scopes??[],...t.clientRegistrationAllowedScopes??[]])]}function Oh(t){let r=t.grant_types??[...Pk];if(r.length>0)return r;throw new U("BAD_REQUEST",{error:"invalid_client_metadata",error_description:"grant_types must contain at least one grant type"})}function xk(t,r){if(t.response_types)return t.response_types;return r.includes("authorization_code")?["code"]:void 0}function Dh(t,r){let n=new Set(Rr(t)),o=r.filter((i)=>n.has(i));if(o.length===0)throw new U("BAD_REQUEST",{error:"invalid_client_metadata",error_description:`no mutually supported grant_type among ${r.join(", ")}`});return o}function Lh(t,r="web"){let n=Oh(t);return{...t,token_endpoint_auth_method:t.token_endpoint_auth_method??"client_secret_basic",application_type:t.application_type??(r===null?void 0:r),grant_types:n,response_types:xk(t,n)}}function zk(t){let r=new URL(t);return r.protocol!=="http:"&&r.protocol!=="https:"&&r.host!==""}function Nk(t){try{let r=new URL(t).protocol;return r!=="http:"&&r!=="https:"}catch{return!1}}function Ph(t,r){let n=t.clientRegistrationDefaultApplicationType??"web";if(n!=="infer")return n;return(r.redirect_uris??[]).some((o)=>Nk(o)||xh(o))?"native":"web"}function or(t){throw new U("BAD_REQUEST",{error:"invalid_redirect_uri",error_description:t})}function qk(t){let r=/^http:\/\/([^/?#]*)/i.exec(t)?.[1];if(!r)return null;let n=r.slice(r.lastIndexOf("@")+1);if(n.startsWith("[")){let o=n.indexOf("]");return o<0?null:n.slice(0,o+1).toLowerCase()}return(n.split(":")[0]??"").toLowerCase()}function xh(t){let r=qk(t);return r==="localhost"||r==="127.0.0.1"||r==="[::1]"}function jk(t,r){let n=new Set([...t.clientRegistrationDefaultResources??[],...t.clientRegistrationAllowedResources??[]]);for(let o of r)if(!n.has(o))throw new U("BAD_REQUEST",{error:"invalid_target",error_description:`requested resource ${o} is not allowed for client registration`})}async function Bk(t,r,n){let o=r.clientRegistrationDefaultResources??[],i=[...new Set([...o,...n])];for(let s of i){let a=await Wo(t,r,s);if(!a)throw new U("BAD_REQUEST",{error:"invalid_target",error_description:`requested resource ${s} does not exist`});if(a.disabled)throw new U("BAD_REQUEST",{error:"invalid_target",error_description:`requested resource ${s} is disabled`})}return i}function $k(t,r){let n;try{n=new URL(t)}catch{or(`redirect URI must be an absolute URI: ${t}`)}if(t.includes("#")||n.username.length>0||n.password.length>0)or(`redirect URI must not include credentials or a fragment: ${t}`);let o=n.protocol==="http:",i=n.protocol==="https:";if(/^localhost\.+$/i.test(n.hostname))or(`redirect URI localhost must not include trailing dots: ${t}`);let s=Fi(n.hostname)||n.hostname==="localhost";if(r==="web"){if(!i||s)or(`web clients require https redirect URIs on non-loopback hosts: ${t}`);return}if(i){if(s)or(`native clients must not use https loopback redirect URIs: ${t}`);return}if(o){if(!xh(t))or(`native clients may use http only on the exact loopback hosts localhost, 127.0.0.1, or [::1]: ${t}`);return}if(!cp(n))or(`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: ${t}`)}async function Mk(t,r){let n=t.body;if(!r.allowDynamicClientRegistration)throw new U("FORBIDDEN",{error:"access_denied",error_description:"Client registration is disabled"});let o=await ee(t),i=o?void 0:await Lk(t,r,n),s=Boolean(i);if(!(o||s||r.allowUnauthenticatedClientRegistration))throw new U("UNAUTHORIZED",{error_description:"Authentication required for client registration"},{"WWW-Authenticate":"Bearer",...Zr});let a=n.grant_types?.length?Dh(r,n.grant_types):n.grant_types,c=n.grant_types?.includes("authorization_code")&&!a?.includes("authorization_code"),d={...n,grant_types:a,response_types:c?void 0:n.response_types};if(!o&&!s){if(d.grant_types?.includes("client_credentials"))throw new U("BAD_REQUEST",{error:"invalid_client_metadata",error_description:"client_credentials grant requires authenticated registration"})}let u=Array.isArray(n.resources)?n.resources.filter((h)=>typeof h==="string"&&h.length>0):[];if(o)await at(t,o,r,"create");let f=i?.referenceId??(o&&r.clientReference?await r.clientReference({user:o.user,session:o.session}):void 0),p=await jh(t,r,{metadata:d,registrationSource:"dynamic",userId:f?void 0:o?.session.userId,referenceId:f,requestedResources:u});return t.setStatus(201),t.json(p)}async function zh(t,r,n){let o=n?.registrationSource==="clientMetadataDocument",i=Lh(t,o?null:n?.registrationSource==="dynamic"?Ph(r,t):"web"),s=i.token_endpoint_auth_method??"client_secret_basic";if(!new Set(Po(r,{includeNone:!0})).has(s))throw new U("BAD_REQUEST",{error:"invalid_client_metadata",error_description:`unsupported token_endpoint_auth_method ${s}`});if(i.dpop_bound_access_tokens!==void 0&&typeof i.dpop_bound_access_tokens!=="boolean")throw new U("BAD_REQUEST",{error:"invalid_client_metadata",error_description:"dpop_bound_access_tokens must be a boolean"});let a=i.grant_types??[],{response_types:c,application_type:d}=i;if(d!==void 0&&d!=="web"&&d!=="native")throw new U("BAD_REQUEST",{error:"invalid_client_metadata",error_description:"application_type must be web or native"});if(a.includes("authorization_code")&&(!i.redirect_uris||i.redirect_uris.length===0))throw new U("BAD_REQUEST",{error:"invalid_redirect_uri",error_description:"Redirect URIs are required for authorization_code and implicit grant types"});for(let h of i.redirect_uris??[])$k(h,d??(o?"native":"web"));if(o)Dh(r,a);else{let h=new Set(Rr(r));for(let m of a)if(!h.has(m))throw new U("BAD_REQUEST",{error:"invalid_client_metadata",error_description:`unsupported grant_type ${m}`})}if(a.includes("authorization_code")&&!c?.includes("code"))throw new U("BAD_REQUEST",{error:"invalid_client_metadata",error_description:"When 'authorization_code' grant type is used, 'code' response type must be included"});if(!a.includes("authorization_code")&&c?.includes("code"))throw new U("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 U("BAD_REQUEST",{error:"invalid_client_metadata",error_description:'subject_type must be "public" or "pairwise"'});if(i.subject_type==="pairwise"&&!r.pairwiseSecret)throw new U("BAD_REQUEST",{error:"invalid_client_metadata",error_description:"pairwise subject_type requires server pairwiseSecret configuration"});if(i.subject_type==="pairwise"&&i.redirect_uris?.some(zk))throw new U("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){if(new Set(i.redirect_uris.map((h)=>new URL(h).host)).size>1)throw new U("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 u=i?.scope?.split(" ").filter((h)=>h.length),f=n?.registrationSource==="dynamic"||n?.registrationSource==="clientMetadataDocument",p=f?Ch(r):r.scopes;if(p){let h=new Set(p);for(let m of u??[])if(!h?.has(m))throw new U("BAD_REQUEST",{error:"invalid_scope",error_description:`cannot request scope ${m}`})}if(f&&i.require_pkce===!1)throw new U("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 U("BAD_REQUEST",{error:"invalid_client_metadata",error_description:"jwks and jwks_uri are mutually exclusive"});if(i.jwks_uri)try{let h=new URL(i.jwks_uri);if(h.protocol!=="https:")throw new U("BAD_REQUEST",{error:"invalid_client_metadata",error_description:"jwks_uri must use HTTPS"});if(h.username||h.password)throw new U("BAD_REQUEST",{error:"invalid_client_metadata",error_description:"jwks_uri must not contain credentials"});if(i.jwks_uri.includes("#"))throw new U("BAD_REQUEST",{error:"invalid_client_metadata",error_description:"jwks_uri must not include a fragment component"});if(ni(h.hostname))throw new U("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(h.href)){let m=typeof i.client_id==="string"?i.client_id:void 0;if(!(o&&m!==void 0&&URL.canParse(m)&&new URL(m).origin===h.origin))throw new U("BAD_REQUEST",{error:"invalid_client_metadata",error_description:"jwks_uri must belong to a trusted origin or the Client ID Metadata Document origin"})}}catch(h){if(h instanceof U)throw h;throw new U("BAD_REQUEST",{error:"invalid_client_metadata",error_description:"jwks_uri must be a valid URL"})}if(i.jwks)bh(i.jwks)}if(s==="private_key_jwt"&&!i.jwks&&!i.jwks_uri)throw new U("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(r.disableJwtPlugin)throw new U("BAD_REQUEST",{error:"invalid_client_metadata",error_description:"backchannel_logout_uri requires the jwt plugin (disableJwtPlugin must be false)"});let h;try{h=new URL(i.backchannel_logout_uri)}catch{throw new U("BAD_REQUEST",{error:"invalid_client_metadata",error_description:"backchannel_logout_uri must be an absolute URL"})}if(i.backchannel_logout_uri.includes("#"))throw new U("BAD_REQUEST",{error:"invalid_client_metadata",error_description:"backchannel_logout_uri must not include a fragment component"});if(h.protocol!=="https:")throw new U("BAD_REQUEST",{error:"invalid_client_metadata",error_description:"backchannel_logout_uri must use https"});if(h.username||h.password)throw new U("BAD_REQUEST",{error:"invalid_client_metadata",error_description:"backchannel_logout_uri must not contain credentials"});if(ni(h.hostname))throw new U("BAD_REQUEST",{error:"invalid_client_metadata",error_description:"backchannel_logout_uri must not point to a private or reserved address"})}}var ah=Symbol("client-registration-collision");async function Nh(t,r,n){let o=n.registrationSource==="dynamic"&&!n.metadata.scope?{...n.metadata,scope:(r.clientRegistrationDefaultScopes??r.scopes)?.join(" ")}:n.metadata,i=Lh(o,n.registrationSource==="clientMetadataDocument"?null:n.registrationSource==="dynamic"?Ph(r,o):"web"),s=i.token_endpoint_auth_method==="none",a=i.token_endpoint_auth_method==="private_key_jwt",c=Gs(r,i.token_endpoint_auth_method);await zh(i,r,{registrationSource:n.registrationSource,ctx:t});let d=n.clientId??r.generateClientId?.()??_e(32,"a-z","A-Z"),u=s||a||c?void 0:r.generateClientSecret?.()||_e(32,"a-z","A-Z"),f=u?await No(t,r,u):void 0,p=n.registrationSource==="dynamic"&&!s&&r.clientRegistrationRequirePKCE===!1,h=i.require_pkce??(p?!1:void 0),m=Math.floor(Date.now()/1000),{resources:w,...y}=n.registrationSource==="dynamic"||n.registrationSource==="clientMetadataDocument"?{...i,scope:Ch(r).join(" ")}:i,I=n.registrationSource==="clientMetadataDocument"?void 0:{userId:n.userId,referenceId:n.referenceId},R=$h({...y,redirect_uris:i.redirect_uris??[],disabled:void 0,client_secret_expires_at:f?n.registrationSource==="dynamic"&&r.clientRegistrationClientSecretExpiration?Yt(r.clientRegistrationClientSecretExpiration,m):0:void 0,client_id:d,client_secret:f,client_id_issued_at:m,require_pkce:h,user_id:I?.referenceId?void 0:I?.userId,reference_id:I?.referenceId});if(R.clientCredentialsScopes=n.registrationSource==="managed"?n.clientCredentialsScopes??[]:[],R.clientDiscoveryId=n.registrationSource==="clientMetadataDocument"?n.clientDiscoveryId:null,n.registrationSource==="clientMetadataDocument"&&i.application_type===void 0)R.applicationType=null;let b=n.registrationSource==="clientMetadataDocument"?[]:n.requestedResources??[];if(n.registrationSource==="dynamic")jk(r,b);let O=await Bk(t,r,b),g=r.schema?.oauthClient?.modelName??"oauthClient",S=r.schema?.oauthClientResource?.modelName??"oauthClientResource",C=n.registrationSource==="clientMetadataDocument"?n.existingClient:void 0,z=n.registrationSource==="clientMetadataDocument"?n.clientDiscoveryId:null,L=await Ue(t.context.adapter,async()=>{let x=await X(t.context.adapter),P,j=!1;if(C){let{clientCredentialsScopes:W,disabled:Q,skipConsent:G,enableEndSession:M,...Y}=R,Z=await x.update({model:g,where:[{field:"clientId",value:d},{field:"clientDiscoveryId",value:z}],update:{...Y,createdAt:C.createdAt,updatedAt:new Date(m*1000)}});if(!Z)throw new U("BAD_REQUEST",{error:"invalid_client",error_description:"client no longer exists"});P=Z}else{try{P=await x.create({model:g,data:{...R,createdAt:new Date(m*1000),updatedAt:new Date(m*1000)}})}catch(W){if(n.registrationSource==="clientMetadataDocument"&&ch(W))throw{[ah]:!0,kind:"oauth-client-row-unique",clientId:d,cause:W};throw W}j=!0}let B=O.length===0?[]:await x.findMany({model:S,where:[{field:"clientId",value:d}]}),H=new Set(B.map((W)=>W.resourceId)),q=new Date;for(let W of O){if(H.has(W))continue;try{await x.create({model:S,data:{clientId:d,resourceId:W,createdAt:q}})}catch(Q){if(n.registrationSource==="clientMetadataDocument"&&ch(Q))throw{[ah]:!0,kind:"oauth-client-resource-link-unique",clientId:d,resourceId:W,cause:Q};throw Q}}return{client:P,created:j}});return{client:L.client,clientSecret:u,resources:O,created:L.created}}function qh(t,r){let n=ht({...t.client,clientSecret:t.clientSecret?(r.prefix?.clientSecret??"")+t.clientSecret:void 0});if(t.resources.length>0)n.resources=t.resources;return n}function Hk(t,r){return{...qh(t,r),client_credentials_scopes:[...t.client.clientCredentialsScopes??[]]}}async function jh(t,r,n){return qh(await Nh(t,r,n),r)}async function Vk(t,r,n){return Hk(await Nh(t,r,n),r)}function ch(t){if(!t||typeof t!=="object")return!1;let r=t,n=String(r.code??r.errno??"");if(["1062","11000","23505","ER_DUP_ENTRY","P2002","SQLITE_CONSTRAINT_UNIQUE"].includes(n))return!0;if(r.name==="MongoServerError"&&r.code===11000)return!0;return typeof r.message==="string"&&/(?:duplicate|unique constraint|unique key)/i.test(r.message)}async function Bh(t,r,n){let o=await ee(t);if(await at(t,o,r,"create"),!o)throw new U("UNAUTHORIZED");let i=r.clientReference?await r.clientReference({user:o.user,session:o.session}):void 0,{client_credentials_scopes:s,...a}=t.body,c=n?.admin?wa(s??[]):[];if(ya(c,Oh(a),a.token_endpoint_auth_method,r),c.length>0)await at(t,o,r,"configure-client-credentials-scopes");let d=n?.admin?a.resources:void 0;for(let p of new Set(d??[]))await qt(t,o,r,"link",p);let u={metadata:a,registrationSource:"managed",userId:i?void 0:o.session.userId,referenceId:i,clientCredentialsScopes:c,...d?{requestedResources:d}:{}},f=n?.admin?await Vk(t,r,u):await jh(t,r,u);return t.setStatus(201),t.json(f)}function $h(t){let{client_id:r,client_secret:n,client_secret_expires_at:o,scope:i,user_id:s,client_id_issued_at:a,client_name:c,client_uri:d,logo_uri:u,contacts:f,tos_uri:p,policy_uri:h,jwks:m,jwks_uri:w,software_id:y,software_version:I,software_statement:R,redirect_uris:b,post_logout_redirect_uris:O,backchannel_logout_uri:g,backchannel_logout_session_required:S,token_endpoint_auth_method:C,grant_types:z,response_types:L,application_type:x,disabled:P,skip_consent:j,enable_end_session:B,require_pkce:H,dpop_bound_access_tokens:q,subject_type:W,reference_id:Q,metadata:G}=t,M=o?new Date(Number(o)*1000):void 0,Y=a?new Date(a*1000):void 0,Z=i?.split(" "),re=vh(G??{}),ie=re&&Object.keys(re).length?JSON.stringify(re):void 0;return{clientId:r,clientSecret:n,disabled:P,scopes:Z,userId:s,createdAt:Y,expiresAt:M,name:c,uri:d,icon:u,contacts:f,tos:p,policy:h,softwareId:y,softwareVersion:I,softwareStatement:R,redirectUris:b,postLogoutRedirectUris:O,backchannelLogoutUri:g,backchannelLogoutSessionRequired:S,tokenEndpointAuthMethod:C,grantTypes:z,responseTypes:L,jwks:m?JSON.stringify(m):void 0,jwksUri:w,applicationType:x,skipConsent:j,enableEndSession:B,requirePKCE:H,dpopBoundAccessTokens:q,subjectType:W,referenceId:Q,metadata:ie}}function ht(t){let{clientId:r,clientSecret:n,disabled:o,scopes:i,userId:s,createdAt:a,updatedAt:c,expiresAt:d,name:u,uri:f,icon:p,contacts:h,tos:m,policy:w,softwareId:y,softwareVersion:I,softwareStatement:R,redirectUris:b,postLogoutRedirectUris:O,backchannelLogoutUri:g,backchannelLogoutSessionRequired:S,tokenEndpointAuthMethod:C,grantTypes:z,responseTypes:L,applicationType:x,jwks:P,jwksUri:j,skipConsent:B,enableEndSession:H,requirePKCE:q,dpopBoundAccessTokens:W,subjectType:Q,referenceId:G,metadata:M}=t,Y=d?Math.round(new Date(d).getTime()/1000):void 0,Z=a?Math.round(new Date(a).getTime()/1000):void 0,re=i?.join(" ");return{...vh(rr(M)),client_id:r,client_secret:n??void 0,client_secret_expires_at:n?Y??0:void 0,scope:re??void 0,user_id:s??void 0,client_id_issued_at:Z??void 0,client_name:u??void 0,client_uri:f??void 0,logo_uri:p??void 0,contacts:h??void 0,tos_uri:m??void 0,policy_uri:w??void 0,jwks:P?JSON.parse(P):void 0,jwks_uri:j??void 0,software_id:y??void 0,software_version:I??void 0,software_statement:R??void 0,redirect_uris:b??[],post_logout_redirect_uris:O??void 0,backchannel_logout_uri:g??void 0,backchannel_logout_session_required:S??void 0,token_endpoint_auth_method:C??void 0,grant_types:z??void 0,response_types:L??void 0,application_type:x??void 0,disabled:o??void 0,skip_consent:B??void 0,enable_end_session:H??void 0,require_pkce:q??void 0,dpop_bound_access_tokens:W??void 0,subject_type:Q??void 0,reference_id:G??void 0}}async function Fk(t,r){let n=await ee(t);if(await at(t,n,r,"read",t.query.client_id),!n)throw new U("UNAUTHORIZED");let o=await ke(t,r,t.query.client_id);if(!o)throw new U("NOT_FOUND",{error_description:"client not found",error:"not_found"});if(o.userId){if(o.userId!==n.user.id)throw new U("UNAUTHORIZED")}else if(o.referenceId&&r.clientReference){if(o.referenceId!==await r.clientReference(n))throw new U("UNAUTHORIZED")}else throw new U("UNAUTHORIZED");let i=ht(o);return i.client_secret=void 0,i}async function Mh(t,r,n){let o=await ke(t,r,n);if(!o)throw new U("NOT_FOUND",{error_description:"client not found",error:"not_found"});if(o.disabled)throw new U("NOT_FOUND",{error_description:"client not found",error:"not_found"});return ht({clientId:o.clientId,name:o.name,uri:o.uri,contacts:o.contacts,icon:o.icon,tos:o.tos,policy:o.policy})}async function Kk(t,r){let n=await ee(t);if(await at(t,n,r,"list"),!n)throw new U("UNAUTHORIZED");let o=await r.clientReference?.(n);if(o)return await t.context.adapter.findMany({model:"oauthClient",where:[{field:"referenceId",value:o}]}).then((i)=>{if(!i)return null;return i.map((s)=>{let a=ht(s);return a.client_secret=void 0,a})});else if(n.user.id)return await t.context.adapter.findMany({model:"oauthClient",where:[{field:"userId",value:n.user.id}]}).then((i)=>{if(!i)return null;return i.map((s)=>{let a=ht(s);return a.client_secret=void 0,a})});else throw new U("BAD_REQUEST",{message:"either user_id or reference_id must be provided"})}async function Wk(t,r){let n=await ee(t);if(await at(t,n,r,"delete",t.body.client_id),!n)throw new U("UNAUTHORIZED");let o=t.body.client_id;Un(r,o);let i=await ke(t,r,o);if(!i)throw new U("NOT_FOUND",{error_description:"client not found",error:"not_found"});if(i.userId){if(i.userId!==n.user.id)throw new U("UNAUTHORIZED")}else if(i.referenceId&&r.clientReference){if(i.referenceId!==await r.clientReference(n))throw new U("UNAUTHORIZED")}else throw new U("UNAUTHORIZED");await t.context.adapter.delete({model:"oauthClient",where:[{field:"clientId",value:o}]})}async function Hh(t,r,n){let o=await ee(t);if(await at(t,o,r,"update",t.body.client_id),!o)throw new U("UNAUTHORIZED");let i=t.body.client_id;Un(r,i);let s=await ke(t,r,i);if(!s)throw new U("NOT_FOUND",{error_description:"client not found",error:"not_found"});let{client_credentials_scopes:a,...c}=t.body.update,d=s.userId?s.userId===o.user.id:s.referenceId&&r.clientReference?s.referenceId===await r.clientReference(o):!1,u=!d&&n?.admin&&a!==void 0&&Object.keys(c).length===0;if(!d&&!u)throw new U("UNAUTHORIZED");if(u)await at(t,o,r,"configure-client-credentials-scopes",i);if(Object.keys(c).length===0&&a===void 0){let I=ht(s);if(I.client_secret=void 0,n?.admin)return{...I,client_credentials_scopes:[...s.clientCredentialsScopes??[]]};return I}let f=c.grant_types??s.grantTypes??[],p=c.token_endpoint_auth_method??s.tokenEndpointAuthMethod,h=a===void 0?void 0:wa(a);if(h!==void 0){if(ya(h,f,p,r),h.length>0&&!u)await at(t,o,r,"configure-client-credentials-scopes",i)}await zh({...ht(s),...c},r,{ctx:t});let m={...$h(c)};if(!f.includes("client_credentials")||p==="none")m.clientCredentialsScopes=[];else if(h!==void 0)m.clientCredentialsScopes=h;if(c.token_endpoint_auth_method){if(c.token_endpoint_auth_method==="private_key_jwt")m.clientSecret=null;else if(m.jwks=null,m.jwksUri=null,!m.clientSecret)m.clientSecret=await No(t,r,r.generateClientSecret?.()||_e(32,"a-z","A-Z"))}let w=await t.context.adapter.update({model:"oauthClient",where:[{field:"clientId",value:i}],update:{...m,updatedAt:new Date(Math.floor(Date.now()/1000)*1000)}});if(!w)throw new U("INTERNAL_SERVER_ERROR",{error_description:"unable to update client",error:"invalid_client"});let y=ht(w);if(y.client_secret=void 0,n?.admin)return{...y,client_credentials_scopes:[...w.clientCredentialsScopes??[]]};return y}async function Jk(t,r){let n=await ee(t);if(await at(t,n,r,"rotate",t.body.client_id),!n)throw new U("UNAUTHORIZED");let o=t.body.client_id;Un(r,o);let i=await ke(t,r,o);if(!i)throw new U("NOT_FOUND",{error_description:"client not found",error:"not_found"});if(i.userId){if(i.userId!==n.user.id)throw new U("UNAUTHORIZED")}else if(i.referenceId&&r.clientReference){if(i.referenceId!==await r.clientReference(n))throw new U("UNAUTHORIZED")}else throw new U("UNAUTHORIZED");if(i.tokenEndpointAuthMethod==="none"||!i.clientSecret)throw new U("BAD_REQUEST",{error_description:"secret rotation is only available for clients using client_secret authentication",error:"invalid_client"});let s=r.generateClientSecret?.()||_e(32,"a-z","A-Z"),a=s?await No(t,r,s):void 0,c=await t.context.adapter.update({model:"oauthClient",where:[{field:"clientId",value:o}],update:{clientSecret:a,updatedAt:new Date(Math.floor(Date.now()/1000)*1000)}});if(!c)throw new U("INTERNAL_SERVER_ERROR",{error_description:"unable to update client",error:"invalid_client"});return ht({...c,clientSecret:(r.prefix?.clientSecret??"")+s})}async function Qk(t,r){if(!r.allowClientKeyRotation)throw new U("FORBIDDEN",{error:"access_denied",error_description:"Client key rotation is disabled"});let{body:n}=t;bh(n.jwks);let{client:o}=await Uh(t,r,n.client_assertion,n.client_assertion_type,void 0,Jo({context:t.context,request:void 0},"/oauth2/client/rotate-keys"),{endpointAudienceOnly:!0,assertClient:(i)=>Gk(r,i)});if(!await t.context.adapter.incrementOne({model:"oauthClient",where:[{field:"clientId",value:o.clientId},{field:"jwks",value:o.jwks}],increment:{},set:{jwks:JSON.stringify(n.jwks),updatedAt:new Date}}))throw new U("CONFLICT",{error:"invalid_request",error_description:"client keys changed while rotating; retry with a fresh client assertion"});return{client_id:o.clientId,jwks:n.jwks}}function Gk(t,r){if(Un(t,r.clientId),r.clientDiscoveryId||r.jwksUri||!r.jwks)throw new U("BAD_REQUEST",{error:"invalid_client",error_description:"client keys are not stored inline; rotate them where the client publishes them"})}var Vh=e().trim().min(1),ii=A(e().trim().min(1)).min(1),Zk=(t)=>Pe("/admin/oauth2/create-client",{method:"POST",body:l({redirect_uris:A(le).min(1).optional(),scope:e().optional(),client_name:e().optional(),client_uri:e().optional(),logo_uri:e().optional(),contacts:A(e().min(1)).min(1).optional(),tos_uri:e().optional(),policy_uri:e().optional(),software_id:e().optional(),software_version:e().optional(),software_statement:e().optional(),post_logout_redirect_uris:A(le).min(1).optional(),backchannel_logout_uri:le.optional(),backchannel_logout_session_required:E().optional(),token_endpoint_auth_method:Vh.optional(),application_type:T(["web","native"]).optional(),jwks:Pn.optional(),jwks_uri:e().optional(),grant_types:ii.optional(),client_credentials_scopes:A(e().trim().min(1)).optional(),resources:A(Qs).optional(),response_types:A(T(["code"])).optional(),client_secret_expires_at:D([e(),_()]).optional().default(0),skip_consent:E().optional(),enable_end_session:E().optional(),require_pkce:E().optional(),dpop_bound_access_tokens:E().optional(),subject_type:T(["public","pairwise"]).optional(),metadata:k(e(),J()).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(r)=>Bh(r,t,{admin:!0})),Yk=(t)=>Pe("/oauth2/create-client",{method:"POST",use:[Hr],body:l({redirect_uris:A(le).min(1).optional(),scope:e().optional(),client_name:e().optional(),client_uri:e().optional(),logo_uri:e().optional(),contacts:A(e().min(1)).min(1).optional(),tos_uri:e().optional(),policy_uri:e().optional(),software_id:e().optional(),software_version:e().optional(),software_statement:e().optional(),post_logout_redirect_uris:A(le).min(1).optional(),backchannel_logout_uri:le.optional(),backchannel_logout_session_required:E().optional(),token_endpoint_auth_method:Vh.optional(),application_type:T(["web","native"]).optional(),jwks:Pn.optional(),jwks_uri:e().optional(),grant_types:ii.optional(),response_types:A(T(["code"])).optional(),dpop_bound_access_tokens:E().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(r)=>Bh(r,t)),Xk=(t)=>Pe("/oauth2/get-client",{method:"GET",use:[Hr],query:l({client_id:e()}),metadata:{openapi:{description:"Get OAuth2 formatted client details"}}},async(r)=>Fk(r,t)),eE=(t)=>Pe("/oauth2/public-client",{method:"GET",use:[Hr],query:l({client_id:e()}),metadata:{openapi:{description:"Gets publicly available client fields"}}},async(r)=>{let n=r.query.client_id;return Mh(r,t,n)}),tE=(t)=>Pe("/oauth2/public-client-prelogin",{method:"POST",use:[wk(t)],body:l({client_id:e(),oauth_query:e().optional()}),metadata:{openapi:{description:"Gets publicly available client fields (prior to login)"}}},async(r)=>{let n=r.body.client_id;return Mh(r,t,n)}),rE=(t)=>Pe("/oauth2/get-clients",{method:"GET",use:[Hr],metadata:{openapi:{description:"Get OAuth2 formatted client details for a user or organization"}}},async(r)=>Kk(r,t)),nE=(t)=>Pe("/admin/oauth2/update-client",{method:"PATCH",body:l({client_id:e(),update:l({redirect_uris:A(le).min(1).optional(),scope:e().optional(),client_name:e().optional(),client_uri:e().optional(),logo_uri:e().optional(),contacts:A(e().min(1)).min(1).optional(),tos_uri:e().optional(),policy_uri:e().optional(),software_id:e().optional(),software_version:e().optional(),software_statement:e().optional(),post_logout_redirect_uris:A(le).min(1).optional(),backchannel_logout_uri:le.optional(),backchannel_logout_session_required:E().optional(),application_type:T(["web","native"]).optional(),grant_types:ii.optional(),client_credentials_scopes:A(e().trim().min(1)).optional(),response_types:A(T(["code"])).optional(),client_secret_expires_at:D([e(),_()]).optional(),skip_consent:E().optional(),enable_end_session:E().optional(),disabled:E().optional(),dpop_bound_access_tokens:E().optional(),metadata:k(e(),J()).optional()})}),metadata:{SERVER_ONLY:!0,openapi:{description:"Updates OAuth2 formatted client details."}}},async(r)=>Hh(r,t,{admin:!0})),oE=(t)=>Pe("/oauth2/update-client",{method:"POST",use:[Hr],body:l({client_id:e(),update:l({redirect_uris:A(le).min(1).optional(),scope:e().optional(),client_name:e().optional(),client_uri:e().optional(),logo_uri:e().optional(),contacts:A(e().min(1)).min(1).optional(),tos_uri:e().optional(),policy_uri:e().optional(),software_id:e().optional(),software_version:e().optional(),software_statement:e().optional(),post_logout_redirect_uris:A(le).min(1).optional(),backchannel_logout_uri:le.optional(),backchannel_logout_session_required:E().optional(),application_type:T(["web","native"]).optional(),grant_types:ii.optional(),response_types:A(T(["code"])).optional()})}),metadata:{openapi:{description:"Updates OAuth2 formatted client details."}}},async(r)=>Hh(r,t)),iE=(t)=>Pe("/oauth2/client/rotate-secret",{method:"POST",use:[Hr],body:l({client_id:e()}),metadata:{noStore:!0,openapi:{description:"Rotates a confidential client's secret"}}},async(r)=>Jk(r,t)),sE=(t)=>Pt("/oauth2/client/rotate-keys",{method:"POST",body:l({client_assertion:e(),client_assertion_type:e(),jwks:Pn}),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(r)=>Qk(r,t)),aE=(t)=>Pe("/oauth2/delete-client",{method:"POST",use:[Hr],body:l({client_id:e()}),metadata:{openapi:{description:"Deletes an oauth client"}}},async(r)=>Wk(r,t));async function La(t,r,n){return await t.context.adapter.findOne({model:"oauthConsent",where:[{field:"id",value:n}]})}async function cE(t,r){let n=await ee(t);if(!n)throw new U("UNAUTHORIZED");let{id:o}=t.query;if(!o)throw new U("NOT_FOUND",{error_description:"missing id parameter",error:"not_found"});let i=await La(t,r,o);if(!i)throw new U("NOT_FOUND",{error_description:"no consent",error:"not_found"});if(i.userId!==n.user.id)throw new U("UNAUTHORIZED");return i}async function dE(t,r){let n=await ee(t);if(!n)throw new U("UNAUTHORIZED");return await t.context.adapter.findMany({model:"oauthConsent",where:[{field:"userId",value:n.user.id}]})}async function uE(t,r){let n=await ee(t);if(!n)throw new U("UNAUTHORIZED");let{id:o}=t.body;if(!o)throw new U("NOT_FOUND",{error_description:"missing id parameter",error:"not_found"});let i=await La(t,r,o);if(!i)throw new U("NOT_FOUND",{error_description:"no consent",error:"not_found"});if(i.userId!==n.user.id)throw new U("UNAUTHORIZED");await t.context.adapter.delete({model:"oauthConsent",where:[{field:"id",value:o}]})}async function lE(t,r){let n=await ee(t);if(!n)throw new U("UNAUTHORIZED");let{id:o}=t.body;if(!o)throw new U("NOT_FOUND",{error_description:"missing id parameter",error:"not_found"});let i=await La(t,r,o);if(!i)throw new U("NOT_FOUND",{error_description:"no consent",error:"not_found"});if(i.userId!==n.user.id)throw new U("UNAUTHORIZED");let s=await ke(t,r,i.clientId);if(!s)throw new U("NOT_FOUND",{error_description:"client not found",error:"not_found"});let a=s?.scopes??r.scopes??[],c=t.body.update,d=c.scopes;if(d&&!d.every((f)=>a?.includes(f)))throw new U("BAD_REQUEST",{error_description:`unable to provide scopes to ${s?.referenceId??s?.userId}`,error:"invalid_request"});let u=Math.floor(Date.now()/1000);return await t.context.adapter.update({model:"oauthConsent",where:[{field:"id",value:o}],update:{...c,updatedAt:new Date(u*1000)}})}var fE=(t)=>Pe("/oauth2/get-consent",{method:"GET",query:l({id:e()}),use:[Hr],metadata:{openapi:{description:"Gets details of a specific OAuth2 consent for a user"}}},async(r)=>cE(r,t)),pE=(t)=>Pe("/oauth2/get-consents",{method:"GET",use:[Hr],metadata:{openapi:{description:"Gets all available OAuth2 consents for a user"}}},async(r)=>dE(r,t)),hE=(t)=>Pe("/oauth2/update-consent",{method:"POST",use:[Hr],body:l({id:e(),update:l({scopes:A(e())})}),metadata:{openapi:{description:"Updates consent granted to a client."}}},async(r)=>lE(r,t)),mE=(t)=>Pe("/oauth2/delete-consent",{method:"POST",use:[Hr],body:l({id:e()}),metadata:{openapi:{description:"Deletes consent granted to a client"}}},async(r)=>uE(r,t)),mt=(t)=>t.schema?.oauthResource?.modelName??"oauthResource",Fh=(t)=>t.schema?.oauthClientResource?.modelName??"oauthClientResource",gE=(t)=>t.schema?.oauthClient?.modelName??"oauthClient";function sr(t){try{return decodeURIComponent(t)}catch{return t}}function wE(t,r){return{identifier:t.identifier,name:t.name??t.identifier,accessTokenTtl:t.accessTokenTtl??null,refreshTokenTtl:t.refreshTokenTtl??null,signingAlgorithm:t.signingAlgorithm??null,signingKeyId:t.signingKeyId??null,allowedScopes:t.allowedScopes??null,customClaims:t.customClaims??null,dpopBoundAccessTokensRequired:t.dpopBoundAccessTokensRequired??!1,disabled:t.disabled??!1,policyVersion:1,metadata:t.metadata??null,createdAt:r,updatedAt:r}}async function yE(t,r){await qt(t,await ee(t),r,"create");let n=t.body;if(!n?.identifier)throw new U("BAD_REQUEST",{error:"invalid_request",error_description:"identifier is required"});await Rp(r,n.identifier);let o=new Date,i;try{i=await t.context.adapter.create({model:mt(r),data:wE(n,o)})}catch(s){let a=s instanceof Error?s.message:String(s);if(/unique|duplicate|UNIQUE/i.test(a))throw new U("BAD_REQUEST",{error:"invalid_request",error_description:`resource ${n.identifier} already exists`});throw s}if(!i)throw new U("BAD_REQUEST",{error:"invalid_request",error_description:`resource ${n.identifier} could not be created`});return Ko(i.identifier),t.json(i,{status:201})}async function _E(t,r){await qt(t,await ee(t),r,"list");let n=await t.context.adapter.findMany({model:mt(r)});return t.json(n??[])}async function AE(t,r){let n=sr(t.params.identifier);await qt(t,await ee(t),r,"read",n);let o=await t.context.adapter.findOne({model:mt(r),where:[{field:"identifier",value:n}]});if(!o)throw new U("NOT_FOUND",{error:"not_found",error_description:`resource ${n} not found`});return t.json(o)}async function kE(t,r){let n=sr(t.params.identifier);if(await qt(t,await ee(t),r,"update",n),!await t.context.adapter.findOne({model:mt(r),where:[{field:"identifier",value:n}]}))throw new U("NOT_FOUND",{error:"not_found",error_description:`resource ${n} not found`});let o={updatedAt:new Date};for(let s of["name","accessTokenTtl","refreshTokenTtl","signingAlgorithm","signingKeyId","allowedScopes","customClaims","dpopBoundAccessTokensRequired","disabled","metadata"])if(Object.prototype.hasOwnProperty.call(t.body,s))o[s]=t.body[s];await t.context.adapter.update({model:mt(r),where:[{field:"identifier",value:n}],update:o}),Ko(n);let i=await t.context.adapter.findOne({model:mt(r),where:[{field:"identifier",value:n}]});if(!i)throw new U("NOT_FOUND",{error:"not_found",error_description:`resource ${n} not found`});return t.json(i)}async function EE(t,r){let n=sr(t.params.identifier);if(await qt(t,await ee(t),r,"delete",n),!await t.context.adapter.findOne({model:mt(r),where:[{field:"identifier",value:n}]}))throw new U("NOT_FOUND",{error:"not_found",error_description:`resource ${n} not found`});return await t.context.adapter.delete({model:mt(r),where:[{field:"identifier",value:n}]}),Ko(n),t.json({deleted:!0})}async function bE(t,r){let n=await ee(t),o=sr(t.params.identifier),i=sr(t.params.client_id);if(await qt(t,n,r,"link",o),!await t.context.adapter.findOne({model:mt(r),where:[{field:"identifier",value:o}]}))throw new U("NOT_FOUND",{error:"not_found",error_description:`resource ${o} not found`});if(!await t.context.adapter.findOne({model:gE(r),where:[{field:"clientId",value:i}]}))throw new U("NOT_FOUND",{error:"not_found",error_description:`client ${i} not found`});try{await t.context.adapter.create({model:Fh(r),data:{clientId:i,resourceId:o,createdAt:new Date}})}catch(s){let a=s instanceof Error?s.message:String(s);if(/unique|duplicate|UNIQUE/i.test(a))return t.json({linked:!0,alreadyLinked:!0});throw s}return t.json({linked:!0})}async function vE(t,r){let n=await ee(t),o=sr(t.params.identifier),i=sr(t.params.client_id);return await qt(t,n,r,"unlink",o),await t.context.adapter.deleteMany({model:Fh(r),where:[{field:"clientId",value:i},{field:"resourceId",value:o}]}),t.json({unlinked:!0})}var Kh=l({identifier:e().min(1).optional(),name:e().optional(),accessTokenTtl:_().int().positive().nullable().optional(),refreshTokenTtl:_().int().positive().nullable().optional(),signingAlgorithm:T(Ho).nullable().optional(),signingKeyId:e().nullable().optional(),allowedScopes:A(e()).nullable().optional(),customClaims:k(e(),J()).nullable().optional(),dpopBoundAccessTokensRequired:E().optional(),disabled:E().optional(),metadata:k(e(),J()).nullable().optional()}),SE=(t)=>Pe("/admin/oauth2/resources",{method:"POST",body:Kh.required({identifier:!0}),metadata:{SERVER_ONLY:!0}},async(r)=>yE(r,t)),RE=(t)=>Pe("/admin/oauth2/resources",{method:"GET",metadata:{SERVER_ONLY:!0}},async(r)=>_E(r,t)),TE=(t)=>Pe("/admin/oauth2/resources/:identifier",{method:"GET",metadata:{SERVER_ONLY:!0}},async(r)=>AE(r,t)),IE=(t)=>Pe("/admin/oauth2/resources/:identifier",{method:"PATCH",body:Kh,metadata:{SERVER_ONLY:!0}},async(r)=>kE(r,t)),UE=(t)=>Pe("/admin/oauth2/resources/:identifier",{method:"DELETE",metadata:{SERVER_ONLY:!0}},async(r)=>EE(r,t)),CE=(t)=>Pe("/admin/oauth2/resources/:identifier/clients/:client_id",{method:"POST",metadata:{SERVER_ONLY:!0}},async(r)=>bE(r,t)),OE=(t)=>Pe("/admin/oauth2/resources/:identifier/clients/:client_id",{method:"DELETE",metadata:{SERVER_ONLY:!0}},async(r)=>vE(r,t));async function DE(t,r,n){if(r.disableJwtPlugin)throw new ce("BAD_REQUEST",{error_description:"JWT access tokens are disabled",error:"invalid_request"});let o=Oe(t.context),i=o.options,s;try{s=(await Qr(n,Qo(await Ar(n,{jwksFetch:i?.jwks?.remoteUrl?i.jwks.remoteUrl:async()=>(await o.endpoints.getJwks(t))?.response,jwksCacheKey:o})),{issuer:i?.jwt?.issuer??t.context.baseURL})).payload}catch(c){if(c instanceof yi||c instanceof jr)return null;if(c instanceof TypeError||xo(c))throw new ce("BAD_REQUEST",{error_description:"invalid JWT signature",error:"invalid_request"});throw c}let a=`${t.context.baseURL}/oauth2/userinfo`;if(!s.azp||!await Fo(t,r,s.aud,[a]))return null;throw new ce("BAD_REQUEST",{error_description:"JWT access tokens are self-contained and cannot be revoked server-side",error:"unsupported_token_type"})}async function LE(t,r,n,o){let i=n;if(r.prefix?.opaqueAccessToken)if(i.startsWith(r.prefix.opaqueAccessToken))i=i.replace(r.prefix.opaqueAccessToken,"");else throw new ce("BAD_REQUEST",{error_description:"opaque access token not found",error:"invalid_request"});let s=await t.context.adapter.findOne({model:"oauthAccessToken",where:[{field:"token",value:await tr(r.storeTokens,i,"access_token")}]});if(!s)throw new ce("BAD_REQUEST",{error_description:"opaque access token not found",error:"invalid_request"});if(!s.clientId||s.clientId!==o)return null;s.id?await t.context.adapter.delete({model:"oauthAccessToken",where:[{field:"id",value:s.id}]}):await t.context.adapter.delete({model:"oauthAccessToken",where:[{field:"token",value:s.token}]})}async function PE(t,r,n,o){let i=await t.context.adapter.findOne({model:"oauthRefreshToken",where:[{field:"token",value:await tr(r.storeTokens,n,"refresh_token")}]});if(!i)throw new ce("BAD_REQUEST",{error_description:"token not found",error:"invalid_request"});if(i.revoked)throw await Yo(t,o,i.userId),new ce("BAD_REQUEST",{error_description:"refresh token revoked",error:"invalid_request"});if(!i.clientId||i.clientId!==o)return null;let s=Math.floor(Date.now()/1000);if(!await t.context.adapter.incrementOne({model:"oauthRefreshToken",where:[{field:"id",value:i.id},{field:"revoked",operator:"eq",value:null}],increment:{},set:{revoked:new Date(s*1000)}}))throw await Yo(t,o,i.userId),new ce("BAD_REQUEST",{error_description:"refresh token revoked",error:"invalid_request"});await t.context.adapter.deleteMany({model:"oauthAccessToken",where:[{field:"refreshId",value:i.id}]})}async function xE(t,r,n,o){try{return await DE(t,r,o)}catch(i){if(i instanceof ce){if(i.body?.error==="unsupported_token_type")throw i}else if(i instanceof Error)throw i;else throw Error(i)}try{return await LE(t,r,o,n)}catch(i){if(i instanceof ce);else if(i instanceof Error)throw i;else throw Error("Unknown error validating access token")}throw new ce("BAD_REQUEST",{error_description:"Invalid access token",error:"invalid_request"})}async function zE(t,r){let{token:n,token_type_hint:o}=t.body;if(o!=="access_token"&&o!=="refresh_token")o=void 0;let{clientId:i,clientSecret:s,preVerified:a,authMethod:c}=Ot(await Dt(t,r,`${t.context.baseURL}/oauth2/revoke`));if(!i)throw new ce("UNAUTHORIZED",{error_description:"missing required credentials",error:"invalid_client"});if(typeof n==="string")n=fn(n);if(!n?.length)throw new ce("BAD_REQUEST",{error_description:"missing a required token for introspection",error:"invalid_request"});let d=await Ct(t,r,i,s,void 0,a,void 0,c);try{if(o===void 0||o==="access_token")try{return await xE(t,r,d.clientId,n)}catch(u){if(u instanceof ce){if(o==="access_token"||u.body?.error==="unsupported_token_type")throw u}else if(u instanceof Error)throw u;else throw Error(u)}if(o===void 0||o==="refresh_token")try{return await PE(t,r,(await Zo(r,n)).token,d.clientId)}catch(u){if(u instanceof ce){if(o==="refresh_token")throw u}else if(u instanceof Error)throw u;else throw Error(u)}throw new ce("BAD_REQUEST",{error_description:"token not found",error:"invalid_request"})}catch(u){if(u instanceof ce){if(u.body?.error==="unsupported_token_type")throw u;if(u.name==="BAD_REQUEST")return null;throw u}else if(u instanceof Error)throw Ee.error("Introspection error:",u.message,u.stack),new ce("INTERNAL_SERVER_ERROR");else throw Ee.error("Introspection error:",u),new ce("INTERNAL_SERVER_ERROR")}}var NE={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},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},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},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}}}},Vy=["openid","profile","email","offline_access"],dh=l({id_token_hint:e().optional(),client_id:e().optional(),post_logout_redirect_uri:le.optional(),state:e().optional()}),Nt=Et(()=>null),dP=Nt.get,ti=new WeakMap,uh="signedQueryIssuedAtMs";function qE(t){let r=typeof t==="number"?t:typeof t==="string"?Number(t):void 0;if(!r||!Number.isFinite(r)||r<=0)return;return new Date(r)}var gf=(t)=>{let r=t.clientRegistrationAllowedScopes;if(t.clientRegistrationDefaultScopes){let u=r?new Set([...r,...t.clientRegistrationDefaultScopes]):new Set([...t.clientRegistrationDefaultScopes]);r=Array.from(u)}let n=new Set((t.scopes??Vy).filter((u)=>u.length));if(r){for(let u of r)if(!n.has(u))throw new te(`clientRegistrationAllowedScope ${u} not found in scopes`)}for(let u of t.advertisedMetadata?.scopes_supported??[])if(!n?.has(u))throw new te(`advertisedMetadata.scopes_supported ${u} not found in scopes`);let o=new Set((t.resources??[]).map((u)=>typeof u==="string"?u:u.identifier));for(let[u,f]of[["clientRegistrationDefaultResources",t.clientRegistrationDefaultResources],["clientRegistrationAllowedResources",t.clientRegistrationAllowedResources]])for(let p of f??[])if(!o.has(p))throw new te(`${u} resource ${p} not found in resources`);let i=new Set(["sub","iss","aud","exp","iat","sid","scope","azp",...fa.filter((u)=>n.has(Mo[u].scope))]),s={codeExpiresIn:600,accessTokenExpiresIn:3600,m2mAccessTokenExpiresIn:3600,refreshTokenExpiresIn:2592000,refreshTokenReuseInterval:0,allowUnauthenticatedClientRegistration:!1,allowDynamicClientRegistration:!1,disableJwtPlugin:!1,storeClientSecret:t.disableJwtPlugin?"encrypted":"hashed",storeTokens:"hashed",grantTypes:["authorization_code","client_credentials","refresh_token"],...t,scopes:Array.from(n),claims:Array.from(i),clientRegistrationAllowedScopes:r};if(Xf(s.extensions),s.pairwiseSecret&&s.pairwiseSecret.length<32)throw new te("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 te("refresh_token grant requires authorization_code grant");if(s.disableJwtPlugin&&(s.storeClientSecret==="hashed"||typeof s.storeClientSecret==="object"&&("hash"in s.storeClientSecret)))throw new te("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 te("encryption method not recommended, please use 'hashed' or the 'hash' function");let a=async(u,f)=>{let p=new URL(u.url).pathname,h=f.options.advanced?.skipTrailingSlashes?p.replace(/\/+$/,"")||"/":p,m=s.disableJwtPlugin?f.baseURL:Oe(f)?.options?.jwt?.issuer??f.baseURL,w="/";try{w=new URL(m).pathname.replace(/\/$/,"")||""}catch{w=new URL(f.baseURL).pathname.replace(/\/$/,"")||""}let y={context:f},I=new Set([`/.well-known/oauth-authorization-server${w}`,`${w}/.well-known/oauth-authorization-server`]),R=`${w}/.well-known/openid-configuration`,b=I.has(h),O=s.scopes?.includes("openid")&&h===R,g=(S)=>{let C=Al(S);if(u.method==="HEAD")return new Response(null,{status:C.status,headers:C.headers});return C};if(b||O){if(u.method!=="GET"&&u.method!=="HEAD")return{response:new Response(null,{status:405,headers:{Allow:"GET, HEAD"}})}}if(b){if(s.scopes?.includes("openid"))return{response:g(hf(y,s))};return{response:g(Yg(y,s))}}if(O)return{response:g(hf(y,s))}},c=Pt("/oauth2/authorize",{method:["GET","POST"],body:l({}).passthrough(),redirectOnError:xt(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:"client_id",in:"query",required:!0,schema:{type:"string"},description:"OAuth 2.1 client ID"},{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(u)=>KE(u,s,u.authorizeSettings??{isAuthorize:!0})),d=(u,f)=>bn(c,{...u,asResponse:!1,returnHeaders:!1,returnStatus:!1,authorizeSettings:f??{}});return{id:"oauth-provider",version:Vp,options:s,onRequest:a,init:async(u)=>{if(u.options.secondaryStorage&&u.options.session?.storeSessionInDatabase!==!0)throw new te("OAuth Provider requires `session.storeSessionInDatabase: true` when using secondaryStorage");if(s.allowClientKeyRotation){let f=u.adapter.id==="memory"?"the memory adapter":u.options.advanced?.database?.generateId==="serial"?'`advanced.database.generateId: "serial"`':void 0;if(f)throw new te(`\`allowClientKeyRotation\` requires single-use client assertions, which ${f} does not enforce`)}if(await ga(u,s).catch((f)=>Cp(u,f)),Op(s),!s.disableJwtPlugin){let f=Oe(u)?.options,p=f?.jwt?.issuer??u.baseURL,h=f?.jwt?.issuer==null&&typeof u.options.baseURL==="object"&&u.options.baseURL!==null&&"allowedHosts"in u.options.baseURL;try{new URL(p)}catch(m){if(!h||p!=="")throw m}}return{options:{databaseHooks:{session:{delete:{async before(f,p){if(!p)return;let h=await YA(p,s,{sessionId:f.id,userId:f.userId});if(!h)return;let m=ti.get(p)??new Map;m.set(f.id,h),ti.set(p,m)},async after(f,p){if(!p)return;let h=ti.get(p);if(!h)return;let m=h.get(f.id);if(h.delete(f.id),h.size===0)ti.delete(p);if(!m)return;let w=XA(p,m).catch((y)=>{p.context.logger.error("Back-channel logout failed after session deletion",y)});await p.context.runInBackgroundOrAwait(w)}}}}}}},hooks:{before:[{matcher(u){return u.body?.oauth_query},handler:Sn(async(u)=>{let f=u.body.oauth_query;if(!await ra(f,u.context.secret))throw new U("BAD_REQUEST",{error:"invalid_signature"});let p=Qf(f),h=new URLSearchParams(f),m=h.get("ba_pl")??void 0;if(h.delete("sig"),h.delete("exp"),h.delete(Ms),h.delete(Oo),await Nt.set({query:h.toString(),signedQueryIssuedAt:p??void 0,postLoginClearedForSession:m}),u.path==="/sign-in/social")await es({query:h.toString(),...p?{[uh]:p.getTime()}:{}})})}],after:[{matcher(u){return Qn(u.context.responseHeaders?.get("set-cookie")||"").has(u.context.authCookies.sessionToken.name)},handler:Sn(async(u)=>{let f=Qn(u.context.responseHeaders?.get("set-cookie")||"").get(u.context.authCookies.sessionToken.name)?.value.split(".")[0];if(!f)return;let p=await Nt.get(),h=(await Zi())?.serverContext,m=p?.query??h?.query;if(!m)return;let w=new URLSearchParams(m),y=await u.context.internalAdapter.findSession(f);if(!y)return;u.context.session=y;let I=u.request?.headers?.get("sec-fetch-mode")?.toLowerCase(),R=u.request?.headers?.get("accept")?.toLowerCase()??"";if(!(I==="navigate"||!I&&(R.includes("text/html")||R.includes("application/xhtml+xml"))))u.headers?.set("accept","application/json");let b=p?.signedQueryIssuedAt??qE(h?.[uh]),O=Ir(w,"login");if(ca(y.session.createdAt,b))O=da(O);return u.query=nr(O),await d(u)})}]},endpoints:{getOAuthServerConfig:Pe("/.well-known/oauth-authorization-server",{method:"GET",metadata:{SERVER_ONLY:!0}},async(u)=>{if(s.scopes&&s.scopes.includes("openid"))return hf(u,s);else return Yg(u,s)}),getOpenIdConfig:Pe("/.well-known/openid-configuration",{method:"GET",metadata:{SERVER_ONLY:!0}},async(u)=>{if(s.scopes&&!s.scopes.includes("openid"))throw new U("NOT_FOUND");return hf(u,s)}),oauth2Authorize:c,oauth2Consent:Pe("/oauth2/consent",{method:"POST",body:l({accept:E().meta({description:"Accept or deny user consent for a set of scopes"}),scope:e().optional().meta({description:"List of accept of accepted space-separated scopes. If none is provided, then all originally requested scopes are accepted."}),claims:la.optional().meta({description:"Accepted OIDC claims request object. If none is provided, then all originally requested claims are accepted."}),oauth_query:e().optional().meta({description:"The redirected page's query parameters"})}),use:[Hr],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(u)=>MA(u,s,d)),oauth2Continue:Pe("/oauth2/continue",{method:"POST",body:l({selected:E().optional().meta({description:"Confirms an account has been selected and authorization can proceed."}),created:E().optional().meta({description:"Confirms an account was registered"}),postLogin:E().optional().meta({description:"Resumes after the post login page. postLogin.shouldRedirect runs again with isContinuation: true."}),oauth_query:e().optional().meta({description:"The redirected page's query parameters"})}),use:[Hr],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(u)=>HA(u,d)),oauth2Token:Pt("/oauth2/token",{method:"POST",cloneRequest:!0,body:l({grant_type:e().trim().min(1),client_id:e().optional(),client_secret:e().optional(),client_assertion:e().optional(),client_assertion_type:e().optional(),code:e().optional(),code_verifier:e().optional(),redirect_uri:le.optional(),refresh_token:e().optional(),resource:D([Qs,A(Qs).min(1)]).optional(),scope:e().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(u)=>{if(u.request){let f=await Tp(u.request);if(f&&f.length>1)u.body.resource=f}return xp(u,s)}),oauth2Introspect:Pt("/oauth2/introspect",{method:"POST",cloneRequest:!0,body:l({client_id:e().optional(),client_secret:e().optional(),client_assertion:e().optional(),client_assertion_type:e().optional(),token:e(),token_type_hint:e().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(u)=>ka(u,s)),oauth2Revoke:Pt("/oauth2/revoke",{method:"POST",cloneRequest:!0,body:l({client_id:e().optional(),client_secret:e().optional(),client_assertion:e().optional(),client_assertion_type:e().optional(),token:e(),token_type_hint:e().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(u)=>zE(u,s)),oauth2UserInfo:Pe("/oauth2/userinfo",{method:["GET","POST"],body:l({access_token:e().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(u)=>Pp(u,s)),oauth2EndSession:Pt("/oauth2/end-session",{method:["GET","POST"],body:dh.optional(),query:dh.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 confirmation page was returned for browser navigation. 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"}}}}}}}},async(u)=>lk(u,s)),oauth2EndSessionConfirmation:Pt("/oauth2/end-session/confirm",{method:"POST",body:l({action:v("confirm")}),metadata:{noStore:!0,allowedMediaTypes:["application/x-www-form-urlencoded"],scope:"http"}},async(u)=>fk(u,s)),registerOAuthClient:Pt("/oauth2/register",{method:"POST",body:ha,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"},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(u)=>Mk(u,s)),adminCreateOAuthClient:Zk(s),createOAuthClient:Yk(s),getOAuthClient:Xk(s),getOAuthClientPublic:eE(s),getOAuthClientPublicPrelogin:tE(s),getOAuthClients:rE(s),adminUpdateOAuthClient:nE(s),updateOAuthClient:oE(s),rotateClientSecret:iE(s),rotateClientKeys:sE(s),deleteOAuthClient:aE(s),getOAuthConsent:fE(s),getOAuthConsents:pE(s),updateOAuthConsent:hE(s),deleteOAuthConsent:mE(s),adminCreateOAuthResource:SE(s),adminListOAuthResources:RE(s),adminGetOAuthResource:TE(s),adminUpdateOAuthResource:IE(s),adminDeleteOAuthResource:UE(s),adminLinkClientResource:CE(s),adminUnlinkClientResource:OE(s)},schema:hc(structuredClone(NE),s?.schema),rateLimit:[...s.rateLimit?.token!==!1?[{pathMatcher:(u)=>u==="/oauth2/token",window:s.rateLimit?.token?.window??60,max:s.rateLimit?.token?.max??20}]:[],...s.rateLimit?.authorize!==!1?[{pathMatcher:(u)=>u==="/oauth2/authorize",window:s.rateLimit?.authorize?.window??60,max:s.rateLimit?.authorize?.max??30}]:[],...s.rateLimit?.introspect!==!1?[{pathMatcher:(u)=>u==="/oauth2/introspect",window:s.rateLimit?.introspect?.window??60,max:s.rateLimit?.introspect?.max??100}]:[],...s.rateLimit?.revoke!==!1?[{pathMatcher:(u)=>u==="/oauth2/revoke",window:s.rateLimit?.revoke?.window??60,max:s.rateLimit?.revoke?.max??30}]:[],...s.rateLimit?.register!==!1?[{pathMatcher:(u)=>u==="/oauth2/register",window:s.rateLimit?.register?.window??60,max:s.rateLimit?.register?.max??5}]:[],...s.rateLimit?.rotateClientKeys!==!1?[{pathMatcher:(u)=>u==="/oauth2/client/rotate-keys",window:s.rateLimit?.rotateClientKeys?.window??60,max:s.rateLimit?.rotateClientKeys?.max??5}]:[],...s.rateLimit?.userinfo!==!1?[{pathMatcher:(u)=>u==="/oauth2/userinfo",window:s.rateLimit?.userinfo?.window??60,max:s.rateLimit?.userinfo?.max??60}]:[]]}};function jE(t,r,n){if(r===0)return!1;return n.getTime()-t.getTime()<=r*1000}function BE(t){let{max_age:r,...n}=t;return n}function Ve(t,r,n,o,i,s="query"){let a=new URLSearchParams({error:r,error_description:n});if(o&&a.append("state",o),i&&a.append("iss",i),s==="fragment")return`${t}#${a.toString()}`;return $e(t,a)}function $E(t){let r=typeof t.response_mode==="string"?t.response_mode:void 0;if(r==="fragment")return"fragment";if(r==="query")return"query";let n=typeof t.response_type==="string"?t.response_type:void 0;if(n&&/\b(token|id_token)\b/.test(n))return"fragment";return"query"}var ME={response_type:{invalid:"unsupported_response_type"},resource:{invalid:"invalid_target"}};function HE(t){return typeof t==="object"&&t!==null&&!Array.isArray(t)}function Ra(t){return typeof t==="string"?t:void 0}function VE(t,r){let n=t.method==="POST"&&r?.isAuthorize===!0?t.body:t.query;return{...HE(n)?n:{}}}var fe=(t,r)=>{let n=Ea(t.request?.headers),o=t.headers?.get("accept")?.includes("application/json");if(n||o)return{redirect:!0,url:r.toString()};else throw t.redirect(r)};function Or(t,r,n,o,i){return fe(t,Ve(n.redirect_uri,o,i,n.state,Gn(t,r)))}function Wh(t){try{let r=new URL(t);if(r.protocol!=="https:"&&!hr(r.host))r.protocol="https:";return r.search="",r.hash="",r.toString().replace(/\/$/,"")}catch{return t}}function Gn(t,r){let n;if(r.disableJwtPlugin)n=t.context.baseURL;else try{n=Oe(t.context).options?.jwt?.issuer??t.context.baseURL}catch{n=t.context.baseURL}return Wh(n)}function ir(t,r,n){return Ve(t.context.options.onAPIError?.errorURL||`${t.context.baseURL}/error`,r,n)}function lh(t){let r;try{r=new URL(t)}catch{return}let n=Fi(r.hostname)||r.hostname==="localhost";if(r.protocol!=="http:"||!n)return;let o=t.indexOf("://");if(o<0)return;let i=o+3,s=t.slice(i).search(/[/?#]/u),a=t.length;if(s>=0)a=i+s;let c=t.slice(i,a),d;if(c.startsWith("[")){let p=c.indexOf("]");if(p<0)return;if(c[p+1]!==":")return t;d=p+1}else if(d=c.lastIndexOf(":"),d<0)return t;let u=c.slice(d+1);if(!/^\d*$/u.test(u))return;let f=i+d;return`${t.slice(0,f)}${t.slice(a)}`}function Jh(t,r){if(!t||!r)return;let n;try{n=new URL(r)}catch{return}let o=r.includes("#"),i=n.username.length>0||n.password.length>0;if(o||i)return;let s=lh(r);return t.find((a)=>{if(a===r)return!0;if(!s)return!1;return lh(a)===s})}function Qh(t){if(!le.safeParse(t).success)return!1;let r=new URL(t);return r.username.length===0&&r.password.length===0}async function FE(t,r,n,o){if(!n||!o)return null;let i;try{i=await ke(t,r,n)}catch{return null}if(!i||i.disabled)return null;let s=i.redirectUris??[],a=Jh(s,o);if(r.validateRedirectUri){if(!Qh(o))return null;try{return await r.validateRedirectUri(o,s,Boolean(a))?o:null}catch{return null}}return a?o:null}function xt(t){return async({error:r,error_description:n,ctx:o})=>{let i=o.query??{},s=await FE(o,t,typeof i.client_id==="string"?i.client_id:void 0,typeof i.redirect_uri==="string"?i.redirect_uri:void 0);if(s)return fe(o,Ve(s,r,n,typeof i.state==="string"?i.state:void 0,Gn(o,t),$E(i)));return fe(o,ir(o,r,n))}}async function KE(t,r,n){if(r.grantTypes&&!r.grantTypes.includes("authorization_code"))throw new ce("NOT_FOUND");if(!t.request)throw new ce("UNAUTHORIZED",{error_description:"request not found",error:"invalid_request"});let o=t.request,i=VE(t,n);t.query=i;let s=Ra(i.request),a=Ra(i.request_uri);if(s!==void 0&&a!==void 0)return xt(r)({error:"invalid_request",error_description:"request and request_uri cannot be used together",ctx:t});if(s!==void 0)return xt(r)({error:"request_not_supported",error_description:"request object not supported",ctx:t});if(a!==void 0){let L=Ra(i.client_id);if(!L)return xt(r)({error:"invalid_request",error_description:"client_id is required",ctx:t});if(!r.requestUriResolver)return xt(r)({error:"request_uri_not_supported",error_description:"request_uri not supported",ctx:t});let x=await r.requestUriResolver({requestUri:a,clientId:L,ctx:t});if(!x)return xt(r)({error:"invalid_request_uri",error_description:"request_uri is invalid or expired",ctx:t});let P=i.client_id;if(i=x,P)i.client_id=P}t.query=i;let c=pa.safeParse(i);if(!c.success){let L=Ua(c.error.issues,ME);return xt(r)({...L,ctx:t})}if(i=c.data,t.query=i,await Nt.set({query:Gh(i).toString()}),!i.response_type)return xt(r)({error:"invalid_request",error_description:"response_type is required",ctx:t});let d=t.query?.prompt?ia(t.query?.prompt):void 0,u=d?.has("none")??!1;if(d?.has("select_account")&&!r.selectAccount?.page)return fe(t,ir(t,"unsupported_prompt_select_account","unsupported prompt type"));if(i.response_type!=="code")return fe(t,ir(t,"unsupported_response_type","unsupported response type"));let f=await ke(t,r,i.client_id);if(!f)return fe(t,ir(t,"invalid_client","client not found"));if(f.disabled)return fe(t,ir(t,"client_disabled","client is disabled"));if(!Cn(f,"authorization_code"))return fe(t,ir(t,"unauthorized_client","client is not authorized to use the authorization_code grant"));let p=f.redirectUris??[],h=!1;if(i.redirect_uri){let L=Boolean(Jh(p,i.redirect_uri));if(r.validateRedirectUri&&Qh(i.redirect_uri))try{h=await r.validateRedirectUri(i.redirect_uri,p,L)}catch{h=!1}else if(!r.validateRedirectUri)h=L}if(!h)return fe(t,ir(t,"invalid_redirect","invalid redirect uri"));let m=i.scope?.split(" ").filter((L)=>L);if(m){let L=new Set(f.scopes??r.scopes),x=m.filter((P)=>!L?.has(P));if(x.length)return fe(t,Ve(i.redirect_uri,"invalid_scope",`The following scopes are invalid: ${x.join(", ")}`,i.state,Gn(t,r)))}if(!m)m=f.scopes??r.scopes??[],i.scope=m.join(" ");let w=m.includes("openid");if(i.claims!==void 0&&!w)return fe(t,Ve(i.redirect_uri,"invalid_request","openid scope must be requested when using the claims parameter",i.state,Gn(t,r)));if(w&&!kp(i.claims))return fe(t,Ve(i.redirect_uri,"invalid_request","claims must be a valid Claims request object",i.state,Gn(t,r)));if(w&&!Ep(i.claims,"0"))return fe(t,Ve(i.redirect_uri,"access_denied","essential acr requirement cannot be met",i.state,Gn(t,r)));let y=Dn(i.claims,Ln(r));if(i.resource!==void 0)try{await ma(t,r,{resource:i.resource,clientId:f.clientId,requestedScopes:m})}catch(L){if(L instanceof ce){let x=L.body?.error??"invalid_target",P=L.body?.error_description??"requested resource invalid";return fe(t,Ve(i.redirect_uri,x,P,i.state,Gn(t,r)))}throw L}let I=jo(f,{scopes:m,nonce:i.nonce});if(I){if(!i.code_challenge||!i.code_challenge_method)return fe(t,Ve(i.redirect_uri,"invalid_request",I.valueOf(),i.state,Gn(t,r)))}if(i.code_challenge||i.code_challenge_method){if(!i.code_challenge||!i.code_challenge_method)return fe(t,Ve(i.redirect_uri,"invalid_request","code_challenge and code_challenge_method must both be provided",i.state,Gn(t,r)));if(!["S256"].includes(i.code_challenge_method))return fe(t,Ve(i.redirect_uri,"invalid_request","invalid code_challenge method, only S256 is supported",i.state,Gn(t,r)))}let R=Ut(i.resource)??[],b=await ee(t),O=i.max_age,g=b!=null&&O!==void 0&&jE(new Date(b.session.createdAt),O,new Date);if(!b||b!=null&&O!==void 0&&!g||d?.has("login")||d?.has("create")){if(u)return Or(t,r,i,"login_required","authentication required");return Lt(t,r,d?.has("create")?"create":"login")}if(g)i=BE(i),t.query=i;if(n?.isAuthorize&&d?.has("select_account"))return Lt(t,r,"select_account");if(n?.isAuthorize&&r.selectAccount){if(await r.selectAccount.shouldRedirect({headers:o.headers,user:b.user,session:b.session,scopes:m})){if(u)return Or(t,r,i,"account_selection_required","End-User account selection is required");return Lt(t,r,"select_account")}}if(r.signup?.shouldRedirect){let L=await r.signup.shouldRedirect({headers:o.headers,user:b.user,session:b.session,scopes:m});if(L){if(u)return Or(t,r,i,"interaction_required","End-User interaction is required");return Lt(t,r,"create",{page:typeof L==="string"?L:void 0})}}if(!n?.postLogin&&r.postLogin){if(await r.postLogin.shouldRedirect({headers:o.headers,user:b.user,session:b.session,scopes:m,isContinuation:n?.isPostLoginContinuation??!1})){if(u)return Or(t,r,i,"interaction_required","End-User interaction is required");return Lt(t,r,"post_login")}}if(d?.has("consent"))return Lt(t,r,"consent",{sessionId:b.session.id});let S=await sa(r,{user:b.user,session:b.session,scopes:m});if(f.skipConsent)return fh(t,r,{query:i,clientId:f.clientId,userId:b.user.id,sessionId:b.session.id,authTime:new Date(b.session.createdAt).getTime(),referenceId:S,resource:R});let C=await aa(t,f.clientId,b.user.id,S);if(!C||!m.every((L)=>C.scopes.includes(L))||!y.every((L)=>(C.requestedUserInfoClaims??[]).includes(L))){if(u)return Or(t,r,i,"consent_required","End-User consent is required");return Lt(t,r,"consent",{sessionId:b.session.id})}let z=C?.resources??[];if(R.some((L)=>!z.includes(L))){if(u)return Or(t,r,i,"consent_required","End-User consent is required");return Lt(t,r,"consent",{sessionId:b.session.id})}return fh(t,r,{query:i,clientId:f.clientId,userId:b.user.id,sessionId:b.session.id,authTime:new Date(b.session.createdAt).getTime(),referenceId:S,resource:R})}function Gh(t){let r=new URLSearchParams;for(let[n,o]of Object.entries(t)){if(o==null)continue;if(Array.isArray(o))for(let i of o)r.append(n,String(i));else if(n==="claims"&&typeof o==="object")r.set(n,JSON.stringify(o));else r.set(n,String(o))}return r}async function fh(t,r,n){let o=_e(32,"a-z","A-Z","0-9"),i=Math.floor(Date.now()/1000),s=i+(r.codeExpiresIn??600),a={identifier:await er(r.storeTokens,o,"authorization_code"),updatedAt:new Date(i*1000),expiresAt:new Date(s*1000),value:JSON.stringify({type:"authorization_code",query:n.query,userId:n.userId,sessionId:n?.sessionId,referenceId:n.referenceId,authTime:n.authTime,resource:n.resource})};await t.context.internalAdapter.createVerificationValue({...a,createdAt:new Date(i*1000)});let c=new URL(n.query.redirect_uri);if(c.searchParams.set("code",o),n.query.state)c.searchParams.set("state",n.query.state);return c.searchParams.set("iss",Gn(t,r)),fe(t,c.toString())}async function Lt(t,r,n,o){let i=await WE(t,r,{postLoginClearedForSession:n==="consent"&&r.postLogin?o?.sessionId:void 0}),s=r.loginPage;if(n==="select_account")s=r.selectAccount?.page??r.loginPage;else if(n==="post_login"){if(!r.postLogin?.page)throw new ce("INTERNAL_SERVER_ERROR",{error_description:"postLogin should have been defined"});s=r.postLogin?.page}else if(n==="consent")s=r.consentPage;else if(n==="create")s=r.signup?.page??r.loginPage;return fe(t,`${o?.page??s}?${i}`)}async function WE(t,r,n){let o=Date.now(),i=Math.floor(o/1000)+(r.codeExpiresIn??600),s=Gh(t.query);if(s.set("exp",String(i)),s.set(Ms,String(o)),s.delete("sig"),s.delete(Oo),n?.postLoginClearedForSession)s.set(Oo,n.postLoginClearedForSession);Jf(s);let a=await on(Do(s).toString(),t.context.secret);return s.set("sig",a),s.toString()}export{Ae,bm,Hs,Ai,ls,cf,uf,mc,hc,gc,Uu,df,cs,zu,wm,Qg,Ac,ju,Gg,Vg,qu,ff,pf,$u,Kg,Ur,Sn,Pe,Hr,Me,ja,_c,Em,Hu,xm,Cm,Wg,Sm,Jg,vs,_i,yc,Ki,Wi,mf,Gy,Yg,hf,Al,lP,cP,uP,Xg,Vy,dP,gf,Gn,Qs};