better-auth 0.7.6-beta.3 → 0.8.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/adapters/drizzle.d.cts +4 -3
- package/dist/adapters/drizzle.d.ts +4 -3
- package/dist/adapters/kysely.cjs +1 -1
- package/dist/adapters/kysely.d.cts +4 -3
- package/dist/adapters/kysely.d.ts +4 -3
- package/dist/adapters/kysely.js +1 -1
- package/dist/adapters/memory.d.cts +4 -3
- package/dist/adapters/memory.d.ts +4 -3
- package/dist/adapters/mongodb.d.cts +4 -3
- package/dist/adapters/mongodb.d.ts +4 -3
- package/dist/adapters/prisma.d.cts +4 -3
- package/dist/adapters/prisma.d.ts +4 -3
- package/dist/api.cjs +5 -5
- package/dist/api.d.cts +3 -2
- package/dist/api.d.ts +3 -2
- package/dist/api.js +5 -5
- package/dist/{auth-C-uryrMH.d.cts → auth-CRDJtWaN.d.cts} +873 -208
- package/dist/{auth-BmcfH9ig.d.ts → auth-DP-ZFlGK.d.ts} +873 -208
- package/dist/client/plugins.cjs +1 -1
- package/dist/client/plugins.d.cts +5 -4
- package/dist/client/plugins.d.ts +5 -4
- package/dist/client/plugins.js +1 -1
- package/dist/client.cjs +1 -1
- package/dist/client.d.cts +3 -2
- package/dist/client.d.ts +3 -2
- package/dist/client.js +1 -1
- package/dist/cookies.d.cts +3 -2
- package/dist/cookies.d.ts +3 -2
- package/dist/db.cjs +2 -2
- package/dist/db.d.cts +5 -4
- package/dist/db.d.ts +5 -4
- package/dist/db.js +3 -3
- package/dist/{index-CSObwEfn.d.ts → index-BH4FVjl_.d.ts} +318 -471
- package/dist/{index-DNLBhV2f.d.cts → index-CENJlACM.d.cts} +318 -471
- package/dist/{index-Bn9csJDG.d.ts → index-DN9ozDRm.d.ts} +37 -107
- package/dist/{index-DI6hwBqO.d.cts → index-cqC7BcV_.d.cts} +37 -107
- package/dist/index.cjs +5 -5
- package/dist/index.d.cts +4 -3
- package/dist/index.d.ts +4 -3
- package/dist/index.js +5 -5
- package/dist/node.d.cts +4 -3
- package/dist/node.d.ts +4 -3
- package/dist/oauth2.cjs +2 -2
- package/dist/oauth2.d.cts +8 -6
- package/dist/oauth2.d.ts +8 -6
- package/dist/oauth2.js +2 -2
- package/dist/plugins.cjs +5 -6
- package/dist/plugins.d.cts +5 -4
- package/dist/plugins.d.ts +5 -4
- package/dist/plugins.js +5 -6
- package/dist/react.cjs +1 -1
- package/dist/react.d.cts +23 -3
- package/dist/react.d.ts +23 -3
- package/dist/react.js +1 -1
- package/dist/social.cjs +2 -2
- package/dist/social.d.cts +2 -1
- package/dist/social.d.ts +2 -1
- package/dist/social.js +2 -2
- package/dist/solid-start.d.cts +4 -3
- package/dist/solid-start.d.ts +4 -3
- package/dist/solid.cjs +1 -1
- package/dist/solid.d.cts +3 -2
- package/dist/solid.d.ts +3 -2
- package/dist/solid.js +1 -1
- package/dist/{state-CbHVShbJ.d.cts → state-CfvqSQJk.d.cts} +1 -1
- package/dist/{state-UUNY3E78.d.ts → state-_22Ngsc7.d.ts} +1 -1
- package/dist/svelte-kit.d.cts +4 -3
- package/dist/svelte-kit.d.ts +4 -3
- package/dist/svelte.cjs +1 -1
- package/dist/svelte.d.cts +3 -2
- package/dist/svelte.d.ts +3 -2
- package/dist/svelte.js +1 -1
- package/dist/types.d.cts +4 -3
- package/dist/types.d.ts +4 -3
- package/dist/vue.cjs +1 -1
- package/dist/vue.d.cts +3 -2
- package/dist/vue.d.ts +3 -2
- package/dist/vue.js +1 -1
- package/package.json +1 -5
|
@@ -1,9 +1,10 @@
|
|
|
1
|
-
import { A as Adapter } from '../auth-
|
|
1
|
+
import { A as Adapter } from '../auth-CRDJtWaN.cjs';
|
|
2
2
|
import 'zod';
|
|
3
3
|
import 'kysely';
|
|
4
|
-
import '../index-DI6hwBqO.cjs';
|
|
5
|
-
import '../helper-DPDj8Nix.cjs';
|
|
6
4
|
import 'better-call';
|
|
5
|
+
import '../index-cqC7BcV_.cjs';
|
|
6
|
+
import '../helper-DPDj8Nix.cjs';
|
|
7
|
+
import 'jose';
|
|
7
8
|
import 'better-sqlite3';
|
|
8
9
|
|
|
9
10
|
interface DrizzleAdapterOptions {
|
|
@@ -1,9 +1,10 @@
|
|
|
1
|
-
import { A as Adapter } from '../auth-
|
|
1
|
+
import { A as Adapter } from '../auth-DP-ZFlGK.js';
|
|
2
2
|
import 'zod';
|
|
3
3
|
import 'kysely';
|
|
4
|
-
import '../index-Bn9csJDG.js';
|
|
5
|
-
import '../helper-DPDj8Nix.js';
|
|
6
4
|
import 'better-call';
|
|
5
|
+
import '../index-DN9ozDRm.js';
|
|
6
|
+
import '../helper-DPDj8Nix.js';
|
|
7
|
+
import 'jose';
|
|
7
8
|
import 'better-sqlite3';
|
|
8
9
|
|
|
9
10
|
interface DrizzleAdapterOptions {
|
package/dist/adapters/kysely.cjs
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
"use strict";var A=Object.defineProperty;var
|
|
1
|
+
"use strict";var A=Object.defineProperty;var k=Object.getOwnPropertyDescriptor;var q=Object.getOwnPropertyNames;var x=Object.prototype.hasOwnProperty;var F=(r,e)=>{for(var s in e)A(r,s,{get:e[s],enumerable:!0})},T=(r,e,s,n)=>{if(e&&typeof e=="object"||typeof e=="function")for(let a of q(e))!x.call(r,a)&&a!==s&&A(r,a,{get:()=>e[a],enumerable:!(n=k(e,a))||n.enumerable});return r};var K=r=>T(A({},"__esModule",{value:!0}),r);var I={};F(I,{createKyselyAdapter:()=>C,kyselyAdapter:()=>O});module.exports=K(I);var p=require("kysely"),c=require("kysely");function D(r){if("dialect"in r)return D(r.dialect);if("createDriver"in r){if(r instanceof c.SqliteDialect)return"sqlite";if(r instanceof c.MysqlDialect)return"mysql";if(r instanceof c.PostgresDialect)return"postgres";if(r instanceof p.MssqlDialect)return"mssql"}return"aggregate"in r?"sqlite":"getConnection"in r?"mysql":"connect"in r?"postgres":null}var C=async r=>{let e=r.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 s,n=D(e);return"createDriver"in e&&(s=e),"aggregate"in e&&(s=new c.SqliteDialect({database:e})),"getConnection"in e&&(s=new c.MysqlDialect(e)),"connect"in e&&(s=new c.PostgresDialect({pool:e})),{kysely:s?new p.Kysely({dialect:s}):null,databaseType:n}};function h(r){if(!r)return{and:null,or:null};let e={and:[],or:[]};return r.forEach(s=>{let{field:n,value:a,operator:i="=",connector:f="AND"}=s,l=t=>i.toLowerCase()==="in"?t(n,"in",Array.isArray(a)?a:[a]):i==="contains"?t(n,"like",`%${a}%`):i==="starts_with"?t(n,"like",`${a}%`):i==="ends_with"?t(n,"like",`%${a}`):i==="eq"?t(n,"=",a):i==="ne"?t(n,"<>",a):i==="gt"?t(n,">",a):i==="gte"?t(n,">=",a):i==="lt"?t(n,"<",a):i==="lte"?t(n,"<=",a):t(n,i,a);f==="OR"?e.or.push(l):e.and.push(l)}),{and:e.and.length?e.and:null,or:e.or.length?e.or:null}}function w(r,e,s){for(let n in r){let a=e[n]||Object.values(e).find(i=>i.fieldName===n);r[n]===0&&a.type==="boolean"&&s?.boolean&&(r[n]=!1),r[n]===1&&a?.type==="boolean"&&s?.boolean&&(r[n]=!0),a?.type==="date"&&(r[n]instanceof Date||(r[n]=new Date(r[n])))}return r}function g(r,e){for(let s in r)typeof r[s]=="boolean"&&e?.boolean&&(r[s]=r[s]?1:0),r[s]instanceof Date&&(r[s]=r[s].toISOString());return r}var O=(r,e)=>({id:"kysely",async create(s){let{model:n,data:a,select:i}=s;e?.transform&&(a=g(a,e.transform)),e?.generateId!==void 0&&(a.id=e.generateId?e.generateId():void 0);let f=await r.insertInto(n).values(a).returningAll().executeTakeFirst();if(e?.transform){let l=e.transform.schema[n];f=l?w(a,l,e.transform):f}return i?.length&&(f=f?i.reduce((t,o)=>f?.[o]?{...t,[o]:f[o]}:t,{}):null),f},async findOne(s){let{model:n,where:a,select:i}=s,{and:f,or:l}=h(a),t=r.selectFrom(n).selectAll();f&&(t=t.where(y=>y.and(f.map(u=>u(y))))),l&&(t=t.where(y=>y.or(l.map(u=>u(y)))));let o=await t.executeTakeFirst();if(i?.length&&(o=o?i.reduce((u,d)=>o?.[d]?{...u,[d]:o[d]}: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(s){let{model:n,where:a,limit:i,offset:f,sortBy:l}=s,t=r.selectFrom(n),{and:o,or:y}=h(a);o&&(t=t.where(d=>d.and(o.map(m=>m(d))))),y&&(t=t.where(d=>d.or(y.map(m=>m(d))))),t=t.limit(i||100),f&&(t=t.offset(f)),l&&(t=t.orderBy(l.field,l.direction));let u=await t.selectAll().execute();if(e?.transform){let d=e.transform.schema[n];return d?u.map(m=>w(m,d,e.transform)):u}return u},async update(s){let{model:n,where:a,update:i}=s,{and:f,or:l}=h(a);e?.transform&&(i=g(i,e.transform)),i.id&&(i.id=void 0);let t=r.updateTable(n).set(i);f&&(t=t.where(y=>y.and(f.map(u=>u(y))))),l&&(t=t.where(y=>y.or(l.map(u=>u(y)))));let o=await t.returningAll().executeTakeFirst()||null;if(e?.transform){let y=e.transform.schema[n];return y?w(o,y,e.transform):o}return o},async delete(s){let{model:n,where:a}=s,{and:i,or:f}=h(a),l=r.deleteFrom(n);i&&(l=l.where(t=>t.and(i.map(o=>o(t))))),f&&(l=l.where(t=>t.or(f.map(o=>o(t))))),await l.execute()},async deleteMany(s){let{model:n,where:a}=s,{and:i,or:f}=h(a),l=r.deleteFrom(n);i&&(l=l.where(t=>t.and(i.map(o=>o(t))))),f&&(l=l.where(t=>t.or(f.map(o=>o(t))))),await l.execute()}});0&&(module.exports={createKyselyAdapter,kyselyAdapter});
|
|
@@ -1,9 +1,10 @@
|
|
|
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-CRDJtWaN.cjs';
|
|
3
3
|
import 'zod';
|
|
4
|
-
import '../index-DI6hwBqO.cjs';
|
|
5
|
-
import '../helper-DPDj8Nix.cjs';
|
|
6
4
|
import 'better-call';
|
|
5
|
+
import '../index-cqC7BcV_.cjs';
|
|
6
|
+
import '../helper-DPDj8Nix.cjs';
|
|
7
|
+
import 'jose';
|
|
7
8
|
import 'better-sqlite3';
|
|
8
9
|
|
|
9
10
|
declare const createKyselyAdapter: (config: BetterAuthOptions) => Promise<{
|
|
@@ -1,9 +1,10 @@
|
|
|
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-DP-ZFlGK.js';
|
|
3
3
|
import 'zod';
|
|
4
|
-
import '../index-Bn9csJDG.js';
|
|
5
|
-
import '../helper-DPDj8Nix.js';
|
|
6
4
|
import 'better-call';
|
|
5
|
+
import '../index-DN9ozDRm.js';
|
|
6
|
+
import '../helper-DPDj8Nix.js';
|
|
7
|
+
import 'jose';
|
|
7
8
|
import 'better-sqlite3';
|
|
8
9
|
|
|
9
10
|
declare const createKyselyAdapter: (config: BetterAuthOptions) => Promise<{
|
package/dist/adapters/kysely.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
import{Kysely as h,MssqlDialect as q}from"kysely";import{MysqlDialect as w,PostgresDialect as A,SqliteDialect as D}from"kysely";function
|
|
1
|
+
import{Kysely as h,MssqlDialect as q}from"kysely";import{MysqlDialect as w,PostgresDialect as A,SqliteDialect as D}from"kysely";function g(r){if("dialect"in r)return g(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 t=r.database;if("db"in t)return{kysely:t.db,databaseType:t.type};if("dialect"in t)return{kysely:new h({dialect:t.dialect}),databaseType:t.type};let i,n=g(t);return"createDriver"in t&&(i=t),"aggregate"in t&&(i=new D({database:t})),"getConnection"in t&&(i=new w(t)),"connect"in t&&(i=new A({pool:t})),{kysely:i?new h({dialect:i}):null,databaseType:n}};function m(r){if(!r)return{and:null,or:null};let t={and:[],or:[]};return r.forEach(i=>{let{field:n,value:a,operator:s="=",connector:f="AND"}=i,l=e=>s.toLowerCase()==="in"?e(n,"in",Array.isArray(a)?a:[a]):s==="contains"?e(n,"like",`%${a}%`):s==="starts_with"?e(n,"like",`${a}%`):s==="ends_with"?e(n,"like",`%${a}`):s==="eq"?e(n,"=",a):s==="ne"?e(n,"<>",a):s==="gt"?e(n,">",a):s==="gte"?e(n,">=",a):s==="lt"?e(n,"<",a):s==="lte"?e(n,"<=",a):e(n,s,a);f==="OR"?t.or.push(l):t.and.push(l)}),{and:t.and.length?t.and:null,or:t.or.length?t.or:null}}function p(r,t,i){for(let n in r){let a=t[n]||Object.values(t).find(s=>s.fieldName===n);r[n]===0&&a.type==="boolean"&&i?.boolean&&(r[n]=!1),r[n]===1&&a?.type==="boolean"&&i?.boolean&&(r[n]=!0),a?.type==="date"&&(r[n]instanceof Date||(r[n]=new Date(r[n])))}return r}function k(r,t){for(let i in r)typeof r[i]=="boolean"&&t?.boolean&&(r[i]=r[i]?1:0),r[i]instanceof Date&&(r[i]=r[i].toISOString());return r}var C=(r,t)=>({id:"kysely",async create(i){let{model:n,data:a,select:s}=i;t?.transform&&(a=k(a,t.transform)),t?.generateId!==void 0&&(a.id=t.generateId?t.generateId():void 0);let f=await r.insertInto(n).values(a).returningAll().executeTakeFirst();if(t?.transform){let l=t.transform.schema[n];f=l?p(a,l,t.transform):f}return s?.length&&(f=f?s.reduce((e,o)=>f?.[o]?{...e,[o]:f[o]}:e,{}):null),f},async findOne(i){let{model:n,where:a,select:s}=i,{and:f,or:l}=m(a),e=r.selectFrom(n).selectAll();f&&(e=e.where(y=>y.and(f.map(u=>u(y))))),l&&(e=e.where(y=>y.or(l.map(u=>u(y)))));let o=await e.executeTakeFirst();if(s?.length&&(o=o?s.reduce((u,d)=>o?.[d]?{...u,[d]:o[d]}:u,{}):null),t?.transform){let y=t.transform.schema[n];return o=o&&y?p(o,y,t.transform):o,o||null}return o||null},async findMany(i){let{model:n,where:a,limit:s,offset:f,sortBy:l}=i,e=r.selectFrom(n),{and:o,or:y}=m(a);o&&(e=e.where(d=>d.and(o.map(c=>c(d))))),y&&(e=e.where(d=>d.or(y.map(c=>c(d))))),e=e.limit(s||100),f&&(e=e.offset(f)),l&&(e=e.orderBy(l.field,l.direction));let u=await e.selectAll().execute();if(t?.transform){let d=t.transform.schema[n];return d?u.map(c=>p(c,d,t.transform)):u}return u},async update(i){let{model:n,where:a,update:s}=i,{and:f,or:l}=m(a);t?.transform&&(s=k(s,t.transform)),s.id&&(s.id=void 0);let e=r.updateTable(n).set(s);f&&(e=e.where(y=>y.and(f.map(u=>u(y))))),l&&(e=e.where(y=>y.or(l.map(u=>u(y)))));let o=await e.returningAll().executeTakeFirst()||null;if(t?.transform){let y=t.transform.schema[n];return y?p(o,y,t.transform):o}return o},async delete(i){let{model:n,where:a}=i,{and:s,or:f}=m(a),l=r.deleteFrom(n);s&&(l=l.where(e=>e.and(s.map(o=>o(e))))),f&&(l=l.where(e=>e.or(f.map(o=>o(e))))),await l.execute()},async deleteMany(i){let{model:n,where:a}=i,{and:s,or:f}=m(a),l=r.deleteFrom(n);s&&(l=l.where(e=>e.and(s.map(o=>o(e))))),f&&(l=l.where(e=>e.or(f.map(o=>o(e))))),await l.execute()}});export{T as createKyselyAdapter,C as kyselyAdapter};
|
|
@@ -1,9 +1,10 @@
|
|
|
1
|
-
import { A as Adapter } from '../auth-
|
|
1
|
+
import { A as Adapter } from '../auth-CRDJtWaN.cjs';
|
|
2
2
|
import 'zod';
|
|
3
3
|
import 'kysely';
|
|
4
|
-
import '../index-DI6hwBqO.cjs';
|
|
5
|
-
import '../helper-DPDj8Nix.cjs';
|
|
6
4
|
import 'better-call';
|
|
5
|
+
import '../index-cqC7BcV_.cjs';
|
|
6
|
+
import '../helper-DPDj8Nix.cjs';
|
|
7
|
+
import 'jose';
|
|
7
8
|
import 'better-sqlite3';
|
|
8
9
|
|
|
9
10
|
interface MemoryDB {
|
|
@@ -1,9 +1,10 @@
|
|
|
1
|
-
import { A as Adapter } from '../auth-
|
|
1
|
+
import { A as Adapter } from '../auth-DP-ZFlGK.js';
|
|
2
2
|
import 'zod';
|
|
3
3
|
import 'kysely';
|
|
4
|
-
import '../index-Bn9csJDG.js';
|
|
5
|
-
import '../helper-DPDj8Nix.js';
|
|
6
4
|
import 'better-call';
|
|
5
|
+
import '../index-DN9ozDRm.js';
|
|
6
|
+
import '../helper-DPDj8Nix.js';
|
|
7
|
+
import 'jose';
|
|
7
8
|
import 'better-sqlite3';
|
|
8
9
|
|
|
9
10
|
interface MemoryDB {
|
|
@@ -1,10 +1,11 @@
|
|
|
1
1
|
import { Db } from 'mongodb';
|
|
2
|
-
import { W as Where } from '../auth-
|
|
2
|
+
import { W as Where } from '../auth-CRDJtWaN.cjs';
|
|
3
3
|
import 'zod';
|
|
4
4
|
import 'kysely';
|
|
5
|
-
import '../index-DI6hwBqO.cjs';
|
|
6
|
-
import '../helper-DPDj8Nix.cjs';
|
|
7
5
|
import 'better-call';
|
|
6
|
+
import '../index-cqC7BcV_.cjs';
|
|
7
|
+
import '../helper-DPDj8Nix.cjs';
|
|
8
|
+
import 'jose';
|
|
8
9
|
import 'better-sqlite3';
|
|
9
10
|
|
|
10
11
|
declare const mongodbAdapter: (mongo: Db, opts?: {
|
|
@@ -1,10 +1,11 @@
|
|
|
1
1
|
import { Db } from 'mongodb';
|
|
2
|
-
import { W as Where } from '../auth-
|
|
2
|
+
import { W as Where } from '../auth-DP-ZFlGK.js';
|
|
3
3
|
import 'zod';
|
|
4
4
|
import 'kysely';
|
|
5
|
-
import '../index-Bn9csJDG.js';
|
|
6
|
-
import '../helper-DPDj8Nix.js';
|
|
7
5
|
import 'better-call';
|
|
6
|
+
import '../index-DN9ozDRm.js';
|
|
7
|
+
import '../helper-DPDj8Nix.js';
|
|
8
|
+
import 'jose';
|
|
8
9
|
import 'better-sqlite3';
|
|
9
10
|
|
|
10
11
|
declare const mongodbAdapter: (mongo: Db, opts?: {
|
|
@@ -1,9 +1,10 @@
|
|
|
1
|
-
import { A as Adapter } from '../auth-
|
|
1
|
+
import { A as Adapter } from '../auth-CRDJtWaN.cjs';
|
|
2
2
|
import 'zod';
|
|
3
3
|
import 'kysely';
|
|
4
|
-
import '../index-DI6hwBqO.cjs';
|
|
5
|
-
import '../helper-DPDj8Nix.cjs';
|
|
6
4
|
import 'better-call';
|
|
5
|
+
import '../index-cqC7BcV_.cjs';
|
|
6
|
+
import '../helper-DPDj8Nix.cjs';
|
|
7
|
+
import 'jose';
|
|
7
8
|
import 'better-sqlite3';
|
|
8
9
|
|
|
9
10
|
declare const prismaAdapter: (prisma: any, options: {
|
|
@@ -1,9 +1,10 @@
|
|
|
1
|
-
import { A as Adapter } from '../auth-
|
|
1
|
+
import { A as Adapter } from '../auth-DP-ZFlGK.js';
|
|
2
2
|
import 'zod';
|
|
3
3
|
import 'kysely';
|
|
4
|
-
import '../index-Bn9csJDG.js';
|
|
5
|
-
import '../helper-DPDj8Nix.js';
|
|
6
4
|
import 'better-call';
|
|
5
|
+
import '../index-DN9ozDRm.js';
|
|
6
|
+
import '../helper-DPDj8Nix.js';
|
|
7
|
+
import 'jose';
|
|
7
8
|
import 'better-sqlite3';
|
|
8
9
|
|
|
9
10
|
declare const prismaAdapter: (prisma: any, options: {
|
package/dist/api.cjs
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
|
-
"use strict";var
|
|
2
|
-
`)}}),
|
|
3
|
-
`,`Current list of trustedOrigins: ${c}`),new Ge.APIError("FORBIDDEN",{message:`Invalid ${l}`})};u&&!e.context.options.advanced?.disableCSRFCheck&&h(n,"origin"),i&&h(i,"callbackURL"),s&&h(s,"redirectURL"),a&&h(a,"currentURL")});var O=require("better-call"),x=require("zod");var Ft=require("oslo");var X=require("oslo/crypto");async function Nt({value:e,secret:t}){return new X.HMAC("SHA-256").sign(new TextEncoder().encode(t),new TextEncoder().encode(e)).then(o=>Buffer.from(o).toString("base64"))}function Mt({value:e,signature:t,secret:r}){return new X.HMAC("SHA-256").verify(new TextEncoder().encode(r),Buffer.from(t,"base64"),new TextEncoder().encode(e))}var ee={sign:Nt,verify:Mt};var Qe=require("oslo/encoding");var C=(e,t="ms")=>new Date(Date.now()+(t==="sec"?e*1e3:e));async function T(e,t,r,o){let n=e.context.authCookies.sessionToken.options;n.maxAge=r?void 0:e.context.sessionConfig.expiresIn,await e.setSignedCookie(e.context.authCookies.sessionToken.name,t.session.id,e.context.secret,{...n,...o}),r&&await e.setSignedCookie(e.context.authCookies.dontRememberToken.name,"true",e.context.secret,e.context.authCookies.dontRememberToken.options),e.context.options.session?.cookieCache?.enabled&&e.setCookie(e.context.authCookies.sessionData.name,JSON.stringify(Qe.base64url.encode(new TextEncoder().encode(JSON.stringify({session:t,expiresAt:C(e.context.authCookies.sessionData.options.maxAge||60,"sec").getTime(),signature:await ee.sign({value:JSON.stringify(t),secret:e.context.secret})})))),e.context.authCookies.sessionData.options),e.context.options.secondaryStorage&&await e.context.secondaryStorage?.set(t.session.id,JSON.stringify({user:t.user,session:t.session}),t.session.expiresAt.getTime()-Date.now())}function B(e){e.setCookie(e.context.authCookies.sessionToken.name,"",{maxAge:0}),e.setCookie(e.context.authCookies.sessionData.name,"",{maxAge:0}),e.setCookie(e.context.authCookies.dontRememberToken.name,"",{maxAge:0})}var Xe=require("oslo/jwt");var Ze=require("oslo/crypto"),Je=require("oslo/encoding");async function We(e){let t=await(0,Ze.sha256)(new TextEncoder().encode(e));return Je.base64url.encode(new Uint8Array(t),{includePadding:!1})}function Ye(e){return{tokenType:e.token_type,accessToken:e.access_token,refreshToken:e.refresh_token,accessTokenExpiresAt:e.expires_in?C(e.expires_in,"sec"):void 0,scopes:e?.scope?typeof e.scope=="string"?e.scope.split(" "):e.scope:[],idToken:e.id_token}}async function A({id:e,options:t,authorizationEndpoint:r,state:o,codeVerifier:n,scopes:i,claims:s,redirectURI:a}){let c=new URL(r);if(c.searchParams.set("response_type","code"),c.searchParams.set("client_id",t.clientId),c.searchParams.set("state",o),c.searchParams.set("scope",i.join(" ")),c.searchParams.set("redirect_uri",t.redirectURI||a),n){let u=await We(n);c.searchParams.set("code_challenge_method","S256"),c.searchParams.set("code_challenge",u)}if(s){let u=s.reduce((d,h)=>(d[h]=null,d),{});c.searchParams.set("claims",JSON.stringify({id_token:{email:null,email_verified:null,...u}}))}return c}var Ke=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:a}=await(0,Ke.betterFetch)(n,{method:"POST",body:i,headers:{"content-type":"application/x-www-form-urlencoded",accept:"application/json","user-agent":"better-auth"}});if(a)throw a;return Ye(s)}var et=e=>{let t="https://appleid.apple.com/auth/token";return{id:"apple",name:"Apple",createAuthorizationURL({state:r,scopes:o,redirectURI:n}){let i=o||["email","name","openid"];return e.scope&&i.push(...e.scope),new URL(`https://appleid.apple.com/auth/authorize?client_id=${e.clientId}&response_type=code&redirect_uri=${n||e.redirectURI}&scope=${i.join(" ")}&state=${r}`)},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,Xe.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 tt=require("@better-fetch/fetch");var rt=e=>({id:"discord",name:"Discord",createAuthorizationURL({state:t,scopes:r,redirectURI:o}){let n=r||["identify","email"];return e.scope&&n.push(...e.scope),new URL(`https://discord.com/api/oauth2/authorize?scope=${n.join("+")}&response_type=code&client_id=${e.clientId}&redirect_uri=${encodeURIComponent(e.redirectURI||o)}&state=${t}`)},validateAuthorizationCode:async({code:t,redirectURI:r})=>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,tt.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 ot=require("@better-fetch/fetch");var nt=e=>({id:"facebook",name:"Facebook",async createAuthorizationURL({state:t,scopes:r,redirectURI:o}){let n=r||["email","public_profile"];return e.scope&&n.push(...e.scope),await A({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,ot.betterFetch)("https://graph.facebook.com/me?fields=id,name,email,picture",{auth:{type:"Bearer",token:t.accessToken}});return o?null:{user:{id:r.id,name:r.name,email:r.email,image:r.picture.data.url,emailVerified:r.email_verified},data:r}}});var pe=require("@better-fetch/fetch");var it=e=>{let t="https://github.com/login/oauth/access_token";return{id:"github",name:"GitHub",createAuthorizationURL({state:r,scopes:o,codeVerifier:n,redirectURI:i}){let s=o||["user:email"];return e.scope&&s.push(...e.scope),A({id:"github",options:e,authorizationEndpoint:"https://github.com/login/oauth/authorize",scopes:s,state:r,redirectURI:i})},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,pe.betterFetch)("https://api.github.com/user",{headers:{"User-Agent":"better-auth",authorization:`Bearer ${r.accessToken}`}});if(n)return null;let i=!1;if(!o.email){let{data:s,error:a}=await(0,pe.betterFetch)("https://api.github.com/user/emails",{headers:{authorization:`Bearer ${r.accessToken}`,"User-Agent":"better-auth"}});a||(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 st=require("oslo/jwt");var at=e=>({id:"google",name:"Google",async createAuthorizationURL({state:t,scopes:r,codeVerifier:o,redirectURI:n}){if(!e.clientId||!e.clientSecret)throw f.error("Client Id and Client Secret is required for Google. Make sure to provide them in the options."),new z("CLIENT_ID_AND_SECRET_REQUIRED");if(!o)throw new z("codeVerifier is required for Google");let i=r||["email","profile","openid"];e.scope&&i.push(...e.scope);let s=await A({id:"google",options:e,authorizationEndpoint:"https://accounts.google.com/o/oauth2/auth",scopes:i,state:t,codeVerifier:o,redirectURI:n});return e.accessType&&s.searchParams.set("access_type",e.accessType),e.prompt&&s.searchParams.set("prompt",e.prompt),s},validateAuthorizationCode:async({code:t,codeVerifier:r,redirectURI:o})=>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,st.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 ct=require("@better-fetch/fetch"),dt=require("oslo/jwt");var ut=e=>{let t=e.tenantId||"common",r=`https://login.microsoftonline.com/${t}/oauth2/v2.0/authorize`,o=`https://login.microsoftonline.com/${t}/oauth2/v2.0/token`;return{id:"microsoft",name:"Microsoft EntraID",createAuthorizationURL(n){let i=n.scopes||["openid","profile","email","User.Read"];return e.scope&&i.push(...e.scope),A({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,dt.parseJWT)(n.idToken)?.payload,s=e.profilePhotoSize||48;return await(0,ct.betterFetch)(`https://graph.microsoft.com/v1.0/me/photos/${s}x${s}/$value`,{headers:{Authorization:`Bearer ${n.accessToken}`},async onResponse(a){if(!(e.disableProfilePhoto||!a.response.ok))try{let u=await a.response.clone().arrayBuffer(),d=Buffer.from(u).toString("base64");i.picture=`data:image/jpeg;base64, ${d}`}catch(c){f.error(c)}}}),{user:{id:i.sub,name:i.name,email:i.email,image:i.picture,emailVerified:!0},data:i}}}};var lt=require("@better-fetch/fetch");var pt=e=>({id:"spotify",name:"Spotify",createAuthorizationURL({state:t,scopes:r,codeVerifier:o,redirectURI:n}){let i=r||["user-read-email"];return e.scope&&i.push(...e.scope),A({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,lt.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 wo=require("@better-fetch/fetch");var mt=require("oslo/jwt");var ft=e=>({id:"twitch",name:"Twitch",createAuthorizationURL({state:t,scopes:r,redirectURI:o}){let n=r||["user:read:email","openid"];return e.scope&&n.push(...e.scope),A({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 f.error("No idToken found in token"),null;let o=(0,mt.parseJWT)(r)?.payload;return{user:{id:o.sub,name:o.preferred_username,email:o.email,image:o.picture,emailVerified:!1},data:o}}});var gt=require("@better-fetch/fetch");var ht=e=>({id:"twitter",name:"Twitter",createAuthorizationURL(t){let r=t.scopes||["account_info.read"];return e.scope&&r.push(...e.scope),A({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,gt.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 wt=require("@better-fetch/fetch");var bt=e=>{let t="https://api.dropboxapi.com/oauth2/token";return{id:"dropbox",name:"Dropbox",createAuthorizationURL:async({state:r,scopes:o,codeVerifier:n,redirectURI:i})=>{let s=o||["account_info.read"];return e.scope&&s.push(...e.scope),await A({id:"dropbox",options:e,authorizationEndpoint:"https://www.dropbox.com/oauth2/authorize",scopes:s,state:r,redirectURI:i,codeVerifier:n})},validateAuthorizationCode:async({code:r,codeVerifier:o,redirectURI:n})=>await y({code:r,codeVerifier:o,redirectURI:e.redirectURI||n,options:e,tokenEndpoint:t}),async getUserInfo(r){let{data:o,error:n}=await(0,wt.betterFetch)("https://api.dropboxapi.com/2/users/get_current_account",{method:"POST",headers:{Authorization:`Bearer ${r.accessToken}`}});return n?null:{user:{id:o.account_id,name:o.name?.display_name,email:o.email,emailVerified:o.email_verified||!1,image:o.profile_photo_url},data:o}}}};var yt=require("@better-fetch/fetch");var At=e=>{let t="https://www.linkedin.com/oauth/v2/authorization",r="https://www.linkedin.com/oauth/v2/accessToken";return{id:"linkedin",name:"Linkedin",createAuthorizationURL:async({state:o,scopes:n,redirectURI:i})=>{let s=n||["profile","email","openid"];return e.scope&&s.push(...e.scope),await A({id:"linkedin",options:e,authorizationEndpoint:t,scopes:s,state:o,redirectURI:i})},validateAuthorizationCode:async({code:o,redirectURI:n})=>await y({code:o,redirectURI:e.redirectURI||n,options:e,tokenEndpoint:r}),async getUserInfo(o){let{data:n,error:i}=await(0,yt.betterFetch)("https://api.linkedin.com/v2/userinfo",{method:"GET",headers:{Authorization:`Bearer ${o.accessToken}`}});return i?null:{user:{id:n.sub,name:n.name,email:n.email,emailVerified:n.email_verified||!1,image:n.picture},data:n}}}};var kt=require("@better-fetch/fetch");var me=(e="")=>e.split("://").map(t=>t.replace(/\/{2,}/g,"/")).join("://"),Ht=e=>{let t=e||"https://gitlab.com";return{authorizationEndpoint:me(`${t}/oauth/authorize`),tokenEndpoint:me(`${t}/oauth/token`),userinfoEndpoint:me(`${t}/api/v4/user`)}},Rt=e=>{let{authorizationEndpoint:t,tokenEndpoint:r,userinfoEndpoint:o}=Ht(e.issuer),n="gitlab";return{id:n,name:"Gitlab",createAuthorizationURL:async({state:s,scopes:a,codeVerifier:c,redirectURI:u})=>{let d=a||["read_user"];return e.scope&&d.push(...e.scope),await A({id:n,options:e,authorizationEndpoint:t,scopes:d,state:s,redirectURI:u,codeVerifier:c})},validateAuthorizationCode:async({code:s,redirectURI:a,codeVerifier:c})=>y({code:s,redirectURI:e.redirectURI||a,options:e,codeVerifier:c,tokenEndpoint:r}),async getUserInfo(s){let{data:a,error:c}=await(0,kt.betterFetch)(o,{headers:{authorization:`Bearer ${s.accessToken}`}});return c||a.state!=="active"||a.locked?null:{user:{id:a.id.toString(),name:a.name??a.username,email:a.email,image:a.avatar_url,emailVerified:!0},data:a}}}};var Gt={apple:et,discord:rt,facebook:nt,github:it,microsoft:ut,google:at,spotify:pt,twitch:ft,twitter:ht,dropbox:bt,linkedin:At,gitlab:Rt},te=Object.keys(Gt);var Et=require("oslo"),ne=require("oslo/jwt"),_=require("zod");var j=require("better-call");var M=require("better-call");var F=require("zod");function Ut(e){try{return JSON.parse(e)}catch{return null}}var re=()=>m("/get-session",{method:"GET",query:F.z.optional(F.z.object({disableCookieCache:F.z.boolean().optional()})),requireHeaders:!0},async e=>{try{let t=await e.getSignedCookie(e.context.authCookies.sessionToken.name,e.context.secret);if(!t)return e.json(null,{status:401});let r=e.getCookie(e.context.authCookies.sessionData.name),o=r?Ut(Buffer.from(r,"base64").toString()):null;if(o&&!await ee.verify({value:JSON.stringify(o.session),signature:o?.signature,secret:e.context.secret}))return B(e),e.json(null,{status:401});let n=await e.getSignedCookie(e.context.authCookies.dontRememberToken.name,e.context.secret);if(o?.session&&e.context.options.session?.cookieCache?.enabled&&!e.query?.disableCookieCache){let d=o.session;if(o.expiresAt<Date.now()||d.session.expiresAt<new Date){let p=e.context.authCookies.sessionData.name;e.setCookie(p,"",{maxAge:0})}else return e.json(d)}let i=await e.context.internalAdapter.findSession(t);if(!i||i.session.expiresAt<new Date)return B(e),i&&await e.context.internalAdapter.deleteSession(i.session.id),e.json(null,{status:401});if(n)return e.json(i);let s=e.context.sessionConfig.expiresIn,a=e.context.sessionConfig.updateAge;if(i.session.expiresAt.valueOf()-s*1e3+a*1e3<=Date.now()){let d=await e.context.internalAdapter.updateSession(i.session.id,{expiresAt:C(e.context.sessionConfig.expiresIn,"sec")});if(!d)return B(e),e.json(null,{status:401});let h=(d.expiresAt.valueOf()-Date.now())/1e3;return await T(e,{session:d,user:i.user},!1,{maxAge:h}),e.json({session:d,user:i.user})}return e.json(i)}catch(t){return e.context.logger.error(t),e.json(null,{status:500})}}),oe=async e=>await re()({...e,_flag:"json",headers:e.headers}),v=G(async e=>{let t=await oe(e);if(!t?.session)throw new M.APIError("UNAUTHORIZED");return{session:t}}),fe=()=>m("/list-sessions",{method:"GET",use:[v],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)}),ge=m("/revoke-session",{method:"POST",body:F.z.object({id:F.z.string()}),use:[v],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})}),he=m("/revoke-sessions",{method:"POST",use:[v],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 S(e,t,r){return await(0,ne.createJWT)("HS256",Buffer.from(e),{email:t.toLowerCase(),updateTo:r},{expiresIn:new Et.TimeSpan(1,"h"),issuer:"better-auth",subject:"verify-email",audiences:[t],includeIssuedTimestamp:!0})}var we=m("/send-verification-email",{method:"POST",query:_.z.object({currentURL:_.z.string().optional()}).optional(),body:_.z.object({email:_.z.string().email(),callbackURL:_.z.string().optional()})},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 S(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})}),be=m("/verify-email",{method:"GET",query:_.z.object({token:_.z.string(),callbackURL:_.z.string().optional()})},async e=>{let{token:t}=e.query,r;try{r=await(0,ne.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=_.z.object({email:_.z.string().email(),updateTo:_.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 oe(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 a=await e.context.internalAdapter.updateUserByEmail(n.email,{email:n.updateTo});if(await e.context.options.emailVerification?.sendVerificationEmail?.(a,`${e.context.baseURL}/verify-email?token=${t}`,t),e.query.callbackURL)throw e.redirect(e.query.callbackURL);return e.json({user:a,status:!0})}if(await e.context.internalAdapter.updateUserByEmail(n.email,{emailVerified:!0}),e.query.callbackURL)throw e.redirect(e.query.callbackURL);return e.json({user:null,status:!0})});var ye=m("/sign-in/social",{method:"POST",query:x.z.object({currentURL:x.z.string().optional()}).optional(),body:x.z.object({callbackURL:x.z.string().optional(),provider:x.z.enum(te)})},async e=>{let t=e.context.socialProviders.find(i=>i.id===e.body.provider);if(!t)throw e.context.logger.error("Provider not found. Make sure to add the provider in your auth config",{provider:e.body.provider}),new O.APIError("NOT_FOUND",{message:"Provider not found"});let{codeVerifier:r,state:o}=await K(e),n=await t.createAuthorizationURL({state:o,codeVerifier:r,redirectURI:`${e.context.baseURL}/callback/${t.id}`});return e.json({url:n.toString(),redirect:!0})}),Ae=m("/sign-in/email",{method:"POST",body:x.z.object({email:x.z.string(),password:x.z.string(),callbackURL:x.z.string().optional(),dontRememberMe:x.z.boolean().default(!1).optional()})},async e=>{if(!e.context.options?.emailAndPassword?.enabled)throw e.context.logger.error("Email and password is not enabled. Make sure to enable it in the options on you `auth.ts` file. Check `https://better-auth.com/docs/authentication/email-password` for more!"),new O.APIError("BAD_REQUEST",{message:"Email and password is not enabled"});let{email:t,password:r}=e.body;if(!x.z.string().email().safeParse(t).success)throw new O.APIError("BAD_REQUEST",{message:"Invalid email"});let n=await e.context.internalAdapter.findUserByEmail(t,{includeAccounts:!0});if(!n)throw await e.context.password.hash(r),e.context.logger.error("User not found",{email:t}),new O.APIError("UNAUTHORIZED",{message:"Invalid email or password"});let i=n.accounts.find(u=>u.providerId==="credential");if(!i)throw e.context.logger.error("Credential account not found",{email:t}),new O.APIError("UNAUTHORIZED",{message:"Invalid email or password"});let s=i?.password;if(!s)throw e.context.logger.error("Password not found",{email:t}),new O.APIError("UNAUTHORIZED",{message:"Unexpected error"});if(!await e.context.password.verify(s,r))throw e.context.logger.error("Invalid password"),new O.APIError("UNAUTHORIZED",{message:"Invalid email or password"});if(e.context.options?.emailAndPassword?.requireEmailVerification&&!n.user.emailVerified){if(!e.context.options?.emailVerification?.sendVerificationEmail)throw f.error("Email verification is required but no email verification handler is provided"),new O.APIError("INTERNAL_SERVER_ERROR",{message:"Email is not verified."});let u=await S(e.context.secret,n.user.email),d=`${e.context.options.baseURL}/verify-email?token=${u}`;throw await e.context.options.emailVerification.sendVerificationEmail(n.user,d,u),e.context.logger.error("Email not verified",{email:t}),new O.APIError("FORBIDDEN",{message:"Email is not verified. Check your email for a verification link"})}let c=await e.context.internalAdapter.createSession(n.user.id,e.headers,e.body.dontRememberMe);if(!c)throw e.context.logger.error("Failed to create session"),new O.APIError("UNAUTHORIZED",{message:"Failed to create session"});return await T(e,{session:c,user:n.user},e.body.dontRememberMe),e.json({user:n.user,session:c,redirect:!!e.body.callbackURL,url:e.body.callbackURL})});var Z=require("zod");var g=require("zod"),bn=g.z.object({id:g.z.string(),providerId:g.z.string(),accountId:g.z.string(),userId:g.z.string(),accessToken:g.z.string().nullable().optional(),refreshToken:g.z.string().nullable().optional(),idToken:g.z.string().nullable().optional(),expiresAt:g.z.date().nullable().optional(),password:g.z.string().optional().nullable()}),vt=g.z.object({id:g.z.string(),email:g.z.string().transform(e=>e.toLowerCase()),emailVerified:g.z.boolean().default(!1),name:g.z.string(),image:g.z.string().optional(),createdAt:g.z.date().default(new Date),updatedAt:g.z.date().default(new Date)}),yn=g.z.object({id:g.z.string(),userId:g.z.string(),expiresAt:g.z.date(),ipAddress:g.z.string().optional(),userAgent:g.z.string().optional()}),An=g.z.object({id:g.z.string(),value:g.z.string(),expiresAt:g.z.date(),identifier:g.z.string()});function Qt(e,t){let r={...t==="user"?e.user?.additionalFields:{},...t==="session"?e.session?.additionalFields:{}};for(let o of e.plugins||[])o.schema&&o.schema[t]&&(r={...r,...o.schema[t].fields});return r}function Zt(e,t){let r=t.action||"create",o=t.fields,n={};for(let i in o){if(i in e){if(o[i].input===!1){if(o[i].defaultValue){n[i]=o[i].defaultValue;continue}continue}n[i]=e[i];continue}if(o[i].defaultValue&&r==="create"){n[i]=o[i].defaultValue;continue}}return n}function ie(e,t,r){let o=Qt(e,"user");return Zt(t||{},{fields:o,action:r})}var ke=m("/callback/:id",{method:"GET",query:Z.z.object({state:Z.z.string(),code:Z.z.string().optional(),error:Z.z.string().optional()}),metadata:N},async e=>{if(!e.query.code)throw e.redirect(`${e.context.baseURL}/error?error=${e.query.error||"no_code"}`);let t=e.context.socialProviders.find(w=>w.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{codeVerifier:r,callbackURL:o,link:n,errorURL:i}=await Fe(e),s;try{s=await t.validateAuthorizationCode({code:e.query.code,codeVerifier:r,redirectURI:`${e.context.baseURL}/callback/${t.id}`})}catch(w){throw e.context.logger.error(w),e.redirect(`${e.context.baseURL}/error?error=please_restart_the_process`)}let a=await t.getUserInfo(s).then(w=>w?.user),c=je(),u=vt.safeParse({...a,id:c});if(!a||u.success===!1)throw f.error("Unable to get user info",u.error),e.redirect(`${e.context.baseURL}/error?error=please_restart_the_process`);if(!o)throw f.error("No callback URL found"),e.redirect(`${e.context.baseURL}/error?error=please_restart_the_process`);if(n){if(n.email!==a.email.toLowerCase())return d("email_doesn't_match");if(!await e.context.internalAdapter.createAccount({userId:n.userId,providerId:t.id,accountId:a.id}))return d("unable_to_link_account");let b;try{b=new URL(o).toString()}catch{b=o}throw e.redirect(b)}function d(w){throw e.redirect(`${i||o||`${e.context.baseURL}/error`}?error=${w}`)}let h=await e.context.internalAdapter.findUserByEmail(a.email,{includeAccounts:!0}).catch(w=>{throw f.error(`Better auth was unable to query your database.
|
|
4
|
-
Error: `,w),e.redirect(`${e.context.baseURL}/error?error=internal_server_error`)}),p=h?.user;if(h){let w=h.accounts.find(b=>b.providerId===t.id);if(w)await e.context.internalAdapter.updateAccount(w.id,{accessToken:s.accessToken,idToken:s.idToken,refreshToken:s.refreshToken,expiresAt:s.accessTokenExpiresAt});else{(!e.context.options.account?.accountLinking?.trustedProviders?.includes(t.id)&&!a.emailVerified||e.context.options.account?.accountLinking?.enabled===!1)&&(qe&&f.warn(`User already exist but account isn't linked to ${t.id}. To read more about how account linking works in Better Auth see https://www.better-auth.com/docs/concepts/users-accounts#account-linking.`),d("account_not_linked"));try{await e.context.internalAdapter.linkAccount({providerId:t.id,accountId:a.id.toString(),id:`${t.id}:${a.id}`,userId:h.user.id,accessToken:s.accessToken,idToken:s.idToken,refreshToken:s.refreshToken,expiresAt:s.accessTokenExpiresAt})}catch(ze){f.error("Unable to link account",ze),d("unable_to_link_account")}}}else try{let w=a.emailVerified||!1;if(p=await e.context.internalAdapter.createOAuthUser({...u.data,emailVerified:w},{accessToken:s.accessToken,idToken:s.idToken,refreshToken:s.refreshToken,expiresAt:s.accessTokenExpiresAt,providerId:t.id,accountId:a.id.toString()}).then(b=>b?.user),!w&&p&&e.context.options.emailVerification?.sendOnSignUp){let b=await S(e.context.secret,p.email),R=`${e.context.baseURL}/verify-email?token=${b}&callbackURL=${o}`;await e.context.options.emailVerification?.sendVerificationEmail?.(p,R,b)}}catch(w){f.error("Unable to create user",w),d("unable_to_create_user")}if(!p)return d("unable_to_create_user");let l=await e.context.internalAdapter.createSession(p.id,e.request);l||d("unable_to_create_session"),await T(e,{session:l,user:p});let k;try{k=new URL(o).toString()}catch{k=o}throw e.redirect(k)});var Ln=require("zod");var _t=require("better-call"),Re=m("/sign-out",{method:"POST",requireHeaders:!0},async e=>{let t=await e.getSignedCookie(e.context.authCookies.sessionToken.name,e.context.secret);if(!t)throw new _t.APIError("BAD_REQUEST",{message:"Session not found"});return await e.context.internalAdapter.deleteSession(t),B(e),e.json({success:!0})});var P=require("zod");var J=require("better-call");function xt(e,t,r){let o=t?new URL(t,e.baseURL):new URL(`${e.baseURL}/error`);return r&&Object.entries(r).forEach(([n,i])=>o.searchParams.set(n,i)),o.href}function Jt(e,t,r){let o=new URL(t,e.baseURL);return r&&Object.entries(r).forEach(([n,i])=>o.searchParams.set(n,i)),o.href}var Ue=m("/forget-password",{method:"POST",body:P.z.object({email:P.z.string().email(),redirectTo:P.z.string()})},async e=>{if(!e.context.options.emailAndPassword?.sendResetPassword)throw e.context.logger.error("Reset password isn't enabled.Please pass an emailAndPassword.sendResetPasswordToken function in your auth config!"),new J.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 a=`${e.context.baseURL}/reset-password/${s}?callbackURL=${r}`;return await e.context.options.emailAndPassword.sendResetPassword(o.user,a),e.json({status:!0})}),Ee=m("/reset-password/:token",{method:"GET",query:P.z.object({callbackURL:P.z.string()})},async e=>{let{token:t}=e.params,{callbackURL:r}=e.query;if(!t||!r)throw e.redirect(xt(e.context,r,{error:"INVALID_TOKEN"}));let o=await e.context.internalAdapter.findVerificationValue(`reset-password:${t}`);throw!o||o.expiresAt<new Date?e.redirect(xt(e.context,r,{error:"INVALID_TOKEN"})):e.redirect(Jt(e.context,r,{token:t}))}),ve=m("/reset-password",{query:P.z.optional(P.z.object({token:P.z.string().optional(),currentURL:P.z.string().optional()})),method:"POST",body:P.z.object({newPassword:P.z.string()})},async e=>{let t=e.query?.token||(e.query?.currentURL?new URL(e.query.currentURL).searchParams.get("token"):"");if(!t)throw new J.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 J.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(d=>d.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 J.APIError("BAD_REQUEST",{message:"Failed to update password"});return e.json({status:!0})});var U=require("zod");var E=require("better-call");var _e=()=>m("/update-user",{method:"POST",body:U.z.record(U.z.string(),U.z.any()),use:[v]},async e=>{let t=e.body;if(t.email)throw new E.APIError("BAD_REQUEST",{message:"You can't update email"});let{name:r,image:o,...n}=t,i=e.context.session;if(!o&&!r&&Object.keys(n).length===0)return e.json({user:i.user});let s=ie(e.context.options,n,"update"),a=await e.context.internalAdapter.updateUserByEmail(i.user.email,{name:r,image:o,...s});return await T(e,{session:i.session,user:a}),e.json({user:a})}),xe=m("/change-password",{method:"POST",body:U.z.object({newPassword:U.z.string(),currentPassword:U.z.string(),revokeOtherSessions:U.z.boolean().optional()}),use:[v]},async e=>{let{newPassword:t,currentPassword:r,revokeOtherSessions:o}=e.body,n=e.context.session,i=e.context.password.config.minPasswordLength;if(t.length<i)throw e.context.logger.error("Password is too short"),new E.APIError("BAD_REQUEST",{message:"Password is too short"});let s=e.context.password.config.maxPasswordLength;if(t.length>s)throw e.context.logger.error("Password is too long"),new E.APIError("BAD_REQUEST",{message:"Password too long"});let c=(await e.context.internalAdapter.findAccounts(n.user.id)).find(h=>h.providerId==="credential"&&h.password);if(!c||!c.password)throw new E.APIError("BAD_REQUEST",{message:"User does not have a password"});let u=await e.context.password.hash(t);if(!await e.context.password.verify(c.password,r))throw new E.APIError("BAD_REQUEST",{message:"Incorrect password"});if(await e.context.internalAdapter.updateAccount(c.id,{password:u}),o){await e.context.internalAdapter.deleteSessions(n.user.id);let h=await e.context.internalAdapter.createSession(n.user.id,e.headers);if(!h)throw new E.APIError("INTERNAL_SERVER_ERROR",{message:"Unable to create session"});await T(e,{session:h,user:n.user})}return e.json(n.user)}),Pe=m("/set-password",{method:"POST",body:U.z.object({newPassword:U.z.string()}),metadata:{SERVER_ONLY:!0},use:[v]},async e=>{let{newPassword:t}=e.body,r=e.context.session,o=e.context.password.config.minPasswordLength;if(t.length<o)throw e.context.logger.error("Password is too short"),new E.APIError("BAD_REQUEST",{message:"Password is too short"});let n=e.context.password.config.maxPasswordLength;if(t.length>n)throw e.context.logger.error("Password is too long"),new E.APIError("BAD_REQUEST",{message:"Password too long"});let s=(await e.context.internalAdapter.findAccounts(r.user.id)).find(c=>c.providerId==="credential"&&c.password),a=await e.context.password.hash(t);if(!s)return await e.context.internalAdapter.linkAccount({userId:r.user.id,providerId:"credential",accountId:r.user.id,password:a}),e.json(r.user);throw new E.APIError("BAD_REQUEST",{message:"user already has a password"})}),Te=m("/delete-user",{method:"POST",body:U.z.object({password:U.z.string()}),use:[v]},async e=>{let{password:t}=e.body,r=e.context.session,n=(await e.context.internalAdapter.findAccounts(r.user.id)).find(s=>s.providerId==="credential"&&s.password);if(!n||!n.password)throw new E.APIError("BAD_REQUEST",{message:"User does not have a password"});if(!await e.context.password.verify(n.password,t))throw new E.APIError("BAD_REQUEST",{message:"Incorrect password"});return await e.context.internalAdapter.deleteUser(r.user.id),await e.context.internalAdapter.deleteSessions(r.user.id),B(e),e.json(null)}),Oe=m("/change-email",{method:"POST",query:U.z.object({currentURL:U.z.string().optional()}).optional(),body:U.z.object({newEmail:U.z.string().email(),callbackURL:U.z.string().optional()}),use:[v]},async e=>{if(!e.context.options.user?.changeEmail?.enabled)throw e.context.logger.error("Change email is disabled."),new E.APIError("BAD_REQUEST",{message:"Change email is disabled"});if(e.body.newEmail===e.context.session.user.email)throw e.context.logger.error("Email is the same"),new E.APIError("BAD_REQUEST",{message:"Email is the same"});if(await e.context.internalAdapter.findUserByEmail(e.body.newEmail))throw e.context.logger.error("Email already exists"),new E.APIError("BAD_REQUEST",{message:"Couldn't update your email"});if(e.context.session.user.emailVerified!==!0){let n=await e.context.internalAdapter.updateUserByEmail(e.context.session.user.email,{email:e.body.newEmail});return e.json({user:n,status:!0})}if(!e.context.options.user.changeEmail.sendChangeEmailVerification)throw e.context.logger.error("Verification email isn't enabled."),new E.APIError("BAD_REQUEST",{message:"Verification email isn't enabled"});let r=await S(e.context.secret,e.context.session.user.email,e.body.newEmail),o=`${e.context.baseURL}/verify-email?token=${r}&callbackURL=${e.body.callbackURL||e.query?.currentURL||"/"}`;return await e.context.options.user.changeEmail.sendChangeEmailVerification(e.context.session.user,e.body.newEmail,o,r),e.json({user:null,status:!0})});var Wt=(e="Unknown")=>`<!DOCTYPE html>
|
|
1
|
+
"use strict";var ce=Object.defineProperty;var zt=Object.getOwnPropertyDescriptor;var jt=Object.getOwnPropertyNames;var $t=Object.prototype.hasOwnProperty;var qt=(e,t)=>{for(var r in t)ce(e,r,{get:t[r],enumerable:!0})},Nt=(e,t,r,o)=>{if(t&&typeof t=="object"||typeof t=="function")for(let i of jt(t))!$t.call(e,i)&&i!==r&&ce(e,i,{get:()=>t[i],enumerable:!(o=zt(t,i))||o.enumerable});return e};var Ft=e=>Nt(ce({},"__esModule",{value:!0}),e);var cr={};qt(cr,{APIError:()=>Dt.APIError,callbackOAuth:()=>ve,changeEmail:()=>Le,changePassword:()=>Oe,createAuthEndpoint:()=>p,createAuthMiddleware:()=>Q,createEmailVerificationToken:()=>I,deleteUser:()=>Se,error:()=>Ce,forgetPassword:()=>_e,forgetPasswordCallback:()=>Te,getEndpoints:()=>Bt,getSession:()=>oe,getSessionFromCtx:()=>ie,linkSocialAccount:()=>je,listSessions:()=>he,listUserAccounts:()=>ze,ok:()=>Be,optionsMiddleware:()=>le,originCheckMiddleware:()=>me,resetPassword:()=>xe,revokeOtherSessions:()=>ye,revokeSession:()=>we,revokeSessions:()=>be,router:()=>dr,sendVerificationEmail:()=>Ae,sessionMiddleware:()=>T,setPassword:()=>Ie,signInEmail:()=>Ue,signInSocial:()=>Re,signOut:()=>Ee,signUpEmail:()=>De,updateUser:()=>Pe,verifyEmail:()=>ke});module.exports=Ft(cr);var N=require("better-call");var Ze=require("better-call");var D=require("better-call"),le=(0,D.createMiddleware)(async()=>({})),Q=(0,D.createMiddlewareCreator)({use:[le,(0,D.createMiddleware)(async()=>({}))]}),p=(0,D.createEndpointCreator)({use:[le]});var F={isAction:!1};var $e=require("nanoid"),qe=e=>(0,$e.nanoid)(e);var Y=require("oslo/oauth2"),L=require("zod"),pe=require("better-call");var K=Object.create(null),Z=e=>globalThis.process?.env||globalThis.Deno?.env.toObject()||globalThis.__env__||(e?K:globalThis),Ne=new Proxy(K,{get(e,t){return Z()[t]??K[t]},has(e,t){let r=Z();return t in r||t in K},set(e,t,r){let o=Z(!0);return o[t]=r,!0},deleteProperty(e,t){if(!t)return!1;let r=Z(!0);return delete r[t],!0},ownKeys(){let e=Z(!0);return Object.keys(e)}});function Mt(e){return e?e!=="false":!1}var ue=typeof process<"u"&&process.env&&process.env.NODE_ENV||"";var Fe=ue==="dev"||ue==="development",Me=ue==="test"||Mt(Ne.TEST);var V=class extends Error{constructor(t,r){super(t),this.name="BetterAuthError",this.message=t,this.cause=r}};function He(e){try{return new URL(e).origin}catch{return null}}async function X(e,t){let r=e.body?.callbackURL||(e.query?.currentURL?He(e.query?.currentURL):"")||e.context.options.baseURL;if(!r)throw new pe.APIError("BAD_REQUEST",{message:"callbackURL is required"});let o=(0,Y.generateCodeVerifier)(),i=(0,Y.generateState)(),n=JSON.stringify({callbackURL:r,codeVerifier:o,errorURL:e.query?.currentURL,link:t,expiresAt:Date.now()+10*60*1e3}),s=new Date;s.setMinutes(s.getMinutes()+10);let a=await e.context.internalAdapter.createVerificationValue({value:n,identifier:i,expiresAt:s});if(!a)throw m.error("Unable to create verification. Make sure the database adapter is properly working and there is a verification table in the database"),new pe.APIError("INTERNAL_SERVER_ERROR",{message:"Unable to create verification"});return{state:a.identifier,codeVerifier:o}}async function Ge(e){let t=e.query.state,r=await e.context.internalAdapter.findVerificationValue(t);if(!r)throw m.error("State Mismatch. Verification not found",{state:t}),e.redirect(`${e.context.baseURL}/error?error=please_restart_the_process`);let o=L.z.object({callbackURL:L.z.string(),codeVerifier:L.z.string(),errorURL:L.z.string().optional(),expiresAt:L.z.number(),link:L.z.object({email:L.z.string(),userId:L.z.string()}).optional()}).parse(JSON.parse(r.value));if(o.errorURL||(o.errorURL=`${e.context.baseURL}/error`),o.expiresAt<Date.now())throw await e.context.internalAdapter.deleteVerificationValue(r.id),m.error("State expired.",{state:t}),e.redirect(`${e.context.baseURL}/error?error=please_restart_the_process`);return await e.context.internalAdapter.deleteVerificationValue(r.id),o}var Qe=require("consola"),z=(0,Qe.createConsola)({formatOptions:{date:!1,colors:!0,compact:!0},defaults:{tag:"Better Auth"}}),Ht=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
|
+
`)}}),m=Ht();var me=Q(async e=>{if(e.request?.method!=="POST")return;let{body:t,query:r,context:o}=e,i=e.headers?.get("origin")||e.headers?.get("referer")||"",n=t?.callbackURL||r?.callbackURL,s=t?.redirectTo,a=r?.currentURL,d=o.trustedOrigins,c=e.headers?.has("cookie"),l=(g,u)=>u.includes("*")?new RegExp("^"+u.replace(/\*/g,"[^/]+").replace(/\./g,"\\.")+"$").test(g):g.startsWith(u),f=(g,u)=>{if(!g)return;if(!d.some(y=>l(g,y)||g?.startsWith("/")&&u!=="origin"&&!g.includes(":")))throw m.error(`Invalid ${u}: ${g}`),m.info(`If it's a valid URL, please add ${g} to trustedOrigins in your auth config
|
|
3
|
+
`,`Current list of trustedOrigins: ${d}`),new Ze.APIError("FORBIDDEN",{message:`Invalid ${u}`})};c&&!e.context.options.advanced?.disableCSRFCheck&&f(i,"origin"),n&&f(n,"callbackURL"),s&&f(s,"redirectURL"),a&&f(a,"currentURL")});var v=require("better-call"),k=require("zod");var Zt=require("oslo");var ee=require("oslo/crypto");async function Gt({value:e,secret:t}){return new ee.HMAC("SHA-256").sign(new TextEncoder().encode(t),new TextEncoder().encode(e)).then(o=>Buffer.from(o).toString("base64"))}function Qt({value:e,signature:t,secret:r}){return new ee.HMAC("SHA-256").verify(new TextEncoder().encode(r),Buffer.from(t,"base64"),new TextEncoder().encode(e))}var te={sign:Gt,verify:Qt};var Je=require("oslo/encoding");var C=(e,t="ms")=>new Date(Date.now()+(t==="sec"?e*1e3:e));async function x(e,t,r,o){let i=e.context.authCookies.sessionToken.options;i.maxAge=r?void 0:e.context.sessionConfig.expiresIn,await e.setSignedCookie(e.context.authCookies.sessionToken.name,t.session.id,e.context.secret,{...i,...o}),r&&await e.setSignedCookie(e.context.authCookies.dontRememberToken.name,"true",e.context.secret,e.context.authCookies.dontRememberToken.options),e.context.options.session?.cookieCache?.enabled&&e.setCookie(e.context.authCookies.sessionData.name,JSON.stringify(Je.base64url.encode(new TextEncoder().encode(JSON.stringify({session:t,expiresAt:C(e.context.authCookies.sessionData.options.maxAge||60,"sec").getTime(),signature:await te.sign({value:JSON.stringify(t),secret:e.context.secret})})))),e.context.authCookies.sessionData.options),e.context.options.secondaryStorage&&await e.context.secondaryStorage?.set(t.session.id,JSON.stringify({user:t.user,session:t.session}),t.session.expiresAt.getTime()-Date.now())}function B(e){e.setCookie(e.context.authCookies.sessionToken.name,"",{maxAge:0}),e.setCookie(e.context.authCookies.sessionData.name,"",{maxAge:0}),e.setCookie(e.context.authCookies.dontRememberToken.name,"",{maxAge:0})}var tt=require("oslo/jwt");var We=require("oslo/crypto"),Ke=require("oslo/encoding");async function Ye(e){let t=await(0,We.sha256)(new TextEncoder().encode(e));return Ke.base64url.encode(new Uint8Array(t),{includePadding:!1})}function Xe(e){return{tokenType:e.token_type,accessToken:e.access_token,refreshToken:e.refresh_token,accessTokenExpiresAt:e.expires_in?C(e.expires_in,"sec"):void 0,scopes:e?.scope?typeof e.scope=="string"?e.scope.split(" "):e.scope:[],idToken:e.id_token}}async function A({id:e,options:t,authorizationEndpoint:r,state:o,codeVerifier:i,scopes:n,claims:s,redirectURI:a}){let d=new URL(r);if(d.searchParams.set("response_type","code"),d.searchParams.set("client_id",t.clientId),d.searchParams.set("state",o),d.searchParams.set("scope",n.join(" ")),d.searchParams.set("redirect_uri",t.redirectURI||a),i){let c=await Ye(i);d.searchParams.set("code_challenge_method","S256"),d.searchParams.set("code_challenge",c)}if(s){let c=s.reduce((l,f)=>(l[f]=null,l),{});d.searchParams.set("claims",JSON.stringify({id_token:{email:null,email_verified:null,...c}}))}return d}var et=require("@better-fetch/fetch");async function b({code:e,codeVerifier:t,redirectURI:r,options:o,tokenEndpoint:i,authentication:n}){let s=new URLSearchParams,a={"content-type":"application/x-www-form-urlencoded",accept:"application/json","user-agent":"better-auth"};if(s.set("grant_type","authorization_code"),s.set("code",e),t&&s.set("code_verifier",t),s.set("redirect_uri",r),n==="basic"){let f=btoa(`${o.clientId}:${o.clientSecret}`);a.authorization=`Basic ${f}`}else s.set("client_id",o.clientId),s.set("client_secret",o.clientSecret);let{data:d,error:c}=await(0,et.betterFetch)(i,{method:"POST",body:s,headers:a});if(c)throw c;return Xe(d)}var M=require("jose"),rt=require("@better-fetch/fetch"),ot=require("better-call"),so=require("zod"),it=e=>{let t="https://appleid.apple.com/auth/token";return{id:"apple",name:"Apple",createAuthorizationURL({state:r,scopes:o,redirectURI:i}){let n=o||["email","name","openid"];return e.scope&&n.push(...e.scope),new URL(`https://appleid.apple.com/auth/authorize?client_id=${e.clientId}&response_type=code&redirect_uri=${i||e.redirectURI}&scope=${n.join(" ")}&state=${r}`)},validateAuthorizationCode:async({code:r,codeVerifier:o,redirectURI:i})=>b({code:r,codeVerifier:o,redirectURI:e.redirectURI||i,options:e,tokenEndpoint:t}),async verifyIdToken(r,o){if(e.disableIdTokenSignIn)return!1;if(e.verifyIdToken)return e.verifyIdToken(r,o);let i=(0,M.decodeJwt)(r),{kid:n,alg:s}=i.header,a=await Jt(n),{payload:d}=await(0,M.jwtVerify)(r,a,{algorithms:[s],issuer:"https://appleid.apple.com",audience:e.clientId,maxTokenAge:"1h"});return["email_verified","is_private_email"].forEach(c=>{d[c]!==void 0&&(d[c]=!!d[c])}),o&&d.nonce!==o?!1:!!d},async getUserInfo(r){if(!r.idToken)return null;let o=(0,tt.parseJWT)(r.idToken)?.payload;return o?{user:{id:o.sub,name:o.name,email:o.email,emailVerified:o.email_verified==="true",image:o.picture},data:o}:null}}},Jt=async e=>{let t="https://appleid.apple.com",r="/auth/keys",{data:o}=await(0,rt.betterFetch)(`${t}${r}`);if(!o?.keys)throw new ot.APIError("BAD_REQUEST",{message:"Keys not found"});let i=o.keys.find(n=>n.kid===e);if(!i)throw new Error(`JWK with kid ${e} not found`);return await(0,M.importJWK)(i,i.alg)};var nt=require("@better-fetch/fetch");var st=e=>({id:"discord",name:"Discord",createAuthorizationURL({state:t,scopes:r,redirectURI:o}){let i=r||["identify","email"];return e.scope&&i.push(...e.scope),new URL(`https://discord.com/api/oauth2/authorize?scope=${i.join("+")}&response_type=code&client_id=${e.clientId}&redirect_uri=${encodeURIComponent(e.redirectURI||o)}&state=${t}`)},validateAuthorizationCode:async({code:t,redirectURI:r})=>b({code:t,redirectURI:e.redirectURI||r,options:e,tokenEndpoint:"https://discord.com/api/oauth2/token"}),async getUserInfo(t){let{data:r,error:o}=await(0,nt.betterFetch)("https://discord.com/api/users/@me",{headers:{authorization:`Bearer ${t.accessToken}`}});if(o)return null;if(r.avatar===null){let i=r.discriminator==="0"?Number(BigInt(r.id)>>BigInt(22))%6:parseInt(r.discriminator)%5;r.image_url=`https://cdn.discordapp.com/embed/avatars/${i}.png`}else{let i=r.avatar.startsWith("a_")?"gif":"png";r.image_url=`https://cdn.discordapp.com/avatars/${r.id}/${r.avatar}.${i}`}return{user:{id:r.id,name:r.display_name||r.username||"",email:r.email,emailVerified:r.verified,image:r.image_url},data:r}}});var at=require("@better-fetch/fetch");var dt=e=>({id:"facebook",name:"Facebook",async createAuthorizationURL({state:t,scopes:r,redirectURI:o}){let i=r||["email","public_profile"];return e.scope&&i.push(...e.scope),await A({id:"facebook",options:e,authorizationEndpoint:"https://www.facebook.com/v21.0/dialog/oauth",scopes:i,state:t,redirectURI:o})},validateAuthorizationCode:async({code:t,redirectURI:r})=>b({code:t,redirectURI:e.redirectURI||r,options:e,tokenEndpoint:"https://graph.facebook.com/oauth/access_token"}),async getUserInfo(t){let{data:r,error:o}=await(0,at.betterFetch)("https://graph.facebook.com/me?fields=id,name,email,picture",{auth:{type:"Bearer",token:t.accessToken}});return o?null:{user:{id:r.id,name:r.name,email:r.email,image:r.picture.data.url,emailVerified:r.email_verified},data:r}}});var fe=require("@better-fetch/fetch");var ct=e=>{let t="https://github.com/login/oauth/access_token";return{id:"github",name:"GitHub",createAuthorizationURL({state:r,scopes:o,codeVerifier:i,redirectURI:n}){let s=o||["user:email"];return e.scope&&s.push(...e.scope),A({id:"github",options:e,authorizationEndpoint:"https://github.com/login/oauth/authorize",scopes:s,state:r,redirectURI:n})},validateAuthorizationCode:async({code:r,redirectURI:o})=>b({code:r,redirectURI:e.redirectURI||o,options:e,tokenEndpoint:t}),async getUserInfo(r){let{data:o,error:i}=await(0,fe.betterFetch)("https://api.github.com/user",{headers:{"User-Agent":"better-auth",authorization:`Bearer ${r.accessToken}`}});if(i)return null;let n=!1;if(!o.email){let{data:s,error:a}=await(0,fe.betterFetch)("https://api.github.com/user/emails",{headers:{authorization:`Bearer ${r.accessToken}`,"User-Agent":"better-auth"}});a||(o.email=(s.find(d=>d.primary)??s[0])?.email,n=s.find(d=>d.email===o.email)?.verified??!1)}return{user:{id:o.id.toString(),name:o.name||o.login,email:o.email,image:o.avatar_url,emailVerified:n},data:o}}}};var lt=require("oslo/jwt");var ut=require("@better-fetch/fetch"),pt=e=>({id:"google",name:"Google",async createAuthorizationURL({state:t,scopes:r,codeVerifier:o,redirectURI:i}){if(!e.clientId||!e.clientSecret)throw m.error("Client Id and Client Secret is required for Google. Make sure to provide them in the options."),new V("CLIENT_ID_AND_SECRET_REQUIRED");if(!o)throw new V("codeVerifier is required for Google");let n=r||["email","profile","openid"];e.scope&&n.push(...e.scope);let s=await A({id:"google",options:e,authorizationEndpoint:"https://accounts.google.com/o/oauth2/auth",scopes:n,state:t,codeVerifier:o,redirectURI:i});return e.accessType&&s.searchParams.set("access_type",e.accessType),e.prompt&&s.searchParams.set("prompt",e.prompt),s},validateAuthorizationCode:async({code:t,codeVerifier:r,redirectURI:o})=>b({code:t,codeVerifier:r,redirectURI:e.redirectURI||o,options:e,tokenEndpoint:"https://oauth2.googleapis.com/token"}),async verifyIdToken(t,r){if(e.disableIdTokenSignIn)return!1;if(e.verifyIdToken)return e.verifyIdToken(t,r);let o=`https://www.googleapis.com/oauth2/v3/tokeninfo?id_token=${t}`,{data:i}=await(0,ut.betterFetch)(o);return i?i.aud===e.clientId&&i.iss==="https://accounts.google.com":!1},async getUserInfo(t){if(!t.idToken)return null;let r=(0,lt.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 mt=require("@better-fetch/fetch"),ft=require("oslo/jwt");var gt=e=>{let t=e.tenantId||"common",r=`https://login.microsoftonline.com/${t}/oauth2/v2.0/authorize`,o=`https://login.microsoftonline.com/${t}/oauth2/v2.0/token`;return{id:"microsoft",name:"Microsoft EntraID",createAuthorizationURL(i){let n=i.scopes||["openid","profile","email","User.Read"];return e.scope&&n.push(...e.scope),A({id:"microsoft",options:e,authorizationEndpoint:r,state:i.state,codeVerifier:i.codeVerifier,scopes:n,redirectURI:i.redirectURI})},validateAuthorizationCode({code:i,codeVerifier:n,redirectURI:s}){return b({code:i,codeVerifier:n,redirectURI:e.redirectURI||s,options:e,tokenEndpoint:o})},async getUserInfo(i){if(!i.idToken)return null;let n=(0,ft.parseJWT)(i.idToken)?.payload,s=e.profilePhotoSize||48;return await(0,mt.betterFetch)(`https://graph.microsoft.com/v1.0/me/photos/${s}x${s}/$value`,{headers:{Authorization:`Bearer ${i.accessToken}`},async onResponse(a){if(!(e.disableProfilePhoto||!a.response.ok))try{let c=await a.response.clone().arrayBuffer(),l=Buffer.from(c).toString("base64");n.picture=`data:image/jpeg;base64, ${l}`}catch(d){m.error(d)}}}),{user:{id:n.sub,name:n.name,email:n.email,image:n.picture,emailVerified:!0},data:n}}}};var ht=require("@better-fetch/fetch");var wt=e=>({id:"spotify",name:"Spotify",createAuthorizationURL({state:t,scopes:r,codeVerifier:o,redirectURI:i}){let n=r||["user-read-email"];return e.scope&&n.push(...e.scope),A({id:"spotify",options:e,authorizationEndpoint:"https://accounts.spotify.com/authorize",scopes:n,state:t,codeVerifier:o,redirectURI:i})},validateAuthorizationCode:async({code:t,codeVerifier:r,redirectURI:o})=>b({code:t,codeVerifier:r,redirectURI:e.redirectURI||o,options:e,tokenEndpoint:"https://accounts.spotify.com/api/token"}),async getUserInfo(t){let{data:r,error:o}=await(0,ht.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 Eo=require("@better-fetch/fetch");var bt=require("oslo/jwt");var yt=e=>({id:"twitch",name:"Twitch",createAuthorizationURL({state:t,scopes:r,redirectURI:o}){let i=r||["user:read:email","openid"];return e.scope&&i.push(...e.scope),A({id:"twitch",redirectURI:o,options:e,authorizationEndpoint:"https://id.twitch.tv/oauth2/authorize",scopes:i,state:t,claims:e.claims||["email","email_verified","preferred_username","picture"]})},validateAuthorizationCode:async({code:t,redirectURI:r})=>b({code:t,redirectURI:e.redirectURI||r,options:e,tokenEndpoint:"https://id.twitch.tv/oauth2/token"}),async getUserInfo(t){let r=t.idToken;if(!r)return m.error("No idToken found in token"),null;let o=(0,bt.parseJWT)(r)?.payload;return{user:{id:o.sub,name:o.preferred_username,email:o.email,image:o.picture,emailVerified:!1},data:o}}});var At=require("@better-fetch/fetch");var kt=e=>({id:"twitter",name:"Twitter",createAuthorizationURL(t){let r=t.scopes||["users.read","tweet.read","offline.access"];return e.scope&&r.push(...e.scope),A({id:"twitter",options:e,authorizationEndpoint:"https://x.com/i/oauth2/authorize",scopes:r,state:t.state,codeVerifier:t.codeVerifier,redirectURI:t.redirectURI})},validateAuthorizationCode:async({code:t,codeVerifier:r,redirectURI:o})=>b({code:t,codeVerifier:r,authentication:"basic",redirectURI:e.redirectURI||o,options:e,tokenEndpoint:"https://api.x.com/2/oauth2/token"}),async getUserInfo(t){let{data:r,error:o}=await(0,At.betterFetch)("https://api.x.com/2/users/me?user.fields=profile_image_url",{method:"GET",headers:{Authorization:`Bearer ${t.accessToken}`}});return o?null:{user:{id:r.data.id,name:r.data.name,email:r.data.email||null,image:r.data.profile_image_url,emailVerified:r.data.verified||!1},data:r}}});var Rt=require("@better-fetch/fetch");var Ut=e=>{let t="https://api.dropboxapi.com/oauth2/token";return{id:"dropbox",name:"Dropbox",createAuthorizationURL:async({state:r,scopes:o,codeVerifier:i,redirectURI:n})=>{let s=o||["account_info.read"];return e.scope&&s.push(...e.scope),await A({id:"dropbox",options:e,authorizationEndpoint:"https://www.dropbox.com/oauth2/authorize",scopes:s,state:r,redirectURI:n,codeVerifier:i})},validateAuthorizationCode:async({code:r,codeVerifier:o,redirectURI:i})=>await b({code:r,codeVerifier:o,redirectURI:e.redirectURI||i,options:e,tokenEndpoint:t}),async getUserInfo(r){let{data:o,error:i}=await(0,Rt.betterFetch)("https://api.dropboxapi.com/2/users/get_current_account",{method:"POST",headers:{Authorization:`Bearer ${r.accessToken}`}});return i?null:{user:{id:o.account_id,name:o.name?.display_name,email:o.email,emailVerified:o.email_verified||!1,image:o.profile_photo_url},data:o}}}};var vt=require("@better-fetch/fetch");var Et=e=>{let t="https://www.linkedin.com/oauth/v2/authorization",r="https://www.linkedin.com/oauth/v2/accessToken";return{id:"linkedin",name:"Linkedin",createAuthorizationURL:async({state:o,scopes:i,redirectURI:n})=>{let s=i||["profile","email","openid"];return e.scope&&s.push(...e.scope),await A({id:"linkedin",options:e,authorizationEndpoint:t,scopes:s,state:o,redirectURI:n})},validateAuthorizationCode:async({code:o,redirectURI:i})=>await b({code:o,redirectURI:e.redirectURI||i,options:e,tokenEndpoint:r}),async getUserInfo(o){let{data:i,error:n}=await(0,vt.betterFetch)("https://api.linkedin.com/v2/userinfo",{method:"GET",headers:{Authorization:`Bearer ${o.accessToken}`}});return n?null:{user:{id:i.sub,name:i.name,email:i.email,emailVerified:i.email_verified||!1,image:i.picture},data:i}}}};var _t=require("@better-fetch/fetch");var ge=(e="")=>e.split("://").map(t=>t.replace(/\/{2,}/g,"/")).join("://"),Wt=e=>{let t=e||"https://gitlab.com";return{authorizationEndpoint:ge(`${t}/oauth/authorize`),tokenEndpoint:ge(`${t}/oauth/token`),userinfoEndpoint:ge(`${t}/api/v4/user`)}},Tt=e=>{let{authorizationEndpoint:t,tokenEndpoint:r,userinfoEndpoint:o}=Wt(e.issuer),i="gitlab";return{id:i,name:"Gitlab",createAuthorizationURL:async({state:s,scopes:a,codeVerifier:d,redirectURI:c})=>{let l=a||["read_user"];return e.scope&&l.push(...e.scope),await A({id:i,options:e,authorizationEndpoint:t,scopes:l,state:s,redirectURI:c,codeVerifier:d})},validateAuthorizationCode:async({code:s,redirectURI:a,codeVerifier:d})=>b({code:s,redirectURI:e.redirectURI||a,options:e,codeVerifier:d,tokenEndpoint:r}),async getUserInfo(s){let{data:a,error:d}=await(0,_t.betterFetch)(o,{headers:{authorization:`Bearer ${s.accessToken}`}});return d||a.state!=="active"||a.locked?null:{user:{id:a.id.toString(),name:a.name??a.username,email:a.email,image:a.avatar_url,emailVerified:!0},data:a}}}};var Kt={apple:it,discord:st,facebook:dt,github:ct,microsoft:gt,google:pt,spotify:wt,twitch:yt,twitter:kt,dropbox:Ut,linkedin:Et,gitlab:Tt},re=Object.keys(Kt);var Pt=require("oslo"),ne=require("oslo/jwt"),P=require("zod");var $=require("better-call");var j=require("better-call");var H=require("zod");function xt(e){try{return JSON.parse(e)}catch{return null}}var oe=()=>p("/get-session",{method:"GET",query:H.z.optional(H.z.object({disableCookieCache:H.z.boolean().optional()})),requireHeaders:!0},async e=>{try{let t=await e.getSignedCookie(e.context.authCookies.sessionToken.name,e.context.secret);if(!t)return e.json(null,{status:401});let r=e.getCookie(e.context.authCookies.sessionData.name),o=r?xt(Buffer.from(r,"base64").toString()):null;if(o&&!await te.verify({value:JSON.stringify(o.session),signature:o?.signature,secret:e.context.secret}))return B(e),e.json(null,{status:401});let i=await e.getSignedCookie(e.context.authCookies.dontRememberToken.name,e.context.secret);if(o?.session&&e.context.options.session?.cookieCache?.enabled&&!e.query?.disableCookieCache){let l=o.session;if(o.expiresAt<Date.now()||l.session.expiresAt<new Date){let g=e.context.authCookies.sessionData.name;e.setCookie(g,"",{maxAge:0})}else return e.json(l)}let n=await e.context.internalAdapter.findSession(t);if(!n||n.session.expiresAt<new Date)return B(e),n&&await e.context.internalAdapter.deleteSession(n.session.id),e.json(null,{status:401});if(i)return e.json(n);let s=e.context.sessionConfig.expiresIn,a=e.context.sessionConfig.updateAge;if(n.session.expiresAt.valueOf()-s*1e3+a*1e3<=Date.now()){let l=await e.context.internalAdapter.updateSession(n.session.id,{expiresAt:C(e.context.sessionConfig.expiresIn,"sec")});if(!l)return B(e),e.json(null,{status:401});let f=(l.expiresAt.valueOf()-Date.now())/1e3;return await x(e,{session:l,user:n.user},!1,{maxAge:f}),e.json({session:l,user:n.user})}return e.json(n)}catch(t){return e.context.logger.error(t),e.json(null,{status:500})}}),ie=async e=>await oe()({...e,_flag:"json",headers:e.headers}),T=Q(async e=>{let t=await ie(e);if(!t?.session)throw new j.APIError("UNAUTHORIZED");return{session:t}}),he=()=>p("/list-sessions",{method:"GET",use:[T],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)}),we=p("/revoke-session",{method:"POST",body:H.z.object({id:H.z.string()}),use:[T],requireHeaders:!0},async e=>{let t=e.body.id,r=await e.context.internalAdapter.findSession(t);if(!r)throw new j.APIError("BAD_REQUEST",{message:"Session not found"});if(r.session.userId!==e.context.session.user.id)throw new j.APIError("UNAUTHORIZED");try{await e.context.internalAdapter.deleteSession(t)}catch(o){throw e.context.logger.error(o),new j.APIError("INTERNAL_SERVER_ERROR")}return e.json({status:!0})}),be=p("/revoke-sessions",{method:"POST",use:[T],requireHeaders:!0},async e=>{try{await e.context.internalAdapter.deleteSessions(e.context.session.user.id)}catch(t){throw e.context.logger.error(t),new j.APIError("INTERNAL_SERVER_ERROR")}return e.json({status:!0})}),ye=p("/revoke-other-sessions",{method:"POST",requireHeaders:!0,use:[T]},async e=>{let t=e.context.session;if(!t.user)throw new j.APIError("UNAUTHORIZED");let i=(await e.context.internalAdapter.listSessions(t.user.id)).filter(n=>n.expiresAt>new Date).filter(n=>n.id!==e.context.session.session.id);return await Promise.all(i.map(n=>e.context.internalAdapter.deleteSession(n.id))),e.json({status:!0})});async function I(e,t,r){return await(0,ne.createJWT)("HS256",Buffer.from(e),{email:t.toLowerCase(),updateTo:r},{expiresIn:new Pt.TimeSpan(1,"h"),issuer:"better-auth",subject:"verify-email",audiences:[t],includeIssuedTimestamp:!0})}var Ae=p("/send-verification-email",{method:"POST",query:P.z.object({currentURL:P.z.string().optional()}).optional(),body:P.z.object({email:P.z.string().email(),callbackURL:P.z.string().optional()})},async e=>{if(!e.context.options.emailVerification?.sendVerificationEmail)throw e.context.logger.error("Verification email isn't enabled."),new $.APIError("BAD_REQUEST",{message:"Verification email isn't enabled"});let{email:t}=e.body,r=await e.context.internalAdapter.findUserByEmail(t);if(!r)throw new $.APIError("BAD_REQUEST",{message:"User not found"});let o=await I(e.context.secret,t),i=`${e.context.baseURL}/verify-email?token=${o}&callbackURL=${e.body.callbackURL||e.query?.currentURL||"/"}`;return await e.context.options.emailVerification.sendVerificationEmail(r.user,i,o),e.json({status:!0})}),ke=p("/verify-email",{method:"GET",query:P.z.object({token:P.z.string(),callbackURL:P.z.string().optional()})},async e=>{let{token:t}=e.query,r;try{r=await(0,ne.validateJWT)("HS256",Buffer.from(e.context.secret),t)}catch(s){throw e.context.logger.error("Failed to verify email",s),new $.APIError("BAD_REQUEST",{message:"Invalid token"})}let i=P.z.object({email:P.z.string().email(),updateTo:P.z.string().optional()}).parse(r.payload);if(!await e.context.internalAdapter.findUserByEmail(i.email))throw new $.APIError("BAD_REQUEST",{message:"User not found"});if(i.updateTo){let s=await ie(e);if(!s)throw e.query.callbackURL?e.redirect(`${e.query.callbackURL}?error=unauthorized`):new $.APIError("UNAUTHORIZED",{message:"Session not found"});if(s.user.email!==i.email)throw e.query.callbackURL?e.redirect(`${e.query.callbackURL}?error=unauthorized`):new $.APIError("UNAUTHORIZED",{message:"Invalid session"});let a=await e.context.internalAdapter.updateUserByEmail(i.email,{email:i.updateTo});if(await e.context.options.emailVerification?.sendVerificationEmail?.(a,`${e.context.baseURL}/verify-email?token=${t}`,t),e.query.callbackURL)throw e.redirect(e.query.callbackURL);return e.json({user:a,status:!0})}if(await e.context.internalAdapter.updateUserByEmail(i.email,{emailVerified:!0}),e.query.callbackURL)throw e.redirect(e.query.callbackURL);return e.json({user:null,status:!0})});async function se(e,{userInfo:t,account:r,callbackURL:o}){let i=await e.context.internalAdapter.findUserByEmail(t.email,{includeAccounts:!0}).catch(a=>{throw m.error(`Better auth was unable to query your database.
|
|
4
|
+
Error: `,a),e.redirect(`${e.context.baseURL}/error?error=internal_server_error`)}),n=i?.user;if(i){let a=i.accounts.find(d=>d.providerId===r.providerId);if(a)await e.context.internalAdapter.updateAccount(a.id,{accessToken:r.accessToken,idToken:r.idToken,refreshToken:r.refreshToken,expiresAt:r.expiresAt});else{if(!e.context.options.account?.accountLinking?.trustedProviders?.includes(r.providerId)&&!t.emailVerified||e.context.options.account?.accountLinking?.enabled===!1)return Fe&&m.warn(`User already exist but account isn't linked to ${r.providerId}. To read more about how account linking works in Better Auth see https://www.better-auth.com/docs/concepts/users-accounts#account-linking.`),{error:"account not linked",data:null};try{await e.context.internalAdapter.linkAccount({providerId:r.providerId,accountId:t.id.toString(),id:e.context.uuid(),userId:i.user.id,accessToken:r.accessToken,idToken:r.idToken,refreshToken:r.refreshToken,expiresAt:r.expiresAt})}catch(l){return m.error("Unable to link account",l),{error:"unable to link account",data:null}}}}else try{let a=t.emailVerified||!1;if(n=await e.context.internalAdapter.createOAuthUser({...t,emailVerified:a},{accessToken:r.accessToken,idToken:r.idToken,refreshToken:r.refreshToken,expiresAt:r.expiresAt,providerId:r.providerId,accountId:t.id.toString()}).then(d=>d?.user),!a&&n&&e.context.options.emailVerification?.sendOnSignUp){let d=await I(e.context.secret,n.email),c=`${e.context.baseURL}/verify-email?token=${d}&callbackURL=${o}`;await e.context.options.emailVerification?.sendVerificationEmail?.(n,c,d)}}catch(a){return m.error("Unable to create user",a),{error:"unable to create user",data:null}}if(!n)return{error:"unable to create user",data:null};let s=await e.context.internalAdapter.createSession(n.id,e.request);return s?{data:{session:s,user:n},error:null}:{error:"unable to create session",data:null}}var Re=p("/sign-in/social",{method:"POST",query:k.z.object({currentURL:k.z.string().optional()}).optional(),body:k.z.object({callbackURL:k.z.string().optional(),provider:k.z.enum(re),idToken:k.z.optional(k.z.object({token:k.z.string(),nonce:k.z.string().optional(),accessToken:k.z.string().optional(),refreshToken:k.z.string().optional(),expiresAt:k.z.number().optional()}))})},async e=>{let t=e.context.socialProviders.find(n=>n.id===e.body.provider);if(!t)throw e.context.logger.error("Provider not found. Make sure to add the provider in your auth config",{provider:e.body.provider}),new v.APIError("NOT_FOUND",{message:"Provider not found"});if(e.body.idToken){if(!t.verifyIdToken)throw e.context.logger.error("Provider does not support id token verification",{provider:e.body.provider}),new v.APIError("NOT_FOUND",{message:"Provider does not support id token verification"});let{token:n,nonce:s}=e.body.idToken;if(!await t.verifyIdToken(n,s))throw e.context.logger.error("Invalid id token",{provider:e.body.provider}),new v.APIError("UNAUTHORIZED",{message:"Invalid id token"});let d=await t.getUserInfo({idToken:n,accessToken:e.body.idToken.accessToken,refreshToken:e.body.idToken.refreshToken});if(!d||!d?.user)throw e.context.logger.error("Failed to get user info",{provider:e.body.provider}),new v.APIError("UNAUTHORIZED",{message:"Failed to get user info"});if(!d.user.email)throw e.context.logger.error("User email not found",{provider:e.body.provider}),new v.APIError("UNAUTHORIZED",{message:"User email not found"});let c=await se(e,{userInfo:{email:d.user.email,id:d.user.id,name:d.user.name||"",image:d.user.image,emailVerified:d.user.emailVerified||!1},account:{providerId:t.id,accountId:d.user.id,accessToken:e.body.idToken.accessToken}});if(c.error)throw new v.APIError("UNAUTHORIZED",{message:c.error});return await x(e,c.data),e.json({session:c.data.session,user:c.data.user,url:`${e.body.callbackURL||e.query?.currentURL||e.context.options.baseURL}`,redirect:!0})}let{codeVerifier:r,state:o}=await X(e),i=await t.createAuthorizationURL({state:o,codeVerifier:r,redirectURI:`${e.context.baseURL}/callback/${t.id}`});return e.json({url:i.toString(),redirect:!0})}),Ue=p("/sign-in/email",{method:"POST",body:k.z.object({email:k.z.string(),password:k.z.string(),callbackURL:k.z.string().optional(),dontRememberMe:k.z.boolean().default(!1).optional()})},async e=>{if(!e.context.options?.emailAndPassword?.enabled)throw e.context.logger.error("Email and password is not enabled. Make sure to enable it in the options on you `auth.ts` file. Check `https://better-auth.com/docs/authentication/email-password` for more!"),new v.APIError("BAD_REQUEST",{message:"Email and password is not enabled"});let{email:t,password:r}=e.body;if(!k.z.string().email().safeParse(t).success)throw new v.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 v.APIError("UNAUTHORIZED",{message:"Invalid email or password"});let n=i.accounts.find(c=>c.providerId==="credential");if(!n)throw e.context.logger.error("Credential account not found",{email:t}),new v.APIError("UNAUTHORIZED",{message:"Invalid email or password"});let s=n?.password;if(!s)throw e.context.logger.error("Password not found",{email:t}),new v.APIError("UNAUTHORIZED",{message:"Unexpected error"});if(!await e.context.password.verify(s,r))throw e.context.logger.error("Invalid password"),new v.APIError("UNAUTHORIZED",{message:"Invalid email or password"});if(e.context.options?.emailAndPassword?.requireEmailVerification&&!i.user.emailVerified){if(!e.context.options?.emailVerification?.sendVerificationEmail)throw m.error("Email verification is required but no email verification handler is provided"),new v.APIError("INTERNAL_SERVER_ERROR",{message:"Email is not verified."});let c=await I(e.context.secret,i.user.email),l=`${e.context.options.baseURL}/verify-email?token=${c}`;throw await e.context.options.emailVerification.sendVerificationEmail(i.user,l,c),e.context.logger.error("Email not verified",{email:t}),new v.APIError("FORBIDDEN",{message:"Email is not verified. Check your email for a verification link"})}let d=await e.context.internalAdapter.createSession(i.user.id,e.headers,e.body.dontRememberMe);if(!d)throw e.context.logger.error("Failed to create session"),new v.APIError("UNAUTHORIZED",{message:"Failed to create session"});return await x(e,{session:d,user:i.user},e.body.dontRememberMe),e.json({user:i.user,session:d,redirect:!!e.body.callbackURL,url:e.body.callbackURL})});var J=require("zod");var h=require("zod"),Oi=h.z.object({id:h.z.string(),providerId:h.z.string(),accountId:h.z.string(),userId:h.z.string(),accessToken:h.z.string().nullable().optional(),refreshToken:h.z.string().nullable().optional(),idToken:h.z.string().nullable().optional(),expiresAt:h.z.date().nullable().optional(),password:h.z.string().optional().nullable()}),Ii=h.z.object({id:h.z.string(),email:h.z.string().transform(e=>e.toLowerCase()),emailVerified:h.z.boolean().default(!1),name:h.z.string(),image:h.z.string().optional(),createdAt:h.z.date().default(new Date),updatedAt:h.z.date().default(new Date)}),Si=h.z.object({id:h.z.string(),userId:h.z.string(),expiresAt:h.z.date(),ipAddress:h.z.string().optional(),userAgent:h.z.string().optional()}),Li=h.z.object({id:h.z.string(),value:h.z.string(),expiresAt:h.z.date(),identifier:h.z.string()});function Yt(e,t){let r={...t==="user"?e.user?.additionalFields:{},...t==="session"?e.session?.additionalFields:{}};for(let o of e.plugins||[])o.schema&&o.schema[t]&&(r={...r,...o.schema[t].fields});return r}function Xt(e,t){let r=t.action||"create",o=t.fields,i={};for(let n in o){if(n in e){if(o[n].input===!1){if(o[n].defaultValue){i[n]=o[n].defaultValue;continue}continue}i[n]=e[n];continue}if(o[n].defaultValue&&r==="create"){i[n]=o[n].defaultValue;continue}}return i}function ae(e,t,r){let o=Yt(e,"user");return Xt(t||{},{fields:o,action:r})}var ve=p("/callback/:id",{method:"GET",query:J.z.object({state:J.z.string(),code:J.z.string().optional(),error:J.z.string().optional()}),metadata:F},async e=>{if(!e.query.code)throw e.redirect(`${e.context.baseURL}/error?error=${e.query.error||"no_code"}`);let t=e.context.socialProviders.find(y=>y.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{codeVerifier:r,callbackURL:o,link:i,errorURL:n}=await Ge(e),s;try{s=await t.validateAuthorizationCode({code:e.query.code,codeVerifier:r,redirectURI:`${e.context.baseURL}/callback/${t.id}`})}catch(y){throw e.context.logger.error(y),e.redirect(`${e.context.baseURL}/error?error=please_restart_the_process`)}let a=await t.getUserInfo(s).then(y=>y?.user),c={id:qe(),...a};function l(y){let w=n||o||`${e.context.baseURL}/error`;throw w.includes("?")?w=`${w}&error=${y}`:w=`${w}?error=${y}`,e.redirect(w)}if(!a)return m.error("Unable to get user info"),l("unable_to_get_user_info");if(!c.email)return e.context.logger.error("Provider did not return email. This could be due to misconfiguration in the provider settings."),l("email_not_found");if(!o)throw m.error("No callback URL found"),e.redirect(`${e.context.baseURL}/error?error=please_restart_the_process`);if(i){if(i.email!==c.email.toLowerCase())return l("email_doesn't_match");if(!await e.context.internalAdapter.createAccount({userId:i.userId,providerId:t.id,accountId:a.id}))return l("unable_to_link_account");let w;try{w=new URL(o).toString()}catch{w=o}throw e.redirect(w)}let f=await se(e,{userInfo:{email:c.email,id:c.id,name:c.name||"",image:c.image,emailVerified:c.emailVerified||!1},account:{providerId:t.id,accountId:a.id,accessToken:s.accessToken,refreshToken:s.refreshToken,expiresAt:s.accessTokenExpiresAt},callbackURL:o});if(f.error)return l(f.error.split(" ").join("_"));let{session:g,user:u}=f.data;await x(e,{session:g,user:u});let R;try{R=new URL(o).toString()}catch{R=o}throw e.redirect(R)});var Hi=require("zod");var Ot=require("better-call"),Ee=p("/sign-out",{method:"POST",requireHeaders:!0},async e=>{let t=await e.getSignedCookie(e.context.authCookies.sessionToken.name,e.context.secret);if(!t)throw new Ot.APIError("BAD_REQUEST",{message:"Session not found"});return await e.context.internalAdapter.deleteSession(t),B(e),e.json({success:!0})});var O=require("zod");var W=require("better-call");function It(e,t,r){let o=t?new URL(t,e.baseURL):new URL(`${e.baseURL}/error`);return r&&Object.entries(r).forEach(([i,n])=>o.searchParams.set(i,n)),o.href}function er(e,t,r){let o=new URL(t,e.baseURL);return r&&Object.entries(r).forEach(([i,n])=>o.searchParams.set(i,n)),o.href}var _e=p("/forget-password",{method:"POST",body:O.z.object({email:O.z.string().email(),redirectTo:O.z.string()})},async e=>{if(!e.context.options.emailAndPassword?.sendResetPassword)throw e.context.logger.error("Reset password isn't enabled.Please pass an emailAndPassword.sendResetPasswordToken function in your auth config!"),new W.APIError("BAD_REQUEST",{message:"Reset password isn't enabled"});let{email:t,redirectTo:r}=e.body,o=await e.context.internalAdapter.findUserByEmail(t,{includeAccounts:!0});if(!o)return e.context.logger.error("Reset Password: User not found",{email:t}),e.json({status:!1},{body:{status:!0}});let i=60*60*1,n=new Date(Date.now()+1e3*(e.context.options.emailAndPassword.resetPasswordTokenExpiresIn||i)),s=e.context.uuid();await e.context.internalAdapter.createVerificationValue({value:o.user.id,identifier:`reset-password:${s}`,expiresAt:n});let a=`${e.context.baseURL}/reset-password/${s}?callbackURL=${r}`;return await e.context.options.emailAndPassword.sendResetPassword(o.user,a),e.json({status:!0})}),Te=p("/reset-password/:token",{method:"GET",query:O.z.object({callbackURL:O.z.string()})},async e=>{let{token:t}=e.params,{callbackURL:r}=e.query;if(!t||!r)throw e.redirect(It(e.context,r,{error:"INVALID_TOKEN"}));let o=await e.context.internalAdapter.findVerificationValue(`reset-password:${t}`);throw!o||o.expiresAt<new Date?e.redirect(It(e.context,r,{error:"INVALID_TOKEN"})):e.redirect(er(e.context,r,{token:t}))}),xe=p("/reset-password",{query:O.z.optional(O.z.object({token:O.z.string().optional(),currentURL:O.z.string().optional()})),method:"POST",body:O.z.object({newPassword:O.z.string()})},async e=>{let t=e.query?.token||(e.query?.currentURL?new URL(e.query.currentURL).searchParams.get("token"):"");if(!t)throw new W.APIError("BAD_REQUEST",{message:"Token not found"});let{newPassword:r}=e.body,o=`reset-password:${t}`,i=await e.context.internalAdapter.findVerificationValue(o);if(!i||i.expiresAt<new Date)throw new W.APIError("BAD_REQUEST",{message:"Invalid token"});await e.context.internalAdapter.deleteVerificationValue(i.id);let n=i.value,s=await e.context.password.hash(r);if(!(await e.context.internalAdapter.findAccounts(n)).find(l=>l.providerId==="credential"))return await e.context.internalAdapter.createAccount({userId:n,providerId:"credential",password:s,accountId:e.context.uuid()}),e.json({status:!0});if(!await e.context.internalAdapter.updatePassword(n,s))throw new W.APIError("BAD_REQUEST",{message:"Failed to update password"});return e.json({status:!0})});var U=require("zod");var E=require("better-call");var Pe=()=>p("/update-user",{method:"POST",body:U.z.record(U.z.string(),U.z.any()),use:[T]},async e=>{let t=e.body;if(t.email)throw new E.APIError("BAD_REQUEST",{message:"You can't update email"});let{name:r,image:o,...i}=t,n=e.context.session;if(!o&&!r&&Object.keys(i).length===0)return e.json({user:n.user});let s=ae(e.context.options,i,"update"),a=await e.context.internalAdapter.updateUserByEmail(n.user.email,{name:r,image:o,...s});return await x(e,{session:n.session,user:a}),e.json({user:a})}),Oe=p("/change-password",{method:"POST",body:U.z.object({newPassword:U.z.string(),currentPassword:U.z.string(),revokeOtherSessions:U.z.boolean().optional()}),use:[T]},async e=>{let{newPassword:t,currentPassword:r,revokeOtherSessions:o}=e.body,i=e.context.session,n=e.context.password.config.minPasswordLength;if(t.length<n)throw e.context.logger.error("Password is too short"),new E.APIError("BAD_REQUEST",{message:"Password is too short"});let s=e.context.password.config.maxPasswordLength;if(t.length>s)throw e.context.logger.error("Password is too long"),new E.APIError("BAD_REQUEST",{message:"Password too long"});let d=(await e.context.internalAdapter.findAccounts(i.user.id)).find(f=>f.providerId==="credential"&&f.password);if(!d||!d.password)throw new E.APIError("BAD_REQUEST",{message:"User does not have a password"});let c=await e.context.password.hash(t);if(!await e.context.password.verify(d.password,r))throw new E.APIError("BAD_REQUEST",{message:"Incorrect password"});if(await e.context.internalAdapter.updateAccount(d.id,{password:c}),o){await e.context.internalAdapter.deleteSessions(i.user.id);let f=await e.context.internalAdapter.createSession(i.user.id,e.headers);if(!f)throw new E.APIError("INTERNAL_SERVER_ERROR",{message:"Unable to create session"});await x(e,{session:f,user:i.user})}return e.json(i.user)}),Ie=p("/set-password",{method:"POST",body:U.z.object({newPassword:U.z.string()}),metadata:{SERVER_ONLY:!0},use:[T]},async e=>{let{newPassword:t}=e.body,r=e.context.session,o=e.context.password.config.minPasswordLength;if(t.length<o)throw e.context.logger.error("Password is too short"),new E.APIError("BAD_REQUEST",{message:"Password is too short"});let i=e.context.password.config.maxPasswordLength;if(t.length>i)throw e.context.logger.error("Password is too long"),new E.APIError("BAD_REQUEST",{message:"Password too long"});let s=(await e.context.internalAdapter.findAccounts(r.user.id)).find(d=>d.providerId==="credential"&&d.password),a=await e.context.password.hash(t);if(!s)return await e.context.internalAdapter.linkAccount({userId:r.user.id,providerId:"credential",accountId:r.user.id,password:a}),e.json(r.user);throw new E.APIError("BAD_REQUEST",{message:"user already has a password"})}),Se=p("/delete-user",{method:"POST",body:U.z.object({password:U.z.string()}),use:[T]},async e=>{let{password:t}=e.body,r=e.context.session,i=(await e.context.internalAdapter.findAccounts(r.user.id)).find(s=>s.providerId==="credential"&&s.password);if(!i||!i.password)throw new E.APIError("BAD_REQUEST",{message:"User does not have a password"});if(!await e.context.password.verify(i.password,t))throw new E.APIError("BAD_REQUEST",{message:"Incorrect password"});return await e.context.internalAdapter.deleteUser(r.user.id),await e.context.internalAdapter.deleteSessions(r.user.id),B(e),e.json(null)}),Le=p("/change-email",{method:"POST",query:U.z.object({currentURL:U.z.string().optional()}).optional(),body:U.z.object({newEmail:U.z.string().email(),callbackURL:U.z.string().optional()}),use:[T]},async e=>{if(!e.context.options.user?.changeEmail?.enabled)throw e.context.logger.error("Change email is disabled."),new E.APIError("BAD_REQUEST",{message:"Change email is disabled"});if(e.body.newEmail===e.context.session.user.email)throw e.context.logger.error("Email is the same"),new E.APIError("BAD_REQUEST",{message:"Email is the same"});if(await e.context.internalAdapter.findUserByEmail(e.body.newEmail))throw e.context.logger.error("Email already exists"),new E.APIError("BAD_REQUEST",{message:"Couldn't update your email"});if(e.context.session.user.emailVerified!==!0){let i=await e.context.internalAdapter.updateUserByEmail(e.context.session.user.email,{email:e.body.newEmail});return e.json({user:i,status:!0})}if(!e.context.options.user.changeEmail.sendChangeEmailVerification)throw e.context.logger.error("Verification email isn't enabled."),new E.APIError("BAD_REQUEST",{message:"Verification email isn't enabled"});let r=await I(e.context.secret,e.context.session.user.email,e.body.newEmail),o=`${e.context.baseURL}/verify-email?token=${r}&callbackURL=${e.body.callbackURL||e.query?.currentURL||"/"}`;return await e.context.options.user.changeEmail.sendChangeEmailVerification(e.context.session.user,e.body.newEmail,o,r),e.json({user:null,status:!0})});var tr=(e="Unknown")=>`<!DOCTYPE html>
|
|
5
5
|
<html lang="en">
|
|
6
6
|
<head>
|
|
7
7
|
<meta charset="UTF-8">
|
|
@@ -81,4 +81,4 @@ Error: `,w),e.redirect(`${e.context.baseURL}/error?error=internal_server_error`)
|
|
|
81
81
|
<div class="error-code">Error Code: <span id="errorCode">${e}</span></div>
|
|
82
82
|
</div>
|
|
83
83
|
</body>
|
|
84
|
-
</html>`,
|
|
84
|
+
</html>`,Ce=p("/error",{method:"GET",metadata:F},async e=>{let t=new URL(e.request?.url||"").searchParams.get("error")||"Unknown";return new Response(tr(t),{headers:{"Content-Type":"text/html"}})});var Be=p("/ok",{method:"GET",metadata:F},async e=>e.json({ok:!0}));var q=require("zod");var S=require("better-call");var De=()=>p("/sign-up/email",{method:"POST",query:q.z.object({currentURL:q.z.string().optional()}).optional(),body:q.z.record(q.z.string(),q.z.any())},async e=>{if(!e.context.options.emailAndPassword?.enabled)throw new S.APIError("BAD_REQUEST",{message:"Email and password sign up is not enabled"});let t=e.body,{name:r,email:o,password:i,image:n,callbackURL:s,...a}=t;if(!q.z.string().email().safeParse(o).success)throw new S.APIError("BAD_REQUEST",{message:"Invalid email"});let c=e.context.password.config.minPasswordLength;if(i.length<c)throw e.context.logger.error("Password is too short"),new S.APIError("BAD_REQUEST",{message:"Password is too short"});let l=e.context.password.config.maxPasswordLength;if(i.length>l)throw e.context.logger.error("Password is too long"),new S.APIError("BAD_REQUEST",{message:"Password is too long"});if((await e.context.internalAdapter.findUserByEmail(o))?.user)throw e.context.logger.info(`Sign-up attempt for existing email: ${o}`),new S.APIError("UNPROCESSABLE_ENTITY",{message:"User with this email already exists"});let g=ae(e.context.options,a),u;try{if(u=await e.context.internalAdapter.createUser({email:o.toLowerCase(),name:r,image:n,...g,emailVerified:!1}),!u)throw new S.APIError("BAD_REQUEST",{message:"Failed to create user"})}catch(w){throw m.error("Failed to create user",w),new S.APIError("UNPROCESSABLE_ENTITY",{message:"Failed to create user",details:w})}if(!u)throw new S.APIError("UNPROCESSABLE_ENTITY",{message:"Failed to create user"});let R=await e.context.password.hash(i);if(await e.context.internalAdapter.linkAccount({userId:u.id,providerId:"credential",accountId:u.id,password:R,expiresAt:C(60*60*24*30,"sec")}),e.context.options.emailVerification?.sendOnSignUp){let w=await I(e.context.secret,u.email),_=`${e.context.baseURL}/verify-email?token=${w}&callbackURL=${t.callbackURL||e.query?.currentURL||"/"}`;await e.context.options.emailVerification?.sendVerificationEmail?.(u,_,w)}if(!e.context.options.emailAndPassword.autoSignIn||e.context.options.emailAndPassword.requireEmailVerification)return e.json({user:u,session:null},{body:t.callbackURL?{url:t.callbackURL,redirect:!0}:{user:u,session:null}});let y=await e.context.internalAdapter.createSession(u.id,e.request);if(!y)throw new S.APIError("BAD_REQUEST",{message:"Failed to create session"});return await x(e,{session:y,user:u}),e.json({user:u,session:y})});var G=require("zod");var Ve=require("better-call");var ze=p("/list-accounts",{method:"GET",use:[T]},async e=>{let t=e.context.session,r=await e.context.internalAdapter.findAccounts(t.user.id);return e.json(r.map(o=>({id:o.id,provider:o.providerId})))}),je=p("/link-social",{method:"POST",requireHeaders:!0,query:G.z.object({currentURL:G.z.string().optional()}).optional(),body:G.z.object({callbackURL:G.z.string().optional(),provider:G.z.enum(re)}),use:[T]},async e=>{let t=e.context.session;if((await e.context.internalAdapter.findAccounts(t.user.id)).find(a=>a.providerId===e.body.provider))throw new Ve.APIError("BAD_REQUEST",{message:"Social Account is already linked."});let i=e.context.socialProviders.find(a=>a.id===e.body.provider);if(!i)throw e.context.logger.error("Provider not found. Make sure to add the provider in your auth config",{provider:e.body.provider}),new Ve.APIError("NOT_FOUND",{message:"Provider not found"});let n=await X(e,{userId:t.user.id,email:t.user.email}),s=await i.createAuthorizationURL({state:n.state,codeVerifier:n.codeVerifier,redirectURI:`${e.context.baseURL}/callback/${i.id}`});return e.json({url:s.toString(),redirect:!0})});function St(e,t){if(t.advanced?.ipAddress?.disableIpTracking)return null;let r="127.0.0.1";if(Me)return r;let i=t.advanced?.ipAddress?.ipAddressHeaders||["x-client-ip","x-forwarded-for","cf-connecting-ip","fastly-client-ip","x-real-ip","x-cluster-client-ip","x-forwarded","forwarded-for","forwarded"],n=e instanceof Request?e.headers:e;for(let s of i){let a=n.get(s);if(typeof a=="string"){let d=a.split(",")[0].trim();if(d)return d}}return null}function rr(e,t,r){let o=Date.now(),i=t*1e3;return o-r.lastRequest<i&&r.count>=e}function or(e){return new Response(JSON.stringify({message:"Too many requests. Please try again later."}),{status:429,statusText:"Too Many Requests",headers:{"X-Retry-After":e.toString()}})}function ir(e,t){let r=Date.now(),o=t*1e3;return Math.ceil((e+o-r)/1e3)}function nr(e,t){let r=t??"rateLimit",o=e.adapter;return{get:async i=>await o.findOne({model:r,where:[{field:"key",value:i}]}),set:async(i,n,s)=>{try{s?await o.update({model:t??"rateLimit",where:[{field:"key",value:i}],update:{count:n.count,lastRequest:n.lastRequest}}):await o.create({model:t??"rateLimit",data:{key:i,count:n.count,lastRequest:n.lastRequest}})}catch(a){m.error("Error setting rate limit",a)}}}}var Lt=new Map;function sr(e){return e.rateLimit.storage==="secondary-storage"?{get:async r=>{let o=await e.options.secondaryStorage?.get(r);return o?JSON.parse(o):void 0},set:async(r,o)=>{await e.options.secondaryStorage?.set?.(r,JSON.stringify(o))}}:e.rateLimit.storage==="memory"?{async get(r){return Lt.get(r)},async set(r,o,i){Lt.set(r,o)}}:nr(e,e.rateLimit.tableName)}async function Ct(e,t){if(!t.rateLimit.enabled)return;let r=t.baseURL,o=e.url.replace(r,""),i=t.rateLimit.window,n=t.rateLimit.max,s=St(e,t.options)+o,d=ar().find(g=>g.pathMatcher(o));d&&(i=d.window,n=d.max);for(let g of t.options.plugins||[])if(g.rateLimit){let u=g.rateLimit.find(R=>R.pathMatcher(o));if(u){i=u.window,n=u.max;break}}if(t.rateLimit.customRules){let g=t.rateLimit.customRules[o];g&&(i=g.window,n=g.max)}let c=sr(t),l=await c.get(s),f=Date.now();if(!l)await c.set(s,{key:s,count:1,lastRequest:f});else{let g=f-l.lastRequest;if(rr(n,i,l)){let u=ir(l.lastRequest,i);return or(u)}else g>i*1e3?await c.set(s,{...l,count:1,lastRequest:f}):await c.set(s,{...l,count:l.count+1,lastRequest:f})}}function ar(){return[{pathMatcher(t){return t.startsWith("/sign-in")||t.startsWith("/sign-up")||t.startsWith("/change-password")||t.startsWith("/change-email")},window:10,max:3}]}var Dt=require("better-call");function Bt(e,t){let r=t.plugins?.reduce((a,d)=>({...a,...d.endpoints}),{}),o=t.plugins?.map(a=>a.middlewares?.map(d=>{let c=async l=>d.middleware({...l,context:{...e,...l.context}});return c.path=d.path,c.options=d.middleware.options,c.headers=d.middleware.headers,{path:d.path,middleware:c}})).filter(a=>a!==void 0).flat()||[],n={...{signInSocial:Re,callbackOAuth:ve,getSession:oe(),signOut:Ee,signUpEmail:De(),signInEmail:Ue,forgetPassword:_e,resetPassword:xe,verifyEmail:ke,sendVerificationEmail:Ae,changeEmail:Le,changePassword:Oe,setPassword:Ie,updateUser:Pe(),deleteUser:Se,forgetPasswordCallback:Te,listSessions:he(),revokeSession:we,revokeSessions:be,revokeOtherSessions:ye,linkSocialAccount:je,listUserAccounts:ze},...r,ok:Be,error:Ce},s={};for(let[a,d]of Object.entries(n))s[a]=async(c={})=>{let l=await e;for(let u of t.plugins||[])if(u.hooks?.before){for(let R of u.hooks.before)if(R.matcher({...d,...c,context:l})){let w=await R.handler({...c,context:{...l,...c?.context}});w&&"context"in w&&(l={...l,...w.context})}}let f;try{f=await d({...c,context:{...l,...c.context}})}catch(u){if(u instanceof N.APIError){let R=t.plugins?.map(_=>{if(_.hooks?.after)return _.hooks.after}).filter(_=>_!==void 0).flat();if(!R?.length)throw u;let y=new Response(JSON.stringify(u.body),{status:N.statusCode[u.status],headers:u.headers}),w;for(let _ of R||[])if(_.matcher(c)){let Vt=Object.assign(c,{context:{...e,returned:y}}),de=await _.handler(Vt);de&&"response"in de&&(w=de.response)}if(w instanceof Response)return w;throw u}throw u}let g=f;for(let u of t.plugins||[])if(u.hooks?.after){for(let R of u.hooks.after)if(R.matcher(c)){let w=Object.assign(c,{context:{...e,returned:g}}),_=await R.handler(w);_&&"response"in _&&(g=_.response)}}return g},s[a].path=d.path,s[a].method=d.method,s[a].options=d.options,s[a].headers=d.headers;return{api:s,middlewares:o}}var dr=(e,t)=>{let{api:r,middlewares:o}=Bt(e,t),i=new URL(e.baseURL).pathname;return(0,N.createRouter)(r,{extraContext:e,basePath:i,routerMiddleware:[{path:"/**",middleware:me},...o],async onRequest(n){for(let s of e.options.plugins||[])if(s.onRequest){let a=await s.onRequest(n,e);if(a&&"response"in a)return a.response}return Ct(n,e)},async onResponse(n){for(let s of e.options.plugins||[])if(s.onResponse){let a=await s.onResponse(n,e);if(a)return a.response}return n},onError(n){if(t.onAPIError?.throw)throw n;if(t.onAPIError?.onError){t.onAPIError.onError(n,e);return}let s=t.logger?.verboseLogging?m:void 0;t.logger?.disabled!==!0&&(n instanceof N.APIError?(n.status==="INTERNAL_SERVER_ERROR"&&m.error(n),s?.error(n.message)):m?.error(n))}})};0&&(module.exports={APIError,callbackOAuth,changeEmail,changePassword,createAuthEndpoint,createAuthMiddleware,createEmailVerificationToken,deleteUser,error,forgetPassword,forgetPasswordCallback,getEndpoints,getSession,getSessionFromCtx,linkSocialAccount,listSessions,listUserAccounts,ok,optionsMiddleware,originCheckMiddleware,resetPassword,revokeOtherSessions,revokeSession,revokeSessions,router,sendVerificationEmail,sessionMiddleware,setPassword,signInEmail,signInSocial,signOut,signUpEmail,updateUser,verifyEmail});
|
package/dist/api.d.cts
CHANGED
|
@@ -1,7 +1,8 @@
|
|
|
1
|
-
export {
|
|
1
|
+
export { y as AuthEndpoint, z as AuthMiddleware, a3 as callbackOAuth, am as changeEmail, aj as changePassword, x as createAuthEndpoint, w as createAuthMiddleware, af as createEmailVerificationToken, al as deleteUser, an as error, ac as forgetPassword, ad as forgetPasswordCallback, $ as getEndpoints, a4 as getSession, a5 as getSessionFromCtx, ar as linkSocialAccount, a7 as listSessions, aq as listUserAccounts, ao as ok, v as optionsMiddleware, as as originCheckMiddleware, ae as resetPassword, aa as revokeOtherSessions, a8 as revokeSession, a9 as revokeSessions, a0 as router, ag as sendVerificationEmail, a6 as sessionMiddleware, ak as setPassword, a2 as signInEmail, a1 as signInSocial, ab as signOut, ap as signUpEmail, ai as updateUser, ah as verifyEmail } from './auth-CRDJtWaN.cjs';
|
|
2
2
|
import './helper-DPDj8Nix.cjs';
|
|
3
3
|
export { APIError } from 'better-call';
|
|
4
4
|
import 'zod';
|
|
5
5
|
import 'kysely';
|
|
6
|
-
import './index-
|
|
6
|
+
import './index-cqC7BcV_.cjs';
|
|
7
|
+
import 'jose';
|
|
7
8
|
import 'better-sqlite3';
|
package/dist/api.d.ts
CHANGED
|
@@ -1,7 +1,8 @@
|
|
|
1
|
-
export {
|
|
1
|
+
export { y as AuthEndpoint, z as AuthMiddleware, a3 as callbackOAuth, am as changeEmail, aj as changePassword, x as createAuthEndpoint, w as createAuthMiddleware, af as createEmailVerificationToken, al as deleteUser, an as error, ac as forgetPassword, ad as forgetPasswordCallback, $ as getEndpoints, a4 as getSession, a5 as getSessionFromCtx, ar as linkSocialAccount, a7 as listSessions, aq as listUserAccounts, ao as ok, v as optionsMiddleware, as as originCheckMiddleware, ae as resetPassword, aa as revokeOtherSessions, a8 as revokeSession, a9 as revokeSessions, a0 as router, ag as sendVerificationEmail, a6 as sessionMiddleware, ak as setPassword, a2 as signInEmail, a1 as signInSocial, ab as signOut, ap as signUpEmail, ai as updateUser, ah as verifyEmail } from './auth-DP-ZFlGK.js';
|
|
2
2
|
import './helper-DPDj8Nix.js';
|
|
3
3
|
export { APIError } from 'better-call';
|
|
4
4
|
import 'zod';
|
|
5
5
|
import 'kysely';
|
|
6
|
-
import './index-
|
|
6
|
+
import './index-DN9ozDRm.js';
|
|
7
|
+
import 'jose';
|
|
7
8
|
import 'better-sqlite3';
|