better-auth 0.4.12 → 0.4.13
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.d.ts +10 -1
- package/dist/adapters/drizzle.js +1 -1
- package/dist/adapters/kysely.d.ts +10 -1
- package/dist/adapters/kysely.js +1 -2
- package/dist/adapters/mongodb.d.ts +13 -2
- package/dist/adapters/mongodb.js +1 -1
- package/dist/adapters/prisma.d.ts +12 -3
- package/dist/adapters/prisma.js +1 -1
- package/dist/api.d.ts +1 -1
- package/dist/api.js +4 -4
- package/dist/{auth-BqAt6mrY.d.ts → auth-C6fr77co.d.ts} +46 -26
- package/dist/client/plugins.d.ts +3 -3
- package/dist/client.d.ts +1 -1
- package/dist/cookies.d.ts +1 -1
- package/dist/db.d.ts +3 -3
- package/dist/db.js +3 -3
- package/dist/{index-BN_LDD1g.d.ts → index-pILRgibH.d.ts} +1 -1
- package/dist/index.d.ts +1 -1
- package/dist/index.js +4 -4
- package/dist/node.d.ts +1 -1
- package/dist/plugins.d.ts +3 -3
- package/dist/plugins.js +5 -5
- package/dist/react.d.ts +1 -1
- package/dist/social.js +2 -2
- package/dist/solid-start.d.ts +1 -1
- package/dist/solid.d.ts +1 -1
- package/dist/svelte-kit.d.ts +1 -1
- package/dist/svelte.d.ts +1 -1
- package/dist/types.d.ts +2 -2
- package/dist/vue.d.ts +1 -1
- package/package.json +1 -1
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { A as Adapter } from '../auth-
|
|
1
|
+
import { A as Adapter } from '../auth-C6fr77co.js';
|
|
2
2
|
import 'zod';
|
|
3
3
|
import 'kysely';
|
|
4
4
|
import '../schema-Dkt0LqYs.js';
|
|
@@ -18,6 +18,15 @@ interface DrizzleAdapterOptions {
|
|
|
18
18
|
* has an object with a key "users" instead of "user"
|
|
19
19
|
*/
|
|
20
20
|
usePlural?: boolean;
|
|
21
|
+
/**
|
|
22
|
+
* Custom generateId function.
|
|
23
|
+
*
|
|
24
|
+
* If not provided, nanoid will be used.
|
|
25
|
+
* If set to false, the database's auto generated id will be used.
|
|
26
|
+
*
|
|
27
|
+
* @default nanoid
|
|
28
|
+
*/
|
|
29
|
+
generateId?: ((size?: number) => string) | false;
|
|
21
30
|
}
|
|
22
31
|
interface DB {
|
|
23
32
|
[key: string]: any;
|
package/dist/adapters/drizzle.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
import{and as
|
|
1
|
+
import{and as g,asc as y,desc as P,eq as m,or as z}from"drizzle-orm";var h=class extends Error{constructor(t,l){super(t),this.name="BetterAuthError",this.message=t,this.cause=l,this.stack=""}};function f(r,t){let l=t.schema;if(!l)throw new h("Drizzle adapter failed to initialize. Schema not found. Please provide a schema object in the adapter options object.");let u=t.usePlural?`${r}s`:r,s=l[u];if(!s)throw new h(`[# Drizzle Adapter]: The model "${r}" was not found in the schema object. Please pass the schema directly to the adapter options.`);return s}function p(r,t){if(!r)return[];if(r.length===1){let e=r[0];return e?[m(t[e.field],e.value)]:[]}let l=r.filter(e=>e.connector==="AND"||!e.connector),u=r.filter(e=>e.connector==="OR"),s=g(...l.map(e=>m(t[e.field],e.value))),c=z(...u.map(e=>m(t[e.field],e.value))),a=[];return l.length&&a.push(s),u.length&&a.push(c),a}var B=(r,t)=>{let l=t.schema||r._.fullSchema,u=t?.provider;return{id:"drizzle",async create(s){let{model:c,data:a}=s,e=f(c,{schema:l,usePlural:t.usePlural});t.generateId!==void 0&&(a.id=t.generateId?t.generateId():void 0);let n=r.insert(e).values(a);return u!=="mysql"?(await n.returning())[0]:(await n,(await r.select().from(e).where(m(e.id,s.data.id)))[0])},async findOne(s){let{model:c,where:a,select:e}=s,n=f(c,{schema:l,usePlural:t.usePlural}),i=p(a,n),o=null;return e?.length?o=await r.select(...e.map(d=>({[d]:n[d]}))).from(n).where(...i):o=await r.select().from(n).where(...i),o.length?o[0]:null},async findMany(s){let{model:c,where:a,limit:e,offset:n,sortBy:i}=s,o=f(c,{schema:l,usePlural:t.usePlural}),d=a?p(a,o):[],w=i?.direction==="desc"?P:y;return await r.select().from(o).limit(e||100).offset(n||0).orderBy(w(o[i?.field||"id"])).where(...d.length?d:[])},async update(s){let{model:c,where:a,update:e}=s,n=f(c,{schema:l,usePlural:t.usePlural}),i=p(a,n),o=r.update(n).set(e).where(...i);return u!=="mysql"?(await o.returning())[0]:(await o,(await r.select().from(n).where(m(n.id,s.update.id)))[0])},async delete(s){let{model:c,where:a}=s,e=f(c,{schema:l,usePlural:t.usePlural}),n=p(a,e);return(await r.delete(e).where(...n))[0]},options:t}};export{B as drizzleAdapter};
|
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
import { Kysely } from 'kysely';
|
|
2
|
-
import { B as BetterAuthOptions, K as KyselyDatabaseType, F as FieldAttribute, A as Adapter } from '../auth-
|
|
2
|
+
import { B as BetterAuthOptions, K as KyselyDatabaseType, F as FieldAttribute, A as Adapter } from '../auth-C6fr77co.js';
|
|
3
3
|
import 'zod';
|
|
4
4
|
import '../schema-Dkt0LqYs.js';
|
|
5
5
|
import 'better-call';
|
|
@@ -28,6 +28,15 @@ interface KyselyAdapterConfig {
|
|
|
28
28
|
boolean: boolean;
|
|
29
29
|
date: boolean;
|
|
30
30
|
};
|
|
31
|
+
/**
|
|
32
|
+
* Custom generateId function.
|
|
33
|
+
*
|
|
34
|
+
* If not provided, nanoid will be used.
|
|
35
|
+
* If set to false, the database's auto generated id will be used.
|
|
36
|
+
*
|
|
37
|
+
* @default nanoid
|
|
38
|
+
*/
|
|
39
|
+
generateId?: ((size?: number) => string) | false;
|
|
31
40
|
}
|
|
32
41
|
declare const kyselyAdapter: (db: Kysely<any>, config?: KyselyAdapterConfig) => Adapter;
|
|
33
42
|
|
package/dist/adapters/kysely.js
CHANGED
|
@@ -1,2 +1 @@
|
|
|
1
|
-
import"kysely";import{
|
|
2
|
-
`)}}),O=k();import{Kysely as g,MssqlDialect as v}from"kysely";import{MysqlDialect as A,PostgresDialect as h,SqliteDialect as x}from"kysely";function w(t){if("dialect"in t)return w(t.dialect);if("createDriver"in t){if(t instanceof x)return"sqlite";if(t instanceof A)return"mysql";if(t instanceof h)return"postgres";if(t instanceof v)return"mssql"}return"aggregate"in t?"sqlite":"getConnection"in t?"mysql":"connect"in t?"postgres":null}var T=async t=>{let e=t.database;if("db"in e)return{kysely:e.db,databaseType:e.type};if("dialect"in e)return{kysely:new g({dialect:e.dialect}),databaseType:e.type};let i,r=w(e);return"createDriver"in e&&(i=e),"aggregate"in e&&(i=new x({database:e})),"getConnection"in e&&(i=new A({pool:e})),"connect"in e&&(i=new h({pool:e})),{kysely:i?new g({dialect:i}):null,databaseType:r}};import{z as me}from"zod";function y(t){if(!t)return{and:null,or:null};let e=t?.filter(r=>r.connector==="AND"||!r.connector).reduce((r,d)=>({...r,[d.field]:d.value}),{}),i=t?.filter(r=>r.connector==="OR").reduce((r,d)=>({...r,[d.field]:d.value}),{});return{and:Object.keys(e).length?e:null,or:Object.keys(i).length?i:null}}function p(t,e,i){for(let r in t)t[r]===0&&e[r]?.type==="boolean"&&i?.boolean&&(t[r]=!1),t[r]===1&&e[r]?.type==="boolean"&&i?.boolean&&(t[r]=!0),e[r]?.type==="date"&&(t[r]instanceof Date||(t[r]=new Date(t[r])));return t}function F(t,e){for(let i in t)typeof t[i]=="boolean"&&e?.boolean&&(t[i]=t[i]?1:0),t[i]instanceof Date&&(t[i]=t[i].toISOString());return t}var q=(t,e)=>({id:"kysely",async create(i){let{model:r,data:d,select:u}=i;e?.transform&&(d=F(d,e.transform));let a=await t.insertInto(r).values(d).returningAll().executeTakeFirst();if(e?.transform){let o=e.transform.schema[r];a=o?p(d,o,e.transform):a}return u?.length&&(a=a?u.reduce((n,s)=>a?.[s]?{...n,[s]:a[s]}:n,{}):null),a},async findOne(i){let{model:r,where:d,select:u}=i,{and:a,or:o}=y(d),n=t.selectFrom(r).selectAll();o&&(n=n.where(l=>l.or(o))),a&&(n=n.where(l=>l.and(a)));let s=await n.executeTakeFirst();if(u?.length&&(s=s?u.reduce((m,c)=>s?.[c]?{...m,[c]:s[c]}:m,{}):null),e?.transform){let l=e.transform.schema[r];return s=s&&l?p(s,l,e.transform):s,s||null}return s||null},async findMany(i){let{model:r,where:d,limit:u,offset:a,sortBy:o}=i,n=t.selectFrom(r),{and:s,or:l}=y(d);s&&(n=n.where(c=>c.and(s))),l&&(n=n.where(c=>c.or(l))),n=n.limit(u||100),a&&(n=n.offset(a)),o&&(n=n.orderBy(o.field,o.direction));let m=await n.selectAll().execute();if(e?.transform){let c=e.transform.schema[r];return c?m.map(N=>p(N,c,e.transform)):m}return m},async update(i){let{model:r,where:d,update:u}=i,{and:a,or:o}=y(d);e?.transform&&(u=F(u,e.transform));let n=t.updateTable(r).set(u);a&&(n=n.where(l=>l.and(a))),o&&(n=n.where(l=>l.or(o)));let s=await n.returningAll().executeTakeFirst()||null;if(e?.transform){let l=e.transform.schema[r];return l?p(s,l,e.transform):s}return s},async delete(i){let{model:r,where:d}=i,{and:u,or:a}=y(d),o=t.deleteFrom(r);u&&(o=o.where(n=>n.and(u))),a&&(o=o.where(n=>n.or(a))),await o.execute()}});export{T as createKyselyAdapter,q as kyselyAdapter};
|
|
1
|
+
import{Kysely as p,MssqlDialect as k}from"kysely";import{MysqlDialect as h,PostgresDialect as A,SqliteDialect as w}from"kysely";function b(t){if("dialect"in t)return b(t.dialect);if("createDriver"in t){if(t instanceof w)return"sqlite";if(t instanceof h)return"mysql";if(t instanceof A)return"postgres";if(t instanceof k)return"mssql"}return"aggregate"in t?"sqlite":"getConnection"in t?"mysql":"connect"in t?"postgres":null}var x=async t=>{let e=t.database;if("db"in e)return{kysely:e.db,databaseType:e.type};if("dialect"in e)return{kysely:new p({dialect:e.dialect}),databaseType:e.type};let a,r=b(e);return"createDriver"in e&&(a=e),"aggregate"in e&&(a=new w({database:e})),"getConnection"in e&&(a=new h({pool:e})),"connect"in e&&(a=new A({pool:e})),{kysely:a?new p({dialect:a}):null,databaseType:r}};function d(t){if(!t)return{and:null,or:null};let e=t?.filter(r=>r.connector==="AND"||!r.connector).reduce((r,o)=>({...r,[o.field]:o.value}),{}),a=t?.filter(r=>r.connector==="OR").reduce((r,o)=>({...r,[o.field]:o.value}),{});return{and:Object.keys(e).length?e:null,or:Object.keys(a).length?a:null}}function m(t,e,a){for(let r in t)t[r]===0&&e[r]?.type==="boolean"&&a?.boolean&&(t[r]=!1),t[r]===1&&e[r]?.type==="boolean"&&a?.boolean&&(t[r]=!0),e[r]?.type==="date"&&(t[r]instanceof Date||(t[r]=new Date(t[r])));return t}function D(t,e){for(let a in t)typeof t[a]=="boolean"&&e?.boolean&&(t[a]=t[a]?1:0),t[a]instanceof Date&&(t[a]=t[a].toISOString());return t}var K=(t,e)=>({id:"kysely",async create(a){let{model:r,data:o,select:y}=a;e?.transform&&(o=D(o,e.transform)),e?.generateId!==void 0&&(o.id=e.generateId?e.generateId():void 0);let i=await t.insertInto(r).values(o).returningAll().executeTakeFirst();if(e?.transform){let l=e.transform.schema[r];i=l?m(o,l,e.transform):i}return y?.length&&(i=i?y.reduce((n,s)=>i?.[s]?{...n,[s]:i[s]}:n,{}):null),i},async findOne(a){let{model:r,where:o,select:y}=a,{and:i,or:l}=d(o),n=t.selectFrom(r).selectAll();l&&(n=n.where(f=>f.or(l))),i&&(n=n.where(f=>f.and(i)));let s=await n.executeTakeFirst();if(y?.length&&(s=s?y.reduce((u,c)=>s?.[c]?{...u,[c]:s[c]}:u,{}):null),e?.transform){let f=e.transform.schema[r];return s=s&&f?m(s,f,e.transform):s,s||null}return s||null},async findMany(a){let{model:r,where:o,limit:y,offset:i,sortBy:l}=a,n=t.selectFrom(r),{and:s,or:f}=d(o);s&&(n=n.where(c=>c.and(s))),f&&(n=n.where(c=>c.or(f))),n=n.limit(y||100),i&&(n=n.offset(i)),l&&(n=n.orderBy(l.field,l.direction));let u=await n.selectAll().execute();if(e?.transform){let c=e.transform.schema[r];return c?u.map(g=>m(g,c,e.transform)):u}return u},async update(a){let{model:r,where:o,update:y}=a,{and:i,or:l}=d(o);e?.transform&&(y=D(y,e.transform));let n=t.updateTable(r).set(y);i&&(n=n.where(f=>f.and(i))),l&&(n=n.where(f=>f.or(l)));let s=await n.returningAll().executeTakeFirst()||null;if(e?.transform){let f=e.transform.schema[r];return f?m(s,f,e.transform):s}return s},async delete(a){let{model:r,where:o}=a,{and:y,or:i}=d(o),l=t.deleteFrom(r);y&&(l=l.where(n=>n.and(y))),i&&(l=l.where(n=>n.or(i))),await l.execute()}});export{x as createKyselyAdapter,K as kyselyAdapter};
|
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
import { Db } from 'mongodb';
|
|
2
|
-
import { W as Where } from '../auth-
|
|
2
|
+
import { W as Where } from '../auth-C6fr77co.js';
|
|
3
3
|
import 'zod';
|
|
4
4
|
import 'kysely';
|
|
5
5
|
import '../schema-Dkt0LqYs.js';
|
|
@@ -12,9 +12,20 @@ import 'mysql2';
|
|
|
12
12
|
|
|
13
13
|
declare const mongodbAdapter: (mongo: Db, opts?: {
|
|
14
14
|
usePlural?: boolean;
|
|
15
|
+
/**
|
|
16
|
+
* Custom generateId function.
|
|
17
|
+
*
|
|
18
|
+
* If not provided, nanoid will be used.
|
|
19
|
+
* If set to false, the database's auto generated id will be used.
|
|
20
|
+
*
|
|
21
|
+
* @default nanoid
|
|
22
|
+
*/
|
|
23
|
+
generateId?: ((size?: number) => string) | false;
|
|
15
24
|
}) => {
|
|
16
25
|
id: string;
|
|
17
|
-
create<T
|
|
26
|
+
create<T extends {
|
|
27
|
+
id?: string;
|
|
28
|
+
} & Record<string, any>, R = T>(data: {
|
|
18
29
|
model: string;
|
|
19
30
|
data: T;
|
|
20
31
|
select?: string[];
|
package/dist/adapters/mongodb.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
function u(o){if(!o)return{};if(o.length===1){let e=o[0];return e?{[e.field]:e.value}:void 0}let
|
|
1
|
+
function u(o){if(!o)return{};if(o.length===1){let e=o[0];return e?{[e.field]:e.value}:void 0}let l=o.filter(e=>e.connector==="AND"||!e.connector),r=o.filter(e=>e.connector==="OR"),s=l.map(e=>({[e.field]:e.operator==="eq"||!e.operator?e.value:{[e.field]:e.value}})),n=r.map(e=>({[e.field]:e.value})),t={};return s.length&&(t={...t,$and:s}),n.length&&(t={...t,$or:n}),t}function f(o){let{_id:l,...r}=o;return r}function p(o){return o.reduce((r,s)=>(r[s]=1,r),{})}var g=(o,l)=>{let r=o,s=n=>l?.usePlural?`${n}s`:n;return{id:"mongodb",async create(n){let{model:t,data:e}=n;l?.generateId!==void 0&&(e.id=l.generateId?l.generateId():void 0);let i=(await r.collection(s(t)).insertOne({...e})).insertedId,a={...e,id:i};return f(a)},async findOne(n){let{model:t,where:e,select:c}=n,i=u(e),a={};c&&(a=p(c));let m=(await r.collection(s(t)).find({...i},{projection:a}).toArray())[0];return m?f(m):null},async findMany(n){let{model:t,where:e,limit:c,offset:i,sortBy:a}=n,d=u(e);return(await r.collection(s(t)).find().filter(d).skip(i||0).limit(c||100).sort(a?.field||"id",a?.direction==="desc"?-1:1).toArray()).map(f)},async update(n){let{model:t,where:e,update:c}=n,i=u(e);if(e.length===1){let d=await r.collection(s(t)).findOneAndUpdate(i,{$set:c},{returnDocument:"after"});return f(d)}let a=await r.collection(s(t)).updateMany(i,{$set:c});return{}},async delete(n){let{model:t,where:e}=n,c=u(e),i=await r.collection(s(t)).findOneAndDelete(c)}}};export{g as mongodbAdapter};
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { A as Adapter } from '../auth-
|
|
1
|
+
import { A as Adapter } from '../auth-C6fr77co.js';
|
|
2
2
|
import 'zod';
|
|
3
3
|
import 'kysely';
|
|
4
4
|
import '../schema-Dkt0LqYs.js';
|
|
@@ -9,8 +9,17 @@ import '../social.js';
|
|
|
9
9
|
import 'better-sqlite3';
|
|
10
10
|
import 'mysql2';
|
|
11
11
|
|
|
12
|
-
declare const prismaAdapter: (prisma: any, { provider, }: {
|
|
13
|
-
provider: "sqlite" | "cockroachdb" | "mysql" | "postgresql" | "sqlserver";
|
|
12
|
+
declare const prismaAdapter: (prisma: any, { provider, generateId, }: {
|
|
13
|
+
provider: "sqlite" | "cockroachdb" | "mysql" | "postgresql" | "sqlserver" | "mongodb";
|
|
14
|
+
/**
|
|
15
|
+
* Custom generateId function.
|
|
16
|
+
*
|
|
17
|
+
* If not provided, nanoid will be used.
|
|
18
|
+
* If set to false, the database's auto generated id will be used.
|
|
19
|
+
*
|
|
20
|
+
* @default nanoid
|
|
21
|
+
*/
|
|
22
|
+
generateId?: ((size?: number) => string) | false;
|
|
14
23
|
}) => Adapter;
|
|
15
24
|
|
|
16
25
|
export { prismaAdapter };
|
package/dist/adapters/prisma.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
function
|
|
1
|
+
function c(o){if(!o)return{};if(o.length===1){let e=o[0];return e?{[e.field]:e.value}:void 0}let u=o.filter(e=>e.connector==="AND"||!e.connector),i=o.filter(e=>e.connector==="OR"),a=u.map(e=>({[e.field]:e.operator==="eq"||!e.operator?e.value:{[e.operator]:e.value}})),t=i.map(e=>({[e.field]:{[e.operator||"eq"]:e.value}}));return{AND:a.length?a:void 0,OR:t.length?t:void 0}}var f=(o,{provider:u,generateId:i})=>{let a=o;return{id:"prisma",async create(t){let{model:e,data:n,select:r}=t;return i!==void 0&&(n.id=i?i():void 0),await a[e].create({data:n,...r?.length?{select:r.reduce((d,s)=>({...d,[s]:!0}),{})}:{}})},async findOne(t){let{model:e,where:n,select:r}=t,d=c(n);return await a[e].findFirst({where:d,...r?.length?{select:r.reduce((s,l)=>({...s,[l]:!0}),{})}:{}})},async findMany(t){let{model:e,where:n,limit:r,offset:d,sortBy:s}=t,l=c(n);return await a[e].findMany({where:l,take:r||100,skip:d||0,orderBy:s?.field?{[s.field]:s.direction==="desc"?"desc":"asc"}:void 0})},async update(t){let{model:e,where:n,update:r}=t,d=c(n);return n.length===1?await a[e].update({where:d,data:r}):await a[e].updateMany({where:d,data:r})},async delete(t){let{model:e,where:n}=t,r=c(n);return await a[e].delete({where:r})}}};export{f as prismaAdapter};
|
package/dist/api.d.ts
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
export { e as AuthEndpoint, f as AuthMiddleware, a0 as callbackOAuth, af as changePassword, d as createAuthEndpoint, c as createAuthMiddleware, ab as createEmailVerificationToken, am as csrfMiddleware, ah as deleteUser, aj as error, a8 as forgetPassword, a9 as forgetPasswordCallback, ai as getCSRFToken, Y as getEndpoints, a1 as getSession, a2 as getSessionFromCtx, a4 as listSessions, ak as ok, o as optionsMiddleware, aa as resetPassword, a5 as revokeSession, a6 as revokeSessions, Z as router, ac as sendVerificationEmail, a3 as sessionMiddleware, ag as setPassword, $ as signInEmail, _ as signInOAuth, a7 as signOut, al as signUpEmail, ae as updateUser, ad as verifyEmail } from './auth-
|
|
1
|
+
export { e as AuthEndpoint, f as AuthMiddleware, a0 as callbackOAuth, af as changePassword, d as createAuthEndpoint, c as createAuthMiddleware, ab as createEmailVerificationToken, am as csrfMiddleware, ah as deleteUser, aj as error, a8 as forgetPassword, a9 as forgetPasswordCallback, ai as getCSRFToken, Y as getEndpoints, a1 as getSession, a2 as getSessionFromCtx, a4 as listSessions, ak as ok, o as optionsMiddleware, aa as resetPassword, a5 as revokeSession, a6 as revokeSessions, Z as router, ac as sendVerificationEmail, a3 as sessionMiddleware, ag as setPassword, $ as signInEmail, _ as signInOAuth, a7 as signOut, al as signUpEmail, ae as updateUser, ad as verifyEmail } from './auth-C6fr77co.js';
|
|
2
2
|
import './helper-DPDj8Nix.js';
|
|
3
3
|
export { APIError } from 'better-call';
|
|
4
4
|
import 'zod';
|
package/dist/api.js
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
|
-
import{APIError as
|
|
2
|
-
`)}}),w=ot();var U=$(async e=>{let t=e.body?.callbackURL||e.query?.callbackURL||e.query?.redirectTo||e.body?.redirectTo,r=e.headers?.get("referer"),o=e.query?.currentURL||r||e.context.baseURL,n=e.context.trustedOrigins;if(t?.includes("http")){let i=new URL(t).origin;if(!n.includes(i))throw w.error("Invalid callback URL",{callbackURL:t,trustedOrigins:n}),new de("FORBIDDEN",{message:"Invalid callback URL"})}if(o!==e.context.baseURL){let i=new URL(o).origin;if(!n.includes(i))throw w.error("Invalid current URL",{currentURL:o,trustedOrigins:n}),new de("FORBIDDEN",{message:"Invalid callback URL"})}});import{parseJWT as at}from"oslo/jwt";import{sha256 as nt}from"oslo/crypto";import{base64url as it}from"oslo/encoding";async function ue(e){let t=await nt(new TextEncoder().encode(e));return it.encode(new Uint8Array(t),{includePadding:!1})}function le(e){return{tokenType:e.token_type,accessToken:e.access_token,refreshToken:e.refresh_token,accessTokenExpiresAt:e.expires_at?new Date((Date.now()+e.expires_in)*1e3):void 0,scopes:e?.scope?typeof e.scope=="string"?e.scope.split(" "):e.scope:[],idToken:e.id_token}}async function k({id:e,options:t,authorizationEndpoint:r,state:o,codeVerifier:n,scopes:i,claims:s,disablePkce:d,redirectURI:a}){let c=new URL(r);if(c.searchParams.set("response_type","code"),c.searchParams.set("client_id",t.clientId),c.searchParams.set("state",o),c.searchParams.set("scope",i.join(" ")),c.searchParams.set("redirect_uri",t.redirectURI||a),!d&&n){let u=await ue(n);c.searchParams.set("code_challenge_method","S256"),c.searchParams.set("code_challenge",u)}if(s){let u=s.reduce((y,g)=>(y[g]=null,y),{});c.searchParams.set("claims",JSON.stringify({id_token:{email:null,email_verified:null,...u}}))}return c}import{betterFetch as st}from"@better-fetch/fetch";async function b({code:e,codeVerifier:t,redirectURI:r,options:o,tokenEndpoint:n}){let i=new URLSearchParams;i.set("grant_type","authorization_code"),i.set("code",e),t&&i.set("code_verifier",t),i.set("redirect_uri",r),i.set("client_id",o.clientId),i.set("client_secret",o.clientSecret);let{data:s,error:d}=await st(n,{method:"POST",body:i,headers:{"content-type":"application/x-www-form-urlencoded",accept:"application/json","user-agent":"better-auth"}});if(d)throw d;return le(s)}function X(e){let t=e.accessToken,r=e.refreshToken,o;try{o=e.accessTokenExpiresAt}catch{}return{accessToken:t,refreshToken:r,expiresAt:o}}var pe=e=>{let t="https://appleid.apple.com/auth/token";return{id:"apple",name:"Apple",createAuthorizationURL({state:r,scopes:o,redirectURI:n}){let i=e.scope||o||["email","name","openid"];return 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}`)},validateAuthorizationCode:async({code:r,codeVerifier:o,redirectURI:n})=>b({code:r,codeVerifier:o,redirectURI:e.redirectURI||n,options:e,tokenEndpoint:t}),async getUserInfo(r){if(!r.idToken)return null;let o=at(r.idToken)?.payload;return o?{user:{id:o.sub,name:o.name,email:o.email,emailVerified:o.email_verified==="true"},data:o}:null}}};import{betterFetch as ct}from"@better-fetch/fetch";var me=e=>({id:"discord",name:"Discord",createAuthorizationURL({state:t,scopes:r,redirectURI:o}){let n=e.scope||r||["identify","email"];return 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})=>b({code:t,redirectURI:e.redirectURI||r,options:e,tokenEndpoint:"https://discord.com/api/oauth2/token"}),async getUserInfo(t){let{data:r,error:o}=await ct("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 dt}from"@better-fetch/fetch";var fe=e=>({id:"facebook",name:"Facebook",async createAuthorizationURL({state:t,scopes:r,redirectURI:o}){let n=e.scope||r||["email","public_profile"];return await k({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})=>b({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 dt("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,emailVerified:r.email_verified},data:r}}});import{betterFetch as ge}from"@better-fetch/fetch";var he=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=e.scope||o||["user:email"];return k({id:"github",options:e,authorizationEndpoint:"https://github.com/login/oauth/authorize",scopes:s,state:r,redirectURI:i,codeVerifier:n})},validateAuthorizationCode:async({code:r,redirectURI:o})=>b({code:r,redirectURI:e.redirectURI||o,options:e,tokenEndpoint:t}),async getUserInfo(r){let{data:o,error:n}=await ge("https://api.github.com/user",{auth:{type:"Bearer",token:r.accessToken}});if(n)return null;let i=!1;if(!o.email){let{data:s,error:d}=await ge("https://api.github.com/user/emails",{auth:{type:"Bearer",token:r.accessToken}});d||(o.email=(s.find(a=>a.primary)??s[0])?.email,i=s.find(a=>a.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 ut}from"oslo/jwt";var we=e=>({id:"google",name:"Google",createAuthorizationURL({state:t,scopes:r,codeVerifier:o,redirectURI:n}){if(!e.clientId||!e.clientSecret)throw w.error("Client Id and Client Secret is required for Google. Make sure to provide them in the options."),new I("CLIENT_ID_AND_SECRET_REQUIRED");if(!o)throw new I("codeVerifier is required for Google");let i=e.scope||r||["email","profile"];return k({id:"google",options:e,authorizationEndpoint:"https://accounts.google.com/o/oauth2/auth",scopes:i,state:t,codeVerifier:o,redirectURI:n})},validateAuthorizationCode:async({code:t,codeVerifier:r,redirectURI:o})=>b({code:t,codeVerifier:r,redirectURI:e.redirectURI||o,options:e,tokenEndpoint:"https://oauth2.googleapis.com/token"}),async getUserInfo(t){if(!t.idToken)return null;let r=ut(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 lt}from"@better-fetch/fetch";import{parseJWT as pt}from"oslo/jwt";var ye=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=e.scope||n.scopes||["openid","profile","email","User.Read"];return k({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 b({code:n,codeVerifier:i,redirectURI:e.redirectURI||s,options:e,tokenEndpoint:o})},async getUserInfo(n){if(!n.idToken)return null;let i=pt(n.idToken)?.payload,s=e.profilePhotoSize||48;return await lt(`https://graph.microsoft.com/v1.0/me/photos/${s}x${s}/$value`,{headers:{Authorization:`Bearer ${n.accessToken}`},async onResponse(d){if(!(e.disableProfilePhoto||!d.response.ok))try{let c=await d.response.clone().arrayBuffer(),u=Buffer.from(c).toString("base64");i.picture=`data:image/jpeg;base64, ${u}`}catch(a){w.error(a)}}}),{user:{id:i.sub,name:i.name,email:i.email,image:i.picture,emailVerified:!0},data:i}}}};import{betterFetch as mt}from"@better-fetch/fetch";var be=e=>({id:"spotify",name:"Spotify",createAuthorizationURL({state:t,scopes:r,codeVerifier:o,redirectURI:n}){let i=e.scope||r||["user-read-email"];return k({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})=>b({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 mt("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";var L={isAction:!1};var Ae=e=>q(e||21,N("a-z","0-9","A-Z"));import{parseJWT as ft}from"oslo/jwt";var Re=e=>({id:"twitch",name:"Twitch",createAuthorizationURL({state:t,scopes:r,redirectURI:o}){let n=e.scope||r||["user:read:email","openid"];return k({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})=>b({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 w.error("No idToken found in token"),null;let o=ft(r)?.payload;return{user:{id:o.sub,name:o.preferred_username,email:o.email,image:o.picture,emailVerified:!1},data:o}}});import{betterFetch as gt}from"@better-fetch/fetch";var ke=e=>({id:"twitter",name:"Twitter",createAuthorizationURL(t){let r=e.scope||t.scopes||["account_info.read"];return k({id:"twitter",options:e,authorizationEndpoint:"https://twitter.com/i/oauth2/authorize",scopes:r,state:t.state,codeVerifier:t.codeVerifier,redirectURI:t.redirectURI})},validateAuthorizationCode:async({code:t,codeVerifier:r,redirectURI:o})=>b({code:t,codeVerifier:r,redirectURI:e.redirectURI||o,options:e,tokenEndpoint:"https://id.twitch.tv/oauth2/token"}),async getUserInfo(t){let{data:r,error:o}=await gt("https://api.x.com/2/users/me?user.fields=profile_image_url",{method:"GET",headers:{Authorization:`Bearer ${t.accessToken}`}});return o||!r.data.email?null:{user:{id:r.data.id,name:r.data.name,email:r.data.email,image:r.data.profile_image_url,emailVerified:r.data.verified||!1},data:r}}});var ht={apple:pe,discord:me,facebook:fe,github:he,microsoft:ye,google:we,spotify:be,twitch:Re,twitter:ke},Ue=Object.keys(ht);import{TimeSpan as wt}from"oslo";import{createJWT as yt,validateJWT as bt}from"oslo/jwt";import{z as T}from"zod";import{APIError as H}from"better-call";async function B(e,t){return await yt("HS256",Buffer.from(e),{email:t.toLowerCase()},{expiresIn:new wt(1,"h"),issuer:"better-auth",subject:"verify-email",audiences:[t],includeIssuedTimestamp:!0})}var Ee=l("/send-verification-email",{method:"POST",query:T.object({currentURL:T.string().optional()}).optional(),body:T.object({email:T.string().email(),callbackURL:T.string().optional()}),use:[U]},async e=>{if(!e.context.options.emailVerification?.sendVerificationEmail)throw e.context.logger.error("Verification email isn't enabled. Pass `sendVerificationEmail` in `emailAndPassword` options to enable it."),new H("BAD_REQUEST",{message:"Verification email isn't enabled"});let{email:t}=e.body,r=await e.context.internalAdapter.findUserByEmail(t);if(!r)throw new H("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(r.user,n,o),e.json({status:!0})}),xe=l("/verify-email",{method:"GET",query:T.object({token:T.string(),callbackURL:T.string().optional()})},async e=>{let{token:t}=e.query,r;try{r=await bt("HS256",Buffer.from(e.context.secret),t)}catch(s){throw e.context.logger.error("Failed to verify email",s),new H("BAD_REQUEST",{message:"Invalid token"})}let n=T.object({email:T.string().email()}).parse(r.payload);if(!await e.context.internalAdapter.findUserByEmail(n.email))throw new H("BAD_REQUEST",{message:"User not found"});if(await e.context.internalAdapter.updateUserByEmail(n.email,{emailVerified:!0}),e.query.callbackURL)throw e.redirect(e.query.callbackURL);return e.json({status:!0})});var ve=l("/sign-in/social",{method:"POST",requireHeaders:!0,query:E.object({currentURL:E.string().optional()}).optional(),body:E.object({callbackURL:E.string().optional(),provider:E.enum(Ue)}),use:[U]},async e=>{let t=e.context.socialProviders.find(a=>a.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 P("NOT_FOUND",{message:"Provider not found"});let r=e.context.authCookies,o=e.query?.currentURL?new URL(e.query?.currentURL):null,n=e.body.callbackURL?.startsWith("http")?e.body.callbackURL:`${o?.origin}${e.body.callbackURL||""}`,i=await ce(n||o?.origin||e.context.options.baseURL);await e.setSignedCookie(r.state.name,i.hash,e.context.secret,r.state.options);let s=At();await e.setSignedCookie(r.pkCodeVerifier.name,s,e.context.secret,r.pkCodeVerifier.options);let d=await t.createAuthorizationURL({state:i.raw,codeVerifier:s,redirectURI:`${e.context.baseURL}/callback/${t.id}`});return e.json({url:d.toString(),state:i,codeVerifier:s,redirect:!0})}),Te=l("/sign-in/email",{method:"POST",body:E.object({email:E.string().email(),password:E.string(),callbackURL:E.string().optional(),dontRememberMe:E.boolean().default(!1).optional()}),use:[U]},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 P("BAD_REQUEST",{message:"Email and password is not enabled"});let{email:t,password:r}=e.body;if(!E.string().email().safeParse(t).success)throw new P("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 P("UNAUTHORIZED",{message:"Invalid email or password"});if(e.context.options?.emailAndPassword?.requireEmailVerification&&!n.user.emailVerified){if(!e.context.options?.emailVerification?.sendVerificationEmail)throw w.error("Email verification is required but no email verification handler is provided"),new P("INTERNAL_SERVER_ERROR",{message:"Email is not verified."});let c=await B(e.context.secret,n.user.email),u=`${e.context.options.baseURL}/verify-email?token=${c}`;throw await e.context.options.emailVerification.sendVerificationEmail(n.user,u,c),e.context.logger.error("Email not verified",{email:t}),new P("FORBIDDEN",{message:"Email is not verified. Check your email for a verification link"})}let i=n.accounts.find(c=>c.providerId==="credential");if(!i)throw e.context.logger.error("Credential account not found",{email:t}),new P("UNAUTHORIZED",{message:"Invalid email or password"});let s=i?.password;if(!s)throw e.context.logger.error("Password not found",{email:t}),new P("UNAUTHORIZED",{message:"Unexpected error"});if(!await e.context.password.verify(s,r))throw e.context.logger.error("Invalid password"),new P("UNAUTHORIZED",{message:"Invalid email or password"});let a=await e.context.internalAdapter.createSession(n.user.id,e.headers,e.body.dontRememberMe);if(!a)throw e.context.logger.error("Failed to create session"),new P("UNAUTHORIZED",{message:"Failed to create session"});return await v(e,a.id,e.body.dontRememberMe),e.json({user:n.user,session:a,redirect:!!e.body.callbackURL,url:e.body.callbackURL})});import{APIError as kt}from"better-call";import{z as G}from"zod";import{z as m}from"zod";var Ln=m.object({id:m.string(),providerId:m.string(),accountId:m.string(),userId:m.string(),accessToken:m.string().nullable().optional(),refreshToken:m.string().nullable().optional(),idToken:m.string().nullable().optional(),expiresAt:m.date().nullable().optional(),password:m.string().optional().nullable()}),Pe=m.object({id:m.string(),email:m.string().transform(e=>e.toLowerCase()),emailVerified:m.boolean().default(!1),name:m.string(),image:m.string().optional(),createdAt:m.date().default(new Date),updatedAt:m.date().default(new Date)}),On=m.object({id:m.string(),userId:m.string(),expiresAt:m.date(),ipAddress:m.string().optional(),userAgent:m.string().optional()}),In=m.object({id:m.string(),value:m.string(),expiresAt:m.date(),identifier:m.string()});function Rt(e,t){let r=t.fields,o={};for(let n in r){if(n in e){if(r[n].input===!1){if(r[n].defaultValue){o[n]=r[n].defaultValue;continue}continue}o[n]=e[n];continue}if(r[n].defaultValue){o[n]=r[n].defaultValue;continue}}return o}function _e(e,t){let r={...e.user?.additionalFields};return Rt(t||{},{fields:r})}var Se=l("/callback/:id",{method:"GET",query:G.object({state:G.string(),code:G.string().optional(),error:G.string().optional()}),metadata:L},async e=>{if(e.query.error||!e.query.code){let h=K(e.query.state).data?.callbackURL||`${e.context.baseURL}/error`;throw e.context.logger.error(e.query.error,e.params.id),e.redirect(`${h}?error=${e.query.error||"oAuth_code_missing"}`)}let t=e.context.socialProviders.find(p=>p.id===e.params.id);if(!t)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 r=K(e.query.state);if(!r.success)throw e.context.logger.error("Unable to parse state"),e.redirect(`${e.context.baseURL}/error?error=please_restart_the_process`);let{data:{callbackURL:o,currentURL:n}}=r,i=await e.getSignedCookie(e.context.authCookies.state.name,e.context.secret);if(!i)throw w.error("No stored state found"),e.redirect(`${e.context.baseURL}/error?error=please_restart_the_process`);if(!await ae(e.query.state,i))throw w.error("OAuth state mismatch"),e.redirect(`${e.context.baseURL}/error?error=please_restart_the_process`);let d=await e.getSignedCookie(e.context.authCookies.pkCodeVerifier.name,e.context.secret),a;try{a=await t.validateAuthorizationCode({code:e.query.code,codeVerifier:d,redirectURI:`${e.context.baseURL}/callback/${t.id}`})}catch(p){throw e.context.logger.error(p),e.redirect(`${e.context.baseURL}/error?error=please_restart_the_process`)}let c=await t.getUserInfo(a).then(p=>p?.user),u=Ae(),y=Pe.safeParse({...c,id:u});if(!c||y.success===!1)throw w.error("Unable to get user info",y.error),e.redirect(`${e.context.baseURL}/error?error=please_restart_the_process`);if(!o)throw e.redirect(`${e.context.baseURL}/error?error=please_restart_the_process`);let g=await e.context.internalAdapter.findUserByEmail(c.email,{includeAccounts:!0}).catch(p=>{throw w.error(`Better auth was unable to query your database.
|
|
3
|
-
Error: `,p),e.redirect(`${e.context.baseURL}/error?error=internal_server_error`)}),f=g?.user.id;if(g){let p=g.accounts.find(R=>R.providerId===t.id),h=e.context.options.account?.accountLinking?.trustedProviders,A=h?h.includes(t.id):!0;if(!p&&(!c.emailVerified||!A)){let R;try{R=new URL(n||o),R.searchParams.set("error","account_not_linked")}catch{throw e.redirect(`${e.context.baseURL}/error?error=account_not_linked`)}throw e.redirect(R.toString())}if(!p)try{await e.context.internalAdapter.linkAccount({providerId:t.id,accountId:c.id.toString(),id:`${t.id}:${c.id}`,userId:g.user.id,...X(a)})}catch(R){throw console.log(R),e.redirect(`${e.context.baseURL}/error?error=failed_linking_account`)}}else try{let p=c.emailVerified,h=await e.context.internalAdapter.createOAuthUser({...y.data,emailVerified:p},{...X(a),id:`${t.id}:${c.id}`,providerId:t.id,accountId:c.id.toString(),userId:u});if(!p&&h&&e.context.options.emailVerification?.sendOnSignUp){let A=await B(e.context.secret,c.email),R=`${e.context.baseURL}/verify-email?token=${A}&callbackURL=${o}`;await e.context.options.emailVerification?.sendVerificationEmail?.(h.user,R,A)}}catch{let h=new URL(n||o);throw h.searchParams.set("error","unable_to_create_user"),e.redirect(h.toString())}if(!f&&!u)throw new kt("INTERNAL_SERVER_ERROR",{message:"Unable to create user"});try{let p=await e.context.internalAdapter.createSession(f||u,e.request);if(!p){let h=new URL(n||o);throw h.searchParams.set("error","unable_to_create_session"),e.redirect(h.toString())}try{await v(e,p.id)}catch(h){e.context.logger.error("Unable to set session cookie",h);let A=new URL(n||o);throw A.searchParams.set("error","unable_to_create_session"),e.redirect(A.toString())}}catch{let p=new URL(n||o||"");throw p.searchParams.set("error","unable_to_create_session"),e.redirect(p.toString())}throw e.redirect(o)});import{APIError as j}from"better-call";var Q=(e,t="ms")=>new Date(Date.now()+(t==="sec"?e*1e3:e));import{z as Le}from"zod";var Y=()=>l("/session",{method:"GET",requireHeaders:!0},async e=>{try{let t=await e.getSignedCookie(e.context.authCookies.sessionToken.name,e.context.secret);if(!t)return e.json(null,{status:401});let r=await e.context.internalAdapter.findSession(t);if(!r||r.session.expiresAt<new Date)return z(e),r&&await e.context.internalAdapter.deleteSession(r.session.id),e.json(null,{status:401});if(await e.getSignedCookie(e.context.authCookies.dontRememberToken.name,e.context.secret))return e.json(r);let n=e.context.sessionConfig.expiresIn,i=e.context.sessionConfig.updateAge;if(r.session.expiresAt.valueOf()-n*1e3+i*1e3<=Date.now()){let a=await e.context.internalAdapter.updateSession(r.session.id,{expiresAt:Q(e.context.sessionConfig.expiresIn,"sec")});if(!a)return z(e),e.json(null,{status:401});let c=(a.expiresAt.valueOf()-Date.now())/1e3;return await v(e,a.id,!1,{maxAge:c}),e.json({session:a,user:r.user})}return e.json(r)}catch(t){return e.context.logger.error(t),e.json(null,{status:500})}}),Ut=async e=>await Y()({...e,_flag:"json",headers:e.headers}),O=$(async e=>{let t=await Ut(e);if(!t?.session)throw new j("UNAUTHORIZED");return{session:t}}),Oe=()=>l("/user/list-sessions",{method:"GET",use:[O],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)}),Ie=l("/user/revoke-session",{method:"POST",body:Le.object({id:Le.string()}),use:[O],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})}),Ce=l("/user/revoke-sessions",{method:"POST",use:[O],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})});import"zod";import{APIError as Et}from"better-call";var Be=l("/sign-out",{method:"POST"},async e=>{let t=await e.getSignedCookie(e.context.authCookies.sessionToken.name,e.context.secret);if(!t)throw new Et("BAD_REQUEST",{message:"Session not found"});return await e.context.internalAdapter.deleteSession(t),z(e),e.json({success:!0})});import{z as S}from"zod";import{APIError as Z}from"better-call";var De=l("/forget-password",{method:"POST",body:S.object({email:S.string().email(),redirectTo:S.string()}),use:[U]},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 Z("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=new Date(Date.now()+1e3*(e.context.options.emailAndPassword.resetPasswordTokenExpiresIn||n)),s=e.context.uuid();await e.context.internalAdapter.createVerificationValue({value:o.user.id,identifier:`reset-password:${s}`,expiresAt:i});let d=`${e.context.baseURL}/reset-password/${s}?callbackURL=${r}`;return await e.context.options.emailAndPassword.sendResetPassword(o.user,d),e.json({status:!0})}),$e=l("/reset-password/:token",{method:"GET",query:S.object({callbackURL:S.string()}),use:[U]},async e=>{let{token:t}=e.params,r=e.query.callbackURL,o=r.startsWith("http")?r:`${e.context.options.baseURL}${r}`;if(!t||!r)throw e.redirect(`${e.context.baseURL}/error?error=INVALID_TOKEN`);let n=await e.context.internalAdapter.findVerificationValue(`reset-password:${t}`);throw!n||n.expiresAt<new Date?e.redirect(`${o}?error=INVALID_TOKEN`):e.redirect(`${o}?token=${t}`)}),Ve=l("/reset-password",{query:S.object({token:S.string()}).optional(),method:"POST",body:S.object({newPassword:S.string()})},async e=>{let t=e.query?.token;if(!t)throw new Z("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 Z("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 Z("BAD_REQUEST",{message:"Failed to update password"});return e.json({status:!0})});import{z as x}from"zod";import{APIError as _}from"better-call";var ze=l("/user/update",{method:"POST",body:x.object({name:x.string().optional(),image:x.string().optional()}),use:[O,U]},async e=>{let{name:t,image:r}=e.body,o=e.context.session;if(!r&&!t)return e.json({user:o.user});let n=await e.context.internalAdapter.updateUserByEmail(o.user.email,{name:t,image:r});return e.json({user:n})}),je=l("/user/change-password",{method:"POST",body:x.object({newPassword:x.string(),currentPassword:x.string(),revokeOtherSessions:x.boolean().optional()}),use:[O]},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 _("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 _("BAD_REQUEST",{message:"Password too long"});let a=(await e.context.internalAdapter.findAccounts(n.user.id)).find(y=>y.providerId==="credential"&&y.password);if(!a||!a.password)throw new _("BAD_REQUEST",{message:"User does not have a password"});let c=await e.context.password.hash(t);if(!await e.context.password.verify(a.password,r))throw new _("BAD_REQUEST",{message:"Incorrect password"});if(await e.context.internalAdapter.updateAccount(a.id,{password:c}),o){await e.context.internalAdapter.deleteSessions(n.user.id);let y=await e.context.internalAdapter.createSession(n.user.id,e.headers);if(!y)throw new _("INTERNAL_SERVER_ERROR",{message:"Unable to create session"});await v(e,y.id)}return e.json(n.user)}),qe=l("/user/set-password",{method:"POST",body:x.object({newPassword:x.string()}),use:[O]},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 _("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 _("BAD_REQUEST",{message:"Password too long"});let s=(await e.context.internalAdapter.findAccounts(r.user.id)).find(a=>a.providerId==="credential"&&a.password),d=await e.context.password.hash(t);if(!s)return await e.context.internalAdapter.linkAccount({userId:r.user.id,providerId:"credential",accountId:r.user.id,password:d}),e.json(r.user);throw new _("BAD_REQUEST",{message:"user already has a password"})}),Ne=l("/user/delete",{method:"POST",body:x.object({password:x.string()}),use:[O]},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 _("BAD_REQUEST",{message:"User does not have a password"});if(!await e.context.password.verify(n.password,t))throw new _("BAD_REQUEST",{message:"Incorrect password"});return await e.context.internalAdapter.deleteUser(r.user.id),await e.context.internalAdapter.deleteSessions(r.user.id),e.json(null)});var Me=l("/csrf",{method:"GET",metadata:L},async e=>{let t=await e.getSignedCookie(e.context.authCookies.csrfToken.name,e.context.secret);if(t){let[i,s]=t.split("!")||[null,null];return e.json({csrfToken:i})}let r=q(32,N("a-z","0-9","A-Z")),o=await M(e.context.secret,r),n=`${r}!${o}`;return await e.setSignedCookie(e.context.authCookies.csrfToken.name,n,e.context.secret,e.context.authCookies.csrfToken.options),e.json({csrfToken:r})});var xt=(e="Unknown")=>`<!DOCTYPE html>
|
|
1
|
+
import{APIError as It,createRouter as Ct}from"better-call";import{APIError as Z}from"better-call";import{z as oe}from"zod";import{xchacha20poly1305 as Qt}from"@noble/ciphers/chacha";import{bytesToHex as Wt,hexToBytes as Jt,utf8ToBytes as Kt}from"@noble/ciphers/utils";import{managedNonce as Yt}from"@noble/ciphers/webcrypto";import{sha256 as tr}from"oslo/crypto";function Q(e,t){let r=new Uint8Array(e),o=new Uint8Array(t);if(r.length!==o.length)return!1;let n=0;for(let i=0;i<r.length;i++)n|=r[i]^o[i];return n===0}import{decodeHex as zt,encodeHex as jt}from"oslo/encoding";import{scryptAsync as Mt}from"@noble/hashes/scrypt";function Je(e){return e.toString(2).padStart(8,"0")}function Ke(e){return[...e].map(t=>Je(t)).join("")}function X(e){return parseInt(Ke(e),2)}function Xe(e){if(e<0||!Number.isInteger(e))throw new Error("Argument 'max' must be an integer greater than or equal to 0");let t=(e-1).toString(2).length,r=t%8,o=new Uint8Array(Math.ceil(t/8));crypto.getRandomValues(o),r!==0&&(o[0]&=(1<<r)-1);let n=X(o);for(;n>=e;)crypto.getRandomValues(o),r!==0&&(o[0]&=(1<<r)-1),n=X(o);return n}function Y(e,t){let r="";for(let o=0;o<e;o++)r+=t[Xe(t.length)];return r}function ee(...e){let t=new Set(e),r="";for(let o of t)o==="a-z"?r+="abcdefghijklmnopqrstuvwxyz":o==="A-Z"?r+="ABCDEFGHIJKLMNOPQRSTUVWXYZ":o==="0-9"?r+="0123456789":r+=o;return r}async function q(e,t){let r=new TextEncoder,o={name:"HMAC",hash:"SHA-256"},n=await crypto.subtle.importKey("raw",r.encode(e),o,!1,["sign","verify"]),i=await crypto.subtle.sign(o.name,n,r.encode(t));return btoa(String.fromCharCode(...new Uint8Array(i)))}import{createEndpointCreator as Ye,createMiddleware as te,createMiddlewareCreator as et}from"better-call";var re=te(async()=>({})),$=et({use:[re,te(async()=>({}))]}),p=Ye({use:[re]});var ne=$({body:oe.object({csrfToken:oe.string().optional()}).optional()},async e=>{if(e.request?.method!=="POST"||e.context.options.advanced?.disableCSRFCheck)return;let t=new URL(e.request.url);if(e.context.trustedOrigins.includes(t.origin))return;let r=e.body?.csrfToken;if(!r)throw new Z("UNAUTHORIZED",{message:"CSRF Token is required"});let o=await e.getSignedCookie(e.context.authCookies.csrfToken.name,e.context.secret),[n,i]=o?.split("!")||[null,null];if(!r||!o||!n||!i||n!==r)throw e.setCookie(e.context.authCookies.csrfToken.name,"",{maxAge:0}),new Z("UNAUTHORIZED",{message:"Invalid CSRF Token"});let s=await q(e.context.secret,n);if(i!==s)throw e.setCookie(e.context.authCookies.csrfToken.name,"",{maxAge:0}),new Z("UNAUTHORIZED",{message:"Invalid CSRF Token"})});import{APIError as P}from"better-call";import{generateCodeVerifier as Rt}from"oslo/oauth2";import{z as E}from"zod";import{generateState as tt}from"oslo/oauth2";import{z as N}from"zod";import{sha256 as ie}from"oslo/crypto";async function se(e){let t=await ie(typeof e=="string"?new TextEncoder().encode(e):e);return Buffer.from(t).toString("base64")}async function ae(e,t){let r=await ie(typeof e=="string"?new TextEncoder().encode(e):e),o=Buffer.from(t,"base64");return Q(r,o)}import"better-call";async function ce(e){let t=tt(),r=JSON.stringify({code:t,callbackURL:e}),o=await se(r);return{raw:r,hash:o}}function W(e){return N.object({code:N.string(),callbackURL:N.string().optional(),currentURL:N.string().optional()}).safeParse(JSON.parse(e))}import{TimeSpan as vr}from"oslo";var I=class extends Error{constructor(t,r){super(t),this.name="BetterAuthError",this.message=t,this.cause=r,this.stack=""}};async function v(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,e.context.secret,{...n,...o}),r&&await e.setSignedCookie(e.context.authCookies.dontRememberToken.name,"true",e.context.secret,e.context.authCookies.dontRememberToken.options)}function z(e){e.setCookie(e.context.authCookies.sessionToken.name,"",{maxAge:0}),e.setCookie(e.context.authCookies.dontRememberToken.name,"",{maxAge:0})}import{APIError as de}from"better-call";import{createConsola as rt}from"consola";var C=rt({formatOptions:{date:!1,colors:!0,compact:!0},defaults:{tag:"Better Auth"}}),ot=e=>({log:(...t)=>{!e?.disabled&&C.log("",...t)},error:(...t)=>{!e?.disabled&&C.error("",...t)},warn:(...t)=>{!e?.disabled&&C.warn("",...t)},info:(...t)=>{!e?.disabled&&C.info("",...t)},debug:(...t)=>{!e?.disabled&&C.debug("",...t)},box:(...t)=>{!e?.disabled&&C.box("",...t)},success:(...t)=>{!e?.disabled&&C.success("",...t)},break:(...t)=>{!e?.disabled&&console.log(`
|
|
2
|
+
`)}}),w=ot();var U=$(async e=>{let t=e.body?.callbackURL||e.query?.callbackURL||e.query?.redirectTo||e.body?.redirectTo,r=e.headers?.get("referer"),o=e.query?.currentURL||r||e.context.baseURL,n=e.context.trustedOrigins;if(t?.includes("http")){let i=new URL(t).origin;if(!n.includes(i))throw w.error("Invalid callback URL",{callbackURL:t,trustedOrigins:n}),new de("FORBIDDEN",{message:"Invalid callback URL"})}if(o!==e.context.baseURL){let i=new URL(o).origin;if(!n.includes(i))throw w.error("Invalid current URL",{currentURL:o,trustedOrigins:n}),new de("FORBIDDEN",{message:"Invalid callback URL"})}});import{parseJWT as at}from"oslo/jwt";import{sha256 as nt}from"oslo/crypto";import{base64url as it}from"oslo/encoding";async function ue(e){let t=await nt(new TextEncoder().encode(e));return it.encode(new Uint8Array(t),{includePadding:!1})}function pe(e){return{tokenType:e.token_type,accessToken:e.access_token,refreshToken:e.refresh_token,accessTokenExpiresAt:e.expires_at?new Date((Date.now()+e.expires_in)*1e3):void 0,scopes:e?.scope?typeof e.scope=="string"?e.scope.split(" "):e.scope:[],idToken:e.id_token}}async function k({id:e,options:t,authorizationEndpoint:r,state:o,codeVerifier:n,scopes:i,claims:s,disablePkce:d,redirectURI:a}){let c=new URL(r);if(c.searchParams.set("response_type","code"),c.searchParams.set("client_id",t.clientId),c.searchParams.set("state",o),c.searchParams.set("scope",i.join(" ")),c.searchParams.set("redirect_uri",t.redirectURI||a),!d&&n){let u=await ue(n);c.searchParams.set("code_challenge_method","S256"),c.searchParams.set("code_challenge",u)}if(s){let u=s.reduce((y,g)=>(y[g]=null,y),{});c.searchParams.set("claims",JSON.stringify({id_token:{email:null,email_verified:null,...u}}))}return c}import{betterFetch as st}from"@better-fetch/fetch";async function b({code:e,codeVerifier:t,redirectURI:r,options:o,tokenEndpoint:n}){let i=new URLSearchParams;i.set("grant_type","authorization_code"),i.set("code",e),t&&i.set("code_verifier",t),i.set("redirect_uri",r),i.set("client_id",o.clientId),i.set("client_secret",o.clientSecret);let{data:s,error:d}=await st(n,{method:"POST",body:i,headers:{"content-type":"application/x-www-form-urlencoded",accept:"application/json","user-agent":"better-auth"}});if(d)throw d;return pe(s)}function J(e){let t=e.accessToken,r=e.refreshToken,o;try{o=e.accessTokenExpiresAt}catch{}return{accessToken:t,refreshToken:r,expiresAt:o}}var le=e=>{let t="https://appleid.apple.com/auth/token";return{id:"apple",name:"Apple",createAuthorizationURL({state:r,scopes:o,redirectURI:n}){let i=e.scope||o||["email","name","openid"];return 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}`)},validateAuthorizationCode:async({code:r,codeVerifier:o,redirectURI:n})=>b({code:r,codeVerifier:o,redirectURI:e.redirectURI||n,options:e,tokenEndpoint:t}),async getUserInfo(r){if(!r.idToken)return null;let o=at(r.idToken)?.payload;return o?{user:{id:o.sub,name:o.name,email:o.email,emailVerified:o.email_verified==="true"},data:o}:null}}};import{betterFetch as ct}from"@better-fetch/fetch";var me=e=>({id:"discord",name:"Discord",createAuthorizationURL({state:t,scopes:r,redirectURI:o}){let n=e.scope||r||["identify","email"];return 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})=>b({code:t,redirectURI:e.redirectURI||r,options:e,tokenEndpoint:"https://discord.com/api/oauth2/token"}),async getUserInfo(t){let{data:r,error:o}=await ct("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 dt}from"@better-fetch/fetch";var fe=e=>({id:"facebook",name:"Facebook",async createAuthorizationURL({state:t,scopes:r,redirectURI:o}){let n=e.scope||r||["email","public_profile"];return await k({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})=>b({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 dt("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,emailVerified:r.email_verified},data:r}}});import{betterFetch as ge}from"@better-fetch/fetch";var he=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=e.scope||o||["user:email"];return k({id:"github",options:e,authorizationEndpoint:"https://github.com/login/oauth/authorize",scopes:s,state:r,redirectURI:i,codeVerifier:n})},validateAuthorizationCode:async({code:r,redirectURI:o})=>b({code:r,redirectURI:e.redirectURI||o,options:e,tokenEndpoint:t}),async getUserInfo(r){let{data:o,error:n}=await ge("https://api.github.com/user",{auth:{type:"Bearer",token:r.accessToken}});if(n)return null;let i=!1;if(!o.email){let{data:s,error:d}=await ge("https://api.github.com/user/emails",{auth:{type:"Bearer",token:r.accessToken}});d||(o.email=(s.find(a=>a.primary)??s[0])?.email,i=s.find(a=>a.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 ut}from"oslo/jwt";var we=e=>({id:"google",name:"Google",createAuthorizationURL({state:t,scopes:r,codeVerifier:o,redirectURI:n}){if(!e.clientId||!e.clientSecret)throw w.error("Client Id and Client Secret is required for Google. Make sure to provide them in the options."),new I("CLIENT_ID_AND_SECRET_REQUIRED");if(!o)throw new I("codeVerifier is required for Google");let i=e.scope||r||["email","profile"];return k({id:"google",options:e,authorizationEndpoint:"https://accounts.google.com/o/oauth2/auth",scopes:i,state:t,codeVerifier:o,redirectURI:n})},validateAuthorizationCode:async({code:t,codeVerifier:r,redirectURI:o})=>b({code:t,codeVerifier:r,redirectURI:e.redirectURI||o,options:e,tokenEndpoint:"https://oauth2.googleapis.com/token"}),async getUserInfo(t){if(!t.idToken)return null;let r=ut(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 pt}from"@better-fetch/fetch";import{parseJWT as lt}from"oslo/jwt";var ye=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=e.scope||n.scopes||["openid","profile","email","User.Read"];return k({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 b({code:n,codeVerifier:i,redirectURI:e.redirectURI||s,options:e,tokenEndpoint:o})},async getUserInfo(n){if(!n.idToken)return null;let i=lt(n.idToken)?.payload,s=e.profilePhotoSize||48;return await pt(`https://graph.microsoft.com/v1.0/me/photos/${s}x${s}/$value`,{headers:{Authorization:`Bearer ${n.accessToken}`},async onResponse(d){if(!(e.disableProfilePhoto||!d.response.ok))try{let c=await d.response.clone().arrayBuffer(),u=Buffer.from(c).toString("base64");i.picture=`data:image/jpeg;base64, ${u}`}catch(a){w.error(a)}}}),{user:{id:i.sub,name:i.name,email:i.email,image:i.picture,emailVerified:!0},data:i}}}};import{betterFetch as mt}from"@better-fetch/fetch";var be=e=>({id:"spotify",name:"Spotify",createAuthorizationURL({state:t,scopes:r,codeVerifier:o,redirectURI:n}){let i=e.scope||r||["user-read-email"];return k({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})=>b({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 mt("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";var L={isAction:!1};import{nanoid as ft}from"nanoid";var Ae=e=>ft(e);import{parseJWT as gt}from"oslo/jwt";var Re=e=>({id:"twitch",name:"Twitch",createAuthorizationURL({state:t,scopes:r,redirectURI:o}){let n=e.scope||r||["user:read:email","openid"];return k({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})=>b({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 w.error("No idToken found in token"),null;let o=gt(r)?.payload;return{user:{id:o.sub,name:o.preferred_username,email:o.email,image:o.picture,emailVerified:!1},data:o}}});import{betterFetch as ht}from"@better-fetch/fetch";var ke=e=>({id:"twitter",name:"Twitter",createAuthorizationURL(t){let r=e.scope||t.scopes||["account_info.read"];return k({id:"twitter",options:e,authorizationEndpoint:"https://twitter.com/i/oauth2/authorize",scopes:r,state:t.state,codeVerifier:t.codeVerifier,redirectURI:t.redirectURI})},validateAuthorizationCode:async({code:t,codeVerifier:r,redirectURI:o})=>b({code:t,codeVerifier:r,redirectURI:e.redirectURI||o,options:e,tokenEndpoint:"https://id.twitch.tv/oauth2/token"}),async getUserInfo(t){let{data:r,error:o}=await ht("https://api.x.com/2/users/me?user.fields=profile_image_url",{method:"GET",headers:{Authorization:`Bearer ${t.accessToken}`}});return o||!r.data.email?null:{user:{id:r.data.id,name:r.data.name,email:r.data.email,image:r.data.profile_image_url,emailVerified:r.data.verified||!1},data:r}}});var wt={apple:le,discord:me,facebook:fe,github:he,microsoft:ye,google:we,spotify:be,twitch:Re,twitter:ke},Ue=Object.keys(wt);import{TimeSpan as yt}from"oslo";import{createJWT as bt,validateJWT as At}from"oslo/jwt";import{z as T}from"zod";import{APIError as M}from"better-call";async function B(e,t){return await bt("HS256",Buffer.from(e),{email:t.toLowerCase()},{expiresIn:new yt(1,"h"),issuer:"better-auth",subject:"verify-email",audiences:[t],includeIssuedTimestamp:!0})}var Ee=p("/send-verification-email",{method:"POST",query:T.object({currentURL:T.string().optional()}).optional(),body:T.object({email:T.string().email(),callbackURL:T.string().optional()}),use:[U]},async e=>{if(!e.context.options.emailVerification?.sendVerificationEmail)throw e.context.logger.error("Verification email isn't enabled. Pass `sendVerificationEmail` in `emailAndPassword` options to enable it."),new M("BAD_REQUEST",{message:"Verification email isn't enabled"});let{email:t}=e.body,r=await e.context.internalAdapter.findUserByEmail(t);if(!r)throw new M("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(r.user,n,o),e.json({status:!0})}),xe=p("/verify-email",{method:"GET",query:T.object({token:T.string(),callbackURL:T.string().optional()})},async e=>{let{token:t}=e.query,r;try{r=await At("HS256",Buffer.from(e.context.secret),t)}catch(s){throw e.context.logger.error("Failed to verify email",s),new M("BAD_REQUEST",{message:"Invalid token"})}let n=T.object({email:T.string().email()}).parse(r.payload);if(!await e.context.internalAdapter.findUserByEmail(n.email))throw new M("BAD_REQUEST",{message:"User not found"});if(await e.context.internalAdapter.updateUserByEmail(n.email,{emailVerified:!0}),e.query.callbackURL)throw e.redirect(e.query.callbackURL);return e.json({status:!0})});var ve=p("/sign-in/social",{method:"POST",requireHeaders:!0,query:E.object({currentURL:E.string().optional()}).optional(),body:E.object({callbackURL:E.string().optional(),provider:E.enum(Ue)}),use:[U]},async e=>{let t=e.context.socialProviders.find(a=>a.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 P("NOT_FOUND",{message:"Provider not found"});let r=e.context.authCookies,o=e.query?.currentURL?new URL(e.query?.currentURL):null,n=e.body.callbackURL?.startsWith("http")?e.body.callbackURL:`${o?.origin}${e.body.callbackURL||""}`,i=await ce(n||o?.origin||e.context.options.baseURL);await e.setSignedCookie(r.state.name,i.hash,e.context.secret,r.state.options);let s=Rt();await e.setSignedCookie(r.pkCodeVerifier.name,s,e.context.secret,r.pkCodeVerifier.options);let d=await t.createAuthorizationURL({state:i.raw,codeVerifier:s,redirectURI:`${e.context.baseURL}/callback/${t.id}`});return e.json({url:d.toString(),state:i,codeVerifier:s,redirect:!0})}),Te=p("/sign-in/email",{method:"POST",body:E.object({email:E.string().email(),password:E.string(),callbackURL:E.string().optional(),dontRememberMe:E.boolean().default(!1).optional()}),use:[U]},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 P("BAD_REQUEST",{message:"Email and password is not enabled"});let{email:t,password:r}=e.body;if(!E.string().email().safeParse(t).success)throw new P("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 P("UNAUTHORIZED",{message:"Invalid email or password"});if(e.context.options?.emailAndPassword?.requireEmailVerification&&!n.user.emailVerified){if(!e.context.options?.emailVerification?.sendVerificationEmail)throw w.error("Email verification is required but no email verification handler is provided"),new P("INTERNAL_SERVER_ERROR",{message:"Email is not verified."});let c=await B(e.context.secret,n.user.email),u=`${e.context.options.baseURL}/verify-email?token=${c}`;throw await e.context.options.emailVerification.sendVerificationEmail(n.user,u,c),e.context.logger.error("Email not verified",{email:t}),new P("FORBIDDEN",{message:"Email is not verified. Check your email for a verification link"})}let i=n.accounts.find(c=>c.providerId==="credential");if(!i)throw e.context.logger.error("Credential account not found",{email:t}),new P("UNAUTHORIZED",{message:"Invalid email or password"});let s=i?.password;if(!s)throw e.context.logger.error("Password not found",{email:t}),new P("UNAUTHORIZED",{message:"Unexpected error"});if(!await e.context.password.verify(s,r))throw e.context.logger.error("Invalid password"),new P("UNAUTHORIZED",{message:"Invalid email or password"});let a=await e.context.internalAdapter.createSession(n.user.id,e.headers,e.body.dontRememberMe);if(!a)throw e.context.logger.error("Failed to create session"),new P("UNAUTHORIZED",{message:"Failed to create session"});return await v(e,a.id,e.body.dontRememberMe),e.json({user:n.user,session:a,redirect:!!e.body.callbackURL,url:e.body.callbackURL})});import{APIError as Ut}from"better-call";import{z as F}from"zod";import{z as m}from"zod";var Bn=m.object({id:m.string(),providerId:m.string(),accountId:m.string(),userId:m.string(),accessToken:m.string().nullable().optional(),refreshToken:m.string().nullable().optional(),idToken:m.string().nullable().optional(),expiresAt:m.date().nullable().optional(),password:m.string().optional().nullable()}),Pe=m.object({id:m.string(),email:m.string().transform(e=>e.toLowerCase()),emailVerified:m.boolean().default(!1),name:m.string(),image:m.string().optional(),createdAt:m.date().default(new Date),updatedAt:m.date().default(new Date)}),Dn=m.object({id:m.string(),userId:m.string(),expiresAt:m.date(),ipAddress:m.string().optional(),userAgent:m.string().optional()}),$n=m.object({id:m.string(),value:m.string(),expiresAt:m.date(),identifier:m.string()});function kt(e,t){let r=t.fields,o={};for(let n in r){if(n in e){if(r[n].input===!1){if(r[n].defaultValue){o[n]=r[n].defaultValue;continue}continue}o[n]=e[n];continue}if(r[n].defaultValue){o[n]=r[n].defaultValue;continue}}return o}function _e(e,t){let r={...e.user?.additionalFields};return kt(t||{},{fields:r})}var Se=p("/callback/:id",{method:"GET",query:F.object({state:F.string(),code:F.string().optional(),error:F.string().optional()}),metadata:L},async e=>{if(e.query.error||!e.query.code){let h=W(e.query.state).data?.callbackURL||`${e.context.baseURL}/error`;throw e.context.logger.error(e.query.error,e.params.id),e.redirect(`${h}?error=${e.query.error||"oAuth_code_missing"}`)}let t=e.context.socialProviders.find(l=>l.id===e.params.id);if(!t)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 r=W(e.query.state);if(!r.success)throw e.context.logger.error("Unable to parse state"),e.redirect(`${e.context.baseURL}/error?error=please_restart_the_process`);let{data:{callbackURL:o,currentURL:n}}=r,i=await e.getSignedCookie(e.context.authCookies.state.name,e.context.secret);if(!i)throw w.error("No stored state found"),e.redirect(`${e.context.baseURL}/error?error=please_restart_the_process`);if(!await ae(e.query.state,i))throw w.error("OAuth state mismatch"),e.redirect(`${e.context.baseURL}/error?error=please_restart_the_process`);let d=await e.getSignedCookie(e.context.authCookies.pkCodeVerifier.name,e.context.secret),a;try{a=await t.validateAuthorizationCode({code:e.query.code,codeVerifier:d,redirectURI:`${e.context.baseURL}/callback/${t.id}`})}catch(l){throw e.context.logger.error(l),e.redirect(`${e.context.baseURL}/error?error=please_restart_the_process`)}let c=await t.getUserInfo(a).then(l=>l?.user),u=Ae(),y=Pe.safeParse({...c,id:u});if(!c||y.success===!1)throw w.error("Unable to get user info",y.error),e.redirect(`${e.context.baseURL}/error?error=please_restart_the_process`);if(!o)throw e.redirect(`${e.context.baseURL}/error?error=please_restart_the_process`);let g=await e.context.internalAdapter.findUserByEmail(c.email,{includeAccounts:!0}).catch(l=>{throw w.error(`Better auth was unable to query your database.
|
|
3
|
+
Error: `,l),e.redirect(`${e.context.baseURL}/error?error=internal_server_error`)}),f=g?.user.id;if(g){let l=g.accounts.find(R=>R.providerId===t.id),h=e.context.options.account?.accountLinking?.trustedProviders,A=h?h.includes(t.id):!0;if(!l&&(!c.emailVerified||!A)){let R;try{R=new URL(n||o),R.searchParams.set("error","account_not_linked")}catch{throw e.redirect(`${e.context.baseURL}/error?error=account_not_linked`)}throw e.redirect(R.toString())}if(!l)try{await e.context.internalAdapter.linkAccount({providerId:t.id,accountId:c.id.toString(),id:`${t.id}:${c.id}`,userId:g.user.id,...J(a)})}catch(R){throw console.log(R),e.redirect(`${e.context.baseURL}/error?error=failed_linking_account`)}}else try{let l=c.emailVerified,h=await e.context.internalAdapter.createOAuthUser({...y.data,emailVerified:l},{...J(a),id:`${t.id}:${c.id}`,providerId:t.id,accountId:c.id.toString()});if(!l&&h&&e.context.options.emailVerification?.sendOnSignUp){let A=await B(e.context.secret,c.email),R=`${e.context.baseURL}/verify-email?token=${A}&callbackURL=${o}`;await e.context.options.emailVerification?.sendVerificationEmail?.(h.user,R,A)}}catch{let h=new URL(n||o);throw h.searchParams.set("error","unable_to_create_user"),e.redirect(h.toString())}if(!f&&!u)throw new Ut("INTERNAL_SERVER_ERROR",{message:"Unable to create user"});try{let l=await e.context.internalAdapter.createSession(f||u,e.request);if(!l){let h=new URL(n||o);throw h.searchParams.set("error","unable_to_create_session"),e.redirect(h.toString())}try{await v(e,l.id)}catch(h){e.context.logger.error("Unable to set session cookie",h);let A=new URL(n||o);throw A.searchParams.set("error","unable_to_create_session"),e.redirect(A.toString())}}catch{let l=new URL(n||o||"");throw l.searchParams.set("error","unable_to_create_session"),e.redirect(l.toString())}throw e.redirect(o)});import{APIError as j}from"better-call";var H=(e,t="ms")=>new Date(Date.now()+(t==="sec"?e*1e3:e));import{z as Le}from"zod";var K=()=>p("/session",{method:"GET",requireHeaders:!0},async e=>{try{let t=await e.getSignedCookie(e.context.authCookies.sessionToken.name,e.context.secret);if(!t)return e.json(null,{status:401});let r=await e.context.internalAdapter.findSession(t);if(!r||r.session.expiresAt<new Date)return z(e),r&&await e.context.internalAdapter.deleteSession(r.session.id),e.json(null,{status:401});if(await e.getSignedCookie(e.context.authCookies.dontRememberToken.name,e.context.secret))return e.json(r);let n=e.context.sessionConfig.expiresIn,i=e.context.sessionConfig.updateAge;if(r.session.expiresAt.valueOf()-n*1e3+i*1e3<=Date.now()){let a=await e.context.internalAdapter.updateSession(r.session.id,{expiresAt:H(e.context.sessionConfig.expiresIn,"sec")});if(!a)return z(e),e.json(null,{status:401});let c=(a.expiresAt.valueOf()-Date.now())/1e3;return await v(e,a.id,!1,{maxAge:c}),e.json({session:a,user:r.user})}return e.json(r)}catch(t){return e.context.logger.error(t),e.json(null,{status:500})}}),Et=async e=>await K()({...e,_flag:"json",headers:e.headers}),O=$(async e=>{let t=await Et(e);if(!t?.session)throw new j("UNAUTHORIZED");return{session:t}}),Oe=()=>p("/user/list-sessions",{method:"GET",use:[O],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)}),Ie=p("/user/revoke-session",{method:"POST",body:Le.object({id:Le.string()}),use:[O],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})}),Ce=p("/user/revoke-sessions",{method:"POST",use:[O],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})});import"zod";import{APIError as xt}from"better-call";var Be=p("/sign-out",{method:"POST"},async e=>{let t=await e.getSignedCookie(e.context.authCookies.sessionToken.name,e.context.secret);if(!t)throw new xt("BAD_REQUEST",{message:"Session not found"});return await e.context.internalAdapter.deleteSession(t),z(e),e.json({success:!0})});import{z as S}from"zod";import{APIError as G}from"better-call";var De=p("/forget-password",{method:"POST",body:S.object({email:S.string().email(),redirectTo:S.string()}),use:[U]},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 G("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=new Date(Date.now()+1e3*(e.context.options.emailAndPassword.resetPasswordTokenExpiresIn||n)),s=e.context.uuid();await e.context.internalAdapter.createVerificationValue({value:o.user.id,identifier:`reset-password:${s}`,expiresAt:i});let d=`${e.context.baseURL}/reset-password/${s}?callbackURL=${r}`;return await e.context.options.emailAndPassword.sendResetPassword(o.user,d),e.json({status:!0})}),$e=p("/reset-password/:token",{method:"GET",query:S.object({callbackURL:S.string()}),use:[U]},async e=>{let{token:t}=e.params,r=e.query.callbackURL,o=r.startsWith("http")?r:`${e.context.options.baseURL}${r}`;if(!t||!r)throw e.redirect(`${e.context.baseURL}/error?error=INVALID_TOKEN`);let n=await e.context.internalAdapter.findVerificationValue(`reset-password:${t}`);throw!n||n.expiresAt<new Date?e.redirect(`${o}?error=INVALID_TOKEN`):e.redirect(`${o}?token=${t}`)}),Ve=p("/reset-password",{query:S.object({token:S.string()}).optional(),method:"POST",body:S.object({newPassword:S.string()})},async e=>{let t=e.query?.token;if(!t)throw new G("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 G("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 G("BAD_REQUEST",{message:"Failed to update password"});return e.json({status:!0})});import{z as x}from"zod";import{APIError as _}from"better-call";var ze=p("/user/update",{method:"POST",body:x.object({name:x.string().optional(),image:x.string().optional()}),use:[O,U]},async e=>{let{name:t,image:r}=e.body,o=e.context.session;if(!r&&!t)return e.json({user:o.user});let n=await e.context.internalAdapter.updateUserByEmail(o.user.email,{name:t,image:r});return e.json({user:n})}),je=p("/user/change-password",{method:"POST",body:x.object({newPassword:x.string(),currentPassword:x.string(),revokeOtherSessions:x.boolean().optional()}),use:[O]},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 _("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 _("BAD_REQUEST",{message:"Password too long"});let a=(await e.context.internalAdapter.findAccounts(n.user.id)).find(y=>y.providerId==="credential"&&y.password);if(!a||!a.password)throw new _("BAD_REQUEST",{message:"User does not have a password"});let c=await e.context.password.hash(t);if(!await e.context.password.verify(a.password,r))throw new _("BAD_REQUEST",{message:"Incorrect password"});if(await e.context.internalAdapter.updateAccount(a.id,{password:c}),o){await e.context.internalAdapter.deleteSessions(n.user.id);let y=await e.context.internalAdapter.createSession(n.user.id,e.headers);if(!y)throw new _("INTERNAL_SERVER_ERROR",{message:"Unable to create session"});await v(e,y.id)}return e.json(n.user)}),qe=p("/user/set-password",{method:"POST",body:x.object({newPassword:x.string()}),use:[O]},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 _("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 _("BAD_REQUEST",{message:"Password too long"});let s=(await e.context.internalAdapter.findAccounts(r.user.id)).find(a=>a.providerId==="credential"&&a.password),d=await e.context.password.hash(t);if(!s)return await e.context.internalAdapter.linkAccount({userId:r.user.id,providerId:"credential",accountId:r.user.id,password:d}),e.json(r.user);throw new _("BAD_REQUEST",{message:"user already has a password"})}),Ne=p("/user/delete",{method:"POST",body:x.object({password:x.string()}),use:[O]},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 _("BAD_REQUEST",{message:"User does not have a password"});if(!await e.context.password.verify(n.password,t))throw new _("BAD_REQUEST",{message:"Incorrect password"});return await e.context.internalAdapter.deleteUser(r.user.id),await e.context.internalAdapter.deleteSessions(r.user.id),e.json(null)});var Me=p("/csrf",{method:"GET",metadata:L},async e=>{let t=await e.getSignedCookie(e.context.authCookies.csrfToken.name,e.context.secret);if(t){let[i,s]=t.split("!")||[null,null];return e.json({csrfToken:i})}let r=Y(32,ee("a-z","0-9","A-Z")),o=await q(e.context.secret,r),n=`${r}!${o}`;return await e.setSignedCookie(e.context.authCookies.csrfToken.name,n,e.context.secret,e.context.authCookies.csrfToken.options),e.json({csrfToken:r})});var vt=(e="Unknown")=>`<!DOCTYPE html>
|
|
4
4
|
<html lang="en">
|
|
5
5
|
<head>
|
|
6
6
|
<meta charset="UTF-8">
|
|
@@ -80,4 +80,4 @@ Error: `,p),e.redirect(`${e.context.baseURL}/error?error=internal_server_error`)
|
|
|
80
80
|
<div class="error-code">Error Code: <span id="errorCode">${e}</span></div>
|
|
81
81
|
</div>
|
|
82
82
|
</body>
|
|
83
|
-
</html>`,Fe=
|
|
83
|
+
</html>`,Fe=p("/error",{method:"GET",metadata:L},async e=>{let t=new URL(e.request?.url||"").searchParams.get("error")||"Unknown";return new Response(vt(t),{headers:{"Content-Type":"text/html"}})});var He=p("/ok",{method:"GET",metadata:L},async e=>e.json({ok:!0}));import{z as V}from"zod";import{APIError as D}from"better-call";var Ge=()=>p("/sign-up/email",{method:"POST",query:V.object({currentURL:V.string().optional()}).optional(),body:V.record(V.string(),V.any()),use:[U]},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,...d}=t;if(!V.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:"Failed to create user"});let g=_e(e.context.options,d),f=await e.context.internalAdapter.createUser({email:o.toLowerCase(),name:r,image:i,...g,emailVerified:!1});if(!f)throw new D("BAD_REQUEST",{message:"Failed to create user"});let l=await e.context.password.hash(n);if(await e.context.internalAdapter.linkAccount({userId:f.id,providerId:"credential",accountId:f.id,password:l,expiresAt:H(60*60*24*30,"sec")}),e.context.options.emailVerification?.sendOnSignUp){let A=await B(e.context.secret,f.email),R=`${e.context.baseURL}/verify-email?token=${A}&callbackURL=${t.callbackURL||e.query?.currentURL||"/"}`;await e.context.options.emailVerification?.sendVerificationEmail?.(f,R,A)}if(!e.context.options.emailAndPassword.autoSignIn)return e.json({user:f,session:null},{body:t.callbackURL?{url:t.callbackURL,redirect:!0}:{user:f,session:null}});let h=await e.context.internalAdapter.createSession(f.id,e.request);if(!h)throw new D("BAD_REQUEST",{message:"Failed to create session"});return await v(e,h.id),e.json({user:f,session:h},{body:t.callbackURL?{url:t.callbackURL,redirect:!0}:{user:f,session:h}})});function Qe(e){let t="127.0.0.1";if(process.env.NODE_ENV==="test")return t;let r=["x-client-ip","x-forwarded-for","cf-connecting-ip","fastly-client-ip","x-real-ip","x-cluster-client-ip","x-forwarded","forwarded-for","forwarded"];for(let o of r){let n=e.headers.get(o);if(typeof n=="string"){let i=n.split(",")[0].trim();if(i)return i}}return null}function Tt(e,t,r){let o=Date.now(),n=t*1e3;return o-r.lastRequest<n&&r.count>=e}function Pt(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 _t(e,t){let r=Date.now(),o=t*1e3;return Math.ceil((e+o-r)/1e3)}function St(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(d){w.error("Error setting rate limit",d)}}}}var Ze=new Map;function Lt(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 Ze.get(r)},async set(r,o,n){Ze.set(r,o)}}:St(e,e.rateLimit.tableName)}async function We(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=Qe(e)+o,a=Ot().find(g=>g.pathMatcher(o));a&&(n=a.window,i=a.max);for(let g of t.options.plugins||[])if(g.rateLimit){let f=g.rateLimit.find(l=>l.pathMatcher(o));if(f){n=f.window,i=f.max;break}}if(t.rateLimit.customRules){let g=t.rateLimit.customRules[o];g&&(n=g.window,i=g.max)}let c=Lt(t),u=await c.get(s),y=Date.now();if(!u)await c.set(s,{key:s,count:1,lastRequest:y});else{let g=y-u.lastRequest;if(Tt(i,n,u)){let f=_t(u.lastRequest,n);return Pt(f)}else g>n*1e3?await c.set(s,{...u,count:1,lastRequest:y}):await c.set(s,{...u,count:u.count+1,lastRequest:y})}}function Ot(){return[{pathMatcher(t){return t.startsWith("/sign-in")||t.startsWith("/sign-up")},window:10,max:7}]}import{APIError as Ls}from"better-call";function Bt(e,t){let r=t.plugins?.reduce((d,a)=>({...d,...a.endpoints}),{}),o=t.plugins?.map(d=>d.middlewares?.map(a=>{let c=async u=>a.middleware({...u,context:{...e,...u.context}});return c.path=a.path,c.options=a.middleware.options,c.headers=a.middleware.headers,{path:a.path,middleware:c}})).filter(d=>d!==void 0).flat()||[],i={...{signInOAuth:ve,callbackOAuth:Se,getCSRFToken:Me,getSession:K(),signOut:Be,signUpEmail:Ge(),signInEmail:Te,forgetPassword:De,resetPassword:Ve,verifyEmail:xe,sendVerificationEmail:Ee,changePassword:je,setPassword:qe,updateUser:ze,deleteUser:Ne,forgetPasswordCallback:$e,listSessions:Oe(),revokeSession:Ie,revokeSessions:Ce},...r,ok:He,error:Fe},s={};for(let[d,a]of Object.entries(i))s[d]=async(c={})=>{let u=await e;for(let f of t.plugins||[])if(f.hooks?.before){for(let l of f.hooks.before)if(l.matcher({...a,...c,context:u})){let A=await l.handler({...c,context:{...u,...c?.context}});A&&"context"in A&&(u={...u,...A.context})}}let g=await a({...c,context:{...u,...c.context}});for(let f of t.plugins||[])if(f.hooks?.after){for(let l of f.hooks.after)if(l.matcher(c)){let A=Object.assign(c,{context:{...e,returned:g}}),R=await l.handler(A);R&&"response"in R&&(g=R.response)}}return g},s[d].path=a.path,s[d].method=a.method,s[d].options=a.options,s[d].headers=a.headers;return{api:s,middlewares:o}}var xs=(e,t)=>{let{api:r,middlewares:o}=Bt(e,t),n=new URL(e.baseURL).pathname;return Ct(r,{extraContext:e,basePath:n,routerMiddleware:[{path:"/**",middleware:ne},...o],async onRequest(i){for(let s of e.options.plugins||[])if(s.onRequest){let d=await s.onRequest(i,e);if(d)return d}return We(i,e)},async onResponse(i){for(let s of e.options.plugins||[])if(s.onResponse){let d=await s.onResponse(i,e);if(d)return d.response}return i},onError(i){if(t.onAPIError?.throw)throw i;if(t.onAPIError?.onError){t.onAPIError.onError(i,e);return}let s=t.logger?.verboseLogging?w:void 0;t.logger?.disabled!==!0&&(i instanceof It?(i.status==="INTERNAL_SERVER_ERROR"&&w.error(i),s?.error(i.message)):w?.error(i))}})};export{Ls as APIError,Se as callbackOAuth,je as changePassword,p as createAuthEndpoint,$ as createAuthMiddleware,B as createEmailVerificationToken,ne as csrfMiddleware,Ne as deleteUser,Fe as error,De as forgetPassword,$e as forgetPasswordCallback,Me as getCSRFToken,Bt as getEndpoints,K as getSession,Et as getSessionFromCtx,Oe as listSessions,He as ok,re as optionsMiddleware,Ve as resetPassword,Ie as revokeSession,Ce as revokeSessions,xs as router,Ee as sendVerificationEmail,O as sessionMiddleware,qe as setPassword,Te as signInEmail,ve as signInOAuth,Be as signOut,Ge as signUpEmail,ze as updateUser,xe as verifyEmail};
|
|
@@ -546,7 +546,9 @@ type Where = {
|
|
|
546
546
|
*/
|
|
547
547
|
interface Adapter {
|
|
548
548
|
id: string;
|
|
549
|
-
create: <T
|
|
549
|
+
create: <T extends {
|
|
550
|
+
id?: string;
|
|
551
|
+
} & Record<string, any>, R = T>(data: {
|
|
550
552
|
model: string;
|
|
551
553
|
data: T;
|
|
552
554
|
select?: string[];
|
|
@@ -682,6 +684,15 @@ interface BetterAuthOptions {
|
|
|
682
684
|
database: PostgresPool | MysqlPool | BetterSqlite3Database | Dialect | {
|
|
683
685
|
dialect: Dialect;
|
|
684
686
|
type: KyselyDatabaseType;
|
|
687
|
+
/**
|
|
688
|
+
* Custom generateId function.
|
|
689
|
+
*
|
|
690
|
+
* If not provided, nanoid will be used.
|
|
691
|
+
* If set to false, the database's auto generated id will be used.
|
|
692
|
+
*
|
|
693
|
+
* @default nanoid
|
|
694
|
+
*/
|
|
695
|
+
generateId?: ((size?: number) => string) | false;
|
|
685
696
|
} | Adapter | {
|
|
686
697
|
/**
|
|
687
698
|
* Kysely instance
|
|
@@ -691,6 +702,15 @@ interface BetterAuthOptions {
|
|
|
691
702
|
* Database type between postgres, mysql and sqlite
|
|
692
703
|
*/
|
|
693
704
|
type: KyselyDatabaseType;
|
|
705
|
+
/**
|
|
706
|
+
* Custom generateId function.
|
|
707
|
+
*
|
|
708
|
+
* If not provided, nanoid will be used.
|
|
709
|
+
* If set to false, the database's auto generated id will be used.
|
|
710
|
+
*
|
|
711
|
+
* @default nanoid
|
|
712
|
+
*/
|
|
713
|
+
generateId?: ((size?: number) => string) | false;
|
|
694
714
|
};
|
|
695
715
|
/**
|
|
696
716
|
* Secondary storage configuration
|
|
@@ -1072,7 +1092,7 @@ declare const createInternalAdapter: (adapter: Adapter, ctx: {
|
|
|
1072
1092
|
options: BetterAuthOptions;
|
|
1073
1093
|
hooks: Exclude<BetterAuthOptions["databaseHooks"], undefined>[];
|
|
1074
1094
|
}) => {
|
|
1075
|
-
createOAuthUser: (user: User, account: Account) => Promise<{
|
|
1095
|
+
createOAuthUser: (user: User, account: Omit<Account, "userId">) => Promise<{
|
|
1076
1096
|
user: any;
|
|
1077
1097
|
account: any;
|
|
1078
1098
|
} | null>;
|
|
@@ -1208,12 +1228,12 @@ declare const signInOAuth: {
|
|
|
1208
1228
|
/**
|
|
1209
1229
|
* OAuth2 provider to use`
|
|
1210
1230
|
*/
|
|
1211
|
-
provider: z.ZodEnum<["github", ...("
|
|
1231
|
+
provider: z.ZodEnum<["github", ...("apple" | "discord" | "facebook" | "github" | "google" | "microsoft" | "spotify" | "twitch" | "twitter")[]]>;
|
|
1212
1232
|
}, "strip", z.ZodTypeAny, {
|
|
1213
|
-
provider: "
|
|
1233
|
+
provider: "apple" | "discord" | "facebook" | "github" | "google" | "microsoft" | "spotify" | "twitch" | "twitter";
|
|
1214
1234
|
callbackURL?: string | undefined;
|
|
1215
1235
|
}, {
|
|
1216
|
-
provider: "
|
|
1236
|
+
provider: "apple" | "discord" | "facebook" | "github" | "google" | "microsoft" | "spotify" | "twitch" | "twitter";
|
|
1217
1237
|
callbackURL?: string | undefined;
|
|
1218
1238
|
}>;
|
|
1219
1239
|
use: better_call.Endpoint<better_call.Handler<string, better_call.EndpointOptions, void>, better_call.EndpointOptions>[];
|
|
@@ -1251,12 +1271,12 @@ declare const signInOAuth: {
|
|
|
1251
1271
|
/**
|
|
1252
1272
|
* OAuth2 provider to use`
|
|
1253
1273
|
*/
|
|
1254
|
-
provider: z.ZodEnum<["github", ...("
|
|
1274
|
+
provider: z.ZodEnum<["github", ...("apple" | "discord" | "facebook" | "github" | "google" | "microsoft" | "spotify" | "twitch" | "twitter")[]]>;
|
|
1255
1275
|
}, "strip", z.ZodTypeAny, {
|
|
1256
|
-
provider: "
|
|
1276
|
+
provider: "apple" | "discord" | "facebook" | "github" | "google" | "microsoft" | "spotify" | "twitch" | "twitter";
|
|
1257
1277
|
callbackURL?: string | undefined;
|
|
1258
1278
|
}, {
|
|
1259
|
-
provider: "
|
|
1279
|
+
provider: "apple" | "discord" | "facebook" | "github" | "google" | "microsoft" | "spotify" | "twitch" | "twitter";
|
|
1260
1280
|
callbackURL?: string | undefined;
|
|
1261
1281
|
}>;
|
|
1262
1282
|
use: better_call.Endpoint<better_call.Handler<string, better_call.EndpointOptions, void>, better_call.EndpointOptions>[];
|
|
@@ -2453,12 +2473,12 @@ declare function getEndpoints<C extends AuthContext, Option extends BetterAuthOp
|
|
|
2453
2473
|
}>>;
|
|
2454
2474
|
body: zod.ZodObject<{
|
|
2455
2475
|
callbackURL: zod.ZodOptional<zod.ZodString>;
|
|
2456
|
-
provider: zod.ZodEnum<["github", ...("
|
|
2476
|
+
provider: zod.ZodEnum<["github", ...("apple" | "discord" | "facebook" | "github" | "google" | "microsoft" | "spotify" | "twitch" | "twitter")[]]>;
|
|
2457
2477
|
}, "strip", zod.ZodTypeAny, {
|
|
2458
|
-
provider: "
|
|
2478
|
+
provider: "apple" | "discord" | "facebook" | "github" | "google" | "microsoft" | "spotify" | "twitch" | "twitter";
|
|
2459
2479
|
callbackURL?: string | undefined;
|
|
2460
2480
|
}, {
|
|
2461
|
-
provider: "
|
|
2481
|
+
provider: "apple" | "discord" | "facebook" | "github" | "google" | "microsoft" | "spotify" | "twitch" | "twitter";
|
|
2462
2482
|
callbackURL?: string | undefined;
|
|
2463
2483
|
}>;
|
|
2464
2484
|
use: Endpoint<better_call.Handler<string, better_call.EndpointOptions, void>, better_call.EndpointOptions>[];
|
|
@@ -2486,12 +2506,12 @@ declare function getEndpoints<C extends AuthContext, Option extends BetterAuthOp
|
|
|
2486
2506
|
}>>;
|
|
2487
2507
|
body: zod.ZodObject<{
|
|
2488
2508
|
callbackURL: zod.ZodOptional<zod.ZodString>;
|
|
2489
|
-
provider: zod.ZodEnum<["github", ...("
|
|
2509
|
+
provider: zod.ZodEnum<["github", ...("apple" | "discord" | "facebook" | "github" | "google" | "microsoft" | "spotify" | "twitch" | "twitter")[]]>;
|
|
2490
2510
|
}, "strip", zod.ZodTypeAny, {
|
|
2491
|
-
provider: "
|
|
2511
|
+
provider: "apple" | "discord" | "facebook" | "github" | "google" | "microsoft" | "spotify" | "twitch" | "twitter";
|
|
2492
2512
|
callbackURL?: string | undefined;
|
|
2493
2513
|
}, {
|
|
2494
|
-
provider: "
|
|
2514
|
+
provider: "apple" | "discord" | "facebook" | "github" | "google" | "microsoft" | "spotify" | "twitch" | "twitter";
|
|
2495
2515
|
callbackURL?: string | undefined;
|
|
2496
2516
|
}>;
|
|
2497
2517
|
use: Endpoint<better_call.Handler<string, better_call.EndpointOptions, void>, better_call.EndpointOptions>[];
|
|
@@ -3548,12 +3568,12 @@ declare const router: <C extends AuthContext, Option extends BetterAuthOptions>(
|
|
|
3548
3568
|
}>>;
|
|
3549
3569
|
body: zod.ZodObject<{
|
|
3550
3570
|
callbackURL: zod.ZodOptional<zod.ZodString>;
|
|
3551
|
-
provider: zod.ZodEnum<["github", ...("
|
|
3571
|
+
provider: zod.ZodEnum<["github", ...("apple" | "discord" | "facebook" | "github" | "google" | "microsoft" | "spotify" | "twitch" | "twitter")[]]>;
|
|
3552
3572
|
}, "strip", zod.ZodTypeAny, {
|
|
3553
|
-
provider: "
|
|
3573
|
+
provider: "apple" | "discord" | "facebook" | "github" | "google" | "microsoft" | "spotify" | "twitch" | "twitter";
|
|
3554
3574
|
callbackURL?: string | undefined;
|
|
3555
3575
|
}, {
|
|
3556
|
-
provider: "
|
|
3576
|
+
provider: "apple" | "discord" | "facebook" | "github" | "google" | "microsoft" | "spotify" | "twitch" | "twitter";
|
|
3557
3577
|
callbackURL?: string | undefined;
|
|
3558
3578
|
}>;
|
|
3559
3579
|
use: Endpoint<better_call.Handler<string, better_call.EndpointOptions, void>, better_call.EndpointOptions>[];
|
|
@@ -3581,12 +3601,12 @@ declare const router: <C extends AuthContext, Option extends BetterAuthOptions>(
|
|
|
3581
3601
|
}>>;
|
|
3582
3602
|
body: zod.ZodObject<{
|
|
3583
3603
|
callbackURL: zod.ZodOptional<zod.ZodString>;
|
|
3584
|
-
provider: zod.ZodEnum<["github", ...("
|
|
3604
|
+
provider: zod.ZodEnum<["github", ...("apple" | "discord" | "facebook" | "github" | "google" | "microsoft" | "spotify" | "twitch" | "twitter")[]]>;
|
|
3585
3605
|
}, "strip", zod.ZodTypeAny, {
|
|
3586
|
-
provider: "
|
|
3606
|
+
provider: "apple" | "discord" | "facebook" | "github" | "google" | "microsoft" | "spotify" | "twitch" | "twitter";
|
|
3587
3607
|
callbackURL?: string | undefined;
|
|
3588
3608
|
}, {
|
|
3589
|
-
provider: "
|
|
3609
|
+
provider: "apple" | "discord" | "facebook" | "github" | "google" | "microsoft" | "spotify" | "twitch" | "twitter";
|
|
3590
3610
|
callbackURL?: string | undefined;
|
|
3591
3611
|
}>;
|
|
3592
3612
|
use: Endpoint<better_call.Handler<string, better_call.EndpointOptions, void>, better_call.EndpointOptions>[];
|
|
@@ -4645,12 +4665,12 @@ declare const betterAuth: <O extends BetterAuthOptions>(options: O) => {
|
|
|
4645
4665
|
}>>;
|
|
4646
4666
|
body: zod.ZodObject<{
|
|
4647
4667
|
callbackURL: zod.ZodOptional<zod.ZodString>;
|
|
4648
|
-
provider: zod.ZodEnum<["github", ...("
|
|
4668
|
+
provider: zod.ZodEnum<["github", ...("apple" | "discord" | "facebook" | "github" | "google" | "microsoft" | "spotify" | "twitch" | "twitter")[]]>;
|
|
4649
4669
|
}, "strip", zod.ZodTypeAny, {
|
|
4650
|
-
provider: "
|
|
4670
|
+
provider: "apple" | "discord" | "facebook" | "github" | "google" | "microsoft" | "spotify" | "twitch" | "twitter";
|
|
4651
4671
|
callbackURL?: string | undefined;
|
|
4652
4672
|
}, {
|
|
4653
|
-
provider: "
|
|
4673
|
+
provider: "apple" | "discord" | "facebook" | "github" | "google" | "microsoft" | "spotify" | "twitch" | "twitter";
|
|
4654
4674
|
callbackURL?: string | undefined;
|
|
4655
4675
|
}>;
|
|
4656
4676
|
use: Endpoint<better_call.Handler<string, better_call.EndpointOptions, void>, better_call.EndpointOptions>[];
|
|
@@ -4678,12 +4698,12 @@ declare const betterAuth: <O extends BetterAuthOptions>(options: O) => {
|
|
|
4678
4698
|
}>>;
|
|
4679
4699
|
body: zod.ZodObject<{
|
|
4680
4700
|
callbackURL: zod.ZodOptional<zod.ZodString>;
|
|
4681
|
-
provider: zod.ZodEnum<["github", ...("
|
|
4701
|
+
provider: zod.ZodEnum<["github", ...("apple" | "discord" | "facebook" | "github" | "google" | "microsoft" | "spotify" | "twitch" | "twitter")[]]>;
|
|
4682
4702
|
}, "strip", zod.ZodTypeAny, {
|
|
4683
|
-
provider: "
|
|
4703
|
+
provider: "apple" | "discord" | "facebook" | "github" | "google" | "microsoft" | "spotify" | "twitch" | "twitter";
|
|
4684
4704
|
callbackURL?: string | undefined;
|
|
4685
4705
|
}, {
|
|
4686
|
-
provider: "
|
|
4706
|
+
provider: "apple" | "discord" | "facebook" | "github" | "google" | "microsoft" | "spotify" | "twitch" | "twitter";
|
|
4687
4707
|
callbackURL?: string | undefined;
|
|
4688
4708
|
}>;
|
|
4689
4709
|
use: Endpoint<better_call.Handler<string, better_call.EndpointOptions, void>, better_call.EndpointOptions>[];
|