better-auth 1.1.3-beta.2 → 1.1.3-beta.4

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 (69) hide show
  1. package/dist/adapters/drizzle.cjs +1 -1
  2. package/dist/adapters/drizzle.js +1 -1
  3. package/dist/adapters/kysely.cjs +1 -1
  4. package/dist/adapters/kysely.js +1 -1
  5. package/dist/adapters/memory.cjs +1 -1
  6. package/dist/adapters/memory.js +1 -1
  7. package/dist/adapters/mongodb.cjs +1 -1
  8. package/dist/adapters/mongodb.js +1 -1
  9. package/dist/adapters/prisma.cjs +1 -1
  10. package/dist/adapters/prisma.js +1 -1
  11. package/dist/api.cjs +4 -4
  12. package/dist/api.js +4 -4
  13. package/dist/client/plugins.cjs +1 -1
  14. package/dist/client/plugins.js +1 -1
  15. package/dist/client.cjs +1 -1
  16. package/dist/client.js +1 -1
  17. package/dist/db.cjs +2 -2
  18. package/dist/db.js +2 -2
  19. package/dist/index.cjs +4 -4
  20. package/dist/index.js +4 -4
  21. package/dist/oauth2.cjs +1 -1
  22. package/dist/oauth2.js +1 -1
  23. package/dist/plugin/custom-session.cjs +4 -4
  24. package/dist/plugin/custom-session.js +4 -4
  25. package/dist/plugins/admin.cjs +4 -4
  26. package/dist/plugins/admin.js +4 -4
  27. package/dist/plugins/anonymous.cjs +4 -4
  28. package/dist/plugins/anonymous.js +4 -4
  29. package/dist/plugins/bearer.cjs +4 -4
  30. package/dist/plugins/bearer.js +4 -4
  31. package/dist/plugins/email-otp.cjs +4 -4
  32. package/dist/plugins/email-otp.js +4 -4
  33. package/dist/plugins/generic-oauth.cjs +4 -4
  34. package/dist/plugins/generic-oauth.js +4 -4
  35. package/dist/plugins/jwt.cjs +4 -4
  36. package/dist/plugins/jwt.js +4 -4
  37. package/dist/plugins/multi-session.cjs +4 -4
  38. package/dist/plugins/multi-session.js +4 -4
  39. package/dist/plugins/oidc-provider.cjs +4 -4
  40. package/dist/plugins/oidc-provider.js +4 -4
  41. package/dist/plugins/one-tap.cjs +4 -4
  42. package/dist/plugins/one-tap.js +4 -4
  43. package/dist/plugins/open-api.cjs +9 -9
  44. package/dist/plugins/open-api.js +9 -9
  45. package/dist/plugins/organization.cjs +4 -4
  46. package/dist/plugins/organization.js +4 -4
  47. package/dist/plugins/passkey.cjs +4 -4
  48. package/dist/plugins/passkey.js +4 -4
  49. package/dist/plugins/phone-number.cjs +4 -4
  50. package/dist/plugins/phone-number.js +4 -4
  51. package/dist/plugins/sso.cjs +4 -4
  52. package/dist/plugins/sso.js +4 -4
  53. package/dist/plugins/two-factor.cjs +4 -4
  54. package/dist/plugins/two-factor.js +4 -4
  55. package/dist/plugins/username.cjs +4 -4
  56. package/dist/plugins/username.js +4 -4
  57. package/dist/plugins.cjs +7 -7
  58. package/dist/plugins.js +7 -7
  59. package/dist/react.cjs +1 -1
  60. package/dist/react.js +1 -1
  61. package/dist/social.cjs +1 -1
  62. package/dist/social.js +1 -1
  63. package/dist/solid.cjs +1 -1
  64. package/dist/solid.js +1 -1
  65. package/dist/svelte.cjs +1 -1
  66. package/dist/svelte.js +1 -1
  67. package/dist/vue.cjs +1 -1
  68. package/dist/vue.js +1 -1
  69. package/package.json +3 -3
