better-auth 0.6.3-beta.5 → 0.7.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/adapters/drizzle.cjs +1 -1
- package/dist/adapters/drizzle.d.cts +2 -3
- package/dist/adapters/drizzle.d.ts +2 -3
- package/dist/adapters/drizzle.js +1 -1
- package/dist/adapters/kysely.cjs +1 -1
- package/dist/adapters/kysely.d.cts +2 -3
- package/dist/adapters/kysely.d.ts +2 -3
- package/dist/adapters/kysely.js +1 -1
- package/dist/adapters/mongodb.cjs +1 -1
- package/dist/adapters/mongodb.d.cts +2 -3
- package/dist/adapters/mongodb.d.ts +2 -3
- package/dist/adapters/mongodb.js +1 -1
- package/dist/adapters/prisma.cjs +1 -1
- package/dist/adapters/prisma.d.cts +2 -3
- package/dist/adapters/prisma.d.ts +2 -3
- package/dist/adapters/prisma.js +1 -1
- package/dist/api.cjs +1 -84
- package/dist/api.d.cts +2 -3
- package/dist/api.d.ts +2 -3
- package/dist/api.js +1 -1
- package/dist/{auth-DSaajKtw.d.ts → auth-Clegl4dW.d.cts} +49 -50
- package/dist/{auth-DkX9a_VV.d.cts → auth-fiexy-Ap.d.ts} +49 -50
- package/dist/chunk-2FEFLA5K.cjs +1 -0
- package/dist/chunk-2FTT4NBS.cjs +1 -0
- package/dist/chunk-4DCNB6OE.js +3 -0
- package/dist/chunk-4O3SREZX.cjs +1 -0
- package/dist/chunk-4RCA3ANL.cjs +1 -0
- package/dist/chunk-6BZ4ST3T.cjs +1 -0
- package/dist/chunk-7GKOOVQP.js +83 -0
- package/dist/chunk-DU4AD5NF.cjs +1 -0
- package/dist/chunk-FMHKIHLU.cjs +1 -0
- package/dist/chunk-G6DG5D6F.cjs +1 -0
- package/dist/chunk-GEA35WSS.js +1 -0
- package/dist/chunk-IYGMQ3UI.cjs +2 -0
- package/dist/chunk-J6NPEQIV.cjs +1 -0
- package/dist/chunk-JLIUR52U.cjs +1 -0
- package/dist/chunk-KIEUIIFX.js +1 -0
- package/dist/chunk-KY7ED5I7.cjs +3 -0
- package/dist/chunk-O4235OPJ.cjs +1 -0
- package/dist/{chunk-NPA4NTSC.js → chunk-OMVC24RE.js} +1 -1
- package/dist/chunk-QGRJEIVO.cjs +1 -0
- package/dist/{chunk-XM5N7EZG.js → chunk-T5ZV4O5D.js} +1 -1
- package/dist/chunk-UAH4AUYS.cjs +83 -0
- package/dist/chunk-UN6PZ3HT.js +1 -0
- package/dist/chunk-V7Z635RZ.cjs +1 -0
- package/dist/chunk-WFO5B3ON.cjs +1 -0
- package/dist/chunk-WPLWVNYU.cjs +1 -0
- package/dist/chunk-WWY76I3P.cjs +1 -0
- package/dist/chunk-XJR6RYEY.js +1 -0
- package/dist/client/plugins.cjs +1 -1
- package/dist/client/plugins.d.cts +4 -6
- package/dist/client/plugins.d.ts +4 -6
- package/dist/client/plugins.js +1 -1
- package/dist/client.cjs +1 -1
- package/dist/client.d.cts +2 -3
- package/dist/client.d.ts +2 -3
- package/dist/client.js +1 -1
- package/dist/cookies.cjs +1 -1
- package/dist/cookies.d.cts +2 -3
- package/dist/cookies.d.ts +2 -3
- package/dist/cookies.js +1 -1
- package/dist/crypto.cjs +1 -1
- package/dist/crypto.js +1 -1
- package/dist/db.cjs +1 -4
- package/dist/db.d.cts +3 -4
- package/dist/db.d.ts +3 -4
- package/dist/db.js +1 -1
- package/dist/{index-CUDsC5At.d.cts → index-BwRLAahA.d.ts} +51 -5
- package/dist/{index-BgRiS71T.d.cts → index-DUqGSAH3.d.cts} +118 -3
- package/dist/{index-CINoRb0u.d.ts → index-DUqGSAH3.d.ts} +118 -3
- package/dist/{index-TPdLZ0uM.d.ts → index-vi0Dko6t.d.cts} +51 -5
- package/dist/index.cjs +1 -84
- package/dist/index.d.cts +3 -4
- package/dist/index.d.ts +3 -4
- package/dist/index.js +1 -1
- package/dist/next-js.cjs +1 -1
- package/dist/next-js.js +1 -1
- package/dist/node.cjs +1 -1
- package/dist/node.d.cts +2 -3
- package/dist/node.d.ts +2 -3
- package/dist/node.js +1 -1
- package/dist/oauth2.cjs +1 -2
- package/dist/oauth2.d.cts +4 -5
- package/dist/oauth2.d.ts +4 -5
- package/dist/oauth2.js +1 -1
- package/dist/plugins.cjs +2 -85
- package/dist/plugins.d.cts +4 -7
- package/dist/plugins.d.ts +4 -7
- package/dist/plugins.js +2 -2
- package/dist/react.cjs +1 -1
- package/dist/react.d.cts +2 -3
- package/dist/react.d.ts +2 -3
- package/dist/react.js +1 -1
- package/dist/social.cjs +1 -2
- package/dist/social.d.cts +1 -2
- package/dist/social.d.ts +1 -2
- package/dist/social.js +1 -1
- package/dist/solid-start.cjs +1 -1
- package/dist/solid-start.d.cts +2 -3
- package/dist/solid-start.d.ts +2 -3
- package/dist/solid-start.js +1 -1
- package/dist/solid.cjs +1 -1
- package/dist/solid.d.cts +2 -3
- package/dist/solid.d.ts +2 -3
- package/dist/solid.js +1 -1
- package/dist/{state-DOMyLxNM.d.cts → state-C0fWhgUT.d.cts} +1 -1
- package/dist/{state-DEz_tQeq.d.ts → state-DdkSSZ5k.d.ts} +1 -1
- package/dist/svelte-kit.cjs +1 -1
- package/dist/svelte-kit.d.cts +2 -3
- package/dist/svelte-kit.d.ts +2 -3
- package/dist/svelte-kit.js +1 -1
- package/dist/svelte.cjs +1 -1
- package/dist/svelte.d.cts +2 -3
- package/dist/svelte.d.ts +2 -3
- package/dist/svelte.js +1 -1
- package/dist/types.cjs +1 -1
- package/dist/types.d.cts +4 -5
- package/dist/types.d.ts +4 -5
- package/dist/vue.cjs +1 -1
- package/dist/vue.d.cts +2 -3
- package/dist/vue.d.ts +2 -3
- package/dist/vue.js +1 -1
- package/package.json +38 -7
- package/dist/access.cjs +0 -1
- package/dist/access.d.cts +0 -4
- package/dist/access.d.ts +0 -4
- package/dist/access.js +0 -1
- package/dist/chunk-243PJVV3.js +0 -1
- package/dist/chunk-2H2PBNSK.js +0 -1
- package/dist/chunk-3GQOZ67F.js +0 -1
- package/dist/chunk-4A3FTBWV.js +0 -1
- package/dist/chunk-DUSH3DVI.js +0 -3
- package/dist/chunk-TQKSIOGY.js +0 -83
- package/dist/chunk-VMN4HLB7.js +0 -1
- package/dist/chunk-WOT6VMZA.js +0 -1
- package/dist/helper-DPDj8Nix.d.cts +0 -21
- package/dist/helper-DPDj8Nix.d.ts +0 -21
- package/dist/index-BkNFhk9A.d.cts +0 -24
- package/dist/index-DfAHOgpj.d.ts +0 -24
- package/dist/statement-CfnyN34h.d.ts +0 -81
- package/dist/statement-Da_cxgTI.d.cts +0 -81
|
@@ -1 +1 @@
|
|
|
1
|
-
"use strict";
|
|
1
|
+
"use strict";Object.defineProperty(exports, "__esModule", {value: true}); function _optionalChain(ops) { let lastAccessLHS = undefined; let value = ops[0]; let i = 1; while (i < ops.length) { const op = ops[i]; const fn = ops[i + 1]; i += 2; if ((op === 'optionalAccess' || op === 'optionalCall') && value == null) { return undefined; } if (op === 'access' || op === 'optionalAccess') { lastAccessLHS = value; value = fn(value); } else if (op === 'call' || op === 'optionalCall') { value = fn((...args) => value.call(lastAccessLHS, ...args)); lastAccessLHS = undefined; } } return value; }var _chunkJ6NPEQIVcjs = require('../chunk-J6NPEQIV.cjs');var _drizzleorm = require('drizzle-orm');function f(t,r){let i=r.schema;if(!i)throw new (0, _chunkJ6NPEQIVcjs.a)("Drizzle adapter failed to initialize. Schema not found. Please provide a schema object in the adapter options object.");let c=r.usePlural?`${t}s`:t,n=i[c];if(!n)throw new (0, _chunkJ6NPEQIVcjs.a)(`[# Drizzle Adapter]: The model "${t}" was not found in the schema object. Please pass the schema directly to the adapter options.`);return n}function m(t,r){if(!t)return[];if(t.length===1){let e=t[0];if(!e)return[];if(e.operator==="in"){if(!Array.isArray(e.value))throw new (0, _chunkJ6NPEQIVcjs.a)(`The value for the field "${e.field}" must be an array when using the "in" operator.`);return[_drizzleorm.inArray.call(void 0, r[e.field],e.value)]}return e.operator==="contains"?[_drizzleorm.like.call(void 0, r[e.field],`%${e.value}%`)]:e.operator==="starts_with"?[_drizzleorm.like.call(void 0, r[e.field],`${e.value}%`)]:e.operator==="ends_with"?[_drizzleorm.like.call(void 0, r[e.field],`%${e.value}`)]:[_drizzleorm.eq.call(void 0, r[e.field],e.value)]}let i=t.filter(e=>e.connector==="AND"||!e.connector),c=t.filter(e=>e.connector==="OR"),n=_drizzleorm.and.call(void 0, ...i.map(e=>{if(e.operator==="in"){if(!Array.isArray(e.value))throw new (0, _chunkJ6NPEQIVcjs.a)(`The value for the field "${e.field}" must be an array when using the "in" operator.`);return _drizzleorm.inArray.call(void 0, r[e.field],e.value)}return _drizzleorm.eq.call(void 0, r[e.field],e.value)})),l=_drizzleorm.or.call(void 0, ...c.map(e=>_drizzleorm.eq.call(void 0, r[e.field],e.value))),s=[];return i.length&&s.push(n),c.length&&s.push(l),s}var S=(t,r)=>{let i=r.schema||t._.fullSchema,c=_optionalChain([r, 'optionalAccess', _2 => _2.provider]);return{id:"drizzle",async create(n){let{model:l,data:s}=n,e=f(l,{schema:i,usePlural:r.usePlural});r.generateId!==void 0&&(s.id=r.generateId?r.generateId():void 0);let a=t.insert(e).values(s);return c!=="mysql"?(await a.returning())[0]:(await a,(await t.select().from(e).where(_drizzleorm.eq.call(void 0, e.id,n.data.id)))[0])},async findOne(n){let{model:l,where:s,select:e}=n,a=f(l,{schema:i,usePlural:r.usePlural}),u=m(s,a),o=null;return _optionalChain([e, 'optionalAccess', _3 => _3.length])?o=await t.select(...e.map(d=>({[d]:a[d]}))).from(a).where(...u):o=await t.select().from(a).where(...u),o.length?o[0]:null},async findMany(n){let{model:l,where:s,limit:e,offset:a,sortBy:u}=n,o=f(l,{schema:i,usePlural:r.usePlural}),d=s?m(s,o):[],g=_optionalChain([u, 'optionalAccess', _4 => _4.direction])==="desc"?_drizzleorm.desc:_drizzleorm.asc;return await t.select().from(o).limit(e||100).offset(a||0).orderBy(g(o[_optionalChain([u, 'optionalAccess', _5 => _5.field])||"id"])).where(...d.length?d:[])},async update(n){let{model:l,where:s,update:e}=n,a=f(l,{schema:i,usePlural:r.usePlural});e.id&&(e.id=void 0);let u=m(s,a),o=t.update(a).set(e).where(...u);return c!=="mysql"?(await o.returning())[0]:(await o,(await t.select().from(a).where(_drizzleorm.eq.call(void 0, a.id,n.update.id)))[0])},async delete(n){let{model:l,where:s}=n,e=f(l,{schema:i,usePlural:r.usePlural}),a=m(s,e);return(await t.delete(e).where(...a))[0]},async deleteMany(n){let{model:l,where:s}=n,e=f(l,{schema:i,usePlural:r.usePlural}),a=m(s,e);await t.delete(e).where(...a)},options:r}};exports.drizzleAdapter = S;
|
|
@@ -1,8 +1,7 @@
|
|
|
1
|
-
import { A as Adapter } from '../auth-
|
|
1
|
+
import { A as Adapter } from '../auth-Clegl4dW.cjs';
|
|
2
2
|
import 'zod';
|
|
3
3
|
import 'kysely';
|
|
4
|
-
import '../index-
|
|
5
|
-
import '../helper-DPDj8Nix.cjs';
|
|
4
|
+
import '../index-DUqGSAH3.cjs';
|
|
6
5
|
import 'better-call';
|
|
7
6
|
import 'better-sqlite3';
|
|
8
7
|
import 'mysql2';
|
|
@@ -1,8 +1,7 @@
|
|
|
1
|
-
import { A as Adapter } from '../auth-
|
|
1
|
+
import { A as Adapter } from '../auth-fiexy-Ap.js';
|
|
2
2
|
import 'zod';
|
|
3
3
|
import 'kysely';
|
|
4
|
-
import '../index-
|
|
5
|
-
import '../helper-DPDj8Nix.js';
|
|
4
|
+
import '../index-DUqGSAH3.js';
|
|
6
5
|
import 'better-call';
|
|
7
6
|
import 'better-sqlite3';
|
|
8
7
|
import 'mysql2';
|
package/dist/adapters/drizzle.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
import{a as h}from"../chunk-72JSMFWS.js";import
|
|
1
|
+
import{a as h}from"../chunk-72JSMFWS.js";import{and as v,asc as P,desc as z,eq as p,or as A,inArray as y,like as w}from"drizzle-orm";function f(t,r){let i=r.schema;if(!i)throw new h("Drizzle adapter failed to initialize. Schema not found. Please provide a schema object in the adapter options object.");let c=r.usePlural?`${t}s`:t,n=i[c];if(!n)throw new h(`[# Drizzle Adapter]: The model "${t}" was not found in the schema object. Please pass the schema directly to the adapter options.`);return n}function m(t,r){if(!t)return[];if(t.length===1){let e=t[0];if(!e)return[];if(e.operator==="in"){if(!Array.isArray(e.value))throw new h(`The value for the field "${e.field}" must be an array when using the "in" operator.`);return[y(r[e.field],e.value)]}return e.operator==="contains"?[w(r[e.field],`%${e.value}%`)]:e.operator==="starts_with"?[w(r[e.field],`${e.value}%`)]:e.operator==="ends_with"?[w(r[e.field],`%${e.value}`)]:[p(r[e.field],e.value)]}let i=t.filter(e=>e.connector==="AND"||!e.connector),c=t.filter(e=>e.connector==="OR"),n=v(...i.map(e=>{if(e.operator==="in"){if(!Array.isArray(e.value))throw new h(`The value for the field "${e.field}" must be an array when using the "in" operator.`);return y(r[e.field],e.value)}return p(r[e.field],e.value)})),l=A(...c.map(e=>p(r[e.field],e.value))),s=[];return i.length&&s.push(n),c.length&&s.push(l),s}var S=(t,r)=>{let i=r.schema||t._.fullSchema,c=r?.provider;return{id:"drizzle",async create(n){let{model:l,data:s}=n,e=f(l,{schema:i,usePlural:r.usePlural});r.generateId!==void 0&&(s.id=r.generateId?r.generateId():void 0);let a=t.insert(e).values(s);return c!=="mysql"?(await a.returning())[0]:(await a,(await t.select().from(e).where(p(e.id,n.data.id)))[0])},async findOne(n){let{model:l,where:s,select:e}=n,a=f(l,{schema:i,usePlural:r.usePlural}),u=m(s,a),o=null;return e?.length?o=await t.select(...e.map(d=>({[d]:a[d]}))).from(a).where(...u):o=await t.select().from(a).where(...u),o.length?o[0]:null},async findMany(n){let{model:l,where:s,limit:e,offset:a,sortBy:u}=n,o=f(l,{schema:i,usePlural:r.usePlural}),d=s?m(s,o):[],g=u?.direction==="desc"?z:P;return await t.select().from(o).limit(e||100).offset(a||0).orderBy(g(o[u?.field||"id"])).where(...d.length?d:[])},async update(n){let{model:l,where:s,update:e}=n,a=f(l,{schema:i,usePlural:r.usePlural});e.id&&(e.id=void 0);let u=m(s,a),o=t.update(a).set(e).where(...u);return c!=="mysql"?(await o.returning())[0]:(await o,(await t.select().from(a).where(p(a.id,n.update.id)))[0])},async delete(n){let{model:l,where:s}=n,e=f(l,{schema:i,usePlural:r.usePlural}),a=m(s,e);return(await t.delete(e).where(...a))[0]},async deleteMany(n){let{model:l,where:s}=n,e=f(l,{schema:i,usePlural:r.usePlural}),a=m(s,e);await t.delete(e).where(...a)},options:r}};export{S as drizzleAdapter};
|
package/dist/adapters/kysely.cjs
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
"use strict";
|
|
1
|
+
"use strict";Object.defineProperty(exports, "__esModule", {value: true});var _chunkWWY76I3Pcjs = require('../chunk-WWY76I3P.cjs');exports.createKyselyAdapter = _chunkWWY76I3Pcjs.a; exports.kyselyAdapter = _chunkWWY76I3Pcjs.b;
|
|
@@ -1,8 +1,7 @@
|
|
|
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-Clegl4dW.cjs';
|
|
3
3
|
import 'zod';
|
|
4
|
-
import '../index-
|
|
5
|
-
import '../helper-DPDj8Nix.cjs';
|
|
4
|
+
import '../index-DUqGSAH3.cjs';
|
|
6
5
|
import 'better-call';
|
|
7
6
|
import 'better-sqlite3';
|
|
8
7
|
import 'mysql2';
|
|
@@ -1,8 +1,7 @@
|
|
|
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-fiexy-Ap.js';
|
|
3
3
|
import 'zod';
|
|
4
|
-
import '../index-
|
|
5
|
-
import '../helper-DPDj8Nix.js';
|
|
4
|
+
import '../index-DUqGSAH3.js';
|
|
6
5
|
import 'better-call';
|
|
7
6
|
import 'better-sqlite3';
|
|
8
7
|
import 'mysql2';
|
package/dist/adapters/kysely.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
import{a,b}from"../chunk-CM4YNNZQ.js";
|
|
1
|
+
import{a,b}from"../chunk-CM4YNNZQ.js";export{a as createKyselyAdapter,b as kyselyAdapter};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
"use strict";
|
|
1
|
+
"use strict";Object.defineProperty(exports, "__esModule", {value: true}); function _optionalChain(ops) { let lastAccessLHS = undefined; let value = ops[0]; let i = 1; while (i < ops.length) { const op = ops[i]; const fn = ops[i + 1]; i += 2; if ((op === 'optionalAccess' || op === 'optionalCall') && value == null) { return undefined; } if (op === 'access' || op === 'optionalAccess') { lastAccessLHS = value; value = fn(value); } else if (op === 'call' || op === 'optionalCall') { value = fn((...args) => value.call(lastAccessLHS, ...args)); lastAccessLHS = undefined; } } return value; }function u(l){if(!l)return{};let d=l.map(n=>{let{field:t,value:e,operator:c="eq",connector:i="AND"}=n,o;switch(c.toLowerCase()){case"eq":o={[t]:e};break;case"in":o={[t]:{$in:Array.isArray(e)?e:[e]}};break;case"gt":o={[t]:{$gt:e}};break;case"gte":o={[t]:{$gte:e}};break;case"lt":o={[t]:{$lt:e}};break;case"lte":o={[t]:{$lte:e}};break;case"ne":o={[t]:{$ne:e}};break;case"contains":o={[t]:{$regex:`.*${e}.*`}};break;case"starts_with":o={[t]:{$regex:`${e}.*`}};break;case"ends_with":o={[t]:{$regex:`.*${e}`}};break;default:throw new Error(`Unsupported operator: ${c}`)}return{condition:o,connector:i}}),s=d.filter(n=>n.connector==="AND").map(n=>n.condition),a=d.filter(n=>n.connector==="OR").map(n=>n.condition),r={};return s.length&&(r={...r,$and:s}),a.length&&(r={...r,$or:a}),r}function f(l){let{_id:d,...s}=l;return s}function w(l){return l.reduce((s,a)=>(s[a]=1,s),{})}var m=(l,d)=>{let s=l,a=r=>_optionalChain([d, 'optionalAccess', _ => _.usePlural])?`${r}s`:r;return{id:"mongodb",async create(r){let{model:n,data:t}=r;_optionalChain([d, 'optionalAccess', _2 => _2.generateId])!==void 0&&(t.id=d.generateId?d.generateId():void 0);let c=(await s.collection(a(n)).insertOne({...t})).insertedId,i={...t,id:c};return f(i)},async findOne(r){let{model:n,where:t,select:e}=r,c=u(t),i={};e&&(i=w(e));let o=await s.collection(a(n)).findOne(c,{projection:i});return o?f(o):null},async findMany(r){let{model:n,where:t,limit:e,offset:c,sortBy:i}=r,o=u(t);return(await s.collection(a(n)).find(o).skip(c||0).limit(e||100).sort(_optionalChain([i, 'optionalAccess', _3 => _3.field])||"id",_optionalChain([i, 'optionalAccess', _4 => _4.direction])==="desc"?-1:1).toArray()).map(f)},async update(r){let{model:n,where:t,update:e}=r,c=u(t);if(e.id&&(e.id=void 0),t.length===1){let o=await s.collection(a(n)).findOneAndUpdate(c,{$set:e},{returnDocument:"after"});return f(o)}let i=await s.collection(a(n)).updateMany(c,{$set:e});return{}},async delete(r){let{model:n,where:t}=r,e=u(t),c=await s.collection(a(n)).findOneAndDelete(e)},async deleteMany(r){let{model:n,where:t}=r,e=u(t),c=await s.collection(a(n)).deleteMany(e)}}};exports.mongodbAdapter = m;
|
|
@@ -1,9 +1,8 @@
|
|
|
1
1
|
import { Db } from 'mongodb';
|
|
2
|
-
import { W as Where } from '../auth-
|
|
2
|
+
import { W as Where } from '../auth-Clegl4dW.cjs';
|
|
3
3
|
import 'zod';
|
|
4
4
|
import 'kysely';
|
|
5
|
-
import '../index-
|
|
6
|
-
import '../helper-DPDj8Nix.cjs';
|
|
5
|
+
import '../index-DUqGSAH3.cjs';
|
|
7
6
|
import 'better-call';
|
|
8
7
|
import 'better-sqlite3';
|
|
9
8
|
import 'mysql2';
|
|
@@ -1,9 +1,8 @@
|
|
|
1
1
|
import { Db } from 'mongodb';
|
|
2
|
-
import { W as Where } from '../auth-
|
|
2
|
+
import { W as Where } from '../auth-fiexy-Ap.js';
|
|
3
3
|
import 'zod';
|
|
4
4
|
import 'kysely';
|
|
5
|
-
import '../index-
|
|
6
|
-
import '../helper-DPDj8Nix.js';
|
|
5
|
+
import '../index-DUqGSAH3.js';
|
|
7
6
|
import 'better-call';
|
|
8
7
|
import 'better-sqlite3';
|
|
9
8
|
import 'mysql2';
|
package/dist/adapters/mongodb.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
|
|
1
|
+
function u(l){if(!l)return{};let d=l.map(n=>{let{field:t,value:e,operator:c="eq",connector:i="AND"}=n,o;switch(c.toLowerCase()){case"eq":o={[t]:e};break;case"in":o={[t]:{$in:Array.isArray(e)?e:[e]}};break;case"gt":o={[t]:{$gt:e}};break;case"gte":o={[t]:{$gte:e}};break;case"lt":o={[t]:{$lt:e}};break;case"lte":o={[t]:{$lte:e}};break;case"ne":o={[t]:{$ne:e}};break;case"contains":o={[t]:{$regex:`.*${e}.*`}};break;case"starts_with":o={[t]:{$regex:`${e}.*`}};break;case"ends_with":o={[t]:{$regex:`.*${e}`}};break;default:throw new Error(`Unsupported operator: ${c}`)}return{condition:o,connector:i}}),s=d.filter(n=>n.connector==="AND").map(n=>n.condition),a=d.filter(n=>n.connector==="OR").map(n=>n.condition),r={};return s.length&&(r={...r,$and:s}),a.length&&(r={...r,$or:a}),r}function f(l){let{_id:d,...s}=l;return s}function w(l){return l.reduce((s,a)=>(s[a]=1,s),{})}var m=(l,d)=>{let s=l,a=r=>d?.usePlural?`${r}s`:r;return{id:"mongodb",async create(r){let{model:n,data:t}=r;d?.generateId!==void 0&&(t.id=d.generateId?d.generateId():void 0);let c=(await s.collection(a(n)).insertOne({...t})).insertedId,i={...t,id:c};return f(i)},async findOne(r){let{model:n,where:t,select:e}=r,c=u(t),i={};e&&(i=w(e));let o=await s.collection(a(n)).findOne(c,{projection:i});return o?f(o):null},async findMany(r){let{model:n,where:t,limit:e,offset:c,sortBy:i}=r,o=u(t);return(await s.collection(a(n)).find(o).skip(c||0).limit(e||100).sort(i?.field||"id",i?.direction==="desc"?-1:1).toArray()).map(f)},async update(r){let{model:n,where:t,update:e}=r,c=u(t);if(e.id&&(e.id=void 0),t.length===1){let o=await s.collection(a(n)).findOneAndUpdate(c,{$set:e},{returnDocument:"after"});return f(o)}let i=await s.collection(a(n)).updateMany(c,{$set:e});return{}},async delete(r){let{model:n,where:t}=r,e=u(t),c=await s.collection(a(n)).findOneAndDelete(e)},async deleteMany(r){let{model:n,where:t}=r,e=u(t),c=await s.collection(a(n)).deleteMany(e)}}};export{m as mongodbAdapter};
|
package/dist/adapters/prisma.cjs
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
"use strict";
|
|
1
|
+
"use strict";Object.defineProperty(exports, "__esModule", {value: true}); function _optionalChain(ops) { let lastAccessLHS = undefined; let value = ops[0]; let i = 1; while (i < ops.length) { const op = ops[i]; const fn = ops[i + 1]; i += 2; if ((op === 'optionalAccess' || op === 'optionalCall') && value == null) { return undefined; } if (op === 'access' || op === 'optionalAccess') { lastAccessLHS = value; value = fn(value); } else if (op === 'call' || op === 'optionalCall') { value = fn((...args) => value.call(lastAccessLHS, ...args)); lastAccessLHS = undefined; } } return value; }function f(a){switch(a){case"starts_with":return"startsWith";case"ends_with":return"endsWith";default:return a}}function c(a){if(!a)return{};if(a.length===1){let e=a[0];return e?{[e.field]:e.operator==="eq"||!e.operator?e.value:{[f(e.operator)]:e.value}}:void 0}let l=a.filter(e=>e.connector==="AND"||!e.connector),s=a.filter(e=>e.connector==="OR"),o=l.map(e=>({[e.field]:e.operator==="eq"||!e.operator?e.value:{[f(e.operator)]:e.value}})),r=s.map(e=>({[e.field]:{[e.operator||"eq"]:e.value}}));return{AND:o.length?o:void 0,OR:r.length?r:void 0}}var y=(a,l)=>{let s=a,o=l.generateId;return{id:"prisma",async create(r){let{model:e,data:n,select:t}=r;return o!==void 0&&(n.id=o?o():void 0),await s[e].create({data:n,..._optionalChain([t, 'optionalAccess', _ => _.length])?{select:t.reduce((d,i)=>({...d,[i]:!0}),{})}:{}})},async findOne(r){let{model:e,where:n,select:t}=r,d=c(n);return await s[e].findFirst({where:d,..._optionalChain([t, 'optionalAccess', _2 => _2.length])?{select:t.reduce((i,u)=>({...i,[u]:!0}),{})}:{}})},async findMany(r){let{model:e,where:n,limit:t,offset:d,sortBy:i}=r,u=c(n);return await s[e].findMany({where:u,take:t||100,skip:d||0,orderBy:_optionalChain([i, 'optionalAccess', _3 => _3.field])?{[i.field]:i.direction==="desc"?"desc":"asc"}:void 0})},async update(r){let{model:e,where:n,update:t}=r;t.id&&(t.id=void 0);let d=c(n);return n.length===1?await s[e].update({where:d,data:t}):await s[e].updateMany({where:d,data:t})},async delete(r){let{model:e,where:n}=r,t=c(n);return await s[e].delete({where:t}).catch(d=>{})},async deleteMany(r){let{model:e,where:n}=r,t=c(n);return await s[e].deleteMany({where:t})},options:l}};exports.prismaAdapter = y;
|
|
@@ -1,8 +1,7 @@
|
|
|
1
|
-
import { A as Adapter } from '../auth-
|
|
1
|
+
import { A as Adapter } from '../auth-Clegl4dW.cjs';
|
|
2
2
|
import 'zod';
|
|
3
3
|
import 'kysely';
|
|
4
|
-
import '../index-
|
|
5
|
-
import '../helper-DPDj8Nix.cjs';
|
|
4
|
+
import '../index-DUqGSAH3.cjs';
|
|
6
5
|
import 'better-call';
|
|
7
6
|
import 'better-sqlite3';
|
|
8
7
|
import 'mysql2';
|
|
@@ -1,8 +1,7 @@
|
|
|
1
|
-
import { A as Adapter } from '../auth-
|
|
1
|
+
import { A as Adapter } from '../auth-fiexy-Ap.js';
|
|
2
2
|
import 'zod';
|
|
3
3
|
import 'kysely';
|
|
4
|
-
import '../index-
|
|
5
|
-
import '../helper-DPDj8Nix.js';
|
|
4
|
+
import '../index-DUqGSAH3.js';
|
|
6
5
|
import 'better-call';
|
|
7
6
|
import 'better-sqlite3';
|
|
8
7
|
import 'mysql2';
|
package/dist/adapters/prisma.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
|
|
1
|
+
function f(a){switch(a){case"starts_with":return"startsWith";case"ends_with":return"endsWith";default:return a}}function c(a){if(!a)return{};if(a.length===1){let e=a[0];return e?{[e.field]:e.operator==="eq"||!e.operator?e.value:{[f(e.operator)]:e.value}}:void 0}let l=a.filter(e=>e.connector==="AND"||!e.connector),s=a.filter(e=>e.connector==="OR"),o=l.map(e=>({[e.field]:e.operator==="eq"||!e.operator?e.value:{[f(e.operator)]:e.value}})),r=s.map(e=>({[e.field]:{[e.operator||"eq"]:e.value}}));return{AND:o.length?o:void 0,OR:r.length?r:void 0}}var y=(a,l)=>{let s=a,o=l.generateId;return{id:"prisma",async create(r){let{model:e,data:n,select:t}=r;return o!==void 0&&(n.id=o?o():void 0),await s[e].create({data:n,...t?.length?{select:t.reduce((d,i)=>({...d,[i]:!0}),{})}:{}})},async findOne(r){let{model:e,where:n,select:t}=r,d=c(n);return await s[e].findFirst({where:d,...t?.length?{select:t.reduce((i,u)=>({...i,[u]:!0}),{})}:{}})},async findMany(r){let{model:e,where:n,limit:t,offset:d,sortBy:i}=r,u=c(n);return await s[e].findMany({where:u,take:t||100,skip:d||0,orderBy:i?.field?{[i.field]:i.direction==="desc"?"desc":"asc"}:void 0})},async update(r){let{model:e,where:n,update:t}=r;t.id&&(t.id=void 0);let d=c(n);return n.length===1?await s[e].update({where:d,data:t}):await s[e].updateMany({where:d,data:t})},async delete(r){let{model:e,where:n}=r,t=c(n);return await s[e].delete({where:t}).catch(d=>{})},async deleteMany(r){let{model:e,where:n}=r,t=c(n);return await s[e].deleteMany({where:t})},options:l}};export{y as prismaAdapter};
|
package/dist/api.cjs
CHANGED
|
@@ -1,84 +1 @@
|
|
|
1
|
-
"use strict";
|
|
2
|
-
`)}}),f=It();var le=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,l=o.trustedOrigins,c=e.headers?.has("cookie"),d=(h,m)=>{if(!l.some(R=>h?.startsWith(R)||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: ${l}`),new Me.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 x=require("better-call"),Qo=require("oslo/oauth2"),v=require("zod");var Ct=require("oslo");async function P(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})}var We=require("oslo/jwt");var He=require("oslo/crypto"),Qe=require("oslo/encoding");var q=(e,t="ms")=>new Date(Date.now()+(t==="sec"?e*1e3:e));async function Ge(e){let t=await(0,He.sha256)(new TextEncoder().encode(e));return Qe.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?q(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:l}){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||l),!a&&n){let d=await Ge(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 b({code:e,codeVerifier:t,redirectURI:r,options:o,tokenEndpoint:n}){let i=new URLSearchParams;i.set("grant_type","authorization_code"),i.set("code",e),t&&i.set("code_verifier",t),i.set("redirect_uri",r),i.set("client_id",o.clientId),i.set("client_secret",o.clientSecret);let{data:s,error: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})=>b({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})=>b({code:t,redirectURI:e.redirectURI||r,options:e,tokenEndpoint:"https://discord.com/api/oauth2/token"}),async getUserInfo(t){let{data:r,error:o}=await(0,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})=>b({code:t,redirectURI:e.redirectURI||r,options:e,tokenEndpoint:"https://graph.facebook.com/oauth/access_token"}),async getUserInfo(t){let{data:r,error:o}=await(0,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})=>b({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(l=>l.primary)??s[0])?.email,i=s.find(l=>l.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 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})=>b({code:t,codeVerifier:r,redirectURI:e.redirectURI||o,options:e,tokenEndpoint:"https://oauth2.googleapis.com/token"}),async getUserInfo(t){if(!t.idToken)return null;let r=(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 b({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(l){f.error(l)}}}),{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})=>b({code:t,codeVerifier:r,redirectURI:e.redirectURI||o,options:e,tokenEndpoint:"https://accounts.spotify.com/api/token"}),async getUserInfo(t){let{data:r,error:o}=await(0,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 no=require("@better-fetch/fetch");var lt=require("oslo/jwt");var ut=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})=>b({code:t,redirectURI:e.redirectURI||r,options:e,tokenEndpoint:"https://id.twitch.tv/oauth2/token"}),async getUserInfo(t){let r=t.idToken;if(!r)return f.error("No idToken found in token"),null;let o=(0,lt.parseJWT)(r)?.payload;return{user:{id:o.sub,name:o.preferred_username,email:o.email,image:o.picture,emailVerified:!1},data:o}}});var pt=require("@better-fetch/fetch");var mt=e=>({id:"twitter",name:"Twitter",createAuthorizationURL(t){let r=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})=>b({code:t,codeVerifier:r,redirectURI:e.redirectURI||o,options:e,tokenEndpoint:"https://id.twitch.tv/oauth2/token"}),async getUserInfo(t){let{data:r,error:o}=await(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 b({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 b({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={apple:Ye,discord:Xe,facebook:tt,github:rt,microsoft:at,google:nt,spotify:dt,twitch:ut,twitter:mt,dropbox:gt,linkedin:wt},X=Object.keys(Bt);var yt=require("oslo"),re=require("oslo/jwt"),_=require("zod");var V=require("better-call");var N=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 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:q(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 P(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}),E=H(async e=>{let t=await te(e);if(!t?.session)throw new N.APIError("UNAUTHORIZED");return{session:t}}),pe=()=>p("/list-sessions",{method:"GET",use:[E],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:[E],requireHeaders:!0},async e=>{let t=e.body.id,r=await e.context.internalAdapter.findSession(t);if(!r)throw new N.APIError("BAD_REQUEST",{message:"Session not found"});if(r.session.userId!==e.context.session.user.id)throw new N.APIError("UNAUTHORIZED");try{await e.context.internalAdapter.deleteSession(t)}catch(o){throw e.context.logger.error(o),new N.APIError("INTERNAL_SERVER_ERROR")}return e.json({status:!0})}),fe=p("/revoke-sessions",{method:"POST",use:[E],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.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 yt.TimeSpan(1,"h"),issuer:"better-auth",subject:"verify-email",audiences:[t],includeIssuedTimestamp:!0})}var ge=p("/send-verification-email",{method:"POST",query:_.z.object({currentURL:_.z.string().optional()}).optional(),body:_.z.object({email:_.z.string().email(),callbackURL:_.z.string().optional()})},async e=>{if(!e.context.options.emailVerification?.sendVerificationEmail)throw e.context.logger.error("Verification email isn't enabled."),new 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:_.z.object({token:_.z.string(),callbackURL:_.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=_.z.object({email:_.z.string().email(),updateTo:_.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 we=p("/sign-in/social",{method:"POST",requireHeaders:!0,query:v.z.object({currentURL:v.z.string().optional()}).optional(),body:v.z.object({callbackURL:v.z.string().optional(),provider:v.z.enum(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 x.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})}),ye=p("/sign-in/email",{method:"POST",body:v.z.object({email:v.z.string(),password:v.z.string(),callbackURL:v.z.string().optional(),dontRememberMe:v.z.boolean().default(!1).optional()})},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 x.APIError("BAD_REQUEST",{message:"Email and password is not enabled"});let{email:t,password:r}=e.body;if(!v.z.string().email().safeParse(t).success)throw new x.APIError("BAD_REQUEST",{message:"Invalid email"});if(!v.z.string().email().safeParse(t).success)throw new x.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 x.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 x.APIError("UNAUTHORIZED",{message:"Invalid email or password"});let a=s?.password;if(!a)throw e.context.logger.error("Password not found",{email:t}),new x.APIError("UNAUTHORIZED",{message:"Unexpected error"});if(!await e.context.password.verify(a,r))throw e.context.logger.error("Invalid password"),new x.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 x.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 x.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 x.APIError("UNAUTHORIZED",{message:"Failed to create session"});return await P(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"),rn=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()}),bt=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)}),on=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()}),nn=g.z.object({id:g.z.string(),value:g.z.string(),expiresAt:g.z.date(),identifier:g.z.string()});function Dt(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 Vt(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=Dt(e,"user");return Vt(t||{},{fields:o,action:r})}var be=p("/callback/:id",{method:"GET",query:Z.z.object({state:Z.z.string(),code:Z.z.string().optional(),error:Z.z.string().optional()}),metadata:j},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),l=De(),c=bt.safeParse({...a,id:l});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");throw e.redirect(i||o||e.context.options.baseURL)}function d(w){throw e.redirect(`${i||o||`${e.context.baseURL}/error`}?error=${w}`)}let h=await e.context.internalAdapter.findUserByEmail(a.email,{includeAccounts:!0}).catch(w=>{throw f.error(`Better auth was unable to query your database.
|
|
4
|
-
Error: `,w),e.redirect(`${e.context.baseURL}/error?error=internal_server_error`)}),m=h?.user;if(h){let w=h.accounts.find(y=>y.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(ne){f.error("Unable to link account",ne),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(y=>y?.user),!w&&m&&e.context.options.emailVerification?.sendOnSignUp){let y=await S(e.context.secret,m.email),L=`${e.context.baseURL}/verify-email?token=${y}&callbackURL=${o}`;await e.context.options.emailVerification?.sendVerificationEmail?.(m,L,y)}}catch(w){f.error("Unable to create user",w),d("unable_to_create_user")}if(!m)return d("unable_to_create_user");let u=await e.context.internalAdapter.createSession(m.id,e.request);u||d("unable_to_create_session"),await P(e,{session:u,user:m});let R=new URL(o);throw e.redirect(R.toString())});var wn=require("zod");var At=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 At.APIError("BAD_REQUEST",{message:"Session not found"});return await e.context.internalAdapter.deleteSession(t),D(e),e.json({success:!0})});var T=require("zod");var J=require("better-call"),ke=p("/forget-password",{method:"POST",body:T.z.object({email:T.z.string().email(),redirectTo:T.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:T.z.object({callbackURL:T.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:T.z.optional(T.z.object({token:T.z.string().optional(),currentURL:T.z.string().optional()})),method:"POST",body:T.z.object({newPassword:T.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 k=require("zod");var U=require("better-call");var Ee=()=>p("/update-user",{method:"POST",body:k.z.record(k.z.string(),k.z.any()),use:[E]},async e=>{let t=e.body;if(t.email)throw new U.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 P(e,{session:i.session,user:a}),e.json({user:a})}),ve=p("/change-password",{method:"POST",body:k.z.object({newPassword:k.z.string(),currentPassword:k.z.string(),revokeOtherSessions:k.z.boolean().optional()}),use:[E]},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 U.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 U.APIError("BAD_REQUEST",{message:"Password too long"});let l=(await e.context.internalAdapter.findAccounts(n.user.id)).find(h=>h.providerId==="credential"&&h.password);if(!l||!l.password)throw new U.APIError("BAD_REQUEST",{message:"User does not have a password"});let c=await e.context.password.hash(t);if(!await e.context.password.verify(l.password,r))throw new U.APIError("BAD_REQUEST",{message:"Incorrect password"});if(await e.context.internalAdapter.updateAccount(l.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 U.APIError("INTERNAL_SERVER_ERROR",{message:"Unable to create session"});await P(e,{session:h,user:n.user})}return e.json(n.user)}),_e=p("/set-password",{method:"POST",body:k.z.object({newPassword:k.z.string()}),metadata:{SERVER_ONLY:!0},use:[E]},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 U.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 U.APIError("BAD_REQUEST",{message:"Password too long"});let s=(await e.context.internalAdapter.findAccounts(r.user.id)).find(l=>l.providerId==="credential"&&l.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 U.APIError("BAD_REQUEST",{message:"user already has a password"})}),xe=p("/delete-user",{method:"POST",body:k.z.object({password:k.z.string()}),use:[E]},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 U.APIError("BAD_REQUEST",{message:"User does not have a password"});if(!await e.context.password.verify(n.password,t))throw new U.APIError("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)}),Te=p("/change-email",{method:"POST",query:k.z.object({currentURL:k.z.string().optional()}).optional(),body:k.z.object({newEmail:k.z.string().email(),callbackURL:k.z.string().optional()}),use:[E]},async e=>{if(!e.context.options.user?.changeEmail?.enabled)throw e.context.logger.error("Change email is disabled."),new U.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 U.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 U.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 U.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 zt=(e="Unknown")=>`<!DOCTYPE html>
|
|
5
|
-
<html lang="en">
|
|
6
|
-
<head>
|
|
7
|
-
<meta charset="UTF-8">
|
|
8
|
-
<meta name="viewport" content="width=device-width, initial-scale=1.0">
|
|
9
|
-
<title>Authentication Error</title>
|
|
10
|
-
<style>
|
|
11
|
-
:root {
|
|
12
|
-
--bg-color: #f8f9fa;
|
|
13
|
-
--text-color: #212529;
|
|
14
|
-
--accent-color: #000000;
|
|
15
|
-
--error-color: #dc3545;
|
|
16
|
-
--border-color: #e9ecef;
|
|
17
|
-
}
|
|
18
|
-
body {
|
|
19
|
-
font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, 'Helvetica Neue', Arial, sans-serif;
|
|
20
|
-
background-color: var(--bg-color);
|
|
21
|
-
color: var(--text-color);
|
|
22
|
-
display: flex;
|
|
23
|
-
justify-content: center;
|
|
24
|
-
align-items: center;
|
|
25
|
-
height: 100vh;
|
|
26
|
-
margin: 0;
|
|
27
|
-
line-height: 1.5;
|
|
28
|
-
}
|
|
29
|
-
.error-container {
|
|
30
|
-
background-color: #ffffff;
|
|
31
|
-
border-radius: 12px;
|
|
32
|
-
box-shadow: 0 4px 6px rgba(0, 0, 0, 0.05);
|
|
33
|
-
padding: 2.5rem;
|
|
34
|
-
text-align: center;
|
|
35
|
-
max-width: 90%;
|
|
36
|
-
width: 400px;
|
|
37
|
-
}
|
|
38
|
-
h1 {
|
|
39
|
-
color: var(--error-color);
|
|
40
|
-
font-size: 1.75rem;
|
|
41
|
-
margin-bottom: 1rem;
|
|
42
|
-
font-weight: 600;
|
|
43
|
-
}
|
|
44
|
-
p {
|
|
45
|
-
margin-bottom: 1.5rem;
|
|
46
|
-
color: #495057;
|
|
47
|
-
}
|
|
48
|
-
.btn {
|
|
49
|
-
background-color: var(--accent-color);
|
|
50
|
-
color: #ffffff;
|
|
51
|
-
text-decoration: none;
|
|
52
|
-
padding: 0.75rem 1.5rem;
|
|
53
|
-
border-radius: 6px;
|
|
54
|
-
transition: all 0.3s ease;
|
|
55
|
-
display: inline-block;
|
|
56
|
-
font-weight: 500;
|
|
57
|
-
border: 2px solid var(--accent-color);
|
|
58
|
-
}
|
|
59
|
-
.btn:hover {
|
|
60
|
-
background-color: #131721;
|
|
61
|
-
}
|
|
62
|
-
.error-code {
|
|
63
|
-
font-size: 0.875rem;
|
|
64
|
-
color: #6c757d;
|
|
65
|
-
margin-top: 1.5rem;
|
|
66
|
-
padding-top: 1.5rem;
|
|
67
|
-
border-top: 1px solid var(--border-color);
|
|
68
|
-
}
|
|
69
|
-
.icon {
|
|
70
|
-
font-size: 3rem;
|
|
71
|
-
margin-bottom: 1rem;
|
|
72
|
-
}
|
|
73
|
-
</style>
|
|
74
|
-
</head>
|
|
75
|
-
<body>
|
|
76
|
-
<div class="error-container">
|
|
77
|
-
<div class="icon">\u26A0\uFE0F</div>
|
|
78
|
-
<h1>Better Auth Error</h1>
|
|
79
|
-
<p>We encountered an issue while processing your request. Please try again or contact the application owner if the problem persists.</p>
|
|
80
|
-
<a href="/" id="returnLink" class="btn">Return to Application</a>
|
|
81
|
-
<div class="error-code">Error Code: <span id="errorCode">${e}</span></div>
|
|
82
|
-
</div>
|
|
83
|
-
</body>
|
|
84
|
-
</html>`,Pe=p("/error",{method:"GET",metadata:j},async e=>{let t=new URL(e.request?.url||"").searchParams.get("error")||"Unknown";return new Response(zt(t),{headers:{"Content-Type":"text/html"}})});var Se=p("/ok",{method:"GET",metadata:j},async e=>e.json({ok:!0}));var z=require("zod");var O=require("better-call");var Oe=()=>p("/sign-up/email",{method:"POST",query:z.z.object({currentURL:z.z.string().optional()}).optional(),body:z.z.record(z.z.string(),z.z.any())},async e=>{if(!e.context.options.emailAndPassword?.enabled)throw new O.APIError("BAD_REQUEST",{message:"Email and password sign up is not enabled"});let t=e.body,{name:r,email:o,password:n,image:i,callbackURL:s,...a}=t;if(!z.z.string().email().safeParse(o).success)throw new O.APIError("BAD_REQUEST",{message:"Invalid email"});let c=e.context.password.config.minPasswordLength;if(n.length<c)throw e.context.logger.error("Password is too short"),new O.APIError("BAD_REQUEST",{message:"Password is too short"});let d=e.context.password.config.maxPasswordLength;if(n.length>d)throw e.context.logger.error("Password is too long"),new O.APIError("BAD_REQUEST",{message:"Password is too long"});if((await e.context.internalAdapter.findUserByEmail(o))?.user)throw e.context.logger.info(`Sign-up attempt for existing email: ${o}`),new O.APIError("UNPROCESSABLE_ENTITY",{message:"User with this email already exists"});let m=oe(e.context.options,a),u;try{if(u=await e.context.internalAdapter.createUser({email:o.toLowerCase(),name:r,image:i,...m,emailVerified:!1}),!u)throw new O.APIError("BAD_REQUEST",{message:"Failed to create user"})}catch(y){throw f.error("Failed to create user",y),new O.APIError("UNPROCESSABLE_ENTITY",{message:"Failed to create user",details:y})}if(!u)throw new O.APIError("UNPROCESSABLE_ENTITY",{message:"Failed to create user"});let R=await e.context.password.hash(n);if(await e.context.internalAdapter.linkAccount({userId:u.id,providerId:"credential",accountId:u.id,password:R,expiresAt:q(60*60*24*30,"sec")}),e.context.options.emailVerification?.sendOnSignUp){let y=await S(e.context.secret,u.email),L=`${e.context.baseURL}/verify-email?token=${y}&callbackURL=${t.callbackURL||e.query?.currentURL||"/"}`;await e.context.options.emailVerification?.sendVerificationEmail?.(u,L,y)}if(!e.context.options.emailAndPassword.autoSignIn||e.context.options.emailAndPassword.requireEmailVerification)return e.json({user:u,session:null},{body:t.callbackURL?{url:t.callbackURL,redirect:!0}:{user:u,session:null}});let w=await e.context.internalAdapter.createSession(u.id,e.request);if(!w)throw new O.APIError("BAD_REQUEST",{message:"Failed to create session"});return await P(e,{session:w,user:u}),e.json({user:u,session:w})});var M=require("zod");var Le=require("better-call");var Kn=require("oslo/oauth2");var Ie=p("/list-accounts",{method:"GET",use:[E]},async e=>{let t=e.context.session,r=await e.context.internalAdapter.findAccounts(t.user.id);return e.json(r)}),Ce=p("/link-social",{method:"POST",requireHeaders:!0,query:M.z.object({currentURL:M.z.string().optional()}).optional(),body:M.z.object({callbackURL:M.z.string().optional(),provider:M.z.enum(X)}),use:[E]},async e=>{let t=e.context.session;if((await e.context.internalAdapter.findAccounts(t.user.id)).find(a=>a.providerId===e.body.provider))throw new Le.APIError("BAD_REQUEST",{message:"Social Account is already linked."});let n=e.context.socialProviders.find(a=>a.id===e.body.provider);if(!n)throw e.context.logger.error("Provider not found. Make sure to add the provider in your auth config",{provider:e.body.provider}),new Le.APIError("NOT_FOUND",{message:"Provider not found"});let i=await K(e),s=await n.createAuthorizationURL({state:i.state,codeVerifier:i.codeVerifier,redirectURI:`${e.context.baseURL}/callback/${n.id}`});return e.json({url:s.toString(),redirect:!0})});function kt(e){let t="127.0.0.1";if(je)return t;let r=["x-client-ip","x-forwarded-for","cf-connecting-ip","fastly-client-ip","x-real-ip","x-cluster-client-ip","x-forwarded","forwarded-for","forwarded"],o=e instanceof Request?e.headers:e;for(let n of r){let i=o.get(n);if(typeof i=="string"){let s=i.split(",")[0].trim();if(s)return s}}return null}function $t(e,t,r){let o=Date.now(),n=t*1e3;return o-r.lastRequest<n&&r.count>=e}function jt(e){return new Response(JSON.stringify({message:"Too many requests. Please try again later."}),{status:429,statusText:"Too Many Requests",headers:{"X-Retry-After":e.toString()}})}function qt(e,t){let r=Date.now(),o=t*1e3;return Math.ceil((e+o-r)/1e3)}function Nt(e,t){let r=t??"rateLimit",o=e.adapter;return{get:async n=>await o.findOne({model:r,where:[{field:"key",value:n}]}),set:async(n,i,s)=>{try{s?await o.update({model:t??"rateLimit",where:[{field:"key",value:n}],update:{count:i.count,lastRequest:i.lastRequest}}):await o.create({model:t??"rateLimit",data:{key:n,count:i.count,lastRequest:i.lastRequest}})}catch(a){f.error("Error setting rate limit",a)}}}}var Rt=new Map;function Ft(e){return e.rateLimit.storage==="secondary-storage"?{get:async r=>{let o=await e.options.secondaryStorage?.get(r);return o?JSON.parse(o):void 0},set:async(r,o)=>{await e.options.secondaryStorage?.set?.(r,JSON.stringify(o))}}:e.rateLimit.storage==="memory"?{async get(r){return Rt.get(r)},async set(r,o,n){Rt.set(r,o)}}:Nt(e,e.rateLimit.tableName)}async function Ut(e,t){if(!t.rateLimit.enabled)return;let r=t.baseURL,o=e.url.replace(r,""),n=t.rateLimit.window,i=t.rateLimit.max,s=kt(e)+o,l=Mt().find(m=>m.pathMatcher(o));l&&(n=l.window,i=l.max);for(let m of t.options.plugins||[])if(m.rateLimit){let u=m.rateLimit.find(R=>R.pathMatcher(o));if(u){n=u.window,i=u.max;break}}if(t.rateLimit.customRules){let m=t.rateLimit.customRules[o];m&&(n=m.window,i=m.max)}let c=Ft(t),d=await c.get(s),h=Date.now();if(!d)await c.set(s,{key:s,count:1,lastRequest:h});else{let m=h-d.lastRequest;if($t(i,n,d)){let u=qt(d.lastRequest,n);return jt(u)}else m>n*1e3?await c.set(s,{...d,count:1,lastRequest:h}):await c.set(s,{...d,count:d.count+1,lastRequest:h})}}function Mt(){return[{pathMatcher(t){return t.startsWith("/sign-in")||t.startsWith("/sign-up")},window:10,max:3}]}var vt=require("better-call");function Et(e,t){let r=t.plugins?.reduce((a,l)=>({...a,...l.endpoints}),{}),o=t.plugins?.map(a=>a.middlewares?.map(l=>{let c=async d=>l.middleware({...d,context:{...e,...d.context}});return c.path=l.path,c.options=l.middleware.options,c.headers=l.middleware.headers,{path:l.path,middleware:c}})).filter(a=>a!==void 0).flat()||[],i={...{signInOAuth:we,callbackOAuth:be,getSession:ee(),signOut:Ae,signUpEmail:Oe(),signInEmail:ye,forgetPassword:ke,resetPassword:Ue,verifyEmail:he,sendVerificationEmail:ge,changeEmail:Te,changePassword:ve,setPassword:_e,updateUser:Ee(),deleteUser:xe,forgetPasswordCallback:Re,listSessions:pe(),revokeSession:me,revokeSessions:fe,linkSocialAccount:Ce,listUserAccounts:Ie},...r,ok:Se,error:Pe},s={};for(let[a,l]of Object.entries(i))s[a]=async(c={})=>{let d=await e;for(let u of t.plugins||[])if(u.hooks?.before){for(let R of u.hooks.before)if(R.matcher({...l,...c,context:d})){let y=await R.handler({...c,context:{...d,...c?.context}});y&&"context"in y&&(d={...d,...y.context})}}let h;try{h=await l({...c,context:{...d,...c.context}})}catch(u){if(u instanceof $.APIError){let R=t.plugins?.map(y=>{if(y.hooks?.after)return y.hooks.after}).filter(y=>y!==void 0).flat();if(!R?.length)throw u;let w=new Response(JSON.stringify(u.body),{status:$.statusCode[u.status],headers:u.headers});for(let y of R||[])if(y.matcher(c)){let ne=Object.assign(c,{context:{...e,returned:w}}),ie=await y.handler(ne);ie&&"response"in ie&&(w=ie.response)}return w}throw u}let m=h;for(let u of t.plugins||[])if(u.hooks?.after){for(let R of u.hooks.after)if(R.matcher(c)){let y=Object.assign(c,{context:{...e,returned:m}}),L=await R.handler(y);L&&"response"in L&&(m=L.response)}}return m},s[a].path=l.path,s[a].method=l.method,s[a].options=l.options,s[a].headers=l.headers;return{api:s,middlewares:o}}var Ht=(e,t)=>{let{api:r,middlewares:o}=Et(e,t),n=new URL(e.baseURL).pathname;return(0,$.createRouter)(r,{extraContext:e,basePath:n,routerMiddleware:[{path:"/**",middleware:le},...o],async onRequest(i){for(let s of e.options.plugins||[])if(s.onRequest){let a=await s.onRequest(i,e);if(a)return a}return Ut(i,e)},async onResponse(i){for(let s of e.options.plugins||[])if(s.onResponse){let a=await s.onResponse(i,e);if(a)return a.response}return i},onError(i){if(t.onAPIError?.throw)throw i;if(t.onAPIError?.onError){t.onAPIError.onError(i,e);return}let s=t.logger?.verboseLogging?f:void 0;t.logger?.disabled!==!0&&(i instanceof $.APIError?(i.status==="INTERNAL_SERVER_ERROR"&&f.error(i),s?.error(i.message)):f?.error(i))}})};0&&(module.exports={APIError,callbackOAuth,changeEmail,changePassword,createAuthEndpoint,createAuthMiddleware,createEmailVerificationToken,deleteUser,error,forgetPassword,forgetPasswordCallback,getEndpoints,getSession,getSessionFromCtx,linkSocialAccount,listSessions,listUserAccounts,ok,optionsMiddleware,originCheckMiddleware,resetPassword,revokeSession,revokeSessions,router,sendVerificationEmail,sessionMiddleware,setPassword,signInEmail,signInOAuth,signOut,signUpEmail,updateUser,verifyEmail});
|
|
1
|
+
"use strict";Object.defineProperty(exports, "__esModule", {value: true});var _chunkUAH4AUYScjs = require('./chunk-UAH4AUYS.cjs');require('./chunk-G6DG5D6F.cjs');require('./chunk-DU4AD5NF.cjs');require('./chunk-WFO5B3ON.cjs');require('./chunk-IYGMQ3UI.cjs');require('./chunk-2FTT4NBS.cjs');require('./chunk-QGRJEIVO.cjs');require('./chunk-V7Z635RZ.cjs');require('./chunk-JLIUR52U.cjs');require('./chunk-6BZ4ST3T.cjs');require('./chunk-J6NPEQIV.cjs');exports.APIError = _chunkUAH4AUYScjs.H; exports.callbackOAuth = _chunkUAH4AUYScjs.q; exports.changeEmail = _chunkUAH4AUYScjs.z; exports.changePassword = _chunkUAH4AUYScjs.w; exports.createAuthEndpoint = _chunkUAH4AUYScjs.c; exports.createAuthMiddleware = _chunkUAH4AUYScjs.b; exports.createEmailVerificationToken = _chunkUAH4AUYScjs.k; exports.deleteUser = _chunkUAH4AUYScjs.y; exports.error = _chunkUAH4AUYScjs.A; exports.forgetPassword = _chunkUAH4AUYScjs.s; exports.forgetPasswordCallback = _chunkUAH4AUYScjs.t; exports.getEndpoints = _chunkUAH4AUYScjs.F; exports.getSession = _chunkUAH4AUYScjs.e; exports.getSessionFromCtx = _chunkUAH4AUYScjs.f; exports.linkSocialAccount = _chunkUAH4AUYScjs.E; exports.listSessions = _chunkUAH4AUYScjs.h; exports.listUserAccounts = _chunkUAH4AUYScjs.D; exports.ok = _chunkUAH4AUYScjs.B; exports.optionsMiddleware = _chunkUAH4AUYScjs.a; exports.originCheckMiddleware = _chunkUAH4AUYScjs.d; exports.resetPassword = _chunkUAH4AUYScjs.u; exports.revokeSession = _chunkUAH4AUYScjs.i; exports.revokeSessions = _chunkUAH4AUYScjs.j; exports.router = _chunkUAH4AUYScjs.G; exports.sendVerificationEmail = _chunkUAH4AUYScjs.l; exports.sessionMiddleware = _chunkUAH4AUYScjs.g; exports.setPassword = _chunkUAH4AUYScjs.x; exports.signInEmail = _chunkUAH4AUYScjs.o; exports.signInOAuth = _chunkUAH4AUYScjs.n; exports.signOut = _chunkUAH4AUYScjs.r; exports.signUpEmail = _chunkUAH4AUYScjs.C; exports.updateUser = _chunkUAH4AUYScjs.v; exports.verifyEmail = _chunkUAH4AUYScjs.m;
|
package/dist/api.d.cts
CHANGED
|
@@ -1,8 +1,7 @@
|
|
|
1
|
-
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-
|
|
2
|
-
import './
|
|
1
|
+
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-Clegl4dW.cjs';
|
|
2
|
+
import './index-DUqGSAH3.cjs';
|
|
3
3
|
export { APIError } from 'better-call';
|
|
4
4
|
import 'zod';
|
|
5
5
|
import 'kysely';
|
|
6
|
-
import './index-BgRiS71T.cjs';
|
|
7
6
|
import 'better-sqlite3';
|
|
8
7
|
import 'mysql2';
|
package/dist/api.d.ts
CHANGED
|
@@ -1,8 +1,7 @@
|
|
|
1
|
-
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-
|
|
2
|
-
import './
|
|
1
|
+
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-fiexy-Ap.js';
|
|
2
|
+
import './index-DUqGSAH3.js';
|
|
3
3
|
export { APIError } from 'better-call';
|
|
4
4
|
import 'zod';
|
|
5
5
|
import 'kysely';
|
|
6
|
-
import './index-CINoRb0u.js';
|
|
7
6
|
import 'better-sqlite3';
|
|
8
7
|
import 'mysql2';
|
package/dist/api.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
import{A as z,B as A,C as B,D as C,E as D,F as E,G as F,H as G,a,b,c,d,e,f,g,h,i,j,k,l,m,n,o,q as p,r as q,s as r,t as s,u as t,v as u,w as v,x as w,y as x,z as y}from"./chunk-
|
|
1
|
+
import{A as z,B as A,C as B,D as C,E as D,F as E,G as F,H as G,a,b,c,d,e,f,g,h,i,j,k,l,m,n,o,q as p,r as q,s as r,t as s,u as t,v as u,w as v,x as w,y as x,z as y}from"./chunk-7GKOOVQP.js";import"./chunk-GW5UFHUL.js";import"./chunk-XJR6RYEY.js";import"./chunk-UN6PZ3HT.js";import"./chunk-TCBMYTN7.js";import"./chunk-J744ED5S.js";import"./chunk-KIEUIIFX.js";import"./chunk-HZVOBC5R.js";import"./chunk-FAFRRPOC.js";import"./chunk-RBJV2U7C.js";import"./chunk-72JSMFWS.js";export{G as APIError,p as callbackOAuth,y as changeEmail,v as changePassword,c as createAuthEndpoint,b as createAuthMiddleware,k as createEmailVerificationToken,x as deleteUser,z as error,r as forgetPassword,s as forgetPasswordCallback,E as getEndpoints,e as getSession,f as getSessionFromCtx,D as linkSocialAccount,h as listSessions,C as listUserAccounts,A as ok,a as optionsMiddleware,d as originCheckMiddleware,t as resetPassword,i as revokeSession,j as revokeSessions,F as router,l as sendVerificationEmail,g as sessionMiddleware,w as setPassword,o as signInEmail,n as signInOAuth,q as signOut,B as signUpEmail,u as updateUser,m as verifyEmail};
|