better-auth 0.8.5 → 0.8.6-beta.2
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/adapters/drizzle.cjs +2 -2
- package/dist/adapters/drizzle.js +2 -2
- package/dist/api.cjs +2 -2
- package/dist/api.js +2 -2
- package/dist/index.cjs +2 -2
- package/dist/index.js +2 -2
- package/dist/oauth2.cjs +1 -1
- package/dist/oauth2.js +1 -1
- package/dist/plugins.cjs +4 -4
- package/dist/plugins.js +3 -3
- package/package.json +1 -1
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
"use strict";var
|
|
2
|
-
`)}}),L
|
|
1
|
+
"use strict";var k=Object.defineProperty;var R=Object.getOwnPropertyDescriptor;var q=Object.getOwnPropertyNames;var B=Object.prototype.hasOwnProperty;var M=(e,t)=>{for(var u in t)k(e,u,{get:t[u],enumerable:!0})},V=(e,t,u,f)=>{if(t&&typeof t=="object"||typeof t=="function")for(let y of q(t))!B.call(e,y)&&y!==u&&k(e,y,{get:()=>t[y],enumerable:!(f=R(t,y))||f.enumerable});return e};var U=e=>V(k({},"__esModule",{value:!0}),e);var G={};M(G,{drizzleAdapter:()=>J});module.exports=U(G);var c=require("drizzle-orm");var a=require("zod"),ee=a.z.object({id:a.z.string(),providerId:a.z.string(),accountId:a.z.string(),userId:a.z.string(),accessToken:a.z.string().nullish(),refreshToken:a.z.string().nullish(),idToken:a.z.string().nullish(),expiresAt:a.z.date().nullish(),password:a.z.string().nullish()}),te=a.z.object({id:a.z.string(),email:a.z.string().transform(e=>e.toLowerCase()),emailVerified:a.z.boolean().default(!1),name:a.z.string(),image:a.z.string().nullish(),createdAt:a.z.date().default(new Date),updatedAt:a.z.date().default(new Date)}),re=a.z.object({id:a.z.string(),userId:a.z.string(),expiresAt:a.z.date(),ipAddress:a.z.string().nullish(),userAgent:a.z.string().nullish()}),ne=a.z.object({id:a.z.string(),value:a.z.string(),createdAt:a.z.date(),expiresAt:a.z.date(),identifier:a.z.string()});var P=require("nanoid");var F=Object.create(null),v=e=>globalThis.process?.env||globalThis.Deno?.env.toObject()||globalThis.__env__||(e?F:globalThis),C=new Proxy(F,{get(e,t){return v()[t]??F[t]},has(e,t){let u=v();return t in u||t in F},set(e,t,u){let f=v(!0);return f[t]=u,!0},deleteProperty(e,t){if(!t)return!1;let u=v(!0);return delete u[t],!0},ownKeys(){let e=v(!0);return Object.keys(e)}});function j(e){return e?e!=="false":!1}var K=typeof process<"u"&&process.env&&process.env.NODE_ENV||"";var z=K==="test"||j(C.TEST);var O=e=>{let t=e.plugins?.reduce((i,l)=>{let s=l.schema;if(!s)return i;for(let[r,o]of Object.entries(s))i[r]={fields:{...i[r]?.fields,...o.fields},tableName:o.tableName||r};return i},{}),u=e.rateLimit?.storage==="database",f={rateLimit:{tableName:e.rateLimit?.tableName||"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:y,session:A,account:h,...x}=t||{};return{user:{tableName: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"},...y?.fields,...e.user?.additionalFields},order:1},session:{tableName:e.session?.modelName||"session",fields:{expiresAt:{type:"date",required:!0,fieldName:e.session?.fields?.expiresAt||"expiresAt"},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},...A?.fields,...e.session?.additionalFields},order:2},account:{tableName: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"},expiresAt:{type:"date",required:!1,fieldName:e.account?.fields?.expiresAt||"expiresAt"},password:{type:"string",required:!1,fieldName:e.account?.fields?.password||"password"},...h?.fields},order:3},verification:{tableName: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"}},order:4},...x,...u?f:{}}};var $=require("zod");var b=class extends Error{constructor(t,u){super(t),this.name="BetterAuthError",this.message=t,this.cause=u,this.stack=""}};var D=require("kysely"),I=require("kysely");var S=require("consola"),w=(0,S.createConsola)({formatOptions:{date:!1,colors:!0,compact:!0},defaults:{tag:"Better Auth"}}),L=e=>({log:(...t)=>{!e?.disabled&&w.log("",...t)},error:(...t)=>{!e?.disabled&&w.error("",...t)},warn:(...t)=>{!e?.disabled&&w.warn("",...t)},info:(...t)=>{!e?.disabled&&w.info("",...t)},debug:(...t)=>{!e?.disabled&&w.debug("",...t)},box:(...t)=>{!e?.disabled&&w.box("",...t)},success:(...t)=>{!e?.disabled&&w.success("",...t)},break:(...t)=>{!e?.disabled&&console.log(`
|
|
2
|
+
`)}}),_=L();var W=(e,t,u)=>{let f=O(u);function y(i,l){return l==="id"?l:f[i].fields[l].fieldName||l}function A(i){let l=t.schema||e._.fullSchema;if(!l)throw new b("Drizzle adapter failed to initialize. Schema not found. Please provide a schema object in the adapter options object.");let s=h(i),r=l[s];if(!r)throw new b(`[# Drizzle Adapter]: The model "${i}" was not found in the schema object. Please pass the schema directly to the adapter options.`);return r}let h=i=>f[i].tableName!==i?f[i].tableName:t.usePlural?`${i}s`:i,x=t?.generateId!==!1;return{getSchema:A,transformInput(i,l){let s=i.id&&x?{id:t?.generateId?t.generateId():i.id}:{};for(let r in i){let o=f[l].fields[r];o&&(s[o.fieldName||r]=i[r])}return s},transformOutput(i,l,s=[]){if(!i)return null;let r=i.id||i._id?s.length===0||s.includes("id")?{id:i.id}:{}:{},o=f[l].fields;for(let d in o){if(s.length&&!s.includes(d))continue;let p=o[d];p&&(r[d]=i[p.fieldName||d])}return r},convertWhereClause(i,l){let s=A(l);if(!i)return[];if(i.length===1){let n=i[0];if(!n)return[];let m=y(l,n.field);if(!s[m])throw new b(`The field "${n.field}" does not exist in the schema for the model "${l}". Please update your schema.`);if(n.operator==="in"){if(!Array.isArray(n.value))throw new b(`The value for the field "${n.field}" must be an array when using the "in" operator.`);return[(0,c.inArray)(s[m],n.value)]}return n.operator==="contains"?[(0,c.like)(s[m],`%${n.value}%`)]:n.operator==="starts_with"?[(0,c.like)(s[m],`${n.value}%`)]:n.operator==="ends_with"?[(0,c.like)(s[m],`%${n.value}`)]:[(0,c.eq)(s[m],n.value)]}let r=i.filter(n=>n.connector==="AND"||!n.connector),o=i.filter(n=>n.connector==="OR"),d=(0,c.and)(...r.map(n=>{let m=y(l,n.field);if(n.operator==="in"){if(!Array.isArray(n.value))throw new b(`The value for the field "${n.field}" must be an array when using the "in" operator.`);return(0,c.inArray)(s[m],n.value)}return(0,c.eq)(s[m],n.value)})),p=(0,c.or)(...o.map(n=>{let m=y(l,n.field);return(0,c.eq)(s[m],n.value)})),g=[];return r.length&&g.push(d),o.length&&g.push(p),g},withReturning:async(i,l,s)=>{if(t.provider!=="mysql")return(await l.returning())[0];await l;let r=A(h(i));return(await e.select().from(r).where((0,c.eq)(r.id,s.id)))[0]},getField:y,getModelName:h}};function H(e,t,u){if(!e)throw new b("Drizzle adapter failed to initialize. Schema not found. Please provide a schema object in the adapter options object.");for(let f in u)if(!e[f])throw new b(`The field "${f}" does not exist in the "${t}" schema. Please update your drizzle schema or re-generate using "npx @better-auth/cli generate".`)}var J=(e,t)=>u=>{let{transformInput:f,transformOutput:y,convertWhereClause:A,getSchema:h,withReturning:x,getField:i,getModelName:l}=W(e,t,u);return{id:"drizzle",async create(s){let{model:r,data:o}=s,d=f(o,r),p=h(r);H(p,l(r),d);let g=e.insert(p).values(d),n=await x(r,g,d);return y(n,r)},async findOne(s){let{model:r,where:o,select:d}=s,p=h(r),g=A(o,r),n=await e.select().from(p).where(...g);return n.length?y(n[0],r,d):null},async findMany(s){let{model:r,where:o,sortBy:d,limit:p,offset:g}=s,n=h(r),m=o?A(o,r):[],T=d?.direction==="desc"?c.desc:c.asc;return(await e.select().from(n).limit(p||100).offset(g||0).orderBy(T(n[d?.field?i(r,d?.field):"id"])).where(...m)).map(N=>y(N,r))},async update(s){let{model:r,where:o,update:d}=s,p=h(r),g=A(o,r),n=f(d,r),m=e.update(p).set(n).where(...g),T=await x(r,m,n);return y(T,r)},async updateMany(s){let{model:r,where:o,update:d}=s,p=h(r),g=A(o,r),n=f(d,r),T=await e.update(p).set(n).where(...g);return T?T.changes:0},async delete(s){let{model:r,where:o}=s,d=h(r),p=A(o,r);await e.delete(d).where(...p)},async deleteMany(s){let{model:r,where:o}=s,d=h(r),p=A(o,r),n=await e.delete(d).where(...p);return n?n.length:0},options:t}};0&&(module.exports={drizzleAdapter});
|
package/dist/adapters/drizzle.js
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import{and as
|
|
2
|
-
`)}}),V
|
|
1
|
+
import{and as P,asc as C,desc as j,eq as O,inArray as I,like as k,or as K}from"drizzle-orm";import{z as a}from"zod";var H=a.object({id:a.string(),providerId:a.string(),accountId:a.string(),userId:a.string(),accessToken:a.string().nullish(),refreshToken:a.string().nullish(),idToken:a.string().nullish(),expiresAt:a.date().nullish(),password:a.string().nullish()}),J=a.object({id:a.string(),email:a.string().transform(e=>e.toLowerCase()),emailVerified:a.boolean().default(!1),name:a.string(),image:a.string().nullish(),createdAt:a.date().default(new Date),updatedAt:a.date().default(new Date)}),G=a.object({id:a.string(),userId:a.string(),expiresAt:a.date(),ipAddress:a.string().nullish(),userAgent:a.string().nullish()}),Q=a.object({id:a.string(),value:a.string(),createdAt:a.date(),expiresAt:a.date(),identifier:a.string()});import{nanoid as X}from"nanoid";var v=Object.create(null),T=e=>globalThis.process?.env||globalThis.Deno?.env.toObject()||globalThis.__env__||(e?v:globalThis),S=new Proxy(v,{get(e,n){return T()[n]??v[n]},has(e,n){let c=T();return n in c||n in v},set(e,n,c){let f=T(!0);return f[n]=c,!0},deleteProperty(e,n){if(!n)return!1;let c=T(!0);return delete c[n],!0},ownKeys(){let e=T(!0);return Object.keys(e)}});function N(e){return e?e!=="false":!1}var R=typeof process<"u"&&process.env&&process.env.NODE_ENV||"";var q=R==="test"||N(S.TEST);var F=e=>{let n=e.plugins?.reduce((i,l)=>{let s=l.schema;if(!s)return i;for(let[t,o]of Object.entries(s))i[t]={fields:{...i[t]?.fields,...o.fields},tableName:o.tableName||t};return i},{}),c=e.rateLimit?.storage==="database",f={rateLimit:{tableName:e.rateLimit?.tableName||"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:h,session:g,account:m,...w}=n||{};return{user:{tableName: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"},...h?.fields,...e.user?.additionalFields},order:1},session:{tableName:e.session?.modelName||"session",fields:{expiresAt:{type:"date",required:!0,fieldName:e.session?.fields?.expiresAt||"expiresAt"},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},...g?.fields,...e.session?.additionalFields},order:2},account:{tableName: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"},expiresAt:{type:"date",required:!1,fieldName:e.account?.fields?.expiresAt||"expiresAt"},password:{type:"string",required:!1,fieldName:e.account?.fields?.password||"password"},...m?.fields},order:3},verification:{tableName: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"}},order:4},...w,...c?f:{}}};import{z as ve}from"zod";var A=class extends Error{constructor(n,c){super(n),this.name="BetterAuthError",this.message=n,this.cause=c,this.stack=""}};import{Kysely as Ie,MssqlDialect as De}from"kysely";import{MysqlDialect as Ne,PostgresDialect as Re,SqliteDialect as qe}from"kysely";import{createConsola as M}from"consola";var b=M({formatOptions:{date:!1,colors:!0,compact:!0},defaults:{tag:"Better Auth"}}),V=e=>({log:(...n)=>{!e?.disabled&&b.log("",...n)},error:(...n)=>{!e?.disabled&&b.error("",...n)},warn:(...n)=>{!e?.disabled&&b.warn("",...n)},info:(...n)=>{!e?.disabled&&b.info("",...n)},debug:(...n)=>{!e?.disabled&&b.debug("",...n)},box:(...n)=>{!e?.disabled&&b.box("",...n)},success:(...n)=>{!e?.disabled&&b.success("",...n)},break:(...n)=>{!e?.disabled&&console.log(`
|
|
2
|
+
`)}}),U=V();var z=(e,n,c)=>{let f=F(c);function h(i,l){return l==="id"?l:f[i].fields[l].fieldName||l}function g(i){let l=n.schema||e._.fullSchema;if(!l)throw new A("Drizzle adapter failed to initialize. Schema not found. Please provide a schema object in the adapter options object.");let s=m(i),t=l[s];if(!t)throw new A(`[# Drizzle Adapter]: The model "${i}" was not found in the schema object. Please pass the schema directly to the adapter options.`);return t}let m=i=>f[i].tableName!==i?f[i].tableName:n.usePlural?`${i}s`:i,w=n?.generateId!==!1;return{getSchema:g,transformInput(i,l){let s=i.id&&w?{id:n?.generateId?n.generateId():i.id}:{};for(let t in i){let o=f[l].fields[t];o&&(s[o.fieldName||t]=i[t])}return s},transformOutput(i,l,s=[]){if(!i)return null;let t=i.id||i._id?s.length===0||s.includes("id")?{id:i.id}:{}:{},o=f[l].fields;for(let d in o){if(s.length&&!s.includes(d))continue;let u=o[d];u&&(t[d]=i[u.fieldName||d])}return t},convertWhereClause(i,l){let s=g(l);if(!i)return[];if(i.length===1){let r=i[0];if(!r)return[];let p=h(l,r.field);if(!s[p])throw new A(`The field "${r.field}" does not exist in the schema for the model "${l}". Please update your schema.`);if(r.operator==="in"){if(!Array.isArray(r.value))throw new A(`The value for the field "${r.field}" must be an array when using the "in" operator.`);return[I(s[p],r.value)]}return r.operator==="contains"?[k(s[p],`%${r.value}%`)]:r.operator==="starts_with"?[k(s[p],`${r.value}%`)]:r.operator==="ends_with"?[k(s[p],`%${r.value}`)]:[O(s[p],r.value)]}let t=i.filter(r=>r.connector==="AND"||!r.connector),o=i.filter(r=>r.connector==="OR"),d=P(...t.map(r=>{let p=h(l,r.field);if(r.operator==="in"){if(!Array.isArray(r.value))throw new A(`The value for the field "${r.field}" must be an array when using the "in" operator.`);return I(s[p],r.value)}return O(s[p],r.value)})),u=K(...o.map(r=>{let p=h(l,r.field);return O(s[p],r.value)})),y=[];return t.length&&y.push(d),o.length&&y.push(u),y},withReturning:async(i,l,s)=>{if(n.provider!=="mysql")return(await l.returning())[0];await l;let t=g(m(i));return(await e.select().from(t).where(O(t.id,s.id)))[0]},getField:h,getModelName:m}};function $(e,n,c){if(!e)throw new A("Drizzle adapter failed to initialize. Schema not found. Please provide a schema object in the adapter options object.");for(let f in c)if(!e[f])throw new A(`The field "${f}" does not exist in the "${n}" schema. Please update your drizzle schema or re-generate using "npx @better-auth/cli generate".`)}var mt=(e,n)=>c=>{let{transformInput:f,transformOutput:h,convertWhereClause:g,getSchema:m,withReturning:w,getField:i,getModelName:l}=z(e,n,c);return{id:"drizzle",async create(s){let{model:t,data:o}=s,d=f(o,t),u=m(t);$(u,l(t),d);let y=e.insert(u).values(d),r=await w(t,y,d);return h(r,t)},async findOne(s){let{model:t,where:o,select:d}=s,u=m(t),y=g(o,t),r=await e.select().from(u).where(...y);return r.length?h(r[0],t,d):null},async findMany(s){let{model:t,where:o,sortBy:d,limit:u,offset:y}=s,r=m(t),p=o?g(o,t):[],x=d?.direction==="desc"?j:C;return(await e.select().from(r).limit(u||100).offset(y||0).orderBy(x(r[d?.field?i(t,d?.field):"id"])).where(...p)).map(D=>h(D,t))},async update(s){let{model:t,where:o,update:d}=s,u=m(t),y=g(o,t),r=f(d,t),p=e.update(u).set(r).where(...y),x=await w(t,p,r);return h(x,t)},async updateMany(s){let{model:t,where:o,update:d}=s,u=m(t),y=g(o,t),r=f(d,t),x=await e.update(u).set(r).where(...y);return x?x.changes:0},async delete(s){let{model:t,where:o}=s,d=m(t),u=g(o,t);await e.delete(d).where(...u)},async deleteMany(s){let{model:t,where:o}=s,d=m(t),u=g(o,t),r=await e.delete(d).where(...u);return r?r.length:0},options:n}};export{mt as drizzleAdapter};
|
package/dist/api.cjs
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
"use strict";var pe=Object.defineProperty;var jt=Object.getOwnPropertyDescriptor;var qt=Object.getOwnPropertyNames;var Nt=Object.prototype.hasOwnProperty;var Ft=(e,t)=>{for(var r in t)pe(e,r,{get:t[r],enumerable:!0})},Ht=(e,t,r,o)=>{if(t&&typeof t=="object"||typeof t=="function")for(let n of qt(t))!Nt.call(e,n)&&n!==r&&pe(e,n,{get:()=>t[n],enumerable:!(o=jt(t,n))||o.enumerable});return e};var Mt=e=>Ht(pe({},"__esModule",{value:!0}),e);var lr={};Ft(lr,{APIError:()=>$t.APIError,callbackOAuth:()=>xe,changeEmail:()=>De,changePassword:()=>Le,createAuthEndpoint:()=>p,createAuthMiddleware:()=>J,createEmailVerificationToken:()=>C,deleteUser:()=>Be,error:()=>Ve,forgetPassword:()=>Pe,forgetPasswordCallback:()=>Se,getEndpoints:()=>zt,getSession:()=>ae,getSessionFromCtx:()=>K,linkSocialAccount:()=>Ne,listSessions:()=>ye,listUserAccounts:()=>qe,ok:()=>ze,optionsMiddleware:()=>me,originCheckMiddleware:()=>he,resetPassword:()=>Oe,revokeOtherSessions:()=>Re,revokeSession:()=>Ae,revokeSessions:()=>ke,router:()=>ur,sendVerificationEmail:()=>Ue,sessionMiddleware:()=>P,setPassword:()=>Ce,signInEmail:()=>_e,signInSocial:()=>Ee,signOut:()=>Te,signUpEmail:()=>$e,updateUser:()=>Ie,verifyEmail:()=>ve});module.exports=Mt(lr);var j=require("better-call");var Ke=require("better-call");var q=require("better-call"),me=(0,q.createMiddleware)(async()=>({})),J=(0,q.createMiddlewareCreator)({use:[me,(0,q.createMiddleware)(async()=>({}))]}),p=(0,q.createEndpointCreator)({use:[me]});var M={isAction:!1};var Fe=require("nanoid"),He=e=>(0,Fe.nanoid)(e);var ge=require("better-call"),re=require("oslo/oauth2"),D=require("zod");var te=Object.create(null),W=e=>globalThis.process?.env||globalThis.Deno?.env.toObject()||globalThis.__env__||(e?te:globalThis),Me=new Proxy(te,{get(e,t){return W()[t]??te[t]},has(e,t){let r=W();return t in r||t in te},set(e,t,r){let o=W(!0);return o[t]=r,!0},deleteProperty(e,t){if(!t)return!1;let r=W(!0);return delete r[t],!0},ownKeys(){let e=W(!0);return Object.keys(e)}});function Gt(e){return e?e!=="false":!1}var fe=typeof process<"u"&&process.env&&process.env.NODE_ENV||"";var Ge=fe==="dev"||fe==="development",Qe=fe==="test"||Gt(Me.TEST);var N=class extends Error{constructor(t,r){super(t),this.name="BetterAuthError",this.message=t,this.cause=r,this.stack=""}};function Ze(e){try{return new URL(e).origin}catch{return null}}async function oe(e,t){let r=e.body?.callbackURL||(e.query?.currentURL?Ze(e.query?.currentURL):"")||e.context.options.baseURL;if(!r)throw new ge.APIError("BAD_REQUEST",{message:"callbackURL is required"});let o=(0,re.generateCodeVerifier)(),n=(0,re.generateState)(),i=JSON.stringify({callbackURL:r,codeVerifier:o,errorURL:e.body?.errorCallbackURL||e.query?.currentURL,link:t,expiresAt:Date.now()+10*60*1e3}),s=new Date;s.setMinutes(s.getMinutes()+10);let a=await e.context.internalAdapter.createVerificationValue({value:i,identifier:n,expiresAt:s});if(!a)throw m.error("Unable to create verification. Make sure the database adapter is properly working and there is a verification table in the database"),new ge.APIError("INTERNAL_SERVER_ERROR",{message:"Unable to create verification"});return{state:a.identifier,codeVerifier:o}}async function Je(e){let t=e.query.state||e.body.state
|
|
1
|
+
"use strict";var pe=Object.defineProperty;var jt=Object.getOwnPropertyDescriptor;var qt=Object.getOwnPropertyNames;var Nt=Object.prototype.hasOwnProperty;var Ft=(e,t)=>{for(var r in t)pe(e,r,{get:t[r],enumerable:!0})},Ht=(e,t,r,o)=>{if(t&&typeof t=="object"||typeof t=="function")for(let n of qt(t))!Nt.call(e,n)&&n!==r&&pe(e,n,{get:()=>t[n],enumerable:!(o=jt(t,n))||o.enumerable});return e};var Mt=e=>Ht(pe({},"__esModule",{value:!0}),e);var lr={};Ft(lr,{APIError:()=>$t.APIError,callbackOAuth:()=>xe,changeEmail:()=>De,changePassword:()=>Le,createAuthEndpoint:()=>p,createAuthMiddleware:()=>J,createEmailVerificationToken:()=>C,deleteUser:()=>Be,error:()=>Ve,forgetPassword:()=>Pe,forgetPasswordCallback:()=>Se,getEndpoints:()=>zt,getSession:()=>ae,getSessionFromCtx:()=>K,linkSocialAccount:()=>Ne,listSessions:()=>ye,listUserAccounts:()=>qe,ok:()=>ze,optionsMiddleware:()=>me,originCheckMiddleware:()=>he,resetPassword:()=>Oe,revokeOtherSessions:()=>Re,revokeSession:()=>Ae,revokeSessions:()=>ke,router:()=>ur,sendVerificationEmail:()=>Ue,sessionMiddleware:()=>P,setPassword:()=>Ce,signInEmail:()=>_e,signInSocial:()=>Ee,signOut:()=>Te,signUpEmail:()=>$e,updateUser:()=>Ie,verifyEmail:()=>ve});module.exports=Mt(lr);var j=require("better-call");var Ke=require("better-call");var q=require("better-call"),me=(0,q.createMiddleware)(async()=>({})),J=(0,q.createMiddlewareCreator)({use:[me,(0,q.createMiddleware)(async()=>({}))]}),p=(0,q.createEndpointCreator)({use:[me]});var M={isAction:!1};var Fe=require("nanoid"),He=e=>(0,Fe.nanoid)(e);var ge=require("better-call"),re=require("oslo/oauth2"),D=require("zod");var te=Object.create(null),W=e=>globalThis.process?.env||globalThis.Deno?.env.toObject()||globalThis.__env__||(e?te:globalThis),Me=new Proxy(te,{get(e,t){return W()[t]??te[t]},has(e,t){let r=W();return t in r||t in te},set(e,t,r){let o=W(!0);return o[t]=r,!0},deleteProperty(e,t){if(!t)return!1;let r=W(!0);return delete r[t],!0},ownKeys(){let e=W(!0);return Object.keys(e)}});function Gt(e){return e?e!=="false":!1}var fe=typeof process<"u"&&process.env&&process.env.NODE_ENV||"";var Ge=fe==="dev"||fe==="development",Qe=fe==="test"||Gt(Me.TEST);var N=class extends Error{constructor(t,r){super(t),this.name="BetterAuthError",this.message=t,this.cause=r,this.stack=""}};function Ze(e){try{return new URL(e).origin}catch{return null}}async function oe(e,t){let r=e.body?.callbackURL||(e.query?.currentURL?Ze(e.query?.currentURL):"")||e.context.options.baseURL;if(!r)throw new ge.APIError("BAD_REQUEST",{message:"callbackURL is required"});let o=(0,re.generateCodeVerifier)(),n=(0,re.generateState)(),i=JSON.stringify({callbackURL:r,codeVerifier:o,errorURL:e.body?.errorCallbackURL||e.query?.currentURL,link:t,expiresAt:Date.now()+10*60*1e3}),s=new Date;s.setMinutes(s.getMinutes()+10);let a=await e.context.internalAdapter.createVerificationValue({value:i,identifier:n,expiresAt:s});if(!a)throw m.error("Unable to create verification. Make sure the database adapter is properly working and there is a verification table in the database"),new ge.APIError("INTERNAL_SERVER_ERROR",{message:"Unable to create verification"});return{state:a.identifier,codeVerifier:o}}async function Je(e){let t=e.query.state||e.body.state,r=await e.context.internalAdapter.findVerificationValue(t);if(!r)throw m.error("State Mismatch. Verification not found",{state:t}),e.redirect(`${e.context.baseURL}/error?error=please_restart_the_process`);let o=D.z.object({callbackURL:D.z.string(),codeVerifier:D.z.string(),errorURL:D.z.string().optional(),expiresAt:D.z.number(),link:D.z.object({email:D.z.string(),userId:D.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),m.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 We=require("consola"),F=(0,We.createConsola)({formatOptions:{date:!1,colors:!0,compact:!0},defaults:{tag:"Better Auth"}}),Qt=e=>({log:(...t)=>{!e?.disabled&&F.log("",...t)},error:(...t)=>{!e?.disabled&&F.error("",...t)},warn:(...t)=>{!e?.disabled&&F.warn("",...t)},info:(...t)=>{!e?.disabled&&F.info("",...t)},debug:(...t)=>{!e?.disabled&&F.debug("",...t)},box:(...t)=>{!e?.disabled&&F.box("",...t)},success:(...t)=>{!e?.disabled&&F.success("",...t)},break:(...t)=>{!e?.disabled&&console.log(`
|
|
2
2
|
`)}}),m=Qt();var he=J(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,a=r?.currentURL,d=o.trustedOrigins,c=e.headers?.has("cookie"),u=(h,l)=>l.includes("*")?new RegExp("^"+l.replace(/\*/g,"[^/]+").replace(/\./g,"\\.")+"$").test(h):h.startsWith(l),f=(h,l)=>{if(!h)return;if(!d.some(R=>u(h,R)||h?.startsWith("/")&&l!=="origin"&&!h.includes(":")))throw m.error(`Invalid ${l}: ${h}`),m.info(`If it's a valid URL, please add ${h} to trustedOrigins in your auth config
|
|
3
3
|
`,`Current list of trustedOrigins: ${d}`),new Ke.APIError("FORBIDDEN",{message:`Invalid ${l}`})};c&&!e.context.options.advanced?.disableCSRFCheck&&f(n,"origin"),i&&f(i,"callbackURL"),s&&f(s,"redirectURL"),a&&f(a,"currentURL")});var v=require("better-call"),A=require("zod");var Wt=require("oslo"),Ye=require("oslo/encoding");var ne=require("oslo/crypto");async function Zt({value:e,secret:t}){return new ne.HMAC("SHA-256").sign(new TextEncoder().encode(t),new TextEncoder().encode(e)).then(o=>Buffer.from(o).toString("base64"))}function Jt({value:e,signature:t,secret:r}){return new ne.HMAC("SHA-256").verify(new TextEncoder().encode(r),Buffer.from(t,"base64"),new TextEncoder().encode(e))}var ie={sign:Zt,verify:Jt};var L=(e,t="ms")=>new Date(Date.now()+(t==="sec"?e*1e3:e));async function T(e,t,r,o){let n=e.context.authCookies.sessionToken.options;n.maxAge=r?void 0:e.context.sessionConfig.expiresIn,await e.setSignedCookie(e.context.authCookies.sessionToken.name,t.session.id,e.context.secret,{...n,...o}),r&&await e.setSignedCookie(e.context.authCookies.dontRememberToken.name,"true",e.context.secret,e.context.authCookies.dontRememberToken.options),e.context.options.session?.cookieCache?.enabled&&e.setCookie(e.context.authCookies.sessionData.name,JSON.stringify(Ye.base64url.encode(new TextEncoder().encode(JSON.stringify({session:t,expiresAt:L(e.context.authCookies.sessionData.options.maxAge||60,"sec").getTime(),signature:await ie.sign({value:JSON.stringify(t),secret:e.context.secret})})))),e.context.authCookies.sessionData.options),e.context.options.secondaryStorage&&await e.context.secondaryStorage?.set(t.session.id,JSON.stringify({user:t.user,session:t.session}),t.session.expiresAt.getTime()-Date.now())}function V(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 nt=require("@better-fetch/fetch"),it=require("better-call"),G=require("jose"),st=require("oslo/jwt");var Xe=require("oslo/crypto"),et=require("oslo/encoding");async function tt(e){let t=await(0,Xe.sha256)(new TextEncoder().encode(e));return et.base64url.encode(new Uint8Array(t),{includePadding:!1})}function rt(e){return{tokenType:e.token_type,accessToken:e.access_token,refreshToken:e.refresh_token,accessTokenExpiresAt:e.expires_in?L(e.expires_in,"sec"):void 0,scopes:e?.scope?typeof e.scope=="string"?e.scope.split(" "):e.scope:[],idToken:e.id_token}}async function y({id:e,options:t,authorizationEndpoint:r,state:o,codeVerifier:n,scopes:i,claims:s,redirectURI: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||a),n){let c=await tt(n);d.searchParams.set("code_challenge_method","S256"),d.searchParams.set("code_challenge",c)}if(s){let c=s.reduce((u,f)=>(u[f]=null,u),{});d.searchParams.set("claims",JSON.stringify({id_token:{email:null,email_verified:null,...c}}))}return d}var ot=require("@better-fetch/fetch");async function w({code:e,codeVerifier:t,redirectURI:r,options:o,tokenEndpoint:n,authentication:i}){let s=new URLSearchParams,a={"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 f=btoa(`${o.clientId}:${o.clientSecret}`);a.authorization=`Basic ${f}`}else s.set("client_id",o.clientId),s.set("client_secret",o.clientSecret);let{data:d,error:c}=await(0,ot.betterFetch)(n,{method:"POST",body:s,headers:a});if(c)throw c;return rt(d)}var at=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=${n||e.redirectURI}&scope=${i.join(" ")}&state=${r}&response_mode=form_post`)},validateAuthorizationCode:async({code:r,codeVerifier:o,redirectURI:n})=>w({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,G.decodeProtectedHeader)(r),{kid:i,alg:s}=n;if(!i||!s)return!1;let a=await Kt(i),{payload:d}=await(0,G.jwtVerify)(r,a,{algorithms:[s],issuer:"https://appleid.apple.com",audience:e.clientId,maxTokenAge:"1h"});return["email_verified","is_private_email"].forEach(c=>{d[c]!==void 0&&(d[c]=!!d[c])}),o&&d.nonce!==o?!1:!!d},async getUserInfo(r){if(!r.idToken)return null;let o=(0,st.parseJWT)(r.idToken)?.payload;if(!o)return null;let n=o.user?`${o.user.name.firstName} ${o.user.name.lastName}`:o.email;return{user:{id:o.sub,name:n,emailVerified:!1,email:o.email},data:o}}}},Kt=async e=>{let t="https://appleid.apple.com",r="/auth/keys",{data:o}=await(0,nt.betterFetch)(`${t}${r}`);if(!o?.keys)throw new it.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,G.importJWK)(n,n.alg)};var dt=require("@better-fetch/fetch");var ct=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}`)},validateAuthorizationCode:async({code:t,redirectURI:r})=>w({code:t,redirectURI:e.redirectURI||r,options:e,tokenEndpoint:"https://discord.com/api/oauth2/token"}),async getUserInfo(t){let{data:r,error:o}=await(0,dt.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}`}return{user:{id:r.id,name:r.display_name||r.username||"",email:r.email,emailVerified:r.verified,image:r.image_url},data:r}}});var ut=require("@better-fetch/fetch");var lt=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 y({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})=>w({code:t,redirectURI:e.redirectURI||r,options:e,tokenEndpoint:"https://graph.facebook.com/oauth/access_token"}),async getUserInfo(t){let{data:r,error:o}=await(0,ut.betterFetch)("https://graph.facebook.com/me?fields=id,name,email,picture",{auth:{type:"Bearer",token:t.accessToken}});return o?null:{user:{id:r.id,name:r.name,email:r.email,image:r.picture.data.url,emailVerified:r.email_verified},data:r}}});var we=require("@better-fetch/fetch");var pt=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),y({id:"github",options:e,authorizationEndpoint:"https://github.com/login/oauth/authorize",scopes:s,state:r,redirectURI:i})},validateAuthorizationCode:async({code:r,redirectURI:o})=>w({code:r,redirectURI:e.redirectURI||o,options:e,tokenEndpoint:t}),async getUserInfo(r){let{data:o,error:n}=await(0,we.betterFetch)("https://api.github.com/user",{headers:{"User-Agent":"better-auth",authorization:`Bearer ${r.accessToken}`}});if(n)return null;let i=!1;if(!o.email){let{data:s,error:a}=await(0,we.betterFetch)("https://api.github.com/user/emails",{headers:{authorization:`Bearer ${r.accessToken}`,"User-Agent":"better-auth"}});a||(o.email=(s.find(d=>d.primary)??s[0])?.email,i=s.find(d=>d.email===o.email)?.verified??!1)}return{user:{id:o.id.toString(),name:o.name||o.login,email:o.email,image:o.avatar_url,emailVerified:i},data:o}}}};var mt=require("oslo/jwt");var ft=require("@better-fetch/fetch"),gt=e=>({id:"google",name:"Google",async createAuthorizationURL({state:t,scopes:r,codeVerifier:o,redirectURI:n}){if(!e.clientId||!e.clientSecret)throw m.error("Client Id and Client Secret is required for Google. Make sure to provide them in the options."),new N("CLIENT_ID_AND_SECRET_REQUIRED");if(!o)throw new N("codeVerifier is required for Google");let i=r||["email","profile","openid"];e.scope&&i.push(...e.scope);let s=await y({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})=>w({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(0,ft.betterFetch)(o);return n?n.aud===e.clientId&&n.iss==="https://accounts.google.com":!1},async getUserInfo(t){if(!t.idToken)return null;let r=(0,mt.parseJWT)(t.idToken)?.payload;return{user:{id:r.sub,name:r.name,email:r.email,image:r.picture,emailVerified:r.email_verified},data:r}}});var ht=require("@better-fetch/fetch"),wt=require("oslo/jwt");var bt=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),y({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 w({code:n,codeVerifier:i,redirectURI:e.redirectURI||s,options:e,tokenEndpoint:o})},async getUserInfo(n){if(!n.idToken)return null;let i=(0,wt.parseJWT)(n.idToken)?.payload,s=e.profilePhotoSize||48;return await(0,ht.betterFetch)(`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 c=await a.response.clone().arrayBuffer(),u=Buffer.from(c).toString("base64");i.picture=`data:image/jpeg;base64, ${u}`}catch(d){m.error(d)}}}),{user:{id:i.sub,name:i.name,email:i.email,image:i.picture,emailVerified:!0},data:i}}}};var yt=require("@better-fetch/fetch");var At=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),y({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})=>w({code:t,codeVerifier:r,redirectURI:e.redirectURI||o,options:e,tokenEndpoint:"https://accounts.spotify.com/api/token"}),async getUserInfo(t){let{data:r,error:o}=await(0,yt.betterFetch)("https://api.spotify.com/v1/me",{method:"GET",headers:{Authorization:`Bearer ${t.accessToken}`}});return o?null:{user:{id:r.id,name:r.display_name,email:r.email,image:r.images[0]?.url,emailVerified:!1},data:r}}});var _o=require("@better-fetch/fetch");var kt=require("oslo/jwt");var Rt=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),y({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})=>w({code:t,redirectURI:e.redirectURI||r,options:e,tokenEndpoint:"https://id.twitch.tv/oauth2/token"}),async getUserInfo(t){let r=t.idToken;if(!r)return m.error("No idToken found in token"),null;let o=(0,kt.parseJWT)(r)?.payload;return{user:{id:o.sub,name:o.preferred_username,email:o.email,image:o.picture,emailVerified:!1},data:o}}});var Ut=require("@better-fetch/fetch");var vt=e=>({id:"twitter",name:"Twitter",createAuthorizationURL(t){let r=t.scopes||["users.read","tweet.read","offline.access"];return e.scope&&r.push(...e.scope),y({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})=>w({code:t,codeVerifier:r,authentication:"basic",redirectURI:e.redirectURI||o,options:e,tokenEndpoint:"https://api.x.com/2/oauth2/token"}),async getUserInfo(t){let{data:r,error:o}=await(0,Ut.betterFetch)("https://api.x.com/2/users/me?user.fields=profile_image_url",{method:"GET",headers:{Authorization:`Bearer ${t.accessToken}`}});return o?null:{user:{id:r.data.id,name:r.data.name,email:r.data.email||null,image:r.data.profile_image_url,emailVerified:r.data.verified||!1},data:r}}});var Et=require("@better-fetch/fetch");var _t=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 y({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 w({code:r,codeVerifier:o,redirectURI:e.redirectURI||n,options:e,tokenEndpoint:t}),async getUserInfo(r){let{data:o,error:n}=await(0,Et.betterFetch)("https://api.dropboxapi.com/2/users/get_current_account",{method:"POST",headers:{Authorization:`Bearer ${r.accessToken}`}});return n?null:{user:{id:o.account_id,name:o.name?.display_name,email:o.email,emailVerified:o.email_verified||!1,image:o.profile_photo_url},data:o}}}};var xt=require("@better-fetch/fetch");var Tt=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 y({id:"linkedin",options:e,authorizationEndpoint:t,scopes:s,state:o,redirectURI:i})},validateAuthorizationCode:async({code:o,redirectURI:n})=>await w({code:o,redirectURI:e.redirectURI||n,options:e,tokenEndpoint:r}),async getUserInfo(o){let{data:n,error:i}=await(0,xt.betterFetch)("https://api.linkedin.com/v2/userinfo",{method:"GET",headers:{Authorization:`Bearer ${o.accessToken}`}});return i?null:{user:{id:n.sub,name:n.name,email:n.email,emailVerified:n.email_verified||!1,image:n.picture},data:n}}}};var Pt=require("@better-fetch/fetch");var be=(e="")=>e.split("://").map(t=>t.replace(/\/{2,}/g,"/")).join("://"),Yt=e=>{let t=e||"https://gitlab.com";return{authorizationEndpoint:be(`${t}/oauth/authorize`),tokenEndpoint:be(`${t}/oauth/token`),userinfoEndpoint:be(`${t}/api/v4/user`)}},St=e=>{let{authorizationEndpoint:t,tokenEndpoint:r,userinfoEndpoint:o}=Yt(e.issuer),n="gitlab";return{id:n,name:"Gitlab",createAuthorizationURL:async({state:s,scopes:a,codeVerifier:d,redirectURI:c})=>{let u=a||["read_user"];return e.scope&&u.push(...e.scope),await y({id:n,options:e,authorizationEndpoint:t,scopes:u,state:s,redirectURI:c,codeVerifier:d})},validateAuthorizationCode:async({code:s,redirectURI:a,codeVerifier:d})=>w({code:s,redirectURI:e.redirectURI||a,options:e,codeVerifier:d,tokenEndpoint:r}),async getUserInfo(s){let{data:a,error:d}=await(0,Pt.betterFetch)(o,{headers:{authorization:`Bearer ${s.accessToken}`}});return d||a.state!=="active"||a.locked?null:{user:{id:a.id.toString(),name:a.name??a.username,email:a.email,image:a.avatar_url,emailVerified:!0},data:a}}}};var Xt={apple:at,discord:ct,facebook:lt,github:pt,microsoft:bt,google:gt,spotify:At,twitch:Rt,twitter:vt,dropbox:_t,linkedin:Tt,gitlab:St},se=Object.keys(Xt);var It=require("oslo"),de=require("oslo/jwt"),I=require("zod");var $=require("better-call");var z=require("better-call");var Q=require("zod");function Ot(e){try{return JSON.parse(e)}catch{return null}}var ae=()=>p("/get-session",{method:"GET",query:Q.z.optional(Q.z.object({disableCookieCache:Q.z.boolean().optional()})),requireHeaders:!0},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?Ot(Buffer.from(r,"base64").toString()):null;if(o&&!await ie.verify({value:JSON.stringify(o.session),signature:o?.signature,secret:e.context.secret}))return V(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 h=e.context.authCookies.sessionData.name;e.setCookie(h,"",{maxAge:0})}else return e.json(u)}let i=await e.context.internalAdapter.findSession(t);if(!i||i.session.expiresAt<new Date)return V(e),i&&await e.context.internalAdapter.deleteSession(i.session.id),e.json(null);if(n)return e.json(i);let s=e.context.sessionConfig.expiresIn,a=e.context.sessionConfig.updateAge;if(i.session.expiresAt.valueOf()-s*1e3+a*1e3<=Date.now()){let u=await e.context.internalAdapter.updateSession(i.session.id,{expiresAt:L(e.context.sessionConfig.expiresIn,"sec")});if(!u)return V(e),e.json(null,{status:401});let f=(u.expiresAt.valueOf()-Date.now())/1e3;return await T(e,{session:u,user:i.user},!1,{maxAge:f}),e.json({session:u,user:i.user})}return e.json(i)}catch(t){throw e.context.logger.error(t),new z.APIError("INTERNAL_SERVER_ERROR",{message:"internal server error"})}}),K=async e=>{if(e.context.session)return e.context.session;let t=await ae()({...e,_flag:"json",headers:e.headers});return e.context.session=t,t},P=J(async e=>{let t=await K(e);if(!t?.session)throw new z.APIError("UNAUTHORIZED");return{session:t}}),ye=()=>p("/list-sessions",{method:"GET",use:[P],requireHeaders:!0},async e=>{let r=(await e.context.internalAdapter.listSessions(e.context.session.user.id)).filter(o=>o.expiresAt>new Date);return e.json(r)}),Ae=p("/revoke-session",{method:"POST",body:Q.z.object({id:Q.z.string()}),use:[P],requireHeaders:!0},async e=>{let t=e.body.id,r=await e.context.internalAdapter.findSession(t);if(!r)throw new z.APIError("BAD_REQUEST",{message:"Session not found"});if(r.session.userId!==e.context.session.user.id)throw new z.APIError("UNAUTHORIZED");try{await e.context.internalAdapter.deleteSession(t)}catch(o){throw e.context.logger.error(o),new z.APIError("INTERNAL_SERVER_ERROR")}return e.json({status:!0})}),ke=p("/revoke-sessions",{method:"POST",use:[P],requireHeaders:!0},async e=>{try{await e.context.internalAdapter.deleteSessions(e.context.session.user.id)}catch(t){throw e.context.logger.error(t),new z.APIError("INTERNAL_SERVER_ERROR")}return e.json({status:!0})}),Re=p("/revoke-other-sessions",{method:"POST",requireHeaders:!0,use:[P]},async e=>{let t=e.context.session;if(!t.user)throw new z.APIError("UNAUTHORIZED");let n=(await e.context.internalAdapter.listSessions(t.user.id)).filter(i=>i.expiresAt>new Date).filter(i=>i.id!==e.context.session.session.id);return await Promise.all(n.map(i=>e.context.internalAdapter.deleteSession(i.id))),e.json({status:!0})});async function C(e,t,r){return await(0,de.createJWT)("HS256",Buffer.from(e),{email:t.toLowerCase(),updateTo:r},{expiresIn:new It.TimeSpan(1,"h"),issuer:"better-auth",subject:"verify-email",audiences:[t],includeIssuedTimestamp:!0})}var Ue=p("/send-verification-email",{method:"POST",query:I.z.object({currentURL:I.z.string().optional()}).optional(),body:I.z.object({email:I.z.string().email(),callbackURL:I.z.string().optional()})},async e=>{if(!e.context.options.emailVerification?.sendVerificationEmail)throw e.context.logger.error("Verification email isn't enabled."),new $.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 $.APIError("BAD_REQUEST",{message:"User not found"});let o=await C(e.context.secret,t),n=`${e.context.baseURL}/verify-email?token=${o}&callbackURL=${e.body.callbackURL||e.query?.currentURL||"/"}`;return await e.context.options.emailVerification.sendVerificationEmail({user:r.user,url:n,token:o},e.request),e.json({status:!0})}),ve=p("/verify-email",{method:"GET",query:I.z.object({token:I.z.string(),callbackURL:I.z.string().optional()})},async e=>{let{token:t}=e.query,r;try{r=await(0,de.validateJWT)("HS256",Buffer.from(e.context.secret),t)}catch(s){throw e.context.logger.error("Failed to verify email",s),new $.APIError("BAD_REQUEST",{message:"Invalid token"})}let n=I.z.object({email:I.z.string().email(),updateTo:I.z.string().optional()}).parse(r.payload),i=await e.context.internalAdapter.findUserByEmail(n.email);if(!i)throw new $.APIError("BAD_REQUEST",{message:"User not found"});if(n.updateTo){let s=await K(e);if(!s)throw e.query.callbackURL?e.redirect(`${e.query.callbackURL}?error=unauthorized`):new $.APIError("UNAUTHORIZED",{message:"Session not found"});if(s.user.email!==n.email)throw e.query.callbackURL?e.redirect(`${e.query.callbackURL}?error=unauthorized`):new $.APIError("UNAUTHORIZED",{message:"Invalid session"});let a=await e.context.internalAdapter.updateUserByEmail(n.email,{email:n.updateTo});if(await e.context.options.emailVerification?.sendVerificationEmail?.({user:a,url:`${e.context.baseURL}/verify-email?token=${t}`,token:t},e.request),e.query.callbackURL)throw e.redirect(e.query.callbackURL);return e.json({user:a,status:!0})}if(await e.context.internalAdapter.updateUserByEmail(n.email,{emailVerified:!0}),e.context.options.emailVerification?.autoSignInAfterVerification&&!await K(e)){let a=await e.context.internalAdapter.createSession(i.user.id,e.request);if(!a)throw new $.APIError("INTERNAL_SERVER_ERROR",{message:"Failed to create session"});await T(e,{session:a,user:i.user})}if(e.query.callbackURL)throw e.redirect(e.query.callbackURL);return e.json({user:null,status:!0})});async function ce(e,{userInfo:t,account:r,callbackURL:o}){let n=await e.context.internalAdapter.findUserByEmail(t.email.toLowerCase(),{includeAccounts:!0}).catch(a=>{throw m.error(`Better auth was unable to query your database.
|
|
4
4
|
Error: `,a),e.redirect(`${e.context.baseURL}/error?error=internal_server_error`)}),i=n?.user;if(n){let a=n.accounts.find(d=>d.providerId===r.providerId);if(a)await e.context.internalAdapter.updateAccount(a.id,{accessToken:r.accessToken,idToken:r.idToken,refreshToken:r.refreshToken,expiresAt:r.expiresAt});else{if(!e.context.options.account?.accountLinking?.trustedProviders?.includes(r.providerId)&&!t.emailVerified||e.context.options.account?.accountLinking?.enabled===!1)return Ge&&m.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(),id:e.context.uuid(),userId:n.user.id,accessToken:r.accessToken,idToken:r.idToken,refreshToken:r.refreshToken,expiresAt:r.expiresAt})}catch(u){return m.error("Unable to link account",u),{error:"unable to link account",data:null}}}}else try{let a=t.emailVerified||!1;if(i=await e.context.internalAdapter.createOAuthUser({...t,id:e.context.uuid(),emailVerified:a,email:t.email.toLowerCase()},{accessToken:r.accessToken,idToken:r.idToken,refreshToken:r.refreshToken,expiresAt:r.expiresAt,providerId:r.providerId,accountId:t.id.toString()}).then(d=>d?.user),!a&&i&&e.context.options.emailVerification?.sendOnSignUp){let d=await C(e.context.secret,i.email),c=`${e.context.baseURL}/verify-email?token=${d}&callbackURL=${o}`;await e.context.options.emailVerification?.sendVerificationEmail?.({user:i,url:c,token:d},e.request)}}catch(a){return m.error("Unable to create user",a),{error:"unable to create user",data:null}}if(!i)return{error:"unable to create user",data:null};let s=await e.context.internalAdapter.createSession(i.id,e.request);return s?{data:{session:s,user:i},error:null}:{error:"unable to create session",data:null}}var Ee=p("/sign-in/social",{method:"POST",query:A.z.object({currentURL:A.z.string().optional()}).optional(),body:A.z.object({callbackURL:A.z.string().optional(),errorCallbackURL:A.z.string().optional(),provider:A.z.enum(se),idToken:A.z.optional(A.z.object({token:A.z.string(),nonce:A.z.string().optional(),accessToken:A.z.string().optional(),refreshToken:A.z.string().optional(),expiresAt:A.z.number().optional()}))})},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 v.APIError("NOT_FOUND",{message:"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:"Provider does not support id token verification"});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 v.APIError("UNAUTHORIZED",{message:"Invalid id token"});let d=await t.getUserInfo({idToken:i,accessToken:e.body.idToken.accessToken,refreshToken:e.body.idToken.refreshToken});if(!d||!d?.user)throw e.context.logger.error("Failed to get user info",{provider:e.body.provider}),new v.APIError("UNAUTHORIZED",{message:"Failed to get user info"});if(!d.user.email)throw e.context.logger.error("User email not found",{provider:e.body.provider}),new v.APIError("UNAUTHORIZED",{message:"User email not found"});let c=await ce(e,{userInfo:{email:d.user.email,id:d.user.id,name:d.user.name||"",image:d.user.image,emailVerified:d.user.emailVerified||!1},account:{providerId:t.id,accountId:d.user.id,accessToken:e.body.idToken.accessToken}});if(c.error)throw new v.APIError("UNAUTHORIZED",{message:c.error});return await T(e,c.data),e.json({session:c.data.session,user:c.data.user,url:`${e.body.callbackURL||e.query?.currentURL||e.context.options.baseURL}`,redirect:!0})}let{codeVerifier:r,state:o}=await oe(e),n=await t.createAuthorizationURL({state:o,codeVerifier:r,redirectURI:`${e.context.baseURL}/callback/${t.id}`});return e.json({url:n.toString(),redirect:!0})}),_e=p("/sign-in/email",{method:"POST",body:A.z.object({email:A.z.string(),password:A.z.string(),callbackURL:A.z.string().optional(),rememberMe:A.z.boolean().default(!1).optional()})},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(!A.z.string().email().safeParse(t).success)throw new v.APIError("BAD_REQUEST",{message:"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 v.APIError("UNAUTHORIZED",{message:"Invalid email or password"});let i=n.accounts.find(c=>c.providerId==="credential");if(!i)throw e.context.logger.error("Credential account not found",{email:t}),new v.APIError("UNAUTHORIZED",{message:"Invalid email or password"});let s=i?.password;if(!s)throw e.context.logger.error("Password not found",{email:t}),new v.APIError("UNAUTHORIZED",{message:"Unexpected error"});if(!await e.context.password.verify(s,r))throw e.context.logger.error("Invalid password"),new v.APIError("UNAUTHORIZED",{message:"Invalid email or password"});if(e.context.options?.emailAndPassword?.requireEmailVerification&&!n.user.emailVerified){if(!e.context.options?.emailVerification?.sendVerificationEmail)throw m.error("Email verification is required but no email verification handler is provided"),new v.APIError("INTERNAL_SERVER_ERROR",{message:"Email is not verified."});let c=await C(e.context.secret,n.user.email),u=`${e.context.baseURL}/verify-email?token=${c}`;throw await e.context.options.emailVerification.sendVerificationEmail({user:n.user,url:u,token:c},e.request),e.context.logger.error("Email not verified",{email:t}),new v.APIError("FORBIDDEN",{message:"Email is not verified. Check your email for a verification link"})}let d=await e.context.internalAdapter.createSession(n.user.id,e.headers,e.body.rememberMe===!1);if(!d)throw e.context.logger.error("Failed to create session"),new v.APIError("UNAUTHORIZED",{message:"Failed to create session"});return await T(e,{session:d,user:n.user},e.body.rememberMe===!1),e.json({user:n.user,session:d,redirect:!!e.body.callbackURL,url:e.body.callbackURL})});var Y=require("zod");var ue=Y.z.object({code:Y.z.string().optional(),error:Y.z.string().optional(),state:Y.z.string().optional()}),xe=p("/callback/:id",{method:["GET","POST"],body:ue.optional(),query:ue.optional(),metadata:M},async e=>{let t;try{if(e.method==="GET")t=ue.parse(e.query);else if(e.method==="POST")t=ue.parse(e.body);else throw new Error("Unsupported method")}catch(_){throw e.context.logger.error(_),e.redirect(`${e.context.baseURL}/error?error=invalid_callback_request`)}let{code:r,error:o,state:n}=t;if(!n)throw e.context.logger.error("State not found"),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"}`);let i=e.context.socialProviders.find(_=>_.id===e.params.id);if(!i)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:s,callbackURL:a,link:d,errorURL:c}=await Je(e),u;try{u=await i.validateAuthorizationCode({code:r,codeVerifier:s,redirectURI:`${e.context.baseURL}/callback/${i.id}`})}catch(_){throw e.context.logger.error(_),e.redirect(`${e.context.baseURL}/error?error=please_restart_the_process`)}let f=await i.getUserInfo(u).then(_=>_?.user),l={id:He(),...f};function b(_){let x=c||a||`${e.context.baseURL}/error`;throw x.includes("?")?x=`${x}&error=${_}`:x=`${x}?error=${_}`,e.redirect(x)}if(!f)return m.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 m.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:i.id,accountId:f.id}))return b("unable_to_link_account");let x;try{x=new URL(a).toString()}catch{x=a}throw e.redirect(x)}let R=await ce(e,{userInfo:{email:l.email,id:l.id,name:l.name||"",image:l.image,emailVerified:l.emailVerified||!1},account:{providerId:i.id,accountId:f.id,accessToken:u.accessToken,refreshToken:u.refreshToken,expiresAt:u.accessTokenExpiresAt},callbackURL:a});if(R.error)return b(R.error.split(" ").join("_"));let{session:S,user:k}=R.data;await T(e,{session:S,user:k});let ee;try{ee=new URL(a).toString()}catch{ee=a}throw e.redirect(ee)});var qn=require("zod");var Lt=require("better-call"),Te=p("/sign-out",{method:"POST",requireHeaders:!0},async e=>{let t=await e.getSignedCookie(e.context.authCookies.sessionToken.name,e.context.secret);if(!t)throw V(e),new Lt.APIError("BAD_REQUEST",{message:"Session not found"});return await e.context.internalAdapter.deleteSession(t),V(e),e.json({success:!0})});var O=require("zod");var X=require("better-call");function Ct(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 er(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 Pe=p("/forget-password",{method:"POST",body:O.z.object({email:O.z.string().email(),redirectTo:O.z.string()})},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 X.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=L(e.context.options.emailAndPassword.resetPasswordTokenExpiresIn||n,"sec"),s=e.context.uuid();await e.context.internalAdapter.createVerificationValue({value:o.user.id,identifier:`reset-password:${s}`,expiresAt:i});let a=`${e.context.baseURL}/reset-password/${s}?callbackURL=${r}`;return await e.context.options.emailAndPassword.sendResetPassword({user:o.user,url:a,token:s},e.request),e.json({status:!0})}),Se=p("/reset-password/:token",{method:"GET",query:O.z.object({callbackURL:O.z.string()})},async e=>{let{token:t}=e.params,{callbackURL:r}=e.query;if(!t||!r)throw e.redirect(Ct(e.context,r,{error:"INVALID_TOKEN"}));let o=await e.context.internalAdapter.findVerificationValue(`reset-password:${t}`);throw!o||o.expiresAt<new Date?e.redirect(Ct(e.context,r,{error:"INVALID_TOKEN"})):e.redirect(er(e.context,r,{token:t}))}),Oe=p("/reset-password",{query:O.z.optional(O.z.object({token:O.z.string().optional(),currentURL:O.z.string().optional()})),method:"POST",body:O.z.object({newPassword:O.z.string(),token:O.z.string().optional()})},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 X.APIError("BAD_REQUEST",{message:"Token not found"});let{newPassword:r}=e.body,o=`reset-password:${t}`,n=await e.context.internalAdapter.findVerificationValue(o);if(!n||n.expiresAt<new Date)throw new X.APIError("BAD_REQUEST",{message:"Invalid token"});await e.context.internalAdapter.deleteVerificationValue(n.id);let i=n.value,s=await e.context.password.hash(r);if(!(await e.context.internalAdapter.findAccounts(i)).find(u=>u.providerId==="credential"))return await e.context.internalAdapter.createAccount({userId:i,providerId:"credential",password:s,accountId:e.context.uuid()}),e.json({status:!0});if(!await e.context.internalAdapter.updatePassword(i,s))throw new X.APIError("BAD_REQUEST",{message:"Failed to update password"});return e.json({status:!0})});var U=require("zod");var E=require("better-call");var g=require("zod"),Jn=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(),expiresAt:g.z.date().nullish(),password:g.z.string().nullish()}),Wn=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)}),Kn=g.z.object({id:g.z.string(),userId:g.z.string(),expiresAt:g.z.date(),ipAddress:g.z.string().nullish(),userAgent:g.z.string().nullish()}),Yn=g.z.object({id:g.z.string(),value:g.z.string(),createdAt:g.z.date(),expiresAt:g.z.date(),identifier:g.z.string()});function tr(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 rr(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}n[i]=e[i];continue}if(o[i].defaultValue&&r==="create"){n[i]=o[i].defaultValue;continue}}return n}function le(e,t,r){let o=tr(e,"user");return rr(t||{},{fields:o,action:r})}var Ie=()=>p("/update-user",{method:"POST",body:U.z.record(U.z.string(),U.z.any()),use:[P]},async e=>{let t=e.body;if(t.email)throw new E.APIError("BAD_REQUEST",{message:"You can't update email"});let{name:r,image:o,...n}=t,i=e.context.session;if(!o&&!r&&Object.keys(n).length===0)return e.json({user:i.user});let s=le(e.context.options,n,"update"),a=await e.context.internalAdapter.updateUserByEmail(i.user.email,{name:r,image:o,...s});return await T(e,{session:i.session,user:a}),e.json({user:a})}),Le=p("/change-password",{method:"POST",body:U.z.object({newPassword:U.z.string(),currentPassword:U.z.string(),revokeOtherSessions:U.z.boolean().optional()}),use:[P]},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 E.APIError("BAD_REQUEST",{message:"Password is 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:"Password too long"});let d=(await e.context.internalAdapter.findAccounts(n.user.id)).find(f=>f.providerId==="credential"&&f.password);if(!d||!d.password)throw new E.APIError("BAD_REQUEST",{message:"User does not have a password"});let c=await e.context.password.hash(t);if(!await e.context.password.verify(d.password,r))throw new E.APIError("BAD_REQUEST",{message:"Incorrect password"});if(await e.context.internalAdapter.updateAccount(d.id,{password:c}),o){await e.context.internalAdapter.deleteSessions(n.user.id);let f=await e.context.internalAdapter.createSession(n.user.id,e.headers);if(!f)throw new E.APIError("INTERNAL_SERVER_ERROR",{message:"Unable to create session"});await T(e,{session:f,user:n.user})}return e.json(n.user)}),Ce=p("/set-password",{method:"POST",body:U.z.object({newPassword:U.z.string()}),metadata:{SERVER_ONLY:!0},use:[P]},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:"Password is too short"});let n=e.context.password.config.maxPasswordLength;if(t.length>n)throw e.context.logger.error("Password is too long"),new E.APIError("BAD_REQUEST",{message:"Password too long"});let s=(await e.context.internalAdapter.findAccounts(r.user.id)).find(d=>d.providerId==="credential"&&d.password),a=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:a}),e.json(r.user);throw new E.APIError("BAD_REQUEST",{message:"user already has a password"})}),Be=p("/delete-user",{method:"POST",body:U.z.object({password:U.z.string()}),use:[P]},async e=>{let{password:t}=e.body,r=e.context.session,n=(await e.context.internalAdapter.findAccounts(r.user.id)).find(s=>s.providerId==="credential"&&s.password);if(!n||!n.password)throw new E.APIError("BAD_REQUEST",{message:"User does not have a password"});if(!await e.context.password.verify(n.password,t))throw new E.APIError("BAD_REQUEST",{message:"Incorrect password"});return await e.context.internalAdapter.deleteUser(r.user.id),await e.context.internalAdapter.deleteSessions(r.user.id),V(e),e.json(null)}),De=p("/change-email",{method:"POST",query:U.z.object({currentURL:U.z.string().optional()}).optional(),body:U.z.object({newEmail:U.z.string().email(),callbackURL:U.z.string().optional()}),use:[P]},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 n=await e.context.internalAdapter.updateUserByEmail(e.context.session.user.email,{email:e.body.newEmail});return e.json({user:n,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 C(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({user:null,status:!0})});var or=(e="Unknown")=>`<!DOCTYPE html>
|
|
@@ -81,4 +81,4 @@ Error: `,a),e.redirect(`${e.context.baseURL}/error?error=internal_server_error`)
|
|
|
81
81
|
<div class="error-code">Error Code: <span id="errorCode">${e}</span></div>
|
|
82
82
|
</div>
|
|
83
83
|
</body>
|
|
84
|
-
</html>`,Ve=p("/error",{method:"GET",metadata:M},async e=>{let t=new URL(e.request?.url||"").searchParams.get("error")||"Unknown";return new Response(or(t),{headers:{"Content-Type":"text/html"}})});var ze=p("/ok",{method:"GET",metadata:M},async e=>e.json({ok:!0}));var H=require("zod");var B=require("better-call");var $e=()=>p("/sign-up/email",{method:"POST",query:H.z.object({currentURL:H.z.string().optional()}).optional(),body:H.z.record(H.z.string(),H.z.any())},async e=>{if(!e.context.options.emailAndPassword?.enabled)throw new B.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,...a}=t;if(!H.z.string().email().safeParse(o).success)throw new B.APIError("BAD_REQUEST",{message:"Invalid email"});let c=e.context.password.config.minPasswordLength;if(n.length<c)throw e.context.logger.error("Password is too short"),new B.APIError("BAD_REQUEST",{message:"Password is too short"});let u=e.context.password.config.maxPasswordLength;if(n.length>u)throw e.context.logger.error("Password is too long"),new B.APIError("BAD_REQUEST",{message:"Password is too long"});if((await e.context.internalAdapter.findUserByEmail(o))?.user)throw e.context.logger.info(`Sign-up attempt for existing email: ${o}`),new B.APIError("UNPROCESSABLE_ENTITY",{message:"User with this email already exists"});let h=le(e.context.options,a),l;try{if(l=await e.context.internalAdapter.createUser({email:o.toLowerCase(),name:r,image:i,...h,emailVerified:!1}),!l)throw new B.APIError("BAD_REQUEST",{message:"Failed to create user"})}catch(S){throw m.error("Failed to create user",S),new B.APIError("UNPROCESSABLE_ENTITY",{message:"Failed to create user",details:S})}if(!l)throw new B.APIError("UNPROCESSABLE_ENTITY",{message:"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,expiresAt:L(60*60*24*30,"sec")}),e.context.options.emailVerification?.sendOnSignUp){let S=await C(e.context.secret,l.email),k=`${e.context.baseURL}/verify-email?token=${S}&callbackURL=${t.callbackURL||e.query?.currentURL||"/"}`;await e.context.options.emailVerification?.sendVerificationEmail?.({user:l,url:k,token:S},e.request)}if(!e.context.options.emailAndPassword.autoSignIn||e.context.options.emailAndPassword.requireEmailVerification)return e.json({user:l,session:null},{body:t.callbackURL?{url:t.callbackURL,redirect:!0}:{user:l,session:null}});let R=await e.context.internalAdapter.createSession(l.id,e.request);if(!R)throw new B.APIError("BAD_REQUEST",{message:"Failed to create session"});return await T(e,{session:R,user:l}),e.json({user:l,session:R})});var Z=require("zod");var je=require("better-call");var qe=p("/list-accounts",{method:"GET",use:[P]},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})))}),Ne=p("/link-social",{method:"POST",requireHeaders:!0,query:Z.z.object({currentURL:Z.z.string().optional()}).optional(),body:Z.z.object({callbackURL:Z.z.string().optional(),provider:Z.z.enum(se)}),use:[P]},async e=>{let t=e.context.session;if((await e.context.internalAdapter.findAccounts(t.user.id)).find(a=>a.providerId===e.body.provider))throw new je.APIError("BAD_REQUEST",{message:"Social Account is already linked."});let n=e.context.socialProviders.find(a=>a.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 je.APIError("NOT_FOUND",{message:"Provider not found"});let i=await oe(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 Bt(e,t){if(t.advanced?.ipAddress?.disableIpTracking)return null;let r="127.0.0.1";if(Qe)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 a=i.get(s);if(typeof a=="string"){let d=a.split(",")[0].trim();if(d)return d}}return null}function nr(e,t,r){let o=Date.now(),n=t*1e3;return o-r.lastRequest<n&&r.count>=e}function ir(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 sr(e,t){let r=Date.now(),o=t*1e3;return Math.ceil((e+o-r)/1e3)}function ar(e,t){let r=t??"rateLimit",o=e.adapter;return{get:async n=>await o.findOne({model:r,where:[{field:"key",value:n}]}),set:async(n,i,s)=>{try{s?await o.update({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(a){m.error("Error setting rate limit",a)}}}}var Dt=new Map;function dr(e){return 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 Dt.get(r)},async set(r,o,n){Dt.set(r,o)}}:ar(e,e.rateLimit.tableName)}async function Vt(e,t){if(!t.rateLimit.enabled)return;let r=t.baseURL,o=e.url.replace(r,""),n=t.rateLimit.window,i=t.rateLimit.max,s=Bt(e,t.options)+o,d=cr().find(h=>h.pathMatcher(o));d&&(n=d.window,i=d.max);for(let h of t.options.plugins||[])if(h.rateLimit){let l=h.rateLimit.find(b=>b.pathMatcher(o));if(l){n=l.window,i=l.max;break}}if(t.rateLimit.customRules){let h=t.rateLimit.customRules[o];h&&(n=h.window,i=h.max)}let c=dr(t),u=await c.get(s),f=Date.now();if(!u)await c.set(s,{key:s,count:1,lastRequest:f});else{let h=f-u.lastRequest;if(nr(i,n,u)){let l=sr(u.lastRequest,n);return ir(l)}else h>n*1e3?await c.set(s,{...u,count:1,lastRequest:f}):await c.set(s,{...u,count:u.count+1,lastRequest:f})}}function cr(){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 $t=require("better-call");function zt(e,t){let r=t.plugins?.reduce((a,d)=>({...a,...d.endpoints}),{}),o=t.plugins?.map(a=>a.middlewares?.map(d=>{let c=async u=>d.middleware({...u,context:{...e,...u.context}});return c.path=d.path,c.options=d.middleware.options,c.headers=d.middleware.headers,{path:d.path,middleware:c}})).filter(a=>a!==void 0).flat()||[],i={...{signInSocial:Ee,callbackOAuth:xe,getSession:ae(),signOut:Te,signUpEmail:$e(),signInEmail:_e,forgetPassword:Pe,resetPassword:Oe,verifyEmail:ve,sendVerificationEmail:Ue,changeEmail:De,changePassword:Le,setPassword:Ce,updateUser:Ie(),deleteUser:Be,forgetPasswordCallback:Se,listSessions:ye(),revokeSession:Ae,revokeSessions:ke,revokeOtherSessions:Re,linkSocialAccount:Ne,listUserAccounts:qe},...r,ok:ze,error:Ve},s={};for(let[a,d]of Object.entries(i))s[a]=async(c={})=>{let u=await e;u.session=null;for(let l of t.plugins||[])if(l.hooks?.before)for(let b of l.hooks.before){let R={...d,...c,context:{...u,...c?.context}};if(b.matcher(R)){let k=await b.handler(R);k&&"context"in k&&(c={...k,...c})}}let f;try{f=await d({...c,context:{...u,...c.context}})}catch(l){if(l instanceof j.APIError){let b=t.plugins?.map(k=>{if(k.hooks?.after)return k.hooks.after}).filter(k=>k!==void 0).flat();if(!b?.length)throw l;let R=new Response(JSON.stringify(l.body),{status:j.statusCode[l.status],headers:l.headers}),S;for(let k of b||[])if(k.matcher(c)){u.returned=R;let _={...d,...c,context:u},x=await k.handler(_);x&&"response"in x&&(S=x.response)}if(S instanceof Response)return S;throw l}throw l}let h=f;for(let l of t.plugins||[])if(l.hooks?.after)for(let b of l.hooks.after){let R={...c,context:{...u,...c.context,endpoint:d,returned:h}};if(b.matcher(R)){let k=await b.handler(R);k&&"response"in k&&(h=k.response)}}return h},s[a].path=d.path,s[a].method=d.method,s[a].options=d.options,s[a].headers=d.headers;return{api:s,middlewares:o}}var ur=(e,t)=>{let{api:r,middlewares:o}=zt(e,t),n=new URL(e.baseURL).pathname;return(0,j.createRouter)(r,{extraContext:e,basePath:n,routerMiddleware:[{path:"/**",middleware:he},...o],async onRequest(i){for(let s of e.options.plugins||[])if(s.onRequest){let a=await s.onRequest(i,e);if(a&&"response"in a)return a.response}return Vt(i,e)},async onResponse(i){for(let s of e.options.plugins||[])if(s.onResponse){let a=await s.onResponse(i,e);if(a)return a.response}return i},onError(i){if(i instanceof j.APIError&&i.status==="FOUND")return;if(t.onAPIError?.throw)throw i;if(t.onAPIError?.onError){t.onAPIError.onError(i,e);return}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"))){m.error(i.message),m.error("If you are seeing this error, it is likely that you need to run the migrations for the database or you need to update your database schema. If you recently updated the package, make sure to run the migrations.");return}let s=t.logger?.verboseLogging?m:void 0;t.logger?.disabled!==!0&&(i instanceof j.APIError?(i.status==="INTERNAL_SERVER_ERROR"&&m.error(i),s?.error(i.message)):m?.error(i))}})};0&&(module.exports={APIError,callbackOAuth,changeEmail,changePassword,createAuthEndpoint,createAuthMiddleware,createEmailVerificationToken,deleteUser,error,forgetPassword,forgetPasswordCallback,getEndpoints,getSession,getSessionFromCtx,linkSocialAccount,listSessions,listUserAccounts,ok,optionsMiddleware,originCheckMiddleware,resetPassword,revokeOtherSessions,revokeSession,revokeSessions,router,sendVerificationEmail,sessionMiddleware,setPassword,signInEmail,signInSocial,signOut,signUpEmail,updateUser,verifyEmail});
|
|
84
|
+
</html>`,Ve=p("/error",{method:"GET",metadata:M},async e=>{let t=new URL(e.request?.url||"").searchParams.get("error")||"Unknown";return new Response(or(t),{headers:{"Content-Type":"text/html"}})});var ze=p("/ok",{method:"GET",metadata:M},async e=>e.json({ok:!0}));var H=require("zod");var B=require("better-call");var $e=()=>p("/sign-up/email",{method:"POST",query:H.z.object({currentURL:H.z.string().optional()}).optional(),body:H.z.record(H.z.string(),H.z.any())},async e=>{if(!e.context.options.emailAndPassword?.enabled)throw new B.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,...a}=t;if(!H.z.string().email().safeParse(o).success)throw new B.APIError("BAD_REQUEST",{message:"Invalid email"});let c=e.context.password.config.minPasswordLength;if(n.length<c)throw e.context.logger.error("Password is too short"),new B.APIError("BAD_REQUEST",{message:"Password is too short"});let u=e.context.password.config.maxPasswordLength;if(n.length>u)throw e.context.logger.error("Password is too long"),new B.APIError("BAD_REQUEST",{message:"Password is too long"});if((await e.context.internalAdapter.findUserByEmail(o))?.user)throw e.context.logger.info(`Sign-up attempt for existing email: ${o}`),new B.APIError("UNPROCESSABLE_ENTITY",{message:"User with this email already exists"});let h=le(e.context.options,a),l;try{if(l=await e.context.internalAdapter.createUser({email:o.toLowerCase(),name:r,image:i,...h,emailVerified:!1}),!l)throw new B.APIError("BAD_REQUEST",{message:"Failed to create user"})}catch(S){throw m.error("Failed to create user",S),new B.APIError("UNPROCESSABLE_ENTITY",{message:"Failed to create user",details:S})}if(!l)throw new B.APIError("UNPROCESSABLE_ENTITY",{message:"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,expiresAt:L(60*60*24*30,"sec")}),e.context.options.emailVerification?.sendOnSignUp){let S=await C(e.context.secret,l.email),k=`${e.context.baseURL}/verify-email?token=${S}&callbackURL=${t.callbackURL||e.query?.currentURL||"/"}`;await e.context.options.emailVerification?.sendVerificationEmail?.({user:l,url:k,token:S},e.request)}if(!e.context.options.emailAndPassword.autoSignIn||e.context.options.emailAndPassword.requireEmailVerification)return e.json({user:l,session:null});let R=await e.context.internalAdapter.createSession(l.id,e.request);if(!R)throw new B.APIError("BAD_REQUEST",{message:"Failed to create session"});return await T(e,{session:R,user:l}),e.json({user:l,session:R})});var Z=require("zod");var je=require("better-call");var qe=p("/list-accounts",{method:"GET",use:[P]},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})))}),Ne=p("/link-social",{method:"POST",requireHeaders:!0,query:Z.z.object({currentURL:Z.z.string().optional()}).optional(),body:Z.z.object({callbackURL:Z.z.string().optional(),provider:Z.z.enum(se)}),use:[P]},async e=>{let t=e.context.session;if((await e.context.internalAdapter.findAccounts(t.user.id)).find(a=>a.providerId===e.body.provider))throw new je.APIError("BAD_REQUEST",{message:"Social Account is already linked."});let n=e.context.socialProviders.find(a=>a.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 je.APIError("NOT_FOUND",{message:"Provider not found"});let i=await oe(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 Bt(e,t){if(t.advanced?.ipAddress?.disableIpTracking)return null;let r="127.0.0.1";if(Qe)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 a=i.get(s);if(typeof a=="string"){let d=a.split(",")[0].trim();if(d)return d}}return null}function nr(e,t,r){let o=Date.now(),n=t*1e3;return o-r.lastRequest<n&&r.count>=e}function ir(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 sr(e,t){let r=Date.now(),o=t*1e3;return Math.ceil((e+o-r)/1e3)}function ar(e,t){let r=t??"rateLimit",o=e.adapter;return{get:async n=>await o.findOne({model:r,where:[{field:"key",value:n}]}),set:async(n,i,s)=>{try{s?await o.update({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(a){m.error("Error setting rate limit",a)}}}}var Dt=new Map;function dr(e){return 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 Dt.get(r)},async set(r,o,n){Dt.set(r,o)}}:ar(e,e.rateLimit.tableName)}async function Vt(e,t){if(!t.rateLimit.enabled)return;let r=t.baseURL,o=e.url.replace(r,""),n=t.rateLimit.window,i=t.rateLimit.max,s=Bt(e,t.options)+o,d=cr().find(h=>h.pathMatcher(o));d&&(n=d.window,i=d.max);for(let h of t.options.plugins||[])if(h.rateLimit){let l=h.rateLimit.find(b=>b.pathMatcher(o));if(l){n=l.window,i=l.max;break}}if(t.rateLimit.customRules){let h=t.rateLimit.customRules[o];h&&(n=h.window,i=h.max)}let c=dr(t),u=await c.get(s),f=Date.now();if(!u)await c.set(s,{key:s,count:1,lastRequest:f});else{let h=f-u.lastRequest;if(nr(i,n,u)){let l=sr(u.lastRequest,n);return ir(l)}else h>n*1e3?await c.set(s,{...u,count:1,lastRequest:f}):await c.set(s,{...u,count:u.count+1,lastRequest:f})}}function cr(){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 $t=require("better-call");function zt(e,t){let r=t.plugins?.reduce((a,d)=>({...a,...d.endpoints}),{}),o=t.plugins?.map(a=>a.middlewares?.map(d=>{let c=async u=>d.middleware({...u,context:{...e,...u.context}});return c.path=d.path,c.options=d.middleware.options,c.headers=d.middleware.headers,{path:d.path,middleware:c}})).filter(a=>a!==void 0).flat()||[],i={...{signInSocial:Ee,callbackOAuth:xe,getSession:ae(),signOut:Te,signUpEmail:$e(),signInEmail:_e,forgetPassword:Pe,resetPassword:Oe,verifyEmail:ve,sendVerificationEmail:Ue,changeEmail:De,changePassword:Le,setPassword:Ce,updateUser:Ie(),deleteUser:Be,forgetPasswordCallback:Se,listSessions:ye(),revokeSession:Ae,revokeSessions:ke,revokeOtherSessions:Re,linkSocialAccount:Ne,listUserAccounts:qe},...r,ok:ze,error:Ve},s={};for(let[a,d]of Object.entries(i))s[a]=async(c={})=>{let u=await e;u.session=null;for(let l of t.plugins||[])if(l.hooks?.before)for(let b of l.hooks.before){let R={...d,...c,context:{...u,...c?.context}};if(b.matcher(R)){let k=await b.handler(R);k&&"context"in k&&(c={...k,...c})}}let f;try{f=await d({...c,context:{...u,...c.context}})}catch(l){if(l instanceof j.APIError){let b=t.plugins?.map(k=>{if(k.hooks?.after)return k.hooks.after}).filter(k=>k!==void 0).flat();if(!b?.length)throw l;let R=new Response(JSON.stringify(l.body),{status:j.statusCode[l.status],headers:l.headers}),S;for(let k of b||[])if(k.matcher(c)){u.returned=R;let _={...d,...c,context:u},x=await k.handler(_);x&&"response"in x&&(S=x.response)}if(S instanceof Response)return S;throw l}throw l}let h=f;for(let l of t.plugins||[])if(l.hooks?.after)for(let b of l.hooks.after){let R={...c,context:{...u,...c.context,endpoint:d,returned:h}};if(b.matcher(R)){let k=await b.handler(R);k&&"response"in k&&(h=k.response)}}return h},s[a].path=d.path,s[a].method=d.method,s[a].options=d.options,s[a].headers=d.headers;return{api:s,middlewares:o}}var ur=(e,t)=>{let{api:r,middlewares:o}=zt(e,t),n=new URL(e.baseURL).pathname;return(0,j.createRouter)(r,{extraContext:e,basePath:n,routerMiddleware:[{path:"/**",middleware:he},...o],async onRequest(i){for(let s of e.options.plugins||[])if(s.onRequest){let a=await s.onRequest(i,e);if(a&&"response"in a)return a.response}return Vt(i,e)},async onResponse(i){for(let s of e.options.plugins||[])if(s.onResponse){let a=await s.onResponse(i,e);if(a)return a.response}return i},onError(i){if(i instanceof j.APIError&&i.status==="FOUND")return;if(t.onAPIError?.throw)throw i;if(t.onAPIError?.onError){t.onAPIError.onError(i,e);return}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"))){m.error(i.message),m.error("If you are seeing this error, it is likely that you need to run the migrations for the database or you need to update your database schema. If you recently updated the package, make sure to run the migrations.");return}let s=t.logger?.verboseLogging?m:void 0;t.logger?.disabled!==!0&&(i instanceof j.APIError?(i.status==="INTERNAL_SERVER_ERROR"&&m.error(i),s?.error(i.message)):m?.error(i))}})};0&&(module.exports={APIError,callbackOAuth,changeEmail,changePassword,createAuthEndpoint,createAuthMiddleware,createEmailVerificationToken,deleteUser,error,forgetPassword,forgetPasswordCallback,getEndpoints,getSession,getSessionFromCtx,linkSocialAccount,listSessions,listUserAccounts,ok,optionsMiddleware,originCheckMiddleware,resetPassword,revokeOtherSessions,revokeSession,revokeSessions,router,sendVerificationEmail,sessionMiddleware,setPassword,signInEmail,signInSocial,signOut,signUpEmail,updateUser,verifyEmail});
|
package/dist/api.js
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import{APIError as de,createRouter as sr,statusCode as ar}from"better-call";import{APIError as bt}from"better-call";import{createEndpointCreator as ut,createMiddleware as ce,createMiddlewareCreator as lt}from"better-call";var ue=ce(async()=>({})),Z=lt({use:[ue,ce(async()=>({}))]}),p=ut({use:[ue]});var N={isAction:!1};import{nanoid as pt}from"nanoid";var le=e=>pt(e);import{APIError as he}from"better-call";import{generateCodeVerifier as ft,generateState as gt}from"oslo/oauth2";import{z as V}from"zod";var J=Object.create(null),H=e=>globalThis.process?.env||globalThis.Deno?.env.toObject()||globalThis.__env__||(e?J:globalThis),pe=new Proxy(J,{get(e,t){return H()[t]??J[t]},has(e,t){let r=H();return t in r||t in J},set(e,t,r){let o=H(!0);return o[t]=r,!0},deleteProperty(e,t){if(!t)return!1;let r=H(!0);return delete r[t],!0},ownKeys(){let e=H(!0);return Object.keys(e)}});function mt(e){return e?e!=="false":!1}var ie=typeof process<"u"&&process.env&&process.env.NODE_ENV||"";var me=ie==="dev"||ie==="development",fe=ie==="test"||mt(pe.TEST);var z=class extends Error{constructor(t,r){super(t),this.name="BetterAuthError",this.message=t,this.cause=r,this.stack=""}};function ge(e){try{return new URL(e).origin}catch{return null}}async function W(e,t){let r=e.body?.callbackURL||(e.query?.currentURL?ge(e.query?.currentURL):"")||e.context.options.baseURL;if(!r)throw new he("BAD_REQUEST",{message:"callbackURL is required"});let o=ft(),n=gt(),i=JSON.stringify({callbackURL:r,codeVerifier:o,errorURL:e.body?.errorCallbackURL||e.query?.currentURL,link:t,expiresAt:Date.now()+10*60*1e3}),s=new Date;s.setMinutes(s.getMinutes()+10);let a=await e.context.internalAdapter.createVerificationValue({value:i,identifier:n,expiresAt:s});if(!a)throw m.error("Unable to create verification. Make sure the database adapter is properly working and there is a verification table in the database"),new he("INTERNAL_SERVER_ERROR",{message:"Unable to create verification"});return{state:a.identifier,codeVerifier:o}}async function we(e){let t=e.query.state||e.body.state
|
|
1
|
+
import{APIError as de,createRouter as sr,statusCode as ar}from"better-call";import{APIError as bt}from"better-call";import{createEndpointCreator as ut,createMiddleware as ce,createMiddlewareCreator as lt}from"better-call";var ue=ce(async()=>({})),Z=lt({use:[ue,ce(async()=>({}))]}),p=ut({use:[ue]});var N={isAction:!1};import{nanoid as pt}from"nanoid";var le=e=>pt(e);import{APIError as he}from"better-call";import{generateCodeVerifier as ft,generateState as gt}from"oslo/oauth2";import{z as V}from"zod";var J=Object.create(null),H=e=>globalThis.process?.env||globalThis.Deno?.env.toObject()||globalThis.__env__||(e?J:globalThis),pe=new Proxy(J,{get(e,t){return H()[t]??J[t]},has(e,t){let r=H();return t in r||t in J},set(e,t,r){let o=H(!0);return o[t]=r,!0},deleteProperty(e,t){if(!t)return!1;let r=H(!0);return delete r[t],!0},ownKeys(){let e=H(!0);return Object.keys(e)}});function mt(e){return e?e!=="false":!1}var ie=typeof process<"u"&&process.env&&process.env.NODE_ENV||"";var me=ie==="dev"||ie==="development",fe=ie==="test"||mt(pe.TEST);var z=class extends Error{constructor(t,r){super(t),this.name="BetterAuthError",this.message=t,this.cause=r,this.stack=""}};function ge(e){try{return new URL(e).origin}catch{return null}}async function W(e,t){let r=e.body?.callbackURL||(e.query?.currentURL?ge(e.query?.currentURL):"")||e.context.options.baseURL;if(!r)throw new he("BAD_REQUEST",{message:"callbackURL is required"});let o=ft(),n=gt(),i=JSON.stringify({callbackURL:r,codeVerifier:o,errorURL:e.body?.errorCallbackURL||e.query?.currentURL,link:t,expiresAt:Date.now()+10*60*1e3}),s=new Date;s.setMinutes(s.getMinutes()+10);let a=await e.context.internalAdapter.createVerificationValue({value:i,identifier:n,expiresAt:s});if(!a)throw m.error("Unable to create verification. Make sure the database adapter is properly working and there is a verification table in the database"),new he("INTERNAL_SERVER_ERROR",{message:"Unable to create verification"});return{state:a.identifier,codeVerifier:o}}async function we(e){let t=e.query.state||e.body.state,r=await e.context.internalAdapter.findVerificationValue(t);if(!r)throw m.error("State Mismatch. Verification not found",{state:t}),e.redirect(`${e.context.baseURL}/error?error=please_restart_the_process`);let o=V.object({callbackURL:V.string(),codeVerifier:V.string(),errorURL:V.string().optional(),expiresAt:V.number(),link:V.object({email:V.string(),userId:V.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),m.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}import{createConsola as ht}from"consola";var $=ht({formatOptions:{date:!1,colors:!0,compact:!0},defaults:{tag:"Better Auth"}}),wt=e=>({log:(...t)=>{!e?.disabled&&$.log("",...t)},error:(...t)=>{!e?.disabled&&$.error("",...t)},warn:(...t)=>{!e?.disabled&&$.warn("",...t)},info:(...t)=>{!e?.disabled&&$.info("",...t)},debug:(...t)=>{!e?.disabled&&$.debug("",...t)},box:(...t)=>{!e?.disabled&&$.box("",...t)},success:(...t)=>{!e?.disabled&&$.success("",...t)},break:(...t)=>{!e?.disabled&&console.log(`
|
|
2
2
|
`)}}),m=wt();var be=Z(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,a=r?.currentURL,d=o.trustedOrigins,c=e.headers?.has("cookie"),u=(h,l)=>l.includes("*")?new RegExp("^"+l.replace(/\*/g,"[^/]+").replace(/\./g,"\\.")+"$").test(h):h.startsWith(l),f=(h,l)=>{if(!h)return;if(!d.some(R=>u(h,R)||h?.startsWith("/")&&l!=="origin"&&!h.includes(":")))throw m.error(`Invalid ${l}: ${h}`),m.info(`If it's a valid URL, please add ${h} to trustedOrigins in your auth config
|
|
3
3
|
`,`Current list of trustedOrigins: ${d}`),new bt("FORBIDDEN",{message:`Invalid ${l}`})};c&&!e.context.options.advanced?.disableCSRFCheck&&f(n,"origin"),i&&f(i,"callbackURL"),s&&f(s,"redirectURL"),a&&f(a,"currentURL")});import{APIError as v}from"better-call";import{z as k}from"zod";import{TimeSpan as Wr}from"oslo";import{base64url as kt}from"oslo/encoding";import{HMAC as ye,sha256 as Fr}from"oslo/crypto";async function yt({value:e,secret:t}){return new ye("SHA-256").sign(new TextEncoder().encode(t),new TextEncoder().encode(e)).then(o=>Buffer.from(o).toString("base64"))}function At({value:e,signature:t,secret:r}){return new ye("SHA-256").verify(new TextEncoder().encode(r),Buffer.from(t,"base64"),new TextEncoder().encode(e))}var K={sign:yt,verify:At};var L=(e,t="ms")=>new Date(Date.now()+(t==="sec"?e*1e3:e));async function T(e,t,r,o){let n=e.context.authCookies.sessionToken.options;n.maxAge=r?void 0:e.context.sessionConfig.expiresIn,await e.setSignedCookie(e.context.authCookies.sessionToken.name,t.session.id,e.context.secret,{...n,...o}),r&&await e.setSignedCookie(e.context.authCookies.dontRememberToken.name,"true",e.context.secret,e.context.authCookies.dontRememberToken.options),e.context.options.session?.cookieCache?.enabled&&e.setCookie(e.context.authCookies.sessionData.name,JSON.stringify(kt.encode(new TextEncoder().encode(JSON.stringify({session:t,expiresAt:L(e.context.authCookies.sessionData.options.maxAge||60,"sec").getTime(),signature:await K.sign({value:JSON.stringify(t),secret:e.context.secret})})))),e.context.authCookies.sessionData.options),e.context.options.secondaryStorage&&await e.context.secondaryStorage?.set(t.session.id,JSON.stringify({user:t.user,session:t.session}),t.session.expiresAt.getTime()-Date.now())}function C(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})}import{betterFetch as Et}from"@better-fetch/fetch";import{APIError as _t}from"better-call";import{decodeProtectedHeader as xt,importJWK as Tt,jwtVerify as Pt}from"jose";import{parseJWT as St}from"oslo/jwt";import{sha256 as Rt}from"oslo/crypto";import{base64url as Ut}from"oslo/encoding";async function Ae(e){let t=await Rt(new TextEncoder().encode(e));return Ut.encode(new Uint8Array(t),{includePadding:!1})}function ke(e){return{tokenType:e.token_type,accessToken:e.access_token,refreshToken:e.refresh_token,accessTokenExpiresAt:e.expires_in?L(e.expires_in,"sec"):void 0,scopes:e?.scope?typeof e.scope=="string"?e.scope.split(" "):e.scope:[],idToken:e.id_token}}async function y({id:e,options:t,authorizationEndpoint:r,state:o,codeVerifier:n,scopes:i,claims:s,redirectURI: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||a),n){let c=await Ae(n);d.searchParams.set("code_challenge_method","S256"),d.searchParams.set("code_challenge",c)}if(s){let c=s.reduce((u,f)=>(u[f]=null,u),{});d.searchParams.set("claims",JSON.stringify({id_token:{email:null,email_verified:null,...c}}))}return d}import{betterFetch as vt}from"@better-fetch/fetch";async function w({code:e,codeVerifier:t,redirectURI:r,options:o,tokenEndpoint:n,authentication:i}){let s=new URLSearchParams,a={"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 f=btoa(`${o.clientId}:${o.clientSecret}`);a.authorization=`Basic ${f}`}else s.set("client_id",o.clientId),s.set("client_secret",o.clientSecret);let{data:d,error:c}=await vt(n,{method:"POST",body:s,headers:a});if(c)throw c;return ke(d)}var Re=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=${n||e.redirectURI}&scope=${i.join(" ")}&state=${r}&response_mode=form_post`)},validateAuthorizationCode:async({code:r,codeVerifier:o,redirectURI:n})=>w({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=xt(r),{kid:i,alg:s}=n;if(!i||!s)return!1;let a=await Ot(i),{payload:d}=await Pt(r,a,{algorithms:[s],issuer:"https://appleid.apple.com",audience:e.clientId,maxTokenAge:"1h"});return["email_verified","is_private_email"].forEach(c=>{d[c]!==void 0&&(d[c]=!!d[c])}),o&&d.nonce!==o?!1:!!d},async getUserInfo(r){if(!r.idToken)return null;let o=St(r.idToken)?.payload;if(!o)return null;let n=o.user?`${o.user.name.firstName} ${o.user.name.lastName}`:o.email;return{user:{id:o.sub,name:n,emailVerified:!1,email:o.email},data:o}}}},Ot=async e=>{let t="https://appleid.apple.com",r="/auth/keys",{data:o}=await Et(`${t}${r}`);if(!o?.keys)throw new _t("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 Tt(n,n.alg)};import{betterFetch as It}from"@better-fetch/fetch";var Ue=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}`)},validateAuthorizationCode:async({code:t,redirectURI:r})=>w({code:t,redirectURI:e.redirectURI||r,options:e,tokenEndpoint:"https://discord.com/api/oauth2/token"}),async getUserInfo(t){let{data:r,error:o}=await It("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}`}return{user:{id:r.id,name:r.display_name||r.username||"",email:r.email,emailVerified:r.verified,image:r.image_url},data:r}}});import{betterFetch as Lt}from"@better-fetch/fetch";var ve=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 y({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})=>w({code:t,redirectURI:e.redirectURI||r,options:e,tokenEndpoint:"https://graph.facebook.com/oauth/access_token"}),async getUserInfo(t){let{data:r,error:o}=await Lt("https://graph.facebook.com/me?fields=id,name,email,picture",{auth:{type:"Bearer",token:t.accessToken}});return o?null:{user:{id:r.id,name:r.name,email:r.email,image:r.picture.data.url,emailVerified:r.email_verified},data:r}}});import{betterFetch as Ee}from"@better-fetch/fetch";var _e=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),y({id:"github",options:e,authorizationEndpoint:"https://github.com/login/oauth/authorize",scopes:s,state:r,redirectURI:i})},validateAuthorizationCode:async({code:r,redirectURI:o})=>w({code:r,redirectURI:e.redirectURI||o,options:e,tokenEndpoint:t}),async getUserInfo(r){let{data:o,error:n}=await Ee("https://api.github.com/user",{headers:{"User-Agent":"better-auth",authorization:`Bearer ${r.accessToken}`}});if(n)return null;let i=!1;if(!o.email){let{data:s,error:a}=await Ee("https://api.github.com/user/emails",{headers:{authorization:`Bearer ${r.accessToken}`,"User-Agent":"better-auth"}});a||(o.email=(s.find(d=>d.primary)??s[0])?.email,i=s.find(d=>d.email===o.email)?.verified??!1)}return{user:{id:o.id.toString(),name:o.name||o.login,email:o.email,image:o.avatar_url,emailVerified:i},data:o}}}};import{parseJWT as Ct}from"oslo/jwt";import{betterFetch as Bt}from"@better-fetch/fetch";var xe=e=>({id:"google",name:"Google",async createAuthorizationURL({state:t,scopes:r,codeVerifier:o,redirectURI:n}){if(!e.clientId||!e.clientSecret)throw m.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 y({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})=>w({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 Bt(o);return n?n.aud===e.clientId&&n.iss==="https://accounts.google.com":!1},async getUserInfo(t){if(!t.idToken)return null;let r=Ct(t.idToken)?.payload;return{user:{id:r.sub,name:r.name,email:r.email,image:r.picture,emailVerified:r.email_verified},data:r}}});import{betterFetch as Dt}from"@better-fetch/fetch";import{parseJWT as Vt}from"oslo/jwt";var Te=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),y({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 w({code:n,codeVerifier:i,redirectURI:e.redirectURI||s,options:e,tokenEndpoint:o})},async getUserInfo(n){if(!n.idToken)return null;let i=Vt(n.idToken)?.payload,s=e.profilePhotoSize||48;return await Dt(`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 c=await a.response.clone().arrayBuffer(),u=Buffer.from(c).toString("base64");i.picture=`data:image/jpeg;base64, ${u}`}catch(d){m.error(d)}}}),{user:{id:i.sub,name:i.name,email:i.email,image:i.picture,emailVerified:!0},data:i}}}};import{betterFetch as zt}from"@better-fetch/fetch";var Pe=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),y({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})=>w({code:t,codeVerifier:r,redirectURI:e.redirectURI||o,options:e,tokenEndpoint:"https://accounts.spotify.com/api/token"}),async getUserInfo(t){let{data:r,error:o}=await zt("https://api.spotify.com/v1/me",{method:"GET",headers:{Authorization:`Bearer ${t.accessToken}`}});return o?null:{user:{id:r.id,name:r.display_name,email:r.email,image:r.images[0]?.url,emailVerified:!1},data:r}}});import"@better-fetch/fetch";import{parseJWT as $t}from"oslo/jwt";var Se=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),y({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})=>w({code:t,redirectURI:e.redirectURI||r,options:e,tokenEndpoint:"https://id.twitch.tv/oauth2/token"}),async getUserInfo(t){let r=t.idToken;if(!r)return m.error("No idToken found in token"),null;let o=$t(r)?.payload;return{user:{id:o.sub,name:o.preferred_username,email:o.email,image:o.picture,emailVerified:!1},data:o}}});import{betterFetch as jt}from"@better-fetch/fetch";var Oe=e=>({id:"twitter",name:"Twitter",createAuthorizationURL(t){let r=t.scopes||["users.read","tweet.read","offline.access"];return e.scope&&r.push(...e.scope),y({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})=>w({code:t,codeVerifier:r,authentication:"basic",redirectURI:e.redirectURI||o,options:e,tokenEndpoint:"https://api.x.com/2/oauth2/token"}),async getUserInfo(t){let{data:r,error:o}=await jt("https://api.x.com/2/users/me?user.fields=profile_image_url",{method:"GET",headers:{Authorization:`Bearer ${t.accessToken}`}});return o?null:{user:{id:r.data.id,name:r.data.name,email:r.data.email||null,image:r.data.profile_image_url,emailVerified:r.data.verified||!1},data:r}}});import{betterFetch as qt}from"@better-fetch/fetch";var Ie=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 y({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 w({code:r,codeVerifier:o,redirectURI:e.redirectURI||n,options:e,tokenEndpoint:t}),async getUserInfo(r){let{data:o,error:n}=await qt("https://api.dropboxapi.com/2/users/get_current_account",{method:"POST",headers:{Authorization:`Bearer ${r.accessToken}`}});return n?null:{user:{id:o.account_id,name:o.name?.display_name,email:o.email,emailVerified:o.email_verified||!1,image:o.profile_photo_url},data:o}}}};import{betterFetch as Nt}from"@better-fetch/fetch";var Le=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 y({id:"linkedin",options:e,authorizationEndpoint:t,scopes:s,state:o,redirectURI:i})},validateAuthorizationCode:async({code:o,redirectURI:n})=>await w({code:o,redirectURI:e.redirectURI||n,options:e,tokenEndpoint:r}),async getUserInfo(o){let{data:n,error:i}=await Nt("https://api.linkedin.com/v2/userinfo",{method:"GET",headers:{Authorization:`Bearer ${o.accessToken}`}});return i?null:{user:{id:n.sub,name:n.name,email:n.email,emailVerified:n.email_verified||!1,image:n.picture},data:n}}}};import{betterFetch as Ft}from"@better-fetch/fetch";var se=(e="")=>e.split("://").map(t=>t.replace(/\/{2,}/g,"/")).join("://"),Ht=e=>{let t=e||"https://gitlab.com";return{authorizationEndpoint:se(`${t}/oauth/authorize`),tokenEndpoint:se(`${t}/oauth/token`),userinfoEndpoint:se(`${t}/api/v4/user`)}},Ce=e=>{let{authorizationEndpoint:t,tokenEndpoint:r,userinfoEndpoint:o}=Ht(e.issuer),n="gitlab";return{id:n,name:"Gitlab",createAuthorizationURL:async({state:s,scopes:a,codeVerifier:d,redirectURI:c})=>{let u=a||["read_user"];return e.scope&&u.push(...e.scope),await y({id:n,options:e,authorizationEndpoint:t,scopes:u,state:s,redirectURI:c,codeVerifier:d})},validateAuthorizationCode:async({code:s,redirectURI:a,codeVerifier:d})=>w({code:s,redirectURI:e.redirectURI||a,options:e,codeVerifier:d,tokenEndpoint:r}),async getUserInfo(s){let{data:a,error:d}=await Ft(o,{headers:{authorization:`Bearer ${s.accessToken}`}});return d||a.state!=="active"||a.locked?null:{user:{id:a.id.toString(),name:a.name??a.username,email:a.email,image:a.avatar_url,emailVerified:!0},data:a}}}};var Mt={apple:Re,discord:Ue,facebook:ve,github:_e,microsoft:Te,google:xe,spotify:Pe,twitch:Se,twitter:Oe,dropbox:Ie,linkedin:Le,gitlab:Ce},Y=Object.keys(Mt);import{TimeSpan as Gt}from"oslo";import{createJWT as Qt,validateJWT as Zt}from"oslo/jwt";import{z as I}from"zod";import{APIError as q}from"better-call";import{APIError as j}from"better-call";import{z as M}from"zod";function Be(e){try{return JSON.parse(e)}catch{return null}}var ae=()=>p("/get-session",{method:"GET",query:M.optional(M.object({disableCookieCache:M.boolean().optional()})),requireHeaders:!0},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?Be(Buffer.from(r,"base64").toString()):null;if(o&&!await K.verify({value:JSON.stringify(o.session),signature:o?.signature,secret:e.context.secret}))return C(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 h=e.context.authCookies.sessionData.name;e.setCookie(h,"",{maxAge:0})}else return e.json(u)}let i=await e.context.internalAdapter.findSession(t);if(!i||i.session.expiresAt<new Date)return C(e),i&&await e.context.internalAdapter.deleteSession(i.session.id),e.json(null);if(n)return e.json(i);let s=e.context.sessionConfig.expiresIn,a=e.context.sessionConfig.updateAge;if(i.session.expiresAt.valueOf()-s*1e3+a*1e3<=Date.now()){let u=await e.context.internalAdapter.updateSession(i.session.id,{expiresAt:L(e.context.sessionConfig.expiresIn,"sec")});if(!u)return C(e),e.json(null,{status:401});let f=(u.expiresAt.valueOf()-Date.now())/1e3;return await T(e,{session:u,user:i.user},!1,{maxAge:f}),e.json({session:u,user:i.user})}return e.json(i)}catch(t){throw e.context.logger.error(t),new j("INTERNAL_SERVER_ERROR",{message:"internal server error"})}}),X=async e=>{if(e.context.session)return e.context.session;let t=await ae()({...e,_flag:"json",headers:e.headers});return e.context.session=t,t},S=Z(async e=>{let t=await X(e);if(!t?.session)throw new j("UNAUTHORIZED");return{session:t}}),De=()=>p("/list-sessions",{method:"GET",use:[S],requireHeaders:!0},async e=>{let r=(await e.context.internalAdapter.listSessions(e.context.session.user.id)).filter(o=>o.expiresAt>new Date);return e.json(r)}),Ve=p("/revoke-session",{method:"POST",body:M.object({id:M.string()}),use:[S],requireHeaders:!0},async e=>{let t=e.body.id,r=await e.context.internalAdapter.findSession(t);if(!r)throw new j("BAD_REQUEST",{message:"Session not found"});if(r.session.userId!==e.context.session.user.id)throw new j("UNAUTHORIZED");try{await e.context.internalAdapter.deleteSession(t)}catch(o){throw e.context.logger.error(o),new j("INTERNAL_SERVER_ERROR")}return e.json({status:!0})}),ze=p("/revoke-sessions",{method:"POST",use:[S],requireHeaders:!0},async e=>{try{await e.context.internalAdapter.deleteSessions(e.context.session.user.id)}catch(t){throw e.context.logger.error(t),new j("INTERNAL_SERVER_ERROR")}return e.json({status:!0})}),$e=p("/revoke-other-sessions",{method:"POST",requireHeaders:!0,use:[S]},async e=>{let t=e.context.session;if(!t.user)throw new j("UNAUTHORIZED");let n=(await e.context.internalAdapter.listSessions(t.user.id)).filter(i=>i.expiresAt>new Date).filter(i=>i.id!==e.context.session.session.id);return await Promise.all(n.map(i=>e.context.internalAdapter.deleteSession(i.id))),e.json({status:!0})});async function B(e,t,r){return await Qt("HS256",Buffer.from(e),{email:t.toLowerCase(),updateTo:r},{expiresIn:new Gt(1,"h"),issuer:"better-auth",subject:"verify-email",audiences:[t],includeIssuedTimestamp:!0})}var je=p("/send-verification-email",{method:"POST",query:I.object({currentURL:I.string().optional()}).optional(),body:I.object({email:I.string().email(),callbackURL:I.string().optional()})},async e=>{if(!e.context.options.emailVerification?.sendVerificationEmail)throw e.context.logger.error("Verification email isn't enabled."),new q("BAD_REQUEST",{message:"Verification email isn't enabled"});let{email:t}=e.body,r=await e.context.internalAdapter.findUserByEmail(t);if(!r)throw new q("BAD_REQUEST",{message:"User not found"});let o=await B(e.context.secret,t),n=`${e.context.baseURL}/verify-email?token=${o}&callbackURL=${e.body.callbackURL||e.query?.currentURL||"/"}`;return await e.context.options.emailVerification.sendVerificationEmail({user:r.user,url:n,token:o},e.request),e.json({status:!0})}),qe=p("/verify-email",{method:"GET",query:I.object({token:I.string(),callbackURL:I.string().optional()})},async e=>{let{token:t}=e.query,r;try{r=await Zt("HS256",Buffer.from(e.context.secret),t)}catch(s){throw e.context.logger.error("Failed to verify email",s),new q("BAD_REQUEST",{message:"Invalid token"})}let n=I.object({email:I.string().email(),updateTo:I.string().optional()}).parse(r.payload),i=await e.context.internalAdapter.findUserByEmail(n.email);if(!i)throw new q("BAD_REQUEST",{message:"User not found"});if(n.updateTo){let s=await X(e);if(!s)throw e.query.callbackURL?e.redirect(`${e.query.callbackURL}?error=unauthorized`):new q("UNAUTHORIZED",{message:"Session not found"});if(s.user.email!==n.email)throw e.query.callbackURL?e.redirect(`${e.query.callbackURL}?error=unauthorized`):new q("UNAUTHORIZED",{message:"Invalid session"});let a=await e.context.internalAdapter.updateUserByEmail(n.email,{email:n.updateTo});if(await e.context.options.emailVerification?.sendVerificationEmail?.({user:a,url:`${e.context.baseURL}/verify-email?token=${t}`,token:t},e.request),e.query.callbackURL)throw e.redirect(e.query.callbackURL);return e.json({user:a,status:!0})}if(await e.context.internalAdapter.updateUserByEmail(n.email,{emailVerified:!0}),e.context.options.emailVerification?.autoSignInAfterVerification&&!await X(e)){let a=await e.context.internalAdapter.createSession(i.user.id,e.request);if(!a)throw new q("INTERNAL_SERVER_ERROR",{message:"Failed to create session"});await T(e,{session:a,user:i.user})}if(e.query.callbackURL)throw e.redirect(e.query.callbackURL);return e.json({user:null,status:!0})});async function ee(e,{userInfo:t,account:r,callbackURL:o}){let n=await e.context.internalAdapter.findUserByEmail(t.email.toLowerCase(),{includeAccounts:!0}).catch(a=>{throw m.error(`Better auth was unable to query your database.
|
|
4
4
|
Error: `,a),e.redirect(`${e.context.baseURL}/error?error=internal_server_error`)}),i=n?.user;if(n){let a=n.accounts.find(d=>d.providerId===r.providerId);if(a)await e.context.internalAdapter.updateAccount(a.id,{accessToken:r.accessToken,idToken:r.idToken,refreshToken:r.refreshToken,expiresAt:r.expiresAt});else{if(!e.context.options.account?.accountLinking?.trustedProviders?.includes(r.providerId)&&!t.emailVerified||e.context.options.account?.accountLinking?.enabled===!1)return me&&m.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(),id:e.context.uuid(),userId:n.user.id,accessToken:r.accessToken,idToken:r.idToken,refreshToken:r.refreshToken,expiresAt:r.expiresAt})}catch(u){return m.error("Unable to link account",u),{error:"unable to link account",data:null}}}}else try{let a=t.emailVerified||!1;if(i=await e.context.internalAdapter.createOAuthUser({...t,id:e.context.uuid(),emailVerified:a,email:t.email.toLowerCase()},{accessToken:r.accessToken,idToken:r.idToken,refreshToken:r.refreshToken,expiresAt:r.expiresAt,providerId:r.providerId,accountId:t.id.toString()}).then(d=>d?.user),!a&&i&&e.context.options.emailVerification?.sendOnSignUp){let d=await B(e.context.secret,i.email),c=`${e.context.baseURL}/verify-email?token=${d}&callbackURL=${o}`;await e.context.options.emailVerification?.sendVerificationEmail?.({user:i,url:c,token:d},e.request)}}catch(a){return m.error("Unable to create user",a),{error:"unable to create user",data:null}}if(!i)return{error:"unable to create user",data:null};let s=await e.context.internalAdapter.createSession(i.id,e.request);return s?{data:{session:s,user:i},error:null}:{error:"unable to create session",data:null}}var Ne=p("/sign-in/social",{method:"POST",query:k.object({currentURL:k.string().optional()}).optional(),body:k.object({callbackURL:k.string().optional(),errorCallbackURL:k.string().optional(),provider:k.enum(Y),idToken:k.optional(k.object({token:k.string(),nonce:k.string().optional(),accessToken:k.string().optional(),refreshToken:k.string().optional(),expiresAt:k.number().optional()}))})},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 v("NOT_FOUND",{message:"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("NOT_FOUND",{message:"Provider does not support id token verification"});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 v("UNAUTHORIZED",{message:"Invalid id token"});let d=await t.getUserInfo({idToken:i,accessToken:e.body.idToken.accessToken,refreshToken:e.body.idToken.refreshToken});if(!d||!d?.user)throw e.context.logger.error("Failed to get user info",{provider:e.body.provider}),new v("UNAUTHORIZED",{message:"Failed to get user info"});if(!d.user.email)throw e.context.logger.error("User email not found",{provider:e.body.provider}),new v("UNAUTHORIZED",{message:"User email not found"});let c=await ee(e,{userInfo:{email:d.user.email,id:d.user.id,name:d.user.name||"",image:d.user.image,emailVerified:d.user.emailVerified||!1},account:{providerId:t.id,accountId:d.user.id,accessToken:e.body.idToken.accessToken}});if(c.error)throw new v("UNAUTHORIZED",{message:c.error});return await T(e,c.data),e.json({session:c.data.session,user:c.data.user,url:`${e.body.callbackURL||e.query?.currentURL||e.context.options.baseURL}`,redirect:!0})}let{codeVerifier:r,state:o}=await W(e),n=await t.createAuthorizationURL({state:o,codeVerifier:r,redirectURI:`${e.context.baseURL}/callback/${t.id}`});return e.json({url:n.toString(),redirect:!0})}),Fe=p("/sign-in/email",{method:"POST",body:k.object({email:k.string(),password:k.string(),callbackURL:k.string().optional(),rememberMe:k.boolean().default(!1).optional()})},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("BAD_REQUEST",{message:"Email and password is not enabled"});let{email:t,password:r}=e.body;if(!k.string().email().safeParse(t).success)throw new v("BAD_REQUEST",{message:"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 v("UNAUTHORIZED",{message:"Invalid email or password"});let i=n.accounts.find(c=>c.providerId==="credential");if(!i)throw e.context.logger.error("Credential account not found",{email:t}),new v("UNAUTHORIZED",{message:"Invalid email or password"});let s=i?.password;if(!s)throw e.context.logger.error("Password not found",{email:t}),new v("UNAUTHORIZED",{message:"Unexpected error"});if(!await e.context.password.verify(s,r))throw e.context.logger.error("Invalid password"),new v("UNAUTHORIZED",{message:"Invalid email or password"});if(e.context.options?.emailAndPassword?.requireEmailVerification&&!n.user.emailVerified){if(!e.context.options?.emailVerification?.sendVerificationEmail)throw m.error("Email verification is required but no email verification handler is provided"),new v("INTERNAL_SERVER_ERROR",{message:"Email is not verified."});let c=await B(e.context.secret,n.user.email),u=`${e.context.baseURL}/verify-email?token=${c}`;throw await e.context.options.emailVerification.sendVerificationEmail({user:n.user,url:u,token:c},e.request),e.context.logger.error("Email not verified",{email:t}),new v("FORBIDDEN",{message:"Email is not verified. Check your email for a verification link"})}let d=await e.context.internalAdapter.createSession(n.user.id,e.headers,e.body.rememberMe===!1);if(!d)throw e.context.logger.error("Failed to create session"),new v("UNAUTHORIZED",{message:"Failed to create session"});return await T(e,{session:d,user:n.user},e.body.rememberMe===!1),e.json({user:n.user,session:d,redirect:!!e.body.callbackURL,url:e.body.callbackURL})});import{z as te}from"zod";var re=te.object({code:te.string().optional(),error:te.string().optional(),state:te.string().optional()}),He=p("/callback/:id",{method:["GET","POST"],body:re.optional(),query:re.optional(),metadata:N},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(_){throw e.context.logger.error(_),e.redirect(`${e.context.baseURL}/error?error=invalid_callback_request`)}let{code:r,error:o,state:n}=t;if(!n)throw e.context.logger.error("State not found"),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"}`);let i=e.context.socialProviders.find(_=>_.id===e.params.id);if(!i)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:s,callbackURL:a,link:d,errorURL:c}=await we(e),u;try{u=await i.validateAuthorizationCode({code:r,codeVerifier:s,redirectURI:`${e.context.baseURL}/callback/${i.id}`})}catch(_){throw e.context.logger.error(_),e.redirect(`${e.context.baseURL}/error?error=please_restart_the_process`)}let f=await i.getUserInfo(u).then(_=>_?.user),l={id:le(),...f};function b(_){let x=c||a||`${e.context.baseURL}/error`;throw x.includes("?")?x=`${x}&error=${_}`:x=`${x}?error=${_}`,e.redirect(x)}if(!f)return m.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 m.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:i.id,accountId:f.id}))return b("unable_to_link_account");let x;try{x=new URL(a).toString()}catch{x=a}throw e.redirect(x)}let R=await ee(e,{userInfo:{email:l.email,id:l.id,name:l.name||"",image:l.image,emailVerified:l.emailVerified||!1},account:{providerId:i.id,accountId:f.id,accessToken:u.accessToken,refreshToken:u.refreshToken,expiresAt:u.accessTokenExpiresAt},callbackURL:a});if(R.error)return b(R.error.split(" ").join("_"));let{session:P,user:A}=R.data;await T(e,{session:P,user:A});let Q;try{Q=new URL(a).toString()}catch{Q=a}throw e.redirect(Q)});import"zod";import{APIError as Jt}from"better-call";var Me=p("/sign-out",{method:"POST",requireHeaders:!0},async e=>{let t=await e.getSignedCookie(e.context.authCookies.sessionToken.name,e.context.secret);if(!t)throw C(e),new Jt("BAD_REQUEST",{message:"Session not found"});return await e.context.internalAdapter.deleteSession(t),C(e),e.json({success:!0})});import{z as O}from"zod";import{APIError as oe}from"better-call";function Ge(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 Wt(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 Qe=p("/forget-password",{method:"POST",body:O.object({email:O.string().email(),redirectTo:O.string()})},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 oe("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=L(e.context.options.emailAndPassword.resetPasswordTokenExpiresIn||n,"sec"),s=e.context.uuid();await e.context.internalAdapter.createVerificationValue({value:o.user.id,identifier:`reset-password:${s}`,expiresAt:i});let a=`${e.context.baseURL}/reset-password/${s}?callbackURL=${r}`;return await e.context.options.emailAndPassword.sendResetPassword({user:o.user,url:a,token:s},e.request),e.json({status:!0})}),Ze=p("/reset-password/:token",{method:"GET",query:O.object({callbackURL:O.string()})},async e=>{let{token:t}=e.params,{callbackURL:r}=e.query;if(!t||!r)throw e.redirect(Ge(e.context,r,{error:"INVALID_TOKEN"}));let o=await e.context.internalAdapter.findVerificationValue(`reset-password:${t}`);throw!o||o.expiresAt<new Date?e.redirect(Ge(e.context,r,{error:"INVALID_TOKEN"})):e.redirect(Wt(e.context,r,{token:t}))}),Je=p("/reset-password",{query:O.optional(O.object({token:O.string().optional(),currentURL:O.string().optional()})),method:"POST",body:O.object({newPassword:O.string(),token:O.string().optional()})},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 oe("BAD_REQUEST",{message:"Token not found"});let{newPassword:r}=e.body,o=`reset-password:${t}`,n=await e.context.internalAdapter.findVerificationValue(o);if(!n||n.expiresAt<new Date)throw new oe("BAD_REQUEST",{message:"Invalid token"});await e.context.internalAdapter.deleteVerificationValue(n.id);let i=n.value,s=await e.context.password.hash(r);if(!(await e.context.internalAdapter.findAccounts(i)).find(u=>u.providerId==="credential"))return await e.context.internalAdapter.createAccount({userId:i,providerId:"credential",password:s,accountId:e.context.uuid()}),e.json({status:!0});if(!await e.context.internalAdapter.updatePassword(i,s))throw new oe("BAD_REQUEST",{message:"Failed to update password"});return e.json({status:!0})});import{z as U}from"zod";import{APIError as E}from"better-call";import{z as g}from"zod";var Di=g.object({id:g.string(),providerId:g.string(),accountId:g.string(),userId:g.string(),accessToken:g.string().nullish(),refreshToken:g.string().nullish(),idToken:g.string().nullish(),expiresAt:g.date().nullish(),password:g.string().nullish()}),Vi=g.object({id:g.string(),email:g.string().transform(e=>e.toLowerCase()),emailVerified:g.boolean().default(!1),name:g.string(),image:g.string().nullish(),createdAt:g.date().default(new Date),updatedAt:g.date().default(new Date)}),zi=g.object({id:g.string(),userId:g.string(),expiresAt:g.date(),ipAddress:g.string().nullish(),userAgent:g.string().nullish()}),$i=g.object({id:g.string(),value:g.string(),createdAt:g.date(),expiresAt:g.date(),identifier:g.string()});function Kt(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 Yt(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}n[i]=e[i];continue}if(o[i].defaultValue&&r==="create"){n[i]=o[i].defaultValue;continue}}return n}function ne(e,t,r){let o=Kt(e,"user");return Yt(t||{},{fields:o,action:r})}var We=()=>p("/update-user",{method:"POST",body:U.record(U.string(),U.any()),use:[S]},async e=>{let t=e.body;if(t.email)throw new E("BAD_REQUEST",{message:"You can't update email"});let{name:r,image:o,...n}=t,i=e.context.session;if(!o&&!r&&Object.keys(n).length===0)return e.json({user:i.user});let s=ne(e.context.options,n,"update"),a=await e.context.internalAdapter.updateUserByEmail(i.user.email,{name:r,image:o,...s});return await T(e,{session:i.session,user:a}),e.json({user:a})}),Ke=p("/change-password",{method:"POST",body:U.object({newPassword:U.string(),currentPassword:U.string(),revokeOtherSessions:U.boolean().optional()}),use:[S]},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 E("BAD_REQUEST",{message:"Password is too short"});let s=e.context.password.config.maxPasswordLength;if(t.length>s)throw e.context.logger.error("Password is too long"),new E("BAD_REQUEST",{message:"Password too long"});let d=(await e.context.internalAdapter.findAccounts(n.user.id)).find(f=>f.providerId==="credential"&&f.password);if(!d||!d.password)throw new E("BAD_REQUEST",{message:"User does not have a password"});let c=await e.context.password.hash(t);if(!await e.context.password.verify(d.password,r))throw new E("BAD_REQUEST",{message:"Incorrect password"});if(await e.context.internalAdapter.updateAccount(d.id,{password:c}),o){await e.context.internalAdapter.deleteSessions(n.user.id);let f=await e.context.internalAdapter.createSession(n.user.id,e.headers);if(!f)throw new E("INTERNAL_SERVER_ERROR",{message:"Unable to create session"});await T(e,{session:f,user:n.user})}return e.json(n.user)}),Ye=p("/set-password",{method:"POST",body:U.object({newPassword:U.string()}),metadata:{SERVER_ONLY:!0},use:[S]},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("BAD_REQUEST",{message:"Password is too short"});let n=e.context.password.config.maxPasswordLength;if(t.length>n)throw e.context.logger.error("Password is too long"),new E("BAD_REQUEST",{message:"Password too long"});let s=(await e.context.internalAdapter.findAccounts(r.user.id)).find(d=>d.providerId==="credential"&&d.password),a=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:a}),e.json(r.user);throw new E("BAD_REQUEST",{message:"user already has a password"})}),Xe=p("/delete-user",{method:"POST",body:U.object({password:U.string()}),use:[S]},async e=>{let{password:t}=e.body,r=e.context.session,n=(await e.context.internalAdapter.findAccounts(r.user.id)).find(s=>s.providerId==="credential"&&s.password);if(!n||!n.password)throw new E("BAD_REQUEST",{message:"User does not have a password"});if(!await e.context.password.verify(n.password,t))throw new E("BAD_REQUEST",{message:"Incorrect password"});return await e.context.internalAdapter.deleteUser(r.user.id),await e.context.internalAdapter.deleteSessions(r.user.id),C(e),e.json(null)}),et=p("/change-email",{method:"POST",query:U.object({currentURL:U.string().optional()}).optional(),body:U.object({newEmail:U.string().email(),callbackURL:U.string().optional()}),use:[S]},async e=>{if(!e.context.options.user?.changeEmail?.enabled)throw e.context.logger.error("Change email is disabled."),new E("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("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("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({user:n,status:!0})}if(!e.context.options.user.changeEmail.sendChangeEmailVerification)throw e.context.logger.error("Verification email isn't enabled."),new E("BAD_REQUEST",{message:"Verification email isn't enabled"});let r=await B(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({user:null,status:!0})});var Xt=(e="Unknown")=>`<!DOCTYPE html>
|
|
@@ -81,4 +81,4 @@ Error: `,a),e.redirect(`${e.context.baseURL}/error?error=internal_server_error`)
|
|
|
81
81
|
<div class="error-code">Error Code: <span id="errorCode">${e}</span></div>
|
|
82
82
|
</div>
|
|
83
83
|
</body>
|
|
84
|
-
</html>`,tt=p("/error",{method:"GET",metadata:N},async e=>{let t=new URL(e.request?.url||"").searchParams.get("error")||"Unknown";return new Response(Xt(t),{headers:{"Content-Type":"text/html"}})});var rt=p("/ok",{method:"GET",metadata:N},async e=>e.json({ok:!0}));import{z as F}from"zod";import{APIError as D}from"better-call";var ot=()=>p("/sign-up/email",{method:"POST",query:F.object({currentURL:F.string().optional()}).optional(),body:F.record(F.string(),F.any())},async e=>{if(!e.context.options.emailAndPassword?.enabled)throw new D("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,...a}=t;if(!F.string().email().safeParse(o).success)throw new D("BAD_REQUEST",{message:"Invalid email"});let c=e.context.password.config.minPasswordLength;if(n.length<c)throw e.context.logger.error("Password is too short"),new D("BAD_REQUEST",{message:"Password is too short"});let u=e.context.password.config.maxPasswordLength;if(n.length>u)throw e.context.logger.error("Password is too long"),new D("BAD_REQUEST",{message:"Password is too long"});if((await e.context.internalAdapter.findUserByEmail(o))?.user)throw e.context.logger.info(`Sign-up attempt for existing email: ${o}`),new D("UNPROCESSABLE_ENTITY",{message:"User with this email already exists"});let h=ne(e.context.options,a),l;try{if(l=await e.context.internalAdapter.createUser({email:o.toLowerCase(),name:r,image:i,...h,emailVerified:!1}),!l)throw new D("BAD_REQUEST",{message:"Failed to create user"})}catch(P){throw m.error("Failed to create user",P),new D("UNPROCESSABLE_ENTITY",{message:"Failed to create user",details:P})}if(!l)throw new D("UNPROCESSABLE_ENTITY",{message:"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,expiresAt:L(60*60*24*30,"sec")}),e.context.options.emailVerification?.sendOnSignUp){let P=await B(e.context.secret,l.email),A=`${e.context.baseURL}/verify-email?token=${P}&callbackURL=${t.callbackURL||e.query?.currentURL||"/"}`;await e.context.options.emailVerification?.sendVerificationEmail?.({user:l,url:A,token:P},e.request)}if(!e.context.options.emailAndPassword.autoSignIn||e.context.options.emailAndPassword.requireEmailVerification)return e.json({user:l,session:null},{body:t.callbackURL?{url:t.callbackURL,redirect:!0}:{user:l,session:null}});let R=await e.context.internalAdapter.createSession(l.id,e.request);if(!R)throw new D("BAD_REQUEST",{message:"Failed to create session"});return await T(e,{session:R,user:l}),e.json({user:l,session:R})});import{z as G}from"zod";import{APIError as nt}from"better-call";var it=p("/list-accounts",{method:"GET",use:[S]},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})))}),st=p("/link-social",{method:"POST",requireHeaders:!0,query:G.object({currentURL:G.string().optional()}).optional(),body:G.object({callbackURL:G.string().optional(),provider:G.enum(Y)}),use:[S]},async e=>{let t=e.context.session;if((await e.context.internalAdapter.findAccounts(t.user.id)).find(a=>a.providerId===e.body.provider))throw new nt("BAD_REQUEST",{message:"Social Account is already linked."});let n=e.context.socialProviders.find(a=>a.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 nt("NOT_FOUND",{message:"Provider not found"});let i=await W(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 at(e,t){if(t.advanced?.ipAddress?.disableIpTracking)return null;let r="127.0.0.1";if(fe)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 a=i.get(s);if(typeof a=="string"){let d=a.split(",")[0].trim();if(d)return d}}return null}function er(e,t,r){let o=Date.now(),n=t*1e3;return o-r.lastRequest<n&&r.count>=e}function tr(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 rr(e,t){let r=Date.now(),o=t*1e3;return Math.ceil((e+o-r)/1e3)}function or(e,t){let r=t??"rateLimit",o=e.adapter;return{get:async n=>await o.findOne({model:r,where:[{field:"key",value:n}]}),set:async(n,i,s)=>{try{s?await o.update({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(a){m.error("Error setting rate limit",a)}}}}var dt=new Map;function nr(e){return 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 dt.get(r)},async set(r,o,n){dt.set(r,o)}}:or(e,e.rateLimit.tableName)}async function ct(e,t){if(!t.rateLimit.enabled)return;let r=t.baseURL,o=e.url.replace(r,""),n=t.rateLimit.window,i=t.rateLimit.max,s=at(e,t.options)+o,d=ir().find(h=>h.pathMatcher(o));d&&(n=d.window,i=d.max);for(let h of t.options.plugins||[])if(h.rateLimit){let l=h.rateLimit.find(b=>b.pathMatcher(o));if(l){n=l.window,i=l.max;break}}if(t.rateLimit.customRules){let h=t.rateLimit.customRules[o];h&&(n=h.window,i=h.max)}let c=nr(t),u=await c.get(s),f=Date.now();if(!u)await c.set(s,{key:s,count:1,lastRequest:f});else{let h=f-u.lastRequest;if(er(i,n,u)){let l=rr(u.lastRequest,n);return tr(l)}else h>n*1e3?await c.set(s,{...u,count:1,lastRequest:f}):await c.set(s,{...u,count:u.count+1,lastRequest:f})}}function ir(){return[{pathMatcher(t){return t.startsWith("/sign-in")||t.startsWith("/sign-up")||t.startsWith("/change-password")||t.startsWith("/change-email")},window:10,max:3}]}import{APIError as ra}from"better-call";function dr(e,t){let r=t.plugins?.reduce((a,d)=>({...a,...d.endpoints}),{}),o=t.plugins?.map(a=>a.middlewares?.map(d=>{let c=async u=>d.middleware({...u,context:{...e,...u.context}});return c.path=d.path,c.options=d.middleware.options,c.headers=d.middleware.headers,{path:d.path,middleware:c}})).filter(a=>a!==void 0).flat()||[],i={...{signInSocial:Ne,callbackOAuth:He,getSession:ae(),signOut:Me,signUpEmail:ot(),signInEmail:Fe,forgetPassword:Qe,resetPassword:Je,verifyEmail:qe,sendVerificationEmail:je,changeEmail:et,changePassword:Ke,setPassword:Ye,updateUser:We(),deleteUser:Xe,forgetPasswordCallback:Ze,listSessions:De(),revokeSession:Ve,revokeSessions:ze,revokeOtherSessions:$e,linkSocialAccount:st,listUserAccounts:it},...r,ok:rt,error:tt},s={};for(let[a,d]of Object.entries(i))s[a]=async(c={})=>{let u=await e;u.session=null;for(let l of t.plugins||[])if(l.hooks?.before)for(let b of l.hooks.before){let R={...d,...c,context:{...u,...c?.context}};if(b.matcher(R)){let A=await b.handler(R);A&&"context"in A&&(c={...A,...c})}}let f;try{f=await d({...c,context:{...u,...c.context}})}catch(l){if(l instanceof de){let b=t.plugins?.map(A=>{if(A.hooks?.after)return A.hooks.after}).filter(A=>A!==void 0).flat();if(!b?.length)throw l;let R=new Response(JSON.stringify(l.body),{status:ar[l.status],headers:l.headers}),P;for(let A of b||[])if(A.matcher(c)){u.returned=R;let _={...d,...c,context:u},x=await A.handler(_);x&&"response"in x&&(P=x.response)}if(P instanceof Response)return P;throw l}throw l}let h=f;for(let l of t.plugins||[])if(l.hooks?.after)for(let b of l.hooks.after){let R={...c,context:{...u,...c.context,endpoint:d,returned:h}};if(b.matcher(R)){let A=await b.handler(R);A&&"response"in A&&(h=A.response)}}return h},s[a].path=d.path,s[a].method=d.method,s[a].options=d.options,s[a].headers=d.headers;return{api:s,middlewares:o}}var Ws=(e,t)=>{let{api:r,middlewares:o}=dr(e,t),n=new URL(e.baseURL).pathname;return sr(r,{extraContext:e,basePath:n,routerMiddleware:[{path:"/**",middleware:be},...o],async onRequest(i){for(let s of e.options.plugins||[])if(s.onRequest){let a=await s.onRequest(i,e);if(a&&"response"in a)return a.response}return ct(i,e)},async onResponse(i){for(let s of e.options.plugins||[])if(s.onResponse){let a=await s.onResponse(i,e);if(a)return a.response}return i},onError(i){if(i instanceof de&&i.status==="FOUND")return;if(t.onAPIError?.throw)throw i;if(t.onAPIError?.onError){t.onAPIError.onError(i,e);return}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"))){m.error(i.message),m.error("If you are seeing this error, it is likely that you need to run the migrations for the database or you need to update your database schema. If you recently updated the package, make sure to run the migrations.");return}let s=t.logger?.verboseLogging?m:void 0;t.logger?.disabled!==!0&&(i instanceof de?(i.status==="INTERNAL_SERVER_ERROR"&&m.error(i),s?.error(i.message)):m?.error(i))}})};export{ra as APIError,He as callbackOAuth,et as changeEmail,Ke as changePassword,p as createAuthEndpoint,Z as createAuthMiddleware,B as createEmailVerificationToken,Xe as deleteUser,tt as error,Qe as forgetPassword,Ze as forgetPasswordCallback,dr as getEndpoints,ae as getSession,X as getSessionFromCtx,st as linkSocialAccount,De as listSessions,it as listUserAccounts,rt as ok,ue as optionsMiddleware,be as originCheckMiddleware,Je as resetPassword,$e as revokeOtherSessions,Ve as revokeSession,ze as revokeSessions,Ws as router,je as sendVerificationEmail,S as sessionMiddleware,Ye as setPassword,Fe as signInEmail,Ne as signInSocial,Me as signOut,ot as signUpEmail,We as updateUser,qe as verifyEmail};
|
|
84
|
+
</html>`,tt=p("/error",{method:"GET",metadata:N},async e=>{let t=new URL(e.request?.url||"").searchParams.get("error")||"Unknown";return new Response(Xt(t),{headers:{"Content-Type":"text/html"}})});var rt=p("/ok",{method:"GET",metadata:N},async e=>e.json({ok:!0}));import{z as F}from"zod";import{APIError as D}from"better-call";var ot=()=>p("/sign-up/email",{method:"POST",query:F.object({currentURL:F.string().optional()}).optional(),body:F.record(F.string(),F.any())},async e=>{if(!e.context.options.emailAndPassword?.enabled)throw new D("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,...a}=t;if(!F.string().email().safeParse(o).success)throw new D("BAD_REQUEST",{message:"Invalid email"});let c=e.context.password.config.minPasswordLength;if(n.length<c)throw e.context.logger.error("Password is too short"),new D("BAD_REQUEST",{message:"Password is too short"});let u=e.context.password.config.maxPasswordLength;if(n.length>u)throw e.context.logger.error("Password is too long"),new D("BAD_REQUEST",{message:"Password is too long"});if((await e.context.internalAdapter.findUserByEmail(o))?.user)throw e.context.logger.info(`Sign-up attempt for existing email: ${o}`),new D("UNPROCESSABLE_ENTITY",{message:"User with this email already exists"});let h=ne(e.context.options,a),l;try{if(l=await e.context.internalAdapter.createUser({email:o.toLowerCase(),name:r,image:i,...h,emailVerified:!1}),!l)throw new D("BAD_REQUEST",{message:"Failed to create user"})}catch(P){throw m.error("Failed to create user",P),new D("UNPROCESSABLE_ENTITY",{message:"Failed to create user",details:P})}if(!l)throw new D("UNPROCESSABLE_ENTITY",{message:"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,expiresAt:L(60*60*24*30,"sec")}),e.context.options.emailVerification?.sendOnSignUp){let P=await B(e.context.secret,l.email),A=`${e.context.baseURL}/verify-email?token=${P}&callbackURL=${t.callbackURL||e.query?.currentURL||"/"}`;await e.context.options.emailVerification?.sendVerificationEmail?.({user:l,url:A,token:P},e.request)}if(!e.context.options.emailAndPassword.autoSignIn||e.context.options.emailAndPassword.requireEmailVerification)return e.json({user:l,session:null});let R=await e.context.internalAdapter.createSession(l.id,e.request);if(!R)throw new D("BAD_REQUEST",{message:"Failed to create session"});return await T(e,{session:R,user:l}),e.json({user:l,session:R})});import{z as G}from"zod";import{APIError as nt}from"better-call";var it=p("/list-accounts",{method:"GET",use:[S]},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})))}),st=p("/link-social",{method:"POST",requireHeaders:!0,query:G.object({currentURL:G.string().optional()}).optional(),body:G.object({callbackURL:G.string().optional(),provider:G.enum(Y)}),use:[S]},async e=>{let t=e.context.session;if((await e.context.internalAdapter.findAccounts(t.user.id)).find(a=>a.providerId===e.body.provider))throw new nt("BAD_REQUEST",{message:"Social Account is already linked."});let n=e.context.socialProviders.find(a=>a.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 nt("NOT_FOUND",{message:"Provider not found"});let i=await W(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 at(e,t){if(t.advanced?.ipAddress?.disableIpTracking)return null;let r="127.0.0.1";if(fe)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 a=i.get(s);if(typeof a=="string"){let d=a.split(",")[0].trim();if(d)return d}}return null}function er(e,t,r){let o=Date.now(),n=t*1e3;return o-r.lastRequest<n&&r.count>=e}function tr(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 rr(e,t){let r=Date.now(),o=t*1e3;return Math.ceil((e+o-r)/1e3)}function or(e,t){let r=t??"rateLimit",o=e.adapter;return{get:async n=>await o.findOne({model:r,where:[{field:"key",value:n}]}),set:async(n,i,s)=>{try{s?await o.update({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(a){m.error("Error setting rate limit",a)}}}}var dt=new Map;function nr(e){return 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 dt.get(r)},async set(r,o,n){dt.set(r,o)}}:or(e,e.rateLimit.tableName)}async function ct(e,t){if(!t.rateLimit.enabled)return;let r=t.baseURL,o=e.url.replace(r,""),n=t.rateLimit.window,i=t.rateLimit.max,s=at(e,t.options)+o,d=ir().find(h=>h.pathMatcher(o));d&&(n=d.window,i=d.max);for(let h of t.options.plugins||[])if(h.rateLimit){let l=h.rateLimit.find(b=>b.pathMatcher(o));if(l){n=l.window,i=l.max;break}}if(t.rateLimit.customRules){let h=t.rateLimit.customRules[o];h&&(n=h.window,i=h.max)}let c=nr(t),u=await c.get(s),f=Date.now();if(!u)await c.set(s,{key:s,count:1,lastRequest:f});else{let h=f-u.lastRequest;if(er(i,n,u)){let l=rr(u.lastRequest,n);return tr(l)}else h>n*1e3?await c.set(s,{...u,count:1,lastRequest:f}):await c.set(s,{...u,count:u.count+1,lastRequest:f})}}function ir(){return[{pathMatcher(t){return t.startsWith("/sign-in")||t.startsWith("/sign-up")||t.startsWith("/change-password")||t.startsWith("/change-email")},window:10,max:3}]}import{APIError as ra}from"better-call";function dr(e,t){let r=t.plugins?.reduce((a,d)=>({...a,...d.endpoints}),{}),o=t.plugins?.map(a=>a.middlewares?.map(d=>{let c=async u=>d.middleware({...u,context:{...e,...u.context}});return c.path=d.path,c.options=d.middleware.options,c.headers=d.middleware.headers,{path:d.path,middleware:c}})).filter(a=>a!==void 0).flat()||[],i={...{signInSocial:Ne,callbackOAuth:He,getSession:ae(),signOut:Me,signUpEmail:ot(),signInEmail:Fe,forgetPassword:Qe,resetPassword:Je,verifyEmail:qe,sendVerificationEmail:je,changeEmail:et,changePassword:Ke,setPassword:Ye,updateUser:We(),deleteUser:Xe,forgetPasswordCallback:Ze,listSessions:De(),revokeSession:Ve,revokeSessions:ze,revokeOtherSessions:$e,linkSocialAccount:st,listUserAccounts:it},...r,ok:rt,error:tt},s={};for(let[a,d]of Object.entries(i))s[a]=async(c={})=>{let u=await e;u.session=null;for(let l of t.plugins||[])if(l.hooks?.before)for(let b of l.hooks.before){let R={...d,...c,context:{...u,...c?.context}};if(b.matcher(R)){let A=await b.handler(R);A&&"context"in A&&(c={...A,...c})}}let f;try{f=await d({...c,context:{...u,...c.context}})}catch(l){if(l instanceof de){let b=t.plugins?.map(A=>{if(A.hooks?.after)return A.hooks.after}).filter(A=>A!==void 0).flat();if(!b?.length)throw l;let R=new Response(JSON.stringify(l.body),{status:ar[l.status],headers:l.headers}),P;for(let A of b||[])if(A.matcher(c)){u.returned=R;let _={...d,...c,context:u},x=await A.handler(_);x&&"response"in x&&(P=x.response)}if(P instanceof Response)return P;throw l}throw l}let h=f;for(let l of t.plugins||[])if(l.hooks?.after)for(let b of l.hooks.after){let R={...c,context:{...u,...c.context,endpoint:d,returned:h}};if(b.matcher(R)){let A=await b.handler(R);A&&"response"in A&&(h=A.response)}}return h},s[a].path=d.path,s[a].method=d.method,s[a].options=d.options,s[a].headers=d.headers;return{api:s,middlewares:o}}var Ws=(e,t)=>{let{api:r,middlewares:o}=dr(e,t),n=new URL(e.baseURL).pathname;return sr(r,{extraContext:e,basePath:n,routerMiddleware:[{path:"/**",middleware:be},...o],async onRequest(i){for(let s of e.options.plugins||[])if(s.onRequest){let a=await s.onRequest(i,e);if(a&&"response"in a)return a.response}return ct(i,e)},async onResponse(i){for(let s of e.options.plugins||[])if(s.onResponse){let a=await s.onResponse(i,e);if(a)return a.response}return i},onError(i){if(i instanceof de&&i.status==="FOUND")return;if(t.onAPIError?.throw)throw i;if(t.onAPIError?.onError){t.onAPIError.onError(i,e);return}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"))){m.error(i.message),m.error("If you are seeing this error, it is likely that you need to run the migrations for the database or you need to update your database schema. If you recently updated the package, make sure to run the migrations.");return}let s=t.logger?.verboseLogging?m:void 0;t.logger?.disabled!==!0&&(i instanceof de?(i.status==="INTERNAL_SERVER_ERROR"&&m.error(i),s?.error(i.message)):m?.error(i))}})};export{ra as APIError,He as callbackOAuth,et as changeEmail,Ke as changePassword,p as createAuthEndpoint,Z as createAuthMiddleware,B as createEmailVerificationToken,Xe as deleteUser,tt as error,Qe as forgetPassword,Ze as forgetPasswordCallback,dr as getEndpoints,ae as getSession,X as getSessionFromCtx,st as linkSocialAccount,De as listSessions,it as listUserAccounts,rt as ok,ue as optionsMiddleware,be as originCheckMiddleware,Je as resetPassword,$e as revokeOtherSessions,Ve as revokeSession,ze as revokeSessions,Ws as router,je as sendVerificationEmail,S as sessionMiddleware,Ye as setPassword,Fe as signInEmail,Ne as signInSocial,Me as signOut,ot as signUpEmail,We as updateUser,qe as verifyEmail};
|