@@ -1 +1 @@
1
- import{z as n}from"zod";import{APIError as H}from"better-call";var W=n.object({id:n.string(),providerId:n.string(),accountId:n.string(),userId:n.string(),accessToken:n.string().nullish(),refreshToken:n.string().nullish(),idToken:n.string().nullish(),accessTokenExpiresAt:n.date().nullish(),refreshTokenExpiresAt:n.date().nullish(),scope:n.string().nullish(),password:n.string().nullish(),createdAt:n.date().default(()=>new Date),updatedAt:n.date().default(()=>new Date)}),J=n.object({id:n.string(),email:n.string().transform(e=>e.toLowerCase()),emailVerified:n.boolean().default(!1),name:n.string(),image:n.string().nullish(),createdAt:n.date().default(()=>new Date),updatedAt:n.date().default(()=>new Date)}),G=n.object({id:n.string(),userId:n.string(),expiresAt:n.date(),createdAt:n.date().default(()=>new Date),updatedAt:n.date().default(()=>new Date),token:n.string(),ipAddress:n.string().nullish(),userAgent:n.string().nullish()}),z=n.object({id:n.string(),value:n.string(),createdAt:n.date().default(()=>new Date),updatedAt:n.date().default(()=>new Date),expiresAt:n.date(),identifier:n.string()});var T=Object.create(null),b=e=>globalThis.process?.env||globalThis.Deno?.env.toObject()||globalThis.__env__||(e?T:globalThis),I=new Proxy(T,{get(e,i){return b()[i]??T[i]},has(e,i){let u=b();return i in u||i in T},set(e,i,u){let c=b(!0);return c[i]=u,!0},deleteProperty(e,i){if(!i)return!1;let u=b(!0);return delete u[i],!0},ownKeys(){let e=b(!0);return Object.keys(e)}});function D(e){return e?e!=="false":!1}var N=typeof process<"u"&&process.env&&process.env.NODE_ENV||"";var q=N==="test"||D(I.TEST);import{createRandomStringGenerator as U}from"@better-auth/utils/random";var v=e=>U("a-z","A-Z","0-9")(e||32);import{z as _e}from"zod";import{APIError as je}from"better-call";var A=class extends Error{constructor(i,u){super(i),this.name="BetterAuthError",this.message=i,this.cause=u,this.stack=""}};import{createHash as Re}from"@better-auth/utils/hash";import{xchacha20poly1305 as Oe}from"@noble/ciphers/chacha";import{bytesToHex as De,hexToBytes as Ne,utf8ToBytes as qe}from"@noble/ciphers/utils";import{managedNonce as Se}from"@noble/ciphers/webcrypto";import{scryptAsync as ge}from"@noble/hashes/scrypt";import{getRandomValues as Ae}from"uncrypto";import{hex as we}from"@better-auth/utils/hex";import{createRandomStringGenerator as S}from"@better-auth/utils/random";var B=S("a-z","0-9","A-Z","-_");var R=["info","success","warn","error","debug"];function L(e,i){return R.indexOf(i)<=R.indexOf(e)}var h={reset:"\x1B[0m",bright:"\x1B[1m",dim:"\x1B[2m",underscore:"\x1B[4m",blink:"\x1B[5m",reverse:"\x1B[7m",hidden:"\x1B[8m",fg:{black:"\x1B[30m",red:"\x1B[31m",green:"\x1B[32m",yellow:"\x1B[33m",blue:"\x1B[34m",magenta:"\x1B[35m",cyan:"\x1B[36m",white:"\x1B[37m"},bg:{black:"\x1B[40m",red:"\x1B[41m",green:"\x1B[42m",yellow:"\x1B[43m",blue:"\x1B[44m",magenta:"\x1B[45m",cyan:"\x1B[46m",white:"\x1B[47m"}},P={info:h.fg.blue,success:h.fg.green,warn:h.fg.yellow,error:h.fg.red,debug:h.fg.magenta},E=(e,i)=>{let u=new Date().toISOString();return`${h.dim}${u}${h.reset} ${P[e]}${e.toUpperCase()}${h.reset} ${h.bright}Better Auth${h.reset} ${i}`},O=e=>{let i=e?.disabled!==!0,u=e?.level??"error",c=(l,y,f=[])=>{if(!i||!L(u,l))return;let a=E(l,y);if(!e||typeof e.log!="function"){l==="error"?console.error(a,...f):l==="warn"?console.warn(a,...f):console.log(a,...f);return}e.log(l==="success"?"info":l,a,...f)};return Object.fromEntries(R.map(l=>[l,(...[y,...f])=>c(l,y,f)]))},M=O();var w=e=>{let i=e.plugins?.reduce((s,p)=>{let d=p.schema;if(!d)return s;for(let[t,o]of Object.entries(d))s[t]={fields:{...s[t]?.fields,...o.fields},modelName:o.modelName||t};return s},{}),u=e.rateLimit?.storage==="database",c={rateLimit:{modelName:e.rateLimit?.modelName||"rateLimit",fields:{key:{type:"string",fieldName:e.rateLimit?.fields?.key||"key"},count:{type:"number",fieldName:e.rateLimit?.fields?.count||"count"},lastRequest:{type:"number",fieldName:e.rateLimit?.fields?.lastRequest||"lastRequest"}}}},{user:l,session:y,account:f,...a}=i||{};return{user:{modelName:e.user?.modelName||"user",fields:{name:{type:"string",required:!0,fieldName:e.user?.fields?.name||"name"},email:{type:"string",unique:!0,required:!0,fieldName:e.user?.fields?.email||"email"},emailVerified:{type:"boolean",defaultValue:()=>!1,required:!0,fieldName:e.user?.fields?.emailVerified||"emailVerified"},image:{type:"string",required:!1,fieldName:e.user?.fields?.image||"image"},createdAt:{type:"date",defaultValue:()=>new Date,required:!0,fieldName:e.user?.fields?.createdAt||"createdAt"},updatedAt:{type:"date",defaultValue:()=>new Date,required:!0,fieldName:e.user?.fields?.updatedAt||"updatedAt"},...l?.fields,...e.user?.additionalFields},order:1},session:{modelName:e.session?.modelName||"session",fields:{expiresAt:{type:"date",required:!0,fieldName:e.session?.fields?.expiresAt||"expiresAt"},token:{type:"string",required:!0,fieldName:e.session?.fields?.token||"token",unique:!0},createdAt:{type:"date",required:!0,fieldName:e.session?.fields?.createdAt||"createdAt"},updatedAt:{type:"date",required:!0,fieldName:e.session?.fields?.updatedAt||"updatedAt"},ipAddress:{type:"string",required:!1,fieldName:e.session?.fields?.ipAddress||"ipAddress"},userAgent:{type:"string",required:!1,fieldName:e.session?.fields?.userAgent||"userAgent"},userId:{type:"string",fieldName:e.session?.fields?.userId||"userId",references:{model:e.user?.modelName||"user",field:"id",onDelete:"cascade"},required:!0},...y?.fields,...e.session?.additionalFields},order:2},account:{modelName:e.account?.modelName||"account",fields:{accountId:{type:"string",required:!0,fieldName:e.account?.fields?.accountId||"accountId"},providerId:{type:"string",required:!0,fieldName:e.account?.fields?.providerId||"providerId"},userId:{type:"string",references:{model:e.user?.modelName||"user",field:"id",onDelete:"cascade"},required:!0,fieldName:e.account?.fields?.userId||"userId"},accessToken:{type:"string",required:!1,fieldName:e.account?.fields?.accessToken||"accessToken"},refreshToken:{type:"string",required:!1,fieldName:e.account?.fields?.refreshToken||"refreshToken"},idToken:{type:"string",required:!1,fieldName:e.account?.fields?.idToken||"idToken"},accessTokenExpiresAt:{type:"date",required:!1,fieldName:e.account?.fields?.accessTokenExpiresAt||"accessTokenExpiresAt"},refreshTokenExpiresAt:{type:"date",required:!1,fieldName:e.account?.fields?.accessTokenExpiresAt||"refreshTokenExpiresAt"},scope:{type:"string",required:!1,fieldName:e.account?.fields?.scope||"scope"},password:{type:"string",required:!1,fieldName:e.account?.fields?.password||"password"},createdAt:{type:"date",required:!0,fieldName:e.account?.fields?.createdAt||"createdAt"},updatedAt:{type:"date",required:!0,fieldName:e.account?.fields?.updatedAt||"updatedAt"},...f?.fields},order:3},verification:{modelName:e.verification?.modelName||"verification",fields:{identifier:{type:"string",required:!0,fieldName:e.verification?.fields?.identifier||"identifier"},value:{type:"string",required:!0,fieldName:e.verification?.fields?.value||"value"},expiresAt:{type:"date",required:!0,fieldName:e.verification?.fields?.expiresAt||"expiresAt"},createdAt:{type:"date",required:!1,defaultValue:()=>new Date,fieldName:e.verification?.fields?.createdAt||"createdAt"},updatedAt:{type:"date",required:!1,defaultValue:()=>new Date,fieldName:e.verification?.fields?.updatedAt||"updatedAt"}},order:4},...a,...u?c:{}}};import{z as At}from"zod";import{Kysely as bt,MssqlDialect as vt}from"kysely";import{MysqlDialect as kt,PostgresDialect as Rt,SqliteDialect as It}from"kysely";function k(e,i,u){return u==="update"?e:e==null&&i.defaultValue?typeof i.defaultValue=="function"?i.defaultValue():i.defaultValue:e}var C=(e,i)=>{let u=w(i);function c(a,s){return s==="id"?s:u[a].fields[s].fieldName||s}function l(a){switch(a){case"starts_with":return"startsWith";case"ends_with":return"endsWith";default:return a}}function y(a){return u[a].modelName}let f=i?.advanced?.generateId===!1;return{transformInput(a,s,p){let d=f||p==="update"?{}:{id:i.advanced?.generateId?i.advanced.generateId({model:s}):a.id||v()},t=u[s].fields;for(let o in t){let r=a[o];r===void 0&&(!t[o].defaultValue||p==="update")||(d[t[o].fieldName||o]=k(r,t[o],p))}return d},transformOutput(a,s,p=[]){if(!a)return null;let d=a.id||a._id?p.length===0||p.includes("id")?{id:a.id}:{}:{},t=u[s].fields;for(let o in t){if(p.length&&!p.includes(o))continue;let r=t[o];r&&(d[o]=a[r.fieldName||o])}return d},convertWhereClause(a,s){if(!s)return{};if(s.length===1){let r=s[0];return r?{[c(a,r.field)]:r.operator==="eq"||!r.operator?r.value:{[l(r.operator)]:r.value}}:void 0}let p=s.filter(r=>r.connector==="AND"||!r.connector),d=s.filter(r=>r.connector==="OR"),t=p.map(r=>({[c(a,r.field)]:r.operator==="eq"||!r.operator?r.value:{[l(r.operator)]:r.value}})),o=d.map(r=>({[c(a,r.field)]:{[r.operator||"eq"]:r.value}}));return{...t.length?{AND:t}:{},...o.length?{OR:o}:{}}},convertSelect:(a,s)=>{if(!(!a||!s))return a.reduce((p,d)=>({...p,[c(s,d)]:!0}),{})},getModelName:y,getField:c}},Ar=(e,i)=>u=>{let c=e,{transformInput:l,transformOutput:y,convertWhereClause:f,convertSelect:a,getModelName:s,getField:p}=C(i,u);return{id:"prisma",async create(d){let{model:t,data:o,select:r}=d,m=l(o,t,"create");if(!c[s(t)])throw new A(`Model ${t} does not exist in the database. If you haven't generated the Prisma client, you need to run 'npx prisma generate'`);let g=await c[s(t)].create({data:m,select:a(r,t)});return y(g,t,r)},async findOne(d){let{model:t,where:o,select:r}=d,m=f(t,o);if(!c[s(t)])throw new A(`Model ${t} does not exist in the database. If you haven't generated the Prisma client, you need to run 'npx prisma generate'`);let g=await c[s(t)].findFirst({where:m,select:a(r,t)});return y(g,t,r)},async findMany(d){let{model:t,where:o,limit:r,offset:m,sortBy:g}=d,x=f(t,o);if(!c[s(t)])throw new A(`Model ${t} does not exist in the database. If you haven't generated the Prisma client, you need to run 'npx prisma generate'`);return(await c[s(t)].findMany({where:x,take:r||100,skip:m||0,...g?.field?{orderBy:{[p(t,g.field)]:g.direction==="desc"?"desc":"asc"}}:{}})).map(F=>y(F,t))},async update(d){let{model:t,where:o,update:r}=d;if(!c[s(t)])throw new A(`Model ${t} does not exist in the database. If you haven't generated the Prisma client, you need to run 'npx prisma generate'`);let m=f(t,o),g=l(r,t,"update"),x=await c[s(t)].update({where:m,data:g});return y(x,t)},async updateMany(d){let{model:t,where:o,update:r}=d,m=f(t,o),g=l(r,t,"update"),x=await c[s(t)].updateMany({where:m,data:g});return x?x.count:0},async delete(d){let{model:t,where:o}=d,r=f(t,o);try{await c[s(t)].delete({where:r})}catch{}},async deleteMany(d){let{model:t,where:o}=d,r=f(t,o),m=await c[s(t)].deleteMany({where:r});return m?m.count:0},options:i}};export{Ar as prismaAdapter};
1
+ import{z as n}from"zod";import{APIError as H}from"better-call";var W=n.object({id:n.string(),providerId:n.string(),accountId:n.string(),userId:n.string(),accessToken:n.string().nullish(),refreshToken:n.string().nullish(),idToken:n.string().nullish(),accessTokenExpiresAt:n.date().nullish(),refreshTokenExpiresAt:n.date().nullish(),scope:n.string().nullish(),password:n.string().nullish(),createdAt:n.date().default(()=>new Date),updatedAt:n.date().default(()=>new Date)}),J=n.object({id:n.string(),email:n.string().transform(e=>e.toLowerCase()),emailVerified:n.boolean().default(!1),name:n.string(),image:n.string().nullish(),createdAt:n.date().default(()=>new Date),updatedAt:n.date().default(()=>new Date)}),G=n.object({id:n.string(),userId:n.string(),expiresAt:n.date(),createdAt:n.date().default(()=>new Date),updatedAt:n.date().default(()=>new Date),token:n.string(),ipAddress:n.string().nullish(),userAgent:n.string().nullish()}),z=n.object({id:n.string(),value:n.string(),createdAt:n.date().default(()=>new Date),updatedAt:n.date().default(()=>new Date),expiresAt:n.date(),identifier:n.string()});var T=Object.create(null),b=e=>globalThis.process?.env||globalThis.Deno?.env.toObject()||globalThis.__env__||(e?T:globalThis),O=new Proxy(T,{get(e,i){return b()[i]??T[i]},has(e,i){let u=b();return i in u||i in T},set(e,i,u){let c=b(!0);return c[i]=u,!0},deleteProperty(e,i){if(!i)return!1;let u=b(!0);return delete u[i],!0},ownKeys(){let e=b(!0);return Object.keys(e)}});function D(e){return e?e!=="false":!1}var N=typeof process<"u"&&process.env&&process.env.NODE_ENV||"";var U=N==="test"||D(O.TEST);import{createRandomStringGenerator as q}from"@better-auth/utils/random";var v=e=>q("a-z","A-Z","0-9")(e||32);import{z as _e}from"zod";import{APIError as je}from"better-call";var A=class extends Error{constructor(i,u){super(i),this.name="BetterAuthError",this.message=i,this.cause=u,this.stack=""}};import{createHash as Re}from"@better-auth/utils/hash";import{xchacha20poly1305 as Ie}from"@noble/ciphers/chacha";import{bytesToHex as De,hexToBytes as Ne,utf8ToBytes as Ue}from"@noble/ciphers/utils";import{managedNonce as Se}from"@noble/ciphers/webcrypto";import{scryptAsync as ge}from"@noble/hashes/scrypt";import{getRandomValues as Ae}from"uncrypto";import{hex as we}from"@better-auth/utils/hex";import{createRandomStringGenerator as S}from"@better-auth/utils/random";var B=S("a-z","0-9","A-Z","-_");var R=["info","success","warn","error","debug"];function L(e,i){return R.indexOf(i)<=R.indexOf(e)}var h={reset:"\x1B[0m",bright:"\x1B[1m",dim:"\x1B[2m",underscore:"\x1B[4m",blink:"\x1B[5m",reverse:"\x1B[7m",hidden:"\x1B[8m",fg:{black:"\x1B[30m",red:"\x1B[31m",green:"\x1B[32m",yellow:"\x1B[33m",blue:"\x1B[34m",magenta:"\x1B[35m",cyan:"\x1B[36m",white:"\x1B[37m"},bg:{black:"\x1B[40m",red:"\x1B[41m",green:"\x1B[42m",yellow:"\x1B[43m",blue:"\x1B[44m",magenta:"\x1B[45m",cyan:"\x1B[46m",white:"\x1B[47m"}},P={info:h.fg.blue,success:h.fg.green,warn:h.fg.yellow,error:h.fg.red,debug:h.fg.magenta},E=(e,i)=>{let u=new Date().toISOString();return`${h.dim}${u}${h.reset} ${P[e]}${e.toUpperCase()}${h.reset} ${h.bright}Better Auth${h.reset} ${i}`},I=e=>{let i=e?.disabled!==!0,u=e?.level??"error",c=(l,y,f=[])=>{if(!i||!L(u,l))return;let a=E(l,y);if(!e||typeof e.log!="function"){l==="error"?console.error(a,...f):l==="warn"?console.warn(a,...f):console.log(a,...f);return}e.log(l==="success"?"info":l,a,...f)};return Object.fromEntries(R.map(l=>[l,(...[y,...f])=>c(l,y,f)]))},M=I();var w=e=>{let i=e.plugins?.reduce((s,p)=>{let d=p.schema;if(!d)return s;for(let[t,o]of Object.entries(d))s[t]={fields:{...s[t]?.fields,...o.fields},modelName:o.modelName||t};return s},{}),u=e.rateLimit?.storage==="database",c={rateLimit:{modelName:e.rateLimit?.modelName||"rateLimit",fields:{key:{type:"string",fieldName:e.rateLimit?.fields?.key||"key"},count:{type:"number",fieldName:e.rateLimit?.fields?.count||"count"},lastRequest:{type:"number",fieldName:e.rateLimit?.fields?.lastRequest||"lastRequest"}}}},{user:l,session:y,account:f,...a}=i||{};return{user:{modelName:e.user?.modelName||"user",fields:{name:{type:"string",required:!0,fieldName:e.user?.fields?.name||"name"},email:{type:"string",unique:!0,required:!0,fieldName:e.user?.fields?.email||"email"},emailVerified:{type:"boolean",defaultValue:()=>!1,required:!0,fieldName:e.user?.fields?.emailVerified||"emailVerified"},image:{type:"string",required:!1,fieldName:e.user?.fields?.image||"image"},createdAt:{type:"date",defaultValue:()=>new Date,required:!0,fieldName:e.user?.fields?.createdAt||"createdAt"},updatedAt:{type:"date",defaultValue:()=>new Date,required:!0,fieldName:e.user?.fields?.updatedAt||"updatedAt"},...l?.fields,...e.user?.additionalFields},order:1},session:{modelName:e.session?.modelName||"session",fields:{expiresAt:{type:"date",required:!0,fieldName:e.session?.fields?.expiresAt||"expiresAt"},token:{type:"string",required:!0,fieldName:e.session?.fields?.token||"token",unique:!0},createdAt:{type:"date",required:!0,fieldName:e.session?.fields?.createdAt||"createdAt"},updatedAt:{type:"date",required:!0,fieldName:e.session?.fields?.updatedAt||"updatedAt"},ipAddress:{type:"string",required:!1,fieldName:e.session?.fields?.ipAddress||"ipAddress"},userAgent:{type:"string",required:!1,fieldName:e.session?.fields?.userAgent||"userAgent"},userId:{type:"string",fieldName:e.session?.fields?.userId||"userId",references:{model:e.user?.modelName||"user",field:"id",onDelete:"cascade"},required:!0},...y?.fields,...e.session?.additionalFields},order:2},account:{modelName:e.account?.modelName||"account",fields:{accountId:{type:"string",required:!0,fieldName:e.account?.fields?.accountId||"accountId"},providerId:{type:"string",required:!0,fieldName:e.account?.fields?.providerId||"providerId"},userId:{type:"string",references:{model:e.user?.modelName||"user",field:"id",onDelete:"cascade"},required:!0,fieldName:e.account?.fields?.userId||"userId"},accessToken:{type:"string",required:!1,fieldName:e.account?.fields?.accessToken||"accessToken"},refreshToken:{type:"string",required:!1,fieldName:e.account?.fields?.refreshToken||"refreshToken"},idToken:{type:"string",required:!1,fieldName:e.account?.fields?.idToken||"idToken"},accessTokenExpiresAt:{type:"date",required:!1,fieldName:e.account?.fields?.accessTokenExpiresAt||"accessTokenExpiresAt"},refreshTokenExpiresAt:{type:"date",required:!1,fieldName:e.account?.fields?.accessTokenExpiresAt||"refreshTokenExpiresAt"},scope:{type:"string",required:!1,fieldName:e.account?.fields?.scope||"scope"},password:{type:"string",required:!1,fieldName:e.account?.fields?.password||"password"},createdAt:{type:"date",required:!0,fieldName:e.account?.fields?.createdAt||"createdAt"},updatedAt:{type:"date",required:!0,fieldName:e.account?.fields?.updatedAt||"updatedAt"},...f?.fields},order:3},verification:{modelName:e.verification?.modelName||"verification",fields:{identifier:{type:"string",required:!0,fieldName:e.verification?.fields?.identifier||"identifier"},value:{type:"string",required:!0,fieldName:e.verification?.fields?.value||"value"},expiresAt:{type:"date",required:!0,fieldName:e.verification?.fields?.expiresAt||"expiresAt"},createdAt:{type:"date",required:!1,defaultValue:()=>new Date,fieldName:e.verification?.fields?.createdAt||"createdAt"},updatedAt:{type:"date",required:!1,defaultValue:()=>new Date,fieldName:e.verification?.fields?.updatedAt||"updatedAt"}},order:4},...a,...u?c:{}}};import{z as At}from"zod";import{Kysely as bt,MssqlDialect as vt}from"kysely";import{MysqlDialect as kt,PostgresDialect as Rt,SqliteDialect as Ot}from"kysely";function k(e,i,u){return u==="update"?e:e==null&&i.defaultValue?typeof i.defaultValue=="function"?i.defaultValue():i.defaultValue:e}var C=(e,i)=>{let u=w(i);function c(a,s){return s==="id"?s:u[a].fields[s].fieldName||s}function l(a){switch(a){case"starts_with":return"startsWith";case"ends_with":return"endsWith";default:return a}}function y(a){return u[a].modelName}let f=i?.advanced?.generateId===!1;return{transformInput(a,s,p){let d=f||p==="update"?{}:{id:i.advanced?.generateId?i.advanced.generateId({model:s}):a.id||v()},t=u[s].fields;for(let o in t){let r=a[o];r===void 0&&(!t[o].defaultValue||p==="update")||(d[t[o].fieldName||o]=k(r,t[o],p))}return d},transformOutput(a,s,p=[]){if(!a)return null;let d=a.id||a._id?p.length===0||p.includes("id")?{id:a.id}:{}:{},t=u[s].fields;for(let o in t){if(p.length&&!p.includes(o))continue;let r=t[o];r&&(d[o]=a[r.fieldName||o])}return d},convertWhereClause(a,s){if(!s)return{};if(s.length===1){let r=s[0];return r?{[c(a,r.field)]:r.operator==="eq"||!r.operator?r.value:{[l(r.operator)]:r.value}}:void 0}let p=s.filter(r=>r.connector==="AND"||!r.connector),d=s.filter(r=>r.connector==="OR"),t=p.map(r=>({[c(a,r.field)]:r.operator==="eq"||!r.operator?r.value:{[l(r.operator)]:r.value}})),o=d.map(r=>({[c(a,r.field)]:{[r.operator||"eq"]:r.value}}));return{...t.length?{AND:t}:{},...o.length?{OR:o}:{}}},convertSelect:(a,s)=>{if(!(!a||!s))return a.reduce((p,d)=>({...p,[c(s,d)]:!0}),{})},getModelName:y,getField:c}},Ar=(e,i)=>u=>{let c=e,{transformInput:l,transformOutput:y,convertWhereClause:f,convertSelect:a,getModelName:s,getField:p}=C(i,u);return{id:"prisma",async create(d){let{model:t,data:o,select:r}=d,m=l(o,t,"create");if(!c[s(t)])throw new A(`Model ${t} does not exist in the database. If you haven't generated the Prisma client, you need to run 'npx prisma generate'`);let g=await c[s(t)].create({data:m,select:a(r,t)});return y(g,t,r)},async findOne(d){let{model:t,where:o,select:r}=d,m=f(t,o);if(!c[s(t)])throw new A(`Model ${t} does not exist in the database. If you haven't generated the Prisma client, you need to run 'npx prisma generate'`);let g=await c[s(t)].findFirst({where:m,select:a(r,t)});return y(g,t,r)},async findMany(d){let{model:t,where:o,limit:r,offset:m,sortBy:g}=d,x=f(t,o);if(!c[s(t)])throw new A(`Model ${t} does not exist in the database. If you haven't generated the Prisma client, you need to run 'npx prisma generate'`);return(await c[s(t)].findMany({where:x,take:r||100,skip:m||0,...g?.field?{orderBy:{[p(t,g.field)]:g.direction==="desc"?"desc":"asc"}}:{}})).map(F=>y(F,t))},async update(d){let{model:t,where:o,update:r}=d;if(!c[s(t)])throw new A(`Model ${t} does not exist in the database. If you haven't generated the Prisma client, you need to run 'npx prisma generate'`);let m=f(t,o),g=l(r,t,"update"),x=await c[s(t)].update({where:m,data:g});return y(x,t)},async updateMany(d){let{model:t,where:o,update:r}=d,m=f(t,o),g=l(r,t,"update"),x=await c[s(t)].updateMany({where:m,data:g});return x?x.count:0},async delete(d){let{model:t,where:o}=d,r=f(t,o);try{await c[s(t)].delete({where:r})}catch{}},async deleteMany(d){let{model:t,where:o}=d,r=f(t,o),m=await c[s(t)].deleteMany({where:r});return m?m.count:0},options:i}};export{Ar as prismaAdapter};
package/dist/api.cjs CHANGED
@@ -1,6 +1,6 @@
1
- "use strict";var he=Object.defineProperty;var sr=Object.getOwnPropertyDescriptor;var ar=Object.getOwnPropertyNames;var dr=Object.prototype.hasOwnProperty;var cr=(e,t)=>{for(var r in t)he(e,r,{get:t[r],enumerable:!0})},lr=(e,t,r,o)=>{if(t&&typeof t=="object"||typeof t=="function")for(let i of ar(t))!dr.call(e,i)&&i!==r&&he(e,i,{get:()=>t[i],enumerable:!(o=sr(t,i))||o.enumerable});return e};var ur=e=>lr(he({},"__esModule",{value:!0}),e);var Mr={};cr(Mr,{APIError:()=>pe.APIError,callbackOAuth:()=>je,changeEmail:()=>Ge,changePassword:()=>qe,createAuthEndpoint:()=>h,createAuthMiddleware:()=>J,createEmailVerificationToken:()=>j,deleteUser:()=>He,deleteUserCallback:()=>ge,error:()=>We,forgetPassword:()=>Ve,forgetPasswordCallback:()=>Be,freshSessionMiddleware:()=>vr,getEndpoints:()=>ir,getSession:()=>le,getSessionFromCtx:()=>Q,linkSocialAccount:()=>Ye,listSessions:()=>ve,listUserAccounts:()=>Je,ok:()=>Qe,optionsMiddleware:()=>we,originCheckMiddleware:()=>Ae,resetPassword:()=>Me,revokeOtherSessions:()=>xe,revokeSession:()=>Ie,revokeSessions:()=>Le,router:()=>Br,sendVerificationEmail:()=>Pe,sendVerificationEmailFn:()=>Jt,sessionMiddleware:()=>L,setPassword:()=>Fe,signInEmail:()=>Ne,signInSocial:()=>Ce,signOut:()=>$e,signUpEmail:()=>Ze,updateUser:()=>ze,verifyEmail:()=>De});module.exports=ur(Mr);var T=require("better-call");var it=require("better-call");var Z=require("better-call"),we=(0,Z.createMiddleware)(async()=>({})),J=(0,Z.createMiddlewareCreator)({use:[we,(0,Z.createMiddleware)(async()=>({}))]}),h=(0,Z.createEndpointCreator)({use:[we]});function be(e){return e==="-"||e==="^"||e==="$"||e==="+"||e==="."||e==="("||e===")"||e==="|"||e==="["||e==="]"||e==="{"||e==="}"||e==="*"||e==="?"||e==="\\"?`\\${e}`:e}function pr(e){let t="";for(let r=0;r<e.length;r++)t+=be(e[r]);return t}function Xe(e,t=!0){if(Array.isArray(e))return`(?:${e.map(u=>`^${Xe(u,t)}$`).join("|")})`;let r="",o="",i=".";t===!0?(r="/",o="[/\\\\]",i="[^/\\\\]"):t&&(r=t,o=pr(r),o.length>1?(o=`(?:${o})`,i=`((?!${o}).)`):i=`[^${o}]`);let n=t?`${o}+?`:"",s=t?`${o}*?`:"",d=t?e.split(r):[e],a="";for(let c=0;c<d.length;c++){let u=d[c],b=d[c+1],f="";if(!(!u&&c>0)){if(t&&(c===d.length-1?f=s:b!=="**"?f=n:f=""),t&&u==="**"){f&&(a+=c===0?"":f,a+=`(?:${i}*?${f})*?`);continue}for(let l=0;l<u.length;l++){let y=u[l];y==="\\"?l<u.length-1&&(a+=be(u[l+1]),l++):y==="?"?a+=i:y==="*"?a+=`${i}*?`:a+=be(y)}a+=f}}return a}function mr(e,t){if(typeof t!="string")throw new TypeError(`Sample must be a string, but ${typeof t} given`);return e.test(t)}function ne(e,t){if(typeof e!="string"&&!Array.isArray(e))throw new TypeError(`The first argument must be a single pattern string or an array of patterns, but ${typeof e} given`);if((typeof t=="string"||typeof t=="boolean")&&(t={separator:t}),arguments.length===2&&!(typeof t>"u"||typeof t=="object"&&t!==null&&!Array.isArray(t)))throw new TypeError(`The second argument must be an options object or a string/boolean separator, but ${typeof t} given`);if(t=t||{},t.separator==="\\")throw new Error("\\ is not a valid separator because it is used for escaping. Try setting the separator to `true` instead");let r=Xe(e,t.separator),o=new RegExp(`^${r}$`,t.flags),i=mr.bind(null,o);return i.options=t,i.pattern=e,i.regexp=o,i}var se=Object.create(null),oe=e=>globalThis.process?.env||globalThis.Deno?.env.toObject()||globalThis.__env__||(e?se:globalThis),et=new Proxy(se,{get(e,t){return oe()[t]??se[t]},has(e,t){let r=oe();return t in r||t in se},set(e,t,r){let o=oe(!0);return o[t]=r,!0},deleteProperty(e,t){if(!t)return!1;let r=oe(!0);return delete r[t],!0},ownKeys(){let e=oe(!0);return Object.keys(e)}});function fr(e){return e?e!=="false":!1}var ye=typeof process<"u"&&process.env&&process.env.NODE_ENV||"";var ae=ye==="dev"||ye==="development",tt=ye==="test"||fr(et.TEST);var F=class extends Error{constructor(t,r){super(t),this.name="BetterAuthError",this.message=t,this.cause=r,this.stack=""}};function rt(e){try{return new URL(e).origin}catch{return null}}function ot(e){return e.includes("://")?new URL(e).host:e}var Ae=J(async e=>{if(e.request?.method!=="POST")return;let{body:t,query:r,context:o}=e,i=e.headers?.get("origin")||e.headers?.get("referer")||"",n=t?.callbackURL||r?.callbackURL,s=t?.redirectTo,d=r?.currentURL,a=t?.errorCallbackURL,c=t?.newUserCallbackURL,u=o.trustedOrigins,b=e.headers?.has("cookie"),f=(y,U)=>y.startsWith("/")?!1:U.includes("*")?ne(U)(ot(y)):y.startsWith(U),l=(y,U)=>{if(!y)return;if(!u.some(q=>f(y,q)||y?.startsWith("/")&&U!=="origin"&&!y.includes(":")))throw e.context.logger.error(`Invalid ${U}: ${y}`),e.context.logger.info(`If it's a valid URL, please add ${y} to trustedOrigins in your auth config
2
- `,`Current list of trustedOrigins: ${u}`),new it.APIError("FORBIDDEN",{message:`Invalid ${U}`})};b&&!e.context.options.advanced?.disableCSRFCheck&&l(i,"origin"),n&&l(n,"callbackURL"),s&&l(s,"redirectURL"),d&&l(d,"currentURL"),a&&l(a,"errorCallbackURL"),c&&l(s,"newUserCallbackURL")});var v=require("better-call"),_=require("zod");var H=(e,t="ms")=>new Date(Date.now()+(t==="sec"?e*1e3:e));var nt=require("@better-auth/utils/base64");var st=require("@better-auth/utils/hmac");async function ke(e,t){if(e.context.options.session?.cookieCache?.enabled){let o=nt.base64Url.encode(JSON.stringify({session:t,expiresAt:H(e.context.authCookies.sessionData.options.maxAge||60,"sec").getTime(),signature:await(0,st.createHMAC)("SHA-256","base64urlnopad").sign(e.context.secret,JSON.stringify(t))}),{padding:!1});if(o.length>4093)throw new F("Session data is too large to store in the cookie. Please disable session cookie caching or reduce the size of the session data");e.setCookie(e.context.authCookies.sessionData.name,o,e.context.authCookies.sessionData.options)}}async function I(e,t,r,o){let i=e.context.authCookies.sessionToken.options,n=r?void 0:e.context.sessionConfig.expiresIn;await e.setSignedCookie(e.context.authCookies.sessionToken.name,t.session.token,e.context.secret,{...i,maxAge:n,...o}),r&&await e.setSignedCookie(e.context.authCookies.dontRememberToken.name,"true",e.context.secret,e.context.authCookies.dontRememberToken.options),await ke(e,t),e.context.setNewSession(t),e.context.options.secondaryStorage&&await e.context.secondaryStorage?.set(t.session.token,JSON.stringify({user:t.user,session:t.session}),Math.floor((new Date(t.session.expiresAt).getTime()-Date.now())/1e3))}function $(e){e.setCookie(e.context.authCookies.sessionToken.name,"",{...e.context.authCookies.sessionToken.options,maxAge:0}),e.setCookie(e.context.authCookies.sessionData.name,"",{...e.context.authCookies.sessionData.options,maxAge:0}),e.setCookie(e.context.authCookies.dontRememberToken.name,"",{...e.context.authCookies.dontRememberToken.options,maxAge:0})}var mt=require("@better-fetch/fetch"),ft=require("better-call"),G=require("jose");var at=require("@better-auth/utils/hash"),dt=require("@better-auth/utils/base64");async function ct(e){let t=await(0,at.createHash)("SHA-256").digest(e);return dt.base64Url.encode(new Uint8Array(t),{padding:!1})}function de(e){return{tokenType:e.token_type,accessToken:e.access_token,refreshToken:e.refresh_token,accessTokenExpiresAt:e.expires_in?H(e.expires_in,"sec"):void 0,scopes:e?.scope?typeof e.scope=="string"?e.scope.split(" "):e.scope:[],idToken:e.id_token}}async function k({id:e,options:t,authorizationEndpoint:r,state:o,codeVerifier:i,scopes:n,claims:s,redirectURI:d,duration:a}){let c=new URL(r);if(c.searchParams.set("response_type","code"),c.searchParams.set("client_id",t.clientId),c.searchParams.set("state",o),c.searchParams.set("scope",n.join(" ")),c.searchParams.set("redirect_uri",t.redirectURI||d),i){let u=await ct(i);c.searchParams.set("code_challenge_method","S256"),c.searchParams.set("code_challenge",u)}if(s){let u=s.reduce((b,f)=>(b[f]=null,b),{});c.searchParams.set("claims",JSON.stringify({id_token:{email:null,email_verified:null,...u}}))}return a&&c.searchParams.set("duration",a),c}var lt=require("@better-fetch/fetch");var gr=require("jose");async function A({code:e,codeVerifier:t,redirectURI:r,options:o,tokenEndpoint:i,authentication:n}){let s=new URLSearchParams,d={"content-type":"application/x-www-form-urlencoded",accept:"application/json","user-agent":"better-auth"};if(s.set("grant_type","authorization_code"),s.set("code",e),t&&s.set("code_verifier",t),s.set("redirect_uri",r),n==="basic"){let b=btoa(`${o.clientId}:${o.clientSecret}`);d.authorization=`Basic ${b}`}else s.set("client_id",o.clientId),s.set("client_secret",o.clientSecret);let{data:a,error:c}=await(0,lt.betterFetch)(i,{method:"POST",body:s,headers:d});if(c)throw c;return de(a)}var V=require("zod"),Ee=require("better-call");var yr=require("@better-auth/utils/hash"),Ar=require("@noble/ciphers/chacha"),Re=require("@noble/ciphers/utils"),kr=require("@noble/ciphers/webcrypto");var hr=require("@noble/hashes/scrypt"),wr=require("uncrypto"),br=require("@better-auth/utils/hex");var ut=require("@better-auth/utils/random"),ie=(0,ut.createRandomStringGenerator)("a-z","0-9","A-Z","-_");async function ce(e,t){let r=e.body?.callbackURL||(e.query?.currentURL?rt(e.query?.currentURL):"")||e.context.options.baseURL;if(!r)throw new Ee.APIError("BAD_REQUEST",{message:"callbackURL is required"});let o=ie(128),i=ie(32),n=JSON.stringify({callbackURL:r,codeVerifier:o,errorURL:e.body?.errorCallbackURL||e.query?.currentURL,newUserURL:e.body?.newUserCallbackURL,link:t,expiresAt:Date.now()+10*60*1e3}),s=new Date;s.setMinutes(s.getMinutes()+10);let d=await e.context.internalAdapter.createVerificationValue({value:n,identifier:i,expiresAt:s});if(!d)throw e.context.logger.error("Unable to create verification. Make sure the database adapter is properly working and there is a verification table in the database"),new Ee.APIError("INTERNAL_SERVER_ERROR",{message:"Unable to create verification"});return{state:d.identifier,codeVerifier:o}}async function pt(e){let t=e.query.state||e.body.state,r=await e.context.internalAdapter.findVerificationValue(t);if(!r)throw e.context.logger.error("State Mismatch. Verification not found",{state:t}),e.redirect(`${e.context.baseURL}/error?error=please_restart_the_process`);let o=V.z.object({callbackURL:V.z.string(),codeVerifier:V.z.string(),errorURL:V.z.string().optional(),newUserURL:V.z.string().optional(),expiresAt:V.z.number(),link:V.z.object({email:V.z.string(),userId:V.z.string()}).optional()}).parse(JSON.parse(r.value));if(o.errorURL||(o.errorURL=`${e.context.baseURL}/error`),o.expiresAt<Date.now())throw await e.context.internalAdapter.deleteVerificationValue(r.id),e.context.logger.error("State expired.",{state:t}),e.redirect(`${e.context.baseURL}/error?error=please_restart_the_process`);return await e.context.internalAdapter.deleteVerificationValue(r.id),o}var gt=e=>{let t="https://appleid.apple.com/auth/token";return{id:"apple",name:"Apple",createAuthorizationURL({state:r,scopes:o,redirectURI:i}){let n=o||["email","name"];return e.scope&&n.push(...e.scope),new URL(`https://appleid.apple.com/auth/authorize?client_id=${e.clientId}&response_type=code&redirect_uri=${e.redirectURI||i}&scope=${n.join(" ")}&state=${r}&response_mode=form_post`)},validateAuthorizationCode:async({code:r,codeVerifier:o,redirectURI:i})=>A({code:r,codeVerifier:o,redirectURI:e.redirectURI||i,options:e,tokenEndpoint:t}),async verifyIdToken(r,o){if(e.disableIdTokenSignIn)return!1;if(e.verifyIdToken)return e.verifyIdToken(r,o);let i=(0,G.decodeProtectedHeader)(r),{kid:n,alg:s}=i;if(!n||!s)return!1;let d=await Rr(n),{payload:a}=await(0,G.jwtVerify)(r,d,{algorithms:[s],issuer:"https://appleid.apple.com",audience:e.appBundleIdentifier||e.clientId,maxTokenAge:"1h"});return["email_verified","is_private_email"].forEach(c=>{a[c]!==void 0&&(a[c]=!!a[c])}),o&&a.nonce!==o?!1:!!a},async getUserInfo(r){if(e.getUserInfo)return e.getUserInfo(r);if(!r.idToken)return null;let o=(0,G.decodeJwt)(r.idToken);if(!o)return null;let i=o.user?`${o.user.name.firstName} ${o.user.name.lastName}`:o.email,n=await e.mapProfileToUser?.(o);return{user:{id:o.sub,name:i,emailVerified:!1,email:o.email,...n},data:o}}}},Rr=async e=>{let t="https://appleid.apple.com",r="/auth/keys",{data:o}=await(0,mt.betterFetch)(`${t}${r}`);if(!o?.keys)throw new ft.APIError("BAD_REQUEST",{message:"Keys not found"});let i=o.keys.find(n=>n.kid===e);if(!i)throw new Error(`JWK with kid ${e} not found`);return await(0,G.importJWK)(i,i.alg)};var ht=require("@better-fetch/fetch");var wt=e=>({id:"discord",name:"Discord",createAuthorizationURL({state:t,scopes:r,redirectURI:o}){let i=r||["identify","email"];return e.scope&&i.push(...e.scope),new URL(`https://discord.com/api/oauth2/authorize?scope=${i.join("+")}&response_type=code&client_id=${e.clientId}&redirect_uri=${encodeURIComponent(e.redirectURI||o)}&state=${t}&prompt=${e.prompt||"none"}`)},validateAuthorizationCode:async({code:t,redirectURI:r})=>A({code:t,redirectURI:e.redirectURI||r,options:e,tokenEndpoint:"https://discord.com/api/oauth2/token"}),async getUserInfo(t){if(e.getUserInfo)return e.getUserInfo(t);let{data:r,error:o}=await(0,ht.betterFetch)("https://discord.com/api/users/@me",{headers:{authorization:`Bearer ${t.accessToken}`}});if(o)return null;if(r.avatar===null){let n=r.discriminator==="0"?Number(BigInt(r.id)>>BigInt(22))%6:parseInt(r.discriminator)%5;r.image_url=`https://cdn.discordapp.com/embed/avatars/${n}.png`}else{let n=r.avatar.startsWith("a_")?"gif":"png";r.image_url=`https://cdn.discordapp.com/avatars/${r.id}/${r.avatar}.${n}`}let i=await e.mapProfileToUser?.(r);return{user:{id:r.id,name:r.display_name||r.username||"",email:r.email,emailVerified:r.verified,image:r.image_url,...i},data:r}}});var bt=require("@better-fetch/fetch");var yt=e=>({id:"facebook",name:"Facebook",async createAuthorizationURL({state:t,scopes:r,redirectURI:o}){let i=r||["email","public_profile"];return e.scope&&i.push(...e.scope),await k({id:"facebook",options:e,authorizationEndpoint:"https://www.facebook.com/v21.0/dialog/oauth",scopes:i,state:t,redirectURI:o})},validateAuthorizationCode:async({code:t,redirectURI:r})=>A({code:t,redirectURI:e.redirectURI||r,options:e,tokenEndpoint:"https://graph.facebook.com/oauth/access_token"}),async getUserInfo(t){if(e.getUserInfo)return e.getUserInfo(t);let{data:r,error:o}=await(0,bt.betterFetch)("https://graph.facebook.com/me?fields=id,name,email,picture",{auth:{type:"Bearer",token:t.accessToken}});if(o)return null;let i=await e.mapProfileToUser?.(r);return{user:{id:r.id,name:r.name,email:r.email,image:r.picture.data.url,emailVerified:r.email_verified,...i},data:r}}});var Ue=require("@better-fetch/fetch");var At=e=>{let t="https://github.com/login/oauth/access_token";return{id:"github",name:"GitHub",createAuthorizationURL({state:r,scopes:o,codeVerifier:i,redirectURI:n}){let s=o||["user:email"];return e.scope&&s.push(...e.scope),k({id:"github",options:e,authorizationEndpoint:"https://github.com/login/oauth/authorize",scopes:s,state:r,redirectURI:n})},validateAuthorizationCode:async({code:r,redirectURI:o})=>A({code:r,redirectURI:e.redirectURI||o,options:e,tokenEndpoint:t}),async getUserInfo(r){if(e.getUserInfo)return e.getUserInfo(r);let{data:o,error:i}=await(0,Ue.betterFetch)("https://api.github.com/user",{headers:{"User-Agent":"better-auth",authorization:`Bearer ${r.accessToken}`}});if(i)return null;let n=!1,{data:s}=await(0,Ue.betterFetch)("https://api.github.com/user/emails",{headers:{authorization:`Bearer ${r.accessToken}`,"User-Agent":"better-auth"}});s&&(o.email=(s.find(a=>a.primary)??s[0])?.email,n=s.find(a=>a.email===o.email)?.verified??!1);let d=await e.mapProfileToUser?.(o);return{user:{id:o.id.toString(),name:o.name||o.login,email:o.email,image:o.avatar_url,emailVerified:n,...d},data:o}}}};var _e=["info","success","warn","error","debug"];function Er(e,t){return _e.indexOf(t)<=_e.indexOf(e)}var B={reset:"\x1B[0m",bright:"\x1B[1m",dim:"\x1B[2m",underscore:"\x1B[4m",blink:"\x1B[5m",reverse:"\x1B[7m",hidden:"\x1B[8m",fg:{black:"\x1B[30m",red:"\x1B[31m",green:"\x1B[32m",yellow:"\x1B[33m",blue:"\x1B[34m",magenta:"\x1B[35m",cyan:"\x1B[36m",white:"\x1B[37m"},bg:{black:"\x1B[40m",red:"\x1B[41m",green:"\x1B[42m",yellow:"\x1B[43m",blue:"\x1B[44m",magenta:"\x1B[45m",cyan:"\x1B[46m",white:"\x1B[47m"}},Ur={info:B.fg.blue,success:B.fg.green,warn:B.fg.yellow,error:B.fg.red,debug:B.fg.magenta},_r=(e,t)=>{let r=new Date().toISOString();return`${B.dim}${r}${B.reset} ${Ur[e]}${e.toUpperCase()}${B.reset} ${B.bright}Better Auth${B.reset} ${t}`},Tr=e=>{let t=e?.disabled!==!0,r=e?.level??"error",o=(i,n,s=[])=>{if(!t||!Er(r,i))return;let d=_r(i,n);if(!e||typeof e.log!="function"){i==="error"?console.error(d,...s):i==="warn"?console.warn(d,...s):console.log(d,...s);return}e.log(i==="success"?"info":i,d,...s)};return Object.fromEntries(_e.map(i=>[i,(...[n,...s])=>o(i,n,s)]))},D=Tr();var kt=require("@better-fetch/fetch"),Rt=require("jose"),Et=e=>({id:"google",name:"Google",async createAuthorizationURL({state:t,scopes:r,codeVerifier:o,redirectURI:i}){if(!e.clientId||!e.clientSecret)throw D.error("Client Id and Client Secret is required for Google. Make sure to provide them in the options."),new F("CLIENT_ID_AND_SECRET_REQUIRED");if(!o)throw new F("codeVerifier is required for Google");let n=r||["email","profile","openid"];e.scope&&n.push(...e.scope);let s=await k({id:"google",options:e,authorizationEndpoint:"https://accounts.google.com/o/oauth2/auth",scopes:n,state:t,codeVerifier:o,redirectURI:i});return e.accessType&&s.searchParams.set("access_type",e.accessType),e.prompt&&s.searchParams.set("prompt",e.prompt),s},validateAuthorizationCode:async({code:t,codeVerifier:r,redirectURI:o})=>A({code:t,codeVerifier:r,redirectURI:e.redirectURI||o,options:e,tokenEndpoint:"https://oauth2.googleapis.com/token"}),async verifyIdToken(t,r){if(e.disableIdTokenSignIn)return!1;if(e.verifyIdToken)return e.verifyIdToken(t,r);let o=`https://www.googleapis.com/oauth2/v3/tokeninfo?id_token=${t}`,{data:i}=await(0,kt.betterFetch)(o);return i?i.aud===e.clientId&&i.iss==="https://accounts.google.com":!1},async getUserInfo(t){if(e.getUserInfo)return e.getUserInfo(t);if(!t.idToken)return null;let r=(0,Rt.decodeJwt)(t.idToken),o=await e.mapProfileToUser?.(r);return{user:{id:r.sub,name:r.name,email:r.email,image:r.picture,emailVerified:r.email_verified,...o},data:r}}});var Ut=require("@better-fetch/fetch");var _t=require("jose"),Tt=e=>{let t=e.tenantId||"common",r=`https://login.microsoftonline.com/${t}/oauth2/v2.0/authorize`,o=`https://login.microsoftonline.com/${t}/oauth2/v2.0/token`;return{id:"microsoft",name:"Microsoft EntraID",createAuthorizationURL(i){let n=i.scopes||["openid","profile","email","User.Read"];return e.scope&&n.push(...e.scope),k({id:"microsoft",options:e,authorizationEndpoint:r,state:i.state,codeVerifier:i.codeVerifier,scopes:n,redirectURI:i.redirectURI})},validateAuthorizationCode({code:i,codeVerifier:n,redirectURI:s}){return A({code:i,codeVerifier:n,redirectURI:e.redirectURI||s,options:e,tokenEndpoint:o})},async getUserInfo(i){if(e.getUserInfo)return e.getUserInfo(i);if(!i.idToken)return null;let n=(0,_t.decodeJwt)(i.idToken),s=e.profilePhotoSize||48;await(0,Ut.betterFetch)(`https://graph.microsoft.com/v1.0/me/photos/${s}x${s}/$value`,{headers:{Authorization:`Bearer ${i.accessToken}`},async onResponse(a){if(!(e.disableProfilePhoto||!a.response.ok))try{let u=await a.response.clone().arrayBuffer(),b=Buffer.from(u).toString("base64");n.picture=`data:image/jpeg;base64, ${b}`}catch(c){D.error(c&&typeof c=="object"&&"name"in c?c.name:"",c)}}});let d=await e.mapProfileToUser?.(n);return{user:{id:n.sub,name:n.name,email:n.email,image:n.picture,emailVerified:!0,...d},data:n}}}};var Ot=require("@better-fetch/fetch");var St=e=>({id:"spotify",name:"Spotify",createAuthorizationURL({state:t,scopes:r,codeVerifier:o,redirectURI:i}){let n=r||["user-read-email"];return e.scope&&n.push(...e.scope),k({id:"spotify",options:e,authorizationEndpoint:"https://accounts.spotify.com/authorize",scopes:n,state:t,codeVerifier:o,redirectURI:i})},validateAuthorizationCode:async({code:t,codeVerifier:r,redirectURI:o})=>A({code:t,codeVerifier:r,redirectURI:e.redirectURI||o,options:e,tokenEndpoint:"https://accounts.spotify.com/api/token"}),async getUserInfo(t){if(e.getUserInfo)return e.getUserInfo(t);let{data:r,error:o}=await(0,Ot.betterFetch)("https://api.spotify.com/v1/me",{method:"GET",headers:{Authorization:`Bearer ${t.accessToken}`}});if(o)return null;let i=await e.mapProfileToUser?.(r);return{user:{id:r.id,name:r.display_name,email:r.email,image:r.images[0]?.url,emailVerified:!1,...i},data:r}}});var Y={isAction:!1};var vt=require("@better-auth/utils/random"),It=e=>(0,vt.createRandomStringGenerator)("a-z","A-Z","0-9")(e||32);var Lt=require("jose"),xt=e=>({id:"twitch",name:"Twitch",createAuthorizationURL({state:t,scopes:r,redirectURI:o}){let i=r||["user:read:email","openid"];return e.scope&&i.push(...e.scope),k({id:"twitch",redirectURI:o,options:e,authorizationEndpoint:"https://id.twitch.tv/oauth2/authorize",scopes:i,state:t,claims:e.claims||["email","email_verified","preferred_username","picture"]})},validateAuthorizationCode:async({code:t,redirectURI:r})=>A({code:t,redirectURI:e.redirectURI||r,options:e,tokenEndpoint:"https://id.twitch.tv/oauth2/token"}),async getUserInfo(t){if(e.getUserInfo)return e.getUserInfo(t);let r=t.idToken;if(!r)return D.error("No idToken found in token"),null;let o=(0,Lt.decodeJwt)(r),i=await e.mapProfileToUser?.(o);return{user:{id:o.sub,name:o.preferred_username,email:o.email,image:o.picture,emailVerified:!1,...i},data:o}}});var Pt=require("@better-fetch/fetch");var Dt=e=>({id:"twitter",name:"Twitter",createAuthorizationURL(t){let r=t.scopes||["users.read","tweet.read","offline.access"];return e.scope&&r.push(...e.scope),k({id:"twitter",options:e,authorizationEndpoint:"https://x.com/i/oauth2/authorize",scopes:r,state:t.state,codeVerifier:t.codeVerifier,redirectURI:t.redirectURI})},validateAuthorizationCode:async({code:t,codeVerifier:r,redirectURI:o})=>A({code:t,codeVerifier:r,authentication:"basic",redirectURI:e.redirectURI||o,options:e,tokenEndpoint:"https://api.x.com/2/oauth2/token"}),async getUserInfo(t){if(e.getUserInfo)return e.getUserInfo(t);let{data:r,error:o}=await(0,Pt.betterFetch)("https://api.x.com/2/users/me?user.fields=profile_image_url",{method:"GET",headers:{Authorization:`Bearer ${t.accessToken}`}});if(o)return null;let i=await e.mapProfileToUser?.(r);return{user:{id:r.data.id,name:r.data.name,email:r.data.username||null,image:r.data.profile_image_url,emailVerified:r.data.verified||!1,...i},data:r}}});var Ct=require("@better-fetch/fetch");var Nt=e=>{let t="https://api.dropboxapi.com/oauth2/token";return{id:"dropbox",name:"Dropbox",createAuthorizationURL:async({state:r,scopes:o,codeVerifier:i,redirectURI:n})=>{let s=o||["account_info.read"];return e.scope&&s.push(...e.scope),await k({id:"dropbox",options:e,authorizationEndpoint:"https://www.dropbox.com/oauth2/authorize",scopes:s,state:r,redirectURI:n,codeVerifier:i})},validateAuthorizationCode:async({code:r,codeVerifier:o,redirectURI:i})=>await A({code:r,codeVerifier:o,redirectURI:e.redirectURI||i,options:e,tokenEndpoint:t}),async getUserInfo(r){if(e.getUserInfo)return e.getUserInfo(r);let{data:o,error:i}=await(0,Ct.betterFetch)("https://api.dropboxapi.com/2/users/get_current_account",{method:"POST",headers:{Authorization:`Bearer ${r.accessToken}`}});if(i)return null;let n=await e.mapProfileToUser?.(o);return{user:{id:o.account_id,name:o.name?.display_name,email:o.email,emailVerified:o.email_verified||!1,image:o.profile_photo_url,...n},data:o}}}};var jt=require("@better-fetch/fetch");var $t=e=>{let t="https://www.linkedin.com/oauth/v2/authorization",r="https://www.linkedin.com/oauth/v2/accessToken";return{id:"linkedin",name:"Linkedin",createAuthorizationURL:async({state:o,scopes:i,redirectURI:n})=>{let s=i||["profile","email","openid"];return e.scope&&s.push(...e.scope),await k({id:"linkedin",options:e,authorizationEndpoint:t,scopes:s,state:o,redirectURI:n})},validateAuthorizationCode:async({code:o,redirectURI:i})=>await A({code:o,redirectURI:e.redirectURI||i,options:e,tokenEndpoint:r}),async getUserInfo(o){let{data:i,error:n}=await(0,jt.betterFetch)("https://api.linkedin.com/v2/userinfo",{method:"GET",headers:{Authorization:`Bearer ${o.accessToken}`}});if(n)return null;let s=await e.mapProfileToUser?.(i);return{user:{id:i.sub,name:i.name,email:i.email,emailVerified:i.email_verified||!1,image:i.picture,...s},data:i}}}};var Vt=require("@better-fetch/fetch");var Te=(e="")=>e.split("://").map(t=>t.replace(/\/{2,}/g,"/")).join("://"),Or=e=>{let t=e||"https://gitlab.com";return{authorizationEndpoint:Te(`${t}/oauth/authorize`),tokenEndpoint:Te(`${t}/oauth/token`),userinfoEndpoint:Te(`${t}/api/v4/user`)}},Bt=e=>{let{authorizationEndpoint:t,tokenEndpoint:r,userinfoEndpoint:o}=Or(e.issuer),i="gitlab";return{id:i,name:"Gitlab",createAuthorizationURL:async({state:s,scopes:d,codeVerifier:a,redirectURI:c})=>{let u=d||["read_user"];return e.scope&&u.push(...e.scope),await k({id:i,options:e,authorizationEndpoint:t,scopes:u,state:s,redirectURI:c,codeVerifier:a})},validateAuthorizationCode:async({code:s,redirectURI:d,codeVerifier:a})=>A({code:s,redirectURI:e.redirectURI||d,options:e,codeVerifier:a,tokenEndpoint:r}),async getUserInfo(s){if(e.getUserInfo)return e.getUserInfo(s);let{data:d,error:a}=await(0,Vt.betterFetch)(o,{headers:{authorization:`Bearer ${s.accessToken}`}});if(a||d.state!=="active"||d.locked)return null;let c=await e.mapProfileToUser?.(d);return{user:{id:d.id.toString(),name:d.name??d.username,email:d.email,image:d.avatar_url,emailVerified:!0,...c},data:d}}}};var Oe=require("@better-fetch/fetch");var Mt=e=>({id:"reddit",name:"Reddit",createAuthorizationURL({state:t,scopes:r,redirectURI:o}){let i=r||["identity"];return e.scope&&i.push(...e.scope),k({id:"reddit",options:e,authorizationEndpoint:"https://www.reddit.com/api/v1/authorize",scopes:i,state:t,redirectURI:o,duration:e.duration})},validateAuthorizationCode:async({code:t,redirectURI:r})=>{let o=new URLSearchParams({grant_type:"authorization_code",code:t,redirect_uri:e.redirectURI||r}),i={"content-type":"application/x-www-form-urlencoded",accept:"text/plain","user-agent":"better-auth",Authorization:`Basic ${Buffer.from(`${e.clientId}:${e.clientSecret}`).toString("base64")}`},{data:n,error:s}=await(0,Oe.betterFetch)("https://www.reddit.com/api/v1/access_token",{method:"POST",headers:i,body:o.toString()});if(s)throw s;return de(n)},async getUserInfo(t){if(e.getUserInfo)return e.getUserInfo(t);let{data:r,error:o}=await(0,Oe.betterFetch)("https://oauth.reddit.com/api/v1/me",{headers:{Authorization:`Bearer ${t.accessToken}`,"User-Agent":"better-auth"}});if(o)return null;let i=await e.mapProfileToUser?.(r);return{user:{id:r.id,name:r.name,email:r.oauth_client_id,emailVerified:r.has_verified_email,image:r.icon_img?.split("?")[0],...i},data:r}}});var zt=require("zod"),Sr={apple:gt,discord:wt,facebook:yt,github:At,microsoft:Tt,google:Et,spotify:St,twitch:xt,twitter:Dt,dropbox:Nt,linkedin:$t,gitlab:Bt,reddit:Mt},Se=Object.keys(Sr),qt=zt.z.enum(Se,{description:"OAuth2 provider to use"});var C=require("zod");var X=require("better-call");var M=require("better-call");var W=require("zod");function Ft(e){try{return JSON.parse(e)}catch{return null}}var m={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",SOCIAL_ACCOUNT_ALREADY_LINKED:"Social account already linked",PROVIDER_NOT_FOUND:"Provider not found",INVALID_TOKEN:"invalid token",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",EMAIL_CAN_NOT_BE_UPDATED:"Email can not be updated",CREDENTIAL_ACCOUNT_NOT_FOUND:"Credential account not found",SESSION_EXPIRED:"Session expired. Re-authenticate to perform this action."};var Ht=require("@better-auth/utils/hmac"),Gt=require("@better-auth/utils/base64"),Wt=require("@better-auth/utils/binary"),le=()=>h("/get-session",{method:"GET",query:W.z.optional(W.z.object({disableCookieCache:W.z.boolean({description:"Disable cookie cache and fetch session from database"}).or(W.z.string().transform(e=>e==="true")).optional(),disableRefresh:W.z.boolean({description:"Disable session refresh. Useful for checking session status, without updating the session"}).optional()})),requireHeaders:!0,metadata:{openapi:{description:"Get the current session",responses:{200:{description:"Success",content:{"application/json":{schema:{type:"object",properties:{session:{type:"object",properties:{token:{type:"string"},userId:{type:"string"},expiresAt:{type:"string"}}},user:{type:"object",$ref:"#/components/schemas/User"}}}}}}}}}},async e=>{try{let t=await e.getSignedCookie(e.context.authCookies.sessionToken.name,e.context.secret);if(!t)return e.json(null);let r=e.getCookie(e.context.authCookies.sessionData.name),o=r?Ft(Wt.binary.decode(Gt.base64.decode(r))):null;if(o&&!await(0,Ht.createHMAC)("SHA-256","base64urlnopad").verify(e.context.secret,JSON.stringify(o.session),o.signature))return $(e),e.json(null);let i=await e.getSignedCookie(e.context.authCookies.dontRememberToken.name,e.context.secret);if(o?.session&&e.context.options.session?.cookieCache?.enabled&&!e.query?.disableCookieCache){let u=o.session;if(o.expiresAt<Date.now()||u.session.expiresAt<new Date){let f=e.context.authCookies.sessionData.name;e.setCookie(f,"",{maxAge:0})}else return e.json(u)}let n=await e.context.internalAdapter.findSession(t);if(e.context.session=n,!n||n.session.expiresAt<new Date)return $(e),n&&await e.context.internalAdapter.deleteSession(n.session.token),e.json(null);if(i||e.query?.disableRefresh)return e.json(n);let s=e.context.sessionConfig.expiresIn,d=e.context.sessionConfig.updateAge;if(n.session.expiresAt.valueOf()-s*1e3+d*1e3<=Date.now()){let u=await e.context.internalAdapter.updateSession(n.session.token,{expiresAt:H(e.context.sessionConfig.expiresIn,"sec")});if(!u)return $(e),e.json(null,{status:401});let b=(u.expiresAt.valueOf()-Date.now())/1e3;return await I(e,{session:u,user:n.user},!1,{maxAge:b}),e.json({session:u,user:n.user})}return await ke(e,n),e.json(n)}catch(t){throw e.context.logger.error("INTERNAL_SERVER_ERROR",t),new M.APIError("INTERNAL_SERVER_ERROR",{message:m.FAILED_TO_GET_SESSION})}}),Q=async(e,t)=>{if(e.context.session)return e.context.session;let r=await le()({...e,_flag:"json",headers:e.headers,query:t}).catch(o=>null);return e.context.session=r,r},L=J(async e=>{let t=await Q(e);if(!t?.session)throw new M.APIError("UNAUTHORIZED");return{session:t}}),vr=J(async e=>{let t=await Q(e);if(!t?.session)throw new M.APIError("UNAUTHORIZED");if(e.context.sessionConfig.freshAge===0)return{session:t};let r=e.context.sessionConfig.freshAge,o=t.session.updatedAt?.valueOf()||t.session.createdAt.valueOf();if(!(Date.now()-o<r*1e3))throw new M.APIError("FORBIDDEN",{message:"Session is not fresh"});return{session:t}}),ve=()=>h("/list-sessions",{method:"GET",use:[L],requireHeaders:!0,metadata:{openapi:{description:"List all active sessions for the user",responses:{200:{description:"Success",content:{"application/json":{schema:{type:"array",items:{type:"object",properties:{token:{type:"string"},userId:{type:"string"},expiresAt:{type:"string"}}}}}}}}}}},async e=>{let r=(await e.context.internalAdapter.listSessions(e.context.session.user.id)).filter(o=>o.expiresAt>new Date);return e.json(r)}),Ie=h("/revoke-session",{method:"POST",body:W.z.object({token:W.z.string({description:"The token to revoke"})}),use:[L],requireHeaders:!0,metadata:{openapi:{description:"Revoke a single session",requestBody:{content:{"application/json":{schema:{type:"object",properties:{token:{type:"string"}},required:["token"]}}}}}}},async e=>{let t=e.body.token,r=await e.context.internalAdapter.findSession(t);if(!r)throw new M.APIError("BAD_REQUEST",{message:"Session not found"});if(r.session.userId!==e.context.session.user.id)throw new M.APIError("UNAUTHORIZED");try{await e.context.internalAdapter.deleteSession(t)}catch(o){throw e.context.logger.error(o&&typeof o=="object"&&"name"in o?o.name:"",o),new M.APIError("INTERNAL_SERVER_ERROR")}return e.json({status:!0})}),Le=h("/revoke-sessions",{method:"POST",use:[L],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"}},required:["status"]}}}}}}}},async e=>{try{await e.context.internalAdapter.deleteSessions(e.context.session.user.id)}catch(t){throw e.context.logger.error(t&&typeof t=="object"&&"name"in t?t.name:"",t),new M.APIError("INTERNAL_SERVER_ERROR")}return e.json({status:!0})}),xe=h("/revoke-other-sessions",{method:"POST",requireHeaders:!0,use:[L],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"}}}}}}}}}},async e=>{let t=e.context.session;if(!t.user)throw new M.APIError("UNAUTHORIZED");let i=(await e.context.internalAdapter.listSessions(t.user.id)).filter(n=>n.expiresAt>new Date).filter(n=>n.token!==e.context.session.session.token);return await Promise.all(i.map(n=>e.context.internalAdapter.deleteSession(n.token))),e.json({status:!0})});var Kt=require("jose");var Qt=require("jose");async function Zt(e,t,r=3600){return await new Qt.SignJWT(e).setProtectedHeader({alg:"HS256"}).setIssuedAt().setExpirationTime(Math.floor(Date.now()/1e3)+r).sign(new TextEncoder().encode(t))}async function j(e,t,r){return await Zt({email:t.toLowerCase(),updateTo:r},e)}async function Jt(e,t){if(!e.context.options.emailVerification?.sendVerificationEmail)throw e.context.logger.error("Verification email isn't enabled."),new X.APIError("BAD_REQUEST",{message:"Verification email isn't enabled"});let r=await j(e.context.secret,t.email),o=`${e.context.baseURL}/verify-email?token=${r}&callbackURL=${e.body.callbackURL||e.query?.currentURL||"/"}`;await e.context.options.emailVerification.sendVerificationEmail({user:t,url:o,token:r},e.request)}var Pe=h("/send-verification-email",{method:"POST",query:C.z.object({currentURL:C.z.string({description:"The URL to use for email verification callback"}).optional()}).optional(),body:C.z.object({email:C.z.string({description:"The email to send the verification email to"}).email(),callbackURL:C.z.string({description:"The URL to use for email verification callback"}).optional()}),metadata:{openapi:{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"},callbackURL:{type:"string",description:"The URL to use for email verification callback"}},required:["email"]}}}},responses:{200:{description:"Success",content:{"application/json":{schema:{type:"object",properties:{status:{type:"boolean"}}}}}}}}}},async e=>{if(!e.context.options.emailVerification?.sendVerificationEmail)throw e.context.logger.error("Verification email isn't enabled."),new X.APIError("BAD_REQUEST",{message:"Verification email isn't enabled"});let{email:t}=e.body,r=await e.context.internalAdapter.findUserByEmail(t);if(!r)throw new X.APIError("BAD_REQUEST",{message:m.USER_NOT_FOUND});return await Jt(e,r.user),e.json({status:!0})}),De=h("/verify-email",{method:"GET",query:C.z.object({token:C.z.string({description:"The token to verify the email"}),callbackURL:C.z.string({description:"The URL to redirect to after email verification"}).optional()}),metadata:{openapi:{description:"Verify the email of the user",responses:{200:{description:"Success",content:{"application/json":{schema:{type:"object",properties:{user:{type:"object"},status:{type:"boolean"}},required:["user","status"]}}}}}}}},async e=>{function t(d){throw e.query.callbackURL?e.query.callbackURL.includes("?")?e.redirect(`${e.query.callbackURL}&error=${d}`):e.redirect(`${e.query.callbackURL}?error=${d}`):new X.APIError("UNAUTHORIZED",{message:d})}let{token:r}=e.query,o;try{o=await(0,Kt.jwtVerify)(r,new TextEncoder().encode(e.context.secret),{algorithms:["HS256"]})}catch(d){return e.context.logger.error("Failed to verify email",d),t("invalid_token")}let n=C.z.object({email:C.z.string().email(),updateTo:C.z.string().optional()}).parse(o.payload),s=await e.context.internalAdapter.findUserByEmail(n.email);if(!s)return t("user_not_found");if(n.updateTo){let d=await Q(e);if(!d){if(e.query.callbackURL)throw e.redirect(`${e.query.callbackURL}?error=unauthorized`);return t("unauthorized")}if(d.user.email!==n.email){if(e.query.callbackURL)throw e.redirect(`${e.query.callbackURL}?error=unauthorized`);return t("unauthorized")}let a=await e.context.internalAdapter.updateUserByEmail(n.email,{email:n.updateTo,emailVerified:!1}),c=await j(e.context.secret,n.updateTo);if(await e.context.options.emailVerification?.sendVerificationEmail?.({user:a,url:`${e.context.baseURL}/verify-email?token=${c}`,token:c},e.request),e.query.callbackURL)throw e.redirect(e.query.callbackURL);return e.json({status:!0})}if(await e.context.internalAdapter.updateUserByEmail(n.email,{emailVerified:!0}),e.context.options.emailVerification?.autoSignInAfterVerification&&!await Q(e)){let a=await e.context.internalAdapter.createSession(s.user.id,e.request);if(!a)throw new X.APIError("INTERNAL_SERVER_ERROR",{message:"Failed to create session"});await I(e,{session:a,user:s.user})}if(e.query.callbackURL)throw e.redirect(e.query.callbackURL);return e.json({status:!0})});async function ue(e,{userInfo:t,account:r,callbackURL:o}){let i=await e.context.internalAdapter.findOAuthUser(t.email.toLowerCase(),r.accountId,r.providerId).catch(a=>{throw D.error(`Better auth was unable to query your database.
3
- Error: `,a),e.redirect(`${e.context.baseURL}/error?error=internal_server_error`)}),n=i?.user,s=!n;if(i){let a=i.accounts.find(c=>c.providerId===r.providerId);if(a){let c=Object.fromEntries(Object.entries({accessToken:r.accessToken,idToken:r.idToken,refreshToken:r.refreshToken,accessTokenExpiresAt:r.accessTokenExpiresAt,refreshTokenExpiresAt:r.refreshTokenExpiresAt}).filter(([u,b])=>b!==void 0));Object.keys(c).length>0&&await e.context.internalAdapter.updateAccount(a.id,c)}else{if(!e.context.options.account?.accountLinking?.trustedProviders?.includes(r.providerId)&&!t.emailVerified||e.context.options.account?.accountLinking?.enabled===!1)return ae&&D.warn(`User already exist but account isn't linked to ${r.providerId}. To read more about how account linking works in Better Auth see https://www.better-auth.com/docs/concepts/users-accounts#account-linking.`),{error:"account not linked",data:null};try{await e.context.internalAdapter.linkAccount({providerId:r.providerId,accountId:t.id.toString(),userId:i.user.id,accessToken:r.accessToken,idToken:r.idToken,refreshToken:r.refreshToken,accessTokenExpiresAt:r.accessTokenExpiresAt,refreshTokenExpiresAt:r.refreshTokenExpiresAt,scope:r.scope})}catch(b){return D.error("Unable to link account",b),{error:"unable to link account",data:null}}}}else try{if(n=await e.context.internalAdapter.createOAuthUser({...t,email:t.email.toLowerCase(),id:void 0},{accessToken:r.accessToken,idToken:r.idToken,refreshToken:r.refreshToken,accessTokenExpiresAt:r.accessTokenExpiresAt,refreshTokenExpiresAt:r.refreshTokenExpiresAt,scope:r.scope,providerId:r.providerId,accountId:t.id.toString()}).then(a=>a?.user),!t.emailVerified&&n&&e.context.options.emailVerification?.sendOnSignUp){let a=await j(e.context.secret,n.email),c=`${e.context.baseURL}/verify-email?token=${a}&callbackURL=${o}`;await e.context.options.emailVerification?.sendVerificationEmail?.({user:n,url:c,token:a},e.request)}}catch(a){return a instanceof pe.APIError?{error:a.message,data:null,isRegister:!1}:{error:"unable to create user",data:null,isRegister:!1}}if(!n)return{error:"unable to create user",data:null,isRegister:!1};let d=await e.context.internalAdapter.createSession(n.id,e.request);return d?{data:{session:d,user:n},error:null,isRegister:s}:{error:"unable to create session",data:null,isRegister:!1}}var Ce=h("/sign-in/social",{method:"POST",query:_.z.object({currentURL:_.z.string().optional()}).optional(),body:_.z.object({callbackURL:_.z.string({description:"Callback URL to redirect to after the user has signed in"}).optional(),newUserCallbackURL:_.z.string().optional(),errorCallbackURL:_.z.string({description:"Callback URL to redirect to if an error happens"}).optional(),provider:qt,disableRedirect:_.z.boolean({description:"Disable automatic redirection to the provider. Useful for handling the redirection yourself"}).optional(),idToken:_.z.optional(_.z.object({token:_.z.string({description:"ID token from the provider"}),nonce:_.z.string({description:"Nonce used to generate the token"}).optional(),accessToken:_.z.string({description:"Access token from the provider"}).optional(),refreshToken:_.z.string({description:"Refresh token from the provider"}).optional(),expiresAt:_.z.number({description:"Expiry date of the token"}).optional()}),{description:"ID token from the provider to sign in the user with id token"})}),metadata:{openapi:{description:"Sign in with a social provider",responses:{200:{description:"Success",content:{"application/json":{schema:{type:"object",properties:{session:{type:"string"},user:{type:"object"},url:{type:"string"},redirect:{type:"boolean"}},required:["session","user","url","redirect"]}}}}}}}},async e=>{let t=e.context.socialProviders.find(n=>n.id===e.body.provider);if(!t)throw e.context.logger.error("Provider not found. Make sure to add the provider in your auth config",{provider:e.body.provider}),new v.APIError("NOT_FOUND",{message:m.PROVIDER_NOT_FOUND});if(e.body.idToken){if(!t.verifyIdToken)throw e.context.logger.error("Provider does not support id token verification",{provider:e.body.provider}),new v.APIError("NOT_FOUND",{message:m.ID_TOKEN_NOT_SUPPORTED});let{token:n,nonce:s}=e.body.idToken;if(!await t.verifyIdToken(n,s))throw e.context.logger.error("Invalid id token",{provider:e.body.provider}),new v.APIError("UNAUTHORIZED",{message:m.INVALID_TOKEN});let a=await t.getUserInfo({idToken:n,accessToken:e.body.idToken.accessToken,refreshToken:e.body.idToken.refreshToken});if(!a||!a?.user)throw e.context.logger.error("Failed to get user info",{provider:e.body.provider}),new v.APIError("UNAUTHORIZED",{message:m.FAILED_TO_GET_USER_INFO});if(!a.user.email)throw e.context.logger.error("User email not found",{provider:e.body.provider}),new v.APIError("UNAUTHORIZED",{message:m.USER_EMAIL_NOT_FOUND});let c=await ue(e,{userInfo:{email:a.user.email,id:a.user.id,name:a.user.name||"",image:a.user.image,emailVerified:a.user.emailVerified||!1},account:{providerId:t.id,accountId:a.user.id,accessToken:e.body.idToken.accessToken}});if(c.error)throw new v.APIError("UNAUTHORIZED",{message:c.error});return await I(e,c.data),e.json({token:c.data.session.token,url:void 0,redirect:!1})}let{codeVerifier:r,state:o}=await ce(e),i=await t.createAuthorizationURL({state:o,codeVerifier:r,redirectURI:`${e.context.baseURL}/callback/${t.id}`});return e.json({url:i.toString(),redirect:!e.body.disableRedirect})}),Ne=h("/sign-in/email",{method:"POST",body:_.z.object({email:_.z.string({description:"Email of the user"}),password:_.z.string({description:"Password of the user"}),callbackURL:_.z.string({description:"Callback URL to use as a redirect for email verification"}).optional(),rememberMe:_.z.boolean({description:"If this is false, the session will not be remembered. Default is `true`."}).default(!0).optional()}),metadata:{openapi:{description:"Sign in with email and password",responses:{200:{description:"Success",content:{"application/json":{schema:{type:"object",properties:{user:{type:"object"},url:{type:"string"},redirect:{type:"boolean"}},required:["session","user","url","redirect"]}}}}}}}},async e=>{if(!e.context.options?.emailAndPassword?.enabled)throw e.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!"),new v.APIError("BAD_REQUEST",{message:"Email and password is not enabled"});let{email:t,password:r}=e.body;if(!_.z.string().email().safeParse(t).success)throw new v.APIError("BAD_REQUEST",{message:m.INVALID_EMAIL});let i=await e.context.internalAdapter.findUserByEmail(t,{includeAccounts:!0});if(!i)throw await e.context.password.hash(r),e.context.logger.error("User not found",{email:t}),new v.APIError("UNAUTHORIZED",{message:m.INVALID_EMAIL_OR_PASSWORD});let n=i.accounts.find(c=>c.providerId==="credential");if(!n)throw e.context.logger.error("Credential account not found",{email:t}),new v.APIError("UNAUTHORIZED",{message:m.INVALID_EMAIL_OR_PASSWORD});let s=n?.password;if(!s)throw e.context.logger.error("Password not found",{email:t}),new v.APIError("UNAUTHORIZED",{message:m.INVALID_EMAIL_OR_PASSWORD});if(!await e.context.password.verify({hash:s,password:r}))throw e.context.logger.error("Invalid password"),new v.APIError("UNAUTHORIZED",{message:m.INVALID_EMAIL_OR_PASSWORD});if(e.context.options?.emailAndPassword?.requireEmailVerification&&!i.user.emailVerified){if(!e.context.options?.emailVerification?.sendVerificationEmail)throw new v.APIError("UNAUTHORIZED",{message:m.EMAIL_NOT_VERIFIED});let c=await j(e.context.secret,i.user.email),u=`${e.context.baseURL}/verify-email?token=${c}&callbackURL=${e.body.callbackURL||"/"}`;throw await e.context.options.emailVerification.sendVerificationEmail({user:i.user,url:u,token:c},e.request),e.context.logger.error("Email not verified",{email:t}),new v.APIError("FORBIDDEN",{message:m.EMAIL_NOT_VERIFIED})}let a=await e.context.internalAdapter.createSession(i.user.id,e.headers,e.body.rememberMe===!1);if(!a)throw e.context.logger.error("Failed to create session"),new v.APIError("UNAUTHORIZED",{message:m.FAILED_TO_CREATE_SESSION});return await I(e,{session:a,user:i.user},e.body.rememberMe===!1),e.json({user:{id:i.user.id,email:i.user.email,name:i.user.name,image:i.user.image,emailVerified:i.user.emailVerified,createdAt:i.user.createdAt,updatedAt:i.user.updatedAt},redirect:!!e.body.callbackURL,url:e.body.callbackURL})});var ee=require("zod");var me=ee.z.object({code:ee.z.string().optional(),error:ee.z.string().optional(),error_description:ee.z.string().optional(),state:ee.z.string().optional()}),je=h("/callback/:id",{method:["GET","POST"],body:me.optional(),query:me.optional(),metadata:Y},async e=>{let t;try{if(e.method==="GET")t=me.parse(e.query);else if(e.method==="POST")t=me.parse(e.body);else throw new Error("Unsupported method")}catch(p){throw e.context.logger.error("INVALID_CALLBACK_REQUEST",p),e.redirect(`${e.context.baseURL}/error?error=invalid_callback_request`)}let{code:r,error:o,state:i,error_description:n}=t;if(!i)throw e.context.logger.error("State not found",o),e.redirect(`${e.context.baseURL}/error?error=state_not_found`);if(!r)throw e.context.logger.error("Code not found"),e.redirect(`${e.context.baseURL}/error?error=${o||"no_code"}&error_description=${n}`);let s=e.context.socialProviders.find(p=>p.id===e.params.id);if(!s)throw e.context.logger.error("Oauth provider with id",e.params.id,"not found"),e.redirect(`${e.context.baseURL}/error?error=oauth_provider_not_found`);let{codeVerifier:d,callbackURL:a,link:c,errorURL:u,newUserURL:b}=await pt(e),f;try{f=await s.validateAuthorizationCode({code:r,codeVerifier:d,redirectURI:`${e.context.baseURL}/callback/${s.id}`})}catch(p){throw e.context.logger.error("",p),e.redirect(`${e.context.baseURL}/error?error=please_restart_the_process`)}let l=await s.getUserInfo(f).then(p=>p?.user);function y(p){let w=u||a||`${e.context.baseURL}/error`;throw w.includes("?")?w=`${w}&error=${p}`:w=`${w}?error=${p}`,e.redirect(w)}if(!l)return e.context.logger.error("Unable to get user info"),y("unable_to_get_user_info");if(!l.email)return e.context.logger.error("Provider did not return email. This could be due to misconfiguration in the provider settings."),y("email_not_found");if(!a)throw e.context.logger.error("No callback URL found"),e.redirect(`${e.context.baseURL}/error?error=please_restart_the_process`);if(c){if(c.email!==l.email.toLowerCase())return y("email_doesn't_match");if(!await e.context.internalAdapter.createAccount({userId:c.userId,providerId:s.id,accountId:l.id}))return y("unable_to_link_account");let w;try{w=a.toString()}catch{w=a}throw e.redirect(w)}let U=await ue(e,{userInfo:{...l,email:l.email,name:l.name||l.email},account:{providerId:s.id,accountId:l.id,...f,scope:f.scopes?.join(",")},callbackURL:a});if(U.error)return e.context.logger.error(U.error.split(" ").join("_")),y(U.error.split(" ").join("_"));let{session:x,user:q}=U.data;await I(e,{session:x,user:q});let N;try{N=(U.isRegister&&b||a).toString()}catch{N=U.isRegister&&b||a}throw e.redirect(N)});var Dn=require("zod");var Yt=require("better-call");var $e=h("/sign-out",{method:"POST",requireHeaders:!0,metadata:{openapi:{description:"Sign out the current user",responses:{200:{description:"Success",content:{"application/json":{schema:{type:"object",properties:{success:{type:"boolean"}}}}}}}}}},async e=>{let t=await e.getSignedCookie(e.context.authCookies.sessionToken.name,e.context.secret);if(!t)throw $(e),new Yt.APIError("BAD_REQUEST",{message:m.FAILED_TO_GET_SESSION});return await e.context.internalAdapter.deleteSession(t),$(e),e.json({success:!0})});var P=require("zod");var te=require("better-call");function Xt(e,t,r){let o=t?new URL(t,e.baseURL):new URL(`${e.baseURL}/error`);return r&&Object.entries(r).forEach(([i,n])=>o.searchParams.set(i,n)),o.href}function Ir(e,t,r){let o=new URL(t,e.baseURL);return r&&Object.entries(r).forEach(([i,n])=>o.searchParams.set(i,n)),o.href}var Ve=h("/forget-password",{method:"POST",body:P.z.object({email:P.z.string({description:"The email address of the user to send a password reset email to"}).email(),redirectTo:P.z.string({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:{description:"Send a password reset email to the user",responses:{200:{description:"Success",content:{"application/json":{schema:{type:"object",properties:{status:{type:"boolean"}}}}}}}}}},async e=>{if(!e.context.options.emailAndPassword?.sendResetPassword)throw e.context.logger.error("Reset password isn't enabled.Please pass an emailAndPassword.sendResetPasswordToken function in your auth config!"),new te.APIError("BAD_REQUEST",{message:"Reset password isn't enabled"});let{email:t,redirectTo:r}=e.body,o=await e.context.internalAdapter.findUserByEmail(t,{includeAccounts:!0});if(!o)return e.context.logger.error("Reset Password: User not found",{email:t}),e.json({status:!1},{body:{status:!0}});let i=60*60*1,n=H(e.context.options.emailAndPassword.resetPasswordTokenExpiresIn||i,"sec"),s=It(24);await e.context.internalAdapter.createVerificationValue({value:o.user.id.toString(),identifier:`reset-password:${s}`,expiresAt:n});let d=`${e.context.baseURL}/reset-password/${s}?callbackURL=${r}`;return await e.context.options.emailAndPassword.sendResetPassword({user:o.user,url:d,token:s},e.request),e.json({status:!0})}),Be=h("/reset-password/:token",{method:"GET",query:P.z.object({callbackURL:P.z.string({description:"The URL to redirect the user to reset their password"})}),metadata:{openapi:{description:"Redirects the user to the callback URL with the token",responses:{200:{description:"Success",content:{"application/json":{schema:{type:"object",properties:{token:{type:"string"}}}}}}}}}},async e=>{let{token:t}=e.params,{callbackURL:r}=e.query;if(!t||!r)throw e.redirect(Xt(e.context,r,{error:"INVALID_TOKEN"}));let o=await e.context.internalAdapter.findVerificationValue(`reset-password:${t}`);throw!o||o.expiresAt<new Date?e.redirect(Xt(e.context,r,{error:"INVALID_TOKEN"})):e.redirect(Ir(e.context,r,{token:t}))}),Me=h("/reset-password",{query:P.z.optional(P.z.object({token:P.z.string().optional(),currentURL:P.z.string().optional()})),method:"POST",body:P.z.object({newPassword:P.z.string({description:"The new password to set"}),token:P.z.string({description:"The token to reset the password"}).optional()}),metadata:{openapi:{description:"Reset the password for a user",responses:{200:{description:"Success",content:{"application/json":{schema:{type:"object",properties:{status:{type:"boolean"}}}}}}}}}},async e=>{let t=e.body.token||e.query?.token||(e.query?.currentURL?new URL(e.query.currentURL).searchParams.get("token"):"");if(!t)throw new te.APIError("BAD_REQUEST",{message:m.INVALID_TOKEN});let{newPassword:r}=e.body,o=e.context.password?.config.minPasswordLength,i=e.context.password?.config.maxPasswordLength;if(r.length<o)throw new te.APIError("BAD_REQUEST",{message:m.PASSWORD_TOO_SHORT});if(r.length>i)throw new te.APIError("BAD_REQUEST",{message:m.PASSWORD_TOO_LONG});let n=`reset-password:${t}`,s=await e.context.internalAdapter.findVerificationValue(n);if(!s||s.expiresAt<new Date)throw new te.APIError("BAD_REQUEST",{message:m.INVALID_TOKEN});await e.context.internalAdapter.deleteVerificationValue(s.id);let d=s.value,a=await e.context.password.hash(r);return(await e.context.internalAdapter.findAccounts(d)).find(b=>b.providerId==="credential")?(await e.context.internalAdapter.updatePassword(d,a),e.json({status:!0})):(await e.context.internalAdapter.createAccount({userId:d,providerId:"credential",password:a,accountId:d}),e.json({status:!0}))});var R=require("zod");var E=require("better-call");var g=require("zod"),er=require("better-call"),Hn=g.z.object({id:g.z.string(),providerId:g.z.string(),accountId:g.z.string(),userId:g.z.string(),accessToken:g.z.string().nullish(),refreshToken:g.z.string().nullish(),idToken:g.z.string().nullish(),accessTokenExpiresAt:g.z.date().nullish(),refreshTokenExpiresAt:g.z.date().nullish(),scope:g.z.string().nullish(),password:g.z.string().nullish(),createdAt:g.z.date().default(()=>new Date),updatedAt:g.z.date().default(()=>new Date)}),Gn=g.z.object({id:g.z.string(),email:g.z.string().transform(e=>e.toLowerCase()),emailVerified:g.z.boolean().default(!1),name:g.z.string(),image:g.z.string().nullish(),createdAt:g.z.date().default(()=>new Date),updatedAt:g.z.date().default(()=>new Date)}),Wn=g.z.object({id:g.z.string(),userId:g.z.string(),expiresAt:g.z.date(),createdAt:g.z.date().default(()=>new Date),updatedAt:g.z.date().default(()=>new Date),token:g.z.string(),ipAddress:g.z.string().nullish(),userAgent:g.z.string().nullish()}),Qn=g.z.object({id:g.z.string(),value:g.z.string(),createdAt:g.z.date().default(()=>new Date),updatedAt:g.z.date().default(()=>new Date),expiresAt:g.z.date(),identifier:g.z.string()});function Lr(e,t){let r={...t==="user"?e.user?.additionalFields:{},...t==="session"?e.session?.additionalFields:{}};for(let o of e.plugins||[])o.schema&&o.schema[t]&&(r={...r,...o.schema[t].fields});return r}function xr(e,t){let r=t.action||"create",o=t.fields,i={};for(let n in o){if(n in e){if(o[n].input===!1){if(o[n].defaultValue){i[n]=o[n].defaultValue;continue}continue}if(o[n].validator?.input&&e[n]!==void 0){i[n]=o[n].validator.input.parse(e[n]);continue}if(o[n].transform?.input&&e[n]!==void 0){i[n]=o[n].transform?.input(e[n]);continue}i[n]=e[n];continue}if(o[n].defaultValue&&r==="create"){i[n]=o[n].defaultValue;continue}if(o[n].required&&r==="create")throw new er.APIError("BAD_REQUEST",{message:`${n} is required`})}return i}function fe(e,t,r){let o=Lr(e,"user");return xr(t||{},{fields:o,action:r})}var ze=()=>h("/update-user",{method:"POST",body:R.z.record(R.z.string(),R.z.any()),use:[L],metadata:{openapi:{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"}}}}}},responses:{200:{description:"Success",content:{"application/json":{schema:{type:"object",properties:{user:{type:"object"}}}}}}}}}},async e=>{let t=e.body;if(t.email)throw new E.APIError("BAD_REQUEST",{message:m.EMAIL_CAN_NOT_BE_UPDATED});let{name:r,image:o,...i}=t,n=e.context.session;if(o===void 0&&r===void 0&&Object.keys(i).length===0)return e.json({status:!0});let s=fe(e.context.options,i,"update"),d=await e.context.internalAdapter.updateUserByEmail(n.user.email,{name:r,image:o,...s});return await I(e,{session:n.session,user:d}),e.json({status:!0})}),qe=h("/change-password",{method:"POST",body:R.z.object({newPassword:R.z.string({description:"The new password to set"}),currentPassword:R.z.string({description:"The current password"}),revokeOtherSessions:R.z.boolean({description:"Revoke all other sessions"}).optional()}),use:[L],metadata:{openapi:{description:"Change the password of the user",responses:{200:{description:"Success",content:{"application/json":{schema:{type:"object",properties:{user:{description:"The user object",$ref:"#/components/schemas/User"}}}}}}}}}},async e=>{let{newPassword:t,currentPassword:r,revokeOtherSessions:o}=e.body,i=e.context.session,n=e.context.password.config.minPasswordLength;if(t.length<n)throw e.context.logger.error("Password is too short"),new E.APIError("BAD_REQUEST",{message:m.PASSWORD_TOO_SHORT});let s=e.context.password.config.maxPasswordLength;if(t.length>s)throw e.context.logger.error("Password is too long"),new E.APIError("BAD_REQUEST",{message:m.PASSWORD_TOO_LONG});let a=(await e.context.internalAdapter.findAccounts(i.user.id)).find(f=>f.providerId==="credential"&&f.password);if(!a||!a.password)throw new E.APIError("BAD_REQUEST",{message:m.CREDENTIAL_ACCOUNT_NOT_FOUND});let c=await e.context.password.hash(t);if(!await e.context.password.verify({hash:a.password,password:r}))throw new E.APIError("BAD_REQUEST",{message:m.INVALID_PASSWORD});await e.context.internalAdapter.updateAccount(a.id,{password:c});let b=null;if(o){await e.context.internalAdapter.deleteSessions(i.user.id);let f=await e.context.internalAdapter.createSession(i.user.id,e.headers);if(!f)throw new E.APIError("INTERNAL_SERVER_ERROR",{message:m.FAILED_TO_GET_SESSION});await I(e,{session:f,user:i.user}),b=f.token}return e.json({token:b})}),Fe=h("/set-password",{method:"POST",body:R.z.object({newPassword:R.z.string()}),metadata:{SERVER_ONLY:!0},use:[L]},async e=>{let{newPassword:t}=e.body,r=e.context.session,o=e.context.password.config.minPasswordLength;if(t.length<o)throw e.context.logger.error("Password is too short"),new E.APIError("BAD_REQUEST",{message:m.PASSWORD_TOO_SHORT});let i=e.context.password.config.maxPasswordLength;if(t.length>i)throw e.context.logger.error("Password is too long"),new E.APIError("BAD_REQUEST",{message:m.PASSWORD_TOO_LONG});let s=(await e.context.internalAdapter.findAccounts(r.user.id)).find(a=>a.providerId==="credential"&&a.password),d=await e.context.password.hash(t);if(!s)return await e.context.internalAdapter.linkAccount({userId:r.user.id,providerId:"credential",accountId:r.user.id,password:d}),e.json({status:!0});throw new E.APIError("BAD_REQUEST",{message:"user already has a password"})}),He=h("/delete-user",{method:"POST",use:[L],body:R.z.object({callbackURL:R.z.string().optional(),password:R.z.string().optional(),token:R.z.string().optional()}),metadata:{openapi:{description:"Delete the user",responses:{200:{description:"Success",content:{"application/json":{schema:{type:"object"}}}}}}}},async e=>{if(!e.context.options.user?.deleteUser?.enabled)throw e.context.logger.error("Delete user is disabled. Enable it in the options",{session:e.context.session}),new E.APIError("NOT_FOUND");let t=e.context.session;if(e.body.password){let n=(await e.context.internalAdapter.findAccounts(t.user.id)).find(d=>d.providerId==="credential"&&d.password);if(!n||!n.password)throw new E.APIError("BAD_REQUEST",{message:m.CREDENTIAL_ACCOUNT_NOT_FOUND});if(!await e.context.password.verify({hash:n.password,password:e.body.password}))throw new E.APIError("BAD_REQUEST",{message:m.INVALID_PASSWORD})}else if(e.context.options.session?.freshAge){let i=t.session.createdAt.getTime(),n=e.context.options.session.freshAge;if(Date.now()-i>n)throw new E.APIError("BAD_REQUEST",{message:m.SESSION_EXPIRED})}if(e.body.token)return await ge({...e,query:{token:e.body.token}}),e.json({success:!0,message:"User deleted"});if(e.context.options.user.deleteUser?.sendDeleteAccountVerification){let i=ie(32,"0-9","a-z");await e.context.internalAdapter.createVerificationValue({value:t.user.id,identifier:`delete-account-${i}`,expiresAt:new Date(Date.now()+1e3*60*60*24)});let n=`${e.context.baseURL}/delete-user/callback?token=${i}&callbackURL=${e.body.callbackURL||"/"}`;return await e.context.options.user.deleteUser.sendDeleteAccountVerification({user:t.user,url:n,token:i},e.request),e.json({success:!0,message:"Verification email sent"})}let r=e.context.options.user.deleteUser?.beforeDelete;r&&await r(t.user,e.request),await e.context.internalAdapter.deleteUser(t.user.id),await e.context.internalAdapter.deleteSessions(t.user.id),await e.context.internalAdapter.deleteAccounts(t.user.id),$(e);let o=e.context.options.user.deleteUser?.afterDelete;return o&&await o(t.user,e.request),e.json({success:!0,message:"User deleted"})}),ge=h("/delete-user/callback",{method:"GET",query:R.z.object({token:R.z.string(),callbackURL:R.z.string().optional()})},async e=>{if(!e.context.options.user?.deleteUser?.enabled)throw e.context.logger.error("Delete user is disabled. Enable it in the options"),new E.APIError("NOT_FOUND");let t=await Q(e);if(!t)throw new E.APIError("NOT_FOUND",{message:m.FAILED_TO_GET_USER_INFO});let r=await e.context.internalAdapter.findVerificationValue(`delete-account-${e.query.token}`);if(!r||r.expiresAt<new Date)throw r&&await e.context.internalAdapter.deleteVerificationValue(r.id),new E.APIError("NOT_FOUND",{message:m.INVALID_TOKEN});if(r.value!==t.user.id)throw new E.APIError("NOT_FOUND",{message:m.INVALID_TOKEN});let o=e.context.options.user.deleteUser?.beforeDelete;o&&await o(t.user,e.request),await e.context.internalAdapter.deleteUser(t.user.id),await e.context.internalAdapter.deleteSessions(t.user.id),await e.context.internalAdapter.deleteAccounts(t.user.id),await e.context.internalAdapter.deleteVerificationValue(r.id),$(e);let i=e.context.options.user.deleteUser?.afterDelete;if(i&&await i(t.user,e.request),e.query.callbackURL)throw e.redirect(e.query.callbackURL||"/");return e.json({success:!0,message:"User deleted"})}),Ge=h("/change-email",{method:"POST",query:R.z.object({currentURL:R.z.string().optional()}).optional(),body:R.z.object({newEmail:R.z.string({description:"The new email to set"}).email(),callbackURL:R.z.string({description:"The URL to redirect to after email verification"}).optional()}),use:[L],metadata:{openapi:{responses:{200:{description:"Success",content:{"application/json":{schema:{type:"object",properties:{user:{type:"object"},status:{type:"boolean"}}}}}}}}}},async e=>{if(!e.context.options.user?.changeEmail?.enabled)throw e.context.logger.error("Change email is disabled."),new E.APIError("BAD_REQUEST",{message:"Change email is disabled"});if(e.body.newEmail===e.context.session.user.email)throw e.context.logger.error("Email is the same"),new E.APIError("BAD_REQUEST",{message:"Email is the same"});if(await e.context.internalAdapter.findUserByEmail(e.body.newEmail))throw e.context.logger.error("Email already exists"),new E.APIError("BAD_REQUEST",{message:"Couldn't update your email"});if(e.context.session.user.emailVerified!==!0){let i=await e.context.internalAdapter.updateUserByEmail(e.context.session.user.email,{email:e.body.newEmail});return e.json({status:!0})}if(!e.context.options.user.changeEmail.sendChangeEmailVerification)throw e.context.logger.error("Verification email isn't enabled."),new E.APIError("BAD_REQUEST",{message:"Verification email isn't enabled"});let r=await j(e.context.secret,e.context.session.user.email,e.body.newEmail),o=`${e.context.baseURL}/verify-email?token=${r}&callbackURL=${e.body.callbackURL||e.query?.currentURL||"/"}`;return await e.context.options.user.changeEmail.sendChangeEmailVerification({user:e.context.session.user,newEmail:e.body.newEmail,url:o,token:r},e.request),e.json({status:!0})});var Pr=(e="Unknown")=>`<!DOCTYPE html>
1
+ "use strict";var _e=Object.defineProperty;var pr=Object.getOwnPropertyDescriptor;var mr=Object.getOwnPropertyNames;var fr=Object.prototype.hasOwnProperty;var gr=(e,t)=>{for(var r in t)_e(e,r,{get:t[r],enumerable:!0})},hr=(e,t,r,o)=>{if(t&&typeof t=="object"||typeof t=="function")for(let n of mr(t))!fr.call(e,n)&&n!==r&&_e(e,n,{get:()=>t[n],enumerable:!(o=pr(t,n))||o.enumerable});return e};var wr=e=>hr(_e({},"__esModule",{value:!0}),e);var fo={};gr(fo,{APIError:()=>Ae.APIError,callbackOAuth:()=>Fe,changeEmail:()=>Xe,changePassword:()=>Je,createAuthEndpoint:()=>A,createAuthMiddleware:()=>ne,createEmailVerificationToken:()=>V,deleteUser:()=>Ye,deleteUserCallback:()=>Ee,error:()=>et,forgetPassword:()=>Ge,forgetPasswordCallback:()=>We,freshSessionMiddleware:()=>to,getEndpoints:()=>cr,getSession:()=>ye,getSessionFromCtx:()=>X,linkSocialAccount:()=>it,listSessions:()=>je,listUserAccounts:()=>nt,ok:()=>tt,optionsMiddleware:()=>Te,originCheckMiddleware:()=>Oe,resetPassword:()=>Qe,revokeOtherSessions:()=>Be,revokeSession:()=>Ne,revokeSessions:()=>$e,router:()=>mo,sendVerificationEmail:()=>Ve,sendVerificationEmailFn:()=>tr,sessionMiddleware:()=>D,setPassword:()=>Ke,signInEmail:()=>ze,signInSocial:()=>qe,signOut:()=>He,signUpEmail:()=>rt,updateUser:()=>Ze,verifyEmail:()=>Me});module.exports=wr(fo);var O=require("better-call");var pt=require("better-call");var ee=require("better-call"),Te=(0,ee.createMiddleware)(async()=>({})),ne=(0,ee.createMiddlewareCreator)({use:[Te,(0,ee.createMiddleware)(async()=>({}))]}),A=(0,ee.createEndpointCreator)({use:[Te]});function ve(e){return e==="-"||e==="^"||e==="$"||e==="+"||e==="."||e==="("||e===")"||e==="|"||e==="["||e==="]"||e==="{"||e==="}"||e==="*"||e==="?"||e==="\\"?`\\${e}`:e}function yr(e){let t="";for(let r=0;r<e.length;r++)t+=ve(e[r]);return t}function at(e,t=!0){if(Array.isArray(e))return`(?:${e.map(u=>`^${at(u,t)}$`).join("|")})`;let r="",o="",n=".";t===!0?(r="/",o="[/\\\\]",n="[^/\\\\]"):t&&(r=t,o=yr(r),o.length>1?(o=`(?:${o})`,n=`((?!${o}).)`):n=`[^${o}]`);let i=t?`${o}+?`:"",s=t?`${o}*?`:"",c=t?e.split(r):[e],a="";for(let d=0;d<c.length;d++){let u=c[d],h=c[d+1],p="";if(!(!u&&d>0)){if(t&&(d===c.length-1?p=s:h!=="**"?p=i:p=""),t&&u==="**"){p&&(a+=d===0?"":p,a+=`(?:${n}*?${p})*?`);continue}for(let l=0;l<u.length;l++){let b=u[l];b==="\\"?l<u.length-1&&(a+=ve(u[l+1]),l++):b==="?"?a+=n:b==="*"?a+=`${n}*?`:a+=ve(b)}a+=p}}return a}function br(e,t){if(typeof t!="string")throw new TypeError(`Sample must be a string, but ${typeof t} given`);return e.test(t)}function me(e,t){if(typeof e!="string"&&!Array.isArray(e))throw new TypeError(`The first argument must be a single pattern string or an array of patterns, but ${typeof e} given`);if((typeof t=="string"||typeof t=="boolean")&&(t={separator:t}),arguments.length===2&&!(typeof t>"u"||typeof t=="object"&&t!==null&&!Array.isArray(t)))throw new TypeError(`The second argument must be an options object or a string/boolean separator, but ${typeof t} given`);if(t=t||{},t.separator==="\\")throw new Error("\\ is not a valid separator because it is used for escaping. Try setting the separator to `true` instead");let r=at(e,t.separator),o=new RegExp(`^${r}$`,t.flags),n=br.bind(null,o);return n.options=t,n.pattern=e,n.regexp=o,n}var fe=Object.create(null),le=e=>globalThis.process?.env||globalThis.Deno?.env.toObject()||globalThis.__env__||(e?fe:globalThis),ct=new Proxy(fe,{get(e,t){return le()[t]??fe[t]},has(e,t){let r=le();return t in r||t in fe},set(e,t,r){let o=le(!0);return o[t]=r,!0},deleteProperty(e,t){if(!t)return!1;let r=le(!0);return delete r[t],!0},ownKeys(){let e=le(!0);return Object.keys(e)}});function Ar(e){return e?e!=="false":!1}var Se=typeof process<"u"&&process.env&&process.env.NODE_ENV||"";var ge=Se==="dev"||Se==="development",dt=Se==="test"||Ar(ct.TEST);var Z=class extends Error{constructor(t,r){super(t),this.name="BetterAuthError",this.message=t,this.cause=r,this.stack=""}};function lt(e){try{return new URL(e).origin}catch{return null}}function ut(e){return e.includes("://")?new URL(e).host:e}var Oe=ne(async e=>{if(e.request?.method!=="POST")return;let{body:t,query:r,context:o}=e,n=e.headers?.get("origin")||e.headers?.get("referer")||"",i=t?.callbackURL||r?.callbackURL,s=t?.redirectTo,c=r?.currentURL,a=t?.errorCallbackURL,d=t?.newUserCallbackURL,u=o.trustedOrigins,h=e.headers?.has("cookie"),p=(b,E)=>b.startsWith("/")?!1:E.includes("*")?me(E)(ut(b)):b.startsWith(E),l=(b,E)=>{if(!b)return;if(!u.some(M=>p(b,M)||b?.startsWith("/")&&E!=="origin"&&!b.includes(":")))throw e.context.logger.error(`Invalid ${E}: ${b}`),e.context.logger.info(`If it's a valid URL, please add ${b} to trustedOrigins in your auth config
2
+ `,`Current list of trustedOrigins: ${u}`),new pt.APIError("FORBIDDEN",{message:`Invalid ${E}`})};h&&!e.context.options.advanced?.disableCSRFCheck&&l(n,"origin"),i&&l(i,"callbackURL"),s&&l(s,"redirectURL"),c&&l(c,"currentURL"),a&&l(a,"errorCallbackURL"),d&&l(s,"newUserCallbackURL")});var x=require("better-call"),v=require("zod");var J=(e,t="ms")=>new Date(Date.now()+(t==="sec"?e*1e3:e));var mt=require("@better-auth/utils/base64");var ft=require("@better-auth/utils/hmac");async function xe(e,t){if(e.context.options.session?.cookieCache?.enabled){let o=mt.base64Url.encode(JSON.stringify({session:t,expiresAt:J(e.context.authCookies.sessionData.options.maxAge||60,"sec").getTime(),signature:await(0,ft.createHMAC)("SHA-256","base64urlnopad").sign(e.context.secret,JSON.stringify(t))}),{padding:!1});if(o.length>4093)throw new Z("Session data is too large to store in the cookie. Please disable session cookie caching or reduce the size of the session data");e.setCookie(e.context.authCookies.sessionData.name,o,e.context.authCookies.sessionData.options)}}async function I(e,t,r,o){let n=e.context.authCookies.sessionToken.options,i=r?void 0:e.context.sessionConfig.expiresIn;await e.setSignedCookie(e.context.authCookies.sessionToken.name,t.session.token,e.context.secret,{...n,maxAge:i,...o}),r&&await e.setSignedCookie(e.context.authCookies.dontRememberToken.name,"true",e.context.secret,e.context.authCookies.dontRememberToken.options),await xe(e,t),e.context.setNewSession(t),e.context.options.secondaryStorage&&await e.context.secondaryStorage?.set(t.session.token,JSON.stringify({user:t.user,session:t.session}),Math.floor((new Date(t.session.expiresAt).getTime()-Date.now())/1e3))}function q(e){e.setCookie(e.context.authCookies.sessionToken.name,"",{...e.context.authCookies.sessionToken.options,maxAge:0}),e.setCookie(e.context.authCookies.sessionData.name,"",{...e.context.authCookies.sessionData.options,maxAge:0}),e.setCookie(e.context.authCookies.dontRememberToken.name,"",{...e.context.authCookies.dontRememberToken.options,maxAge:0})}var Rr=Object.defineProperty,kr=Object.defineProperties,Er=Object.getOwnPropertyDescriptors,gt=Object.getOwnPropertySymbols,Ur=Object.prototype.hasOwnProperty,_r=Object.prototype.propertyIsEnumerable,ht=(e,t,r)=>t in e?Rr(e,t,{enumerable:!0,configurable:!0,writable:!0,value:r}):e[t]=r,te=(e,t)=>{for(var r in t||(t={}))Ur.call(t,r)&&ht(e,r,t[r]);if(gt)for(var r of gt(t))_r.call(t,r)&&ht(e,r,t[r]);return e},re=(e,t)=>kr(e,Er(t)),Tr=class extends Error{constructor(e,t,r){super(t||e.toString(),{cause:r}),this.status=e,this.statusText=t,this.error=r}},vr=async(e,t)=>{var r,o,n,i,s,c;let a=t||{},d={onRequest:[t?.onRequest],onResponse:[t?.onResponse],onSuccess:[t?.onSuccess],onError:[t?.onError],onRetry:[t?.onRetry]};if(!t||!t?.plugins)return{url:e,options:a,hooks:d};for(let u of t?.plugins||[]){if(u.init){let h=await((r=u.init)==null?void 0:r.call(u,e.toString(),t));a=h.options||a,e=h.url}d.onRequest.push((o=u.hooks)==null?void 0:o.onRequest),d.onResponse.push((n=u.hooks)==null?void 0:n.onResponse),d.onSuccess.push((i=u.hooks)==null?void 0:i.onSuccess),d.onError.push((s=u.hooks)==null?void 0:s.onError),d.onRetry.push((c=u.hooks)==null?void 0:c.onRetry)}return{url:e,options:a,hooks:d}},wt=class{constructor(e){this.options=e}shouldAttemptRetry(e,t){return this.options.shouldRetry?Promise.resolve(e<this.options.attempts&&this.options.shouldRetry(t)):Promise.resolve(e<this.options.attempts)}getDelay(){return this.options.delay}},Sr=class{constructor(e){this.options=e}shouldAttemptRetry(e,t){return this.options.shouldRetry?Promise.resolve(e<this.options.attempts&&this.options.shouldRetry(t)):Promise.resolve(e<this.options.attempts)}getDelay(e){return Math.min(this.options.maxDelay,this.options.baseDelay*2**e)}};function Or(e){if(typeof e=="number")return new wt({type:"linear",attempts:e,delay:1e3});switch(e.type){case"linear":return new wt(e);case"exponential":return new Sr(e);default:throw new Error("Invalid retry strategy")}}var xr=e=>{let t={},r=o=>typeof o=="function"?o():o;if(e?.auth){if(e.auth.type==="Bearer"){let o=r(e.auth.token);if(!o)return t;t.authorization=`Bearer ${o}`}else if(e.auth.type==="Basic"){let o=r(e.auth.username),n=r(e.auth.password);if(!o||!n)return t;t.authorization=`Basic ${btoa(`${o}:${n}`)}`}else if(e.auth.type==="Custom"){let o=r(e.auth.value);if(!o)return t;t.authorization=`${r(e.auth.prefix)} ${o}`}}return t},At=["get","post","put","patch","delete"];var Lr=/^application\/(?:[\w!#$%&*.^`~-]*\+)?json(;.+)?$/i;function Pr(e){let t=e.headers.get("content-type"),r=new Set(["image/svg","application/xml","application/xhtml","application/html"]);if(!t)return"json";let o=t.split(";").shift()||"";return Lr.test(o)?"json":r.has(o)||o.startsWith("text/")?"text":"blob"}function Ir(e){try{return JSON.parse(e),!0}catch{return!1}}function Rt(e){if(e===void 0)return!1;let t=typeof e;return t==="string"||t==="number"||t==="boolean"||t===null?!0:t!=="object"?!1:Array.isArray(e)?!0:e.buffer?!1:e.constructor&&e.constructor.name==="Object"||typeof e.toJSON=="function"}function yt(e){try{return JSON.parse(e)}catch{return e}}function bt(e){return typeof e=="function"}function Dr(e){if(e?.customFetchImpl)return e.customFetchImpl;if(typeof globalThis<"u"&&bt(globalThis.fetch))return globalThis.fetch;if(typeof window<"u"&&bt(window.fetch))return window.fetch;throw new Error("No fetch implementation found")}function Cr(e){let t=new Headers(e?.headers),r=xr(e);for(let[o,n]of Object.entries(r||{}))t.set(o,n);if(!t.has("content-type")){let o=jr(e?.body);o&&t.set("content-type",o)}return t}function jr(e){return Rt(e)?"application/json":null}function Nr(e){if(!e?.body)return null;let t=new Headers(e?.headers);return Rt(e.body)&&!t.has("content-type")?JSON.stringify(e.body):e.body}function $r(e,t){var r;if(t?.method)return t.method.toUpperCase();if(e.startsWith("@")){let o=(r=e.split("@")[1])==null?void 0:r.split("/")[0];return At.includes(o)?o.toUpperCase():t?.body?"POST":"GET"}return t?.body?"POST":"GET"}function Br(e,t){let r;return!e?.signal&&e?.timeout&&(r=setTimeout(()=>t?.abort(),e?.timeout)),{abortTimeout:r,clearTimeout:()=>{r&&clearTimeout(r)}}}function Vr(e,t){let{baseURL:r,params:o,query:n}=t||{query:{},params:{},baseURL:""},i=e.startsWith("http")?e.split("/").slice(0,3).join("/"):r;if(!i)throw new TypeError(`Invalid URL ${e}. Are you passing in a relative URL but not setting the baseURL?`);if(e.startsWith("@")){let h=e.toString().split("@")[1].split("/")[0];At.includes(h)&&(e=e.replace(`@${h}/`,"/"))}i.endsWith("/")||(i+="/");let[s,c]=e.replace(i,"").split("?"),a=new URLSearchParams(c);for(let[h,p]of Object.entries(n||{}))a.set(h,String(p));if(o)if(Array.isArray(o)){let h=s.split("/").filter(p=>p.startsWith(":"));for(let[p,l]of h.entries()){let b=o[p];s=s.replace(l,b)}}else for(let[h,p]of Object.entries(o))s=s.replace(`:${h}`,String(p));s=s.split("/").map(encodeURIComponent).join("/"),s.startsWith("/")&&(s=s.slice(1));let d=a.size>0?`?${a}`.replace(/\+/g,"%20"):"";return new URL(`${s}${d}`,i)}var R=async(e,t)=>{var r,o,n,i,s,c,a,d;let{hooks:u,url:h,options:p}=await vr(e,t),l=Dr(p),b=new AbortController,E=(r=p.signal)!=null?r:b.signal,L=Vr(h,p),M=Nr(p),C=Cr(p),m=$r(h,p),f=re(te({},p),{url:L,headers:C,body:M,method:m,signal:E});for(let N of u.onRequest)if(N){let P=await N(f);P instanceof Object&&(f=P)}("pipeTo"in f&&typeof f.pipeTo=="function"||typeof((o=t?.body)==null?void 0:o.pipe)=="function")&&("duplex"in f||(f.duplex="half"));let{clearTimeout:S}=Br(p,b),w=await l(f.url,f);S();let pe={response:w,request:f};for(let N of u.onResponse)if(N){let P=await N(re(te({},pe),{response:(n=t?.hookOptions)!=null&&n.cloneResponse?w.clone():w}));P instanceof Response?w=P:P instanceof Object&&(w=P.response)}if(w.ok){if(!(f.method!=="HEAD"))return{data:"",error:null};let P=Pr(w),W={data:"",response:w,request:f};if(P==="json"||P==="text"){let Q=await w.text(),ur=await((i=f.jsonParser)!=null?i:yt)(Q);W.data=ur}else W.data=await w[P]();f?.output&&f.output&&!f.disableValidation&&(W.data=f.output.parse(W.data));for(let Q of u.onSuccess)Q&&await Q(re(te({},W),{response:(s=t?.hookOptions)!=null&&s.cloneResponse?w.clone():w}));return t?.throw?W.data:{data:W.data,error:null}}let dr=(c=t?.jsonParser)!=null?c:yt,st=await w.text(),Ue=Ir(st)?await dr(st):{},lr={response:w,request:f,error:re(te({},Ue),{status:w.status,statusText:w.statusText})};for(let N of u.onError)N&&await N(re(te({},lr),{response:(a=t?.hookOptions)!=null&&a.cloneResponse?w.clone():w}));if(t?.retry){let N=Or(t.retry),P=(d=t.retryAttempt)!=null?d:0;if(await N.shouldAttemptRetry(P,w)){for(let Q of u.onRetry)Q&&await Q(pe);let W=N.getDelay(P);return await new Promise(Q=>setTimeout(Q,W)),await R(e,re(te({},t),{retryAttempt:P+1}))}}if(t?.throw)throw new Tr(w.status,w.statusText,Ue);return{data:null,error:re(te({},Ue),{status:w.status,statusText:w.statusText})}};var vt=require("better-call"),K=require("jose");var kt=require("@better-auth/utils/hash"),Et=require("@better-auth/utils/base64");async function Ut(e){let t=await(0,kt.createHash)("SHA-256").digest(e);return Et.base64Url.encode(new Uint8Array(t),{padding:!1})}function he(e){return{tokenType:e.token_type,accessToken:e.access_token,refreshToken:e.refresh_token,accessTokenExpiresAt:e.expires_in?J(e.expires_in,"sec"):void 0,scopes:e?.scope?typeof e.scope=="string"?e.scope.split(" "):e.scope:[],idToken:e.id_token}}async function U({id:e,options:t,authorizationEndpoint:r,state:o,codeVerifier:n,scopes:i,claims:s,redirectURI:c,duration:a}){let d=new URL(r);if(d.searchParams.set("response_type","code"),d.searchParams.set("client_id",t.clientId),d.searchParams.set("state",o),d.searchParams.set("scope",i.join(" ")),d.searchParams.set("redirect_uri",t.redirectURI||c),n){let u=await Ut(n);d.searchParams.set("code_challenge_method","S256"),d.searchParams.set("code_challenge",u)}if(s){let u=s.reduce((h,p)=>(h[p]=null,h),{});d.searchParams.set("claims",JSON.stringify({id_token:{email:null,email_verified:null,...u}}))}return a&&d.searchParams.set("duration",a),d}var Mr=require("jose");async function k({code:e,codeVerifier:t,redirectURI:r,options:o,tokenEndpoint:n,authentication:i}){let s=new URLSearchParams,c={"content-type":"application/x-www-form-urlencoded",accept:"application/json","user-agent":"better-auth"};if(s.set("grant_type","authorization_code"),s.set("code",e),t&&s.set("code_verifier",t),s.set("redirect_uri",r),i==="basic"){let h=btoa(`${o.clientId}:${o.clientSecret}`);c.authorization=`Basic ${h}`}else s.set("client_id",o.clientId),s.set("client_secret",o.clientSecret);let{data:a,error:d}=await R(n,{method:"POST",body:s,headers:c});if(d)throw d;return he(a)}var z=require("zod"),Pe=require("better-call");var Hr=require("@better-auth/utils/hash"),Gr=require("@noble/ciphers/chacha"),Le=require("@noble/ciphers/utils"),Wr=require("@noble/ciphers/webcrypto");var qr=require("@noble/hashes/scrypt"),zr=require("uncrypto"),Fr=require("@better-auth/utils/hex");var _t=require("@better-auth/utils/random"),ue=(0,_t.createRandomStringGenerator)("a-z","0-9","A-Z","-_");async function we(e,t){let r=e.body?.callbackURL||(e.query?.currentURL?lt(e.query?.currentURL):"")||e.context.options.baseURL;if(!r)throw new Pe.APIError("BAD_REQUEST",{message:"callbackURL is required"});let o=ue(128),n=ue(32),i=JSON.stringify({callbackURL:r,codeVerifier:o,errorURL:e.body?.errorCallbackURL||e.query?.currentURL,newUserURL:e.body?.newUserCallbackURL,link:t,expiresAt:Date.now()+10*60*1e3}),s=new Date;s.setMinutes(s.getMinutes()+10);let c=await e.context.internalAdapter.createVerificationValue({value:i,identifier:n,expiresAt:s});if(!c)throw e.context.logger.error("Unable to create verification. Make sure the database adapter is properly working and there is a verification table in the database"),new Pe.APIError("INTERNAL_SERVER_ERROR",{message:"Unable to create verification"});return{state:c.identifier,codeVerifier:o}}async function Tt(e){let t=e.query.state||e.body.state,r=await e.context.internalAdapter.findVerificationValue(t);if(!r)throw e.context.logger.error("State Mismatch. Verification not found",{state:t}),e.redirect(`${e.context.baseURL}/error?error=please_restart_the_process`);let o=z.z.object({callbackURL:z.z.string(),codeVerifier:z.z.string(),errorURL:z.z.string().optional(),newUserURL:z.z.string().optional(),expiresAt:z.z.number(),link:z.z.object({email:z.z.string(),userId:z.z.string()}).optional()}).parse(JSON.parse(r.value));if(o.errorURL||(o.errorURL=`${e.context.baseURL}/error`),o.expiresAt<Date.now())throw await e.context.internalAdapter.deleteVerificationValue(r.id),e.context.logger.error("State expired.",{state:t}),e.redirect(`${e.context.baseURL}/error?error=please_restart_the_process`);return await e.context.internalAdapter.deleteVerificationValue(r.id),o}var St=e=>{let t="https://appleid.apple.com/auth/token";return{id:"apple",name:"Apple",createAuthorizationURL({state:r,scopes:o,redirectURI:n}){let i=o||["email","name"];return e.scope&&i.push(...e.scope),new URL(`https://appleid.apple.com/auth/authorize?client_id=${e.clientId}&response_type=code&redirect_uri=${e.redirectURI||n}&scope=${i.join(" ")}&state=${r}&response_mode=form_post`)},validateAuthorizationCode:async({code:r,codeVerifier:o,redirectURI:n})=>k({code:r,codeVerifier:o,redirectURI:e.redirectURI||n,options:e,tokenEndpoint:t}),async verifyIdToken(r,o){if(e.disableIdTokenSignIn)return!1;if(e.verifyIdToken)return e.verifyIdToken(r,o);let n=(0,K.decodeProtectedHeader)(r),{kid:i,alg:s}=n;if(!i||!s)return!1;let c=await Qr(i),{payload:a}=await(0,K.jwtVerify)(r,c,{algorithms:[s],issuer:"https://appleid.apple.com",audience:e.appBundleIdentifier||e.clientId,maxTokenAge:"1h"});return["email_verified","is_private_email"].forEach(d=>{a[d]!==void 0&&(a[d]=!!a[d])}),o&&a.nonce!==o?!1:!!a},async getUserInfo(r){if(e.getUserInfo)return e.getUserInfo(r);if(!r.idToken)return null;let o=(0,K.decodeJwt)(r.idToken);if(!o)return null;let n=o.user?`${o.user.name.firstName} ${o.user.name.lastName}`:o.email,i=await e.mapProfileToUser?.(o);return{user:{id:o.sub,name:n,emailVerified:!1,email:o.email,...i},data:o}}}},Qr=async e=>{let t="https://appleid.apple.com",r="/auth/keys",{data:o}=await R(`${t}${r}`);if(!o?.keys)throw new vt.APIError("BAD_REQUEST",{message:"Keys not found"});let n=o.keys.find(i=>i.kid===e);if(!n)throw new Error(`JWK with kid ${e} not found`);return await(0,K.importJWK)(n,n.alg)};var Ot=e=>({id:"discord",name:"Discord",createAuthorizationURL({state:t,scopes:r,redirectURI:o}){let n=r||["identify","email"];return e.scope&&n.push(...e.scope),new URL(`https://discord.com/api/oauth2/authorize?scope=${n.join("+")}&response_type=code&client_id=${e.clientId}&redirect_uri=${encodeURIComponent(e.redirectURI||o)}&state=${t}&prompt=${e.prompt||"none"}`)},validateAuthorizationCode:async({code:t,redirectURI:r})=>k({code:t,redirectURI:e.redirectURI||r,options:e,tokenEndpoint:"https://discord.com/api/oauth2/token"}),async getUserInfo(t){if(e.getUserInfo)return e.getUserInfo(t);let{data:r,error:o}=await R("https://discord.com/api/users/@me",{headers:{authorization:`Bearer ${t.accessToken}`}});if(o)return null;if(r.avatar===null){let i=r.discriminator==="0"?Number(BigInt(r.id)>>BigInt(22))%6:parseInt(r.discriminator)%5;r.image_url=`https://cdn.discordapp.com/embed/avatars/${i}.png`}else{let i=r.avatar.startsWith("a_")?"gif":"png";r.image_url=`https://cdn.discordapp.com/avatars/${r.id}/${r.avatar}.${i}`}let n=await e.mapProfileToUser?.(r);return{user:{id:r.id,name:r.display_name||r.username||"",email:r.email,emailVerified:r.verified,image:r.image_url,...n},data:r}}});var xt=e=>({id:"facebook",name:"Facebook",async createAuthorizationURL({state:t,scopes:r,redirectURI:o}){let n=r||["email","public_profile"];return e.scope&&n.push(...e.scope),await U({id:"facebook",options:e,authorizationEndpoint:"https://www.facebook.com/v21.0/dialog/oauth",scopes:n,state:t,redirectURI:o})},validateAuthorizationCode:async({code:t,redirectURI:r})=>k({code:t,redirectURI:e.redirectURI||r,options:e,tokenEndpoint:"https://graph.facebook.com/oauth/access_token"}),async getUserInfo(t){if(e.getUserInfo)return e.getUserInfo(t);let{data:r,error:o}=await R("https://graph.facebook.com/me?fields=id,name,email,picture",{auth:{type:"Bearer",token:t.accessToken}});if(o)return null;let n=await e.mapProfileToUser?.(r);return{user:{id:r.id,name:r.name,email:r.email,image:r.picture.data.url,emailVerified:r.email_verified,...n},data:r}}});var Lt=e=>{let t="https://github.com/login/oauth/access_token";return{id:"github",name:"GitHub",createAuthorizationURL({state:r,scopes:o,codeVerifier:n,redirectURI:i}){let s=o||["user:email"];return e.scope&&s.push(...e.scope),U({id:"github",options:e,authorizationEndpoint:"https://github.com/login/oauth/authorize",scopes:s,state:r,redirectURI:i})},validateAuthorizationCode:async({code:r,redirectURI:o})=>k({code:r,redirectURI:e.redirectURI||o,options:e,tokenEndpoint:t}),async getUserInfo(r){if(e.getUserInfo)return e.getUserInfo(r);let{data:o,error:n}=await R("https://api.github.com/user",{headers:{"User-Agent":"better-auth",authorization:`Bearer ${r.accessToken}`}});if(n)return null;let i=!1,{data:s}=await R("https://api.github.com/user/emails",{headers:{authorization:`Bearer ${r.accessToken}`,"User-Agent":"better-auth"}});s&&(o.email=(s.find(a=>a.primary)??s[0])?.email,i=s.find(a=>a.email===o.email)?.verified??!1);let c=await e.mapProfileToUser?.(o);return{user:{id:o.id.toString(),name:o.name||o.login,email:o.email,image:o.avatar_url,emailVerified:i,...c},data:o}}}};var Ie=["info","success","warn","error","debug"];function Zr(e,t){return Ie.indexOf(t)<=Ie.indexOf(e)}var F={reset:"\x1B[0m",bright:"\x1B[1m",dim:"\x1B[2m",underscore:"\x1B[4m",blink:"\x1B[5m",reverse:"\x1B[7m",hidden:"\x1B[8m",fg:{black:"\x1B[30m",red:"\x1B[31m",green:"\x1B[32m",yellow:"\x1B[33m",blue:"\x1B[34m",magenta:"\x1B[35m",cyan:"\x1B[36m",white:"\x1B[37m"},bg:{black:"\x1B[40m",red:"\x1B[41m",green:"\x1B[42m",yellow:"\x1B[43m",blue:"\x1B[44m",magenta:"\x1B[45m",cyan:"\x1B[46m",white:"\x1B[47m"}},Jr={info:F.fg.blue,success:F.fg.green,warn:F.fg.yellow,error:F.fg.red,debug:F.fg.magenta},Kr=(e,t)=>{let r=new Date().toISOString();return`${F.dim}${r}${F.reset} ${Jr[e]}${e.toUpperCase()}${F.reset} ${F.bright}Better Auth${F.reset} ${t}`},Yr=e=>{let t=e?.disabled!==!0,r=e?.level??"error",o=(n,i,s=[])=>{if(!t||!Zr(r,n))return;let c=Kr(n,i);if(!e||typeof e.log!="function"){n==="error"?console.error(c,...s):n==="warn"?console.warn(c,...s):console.log(c,...s);return}e.log(n==="success"?"info":n,c,...s)};return Object.fromEntries(Ie.map(n=>[n,(...[i,...s])=>o(n,i,s)]))},$=Yr();var Pt=require("jose"),It=e=>({id:"google",name:"Google",async createAuthorizationURL({state:t,scopes:r,codeVerifier:o,redirectURI:n}){if(!e.clientId||!e.clientSecret)throw $.error("Client Id and Client Secret is required for Google. Make sure to provide them in the options."),new Z("CLIENT_ID_AND_SECRET_REQUIRED");if(!o)throw new Z("codeVerifier is required for Google");let i=r||["email","profile","openid"];e.scope&&i.push(...e.scope);let s=await U({id:"google",options:e,authorizationEndpoint:"https://accounts.google.com/o/oauth2/auth",scopes:i,state:t,codeVerifier:o,redirectURI:n});return e.accessType&&s.searchParams.set("access_type",e.accessType),e.prompt&&s.searchParams.set("prompt",e.prompt),s},validateAuthorizationCode:async({code:t,codeVerifier:r,redirectURI:o})=>k({code:t,codeVerifier:r,redirectURI:e.redirectURI||o,options:e,tokenEndpoint:"https://oauth2.googleapis.com/token"}),async verifyIdToken(t,r){if(e.disableIdTokenSignIn)return!1;if(e.verifyIdToken)return e.verifyIdToken(t,r);let o=`https://www.googleapis.com/oauth2/v3/tokeninfo?id_token=${t}`,{data:n}=await R(o);return n?n.aud===e.clientId&&n.iss==="https://accounts.google.com":!1},async getUserInfo(t){if(e.getUserInfo)return e.getUserInfo(t);if(!t.idToken)return null;let r=(0,Pt.decodeJwt)(t.idToken),o=await e.mapProfileToUser?.(r);return{user:{id:r.sub,name:r.name,email:r.email,image:r.picture,emailVerified:r.email_verified,...o},data:r}}});var Dt=require("jose"),Ct=e=>{let t=e.tenantId||"common",r=`https://login.microsoftonline.com/${t}/oauth2/v2.0/authorize`,o=`https://login.microsoftonline.com/${t}/oauth2/v2.0/token`;return{id:"microsoft",name:"Microsoft EntraID",createAuthorizationURL(n){let i=n.scopes||["openid","profile","email","User.Read"];return e.scope&&i.push(...e.scope),U({id:"microsoft",options:e,authorizationEndpoint:r,state:n.state,codeVerifier:n.codeVerifier,scopes:i,redirectURI:n.redirectURI})},validateAuthorizationCode({code:n,codeVerifier:i,redirectURI:s}){return k({code:n,codeVerifier:i,redirectURI:e.redirectURI||s,options:e,tokenEndpoint:o})},async getUserInfo(n){if(e.getUserInfo)return e.getUserInfo(n);if(!n.idToken)return null;let i=(0,Dt.decodeJwt)(n.idToken),s=e.profilePhotoSize||48;await R(`https://graph.microsoft.com/v1.0/me/photos/${s}x${s}/$value`,{headers:{Authorization:`Bearer ${n.accessToken}`},async onResponse(a){if(!(e.disableProfilePhoto||!a.response.ok))try{let u=await a.response.clone().arrayBuffer(),h=Buffer.from(u).toString("base64");i.picture=`data:image/jpeg;base64, ${h}`}catch(d){$.error(d&&typeof d=="object"&&"name"in d?d.name:"",d)}}});let c=await e.mapProfileToUser?.(i);return{user:{id:i.sub,name:i.name,email:i.email,image:i.picture,emailVerified:!0,...c},data:i}}}};var jt=e=>({id:"spotify",name:"Spotify",createAuthorizationURL({state:t,scopes:r,codeVerifier:o,redirectURI:n}){let i=r||["user-read-email"];return e.scope&&i.push(...e.scope),U({id:"spotify",options:e,authorizationEndpoint:"https://accounts.spotify.com/authorize",scopes:i,state:t,codeVerifier:o,redirectURI:n})},validateAuthorizationCode:async({code:t,codeVerifier:r,redirectURI:o})=>k({code:t,codeVerifier:r,redirectURI:e.redirectURI||o,options:e,tokenEndpoint:"https://accounts.spotify.com/api/token"}),async getUserInfo(t){if(e.getUserInfo)return e.getUserInfo(t);let{data:r,error:o}=await R("https://api.spotify.com/v1/me",{method:"GET",headers:{Authorization:`Bearer ${t.accessToken}`}});if(o)return null;let n=await e.mapProfileToUser?.(r);return{user:{id:r.id,name:r.display_name,email:r.email,image:r.images[0]?.url,emailVerified:!1,...n},data:r}}});var ie={isAction:!1};var Nt=require("@better-auth/utils/random"),$t=e=>(0,Nt.createRandomStringGenerator)("a-z","A-Z","0-9")(e||32);var Bt=require("jose"),Vt=e=>({id:"twitch",name:"Twitch",createAuthorizationURL({state:t,scopes:r,redirectURI:o}){let n=r||["user:read:email","openid"];return e.scope&&n.push(...e.scope),U({id:"twitch",redirectURI:o,options:e,authorizationEndpoint:"https://id.twitch.tv/oauth2/authorize",scopes:n,state:t,claims:e.claims||["email","email_verified","preferred_username","picture"]})},validateAuthorizationCode:async({code:t,redirectURI:r})=>k({code:t,redirectURI:e.redirectURI||r,options:e,tokenEndpoint:"https://id.twitch.tv/oauth2/token"}),async getUserInfo(t){if(e.getUserInfo)return e.getUserInfo(t);let r=t.idToken;if(!r)return $.error("No idToken found in token"),null;let o=(0,Bt.decodeJwt)(r),n=await e.mapProfileToUser?.(o);return{user:{id:o.sub,name:o.preferred_username,email:o.email,image:o.picture,emailVerified:!1,...n},data:o}}});var Mt=e=>({id:"twitter",name:"Twitter",createAuthorizationURL(t){let r=t.scopes||["users.read","tweet.read","offline.access"];return e.scope&&r.push(...e.scope),U({id:"twitter",options:e,authorizationEndpoint:"https://x.com/i/oauth2/authorize",scopes:r,state:t.state,codeVerifier:t.codeVerifier,redirectURI:t.redirectURI})},validateAuthorizationCode:async({code:t,codeVerifier:r,redirectURI:o})=>k({code:t,codeVerifier:r,authentication:"basic",redirectURI:e.redirectURI||o,options:e,tokenEndpoint:"https://api.x.com/2/oauth2/token"}),async getUserInfo(t){if(e.getUserInfo)return e.getUserInfo(t);let{data:r,error:o}=await R("https://api.x.com/2/users/me?user.fields=profile_image_url",{method:"GET",headers:{Authorization:`Bearer ${t.accessToken}`}});if(o)return null;let n=await e.mapProfileToUser?.(r);return{user:{id:r.data.id,name:r.data.name,email:r.data.username||null,image:r.data.profile_image_url,emailVerified:r.data.verified||!1,...n},data:r}}});var qt=e=>{let t="https://api.dropboxapi.com/oauth2/token";return{id:"dropbox",name:"Dropbox",createAuthorizationURL:async({state:r,scopes:o,codeVerifier:n,redirectURI:i})=>{let s=o||["account_info.read"];return e.scope&&s.push(...e.scope),await U({id:"dropbox",options:e,authorizationEndpoint:"https://www.dropbox.com/oauth2/authorize",scopes:s,state:r,redirectURI:i,codeVerifier:n})},validateAuthorizationCode:async({code:r,codeVerifier:o,redirectURI:n})=>await k({code:r,codeVerifier:o,redirectURI:e.redirectURI||n,options:e,tokenEndpoint:t}),async getUserInfo(r){if(e.getUserInfo)return e.getUserInfo(r);let{data:o,error:n}=await R("https://api.dropboxapi.com/2/users/get_current_account",{method:"POST",headers:{Authorization:`Bearer ${r.accessToken}`}});if(n)return null;let i=await e.mapProfileToUser?.(o);return{user:{id:o.account_id,name:o.name?.display_name,email:o.email,emailVerified:o.email_verified||!1,image:o.profile_photo_url,...i},data:o}}}};var zt=e=>{let t="https://www.linkedin.com/oauth/v2/authorization",r="https://www.linkedin.com/oauth/v2/accessToken";return{id:"linkedin",name:"Linkedin",createAuthorizationURL:async({state:o,scopes:n,redirectURI:i})=>{let s=n||["profile","email","openid"];return e.scope&&s.push(...e.scope),await U({id:"linkedin",options:e,authorizationEndpoint:t,scopes:s,state:o,redirectURI:i})},validateAuthorizationCode:async({code:o,redirectURI:n})=>await k({code:o,redirectURI:e.redirectURI||n,options:e,tokenEndpoint:r}),async getUserInfo(o){let{data:n,error:i}=await R("https://api.linkedin.com/v2/userinfo",{method:"GET",headers:{Authorization:`Bearer ${o.accessToken}`}});if(i)return null;let s=await e.mapProfileToUser?.(n);return{user:{id:n.sub,name:n.name,email:n.email,emailVerified:n.email_verified||!1,image:n.picture,...s},data:n}}}};var De=(e="")=>e.split("://").map(t=>t.replace(/\/{2,}/g,"/")).join("://"),Xr=e=>{let t=e||"https://gitlab.com";return{authorizationEndpoint:De(`${t}/oauth/authorize`),tokenEndpoint:De(`${t}/oauth/token`),userinfoEndpoint:De(`${t}/api/v4/user`)}},Ft=e=>{let{authorizationEndpoint:t,tokenEndpoint:r,userinfoEndpoint:o}=Xr(e.issuer),n="gitlab";return{id:n,name:"Gitlab",createAuthorizationURL:async({state:s,scopes:c,codeVerifier:a,redirectURI:d})=>{let u=c||["read_user"];return e.scope&&u.push(...e.scope),await U({id:n,options:e,authorizationEndpoint:t,scopes:u,state:s,redirectURI:d,codeVerifier:a})},validateAuthorizationCode:async({code:s,redirectURI:c,codeVerifier:a})=>k({code:s,redirectURI:e.redirectURI||c,options:e,codeVerifier:a,tokenEndpoint:r}),async getUserInfo(s){if(e.getUserInfo)return e.getUserInfo(s);let{data:c,error:a}=await R(o,{headers:{authorization:`Bearer ${s.accessToken}`}});if(a||c.state!=="active"||c.locked)return null;let d=await e.mapProfileToUser?.(c);return{user:{id:c.id.toString(),name:c.name??c.username,email:c.email,image:c.avatar_url,emailVerified:!0,...d},data:c}}}};var Ht=e=>({id:"reddit",name:"Reddit",createAuthorizationURL({state:t,scopes:r,redirectURI:o}){let n=r||["identity"];return e.scope&&n.push(...e.scope),U({id:"reddit",options:e,authorizationEndpoint:"https://www.reddit.com/api/v1/authorize",scopes:n,state:t,redirectURI:o,duration:e.duration})},validateAuthorizationCode:async({code:t,redirectURI:r})=>{let o=new URLSearchParams({grant_type:"authorization_code",code:t,redirect_uri:e.redirectURI||r}),n={"content-type":"application/x-www-form-urlencoded",accept:"text/plain","user-agent":"better-auth",Authorization:`Basic ${Buffer.from(`${e.clientId}:${e.clientSecret}`).toString("base64")}`},{data:i,error:s}=await R("https://www.reddit.com/api/v1/access_token",{method:"POST",headers:n,body:o.toString()});if(s)throw s;return he(i)},async getUserInfo(t){if(e.getUserInfo)return e.getUserInfo(t);let{data:r,error:o}=await R("https://oauth.reddit.com/api/v1/me",{headers:{Authorization:`Bearer ${t.accessToken}`,"User-Agent":"better-auth"}});if(o)return null;let n=await e.mapProfileToUser?.(r);return{user:{id:r.id,name:r.name,email:r.oauth_client_id,emailVerified:r.has_verified_email,image:r.icon_img?.split("?")[0],...n},data:r}}});var Gt=require("zod"),eo={apple:St,discord:Ot,facebook:xt,github:Lt,microsoft:Ct,google:It,spotify:jt,twitch:Vt,twitter:Mt,dropbox:qt,linkedin:zt,gitlab:Ft,reddit:Ht},Ce=Object.keys(eo),Wt=Gt.z.enum(Ce,{description:"OAuth2 provider to use"});var B=require("zod");var se=require("better-call");var H=require("better-call");var Y=require("zod");function Qt(e){try{return JSON.parse(e)}catch{return null}}var g={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",SOCIAL_ACCOUNT_ALREADY_LINKED:"Social account already linked",PROVIDER_NOT_FOUND:"Provider not found",INVALID_TOKEN:"invalid token",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",EMAIL_CAN_NOT_BE_UPDATED:"Email can not be updated",CREDENTIAL_ACCOUNT_NOT_FOUND:"Credential account not found",SESSION_EXPIRED:"Session expired. Re-authenticate to perform this action."};var Zt=require("@better-auth/utils/hmac"),Jt=require("@better-auth/utils/base64"),Kt=require("@better-auth/utils/binary"),ye=()=>A("/get-session",{method:"GET",query:Y.z.optional(Y.z.object({disableCookieCache:Y.z.boolean({description:"Disable cookie cache and fetch session from database"}).or(Y.z.string().transform(e=>e==="true")).optional(),disableRefresh:Y.z.boolean({description:"Disable session refresh. Useful for checking session status, without updating the session"}).optional()})),requireHeaders:!0,metadata:{openapi:{description:"Get the current session",responses:{200:{description:"Success",content:{"application/json":{schema:{type:"object",properties:{session:{type:"object",properties:{token:{type:"string"},userId:{type:"string"},expiresAt:{type:"string"}}},user:{type:"object",$ref:"#/components/schemas/User"}}}}}}}}}},async e=>{try{let t=await e.getSignedCookie(e.context.authCookies.sessionToken.name,e.context.secret);if(!t)return e.json(null);let r=e.getCookie(e.context.authCookies.sessionData.name),o=r?Qt(Kt.binary.decode(Jt.base64.decode(r))):null;if(o&&!await(0,Zt.createHMAC)("SHA-256","base64urlnopad").verify(e.context.secret,JSON.stringify(o.session),o.signature))return q(e),e.json(null);let n=await e.getSignedCookie(e.context.authCookies.dontRememberToken.name,e.context.secret);if(o?.session&&e.context.options.session?.cookieCache?.enabled&&!e.query?.disableCookieCache){let u=o.session;if(o.expiresAt<Date.now()||u.session.expiresAt<new Date){let p=e.context.authCookies.sessionData.name;e.setCookie(p,"",{maxAge:0})}else return e.json(u)}let i=await e.context.internalAdapter.findSession(t);if(e.context.session=i,!i||i.session.expiresAt<new Date)return q(e),i&&await e.context.internalAdapter.deleteSession(i.session.token),e.json(null);if(n||e.query?.disableRefresh)return e.json(i);let s=e.context.sessionConfig.expiresIn,c=e.context.sessionConfig.updateAge;if(i.session.expiresAt.valueOf()-s*1e3+c*1e3<=Date.now()){let u=await e.context.internalAdapter.updateSession(i.session.token,{expiresAt:J(e.context.sessionConfig.expiresIn,"sec")});if(!u)return q(e),e.json(null,{status:401});let h=(u.expiresAt.valueOf()-Date.now())/1e3;return await I(e,{session:u,user:i.user},!1,{maxAge:h}),e.json({session:u,user:i.user})}return await xe(e,i),e.json(i)}catch(t){throw e.context.logger.error("INTERNAL_SERVER_ERROR",t),new H.APIError("INTERNAL_SERVER_ERROR",{message:g.FAILED_TO_GET_SESSION})}}),X=async(e,t)=>{if(e.context.session)return e.context.session;let r=await ye()({...e,_flag:"json",headers:e.headers,query:t}).catch(o=>null);return e.context.session=r,r},D=ne(async e=>{let t=await X(e);if(!t?.session)throw new H.APIError("UNAUTHORIZED");return{session:t}}),to=ne(async e=>{let t=await X(e);if(!t?.session)throw new H.APIError("UNAUTHORIZED");if(e.context.sessionConfig.freshAge===0)return{session:t};let r=e.context.sessionConfig.freshAge,o=t.session.updatedAt?.valueOf()||t.session.createdAt.valueOf();if(!(Date.now()-o<r*1e3))throw new H.APIError("FORBIDDEN",{message:"Session is not fresh"});return{session:t}}),je=()=>A("/list-sessions",{method:"GET",use:[D],requireHeaders:!0,metadata:{openapi:{description:"List all active sessions for the user",responses:{200:{description:"Success",content:{"application/json":{schema:{type:"array",items:{type:"object",properties:{token:{type:"string"},userId:{type:"string"},expiresAt:{type:"string"}}}}}}}}}}},async e=>{let r=(await e.context.internalAdapter.listSessions(e.context.session.user.id)).filter(o=>o.expiresAt>new Date);return e.json(r)}),Ne=A("/revoke-session",{method:"POST",body:Y.z.object({token:Y.z.string({description:"The token to revoke"})}),use:[D],requireHeaders:!0,metadata:{openapi:{description:"Revoke a single session",requestBody:{content:{"application/json":{schema:{type:"object",properties:{token:{type:"string"}},required:["token"]}}}}}}},async e=>{let t=e.body.token,r=await e.context.internalAdapter.findSession(t);if(!r)throw new H.APIError("BAD_REQUEST",{message:"Session not found"});if(r.session.userId!==e.context.session.user.id)throw new H.APIError("UNAUTHORIZED");try{await e.context.internalAdapter.deleteSession(t)}catch(o){throw e.context.logger.error(o&&typeof o=="object"&&"name"in o?o.name:"",o),new H.APIError("INTERNAL_SERVER_ERROR")}return e.json({status:!0})}),$e=A("/revoke-sessions",{method:"POST",use:[D],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"}},required:["status"]}}}}}}}},async e=>{try{await e.context.internalAdapter.deleteSessions(e.context.session.user.id)}catch(t){throw e.context.logger.error(t&&typeof t=="object"&&"name"in t?t.name:"",t),new H.APIError("INTERNAL_SERVER_ERROR")}return e.json({status:!0})}),Be=A("/revoke-other-sessions",{method:"POST",requireHeaders:!0,use:[D],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"}}}}}}}}}},async e=>{let t=e.context.session;if(!t.user)throw new H.APIError("UNAUTHORIZED");let n=(await e.context.internalAdapter.listSessions(t.user.id)).filter(i=>i.expiresAt>new Date).filter(i=>i.token!==e.context.session.session.token);return await Promise.all(n.map(i=>e.context.internalAdapter.deleteSession(i.token))),e.json({status:!0})});var er=require("jose");var Yt=require("jose");async function Xt(e,t,r=3600){return await new Yt.SignJWT(e).setProtectedHeader({alg:"HS256"}).setIssuedAt().setExpirationTime(Math.floor(Date.now()/1e3)+r).sign(new TextEncoder().encode(t))}async function V(e,t,r){return await Xt({email:t.toLowerCase(),updateTo:r},e)}async function tr(e,t){if(!e.context.options.emailVerification?.sendVerificationEmail)throw e.context.logger.error("Verification email isn't enabled."),new se.APIError("BAD_REQUEST",{message:"Verification email isn't enabled"});let r=await V(e.context.secret,t.email),o=`${e.context.baseURL}/verify-email?token=${r}&callbackURL=${e.body.callbackURL||e.query?.currentURL||"/"}`;await e.context.options.emailVerification.sendVerificationEmail({user:t,url:o,token:r},e.request)}var Ve=A("/send-verification-email",{method:"POST",query:B.z.object({currentURL:B.z.string({description:"The URL to use for email verification callback"}).optional()}).optional(),body:B.z.object({email:B.z.string({description:"The email to send the verification email to"}).email(),callbackURL:B.z.string({description:"The URL to use for email verification callback"}).optional()}),metadata:{openapi:{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"},callbackURL:{type:"string",description:"The URL to use for email verification callback"}},required:["email"]}}}},responses:{200:{description:"Success",content:{"application/json":{schema:{type:"object",properties:{status:{type:"boolean"}}}}}}}}}},async e=>{if(!e.context.options.emailVerification?.sendVerificationEmail)throw e.context.logger.error("Verification email isn't enabled."),new se.APIError("BAD_REQUEST",{message:"Verification email isn't enabled"});let{email:t}=e.body,r=await e.context.internalAdapter.findUserByEmail(t);if(!r)throw new se.APIError("BAD_REQUEST",{message:g.USER_NOT_FOUND});return await tr(e,r.user),e.json({status:!0})}),Me=A("/verify-email",{method:"GET",query:B.z.object({token:B.z.string({description:"The token to verify the email"}),callbackURL:B.z.string({description:"The URL to redirect to after email verification"}).optional()}),metadata:{openapi:{description:"Verify the email of the user",responses:{200:{description:"Success",content:{"application/json":{schema:{type:"object",properties:{user:{type:"object"},status:{type:"boolean"}},required:["user","status"]}}}}}}}},async e=>{function t(c){throw e.query.callbackURL?e.query.callbackURL.includes("?")?e.redirect(`${e.query.callbackURL}&error=${c}`):e.redirect(`${e.query.callbackURL}?error=${c}`):new se.APIError("UNAUTHORIZED",{message:c})}let{token:r}=e.query,o;try{o=await(0,er.jwtVerify)(r,new TextEncoder().encode(e.context.secret),{algorithms:["HS256"]})}catch(c){return e.context.logger.error("Failed to verify email",c),t("invalid_token")}let i=B.z.object({email:B.z.string().email(),updateTo:B.z.string().optional()}).parse(o.payload),s=await e.context.internalAdapter.findUserByEmail(i.email);if(!s)return t("user_not_found");if(i.updateTo){let c=await X(e);if(!c){if(e.query.callbackURL)throw e.redirect(`${e.query.callbackURL}?error=unauthorized`);return t("unauthorized")}if(c.user.email!==i.email){if(e.query.callbackURL)throw e.redirect(`${e.query.callbackURL}?error=unauthorized`);return t("unauthorized")}let a=await e.context.internalAdapter.updateUserByEmail(i.email,{email:i.updateTo,emailVerified:!1}),d=await V(e.context.secret,i.updateTo);if(await e.context.options.emailVerification?.sendVerificationEmail?.({user:a,url:`${e.context.baseURL}/verify-email?token=${d}`,token:d},e.request),e.query.callbackURL)throw e.redirect(e.query.callbackURL);return e.json({status:!0})}if(await e.context.internalAdapter.updateUserByEmail(i.email,{emailVerified:!0}),e.context.options.emailVerification?.autoSignInAfterVerification&&!await X(e)){let a=await e.context.internalAdapter.createSession(s.user.id,e.request);if(!a)throw new se.APIError("INTERNAL_SERVER_ERROR",{message:"Failed to create session"});await I(e,{session:a,user:s.user})}if(e.query.callbackURL)throw e.redirect(e.query.callbackURL);return e.json({status:!0})});async function be(e,{userInfo:t,account:r,callbackURL:o}){let n=await e.context.internalAdapter.findOAuthUser(t.email.toLowerCase(),r.accountId,r.providerId).catch(a=>{throw $.error(`Better auth was unable to query your database.
3
+ Error: `,a),e.redirect(`${e.context.baseURL}/error?error=internal_server_error`)}),i=n?.user,s=!i;if(n){let a=n.accounts.find(d=>d.providerId===r.providerId);if(a){let d=Object.fromEntries(Object.entries({accessToken:r.accessToken,idToken:r.idToken,refreshToken:r.refreshToken,accessTokenExpiresAt:r.accessTokenExpiresAt,refreshTokenExpiresAt:r.refreshTokenExpiresAt}).filter(([u,h])=>h!==void 0));Object.keys(d).length>0&&await e.context.internalAdapter.updateAccount(a.id,d)}else{if(!e.context.options.account?.accountLinking?.trustedProviders?.includes(r.providerId)&&!t.emailVerified||e.context.options.account?.accountLinking?.enabled===!1)return ge&&$.warn(`User already exist but account isn't linked to ${r.providerId}. To read more about how account linking works in Better Auth see https://www.better-auth.com/docs/concepts/users-accounts#account-linking.`),{error:"account not linked",data:null};try{await e.context.internalAdapter.linkAccount({providerId:r.providerId,accountId:t.id.toString(),userId:n.user.id,accessToken:r.accessToken,idToken:r.idToken,refreshToken:r.refreshToken,accessTokenExpiresAt:r.accessTokenExpiresAt,refreshTokenExpiresAt:r.refreshTokenExpiresAt,scope:r.scope})}catch(h){return $.error("Unable to link account",h),{error:"unable to link account",data:null}}}}else try{if(i=await e.context.internalAdapter.createOAuthUser({...t,email:t.email.toLowerCase(),id:void 0},{accessToken:r.accessToken,idToken:r.idToken,refreshToken:r.refreshToken,accessTokenExpiresAt:r.accessTokenExpiresAt,refreshTokenExpiresAt:r.refreshTokenExpiresAt,scope:r.scope,providerId:r.providerId,accountId:t.id.toString()}).then(a=>a?.user),!t.emailVerified&&i&&e.context.options.emailVerification?.sendOnSignUp){let a=await V(e.context.secret,i.email),d=`${e.context.baseURL}/verify-email?token=${a}&callbackURL=${o}`;await e.context.options.emailVerification?.sendVerificationEmail?.({user:i,url:d,token:a},e.request)}}catch(a){return a instanceof Ae.APIError?{error:a.message,data:null,isRegister:!1}:{error:"unable to create user",data:null,isRegister:!1}}if(!i)return{error:"unable to create user",data:null,isRegister:!1};let c=await e.context.internalAdapter.createSession(i.id,e.request);return c?{data:{session:c,user:i},error:null,isRegister:s}:{error:"unable to create session",data:null,isRegister:!1}}var qe=A("/sign-in/social",{method:"POST",query:v.z.object({currentURL:v.z.string().optional()}).optional(),body:v.z.object({callbackURL:v.z.string({description:"Callback URL to redirect to after the user has signed in"}).optional(),newUserCallbackURL:v.z.string().optional(),errorCallbackURL:v.z.string({description:"Callback URL to redirect to if an error happens"}).optional(),provider:Wt,disableRedirect:v.z.boolean({description:"Disable automatic redirection to the provider. Useful for handling the redirection yourself"}).optional(),idToken:v.z.optional(v.z.object({token:v.z.string({description:"ID token from the provider"}),nonce:v.z.string({description:"Nonce used to generate the token"}).optional(),accessToken:v.z.string({description:"Access token from the provider"}).optional(),refreshToken:v.z.string({description:"Refresh token from the provider"}).optional(),expiresAt:v.z.number({description:"Expiry date of the token"}).optional()}),{description:"ID token from the provider to sign in the user with id token"})}),metadata:{openapi:{description:"Sign in with a social provider",responses:{200:{description:"Success",content:{"application/json":{schema:{type:"object",properties:{session:{type:"string"},user:{type:"object"},url:{type:"string"},redirect:{type:"boolean"}},required:["session","user","url","redirect"]}}}}}}}},async e=>{let t=e.context.socialProviders.find(i=>i.id===e.body.provider);if(!t)throw e.context.logger.error("Provider not found. Make sure to add the provider in your auth config",{provider:e.body.provider}),new x.APIError("NOT_FOUND",{message:g.PROVIDER_NOT_FOUND});if(e.body.idToken){if(!t.verifyIdToken)throw e.context.logger.error("Provider does not support id token verification",{provider:e.body.provider}),new x.APIError("NOT_FOUND",{message:g.ID_TOKEN_NOT_SUPPORTED});let{token:i,nonce:s}=e.body.idToken;if(!await t.verifyIdToken(i,s))throw e.context.logger.error("Invalid id token",{provider:e.body.provider}),new x.APIError("UNAUTHORIZED",{message:g.INVALID_TOKEN});let a=await t.getUserInfo({idToken:i,accessToken:e.body.idToken.accessToken,refreshToken:e.body.idToken.refreshToken});if(!a||!a?.user)throw e.context.logger.error("Failed to get user info",{provider:e.body.provider}),new x.APIError("UNAUTHORIZED",{message:g.FAILED_TO_GET_USER_INFO});if(!a.user.email)throw e.context.logger.error("User email not found",{provider:e.body.provider}),new x.APIError("UNAUTHORIZED",{message:g.USER_EMAIL_NOT_FOUND});let d=await be(e,{userInfo:{email:a.user.email,id:a.user.id,name:a.user.name||"",image:a.user.image,emailVerified:a.user.emailVerified||!1},account:{providerId:t.id,accountId:a.user.id,accessToken:e.body.idToken.accessToken}});if(d.error)throw new x.APIError("UNAUTHORIZED",{message:d.error});return await I(e,d.data),e.json({token:d.data.session.token,url:void 0,redirect:!1})}let{codeVerifier:r,state:o}=await we(e),n=await t.createAuthorizationURL({state:o,codeVerifier:r,redirectURI:`${e.context.baseURL}/callback/${t.id}`});return e.json({url:n.toString(),redirect:!e.body.disableRedirect})}),ze=A("/sign-in/email",{method:"POST",body:v.z.object({email:v.z.string({description:"Email of the user"}),password:v.z.string({description:"Password of the user"}),callbackURL:v.z.string({description:"Callback URL to use as a redirect for email verification"}).optional(),rememberMe:v.z.boolean({description:"If this is false, the session will not be remembered. Default is `true`."}).default(!0).optional()}),metadata:{openapi:{description:"Sign in with email and password",responses:{200:{description:"Success",content:{"application/json":{schema:{type:"object",properties:{user:{type:"object"},url:{type:"string"},redirect:{type:"boolean"}},required:["session","user","url","redirect"]}}}}}}}},async e=>{if(!e.context.options?.emailAndPassword?.enabled)throw e.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!"),new x.APIError("BAD_REQUEST",{message:"Email and password is not enabled"});let{email:t,password:r}=e.body;if(!v.z.string().email().safeParse(t).success)throw new x.APIError("BAD_REQUEST",{message:g.INVALID_EMAIL});let n=await e.context.internalAdapter.findUserByEmail(t,{includeAccounts:!0});if(!n)throw await e.context.password.hash(r),e.context.logger.error("User not found",{email:t}),new x.APIError("UNAUTHORIZED",{message:g.INVALID_EMAIL_OR_PASSWORD});let i=n.accounts.find(d=>d.providerId==="credential");if(!i)throw e.context.logger.error("Credential account not found",{email:t}),new x.APIError("UNAUTHORIZED",{message:g.INVALID_EMAIL_OR_PASSWORD});let s=i?.password;if(!s)throw e.context.logger.error("Password not found",{email:t}),new x.APIError("UNAUTHORIZED",{message:g.INVALID_EMAIL_OR_PASSWORD});if(!await e.context.password.verify({hash:s,password:r}))throw e.context.logger.error("Invalid password"),new x.APIError("UNAUTHORIZED",{message:g.INVALID_EMAIL_OR_PASSWORD});if(e.context.options?.emailAndPassword?.requireEmailVerification&&!n.user.emailVerified){if(!e.context.options?.emailVerification?.sendVerificationEmail)throw new x.APIError("UNAUTHORIZED",{message:g.EMAIL_NOT_VERIFIED});let d=await V(e.context.secret,n.user.email),u=`${e.context.baseURL}/verify-email?token=${d}&callbackURL=${e.body.callbackURL||"/"}`;throw await e.context.options.emailVerification.sendVerificationEmail({user:n.user,url:u,token:d},e.request),e.context.logger.error("Email not verified",{email:t}),new x.APIError("FORBIDDEN",{message:g.EMAIL_NOT_VERIFIED})}let a=await e.context.internalAdapter.createSession(n.user.id,e.headers,e.body.rememberMe===!1);if(!a)throw e.context.logger.error("Failed to create session"),new x.APIError("UNAUTHORIZED",{message:g.FAILED_TO_CREATE_SESSION});return await I(e,{session:a,user:n.user},e.body.rememberMe===!1),e.json({user:{id:n.user.id,email:n.user.email,name:n.user.name,image:n.user.image,emailVerified:n.user.emailVerified,createdAt:n.user.createdAt,updatedAt:n.user.updatedAt},redirect:!!e.body.callbackURL,url:e.body.callbackURL})});var ae=require("zod");var Re=ae.z.object({code:ae.z.string().optional(),error:ae.z.string().optional(),error_description:ae.z.string().optional(),state:ae.z.string().optional()}),Fe=A("/callback/:id",{method:["GET","POST"],body:Re.optional(),query:Re.optional(),metadata:ie},async e=>{let t;try{if(e.method==="GET")t=Re.parse(e.query);else if(e.method==="POST")t=Re.parse(e.body);else throw new Error("Unsupported method")}catch(m){throw e.context.logger.error("INVALID_CALLBACK_REQUEST",m),e.redirect(`${e.context.baseURL}/error?error=invalid_callback_request`)}let{code:r,error:o,state:n,error_description:i}=t;if(!n)throw e.context.logger.error("State not found",o),e.redirect(`${e.context.baseURL}/error?error=state_not_found`);if(!r)throw e.context.logger.error("Code not found"),e.redirect(`${e.context.baseURL}/error?error=${o||"no_code"}&error_description=${i}`);let s=e.context.socialProviders.find(m=>m.id===e.params.id);if(!s)throw e.context.logger.error("Oauth provider with id",e.params.id,"not found"),e.redirect(`${e.context.baseURL}/error?error=oauth_provider_not_found`);let{codeVerifier:c,callbackURL:a,link:d,errorURL:u,newUserURL:h}=await Tt(e),p;try{p=await s.validateAuthorizationCode({code:r,codeVerifier:c,redirectURI:`${e.context.baseURL}/callback/${s.id}`})}catch(m){throw e.context.logger.error("",m),e.redirect(`${e.context.baseURL}/error?error=please_restart_the_process`)}let l=await s.getUserInfo(p).then(m=>m?.user);function b(m){let f=u||a||`${e.context.baseURL}/error`;throw f.includes("?")?f=`${f}&error=${m}`:f=`${f}?error=${m}`,e.redirect(f)}if(!l)return e.context.logger.error("Unable to get user info"),b("unable_to_get_user_info");if(!l.email)return e.context.logger.error("Provider did not return email. This could be due to misconfiguration in the provider settings."),b("email_not_found");if(!a)throw e.context.logger.error("No callback URL found"),e.redirect(`${e.context.baseURL}/error?error=please_restart_the_process`);if(d){if(d.email!==l.email.toLowerCase())return b("email_doesn't_match");if(!await e.context.internalAdapter.createAccount({userId:d.userId,providerId:s.id,accountId:l.id}))return b("unable_to_link_account");let f;try{f=a.toString()}catch{f=a}throw e.redirect(f)}let E=await be(e,{userInfo:{...l,email:l.email,name:l.name||l.email},account:{providerId:s.id,accountId:l.id,...p,scope:p.scopes?.join(",")},callbackURL:a});if(E.error)return e.context.logger.error(E.error.split(" ").join("_")),b(E.error.split(" ").join("_"));let{session:L,user:M}=E.data;await I(e,{session:L,user:M});let C;try{C=(E.isRegister&&h||a).toString()}catch{C=E.isRegister&&h||a}throw e.redirect(C)});var Us=require("zod");var rr=require("better-call");var He=A("/sign-out",{method:"POST",requireHeaders:!0,metadata:{openapi:{description:"Sign out the current user",responses:{200:{description:"Success",content:{"application/json":{schema:{type:"object",properties:{success:{type:"boolean"}}}}}}}}}},async e=>{let t=await e.getSignedCookie(e.context.authCookies.sessionToken.name,e.context.secret);if(!t)throw q(e),new rr.APIError("BAD_REQUEST",{message:g.FAILED_TO_GET_SESSION});return await e.context.internalAdapter.deleteSession(t),q(e),e.json({success:!0})});var j=require("zod");var ce=require("better-call");function or(e,t,r){let o=t?new URL(t,e.baseURL):new URL(`${e.baseURL}/error`);return r&&Object.entries(r).forEach(([n,i])=>o.searchParams.set(n,i)),o.href}function ro(e,t,r){let o=new URL(t,e.baseURL);return r&&Object.entries(r).forEach(([n,i])=>o.searchParams.set(n,i)),o.href}var Ge=A("/forget-password",{method:"POST",body:j.z.object({email:j.z.string({description:"The email address of the user to send a password reset email to"}).email(),redirectTo:j.z.string({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:{description:"Send a password reset email to the user",responses:{200:{description:"Success",content:{"application/json":{schema:{type:"object",properties:{status:{type:"boolean"}}}}}}}}}},async e=>{if(!e.context.options.emailAndPassword?.sendResetPassword)throw e.context.logger.error("Reset password isn't enabled.Please pass an emailAndPassword.sendResetPasswordToken function in your auth config!"),new ce.APIError("BAD_REQUEST",{message:"Reset password isn't enabled"});let{email:t,redirectTo:r}=e.body,o=await e.context.internalAdapter.findUserByEmail(t,{includeAccounts:!0});if(!o)return e.context.logger.error("Reset Password: User not found",{email:t}),e.json({status:!1},{body:{status:!0}});let n=60*60*1,i=J(e.context.options.emailAndPassword.resetPasswordTokenExpiresIn||n,"sec"),s=$t(24);await e.context.internalAdapter.createVerificationValue({value:o.user.id.toString(),identifier:`reset-password:${s}`,expiresAt:i});let c=`${e.context.baseURL}/reset-password/${s}?callbackURL=${r}`;return await e.context.options.emailAndPassword.sendResetPassword({user:o.user,url:c,token:s},e.request),e.json({status:!0})}),We=A("/reset-password/:token",{method:"GET",query:j.z.object({callbackURL:j.z.string({description:"The URL to redirect the user to reset their password"})}),metadata:{openapi:{description:"Redirects the user to the callback URL with the token",responses:{200:{description:"Success",content:{"application/json":{schema:{type:"object",properties:{token:{type:"string"}}}}}}}}}},async e=>{let{token:t}=e.params,{callbackURL:r}=e.query;if(!t||!r)throw e.redirect(or(e.context,r,{error:"INVALID_TOKEN"}));let o=await e.context.internalAdapter.findVerificationValue(`reset-password:${t}`);throw!o||o.expiresAt<new Date?e.redirect(or(e.context,r,{error:"INVALID_TOKEN"})):e.redirect(ro(e.context,r,{token:t}))}),Qe=A("/reset-password",{query:j.z.optional(j.z.object({token:j.z.string().optional(),currentURL:j.z.string().optional()})),method:"POST",body:j.z.object({newPassword:j.z.string({description:"The new password to set"}),token:j.z.string({description:"The token to reset the password"}).optional()}),metadata:{openapi:{description:"Reset the password for a user",responses:{200:{description:"Success",content:{"application/json":{schema:{type:"object",properties:{status:{type:"boolean"}}}}}}}}}},async e=>{let t=e.body.token||e.query?.token||(e.query?.currentURL?new URL(e.query.currentURL).searchParams.get("token"):"");if(!t)throw new ce.APIError("BAD_REQUEST",{message:g.INVALID_TOKEN});let{newPassword:r}=e.body,o=e.context.password?.config.minPasswordLength,n=e.context.password?.config.maxPasswordLength;if(r.length<o)throw new ce.APIError("BAD_REQUEST",{message:g.PASSWORD_TOO_SHORT});if(r.length>n)throw new ce.APIError("BAD_REQUEST",{message:g.PASSWORD_TOO_LONG});let i=`reset-password:${t}`,s=await e.context.internalAdapter.findVerificationValue(i);if(!s||s.expiresAt<new Date)throw new ce.APIError("BAD_REQUEST",{message:g.INVALID_TOKEN});await e.context.internalAdapter.deleteVerificationValue(s.id);let c=s.value,a=await e.context.password.hash(r);return(await e.context.internalAdapter.findAccounts(c)).find(h=>h.providerId==="credential")?(await e.context.internalAdapter.updatePassword(c,a),e.json({status:!0})):(await e.context.internalAdapter.createAccount({userId:c,providerId:"credential",password:a,accountId:c}),e.json({status:!0}))});var _=require("zod");var T=require("better-call");var y=require("zod"),nr=require("better-call"),Cs=y.z.object({id:y.z.string(),providerId:y.z.string(),accountId:y.z.string(),userId:y.z.string(),accessToken:y.z.string().nullish(),refreshToken:y.z.string().nullish(),idToken:y.z.string().nullish(),accessTokenExpiresAt:y.z.date().nullish(),refreshTokenExpiresAt:y.z.date().nullish(),scope:y.z.string().nullish(),password:y.z.string().nullish(),createdAt:y.z.date().default(()=>new Date),updatedAt:y.z.date().default(()=>new Date)}),js=y.z.object({id:y.z.string(),email:y.z.string().transform(e=>e.toLowerCase()),emailVerified:y.z.boolean().default(!1),name:y.z.string(),image:y.z.string().nullish(),createdAt:y.z.date().default(()=>new Date),updatedAt:y.z.date().default(()=>new Date)}),Ns=y.z.object({id:y.z.string(),userId:y.z.string(),expiresAt:y.z.date(),createdAt:y.z.date().default(()=>new Date),updatedAt:y.z.date().default(()=>new Date),token:y.z.string(),ipAddress:y.z.string().nullish(),userAgent:y.z.string().nullish()}),$s=y.z.object({id:y.z.string(),value:y.z.string(),createdAt:y.z.date().default(()=>new Date),updatedAt:y.z.date().default(()=>new Date),expiresAt:y.z.date(),identifier:y.z.string()});function oo(e,t){let r={...t==="user"?e.user?.additionalFields:{},...t==="session"?e.session?.additionalFields:{}};for(let o of e.plugins||[])o.schema&&o.schema[t]&&(r={...r,...o.schema[t].fields});return r}function no(e,t){let r=t.action||"create",o=t.fields,n={};for(let i in o){if(i in e){if(o[i].input===!1){if(o[i].defaultValue){n[i]=o[i].defaultValue;continue}continue}if(o[i].validator?.input&&e[i]!==void 0){n[i]=o[i].validator.input.parse(e[i]);continue}if(o[i].transform?.input&&e[i]!==void 0){n[i]=o[i].transform?.input(e[i]);continue}n[i]=e[i];continue}if(o[i].defaultValue&&r==="create"){n[i]=o[i].defaultValue;continue}if(o[i].required&&r==="create")throw new nr.APIError("BAD_REQUEST",{message:`${i} is required`})}return n}function ke(e,t,r){let o=oo(e,"user");return no(t||{},{fields:o,action:r})}var Ze=()=>A("/update-user",{method:"POST",body:_.z.record(_.z.string(),_.z.any()),use:[D],metadata:{openapi:{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"}}}}}},responses:{200:{description:"Success",content:{"application/json":{schema:{type:"object",properties:{user:{type:"object"}}}}}}}}}},async e=>{let t=e.body;if(t.email)throw new T.APIError("BAD_REQUEST",{message:g.EMAIL_CAN_NOT_BE_UPDATED});let{name:r,image:o,...n}=t,i=e.context.session;if(o===void 0&&r===void 0&&Object.keys(n).length===0)return e.json({status:!0});let s=ke(e.context.options,n,"update"),c=await e.context.internalAdapter.updateUserByEmail(i.user.email,{name:r,image:o,...s});return await I(e,{session:i.session,user:c}),e.json({status:!0})}),Je=A("/change-password",{method:"POST",body:_.z.object({newPassword:_.z.string({description:"The new password to set"}),currentPassword:_.z.string({description:"The current password"}),revokeOtherSessions:_.z.boolean({description:"Revoke all other sessions"}).optional()}),use:[D],metadata:{openapi:{description:"Change the password of the user",responses:{200:{description:"Success",content:{"application/json":{schema:{type:"object",properties:{user:{description:"The user object",$ref:"#/components/schemas/User"}}}}}}}}}},async e=>{let{newPassword:t,currentPassword:r,revokeOtherSessions:o}=e.body,n=e.context.session,i=e.context.password.config.minPasswordLength;if(t.length<i)throw e.context.logger.error("Password is too short"),new T.APIError("BAD_REQUEST",{message:g.PASSWORD_TOO_SHORT});let s=e.context.password.config.maxPasswordLength;if(t.length>s)throw e.context.logger.error("Password is too long"),new T.APIError("BAD_REQUEST",{message:g.PASSWORD_TOO_LONG});let a=(await e.context.internalAdapter.findAccounts(n.user.id)).find(p=>p.providerId==="credential"&&p.password);if(!a||!a.password)throw new T.APIError("BAD_REQUEST",{message:g.CREDENTIAL_ACCOUNT_NOT_FOUND});let d=await e.context.password.hash(t);if(!await e.context.password.verify({hash:a.password,password:r}))throw new T.APIError("BAD_REQUEST",{message:g.INVALID_PASSWORD});await e.context.internalAdapter.updateAccount(a.id,{password:d});let h=null;if(o){await e.context.internalAdapter.deleteSessions(n.user.id);let p=await e.context.internalAdapter.createSession(n.user.id,e.headers);if(!p)throw new T.APIError("INTERNAL_SERVER_ERROR",{message:g.FAILED_TO_GET_SESSION});await I(e,{session:p,user:n.user}),h=p.token}return e.json({token:h})}),Ke=A("/set-password",{method:"POST",body:_.z.object({newPassword:_.z.string()}),metadata:{SERVER_ONLY:!0},use:[D]},async e=>{let{newPassword:t}=e.body,r=e.context.session,o=e.context.password.config.minPasswordLength;if(t.length<o)throw e.context.logger.error("Password is too short"),new T.APIError("BAD_REQUEST",{message:g.PASSWORD_TOO_SHORT});let n=e.context.password.config.maxPasswordLength;if(t.length>n)throw e.context.logger.error("Password is too long"),new T.APIError("BAD_REQUEST",{message:g.PASSWORD_TOO_LONG});let s=(await e.context.internalAdapter.findAccounts(r.user.id)).find(a=>a.providerId==="credential"&&a.password),c=await e.context.password.hash(t);if(!s)return await e.context.internalAdapter.linkAccount({userId:r.user.id,providerId:"credential",accountId:r.user.id,password:c}),e.json({status:!0});throw new T.APIError("BAD_REQUEST",{message:"user already has a password"})}),Ye=A("/delete-user",{method:"POST",use:[D],body:_.z.object({callbackURL:_.z.string().optional(),password:_.z.string().optional(),token:_.z.string().optional()}),metadata:{openapi:{description:"Delete the user",responses:{200:{description:"Success",content:{"application/json":{schema:{type:"object"}}}}}}}},async e=>{if(!e.context.options.user?.deleteUser?.enabled)throw e.context.logger.error("Delete user is disabled. Enable it in the options",{session:e.context.session}),new T.APIError("NOT_FOUND");let t=e.context.session;if(e.body.password){let i=(await e.context.internalAdapter.findAccounts(t.user.id)).find(c=>c.providerId==="credential"&&c.password);if(!i||!i.password)throw new T.APIError("BAD_REQUEST",{message:g.CREDENTIAL_ACCOUNT_NOT_FOUND});if(!await e.context.password.verify({hash:i.password,password:e.body.password}))throw new T.APIError("BAD_REQUEST",{message:g.INVALID_PASSWORD})}else if(e.context.options.session?.freshAge){let n=t.session.createdAt.getTime(),i=e.context.options.session.freshAge;if(Date.now()-n>i)throw new T.APIError("BAD_REQUEST",{message:g.SESSION_EXPIRED})}if(e.body.token)return await Ee({...e,query:{token:e.body.token}}),e.json({success:!0,message:"User deleted"});if(e.context.options.user.deleteUser?.sendDeleteAccountVerification){let n=ue(32,"0-9","a-z");await e.context.internalAdapter.createVerificationValue({value:t.user.id,identifier:`delete-account-${n}`,expiresAt:new Date(Date.now()+1e3*60*60*24)});let i=`${e.context.baseURL}/delete-user/callback?token=${n}&callbackURL=${e.body.callbackURL||"/"}`;return await e.context.options.user.deleteUser.sendDeleteAccountVerification({user:t.user,url:i,token:n},e.request),e.json({success:!0,message:"Verification email sent"})}let r=e.context.options.user.deleteUser?.beforeDelete;r&&await r(t.user,e.request),await e.context.internalAdapter.deleteUser(t.user.id),await e.context.internalAdapter.deleteSessions(t.user.id),await e.context.internalAdapter.deleteAccounts(t.user.id),q(e);let o=e.context.options.user.deleteUser?.afterDelete;return o&&await o(t.user,e.request),e.json({success:!0,message:"User deleted"})}),Ee=A("/delete-user/callback",{method:"GET",query:_.z.object({token:_.z.string(),callbackURL:_.z.string().optional()})},async e=>{if(!e.context.options.user?.deleteUser?.enabled)throw e.context.logger.error("Delete user is disabled. Enable it in the options"),new T.APIError("NOT_FOUND");let t=await X(e);if(!t)throw new T.APIError("NOT_FOUND",{message:g.FAILED_TO_GET_USER_INFO});let r=await e.context.internalAdapter.findVerificationValue(`delete-account-${e.query.token}`);if(!r||r.expiresAt<new Date)throw r&&await e.context.internalAdapter.deleteVerificationValue(r.id),new T.APIError("NOT_FOUND",{message:g.INVALID_TOKEN});if(r.value!==t.user.id)throw new T.APIError("NOT_FOUND",{message:g.INVALID_TOKEN});let o=e.context.options.user.deleteUser?.beforeDelete;o&&await o(t.user,e.request),await e.context.internalAdapter.deleteUser(t.user.id),await e.context.internalAdapter.deleteSessions(t.user.id),await e.context.internalAdapter.deleteAccounts(t.user.id),await e.context.internalAdapter.deleteVerificationValue(r.id),q(e);let n=e.context.options.user.deleteUser?.afterDelete;if(n&&await n(t.user,e.request),e.query.callbackURL)throw e.redirect(e.query.callbackURL||"/");return e.json({success:!0,message:"User deleted"})}),Xe=A("/change-email",{method:"POST",query:_.z.object({currentURL:_.z.string().optional()}).optional(),body:_.z.object({newEmail:_.z.string({description:"The new email to set"}).email(),callbackURL:_.z.string({description:"The URL to redirect to after email verification"}).optional()}),use:[D],metadata:{openapi:{responses:{200:{description:"Success",content:{"application/json":{schema:{type:"object",properties:{user:{type:"object"},status:{type:"boolean"}}}}}}}}}},async e=>{if(!e.context.options.user?.changeEmail?.enabled)throw e.context.logger.error("Change email is disabled."),new T.APIError("BAD_REQUEST",{message:"Change email is disabled"});if(e.body.newEmail===e.context.session.user.email)throw e.context.logger.error("Email is the same"),new T.APIError("BAD_REQUEST",{message:"Email is the same"});if(await e.context.internalAdapter.findUserByEmail(e.body.newEmail))throw e.context.logger.error("Email already exists"),new T.APIError("BAD_REQUEST",{message:"Couldn't update your email"});if(e.context.session.user.emailVerified!==!0){let n=await e.context.internalAdapter.updateUserByEmail(e.context.session.user.email,{email:e.body.newEmail});return e.json({status:!0})}if(!e.context.options.user.changeEmail.sendChangeEmailVerification)throw e.context.logger.error("Verification email isn't enabled."),new T.APIError("BAD_REQUEST",{message:"Verification email isn't enabled"});let r=await V(e.context.secret,e.context.session.user.email,e.body.newEmail),o=`${e.context.baseURL}/verify-email?token=${r}&callbackURL=${e.body.callbackURL||e.query?.currentURL||"/"}`;return await e.context.options.user.changeEmail.sendChangeEmailVerification({user:e.context.session.user,newEmail:e.body.newEmail,url:o,token:r},e.request),e.json({status:!0})});var io=(e="Unknown")=>`<!DOCTYPE html>
4
4
  <html lang="en">
5
5
  <head>
6
6
  <meta charset="UTF-8">
@@ -80,4 +80,4 @@ Error: `,a),e.redirect(`${e.context.baseURL}/error?error=internal_server_error`)
80
80
  <div class="error-code">Error Code: <span id="errorCode">${e}</span></div>
