better-auth 0.7.6-beta.1 → 0.7.6-beta.3
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/memory.cjs +1 -0
- package/dist/adapters/memory.d.cts +14 -0
- package/dist/adapters/memory.d.ts +14 -0
- package/dist/adapters/memory.js +1 -0
- package/dist/adapters/mongodb.d.cts +2 -2
- package/dist/adapters/mongodb.d.ts +2 -2
- package/dist/adapters/prisma.d.cts +2 -2
- package/dist/adapters/prisma.d.ts +2 -2
- package/dist/api.cjs +5 -5
- package/dist/api.d.cts +2 -2
- package/dist/api.d.ts +2 -2
- package/dist/api.js +5 -5
- package/dist/{auth-i01HJsBT.d.ts → auth-BmcfH9ig.d.ts} +47 -47
- package/dist/{auth-DnVNaNo4.d.cts → auth-C-uryrMH.d.cts} +47 -47
- package/dist/client/plugins.cjs +1 -1
- package/dist/client/plugins.d.cts +4 -4
- package/dist/client/plugins.d.ts +4 -4
- package/dist/client/plugins.js +1 -1
- package/dist/client.d.cts +2 -2
- package/dist/client.d.ts +2 -2
- package/dist/cookies.cjs +1 -1
- package/dist/cookies.d.cts +2 -2
- package/dist/cookies.d.ts +2 -2
- package/dist/cookies.js +1 -1
- package/dist/db.d.cts +3 -3
- package/dist/db.d.ts +3 -3
- package/dist/{index-TBR5Nwgw.d.ts → index-CSObwEfn.d.ts} +8 -8
- package/dist/{index-B7acmBVh.d.cts → index-DNLBhV2f.d.cts} +8 -8
- package/dist/index.cjs +5 -5
- package/dist/index.d.cts +3 -3
- package/dist/index.d.ts +3 -3
- package/dist/index.js +5 -5
- 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 +6 -6
- package/dist/plugins.d.cts +10 -10
- package/dist/plugins.d.ts +10 -10
- package/dist/plugins.js +6 -6
- 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-B-NKU7yb.d.cts → state-CbHVShbJ.d.cts} +1 -1
- package/dist/{state-BvaftTAj.d.ts → state-UUNY3E78.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 +3 -3
- package/dist/types.d.ts +3 -3
- package/dist/vue.d.cts +2 -2
- package/dist/vue.d.ts +2 -2
- package/package.json +14 -1
- package/dist/{index-D0dedAck.d.ts → index-Bn9csJDG.d.ts} +4 -4
- package/dist/{index-BHDqo6WM.d.cts → index-DI6hwBqO.d.cts} +4 -4
|
@@ -1,7 +1,7 @@
|
|
|
1
|
-
import { A as Adapter } from '../auth-
|
|
1
|
+
import { A as Adapter } from '../auth-C-uryrMH.cjs';
|
|
2
2
|
import 'zod';
|
|
3
3
|
import 'kysely';
|
|
4
|
-
import '../index-
|
|
4
|
+
import '../index-DI6hwBqO.cjs';
|
|
5
5
|
import '../helper-DPDj8Nix.cjs';
|
|
6
6
|
import 'better-call';
|
|
7
7
|
import 'better-sqlite3';
|
|
@@ -1,7 +1,7 @@
|
|
|
1
|
-
import { A as Adapter } from '../auth-
|
|
1
|
+
import { A as Adapter } from '../auth-BmcfH9ig.js';
|
|
2
2
|
import 'zod';
|
|
3
3
|
import 'kysely';
|
|
4
|
-
import '../index-
|
|
4
|
+
import '../index-Bn9csJDG.js';
|
|
5
5
|
import '../helper-DPDj8Nix.js';
|
|
6
6
|
import 'better-call';
|
|
7
7
|
import 'better-sqlite3';
|
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
import { Kysely } from 'kysely';
|
|
2
|
-
import { B as BetterAuthOptions, K as KyselyDatabaseType, F as FieldAttribute, A as Adapter } from '../auth-
|
|
2
|
+
import { B as BetterAuthOptions, K as KyselyDatabaseType, F as FieldAttribute, A as Adapter } from '../auth-C-uryrMH.cjs';
|
|
3
3
|
import 'zod';
|
|
4
|
-
import '../index-
|
|
4
|
+
import '../index-DI6hwBqO.cjs';
|
|
5
5
|
import '../helper-DPDj8Nix.cjs';
|
|
6
6
|
import 'better-call';
|
|
7
7
|
import 'better-sqlite3';
|
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
import { Kysely } from 'kysely';
|
|
2
|
-
import { B as BetterAuthOptions, K as KyselyDatabaseType, F as FieldAttribute, A as Adapter } from '../auth-
|
|
2
|
+
import { B as BetterAuthOptions, K as KyselyDatabaseType, F as FieldAttribute, A as Adapter } from '../auth-BmcfH9ig.js';
|
|
3
3
|
import 'zod';
|
|
4
|
-
import '../index-
|
|
4
|
+
import '../index-Bn9csJDG.js';
|
|
5
5
|
import '../helper-DPDj8Nix.js';
|
|
6
6
|
import 'better-call';
|
|
7
7
|
import 'better-sqlite3';
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
"use strict";var f=Object.defineProperty;var o=Object.getOwnPropertyDescriptor;var p=Object.getOwnPropertyNames;var d=Object.prototype.hasOwnProperty;var h=(s,u)=>{for(var c in u)f(s,c,{get:u[c],enumerable:!0})},m=(s,u,c,t)=>{if(u&&typeof u=="object"||typeof u=="function")for(let n of p(u))!d.call(s,n)&&n!==c&&f(s,n,{get:()=>u[n],enumerable:!(t=o(u,n))||t.enumerable});return s};var A=s=>m(f({},"__esModule",{value:!0}),s);var M={};h(M,{memoryAdapter:()=>w});module.exports=A(M);var w=s=>{let u=(t,n)=>n.filter(e=>t.every(i=>{let{field:a,value:r,operator:l}=i;if(l==="in"){if(!Array.isArray(r))throw new Error("Value must be an array");return r.includes(e[a])}else return l==="contains"?e[a].includes(r):l==="starts_with"?e[a].startsWith(r):l==="ends_with"?e[a].endsWith(r):e[a]===r})),c=(t,n)=>n?n.reduce((e,i)=>(e[i]=t[i],e),{}):t;return{id:"memory",create:async({model:t,data:n})=>(s[t].push(n),n),findOne:async({model:t,where:n,select:e})=>{let i=s[t],r=u(n,i)[0]||null;return r?e?c(r,e):r:null},findMany:async({model:t,where:n,sortBy:e,limit:i,offset:a})=>{let r=s[t];return n&&(r=u(n,r)),e&&(r=r.sort((l,y)=>e.direction==="asc"?l[e.field]>y[e.field]?1:-1:l[e.field]<y[e.field]?1:-1)),a!==void 0&&(r=r.slice(a)),i!==void 0&&(r=r.slice(0,i)),r},update:async({model:t,where:n,update:e})=>{let i=s[t],a=u(n,i);return a.forEach(r=>{Object.assign(r,e)}),a[0]||null},delete:async({model:t,where:n})=>{let e=s[t],i=u(n,e);return s[t]=e.filter(a=>!i.includes(a)),i[0]||null},deleteMany:async({model:t,where:n})=>{let e=s[t],i=u(n,e);s[t]=e.filter(a=>!i.includes(a))}}};0&&(module.exports={memoryAdapter});
|
|
@@ -0,0 +1,14 @@
|
|
|
1
|
+
import { A as Adapter } from '../auth-C-uryrMH.cjs';
|
|
2
|
+
import 'zod';
|
|
3
|
+
import 'kysely';
|
|
4
|
+
import '../index-DI6hwBqO.cjs';
|
|
5
|
+
import '../helper-DPDj8Nix.cjs';
|
|
6
|
+
import 'better-call';
|
|
7
|
+
import 'better-sqlite3';
|
|
8
|
+
|
|
9
|
+
interface MemoryDB {
|
|
10
|
+
[key: string]: any[];
|
|
11
|
+
}
|
|
12
|
+
declare const memoryAdapter: (db: MemoryDB) => Adapter;
|
|
13
|
+
|
|
14
|
+
export { type MemoryDB, memoryAdapter };
|
|
@@ -0,0 +1,14 @@
|
|
|
1
|
+
import { A as Adapter } from '../auth-BmcfH9ig.js';
|
|
2
|
+
import 'zod';
|
|
3
|
+
import 'kysely';
|
|
4
|
+
import '../index-Bn9csJDG.js';
|
|
5
|
+
import '../helper-DPDj8Nix.js';
|
|
6
|
+
import 'better-call';
|
|
7
|
+
import 'better-sqlite3';
|
|
8
|
+
|
|
9
|
+
interface MemoryDB {
|
|
10
|
+
[key: string]: any[];
|
|
11
|
+
}
|
|
12
|
+
declare const memoryAdapter: (db: MemoryDB) => Adapter;
|
|
13
|
+
|
|
14
|
+
export { type MemoryDB, memoryAdapter };
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
var y=a=>{let l=(r,t)=>t.filter(e=>r.every(s=>{let{field:i,value:n,operator:u}=s;if(u==="in"){if(!Array.isArray(n))throw new Error("Value must be an array");return n.includes(e[i])}else return u==="contains"?e[i].includes(n):u==="starts_with"?e[i].startsWith(n):u==="ends_with"?e[i].endsWith(n):e[i]===n})),f=(r,t)=>t?t.reduce((e,s)=>(e[s]=r[s],e),{}):r;return{id:"memory",create:async({model:r,data:t})=>(a[r].push(t),t),findOne:async({model:r,where:t,select:e})=>{let s=a[r],n=l(t,s)[0]||null;return n?e?f(n,e):n:null},findMany:async({model:r,where:t,sortBy:e,limit:s,offset:i})=>{let n=a[r];return t&&(n=l(t,n)),e&&(n=n.sort((u,c)=>e.direction==="asc"?u[e.field]>c[e.field]?1:-1:u[e.field]<c[e.field]?1:-1)),i!==void 0&&(n=n.slice(i)),s!==void 0&&(n=n.slice(0,s)),n},update:async({model:r,where:t,update:e})=>{let s=a[r],i=l(t,s);return i.forEach(n=>{Object.assign(n,e)}),i[0]||null},delete:async({model:r,where:t})=>{let e=a[r],s=l(t,e);return a[r]=e.filter(i=>!s.includes(i)),s[0]||null},deleteMany:async({model:r,where:t})=>{let e=a[r],s=l(t,e);a[r]=e.filter(i=>!s.includes(i))}}};export{y as memoryAdapter};
|
|
@@ -1,8 +1,8 @@
|
|
|
1
1
|
import { Db } from 'mongodb';
|
|
2
|
-
import { W as Where } from '../auth-
|
|
2
|
+
import { W as Where } from '../auth-C-uryrMH.cjs';
|
|
3
3
|
import 'zod';
|
|
4
4
|
import 'kysely';
|
|
5
|
-
import '../index-
|
|
5
|
+
import '../index-DI6hwBqO.cjs';
|
|
6
6
|
import '../helper-DPDj8Nix.cjs';
|
|
7
7
|
import 'better-call';
|
|
8
8
|
import 'better-sqlite3';
|
|
@@ -1,8 +1,8 @@
|
|
|
1
1
|
import { Db } from 'mongodb';
|
|
2
|
-
import { W as Where } from '../auth-
|
|
2
|
+
import { W as Where } from '../auth-BmcfH9ig.js';
|
|
3
3
|
import 'zod';
|
|
4
4
|
import 'kysely';
|
|
5
|
-
import '../index-
|
|
5
|
+
import '../index-Bn9csJDG.js';
|
|
6
6
|
import '../helper-DPDj8Nix.js';
|
|
7
7
|
import 'better-call';
|
|
8
8
|
import 'better-sqlite3';
|
|
@@ -1,7 +1,7 @@
|
|
|
1
|
-
import { A as Adapter } from '../auth-
|
|
1
|
+
import { A as Adapter } from '../auth-C-uryrMH.cjs';
|
|
2
2
|
import 'zod';
|
|
3
3
|
import 'kysely';
|
|
4
|
-
import '../index-
|
|
4
|
+
import '../index-DI6hwBqO.cjs';
|
|
5
5
|
import '../helper-DPDj8Nix.cjs';
|
|
6
6
|
import 'better-call';
|
|
7
7
|
import 'better-sqlite3';
|
|
@@ -1,7 +1,7 @@
|
|
|
1
|
-
import { A as Adapter } from '../auth-
|
|
1
|
+
import { A as Adapter } from '../auth-BmcfH9ig.js';
|
|
2
2
|
import 'zod';
|
|
3
3
|
import 'kysely';
|
|
4
|
-
import '../index-
|
|
4
|
+
import '../index-Bn9csJDG.js';
|
|
5
5
|
import '../helper-DPDj8Nix.js';
|
|
6
6
|
import 'better-call';
|
|
7
7
|
import 'better-sqlite3';
|
package/dist/api.cjs
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
|
-
"use strict";var
|
|
2
|
-
`)}}),f=
|
|
3
|
-
`,`Current list of trustedOrigins: ${d}`),new Me.APIError("FORBIDDEN",{message:`Invalid ${u}`})};c&&!e.context.options.advanced?.disableCSRFCheck&&b(i,"origin"),n&&b(n,"callbackURL"),s&&b(s,"redirectURL"),a&&b(a,"currentURL")});var O=require("better-call"),x=require("zod");var Vt=require("oslo");async function T(e,t,r,o){let i=e.context.authCookies.sessionToken.options;i.maxAge=r?void 0:e.context.sessionConfig.expiresIn,await e.setSignedCookie(e.context.authCookies.sessionToken.name,t.session.id,e.context.secret,{...i,...o}),r&&await e.setSignedCookie(e.context.authCookies.dontRememberToken.name,"true",e.context.secret,e.context.authCookies.dontRememberToken.options),e.context.options.session?.cookieCache?.enabled&&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 Ge=require("oslo/crypto"),He=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,Ge.sha256)(new TextEncoder().encode(e));return He.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:i,scopes:n,claims:s,redirectURI:a}){let d=new URL(r);if(d.searchParams.set("response_type","code"),d.searchParams.set("client_id",t.clientId),d.searchParams.set("state",o),d.searchParams.set("scope",n.join(" ")),d.searchParams.set("redirect_uri",t.redirectURI||a),i){let c=await Qe(i);d.searchParams.set("code_challenge_method","S256"),d.searchParams.set("code_challenge",c)}if(s){let c=s.reduce((l,b)=>(l[b]=null,l),{});d.searchParams.set("claims",JSON.stringify({id_token:{email:null,email_verified:null,...c}}))}return d}var Je=require("@better-fetch/fetch");async function y({code:e,codeVerifier:t,redirectURI:r,options:o,tokenEndpoint:i}){let n=new URLSearchParams;n.set("grant_type","authorization_code"),n.set("code",e),t&&n.set("code_verifier",t),n.set("redirect_uri",r),n.set("client_id",o.clientId),n.set("client_secret",o.clientSecret);let{data:s,error:a}=await(0,Je.betterFetch)(i,{method:"POST",body:n,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:i}){let n=o||["email","name","openid"];return e.scope&&n.push(...e.scope),new URL(`https://appleid.apple.com/auth/authorize?client_id=${e.clientId}&response_type=code&redirect_uri=${i||e.redirectURI}&scope=${n.join(" ")}&state=${r}`)},validateAuthorizationCode:async({code:r,codeVerifier:o,redirectURI:i})=>y({code:r,codeVerifier:o,redirectURI:e.redirectURI||i,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 i=r||["identify","email"];return e.scope&&i.push(...e.scope),new URL(`https://discord.com/api/oauth2/authorize?scope=${i.join("+")}&response_type=code&client_id=${e.clientId}&redirect_uri=${encodeURIComponent(e.redirectURI||o)}&state=${t}`)},validateAuthorizationCode:async({code:t,redirectURI:r})=>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 i=r.discriminator==="0"?Number(BigInt(r.id)>>BigInt(22))%6:parseInt(r.discriminator)%5;r.image_url=`https://cdn.discordapp.com/embed/avatars/${i}.png`}else{let i=r.avatar.startsWith("a_")?"gif":"png";r.image_url=`https://cdn.discordapp.com/avatars/${r.id}/${r.avatar}.${i}`}return{user:{id:r.id,name:r.display_name||r.username||"",email:r.email,emailVerified:r.verified,image:r.image_url},data:r}}});var et=require("@better-fetch/fetch");var tt=e=>({id:"facebook",name:"Facebook",async createAuthorizationURL({state:t,scopes:r,redirectURI:o}){let i=r||["email","public_profile"];return e.scope&&i.push(...e.scope),await A({id:"facebook",options:e,authorizationEndpoint:"https://www.facebook.com/v21.0/dialog/oauth",scopes:i,state:t,redirectURI:o})},validateAuthorizationCode:async({code:t,redirectURI:r})=>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 le=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:i,redirectURI:n}){let s=o||["user:email"];return e.scope&&s.push(...e.scope),A({id:"github",options:e,authorizationEndpoint:"https://github.com/login/oauth/authorize",scopes:s,state:r,redirectURI:n})},validateAuthorizationCode:async({code:r,redirectURI:o})=>y({code:r,redirectURI:e.redirectURI||o,options:e,tokenEndpoint:t}),async getUserInfo(r){let{data:o,error:i}=await(0,le.betterFetch)("https://api.github.com/user",{headers:{"User-Agent":"better-auth",authorization:`Bearer ${r.accessToken}`}});if(i)return null;let n=!1;if(!o.email){let{data:s,error:a}=await(0,le.betterFetch)("https://api.github.com/user/emails",{headers:{authorization:`Bearer ${r.accessToken}`,"User-Agent":"better-auth"}});a||(o.email=(s.find(d=>d.primary)??s[0])?.email,n=s.find(d=>d.email===o.email)?.verified??!1)}return{user:{id:o.id.toString(),name:o.name||o.login,email:o.email,image:o.avatar_url,emailVerified:n},data:o}}}};var ot=require("oslo/jwt");var it=e=>({id:"google",name:"Google",async createAuthorizationURL({state:t,scopes:r,codeVerifier:o,redirectURI:i}){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 D("CLIENT_ID_AND_SECRET_REQUIRED");if(!o)throw new D("codeVerifier is required for Google");let n=r||["email","profile","openid"];e.scope&&n.push(...e.scope);let s=await A({id:"google",options:e,authorizationEndpoint:"https://accounts.google.com/o/oauth2/auth",scopes:n,state:t,codeVerifier:o,redirectURI:i});return e.accessType&&s.searchParams.set("access_type",e.accessType),e.prompt&&s.searchParams.set("prompt",e.prompt),s},validateAuthorizationCode:async({code:t,codeVerifier:r,redirectURI:o})=>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 nt=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(i){let n=i.scopes||["openid","profile","email","User.Read"];return e.scope&&n.push(...e.scope),A({id:"microsoft",options:e,authorizationEndpoint:r,state:i.state,codeVerifier:i.codeVerifier,scopes:n,redirectURI:i.redirectURI})},validateAuthorizationCode({code:i,codeVerifier:n,redirectURI:s}){return y({code:i,codeVerifier:n,redirectURI:e.redirectURI||s,options:e,tokenEndpoint:o})},async getUserInfo(i){if(!i.idToken)return null;let n=(0,st.parseJWT)(i.idToken)?.payload,s=e.profilePhotoSize||48;return await(0,nt.betterFetch)(`https://graph.microsoft.com/v1.0/me/photos/${s}x${s}/$value`,{headers:{Authorization:`Bearer ${i.accessToken}`},async onResponse(a){if(!(e.disableProfilePhoto||!a.response.ok))try{let c=await a.response.clone().arrayBuffer(),l=Buffer.from(c).toString("base64");n.picture=`data:image/jpeg;base64, ${l}`}catch(d){f.error(d)}}}),{user:{id:n.sub,name:n.name,email:n.email,image:n.picture,emailVerified:!0},data:n}}}};var dt=require("@better-fetch/fetch");var ct=e=>({id:"spotify",name:"Spotify",createAuthorizationURL({state:t,scopes:r,codeVerifier:o,redirectURI:i}){let n=r||["user-read-email"];return e.scope&&n.push(...e.scope),A({id:"spotify",options:e,authorizationEndpoint:"https://accounts.spotify.com/authorize",scopes:n,state:t,codeVerifier:o,redirectURI:i})},validateAuthorizationCode:async({code:t,codeVerifier:r,redirectURI:o})=>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,dt.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 oo=require("@better-fetch/fetch");var lt=require("oslo/jwt");var ut=e=>({id:"twitch",name:"Twitch",createAuthorizationURL({state:t,scopes:r,redirectURI:o}){let i=r||["user:read:email","openid"];return e.scope&&i.push(...e.scope),A({id:"twitch",redirectURI:o,options:e,authorizationEndpoint:"https://id.twitch.tv/oauth2/authorize",scopes:i,state:t,claims:e.claims||["email","email_verified","preferred_username","picture"]})},validateAuthorizationCode:async({code:t,redirectURI:r})=>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,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})=>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:i,redirectURI:n})=>{let s=o||["account_info.read"];return e.scope&&s.push(...e.scope),await A({id:"dropbox",options:e,authorizationEndpoint:"https://www.dropbox.com/oauth2/authorize",scopes:s,state:r,redirectURI:n,codeVerifier:i})},validateAuthorizationCode:async({code:r,codeVerifier:o,redirectURI:i})=>await y({code:r,codeVerifier:o,redirectURI:e.redirectURI||i,options:e,tokenEndpoint:t}),async getUserInfo(r){let{data:o,error:i}=await(0,ft.betterFetch)("https://api.dropboxapi.com/2/users/get_current_account",{method:"POST",headers:{Authorization:`Bearer ${r.accessToken}`}});return i?null:{user:{id:o.account_id,name:o.name?.display_name,email:o.email,emailVerified:o.email_verified||!1,image:o.profile_photo_url},data:o}}}};var 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:i,redirectURI:n})=>{let s=i||["profile","email","openid"];return e.scope&&s.push(...e.scope),await A({id:"linkedin",options:e,authorizationEndpoint:t,scopes:s,state:o,redirectURI:n})},validateAuthorizationCode:async({code:o,redirectURI:i})=>await y({code:o,redirectURI:e.redirectURI||i,options:e,tokenEndpoint:r}),async getUserInfo(o){let{data:i,error:n}=await(0,ht.betterFetch)("https://api.linkedin.com/v2/userinfo",{method:"GET",headers:{Authorization:`Bearer ${o.accessToken}`}});return n?null:{user:{id:i.sub,name:i.name,email:i.email,emailVerified:i.email_verified||!1,image:i.picture},data:i}}}};var bt=require("@better-fetch/fetch");var ue=(e="")=>e.split("://").map(t=>t.replace(/\/{2,}/g,"/")).join("://"),jt=e=>{let t=e||"https://gitlab.com";return{authorizationEndpoint:ue(`${t}/oauth/authorize`),tokenEndpoint:ue(`${t}/oauth/token`),userinfoEndpoint:ue(`${t}/api/v4/user`)}},yt=e=>{let{authorizationEndpoint:t,tokenEndpoint:r,userinfoEndpoint:o}=jt(e.issuer),i="gitlab";return{id:i,name:"Gitlab",createAuthorizationURL:async({state:s,scopes:a,codeVerifier:d,redirectURI:c})=>{let l=a||["read_user"];return e.scope&&l.push(...e.scope),await A({id:i,options:e,authorizationEndpoint:t,scopes:l,state:s,redirectURI:c,codeVerifier:d})},validateAuthorizationCode:async({code:s,redirectURI:a,codeVerifier:d})=>y({code:s,redirectURI:e.redirectURI||a,options:e,codeVerifier:d,tokenEndpoint:r}),async getUserInfo(s){let{data:a,error:d}=await(0,bt.betterFetch)(o,{headers:{authorization:`Bearer ${s.accessToken}`}});return d||a.state!=="active"||a.locked?null:{user:{id:a.id.toString(),name:a.name??a.username,email:a.email,image:a.avatar_url,emailVerified:!0},data:a}}}};var $t={apple:Ye,discord:Xe,facebook:tt,github:rt,microsoft:at,google:it,spotify:ct,twitch:ut,twitter:mt,dropbox:gt,linkedin:wt,gitlab:yt},X=Object.keys($t);var At=require("oslo"),re=require("oslo/jwt"),_=require("zod");var V=require("better-call");var F=require("better-call");var M=require("zod"),ee=()=>p("/get-session",{method:"GET",query:M.z.optional(M.z.object({disableCookieCache:M.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 i=await e.context.internalAdapter.findSession(t);if(!i||i.session.expiresAt<new Date)return z(e),i&&await e.context.internalAdapter.deleteSession(i.session.id),e.json(null,{status:401});if(o)return e.json(i);let n=e.context.sessionConfig.expiresIn,s=e.context.sessionConfig.updateAge;if(i.session.expiresAt.valueOf()-n*1e3+s*1e3<=Date.now()){let c=await e.context.internalAdapter.updateSession(i.session.id,{expiresAt:N(e.context.sessionConfig.expiresIn,"sec")});if(!c)return z(e),e.json(null,{status:401});let l=(c.expiresAt.valueOf()-Date.now())/1e3;return await T(e,{session:c,user:i.user},!1,{maxAge:l}),e.json({session:c,user:i.user})}return e.json(i)}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=H(async e=>{let t=await te(e);if(!t?.session)throw new F.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:M.z.object({id:M.z.string()}),use:[v],requireHeaders:!0},async e=>{let t=e.body.id,r=await e.context.internalAdapter.findSession(t);if(!r)throw new F.APIError("BAD_REQUEST",{message:"Session not found"});if(r.session.userId!==e.context.session.user.id)throw new F.APIError("UNAUTHORIZED");try{await e.context.internalAdapter.deleteSession(t)}catch(o){throw e.context.logger.error(o),new F.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 F.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:_.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),i=`${e.context.baseURL}/verify-email?token=${o}&callbackURL=${e.body.callbackURL||e.query?.currentURL||"/"}`;return await e.context.options.emailVerification.sendVerificationEmail(r.user,i,o),e.json({status:!0})}),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 i=_.z.object({email:_.z.string().email(),updateTo:_.z.string().optional()}).parse(r.payload);if(!await e.context.internalAdapter.findUserByEmail(i.email))throw new V.APIError("BAD_REQUEST",{message:"User not found"});if(i.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!==i.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(i.email,{email:i.updateTo});if(await e.context.options.emailVerification?.sendVerificationEmail?.(a,`${e.context.baseURL}/verify-email?token=${t}`,t),e.query.callbackURL)throw e.redirect(e.query.callbackURL);return e.json({user:a,status:!0})}if(await e.context.internalAdapter.updateUserByEmail(i.email,{emailVerified:!0}),e.query.callbackURL)throw e.redirect(e.query.callbackURL);return e.json({user:null,status:!0})});var we=p("/sign-in/social",{method:"POST",query:x.z.object({currentURL:x.z.string().optional()}).optional(),body:x.z.object({callbackURL:x.z.string().optional(),provider:x.z.enum(X)})},async e=>{let t=e.context.socialProviders.find(n=>n.id===e.body.provider);if(!t)throw e.context.logger.error("Provider not found. Make sure to add the provider in your auth config",{provider:e.body.provider}),new O.APIError("NOT_FOUND",{message:"Provider not found"});let{codeVerifier:r,state:o}=await K(e),i=await t.createAuthorizationURL({state:o,codeVerifier:r,redirectURI:`${e.context.baseURL}/callback/${t.id}`});return e.json({url:i.toString(),redirect:!0})}),be=p("/sign-in/email",{method:"POST",body:x.z.object({email:x.z.string(),password:x.z.string(),callbackURL:x.z.string().optional(),dontRememberMe:x.z.boolean().default(!1).optional()})},async e=>{if(!e.context.options?.emailAndPassword?.enabled)throw e.context.logger.error("Email and password is not enabled. Make sure to enable it in the options on you `auth.ts` file. Check `https://better-auth.com/docs/authentication/email-password` for more!"),new O.APIError("BAD_REQUEST",{message:"Email and password is not enabled"});let{email:t,password:r}=e.body;if(!x.z.string().email().safeParse(t).success)throw new O.APIError("BAD_REQUEST",{message:"Invalid email"});let 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 O.APIError("UNAUTHORIZED",{message:"Invalid email or password"});let n=i.accounts.find(c=>c.providerId==="credential");if(!n)throw e.context.logger.error("Credential account not found",{email:t}),new O.APIError("UNAUTHORIZED",{message:"Invalid email or password"});let s=n?.password;if(!s)throw e.context.logger.error("Password not found",{email:t}),new O.APIError("UNAUTHORIZED",{message:"Unexpected error"});if(!await e.context.password.verify(s,r))throw e.context.logger.error("Invalid password"),new O.APIError("UNAUTHORIZED",{message:"Invalid email or password"});if(e.context.options?.emailAndPassword?.requireEmailVerification&&!i.user.emailVerified){if(!e.context.options?.emailVerification?.sendVerificationEmail)throw f.error("Email verification is required but no email verification handler is provided"),new O.APIError("INTERNAL_SERVER_ERROR",{message:"Email is not verified."});let c=await S(e.context.secret,i.user.email),l=`${e.context.options.baseURL}/verify-email?token=${c}`;throw await e.context.options.emailVerification.sendVerificationEmail(i.user,l,c),e.context.logger.error("Email not verified",{email:t}),new O.APIError("FORBIDDEN",{message:"Email is not verified. Check your email for a verification link"})}let d=await e.context.internalAdapter.createSession(i.user.id,e.headers,e.body.dontRememberMe);if(!d)throw e.context.logger.error("Failed to create session"),new O.APIError("UNAUTHORIZED",{message:"Failed to create session"});return await T(e,{session:d,user:i.user},e.body.dontRememberMe),e.json({user:i.user,session:d,redirect:!!e.body.callbackURL,url:e.body.callbackURL})});var Z=require("zod");var g=require("zod"),ti=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)}),ri=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()}),oi=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,i={};for(let n in o){if(n in e){if(o[n].input===!1){if(o[n].defaultValue){i[n]=o[n].defaultValue;continue}continue}i[n]=e[n];continue}if(o[n].defaultValue&&r==="create"){i[n]=o[n].defaultValue;continue}}return i}function 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(h=>h.id===e.params.id);if(!t)throw e.context.logger.error("Oauth provider with id",e.params.id,"not found"),e.redirect(`${e.context.baseURL}/error?error=oauth_provider_not_found`);let{codeVerifier:r,callbackURL:o,link:i,errorURL:n}=await Ne(e),s;try{s=await t.validateAuthorizationCode({code:e.query.code,codeVerifier:r,redirectURI:`${e.context.baseURL}/callback/${t.id}`})}catch(h){throw e.context.logger.error(h),e.redirect(`${e.context.baseURL}/error?error=please_restart_the_process`)}let a=await t.getUserInfo(s).then(h=>h?.user),d=ze(),c=Rt.safeParse({...a,id:d});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(i){if(i.email!==a.email.toLowerCase())return l("email_doesn't_match");if(!await e.context.internalAdapter.createAccount({userId:i.userId,providerId:t.id,accountId:a.id}))return l("unable_to_link_account");let w;try{w=new URL(o).toString()}catch{w=o}throw e.redirect(w)}function l(h){throw e.redirect(`${n||o||`${e.context.baseURL}/error`}?error=${h}`)}let b=await e.context.internalAdapter.findUserByEmail(a.email,{includeAccounts:!0}).catch(h=>{throw f.error(`Better auth was unable to query your database.
|
|
4
|
-
Error: `,
|
|
1
|
+
"use strict";var ae=Object.defineProperty;var Ct=Object.getOwnPropertyDescriptor;var Bt=Object.getOwnPropertyNames;var Dt=Object.prototype.hasOwnProperty;var zt=(e,t)=>{for(var r in t)ae(e,r,{get:t[r],enumerable:!0})},Vt=(e,t,r,o)=>{if(t&&typeof t=="object"||typeof t=="function")for(let n of Bt(t))!Dt.call(e,n)&&n!==r&&ae(e,n,{get:()=>t[n],enumerable:!(o=Ct(t,n))||o.enumerable});return e};var jt=e=>Vt(ae({},"__esModule",{value:!0}),e);var nr={};zt(nr,{APIError:()=>Lt.APIError,callbackOAuth:()=>ke,changeEmail:()=>Oe,changePassword:()=>xe,createAuthEndpoint:()=>m,createAuthMiddleware:()=>G,createEmailVerificationToken:()=>S,deleteUser:()=>Te,error:()=>Se,forgetPassword:()=>Ue,forgetPasswordCallback:()=>Ee,getEndpoints:()=>St,getSession:()=>re,getSessionFromCtx:()=>oe,linkSocialAccount:()=>De,listSessions:()=>fe,listUserAccounts:()=>Be,ok:()=>Le,optionsMiddleware:()=>ce,originCheckMiddleware:()=>le,resetPassword:()=>ve,revokeSession:()=>ge,revokeSessions:()=>he,router:()=>or,sendVerificationEmail:()=>we,sessionMiddleware:()=>v,setPassword:()=>Pe,signInEmail:()=>Ae,signInSocial:()=>ye,signOut:()=>Re,signUpEmail:()=>Ie,updateUser:()=>_e,verifyEmail:()=>be});module.exports=jt(nr);var q=require("better-call");var Ge=require("better-call");var D=require("better-call"),ce=(0,D.createMiddleware)(async()=>({})),G=(0,D.createMiddlewareCreator)({use:[ce,(0,D.createMiddleware)(async()=>({}))]}),m=(0,D.createEndpointCreator)({use:[ce]});var N={isAction:!1};var Ve=require("nanoid"),je=e=>(0,Ve.nanoid)(e);var Y=require("oslo/oauth2"),I=require("zod"),ue=require("better-call");var W=Object.create(null),Q=e=>globalThis.process?.env||globalThis.Deno?.env.toObject()||globalThis.__env__||(e?W:globalThis),$e=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 $t(e){return e?e!=="false":!1}var de=typeof process<"u"&&process.env&&process.env.NODE_ENV||"";var qe=de==="dev"||de==="development",Ne=de==="test"||$t($e.TEST);var z=class extends Error{constructor(t,r){super(t),this.name="BetterAuthError",this.message=t,this.cause=r}};function Me(e){try{return new URL(e).origin}catch{return null}}async function K(e,t){let r=e.body?.callbackURL||(e.query?.currentURL?Me(e.query?.currentURL):"")||e.context.options.baseURL;if(!r)throw new ue.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 ue.APIError("INTERNAL_SERVER_ERROR",{message:"Unable to create verification"});return{state:a.identifier,codeVerifier:o}}async function Fe(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=I.z.object({callbackURL:I.z.string(),codeVerifier:I.z.string(),errorURL:I.z.string().optional(),expiresAt:I.z.number(),link:I.z.object({email:I.z.string(),userId:I.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 He=require("consola"),V=(0,He.createConsola)({formatOptions:{date:!1,colors:!0,compact:!0},defaults:{tag:"Better Auth"}}),qt=e=>({log:(...t)=>{!e?.disabled&&V.log("",...t)},error:(...t)=>{!e?.disabled&&V.error("",...t)},warn:(...t)=>{!e?.disabled&&V.warn("",...t)},info:(...t)=>{!e?.disabled&&V.info("",...t)},debug:(...t)=>{!e?.disabled&&V.debug("",...t)},box:(...t)=>{!e?.disabled&&V.box("",...t)},success:(...t)=>{!e?.disabled&&V.success("",...t)},break:(...t)=>{!e?.disabled&&console.log(`
|
|
2
|
+
`)}}),f=qt();var le=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||r?.callbackURL,s=t?.redirectTo,a=r?.currentURL,c=o.trustedOrigins,u=e.headers?.has("cookie"),d=(p,l)=>l.includes("*")?new RegExp("^"+l.replace(/\*/g,"[^/]+").replace(/\./g,"\\.")+"$").test(p):p.startsWith(l),h=(p,l)=>{if(!p)return;if(!c.some(w=>d(p,w)||p?.startsWith("/")&&l!=="origin"&&!p.includes(":")))throw f.error(`Invalid ${l}: ${p}`),f.info(`If it's a valid URL, please add ${p} to trustedOrigins in your auth config
|
|
3
|
+
`,`Current list of trustedOrigins: ${c}`),new Ge.APIError("FORBIDDEN",{message:`Invalid ${l}`})};u&&!e.context.options.advanced?.disableCSRFCheck&&h(n,"origin"),i&&h(i,"callbackURL"),s&&h(s,"redirectURL"),a&&h(a,"currentURL")});var O=require("better-call"),x=require("zod");var Ft=require("oslo");var X=require("oslo/crypto");async function Nt({value:e,secret:t}){return new X.HMAC("SHA-256").sign(new TextEncoder().encode(t),new TextEncoder().encode(e)).then(o=>Buffer.from(o).toString("base64"))}function Mt({value:e,signature:t,secret:r}){return new X.HMAC("SHA-256").verify(new TextEncoder().encode(r),Buffer.from(t,"base64"),new TextEncoder().encode(e))}var ee={sign:Nt,verify:Mt};var Qe=require("oslo/encoding");var C=(e,t="ms")=>new Date(Date.now()+(t==="sec"?e*1e3:e));async function T(e,t,r,o){let n=e.context.authCookies.sessionToken.options;n.maxAge=r?void 0:e.context.sessionConfig.expiresIn,await e.setSignedCookie(e.context.authCookies.sessionToken.name,t.session.id,e.context.secret,{...n,...o}),r&&await e.setSignedCookie(e.context.authCookies.dontRememberToken.name,"true",e.context.secret,e.context.authCookies.dontRememberToken.options),e.context.options.session?.cookieCache?.enabled&&e.setCookie(e.context.authCookies.sessionData.name,JSON.stringify(Qe.base64url.encode(new TextEncoder().encode(JSON.stringify({session:t,expiresAt:C(e.context.authCookies.sessionData.options.maxAge||60,"sec").getTime(),signature:await ee.sign({value:JSON.stringify(t),secret:e.context.secret})})))),e.context.authCookies.sessionData.options),e.context.options.secondaryStorage&&await e.context.secondaryStorage?.set(t.session.id,JSON.stringify({user:t.user,session:t.session}),t.session.expiresAt.getTime()-Date.now())}function B(e){e.setCookie(e.context.authCookies.sessionToken.name,"",{maxAge:0}),e.setCookie(e.context.authCookies.sessionData.name,"",{maxAge:0}),e.setCookie(e.context.authCookies.dontRememberToken.name,"",{maxAge:0})}var Xe=require("oslo/jwt");var Ze=require("oslo/crypto"),Je=require("oslo/encoding");async function We(e){let t=await(0,Ze.sha256)(new TextEncoder().encode(e));return Je.base64url.encode(new Uint8Array(t),{includePadding:!1})}function Ye(e){return{tokenType:e.token_type,accessToken:e.access_token,refreshToken:e.refresh_token,accessTokenExpiresAt:e.expires_in?C(e.expires_in,"sec"):void 0,scopes:e?.scope?typeof e.scope=="string"?e.scope.split(" "):e.scope:[],idToken:e.id_token}}async function A({id:e,options:t,authorizationEndpoint:r,state:o,codeVerifier:n,scopes:i,claims:s,redirectURI:a}){let c=new URL(r);if(c.searchParams.set("response_type","code"),c.searchParams.set("client_id",t.clientId),c.searchParams.set("state",o),c.searchParams.set("scope",i.join(" ")),c.searchParams.set("redirect_uri",t.redirectURI||a),n){let u=await We(n);c.searchParams.set("code_challenge_method","S256"),c.searchParams.set("code_challenge",u)}if(s){let u=s.reduce((d,h)=>(d[h]=null,d),{});c.searchParams.set("claims",JSON.stringify({id_token:{email:null,email_verified:null,...u}}))}return c}var Ke=require("@better-fetch/fetch");async function y({code:e,codeVerifier:t,redirectURI:r,options:o,tokenEndpoint:n}){let i=new URLSearchParams;i.set("grant_type","authorization_code"),i.set("code",e),t&&i.set("code_verifier",t),i.set("redirect_uri",r),i.set("client_id",o.clientId),i.set("client_secret",o.clientSecret);let{data:s,error:a}=await(0,Ke.betterFetch)(n,{method:"POST",body:i,headers:{"content-type":"application/x-www-form-urlencoded",accept:"application/json","user-agent":"better-auth"}});if(a)throw a;return Ye(s)}var et=e=>{let t="https://appleid.apple.com/auth/token";return{id:"apple",name:"Apple",createAuthorizationURL({state:r,scopes:o,redirectURI:n}){let i=o||["email","name","openid"];return e.scope&&i.push(...e.scope),new URL(`https://appleid.apple.com/auth/authorize?client_id=${e.clientId}&response_type=code&redirect_uri=${n||e.redirectURI}&scope=${i.join(" ")}&state=${r}`)},validateAuthorizationCode:async({code:r,codeVerifier:o,redirectURI:n})=>y({code:r,codeVerifier:o,redirectURI:e.redirectURI||n,options:e,tokenEndpoint:t}),async getUserInfo(r){if(!r.idToken)return null;let o=(0,Xe.parseJWT)(r.idToken)?.payload;return o?{user:{id:o.sub,name:o.name,email:o.email,emailVerified:o.email_verified==="true"},data:o}:null}}};var tt=require("@better-fetch/fetch");var rt=e=>({id:"discord",name:"Discord",createAuthorizationURL({state:t,scopes:r,redirectURI:o}){let n=r||["identify","email"];return e.scope&&n.push(...e.scope),new URL(`https://discord.com/api/oauth2/authorize?scope=${n.join("+")}&response_type=code&client_id=${e.clientId}&redirect_uri=${encodeURIComponent(e.redirectURI||o)}&state=${t}`)},validateAuthorizationCode:async({code:t,redirectURI:r})=>y({code:t,redirectURI:e.redirectURI||r,options:e,tokenEndpoint:"https://discord.com/api/oauth2/token"}),async getUserInfo(t){let{data:r,error:o}=await(0,tt.betterFetch)("https://discord.com/api/users/@me",{headers:{authorization:`Bearer ${t.accessToken}`}});if(o)return null;if(r.avatar===null){let n=r.discriminator==="0"?Number(BigInt(r.id)>>BigInt(22))%6:parseInt(r.discriminator)%5;r.image_url=`https://cdn.discordapp.com/embed/avatars/${n}.png`}else{let n=r.avatar.startsWith("a_")?"gif":"png";r.image_url=`https://cdn.discordapp.com/avatars/${r.id}/${r.avatar}.${n}`}return{user:{id:r.id,name:r.display_name||r.username||"",email:r.email,emailVerified:r.verified,image:r.image_url},data:r}}});var ot=require("@better-fetch/fetch");var nt=e=>({id:"facebook",name:"Facebook",async createAuthorizationURL({state:t,scopes:r,redirectURI:o}){let n=r||["email","public_profile"];return e.scope&&n.push(...e.scope),await A({id:"facebook",options:e,authorizationEndpoint:"https://www.facebook.com/v21.0/dialog/oauth",scopes:n,state:t,redirectURI:o})},validateAuthorizationCode:async({code:t,redirectURI:r})=>y({code:t,redirectURI:e.redirectURI||r,options:e,tokenEndpoint:"https://graph.facebook.com/oauth/access_token"}),async getUserInfo(t){let{data:r,error:o}=await(0,ot.betterFetch)("https://graph.facebook.com/me?fields=id,name,email,picture",{auth:{type:"Bearer",token:t.accessToken}});return o?null:{user:{id:r.id,name:r.name,email:r.email,image:r.picture.data.url,emailVerified:r.email_verified},data:r}}});var pe=require("@better-fetch/fetch");var it=e=>{let t="https://github.com/login/oauth/access_token";return{id:"github",name:"GitHub",createAuthorizationURL({state:r,scopes:o,codeVerifier:n,redirectURI:i}){let s=o||["user:email"];return e.scope&&s.push(...e.scope),A({id:"github",options:e,authorizationEndpoint:"https://github.com/login/oauth/authorize",scopes:s,state:r,redirectURI:i})},validateAuthorizationCode:async({code:r,redirectURI:o})=>y({code:r,redirectURI:e.redirectURI||o,options:e,tokenEndpoint:t}),async getUserInfo(r){let{data:o,error:n}=await(0,pe.betterFetch)("https://api.github.com/user",{headers:{"User-Agent":"better-auth",authorization:`Bearer ${r.accessToken}`}});if(n)return null;let i=!1;if(!o.email){let{data:s,error:a}=await(0,pe.betterFetch)("https://api.github.com/user/emails",{headers:{authorization:`Bearer ${r.accessToken}`,"User-Agent":"better-auth"}});a||(o.email=(s.find(c=>c.primary)??s[0])?.email,i=s.find(c=>c.email===o.email)?.verified??!1)}return{user:{id:o.id.toString(),name:o.name||o.login,email:o.email,image:o.avatar_url,emailVerified:i},data:o}}}};var st=require("oslo/jwt");var at=e=>({id:"google",name:"Google",async createAuthorizationURL({state:t,scopes:r,codeVerifier:o,redirectURI:n}){if(!e.clientId||!e.clientSecret)throw f.error("Client Id and Client Secret is required for Google. Make sure to provide them in the options."),new z("CLIENT_ID_AND_SECRET_REQUIRED");if(!o)throw new z("codeVerifier is required for Google");let i=r||["email","profile","openid"];e.scope&&i.push(...e.scope);let s=await A({id:"google",options:e,authorizationEndpoint:"https://accounts.google.com/o/oauth2/auth",scopes:i,state:t,codeVerifier:o,redirectURI:n});return e.accessType&&s.searchParams.set("access_type",e.accessType),e.prompt&&s.searchParams.set("prompt",e.prompt),s},validateAuthorizationCode:async({code:t,codeVerifier:r,redirectURI:o})=>y({code:t,codeVerifier:r,redirectURI:e.redirectURI||o,options:e,tokenEndpoint:"https://oauth2.googleapis.com/token"}),async getUserInfo(t){if(!t.idToken)return null;let r=(0,st.parseJWT)(t.idToken)?.payload;return{user:{id:r.sub,name:r.name,email:r.email,image:r.picture,emailVerified:r.email_verified},data:r}}});var ct=require("@better-fetch/fetch"),dt=require("oslo/jwt");var ut=e=>{let t=e.tenantId||"common",r=`https://login.microsoftonline.com/${t}/oauth2/v2.0/authorize`,o=`https://login.microsoftonline.com/${t}/oauth2/v2.0/token`;return{id:"microsoft",name:"Microsoft EntraID",createAuthorizationURL(n){let i=n.scopes||["openid","profile","email","User.Read"];return e.scope&&i.push(...e.scope),A({id:"microsoft",options:e,authorizationEndpoint:r,state:n.state,codeVerifier:n.codeVerifier,scopes:i,redirectURI:n.redirectURI})},validateAuthorizationCode({code:n,codeVerifier:i,redirectURI:s}){return y({code:n,codeVerifier:i,redirectURI:e.redirectURI||s,options:e,tokenEndpoint:o})},async getUserInfo(n){if(!n.idToken)return null;let i=(0,dt.parseJWT)(n.idToken)?.payload,s=e.profilePhotoSize||48;return await(0,ct.betterFetch)(`https://graph.microsoft.com/v1.0/me/photos/${s}x${s}/$value`,{headers:{Authorization:`Bearer ${n.accessToken}`},async onResponse(a){if(!(e.disableProfilePhoto||!a.response.ok))try{let u=await a.response.clone().arrayBuffer(),d=Buffer.from(u).toString("base64");i.picture=`data:image/jpeg;base64, ${d}`}catch(c){f.error(c)}}}),{user:{id:i.sub,name:i.name,email:i.email,image:i.picture,emailVerified:!0},data:i}}}};var lt=require("@better-fetch/fetch");var pt=e=>({id:"spotify",name:"Spotify",createAuthorizationURL({state:t,scopes:r,codeVerifier:o,redirectURI:n}){let i=r||["user-read-email"];return e.scope&&i.push(...e.scope),A({id:"spotify",options:e,authorizationEndpoint:"https://accounts.spotify.com/authorize",scopes:i,state:t,codeVerifier:o,redirectURI:n})},validateAuthorizationCode:async({code:t,codeVerifier:r,redirectURI:o})=>y({code:t,codeVerifier:r,redirectURI:e.redirectURI||o,options:e,tokenEndpoint:"https://accounts.spotify.com/api/token"}),async getUserInfo(t){let{data:r,error:o}=await(0,lt.betterFetch)("https://api.spotify.com/v1/me",{method:"GET",headers:{Authorization:`Bearer ${t.accessToken}`}});return o?null:{user:{id:r.id,name:r.display_name,email:r.email,image:r.images[0]?.url,emailVerified:!1},data:r}}});var wo=require("@better-fetch/fetch");var mt=require("oslo/jwt");var ft=e=>({id:"twitch",name:"Twitch",createAuthorizationURL({state:t,scopes:r,redirectURI:o}){let n=r||["user:read:email","openid"];return e.scope&&n.push(...e.scope),A({id:"twitch",redirectURI:o,options:e,authorizationEndpoint:"https://id.twitch.tv/oauth2/authorize",scopes:n,state:t,claims:e.claims||["email","email_verified","preferred_username","picture"]})},validateAuthorizationCode:async({code:t,redirectURI:r})=>y({code:t,redirectURI:e.redirectURI||r,options:e,tokenEndpoint:"https://id.twitch.tv/oauth2/token"}),async getUserInfo(t){let r=t.idToken;if(!r)return f.error("No idToken found in token"),null;let o=(0,mt.parseJWT)(r)?.payload;return{user:{id:o.sub,name:o.preferred_username,email:o.email,image:o.picture,emailVerified:!1},data:o}}});var gt=require("@better-fetch/fetch");var ht=e=>({id:"twitter",name:"Twitter",createAuthorizationURL(t){let r=t.scopes||["account_info.read"];return e.scope&&r.push(...e.scope),A({id:"twitter",options:e,authorizationEndpoint:"https://twitter.com/i/oauth2/authorize",scopes:r,state:t.state,codeVerifier:t.codeVerifier,redirectURI:t.redirectURI})},validateAuthorizationCode:async({code:t,codeVerifier:r,redirectURI:o})=>y({code:t,codeVerifier:r,redirectURI:e.redirectURI||o,options:e,tokenEndpoint:"https://id.twitch.tv/oauth2/token"}),async getUserInfo(t){let{data:r,error:o}=await(0,gt.betterFetch)("https://api.x.com/2/users/me?user.fields=profile_image_url",{method:"GET",headers:{Authorization:`Bearer ${t.accessToken}`}});return o||!r.data.email?null:{user:{id:r.data.id,name:r.data.name,email:r.data.email,image:r.data.profile_image_url,emailVerified:r.data.verified||!1},data:r}}});var wt=require("@better-fetch/fetch");var bt=e=>{let t="https://api.dropboxapi.com/oauth2/token";return{id:"dropbox",name:"Dropbox",createAuthorizationURL:async({state:r,scopes:o,codeVerifier:n,redirectURI:i})=>{let s=o||["account_info.read"];return e.scope&&s.push(...e.scope),await A({id:"dropbox",options:e,authorizationEndpoint:"https://www.dropbox.com/oauth2/authorize",scopes:s,state:r,redirectURI:i,codeVerifier:n})},validateAuthorizationCode:async({code:r,codeVerifier:o,redirectURI:n})=>await y({code:r,codeVerifier:o,redirectURI:e.redirectURI||n,options:e,tokenEndpoint:t}),async getUserInfo(r){let{data:o,error:n}=await(0,wt.betterFetch)("https://api.dropboxapi.com/2/users/get_current_account",{method:"POST",headers:{Authorization:`Bearer ${r.accessToken}`}});return n?null:{user:{id:o.account_id,name:o.name?.display_name,email:o.email,emailVerified:o.email_verified||!1,image:o.profile_photo_url},data:o}}}};var yt=require("@better-fetch/fetch");var At=e=>{let t="https://www.linkedin.com/oauth/v2/authorization",r="https://www.linkedin.com/oauth/v2/accessToken";return{id:"linkedin",name:"Linkedin",createAuthorizationURL:async({state:o,scopes:n,redirectURI:i})=>{let s=n||["profile","email","openid"];return e.scope&&s.push(...e.scope),await A({id:"linkedin",options:e,authorizationEndpoint:t,scopes:s,state:o,redirectURI:i})},validateAuthorizationCode:async({code:o,redirectURI:n})=>await y({code:o,redirectURI:e.redirectURI||n,options:e,tokenEndpoint:r}),async getUserInfo(o){let{data:n,error:i}=await(0,yt.betterFetch)("https://api.linkedin.com/v2/userinfo",{method:"GET",headers:{Authorization:`Bearer ${o.accessToken}`}});return i?null:{user:{id:n.sub,name:n.name,email:n.email,emailVerified:n.email_verified||!1,image:n.picture},data:n}}}};var kt=require("@better-fetch/fetch");var me=(e="")=>e.split("://").map(t=>t.replace(/\/{2,}/g,"/")).join("://"),Ht=e=>{let t=e||"https://gitlab.com";return{authorizationEndpoint:me(`${t}/oauth/authorize`),tokenEndpoint:me(`${t}/oauth/token`),userinfoEndpoint:me(`${t}/api/v4/user`)}},Rt=e=>{let{authorizationEndpoint:t,tokenEndpoint:r,userinfoEndpoint:o}=Ht(e.issuer),n="gitlab";return{id:n,name:"Gitlab",createAuthorizationURL:async({state:s,scopes:a,codeVerifier:c,redirectURI:u})=>{let d=a||["read_user"];return e.scope&&d.push(...e.scope),await A({id:n,options:e,authorizationEndpoint:t,scopes:d,state:s,redirectURI:u,codeVerifier:c})},validateAuthorizationCode:async({code:s,redirectURI:a,codeVerifier:c})=>y({code:s,redirectURI:e.redirectURI||a,options:e,codeVerifier:c,tokenEndpoint:r}),async getUserInfo(s){let{data:a,error:c}=await(0,kt.betterFetch)(o,{headers:{authorization:`Bearer ${s.accessToken}`}});return c||a.state!=="active"||a.locked?null:{user:{id:a.id.toString(),name:a.name??a.username,email:a.email,image:a.avatar_url,emailVerified:!0},data:a}}}};var Gt={apple:et,discord:rt,facebook:nt,github:it,microsoft:ut,google:at,spotify:pt,twitch:ft,twitter:ht,dropbox:bt,linkedin:At,gitlab:Rt},te=Object.keys(Gt);var Et=require("oslo"),ne=require("oslo/jwt"),_=require("zod");var j=require("better-call");var M=require("better-call");var F=require("zod");function Ut(e){try{return JSON.parse(e)}catch{return null}}var re=()=>m("/get-session",{method:"GET",query:F.z.optional(F.z.object({disableCookieCache:F.z.boolean().optional()})),requireHeaders:!0},async e=>{try{let t=await e.getSignedCookie(e.context.authCookies.sessionToken.name,e.context.secret);if(!t)return e.json(null,{status:401});let r=e.getCookie(e.context.authCookies.sessionData.name),o=r?Ut(Buffer.from(r,"base64").toString()):null;if(o&&!await ee.verify({value:JSON.stringify(o.session),signature:o?.signature,secret:e.context.secret}))return B(e),e.json(null,{status:401});let n=await e.getSignedCookie(e.context.authCookies.dontRememberToken.name,e.context.secret);if(o?.session&&e.context.options.session?.cookieCache?.enabled&&!e.query?.disableCookieCache){let d=o.session;if(o.expiresAt<Date.now()||d.session.expiresAt<new Date){let p=e.context.authCookies.sessionData.name;e.setCookie(p,"",{maxAge:0})}else return e.json(d)}let i=await e.context.internalAdapter.findSession(t);if(!i||i.session.expiresAt<new Date)return B(e),i&&await e.context.internalAdapter.deleteSession(i.session.id),e.json(null,{status:401});if(n)return e.json(i);let s=e.context.sessionConfig.expiresIn,a=e.context.sessionConfig.updateAge;if(i.session.expiresAt.valueOf()-s*1e3+a*1e3<=Date.now()){let d=await e.context.internalAdapter.updateSession(i.session.id,{expiresAt:C(e.context.sessionConfig.expiresIn,"sec")});if(!d)return B(e),e.json(null,{status:401});let h=(d.expiresAt.valueOf()-Date.now())/1e3;return await T(e,{session:d,user:i.user},!1,{maxAge:h}),e.json({session:d,user:i.user})}return e.json(i)}catch(t){return e.context.logger.error(t),e.json(null,{status:500})}}),oe=async e=>await re()({...e,_flag:"json",headers:e.headers}),v=G(async e=>{let t=await oe(e);if(!t?.session)throw new M.APIError("UNAUTHORIZED");return{session:t}}),fe=()=>m("/list-sessions",{method:"GET",use:[v],requireHeaders:!0},async e=>{let r=(await e.context.internalAdapter.listSessions(e.context.session.user.id)).filter(o=>o.expiresAt>new Date);return e.json(r)}),ge=m("/revoke-session",{method:"POST",body:F.z.object({id:F.z.string()}),use:[v],requireHeaders:!0},async e=>{let t=e.body.id,r=await e.context.internalAdapter.findSession(t);if(!r)throw new M.APIError("BAD_REQUEST",{message:"Session not found"});if(r.session.userId!==e.context.session.user.id)throw new M.APIError("UNAUTHORIZED");try{await e.context.internalAdapter.deleteSession(t)}catch(o){throw e.context.logger.error(o),new M.APIError("INTERNAL_SERVER_ERROR")}return e.json({status:!0})}),he=m("/revoke-sessions",{method:"POST",use:[v],requireHeaders:!0},async e=>{try{await e.context.internalAdapter.deleteSessions(e.context.session.user.id)}catch(t){throw e.context.logger.error(t),new M.APIError("INTERNAL_SERVER_ERROR")}return e.json({status:!0})});async function S(e,t,r){return await(0,ne.createJWT)("HS256",Buffer.from(e),{email:t.toLowerCase(),updateTo:r},{expiresIn:new Et.TimeSpan(1,"h"),issuer:"better-auth",subject:"verify-email",audiences:[t],includeIssuedTimestamp:!0})}var we=m("/send-verification-email",{method:"POST",query:_.z.object({currentURL:_.z.string().optional()}).optional(),body:_.z.object({email:_.z.string().email(),callbackURL:_.z.string().optional()})},async e=>{if(!e.context.options.emailVerification?.sendVerificationEmail)throw e.context.logger.error("Verification email isn't enabled."),new j.APIError("BAD_REQUEST",{message:"Verification email isn't enabled"});let{email:t}=e.body,r=await e.context.internalAdapter.findUserByEmail(t);if(!r)throw new j.APIError("BAD_REQUEST",{message:"User not found"});let o=await S(e.context.secret,t),n=`${e.context.baseURL}/verify-email?token=${o}&callbackURL=${e.body.callbackURL||e.query?.currentURL||"/"}`;return await e.context.options.emailVerification.sendVerificationEmail(r.user,n,o),e.json({status:!0})}),be=m("/verify-email",{method:"GET",query:_.z.object({token:_.z.string(),callbackURL:_.z.string().optional()})},async e=>{let{token:t}=e.query,r;try{r=await(0,ne.validateJWT)("HS256",Buffer.from(e.context.secret),t)}catch(s){throw e.context.logger.error("Failed to verify email",s),new j.APIError("BAD_REQUEST",{message:"Invalid token"})}let n=_.z.object({email:_.z.string().email(),updateTo:_.z.string().optional()}).parse(r.payload);if(!await e.context.internalAdapter.findUserByEmail(n.email))throw new j.APIError("BAD_REQUEST",{message:"User not found"});if(n.updateTo){let s=await oe(e);if(!s)throw e.query.callbackURL?e.redirect(`${e.query.callbackURL}?error=unauthorized`):new j.APIError("UNAUTHORIZED",{message:"Session not found"});if(s.user.email!==n.email)throw e.query.callbackURL?e.redirect(`${e.query.callbackURL}?error=unauthorized`):new j.APIError("UNAUTHORIZED",{message:"Invalid session"});let a=await e.context.internalAdapter.updateUserByEmail(n.email,{email:n.updateTo});if(await e.context.options.emailVerification?.sendVerificationEmail?.(a,`${e.context.baseURL}/verify-email?token=${t}`,t),e.query.callbackURL)throw e.redirect(e.query.callbackURL);return e.json({user:a,status:!0})}if(await e.context.internalAdapter.updateUserByEmail(n.email,{emailVerified:!0}),e.query.callbackURL)throw e.redirect(e.query.callbackURL);return e.json({user:null,status:!0})});var ye=m("/sign-in/social",{method:"POST",query:x.z.object({currentURL:x.z.string().optional()}).optional(),body:x.z.object({callbackURL:x.z.string().optional(),provider:x.z.enum(te)})},async e=>{let t=e.context.socialProviders.find(i=>i.id===e.body.provider);if(!t)throw e.context.logger.error("Provider not found. Make sure to add the provider in your auth config",{provider:e.body.provider}),new O.APIError("NOT_FOUND",{message:"Provider not found"});let{codeVerifier:r,state:o}=await K(e),n=await t.createAuthorizationURL({state:o,codeVerifier:r,redirectURI:`${e.context.baseURL}/callback/${t.id}`});return e.json({url:n.toString(),redirect:!0})}),Ae=m("/sign-in/email",{method:"POST",body:x.z.object({email:x.z.string(),password:x.z.string(),callbackURL:x.z.string().optional(),dontRememberMe:x.z.boolean().default(!1).optional()})},async e=>{if(!e.context.options?.emailAndPassword?.enabled)throw e.context.logger.error("Email and password is not enabled. Make sure to enable it in the options on you `auth.ts` file. Check `https://better-auth.com/docs/authentication/email-password` for more!"),new O.APIError("BAD_REQUEST",{message:"Email and password is not enabled"});let{email:t,password:r}=e.body;if(!x.z.string().email().safeParse(t).success)throw new O.APIError("BAD_REQUEST",{message:"Invalid email"});let n=await e.context.internalAdapter.findUserByEmail(t,{includeAccounts:!0});if(!n)throw await e.context.password.hash(r),e.context.logger.error("User not found",{email:t}),new O.APIError("UNAUTHORIZED",{message:"Invalid email or password"});let i=n.accounts.find(u=>u.providerId==="credential");if(!i)throw e.context.logger.error("Credential account not found",{email:t}),new O.APIError("UNAUTHORIZED",{message:"Invalid email or password"});let s=i?.password;if(!s)throw e.context.logger.error("Password not found",{email:t}),new O.APIError("UNAUTHORIZED",{message:"Unexpected error"});if(!await e.context.password.verify(s,r))throw e.context.logger.error("Invalid password"),new O.APIError("UNAUTHORIZED",{message:"Invalid email or password"});if(e.context.options?.emailAndPassword?.requireEmailVerification&&!n.user.emailVerified){if(!e.context.options?.emailVerification?.sendVerificationEmail)throw f.error("Email verification is required but no email verification handler is provided"),new O.APIError("INTERNAL_SERVER_ERROR",{message:"Email is not verified."});let u=await S(e.context.secret,n.user.email),d=`${e.context.options.baseURL}/verify-email?token=${u}`;throw await e.context.options.emailVerification.sendVerificationEmail(n.user,d,u),e.context.logger.error("Email not verified",{email:t}),new O.APIError("FORBIDDEN",{message:"Email is not verified. Check your email for a verification link"})}let c=await e.context.internalAdapter.createSession(n.user.id,e.headers,e.body.dontRememberMe);if(!c)throw e.context.logger.error("Failed to create session"),new O.APIError("UNAUTHORIZED",{message:"Failed to create session"});return await T(e,{session:c,user:n.user},e.body.dontRememberMe),e.json({user:n.user,session:c,redirect:!!e.body.callbackURL,url:e.body.callbackURL})});var Z=require("zod");var g=require("zod"),bn=g.z.object({id:g.z.string(),providerId:g.z.string(),accountId:g.z.string(),userId:g.z.string(),accessToken:g.z.string().nullable().optional(),refreshToken:g.z.string().nullable().optional(),idToken:g.z.string().nullable().optional(),expiresAt:g.z.date().nullable().optional(),password:g.z.string().optional().nullable()}),vt=g.z.object({id:g.z.string(),email:g.z.string().transform(e=>e.toLowerCase()),emailVerified:g.z.boolean().default(!1),name:g.z.string(),image:g.z.string().optional(),createdAt:g.z.date().default(new Date),updatedAt:g.z.date().default(new Date)}),yn=g.z.object({id:g.z.string(),userId:g.z.string(),expiresAt:g.z.date(),ipAddress:g.z.string().optional(),userAgent:g.z.string().optional()}),An=g.z.object({id:g.z.string(),value:g.z.string(),expiresAt:g.z.date(),identifier:g.z.string()});function Qt(e,t){let r={...t==="user"?e.user?.additionalFields:{},...t==="session"?e.session?.additionalFields:{}};for(let o of e.plugins||[])o.schema&&o.schema[t]&&(r={...r,...o.schema[t].fields});return r}function Zt(e,t){let r=t.action||"create",o=t.fields,n={};for(let i in o){if(i in e){if(o[i].input===!1){if(o[i].defaultValue){n[i]=o[i].defaultValue;continue}continue}n[i]=e[i];continue}if(o[i].defaultValue&&r==="create"){n[i]=o[i].defaultValue;continue}}return n}function ie(e,t,r){let o=Qt(e,"user");return Zt(t||{},{fields:o,action:r})}var ke=m("/callback/:id",{method:"GET",query:Z.z.object({state:Z.z.string(),code:Z.z.string().optional(),error:Z.z.string().optional()}),metadata:N},async e=>{if(!e.query.code)throw e.redirect(`${e.context.baseURL}/error?error=${e.query.error||"no_code"}`);let t=e.context.socialProviders.find(w=>w.id===e.params.id);if(!t)throw e.context.logger.error("Oauth provider with id",e.params.id,"not found"),e.redirect(`${e.context.baseURL}/error?error=oauth_provider_not_found`);let{codeVerifier:r,callbackURL:o,link:n,errorURL:i}=await Fe(e),s;try{s=await t.validateAuthorizationCode({code:e.query.code,codeVerifier:r,redirectURI:`${e.context.baseURL}/callback/${t.id}`})}catch(w){throw e.context.logger.error(w),e.redirect(`${e.context.baseURL}/error?error=please_restart_the_process`)}let a=await t.getUserInfo(s).then(w=>w?.user),c=je(),u=vt.safeParse({...a,id:c});if(!a||u.success===!1)throw f.error("Unable to get user info",u.error),e.redirect(`${e.context.baseURL}/error?error=please_restart_the_process`);if(!o)throw f.error("No callback URL found"),e.redirect(`${e.context.baseURL}/error?error=please_restart_the_process`);if(n){if(n.email!==a.email.toLowerCase())return d("email_doesn't_match");if(!await e.context.internalAdapter.createAccount({userId:n.userId,providerId:t.id,accountId:a.id}))return d("unable_to_link_account");let b;try{b=new URL(o).toString()}catch{b=o}throw e.redirect(b)}function d(w){throw e.redirect(`${i||o||`${e.context.baseURL}/error`}?error=${w}`)}let h=await e.context.internalAdapter.findUserByEmail(a.email,{includeAccounts:!0}).catch(w=>{throw f.error(`Better auth was unable to query your database.
|
|
4
|
+
Error: `,w),e.redirect(`${e.context.baseURL}/error?error=internal_server_error`)}),p=h?.user;if(h){let w=h.accounts.find(b=>b.providerId===t.id);if(w)await e.context.internalAdapter.updateAccount(w.id,{accessToken:s.accessToken,idToken:s.idToken,refreshToken:s.refreshToken,expiresAt:s.accessTokenExpiresAt});else{(!e.context.options.account?.accountLinking?.trustedProviders?.includes(t.id)&&!a.emailVerified||e.context.options.account?.accountLinking?.enabled===!1)&&(qe&&f.warn(`User already exist but account isn't linked to ${t.id}. To read more about how account linking works in Better Auth see https://www.better-auth.com/docs/concepts/users-accounts#account-linking.`),d("account_not_linked"));try{await e.context.internalAdapter.linkAccount({providerId:t.id,accountId:a.id.toString(),id:`${t.id}:${a.id}`,userId:h.user.id,accessToken:s.accessToken,idToken:s.idToken,refreshToken:s.refreshToken,expiresAt:s.accessTokenExpiresAt})}catch(ze){f.error("Unable to link account",ze),d("unable_to_link_account")}}}else try{let w=a.emailVerified||!1;if(p=await e.context.internalAdapter.createOAuthUser({...u.data,emailVerified:w},{accessToken:s.accessToken,idToken:s.idToken,refreshToken:s.refreshToken,expiresAt:s.accessTokenExpiresAt,providerId:t.id,accountId:a.id.toString()}).then(b=>b?.user),!w&&p&&e.context.options.emailVerification?.sendOnSignUp){let b=await S(e.context.secret,p.email),R=`${e.context.baseURL}/verify-email?token=${b}&callbackURL=${o}`;await e.context.options.emailVerification?.sendVerificationEmail?.(p,R,b)}}catch(w){f.error("Unable to create user",w),d("unable_to_create_user")}if(!p)return d("unable_to_create_user");let l=await e.context.internalAdapter.createSession(p.id,e.request);l||d("unable_to_create_session"),await T(e,{session:l,user:p});let k;try{k=new URL(o).toString()}catch{k=o}throw e.redirect(k)});var Ln=require("zod");var _t=require("better-call"),Re=m("/sign-out",{method:"POST",requireHeaders:!0},async e=>{let t=await e.getSignedCookie(e.context.authCookies.sessionToken.name,e.context.secret);if(!t)throw new _t.APIError("BAD_REQUEST",{message:"Session not found"});return await e.context.internalAdapter.deleteSession(t),B(e),e.json({success:!0})});var P=require("zod");var J=require("better-call");function xt(e,t,r){let o=t?new URL(t,e.baseURL):new URL(`${e.baseURL}/error`);return r&&Object.entries(r).forEach(([n,i])=>o.searchParams.set(n,i)),o.href}function Jt(e,t,r){let o=new URL(t,e.baseURL);return r&&Object.entries(r).forEach(([n,i])=>o.searchParams.set(n,i)),o.href}var Ue=m("/forget-password",{method:"POST",body:P.z.object({email:P.z.string().email(),redirectTo:P.z.string()})},async e=>{if(!e.context.options.emailAndPassword?.sendResetPassword)throw e.context.logger.error("Reset password isn't enabled.Please pass an emailAndPassword.sendResetPasswordToken function in your auth config!"),new J.APIError("BAD_REQUEST",{message:"Reset password isn't enabled"});let{email:t,redirectTo:r}=e.body,o=await e.context.internalAdapter.findUserByEmail(t,{includeAccounts:!0});if(!o)return e.context.logger.error("Reset Password: User not found",{email:t}),e.json({status:!1},{body:{status:!0}});let n=60*60*1,i=new Date(Date.now()+1e3*(e.context.options.emailAndPassword.resetPasswordTokenExpiresIn||n)),s=e.context.uuid();await e.context.internalAdapter.createVerificationValue({value:o.user.id,identifier:`reset-password:${s}`,expiresAt:i});let a=`${e.context.baseURL}/reset-password/${s}?callbackURL=${r}`;return await e.context.options.emailAndPassword.sendResetPassword(o.user,a),e.json({status:!0})}),Ee=m("/reset-password/:token",{method:"GET",query:P.z.object({callbackURL:P.z.string()})},async e=>{let{token:t}=e.params,{callbackURL:r}=e.query;if(!t||!r)throw e.redirect(xt(e.context,r,{error:"INVALID_TOKEN"}));let o=await e.context.internalAdapter.findVerificationValue(`reset-password:${t}`);throw!o||o.expiresAt<new Date?e.redirect(xt(e.context,r,{error:"INVALID_TOKEN"})):e.redirect(Jt(e.context,r,{token:t}))}),ve=m("/reset-password",{query:P.z.optional(P.z.object({token:P.z.string().optional(),currentURL:P.z.string().optional()})),method:"POST",body:P.z.object({newPassword:P.z.string()})},async e=>{let t=e.query?.token||(e.query?.currentURL?new URL(e.query.currentURL).searchParams.get("token"):"");if(!t)throw new J.APIError("BAD_REQUEST",{message:"Token not found"});let{newPassword:r}=e.body,o=`reset-password:${t}`,n=await e.context.internalAdapter.findVerificationValue(o);if(!n||n.expiresAt<new Date)throw new J.APIError("BAD_REQUEST",{message:"Invalid token"});await e.context.internalAdapter.deleteVerificationValue(n.id);let i=n.value,s=await e.context.password.hash(r);if(!(await e.context.internalAdapter.findAccounts(i)).find(d=>d.providerId==="credential"))return await e.context.internalAdapter.createAccount({userId:i,providerId:"credential",password:s,accountId:e.context.uuid()}),e.json({status:!0});if(!await e.context.internalAdapter.updatePassword(i,s))throw new J.APIError("BAD_REQUEST",{message:"Failed to update password"});return e.json({status:!0})});var U=require("zod");var E=require("better-call");var _e=()=>m("/update-user",{method:"POST",body:U.z.record(U.z.string(),U.z.any()),use:[v]},async e=>{let t=e.body;if(t.email)throw new E.APIError("BAD_REQUEST",{message:"You can't update email"});let{name:r,image:o,...n}=t,i=e.context.session;if(!o&&!r&&Object.keys(n).length===0)return e.json({user:i.user});let s=ie(e.context.options,n,"update"),a=await e.context.internalAdapter.updateUserByEmail(i.user.email,{name:r,image:o,...s});return await T(e,{session:i.session,user:a}),e.json({user:a})}),xe=m("/change-password",{method:"POST",body:U.z.object({newPassword:U.z.string(),currentPassword:U.z.string(),revokeOtherSessions:U.z.boolean().optional()}),use:[v]},async e=>{let{newPassword:t,currentPassword:r,revokeOtherSessions:o}=e.body,n=e.context.session,i=e.context.password.config.minPasswordLength;if(t.length<i)throw e.context.logger.error("Password is too short"),new E.APIError("BAD_REQUEST",{message:"Password is too short"});let s=e.context.password.config.maxPasswordLength;if(t.length>s)throw e.context.logger.error("Password is too long"),new E.APIError("BAD_REQUEST",{message:"Password too long"});let c=(await e.context.internalAdapter.findAccounts(n.user.id)).find(h=>h.providerId==="credential"&&h.password);if(!c||!c.password)throw new E.APIError("BAD_REQUEST",{message:"User does not have a password"});let u=await e.context.password.hash(t);if(!await e.context.password.verify(c.password,r))throw new E.APIError("BAD_REQUEST",{message:"Incorrect password"});if(await e.context.internalAdapter.updateAccount(c.id,{password:u}),o){await e.context.internalAdapter.deleteSessions(n.user.id);let h=await e.context.internalAdapter.createSession(n.user.id,e.headers);if(!h)throw new E.APIError("INTERNAL_SERVER_ERROR",{message:"Unable to create session"});await T(e,{session:h,user:n.user})}return e.json(n.user)}),Pe=m("/set-password",{method:"POST",body:U.z.object({newPassword:U.z.string()}),metadata:{SERVER_ONLY:!0},use:[v]},async e=>{let{newPassword:t}=e.body,r=e.context.session,o=e.context.password.config.minPasswordLength;if(t.length<o)throw e.context.logger.error("Password is too short"),new E.APIError("BAD_REQUEST",{message:"Password is too short"});let n=e.context.password.config.maxPasswordLength;if(t.length>n)throw e.context.logger.error("Password is too long"),new E.APIError("BAD_REQUEST",{message:"Password too long"});let s=(await e.context.internalAdapter.findAccounts(r.user.id)).find(c=>c.providerId==="credential"&&c.password),a=await e.context.password.hash(t);if(!s)return await e.context.internalAdapter.linkAccount({userId:r.user.id,providerId:"credential",accountId:r.user.id,password:a}),e.json(r.user);throw new E.APIError("BAD_REQUEST",{message:"user already has a password"})}),Te=m("/delete-user",{method:"POST",body:U.z.object({password:U.z.string()}),use:[v]},async e=>{let{password:t}=e.body,r=e.context.session,n=(await e.context.internalAdapter.findAccounts(r.user.id)).find(s=>s.providerId==="credential"&&s.password);if(!n||!n.password)throw new E.APIError("BAD_REQUEST",{message:"User does not have a password"});if(!await e.context.password.verify(n.password,t))throw new E.APIError("BAD_REQUEST",{message:"Incorrect password"});return await e.context.internalAdapter.deleteUser(r.user.id),await e.context.internalAdapter.deleteSessions(r.user.id),B(e),e.json(null)}),Oe=m("/change-email",{method:"POST",query:U.z.object({currentURL:U.z.string().optional()}).optional(),body:U.z.object({newEmail:U.z.string().email(),callbackURL:U.z.string().optional()}),use:[v]},async e=>{if(!e.context.options.user?.changeEmail?.enabled)throw e.context.logger.error("Change email is disabled."),new E.APIError("BAD_REQUEST",{message:"Change email is disabled"});if(e.body.newEmail===e.context.session.user.email)throw e.context.logger.error("Email is the same"),new E.APIError("BAD_REQUEST",{message:"Email is the same"});if(await e.context.internalAdapter.findUserByEmail(e.body.newEmail))throw e.context.logger.error("Email already exists"),new E.APIError("BAD_REQUEST",{message:"Couldn't update your email"});if(e.context.session.user.emailVerified!==!0){let n=await e.context.internalAdapter.updateUserByEmail(e.context.session.user.email,{email:e.body.newEmail});return e.json({user:n,status:!0})}if(!e.context.options.user.changeEmail.sendChangeEmailVerification)throw e.context.logger.error("Verification email isn't enabled."),new E.APIError("BAD_REQUEST",{message:"Verification email isn't enabled"});let r=await S(e.context.secret,e.context.session.user.email,e.body.newEmail),o=`${e.context.baseURL}/verify-email?token=${r}&callbackURL=${e.body.callbackURL||e.query?.currentURL||"/"}`;return await e.context.options.user.changeEmail.sendChangeEmailVerification(e.context.session.user,e.body.newEmail,o,r),e.json({user:null,status:!0})});var Wt=(e="Unknown")=>`<!DOCTYPE html>
|
|
5
5
|
<html lang="en">
|
|
6
6
|
<head>
|
|
7
7
|
<meta charset="UTF-8">
|
|
@@ -81,4 +81,4 @@ Error: `,h),e.redirect(`${e.context.baseURL}/error?error=internal_server_error`)
|
|
|
81
81
|
<div class="error-code">Error Code: <span id="errorCode">${e}</span></div>
|
|
82
82
|
</div>
|
|
83
83
|
</body>
|
|
84
|
-
</html>`,
|
|
84
|
+
</html>`,Se=m("/error",{method:"GET",metadata:N},async e=>{let t=new URL(e.request?.url||"").searchParams.get("error")||"Unknown";return new Response(Wt(t),{headers:{"Content-Type":"text/html"}})});var Le=m("/ok",{method:"GET",metadata:N},async e=>e.json({ok:!0}));var $=require("zod");var L=require("better-call");var Ie=()=>m("/sign-up/email",{method:"POST",query:$.z.object({currentURL:$.z.string().optional()}).optional(),body:$.z.record($.z.string(),$.z.any())},async e=>{if(!e.context.options.emailAndPassword?.enabled)throw new L.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.string().email().safeParse(o).success)throw new L.APIError("BAD_REQUEST",{message:"Invalid email"});let u=e.context.password.config.minPasswordLength;if(n.length<u)throw e.context.logger.error("Password is too short"),new L.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 L.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 L.APIError("UNPROCESSABLE_ENTITY",{message:"User with this email already exists"});let p=ie(e.context.options,a),l;try{if(l=await e.context.internalAdapter.createUser({email:o.toLowerCase(),name:r,image:i,...p,emailVerified:!1}),!l)throw new L.APIError("BAD_REQUEST",{message:"Failed to create user"})}catch(b){throw f.error("Failed to create user",b),new L.APIError("UNPROCESSABLE_ENTITY",{message:"Failed to create user",details:b})}if(!l)throw new L.APIError("UNPROCESSABLE_ENTITY",{message:"Failed to create user"});let k=await e.context.password.hash(n);if(await e.context.internalAdapter.linkAccount({userId:l.id,providerId:"credential",accountId:l.id,password:k,expiresAt:C(60*60*24*30,"sec")}),e.context.options.emailVerification?.sendOnSignUp){let b=await S(e.context.secret,l.email),R=`${e.context.baseURL}/verify-email?token=${b}&callbackURL=${t.callbackURL||e.query?.currentURL||"/"}`;await e.context.options.emailVerification?.sendVerificationEmail?.(l,R,b)}if(!e.context.options.emailAndPassword.autoSignIn||e.context.options.emailAndPassword.requireEmailVerification)return e.json({user:l,session:null},{body:t.callbackURL?{url:t.callbackURL,redirect:!0}:{user:l,session:null}});let w=await e.context.internalAdapter.createSession(l.id,e.request);if(!w)throw new L.APIError("BAD_REQUEST",{message:"Failed to create session"});return await T(e,{session:w,user:l}),e.json({user:l,session:w})});var H=require("zod");var Ce=require("better-call");var Be=m("/list-accounts",{method:"GET",use:[v]},async e=>{let t=e.context.session,r=await e.context.internalAdapter.findAccounts(t.user.id);return e.json(r.map(o=>({id:o.id,provider:o.providerId})))}),De=m("/link-social",{method:"POST",requireHeaders:!0,query:H.z.object({currentURL:H.z.string().optional()}).optional(),body:H.z.object({callbackURL:H.z.string().optional(),provider:H.z.enum(te)}),use:[v]},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 Ce.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 Ce.APIError("NOT_FOUND",{message:"Provider not found"});let i=await K(e,{userId:t.user.id,email:t.user.email}),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 Pt(e){let t="127.0.0.1";if(Ne)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 Yt(e,t,r){let o=Date.now(),n=t*1e3;return o-r.lastRequest<n&&r.count>=e}function Kt(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 Xt(e,t){let r=Date.now(),o=t*1e3;return Math.ceil((e+o-r)/1e3)}function er(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 Tt=new Map;function tr(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 Tt.get(r)},async set(r,o,n){Tt.set(r,o)}}:er(e,e.rateLimit.tableName)}async function Ot(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=Pt(e)+o,c=rr().find(p=>p.pathMatcher(o));c&&(n=c.window,i=c.max);for(let p of t.options.plugins||[])if(p.rateLimit){let l=p.rateLimit.find(k=>k.pathMatcher(o));if(l){n=l.window,i=l.max;break}}if(t.rateLimit.customRules){let p=t.rateLimit.customRules[o];p&&(n=p.window,i=p.max)}let u=tr(t),d=await u.get(s),h=Date.now();if(!d)await u.set(s,{key:s,count:1,lastRequest:h});else{let p=h-d.lastRequest;if(Yt(i,n,d)){let l=Xt(d.lastRequest,n);return Kt(l)}else p>n*1e3?await u.set(s,{...d,count:1,lastRequest:h}):await u.set(s,{...d,count:d.count+1,lastRequest:h})}}function rr(){return[{pathMatcher(t){return t.startsWith("/sign-in")||t.startsWith("/sign-up")||t.startsWith("/change-password")||t.startsWith("/change-email")},window:10,max:3}]}var Lt=require("better-call");function St(e,t){let r=t.plugins?.reduce((a,c)=>({...a,...c.endpoints}),{}),o=t.plugins?.map(a=>a.middlewares?.map(c=>{let u=async d=>c.middleware({...d,context:{...e,...d.context}});return u.path=c.path,u.options=c.middleware.options,u.headers=c.middleware.headers,{path:c.path,middleware:u}})).filter(a=>a!==void 0).flat()||[],i={...{signInSocial:ye,callbackOAuth:ke,getSession:re(),signOut:Re,signUpEmail:Ie(),signInEmail:Ae,forgetPassword:Ue,resetPassword:ve,verifyEmail:be,sendVerificationEmail:we,changeEmail:Oe,changePassword:xe,setPassword:Pe,updateUser:_e(),deleteUser:Te,forgetPasswordCallback:Ee,listSessions:fe(),revokeSession:ge,revokeSessions:he,linkSocialAccount:De,listUserAccounts:Be},...r,ok:Le,error:Se},s={};for(let[a,c]of Object.entries(i))s[a]=async(u={})=>{let d=await e;for(let l of t.plugins||[])if(l.hooks?.before){for(let k of l.hooks.before)if(k.matcher({...c,...u,context:d})){let b=await k.handler({...u,context:{...d,...u?.context}});b&&"context"in b&&(d={...d,...b.context})}}let h;try{h=await c({...u,context:{...d,...u.context}})}catch(l){if(l instanceof q.APIError){let k=t.plugins?.map(R=>{if(R.hooks?.after)return R.hooks.after}).filter(R=>R!==void 0).flat();if(!k?.length)throw l;let w=new Response(JSON.stringify(l.body),{status:q.statusCode[l.status],headers:l.headers}),b;for(let R of k||[])if(R.matcher(u)){let It=Object.assign(u,{context:{...e,returned:w}}),se=await R.handler(It);se&&"response"in se&&(b=se.response)}if(b instanceof Response)return b;throw l}throw l}let p=h;for(let l of t.plugins||[])if(l.hooks?.after){for(let k of l.hooks.after)if(k.matcher(u)){let b=Object.assign(u,{context:{...e,returned:p}}),R=await k.handler(b);R&&"response"in R&&(p=R.response)}}return p},s[a].path=c.path,s[a].method=c.method,s[a].options=c.options,s[a].headers=c.headers;return{api:s,middlewares:o}}var or=(e,t)=>{let{api:r,middlewares:o}=St(e,t),n=new URL(e.baseURL).pathname;return(0,q.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&&"response"in a)return a.response}return Ot(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 q.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,signInSocial,signOut,signUpEmail,updateUser,verifyEmail});
|
package/dist/api.d.cts
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
|
-
export { x as AuthEndpoint, y as AuthMiddleware, a1 as callbackOAuth, aj as changeEmail, ag as changePassword, w as createAuthEndpoint, v 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, u 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 signInSocial, a8 as signOut, am as signUpEmail, af as updateUser, ae as verifyEmail } from './auth-
|
|
1
|
+
export { x as AuthEndpoint, y as AuthMiddleware, a1 as callbackOAuth, aj as changeEmail, ag as changePassword, w as createAuthEndpoint, v 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, u 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 signInSocial, a8 as signOut, am as signUpEmail, af as updateUser, ae as verifyEmail } from './auth-C-uryrMH.cjs';
|
|
2
2
|
import './helper-DPDj8Nix.cjs';
|
|
3
3
|
export { APIError } from 'better-call';
|
|
4
4
|
import 'zod';
|
|
5
5
|
import 'kysely';
|
|
6
|
-
import './index-
|
|
6
|
+
import './index-DI6hwBqO.cjs';
|
|
7
7
|
import 'better-sqlite3';
|
package/dist/api.d.ts
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
|
-
export { x as AuthEndpoint, y as AuthMiddleware, a1 as callbackOAuth, aj as changeEmail, ag as changePassword, w as createAuthEndpoint, v 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, u 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 signInSocial, a8 as signOut, am as signUpEmail, af as updateUser, ae as verifyEmail } from './auth-
|
|
1
|
+
export { x as AuthEndpoint, y as AuthMiddleware, a1 as callbackOAuth, aj as changeEmail, ag as changePassword, w as createAuthEndpoint, v 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, u 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 signInSocial, a8 as signOut, am as signUpEmail, af as updateUser, ae as verifyEmail } from './auth-BmcfH9ig.js';
|
|
2
2
|
import './helper-DPDj8Nix.js';
|
|
3
3
|
export { APIError } from 'better-call';
|
|
4
4
|
import 'zod';
|
|
5
5
|
import 'kysely';
|
|
6
|
-
import './index-
|
|
6
|
+
import './index-Bn9csJDG.js';
|
|
7
7
|
import 'better-sqlite3';
|