better-auth 0.5.2-beta.8 → 0.5.2-beta.9
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/adapters/drizzle.cjs +1 -1
- package/dist/adapters/drizzle.d.cts +1 -1
- package/dist/adapters/drizzle.d.ts +1 -1
- package/dist/adapters/drizzle.js +1 -1
- package/dist/adapters/kysely.cjs +1 -1
- package/dist/adapters/kysely.d.cts +1 -1
- package/dist/adapters/kysely.d.ts +1 -1
- package/dist/adapters/kysely.js +1 -1
- package/dist/adapters/mongodb.cjs +1 -1
- package/dist/adapters/mongodb.d.cts +1 -1
- package/dist/adapters/mongodb.d.ts +1 -1
- package/dist/adapters/mongodb.js +1 -1
- package/dist/adapters/prisma.cjs +1 -1
- package/dist/adapters/prisma.d.cts +1 -1
- package/dist/adapters/prisma.d.ts +1 -1
- package/dist/adapters/prisma.js +1 -1
- package/dist/api.cjs +1 -1
- package/dist/api.d.cts +1 -1
- package/dist/api.d.ts +1 -1
- package/dist/api.js +1 -1
- package/dist/{auth-BCiGnEDb.d.ts → auth-D1kVkHCi.d.ts} +25 -30
- package/dist/{auth-DRTmeEd6.d.cts → auth-D7_h4yVD.d.cts} +25 -30
- package/dist/client/plugins.d.cts +3 -3
- package/dist/client/plugins.d.ts +3 -3
- package/dist/client.d.cts +1 -1
- package/dist/client.d.ts +1 -1
- package/dist/cookies.d.cts +1 -1
- package/dist/cookies.d.ts +1 -1
- package/dist/db.cjs +3 -3
- package/dist/db.d.cts +2 -2
- package/dist/db.d.ts +2 -2
- package/dist/db.js +3 -3
- package/dist/{index-B9m_P8YT.d.cts → index-BiscX-kB.d.cts} +47 -1
- package/dist/{index-x-IMPjJ7.d.ts → index-C2LqoRnX.d.ts} +47 -1
- package/dist/index.cjs +2 -2
- package/dist/index.d.cts +1 -1
- package/dist/index.d.ts +1 -1
- package/dist/index.js +2 -2
- package/dist/node.d.cts +1 -1
- package/dist/node.d.ts +1 -1
- package/dist/plugins.cjs +5 -5
- package/dist/plugins.d.cts +3 -3
- package/dist/plugins.d.ts +3 -3
- package/dist/plugins.js +5 -5
- package/dist/react.d.cts +1 -1
- package/dist/react.d.ts +1 -1
- package/dist/social.d.cts +4 -0
- package/dist/social.d.ts +4 -0
- package/dist/solid-start.d.cts +1 -1
- package/dist/solid-start.d.ts +1 -1
- package/dist/solid.d.cts +1 -1
- package/dist/solid.d.ts +1 -1
- package/dist/svelte-kit.d.cts +1 -1
- package/dist/svelte-kit.d.ts +1 -1
- package/dist/svelte.d.cts +1 -1
- package/dist/svelte.d.ts +1 -1
- package/dist/types.d.cts +2 -2
- package/dist/types.d.ts +2 -2
- package/dist/vue.d.cts +1 -1
- package/dist/vue.d.ts +1 -1
- package/package.json +74 -1
|
@@ -1 +1 @@
|
|
|
1
|
-
"use strict";var w=Object.defineProperty;var g=Object.getOwnPropertyDescriptor;var
|
|
1
|
+
"use strict";var w=Object.defineProperty;var g=Object.getOwnPropertyDescriptor;var v=Object.getOwnPropertyNames;var P=Object.prototype.hasOwnProperty;var z=(t,r)=>{for(var s in r)w(t,s,{get:r[s],enumerable:!0})},A=(t,r,s,c)=>{if(r&&typeof r=="object"||typeof r=="function")for(let a of v(r))!P.call(t,a)&&a!==s&&w(t,a,{get:()=>r[a],enumerable:!(c=g(r,a))||c.enumerable});return t};var $=t=>A(w({},"__esModule",{value:!0}),t);var x={};z(x,{drizzleAdapter:()=>q});module.exports=$(x);var n=require("drizzle-orm");var f=class extends Error{constructor(r,s){super(r),this.name="BetterAuthError",this.message=r,this.cause=s,this.stack=""}};function m(t,r){let s=r.schema;if(!s)throw new f("Drizzle adapter failed to initialize. Schema not found. Please provide a schema object in the adapter options object.");let c=r.usePlural?`${t}s`:t,a=s[c];if(!a)throw new f(`[# Drizzle Adapter]: The model "${t}" was not found in the schema object. Please pass the schema directly to the adapter options.`);return a}function p(t,r){if(!t)return[];if(t.length===1){let e=t[0];if(!e)return[];if(e.operator==="in"){if(!Array.isArray(e.value))throw new f(`The value for the field "${e.field}" must be an array when using the "in" operator.`);return[(0,n.inArray)(r[e.field],e.value)]}return e.operator==="contains"?[(0,n.like)(r[e.field],`%${e.value}%`)]:e.operator==="starts_with"?[(0,n.like)(r[e.field],`${e.value}%`)]:e.operator==="ends_with"?[(0,n.like)(r[e.field],`%${e.value}`)]:[(0,n.eq)(r[e.field],e.value)]}let s=t.filter(e=>e.connector==="AND"||!e.connector),c=t.filter(e=>e.connector==="OR"),a=(0,n.and)(...s.map(e=>{if(e.operator==="in"){if(!Array.isArray(e.value))throw new f(`The value for the field "${e.field}" must be an array when using the "in" operator.`);return(0,n.inArray)(r[e.field],e.value)}return(0,n.eq)(r[e.field],e.value)})),o=(0,n.or)(...c.map(e=>(0,n.eq)(r[e.field],e.value))),i=[];return s.length&&i.push(a),c.length&&i.push(o),i}var q=(t,r)=>{let s=r.schema||t._.fullSchema,c=r?.provider;return{id:"drizzle",async create(a){let{model:o,data:i}=a,e=m(o,{schema:s,usePlural:r.usePlural});r.generateId!==void 0&&(i.id=r.generateId?r.generateId():void 0);let l=t.insert(e).values(i);return c!=="mysql"?(await l.returning())[0]:(await l,(await t.select().from(e).where((0,n.eq)(e.id,a.data.id)))[0])},async findOne(a){let{model:o,where:i,select:e}=a,l=m(o,{schema:s,usePlural:r.usePlural}),d=p(i,l),u=null;return e?.length?u=await t.select(...e.map(h=>({[h]:l[h]}))).from(l).where(...d):u=await t.select().from(l).where(...d),u.length?u[0]:null},async findMany(a){let{model:o,where:i,limit:e,offset:l,sortBy:d}=a,u=m(o,{schema:s,usePlural:r.usePlural}),h=i?p(i,u):[],y=d?.direction==="desc"?n.desc:n.asc;return await t.select().from(u).limit(e||100).offset(l||0).orderBy(y(u[d?.field||"id"])).where(...h.length?h:[])},async update(a){let{model:o,where:i,update:e}=a,l=m(o,{schema:s,usePlural:r.usePlural}),d=p(i,l),u=t.update(l).set(e).where(...d);return c!=="mysql"?(await u.returning())[0]:(await u,(await t.select().from(l).where((0,n.eq)(l.id,a.update.id)))[0])},async delete(a){let{model:o,where:i}=a,e=m(o,{schema:s,usePlural:r.usePlural}),l=p(i,e);return(await t.delete(e).where(...l))[0]},async deleteMany(a){let{model:o,where:i}=a,e=m(o,{schema:s,usePlural:r.usePlural}),l=p(i,e);await t.delete(e).where(...l)},options:r}};0&&(module.exports={drizzleAdapter});
|
package/dist/adapters/drizzle.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
import{and as
|
|
1
|
+
import{and as v,asc as P,desc as z,eq as p,or as A,inArray as y,like as w}from"drizzle-orm";var d=class extends Error{constructor(r,l){super(r),this.name="BetterAuthError",this.message=r,this.cause=l,this.stack=""}};function h(t,r){let l=r.schema;if(!l)throw new d("Drizzle adapter failed to initialize. Schema not found. Please provide a schema object in the adapter options object.");let c=r.usePlural?`${t}s`:t,a=l[c];if(!a)throw new d(`[# Drizzle Adapter]: The model "${t}" was not found in the schema object. Please pass the schema directly to the adapter options.`);return a}function m(t,r){if(!t)return[];if(t.length===1){let e=t[0];if(!e)return[];if(e.operator==="in"){if(!Array.isArray(e.value))throw new d(`The value for the field "${e.field}" must be an array when using the "in" operator.`);return[y(r[e.field],e.value)]}return e.operator==="contains"?[w(r[e.field],`%${e.value}%`)]:e.operator==="starts_with"?[w(r[e.field],`${e.value}%`)]:e.operator==="ends_with"?[w(r[e.field],`%${e.value}`)]:[p(r[e.field],e.value)]}let l=t.filter(e=>e.connector==="AND"||!e.connector),c=t.filter(e=>e.connector==="OR"),a=v(...l.map(e=>{if(e.operator==="in"){if(!Array.isArray(e.value))throw new d(`The value for the field "${e.field}" must be an array when using the "in" operator.`);return y(r[e.field],e.value)}return p(r[e.field],e.value)})),i=A(...c.map(e=>p(r[e.field],e.value))),s=[];return l.length&&s.push(a),c.length&&s.push(i),s}var B=(t,r)=>{let l=r.schema||t._.fullSchema,c=r?.provider;return{id:"drizzle",async create(a){let{model:i,data:s}=a,e=h(i,{schema:l,usePlural:r.usePlural});r.generateId!==void 0&&(s.id=r.generateId?r.generateId():void 0);let n=t.insert(e).values(s);return c!=="mysql"?(await n.returning())[0]:(await n,(await t.select().from(e).where(p(e.id,a.data.id)))[0])},async findOne(a){let{model:i,where:s,select:e}=a,n=h(i,{schema:l,usePlural:r.usePlural}),u=m(s,n),o=null;return e?.length?o=await t.select(...e.map(f=>({[f]:n[f]}))).from(n).where(...u):o=await t.select().from(n).where(...u),o.length?o[0]:null},async findMany(a){let{model:i,where:s,limit:e,offset:n,sortBy:u}=a,o=h(i,{schema:l,usePlural:r.usePlural}),f=s?m(s,o):[],g=u?.direction==="desc"?z:P;return await t.select().from(o).limit(e||100).offset(n||0).orderBy(g(o[u?.field||"id"])).where(...f.length?f:[])},async update(a){let{model:i,where:s,update:e}=a,n=h(i,{schema:l,usePlural:r.usePlural}),u=m(s,n),o=t.update(n).set(e).where(...u);return c!=="mysql"?(await o.returning())[0]:(await o,(await t.select().from(n).where(p(n.id,a.update.id)))[0])},async delete(a){let{model:i,where:s}=a,e=h(i,{schema:l,usePlural:r.usePlural}),n=m(s,e);return(await t.delete(e).where(...n))[0]},async deleteMany(a){let{model:i,where:s}=a,e=h(i,{schema:l,usePlural:r.usePlural}),n=m(s,e);await t.delete(e).where(...n)},options:r}};export{B as drizzleAdapter};
|
package/dist/adapters/kysely.cjs
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
"use strict";var A=Object.defineProperty;var
|
|
1
|
+
"use strict";var A=Object.defineProperty;var g=Object.getOwnPropertyDescriptor;var q=Object.getOwnPropertyNames;var x=Object.prototype.hasOwnProperty;var F=(t,e)=>{for(var a in e)A(t,a,{get:e[a],enumerable:!0})},T=(t,e,a,n)=>{if(e&&typeof e=="object"||typeof e=="function")for(let s of q(e))!x.call(t,s)&&s!==a&&A(t,s,{get:()=>e[s],enumerable:!(n=g(e,s))||n.enumerable});return t};var K=t=>T(A({},"__esModule",{value:!0}),t);var O={};F(O,{createKyselyAdapter:()=>C,kyselyAdapter:()=>I});module.exports=K(O);var p=require("kysely"),d=require("kysely");function D(t){if("dialect"in t)return D(t.dialect);if("createDriver"in t){if(t instanceof d.SqliteDialect)return"sqlite";if(t instanceof d.MysqlDialect)return"mysql";if(t instanceof d.PostgresDialect)return"postgres";if(t instanceof p.MssqlDialect)return"mssql"}return"aggregate"in t?"sqlite":"getConnection"in t?"mysql":"connect"in t?"postgres":null}var C=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.Kysely({dialect:e.dialect}),databaseType:e.type};let a,n=D(e);return"createDriver"in e&&(a=e),"aggregate"in e&&(a=new d.SqliteDialect({database:e})),"getConnection"in e&&(a=new d.MysqlDialect({pool:e})),"connect"in e&&(a=new d.PostgresDialect({pool:e})),{kysely:a?new p.Kysely({dialect:a}):null,databaseType:n}};function h(t){if(!t)return{and:null,or:null};let e={and:[],or:[]};return t.forEach(a=>{let{field:n,value:s,operator:f="=",connector:l="AND"}=a,i=r=>f.toLowerCase()==="in"?r(n,"in",Array.isArray(s)?s:[s]):f==="contains"?r(n,"like",`%${s}%`):f==="starts_with"?r(n,"like",`${s}%`):f==="ends_with"?r(n,"like",`%${s}`):r(n,f,s);l==="OR"?e.or.push(i):e.and.push(i)}),{and:e.and.length?e.and:null,or:e.or.length?e.or:null}}function w(t,e,a){for(let n in t)t[n]===0&&e[n]?.type==="boolean"&&a?.boolean&&(t[n]=!1),t[n]===1&&e[n]?.type==="boolean"&&a?.boolean&&(t[n]=!0),e[n]?.type==="date"&&(t[n]instanceof Date||(t[n]=new Date(t[n])));return t}function k(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 I=(t,e)=>({id:"kysely",async create(a){let{model:n,data:s,select:f}=a;e?.transform&&(s=k(s,e.transform)),e?.generateId!==void 0&&(s.id=e.generateId?e.generateId():void 0);let l=await t.insertInto(n).values(s).returningAll().executeTakeFirst();if(e?.transform){let i=e.transform.schema[n];l=i?w(s,i,e.transform):l}return f?.length&&(l=l?f.reduce((r,o)=>l?.[o]?{...r,[o]:l[o]}:r,{}):null),l},async findOne(a){let{model:n,where:s,select:f}=a,{and:l,or:i}=h(s),r=t.selectFrom(n).selectAll();l&&(r=r.where(y=>y.and(l.map(u=>u(y))))),i&&(r=r.where(y=>y.or(i.map(u=>u(y)))));let o=await r.executeTakeFirst();if(f?.length&&(o=o?f.reduce((u,c)=>o?.[c]?{...u,[c]:o[c]}:u,{}):null),e?.transform){let y=e.transform.schema[n];return o=o&&y?w(o,y,e.transform):o,o||null}return o||null},async findMany(a){let{model:n,where:s,limit:f,offset:l,sortBy:i}=a,r=t.selectFrom(n),{and:o,or:y}=h(s);o&&(r=r.where(c=>c.and(o.map(m=>m(c))))),y&&(r=r.where(c=>c.or(y.map(m=>m(c))))),r=r.limit(f||100),l&&(r=r.offset(l)),i&&(r=r.orderBy(i.field,i.direction));let u=await r.selectAll().execute();if(e?.transform){let c=e.transform.schema[n];return c?u.map(m=>w(m,c,e.transform)):u}return u},async update(a){let{model:n,where:s,update:f}=a,{and:l,or:i}=h(s);e?.transform&&(f=k(f,e.transform));let r=t.updateTable(n).set(f);l&&(r=r.where(y=>y.and(l.map(u=>u(y))))),i&&(r=r.where(y=>y.or(i.map(u=>u(y)))));let o=await r.returningAll().executeTakeFirst()||null;if(e?.transform){let y=e.transform.schema[n];return y?w(o,y,e.transform):o}return o},async delete(a){let{model:n,where:s}=a,{and:f,or:l}=h(s),i=t.deleteFrom(n);f&&(i=i.where(r=>r.and(f.map(o=>o(r))))),l&&(i=i.where(r=>r.or(l.map(o=>o(r))))),await i.execute()},async deleteMany(a){let{model:n,where:s}=a,{and:f,or:l}=h(s),i=t.deleteFrom(n);f&&(i=i.where(r=>r.and(f.map(o=>o(r))))),l&&(i=i.where(r=>r.or(l.map(o=>o(r))))),await i.execute()}});0&&(module.exports={createKyselyAdapter,kyselyAdapter});
|
|
@@ -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-D7_h4yVD.cjs';
|
|
3
3
|
import 'zod';
|
|
4
4
|
import '../schema-Dkt0LqYs.cjs';
|
|
5
5
|
import 'better-call';
|
|
@@ -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-D1kVkHCi.js';
|
|
3
3
|
import 'zod';
|
|
4
4
|
import '../schema-Dkt0LqYs.js';
|
|
5
5
|
import 'better-call';
|
package/dist/adapters/kysely.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
import{Kysely as h,MssqlDialect as
|
|
1
|
+
import{Kysely as h,MssqlDialect as q}from"kysely";import{MysqlDialect as w,PostgresDialect as A,SqliteDialect as D}from"kysely";function k(r){if("dialect"in r)return k(r.dialect);if("createDriver"in r){if(r instanceof D)return"sqlite";if(r instanceof w)return"mysql";if(r instanceof A)return"postgres";if(r instanceof q)return"mssql"}return"aggregate"in r?"sqlite":"getConnection"in r?"mysql":"connect"in r?"postgres":null}var T=async r=>{let e=r.database;if("db"in e)return{kysely:e.db,databaseType:e.type};if("dialect"in e)return{kysely:new h({dialect:e.dialect}),databaseType:e.type};let a,n=k(e);return"createDriver"in e&&(a=e),"aggregate"in e&&(a=new D({database:e})),"getConnection"in e&&(a=new w({pool:e})),"connect"in e&&(a=new A({pool:e})),{kysely:a?new h({dialect:a}):null,databaseType:n}};function m(r){if(!r)return{and:null,or:null};let e={and:[],or:[]};return r.forEach(a=>{let{field:n,value:l,operator:f="=",connector:i="AND"}=a,o=t=>f.toLowerCase()==="in"?t(n,"in",Array.isArray(l)?l:[l]):f==="contains"?t(n,"like",`%${l}%`):f==="starts_with"?t(n,"like",`${l}%`):f==="ends_with"?t(n,"like",`%${l}`):t(n,f,l);i==="OR"?e.or.push(o):e.and.push(o)}),{and:e.and.length?e.and:null,or:e.or.length?e.or:null}}function p(r,e,a){for(let n in r)r[n]===0&&e[n]?.type==="boolean"&&a?.boolean&&(r[n]=!1),r[n]===1&&e[n]?.type==="boolean"&&a?.boolean&&(r[n]=!0),e[n]?.type==="date"&&(r[n]instanceof Date||(r[n]=new Date(r[n])));return r}function g(r,e){for(let a in r)typeof r[a]=="boolean"&&e?.boolean&&(r[a]=r[a]?1:0),r[a]instanceof Date&&(r[a]=r[a].toISOString());return r}var C=(r,e)=>({id:"kysely",async create(a){let{model:n,data:l,select:f}=a;e?.transform&&(l=g(l,e.transform)),e?.generateId!==void 0&&(l.id=e.generateId?e.generateId():void 0);let i=await r.insertInto(n).values(l).returningAll().executeTakeFirst();if(e?.transform){let o=e.transform.schema[n];i=o?p(l,o,e.transform):i}return f?.length&&(i=i?f.reduce((t,s)=>i?.[s]?{...t,[s]:i[s]}:t,{}):null),i},async findOne(a){let{model:n,where:l,select:f}=a,{and:i,or:o}=m(l),t=r.selectFrom(n).selectAll();i&&(t=t.where(y=>y.and(i.map(u=>u(y))))),o&&(t=t.where(y=>y.or(o.map(u=>u(y)))));let s=await t.executeTakeFirst();if(f?.length&&(s=s?f.reduce((u,c)=>s?.[c]?{...u,[c]:s[c]}:u,{}):null),e?.transform){let y=e.transform.schema[n];return s=s&&y?p(s,y,e.transform):s,s||null}return s||null},async findMany(a){let{model:n,where:l,limit:f,offset:i,sortBy:o}=a,t=r.selectFrom(n),{and:s,or:y}=m(l);s&&(t=t.where(c=>c.and(s.map(d=>d(c))))),y&&(t=t.where(c=>c.or(y.map(d=>d(c))))),t=t.limit(f||100),i&&(t=t.offset(i)),o&&(t=t.orderBy(o.field,o.direction));let u=await t.selectAll().execute();if(e?.transform){let c=e.transform.schema[n];return c?u.map(d=>p(d,c,e.transform)):u}return u},async update(a){let{model:n,where:l,update:f}=a,{and:i,or:o}=m(l);e?.transform&&(f=g(f,e.transform));let t=r.updateTable(n).set(f);i&&(t=t.where(y=>y.and(i.map(u=>u(y))))),o&&(t=t.where(y=>y.or(o.map(u=>u(y)))));let s=await t.returningAll().executeTakeFirst()||null;if(e?.transform){let y=e.transform.schema[n];return y?p(s,y,e.transform):s}return s},async delete(a){let{model:n,where:l}=a,{and:f,or:i}=m(l),o=r.deleteFrom(n);f&&(o=o.where(t=>t.and(f.map(s=>s(t))))),i&&(o=o.where(t=>t.or(i.map(s=>s(t))))),await o.execute()},async deleteMany(a){let{model:n,where:l}=a,{and:f,or:i}=m(l),o=r.deleteFrom(n);f&&(o=o.where(t=>t.and(f.map(s=>s(t))))),i&&(o=o.where(t=>t.or(i.map(s=>s(t))))),await o.execute()}});export{T as createKyselyAdapter,C as kyselyAdapter};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
"use strict";var
|
|
1
|
+
"use strict";var w=Object.defineProperty;var g=Object.getOwnPropertyDescriptor;var m=Object.getOwnPropertyNames;var p=Object.prototype.hasOwnProperty;var h=(a,s)=>{for(var o in s)w(a,o,{get:s[o],enumerable:!0})},y=(a,s,o,i)=>{if(s&&typeof s=="object"||typeof s=="function")for(let e of m(s))!p.call(a,e)&&e!==o&&w(a,e,{get:()=>s[e],enumerable:!(i=g(s,e))||i.enumerable});return a};var b=a=>y(w({},"__esModule",{value:!0}),a);var A={};h(A,{mongodbAdapter:()=>k});module.exports=b(A);function u(a){if(!a)return{};let s=a.map(r=>{let{field:t,value:n,operator:d="eq",connector:l="AND"}=r,c;switch(d.toLowerCase()){case"eq":c={[t]:n};break;case"in":c={[t]:{$in:Array.isArray(n)?n:[n]}};break;case"gt":c={[t]:{$gt:n}};break;case"gte":c={[t]:{$gte:n}};break;case"lt":c={[t]:{$lt:n}};break;case"lte":c={[t]:{$lte:n}};break;case"ne":c={[t]:{$ne:n}};break;case"contains":c={[t]:{$regex:`.*${n}.*`}};break;case"starts_with":c={[t]:{$regex:`${n}.*`}};break;case"ends_with":c={[t]:{$regex:`.*${n}`}};break;default:throw new Error(`Unsupported operator: ${d}`)}return{condition:c,connector:l}}),o=s.filter(r=>r.connector==="AND").map(r=>r.condition),i=s.filter(r=>r.connector==="OR").map(r=>r.condition),e={};return o.length&&(e={...e,$and:o}),i.length&&(e={...e,$or:i}),e}function f(a){let{_id:s,...o}=a;return o}function $(a){return a.reduce((o,i)=>(o[i]=1,o),{})}var k=(a,s)=>{let o=a,i=e=>s?.usePlural?`${e}s`:e;return{id:"mongodb",async create(e){let{model:r,data:t}=e;s?.generateId!==void 0&&(t.id=s.generateId?s.generateId():void 0);let d=(await o.collection(i(r)).insertOne({...t})).insertedId,l={...t,id:d};return f(l)},async findOne(e){let{model:r,where:t,select:n}=e,d=u(t),l={};n&&(l=$(n));let c=await o.collection(i(r)).findOne(d,{projection:l});return c?f(c):null},async findMany(e){let{model:r,where:t,limit:n,offset:d,sortBy:l}=e,c=u(t);return(await o.collection(i(r)).find(c).skip(d||0).limit(n||100).sort(l?.field||"id",l?.direction==="desc"?-1:1).toArray()).map(f)},async update(e){let{model:r,where:t,update:n}=e,d=u(t);if(t.length===1){let c=await o.collection(i(r)).findOneAndUpdate(d,{$set:n},{returnDocument:"after"});return f(c)}let l=await o.collection(i(r)).updateMany(d,{$set:n});return{}},async delete(e){let{model:r,where:t}=e,n=u(t),d=await o.collection(i(r)).findOneAndDelete(n)},async deleteMany(e){let{model:r,where:t}=e,n=u(t),d=await o.collection(i(r)).deleteMany(n)}}};0&&(module.exports={mongodbAdapter});
|
package/dist/adapters/mongodb.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
function u(l){if(!l)return{};let d=l.map(
|
|
1
|
+
function u(l){if(!l)return{};let d=l.map(n=>{let{field:e,value:t,operator:c="eq",connector:i="AND"}=n,o;switch(c.toLowerCase()){case"eq":o={[e]:t};break;case"in":o={[e]:{$in:Array.isArray(t)?t:[t]}};break;case"gt":o={[e]:{$gt:t}};break;case"gte":o={[e]:{$gte:t}};break;case"lt":o={[e]:{$lt:t}};break;case"lte":o={[e]:{$lte:t}};break;case"ne":o={[e]:{$ne:t}};break;case"contains":o={[e]:{$regex:`.*${t}.*`}};break;case"starts_with":o={[e]:{$regex:`${t}.*`}};break;case"ends_with":o={[e]:{$regex:`.*${t}`}};break;default:throw new Error(`Unsupported operator: ${c}`)}return{condition:o,connector:i}}),s=d.filter(n=>n.connector==="AND").map(n=>n.condition),a=d.filter(n=>n.connector==="OR").map(n=>n.condition),r={};return s.length&&(r={...r,$and:s}),a.length&&(r={...r,$or:a}),r}function f(l){let{_id:d,...s}=l;return s}function w(l){return l.reduce((s,a)=>(s[a]=1,s),{})}var m=(l,d)=>{let s=l,a=r=>d?.usePlural?`${r}s`:r;return{id:"mongodb",async create(r){let{model:n,data:e}=r;d?.generateId!==void 0&&(e.id=d.generateId?d.generateId():void 0);let c=(await s.collection(a(n)).insertOne({...e})).insertedId,i={...e,id:c};return f(i)},async findOne(r){let{model:n,where:e,select:t}=r,c=u(e),i={};t&&(i=w(t));let o=await s.collection(a(n)).findOne(c,{projection:i});return o?f(o):null},async findMany(r){let{model:n,where:e,limit:t,offset:c,sortBy:i}=r,o=u(e);return(await s.collection(a(n)).find(o).skip(c||0).limit(t||100).sort(i?.field||"id",i?.direction==="desc"?-1:1).toArray()).map(f)},async update(r){let{model:n,where:e,update:t}=r,c=u(e);if(e.length===1){let o=await s.collection(a(n)).findOneAndUpdate(c,{$set:t},{returnDocument:"after"});return f(o)}let i=await s.collection(a(n)).updateMany(c,{$set:t});return{}},async delete(r){let{model:n,where:e}=r,t=u(e),c=await s.collection(a(n)).findOneAndDelete(t)},async deleteMany(r){let{model:n,where:e}=r,t=u(e),c=await s.collection(a(n)).deleteMany(t)}}};export{m as mongodbAdapter};
|
package/dist/adapters/prisma.cjs
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
"use strict";var
|
|
1
|
+
"use strict";var f=Object.defineProperty;var h=Object.getOwnPropertyDescriptor;var p=Object.getOwnPropertyNames;var m=Object.prototype.hasOwnProperty;var w=(r,n)=>{for(var a in n)f(r,a,{get:n[a],enumerable:!0})},g=(r,n,a,o)=>{if(n&&typeof n=="object"||typeof n=="function")for(let t of p(n))!m.call(r,t)&&t!==a&&f(r,t,{get:()=>n[t],enumerable:!(o=h(n,t))||o.enumerable});return r};var C=r=>g(f({},"__esModule",{value:!0}),r);var P={};w(P,{prismaAdapter:()=>v});module.exports=C(P);function y(r){switch(r){case"starts_with":return"startsWith";case"ends_with":return"endsWith";default:return r}}function l(r){if(!r)return{};if(r.length===1){let e=r[0];return e?{[e.field]:e.operator==="eq"||!e.operator?e.value:{[y(e.operator)]:e.value}}:void 0}let n=r.filter(e=>e.connector==="AND"||!e.connector),a=r.filter(e=>e.connector==="OR"),o=n.map(e=>({[e.field]:e.operator==="eq"||!e.operator?e.value:{[y(e.operator)]:e.value}})),t=a.map(e=>({[e.field]:{[e.operator||"eq"]:e.value}}));return{AND:o.length?o:void 0,OR:t.length?t:void 0}}var v=(r,n)=>{let a=r,o=n.generateId;return{id:"prisma",async create(t){let{model:e,data:d,select:s}=t;return o!==void 0&&(d.id=o?o():void 0),await a[e].create({data:d,...s?.length?{select:s.reduce((i,c)=>({...i,[c]:!0}),{})}:{}})},async findOne(t){let{model:e,where:d,select:s}=t,i=l(d);return await a[e].findFirst({where:i,...s?.length?{select:s.reduce((c,u)=>({...c,[u]:!0}),{})}:{}})},async findMany(t){let{model:e,where:d,limit:s,offset:i,sortBy:c}=t,u=l(d);return await a[e].findMany({where:u,take:s||100,skip:i||0,orderBy:c?.field?{[c.field]:c.direction==="desc"?"desc":"asc"}:void 0})},async update(t){let{model:e,where:d,update:s}=t,i=l(d);return d.length===1?await a[e].update({where:i,data:s}):await a[e].updateMany({where:i,data:s})},async delete(t){let{model:e,where:d}=t,s=l(d);return await a[e].delete({where:s})},async deleteMany(t){let{model:e,where:d}=t,s=l(d);return await a[e].deleteMany({where:s})},options:n}};0&&(module.exports={prismaAdapter});
|
package/dist/adapters/prisma.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
function
|
|
1
|
+
function f(a){switch(a){case"starts_with":return"startsWith";case"ends_with":return"endsWith";default:return a}}function c(a){if(!a)return{};if(a.length===1){let e=a[0];return e?{[e.field]:e.operator==="eq"||!e.operator?e.value:{[f(e.operator)]:e.value}}:void 0}let l=a.filter(e=>e.connector==="AND"||!e.connector),s=a.filter(e=>e.connector==="OR"),i=l.map(e=>({[e.field]:e.operator==="eq"||!e.operator?e.value:{[f(e.operator)]:e.value}})),t=s.map(e=>({[e.field]:{[e.operator||"eq"]:e.value}}));return{AND:i.length?i:void 0,OR:t.length?t:void 0}}var y=(a,l)=>{let s=a,i=l.generateId;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 s[e].create({data:n,...r?.length?{select:r.reduce((d,o)=>({...d,[o]:!0}),{})}:{}})},async findOne(t){let{model:e,where:n,select:r}=t,d=c(n);return await s[e].findFirst({where:d,...r?.length?{select:r.reduce((o,u)=>({...o,[u]:!0}),{})}:{}})},async findMany(t){let{model:e,where:n,limit:r,offset:d,sortBy:o}=t,u=c(n);return await s[e].findMany({where:u,take:r||100,skip:d||0,orderBy:o?.field?{[o.field]:o.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 s[e].update({where:d,data:r}):await s[e].updateMany({where:d,data:r})},async delete(t){let{model:e,where:n}=t,r=c(n);return await s[e].delete({where:r})},async deleteMany(t){let{model:e,where:n}=t,r=c(n);return await s[e].deleteMany({where:r})},options:l}};export{y as prismaAdapter};
|
package/dist/api.cjs
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
"use strict";var te=Object.defineProperty;var Tt=Object.getOwnPropertyDescriptor;var vt=Object.getOwnPropertyNames;var xt=Object.prototype.hasOwnProperty;var Pt=(e,t)=>{for(var r in t)te(e,r,{get:t[r],enumerable:!0})},_t=(e,t,r,o)=>{if(t&&typeof t=="object"||typeof t=="function")for(let n of vt(t))!xt.call(e,n)&&n!==r&&te(e,n,{get:()=>t[n],enumerable:!(o=Tt(t,n))||o.enumerable});return e};var St=e=>_t(te({},"__esModule",{value:!0}),e);var Jt={};Pt(Jt,{APIError:()=>Et.APIError,callbackOAuth:()=>Ae,changeEmail:()=>_e,changePassword:()=>ve,createAuthEndpoint:()=>p,createAuthMiddleware:()=>$,createEmailVerificationToken:()=>O,csrfMiddleware:()=>se,deleteUser:()=>Pe,error:()=>Le,forgetPassword:()=>Re,forgetPasswordCallback:()=>Ue,getCSRFToken:()=>Se,getEndpoints:()=>Ut,getSession:()=>X,getSessionFromCtx:()=>Y,listSessions:()=>me,ok:()=>Oe,optionsMiddleware:()=>ne,resetPassword:()=>Ee,revokeSession:()=>fe,revokeSessions:()=>ge,router:()=>Wt,sendVerificationEmail:()=>he,sessionMiddleware:()=>L,setPassword:()=>xe,signInEmail:()=>be,signInOAuth:()=>ye,signOut:()=>ke,signUpEmail:()=>Ie,updateUser:()=>Te,verifyEmail:()=>we});module.exports=St(Jt);var N=require("better-call");var J=require("better-call"),ie=require("zod");var Bt=require("@noble/ciphers/chacha"),oe=require("@noble/ciphers/utils"),Dt=require("@noble/ciphers/webcrypto"),$t=require("oslo/crypto");function re(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}var Ce=require("oslo/encoding");var Lt=require("@noble/hashes/scrypt");function Ot(e){return e.toString(2).padStart(8,"0")}function It(e){return[...e].map(t=>Ot(t)).join("")}function Be(e){return parseInt(It(e),2)}function Ct(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=Be(o);for(;n>=e;)crypto.getRandomValues(o),r!==0&&(o[0]&=(1<<r)-1),n=Be(o);return n}function De(e,t){let r="";for(let o=0;o<e;o++)r+=t[Ct(t.length)];return r}function $e(...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 W(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)))}var D=require("better-call"),ne=(0,D.createMiddleware)(async()=>({})),$=(0,D.createMiddlewareCreator)({use:[ne,(0,D.createMiddleware)(async()=>({}))]}),p=(0,D.createEndpointCreator)({use:[ne]});var se=$({body:ie.z.object({csrfToken:ie.z.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 J.APIError("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||!n||!i||n!==r)throw e.setCookie(e.context.authCookies.csrfToken.name,"",{maxAge:0}),new J.APIError("UNAUTHORIZED",{message:"Invalid CSRF Token"});let s=await W(e.context.secret,n);if(i!==s)throw e.setCookie(e.context.authCookies.csrfToken.name,"",{maxAge:0}),new J.APIError("UNAUTHORIZED",{message:"Invalid CSRF Token"})});var P=require("better-call"),ht=require("oslo/oauth2"),v=require("zod");var je=require("oslo/oauth2"),H=require("zod");var ae=require("oslo/crypto");async function Ve(e){let t=await(0,ae.sha256)(typeof e=="string"?new TextEncoder().encode(e):e);return Buffer.from(t).toString("base64")}async function ze(e,t){let r=await(0,ae.sha256)(typeof e=="string"?new TextEncoder().encode(e):e),o=Buffer.from(t,"base64");return re(r,o)}var gr=require("better-call");async function qe(e){let t=(0,je.generateState)(),r=JSON.stringify({code:t,callbackURL:e}),o=await Ve(r);return{raw:r,hash:o}}function ce(e){return H.z.object({code:H.z.string(),callbackURL:H.z.string().optional(),currentURL:H.z.string().optional()}).safeParse(JSON.parse(e))}var Vt=require("oslo");var V=class extends Error{constructor(t,r){super(t),this.name="BetterAuthError",this.message=t,this.cause=r,this.stack=""}};async function S(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 Q(e){e.setCookie(e.context.authCookies.sessionToken.name,"",{maxAge:0}),e.setCookie(e.context.authCookies.dontRememberToken.name,"",{maxAge:0})}var de=require("better-call");var Ne=require("consola"),z=(0,Ne.createConsola)({formatOptions:{date:!1,colors:!0,compact:!0},defaults:{tag:"Better Auth"}}),zt=e=>({log:(...t)=>{!e?.disabled&&z.log("",...t)},error:(...t)=>{!e?.disabled&&z.error("",...t)},warn:(...t)=>{!e?.disabled&&z.warn("",...t)},info:(...t)=>{!e?.disabled&&z.info("",...t)},debug:(...t)=>{!e?.disabled&&z.debug("",...t)},box:(...t)=>{!e?.disabled&&z.box("",...t)},success:(...t)=>{!e?.disabled&&z.success("",...t)},break:(...t)=>{!e?.disabled&&console.log(`
|
|
2
|
-
`)}}),h=zt();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 h.error("Invalid callback URL",{callbackURL:t,trustedOrigins:n}),new de.APIError("FORBIDDEN",{message:"Invalid callback URL"})}if(o!==e.context.baseURL){let i=new URL(o).origin;if(!n.includes(i))throw h.error("Invalid current URL",{currentURL:o,trustedOrigins:n}),new de.APIError("FORBIDDEN",{message:"Invalid callback URL"})}});var Ze=require("oslo/jwt");var Me=require("oslo/crypto");var Fe=require("oslo/encoding");async function He(e){let t=await(0,Me.sha256)(new TextEncoder().encode(e));return Fe.base64url.encode(new Uint8Array(t),{includePadding:!1})}function Qe(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 E({id:e,options:t,authorizationEndpoint:r,state:o,codeVerifier:n,scopes:i,claims:s,disablePkce:d,redirectURI:c}){let a=new URL(r);if(a.searchParams.set("response_type","code"),a.searchParams.set("client_id",t.clientId),a.searchParams.set("state",o),a.searchParams.set("scope",i.join(" ")),a.searchParams.set("redirect_uri",t.redirectURI||c),!d&&n){let l=await He(n);a.searchParams.set("code_challenge_method","S256"),a.searchParams.set("code_challenge",l)}if(s){let l=s.reduce((w,g)=>(w[g]=null,w),{});a.searchParams.set("claims",JSON.stringify({id_token:{email:null,email_verified:null,...l}}))}return a}var Ge=require("@better-fetch/fetch");async function y({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(0,Ge.betterFetch)(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 Qe(s)}function le(e){let t=e.accessToken,r=e.refreshToken,o;try{o=e.accessTokenExpiresAt}catch{}return{accessToken:t,refreshToken:r,expiresAt:o}}var We=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})=>y({code:r,codeVerifier:o,redirectURI:e.redirectURI||n,options:e,tokenEndpoint:t}),async getUserInfo(r){if(!r.idToken)return null;let o=(0,Ze.parseJWT)(r.idToken)?.payload;return o?{user:{id:o.sub,name:o.name,email:o.email,emailVerified:o.email_verified==="true"},data:o}:null}}};var Je=require("@better-fetch/fetch");var Ke=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})=>y({code:t,redirectURI:e.redirectURI||r,options:e,tokenEndpoint:"https://discord.com/api/oauth2/token"}),async getUserInfo(t){let{data:r,error:o}=await(0,Je.betterFetch)("https://discord.com/api/users/@me",{headers:{authorization:`Bearer ${t.accessToken}`}});if(o)return null;if(r.avatar===null){let n=r.discriminator==="0"?Number(BigInt(r.id)>>BigInt(22))%6:parseInt(r.discriminator)%5;r.image_url=`https://cdn.discordapp.com/embed/avatars/${n}.png`}else{let n=r.avatar.startsWith("a_")?"gif":"png";r.image_url=`https://cdn.discordapp.com/avatars/${r.id}/${r.avatar}.${n}`}return{user:{id:r.id,name:r.display_name||r.username||"",email:r.email,emailVerified:r.verified,image:r.image_url},data:r}}});var Xe=require("@better-fetch/fetch");var Ye=e=>({id:"facebook",name:"Facebook",async createAuthorizationURL({state:t,scopes:r,redirectURI:o}){let n=e.scope||r||["email","public_profile"];return await E({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})=>y({code:t,redirectURI:e.redirectURI||r,options:e,tokenEndpoint:"https://graph.facebook.com/oauth/access_token"}),async getUserInfo(t){let{data:r,error:o}=await(0,Xe.betterFetch)("https://graph.facebook.com/me?fields=id,name,email,picture",{auth:{type:"Bearer",token:t.accessToken}});return o?null:{user:{id:r.id,name:r.name,email:r.email,emailVerified:r.email_verified},data:r}}});var ue=require("@better-fetch/fetch");var et=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 E({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})=>y({code:r,redirectURI:e.redirectURI||o,options:e,tokenEndpoint:t}),async getUserInfo(r){let{data:o,error:n}=await(0,ue.betterFetch)("https://api.github.com/user",{headers:{"User-Agent":"better-auth",authorization:`Bearer ${r.accessToken}`}});if(n)return null;let i=!1;if(!o.email){let{data:s,error:d}=await(0,ue.betterFetch)("https://api.github.com/user/emails",{headers:{authorization:`Bearer ${r.accessToken}`,"User-Agent":"better-auth"}});d||(o.email=(s.find(c=>c.primary)??s[0])?.email,i=s.find(c=>c.email===o.email)?.verified??!1)}return{user:{id:o.id.toString(),name:o.name||o.login,email:o.email,image:o.avatar_url,emailVerified:i},data:o}}}};var tt=require("oslo/jwt");var rt=e=>({id:"google",name:"Google",createAuthorizationURL({state:t,scopes:r,codeVerifier:o,redirectURI:n}){if(!e.clientId||!e.clientSecret)throw h.error("Client Id and Client Secret is required for Google. Make sure to provide them in the options."),new V("CLIENT_ID_AND_SECRET_REQUIRED");if(!o)throw new V("codeVerifier is required for Google");let i=e.scope||r||["email","profile"];return E({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})=>y({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=(0,tt.parseJWT)(t.idToken)?.payload;return{user:{id:r.sub,name:r.name,email:r.email,image:r.picture,emailVerified:r.email_verified},data:r}}});var ot=require("@better-fetch/fetch"),nt=require("oslo/jwt");var it=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 E({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 y({code:n,codeVerifier:i,redirectURI:e.redirectURI||s,options:e,tokenEndpoint:o})},async getUserInfo(n){if(!n.idToken)return null;let i=(0,nt.parseJWT)(n.idToken)?.payload,s=e.profilePhotoSize||48;return await(0,ot.betterFetch)(`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 a=await d.response.clone().arrayBuffer(),l=Buffer.from(a).toString("base64");i.picture=`data:image/jpeg;base64, ${l}`}catch(c){h.error(c)}}}),{user:{id:i.sub,name:i.name,email:i.email,image:i.picture,emailVerified:!0},data:i}}}};var st=require("@better-fetch/fetch");var at=e=>({id:"spotify",name:"Spotify",createAuthorizationURL({state:t,scopes:r,codeVerifier:o,redirectURI:n}){let i=e.scope||r||["user-read-email"];return E({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})=>y({code:t,codeVerifier:r,redirectURI:e.redirectURI||o,options:e,tokenEndpoint:"https://accounts.spotify.com/api/token"}),async getUserInfo(t){let{data:r,error:o}=await(0,st.betterFetch)("https://api.spotify.com/v1/me",{method:"GET",headers:{Authorization:`Bearer ${t.accessToken}`}});return o?null:{user:{id:r.id,name:r.display_name,email:r.email,image:r.images[0]?.url,emailVerified:!1},data:r}}});var bo=require("@better-fetch/fetch");var I={isAction:!1};var ct=require("nanoid"),dt=e=>(0,ct.nanoid)(e);var lt=require("oslo/jwt");var ut=e=>({id:"twitch",name:"Twitch",createAuthorizationURL({state:t,scopes:r,redirectURI:o}){let n=e.scope||r||["user:read:email","openid"];return E({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})=>y({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 h.error("No idToken found in token"),null;let o=(0,lt.parseJWT)(r)?.payload;return{user:{id:o.sub,name:o.preferred_username,email:o.email,image:o.picture,emailVerified:!1},data:o}}});var pt=require("@better-fetch/fetch");var mt=e=>({id:"twitter",name:"Twitter",createAuthorizationURL(t){let r=e.scope||t.scopes||["account_info.read"];return E({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})=>y({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(0,pt.betterFetch)("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 jt={apple:We,discord:Ke,facebook:Ye,github:et,microsoft:it,google:rt,spotify:at,twitch:ut,twitter:mt},ft=Object.keys(jt);var gt=require("oslo"),ee=require("oslo/jwt"),x=require("zod");var j=require("better-call");var M=require("better-call");var K=(e,t="ms")=>new Date(Date.now()+(t==="sec"?e*1e3:e));var pe=require("zod"),X=()=>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 Q(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 c=await e.context.internalAdapter.updateSession(r.session.id,{expiresAt:K(e.context.sessionConfig.expiresIn,"sec")});if(!c)return Q(e),e.json(null,{status:401});let a=(c.expiresAt.valueOf()-Date.now())/1e3;return await S(e,c.id,!1,{maxAge:a}),e.json({session:c,user:r.user})}return e.json(r)}catch(t){return e.context.logger.error(t),e.json(null,{status:500})}}),Y=async e=>await X()({...e,_flag:"json",headers:e.headers}),L=$(async e=>{let t=await Y(e);if(!t?.session)throw new M.APIError("UNAUTHORIZED");return{session:t}}),me=()=>p("/user/list-sessions",{method:"GET",use:[L],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)}),fe=p("/user/revoke-session",{method:"POST",body:pe.z.object({id:pe.z.string()}),use:[L],requireHeaders:!0},async e=>{let t=e.body.id,r=await e.context.internalAdapter.findSession(t);if(!r)throw new M.APIError("BAD_REQUEST",{message:"Session not found"});if(r.session.userId!==e.context.session.user.id)throw new M.APIError("UNAUTHORIZED");try{await e.context.internalAdapter.deleteSession(t)}catch(o){throw e.context.logger.error(o),new M.APIError("INTERNAL_SERVER_ERROR")}return e.json({status:!0})}),ge=p("/user/revoke-sessions",{method:"POST",use:[L],requireHeaders:!0},async e=>{try{await e.context.internalAdapter.deleteSessions(e.context.session.user.id)}catch(t){throw e.context.logger.error(t),new M.APIError("INTERNAL_SERVER_ERROR")}return e.json({status:!0})});async function O(e,t,r){return await(0,ee.createJWT)("HS256",Buffer.from(e),{email:t.toLowerCase(),updateTo:r},{expiresIn:new gt.TimeSpan(1,"h"),issuer:"better-auth",subject:"verify-email",audiences:[t],includeIssuedTimestamp:!0})}var he=p("/send-verification-email",{method:"POST",query:x.z.object({currentURL:x.z.string().optional()}).optional(),body:x.z.object({email:x.z.string().email(),callbackURL:x.z.string().optional()}),use:[U]},async e=>{if(!e.context.options.emailVerification?.sendVerificationEmail)throw e.context.logger.error("Verification email isn't enabled."),new j.APIError("BAD_REQUEST",{message:"Verification email isn't enabled"});let{email:t}=e.body,r=await e.context.internalAdapter.findUserByEmail(t);if(!r)throw new j.APIError("BAD_REQUEST",{message:"User not found"});let o=await O(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})}),we=p("/verify-email",{method:"GET",query:x.z.object({token:x.z.string(),callbackURL:x.z.string().optional()}),use:[U]},async e=>{let{token:t}=e.query,r;try{r=await(0,ee.validateJWT)("HS256",Buffer.from(e.context.secret),t)}catch(s){throw e.context.logger.error("Failed to verify email",s),new j.APIError("BAD_REQUEST",{message:"Invalid token"})}let n=x.z.object({email:x.z.string().email(),updateTo:x.z.string().optional()}).parse(r.payload);if(!await e.context.internalAdapter.findUserByEmail(n.email))throw new j.APIError("BAD_REQUEST",{message:"User not found"});if(n.updateTo){let s=await Y(e);if(!s)throw e.query.callbackURL?e.redirect(`${e.query.callbackURL}?error=unauthorized`):new j.APIError("UNAUTHORIZED",{message:"Session not found"});if(s.user.email!==n.email)throw e.query.callbackURL?e.redirect(`${e.query.callbackURL}?error=unauthorized`):new j.APIError("UNAUTHORIZED",{message:"Invalid session"});let d=await e.context.internalAdapter.updateUserByEmail(n.email,{email:n.updateTo});if(await e.context.options.emailVerification?.sendVerificationEmail?.(d,`${e.context.baseURL}/verify-email?token=${t}`,t),e.query.callbackURL)throw e.redirect(e.query.callbackURL);return e.json({user:d,status:!0})}if(await e.context.internalAdapter.updateUserByEmail(n.email,{emailVerified:!0}),e.query.callbackURL)throw e.redirect(e.query.callbackURL);return e.json({user:null,status:!0})});var ye=p("/sign-in/social",{method:"POST",requireHeaders:!0,query:v.z.object({currentURL:v.z.string().optional()}).optional(),body:v.z.object({callbackURL:v.z.string().optional(),provider:v.z.enum(ft)}),use:[U]},async e=>{let t=e.context.socialProviders.find(c=>c.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.APIError("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 qe(n||o?.origin||e.context.options.baseURL);await e.setSignedCookie(r.state.name,i.hash,e.context.secret,r.state.options);let s=(0,ht.generateCodeVerifier)();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})}),be=p("/sign-in/email",{method:"POST",body:v.z.object({email:v.z.string(),password:v.z.string(),callbackURL:v.z.string().optional(),dontRememberMe:v.z.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.APIError("BAD_REQUEST",{message:"Email and password is not enabled"});let{email:t,password:r}=e.body;if(!v.z.string().email().safeParse(t).success)throw new P.APIError("BAD_REQUEST",{message:"Invalid email"});if(!v.z.string().email().safeParse(t).success)throw new P.APIError("BAD_REQUEST",{message:"Invalid email"});let i=await e.context.internalAdapter.findUserByEmail(t,{includeAccounts:!0});if(!i)throw await e.context.password.hash(r),e.context.logger.error("User not found",{email:t}),new P.APIError("UNAUTHORIZED",{message:"Invalid email or password"});if(e.context.options?.emailAndPassword?.requireEmailVerification&&!i.user.emailVerified){if(!e.context.options?.emailVerification?.sendVerificationEmail)throw h.error("Email verification is required but no email verification handler is provided"),new P.APIError("INTERNAL_SERVER_ERROR",{message:"Email is not verified."});let l=await O(e.context.secret,i.user.email),w=`${e.context.options.baseURL}/verify-email?token=${l}`;throw await e.context.options.emailVerification.sendVerificationEmail(i.user,w,l),e.context.logger.error("Email not verified",{email:t}),new P.APIError("FORBIDDEN",{message:"Email is not verified. Check your email for a verification link"})}let s=i.accounts.find(l=>l.providerId==="credential");if(!s)throw e.context.logger.error("Credential account not found",{email:t}),new P.APIError("UNAUTHORIZED",{message:"Invalid email or password"});let d=s?.password;if(!d)throw e.context.logger.error("Password not found",{email:t}),new P.APIError("UNAUTHORIZED",{message:"Unexpected error"});if(!await e.context.password.verify(d,r))throw e.context.logger.error("Invalid password"),new P.APIError("UNAUTHORIZED",{message:"Invalid email or password"});let a=await e.context.internalAdapter.createSession(i.user.id,e.headers,e.body.dontRememberMe);if(!a)throw e.context.logger.error("Failed to create session"),new P.APIError("UNAUTHORIZED",{message:"Failed to create session"});return await S(e,a.id,e.body.dontRememberMe),e.json({user:i.user,session:a,redirect:!!e.body.callbackURL,url:e.body.callbackURL})});var G=require("zod");var f=require("zod"),dn=f.z.object({id:f.z.string(),providerId:f.z.string(),accountId:f.z.string(),userId:f.z.string(),accessToken:f.z.string().nullable().optional(),refreshToken:f.z.string().nullable().optional(),idToken:f.z.string().nullable().optional(),expiresAt:f.z.date().nullable().optional(),password:f.z.string().optional().nullable()}),wt=f.z.object({id:f.z.string(),email:f.z.string().transform(e=>e.toLowerCase()),emailVerified:f.z.boolean().default(!1),name:f.z.string(),image:f.z.string().optional(),createdAt:f.z.date().default(new Date),updatedAt:f.z.date().default(new Date)}),ln=f.z.object({id:f.z.string(),userId:f.z.string(),expiresAt:f.z.date(),ipAddress:f.z.string().optional(),userAgent:f.z.string().optional()}),un=f.z.object({id:f.z.string(),value:f.z.string(),expiresAt:f.z.date(),identifier:f.z.string()});function qt(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 yt(e,t){let r={...e.user?.additionalFields};return qt(t||{},{fields:r})}var Ae=p("/callback/:id",{method:"GET",query:G.z.object({state:G.z.string(),code:G.z.string().optional(),error:G.z.string().optional()}),metadata:I},async e=>{if(e.query.error||!e.query.code){let R=ce(e.query.state).data?.callbackURL||`${e.context.baseURL}/error`;throw e.context.logger.error(e.query.error,e.params.id),e.redirect(`${R}?error=${e.query.error||"oAuth_code_missing"}`)}let t=e.context.socialProviders.find(m=>m.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=ce(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 h.error("No stored state found"),e.redirect(`${e.context.baseURL}/error?error=please_restart_the_process`);if(!await ze(e.query.state,i))throw h.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),c;try{c=await t.validateAuthorizationCode({code:e.query.code,codeVerifier:d,redirectURI:`${e.context.baseURL}/callback/${t.id}`})}catch(m){throw e.context.logger.error(m),e.redirect(`${e.context.baseURL}/error?error=please_restart_the_process`)}let a=await t.getUserInfo(c).then(m=>m?.user),l=dt(),w=wt.safeParse({...a,id:l});if(!a||w.success===!1)throw h.error("Unable to get user info",w.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`);function g(m){throw e.redirect(`${n||o||`${e.context.baseURL}/error`}?error=${m}`)}let u=await e.context.internalAdapter.findUserByEmail(a.email,{includeAccounts:!0}).catch(m=>{throw h.error(`Better auth was unable to query your database.
|
|
2
|
+
`)}}),h=zt();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 h.error("Invalid callback URL",{callbackURL:t,trustedOrigins:n}),new de.APIError("FORBIDDEN",{message:"Invalid callback URL"})}if(o!==e.context.baseURL){let i=new URL(o).origin;if(!n.includes(i))throw h.error("Invalid current URL",{currentURL:o,trustedOrigins:n}),new de.APIError("FORBIDDEN",{message:"Invalid callback URL"})}});var Ze=require("oslo/jwt");var Me=require("oslo/crypto");var Fe=require("oslo/encoding");async function He(e){let t=await(0,Me.sha256)(new TextEncoder().encode(e));return Fe.base64url.encode(new Uint8Array(t),{includePadding:!1})}function Qe(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 E({id:e,options:t,authorizationEndpoint:r,state:o,codeVerifier:n,scopes:i,claims:s,disablePkce:d,redirectURI:c}){let a=new URL(r);if(a.searchParams.set("response_type","code"),a.searchParams.set("client_id",t.clientId),a.searchParams.set("state",o),a.searchParams.set("scope",i.join(" ")),a.searchParams.set("redirect_uri",t.redirectURI||c),!d&&n){let l=await He(n);a.searchParams.set("code_challenge_method","S256"),a.searchParams.set("code_challenge",l)}if(s){let l=s.reduce((w,g)=>(w[g]=null,w),{});a.searchParams.set("claims",JSON.stringify({id_token:{email:null,email_verified:null,...l}}))}return a}var Ge=require("@better-fetch/fetch");async function y({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(0,Ge.betterFetch)(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 Qe(s)}function le(e){let t=e.accessToken,r=e.refreshToken,o;try{o=e.accessTokenExpiresAt}catch{}return{accessToken:t,refreshToken:r,expiresAt:o}}var We=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})=>y({code:r,codeVerifier:o,redirectURI:e.redirectURI||n,options:e,tokenEndpoint:t}),async getUserInfo(r){if(!r.idToken)return null;let o=(0,Ze.parseJWT)(r.idToken)?.payload;return o?{user:{id:o.sub,name:o.name,email:o.email,emailVerified:o.email_verified==="true"},data:o}:null}}};var Je=require("@better-fetch/fetch");var Ke=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})=>y({code:t,redirectURI:e.redirectURI||r,options:e,tokenEndpoint:"https://discord.com/api/oauth2/token"}),async getUserInfo(t){let{data:r,error:o}=await(0,Je.betterFetch)("https://discord.com/api/users/@me",{headers:{authorization:`Bearer ${t.accessToken}`}});if(o)return null;if(r.avatar===null){let n=r.discriminator==="0"?Number(BigInt(r.id)>>BigInt(22))%6:parseInt(r.discriminator)%5;r.image_url=`https://cdn.discordapp.com/embed/avatars/${n}.png`}else{let n=r.avatar.startsWith("a_")?"gif":"png";r.image_url=`https://cdn.discordapp.com/avatars/${r.id}/${r.avatar}.${n}`}return{user:{id:r.id,name:r.display_name||r.username||"",email:r.email,emailVerified:r.verified,image:r.image_url},data:r}}});var Xe=require("@better-fetch/fetch");var Ye=e=>({id:"facebook",name:"Facebook",async createAuthorizationURL({state:t,scopes:r,redirectURI:o}){let n=e.scope||r||["email","public_profile"];return await E({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})=>y({code:t,redirectURI:e.redirectURI||r,options:e,tokenEndpoint:"https://graph.facebook.com/oauth/access_token"}),async getUserInfo(t){let{data:r,error:o}=await(0,Xe.betterFetch)("https://graph.facebook.com/me?fields=id,name,email,picture",{auth:{type:"Bearer",token:t.accessToken}});return o?null:{user:{id:r.id,name:r.name,email:r.email,emailVerified:r.email_verified},data:r}}});var ue=require("@better-fetch/fetch");var et=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 E({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})=>y({code:r,redirectURI:e.redirectURI||o,options:e,tokenEndpoint:t}),async getUserInfo(r){let{data:o,error:n}=await(0,ue.betterFetch)("https://api.github.com/user",{headers:{"User-Agent":"better-auth",authorization:`Bearer ${r.accessToken}`}});if(n)return null;let i=!1;if(!o.email){let{data:s,error:d}=await(0,ue.betterFetch)("https://api.github.com/user/emails",{headers:{authorization:`Bearer ${r.accessToken}`,"User-Agent":"better-auth"}});d||(o.email=(s.find(c=>c.primary)??s[0])?.email,i=s.find(c=>c.email===o.email)?.verified??!1)}return{user:{id:o.id.toString(),name:o.name||o.login,email:o.email,image:o.avatar_url,emailVerified:i},data:o}}}};var tt=require("oslo/jwt");var rt=e=>({id:"google",name:"Google",createAuthorizationURL({state:t,scopes:r,codeVerifier:o,redirectURI:n}){if(!e.clientId||!e.clientSecret)throw h.error("Client Id and Client Secret is required for Google. Make sure to provide them in the options."),new V("CLIENT_ID_AND_SECRET_REQUIRED");if(!o)throw new V("codeVerifier is required for Google");let i=e.scope||r||["email","profile"];return E({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})=>y({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=(0,tt.parseJWT)(t.idToken)?.payload;return{user:{id:r.sub,name:r.name,email:r.email,image:r.picture,emailVerified:r.email_verified},data:r}}});var ot=require("@better-fetch/fetch"),nt=require("oslo/jwt");var it=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 E({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 y({code:n,codeVerifier:i,redirectURI:e.redirectURI||s,options:e,tokenEndpoint:o})},async getUserInfo(n){if(!n.idToken)return null;let i=(0,nt.parseJWT)(n.idToken)?.payload,s=e.profilePhotoSize||48;return await(0,ot.betterFetch)(`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 a=await d.response.clone().arrayBuffer(),l=Buffer.from(a).toString("base64");i.picture=`data:image/jpeg;base64, ${l}`}catch(c){h.error(c)}}}),{user:{id:i.sub,name:i.name,email:i.email,image:i.picture,emailVerified:!0},data:i}}}};var st=require("@better-fetch/fetch");var at=e=>({id:"spotify",name:"Spotify",createAuthorizationURL({state:t,scopes:r,codeVerifier:o,redirectURI:n}){let i=e.scope||r||["user-read-email"];return E({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})=>y({code:t,codeVerifier:r,redirectURI:e.redirectURI||o,options:e,tokenEndpoint:"https://accounts.spotify.com/api/token"}),async getUserInfo(t){let{data:r,error:o}=await(0,st.betterFetch)("https://api.spotify.com/v1/me",{method:"GET",headers:{Authorization:`Bearer ${t.accessToken}`}});return o?null:{user:{id:r.id,name:r.display_name,email:r.email,image:r.images[0]?.url,emailVerified:!1},data:r}}});var bo=require("@better-fetch/fetch");var I={isAction:!1};var ct=require("nanoid"),dt=e=>(0,ct.nanoid)(e);var lt=require("oslo/jwt");var ut=e=>({id:"twitch",name:"Twitch",createAuthorizationURL({state:t,scopes:r,redirectURI:o}){let n=e.scope||r||["user:read:email","openid"];return E({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})=>y({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 h.error("No idToken found in token"),null;let o=(0,lt.parseJWT)(r)?.payload;return{user:{id:o.sub,name:o.preferred_username,email:o.email,image:o.picture,emailVerified:!1},data:o}}});var pt=require("@better-fetch/fetch");var mt=e=>({id:"twitter",name:"Twitter",createAuthorizationURL(t){let r=e.scope||t.scopes||["account_info.read"];return E({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})=>y({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(0,pt.betterFetch)("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 jt={apple:We,discord:Ke,facebook:Ye,github:et,microsoft:it,google:rt,spotify:at,twitch:ut,twitter:mt},ft=Object.keys(jt);var gt=require("oslo"),ee=require("oslo/jwt"),x=require("zod");var j=require("better-call");var M=require("better-call");var K=(e,t="ms")=>new Date(Date.now()+(t==="sec"?e*1e3:e));var pe=require("zod"),X=()=>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 Q(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 c=await e.context.internalAdapter.updateSession(r.session.id,{expiresAt:K(e.context.sessionConfig.expiresIn,"sec")});if(!c)return Q(e),e.json(null,{status:401});let a=(c.expiresAt.valueOf()-Date.now())/1e3;return await S(e,c.id,!1,{maxAge:a}),e.json({session:c,user:r.user})}return e.json(r)}catch(t){return e.context.logger.error(t),e.json(null,{status:500})}}),Y=async e=>await X()({...e,_flag:"json",headers:e.headers}),L=$(async e=>{let t=await Y(e);if(!t?.session)throw new M.APIError("UNAUTHORIZED");return{session:t}}),me=()=>p("/user/list-sessions",{method:"GET",use:[L],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)}),fe=p("/user/revoke-session",{method:"POST",body:pe.z.object({id:pe.z.string()}),use:[L],requireHeaders:!0},async e=>{let t=e.body.id,r=await e.context.internalAdapter.findSession(t);if(!r)throw new M.APIError("BAD_REQUEST",{message:"Session not found"});if(r.session.userId!==e.context.session.user.id)throw new M.APIError("UNAUTHORIZED");try{await e.context.internalAdapter.deleteSession(t)}catch(o){throw e.context.logger.error(o),new M.APIError("INTERNAL_SERVER_ERROR")}return e.json({status:!0})}),ge=p("/user/revoke-sessions",{method:"POST",use:[L],requireHeaders:!0},async e=>{try{await e.context.internalAdapter.deleteSessions(e.context.session.user.id)}catch(t){throw e.context.logger.error(t),new M.APIError("INTERNAL_SERVER_ERROR")}return e.json({status:!0})});async function O(e,t,r){return await(0,ee.createJWT)("HS256",Buffer.from(e),{email:t.toLowerCase(),updateTo:r},{expiresIn:new gt.TimeSpan(1,"h"),issuer:"better-auth",subject:"verify-email",audiences:[t],includeIssuedTimestamp:!0})}var he=p("/send-verification-email",{method:"POST",query:x.z.object({currentURL:x.z.string().optional()}).optional(),body:x.z.object({email:x.z.string().email(),callbackURL:x.z.string().optional()}),use:[U]},async e=>{if(!e.context.options.emailVerification?.sendVerificationEmail)throw e.context.logger.error("Verification email isn't enabled."),new j.APIError("BAD_REQUEST",{message:"Verification email isn't enabled"});let{email:t}=e.body,r=await e.context.internalAdapter.findUserByEmail(t);if(!r)throw new j.APIError("BAD_REQUEST",{message:"User not found"});let o=await O(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})}),we=p("/verify-email",{method:"GET",query:x.z.object({token:x.z.string(),callbackURL:x.z.string().optional()}),use:[U]},async e=>{let{token:t}=e.query,r;try{r=await(0,ee.validateJWT)("HS256",Buffer.from(e.context.secret),t)}catch(s){throw e.context.logger.error("Failed to verify email",s),new j.APIError("BAD_REQUEST",{message:"Invalid token"})}let n=x.z.object({email:x.z.string().email(),updateTo:x.z.string().optional()}).parse(r.payload);if(!await e.context.internalAdapter.findUserByEmail(n.email))throw new j.APIError("BAD_REQUEST",{message:"User not found"});if(n.updateTo){let s=await Y(e);if(!s)throw e.query.callbackURL?e.redirect(`${e.query.callbackURL}?error=unauthorized`):new j.APIError("UNAUTHORIZED",{message:"Session not found"});if(s.user.email!==n.email)throw e.query.callbackURL?e.redirect(`${e.query.callbackURL}?error=unauthorized`):new j.APIError("UNAUTHORIZED",{message:"Invalid session"});let d=await e.context.internalAdapter.updateUserByEmail(n.email,{email:n.updateTo});if(await e.context.options.emailVerification?.sendVerificationEmail?.(d,`${e.context.baseURL}/verify-email?token=${t}`,t),e.query.callbackURL)throw e.redirect(e.query.callbackURL);return e.json({user:d,status:!0})}if(await e.context.internalAdapter.updateUserByEmail(n.email,{emailVerified:!0}),e.query.callbackURL)throw e.redirect(e.query.callbackURL);return e.json({user:null,status:!0})});var ye=p("/sign-in/social",{method:"POST",requireHeaders:!0,query:v.z.object({currentURL:v.z.string().optional()}).optional(),body:v.z.object({callbackURL:v.z.string().optional(),provider:v.z.enum(ft)}),use:[U]},async e=>{let t=e.context.socialProviders.find(c=>c.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.APIError("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 qe(n||o?.origin||e.context.options.baseURL);await e.setSignedCookie(r.state.name,i.hash,e.context.secret,r.state.options);let s=(0,ht.generateCodeVerifier)();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})}),be=p("/sign-in/email",{method:"POST",body:v.z.object({email:v.z.string(),password:v.z.string(),callbackURL:v.z.string().optional(),dontRememberMe:v.z.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.APIError("BAD_REQUEST",{message:"Email and password is not enabled"});let{email:t,password:r}=e.body;if(!v.z.string().email().safeParse(t).success)throw new P.APIError("BAD_REQUEST",{message:"Invalid email"});if(!v.z.string().email().safeParse(t).success)throw new P.APIError("BAD_REQUEST",{message:"Invalid email"});let i=await e.context.internalAdapter.findUserByEmail(t,{includeAccounts:!0});if(!i)throw await e.context.password.hash(r),e.context.logger.error("User not found",{email:t}),new P.APIError("UNAUTHORIZED",{message:"Invalid email or password"});let s=i.accounts.find(l=>l.providerId==="credential");if(!s)throw e.context.logger.error("Credential account not found",{email:t}),new P.APIError("UNAUTHORIZED",{message:"Invalid email or password"});let d=s?.password;if(!d)throw e.context.logger.error("Password not found",{email:t}),new P.APIError("UNAUTHORIZED",{message:"Unexpected error"});if(!await e.context.password.verify(d,r))throw e.context.logger.error("Invalid password"),new P.APIError("UNAUTHORIZED",{message:"Invalid email or password"});if(e.context.options?.emailAndPassword?.requireEmailVerification&&!i.user.emailVerified){if(!e.context.options?.emailVerification?.sendVerificationEmail)throw h.error("Email verification is required but no email verification handler is provided"),new P.APIError("INTERNAL_SERVER_ERROR",{message:"Email is not verified."});let l=await O(e.context.secret,i.user.email),w=`${e.context.options.baseURL}/verify-email?token=${l}`;throw await e.context.options.emailVerification.sendVerificationEmail(i.user,w,l),e.context.logger.error("Email not verified",{email:t}),new P.APIError("FORBIDDEN",{message:"Email is not verified. Check your email for a verification link"})}let a=await e.context.internalAdapter.createSession(i.user.id,e.headers,e.body.dontRememberMe);if(!a)throw e.context.logger.error("Failed to create session"),new P.APIError("UNAUTHORIZED",{message:"Failed to create session"});return await S(e,a.id,e.body.dontRememberMe),e.json({user:i.user,session:a,redirect:!!e.body.callbackURL,url:e.body.callbackURL})});var G=require("zod");var f=require("zod"),dn=f.z.object({id:f.z.string(),providerId:f.z.string(),accountId:f.z.string(),userId:f.z.string(),accessToken:f.z.string().nullable().optional(),refreshToken:f.z.string().nullable().optional(),idToken:f.z.string().nullable().optional(),expiresAt:f.z.date().nullable().optional(),password:f.z.string().optional().nullable()}),wt=f.z.object({id:f.z.string(),email:f.z.string().transform(e=>e.toLowerCase()),emailVerified:f.z.boolean().default(!1),name:f.z.string(),image:f.z.string().optional(),createdAt:f.z.date().default(new Date),updatedAt:f.z.date().default(new Date)}),ln=f.z.object({id:f.z.string(),userId:f.z.string(),expiresAt:f.z.date(),ipAddress:f.z.string().optional(),userAgent:f.z.string().optional()}),un=f.z.object({id:f.z.string(),value:f.z.string(),expiresAt:f.z.date(),identifier:f.z.string()});function qt(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 yt(e,t){let r={...e.user?.additionalFields};return qt(t||{},{fields:r})}var Ae=p("/callback/:id",{method:"GET",query:G.z.object({state:G.z.string(),code:G.z.string().optional(),error:G.z.string().optional()}),metadata:I},async e=>{if(e.query.error||!e.query.code){let R=ce(e.query.state).data?.callbackURL||`${e.context.baseURL}/error`;throw e.context.logger.error(e.query.error,e.params.id),e.redirect(`${R}?error=${e.query.error||"oAuth_code_missing"}`)}let t=e.context.socialProviders.find(m=>m.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=ce(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 h.error("No stored state found"),e.redirect(`${e.context.baseURL}/error?error=please_restart_the_process`);if(!await ze(e.query.state,i))throw h.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),c;try{c=await t.validateAuthorizationCode({code:e.query.code,codeVerifier:d,redirectURI:`${e.context.baseURL}/callback/${t.id}`})}catch(m){throw e.context.logger.error(m),e.redirect(`${e.context.baseURL}/error?error=please_restart_the_process`)}let a=await t.getUserInfo(c).then(m=>m?.user),l=dt(),w=wt.safeParse({...a,id:l});if(!a||w.success===!1)throw h.error("Unable to get user info",w.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`);function g(m){throw e.redirect(`${n||o||`${e.context.baseURL}/error`}?error=${m}`)}let u=await e.context.internalAdapter.findUserByEmail(a.email,{includeAccounts:!0}).catch(m=>{throw h.error(`Better auth was unable to query your database.
|
|
3
3
|
Error: `,m),e.redirect(`${e.context.baseURL}/error?error=internal_server_error`)}),A=u?.user.id;if(u){if(!u.accounts.find(R=>R.providerId===t.id)){(!e.context.options.account?.accountLinking?.trustedProviders?.includes(t.id)&&!a.emailVerified||!e.context.options.account?.accountLinking?.enabled)&&g("account_not_linked");try{await e.context.internalAdapter.linkAccount({providerId:t.id,accountId:a.id.toString(),id:`${t.id}:${a.id}`,userId:u.user.id,...le(c)})}catch(B){h.error("Unable to link account",B),g("unable_to_link_account")}}}else try{let m=a.emailVerified||!1,R=await e.context.internalAdapter.createOAuthUser({...w.data,emailVerified:m},{...le(c),providerId:t.id,accountId:a.id.toString()});if(!m&&R&&e.context.options.emailVerification?.sendOnSignUp){let F=await O(e.context.secret,a.email),B=`${e.context.baseURL}/verify-email?token=${F}&callbackURL=${o}`;await e.context.options.emailVerification?.sendVerificationEmail?.(R.user,B,F)}}catch(m){h.error("Unable to create user",m),g("unable_to_create_user")}!A&&!l&&g("unable_to_create_user");let T=await e.context.internalAdapter.createSession(A||l,e.request);throw T||g("unable_to_create_session"),await S(e,T.id),e.redirect(o)});var En=require("zod");var bt=require("better-call");var ke=p("/sign-out",{method:"POST"},async e=>{let t=await e.getSignedCookie(e.context.authCookies.sessionToken.name,e.context.secret);if(!t)throw new bt.APIError("BAD_REQUEST",{message:"Session not found"});return await e.context.internalAdapter.deleteSession(t),Q(e),e.json({success:!0})});var _=require("zod");var Z=require("better-call");var Re=p("/forget-password",{method:"POST",body:_.z.object({email:_.z.string().email(),redirectTo:_.z.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.APIError("BAD_REQUEST",{message:"Reset password isn't enabled"});let{email:t,redirectTo:r}=e.body,o=await e.context.internalAdapter.findUserByEmail(t,{includeAccounts:!0});if(!o)return e.context.logger.error("Reset Password: User not found",{email:t}),e.json({status:!1},{body:{status:!0}});let n=60*60*1,i=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})}),Ue=p("/reset-password/:token",{method:"GET",query:_.z.object({callbackURL:_.z.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}`)}),Ee=p("/reset-password",{query:_.z.optional(_.z.object({token:_.z.string()})),method:"POST",body:_.z.object({newPassword:_.z.string()})},async e=>{let t=e.query?.token;if(!t)throw new Z.APIError("BAD_REQUEST",{message:"Token not found"});let{newPassword:r}=e.body,o=`reset-password:${t}`,n=await e.context.internalAdapter.findVerificationValue(o);if(!n||n.expiresAt<new Date)throw new Z.APIError("BAD_REQUEST",{message:"Invalid token"});await e.context.internalAdapter.deleteVerificationValue(n.id);let i=n.value,s=await e.context.password.hash(r);if(!(await e.context.internalAdapter.findAccounts(i)).find(l=>l.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.APIError("BAD_REQUEST",{message:"Failed to update password"});return e.json({status:!0})});var b=require("zod");var k=require("better-call");var Te=p("/user/update",{method:"POST",body:b.z.object({name:b.z.string().optional(),image:b.z.string().optional()}),use:[L,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})}),ve=p("/user/change-password",{method:"POST",body:b.z.object({newPassword:b.z.string(),currentPassword:b.z.string(),revokeOtherSessions:b.z.boolean().optional()}),use:[L]},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 k.APIError("BAD_REQUEST",{message:"Password is too short"});let s=e.context.password.config.maxPasswordLength;if(t.length>s)throw e.context.logger.error("Password is too long"),new k.APIError("BAD_REQUEST",{message:"Password too long"});let c=(await e.context.internalAdapter.findAccounts(n.user.id)).find(w=>w.providerId==="credential"&&w.password);if(!c||!c.password)throw new k.APIError("BAD_REQUEST",{message:"User does not have a password"});let a=await e.context.password.hash(t);if(!await e.context.password.verify(c.password,r))throw new k.APIError("BAD_REQUEST",{message:"Incorrect password"});if(await e.context.internalAdapter.updateAccount(c.id,{password:a}),o){await e.context.internalAdapter.deleteSessions(n.user.id);let w=await e.context.internalAdapter.createSession(n.user.id,e.headers);if(!w)throw new k.APIError("INTERNAL_SERVER_ERROR",{message:"Unable to create session"});await S(e,w.id)}return e.json(n.user)}),xe=p("/user/set-password",{method:"POST",body:b.z.object({newPassword:b.z.string()}),use:[L]},async e=>{let{newPassword:t}=e.body,r=e.context.session,o=e.context.password.config.minPasswordLength;if(t.length<o)throw e.context.logger.error("Password is too short"),new k.APIError("BAD_REQUEST",{message:"Password is too short"});let n=e.context.password.config.maxPasswordLength;if(t.length>n)throw e.context.logger.error("Password is too long"),new k.APIError("BAD_REQUEST",{message:"Password too long"});let s=(await e.context.internalAdapter.findAccounts(r.user.id)).find(c=>c.providerId==="credential"&&c.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 k.APIError("BAD_REQUEST",{message:"user already has a password"})}),Pe=p("/user/delete",{method:"POST",body:b.z.object({password:b.z.string()}),use:[L]},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 k.APIError("BAD_REQUEST",{message:"User does not have a password"});if(!await e.context.password.verify(n.password,t))throw new k.APIError("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)}),_e=p("/user/change-email",{method:"POST",query:b.z.object({currentURL:b.z.string().optional()}).optional(),body:b.z.object({newEmail:b.z.string().email(),callbackURL:b.z.string().optional()}),use:[L,U]},async e=>{if(!e.context.options.user?.changeEmail?.enabled)throw e.context.logger.error("Change email is disabled."),new k.APIError("BAD_REQUEST",{message:"Change email is disabled"});if(e.body.newEmail===e.context.session.user.email)throw e.context.logger.error("Email is the same"),new k.APIError("BAD_REQUEST",{message:"Email is the same"});if(await e.context.internalAdapter.findUserByEmail(e.body.newEmail))throw e.context.logger.error("Email already exists"),new k.APIError("BAD_REQUEST",{message:"Couldn't update your email"});if(e.context.session.user.emailVerified!==!0){let n=await e.context.internalAdapter.updateUserByEmail(e.context.session.user.email,{email:e.body.newEmail});return e.json({user:n,status:!0})}if(!e.context.options.emailVerification?.sendVerificationEmail)throw e.context.logger.error("Verification email isn't enabled."),new k.APIError("BAD_REQUEST",{message:"Verification email isn't enabled"});let r=await O(e.context.secret,e.context.session.user.email,e.body.newEmail),o=`${e.context.baseURL}/verify-email?token=${r}&callbackURL=${e.body.callbackURL||e.query?.currentURL||"/"}`;return await e.context.options.emailVerification.sendVerificationEmail(e.context.session.user,o,r),e.json({user:null,status:!0})});var Se=p("/csrf",{method:"GET",metadata:I},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=De(32,$e("a-z","0-9","A-Z")),o=await W(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 Nt=(e="Unknown")=>`<!DOCTYPE html>
|
|
4
4
|
<html lang="en">
|
|
5
5
|
<head>
|
package/dist/api.d.cts
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
export { e as AuthEndpoint, f as AuthMiddleware, a1 as callbackOAuth, aj as changeEmail, ag as changePassword, d as createAuthEndpoint, c as createAuthMiddleware, ac as createEmailVerificationToken, ao as csrfMiddleware, ai as deleteUser, al as error, a9 as forgetPassword, aa as forgetPasswordCallback, ak as getCSRFToken, Z as getEndpoints, a2 as getSession, a3 as getSessionFromCtx, a5 as listSessions, am as ok, o as optionsMiddleware, ab as resetPassword, a6 as revokeSession, a7 as revokeSessions, _ as router, ad as sendVerificationEmail, a4 as sessionMiddleware, ah as setPassword, a0 as signInEmail, $ as signInOAuth, a8 as signOut, an as signUpEmail, af as updateUser, ae as verifyEmail } from './auth-
|
|
1
|
+
export { e as AuthEndpoint, f as AuthMiddleware, a1 as callbackOAuth, aj as changeEmail, ag as changePassword, d as createAuthEndpoint, c as createAuthMiddleware, ac as createEmailVerificationToken, ao as csrfMiddleware, ai as deleteUser, al as error, a9 as forgetPassword, aa as forgetPasswordCallback, ak as getCSRFToken, Z as getEndpoints, a2 as getSession, a3 as getSessionFromCtx, a5 as listSessions, am as ok, o as optionsMiddleware, ab as resetPassword, a6 as revokeSession, a7 as revokeSessions, _ as router, ad as sendVerificationEmail, a4 as sessionMiddleware, ah as setPassword, a0 as signInEmail, $ as signInOAuth, a8 as signOut, an as signUpEmail, af as updateUser, ae as verifyEmail } from './auth-D7_h4yVD.cjs';
|
|
2
2
|
import './helper-DPDj8Nix.cjs';
|
|
3
3
|
export { APIError } from 'better-call';
|
|
4
4
|
import 'zod';
|
package/dist/api.d.ts
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
export { e as AuthEndpoint, f as AuthMiddleware, a1 as callbackOAuth, aj as changeEmail, ag as changePassword, d as createAuthEndpoint, c as createAuthMiddleware, ac as createEmailVerificationToken, ao as csrfMiddleware, ai as deleteUser, al as error, a9 as forgetPassword, aa as forgetPasswordCallback, ak as getCSRFToken, Z as getEndpoints, a2 as getSession, a3 as getSessionFromCtx, a5 as listSessions, am as ok, o as optionsMiddleware, ab as resetPassword, a6 as revokeSession, a7 as revokeSessions, _ as router, ad as sendVerificationEmail, a4 as sessionMiddleware, ah as setPassword, a0 as signInEmail, $ as signInOAuth, a8 as signOut, an as signUpEmail, af as updateUser, ae as verifyEmail } from './auth-
|
|
1
|
+
export { e as AuthEndpoint, f as AuthMiddleware, a1 as callbackOAuth, aj as changeEmail, ag as changePassword, d as createAuthEndpoint, c as createAuthMiddleware, ac as createEmailVerificationToken, ao as csrfMiddleware, ai as deleteUser, al as error, a9 as forgetPassword, aa as forgetPasswordCallback, ak as getCSRFToken, Z as getEndpoints, a2 as getSession, a3 as getSessionFromCtx, a5 as listSessions, am as ok, o as optionsMiddleware, ab as resetPassword, a6 as revokeSession, a7 as revokeSessions, _ as router, ad as sendVerificationEmail, a4 as sessionMiddleware, ah as setPassword, a0 as signInEmail, $ as signInOAuth, a8 as signOut, an as signUpEmail, af as updateUser, ae as verifyEmail } from './auth-D1kVkHCi.js';
|
|
2
2
|
import './helper-DPDj8Nix.js';
|
|
3
3
|
export { APIError } from 'better-call';
|
|
4
4
|
import 'zod';
|
package/dist/api.js
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
import{APIError as et,createRouter as Dt,statusCode as $t}from"better-call";import{APIError as J}from"better-call";import{z as se}from"zod";import{xchacha20poly1305 as Wt}from"@noble/ciphers/chacha";import{bytesToHex as Kt,hexToBytes as Xt,utf8ToBytes as Yt}from"@noble/ciphers/utils";import{managedNonce as tr}from"@noble/ciphers/webcrypto";import{sha256 as or}from"oslo/crypto";function W(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 qt,encodeHex as Nt}from"oslo/encoding";import{scryptAsync as Ht}from"@noble/hashes/scrypt";function tt(e){return e.toString(2).padStart(8,"0")}function rt(e){return[...e].map(t=>tt(t)).join("")}function te(e){return parseInt(rt(e),2)}function ot(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=te(o);for(;n>=e;)crypto.getRandomValues(o),r!==0&&(o[0]&=(1<<r)-1),n=te(o);return n}function re(e,t){let r="";for(let o=0;o<e;o++)r+=t[ot(t.length)];return r}function oe(...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 F(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 nt,createMiddleware as ne,createMiddlewareCreator as it}from"better-call";var ie=ne(async()=>({})),V=it({use:[ie,ne(async()=>({}))]}),m=nt({use:[ie]});var ae=V({body:se.object({csrfToken:se.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 J("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||!n||!i||n!==r)throw e.setCookie(e.context.authCookies.csrfToken.name,"",{maxAge:0}),new J("UNAUTHORIZED",{message:"Invalid CSRF Token"});let s=await F(e.context.secret,n);if(i!==s)throw e.setCookie(e.context.authCookies.csrfToken.name,"",{maxAge:0}),new J("UNAUTHORIZED",{message:"Invalid CSRF Token"})});import{APIError as P}from"better-call";import{generateCodeVerifier as vt}from"oslo/oauth2";import{z as v}from"zod";import{generateState as st}from"oslo/oauth2";import{z as H}from"zod";import{sha256 as ce}from"oslo/crypto";async function de(e){let t=await ce(typeof e=="string"?new TextEncoder().encode(e):e);return Buffer.from(t).toString("base64")}async function le(e,t){let r=await ce(typeof e=="string"?new TextEncoder().encode(e):e),o=Buffer.from(t,"base64");return W(r,o)}import"better-call";async function ue(e){let t=st(),r=JSON.stringify({code:t,callbackURL:e}),o=await de(r);return{raw:r,hash:o}}function K(e){return H.object({code:H.string(),callbackURL:H.string().optional(),currentURL:H.string().optional()}).safeParse(JSON.parse(e))}import{TimeSpan as Pr}from"oslo";var B=class extends Error{constructor(t,r){super(t),this.name="BetterAuthError",this.message=t,this.cause=r,this.stack=""}};async function _(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 N(e){e.setCookie(e.context.authCookies.sessionToken.name,"",{maxAge:0}),e.setCookie(e.context.authCookies.dontRememberToken.name,"",{maxAge:0})}import{APIError as pe}from"better-call";import{createConsola as at}from"consola";var D=at({formatOptions:{date:!1,colors:!0,compact:!0},defaults:{tag:"Better Auth"}}),ct=e=>({log:(...t)=>{!e?.disabled&&D.log("",...t)},error:(...t)=>{!e?.disabled&&D.error("",...t)},warn:(...t)=>{!e?.disabled&&D.warn("",...t)},info:(...t)=>{!e?.disabled&&D.info("",...t)},debug:(...t)=>{!e?.disabled&&D.debug("",...t)},box:(...t)=>{!e?.disabled&&D.box("",...t)},success:(...t)=>{!e?.disabled&&D.success("",...t)},break:(...t)=>{!e?.disabled&&console.log(`
|
|
2
|
-
`)}}),h=ct();var R=V(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 h.error("Invalid callback URL",{callbackURL:t,trustedOrigins:n}),new pe("FORBIDDEN",{message:"Invalid callback URL"})}if(o!==e.context.baseURL){let i=new URL(o).origin;if(!n.includes(i))throw h.error("Invalid current URL",{currentURL:o,trustedOrigins:n}),new pe("FORBIDDEN",{message:"Invalid callback URL"})}});import{parseJWT as pt}from"oslo/jwt";import{sha256 as dt}from"oslo/crypto";import{base64url as lt}from"oslo/encoding";async function me(e){let t=await dt(new TextEncoder().encode(e));return lt.encode(new Uint8Array(t),{includePadding:!1})}function fe(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 U({id:e,options:t,authorizationEndpoint:r,state:o,codeVerifier:n,scopes:i,claims:s,disablePkce:d,redirectURI:c}){let a=new URL(r);if(a.searchParams.set("response_type","code"),a.searchParams.set("client_id",t.clientId),a.searchParams.set("state",o),a.searchParams.set("scope",i.join(" ")),a.searchParams.set("redirect_uri",t.redirectURI||c),!d&&n){let l=await me(n);a.searchParams.set("code_challenge_method","S256"),a.searchParams.set("code_challenge",l)}if(s){let l=s.reduce((w,g)=>(w[g]=null,w),{});a.searchParams.set("claims",JSON.stringify({id_token:{email:null,email_verified:null,...l}}))}return a}import{betterFetch as ut}from"@better-fetch/fetch";async function y({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 ut(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 fe(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 ge=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})=>y({code:r,codeVerifier:o,redirectURI:e.redirectURI||n,options:e,tokenEndpoint:t}),async getUserInfo(r){if(!r.idToken)return null;let o=pt(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 mt}from"@better-fetch/fetch";var he=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})=>y({code:t,redirectURI:e.redirectURI||r,options:e,tokenEndpoint:"https://discord.com/api/oauth2/token"}),async getUserInfo(t){let{data:r,error:o}=await mt("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 ft}from"@better-fetch/fetch";var we=e=>({id:"facebook",name:"Facebook",async createAuthorizationURL({state:t,scopes:r,redirectURI:o}){let n=e.scope||r||["email","public_profile"];return await U({id:"facebook",options:e,authorizationEndpoint:"https://www.facebook.com/v21.0/dialog/oauth",scopes:n,state:t,redirectURI:o})},validateAuthorizationCode:async({code:t,redirectURI:r})=>y({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 ft("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 ye}from"@better-fetch/fetch";var be=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 U({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})=>y({code:r,redirectURI:e.redirectURI||o,options:e,tokenEndpoint:t}),async getUserInfo(r){let{data:o,error:n}=await ye("https://api.github.com/user",{headers:{"User-Agent":"better-auth",authorization:`Bearer ${r.accessToken}`}});if(n)return null;let i=!1;if(!o.email){let{data:s,error:d}=await ye("https://api.github.com/user/emails",{headers:{authorization:`Bearer ${r.accessToken}`,"User-Agent":"better-auth"}});d||(o.email=(s.find(c=>c.primary)??s[0])?.email,i=s.find(c=>c.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 gt}from"oslo/jwt";var Ae=e=>({id:"google",name:"Google",createAuthorizationURL({state:t,scopes:r,codeVerifier:o,redirectURI:n}){if(!e.clientId||!e.clientSecret)throw h.error("Client Id and Client Secret is required for Google. Make sure to provide them in the options."),new B("CLIENT_ID_AND_SECRET_REQUIRED");if(!o)throw new B("codeVerifier is required for Google");let i=e.scope||r||["email","profile"];return U({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})=>y({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=gt(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 ht}from"@better-fetch/fetch";import{parseJWT as wt}from"oslo/jwt";var ke=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 U({id:"microsoft",options:e,authorizationEndpoint:r,state:n.state,codeVerifier:n.codeVerifier,scopes:i,redirectURI:n.redirectURI})},validateAuthorizationCode({code:n,codeVerifier:i,redirectURI:s}){return y({code:n,codeVerifier:i,redirectURI:e.redirectURI||s,options:e,tokenEndpoint:o})},async getUserInfo(n){if(!n.idToken)return null;let i=wt(n.idToken)?.payload,s=e.profilePhotoSize||48;return await ht(`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 a=await d.response.clone().arrayBuffer(),l=Buffer.from(a).toString("base64");i.picture=`data:image/jpeg;base64, ${l}`}catch(c){h.error(c)}}}),{user:{id:i.sub,name:i.name,email:i.email,image:i.picture,emailVerified:!0},data:i}}}};import{betterFetch as yt}from"@better-fetch/fetch";var Re=e=>({id:"spotify",name:"Spotify",createAuthorizationURL({state:t,scopes:r,codeVerifier:o,redirectURI:n}){let i=e.scope||r||["user-read-email"];return U({id:"spotify",options:e,authorizationEndpoint:"https://accounts.spotify.com/authorize",scopes:i,state:t,codeVerifier:o,redirectURI:n})},validateAuthorizationCode:async({code:t,codeVerifier:r,redirectURI:o})=>y({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 yt("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 I={isAction:!1};import{nanoid as bt}from"nanoid";var Ue=e=>bt(e);import{parseJWT as At}from"oslo/jwt";var Ee=e=>({id:"twitch",name:"Twitch",createAuthorizationURL({state:t,scopes:r,redirectURI:o}){let n=e.scope||r||["user:read:email","openid"];return U({id:"twitch",redirectURI:o,options:e,authorizationEndpoint:"https://id.twitch.tv/oauth2/authorize",scopes:n,state:t,claims:e.claims||["email","email_verified","preferred_username","picture"]})},validateAuthorizationCode:async({code:t,redirectURI:r})=>y({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 h.error("No idToken found in token"),null;let o=At(r)?.payload;return{user:{id:o.sub,name:o.preferred_username,email:o.email,image:o.picture,emailVerified:!1},data:o}}});import{betterFetch as kt}from"@better-fetch/fetch";var Te=e=>({id:"twitter",name:"Twitter",createAuthorizationURL(t){let r=e.scope||t.scopes||["account_info.read"];return U({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})=>y({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 kt("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 Rt={apple:ge,discord:he,facebook:we,github:be,microsoft:ke,google:Ae,spotify:Re,twitch:Ee,twitter:Te},ve=Object.keys(Rt);import{TimeSpan as Ut}from"oslo";import{createJWT as Et,validateJWT as Tt}from"oslo/jwt";import{z as x}from"zod";import{APIError as z}from"better-call";import{APIError as M}from"better-call";var Q=(e,t="ms")=>new Date(Date.now()+(t==="sec"?e*1e3:e));import{z as xe}from"zod";var Y=()=>m("/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 N(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 c=await e.context.internalAdapter.updateSession(r.session.id,{expiresAt:Q(e.context.sessionConfig.expiresIn,"sec")});if(!c)return N(e),e.json(null,{status:401});let a=(c.expiresAt.valueOf()-Date.now())/1e3;return await _(e,c.id,!1,{maxAge:a}),e.json({session:c,user:r.user})}return e.json(r)}catch(t){return e.context.logger.error(t),e.json(null,{status:500})}}),ee=async e=>await Y()({...e,_flag:"json",headers:e.headers}),L=V(async e=>{let t=await ee(e);if(!t?.session)throw new M("UNAUTHORIZED");return{session:t}}),Pe=()=>m("/user/list-sessions",{method:"GET",use:[L],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)}),_e=m("/user/revoke-session",{method:"POST",body:xe.object({id:xe.string()}),use:[L],requireHeaders:!0},async e=>{let t=e.body.id,r=await e.context.internalAdapter.findSession(t);if(!r)throw new M("BAD_REQUEST",{message:"Session not found"});if(r.session.userId!==e.context.session.user.id)throw new M("UNAUTHORIZED");try{await e.context.internalAdapter.deleteSession(t)}catch(o){throw e.context.logger.error(o),new M("INTERNAL_SERVER_ERROR")}return e.json({status:!0})}),Se=m("/user/revoke-sessions",{method:"POST",use:[L],requireHeaders:!0},async e=>{try{await e.context.internalAdapter.deleteSessions(e.context.session.user.id)}catch(t){throw e.context.logger.error(t),new M("INTERNAL_SERVER_ERROR")}return e.json({status:!0})});async function O(e,t,r){return await Et("HS256",Buffer.from(e),{email:t.toLowerCase(),updateTo:r},{expiresIn:new Ut(1,"h"),issuer:"better-auth",subject:"verify-email",audiences:[t],includeIssuedTimestamp:!0})}var Le=m("/send-verification-email",{method:"POST",query:x.object({currentURL:x.string().optional()}).optional(),body:x.object({email:x.string().email(),callbackURL:x.string().optional()}),use:[R]},async e=>{if(!e.context.options.emailVerification?.sendVerificationEmail)throw e.context.logger.error("Verification email isn't enabled."),new z("BAD_REQUEST",{message:"Verification email isn't enabled"});let{email:t}=e.body,r=await e.context.internalAdapter.findUserByEmail(t);if(!r)throw new z("BAD_REQUEST",{message:"User not found"});let o=await O(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})}),Oe=m("/verify-email",{method:"GET",query:x.object({token:x.string(),callbackURL:x.string().optional()}),use:[R]},async e=>{let{token:t}=e.query,r;try{r=await Tt("HS256",Buffer.from(e.context.secret),t)}catch(s){throw e.context.logger.error("Failed to verify email",s),new z("BAD_REQUEST",{message:"Invalid token"})}let n=x.object({email:x.string().email(),updateTo:x.string().optional()}).parse(r.payload);if(!await e.context.internalAdapter.findUserByEmail(n.email))throw new z("BAD_REQUEST",{message:"User not found"});if(n.updateTo){let s=await ee(e);if(!s)throw e.query.callbackURL?e.redirect(`${e.query.callbackURL}?error=unauthorized`):new z("UNAUTHORIZED",{message:"Session not found"});if(s.user.email!==n.email)throw e.query.callbackURL?e.redirect(`${e.query.callbackURL}?error=unauthorized`):new z("UNAUTHORIZED",{message:"Invalid session"});let d=await e.context.internalAdapter.updateUserByEmail(n.email,{email:n.updateTo});if(await e.context.options.emailVerification?.sendVerificationEmail?.(d,`${e.context.baseURL}/verify-email?token=${t}`,t),e.query.callbackURL)throw e.redirect(e.query.callbackURL);return e.json({user:d,status:!0})}if(await e.context.internalAdapter.updateUserByEmail(n.email,{emailVerified:!0}),e.query.callbackURL)throw e.redirect(e.query.callbackURL);return e.json({user:null,status:!0})});var Ie=m("/sign-in/social",{method:"POST",requireHeaders:!0,query:v.object({currentURL:v.string().optional()}).optional(),body:v.object({callbackURL:v.string().optional(),provider:v.enum(ve)}),use:[R]},async e=>{let t=e.context.socialProviders.find(c=>c.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 ue(n||o?.origin||e.context.options.baseURL);await e.setSignedCookie(r.state.name,i.hash,e.context.secret,r.state.options);let s=vt();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})}),Ce=m("/sign-in/email",{method:"POST",body:v.object({email:v.string(),password:v.string(),callbackURL:v.string().optional(),dontRememberMe:v.boolean().default(!1).optional()}),use:[R]},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(!v.string().email().safeParse(t).success)throw new P("BAD_REQUEST",{message:"Invalid email"});if(!v.string().email().safeParse(t).success)throw new P("BAD_REQUEST",{message:"Invalid email"});let i=await e.context.internalAdapter.findUserByEmail(t,{includeAccounts:!0});if(!i)throw await e.context.password.hash(r),e.context.logger.error("User not found",{email:t}),new P("UNAUTHORIZED",{message:"Invalid email or password"});if(e.context.options?.emailAndPassword?.requireEmailVerification&&!i.user.emailVerified){if(!e.context.options?.emailVerification?.sendVerificationEmail)throw h.error("Email verification is required but no email verification handler is provided"),new P("INTERNAL_SERVER_ERROR",{message:"Email is not verified."});let l=await O(e.context.secret,i.user.email),w=`${e.context.options.baseURL}/verify-email?token=${l}`;throw await e.context.options.emailVerification.sendVerificationEmail(i.user,w,l),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 s=i.accounts.find(l=>l.providerId==="credential");if(!s)throw e.context.logger.error("Credential account not found",{email:t}),new P("UNAUTHORIZED",{message:"Invalid email or password"});let d=s?.password;if(!d)throw e.context.logger.error("Password not found",{email:t}),new P("UNAUTHORIZED",{message:"Unexpected error"});if(!await e.context.password.verify(d,r))throw e.context.logger.error("Invalid password"),new P("UNAUTHORIZED",{message:"Invalid email or password"});let a=await e.context.internalAdapter.createSession(i.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 _(e,a.id,e.body.dontRememberMe),e.json({user:i.user,session:a,redirect:!!e.body.callbackURL,url:e.body.callbackURL})});import{z as G}from"zod";import{z as f}from"zod";var Hn=f.object({id:f.string(),providerId:f.string(),accountId:f.string(),userId:f.string(),accessToken:f.string().nullable().optional(),refreshToken:f.string().nullable().optional(),idToken:f.string().nullable().optional(),expiresAt:f.date().nullable().optional(),password:f.string().optional().nullable()}),Be=f.object({id:f.string(),email:f.string().transform(e=>e.toLowerCase()),emailVerified:f.boolean().default(!1),name:f.string(),image:f.string().optional(),createdAt:f.date().default(new Date),updatedAt:f.date().default(new Date)}),Qn=f.object({id:f.string(),userId:f.string(),expiresAt:f.date(),ipAddress:f.string().optional(),userAgent:f.string().optional()}),Gn=f.object({id:f.string(),value:f.string(),expiresAt:f.date(),identifier:f.string()});function xt(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 De(e,t){let r={...e.user?.additionalFields};return xt(t||{},{fields:r})}var $e=m("/callback/:id",{method:"GET",query:G.object({state:G.string(),code:G.string().optional(),error:G.string().optional()}),metadata:I},async e=>{if(e.query.error||!e.query.code){let k=K(e.query.state).data?.callbackURL||`${e.context.baseURL}/error`;throw e.context.logger.error(e.query.error,e.params.id),e.redirect(`${k}?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 h.error("No stored state found"),e.redirect(`${e.context.baseURL}/error?error=please_restart_the_process`);if(!await le(e.query.state,i))throw h.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),c;try{c=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 a=await t.getUserInfo(c).then(p=>p?.user),l=Ue(),w=Be.safeParse({...a,id:l});if(!a||w.success===!1)throw h.error("Unable to get user info",w.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`);function g(p){throw e.redirect(`${n||o||`${e.context.baseURL}/error`}?error=${p}`)}let u=await e.context.internalAdapter.findUserByEmail(a.email,{includeAccounts:!0}).catch(p=>{throw h.error(`Better auth was unable to query your database.
|
|
2
|
+
`)}}),h=ct();var R=V(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 h.error("Invalid callback URL",{callbackURL:t,trustedOrigins:n}),new pe("FORBIDDEN",{message:"Invalid callback URL"})}if(o!==e.context.baseURL){let i=new URL(o).origin;if(!n.includes(i))throw h.error("Invalid current URL",{currentURL:o,trustedOrigins:n}),new pe("FORBIDDEN",{message:"Invalid callback URL"})}});import{parseJWT as pt}from"oslo/jwt";import{sha256 as dt}from"oslo/crypto";import{base64url as lt}from"oslo/encoding";async function me(e){let t=await dt(new TextEncoder().encode(e));return lt.encode(new Uint8Array(t),{includePadding:!1})}function fe(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 U({id:e,options:t,authorizationEndpoint:r,state:o,codeVerifier:n,scopes:i,claims:s,disablePkce:d,redirectURI:c}){let a=new URL(r);if(a.searchParams.set("response_type","code"),a.searchParams.set("client_id",t.clientId),a.searchParams.set("state",o),a.searchParams.set("scope",i.join(" ")),a.searchParams.set("redirect_uri",t.redirectURI||c),!d&&n){let l=await me(n);a.searchParams.set("code_challenge_method","S256"),a.searchParams.set("code_challenge",l)}if(s){let l=s.reduce((w,g)=>(w[g]=null,w),{});a.searchParams.set("claims",JSON.stringify({id_token:{email:null,email_verified:null,...l}}))}return a}import{betterFetch as ut}from"@better-fetch/fetch";async function y({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 ut(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 fe(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 ge=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})=>y({code:r,codeVerifier:o,redirectURI:e.redirectURI||n,options:e,tokenEndpoint:t}),async getUserInfo(r){if(!r.idToken)return null;let o=pt(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 mt}from"@better-fetch/fetch";var he=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})=>y({code:t,redirectURI:e.redirectURI||r,options:e,tokenEndpoint:"https://discord.com/api/oauth2/token"}),async getUserInfo(t){let{data:r,error:o}=await mt("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 ft}from"@better-fetch/fetch";var we=e=>({id:"facebook",name:"Facebook",async createAuthorizationURL({state:t,scopes:r,redirectURI:o}){let n=e.scope||r||["email","public_profile"];return await U({id:"facebook",options:e,authorizationEndpoint:"https://www.facebook.com/v21.0/dialog/oauth",scopes:n,state:t,redirectURI:o})},validateAuthorizationCode:async({code:t,redirectURI:r})=>y({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 ft("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 ye}from"@better-fetch/fetch";var be=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 U({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})=>y({code:r,redirectURI:e.redirectURI||o,options:e,tokenEndpoint:t}),async getUserInfo(r){let{data:o,error:n}=await ye("https://api.github.com/user",{headers:{"User-Agent":"better-auth",authorization:`Bearer ${r.accessToken}`}});if(n)return null;let i=!1;if(!o.email){let{data:s,error:d}=await ye("https://api.github.com/user/emails",{headers:{authorization:`Bearer ${r.accessToken}`,"User-Agent":"better-auth"}});d||(o.email=(s.find(c=>c.primary)??s[0])?.email,i=s.find(c=>c.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 gt}from"oslo/jwt";var Ae=e=>({id:"google",name:"Google",createAuthorizationURL({state:t,scopes:r,codeVerifier:o,redirectURI:n}){if(!e.clientId||!e.clientSecret)throw h.error("Client Id and Client Secret is required for Google. Make sure to provide them in the options."),new B("CLIENT_ID_AND_SECRET_REQUIRED");if(!o)throw new B("codeVerifier is required for Google");let i=e.scope||r||["email","profile"];return U({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})=>y({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=gt(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 ht}from"@better-fetch/fetch";import{parseJWT as wt}from"oslo/jwt";var ke=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 U({id:"microsoft",options:e,authorizationEndpoint:r,state:n.state,codeVerifier:n.codeVerifier,scopes:i,redirectURI:n.redirectURI})},validateAuthorizationCode({code:n,codeVerifier:i,redirectURI:s}){return y({code:n,codeVerifier:i,redirectURI:e.redirectURI||s,options:e,tokenEndpoint:o})},async getUserInfo(n){if(!n.idToken)return null;let i=wt(n.idToken)?.payload,s=e.profilePhotoSize||48;return await ht(`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 a=await d.response.clone().arrayBuffer(),l=Buffer.from(a).toString("base64");i.picture=`data:image/jpeg;base64, ${l}`}catch(c){h.error(c)}}}),{user:{id:i.sub,name:i.name,email:i.email,image:i.picture,emailVerified:!0},data:i}}}};import{betterFetch as yt}from"@better-fetch/fetch";var Re=e=>({id:"spotify",name:"Spotify",createAuthorizationURL({state:t,scopes:r,codeVerifier:o,redirectURI:n}){let i=e.scope||r||["user-read-email"];return U({id:"spotify",options:e,authorizationEndpoint:"https://accounts.spotify.com/authorize",scopes:i,state:t,codeVerifier:o,redirectURI:n})},validateAuthorizationCode:async({code:t,codeVerifier:r,redirectURI:o})=>y({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 yt("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 I={isAction:!1};import{nanoid as bt}from"nanoid";var Ue=e=>bt(e);import{parseJWT as At}from"oslo/jwt";var Ee=e=>({id:"twitch",name:"Twitch",createAuthorizationURL({state:t,scopes:r,redirectURI:o}){let n=e.scope||r||["user:read:email","openid"];return U({id:"twitch",redirectURI:o,options:e,authorizationEndpoint:"https://id.twitch.tv/oauth2/authorize",scopes:n,state:t,claims:e.claims||["email","email_verified","preferred_username","picture"]})},validateAuthorizationCode:async({code:t,redirectURI:r})=>y({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 h.error("No idToken found in token"),null;let o=At(r)?.payload;return{user:{id:o.sub,name:o.preferred_username,email:o.email,image:o.picture,emailVerified:!1},data:o}}});import{betterFetch as kt}from"@better-fetch/fetch";var Te=e=>({id:"twitter",name:"Twitter",createAuthorizationURL(t){let r=e.scope||t.scopes||["account_info.read"];return U({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})=>y({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 kt("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 Rt={apple:ge,discord:he,facebook:we,github:be,microsoft:ke,google:Ae,spotify:Re,twitch:Ee,twitter:Te},ve=Object.keys(Rt);import{TimeSpan as Ut}from"oslo";import{createJWT as Et,validateJWT as Tt}from"oslo/jwt";import{z as x}from"zod";import{APIError as z}from"better-call";import{APIError as M}from"better-call";var Q=(e,t="ms")=>new Date(Date.now()+(t==="sec"?e*1e3:e));import{z as xe}from"zod";var Y=()=>m("/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 N(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 c=await e.context.internalAdapter.updateSession(r.session.id,{expiresAt:Q(e.context.sessionConfig.expiresIn,"sec")});if(!c)return N(e),e.json(null,{status:401});let a=(c.expiresAt.valueOf()-Date.now())/1e3;return await _(e,c.id,!1,{maxAge:a}),e.json({session:c,user:r.user})}return e.json(r)}catch(t){return e.context.logger.error(t),e.json(null,{status:500})}}),ee=async e=>await Y()({...e,_flag:"json",headers:e.headers}),L=V(async e=>{let t=await ee(e);if(!t?.session)throw new M("UNAUTHORIZED");return{session:t}}),Pe=()=>m("/user/list-sessions",{method:"GET",use:[L],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)}),_e=m("/user/revoke-session",{method:"POST",body:xe.object({id:xe.string()}),use:[L],requireHeaders:!0},async e=>{let t=e.body.id,r=await e.context.internalAdapter.findSession(t);if(!r)throw new M("BAD_REQUEST",{message:"Session not found"});if(r.session.userId!==e.context.session.user.id)throw new M("UNAUTHORIZED");try{await e.context.internalAdapter.deleteSession(t)}catch(o){throw e.context.logger.error(o),new M("INTERNAL_SERVER_ERROR")}return e.json({status:!0})}),Se=m("/user/revoke-sessions",{method:"POST",use:[L],requireHeaders:!0},async e=>{try{await e.context.internalAdapter.deleteSessions(e.context.session.user.id)}catch(t){throw e.context.logger.error(t),new M("INTERNAL_SERVER_ERROR")}return e.json({status:!0})});async function O(e,t,r){return await Et("HS256",Buffer.from(e),{email:t.toLowerCase(),updateTo:r},{expiresIn:new Ut(1,"h"),issuer:"better-auth",subject:"verify-email",audiences:[t],includeIssuedTimestamp:!0})}var Le=m("/send-verification-email",{method:"POST",query:x.object({currentURL:x.string().optional()}).optional(),body:x.object({email:x.string().email(),callbackURL:x.string().optional()}),use:[R]},async e=>{if(!e.context.options.emailVerification?.sendVerificationEmail)throw e.context.logger.error("Verification email isn't enabled."),new z("BAD_REQUEST",{message:"Verification email isn't enabled"});let{email:t}=e.body,r=await e.context.internalAdapter.findUserByEmail(t);if(!r)throw new z("BAD_REQUEST",{message:"User not found"});let o=await O(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})}),Oe=m("/verify-email",{method:"GET",query:x.object({token:x.string(),callbackURL:x.string().optional()}),use:[R]},async e=>{let{token:t}=e.query,r;try{r=await Tt("HS256",Buffer.from(e.context.secret),t)}catch(s){throw e.context.logger.error("Failed to verify email",s),new z("BAD_REQUEST",{message:"Invalid token"})}let n=x.object({email:x.string().email(),updateTo:x.string().optional()}).parse(r.payload);if(!await e.context.internalAdapter.findUserByEmail(n.email))throw new z("BAD_REQUEST",{message:"User not found"});if(n.updateTo){let s=await ee(e);if(!s)throw e.query.callbackURL?e.redirect(`${e.query.callbackURL}?error=unauthorized`):new z("UNAUTHORIZED",{message:"Session not found"});if(s.user.email!==n.email)throw e.query.callbackURL?e.redirect(`${e.query.callbackURL}?error=unauthorized`):new z("UNAUTHORIZED",{message:"Invalid session"});let d=await e.context.internalAdapter.updateUserByEmail(n.email,{email:n.updateTo});if(await e.context.options.emailVerification?.sendVerificationEmail?.(d,`${e.context.baseURL}/verify-email?token=${t}`,t),e.query.callbackURL)throw e.redirect(e.query.callbackURL);return e.json({user:d,status:!0})}if(await e.context.internalAdapter.updateUserByEmail(n.email,{emailVerified:!0}),e.query.callbackURL)throw e.redirect(e.query.callbackURL);return e.json({user:null,status:!0})});var Ie=m("/sign-in/social",{method:"POST",requireHeaders:!0,query:v.object({currentURL:v.string().optional()}).optional(),body:v.object({callbackURL:v.string().optional(),provider:v.enum(ve)}),use:[R]},async e=>{let t=e.context.socialProviders.find(c=>c.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 ue(n||o?.origin||e.context.options.baseURL);await e.setSignedCookie(r.state.name,i.hash,e.context.secret,r.state.options);let s=vt();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})}),Ce=m("/sign-in/email",{method:"POST",body:v.object({email:v.string(),password:v.string(),callbackURL:v.string().optional(),dontRememberMe:v.boolean().default(!1).optional()}),use:[R]},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(!v.string().email().safeParse(t).success)throw new P("BAD_REQUEST",{message:"Invalid email"});if(!v.string().email().safeParse(t).success)throw new P("BAD_REQUEST",{message:"Invalid email"});let i=await e.context.internalAdapter.findUserByEmail(t,{includeAccounts:!0});if(!i)throw await e.context.password.hash(r),e.context.logger.error("User not found",{email:t}),new P("UNAUTHORIZED",{message:"Invalid email or password"});let s=i.accounts.find(l=>l.providerId==="credential");if(!s)throw e.context.logger.error("Credential account not found",{email:t}),new P("UNAUTHORIZED",{message:"Invalid email or password"});let d=s?.password;if(!d)throw e.context.logger.error("Password not found",{email:t}),new P("UNAUTHORIZED",{message:"Unexpected error"});if(!await e.context.password.verify(d,r))throw e.context.logger.error("Invalid password"),new P("UNAUTHORIZED",{message:"Invalid email or password"});if(e.context.options?.emailAndPassword?.requireEmailVerification&&!i.user.emailVerified){if(!e.context.options?.emailVerification?.sendVerificationEmail)throw h.error("Email verification is required but no email verification handler is provided"),new P("INTERNAL_SERVER_ERROR",{message:"Email is not verified."});let l=await O(e.context.secret,i.user.email),w=`${e.context.options.baseURL}/verify-email?token=${l}`;throw await e.context.options.emailVerification.sendVerificationEmail(i.user,w,l),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 a=await e.context.internalAdapter.createSession(i.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 _(e,a.id,e.body.dontRememberMe),e.json({user:i.user,session:a,redirect:!!e.body.callbackURL,url:e.body.callbackURL})});import{z as G}from"zod";import{z as f}from"zod";var Hn=f.object({id:f.string(),providerId:f.string(),accountId:f.string(),userId:f.string(),accessToken:f.string().nullable().optional(),refreshToken:f.string().nullable().optional(),idToken:f.string().nullable().optional(),expiresAt:f.date().nullable().optional(),password:f.string().optional().nullable()}),Be=f.object({id:f.string(),email:f.string().transform(e=>e.toLowerCase()),emailVerified:f.boolean().default(!1),name:f.string(),image:f.string().optional(),createdAt:f.date().default(new Date),updatedAt:f.date().default(new Date)}),Qn=f.object({id:f.string(),userId:f.string(),expiresAt:f.date(),ipAddress:f.string().optional(),userAgent:f.string().optional()}),Gn=f.object({id:f.string(),value:f.string(),expiresAt:f.date(),identifier:f.string()});function xt(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 De(e,t){let r={...e.user?.additionalFields};return xt(t||{},{fields:r})}var $e=m("/callback/:id",{method:"GET",query:G.object({state:G.string(),code:G.string().optional(),error:G.string().optional()}),metadata:I},async e=>{if(e.query.error||!e.query.code){let k=K(e.query.state).data?.callbackURL||`${e.context.baseURL}/error`;throw e.context.logger.error(e.query.error,e.params.id),e.redirect(`${k}?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 h.error("No stored state found"),e.redirect(`${e.context.baseURL}/error?error=please_restart_the_process`);if(!await le(e.query.state,i))throw h.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),c;try{c=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 a=await t.getUserInfo(c).then(p=>p?.user),l=Ue(),w=Be.safeParse({...a,id:l});if(!a||w.success===!1)throw h.error("Unable to get user info",w.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`);function g(p){throw e.redirect(`${n||o||`${e.context.baseURL}/error`}?error=${p}`)}let u=await e.context.internalAdapter.findUserByEmail(a.email,{includeAccounts:!0}).catch(p=>{throw h.error(`Better auth was unable to query your database.
|
|
3
3
|
Error: `,p),e.redirect(`${e.context.baseURL}/error?error=internal_server_error`)}),A=u?.user.id;if(u){if(!u.accounts.find(k=>k.providerId===t.id)){(!e.context.options.account?.accountLinking?.trustedProviders?.includes(t.id)&&!a.emailVerified||!e.context.options.account?.accountLinking?.enabled)&&g("account_not_linked");try{await e.context.internalAdapter.linkAccount({providerId:t.id,accountId:a.id.toString(),id:`${t.id}:${a.id}`,userId:u.user.id,...X(c)})}catch(C){h.error("Unable to link account",C),g("unable_to_link_account")}}}else try{let p=a.emailVerified||!1,k=await e.context.internalAdapter.createOAuthUser({...w.data,emailVerified:p},{...X(c),providerId:t.id,accountId:a.id.toString()});if(!p&&k&&e.context.options.emailVerification?.sendOnSignUp){let q=await O(e.context.secret,a.email),C=`${e.context.baseURL}/verify-email?token=${q}&callbackURL=${o}`;await e.context.options.emailVerification?.sendVerificationEmail?.(k.user,C,q)}}catch(p){h.error("Unable to create user",p),g("unable_to_create_user")}!A&&!l&&g("unable_to_create_user");let T=await e.context.internalAdapter.createSession(A||l,e.request);throw T||g("unable_to_create_session"),await _(e,T.id),e.redirect(o)});import"zod";import{APIError as Pt}from"better-call";var Ve=m("/sign-out",{method:"POST"},async e=>{let t=await e.getSignedCookie(e.context.authCookies.sessionToken.name,e.context.secret);if(!t)throw new Pt("BAD_REQUEST",{message:"Session not found"});return await e.context.internalAdapter.deleteSession(t),N(e),e.json({success:!0})});import{z as S}from"zod";import{APIError as Z}from"better-call";var ze=m("/forget-password",{method:"POST",body:S.object({email:S.string().email(),redirectTo:S.string()}),use:[R]},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})}),je=m("/reset-password/:token",{method:"GET",query:S.object({callbackURL:S.string()}),use:[R]},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}`)}),qe=m("/reset-password",{query:S.optional(S.object({token:S.string()})),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(l=>l.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 b}from"zod";import{APIError as E}from"better-call";var Ne=m("/user/update",{method:"POST",body:b.object({name:b.string().optional(),image:b.string().optional()}),use:[L,R]},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})}),Me=m("/user/change-password",{method:"POST",body:b.object({newPassword:b.string(),currentPassword:b.string(),revokeOtherSessions:b.boolean().optional()}),use:[L]},async e=>{let{newPassword:t,currentPassword:r,revokeOtherSessions:o}=e.body,n=e.context.session,i=e.context.password.config.minPasswordLength;if(t.length<i)throw e.context.logger.error("Password is too short"),new E("BAD_REQUEST",{message:"Password is too short"});let s=e.context.password.config.maxPasswordLength;if(t.length>s)throw e.context.logger.error("Password is too long"),new E("BAD_REQUEST",{message:"Password too long"});let c=(await e.context.internalAdapter.findAccounts(n.user.id)).find(w=>w.providerId==="credential"&&w.password);if(!c||!c.password)throw new E("BAD_REQUEST",{message:"User does not have a password"});let a=await e.context.password.hash(t);if(!await e.context.password.verify(c.password,r))throw new E("BAD_REQUEST",{message:"Incorrect password"});if(await e.context.internalAdapter.updateAccount(c.id,{password:a}),o){await e.context.internalAdapter.deleteSessions(n.user.id);let w=await e.context.internalAdapter.createSession(n.user.id,e.headers);if(!w)throw new E("INTERNAL_SERVER_ERROR",{message:"Unable to create session"});await _(e,w.id)}return e.json(n.user)}),Fe=m("/user/set-password",{method:"POST",body:b.object({newPassword:b.string()}),use:[L]},async e=>{let{newPassword:t}=e.body,r=e.context.session,o=e.context.password.config.minPasswordLength;if(t.length<o)throw e.context.logger.error("Password is too short"),new E("BAD_REQUEST",{message:"Password is too short"});let n=e.context.password.config.maxPasswordLength;if(t.length>n)throw e.context.logger.error("Password is too long"),new E("BAD_REQUEST",{message:"Password too long"});let s=(await e.context.internalAdapter.findAccounts(r.user.id)).find(c=>c.providerId==="credential"&&c.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 E("BAD_REQUEST",{message:"user already has a password"})}),He=m("/user/delete",{method:"POST",body:b.object({password:b.string()}),use:[L]},async e=>{let{password:t}=e.body,r=e.context.session,n=(await e.context.internalAdapter.findAccounts(r.user.id)).find(s=>s.providerId==="credential"&&s.password);if(!n||!n.password)throw new E("BAD_REQUEST",{message:"User does not have a password"});if(!await e.context.password.verify(n.password,t))throw new E("BAD_REQUEST",{message:"Incorrect password"});return await e.context.internalAdapter.deleteUser(r.user.id),await e.context.internalAdapter.deleteSessions(r.user.id),e.json(null)}),Qe=m("/user/change-email",{method:"POST",query:b.object({currentURL:b.string().optional()}).optional(),body:b.object({newEmail:b.string().email(),callbackURL:b.string().optional()}),use:[L,R]},async e=>{if(!e.context.options.user?.changeEmail?.enabled)throw e.context.logger.error("Change email is disabled."),new E("BAD_REQUEST",{message:"Change email is disabled"});if(e.body.newEmail===e.context.session.user.email)throw e.context.logger.error("Email is the same"),new E("BAD_REQUEST",{message:"Email is the same"});if(await e.context.internalAdapter.findUserByEmail(e.body.newEmail))throw e.context.logger.error("Email already exists"),new E("BAD_REQUEST",{message:"Couldn't update your email"});if(e.context.session.user.emailVerified!==!0){let n=await e.context.internalAdapter.updateUserByEmail(e.context.session.user.email,{email:e.body.newEmail});return e.json({user:n,status:!0})}if(!e.context.options.emailVerification?.sendVerificationEmail)throw e.context.logger.error("Verification email isn't enabled."),new E("BAD_REQUEST",{message:"Verification email isn't enabled"});let r=await O(e.context.secret,e.context.session.user.email,e.body.newEmail),o=`${e.context.baseURL}/verify-email?token=${r}&callbackURL=${e.body.callbackURL||e.query?.currentURL||"/"}`;return await e.context.options.emailVerification.sendVerificationEmail(e.context.session.user,o,r),e.json({user:null,status:!0})});var Ge=m("/csrf",{method:"GET",metadata:I},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=re(32,oe("a-z","0-9","A-Z")),o=await F(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 _t=(e="Unknown")=>`<!DOCTYPE html>
|
|
4
4
|
<html lang="en">
|
|
5
5
|
<head>
|