81
81
  </div>
82
82
  </body>
83
- </html>`,We=h("/error",{method:"GET",metadata:{...Y,openapi:{description:"Displays an error page",responses:{200:{description:"Success",content:{"text/html":{schema:{type:"string"}}}}}}}},async e=>{let t=new URL(e.request?.url||"").searchParams.get("error")||"Unknown";return new Response(Pr(t),{headers:{"Content-Type":"text/html"}})});var Qe=h("/ok",{method:"GET",metadata:{...Y,openapi:{description:"Check if the API is working",responses:{200:{description:"Success",content:{"application/json":{schema:{type:"object",properties:{ok:{type:"boolean"}}}}}}}}}},async e=>e.json({ok:!0}));var K=require("zod");var z=require("better-call");var Ze=()=>h("/sign-up/email",{method:"POST",query:K.z.object({currentURL:K.z.string().optional()}).optional(),body:K.z.record(K.z.string(),K.z.any()),metadata:{openapi:{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"},callbackURL:{type:"string",description:"The URL to use for email verification callback"}},required:["name","email","password"]}}}},responses:{200:{description:"Success",content:{"application/json":{schema:{type:"object",properties:{id:{type:"string",description:"The id of the user"},email:{type:"string",description:"The email of the user"},name:{type:"string",description:"The name of the user"},image:{type:"string",description:"The image of the user"},emailVerified:{type:"boolean",description:"If the email is verified"}}}}}}}}}},async e=>{if(!e.context.options.emailAndPassword?.enabled)throw new z.APIError("BAD_REQUEST",{message:"Email and password sign up is not enabled"});let t=e.body,{name:r,email:o,password:i,image:n,callbackURL:s,...d}=t;if(!K.z.string().email().safeParse(o).success)throw new z.APIError("BAD_REQUEST",{message:m.INVALID_EMAIL});let c=e.context.password.config.minPasswordLength;if(i.length<c)throw e.context.logger.error("Password is too short"),new z.APIError("BAD_REQUEST",{message:m.PASSWORD_TOO_SHORT});let u=e.context.password.config.maxPasswordLength;if(i.length>u)throw e.context.logger.error("Password is too long"),new z.APIError("BAD_REQUEST",{message:m.PASSWORD_TOO_LONG});if((await e.context.internalAdapter.findUserByEmail(o))?.user)throw e.context.logger.info(`Sign-up attempt for existing email: ${o}`),new z.APIError("UNPROCESSABLE_ENTITY",{message:m.USER_ALREADY_EXISTS});let f=fe(e.context.options,d),l;try{if(l=await e.context.internalAdapter.createUser({email:o.toLowerCase(),name:r,image:n,...f,emailVerified:!1}),!l)throw new z.APIError("BAD_REQUEST",{message:m.FAILED_TO_CREATE_USER})}catch(x){throw ae&&e.context.logger.error("Failed to create user",x),new z.APIError("UNPROCESSABLE_ENTITY",{message:m.FAILED_TO_CREATE_USER,details:x})}if(!l)throw new z.APIError("UNPROCESSABLE_ENTITY",{message:m.FAILED_TO_CREATE_USER});let y=await e.context.password.hash(i);if(await e.context.internalAdapter.linkAccount({userId:l.id,providerId:"credential",accountId:l.id,password:y}),e.context.options.emailVerification?.sendOnSignUp||e.context.options.emailAndPassword.requireEmailVerification){let x=await j(e.context.secret,l.email),q=`${e.context.baseURL}/verify-email?token=${x}&callbackURL=${t.callbackURL||e.query?.currentURL||"/"}`;await e.context.options.emailVerification?.sendVerificationEmail?.({user:l,url:q,token:x},e.request)}if(!e.context.options.emailAndPassword.autoSignIn||e.context.options.emailAndPassword.requireEmailVerification)return e.json({token:null});let U=await e.context.internalAdapter.createSession(l.id,e.request);if(!U)throw new z.APIError("BAD_REQUEST",{message:m.FAILED_TO_CREATE_SESSION});return await I(e,{session:U,user:l}),e.json({token:U.token})});var re=require("zod");var Ke=require("better-call");var Je=h("/list-accounts",{method:"GET",use:[L],metadata:{openapi:{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"},provider:{type:"string"}}}}}}}}}}},async e=>{let t=e.context.session,r=await e.context.internalAdapter.findAccounts(t.user.id);return e.json(r.map(o=>({id:o.id,provider:o.providerId})))}),Ye=h("/link-social",{method:"POST",requireHeaders:!0,query:re.z.object({currentURL:re.z.string().optional()}).optional(),body:re.z.object({callbackURL:re.z.string({description:"The URL to redirect to after the user has signed in"}).optional(),provider:re.z.enum(Se,{description:"The OAuth2 provider to use"})}),use:[L],metadata:{openapi:{description:"Link a social account to the user",responses:{200:{description:"Success",content:{"application/json":{schema:{type:"object",properties:{url:{type:"string"},redirect:{type:"boolean"}},required:["url","redirect"]}}}}}}}},async e=>{let t=e.context.session;if((await e.context.internalAdapter.findAccounts(t.user.id)).find(d=>d.providerId===e.body.provider))throw new Ke.APIError("BAD_REQUEST",{message:m.SOCIAL_ACCOUNT_ALREADY_LINKED});let i=e.context.socialProviders.find(d=>d.id===e.body.provider);if(!i)throw e.context.logger.error("Provider not found. Make sure to add the provider in your auth config",{provider:e.body.provider}),new Ke.APIError("NOT_FOUND",{message:m.PROVIDER_NOT_FOUND});let n=await ce(e,{userId:t.user.id,email:t.user.email}),s=await i.createAuthorizationURL({state:n.state,codeVerifier:n.codeVerifier,redirectURI:`${e.context.baseURL}/callback/${i.id}`});return e.json({url:s.toString(),redirect:!0})});function tr(e,t){if(t.advanced?.ipAddress?.disableIpTracking)return null;let r="127.0.0.1";if(tt)return r;let i=t.advanced?.ipAddress?.ipAddressHeaders||["x-client-ip","x-forwarded-for","cf-connecting-ip","fastly-client-ip","x-real-ip","x-cluster-client-ip","x-forwarded","forwarded-for","forwarded"],n=e instanceof Request?e.headers:e;for(let s of i){let d=n.get(s);if(typeof d=="string"){let a=d.split(",")[0].trim();if(a)return a}}return null}function Dr(e,t,r){let o=Date.now(),i=t*1e3;return o-r.lastRequest<i&&r.count>=e}function Cr(e){return new Response(JSON.stringify({message:"Too many requests. Please try again later."}),{status:429,statusText:"Too Many Requests",headers:{"X-Retry-After":e.toString()}})}function Nr(e,t){let r=Date.now(),o=t*1e3;return Math.ceil((e+o-r)/1e3)}function jr(e,t){let r="rateLimit",o=e.adapter;return{get:async i=>(await o.findMany({model:r,where:[{field:"key",value:i}]}))[0],set:async(i,n,s)=>{try{s?await o.updateMany({model:t??"rateLimit",where:[{field:"key",value:i}],update:{count:n.count,lastRequest:n.lastRequest}}):await o.create({model:t??"rateLimit",data:{key:i,count:n.count,lastRequest:n.lastRequest}})}catch(d){e.logger.error("Error setting rate limit",d)}}}}var rr=new Map;function $r(e){return e.options.rateLimit?.customStorage?e.options.rateLimit.customStorage:e.rateLimit.storage==="secondary-storage"?{get:async r=>{let o=await e.options.secondaryStorage?.get(r);return o?JSON.parse(o):void 0},set:async(r,o)=>{await e.options.secondaryStorage?.set?.(r,JSON.stringify(o))}}:e.rateLimit.storage==="memory"?{async get(r){return rr.get(r)},async set(r,o,i){rr.set(r,o)}}:jr(e,e.rateLimit.modelName)}async function or(e,t){if(!t.rateLimit.enabled)return;let r=t.baseURL,o=e.url.replace(r,"").split("?")[0],i=t.rateLimit.window,n=t.rateLimit.max,s=tr(e,t.options)+o,a=Vr().find(f=>f.pathMatcher(o));a&&(i=a.window,n=a.max);for(let f of t.options.plugins||[])if(f.rateLimit){let l=f.rateLimit.find(y=>y.pathMatcher(o));if(l){i=l.window,n=l.max;break}}if(t.rateLimit.customRules){let f=Object.keys(t.rateLimit.customRules).find(l=>l.includes("*")?ne(l)(o):l===o);if(f){let l=t.rateLimit.customRules[f],y=typeof l=="function"?await l(e):l;y&&(i=y.window,n=y.max)}}let c=$r(t),u=await c.get(s),b=Date.now();if(!u)await c.set(s,{key:s,count:1,lastRequest:b});else{let f=b-u.lastRequest;if(Dr(n,i,u)){let l=Nr(u.lastRequest,i);return Cr(l)}else f>i*1e3?await c.set(s,{...u,count:1,lastRequest:b},!0):await c.set(s,{...u,count:u.count+1,lastRequest:b},!0)}}function Vr(){return[{pathMatcher(t){return t.startsWith("/sign-in")||t.startsWith("/sign-up")||t.startsWith("/change-password")||t.startsWith("/change-email")},window:10,max:3}]}var ta=require("defu");var pe=require("better-call");function ir(e,t){let r=t.plugins?.reduce((d,a)=>({...d,...a.endpoints}),{}),o=t.plugins?.map(d=>d.middlewares?.map(a=>{let c=async u=>a.middleware({...u,context:{...e,...u.context}});return c.path=a.path,c.options=a.middleware.options,c.headers=a.middleware.headers,{path:a.path,middleware:c}})).filter(d=>d!==void 0).flat()||[],n={...{signInSocial:Ce,callbackOAuth:je,getSession:le(),signOut:$e,signUpEmail:Ze(),signInEmail:Ne,forgetPassword:Ve,resetPassword:Me,verifyEmail:De,sendVerificationEmail:Pe,changeEmail:Ge,changePassword:qe,setPassword:Fe,updateUser:ze(),deleteUser:He,forgetPasswordCallback:Be,listSessions:ve(),revokeSession:Ie,revokeSessions:Le,revokeOtherSessions:xe,linkSocialAccount:Ye,listUserAccounts:Je,deleteUserCallback:ge},...r,ok:Qe,error:We},s={};for(let[d,a]of Object.entries(n))s[d]=async(c={})=>{a.headers=new Headers;let u={setHeader(p,w){a.headers.set(p,w)},setCookie(p,w,O){(0,T.setCookie)(a.headers,p,w,O)},getCookie(p,w){let S=c.headers?.get("cookie");return(0,T.getCookie)(S||"",p,w)},getSignedCookie(p,w,O){let S=c.headers;return S?(0,T.getSignedCookie)(S,w,p,O):null},async setSignedCookie(p,w,O,S){await(0,T.setSignedCookie)(a.headers,p,w,O,S)},redirect(p){return a.headers.set("Location",p),new T.APIError("FOUND")},responseHeader:a.headers},b=await e,f=null,l={...u,...c,path:a.path,context:{...b,...c.context,session:null,setNewSession:function(p){this.newSession=p,f=p}}},y=t.plugins||[],U=y.map(p=>{if(p.hooks?.before)return p.hooks.before}).filter(p=>p!==void 0).flat(),x=y.map(p=>{if(p.hooks?.after)return p.hooks.after}).filter(p=>p!==void 0).flat();t.hooks?.before&&U.push({matcher:()=>!0,handler:t.hooks.before}),t.hooks?.after&&x.push({matcher:()=>!0,handler:t.hooks.after});for(let p of U){if(!p.matcher(l))continue;let w=await p.handler(l);if(w&&"context"in w){l={...l,...w.context};continue}if(w)return w}let q;try{q=await a(l),f&&(l.context.newSession=f)}catch(p){if(f&&(l.context.newSession=f),p instanceof T.APIError){if(!x?.length)throw p.headers=a.headers,p;l.context.returned=p,l.context.returned.headers=a.headers;for(let w of x||[])if(w.matcher(l))try{let S=await w.handler(l);S&&"response"in S&&(l.context.returned=S.response)}catch(S){if(S instanceof T.APIError){l.context.returned=S;continue}throw S}if(l.context.returned instanceof T.APIError)throw l.context.returned.headers=a.headers,l.context.returned;return l.context.returned}throw p}l.context.returned=q,l.responseHeader=a.headers;for(let p of x)if(p.matcher(l))try{let O=await p.handler(l);if(O)if("responseHeader"in O){let S=O.responseHeader;l.responseHeader=S}else l.context.returned=O}catch(O){if(O instanceof T.APIError){l.context.returned=O;continue}throw O}let N=l.context.returned;if(N instanceof Response&&a.headers.forEach((p,w)=>{w==="set-cookie"?N.headers.append(w,p):N.headers.set(w,p)}),N instanceof T.APIError)throw N.headers=a.headers,N;return N},s[d].path=a.path,s[d].method=a.method,s[d].options=a.options,s[d].headers=a.headers;return{api:s,middlewares:o}}var Br=(e,t)=>{let{api:r,middlewares:o}=ir(e,t),i=new URL(e.baseURL).pathname;return(0,T.createRouter)(r,{extraContext:e,basePath:i,routerMiddleware:[{path:"/**",middleware:Ae},...o],async onRequest(n){for(let s of e.options.plugins||[])if(s.onRequest){let d=await s.onRequest(n,e);if(d&&"response"in d)return d.response}return or(n,e)},async onResponse(n){for(let s of e.options.plugins||[])if(s.onResponse){let d=await s.onResponse(n,e);if(d)return d.response}return n},onError(n){if(n instanceof T.APIError&&n.status==="FOUND")return;if(t.onAPIError?.throw)throw n;if(t.onAPIError?.onError){t.onAPIError.onError(n,e);return}let s=t.logger?.level,d=s==="error"||s==="warn"||s==="debug"?D:void 0;if(t.logger?.disabled!==!0){if(n&&typeof n=="object"&&"message"in n&&typeof n.message=="string"&&(n.message.includes("no column")||n.message.includes("column")||n.message.includes("relation")||n.message.includes("table")||n.message.includes("does not exist"))){e.logger?.error(n.message);return}n instanceof T.APIError?(n.status==="INTERNAL_SERVER_ERROR"&&e.logger.error(n.status,n),d?.error(n.message)):e.logger?.error(n&&typeof n=="object"&&"name"in n?n.name:"",n)}}})};0&&(module.exports={APIError,callbackOAuth,changeEmail,changePassword,createAuthEndpoint,createAuthMiddleware,createEmailVerificationToken,deleteUser,deleteUserCallback,error,forgetPassword,forgetPasswordCallback,freshSessionMiddleware,getEndpoints,getSession,getSessionFromCtx,linkSocialAccount,listSessions,listUserAccounts,ok,optionsMiddleware,originCheckMiddleware,resetPassword,revokeOtherSessions,revokeSession,revokeSessions,router,sendVerificationEmail,sendVerificationEmailFn,sessionMiddleware,setPassword,signInEmail,signInSocial,signOut,signUpEmail,updateUser,verifyEmail});
83
+ </html>`,et=A("/error",{method:"GET",metadata:{...ie,openapi:{description:"Displays an error page",responses:{200:{description:"Success",content:{"text/html":{schema:{type:"string"}}}}}}}},async e=>{let t=new URL(e.request?.url||"").searchParams.get("error")||"Unknown";return new Response(io(t),{headers:{"Content-Type":"text/html"}})});var tt=A("/ok",{method:"GET",metadata:{...ie,openapi:{description:"Check if the API is working",responses:{200:{description:"Success",content:{"application/json":{schema:{type:"object",properties:{ok:{type:"boolean"}}}}}}}}}},async e=>e.json({ok:!0}));var oe=require("zod");var G=require("better-call");var rt=()=>A("/sign-up/email",{method:"POST",query:oe.z.object({currentURL:oe.z.string().optional()}).optional(),body:oe.z.record(oe.z.string(),oe.z.any()),metadata:{openapi:{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"},callbackURL:{type:"string",description:"The URL to use for email verification callback"}},required:["name","email","password"]}}}},responses:{200:{description:"Success",content:{"application/json":{schema:{type:"object",properties:{id:{type:"string",description:"The id of the user"},email:{type:"string",description:"The email of the user"},name:{type:"string",description:"The name of the user"},image:{type:"string",description:"The image of the user"},emailVerified:{type:"boolean",description:"If the email is verified"}}}}}}}}}},async e=>{if(!e.context.options.emailAndPassword?.enabled)throw new G.APIError("BAD_REQUEST",{message:"Email and password sign up is not enabled"});let t=e.body,{name:r,email:o,password:n,image:i,callbackURL:s,...c}=t;if(!oe.z.string().email().safeParse(o).success)throw new G.APIError("BAD_REQUEST",{message:g.INVALID_EMAIL});let d=e.context.password.config.minPasswordLength;if(n.length<d)throw e.context.logger.error("Password is too short"),new G.APIError("BAD_REQUEST",{message:g.PASSWORD_TOO_SHORT});let u=e.context.password.config.maxPasswordLength;if(n.length>u)throw e.context.logger.error("Password is too long"),new G.APIError("BAD_REQUEST",{message:g.PASSWORD_TOO_LONG});if((await e.context.internalAdapter.findUserByEmail(o))?.user)throw e.context.logger.info(`Sign-up attempt for existing email: ${o}`),new G.APIError("UNPROCESSABLE_ENTITY",{message:g.USER_ALREADY_EXISTS});let p=ke(e.context.options,c),l;try{if(l=await e.context.internalAdapter.createUser({email:o.toLowerCase(),name:r,image:i,...p,emailVerified:!1}),!l)throw new G.APIError("BAD_REQUEST",{message:g.FAILED_TO_CREATE_USER})}catch(L){throw ge&&e.context.logger.error("Failed to create user",L),new G.APIError("UNPROCESSABLE_ENTITY",{message:g.FAILED_TO_CREATE_USER,details:L})}if(!l)throw new G.APIError("UNPROCESSABLE_ENTITY",{message:g.FAILED_TO_CREATE_USER});let b=await e.context.password.hash(n);if(await e.context.internalAdapter.linkAccount({userId:l.id,providerId:"credential",accountId:l.id,password:b}),e.context.options.emailVerification?.sendOnSignUp||e.context.options.emailAndPassword.requireEmailVerification){let L=await V(e.context.secret,l.email),M=`${e.context.baseURL}/verify-email?token=${L}&callbackURL=${t.callbackURL||e.query?.currentURL||"/"}`;await e.context.options.emailVerification?.sendVerificationEmail?.({user:l,url:M,token:L},e.request)}if(!e.context.options.emailAndPassword.autoSignIn||e.context.options.emailAndPassword.requireEmailVerification)return e.json({token:null});let E=await e.context.internalAdapter.createSession(l.id,e.request);if(!E)throw new G.APIError("BAD_REQUEST",{message:g.FAILED_TO_CREATE_SESSION});return await I(e,{session:E,user:l}),e.json({token:E.token})});var de=require("zod");var ot=require("better-call");var nt=A("/list-accounts",{method:"GET",use:[D],metadata:{openapi:{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"},provider:{type:"string"}}}}}}}}}}},async e=>{let t=e.context.session,r=await e.context.internalAdapter.findAccounts(t.user.id);return e.json(r.map(o=>({id:o.id,provider:o.providerId})))}),it=A("/link-social",{method:"POST",requireHeaders:!0,query:de.z.object({currentURL:de.z.string().optional()}).optional(),body:de.z.object({callbackURL:de.z.string({description:"The URL to redirect to after the user has signed in"}).optional(),provider:de.z.enum(Ce,{description:"The OAuth2 provider to use"})}),use:[D],metadata:{openapi:{description:"Link a social account to the user",responses:{200:{description:"Success",content:{"application/json":{schema:{type:"object",properties:{url:{type:"string"},redirect:{type:"boolean"}},required:["url","redirect"]}}}}}}}},async e=>{let t=e.context.session;if((await e.context.internalAdapter.findAccounts(t.user.id)).find(c=>c.providerId===e.body.provider))throw new ot.APIError("BAD_REQUEST",{message:g.SOCIAL_ACCOUNT_ALREADY_LINKED});let n=e.context.socialProviders.find(c=>c.id===e.body.provider);if(!n)throw e.context.logger.error("Provider not found. Make sure to add the provider in your auth config",{provider:e.body.provider}),new ot.APIError("NOT_FOUND",{message:g.PROVIDER_NOT_FOUND});let i=await we(e,{userId:t.user.id,email:t.user.email}),s=await n.createAuthorizationURL({state:i.state,codeVerifier:i.codeVerifier,redirectURI:`${e.context.baseURL}/callback/${n.id}`});return e.json({url:s.toString(),redirect:!0})});function ir(e,t){if(t.advanced?.ipAddress?.disableIpTracking)return null;let r="127.0.0.1";if(dt)return r;let n=t.advanced?.ipAddress?.ipAddressHeaders||["x-client-ip","x-forwarded-for","cf-connecting-ip","fastly-client-ip","x-real-ip","x-cluster-client-ip","x-forwarded","forwarded-for","forwarded"],i=e instanceof Request?e.headers:e;for(let s of n){let c=i.get(s);if(typeof c=="string"){let a=c.split(",")[0].trim();if(a)return a}}return null}function so(e,t,r){let o=Date.now(),n=t*1e3;return o-r.lastRequest<n&&r.count>=e}function ao(e){return new Response(JSON.stringify({message:"Too many requests. Please try again later."}),{status:429,statusText:"Too Many Requests",headers:{"X-Retry-After":e.toString()}})}function co(e,t){let r=Date.now(),o=t*1e3;return Math.ceil((e+o-r)/1e3)}function lo(e,t){let r="rateLimit",o=e.adapter;return{get:async n=>(await o.findMany({model:r,where:[{field:"key",value:n}]}))[0],set:async(n,i,s)=>{try{s?await o.updateMany({model:t??"rateLimit",where:[{field:"key",value:n}],update:{count:i.count,lastRequest:i.lastRequest}}):await o.create({model:t??"rateLimit",data:{key:n,count:i.count,lastRequest:i.lastRequest}})}catch(c){e.logger.error("Error setting rate limit",c)}}}}var sr=new Map;function uo(e){return e.options.rateLimit?.customStorage?e.options.rateLimit.customStorage:e.rateLimit.storage==="secondary-storage"?{get:async r=>{let o=await e.options.secondaryStorage?.get(r);return o?JSON.parse(o):void 0},set:async(r,o)=>{await e.options.secondaryStorage?.set?.(r,JSON.stringify(o))}}:e.rateLimit.storage==="memory"?{async get(r){return sr.get(r)},async set(r,o,n){sr.set(r,o)}}:lo(e,e.rateLimit.modelName)}async function ar(e,t){if(!t.rateLimit.enabled)return;let r=t.baseURL,o=e.url.replace(r,"").split("?")[0],n=t.rateLimit.window,i=t.rateLimit.max,s=ir(e,t.options)+o,a=po().find(p=>p.pathMatcher(o));a&&(n=a.window,i=a.max);for(let p of t.options.plugins||[])if(p.rateLimit){let l=p.rateLimit.find(b=>b.pathMatcher(o));if(l){n=l.window,i=l.max;break}}if(t.rateLimit.customRules){let p=Object.keys(t.rateLimit.customRules).find(l=>l.includes("*")?me(l)(o):l===o);if(p){let l=t.rateLimit.customRules[p],b=typeof l=="function"?await l(e):l;b&&(n=b.window,i=b.max)}}let d=uo(t),u=await d.get(s),h=Date.now();if(!u)await d.set(s,{key:s,count:1,lastRequest:h});else{let p=h-u.lastRequest;if(so(i,n,u)){let l=co(u.lastRequest,n);return ao(l)}else p>n*1e3?await d.set(s,{...u,count:1,lastRequest:h},!0):await d.set(s,{...u,count:u.count+1,lastRequest:h},!0)}}function po(){return[{pathMatcher(t){return t.startsWith("/sign-in")||t.startsWith("/sign-up")||t.startsWith("/change-password")||t.startsWith("/change-email")},window:10,max:3}]}var Ha=require("defu");var Ae=require("better-call");function cr(e,t){let r=t.plugins?.reduce((c,a)=>({...c,...a.endpoints}),{}),o=t.plugins?.map(c=>c.middlewares?.map(a=>{let d=async u=>a.middleware({...u,context:{...e,...u.context}});return d.path=a.path,d.options=a.middleware.options,d.headers=a.middleware.headers,{path:a.path,middleware:d}})).filter(c=>c!==void 0).flat()||[],i={...{signInSocial:qe,callbackOAuth:Fe,getSession:ye(),signOut:He,signUpEmail:rt(),signInEmail:ze,forgetPassword:Ge,resetPassword:Qe,verifyEmail:Me,sendVerificationEmail:Ve,changeEmail:Xe,changePassword:Je,setPassword:Ke,updateUser:Ze(),deleteUser:Ye,forgetPasswordCallback:We,listSessions:je(),revokeSession:Ne,revokeSessions:$e,revokeOtherSessions:Be,linkSocialAccount:it,listUserAccounts:nt,deleteUserCallback:Ee},...r,ok:tt,error:et},s={};for(let[c,a]of Object.entries(i))s[c]=async(d={})=>{a.headers=new Headers;let u={setHeader(m,f){a.headers.set(m,f)},setCookie(m,f,S){(0,O.setCookie)(a.headers,m,f,S)},getCookie(m,f){let w=d.headers?.get("cookie");return(0,O.getCookie)(w||"",m,f)},getSignedCookie(m,f,S){let w=d.headers;return w?(0,O.getSignedCookie)(w,f,m,S):null},async setSignedCookie(m,f,S,w){await(0,O.setSignedCookie)(a.headers,m,f,S,w)},redirect(m){return a.headers.set("Location",m),new O.APIError("FOUND")},responseHeader:a.headers},h=await e,p=null,l={...u,...d,path:a.path,context:{...h,...d.context,session:null,setNewSession:function(m){this.newSession=m,p=m}}},b=t.plugins||[],E=b.map(m=>{if(m.hooks?.before)return m.hooks.before}).filter(m=>m!==void 0).flat(),L=b.map(m=>{if(m.hooks?.after)return m.hooks.after}).filter(m=>m!==void 0).flat();t.hooks?.before&&E.push({matcher:()=>!0,handler:t.hooks.before}),t.hooks?.after&&L.push({matcher:()=>!0,handler:t.hooks.after});for(let m of E){if(!m.matcher(l))continue;let f=await m.handler(l);if(f&&"context"in f){l={...l,...f.context};continue}if(f)return f}let M;try{M=await a(l),p&&(l.context.newSession=p)}catch(m){if(p&&(l.context.newSession=p),m instanceof O.APIError){if(!L?.length)throw m.headers=a.headers,m;l.context.returned=m,l.context.returned.headers=a.headers;for(let f of L||[])if(f.matcher(l))try{let w=await f.handler(l);w&&"response"in w&&(l.context.returned=w.response)}catch(w){if(w instanceof O.APIError){l.context.returned=w;continue}throw w}if(l.context.returned instanceof O.APIError)throw l.context.returned.headers=a.headers,l.context.returned;return l.context.returned}throw m}l.context.returned=M,l.responseHeader=a.headers;for(let m of L)if(m.matcher(l))try{let S=await m.handler(l);if(S)if("responseHeader"in S){let w=S.responseHeader;l.responseHeader=w}else l.context.returned=S}catch(S){if(S instanceof O.APIError){l.context.returned=S;continue}throw S}let C=l.context.returned;if(C instanceof Response&&a.headers.forEach((m,f)=>{f==="set-cookie"?C.headers.append(f,m):C.headers.set(f,m)}),C instanceof O.APIError)throw C.headers=a.headers,C;return C},s[c].path=a.path,s[c].method=a.method,s[c].options=a.options,s[c].headers=a.headers;return{api:s,middlewares:o}}var mo=(e,t)=>{let{api:r,middlewares:o}=cr(e,t),n=new URL(e.baseURL).pathname;return(0,O.createRouter)(r,{extraContext:e,basePath:n,routerMiddleware:[{path:"/**",middleware:Oe},...o],async onRequest(i){for(let s of e.options.plugins||[])if(s.onRequest){let c=await s.onRequest(i,e);if(c&&"response"in c)return c.response}return ar(i,e)},async onResponse(i){for(let s of e.options.plugins||[])if(s.onResponse){let c=await s.onResponse(i,e);if(c)return c.response}return i},onError(i){if(i instanceof O.APIError&&i.status==="FOUND")return;if(t.onAPIError?.throw)throw i;if(t.onAPIError?.onError){t.onAPIError.onError(i,e);return}let s=t.logger?.level,c=s==="error"||s==="warn"||s==="debug"?$:void 0;if(t.logger?.disabled!==!0){if(i&&typeof i=="object"&&"message"in i&&typeof i.message=="string"&&(i.message.includes("no column")||i.message.includes("column")||i.message.includes("relation")||i.message.includes("table")||i.message.includes("does not exist"))){e.logger?.error(i.message);return}i instanceof O.APIError?(i.status==="INTERNAL_SERVER_ERROR"&&e.logger.error(i.status,i),c?.error(i.message)):e.logger?.error(i&&typeof i=="object"&&"name"in i?i.name:"",i)}}})};0&&(module.exports={APIError,callbackOAuth,changeEmail,changePassword,createAuthEndpoint,createAuthMiddleware,createEmailVerificationToken,deleteUser,deleteUserCallback,error,forgetPassword,forgetPasswordCallback,freshSessionMiddleware,getEndpoints,getSession,getSessionFromCtx,linkSocialAccount,listSessions,listUserAccounts,ok,optionsMiddleware,originCheckMiddleware,resetPassword,revokeOtherSessions,revokeSession,revokeSessions,router,sendVerificationEmail,sendVerificationEmailFn,sessionMiddleware,setPassword,signInEmail,signInSocial,signOut,signUpEmail,updateUser,verifyEmail});