better-auth 0.7.1 → 0.7.2-beta.2
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/adapters/drizzle.d.cts +2 -2
- package/dist/adapters/drizzle.d.ts +2 -2
- package/dist/adapters/kysely.d.cts +2 -2
- package/dist/adapters/kysely.d.ts +2 -2
- package/dist/adapters/mongodb.cjs +1 -1
- package/dist/adapters/mongodb.d.cts +2 -11
- package/dist/adapters/mongodb.d.ts +2 -11
- package/dist/adapters/mongodb.js +1 -1
- package/dist/adapters/prisma.d.cts +2 -2
- package/dist/adapters/prisma.d.ts +2 -2
- package/dist/api.cjs +1 -1
- package/dist/api.d.cts +2 -2
- package/dist/api.d.ts +2 -2
- package/dist/api.js +1 -1
- package/dist/{auth-Dmar8nso.d.ts → auth-BYO4oVzl.d.cts} +55 -55
- package/dist/{auth-OD4ZDXz2.d.cts → auth-Dhq27-3h.d.ts} +55 -55
- package/dist/client/plugins.d.cts +4 -4
- package/dist/client/plugins.d.ts +4 -4
- package/dist/client.d.cts +2 -2
- package/dist/client.d.ts +2 -2
- package/dist/cookies.d.cts +2 -2
- package/dist/cookies.d.ts +2 -2
- package/dist/db.d.cts +3 -3
- package/dist/db.d.ts +3 -3
- package/dist/{index-C7kiIRhi.d.ts → index-CoWW39cW.d.ts} +8 -8
- package/dist/{index-CKjjG4Ha.d.cts → index-D2xgatRc.d.cts} +8 -8
- package/dist/index.cjs +1 -1
- package/dist/index.d.cts +3 -3
- package/dist/index.d.ts +3 -3
- package/dist/index.js +1 -1
- package/dist/node.d.cts +2 -2
- package/dist/node.d.ts +2 -2
- package/dist/oauth2.d.cts +4 -4
- package/dist/oauth2.d.ts +4 -4
- package/dist/plugins.cjs +1 -1
- package/dist/plugins.d.cts +4 -4
- package/dist/plugins.d.ts +4 -4
- package/dist/plugins.js +1 -1
- package/dist/react.d.cts +2 -2
- package/dist/react.d.ts +2 -2
- package/dist/social.d.cts +1 -1
- package/dist/social.d.ts +1 -1
- package/dist/solid-start.d.cts +2 -2
- package/dist/solid-start.d.ts +2 -2
- package/dist/solid.d.cts +2 -2
- package/dist/solid.d.ts +2 -2
- package/dist/{state-R6SxX42I.d.cts → state-B5cXxYBw.d.cts} +1 -1
- package/dist/{state-BsZ0OxLG.d.ts → state-DKkih1Nb.d.ts} +1 -1
- package/dist/svelte-kit.d.cts +2 -2
- package/dist/svelte-kit.d.ts +2 -2
- package/dist/svelte.d.cts +2 -2
- package/dist/svelte.d.ts +2 -2
- package/dist/types.d.cts +4 -4
- package/dist/types.d.ts +4 -4
- package/dist/vue.d.cts +2 -2
- package/dist/vue.d.ts +2 -2
- package/package.json +1 -1
- package/dist/{index-DGElGUbq.d.cts → index-DUqGSAH3.d.cts} +4 -4
- package/dist/{index-DGElGUbq.d.ts → index-DUqGSAH3.d.ts} +4 -4
|
@@ -1,8 +1,8 @@
|
|
|
1
|
-
import { A as Adapter } from '../auth-
|
|
1
|
+
import { A as Adapter } from '../auth-BYO4oVzl.cjs';
|
|
2
2
|
import 'node_modules/better-call/dist/router-Bn7zn81P';
|
|
3
3
|
import 'zod';
|
|
4
4
|
import 'kysely';
|
|
5
|
-
import '../index-
|
|
5
|
+
import '../index-DUqGSAH3.cjs';
|
|
6
6
|
import 'better-call';
|
|
7
7
|
import 'better-sqlite3';
|
|
8
8
|
|
|
@@ -1,8 +1,8 @@
|
|
|
1
|
-
import { A as Adapter } from '../auth-
|
|
1
|
+
import { A as Adapter } from '../auth-Dhq27-3h.js';
|
|
2
2
|
import 'node_modules/better-call/dist/router-Bn7zn81P';
|
|
3
3
|
import 'zod';
|
|
4
4
|
import 'kysely';
|
|
5
|
-
import '../index-
|
|
5
|
+
import '../index-DUqGSAH3.js';
|
|
6
6
|
import 'better-call';
|
|
7
7
|
import 'better-sqlite3';
|
|
8
8
|
|
|
@@ -1,8 +1,8 @@
|
|
|
1
1
|
import { Kysely } from 'kysely';
|
|
2
|
-
import { e as BetterAuthOptions, K as KyselyDatabaseType, F as FieldAttribute, A as Adapter } from '../auth-
|
|
2
|
+
import { e as BetterAuthOptions, K as KyselyDatabaseType, F as FieldAttribute, A as Adapter } from '../auth-BYO4oVzl.cjs';
|
|
3
3
|
import 'node_modules/better-call/dist/router-Bn7zn81P';
|
|
4
4
|
import 'zod';
|
|
5
|
-
import '../index-
|
|
5
|
+
import '../index-DUqGSAH3.cjs';
|
|
6
6
|
import 'better-call';
|
|
7
7
|
import 'better-sqlite3';
|
|
8
8
|
|
|
@@ -1,8 +1,8 @@
|
|
|
1
1
|
import { Kysely } from 'kysely';
|
|
2
|
-
import { e as BetterAuthOptions, K as KyselyDatabaseType, F as FieldAttribute, A as Adapter } from '../auth-
|
|
2
|
+
import { e as BetterAuthOptions, K as KyselyDatabaseType, F as FieldAttribute, A as Adapter } from '../auth-Dhq27-3h.js';
|
|
3
3
|
import 'node_modules/better-call/dist/router-Bn7zn81P';
|
|
4
4
|
import 'zod';
|
|
5
|
-
import '../index-
|
|
5
|
+
import '../index-DUqGSAH3.js';
|
|
6
6
|
import 'better-call';
|
|
7
7
|
import 'better-sqlite3';
|
|
8
8
|
|
|
@@ -1 +1 @@
|
|
|
1
|
-
"use strict";var
|
|
1
|
+
"use strict";var h=Object.defineProperty;var g=Object.getOwnPropertyDescriptor;var m=Object.getOwnPropertyNames;var $=Object.prototype.hasOwnProperty;var b=(c,r)=>{for(var i in r)h(c,i,{get:r[i],enumerable:!0})},A=(c,r,i,a)=>{if(r&&typeof r=="object"||typeof r=="function")for(let o of m(r))!$.call(c,o)&&o!==i&&h(c,o,{get:()=>r[o],enumerable:!(a=g(r,o))||a.enumerable});return c};var k=c=>A(h({},"__esModule",{value:!0}),c);var D={};b(D,{mongodbAdapter:()=>O});module.exports=k(D);var p=require("mongodb");function w(c){if(!c)return{};function r(e){return e==="id"?"_id":e}function i(e,t){if(e==="id"){if(typeof t!="string"){if(t instanceof p.ObjectId)return t;if(Array.isArray(t))return t.map(n=>{if(typeof n=="string")try{return new p.ObjectId(n)}catch{return n}if(n instanceof p.ObjectId)return n;throw new Error("Invalid id value")});throw new Error("Invalid id value")}try{return new p.ObjectId(t)}catch{return t}}return t}let a=c.map(e=>{let{field:t,value:n,operator:u="eq",connector:f="AND"}=e,l;switch(u.toLowerCase()){case"eq":l={[r(t)]:i(t,n)};break;case"in":l={[r(t)]:{$in:Array.isArray(n)?i(t,n):[i(t,n)]}};break;case"gt":l={[r(t)]:{$gt:n}};break;case"gte":l={[r(t)]:{$gte:n}};break;case"lt":l={[r(t)]:{$lt:n}};break;case"lte":l={[r(t)]:{$lte:n}};break;case"ne":l={[r(t)]:{$ne:n}};break;case"contains":l={[r(t)]:{$regex:`.*${n}.*`}};break;case"starts_with":l={[r(t)]:{$regex:`${n}.*`}};break;case"ends_with":l={[r(t)]:{$regex:`.*${n}`}};break;default:throw new Error(`Unsupported operator: ${u}`)}return{condition:l,connector:f}}),o=a.filter(e=>e.connector==="AND").map(e=>e.condition),d=a.filter(e=>e.connector==="OR").map(e=>e.condition),s={};return o.length&&(s={...s,$and:o}),d.length&&(s={...s,$or:d}),s}function y(c){let{_id:r,...i}=c;return{...i,id:r}}function C(c){return c.reduce((i,a)=>(i[a]=1,i),{})}var O=(c,r)=>{let i=c,a=o=>r?.usePlural?`${o}s`:o;return{id:"mongodb",async create(o){let{model:d,data:s}=o;s.id&&(s.id=void 0);let t=(await i.collection(a(d)).insertOne(s)).insertedId,n={...s,id:t};return y(n)},async findOne(o){let{model:d,where:s,select:e}=o,t=w(s),n={};e&&(n=C(e));let u=await i.collection(a(d)).findOne(t,{projection:n});if(!u)return null;let f=y(u);return e?.length&&!e.includes("id")&&(f.id=void 0),f},async findMany(o){let{model:d,where:s,limit:e,offset:t,sortBy:n}=o,u=w(s);return(await i.collection(a(d)).find(u).skip(t||0).limit(e||100).sort(n?.field||"_id",n?.direction==="desc"?-1:1).toArray()).map(y)},async update(o){let{model:d,where:s,update:e}=o,t=w(s);if(e.id&&(e.id=void 0),s.length===1){let n=await i.collection(a(d)).findOneAndUpdate(t,{$set:e},{returnDocument:"after"});return y(n)}return await i.collection(a(d)).updateMany(t,{$set:e}),{}},async delete(o){let{model:d,where:s}=o,e=w(s);await i.collection(a(d)).findOneAndDelete(e)},async deleteMany(o){let{model:d,where:s}=o,e=w(s);await i.collection(a(d)).deleteMany(e)}}};0&&(module.exports={mongodbAdapter});
|
|
@@ -3,11 +3,11 @@ import { EventEmitter } from 'events';
|
|
|
3
3
|
import { TcpNetConnectOpts } from 'net';
|
|
4
4
|
import { Readable } from 'stream';
|
|
5
5
|
import { ConnectionOptions as ConnectionOptions$1, TLSSocketOptions } from 'tls';
|
|
6
|
-
import { W as Where } from '../auth-
|
|
6
|
+
import { W as Where } from '../auth-BYO4oVzl.cjs';
|
|
7
7
|
import 'node_modules/better-call/dist/router-Bn7zn81P';
|
|
8
8
|
import 'zod';
|
|
9
9
|
import 'kysely';
|
|
10
|
-
import '../index-
|
|
10
|
+
import '../index-DUqGSAH3.cjs';
|
|
11
11
|
import 'better-call';
|
|
12
12
|
import 'better-sqlite3';
|
|
13
13
|
|
|
@@ -7098,15 +7098,6 @@ declare class WriteError {
|
|
|
7098
7098
|
|
|
7099
7099
|
declare const mongodbAdapter: (mongo: Db, opts?: {
|
|
7100
7100
|
usePlural?: boolean;
|
|
7101
|
-
/**
|
|
7102
|
-
* Custom generateId function.
|
|
7103
|
-
*
|
|
7104
|
-
* If not provided, nanoid will be used.
|
|
7105
|
-
* If set to false, the database's auto generated id will be used.
|
|
7106
|
-
*
|
|
7107
|
-
* @default nanoid
|
|
7108
|
-
*/
|
|
7109
|
-
generateId?: ((size?: number) => string) | false;
|
|
7110
7101
|
}) => {
|
|
7111
7102
|
id: string;
|
|
7112
7103
|
create<T extends {
|
|
@@ -3,11 +3,11 @@ import { EventEmitter } from 'events';
|
|
|
3
3
|
import { TcpNetConnectOpts } from 'net';
|
|
4
4
|
import { Readable } from 'stream';
|
|
5
5
|
import { ConnectionOptions as ConnectionOptions$1, TLSSocketOptions } from 'tls';
|
|
6
|
-
import { W as Where } from '../auth-
|
|
6
|
+
import { W as Where } from '../auth-Dhq27-3h.js';
|
|
7
7
|
import 'node_modules/better-call/dist/router-Bn7zn81P';
|
|
8
8
|
import 'zod';
|
|
9
9
|
import 'kysely';
|
|
10
|
-
import '../index-
|
|
10
|
+
import '../index-DUqGSAH3.js';
|
|
11
11
|
import 'better-call';
|
|
12
12
|
import 'better-sqlite3';
|
|
13
13
|
|
|
@@ -7098,15 +7098,6 @@ declare class WriteError {
|
|
|
7098
7098
|
|
|
7099
7099
|
declare const mongodbAdapter: (mongo: Db, opts?: {
|
|
7100
7100
|
usePlural?: boolean;
|
|
7101
|
-
/**
|
|
7102
|
-
* Custom generateId function.
|
|
7103
|
-
*
|
|
7104
|
-
* If not provided, nanoid will be used.
|
|
7105
|
-
* If set to false, the database's auto generated id will be used.
|
|
7106
|
-
*
|
|
7107
|
-
* @default nanoid
|
|
7108
|
-
*/
|
|
7109
|
-
generateId?: ((size?: number) => string) | false;
|
|
7110
7101
|
}) => {
|
|
7111
7102
|
id: string;
|
|
7112
7103
|
create<T extends {
|
package/dist/adapters/mongodb.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
function
|
|
1
|
+
import{ObjectId as p}from"mongodb";function w(l){if(!l)return{};function s(e){return e==="id"?"_id":e}function i(e,t){if(e==="id"){if(typeof t!="string"){if(t instanceof p)return t;if(Array.isArray(t))return t.map(n=>{if(typeof n=="string")try{return new p(n)}catch{return n}if(n instanceof p)return n;throw new Error("Invalid id value")});throw new Error("Invalid id value")}try{return new p(t)}catch{return t}}return t}let a=l.map(e=>{let{field:t,value:n,operator:u="eq",connector:f="AND"}=e,d;switch(u.toLowerCase()){case"eq":d={[s(t)]:i(t,n)};break;case"in":d={[s(t)]:{$in:Array.isArray(n)?i(t,n):[i(t,n)]}};break;case"gt":d={[s(t)]:{$gt:n}};break;case"gte":d={[s(t)]:{$gte:n}};break;case"lt":d={[s(t)]:{$lt:n}};break;case"lte":d={[s(t)]:{$lte:n}};break;case"ne":d={[s(t)]:{$ne:n}};break;case"contains":d={[s(t)]:{$regex:`.*${n}.*`}};break;case"starts_with":d={[s(t)]:{$regex:`${n}.*`}};break;case"ends_with":d={[s(t)]:{$regex:`.*${n}`}};break;default:throw new Error(`Unsupported operator: ${u}`)}return{condition:d,connector:f}}),o=a.filter(e=>e.connector==="AND").map(e=>e.condition),c=a.filter(e=>e.connector==="OR").map(e=>e.condition),r={};return o.length&&(r={...r,$and:o}),c.length&&(r={...r,$or:c}),r}function y(l){let{_id:s,...i}=l;return{...i,id:s}}function h(l){return l.reduce((i,a)=>(i[a]=1,i),{})}var m=(l,s)=>{let i=l,a=o=>s?.usePlural?`${o}s`:o;return{id:"mongodb",async create(o){let{model:c,data:r}=o;r.id&&(r.id=void 0);let t=(await i.collection(a(c)).insertOne(r)).insertedId,n={...r,id:t};return y(n)},async findOne(o){let{model:c,where:r,select:e}=o,t=w(r),n={};e&&(n=h(e));let u=await i.collection(a(c)).findOne(t,{projection:n});if(!u)return null;let f=y(u);return e?.length&&!e.includes("id")&&(f.id=void 0),f},async findMany(o){let{model:c,where:r,limit:e,offset:t,sortBy:n}=o,u=w(r);return(await i.collection(a(c)).find(u).skip(t||0).limit(e||100).sort(n?.field||"_id",n?.direction==="desc"?-1:1).toArray()).map(y)},async update(o){let{model:c,where:r,update:e}=o,t=w(r);if(e.id&&(e.id=void 0),r.length===1){let n=await i.collection(a(c)).findOneAndUpdate(t,{$set:e},{returnDocument:"after"});return y(n)}return await i.collection(a(c)).updateMany(t,{$set:e}),{}},async delete(o){let{model:c,where:r}=o,e=w(r);await i.collection(a(c)).findOneAndDelete(e)},async deleteMany(o){let{model:c,where:r}=o,e=w(r);await i.collection(a(c)).deleteMany(e)}}};export{m as mongodbAdapter};
|
|
@@ -1,8 +1,8 @@
|
|
|
1
|
-
import { A as Adapter } from '../auth-
|
|
1
|
+
import { A as Adapter } from '../auth-BYO4oVzl.cjs';
|
|
2
2
|
import 'node_modules/better-call/dist/router-Bn7zn81P';
|
|
3
3
|
import 'zod';
|
|
4
4
|
import 'kysely';
|
|
5
|
-
import '../index-
|
|
5
|
+
import '../index-DUqGSAH3.cjs';
|
|
6
6
|
import 'better-call';
|
|
7
7
|
import 'better-sqlite3';
|
|
8
8
|
|
|
@@ -1,8 +1,8 @@
|
|
|
1
|
-
import { A as Adapter } from '../auth-
|
|
1
|
+
import { A as Adapter } from '../auth-Dhq27-3h.js';
|
|
2
2
|
import 'node_modules/better-call/dist/router-Bn7zn81P';
|
|
3
3
|
import 'zod';
|
|
4
4
|
import 'kysely';
|
|
5
|
-
import '../index-
|
|
5
|
+
import '../index-DUqGSAH3.js';
|
|
6
6
|
import 'better-call';
|
|
7
7
|
import 'better-sqlite3';
|
|
8
8
|
|
package/dist/api.cjs
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
"use strict";var ie=Object.defineProperty;var Ot=Object.getOwnPropertyDescriptor;var St=Object.getOwnPropertyNames;var It=Object.prototype.hasOwnProperty;var Lt=(e,t)=>{for(var r in t)ie(e,r,{get:t[r],enumerable:!0})},Ct=(e,t,r,o)=>{if(t&&typeof t=="object"||typeof t=="function")for(let n of St(t))!It.call(e,n)&&n!==r&&ie(e,n,{get:()=>t[n],enumerable:!(o=Ot(t,n))||o.enumerable});return e};var Bt=e=>Ct(ie({},"__esModule",{value:!0}),e);var Yt={};Lt(Yt,{APIError:()=>Tt.APIError,callbackOAuth:()=>ye,changeEmail:()=>Te,changePassword:()=>ve,createAuthEndpoint:()=>p,createAuthMiddleware:()=>G,createEmailVerificationToken:()=>S,deleteUser:()=>xe,error:()=>Pe,forgetPassword:()=>ke,forgetPasswordCallback:()=>Re,getEndpoints:()=>xt,getSession:()=>ee,getSessionFromCtx:()=>te,linkSocialAccount:()=>Ce,listSessions:()=>pe,listUserAccounts:()=>Le,ok:()=>Oe,optionsMiddleware:()=>se,originCheckMiddleware:()=>de,resetPassword:()=>Ue,revokeSession:()=>me,revokeSessions:()=>fe,router:()=>Wt,sendVerificationEmail:()=>ge,sessionMiddleware:()=>v,setPassword:()=>_e,signInEmail:()=>be,signInOAuth:()=>we,signOut:()=>Ae,signUpEmail:()=>Se,updateUser:()=>Ee,verifyEmail:()=>he});module.exports=Bt(Yt);var j=require("better-call");var Fe=require("better-call");var C=require("better-call"),se=(0,C.createMiddleware)(async()=>({})),G=(0,C.createMiddlewareCreator)({use:[se,(0,C.createMiddleware)(async()=>({}))]}),p=(0,C.createEndpointCreator)({use:[se]});var q={isAction:!1};var De=require("nanoid"),ze=e=>(0,De.nanoid)(e);var Y=require("oslo/oauth2"),L=require("zod"),ce=require("better-call");var W=Object.create(null),Q=e=>globalThis.process?.env||globalThis.Deno?.env.toObject()||globalThis.__env__||(e?W:globalThis),Ve=new Proxy(W,{get(e,t){return Q()[t]??W[t]},has(e,t){let r=Q();return t in r||t in W},set(e,t,r){let o=Q(!0);return o[t]=r,!0},deleteProperty(e,t){if(!t)return!1;let r=Q(!0);return delete r[t],!0},ownKeys(){let e=Q(!0);return Object.keys(e)}});function Dt(e){return e?e!=="false":!1}var ae=typeof process<"u"&&process.env&&process.env.NODE_ENV||"";var $e=ae==="dev"||ae==="development",je=ae==="test"||Dt(Ve.TEST);var B=class extends Error{constructor(t,r){super(t),this.name="BetterAuthError",this.message=t,this.cause=r}};function qe(e){try{return new URL(e).origin}catch{return null}}async function K(e,t){let r=e.body?.callbackURL||(e.query?.currentURL?qe(e.query?.currentURL):"");if(!r)throw new ce.APIError("BAD_REQUEST",{message:"callbackURL is required"});let o=(0,Y.generateCodeVerifier)(),n=(0,Y.generateState)(),i=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:i,identifier:n,expiresAt:s});if(!a)throw f.error("Unable to create verification. Make sure the database adapter is properly working and there is a verification table in the database"),new ce.APIError("INTERNAL_SERVER_ERROR",{message:"Unable to create verification"});return{state:a.identifier,codeVerifier:o}}async function Ne(e){let t=e.query.state,r=await e.context.internalAdapter.findVerificationValue(t);if(!r)throw f.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),f.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 Me=require("consola"),D=(0,Me.createConsola)({formatOptions:{date:!1,colors:!0,compact:!0},defaults:{tag:"Better Auth"}}),zt=e=>({log:(...t)=>{!e?.disabled&&D.log("",...t)},error:(...t)=>{!e?.disabled&&D.error("",...t)},warn:(...t)=>{!e?.disabled&&D.warn("",...t)},info:(...t)=>{!e?.disabled&&D.info("",...t)},debug:(...t)=>{!e?.disabled&&D.debug("",...t)},box:(...t)=>{!e?.disabled&&D.box("",...t)},success:(...t)=>{!e?.disabled&&D.success("",...t)},break:(...t)=>{!e?.disabled&&console.log(`
|
|
2
2
|
`)}}),f=zt();var de=G(async e=>{if(e.request?.method!=="POST")return;let{body:t,query:r,context:o}=e,n=e.headers?.get("origin")||e.headers?.get("referer")||"",i=t?.callbackURL,s=t?.redirectTo,a=r?.currentURL,u=o.trustedOrigins,c=e.headers?.has("cookie"),d=(h,m)=>{if(!u.some(k=>h?.startsWith(k)||h?.startsWith("/")&&m!=="origin"))throw f.error(`Invalid ${m}: ${h}`),f.info(`If it's a valid URL, please add ${h} to trustedOrigins in your auth config
|
|
3
|
-
`,`Current list of trustedOrigins: ${u}`),new Fe.APIError("FORBIDDEN",{message:`Invalid ${m}`})};c&&!e.context.options.advanced?.disableCSRFCheck&&d(n,"origin"),i&&d(i,"callbackURL"),s&&d(s,"redirectURL"),a&&d(a,"currentURL")});var T=require("better-call"),Ko=require("oslo/oauth2"),_=require("zod");var Vt=require("oslo");async function O(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&&await e.setSignedCookie(e.context.authCookies.sessionData.name,JSON.stringify(t),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 z(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 We=require("oslo/jwt");var He=require("oslo/crypto"),Ge=require("oslo/encoding");var N=(e,t="ms")=>new Date(Date.now()+(t==="sec"?e*1e3:e));async function Qe(e){let t=await(0,He.sha256)(new TextEncoder().encode(e));return Ge.base64url.encode(new Uint8Array(t),{includePadding:!1})}function Ze(e){return{tokenType:e.token_type,accessToken:e.access_token,refreshToken:e.refresh_token,accessTokenExpiresAt:e.expires_in?N(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,disablePkce:a,redirectURI:u}){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||u),!a&&n){let d=await Qe(n);c.searchParams.set("code_challenge_method","S256"),c.searchParams.set("code_challenge",d)}if(s){let d=s.reduce((h,m)=>(h[m]=null,h),{});c.searchParams.set("claims",JSON.stringify({id_token:{email:null,email_verified:null,...d}}))}return c}var Je=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,Je.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 Ze(s)}var Ye=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,We.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 Ke=require("@better-fetch/fetch");var Xe=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,Ke.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 et=require("@better-fetch/fetch");var tt=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,et.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 ue=require("@better-fetch/fetch");var rt=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,codeVerifier:n})},validateAuthorizationCode:async({code:r,redirectURI:o})=>y({code:r,redirectURI:e.redirectURI||o,options:e,tokenEndpoint:t}),async getUserInfo(r){let{data:o,error:n}=await(0,ue.betterFetch)("https://api.github.com/user",{headers:{"User-Agent":"better-auth",authorization:`Bearer ${r.accessToken}`}});if(n)return null;let i=!1;if(!o.email){let{data:s,error:a}=await(0,ue.betterFetch)("https://api.github.com/user/emails",{headers:{authorization:`Bearer ${r.accessToken}`,"User-Agent":"better-auth"}});a||(o.email=(s.find(u=>u.primary)??s[0])?.email,i=s.find(u=>u.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 ot=require("oslo/jwt");var nt=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 B("CLIENT_ID_AND_SECRET_REQUIRED");if(!o)throw new B("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,ot.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 it=require("@better-fetch/fetch"),st=require("oslo/jwt");var at=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,st.parseJWT)(n.idToken)?.payload,s=e.profilePhotoSize||48;return await(0,it.betterFetch)(`https://graph.microsoft.com/v1.0/me/photos/${s}x${s}/$value`,{headers:{Authorization:`Bearer ${n.accessToken}`},async onResponse(a){if(!(e.disableProfilePhoto||!a.response.ok))try{let c=await a.response.clone().arrayBuffer(),d=Buffer.from(c).toString("base64");i.picture=`data:image/jpeg;base64, ${d}`}catch(u){f.error(u)}}}),{user:{id:i.sub,name:i.name,email:i.email,image:i.picture,emailVerified:!0},data:i}}}};var ct=require("@better-fetch/fetch");var dt=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,ct.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 ro=require("@better-fetch/fetch");var ut=require("oslo/jwt");var lt=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,ut.parseJWT)(r)?.payload;return{user:{id:o.sub,name:o.preferred_username,email:o.email,image:o.picture,emailVerified:!1},data:o}}});var pt=require("@better-fetch/fetch");var mt=e=>({id:"twitter",name:"Twitter",createAuthorizationURL(t){let r=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,pt.betterFetch)("https://api.x.com/2/users/me?user.fields=profile_image_url",{method:"GET",headers:{Authorization:`Bearer ${t.accessToken}`}});return o||!r.data.email?null:{user:{id:r.data.id,name:r.data.name,email:r.data.email,image:r.data.profile_image_url,emailVerified:r.data.verified||!1},data:r}}});var ft=require("@better-fetch/fetch");var gt=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,ft.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 ht=require("@better-fetch/fetch");var wt=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,ht.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 bt=require("@better-fetch/fetch");var le=(e="")=>e.split("://").map(t=>t.replace(/\/{2,}/g,"/")).join("://"),$t=e=>{let t=e||"https://gitlab.com";return{authorizationEndpoint:le(`${t}/oauth/authorize`),tokenEndpoint:le(`${t}/oauth/token`),userinfoEndpoint:le(`${t}/api/v4/user`)}},yt=e=>{let{authorizationEndpoint:t,tokenEndpoint:r,userinfoEndpoint:o}=$t(e.issuer),n="gitlab";return{id:n,name:"Gitlab",createAuthorizationURL:async({state:s,scopes:a,codeVerifier:u,redirectURI:c})=>{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:c,codeVerifier:u})},validateAuthorizationCode:async({code:s,redirectURI:a})=>y({code:s,redirectURI:e.redirectURI||a,options:e,tokenEndpoint:r}),async getUserInfo(s){let{data:a,error:u}=await(0,bt.betterFetch)(o,{headers:{authorization:`Bearer ${s.accessToken}`}});return u||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 jt={apple:Ye,discord:Xe,facebook:tt,github:rt,microsoft:at,google:nt,spotify:dt,twitch:lt,twitter:mt,dropbox:gt,linkedin:wt,gitlab:yt},X=Object.keys(jt);var At=require("oslo"),re=require("oslo/jwt"),x=require("zod");var V=require("better-call");var M=require("better-call");var F=require("zod"),ee=()=>p("/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=await e.getSignedCookie(e.context.authCookies.sessionData.name,e.context.secret),o=await e.getSignedCookie(e.context.authCookies.dontRememberToken.name,e.context.secret);if(r&&e.context.options.session?.cookieCache?.enabled&&!e.query?.disableCookieCache){let c=JSON.parse(r)?.session;if(c?.expiresAt>new Date)return e.json(c)}let n=await e.context.internalAdapter.findSession(t);if(!n||n.session.expiresAt<new Date)return z(e),n&&await e.context.internalAdapter.deleteSession(n.session.id),e.json(null,{status:401});if(o)return e.json(n);let i=e.context.sessionConfig.expiresIn,s=e.context.sessionConfig.updateAge;if(n.session.expiresAt.valueOf()-i*1e3+s*1e3<=Date.now()){let c=await e.context.internalAdapter.updateSession(n.session.id,{expiresAt:N(e.context.sessionConfig.expiresIn,"sec")});if(!c)return z(e),e.json(null,{status:401});let d=(c.expiresAt.valueOf()-Date.now())/1e3;return await O(e,{session:c,user:n.user},!1,{maxAge:d}),e.json({session:c,user:n.user})}return e.json(n)}catch(t){return e.context.logger.error(t),e.json(null,{status:500})}}),te=async e=>await ee()({...e,_flag:"json",headers:e.headers}),v=G(async e=>{let t=await te(e);if(!t?.session)throw new M.APIError("UNAUTHORIZED");return{session:t}}),pe=()=>p("/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)}),me=p("/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})}),fe=p("/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,re.createJWT)("HS256",Buffer.from(e),{email:t.toLowerCase(),updateTo:r},{expiresIn:new At.TimeSpan(1,"h"),issuer:"better-auth",subject:"verify-email",audiences:[t],includeIssuedTimestamp:!0})}var ge=p("/send-verification-email",{method:"POST",query:x.z.object({currentURL:x.z.string().optional()}).optional(),body:x.z.object({email:x.z.string().email(),callbackURL:x.z.string().optional()})},async e=>{if(!e.context.options.emailVerification?.sendVerificationEmail)throw e.context.logger.error("Verification email isn't enabled."),new V.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 V.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})}),he=p("/verify-email",{method:"GET",query:x.z.object({token:x.z.string(),callbackURL:x.z.string().optional()})},async e=>{let{token:t}=e.query,r;try{r=await(0,re.validateJWT)("HS256",Buffer.from(e.context.secret),t)}catch(s){throw e.context.logger.error("Failed to verify email",s),new V.APIError("BAD_REQUEST",{message:"Invalid token"})}let n=x.z.object({email:x.z.string().email(),updateTo:x.z.string().optional()}).parse(r.payload);if(!await e.context.internalAdapter.findUserByEmail(n.email))throw new V.APIError("BAD_REQUEST",{message:"User not found"});if(n.updateTo){let s=await te(e);if(!s)throw e.query.callbackURL?e.redirect(`${e.query.callbackURL}?error=unauthorized`):new V.APIError("UNAUTHORIZED",{message:"Session not found"});if(s.user.email!==n.email)throw e.query.callbackURL?e.redirect(`${e.query.callbackURL}?error=unauthorized`):new V.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 kt=require("oslo/crypto");var we=p("/sign-in/social",{method:"POST",requireHeaders:!0,query:_.z.object({currentURL:_.z.string().optional()}).optional(),body:_.z.object({callbackURL:_.z.string().optional(),provider:_.z.enum(X)})},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 T.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})}),be=p("/sign-in/email",{method:"POST",body:_.z.object({email:_.z.string(),password:_.z.string(),callbackURL:_.z.string().optional(),dontRememberMe:_.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 T.APIError("BAD_REQUEST",{message:"Email and password is not enabled"});let{email:t,password:r}=e.body;if(!_.z.string().email().safeParse(t).success)throw new T.APIError("BAD_REQUEST",{message:"Invalid email"});if(!_.z.string().email().safeParse(t).success)throw new T.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 T.APIError("UNAUTHORIZED",{message:"Invalid email or password"});let s=i.accounts.find(d=>d.providerId==="credential");if(!s)throw e.context.logger.error("Credential account not found",{email:t}),new T.APIError("UNAUTHORIZED",{message:"Invalid email or password"});let a=s?.password;if(!a)throw e.context.logger.error("Password not found",{email:t}),new T.APIError("UNAUTHORIZED",{message:"Unexpected error"});if(!await e.context.password.verify(a,r))throw e.context.logger.error("Invalid password"),new T.APIError("UNAUTHORIZED",{message:"Invalid email or password"});if(e.context.options?.emailAndPassword?.requireEmailVerification&&!i.user.emailVerified){if(!e.context.options?.emailVerification?.sendVerificationEmail)throw f.error("Email verification is required but no email verification handler is provided"),new T.APIError("INTERNAL_SERVER_ERROR",{message:"Email is not verified."});let d=await S(e.context.secret,i.user.email),h=`${e.context.options.baseURL}/verify-email?token=${d}`;throw await e.context.options.emailVerification.sendVerificationEmail(i.user,h,d),e.context.logger.error("Email not verified",{email:t}),new T.APIError("FORBIDDEN",{message:"Email is not verified. Check your email for a verification link"})}let c=await e.context.internalAdapter.createSession(i.user.id,e.headers,e.body.dontRememberMe);if(!c)throw e.context.logger.error("Failed to create session"),new T.APIError("UNAUTHORIZED",{message:"Failed to create session"});return await O(e,{session:c,user:i.user},e.body.dontRememberMe),e.json({user:i.user,session:c,redirect:!!e.body.callbackURL,url:e.body.callbackURL})});var Z=require("zod");var g=require("zod"),dn=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()}),Rt=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)}),un=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()}),ln=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 Nt(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 oe(e,t,r){let o=qt(e,"user");return Nt(t||{},{fields:o,action:r})}var ye=p("/callback/:id",{method:"GET",query:Z.z.object({state:Z.z.string(),code:Z.z.string().optional(),error:Z.z.string().optional()}),metadata:q},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 Ne(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),u=ze(),c=Rt.safeParse({...a,id:u});if(!a||c.success===!1)throw f.error("Unable to get user info",c.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.
|
|
3
|
+
`,`Current list of trustedOrigins: ${u}`),new Fe.APIError("FORBIDDEN",{message:`Invalid ${m}`})};c&&!e.context.options.advanced?.disableCSRFCheck&&d(n,"origin"),i&&d(i,"callbackURL"),s&&d(s,"redirectURL"),a&&d(a,"currentURL")});var T=require("better-call"),Ko=require("oslo/oauth2"),_=require("zod");var Vt=require("oslo");async function O(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&&await e.setSignedCookie(e.context.authCookies.sessionData.name,JSON.stringify(t),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 z(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 We=require("oslo/jwt");var He=require("oslo/crypto"),Ge=require("oslo/encoding");var N=(e,t="ms")=>new Date(Date.now()+(t==="sec"?e*1e3:e));async function Qe(e){let t=await(0,He.sha256)(new TextEncoder().encode(e));return Ge.base64url.encode(new Uint8Array(t),{includePadding:!1})}function Ze(e){return{tokenType:e.token_type,accessToken:e.access_token,refreshToken:e.refresh_token,accessTokenExpiresAt:e.expires_in?N(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,disablePkce:a,redirectURI:u}){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||u),!a&&n){let d=await Qe(n);c.searchParams.set("code_challenge_method","S256"),c.searchParams.set("code_challenge",d)}if(s){let d=s.reduce((h,m)=>(h[m]=null,h),{});c.searchParams.set("claims",JSON.stringify({id_token:{email:null,email_verified:null,...d}}))}return c}var Je=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,Je.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 Ze(s)}var Ye=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,We.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 Ke=require("@better-fetch/fetch");var Xe=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,Ke.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 et=require("@better-fetch/fetch");var tt=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,et.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 ue=require("@better-fetch/fetch");var rt=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,codeVerifier:n})},validateAuthorizationCode:async({code:r,redirectURI:o})=>y({code:r,redirectURI:e.redirectURI||o,options:e,tokenEndpoint:t}),async getUserInfo(r){let{data:o,error:n}=await(0,ue.betterFetch)("https://api.github.com/user",{headers:{"User-Agent":"better-auth",authorization:`Bearer ${r.accessToken}`}});if(n)return null;let i=!1;if(!o.email){let{data:s,error:a}=await(0,ue.betterFetch)("https://api.github.com/user/emails",{headers:{authorization:`Bearer ${r.accessToken}`,"User-Agent":"better-auth"}});a||(o.email=(s.find(u=>u.primary)??s[0])?.email,i=s.find(u=>u.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 ot=require("oslo/jwt");var nt=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 B("CLIENT_ID_AND_SECRET_REQUIRED");if(!o)throw new B("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,ot.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 it=require("@better-fetch/fetch"),st=require("oslo/jwt");var at=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,st.parseJWT)(n.idToken)?.payload,s=e.profilePhotoSize||48;return await(0,it.betterFetch)(`https://graph.microsoft.com/v1.0/me/photos/${s}x${s}/$value`,{headers:{Authorization:`Bearer ${n.accessToken}`},async onResponse(a){if(!(e.disableProfilePhoto||!a.response.ok))try{let c=await a.response.clone().arrayBuffer(),d=Buffer.from(c).toString("base64");i.picture=`data:image/jpeg;base64, ${d}`}catch(u){f.error(u)}}}),{user:{id:i.sub,name:i.name,email:i.email,image:i.picture,emailVerified:!0},data:i}}}};var ct=require("@better-fetch/fetch");var dt=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,ct.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 ro=require("@better-fetch/fetch");var ut=require("oslo/jwt");var lt=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,ut.parseJWT)(r)?.payload;return{user:{id:o.sub,name:o.preferred_username,email:o.email,image:o.picture,emailVerified:!1},data:o}}});var pt=require("@better-fetch/fetch");var mt=e=>({id:"twitter",name:"Twitter",createAuthorizationURL(t){let r=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,pt.betterFetch)("https://api.x.com/2/users/me?user.fields=profile_image_url",{method:"GET",headers:{Authorization:`Bearer ${t.accessToken}`}});return o||!r.data.email?null:{user:{id:r.data.id,name:r.data.name,email:r.data.email,image:r.data.profile_image_url,emailVerified:r.data.verified||!1},data:r}}});var ft=require("@better-fetch/fetch");var gt=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,ft.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 ht=require("@better-fetch/fetch");var wt=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,ht.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 bt=require("@better-fetch/fetch");var le=(e="")=>e.split("://").map(t=>t.replace(/\/{2,}/g,"/")).join("://"),$t=e=>{let t=e||"https://gitlab.com";return{authorizationEndpoint:le(`${t}/oauth/authorize`),tokenEndpoint:le(`${t}/oauth/token`),userinfoEndpoint:le(`${t}/api/v4/user`)}},yt=e=>{let{authorizationEndpoint:t,tokenEndpoint:r,userinfoEndpoint:o}=$t(e.issuer),n="gitlab";return{id:n,name:"Gitlab",createAuthorizationURL:async({state:s,scopes:a,codeVerifier:u,redirectURI:c})=>{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:c,codeVerifier:u})},validateAuthorizationCode:async({code:s,redirectURI:a})=>y({code:s,redirectURI:e.redirectURI||a,options:e,tokenEndpoint:r}),async getUserInfo(s){let{data:a,error:u}=await(0,bt.betterFetch)(o,{headers:{authorization:`Bearer ${s.accessToken}`}});return u||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 jt={apple:Ye,discord:Xe,facebook:tt,github:rt,microsoft:at,google:nt,spotify:dt,twitch:lt,twitter:mt,dropbox:gt,linkedin:wt,gitlab:yt},X=Object.keys(jt);var At=require("oslo"),re=require("oslo/jwt"),x=require("zod");var V=require("better-call");var M=require("better-call");var F=require("zod"),ee=()=>p("/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=await e.getSignedCookie(e.context.authCookies.sessionData.name,e.context.secret),o=await e.getSignedCookie(e.context.authCookies.dontRememberToken.name,e.context.secret);if(r&&e.context.options.session?.cookieCache?.enabled&&!e.query?.disableCookieCache){let c=JSON.parse(r)?.session;if(c?.expiresAt>new Date)return e.json(c)}let n=await e.context.internalAdapter.findSession(t);if(console.log({session:n}),!n||n.session.expiresAt<new Date)return z(e),n&&await e.context.internalAdapter.deleteSession(n.session.id),e.json(null,{status:401});if(o)return e.json(n);let i=e.context.sessionConfig.expiresIn,s=e.context.sessionConfig.updateAge;if(n.session.expiresAt.valueOf()-i*1e3+s*1e3<=Date.now()){let c=await e.context.internalAdapter.updateSession(n.session.id,{expiresAt:N(e.context.sessionConfig.expiresIn,"sec")});if(!c)return z(e),e.json(null,{status:401});let d=(c.expiresAt.valueOf()-Date.now())/1e3;return await O(e,{session:c,user:n.user},!1,{maxAge:d}),e.json({session:c,user:n.user})}return e.json(n)}catch(t){return e.context.logger.error(t),e.json(null,{status:500})}}),te=async e=>await ee()({...e,_flag:"json",headers:e.headers}),v=G(async e=>{let t=await te(e);if(!t?.session)throw new M.APIError("UNAUTHORIZED");return{session:t}}),pe=()=>p("/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)}),me=p("/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})}),fe=p("/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,re.createJWT)("HS256",Buffer.from(e),{email:t.toLowerCase(),updateTo:r},{expiresIn:new At.TimeSpan(1,"h"),issuer:"better-auth",subject:"verify-email",audiences:[t],includeIssuedTimestamp:!0})}var ge=p("/send-verification-email",{method:"POST",query:x.z.object({currentURL:x.z.string().optional()}).optional(),body:x.z.object({email:x.z.string().email(),callbackURL:x.z.string().optional()})},async e=>{if(!e.context.options.emailVerification?.sendVerificationEmail)throw e.context.logger.error("Verification email isn't enabled."),new V.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 V.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})}),he=p("/verify-email",{method:"GET",query:x.z.object({token:x.z.string(),callbackURL:x.z.string().optional()})},async e=>{let{token:t}=e.query,r;try{r=await(0,re.validateJWT)("HS256",Buffer.from(e.context.secret),t)}catch(s){throw e.context.logger.error("Failed to verify email",s),new V.APIError("BAD_REQUEST",{message:"Invalid token"})}let n=x.z.object({email:x.z.string().email(),updateTo:x.z.string().optional()}).parse(r.payload);if(!await e.context.internalAdapter.findUserByEmail(n.email))throw new V.APIError("BAD_REQUEST",{message:"User not found"});if(n.updateTo){let s=await te(e);if(!s)throw e.query.callbackURL?e.redirect(`${e.query.callbackURL}?error=unauthorized`):new V.APIError("UNAUTHORIZED",{message:"Session not found"});if(s.user.email!==n.email)throw e.query.callbackURL?e.redirect(`${e.query.callbackURL}?error=unauthorized`):new V.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 kt=require("oslo/crypto");var we=p("/sign-in/social",{method:"POST",requireHeaders:!0,query:_.z.object({currentURL:_.z.string().optional()}).optional(),body:_.z.object({callbackURL:_.z.string().optional(),provider:_.z.enum(X)})},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 T.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})}),be=p("/sign-in/email",{method:"POST",body:_.z.object({email:_.z.string(),password:_.z.string(),callbackURL:_.z.string().optional(),dontRememberMe:_.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 T.APIError("BAD_REQUEST",{message:"Email and password is not enabled"});let{email:t,password:r}=e.body;if(!_.z.string().email().safeParse(t).success)throw new T.APIError("BAD_REQUEST",{message:"Invalid email"});if(!_.z.string().email().safeParse(t).success)throw new T.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 T.APIError("UNAUTHORIZED",{message:"Invalid email or password"});let s=i.accounts.find(d=>d.providerId==="credential");if(!s)throw e.context.logger.error("Credential account not found",{email:t}),new T.APIError("UNAUTHORIZED",{message:"Invalid email or password"});let a=s?.password;if(!a)throw e.context.logger.error("Password not found",{email:t}),new T.APIError("UNAUTHORIZED",{message:"Unexpected error"});if(!await e.context.password.verify(a,r))throw e.context.logger.error("Invalid password"),new T.APIError("UNAUTHORIZED",{message:"Invalid email or password"});if(e.context.options?.emailAndPassword?.requireEmailVerification&&!i.user.emailVerified){if(!e.context.options?.emailVerification?.sendVerificationEmail)throw f.error("Email verification is required but no email verification handler is provided"),new T.APIError("INTERNAL_SERVER_ERROR",{message:"Email is not verified."});let d=await S(e.context.secret,i.user.email),h=`${e.context.options.baseURL}/verify-email?token=${d}`;throw await e.context.options.emailVerification.sendVerificationEmail(i.user,h,d),e.context.logger.error("Email not verified",{email:t}),new T.APIError("FORBIDDEN",{message:"Email is not verified. Check your email for a verification link"})}let c=await e.context.internalAdapter.createSession(i.user.id,e.headers,e.body.dontRememberMe);if(!c)throw e.context.logger.error("Failed to create session"),new T.APIError("UNAUTHORIZED",{message:"Failed to create session"});return await O(e,{session:c,user:i.user},e.body.dontRememberMe),e.json({user:i.user,session:c,redirect:!!e.body.callbackURL,url:e.body.callbackURL})});var Z=require("zod");var g=require("zod"),dn=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()}),Rt=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)}),un=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()}),ln=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 Nt(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 oe(e,t,r){let o=qt(e,"user");return Nt(t||{},{fields:o,action:r})}var ye=p("/callback/:id",{method:"GET",query:Z.z.object({state:Z.z.string(),code:Z.z.string().optional(),error:Z.z.string().optional()}),metadata:q},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 Ne(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),u=ze(),c=Rt.safeParse({...a,id:u});if(!a||c.success===!1)throw f.error("Unable to get user info",c.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
4
|
Error: `,w),e.redirect(`${e.context.baseURL}/error?error=internal_server_error`)}),m=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)&&($e&&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(Be){f.error("Unable to link account",Be),d("unable_to_link_account")}}}else try{let w=a.emailVerified||!1;if(m=await e.context.internalAdapter.createOAuthUser({...c.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&&m&&e.context.options.emailVerification?.sendOnSignUp){let b=await S(e.context.secret,m.email),R=`${e.context.baseURL}/verify-email?token=${b}&callbackURL=${o}`;await e.context.options.emailVerification?.sendVerificationEmail?.(m,R,b)}}catch(w){f.error("Unable to create user",w),d("unable_to_create_user")}if(!m)return d("unable_to_create_user");let l=await e.context.internalAdapter.createSession(m.id,e.request);l||d("unable_to_create_session"),await O(e,{session:l,user:m});let k;try{k=new URL(o).toString()}catch{k=o}throw e.redirect(k)});var Un=require("zod");var Ut=require("better-call"),Ae=p("/sign-out",{method:"POST"},async e=>{let t=await e.getSignedCookie(e.context.authCookies.sessionToken.name,e.context.secret);if(!t)throw new Ut.APIError("BAD_REQUEST",{message:"Session not found"});return await e.context.internalAdapter.deleteSession(t),z(e),e.json({success:!0})});var P=require("zod");var J=require("better-call"),ke=p("/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})}),Re=p("/reset-password/:token",{method:"GET",query:P.z.object({callbackURL:P.z.string()})},async e=>{let{token:t}=e.params,r=e.query.callbackURL,o=r.startsWith("http")?r:`${e.context.options.baseURL}${r}`;if(!t||!r)throw e.redirect(`${e.context.baseURL}/error?error=INVALID_TOKEN`);let n=await e.context.internalAdapter.findVerificationValue(`reset-password:${t}`);throw!n||n.expiresAt<new Date?e.redirect(`${o}?error=INVALID_TOKEN`):e.redirect(`${o}${o.includes("?")?"&":"?"}token=${t}`)}),Ue=p("/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 Ee=()=>p("/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=oe(e.context.options,n,"update"),a=await e.context.internalAdapter.updateUserByEmail(i.user.email,{name:r,image:o,...s});return await O(e,{session:i.session,user:a}),e.json({user:a})}),ve=p("/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 u=(await e.context.internalAdapter.findAccounts(n.user.id)).find(h=>h.providerId==="credential"&&h.password);if(!u||!u.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(u.password,r))throw new E.APIError("BAD_REQUEST",{message:"Incorrect password"});if(await e.context.internalAdapter.updateAccount(u.id,{password:c}),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 O(e,{session:h,user:n.user})}return e.json(n.user)}),_e=p("/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(u=>u.providerId==="credential"&&u.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"})}),xe=p("/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),z(e),e.json(null)}),Te=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:[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 Mt=(e="Unknown")=>`<!DOCTYPE html>
|
|
5
5
|
<html lang="en">
|
|
6
6
|
<head>
|
package/dist/api.d.cts
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
import 'node_modules/better-call/dist/router-Bn7zn81P';
|
|
2
|
-
export { b as AuthEndpoint, d as AuthMiddleware, a1 as callbackOAuth, aj as changeEmail, ag as changePassword, a as createAuthEndpoint, c as createAuthMiddleware, ac as createEmailVerificationToken, ai as deleteUser, ak as error, a9 as forgetPassword, aa as forgetPasswordCallback, Z as getEndpoints, a2 as getSession, a3 as getSessionFromCtx, ao as linkSocialAccount, a5 as listSessions, an as listUserAccounts, al as ok, o as optionsMiddleware, ap as originCheckMiddleware, ab as resetPassword, a6 as revokeSession, a7 as revokeSessions, _ as router, ad as sendVerificationEmail, a4 as sessionMiddleware, ah as setPassword, a0 as signInEmail, $ as signInOAuth, a8 as signOut, am as signUpEmail, af as updateUser, ae as verifyEmail } from './auth-
|
|
3
|
-
import './index-
|
|
2
|
+
export { b as AuthEndpoint, d as AuthMiddleware, a1 as callbackOAuth, aj as changeEmail, ag as changePassword, a as createAuthEndpoint, c as createAuthMiddleware, ac as createEmailVerificationToken, ai as deleteUser, ak as error, a9 as forgetPassword, aa as forgetPasswordCallback, Z as getEndpoints, a2 as getSession, a3 as getSessionFromCtx, ao as linkSocialAccount, a5 as listSessions, an as listUserAccounts, al as ok, o as optionsMiddleware, ap as originCheckMiddleware, ab as resetPassword, a6 as revokeSession, a7 as revokeSessions, _ as router, ad as sendVerificationEmail, a4 as sessionMiddleware, ah as setPassword, a0 as signInEmail, $ as signInOAuth, a8 as signOut, am as signUpEmail, af as updateUser, ae as verifyEmail } from './auth-BYO4oVzl.cjs';
|
|
3
|
+
import './index-DUqGSAH3.cjs';
|
|
4
4
|
export { APIError } from 'better-call';
|
|
5
5
|
import 'zod';
|
|
6
6
|
import 'kysely';
|
package/dist/api.d.ts
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
import 'node_modules/better-call/dist/router-Bn7zn81P';
|
|
2
|
-
export { b as AuthEndpoint, d as AuthMiddleware, a1 as callbackOAuth, aj as changeEmail, ag as changePassword, a as createAuthEndpoint, c as createAuthMiddleware, ac as createEmailVerificationToken, ai as deleteUser, ak as error, a9 as forgetPassword, aa as forgetPasswordCallback, Z as getEndpoints, a2 as getSession, a3 as getSessionFromCtx, ao as linkSocialAccount, a5 as listSessions, an as listUserAccounts, al as ok, o as optionsMiddleware, ap as originCheckMiddleware, ab as resetPassword, a6 as revokeSession, a7 as revokeSessions, _ as router, ad as sendVerificationEmail, a4 as sessionMiddleware, ah as setPassword, a0 as signInEmail, $ as signInOAuth, a8 as signOut, am as signUpEmail, af as updateUser, ae as verifyEmail } from './auth-
|
|
3
|
-
import './index-
|
|
2
|
+
export { b as AuthEndpoint, d as AuthMiddleware, a1 as callbackOAuth, aj as changeEmail, ag as changePassword, a as createAuthEndpoint, c as createAuthMiddleware, ac as createEmailVerificationToken, ai as deleteUser, ak as error, a9 as forgetPassword, aa as forgetPasswordCallback, Z as getEndpoints, a2 as getSession, a3 as getSessionFromCtx, ao as linkSocialAccount, a5 as listSessions, an as listUserAccounts, al as ok, o as optionsMiddleware, ap as originCheckMiddleware, ab as resetPassword, a6 as revokeSession, a7 as revokeSessions, _ as router, ad as sendVerificationEmail, a4 as sessionMiddleware, ah as setPassword, a0 as signInEmail, $ as signInOAuth, a8 as signOut, am as signUpEmail, af as updateUser, ae as verifyEmail } from './auth-Dhq27-3h.js';
|
|
3
|
+
import './index-DUqGSAH3.js';
|
|
4
4
|
export { APIError } from 'better-call';
|
|
5
5
|
import 'zod';
|
|
6
6
|
import 'kysely';
|
package/dist/api.js
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
import{APIError as rt,createRouter as Mt,statusCode as Ft}from"better-call";import{APIError as pt}from"better-call";import{createEndpointCreator as nt,createMiddleware as ne,createMiddlewareCreator as it}from"better-call";var ie=ne(async()=>({})),H=it({use:[ie,ne(async()=>({}))]}),p=nt({use:[ie]});var z={isAction:!1};import{nanoid as st}from"nanoid";var se=e=>st(e);import{generateCodeVerifier as ct,generateState as dt}from"oslo/oauth2";import{z as L}from"zod";import{APIError as le}from"better-call";var G=Object.create(null),q=e=>globalThis.process?.env||globalThis.Deno?.env.toObject()||globalThis.__env__||(e?G:globalThis),ae=new Proxy(G,{get(e,t){return q()[t]??G[t]},has(e,t){let r=q();return t in r||t in G},set(e,t,r){let o=q(!0);return o[t]=r,!0},deleteProperty(e,t){if(!t)return!1;let r=q(!0);return delete r[t],!0},ownKeys(){let e=q(!0);return Object.keys(e)}});function at(e){return e?e!=="false":!1}var X=typeof process<"u"&&process.env&&process.env.NODE_ENV||"";var ce=X==="dev"||X==="development",de=X==="test"||at(ae.TEST);var C=class extends Error{constructor(t,r){super(t),this.name="BetterAuthError",this.message=t,this.cause=r}};function ue(e){try{return new URL(e).origin}catch{return null}}async function Q(e,t){let r=e.body?.callbackURL||(e.query?.currentURL?ue(e.query?.currentURL):"");if(!r)throw new le("BAD_REQUEST",{message:"callbackURL is required"});let o=ct(),n=dt(),i=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:i,identifier:n,expiresAt:s});if(!a)throw f.error("Unable to create verification. Make sure the database adapter is properly working and there is a verification table in the database"),new le("INTERNAL_SERVER_ERROR",{message:"Unable to create verification"});return{state:a.identifier,codeVerifier:o}}async function pe(e){let t=e.query.state,r=await e.context.internalAdapter.findVerificationValue(t);if(!r)throw f.error("State Mismatch. Verification not found",{state:t}),e.redirect(`${e.context.baseURL}/error?error=please_restart_the_process`);let o=L.object({callbackURL:L.string(),codeVerifier:L.string(),errorURL:L.string().optional(),expiresAt:L.number(),link:L.object({email:L.string(),userId:L.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),f.error("State expired.",{state:t}),e.redirect(`${e.context.baseURL}/error?error=please_restart_the_process`);return await e.context.internalAdapter.deleteVerificationValue(r.id),o}import{createConsola as ut}from"consola";var B=ut({formatOptions:{date:!1,colors:!0,compact:!0},defaults:{tag:"Better Auth"}}),lt=e=>({log:(...t)=>{!e?.disabled&&B.log("",...t)},error:(...t)=>{!e?.disabled&&B.error("",...t)},warn:(...t)=>{!e?.disabled&&B.warn("",...t)},info:(...t)=>{!e?.disabled&&B.info("",...t)},debug:(...t)=>{!e?.disabled&&B.debug("",...t)},box:(...t)=>{!e?.disabled&&B.box("",...t)},success:(...t)=>{!e?.disabled&&B.success("",...t)},break:(...t)=>{!e?.disabled&&console.log(`
|
|
2
2
|
`)}}),f=lt();var me=H(async e=>{if(e.request?.method!=="POST")return;let{body:t,query:r,context:o}=e,n=e.headers?.get("origin")||e.headers?.get("referer")||"",i=t?.callbackURL,s=t?.redirectTo,a=r?.currentURL,u=o.trustedOrigins,c=e.headers?.has("cookie"),d=(g,m)=>{if(!u.some(k=>g?.startsWith(k)||g?.startsWith("/")&&m!=="origin"))throw f.error(`Invalid ${m}: ${g}`),f.info(`If it's a valid URL, please add ${g} to trustedOrigins in your auth config
|
|
3
|
-
`,`Current list of trustedOrigins: ${u}`),new pt("FORBIDDEN",{message:`Invalid ${m}`})};c&&!e.context.options.advanced?.disableCSRFCheck&&d(n,"origin"),i&&d(i,"callbackURL"),s&&d(s,"redirectURL"),a&&d(a,"currentURL")});import{APIError as P}from"better-call";import"oslo/oauth2";import{z as _}from"zod";import{TimeSpan as Er}from"oslo";async function x(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&&await e.setSignedCookie(e.context.authCookies.sessionData.name,JSON.stringify(t),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 D(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})}import{parseJWT as ht}from"oslo/jwt";import{sha256 as mt}from"oslo/crypto";import{base64url as ft}from"oslo/encoding";var V=(e,t="ms")=>new Date(Date.now()+(t==="sec"?e*1e3:e));async function fe(e){let t=await mt(new TextEncoder().encode(e));return ft.encode(new Uint8Array(t),{includePadding:!1})}function ge(e){return{tokenType:e.token_type,accessToken:e.access_token,refreshToken:e.refresh_token,accessTokenExpiresAt:e.expires_in?V(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,disablePkce:a,redirectURI:u}){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||u),!a&&n){let d=await fe(n);c.searchParams.set("code_challenge_method","S256"),c.searchParams.set("code_challenge",d)}if(s){let d=s.reduce((g,m)=>(g[m]=null,g),{});c.searchParams.set("claims",JSON.stringify({id_token:{email:null,email_verified:null,...d}}))}return c}import{betterFetch as gt}from"@better-fetch/fetch";async function y({code:e,codeVerifier:t,redirectURI:r,options:o,tokenEndpoint:n}){let i=new URLSearchParams;i.set("grant_type","authorization_code"),i.set("code",e),t&&i.set("code_verifier",t),i.set("redirect_uri",r),i.set("client_id",o.clientId),i.set("client_secret",o.clientSecret);let{data:s,error:a}=await gt(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 ge(s)}var he=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=ht(r.idToken)?.payload;return o?{user:{id:o.sub,name:o.name,email:o.email,emailVerified:o.email_verified==="true"},data:o}:null}}};import{betterFetch as wt}from"@better-fetch/fetch";var we=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 wt("https://discord.com/api/users/@me",{headers:{authorization:`Bearer ${t.accessToken}`}});if(o)return null;if(r.avatar===null){let n=r.discriminator==="0"?Number(BigInt(r.id)>>BigInt(22))%6:parseInt(r.discriminator)%5;r.image_url=`https://cdn.discordapp.com/embed/avatars/${n}.png`}else{let n=r.avatar.startsWith("a_")?"gif":"png";r.image_url=`https://cdn.discordapp.com/avatars/${r.id}/${r.avatar}.${n}`}return{user:{id:r.id,name:r.display_name||r.username||"",email:r.email,emailVerified:r.verified,image:r.image_url},data:r}}});import{betterFetch as bt}from"@better-fetch/fetch";var be=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 bt("https://graph.facebook.com/me?fields=id,name,email,picture",{auth:{type:"Bearer",token:t.accessToken}});return o?null:{user:{id:r.id,name:r.name,email:r.email,image:r.picture.data.url,emailVerified:r.email_verified},data:r}}});import{betterFetch as ye}from"@better-fetch/fetch";var Ae=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,codeVerifier:n})},validateAuthorizationCode:async({code:r,redirectURI:o})=>y({code:r,redirectURI:e.redirectURI||o,options:e,tokenEndpoint:t}),async getUserInfo(r){let{data:o,error:n}=await ye("https://api.github.com/user",{headers:{"User-Agent":"better-auth",authorization:`Bearer ${r.accessToken}`}});if(n)return null;let i=!1;if(!o.email){let{data:s,error:a}=await ye("https://api.github.com/user/emails",{headers:{authorization:`Bearer ${r.accessToken}`,"User-Agent":"better-auth"}});a||(o.email=(s.find(u=>u.primary)??s[0])?.email,i=s.find(u=>u.email===o.email)?.verified??!1)}return{user:{id:o.id.toString(),name:o.name||o.login,email:o.email,image:o.avatar_url,emailVerified:i},data:o}}}};import{parseJWT as yt}from"oslo/jwt";var ke=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 C("CLIENT_ID_AND_SECRET_REQUIRED");if(!o)throw new C("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=yt(t.idToken)?.payload;return{user:{id:r.sub,name:r.name,email:r.email,image:r.picture,emailVerified:r.email_verified},data:r}}});import{betterFetch as At}from"@better-fetch/fetch";import{parseJWT as kt}from"oslo/jwt";var Re=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=kt(n.idToken)?.payload,s=e.profilePhotoSize||48;return await At(`https://graph.microsoft.com/v1.0/me/photos/${s}x${s}/$value`,{headers:{Authorization:`Bearer ${n.accessToken}`},async onResponse(a){if(!(e.disableProfilePhoto||!a.response.ok))try{let c=await a.response.clone().arrayBuffer(),d=Buffer.from(c).toString("base64");i.picture=`data:image/jpeg;base64, ${d}`}catch(u){f.error(u)}}}),{user:{id:i.sub,name:i.name,email:i.email,image:i.picture,emailVerified:!0},data:i}}}};import{betterFetch as Rt}from"@better-fetch/fetch";var Ue=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 Rt("https://api.spotify.com/v1/me",{method:"GET",headers:{Authorization:`Bearer ${t.accessToken}`}});return o?null:{user:{id:r.id,name:r.display_name,email:r.email,image:r.images[0]?.url,emailVerified:!1},data:r}}});import"@better-fetch/fetch";import{parseJWT as Ut}from"oslo/jwt";var Ee=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=Ut(r)?.payload;return{user:{id:o.sub,name:o.preferred_username,email:o.email,image:o.picture,emailVerified:!1},data:o}}});import{betterFetch as Et}from"@better-fetch/fetch";var ve=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 Et("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}}});import{betterFetch as vt}from"@better-fetch/fetch";var _e=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 vt("https://api.dropboxapi.com/2/users/get_current_account",{method:"POST",headers:{Authorization:`Bearer ${r.accessToken}`}});return n?null:{user:{id:o.account_id,name:o.name?.display_name,email:o.email,emailVerified:o.email_verified||!1,image:o.profile_photo_url},data:o}}}};import{betterFetch as _t}from"@better-fetch/fetch";var xe=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 _t("https://api.linkedin.com/v2/userinfo",{method:"GET",headers:{Authorization:`Bearer ${o.accessToken}`}});return i?null:{user:{id:n.sub,name:n.name,email:n.email,emailVerified:n.email_verified||!1,image:n.picture},data:n}}}};import{betterFetch as xt}from"@better-fetch/fetch";var ee=(e="")=>e.split("://").map(t=>t.replace(/\/{2,}/g,"/")).join("://"),Tt=e=>{let t=e||"https://gitlab.com";return{authorizationEndpoint:ee(`${t}/oauth/authorize`),tokenEndpoint:ee(`${t}/oauth/token`),userinfoEndpoint:ee(`${t}/api/v4/user`)}},Te=e=>{let{authorizationEndpoint:t,tokenEndpoint:r,userinfoEndpoint:o}=Tt(e.issuer),n="gitlab";return{id:n,name:"Gitlab",createAuthorizationURL:async({state:s,scopes:a,codeVerifier:u,redirectURI:c})=>{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:c,codeVerifier:u})},validateAuthorizationCode:async({code:s,redirectURI:a})=>y({code:s,redirectURI:e.redirectURI||a,options:e,tokenEndpoint:r}),async getUserInfo(s){let{data:a,error:u}=await xt(o,{headers:{authorization:`Bearer ${s.accessToken}`}});return u||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 Pt={apple:he,discord:we,facebook:be,github:Ae,microsoft:Re,google:ke,spotify:Ue,twitch:Ee,twitter:ve,dropbox:_e,linkedin:xe,gitlab:Te},Z=Object.keys(Pt);import{TimeSpan as Ot}from"oslo";import{createJWT as St,validateJWT as It}from"oslo/jwt";import{z as T}from"zod";import{APIError as $}from"better-call";import{APIError as N}from"better-call";import{z as M}from"zod";var te=()=>p("/get-session",{method:"GET",query:M.optional(M.object({disableCookieCache:M.boolean().optional()})),requireHeaders:!0},async e=>{try{let t=await e.getSignedCookie(e.context.authCookies.sessionToken.name,e.context.secret);if(!t)return e.json(null,{status:401});let r=await e.getSignedCookie(e.context.authCookies.sessionData.name,e.context.secret),o=await e.getSignedCookie(e.context.authCookies.dontRememberToken.name,e.context.secret);if(r&&e.context.options.session?.cookieCache?.enabled&&!e.query?.disableCookieCache){let c=JSON.parse(r)?.session;if(c?.expiresAt>new Date)return e.json(c)}let n=await e.context.internalAdapter.findSession(t);if(!n||n.session.expiresAt<new Date)return D(e),n&&await e.context.internalAdapter.deleteSession(n.session.id),e.json(null,{status:401});if(o)return e.json(n);let i=e.context.sessionConfig.expiresIn,s=e.context.sessionConfig.updateAge;if(n.session.expiresAt.valueOf()-i*1e3+s*1e3<=Date.now()){let c=await e.context.internalAdapter.updateSession(n.session.id,{expiresAt:V(e.context.sessionConfig.expiresIn,"sec")});if(!c)return D(e),e.json(null,{status:401});let d=(c.expiresAt.valueOf()-Date.now())/1e3;return await x(e,{session:c,user:n.user},!1,{maxAge:d}),e.json({session:c,user:n.user})}return e.json(n)}catch(t){return e.context.logger.error(t),e.json(null,{status:500})}}),re=async e=>await te()({...e,_flag:"json",headers:e.headers}),v=H(async e=>{let t=await re(e);if(!t?.session)throw new N("UNAUTHORIZED");return{session:t}}),Pe=()=>p("/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)}),Oe=p("/revoke-session",{method:"POST",body:M.object({id:M.string()}),use:[v],requireHeaders:!0},async e=>{let t=e.body.id,r=await e.context.internalAdapter.findSession(t);if(!r)throw new N("BAD_REQUEST",{message:"Session not found"});if(r.session.userId!==e.context.session.user.id)throw new N("UNAUTHORIZED");try{await e.context.internalAdapter.deleteSession(t)}catch(o){throw e.context.logger.error(o),new N("INTERNAL_SERVER_ERROR")}return e.json({status:!0})}),Se=p("/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 N("INTERNAL_SERVER_ERROR")}return e.json({status:!0})});async function S(e,t,r){return await St("HS256",Buffer.from(e),{email:t.toLowerCase(),updateTo:r},{expiresIn:new Ot(1,"h"),issuer:"better-auth",subject:"verify-email",audiences:[t],includeIssuedTimestamp:!0})}var Ie=p("/send-verification-email",{method:"POST",query:T.object({currentURL:T.string().optional()}).optional(),body:T.object({email:T.string().email(),callbackURL:T.string().optional()})},async e=>{if(!e.context.options.emailVerification?.sendVerificationEmail)throw e.context.logger.error("Verification email isn't enabled."),new $("BAD_REQUEST",{message:"Verification email isn't enabled"});let{email:t}=e.body,r=await e.context.internalAdapter.findUserByEmail(t);if(!r)throw new $("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})}),Le=p("/verify-email",{method:"GET",query:T.object({token:T.string(),callbackURL:T.string().optional()})},async e=>{let{token:t}=e.query,r;try{r=await It("HS256",Buffer.from(e.context.secret),t)}catch(s){throw e.context.logger.error("Failed to verify email",s),new $("BAD_REQUEST",{message:"Invalid token"})}let n=T.object({email:T.string().email(),updateTo:T.string().optional()}).parse(r.payload);if(!await e.context.internalAdapter.findUserByEmail(n.email))throw new $("BAD_REQUEST",{message:"User not found"});if(n.updateTo){let s=await re(e);if(!s)throw e.query.callbackURL?e.redirect(`${e.query.callbackURL}?error=unauthorized`):new $("UNAUTHORIZED",{message:"Session not found"});if(s.user.email!==n.email)throw e.query.callbackURL?e.redirect(`${e.query.callbackURL}?error=unauthorized`):new $("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})});import{HMAC as Rn,sha256 as Un}from"oslo/crypto";var Ce=p("/sign-in/social",{method:"POST",requireHeaders:!0,query:_.object({currentURL:_.string().optional()}).optional(),body:_.object({callbackURL:_.string().optional(),provider:_.enum(Z)})},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 P("NOT_FOUND",{message:"Provider not found"});let{codeVerifier:r,state:o}=await Q(e),n=await t.createAuthorizationURL({state:o,codeVerifier:r,redirectURI:`${e.context.baseURL}/callback/${t.id}`});return e.json({url:n.toString(),redirect:!0})}),Be=p("/sign-in/email",{method:"POST",body:_.object({email:_.string(),password:_.string(),callbackURL:_.string().optional(),dontRememberMe:_.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 P("BAD_REQUEST",{message:"Email and password is not enabled"});let{email:t,password:r}=e.body;if(!_.string().email().safeParse(t).success)throw new P("BAD_REQUEST",{message:"Invalid email"});if(!_.string().email().safeParse(t).success)throw new P("BAD_REQUEST",{message:"Invalid email"});let i=await e.context.internalAdapter.findUserByEmail(t,{includeAccounts:!0});if(!i)throw await e.context.password.hash(r),e.context.logger.error("User not found",{email:t}),new P("UNAUTHORIZED",{message:"Invalid email or password"});let s=i.accounts.find(d=>d.providerId==="credential");if(!s)throw e.context.logger.error("Credential account not found",{email:t}),new P("UNAUTHORIZED",{message:"Invalid email or password"});let a=s?.password;if(!a)throw e.context.logger.error("Password not found",{email:t}),new P("UNAUTHORIZED",{message:"Unexpected error"});if(!await e.context.password.verify(a,r))throw e.context.logger.error("Invalid password"),new P("UNAUTHORIZED",{message:"Invalid email or password"});if(e.context.options?.emailAndPassword?.requireEmailVerification&&!i.user.emailVerified){if(!e.context.options?.emailVerification?.sendVerificationEmail)throw f.error("Email verification is required but no email verification handler is provided"),new P("INTERNAL_SERVER_ERROR",{message:"Email is not verified."});let d=await S(e.context.secret,i.user.email),g=`${e.context.options.baseURL}/verify-email?token=${d}`;throw await e.context.options.emailVerification.sendVerificationEmail(i.user,g,d),e.context.logger.error("Email not verified",{email:t}),new P("FORBIDDEN",{message:"Email is not verified. Check your email for a verification link"})}let c=await e.context.internalAdapter.createSession(i.user.id,e.headers,e.body.dontRememberMe);if(!c)throw e.context.logger.error("Failed to create session"),new P("UNAUTHORIZED",{message:"Failed to create session"});return await x(e,{session:c,user:i.user},e.body.dontRememberMe),e.json({user:i.user,session:c,redirect:!!e.body.callbackURL,url:e.body.callbackURL})});import{z as W}from"zod";import{z as h}from"zod";var $n=h.object({id:h.string(),providerId:h.string(),accountId:h.string(),userId:h.string(),accessToken:h.string().nullable().optional(),refreshToken:h.string().nullable().optional(),idToken:h.string().nullable().optional(),expiresAt:h.date().nullable().optional(),password:h.string().optional().nullable()}),De=h.object({id:h.string(),email:h.string().transform(e=>e.toLowerCase()),emailVerified:h.boolean().default(!1),name:h.string(),image:h.string().optional(),createdAt:h.date().default(new Date),updatedAt:h.date().default(new Date)}),jn=h.object({id:h.string(),userId:h.string(),expiresAt:h.date(),ipAddress:h.string().optional(),userAgent:h.string().optional()}),qn=h.object({id:h.string(),value:h.string(),expiresAt:h.date(),identifier:h.string()});function Lt(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 Ct(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 J(e,t,r){let o=Lt(e,"user");return Ct(t||{},{fields:o,action:r})}var ze=p("/callback/:id",{method:"GET",query:W.object({state:W.string(),code:W.string().optional(),error:W.string().optional()}),metadata:z},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 pe(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),u=se(),c=De.safeParse({...a,id:u});if(!a||c.success===!1)throw f.error("Unable to get user info",c.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 g=await e.context.internalAdapter.findUserByEmail(a.email,{includeAccounts:!0}).catch(w=>{throw f.error(`Better auth was unable to query your database.
|
|
3
|
+
`,`Current list of trustedOrigins: ${u}`),new pt("FORBIDDEN",{message:`Invalid ${m}`})};c&&!e.context.options.advanced?.disableCSRFCheck&&d(n,"origin"),i&&d(i,"callbackURL"),s&&d(s,"redirectURL"),a&&d(a,"currentURL")});import{APIError as P}from"better-call";import"oslo/oauth2";import{z as _}from"zod";import{TimeSpan as Er}from"oslo";async function x(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&&await e.setSignedCookie(e.context.authCookies.sessionData.name,JSON.stringify(t),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 D(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})}import{parseJWT as ht}from"oslo/jwt";import{sha256 as mt}from"oslo/crypto";import{base64url as ft}from"oslo/encoding";var V=(e,t="ms")=>new Date(Date.now()+(t==="sec"?e*1e3:e));async function fe(e){let t=await mt(new TextEncoder().encode(e));return ft.encode(new Uint8Array(t),{includePadding:!1})}function ge(e){return{tokenType:e.token_type,accessToken:e.access_token,refreshToken:e.refresh_token,accessTokenExpiresAt:e.expires_in?V(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,disablePkce:a,redirectURI:u}){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||u),!a&&n){let d=await fe(n);c.searchParams.set("code_challenge_method","S256"),c.searchParams.set("code_challenge",d)}if(s){let d=s.reduce((g,m)=>(g[m]=null,g),{});c.searchParams.set("claims",JSON.stringify({id_token:{email:null,email_verified:null,...d}}))}return c}import{betterFetch as gt}from"@better-fetch/fetch";async function y({code:e,codeVerifier:t,redirectURI:r,options:o,tokenEndpoint:n}){let i=new URLSearchParams;i.set("grant_type","authorization_code"),i.set("code",e),t&&i.set("code_verifier",t),i.set("redirect_uri",r),i.set("client_id",o.clientId),i.set("client_secret",o.clientSecret);let{data:s,error:a}=await gt(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 ge(s)}var he=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=ht(r.idToken)?.payload;return o?{user:{id:o.sub,name:o.name,email:o.email,emailVerified:o.email_verified==="true"},data:o}:null}}};import{betterFetch as wt}from"@better-fetch/fetch";var we=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 wt("https://discord.com/api/users/@me",{headers:{authorization:`Bearer ${t.accessToken}`}});if(o)return null;if(r.avatar===null){let n=r.discriminator==="0"?Number(BigInt(r.id)>>BigInt(22))%6:parseInt(r.discriminator)%5;r.image_url=`https://cdn.discordapp.com/embed/avatars/${n}.png`}else{let n=r.avatar.startsWith("a_")?"gif":"png";r.image_url=`https://cdn.discordapp.com/avatars/${r.id}/${r.avatar}.${n}`}return{user:{id:r.id,name:r.display_name||r.username||"",email:r.email,emailVerified:r.verified,image:r.image_url},data:r}}});import{betterFetch as bt}from"@better-fetch/fetch";var be=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 bt("https://graph.facebook.com/me?fields=id,name,email,picture",{auth:{type:"Bearer",token:t.accessToken}});return o?null:{user:{id:r.id,name:r.name,email:r.email,image:r.picture.data.url,emailVerified:r.email_verified},data:r}}});import{betterFetch as ye}from"@better-fetch/fetch";var Ae=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,codeVerifier:n})},validateAuthorizationCode:async({code:r,redirectURI:o})=>y({code:r,redirectURI:e.redirectURI||o,options:e,tokenEndpoint:t}),async getUserInfo(r){let{data:o,error:n}=await ye("https://api.github.com/user",{headers:{"User-Agent":"better-auth",authorization:`Bearer ${r.accessToken}`}});if(n)return null;let i=!1;if(!o.email){let{data:s,error:a}=await ye("https://api.github.com/user/emails",{headers:{authorization:`Bearer ${r.accessToken}`,"User-Agent":"better-auth"}});a||(o.email=(s.find(u=>u.primary)??s[0])?.email,i=s.find(u=>u.email===o.email)?.verified??!1)}return{user:{id:o.id.toString(),name:o.name||o.login,email:o.email,image:o.avatar_url,emailVerified:i},data:o}}}};import{parseJWT as yt}from"oslo/jwt";var ke=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 C("CLIENT_ID_AND_SECRET_REQUIRED");if(!o)throw new C("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=yt(t.idToken)?.payload;return{user:{id:r.sub,name:r.name,email:r.email,image:r.picture,emailVerified:r.email_verified},data:r}}});import{betterFetch as At}from"@better-fetch/fetch";import{parseJWT as kt}from"oslo/jwt";var Re=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=kt(n.idToken)?.payload,s=e.profilePhotoSize||48;return await At(`https://graph.microsoft.com/v1.0/me/photos/${s}x${s}/$value`,{headers:{Authorization:`Bearer ${n.accessToken}`},async onResponse(a){if(!(e.disableProfilePhoto||!a.response.ok))try{let c=await a.response.clone().arrayBuffer(),d=Buffer.from(c).toString("base64");i.picture=`data:image/jpeg;base64, ${d}`}catch(u){f.error(u)}}}),{user:{id:i.sub,name:i.name,email:i.email,image:i.picture,emailVerified:!0},data:i}}}};import{betterFetch as Rt}from"@better-fetch/fetch";var Ue=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 Rt("https://api.spotify.com/v1/me",{method:"GET",headers:{Authorization:`Bearer ${t.accessToken}`}});return o?null:{user:{id:r.id,name:r.display_name,email:r.email,image:r.images[0]?.url,emailVerified:!1},data:r}}});import"@better-fetch/fetch";import{parseJWT as Ut}from"oslo/jwt";var Ee=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=Ut(r)?.payload;return{user:{id:o.sub,name:o.preferred_username,email:o.email,image:o.picture,emailVerified:!1},data:o}}});import{betterFetch as Et}from"@better-fetch/fetch";var ve=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 Et("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}}});import{betterFetch as vt}from"@better-fetch/fetch";var _e=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 vt("https://api.dropboxapi.com/2/users/get_current_account",{method:"POST",headers:{Authorization:`Bearer ${r.accessToken}`}});return n?null:{user:{id:o.account_id,name:o.name?.display_name,email:o.email,emailVerified:o.email_verified||!1,image:o.profile_photo_url},data:o}}}};import{betterFetch as _t}from"@better-fetch/fetch";var xe=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 _t("https://api.linkedin.com/v2/userinfo",{method:"GET",headers:{Authorization:`Bearer ${o.accessToken}`}});return i?null:{user:{id:n.sub,name:n.name,email:n.email,emailVerified:n.email_verified||!1,image:n.picture},data:n}}}};import{betterFetch as xt}from"@better-fetch/fetch";var ee=(e="")=>e.split("://").map(t=>t.replace(/\/{2,}/g,"/")).join("://"),Tt=e=>{let t=e||"https://gitlab.com";return{authorizationEndpoint:ee(`${t}/oauth/authorize`),tokenEndpoint:ee(`${t}/oauth/token`),userinfoEndpoint:ee(`${t}/api/v4/user`)}},Te=e=>{let{authorizationEndpoint:t,tokenEndpoint:r,userinfoEndpoint:o}=Tt(e.issuer),n="gitlab";return{id:n,name:"Gitlab",createAuthorizationURL:async({state:s,scopes:a,codeVerifier:u,redirectURI:c})=>{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:c,codeVerifier:u})},validateAuthorizationCode:async({code:s,redirectURI:a})=>y({code:s,redirectURI:e.redirectURI||a,options:e,tokenEndpoint:r}),async getUserInfo(s){let{data:a,error:u}=await xt(o,{headers:{authorization:`Bearer ${s.accessToken}`}});return u||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 Pt={apple:he,discord:we,facebook:be,github:Ae,microsoft:Re,google:ke,spotify:Ue,twitch:Ee,twitter:ve,dropbox:_e,linkedin:xe,gitlab:Te},Z=Object.keys(Pt);import{TimeSpan as Ot}from"oslo";import{createJWT as St,validateJWT as It}from"oslo/jwt";import{z as T}from"zod";import{APIError as $}from"better-call";import{APIError as N}from"better-call";import{z as M}from"zod";var te=()=>p("/get-session",{method:"GET",query:M.optional(M.object({disableCookieCache:M.boolean().optional()})),requireHeaders:!0},async e=>{try{let t=await e.getSignedCookie(e.context.authCookies.sessionToken.name,e.context.secret);if(!t)return e.json(null,{status:401});let r=await e.getSignedCookie(e.context.authCookies.sessionData.name,e.context.secret),o=await e.getSignedCookie(e.context.authCookies.dontRememberToken.name,e.context.secret);if(r&&e.context.options.session?.cookieCache?.enabled&&!e.query?.disableCookieCache){let c=JSON.parse(r)?.session;if(c?.expiresAt>new Date)return e.json(c)}let n=await e.context.internalAdapter.findSession(t);if(console.log({session:n}),!n||n.session.expiresAt<new Date)return D(e),n&&await e.context.internalAdapter.deleteSession(n.session.id),e.json(null,{status:401});if(o)return e.json(n);let i=e.context.sessionConfig.expiresIn,s=e.context.sessionConfig.updateAge;if(n.session.expiresAt.valueOf()-i*1e3+s*1e3<=Date.now()){let c=await e.context.internalAdapter.updateSession(n.session.id,{expiresAt:V(e.context.sessionConfig.expiresIn,"sec")});if(!c)return D(e),e.json(null,{status:401});let d=(c.expiresAt.valueOf()-Date.now())/1e3;return await x(e,{session:c,user:n.user},!1,{maxAge:d}),e.json({session:c,user:n.user})}return e.json(n)}catch(t){return e.context.logger.error(t),e.json(null,{status:500})}}),re=async e=>await te()({...e,_flag:"json",headers:e.headers}),v=H(async e=>{let t=await re(e);if(!t?.session)throw new N("UNAUTHORIZED");return{session:t}}),Pe=()=>p("/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)}),Oe=p("/revoke-session",{method:"POST",body:M.object({id:M.string()}),use:[v],requireHeaders:!0},async e=>{let t=e.body.id,r=await e.context.internalAdapter.findSession(t);if(!r)throw new N("BAD_REQUEST",{message:"Session not found"});if(r.session.userId!==e.context.session.user.id)throw new N("UNAUTHORIZED");try{await e.context.internalAdapter.deleteSession(t)}catch(o){throw e.context.logger.error(o),new N("INTERNAL_SERVER_ERROR")}return e.json({status:!0})}),Se=p("/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 N("INTERNAL_SERVER_ERROR")}return e.json({status:!0})});async function S(e,t,r){return await St("HS256",Buffer.from(e),{email:t.toLowerCase(),updateTo:r},{expiresIn:new Ot(1,"h"),issuer:"better-auth",subject:"verify-email",audiences:[t],includeIssuedTimestamp:!0})}var Ie=p("/send-verification-email",{method:"POST",query:T.object({currentURL:T.string().optional()}).optional(),body:T.object({email:T.string().email(),callbackURL:T.string().optional()})},async e=>{if(!e.context.options.emailVerification?.sendVerificationEmail)throw e.context.logger.error("Verification email isn't enabled."),new $("BAD_REQUEST",{message:"Verification email isn't enabled"});let{email:t}=e.body,r=await e.context.internalAdapter.findUserByEmail(t);if(!r)throw new $("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})}),Le=p("/verify-email",{method:"GET",query:T.object({token:T.string(),callbackURL:T.string().optional()})},async e=>{let{token:t}=e.query,r;try{r=await It("HS256",Buffer.from(e.context.secret),t)}catch(s){throw e.context.logger.error("Failed to verify email",s),new $("BAD_REQUEST",{message:"Invalid token"})}let n=T.object({email:T.string().email(),updateTo:T.string().optional()}).parse(r.payload);if(!await e.context.internalAdapter.findUserByEmail(n.email))throw new $("BAD_REQUEST",{message:"User not found"});if(n.updateTo){let s=await re(e);if(!s)throw e.query.callbackURL?e.redirect(`${e.query.callbackURL}?error=unauthorized`):new $("UNAUTHORIZED",{message:"Session not found"});if(s.user.email!==n.email)throw e.query.callbackURL?e.redirect(`${e.query.callbackURL}?error=unauthorized`):new $("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})});import{HMAC as Rn,sha256 as Un}from"oslo/crypto";var Ce=p("/sign-in/social",{method:"POST",requireHeaders:!0,query:_.object({currentURL:_.string().optional()}).optional(),body:_.object({callbackURL:_.string().optional(),provider:_.enum(Z)})},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 P("NOT_FOUND",{message:"Provider not found"});let{codeVerifier:r,state:o}=await Q(e),n=await t.createAuthorizationURL({state:o,codeVerifier:r,redirectURI:`${e.context.baseURL}/callback/${t.id}`});return e.json({url:n.toString(),redirect:!0})}),Be=p("/sign-in/email",{method:"POST",body:_.object({email:_.string(),password:_.string(),callbackURL:_.string().optional(),dontRememberMe:_.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 P("BAD_REQUEST",{message:"Email and password is not enabled"});let{email:t,password:r}=e.body;if(!_.string().email().safeParse(t).success)throw new P("BAD_REQUEST",{message:"Invalid email"});if(!_.string().email().safeParse(t).success)throw new P("BAD_REQUEST",{message:"Invalid email"});let i=await e.context.internalAdapter.findUserByEmail(t,{includeAccounts:!0});if(!i)throw await e.context.password.hash(r),e.context.logger.error("User not found",{email:t}),new P("UNAUTHORIZED",{message:"Invalid email or password"});let s=i.accounts.find(d=>d.providerId==="credential");if(!s)throw e.context.logger.error("Credential account not found",{email:t}),new P("UNAUTHORIZED",{message:"Invalid email or password"});let a=s?.password;if(!a)throw e.context.logger.error("Password not found",{email:t}),new P("UNAUTHORIZED",{message:"Unexpected error"});if(!await e.context.password.verify(a,r))throw e.context.logger.error("Invalid password"),new P("UNAUTHORIZED",{message:"Invalid email or password"});if(e.context.options?.emailAndPassword?.requireEmailVerification&&!i.user.emailVerified){if(!e.context.options?.emailVerification?.sendVerificationEmail)throw f.error("Email verification is required but no email verification handler is provided"),new P("INTERNAL_SERVER_ERROR",{message:"Email is not verified."});let d=await S(e.context.secret,i.user.email),g=`${e.context.options.baseURL}/verify-email?token=${d}`;throw await e.context.options.emailVerification.sendVerificationEmail(i.user,g,d),e.context.logger.error("Email not verified",{email:t}),new P("FORBIDDEN",{message:"Email is not verified. Check your email for a verification link"})}let c=await e.context.internalAdapter.createSession(i.user.id,e.headers,e.body.dontRememberMe);if(!c)throw e.context.logger.error("Failed to create session"),new P("UNAUTHORIZED",{message:"Failed to create session"});return await x(e,{session:c,user:i.user},e.body.dontRememberMe),e.json({user:i.user,session:c,redirect:!!e.body.callbackURL,url:e.body.callbackURL})});import{z as W}from"zod";import{z as h}from"zod";var $n=h.object({id:h.string(),providerId:h.string(),accountId:h.string(),userId:h.string(),accessToken:h.string().nullable().optional(),refreshToken:h.string().nullable().optional(),idToken:h.string().nullable().optional(),expiresAt:h.date().nullable().optional(),password:h.string().optional().nullable()}),De=h.object({id:h.string(),email:h.string().transform(e=>e.toLowerCase()),emailVerified:h.boolean().default(!1),name:h.string(),image:h.string().optional(),createdAt:h.date().default(new Date),updatedAt:h.date().default(new Date)}),jn=h.object({id:h.string(),userId:h.string(),expiresAt:h.date(),ipAddress:h.string().optional(),userAgent:h.string().optional()}),qn=h.object({id:h.string(),value:h.string(),expiresAt:h.date(),identifier:h.string()});function Lt(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 Ct(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 J(e,t,r){let o=Lt(e,"user");return Ct(t||{},{fields:o,action:r})}var ze=p("/callback/:id",{method:"GET",query:W.object({state:W.string(),code:W.string().optional(),error:W.string().optional()}),metadata:z},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 pe(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),u=se(),c=De.safeParse({...a,id:u});if(!a||c.success===!1)throw f.error("Unable to get user info",c.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 g=await e.context.internalAdapter.findUserByEmail(a.email,{includeAccounts:!0}).catch(w=>{throw f.error(`Better auth was unable to query your database.
|
|
4
4
|
Error: `,w),e.redirect(`${e.context.baseURL}/error?error=internal_server_error`)}),m=g?.user;if(g){let w=g.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)&&(ce&&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:g.user.id,accessToken:s.accessToken,idToken:s.idToken,refreshToken:s.refreshToken,expiresAt:s.accessTokenExpiresAt})}catch(oe){f.error("Unable to link account",oe),d("unable_to_link_account")}}}else try{let w=a.emailVerified||!1;if(m=await e.context.internalAdapter.createOAuthUser({...c.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&&m&&e.context.options.emailVerification?.sendOnSignUp){let b=await S(e.context.secret,m.email),R=`${e.context.baseURL}/verify-email?token=${b}&callbackURL=${o}`;await e.context.options.emailVerification?.sendVerificationEmail?.(m,R,b)}}catch(w){f.error("Unable to create user",w),d("unable_to_create_user")}if(!m)return d("unable_to_create_user");let l=await e.context.internalAdapter.createSession(m.id,e.request);l||d("unable_to_create_session"),await x(e,{session:l,user:m});let k;try{k=new URL(o).toString()}catch{k=o}throw e.redirect(k)});import"zod";import{APIError as Bt}from"better-call";var Ve=p("/sign-out",{method:"POST"},async e=>{let t=await e.getSignedCookie(e.context.authCookies.sessionToken.name,e.context.secret);if(!t)throw new Bt("BAD_REQUEST",{message:"Session not found"});return await e.context.internalAdapter.deleteSession(t),D(e),e.json({success:!0})});import{z as O}from"zod";import{APIError as Y}from"better-call";var $e=p("/forget-password",{method:"POST",body:O.object({email:O.string().email(),redirectTo:O.string()})},async e=>{if(!e.context.options.emailAndPassword?.sendResetPassword)throw e.context.logger.error("Reset password isn't enabled.Please pass an emailAndPassword.sendResetPasswordToken function in your auth config!"),new Y("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})}),je=p("/reset-password/:token",{method:"GET",query:O.object({callbackURL:O.string()})},async e=>{let{token:t}=e.params,r=e.query.callbackURL,o=r.startsWith("http")?r:`${e.context.options.baseURL}${r}`;if(!t||!r)throw e.redirect(`${e.context.baseURL}/error?error=INVALID_TOKEN`);let n=await e.context.internalAdapter.findVerificationValue(`reset-password:${t}`);throw!n||n.expiresAt<new Date?e.redirect(`${o}?error=INVALID_TOKEN`):e.redirect(`${o}${o.includes("?")?"&":"?"}token=${t}`)}),qe=p("/reset-password",{query:O.optional(O.object({token:O.string().optional(),currentURL:O.string().optional()})),method:"POST",body:O.object({newPassword:O.string()})},async e=>{let t=e.query?.token||(e.query?.currentURL?new URL(e.query.currentURL).searchParams.get("token"):"");if(!t)throw new Y("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 Y("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 Y("BAD_REQUEST",{message:"Failed to update password"});return e.json({status:!0})});import{z as U}from"zod";import{APIError as E}from"better-call";var Ne=()=>p("/update-user",{method:"POST",body:U.record(U.string(),U.any()),use:[v]},async e=>{let t=e.body;if(t.email)throw new E("BAD_REQUEST",{message:"You can't update email"});let{name:r,image:o,...n}=t,i=e.context.session;if(!o&&!r&&Object.keys(n).length===0)return e.json({user:i.user});let s=J(e.context.options,n,"update"),a=await e.context.internalAdapter.updateUserByEmail(i.user.email,{name:r,image:o,...s});return await x(e,{session:i.session,user:a}),e.json({user:a})}),Me=p("/change-password",{method:"POST",body:U.object({newPassword:U.string(),currentPassword:U.string(),revokeOtherSessions:U.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("BAD_REQUEST",{message:"Password is too short"});let s=e.context.password.config.maxPasswordLength;if(t.length>s)throw e.context.logger.error("Password is too long"),new E("BAD_REQUEST",{message:"Password too long"});let u=(await e.context.internalAdapter.findAccounts(n.user.id)).find(g=>g.providerId==="credential"&&g.password);if(!u||!u.password)throw new E("BAD_REQUEST",{message:"User does not have a password"});let c=await e.context.password.hash(t);if(!await e.context.password.verify(u.password,r))throw new E("BAD_REQUEST",{message:"Incorrect password"});if(await e.context.internalAdapter.updateAccount(u.id,{password:c}),o){await e.context.internalAdapter.deleteSessions(n.user.id);let g=await e.context.internalAdapter.createSession(n.user.id,e.headers);if(!g)throw new E("INTERNAL_SERVER_ERROR",{message:"Unable to create session"});await x(e,{session:g,user:n.user})}return e.json(n.user)}),Fe=p("/set-password",{method:"POST",body:U.object({newPassword:U.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("BAD_REQUEST",{message:"Password is too short"});let n=e.context.password.config.maxPasswordLength;if(t.length>n)throw e.context.logger.error("Password is too long"),new E("BAD_REQUEST",{message:"Password too long"});let s=(await e.context.internalAdapter.findAccounts(r.user.id)).find(u=>u.providerId==="credential"&&u.password),a=await e.context.password.hash(t);if(!s)return await e.context.internalAdapter.linkAccount({userId:r.user.id,providerId:"credential",accountId:r.user.id,password:a}),e.json(r.user);throw new E("BAD_REQUEST",{message:"user already has a password"})}),He=p("/delete-user",{method:"POST",body:U.object({password:U.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("BAD_REQUEST",{message:"User does not have a password"});if(!await e.context.password.verify(n.password,t))throw new E("BAD_REQUEST",{message:"Incorrect password"});return await e.context.internalAdapter.deleteUser(r.user.id),await e.context.internalAdapter.deleteSessions(r.user.id),D(e),e.json(null)}),Ge=p("/change-email",{method:"POST",query:U.object({currentURL:U.string().optional()}).optional(),body:U.object({newEmail:U.string().email(),callbackURL:U.string().optional()}),use:[v]},async e=>{if(!e.context.options.user?.changeEmail?.enabled)throw e.context.logger.error("Change email is disabled."),new E("BAD_REQUEST",{message:"Change email is disabled"});if(e.body.newEmail===e.context.session.user.email)throw e.context.logger.error("Email is the same"),new E("BAD_REQUEST",{message:"Email is the same"});if(await e.context.internalAdapter.findUserByEmail(e.body.newEmail))throw e.context.logger.error("Email already exists"),new E("BAD_REQUEST",{message:"Couldn't update your email"});if(e.context.session.user.emailVerified!==!0){let n=await e.context.internalAdapter.updateUserByEmail(e.context.session.user.email,{email:e.body.newEmail});return e.json({user:n,status:!0})}if(!e.context.options.user.changeEmail.sendChangeEmailVerification)throw e.context.logger.error("Verification email isn't enabled."),new E("BAD_REQUEST",{message:"Verification email isn't enabled"});let r=await 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 Dt=(e="Unknown")=>`<!DOCTYPE html>
|
|
5
5
|
<html lang="en">
|
|
6
6
|
<head>
|