better-auth 0.6.2-beta.2 → 0.6.2-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/api.cjs +1 -1
- package/dist/api.cjs.map +1 -1
- package/dist/api.js +1 -1
- package/dist/chunk-22HMFLRO.js +2 -0
- package/dist/chunk-22HMFLRO.js.map +1 -0
- package/dist/chunk-36URECJ6.cjs +84 -0
- package/dist/chunk-36URECJ6.cjs.map +1 -0
- package/dist/chunk-3MYUOPUJ.js +84 -0
- package/dist/chunk-3MYUOPUJ.js.map +1 -0
- package/dist/chunk-4KOW6P26.cjs +2 -0
- package/dist/chunk-4KOW6P26.cjs.map +1 -0
- package/dist/chunk-4V3ONM2X.cjs +2 -0
- package/dist/chunk-4V3ONM2X.cjs.map +1 -0
- package/dist/chunk-6MLVY3ZP.cjs +2 -0
- package/dist/chunk-6MLVY3ZP.cjs.map +1 -0
- package/dist/chunk-765KWDJJ.cjs +2 -0
- package/dist/chunk-765KWDJJ.cjs.map +1 -0
- package/dist/chunk-76CJSX5Z.cjs +84 -0
- package/dist/chunk-76CJSX5Z.cjs.map +1 -0
- package/dist/chunk-ANUVE5N2.cjs +2 -0
- package/dist/chunk-ANUVE5N2.cjs.map +1 -0
- package/dist/chunk-ASXTBHRY.cjs +2 -0
- package/dist/chunk-ASXTBHRY.cjs.map +1 -0
- package/dist/chunk-BB4FOHYJ.cjs +2 -0
- package/dist/chunk-BB4FOHYJ.cjs.map +1 -0
- package/dist/chunk-BCUEUV5U.cjs +2 -0
- package/dist/chunk-BCUEUV5U.cjs.map +1 -0
- package/dist/chunk-BF3ZIVEP.cjs +2 -0
- package/dist/chunk-BF3ZIVEP.cjs.map +1 -0
- package/dist/chunk-EUCIVSQA.cjs +84 -0
- package/dist/chunk-EUCIVSQA.cjs.map +1 -0
- package/dist/chunk-FEPJQ3QM.js +2 -0
- package/dist/chunk-FEPJQ3QM.js.map +1 -0
- package/dist/chunk-FSQ234LF.cjs +2 -0
- package/dist/chunk-FSQ234LF.cjs.map +1 -0
- package/dist/chunk-GOSX7KHG.cjs +2 -0
- package/dist/chunk-GOSX7KHG.cjs.map +1 -0
- package/dist/chunk-GTML3H7T.js +84 -0
- package/dist/chunk-GTML3H7T.js.map +1 -0
- package/dist/chunk-H4HZDW3K.js +2 -0
- package/dist/chunk-H4HZDW3K.js.map +1 -0
- package/dist/chunk-HCMBYNIG.cjs +84 -0
- package/dist/chunk-HCMBYNIG.cjs.map +1 -0
- package/dist/chunk-HE3JFIDQ.cjs +84 -0
- package/dist/chunk-HE3JFIDQ.cjs.map +1 -0
- package/dist/chunk-IHXN5FP4.js +2 -0
- package/dist/chunk-IHXN5FP4.js.map +1 -0
- package/dist/chunk-IRFV6U22.js +84 -0
- package/dist/chunk-IRFV6U22.js.map +1 -0
- package/dist/chunk-J5FOTKTB.js +2 -0
- package/dist/chunk-J5FOTKTB.js.map +1 -0
- package/dist/chunk-JBKMXGMI.js +2 -0
- package/dist/chunk-JBKMXGMI.js.map +1 -0
- package/dist/chunk-JFDMKZQC.js +2 -0
- package/dist/chunk-JFDMKZQC.js.map +1 -0
- package/dist/chunk-JOTNAFNS.js +2 -0
- package/dist/chunk-JOTNAFNS.js.map +1 -0
- package/dist/chunk-KHX7IOTX.cjs +2 -0
- package/dist/chunk-KHX7IOTX.cjs.map +1 -0
- package/dist/chunk-L7UQ5ZRF.cjs +84 -0
- package/dist/chunk-L7UQ5ZRF.cjs.map +1 -0
- package/dist/chunk-LX2KEOYP.js +2 -0
- package/dist/chunk-LX2KEOYP.js.map +1 -0
- package/dist/chunk-M43BLA3S.js +2 -0
- package/dist/chunk-M43BLA3S.js.map +1 -0
- package/dist/chunk-M7DGIHEC.js +2 -0
- package/dist/chunk-M7DGIHEC.js.map +1 -0
- package/dist/chunk-MYWEYRDB.js +2 -0
- package/dist/chunk-MYWEYRDB.js.map +1 -0
- package/dist/chunk-MZWQDKKQ.cjs +2 -0
- package/dist/chunk-MZWQDKKQ.cjs.map +1 -0
- package/dist/chunk-N7CDYTQY.js +2 -0
- package/dist/chunk-N7CDYTQY.js.map +1 -0
- package/dist/chunk-NOBBPP5T.js +2 -0
- package/dist/chunk-NOBBPP5T.js.map +1 -0
- package/dist/chunk-OPHRPBJ7.js +84 -0
- package/dist/chunk-OPHRPBJ7.js.map +1 -0
- package/dist/chunk-P4HGNL56.cjs +2 -0
- package/dist/chunk-P4HGNL56.cjs.map +1 -0
- package/dist/chunk-PA4ZPKTK.cjs +84 -0
- package/dist/chunk-PA4ZPKTK.cjs.map +1 -0
- package/dist/chunk-PAZZSTP2.js +2 -0
- package/dist/chunk-PAZZSTP2.js.map +1 -0
- package/dist/chunk-PPGBUVF4.cjs +2 -0
- package/dist/chunk-PPGBUVF4.cjs.map +1 -0
- package/dist/chunk-PV2BTKX2.cjs +2 -0
- package/dist/chunk-PV2BTKX2.cjs.map +1 -0
- package/dist/chunk-PYBJ4IUP.js +84 -0
- package/dist/chunk-PYBJ4IUP.js.map +1 -0
- package/dist/chunk-QE6KOCJD.cjs +2 -0
- package/dist/chunk-QE6KOCJD.cjs.map +1 -0
- package/dist/chunk-QMJ3PTW5.js +2 -0
- package/dist/chunk-QMJ3PTW5.js.map +1 -0
- package/dist/chunk-R52GWWV6.js +2 -0
- package/dist/chunk-R52GWWV6.js.map +1 -0
- package/dist/chunk-RPB3ZZFX.cjs +84 -0
- package/dist/chunk-RPB3ZZFX.cjs.map +1 -0
- package/dist/chunk-SD6SISNT.cjs +84 -0
- package/dist/chunk-SD6SISNT.cjs.map +1 -0
- package/dist/chunk-SDLJNIOO.js +84 -0
- package/dist/chunk-SDLJNIOO.js.map +1 -0
- package/dist/chunk-SUN5UQMP.js +84 -0
- package/dist/chunk-SUN5UQMP.js.map +1 -0
- package/dist/chunk-SXE3C5RF.cjs +2 -0
- package/dist/chunk-SXE3C5RF.cjs.map +1 -0
- package/dist/chunk-T7HYVNE5.cjs +2 -0
- package/dist/chunk-T7HYVNE5.cjs.map +1 -0
- package/dist/chunk-TAM5GREG.js +2 -0
- package/dist/chunk-TAM5GREG.js.map +1 -0
- package/dist/chunk-TY7GF3WV.js +84 -0
- package/dist/chunk-TY7GF3WV.js.map +1 -0
- package/dist/chunk-V777PRH6.cjs +2 -0
- package/dist/chunk-V777PRH6.cjs.map +1 -0
- package/dist/chunk-VVJASVLG.cjs +84 -0
- package/dist/chunk-VVJASVLG.cjs.map +1 -0
- package/dist/chunk-W6ITWVFO.js +2 -0
- package/dist/chunk-W6ITWVFO.js.map +1 -0
- package/dist/chunk-WEHFNO5E.js +84 -0
- package/dist/chunk-WEHFNO5E.js.map +1 -0
- package/dist/chunk-WZNIR7S4.cjs +2 -0
- package/dist/chunk-WZNIR7S4.cjs.map +1 -0
- package/dist/chunk-WZVI2E6Z.js +2 -0
- package/dist/chunk-WZVI2E6Z.js.map +1 -0
- package/dist/chunk-XGVKJREJ.js +2 -0
- package/dist/chunk-XGVKJREJ.js.map +1 -0
- package/dist/chunk-XMGHGIST.js +84 -0
- package/dist/chunk-XMGHGIST.js.map +1 -0
- package/dist/client/plugins.cjs +1 -1
- package/dist/client/plugins.js +1 -1
- package/dist/client.cjs +1 -1
- package/dist/client.js +1 -1
- package/dist/crypto.cjs +1 -1
- package/dist/crypto.cjs.map +1 -1
- package/dist/crypto.js +1 -1
- package/dist/index.cjs +1 -1
- package/dist/index.cjs.map +1 -1
- package/dist/index.js +1 -1
- package/dist/index.js.map +1 -1
- package/dist/plugins.cjs +2 -2
- package/dist/plugins.cjs.map +1 -1
- package/dist/plugins.js +2 -2
- package/dist/plugins.js.map +1 -1
- package/dist/react.cjs +1 -1
- package/dist/react.js +1 -1
- package/dist/solid.cjs +1 -1
- package/dist/solid.js +1 -1
- package/dist/svelte.cjs +1 -1
- package/dist/svelte.js +1 -1
- package/dist/vue.cjs +1 -1
- package/dist/vue.js +1 -1
- package/package.json +1 -1
package/dist/api.cjs
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
"use strict";Object.defineProperty(exports, "__esModule", {value: true});var
|
|
1
|
+
"use strict";Object.defineProperty(exports, "__esModule", {value: true});var _chunkL7UQ5ZRFcjs = require('./chunk-L7UQ5ZRF.cjs');require('./chunk-5CGFZN2L.cjs');require('./chunk-2BBAB6DP.cjs');require('./chunk-4INQICGP.cjs');require('./chunk-U5FXGV3G.cjs');require('./chunk-DMAK6URH.cjs');require('./chunk-6YSOZOBL.cjs');require('./chunk-BF3ZIVEP.cjs');require('./chunk-4CFYZITA.cjs');require('./chunk-LF4SJYGR.cjs');require('./chunk-WNGZ4EQP.cjs');require('./chunk-M4G6J7DP.cjs');exports.APIError = _chunkL7UQ5ZRFcjs.I; exports.callbackOAuth = _chunkL7UQ5ZRFcjs.r; exports.changeEmail = _chunkL7UQ5ZRFcjs.A; exports.changePassword = _chunkL7UQ5ZRFcjs.x; exports.createAuthEndpoint = _chunkL7UQ5ZRFcjs.c; exports.createAuthMiddleware = _chunkL7UQ5ZRFcjs.b; exports.createEmailVerificationToken = _chunkL7UQ5ZRFcjs.l; exports.csrfMiddleware = _chunkL7UQ5ZRFcjs.d; exports.deleteUser = _chunkL7UQ5ZRFcjs.z; exports.error = _chunkL7UQ5ZRFcjs.B; exports.forgetPassword = _chunkL7UQ5ZRFcjs.t; exports.forgetPasswordCallback = _chunkL7UQ5ZRFcjs.u; exports.getEndpoints = _chunkL7UQ5ZRFcjs.G; exports.getSession = _chunkL7UQ5ZRFcjs.f; exports.getSessionFromCtx = _chunkL7UQ5ZRFcjs.g; exports.linkSocialAccount = _chunkL7UQ5ZRFcjs.F; exports.listSessions = _chunkL7UQ5ZRFcjs.i; exports.listUserAccounts = _chunkL7UQ5ZRFcjs.E; exports.ok = _chunkL7UQ5ZRFcjs.C; exports.optionsMiddleware = _chunkL7UQ5ZRFcjs.a; exports.resetPassword = _chunkL7UQ5ZRFcjs.v; exports.revokeSession = _chunkL7UQ5ZRFcjs.j; exports.revokeSessions = _chunkL7UQ5ZRFcjs.k; exports.router = _chunkL7UQ5ZRFcjs.H; exports.sendVerificationEmail = _chunkL7UQ5ZRFcjs.m; exports.sessionMiddleware = _chunkL7UQ5ZRFcjs.h; exports.setPassword = _chunkL7UQ5ZRFcjs.y; exports.signInEmail = _chunkL7UQ5ZRFcjs.p; exports.signInOAuth = _chunkL7UQ5ZRFcjs.o; exports.signOut = _chunkL7UQ5ZRFcjs.s; exports.signUpEmail = _chunkL7UQ5ZRFcjs.D; exports.updateUser = _chunkL7UQ5ZRFcjs.w; exports.verifyEmail = _chunkL7UQ5ZRFcjs.n;
|
|
2
2
|
//# sourceMappingURL=api.cjs.map
|
package/dist/api.cjs.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["/Users/beka/Desktop/Development/better-auth/packages/better-auth/dist/api.cjs"],"names":[],"mappings":"AAAA,
|
|
1
|
+
{"version":3,"sources":["/Users/beka/Desktop/Development/better-auth/packages/better-auth/dist/api.cjs"],"names":[],"mappings":"AAAA,iIAAoP,gCAA6B,gCAA6B,gCAA6B,gCAA6B,gCAA6B,gCAA6B,gCAA6B,gCAA6B,gCAA6B,gCAA6B,gCAA6B,m9CAAkoB","file":"/Users/beka/Desktop/Development/better-auth/packages/better-auth/dist/api.cjs"}
|
package/dist/api.js
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import{A as y,B as z,C as A,D as B,E as C,F as D,G as E,H as F,I as G,
|
|
1
|
+
import{A as y,B as z,C as A,D as B,E as C,F as D,G as E,H as F,I as G,a,b,c,d,f as e,g as f,h as g,i as h,j as i,k as j,l as k,m as l,n as m,o as n,p as o,r as p,s as q,t as r,u as s,v as t,w as u,x as v,y as w,z as x}from"./chunk-SUN5UQMP.js";import"./chunk-57KKPQYR.js";import"./chunk-UMXT2JXJ.js";import"./chunk-L3RMKKWR.js";import"./chunk-4X5O2226.js";import"./chunk-TUL3AUOB.js";import"./chunk-C57CCQKY.js";import"./chunk-N7CDYTQY.js";import"./chunk-AFA2APLD.js";import"./chunk-4CY5SJAH.js";import"./chunk-GNYPEE5I.js";import"./chunk-4C666HHU.js";export{G as APIError,p as callbackOAuth,y as changeEmail,v as changePassword,c as createAuthEndpoint,b as createAuthMiddleware,k as createEmailVerificationToken,d as csrfMiddleware,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,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};
|
|
2
2
|
//# sourceMappingURL=api.js.map
|
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
import{c as n}from"./chunk-LX2KEOYP.js";var m=(e={redirect:!0,twoFactorPage:"/"})=>({id:"two-factor",$InferServerPlugin:{},atomListeners:[{matcher:t=>t.startsWith("/two-factor/"),signal:"_sessionSignal"}],pathMethods:{"/two-factor/disable":"POST","/two-factor/enable":"POST","/two-factor/send-otp":"POST","/two-factor/generate-backup-codes":"POST"},fetchPlugins:[{id:"two-factor",name:"two-factor",hooks:{async onSuccess(t){t.data?.twoFactorRedirect&&(e.redirect||e.twoFactorPage)&&typeof window<"u"&&(window.location.href=e.twoFactorPage)}}}]});import{WebAuthnError as p,startAuthentication as y,startRegistration as u}from"@simplewebauthn/browser";import{atom as l}from"nanostores";var f=(e,{_listPasskeys:t})=>({signIn:{passkey:async(r,i)=>{let a=await e("/passkey/generate-authenticate-options",{method:"POST",body:{email:r?.email}});if(!a.data)return a;try{let s=await y(a.data,r?.autoFill||!1),o=await e("/passkey/verify-authentication",{body:{response:s},...r?.fetchOptions,...i,method:"POST"});if(!o.data)return o}catch(s){console.log(s)}}},passkey:{addPasskey:async(r,i)=>{let a=await e("/passkey/generate-register-options",{method:"GET"});if(!a.data)return a;try{let s=await u(a.data),o=await e("/passkey/verify-registration",{...r?.fetchOptions,...i,body:{response:s,name:r?.name},method:"POST"});if(!o.data)return o;t.set(Math.random())}catch(s){return s instanceof p?s.code==="ERROR_AUTHENTICATOR_PREVIOUSLY_REGISTERED"?{data:null,error:{message:"previously registered",status:400,statusText:"BAD_REQUEST"}}:s.code==="ERROR_CEREMONY_ABORTED"?{data:null,error:{message:"registration cancelled",status:400,statusText:"BAD_REQUEST"}}:{data:null,error:{message:s.message,status:400,statusText:"BAD_REQUEST"}}:{data:null,error:{message:s instanceof Error?s.message:"unknown error",status:500,statusText:"INTERNAL_SERVER_ERROR"}}}}},$Infer:{}}),O=()=>{let e=l();return{id:"passkey",$InferServerPlugin:{},getActions:t=>f(t,{_listPasskeys:e}),getAtoms(t){return{listPasskeys:n(e,"/passkey/list-user-passkeys",t,{method:"GET",credentials:"include"}),_listPasskeys:e}},pathMethods:{"/passkey/register":"POST","/passkey/authenticate":"POST"},atomListeners:[{matcher(t){return t==="/passkey/verify-registration"||t==="/passkey/delete-passkey"},signal:"_listPasskeys"}]}};export{m as a,f as b,O as c};
|
|
2
|
+
//# sourceMappingURL=chunk-22HMFLRO.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../src/plugins/two-factor/client.ts","../src/plugins/passkey/client.ts"],"sourcesContent":["import type { BetterAuthClientPlugin } from \"../../client/types\";\nimport type { twoFactor as twoFa } from \"../../plugins/two-factor\";\n\nexport const twoFactorClient = (\n\toptions: {\n\t\ttwoFactorPage: string;\n\t\t/**\n\t\t * Redirect to the two factor page. If twoFactorPage\n\t\t * is not set this will redirect to the root path.\n\t\t * @default true\n\t\t */\n\t\tredirect?: boolean;\n\t} = {\n\t\tredirect: true,\n\t\ttwoFactorPage: \"/\",\n\t},\n) => {\n\treturn {\n\t\tid: \"two-factor\",\n\t\t$InferServerPlugin: {} as ReturnType<typeof twoFa>,\n\t\tatomListeners: [\n\t\t\t{\n\t\t\t\tmatcher: (path) => path.startsWith(\"/two-factor/\"),\n\t\t\t\tsignal: \"_sessionSignal\",\n\t\t\t},\n\t\t],\n\t\tpathMethods: {\n\t\t\t\"/two-factor/disable\": \"POST\",\n\t\t\t\"/two-factor/enable\": \"POST\",\n\t\t\t\"/two-factor/send-otp\": \"POST\",\n\t\t\t\"/two-factor/generate-backup-codes\": \"POST\",\n\t\t},\n\t\tfetchPlugins: [\n\t\t\t{\n\t\t\t\tid: \"two-factor\",\n\t\t\t\tname: \"two-factor\",\n\t\t\t\thooks: {\n\t\t\t\t\tasync onSuccess(context) {\n\t\t\t\t\t\tif (context.data?.twoFactorRedirect) {\n\t\t\t\t\t\t\tif (options.redirect || options.twoFactorPage) {\n\t\t\t\t\t\t\t\tif (typeof window !== \"undefined\") {\n\t\t\t\t\t\t\t\t\twindow.location.href = options.twoFactorPage;\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t}\n\t\t\t\t\t},\n\t\t\t\t},\n\t\t\t},\n\t\t],\n\t} satisfies BetterAuthClientPlugin;\n};\n","import type { BetterFetch, BetterFetchOption } from \"@better-fetch/fetch\";\nimport {\n\tWebAuthnError,\n\tstartAuthentication,\n\tstartRegistration,\n} from \"@simplewebauthn/browser\";\nimport type {\n\tPublicKeyCredentialCreationOptionsJSON,\n\tPublicKeyCredentialRequestOptionsJSON,\n} from \"@simplewebauthn/types\";\nimport type { Session } from \"inspector\";\nimport type { User } from \"../../db/schema\";\nimport type { passkey as passkeyPl, Passkey } from \"../../plugins\";\nimport type { BetterAuthClientPlugin } from \"../../client/types\";\nimport { useAuthQuery } from \"../../client\";\nimport { atom } from \"nanostores\";\n\nexport const getPasskeyActions = (\n\t$fetch: BetterFetch,\n\t{\n\t\t_listPasskeys,\n\t}: {\n\t\t_listPasskeys: ReturnType<typeof atom<any>>;\n\t},\n) => {\n\tconst signInPasskey = async (\n\t\topts?: {\n\t\t\tautoFill?: boolean;\n\t\t\temail?: string;\n\t\t\tfetchOptions?: BetterFetchOption;\n\t\t},\n\t\toptions?: BetterFetchOption,\n\t) => {\n\t\tconst response = await $fetch<PublicKeyCredentialRequestOptionsJSON>(\n\t\t\t\"/passkey/generate-authenticate-options\",\n\t\t\t{\n\t\t\t\tmethod: \"POST\",\n\t\t\t\tbody: {\n\t\t\t\t\temail: opts?.email,\n\t\t\t\t},\n\t\t\t},\n\t\t);\n\t\tif (!response.data) {\n\t\t\treturn response;\n\t\t}\n\t\ttry {\n\t\t\tconst res = await startAuthentication(\n\t\t\t\tresponse.data,\n\t\t\t\topts?.autoFill || false,\n\t\t\t);\n\t\t\tconst verified = await $fetch<{\n\t\t\t\tsession: Session;\n\t\t\t\tuser: User;\n\t\t\t}>(\"/passkey/verify-authentication\", {\n\t\t\t\tbody: {\n\t\t\t\t\tresponse: res,\n\t\t\t\t},\n\t\t\t\t...opts?.fetchOptions,\n\t\t\t\t...options,\n\t\t\t\tmethod: \"POST\",\n\t\t\t});\n\t\t\tif (!verified.data) {\n\t\t\t\treturn verified;\n\t\t\t}\n\t\t} catch (e) {\n\t\t\tconsole.log(e);\n\t\t}\n\t};\n\n\tconst registerPasskey = async (\n\t\topts?: {\n\t\t\tfetchOptions?: BetterFetchOption;\n\t\t\t/**\n\t\t\t * The name of the passkey. This is used to\n\t\t\t * identify the passkey in the UI.\n\t\t\t */\n\t\t\tname?: string;\n\t\t},\n\t\tfetchOpts?: BetterFetchOption,\n\t) => {\n\t\tconst options = await $fetch<PublicKeyCredentialCreationOptionsJSON>(\n\t\t\t\"/passkey/generate-register-options\",\n\t\t\t{\n\t\t\t\tmethod: \"GET\",\n\t\t\t},\n\t\t);\n\t\tif (!options.data) {\n\t\t\treturn options;\n\t\t}\n\t\ttry {\n\t\t\tconst res = await startRegistration(options.data);\n\t\t\tconst verified = await $fetch<{\n\t\t\t\tpasskey: Passkey;\n\t\t\t}>(\"/passkey/verify-registration\", {\n\t\t\t\t...opts?.fetchOptions,\n\t\t\t\t...fetchOpts,\n\t\t\t\tbody: {\n\t\t\t\t\tresponse: res,\n\t\t\t\t\tname: opts?.name,\n\t\t\t\t},\n\t\t\t\tmethod: \"POST\",\n\t\t\t});\n\t\t\tif (!verified.data) {\n\t\t\t\treturn verified;\n\t\t\t}\n\t\t\t_listPasskeys.set(Math.random());\n\t\t} catch (e) {\n\t\t\tif (e instanceof WebAuthnError) {\n\t\t\t\tif (e.code === \"ERROR_AUTHENTICATOR_PREVIOUSLY_REGISTERED\") {\n\t\t\t\t\treturn {\n\t\t\t\t\t\tdata: null,\n\t\t\t\t\t\terror: {\n\t\t\t\t\t\t\tmessage: \"previously registered\",\n\t\t\t\t\t\t\tstatus: 400,\n\t\t\t\t\t\t\tstatusText: \"BAD_REQUEST\",\n\t\t\t\t\t\t},\n\t\t\t\t\t};\n\t\t\t\t}\n\t\t\t\tif (e.code === \"ERROR_CEREMONY_ABORTED\") {\n\t\t\t\t\treturn {\n\t\t\t\t\t\tdata: null,\n\t\t\t\t\t\terror: {\n\t\t\t\t\t\t\tmessage: \"registration cancelled\",\n\t\t\t\t\t\t\tstatus: 400,\n\t\t\t\t\t\t\tstatusText: \"BAD_REQUEST\",\n\t\t\t\t\t\t},\n\t\t\t\t\t};\n\t\t\t\t}\n\t\t\t\treturn {\n\t\t\t\t\tdata: null,\n\t\t\t\t\terror: {\n\t\t\t\t\t\tmessage: e.message,\n\t\t\t\t\t\tstatus: 400,\n\t\t\t\t\t\tstatusText: \"BAD_REQUEST\",\n\t\t\t\t\t},\n\t\t\t\t};\n\t\t\t}\n\t\t\treturn {\n\t\t\t\tdata: null,\n\t\t\t\terror: {\n\t\t\t\t\tmessage: e instanceof Error ? e.message : \"unknown error\",\n\t\t\t\t\tstatus: 500,\n\t\t\t\t\tstatusText: \"INTERNAL_SERVER_ERROR\",\n\t\t\t\t},\n\t\t\t};\n\t\t}\n\t};\n\n\treturn {\n\t\tsignIn: {\n\t\t\t/**\n\t\t\t * Sign in with a registered passkey\n\t\t\t */\n\t\t\tpasskey: signInPasskey,\n\t\t},\n\t\tpasskey: {\n\t\t\t/**\n\t\t\t * Add a passkey to the user account\n\t\t\t */\n\t\t\taddPasskey: registerPasskey,\n\t\t},\n\t\t/**\n\t\t * Inferred Internal Types\n\t\t */\n\t\t$Infer: {} as {\n\t\t\tPasskey: Passkey;\n\t\t},\n\t};\n};\n\nexport const passkeyClient = () => {\n\tconst _listPasskeys = atom<any>();\n\treturn {\n\t\tid: \"passkey\",\n\t\t$InferServerPlugin: {} as ReturnType<typeof passkeyPl>,\n\t\tgetActions: ($fetch) =>\n\t\t\tgetPasskeyActions($fetch, {\n\t\t\t\t_listPasskeys,\n\t\t\t}),\n\t\tgetAtoms($fetch) {\n\t\t\tconst listPasskeys = useAuthQuery<Passkey[]>(\n\t\t\t\t_listPasskeys,\n\t\t\t\t\"/passkey/list-user-passkeys\",\n\t\t\t\t$fetch,\n\t\t\t\t{\n\t\t\t\t\tmethod: \"GET\",\n\t\t\t\t\tcredentials: \"include\",\n\t\t\t\t},\n\t\t\t);\n\t\t\treturn {\n\t\t\t\tlistPasskeys,\n\t\t\t\t_listPasskeys,\n\t\t\t};\n\t\t},\n\t\tpathMethods: {\n\t\t\t\"/passkey/register\": \"POST\",\n\t\t\t\"/passkey/authenticate\": \"POST\",\n\t\t},\n\t\tatomListeners: [\n\t\t\t{\n\t\t\t\tmatcher(path) {\n\t\t\t\t\treturn (\n\t\t\t\t\t\tpath === \"/passkey/verify-registration\" ||\n\t\t\t\t\t\tpath === \"/passkey/delete-passkey\"\n\t\t\t\t\t);\n\t\t\t\t},\n\t\t\t\tsignal: \"_listPasskeys\",\n\t\t\t},\n\t\t],\n\t} satisfies BetterAuthClientPlugin;\n};\n"],"mappings":"wCAGO,IAAMA,EAAkB,CAC9BC,EAQI,CACH,SAAU,GACV,cAAe,GAChB,KAEO,CACN,GAAI,aACJ,mBAAoB,CAAC,EACrB,cAAe,CACd,CACC,QAAUC,GAASA,EAAK,WAAW,cAAc,EACjD,OAAQ,gBACT,CACD,EACA,YAAa,CACZ,sBAAuB,OACvB,qBAAsB,OACtB,uBAAwB,OACxB,oCAAqC,MACtC,EACA,aAAc,CACb,CACC,GAAI,aACJ,KAAM,aACN,MAAO,CACN,MAAM,UAAUC,EAAS,CACpBA,EAAQ,MAAM,oBACbF,EAAQ,UAAYA,EAAQ,gBAC3B,OAAO,OAAW,MACrB,OAAO,SAAS,KAAOA,EAAQ,cAInC,CACD,CACD,CACD,CACD,GChDD,OACC,iBAAAG,EACA,uBAAAC,EACA,qBAAAC,MACM,0BAUP,OAAS,QAAAC,MAAY,aAEd,IAAMC,EAAoB,CAChCC,EACA,CACC,cAAAC,CACD,KA+HO,CACN,OAAQ,CAIP,QAhIoB,MACrBC,EAKAC,IACI,CACJ,IAAMC,EAAW,MAAMJ,EACtB,yCACA,CACC,OAAQ,OACR,KAAM,CACL,MAAOE,GAAM,KACd,CACD,CACD,EACA,GAAI,CAACE,EAAS,KACb,OAAOA,EAER,GAAI,CACH,IAAMC,EAAM,MAAMC,EACjBF,EAAS,KACTF,GAAM,UAAY,EACnB,EACMK,EAAW,MAAMP,EAGpB,iCAAkC,CACpC,KAAM,CACL,SAAUK,CACX,EACA,GAAGH,GAAM,aACT,GAAGC,EACH,OAAQ,MACT,CAAC,EACD,GAAI,CAACI,EAAS,KACb,OAAOA,CAET,OAASC,EAAG,CACX,QAAQ,IAAIA,CAAC,CACd,CACD,CAuFC,EACA,QAAS,CAIR,WA1FsB,MACvBN,EAQAO,IACI,CACJ,IAAMN,EAAU,MAAMH,EACrB,qCACA,CACC,OAAQ,KACT,CACD,EACA,GAAI,CAACG,EAAQ,KACZ,OAAOA,EAER,GAAI,CACH,IAAME,EAAM,MAAMK,EAAkBP,EAAQ,IAAI,EAC1CI,EAAW,MAAMP,EAEpB,+BAAgC,CAClC,GAAGE,GAAM,aACT,GAAGO,EACH,KAAM,CACL,SAAUJ,EACV,KAAMH,GAAM,IACb,EACA,OAAQ,MACT,CAAC,EACD,GAAI,CAACK,EAAS,KACb,OAAOA,EAERN,EAAc,IAAI,KAAK,OAAO,CAAC,CAChC,OAASO,EAAG,CACX,OAAIA,aAAaG,EACZH,EAAE,OAAS,4CACP,CACN,KAAM,KACN,MAAO,CACN,QAAS,wBACT,OAAQ,IACR,WAAY,aACb,CACD,EAEGA,EAAE,OAAS,yBACP,CACN,KAAM,KACN,MAAO,CACN,QAAS,yBACT,OAAQ,IACR,WAAY,aACb,CACD,EAEM,CACN,KAAM,KACN,MAAO,CACN,QAASA,EAAE,QACX,OAAQ,IACR,WAAY,aACb,CACD,EAEM,CACN,KAAM,KACN,MAAO,CACN,QAASA,aAAa,MAAQA,EAAE,QAAU,gBAC1C,OAAQ,IACR,WAAY,uBACb,CACD,CACD,CACD,CAcC,EAIA,OAAQ,CAAC,CAGV,GAGYI,EAAgB,IAAM,CAClC,IAAMX,EAAgBH,EAAU,EAChC,MAAO,CACN,GAAI,UACJ,mBAAoB,CAAC,EACrB,WAAaE,GACZD,EAAkBC,EAAQ,CACzB,cAAAC,CACD,CAAC,EACF,SAASD,EAAQ,CAUhB,MAAO,CACN,aAVoBa,EACpBZ,EACA,8BACAD,EACA,CACC,OAAQ,MACR,YAAa,SACd,CACD,EAGC,cAAAC,CACD,CACD,EACA,YAAa,CACZ,oBAAqB,OACrB,wBAAyB,MAC1B,EACA,cAAe,CACd,CACC,QAAQa,EAAM,CACb,OACCA,IAAS,gCACTA,IAAS,yBAEX,EACA,OAAQ,eACT,CACD,CACD,CACD","names":["twoFactorClient","options","path","context","WebAuthnError","startAuthentication","startRegistration","atom","getPasskeyActions","$fetch","_listPasskeys","opts","options","response","res","startAuthentication","verified","e","fetchOpts","startRegistration","WebAuthnError","passkeyClient","useAuthQuery","path"]}
|
|
@@ -0,0 +1,84 @@
|
|
|
1
|
+
"use strict";Object.defineProperty(exports, "__esModule", {value: true}); function _nullishCoalesce(lhs, rhsFn) { if (lhs != null) { return lhs; } else { return rhsFn(); } } 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; } async function _asyncOptionalChain(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 = await fn(value); } else if (op === 'call' || op === 'optionalCall') { value = await fn((...args) => value.call(lastAccessLHS, ...args)); lastAccessLHS = undefined; } } return value; }var _chunk5CGFZN2Lcjs = require('./chunk-5CGFZN2L.cjs');var _chunk2BBAB6DPcjs = require('./chunk-2BBAB6DP.cjs');var _chunk4INQICGPcjs = require('./chunk-4INQICGP.cjs');var _chunkU5FXGV3Gcjs = require('./chunk-U5FXGV3G.cjs');var _chunkDMAK6URHcjs = require('./chunk-DMAK6URH.cjs');var _chunkOQSWDMGGcjs = require('./chunk-OQSWDMGG.cjs');var _chunkLF4SJYGRcjs = require('./chunk-LF4SJYGR.cjs');var _bettercall = require('better-call');var _zod = require('zod');var ne=_bettercall.createMiddleware.call(void 0, async()=>({})),B= exports.b =_bettercall.createMiddlewareCreator.call(void 0, {use:[ne,_bettercall.createMiddleware.call(void 0, async()=>({}))]}),p= exports.c =_bettercall.createEndpointCreator.call(void 0, {use:[ne]});var ae=B({body:_zod.z.object({csrfToken:_zod.z.string().optional()}).optional()},async e=>{if(_optionalChain([e, 'access', _2 => _2.request, 'optionalAccess', _3 => _3.method])!=="POST"||_optionalChain([e, 'access', _4 => _4.context, 'access', _5 => _5.options, 'access', _6 => _6.advanced, 'optionalAccess', _7 => _7.disableCSRFCheck]))return;let t=_optionalChain([e, 'access', _8 => _8.headers, 'optionalAccess', _9 => _9.get, 'call', _10 => _10("origin")])||"";if(t){let d=new URL(t).origin;if(e.context.trustedOrigins.includes(d))return}let o=_optionalChain([e, 'access', _11 => _11.body, 'optionalAccess', _12 => _12.csrfToken]);if(!o)throw new (0, _bettercall.APIError)("UNAUTHORIZED",{message:"CSRF Token is required"});let s=await e.getSignedCookie(e.context.authCookies.csrfToken.name,e.context.secret),[r,n]=_optionalChain([s, 'optionalAccess', _13 => _13.split, 'call', _14 => _14("!")])||[null,null];if(!o||!r||!n||r!==o)throw new (0, _bettercall.APIError)("UNAUTHORIZED",{message:"Invalid CSRF Token"});let i=await _chunkOQSWDMGGcjs.j.call(void 0, e.context.secret,r);if(n!==i)throw e.setCookie(e.context.authCookies.csrfToken.name,"",{maxAge:0}),new (0, _bettercall.APIError)("UNAUTHORIZED",{message:"Invalid CSRF Token"})});var _oauth2 = require('oslo/oauth2');var b=B(async e=>{let{body:t,query:o,context:s}=e,r=_optionalChain([t, 'optionalAccess', _15 => _15.callbackURL])||_optionalChain([o, 'optionalAccess', _16 => _16.callbackURL])||_optionalChain([o, 'optionalAccess', _17 => _17.redirectTo])||_optionalChain([t, 'optionalAccess', _18 => _18.redirectTo]),n=_optionalChain([o, 'optionalAccess', _19 => _19.currentURL]),i=s.trustedOrigins,d=(c,a)=>{if(_optionalChain([c, 'optionalAccess', _20 => _20.startsWith, 'call', _21 => _21("http")])&&!i.some(w=>c.startsWith(w)))throw _chunk4INQICGPcjs.b.error(`Invalid ${a}: ${c}`),_chunk4INQICGPcjs.b.info(`If it's a valid URL, please add ${c} to trustedOrigins in your auth config
|
|
2
|
+
`,`Current list of trustedOrigins: ${i}`),new (0, _bettercall.APIError)("FORBIDDEN",{message:`Invalid ${a}`})};d(r,"callbackURL"),d(n,"currentURL")});var _oslo = require('oslo');var _jwt = require('oslo/jwt');var Y=()=>p("/get-session",{method:"GET",query:_zod.z.optional(_zod.z.object({disableCookieCache:_zod.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 o=await e.getSignedCookie(e.context.authCookies.sessionData.name,e.context.secret),s=await e.getSignedCookie(e.context.authCookies.dontRememberToken.name,e.context.secret);if(o&&_optionalChain([e, 'access', _22 => _22.context, 'access', _23 => _23.options, 'access', _24 => _24.session, 'optionalAccess', _25 => _25.cookieCache, 'optionalAccess', _26 => _26.enabled])&&!_optionalChain([e, 'access', _27 => _27.query, 'optionalAccess', _28 => _28.disableCookieCache])){let a=_optionalChain([JSON, 'access', _29 => _29.parse, 'call', _30 => _30(o), 'optionalAccess', _31 => _31.session]);if(_optionalChain([a, 'optionalAccess', _32 => _32.expiresAt])>new Date)return e.json(a)}let r=await e.context.internalAdapter.findSession(t);if(!r||r.session.expiresAt<new Date)return _chunkLF4SJYGRcjs.d.call(void 0, e),r&&await e.context.internalAdapter.deleteSession(r.session.id),e.json(null,{status:401});if(s)return e.json(r);let n=e.context.sessionConfig.expiresIn,i=e.context.sessionConfig.updateAge;if(r.session.expiresAt.valueOf()-n*1e3+i*1e3<=Date.now()){let a=await e.context.internalAdapter.updateSession(r.session.id,{expiresAt:_chunkDMAK6URHcjs.a.call(void 0, e.context.sessionConfig.expiresIn,"sec")});if(!a)return _chunkLF4SJYGRcjs.d.call(void 0, e),e.json(null,{status:401});let l=(a.expiresAt.valueOf()-Date.now())/1e3;return await _chunkLF4SJYGRcjs.c.call(void 0, e,{session:a,user:r.user},!1,{maxAge:l}),e.json({session:a,user:r.user})}return e.json(r)}catch(t){return e.context.logger.error(t),e.json(null,{status:500})}}),K= exports.g =async e=>await Y()({...e,_flag:"json",headers:e.headers}),E= exports.h =B(async e=>{let t=await K(e);if(!_optionalChain([t, 'optionalAccess', _33 => _33.session]))throw new (0, _bettercall.APIError)("UNAUTHORIZED");return{session:t}}),de= exports.i =()=>p("/user/list-sessions",{method:"GET",use:[E],requireHeaders:!0},async e=>{let o=(await e.context.internalAdapter.listSessions(e.context.session.user.id)).filter(s=>s.expiresAt>new Date);return e.json(o)}),ce= exports.j =p("/user/revoke-session",{method:"POST",body:_zod.z.object({id:_zod.z.string()}),use:[E],requireHeaders:!0},async e=>{let t=e.body.id,o=await e.context.internalAdapter.findSession(t);if(!o)throw new (0, _bettercall.APIError)("BAD_REQUEST",{message:"Session not found"});if(o.session.userId!==e.context.session.user.id)throw new (0, _bettercall.APIError)("UNAUTHORIZED");try{await e.context.internalAdapter.deleteSession(t)}catch(s){throw e.context.logger.error(s),new (0, _bettercall.APIError)("INTERNAL_SERVER_ERROR")}return e.json({status:!0})}),le= exports.k =p("/user/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 (0, _bettercall.APIError)("INTERNAL_SERVER_ERROR")}return e.json({status:!0})});async function v(e,t,o){return await _jwt.createJWT.call(void 0, "HS256",Buffer.from(e),{email:t.toLowerCase(),updateTo:o},{expiresIn:new (0, _oslo.TimeSpan)(1,"h"),issuer:"better-auth",subject:"verify-email",audiences:[t],includeIssuedTimestamp:!0})}var ue=p("/send-verification-email",{method:"POST",query:_zod.z.object({currentURL:_zod.z.string().optional()}).optional(),body:_zod.z.object({email:_zod.z.string().email(),callbackURL:_zod.z.string().optional()}),use:[b]},async e=>{if(!_optionalChain([e, 'access', _34 => _34.context, 'access', _35 => _35.options, 'access', _36 => _36.emailVerification, 'optionalAccess', _37 => _37.sendVerificationEmail]))throw e.context.logger.error("Verification email isn't enabled."),new (0, _bettercall.APIError)("BAD_REQUEST",{message:"Verification email isn't enabled"});let{email:t}=e.body,o=await e.context.internalAdapter.findUserByEmail(t);if(!o)throw new (0, _bettercall.APIError)("BAD_REQUEST",{message:"User not found"});let s=await v(e.context.secret,t),r=`${e.context.baseURL}/verify-email?token=${s}&callbackURL=${e.body.callbackURL||_optionalChain([e, 'access', _38 => _38.query, 'optionalAccess', _39 => _39.currentURL])||"/"}`;return await e.context.options.emailVerification.sendVerificationEmail(o.user,r,s),e.json({status:!0})}),pe= exports.n =p("/verify-email",{method:"GET",query:_zod.z.object({token:_zod.z.string(),callbackURL:_zod.z.string().optional()}),use:[b]},async e=>{let{token:t}=e.query,o;try{o=await _jwt.validateJWT.call(void 0, "HS256",Buffer.from(e.context.secret),t)}catch(i){throw e.context.logger.error("Failed to verify email",i),new (0, _bettercall.APIError)("BAD_REQUEST",{message:"Invalid token"})}let r=_zod.z.object({email:_zod.z.string().email(),updateTo:_zod.z.string().optional()}).parse(o.payload);if(!await e.context.internalAdapter.findUserByEmail(r.email))throw new (0, _bettercall.APIError)("BAD_REQUEST",{message:"User not found"});if(r.updateTo){let i=await K(e);if(!i)throw e.query.callbackURL?e.redirect(`${e.query.callbackURL}?error=unauthorized`):new (0, _bettercall.APIError)("UNAUTHORIZED",{message:"Session not found"});if(i.user.email!==r.email)throw e.query.callbackURL?e.redirect(`${e.query.callbackURL}?error=unauthorized`):new (0, _bettercall.APIError)("UNAUTHORIZED",{message:"Invalid session"});let d=await e.context.internalAdapter.updateUserByEmail(r.email,{email:r.updateTo});if(await _optionalChain([e, 'access', _40 => _40.context, 'access', _41 => _41.options, 'access', _42 => _42.emailVerification, 'optionalAccess', _43 => _43.sendVerificationEmail, 'optionalCall', _44 => _44(d,`${e.context.baseURL}/verify-email?token=${t}`,t)]),e.query.callbackURL)throw e.redirect(e.query.callbackURL);return e.json({user:d,status:!0})}if(await e.context.internalAdapter.updateUserByEmail(r.email,{emailVerified:!0}),e.query.callbackURL)throw e.redirect(e.query.callbackURL);return e.json({user:null,status:!0})});var me=p("/sign-in/social",{method:"POST",requireHeaders:!0,query:_zod.z.object({currentURL:_zod.z.string().optional()}).optional(),body:_zod.z.object({callbackURL:_zod.z.string().optional(),provider:_zod.z.enum(_chunk2BBAB6DPcjs.n)}),use:[b]},async e=>{let t=e.context.socialProviders.find(c=>c.id===e.body.provider);if(!t)throw e.context.logger.error("Provider not found. Make sure to add the provider in your auth config",{provider:e.body.provider}),new (0, _bettercall.APIError)("NOT_FOUND",{message:"Provider not found"});let o=e.context.authCookies,s=_optionalChain([e, 'access', _45 => _45.query, 'optionalAccess', _46 => _46.currentURL])?new URL(_optionalChain([e, 'access', _47 => _47.query, 'optionalAccess', _48 => _48.currentURL])):null,r=_optionalChain([e, 'access', _49 => _49.body, 'access', _50 => _50.callbackURL, 'optionalAccess', _51 => _51.startsWith, 'call', _52 => _52("http")])?e.body.callbackURL:`${_optionalChain([s, 'optionalAccess', _53 => _53.origin])}${e.body.callbackURL||""}`,n=await _chunkU5FXGV3Gcjs.b.call(void 0, r||_optionalChain([s, 'optionalAccess', _54 => _54.origin])||e.context.options.baseURL);await e.setSignedCookie(o.state.name,n.hash,e.context.secret,o.state.options);let i=_oauth2.generateCodeVerifier.call(void 0, );await e.setSignedCookie(o.pkCodeVerifier.name,i,e.context.secret,o.pkCodeVerifier.options);let d=await t.createAuthorizationURL({state:n.raw,codeVerifier:i,redirectURI:`${e.context.baseURL}/callback/${t.id}`});return e.json({url:d.toString(),state:n,codeVerifier:i,redirect:!0})}),fe= exports.p =p("/sign-in/email",{method:"POST",body:_zod.z.object({email:_zod.z.string(),password:_zod.z.string(),callbackURL:_zod.z.string().optional(),dontRememberMe:_zod.z.boolean().default(!1).optional()}),use:[b]},async e=>{if(!_optionalChain([e, 'access', _55 => _55.context, 'access', _56 => _56.options, 'optionalAccess', _57 => _57.emailAndPassword, 'optionalAccess', _58 => _58.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 (0, _bettercall.APIError)("BAD_REQUEST",{message:"Email and password is not enabled"});let{email:t,password:o}=e.body;if(!_zod.z.string().email().safeParse(t).success)throw new (0, _bettercall.APIError)("BAD_REQUEST",{message:"Invalid email"});if(!_zod.z.string().email().safeParse(t).success)throw new (0, _bettercall.APIError)("BAD_REQUEST",{message:"Invalid email"});let n=await e.context.internalAdapter.findUserByEmail(t,{includeAccounts:!0});if(!n)throw await e.context.password.hash(o),e.context.logger.error("User not found",{email:t}),new (0, _bettercall.APIError)("UNAUTHORIZED",{message:"Invalid email or password"});let i=n.accounts.find(l=>l.providerId==="credential");if(!i)throw e.context.logger.error("Credential account not found",{email:t}),new (0, _bettercall.APIError)("UNAUTHORIZED",{message:"Invalid email or password"});let d=_optionalChain([i, 'optionalAccess', _59 => _59.password]);if(!d)throw e.context.logger.error("Password not found",{email:t}),new (0, _bettercall.APIError)("UNAUTHORIZED",{message:"Unexpected error"});if(!await e.context.password.verify(d,o))throw e.context.logger.error("Invalid password"),new (0, _bettercall.APIError)("UNAUTHORIZED",{message:"Invalid email or password"});if(_optionalChain([e, 'access', _60 => _60.context, 'access', _61 => _61.options, 'optionalAccess', _62 => _62.emailAndPassword, 'optionalAccess', _63 => _63.requireEmailVerification])&&!n.user.emailVerified){if(!_optionalChain([e, 'access', _64 => _64.context, 'access', _65 => _65.options, 'optionalAccess', _66 => _66.emailVerification, 'optionalAccess', _67 => _67.sendVerificationEmail]))throw _chunk4INQICGPcjs.b.error("Email verification is required but no email verification handler is provided"),new (0, _bettercall.APIError)("INTERNAL_SERVER_ERROR",{message:"Email is not verified."});let l=await v(e.context.secret,n.user.email),w=`${e.context.options.baseURL}/verify-email?token=${l}`;throw await e.context.options.emailVerification.sendVerificationEmail(n.user,w,l),e.context.logger.error("Email not verified",{email:t}),new (0, _bettercall.APIError)("FORBIDDEN",{message:"Email is not verified. Check your email for a verification link"})}let a=await e.context.internalAdapter.createSession(n.user.id,e.headers,e.body.dontRememberMe);if(!a)throw e.context.logger.error("Failed to create session"),new (0, _bettercall.APIError)("UNAUTHORIZED",{message:"Failed to create session"});return await _chunkLF4SJYGRcjs.c.call(void 0, e,{session:a,user:n.user},e.body.dontRememberMe),e.json({user:n.user,session:a,redirect:!!e.body.callbackURL,url:e.body.callbackURL})});var Zt=_zod.z.object({id:_zod.z.string(),providerId:_zod.z.string(),accountId:_zod.z.string(),userId:_zod.z.string(),accessToken:_zod.z.string().nullable().optional(),refreshToken:_zod.z.string().nullable().optional(),idToken:_zod.z.string().nullable().optional(),expiresAt:_zod.z.date().nullable().optional(),password:_zod.z.string().optional().nullable()}),we= exports.q =_zod.z.object({id:_zod.z.string(),email:_zod.z.string().transform(e=>e.toLowerCase()),emailVerified:_zod.z.boolean().default(!1),name:_zod.z.string(),image:_zod.z.string().optional(),createdAt:_zod.z.date().default(new Date),updatedAt:_zod.z.date().default(new Date)}),Ht=_zod.z.object({id:_zod.z.string(),userId:_zod.z.string(),expiresAt:_zod.z.date(),ipAddress:_zod.z.string().optional(),userAgent:_zod.z.string().optional()}),zt=_zod.z.object({id:_zod.z.string(),value:_zod.z.string(),expiresAt:_zod.z.date(),identifier:_zod.z.string()});function Qe(e,t){let o={...t==="user"?_optionalChain([e, 'access', _68 => _68.user, 'optionalAccess', _69 => _69.additionalFields]):{},...t==="session"?_optionalChain([e, 'access', _70 => _70.session, 'optionalAccess', _71 => _71.additionalFields]):{}};for(let s of e.plugins||[])s.schema&&s.schema[t]&&(o={...o,...s.schema[t].fields});return o}function Ze(e,t){let o=t.action||"create",s=t.fields,r={};for(let n in s){if(n in e){if(s[n].input===!1){if(s[n].defaultValue){r[n]=s[n].defaultValue;continue}continue}r[n]=e[n];continue}if(s[n].defaultValue&&o==="create"){r[n]=s[n].defaultValue;continue}}return r}function H(e,t,o){let s=Qe(e,"user");return Ze(t||{},{fields:s,action:o})}var _stdenv = require('std-env');var ge=p("/callback/:id",{method:"GET",query:_zod.z.object({state:_zod.z.string(),code:_zod.z.string().optional(),error:_zod.z.string().optional()}),metadata:_chunk2BBAB6DPcjs.h},async e=>{if(e.query.error||!e.query.code){let T=_optionalChain([_chunkU5FXGV3Gcjs.c.call(void 0, e.query.state), 'access', _72 => _72.data, 'optionalAccess', _73 => _73.callbackURL])||`${e.context.baseURL}/error`;throw e.context.logger.error(e.query.error,e.params.id),e.redirect(`${T}?error=${e.query.error||"oAuth_code_missing"}`)}let t=e.context.socialProviders.find(f=>f.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 o=_chunkU5FXGV3Gcjs.c.call(void 0, e.query.state);if(!o.success)throw e.context.logger.error("Unable to parse state"),e.redirect(`${e.context.baseURL}/error?error=please_restart_the_process`);let{data:{callbackURL:s,currentURL:r,link:n}}=o,i=await e.getSignedCookie(e.context.authCookies.state.name,e.context.secret);if(!i)throw _chunk4INQICGPcjs.b.error("No stored state found"),e.redirect(`${e.context.baseURL}/error?error=please_restart_the_process`);if(!await _chunkU5FXGV3Gcjs.a.call(void 0, e.query.state,i))throw _chunk4INQICGPcjs.b.error("OAuth state mismatch"),e.redirect(`${e.context.baseURL}/error?error=please_restart_the_process`);let c=await e.getSignedCookie(e.context.authCookies.pkCodeVerifier.name,e.context.secret),a;try{a=await t.validateAuthorizationCode({code:e.query.code,codeVerifier:c,redirectURI:`${e.context.baseURL}/callback/${t.id}`})}catch(f){throw e.context.logger.error(f),e.redirect(`${e.context.baseURL}/error?error=please_restart_the_process`)}let l=await t.getUserInfo(a).then(f=>_optionalChain([f, 'optionalAccess', _74 => _74.user])),w=_chunk4INQICGPcjs.c.call(void 0, ),y=we.safeParse({...l,id:w});if(!l||y.success===!1)throw _chunk4INQICGPcjs.b.error("Unable to get user info",y.error),e.redirect(`${e.context.baseURL}/error?error=please_restart_the_process`);if(!s)throw _chunk4INQICGPcjs.b.error("No callback URL found"),e.redirect(`${e.context.baseURL}/error?error=please_restart_the_process`);if(n){if(n.email!==l.email.toLowerCase())return u("email_doesn't_match");if(!await e.context.internalAdapter.createAccount({userId:n.userId,providerId:t.id,accountId:l.id}))return u("unable_to_link_account");throw e.redirect(s||r||e.context.options.baseURL)}function u(f){throw e.redirect(`${r||s||`${e.context.baseURL}/error`}?error=${f}`)}let R=await e.context.internalAdapter.findUserByEmail(l.email,{includeAccounts:!0}).catch(f=>{throw _chunk4INQICGPcjs.b.error(`Better auth was unable to query your database.
|
|
3
|
+
Error: `,f),e.redirect(`${e.context.baseURL}/error?error=internal_server_error`)}),A=_optionalChain([R, 'optionalAccess', _75 => _75.user]);if(R){let f=R.accounts.find(T=>T.providerId===t.id);if(f)await e.context.internalAdapter.updateAccount(f.id,{accessToken:a.accessToken,idToken:a.idToken,refreshToken:a.refreshToken,expiresAt:a.accessTokenExpiresAt});else{(!_optionalChain([e, 'access', _76 => _76.context, 'access', _77 => _77.options, 'access', _78 => _78.account, 'optionalAccess', _79 => _79.accountLinking, 'optionalAccess', _80 => _80.trustedProviders, 'optionalAccess', _81 => _81.includes, 'call', _82 => _82(t.id)])&&!l.emailVerified||!_optionalChain([e, 'access', _83 => _83.context, 'access', _84 => _84.options, 'access', _85 => _85.account, 'optionalAccess', _86 => _86.accountLinking, 'optionalAccess', _87 => _87.enabled]))&&(_stdenv.isDevelopment&&_chunk4INQICGPcjs.b.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.`),u("account_not_linked"));try{await e.context.internalAdapter.linkAccount({providerId:t.id,accountId:l.id.toString(),id:`${t.id}:${l.id}`,userId:R.user.id,accessToken:a.accessToken,idToken:a.idToken,refreshToken:a.refreshToken,expiresAt:a.accessTokenExpiresAt})}catch(Be){_chunk4INQICGPcjs.b.error("Unable to link account",Be),u("unable_to_link_account")}}}else try{let f=l.emailVerified||!1;if(A=await e.context.internalAdapter.createOAuthUser({...y.data,emailVerified:f},{accessToken:a.accessToken,idToken:a.idToken,refreshToken:a.refreshToken,expiresAt:a.accessTokenExpiresAt,providerId:t.id,accountId:l.id.toString()}).then(T=>_optionalChain([T, 'optionalAccess', _88 => _88.user])),!f&&A&&_optionalChain([e, 'access', _89 => _89.context, 'access', _90 => _90.options, 'access', _91 => _91.emailVerification, 'optionalAccess', _92 => _92.sendOnSignUp])){let T=await v(e.context.secret,A.email),D=`${e.context.baseURL}/verify-email?token=${T}&callbackURL=${s}`;await _optionalChain([e, 'access', _93 => _93.context, 'access', _94 => _94.options, 'access', _95 => _95.emailVerification, 'optionalAccess', _96 => _96.sendVerificationEmail, 'optionalCall', _97 => _97(A,D,T)])}}catch(f){_chunk4INQICGPcjs.b.error("Unable to create user",f),u("unable_to_create_user")}if(!A)return u("unable_to_create_user");let g=await e.context.internalAdapter.createSession(A.id,e.request);throw g||u("unable_to_create_session"),await _chunkLF4SJYGRcjs.c.call(void 0, e,{session:g,user:A}),e.redirect(s)});var he=p("/sign-out",{method:"POST"},async e=>{let t=await e.getSignedCookie(e.context.authCookies.sessionToken.name,e.context.secret);if(!t)throw new (0, _bettercall.APIError)("BAD_REQUEST",{message:"Session not found"});return await e.context.internalAdapter.deleteSession(t),_chunkLF4SJYGRcjs.d.call(void 0, e),e.json({success:!0})});var ye=p("/forget-password",{method:"POST",body:_zod.z.object({email:_zod.z.string().email(),redirectTo:_zod.z.string()}),use:[b]},async e=>{if(!_optionalChain([e, 'access', _98 => _98.context, 'access', _99 => _99.options, 'access', _100 => _100.emailAndPassword, 'optionalAccess', _101 => _101.sendResetPassword]))throw e.context.logger.error("Reset password isn't enabled.Please pass an emailAndPassword.sendResetPasswordToken function in your auth config!"),new (0, _bettercall.APIError)("BAD_REQUEST",{message:"Reset password isn't enabled"});let{email:t,redirectTo:o}=e.body,s=await e.context.internalAdapter.findUserByEmail(t,{includeAccounts:!0});if(!s)return e.context.logger.error("Reset Password: User not found",{email:t}),e.json({status:!1},{body:{status:!0}});let r=60*60*1,n=new Date(Date.now()+1e3*(e.context.options.emailAndPassword.resetPasswordTokenExpiresIn||r)),i=e.context.uuid();await e.context.internalAdapter.createVerificationValue({value:s.user.id,identifier:`reset-password:${i}`,expiresAt:n});let d=`${e.context.baseURL}/reset-password/${i}?callbackURL=${o}`;return await e.context.options.emailAndPassword.sendResetPassword(s.user,d),e.json({status:!0})}),Re= exports.u =p("/reset-password/:token",{method:"GET",query:_zod.z.object({callbackURL:_zod.z.string()}),use:[b]},async e=>{let{token:t}=e.params,o=e.query.callbackURL,s=o.startsWith("http")?o:`${e.context.options.baseURL}${o}`;if(!t||!o)throw e.redirect(`${e.context.baseURL}/error?error=INVALID_TOKEN`);let r=await e.context.internalAdapter.findVerificationValue(`reset-password:${t}`);throw!r||r.expiresAt<new Date?e.redirect(`${s}?error=INVALID_TOKEN`):e.redirect(`${s}${s.includes("?")?"&":"?"}token=${t}`)}),Ae= exports.v =p("/reset-password",{query:_zod.z.optional(_zod.z.object({token:_zod.z.string().optional(),currentURL:_zod.z.string().optional()})),method:"POST",body:_zod.z.object({newPassword:_zod.z.string()})},async e=>{let t=_optionalChain([e, 'access', _102 => _102.query, 'optionalAccess', _103 => _103.token])||(_optionalChain([e, 'access', _104 => _104.query, 'optionalAccess', _105 => _105.currentURL])?new URL(e.query.currentURL).searchParams.get("token"):"");if(!t)throw new (0, _bettercall.APIError)("BAD_REQUEST",{message:"Token not found"});let{newPassword:o}=e.body,s=`reset-password:${t}`,r=await e.context.internalAdapter.findVerificationValue(s);if(!r||r.expiresAt<new Date)throw new (0, _bettercall.APIError)("BAD_REQUEST",{message:"Invalid token"});await e.context.internalAdapter.deleteVerificationValue(r.id);let n=r.value,i=await e.context.password.hash(o);if(!(await e.context.internalAdapter.findAccounts(n)).find(l=>l.providerId==="credential"))return await e.context.internalAdapter.createAccount({userId:n,providerId:"credential",password:i,accountId:e.context.uuid()}),e.json({status:!0});if(!await e.context.internalAdapter.updatePassword(n,i))throw new (0, _bettercall.APIError)("BAD_REQUEST",{message:"Failed to update password"});return e.json({status:!0})});var be=()=>p("/user/update",{method:"POST",body:_zod.z.record(_zod.z.string(),_zod.z.any()),use:[E,b]},async e=>{let t=e.body;if(t.email)throw new (0, _bettercall.APIError)("BAD_REQUEST",{message:"You can't update email"});let{name:o,image:s,...r}=t,n=e.context.session;if(!s&&!o&&Object.keys(r).length===0)return e.json({user:n.user});let i=H(e.context.options,r,"update"),d=await e.context.internalAdapter.updateUserByEmail(n.user.email,{name:o,image:s,...i});return await _chunkLF4SJYGRcjs.c.call(void 0, e,{session:n.session,user:d}),e.json({user:d})}),ke= exports.x =p("/user/change-password",{method:"POST",body:_zod.z.object({newPassword:_zod.z.string(),currentPassword:_zod.z.string(),revokeOtherSessions:_zod.z.boolean().optional()}),use:[E]},async e=>{let{newPassword:t,currentPassword:o,revokeOtherSessions:s}=e.body,r=e.context.session,n=e.context.password.config.minPasswordLength;if(t.length<n)throw e.context.logger.error("Password is too short"),new (0, _bettercall.APIError)("BAD_REQUEST",{message:"Password is too short"});let i=e.context.password.config.maxPasswordLength;if(t.length>i)throw e.context.logger.error("Password is too long"),new (0, _bettercall.APIError)("BAD_REQUEST",{message:"Password too long"});let c=(await e.context.internalAdapter.findAccounts(r.user.id)).find(w=>w.providerId==="credential"&&w.password);if(!c||!c.password)throw new (0, _bettercall.APIError)("BAD_REQUEST",{message:"User does not have a password"});let a=await e.context.password.hash(t);if(!await e.context.password.verify(c.password,o))throw new (0, _bettercall.APIError)("BAD_REQUEST",{message:"Incorrect password"});if(await e.context.internalAdapter.updateAccount(c.id,{password:a}),s){await e.context.internalAdapter.deleteSessions(r.user.id);let w=await e.context.internalAdapter.createSession(r.user.id,e.headers);if(!w)throw new (0, _bettercall.APIError)("INTERNAL_SERVER_ERROR",{message:"Unable to create session"});await _chunkLF4SJYGRcjs.c.call(void 0, e,{session:w,user:r.user})}return e.json(r.user)}),Ue= exports.y =p("/user/set-password",{method:"POST",body:_zod.z.object({newPassword:_zod.z.string()}),metadata:{SERVER_ONLY:!0},use:[E]},async e=>{let{newPassword:t}=e.body,o=e.context.session,s=e.context.password.config.minPasswordLength;if(t.length<s)throw e.context.logger.error("Password is too short"),new (0, _bettercall.APIError)("BAD_REQUEST",{message:"Password is too short"});let r=e.context.password.config.maxPasswordLength;if(t.length>r)throw e.context.logger.error("Password is too long"),new (0, _bettercall.APIError)("BAD_REQUEST",{message:"Password too long"});let i=(await e.context.internalAdapter.findAccounts(o.user.id)).find(c=>c.providerId==="credential"&&c.password),d=await e.context.password.hash(t);if(!i)return await e.context.internalAdapter.linkAccount({userId:o.user.id,providerId:"credential",accountId:o.user.id,password:d}),e.json(o.user);throw new (0, _bettercall.APIError)("BAD_REQUEST",{message:"user already has a password"})}),Ee= exports.z =p("/user/delete",{method:"POST",body:_zod.z.object({password:_zod.z.string()}),use:[E]},async e=>{let{password:t}=e.body,o=e.context.session,r=(await e.context.internalAdapter.findAccounts(o.user.id)).find(i=>i.providerId==="credential"&&i.password);if(!r||!r.password)throw new (0, _bettercall.APIError)("BAD_REQUEST",{message:"User does not have a password"});if(!await e.context.password.verify(r.password,t))throw new (0, _bettercall.APIError)("BAD_REQUEST",{message:"Incorrect password"});return await e.context.internalAdapter.deleteUser(o.user.id),await e.context.internalAdapter.deleteSessions(o.user.id),_chunkLF4SJYGRcjs.d.call(void 0, e),e.json(null)}),Se= exports.A =p("/user/change-email",{method:"POST",query:_zod.z.object({currentURL:_zod.z.string().optional()}).optional(),body:_zod.z.object({newEmail:_zod.z.string().email(),callbackURL:_zod.z.string().optional()}),use:[E,b]},async e=>{if(!_optionalChain([e, 'access', _106 => _106.context, 'access', _107 => _107.options, 'access', _108 => _108.user, 'optionalAccess', _109 => _109.changeEmail, 'optionalAccess', _110 => _110.enabled]))throw e.context.logger.error("Change email is disabled."),new (0, _bettercall.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 (0, _bettercall.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 (0, _bettercall.APIError)("BAD_REQUEST",{message:"Couldn't update your email"});if(e.context.session.user.emailVerified!==!0){let r=await e.context.internalAdapter.updateUserByEmail(e.context.session.user.email,{email:e.body.newEmail});return e.json({user:r,status:!0})}if(!e.context.options.user.changeEmail.sendChangeEmailVerification)throw e.context.logger.error("Verification email isn't enabled."),new (0, _bettercall.APIError)("BAD_REQUEST",{message:"Verification email isn't enabled"});let o=await v(e.context.secret,e.context.session.user.email,e.body.newEmail),s=`${e.context.baseURL}/verify-email?token=${o}&callbackURL=${e.body.callbackURL||_optionalChain([e, 'access', _111 => _111.query, 'optionalAccess', _112 => _112.currentURL])||"/"}`;return await e.context.options.user.changeEmail.sendChangeEmailVerification(e.context.session.user,e.body.newEmail,s,o),e.json({user:null,status:!0})});var Te=p("/csrf",{method:"GET",metadata:_chunk2BBAB6DPcjs.h},async e=>{let t=await e.getSignedCookie(e.context.authCookies.csrfToken.name,e.context.secret);if(t){let[n,i]=t.split("!")||[null,null];return e.json({csrfToken:n})}let o=_chunkOQSWDMGGcjs.h.call(void 0, 32,_chunkOQSWDMGGcjs.i.call(void 0, "a-z","0-9","A-Z")),s=await _chunkOQSWDMGGcjs.j.call(void 0, e.context.secret,o),r=`${o}!${s}`;return await e.setSignedCookie(e.context.authCookies.csrfToken.name,r,e.context.secret,e.context.authCookies.csrfToken.options),e.json({csrfToken:o})});var We=(e="Unknown")=>`<!DOCTYPE html>
|
|
4
|
+
<html lang="en">
|
|
5
|
+
<head>
|
|
6
|
+
<meta charset="UTF-8">
|
|
7
|
+
<meta name="viewport" content="width=device-width, initial-scale=1.0">
|
|
8
|
+
<title>Authentication Error</title>
|
|
9
|
+
<style>
|
|
10
|
+
:root {
|
|
11
|
+
--bg-color: #f8f9fa;
|
|
12
|
+
--text-color: #212529;
|
|
13
|
+
--accent-color: #000000;
|
|
14
|
+
--error-color: #dc3545;
|
|
15
|
+
--border-color: #e9ecef;
|
|
16
|
+
}
|
|
17
|
+
body {
|
|
18
|
+
font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, 'Helvetica Neue', Arial, sans-serif;
|
|
19
|
+
background-color: var(--bg-color);
|
|
20
|
+
color: var(--text-color);
|
|
21
|
+
display: flex;
|
|
22
|
+
justify-content: center;
|
|
23
|
+
align-items: center;
|
|
24
|
+
height: 100vh;
|
|
25
|
+
margin: 0;
|
|
26
|
+
line-height: 1.5;
|
|
27
|
+
}
|
|
28
|
+
.error-container {
|
|
29
|
+
background-color: #ffffff;
|
|
30
|
+
border-radius: 12px;
|
|
31
|
+
box-shadow: 0 4px 6px rgba(0, 0, 0, 0.05);
|
|
32
|
+
padding: 2.5rem;
|
|
33
|
+
text-align: center;
|
|
34
|
+
max-width: 90%;
|
|
35
|
+
width: 400px;
|
|
36
|
+
}
|
|
37
|
+
h1 {
|
|
38
|
+
color: var(--error-color);
|
|
39
|
+
font-size: 1.75rem;
|
|
40
|
+
margin-bottom: 1rem;
|
|
41
|
+
font-weight: 600;
|
|
42
|
+
}
|
|
43
|
+
p {
|
|
44
|
+
margin-bottom: 1.5rem;
|
|
45
|
+
color: #495057;
|
|
46
|
+
}
|
|
47
|
+
.btn {
|
|
48
|
+
background-color: var(--accent-color);
|
|
49
|
+
color: #ffffff;
|
|
50
|
+
text-decoration: none;
|
|
51
|
+
padding: 0.75rem 1.5rem;
|
|
52
|
+
border-radius: 6px;
|
|
53
|
+
transition: all 0.3s ease;
|
|
54
|
+
display: inline-block;
|
|
55
|
+
font-weight: 500;
|
|
56
|
+
border: 2px solid var(--accent-color);
|
|
57
|
+
}
|
|
58
|
+
.btn:hover {
|
|
59
|
+
background-color: #131721;
|
|
60
|
+
}
|
|
61
|
+
.error-code {
|
|
62
|
+
font-size: 0.875rem;
|
|
63
|
+
color: #6c757d;
|
|
64
|
+
margin-top: 1.5rem;
|
|
65
|
+
padding-top: 1.5rem;
|
|
66
|
+
border-top: 1px solid var(--border-color);
|
|
67
|
+
}
|
|
68
|
+
.icon {
|
|
69
|
+
font-size: 3rem;
|
|
70
|
+
margin-bottom: 1rem;
|
|
71
|
+
}
|
|
72
|
+
</style>
|
|
73
|
+
</head>
|
|
74
|
+
<body>
|
|
75
|
+
<div class="error-container">
|
|
76
|
+
<div class="icon">\u26A0\uFE0F</div>
|
|
77
|
+
<h1>Better Auth Error</h1>
|
|
78
|
+
<p>We encountered an issue while processing your request. Please try again or contact the application owner if the problem persists.</p>
|
|
79
|
+
<a href="/" id="returnLink" class="btn">Return to Application</a>
|
|
80
|
+
<div class="error-code">Error Code: <span id="errorCode">${e}</span></div>
|
|
81
|
+
</div>
|
|
82
|
+
</body>
|
|
83
|
+
</html>`,Le= exports.C =p("/error",{method:"GET",metadata:_chunk2BBAB6DPcjs.h},async e=>{let t=new URL(_optionalChain([e, 'access', _113 => _113.request, 'optionalAccess', _114 => _114.url])||"").searchParams.get("error")||"Unknown";return new Response(We(t),{headers:{"Content-Type":"text/html"}})});var Ie=p("/ok",{method:"GET",metadata:_chunk2BBAB6DPcjs.h},async e=>e.json({ok:!0}));var Oe=()=>p("/sign-up/email",{method:"POST",query:_zod.z.object({currentURL:_zod.z.string().optional()}).optional(),body:_zod.z.record(_zod.z.string(),_zod.z.any()),use:[b]},async e=>{if(!_optionalChain([e, 'access', _115 => _115.context, 'access', _116 => _116.options, 'access', _117 => _117.emailAndPassword, 'optionalAccess', _118 => _118.enabled]))throw new (0, _bettercall.APIError)("BAD_REQUEST",{message:"Email and password sign up is not enabled"});let t=e.body,{name:o,email:s,password:r,image:n,callbackURL:i,...d}=t;if(!_zod.z.string().email().safeParse(s).success)throw new (0, _bettercall.APIError)("BAD_REQUEST",{message:"Invalid email"});let a=e.context.password.config.minPasswordLength;if(r.length<a)throw e.context.logger.error("Password is too short"),new (0, _bettercall.APIError)("BAD_REQUEST",{message:"Password is too short"});let l=e.context.password.config.maxPasswordLength;if(r.length>l)throw e.context.logger.error("Password is too long"),new (0, _bettercall.APIError)("BAD_REQUEST",{message:"Password is too long"});if(await _asyncOptionalChain([(await e.context.internalAdapter.findUserByEmail(s)), 'optionalAccess', async _119 => _119.user]))throw e.context.logger.info(`Sign-up attempt for existing email: ${s}`),new (0, _bettercall.APIError)("UNPROCESSABLE_ENTITY",{message:"User with this email already exists"});let y=H(e.context.options,d),u;try{if(u=await e.context.internalAdapter.createUser({email:s.toLowerCase(),name:o,image:n,...y,emailVerified:!1}),!u)throw new (0, _bettercall.APIError)("BAD_REQUEST",{message:"Failed to create user"})}catch(g){throw _chunk4INQICGPcjs.b.error("Failed to create user",g),new (0, _bettercall.APIError)("UNPROCESSABLE_ENTITY",{message:"Failed to create user",details:g})}if(!u)throw new (0, _bettercall.APIError)("UNPROCESSABLE_ENTITY",{message:"Failed to create user"});let R=await e.context.password.hash(r);if(await e.context.internalAdapter.linkAccount({userId:u.id,providerId:"credential",accountId:u.id,password:R,expiresAt:_chunkDMAK6URHcjs.a.call(void 0, 60*60*24*30,"sec")}),_optionalChain([e, 'access', _120 => _120.context, 'access', _121 => _121.options, 'access', _122 => _122.emailVerification, 'optionalAccess', _123 => _123.sendOnSignUp])){let g=await v(e.context.secret,u.email),f=`${e.context.baseURL}/verify-email?token=${g}&callbackURL=${t.callbackURL||_optionalChain([e, 'access', _124 => _124.query, 'optionalAccess', _125 => _125.currentURL])||"/"}`;await _optionalChain([e, 'access', _126 => _126.context, 'access', _127 => _127.options, 'access', _128 => _128.emailVerification, 'optionalAccess', _129 => _129.sendVerificationEmail, 'optionalCall', _130 => _130(u,f,g)])}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 A=await e.context.internalAdapter.createSession(u.id,e.request);if(!A)throw new (0, _bettercall.APIError)("BAD_REQUEST",{message:"Failed to create session"});return await _chunkLF4SJYGRcjs.c.call(void 0, e,{session:A,user:u}),e.json({user:u,session:A},{body:t.callbackURL?{url:t.callbackURL,redirect:!0}:{user:u,session:A}})});var ve=p("/user/list-accounts",{method:"GET",use:[E]},async e=>{let t=e.context.session,o=await e.context.internalAdapter.findAccounts(t.user.id);return e.json(o)}),xe= exports.G =p("/user/link-social",{method:"POST",requireHeaders:!0,query:_zod.z.object({currentURL:_zod.z.string().optional()}).optional(),body:_zod.z.object({callbackURL:_zod.z.string().optional(),provider:_zod.z.enum(_chunk2BBAB6DPcjs.n)}),use:[b,E]},async e=>{let t=e.context.session;if((await e.context.internalAdapter.findAccounts(t.user.id)).find(w=>w.providerId===e.body.provider))throw new (0, _bettercall.APIError)("BAD_REQUEST",{message:"Social Account is already linked."});let r=e.context.socialProviders.find(w=>w.id===e.body.provider);if(!r)throw e.context.logger.error("Provider not found. Make sure to add the provider in your auth config",{provider:e.body.provider}),new (0, _bettercall.APIError)("NOT_FOUND",{message:"Provider not found"});let n=e.context.authCookies,i=_optionalChain([e, 'access', _131 => _131.query, 'optionalAccess', _132 => _132.currentURL])?new URL(_optionalChain([e, 'access', _133 => _133.query, 'optionalAccess', _134 => _134.currentURL])):null,d=_optionalChain([e, 'access', _135 => _135.body, 'access', _136 => _136.callbackURL, 'optionalAccess', _137 => _137.startsWith, 'call', _138 => _138("http")])?e.body.callbackURL:`${_optionalChain([i, 'optionalAccess', _139 => _139.origin])}${e.body.callbackURL||""}`,c=await _chunkU5FXGV3Gcjs.b.call(void 0, d||_optionalChain([i, 'optionalAccess', _140 => _140.origin])||e.context.options.baseURL,{email:t.user.email,userId:t.user.id});await e.setSignedCookie(n.state.name,c.hash,e.context.secret,n.state.options);let a=_oauth2.generateCodeVerifier.call(void 0, );await e.setSignedCookie(n.pkCodeVerifier.name,a,e.context.secret,n.pkCodeVerifier.options);let l=await r.createAuthorizationURL({state:c.raw,codeVerifier:a,redirectURI:`${e.context.baseURL}/link-account/${r.id}`});return e.json({url:l.toString(),state:c,codeVerifier:a,redirect:!0})});function Je(e,t,o){let s=Date.now(),r=t*1e3;return s-o.lastRequest<r&&o.count>=e}function Ye(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 Ke(e,t){let o=Date.now(),s=t*1e3;return Math.ceil((e+s-o)/1e3)}function Xe(e,t){let o=_nullishCoalesce(t, () => ("rateLimit")),s=e.adapter;return{get:async r=>await s.findOne({model:o,where:[{field:"key",value:r}]}),set:async(r,n,i)=>{try{i?await s.update({model:_nullishCoalesce(t, () => ("rateLimit")),where:[{field:"key",value:r}],update:{count:n.count,lastRequest:n.lastRequest}}):await s.create({model:_nullishCoalesce(t, () => ("rateLimit")),data:{key:r,count:n.count,lastRequest:n.lastRequest}})}catch(d){_chunk4INQICGPcjs.b.error("Error setting rate limit",d)}}}}var Ce=new Map;function et(e){return e.rateLimit.storage==="secondary-storage"?{get:async o=>{let s=await _optionalChain([e, 'access', _141 => _141.options, 'access', _142 => _142.secondaryStorage, 'optionalAccess', _143 => _143.get, 'call', _144 => _144(o)]);return s?JSON.parse(s):void 0},set:async(o,s)=>{await _optionalChain([e, 'access', _145 => _145.options, 'access', _146 => _146.secondaryStorage, 'optionalAccess', _147 => _147.set, 'optionalCall', _148 => _148(o,JSON.stringify(s))])}}:e.rateLimit.storage==="memory"?{async get(o){return Ce.get(o)},async set(o,s,r){Ce.set(o,s)}}:Xe(e,e.rateLimit.tableName)}async function _e(e,t){if(!t.rateLimit.enabled)return;let o=t.baseURL,s=e.url.replace(o,""),r=t.rateLimit.window,n=t.rateLimit.max,i=_chunk5CGFZN2Lcjs.a.call(void 0, e)+s,c=tt().find(y=>y.pathMatcher(s));c&&(r=c.window,n=c.max);for(let y of t.options.plugins||[])if(y.rateLimit){let u=y.rateLimit.find(R=>R.pathMatcher(s));if(u){r=u.window,n=u.max;break}}if(t.rateLimit.customRules){let y=t.rateLimit.customRules[s];y&&(r=y.window,n=y.max)}let a=et(t),l=await a.get(i),w=Date.now();if(!l)await a.set(i,{key:i,count:1,lastRequest:w});else{let y=w-l.lastRequest;if(Je(n,r,l)){let u=Ke(l.lastRequest,r);return Ye(u)}else y>r*1e3?await a.set(i,{...l,count:1,lastRequest:w}):await a.set(i,{...l,count:l.count+1,lastRequest:w})}}function tt(){return[{pathMatcher(t){return t.startsWith("/sign-in")||t.startsWith("/sign-up")},window:10,max:3}]}function st(e,t){let o=_optionalChain([t, 'access', _149 => _149.plugins, 'optionalAccess', _150 => _150.reduce, 'call', _151 => _151((d,c)=>({...d,...c.endpoints}),{})]),s=_optionalChain([t, 'access', _152 => _152.plugins, 'optionalAccess', _153 => _153.map, 'call', _154 => _154(d=>_optionalChain([d, 'access', _155 => _155.middlewares, 'optionalAccess', _156 => _156.map, 'call', _157 => _157(c=>{let a=async l=>c.middleware({...l,context:{...e,...l.context}});return a.path=c.path,a.options=c.middleware.options,a.headers=c.middleware.headers,{path:c.path,middleware:a}})])), 'access', _158 => _158.filter, 'call', _159 => _159(d=>d!==void 0), 'access', _160 => _160.flat, 'call', _161 => _161()])||[],n={...{signInOAuth:me,callbackOAuth:ge,getCSRFToken:Te,getSession:Y(),signOut:he,signUpEmail:Oe(),signInEmail:fe,forgetPassword:ye,resetPassword:Ae,verifyEmail:pe,sendVerificationEmail:ue,changeEmail:Se,changePassword:ke,setPassword:Ue,updateUser:be(),deleteUser:Ee,forgetPasswordCallback:Re,listSessions:de(),revokeSession:ce,revokeSessions:le,linkSocialAccount:xe,listUserAccounts:ve},...o,ok:Ie,error:Le},i={};for(let[d,c]of Object.entries(n))i[d]=async(a={})=>{let l=await e;for(let u of t.plugins||[])if(_optionalChain([u, 'access', _162 => _162.hooks, 'optionalAccess', _163 => _163.before])){for(let R of u.hooks.before)if(R.matcher({...c,...a,context:l})){let g=await R.handler({...a,context:{...l,..._optionalChain([a, 'optionalAccess', _164 => _164.context])}});g&&"context"in g&&(l={...l,...g.context})}}let w;try{w=await c({...a,context:{...l,...a.context}})}catch(u){if(u instanceof _bettercall.APIError){let R=_optionalChain([t, 'access', _165 => _165.plugins, 'optionalAccess', _166 => _166.map, 'call', _167 => _167(g=>{if(_optionalChain([g, 'access', _168 => _168.hooks, 'optionalAccess', _169 => _169.after]))return g.hooks.after}), 'access', _170 => _170.filter, 'call', _171 => _171(g=>g!==void 0), 'access', _172 => _172.flat, 'call', _173 => _173()]);if(!_optionalChain([R, 'optionalAccess', _174 => _174.length]))throw u;console.log({afterPlugins:R.length,e:u});let A=new Response(JSON.stringify(u.body),{status:_bettercall.statusCode[u.status],headers:u.headers});for(let g of R||[])if(g.matcher(a)){let T=Object.assign(a,{context:{...e,returned:A}}),D=await g.handler(T);D&&"response"in D&&(A=D.response)}return A}throw u}let y=w;for(let u of t.plugins||[])if(_optionalChain([u, 'access', _175 => _175.hooks, 'optionalAccess', _176 => _176.after])){for(let R of u.hooks.after)if(R.matcher(a)){let g=Object.assign(a,{context:{...e,returned:y}}),f=await R.handler(g);f&&"response"in f&&(y=f.response)}}return y},i[d].path=c.path,i[d].method=c.method,i[d].options=c.options,i[d].headers=c.headers;return{api:i,middlewares:s}}var Yr=(e,t)=>{let{api:o,middlewares:s}=st(e,t),r=new URL(e.baseURL).pathname;return _bettercall.createRouter.call(void 0, o,{extraContext:e,basePath:r,routerMiddleware:[{path:"/**",middleware:ae},...s],async onRequest(n){for(let i of e.options.plugins||[])if(i.onRequest){let d=await i.onRequest(n,e);if(d)return d}return _e(n,e)},async onResponse(n){for(let i of e.options.plugins||[])if(i.onResponse){let d=await i.onResponse(n,e);if(d)return d.response}return n},onError(n){if(_optionalChain([t, 'access', _177 => _177.onAPIError, 'optionalAccess', _178 => _178.throw]))throw n;if(_optionalChain([t, 'access', _179 => _179.onAPIError, 'optionalAccess', _180 => _180.onError])){t.onAPIError.onError(n,e);return}let i=_optionalChain([t, 'access', _181 => _181.logger, 'optionalAccess', _182 => _182.verboseLogging])?_chunk4INQICGPcjs.b:void 0;_optionalChain([t, 'access', _183 => _183.logger, 'optionalAccess', _184 => _184.disabled])!==!0&&(n instanceof _bettercall.APIError?(n.status==="INTERNAL_SERVER_ERROR"&&_chunk4INQICGPcjs.b.error(n),_optionalChain([i, 'optionalAccess', _185 => _185.error, 'call', _186 => _186(n.message)])):_optionalChain([_chunk4INQICGPcjs.b, 'optionalAccess', _187 => _187.error, 'call', _188 => _188(n)]))}})};exports.a = ne; exports.b = B; exports.c = p; exports.d = ae; exports.e = b; exports.f = Y; exports.g = K; exports.h = E; exports.i = de; exports.j = ce; exports.k = le; exports.l = v; exports.m = ue; exports.n = pe; exports.o = me; exports.p = fe; exports.q = we; exports.r = ge; exports.s = he; exports.t = ye; exports.u = Re; exports.v = Ae; exports.w = be; exports.x = ke; exports.y = Ue; exports.z = Ee; exports.A = Se; exports.B = Te; exports.C = Le; exports.D = Ie; exports.E = Oe; exports.F = ve; exports.G = xe; exports.H = st; exports.I = Yr; exports.J = _bettercall.APIError;
|
|
84
|
+
//# sourceMappingURL=chunk-36URECJ6.cjs.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["/Users/beka/Desktop/Development/better-auth/packages/better-auth/dist/chunk-36URECJ6.cjs","../src/api/index.ts","../src/api/middlewares/csrf.ts","../src/api/call.ts","../src/api/routes/sign-in.ts","../src/api/middlewares/redirect.ts","../src/api/routes/session.ts","../src/api/routes/sign-out.ts","../src/api/routes/error.ts","../src/api/routes/sign-up.ts"],"names":["optionsMiddleware","createMiddleware","createAuthMiddleware","createMiddlewareCreator","createAuthEndpoint","createEndpointCreator","csrfMiddleware","z","ctx","originHeader","origin","csrfToken","APIError","csrfCookie","token","hash","expectedHash","hs256","redirectURLMiddleware","body","query","context","callbackURL","currentURL","trustedOrigins","validateURL","url","label","logger"],"mappings":"AAAA,owCAAyC,wDAAgD,wDAAiD,wDAAwD,wDAAyC,wDAAwD,wDAAgD,yCCAjR,0BCChD,ICULA,EAAAA,CAAoBC,0CAAAA,KAAiB,CAAA,CAAA,EAAA,CAM1C,CAAC,CAAA,CACR,CAAA,CAEYC,CAAAA,aAAuBC,iDAAAA,CACnC,GAAA,CAAK,CACJH,EAAAA,CAIAC,0CAAAA,KAAiB,CAAA,CAAA,EAAA,CACT,CAAC,CAAA,CAGR,CACF,CACD,CAAC,CAAA,CAEYG,CAAAA,aAAqBC,+CAAAA,CACjC,GAAA,CAAK,CAACL,EAAiB,CACxB,CAAC,CAAA,CD9BM,IAAMM,EAAAA,CAAiBJ,CAAAA,CAC7B,CACC,IAAA,CAAMK,MAAAA,CACJ,MAAA,CAAO,CACP,SAAA,CAAWA,MAAAA,CAAE,MAAA,CAAO,CAAA,CAAE,QAAA,CAAS,CAChC,CAAC,CAAA,CACA,QAAA,CAAS,CACZ,CAAA,CACA,MAAOC,CAAAA,EAAQ,CACd,EAAA,iBACCA,CAAAA,qBAAI,OAAA,6BAAS,QAAA,GAAW,MAAA,kBACxBA,CAAAA,qBAAI,OAAA,qBAAQ,OAAA,qBAAQ,QAAA,6BAAU,kBAAA,CAE9B,MAAA,CAED,IAAMC,CAAAA,iBAAeD,CAAAA,qBAAI,OAAA,6BAAS,GAAA,qBAAI,QAAQ,GAAA,EAAK,EAAA,CAMnD,EAAA,CAAIC,CAAAA,CAAc,CACjB,IAAMC,CAAAA,CAAS,IAAI,GAAA,CAAID,CAAY,CAAA,CAAE,MAAA,CACrC,EAAA,CAAID,CAAAA,CAAI,OAAA,CAAQ,cAAA,CAAe,QAAA,CAASE,CAAM,CAAA,CAC7C,MAEF,CAEA,IAAMC,CAAAA,iBAAYH,CAAAA,uBAAI,IAAA,+BAAM,WAAA,CAC5B,EAAA,CAAI,CAACG,CAAAA,CACJ,MAAM,IAAIC,yBAAAA,CAAS,cAAA,CAAgB,CAClC,OAAA,CAAS,wBACV,CAAC,CAAA,CAEF,IAAMC,CAAAA,CAAa,MAAML,CAAAA,CAAI,eAAA,CAC5BA,CAAAA,CAAI,OAAA,CAAQ,WAAA,CAAY,SAAA,CAAU,IAAA,CAClCA,CAAAA,CAAI,OAAA,CAAQ,MACb,CAAA,CACM,CAACM,CAAAA,CAAOC,CAAI,CAAA,iBAAIF,CAAAA,+BAAY,KAAA,qBAAM,GAAG,GAAA,EAAK,CAAC,IAAA,CAAM,IAAI,CAAA,CAC3D,EAAA,CAAI,CAACF,CAAAA,EAAa,CAACG,CAAAA,EAAS,CAACC,CAAAA,EAAQD,CAAAA,GAAUH,CAAAA,CAC9C,MAAM,IAAIC,yBAAAA,CAAS,cAAA,CAAgB,CAClC,OAAA,CAAS,oBACV,CAAC,CAAA,CAEF,IAAMI,CAAAA,CAAe,MAAMC,iCAAAA,CAAMT,CAAI,OAAA,CAAQ,MAAA,CAAQM,CAAK,CAAA,CAC1D,EAAA,CAAIC,CAAAA,GAASC,CAAAA,CACZ,MAAAR,CAAAA,CAAI,SAAA,CAAUA,CAAAA,CAAI,OAAA,CAAQ,WAAA,CAAY,SAAA,CAAU,IAAA,CAAM,EAAA,CAAI,CACzD,MAAA,CAAQ,CACT,CAAC,CAAA,CACK,IAAII,yBAAAA,CAAS,cAAA,CAAgB,CAClC,OAAA,CAAS,oBACV,CAAC,CAEH,CACD,CAAA,CE5DA,qCACqC,ICOxBM,CAAAA,CAAwBhB,CAAAA,CAAqB,MAAOM,CAAAA,EAAQ,CACxE,GAAM,CAAE,IAAA,CAAAW,CAAAA,CAAM,KAAA,CAAAC,CAAAA,CAAO,OAAA,CAAAC,CAAQ,CAAA,CAAIb,CAAAA,CAE3Bc,CAAAA,iBACLH,CAAAA,+BAAM,aAAA,kBACNC,CAAAA,+BAAO,aAAA,kBACPA,CAAAA,+BAAO,YAAA,kBACPD,CAAAA,+BAAM,YAAA,CACDI,CAAAA,iBAAaH,CAAAA,+BAAO,YAAA,CACpBI,CAAAA,CAAiBH,CAAAA,CAAQ,cAAA,CAEzBI,CAAAA,CAAc,CAACC,CAAAA,CAAyBC,CAAAA,CAAAA,EAAkB,CAC/D,EAAA,iBAAID,CAAAA,+BAAK,UAAA,qBAAW,MAAM,GAAA,EAIrB,CAHoBF,CAAAA,CAAe,IAAA,CAAMd,CAAAA,EAC5CgB,CAAAA,CAAI,UAAA,CAAWhB,CAAM,CACtB,CAAA,CAEC,MAAAkB,mBAAAA,CAAO,KAAA,CAAM,CAAA,QAAA,EAAWD,CAAK,CAAA,EAAA,EAAKD,CAAG,CAAA,CAAA;ACqJpB;AC9KrB,OAAA;ACGgD;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AA6E4B,iEAAA;AAAA;AAAA;ACoC/D,OAAA","file":"/Users/beka/Desktop/Development/better-auth/packages/better-auth/dist/chunk-36URECJ6.cjs","sourcesContent":[null,"import { APIError, type Endpoint, createRouter, statusCode } from \"better-call\";\nimport type { AuthContext } from \"../init\";\nimport type { BetterAuthOptions } from \"../types\";\nimport type { UnionToIntersection } from \"../types/helper\";\nimport { csrfMiddleware } from \"./middlewares/csrf\";\nimport {\n\tcallbackOAuth,\n\tforgetPassword,\n\tforgetPasswordCallback,\n\tgetSession,\n\tlistSessions,\n\tresetPassword,\n\trevokeSession,\n\trevokeSessions,\n\tsendVerificationEmail,\n\tchangeEmail,\n\tsignInEmail,\n\tsignInOAuth,\n\tsignOut,\n\tverifyEmail,\n\tlinkSocialAccount,\n\tlistUserAccounts,\n\tchangePassword,\n\tdeleteUser,\n\tsetPassword,\n\tupdateUser,\n} from \"./routes\";\nimport { getCSRFToken } from \"./routes/csrf\";\nimport { ok } from \"./routes/ok\";\nimport { signUpEmail } from \"./routes/sign-up\";\nimport { error } from \"./routes/error\";\nimport { logger } from \"../utils/logger\";\nimport type { BetterAuthPlugin } from \"../plugins\";\nimport { onRequestRateLimit } from \"./rate-limiter\";\n\nexport function getEndpoints<\n\tC extends AuthContext,\n\tOption extends BetterAuthOptions,\n>(ctx: Promise<C> | C, options: Option) {\n\tconst pluginEndpoints = options.plugins?.reduce(\n\t\t(acc, plugin) => {\n\t\t\treturn {\n\t\t\t\t...acc,\n\t\t\t\t...plugin.endpoints,\n\t\t\t};\n\t\t},\n\t\t{} as Record<string, any>,\n\t);\n\n\ttype PluginEndpoint = UnionToIntersection<\n\t\tOption[\"plugins\"] extends Array<infer T>\n\t\t\t? T extends BetterAuthPlugin\n\t\t\t\t? T extends {\n\t\t\t\t\t\tendpoints: infer E;\n\t\t\t\t\t}\n\t\t\t\t\t? E\n\t\t\t\t\t: {}\n\t\t\t\t: {}\n\t\t\t: {}\n\t>;\n\n\tconst middlewares =\n\t\toptions.plugins\n\t\t\t?.map((plugin) =>\n\t\t\t\tplugin.middlewares?.map((m) => {\n\t\t\t\t\tconst middleware = (async (context: any) => {\n\t\t\t\t\t\treturn m.middleware({\n\t\t\t\t\t\t\t...context,\n\t\t\t\t\t\t\tcontext: {\n\t\t\t\t\t\t\t\t...ctx,\n\t\t\t\t\t\t\t\t...context.context,\n\t\t\t\t\t\t\t},\n\t\t\t\t\t\t});\n\t\t\t\t\t}) as Endpoint;\n\t\t\t\t\tmiddleware.path = m.path;\n\t\t\t\t\tmiddleware.options = m.middleware.options;\n\t\t\t\t\tmiddleware.headers = m.middleware.headers;\n\t\t\t\t\treturn {\n\t\t\t\t\t\tpath: m.path,\n\t\t\t\t\t\tmiddleware,\n\t\t\t\t\t};\n\t\t\t\t}),\n\t\t\t)\n\t\t\t.filter((plugin) => plugin !== undefined)\n\t\t\t.flat() || [];\n\n\tconst baseEndpoints = {\n\t\tsignInOAuth,\n\t\tcallbackOAuth,\n\t\tgetCSRFToken,\n\t\tgetSession: getSession<Option>(),\n\t\tsignOut,\n\t\tsignUpEmail: signUpEmail<Option>(),\n\t\tsignInEmail,\n\t\tforgetPassword,\n\t\tresetPassword,\n\t\tverifyEmail,\n\t\tsendVerificationEmail,\n\t\tchangeEmail,\n\t\tchangePassword,\n\t\tsetPassword,\n\t\tupdateUser: updateUser<Option>(),\n\t\tdeleteUser,\n\t\tforgetPasswordCallback,\n\t\tlistSessions: listSessions<Option>(),\n\t\trevokeSession,\n\t\trevokeSessions,\n\t\tlinkSocialAccount,\n\t\tlistUserAccounts,\n\t};\n\tconst endpoints = {\n\t\t...baseEndpoints,\n\t\t...pluginEndpoints,\n\t\tok,\n\t\terror,\n\t};\n\tlet api: Record<string, any> = {};\n\tfor (const [key, value] of Object.entries(endpoints)) {\n\t\tapi[key] = async (context = {} as any) => {\n\t\t\tlet c = await ctx;\n\t\t\tfor (const plugin of options.plugins || []) {\n\t\t\t\tif (plugin.hooks?.before) {\n\t\t\t\t\tfor (const hook of plugin.hooks.before) {\n\t\t\t\t\t\tconst match = hook.matcher({\n\t\t\t\t\t\t\t...value,\n\t\t\t\t\t\t\t...context,\n\t\t\t\t\t\t\tcontext: c,\n\t\t\t\t\t\t});\n\t\t\t\t\t\tif (match) {\n\t\t\t\t\t\t\tconst hookRes = await hook.handler({\n\t\t\t\t\t\t\t\t...context,\n\t\t\t\t\t\t\t\tcontext: {\n\t\t\t\t\t\t\t\t\t...c,\n\t\t\t\t\t\t\t\t\t...context?.context,\n\t\t\t\t\t\t\t\t},\n\t\t\t\t\t\t\t});\n\t\t\t\t\t\t\tif (hookRes && \"context\" in hookRes) {\n\t\t\t\t\t\t\t\tc = {\n\t\t\t\t\t\t\t\t\t...c,\n\t\t\t\t\t\t\t\t\t...hookRes.context,\n\t\t\t\t\t\t\t\t};\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t\tlet endpointRes: any;\n\t\t\ttry {\n\t\t\t\t//@ts-ignore\n\t\t\t\tendpointRes = await value({\n\t\t\t\t\t...context,\n\t\t\t\t\tcontext: {\n\t\t\t\t\t\t...c,\n\t\t\t\t\t\t...context.context,\n\t\t\t\t\t},\n\t\t\t\t});\n\t\t\t} catch (e) {\n\t\t\t\tif (e instanceof APIError) {\n\t\t\t\t\tconst afterPlugins = options.plugins\n\t\t\t\t\t\t?.map((plugin) => {\n\t\t\t\t\t\t\tif (plugin.hooks?.after) {\n\t\t\t\t\t\t\t\treturn plugin.hooks.after;\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t})\n\t\t\t\t\t\t.filter((plugin) => plugin !== undefined)\n\t\t\t\t\t\t.flat();\n\n\t\t\t\t\tif (!afterPlugins?.length) {\n\t\t\t\t\t\tthrow e;\n\t\t\t\t\t}\n\t\t\t\t\tconsole.log({\n\t\t\t\t\t\tafterPlugins: afterPlugins.length,\n\t\t\t\t\t\te,\n\t\t\t\t\t});\n\t\t\t\t\tlet response = new Response(JSON.stringify(e.body), {\n\t\t\t\t\t\tstatus: statusCode[e.status],\n\t\t\t\t\t\theaders: e.headers,\n\t\t\t\t\t});\n\n\t\t\t\t\tfor (const hook of afterPlugins || []) {\n\t\t\t\t\t\tconst match = hook.matcher(context);\n\t\t\t\t\t\tif (match) {\n\t\t\t\t\t\t\tconst obj = Object.assign(context, {\n\t\t\t\t\t\t\t\tcontext: {\n\t\t\t\t\t\t\t\t\t...ctx,\n\t\t\t\t\t\t\t\t\treturned: response,\n\t\t\t\t\t\t\t\t},\n\t\t\t\t\t\t\t});\n\t\t\t\t\t\t\tconst hookRes = await hook.handler(obj);\n\t\t\t\t\t\t\tif (hookRes && \"response\" in hookRes) {\n\t\t\t\t\t\t\t\tresponse = hookRes.response as any;\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t\treturn response;\n\t\t\t\t}\n\t\t\t\tthrow e;\n\t\t\t}\n\t\t\tlet response = endpointRes;\n\t\t\tfor (const plugin of options.plugins || []) {\n\t\t\t\tif (plugin.hooks?.after) {\n\t\t\t\t\tfor (const hook of plugin.hooks.after) {\n\t\t\t\t\t\tconst match = hook.matcher(context);\n\t\t\t\t\t\tif (match) {\n\t\t\t\t\t\t\tconst obj = Object.assign(context, {\n\t\t\t\t\t\t\t\tcontext: {\n\t\t\t\t\t\t\t\t\t...ctx,\n\t\t\t\t\t\t\t\t\treturned: response,\n\t\t\t\t\t\t\t\t},\n\t\t\t\t\t\t\t});\n\t\t\t\t\t\t\tconst hookRes = await hook.handler(obj);\n\t\t\t\t\t\t\tif (hookRes && \"response\" in hookRes) {\n\t\t\t\t\t\t\t\tresponse = hookRes.response as any;\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t\treturn response;\n\t\t};\n\t\tapi[key].path = value.path;\n\t\tapi[key].method = value.method;\n\t\tapi[key].options = value.options;\n\t\tapi[key].headers = value.headers;\n\t}\n\treturn {\n\t\tapi: api as typeof endpoints & PluginEndpoint,\n\t\tmiddlewares,\n\t};\n}\n\nexport const router = <C extends AuthContext, Option extends BetterAuthOptions>(\n\tctx: C,\n\toptions: Option,\n) => {\n\tconst { api, middlewares } = getEndpoints(ctx, options);\n\tconst basePath = new URL(ctx.baseURL).pathname;\n\n\treturn createRouter(api, {\n\t\textraContext: ctx,\n\t\tbasePath,\n\t\trouterMiddleware: [\n\t\t\t{\n\t\t\t\tpath: \"/**\",\n\t\t\t\tmiddleware: csrfMiddleware,\n\t\t\t},\n\t\t\t...middlewares,\n\t\t],\n\t\tasync onRequest(req) {\n\t\t\tfor (const plugin of ctx.options.plugins || []) {\n\t\t\t\tif (plugin.onRequest) {\n\t\t\t\t\tconst response = await plugin.onRequest(req, ctx);\n\t\t\t\t\tif (response) {\n\t\t\t\t\t\treturn response;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t\treturn onRequestRateLimit(req, ctx);\n\t\t},\n\t\tasync onResponse(res) {\n\t\t\tfor (const plugin of ctx.options.plugins || []) {\n\t\t\t\tif (plugin.onResponse) {\n\t\t\t\t\tconst response = await plugin.onResponse(res, ctx);\n\t\t\t\t\tif (response) {\n\t\t\t\t\t\treturn response.response;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t\treturn res;\n\t\t},\n\t\tonError(e) {\n\t\t\tif (options.onAPIError?.throw) {\n\t\t\t\tthrow e;\n\t\t\t}\n\t\t\tif (options.onAPIError?.onError) {\n\t\t\t\toptions.onAPIError.onError(e, ctx);\n\t\t\t\treturn;\n\t\t\t}\n\n\t\t\tconst log = options.logger?.verboseLogging ? logger : undefined;\n\t\t\tif (options.logger?.disabled !== true) {\n\t\t\t\tif (e instanceof APIError) {\n\t\t\t\t\tif (e.status === \"INTERNAL_SERVER_ERROR\") {\n\t\t\t\t\t\tlogger.error(e);\n\t\t\t\t\t}\n\t\t\t\t\tlog?.error(e.message);\n\t\t\t\t} else {\n\t\t\t\t\tlogger?.error(e);\n\t\t\t\t}\n\t\t\t}\n\t\t},\n\t});\n};\n\nexport * from \"./routes\";\nexport * from \"./middlewares\";\nexport * from \"./call\";\nexport { APIError } from \"better-call\";\n","import { APIError } from \"better-call\";\nimport { z } from \"zod\";\nimport { hs256 } from \"../../crypto\";\nimport { createAuthMiddleware } from \"../call\";\nimport { deleteSessionCookie } from \"../../cookies\";\n\nexport const csrfMiddleware = createAuthMiddleware(\n\t{\n\t\tbody: z\n\t\t\t.object({\n\t\t\t\tcsrfToken: z.string().optional(),\n\t\t\t})\n\t\t\t.optional(),\n\t},\n\tasync (ctx) => {\n\t\tif (\n\t\t\tctx.request?.method !== \"POST\" ||\n\t\t\tctx.context.options.advanced?.disableCSRFCheck\n\t\t) {\n\t\t\treturn;\n\t\t}\n\t\tconst originHeader = ctx.headers?.get(\"origin\") || \"\";\n\t\t/**\n\t\t * If origin is the same as baseURL or if the\n\t\t * origin is in the trustedOrigins then we\n\t\t * don't need to check the CSRF token.\n\t\t */\n\t\tif (originHeader) {\n\t\t\tconst origin = new URL(originHeader).origin;\n\t\t\tif (ctx.context.trustedOrigins.includes(origin)) {\n\t\t\t\treturn;\n\t\t\t}\n\t\t}\n\n\t\tconst csrfToken = ctx.body?.csrfToken;\n\t\tif (!csrfToken) {\n\t\t\tthrow new APIError(\"UNAUTHORIZED\", {\n\t\t\t\tmessage: \"CSRF Token is required\",\n\t\t\t});\n\t\t}\n\t\tconst csrfCookie = await ctx.getSignedCookie(\n\t\t\tctx.context.authCookies.csrfToken.name,\n\t\t\tctx.context.secret,\n\t\t);\n\t\tconst [token, hash] = csrfCookie?.split(\"!\") || [null, null];\n\t\tif (!csrfToken || !token || !hash || token !== csrfToken) {\n\t\t\tthrow new APIError(\"UNAUTHORIZED\", {\n\t\t\t\tmessage: \"Invalid CSRF Token\",\n\t\t\t});\n\t\t}\n\t\tconst expectedHash = await hs256(ctx.context.secret, token);\n\t\tif (hash !== expectedHash) {\n\t\t\tctx.setCookie(ctx.context.authCookies.csrfToken.name, \"\", {\n\t\t\t\tmaxAge: 0,\n\t\t\t});\n\t\t\tthrow new APIError(\"UNAUTHORIZED\", {\n\t\t\t\tmessage: \"Invalid CSRF Token\",\n\t\t\t});\n\t\t}\n\t},\n);\n","import {\n\tAPIError,\n\ttype Endpoint,\n\ttype EndpointResponse,\n\tcreateEndpointCreator,\n\tcreateMiddleware,\n\tcreateMiddlewareCreator,\n} from \"better-call\";\nimport type { AuthContext } from \"../init\";\nimport type { BetterAuthOptions } from \"../types/options\";\n\nexport const optionsMiddleware = createMiddleware(async () => {\n\t/**\n\t * This will be passed on the instance of\n\t * the context. Used to infer the type\n\t * here.\n\t */\n\treturn {} as AuthContext;\n});\n\nexport const createAuthMiddleware = createMiddlewareCreator({\n\tuse: [\n\t\toptionsMiddleware,\n\t\t/**\n\t\t * Only use for post hooks\n\t\t */\n\t\tcreateMiddleware(async () => {\n\t\t\treturn {} as {\n\t\t\t\treturned?: Response;\n\t\t\t};\n\t\t}),\n\t],\n});\n\nexport const createAuthEndpoint = createEndpointCreator({\n\tuse: [optionsMiddleware],\n});\n\nexport type AuthEndpoint = Endpoint<\n\t(ctx: {\n\t\toptions: BetterAuthOptions;\n\t\tbody: any;\n\t\tquery: any;\n\t\tparams: any;\n\t\theaders: Headers;\n\t}) => Promise<EndpointResponse>\n>;\n\nexport type AuthMiddleware = ReturnType<typeof createAuthMiddleware>;\n","import { APIError } from \"better-call\";\nimport { generateCodeVerifier } from \"oslo/oauth2\";\nimport { z } from \"zod\";\nimport { generateState } from \"../../oauth2/state\";\nimport { createAuthEndpoint } from \"../call\";\nimport { setSessionCookie } from \"../../cookies\";\nimport { redirectURLMiddleware } from \"../middlewares/redirect\";\nimport { socialProviderList } from \"../../social-providers\";\nimport { createEmailVerificationToken } from \"./email-verification\";\nimport { logger } from \"../../utils\";\n\nexport const signInOAuth = createAuthEndpoint(\n\t\"/sign-in/social\",\n\t{\n\t\tmethod: \"POST\",\n\t\trequireHeaders: true,\n\t\tquery: z\n\t\t\t.object({\n\t\t\t\t/**\n\t\t\t\t * Redirect to the current URL after the\n\t\t\t\t * user has signed in.\n\t\t\t\t */\n\t\t\t\tcurrentURL: z.string().optional(),\n\t\t\t})\n\t\t\t.optional(),\n\t\tbody: z.object({\n\t\t\t/**\n\t\t\t * Callback URL to redirect to after the user has signed in.\n\t\t\t */\n\t\t\tcallbackURL: z.string().optional(),\n\t\t\t/**\n\t\t\t * OAuth2 provider to use`\n\t\t\t */\n\t\t\tprovider: z.enum(socialProviderList),\n\t\t}),\n\t\tuse: [redirectURLMiddleware],\n\t},\n\tasync (c) => {\n\t\tconst provider = c.context.socialProviders.find(\n\t\t\t(p) => p.id === c.body.provider,\n\t\t);\n\t\tif (!provider) {\n\t\t\tc.context.logger.error(\n\t\t\t\t\"Provider not found. Make sure to add the provider in your auth config\",\n\t\t\t\t{\n\t\t\t\t\tprovider: c.body.provider,\n\t\t\t\t},\n\t\t\t);\n\t\t\tthrow new APIError(\"NOT_FOUND\", {\n\t\t\t\tmessage: \"Provider not found\",\n\t\t\t});\n\t\t}\n\t\tconst cookie = c.context.authCookies;\n\t\tconst currentURL = c.query?.currentURL\n\t\t\t? new URL(c.query?.currentURL)\n\t\t\t: null;\n\n\t\tconst callbackURL = c.body.callbackURL?.startsWith(\"http\")\n\t\t\t? c.body.callbackURL\n\t\t\t: `${currentURL?.origin}${c.body.callbackURL || \"\"}`;\n\n\t\tconst state = await generateState(\n\t\t\tcallbackURL || currentURL?.origin || c.context.options.baseURL,\n\t\t);\n\t\tawait c.setSignedCookie(\n\t\t\tcookie.state.name,\n\t\t\tstate.hash,\n\t\t\tc.context.secret,\n\t\t\tcookie.state.options,\n\t\t);\n\t\tconst codeVerifier = generateCodeVerifier();\n\t\tawait c.setSignedCookie(\n\t\t\tcookie.pkCodeVerifier.name,\n\t\t\tcodeVerifier,\n\t\t\tc.context.secret,\n\t\t\tcookie.pkCodeVerifier.options,\n\t\t);\n\t\tconst url = await provider.createAuthorizationURL({\n\t\t\tstate: state.raw,\n\t\t\tcodeVerifier,\n\t\t\tredirectURI: `${c.context.baseURL}/callback/${provider.id}`,\n\t\t});\n\t\treturn c.json({\n\t\t\turl: url.toString(),\n\t\t\tstate: state,\n\t\t\tcodeVerifier,\n\t\t\tredirect: true,\n\t\t});\n\t},\n);\n\nexport const signInEmail = createAuthEndpoint(\n\t\"/sign-in/email\",\n\t{\n\t\tmethod: \"POST\",\n\t\tbody: z.object({\n\t\t\temail: z.string(),\n\t\t\tpassword: z.string(),\n\t\t\tcallbackURL: z.string().optional(),\n\t\t\t/**\n\t\t\t * If this is true the session will only be valid for the current browser session\n\t\t\t * @default false\n\t\t\t */\n\t\t\tdontRememberMe: z.boolean().default(false).optional(),\n\t\t}),\n\t\tuse: [redirectURLMiddleware],\n\t},\n\tasync (ctx) => {\n\t\tif (!ctx.context.options?.emailAndPassword?.enabled) {\n\t\t\tctx.context.logger.error(\n\t\t\t\t\"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!\",\n\t\t\t);\n\t\t\tthrow new APIError(\"BAD_REQUEST\", {\n\t\t\t\tmessage: \"Email and password is not enabled\",\n\t\t\t});\n\t\t}\n\t\tconst { email, password } = ctx.body;\n\t\tconst isValidEmail = z.string().email().safeParse(email);\n\t\tif (!isValidEmail.success) {\n\t\t\tthrow new APIError(\"BAD_REQUEST\", {\n\t\t\t\tmessage: \"Invalid email\",\n\t\t\t});\n\t\t}\n\t\tconst checkEmail = z.string().email().safeParse(email);\n\t\tif (!checkEmail.success) {\n\t\t\tthrow new APIError(\"BAD_REQUEST\", {\n\t\t\t\tmessage: \"Invalid email\",\n\t\t\t});\n\t\t}\n\t\tconst user = await ctx.context.internalAdapter.findUserByEmail(email, {\n\t\t\tincludeAccounts: true,\n\t\t});\n\n\t\tif (!user) {\n\t\t\tawait ctx.context.password.hash(password);\n\t\t\tctx.context.logger.error(\"User not found\", { email });\n\t\t\tthrow new APIError(\"UNAUTHORIZED\", {\n\t\t\t\tmessage: \"Invalid email or password\",\n\t\t\t});\n\t\t}\n\n\t\tconst credentialAccount = user.accounts.find(\n\t\t\t(a) => a.providerId === \"credential\",\n\t\t);\n\t\tif (!credentialAccount) {\n\t\t\tctx.context.logger.error(\"Credential account not found\", { email });\n\t\t\tthrow new APIError(\"UNAUTHORIZED\", {\n\t\t\t\tmessage: \"Invalid email or password\",\n\t\t\t});\n\t\t}\n\t\tconst currentPassword = credentialAccount?.password;\n\t\tif (!currentPassword) {\n\t\t\tctx.context.logger.error(\"Password not found\", { email });\n\t\t\tthrow new APIError(\"UNAUTHORIZED\", {\n\t\t\t\tmessage: \"Unexpected error\",\n\t\t\t});\n\t\t}\n\t\tconst validPassword = await ctx.context.password.verify(\n\t\t\tcurrentPassword,\n\t\t\tpassword,\n\t\t);\n\t\tif (!validPassword) {\n\t\t\tctx.context.logger.error(\"Invalid password\");\n\t\t\tthrow new APIError(\"UNAUTHORIZED\", {\n\t\t\t\tmessage: \"Invalid email or password\",\n\t\t\t});\n\t\t}\n\n\t\tif (\n\t\t\tctx.context.options?.emailAndPassword?.requireEmailVerification &&\n\t\t\t!user.user.emailVerified\n\t\t) {\n\t\t\tif (!ctx.context.options?.emailVerification?.sendVerificationEmail) {\n\t\t\t\tlogger.error(\n\t\t\t\t\t\"Email verification is required but no email verification handler is provided\",\n\t\t\t\t);\n\t\t\t\tthrow new APIError(\"INTERNAL_SERVER_ERROR\", {\n\t\t\t\t\tmessage: \"Email is not verified.\",\n\t\t\t\t});\n\t\t\t}\n\t\t\tconst token = await createEmailVerificationToken(\n\t\t\t\tctx.context.secret,\n\t\t\t\tuser.user.email,\n\t\t\t);\n\t\t\tconst url = `${ctx.context.options.baseURL}/verify-email?token=${token}`;\n\t\t\tawait ctx.context.options.emailVerification.sendVerificationEmail(\n\t\t\t\tuser.user,\n\t\t\t\turl,\n\t\t\t\ttoken,\n\t\t\t);\n\t\t\tctx.context.logger.error(\"Email not verified\", { email });\n\t\t\tthrow new APIError(\"FORBIDDEN\", {\n\t\t\t\tmessage:\n\t\t\t\t\t\"Email is not verified. Check your email for a verification link\",\n\t\t\t});\n\t\t}\n\n\t\tconst session = await ctx.context.internalAdapter.createSession(\n\t\t\tuser.user.id,\n\t\t\tctx.headers,\n\t\t\tctx.body.dontRememberMe,\n\t\t);\n\n\t\tif (!session) {\n\t\t\tctx.context.logger.error(\"Failed to create session\");\n\t\t\tthrow new APIError(\"UNAUTHORIZED\", {\n\t\t\t\tmessage: \"Failed to create session\",\n\t\t\t});\n\t\t}\n\n\t\tawait setSessionCookie(\n\t\t\tctx,\n\t\t\t{\n\t\t\t\tsession,\n\t\t\t\tuser: user.user,\n\t\t\t},\n\t\t\tctx.body.dontRememberMe,\n\t\t);\n\t\treturn ctx.json({\n\t\t\tuser: user.user,\n\t\t\tsession,\n\t\t\tredirect: !!ctx.body.callbackURL,\n\t\t\turl: ctx.body.callbackURL,\n\t\t});\n\t},\n);\n","import { APIError } from \"better-call\";\nimport { createAuthMiddleware } from \"../call\";\nimport { logger } from \"../../utils/logger\";\n\n/**\n * Middleware to validate callbackURL and currentURL against trustedOrigins,\n * preventing open redirect attacks.\n */\nexport const redirectURLMiddleware = createAuthMiddleware(async (ctx) => {\n\tconst { body, query, context } = ctx;\n\n\tconst callbackURL =\n\t\tbody?.callbackURL ||\n\t\tquery?.callbackURL ||\n\t\tquery?.redirectTo ||\n\t\tbody?.redirectTo;\n\tconst currentURL = query?.currentURL;\n\tconst trustedOrigins = context.trustedOrigins;\n\n\tconst validateURL = (url: string | undefined, label: string) => {\n\t\tif (url?.startsWith(\"http\")) {\n\t\t\tconst isTrustedOrigin = trustedOrigins.some((origin) =>\n\t\t\t\turl.startsWith(origin),\n\t\t\t);\n\t\t\tif (!isTrustedOrigin) {\n\t\t\t\tlogger.error(`Invalid ${label}: ${url}`);\n\t\t\t\tlogger.info(\n\t\t\t\t\t`If it's a valid URL, please add ${url} to trustedOrigins in your auth config\\n`,\n\t\t\t\t\t`Current list of trustedOrigins: ${trustedOrigins}`,\n\t\t\t\t);\n\t\t\t\tthrow new APIError(\"FORBIDDEN\", { message: `Invalid ${label}` });\n\t\t\t}\n\t\t}\n\t};\n\n\tvalidateURL(callbackURL, \"callbackURL\");\n\tvalidateURL(currentURL, \"currentURL\");\n});\n","import { APIError, type Context } from \"better-call\";\nimport { createAuthEndpoint, createAuthMiddleware } from \"../call\";\nimport { getDate } from \"../../utils/date\";\nimport { deleteSessionCookie, setSessionCookie } from \"../../cookies\";\nimport { z } from \"zod\";\nimport type {\n\tBetterAuthOptions,\n\tInferSession,\n\tInferUser,\n\tPrettify,\n} from \"../../types\";\n\nexport const getSession = <Option extends BetterAuthOptions>() =>\n\tcreateAuthEndpoint(\n\t\t\"/get-session\",\n\t\t{\n\t\t\tmethod: \"GET\",\n\t\t\tquery: z.optional(\n\t\t\t\tz.object({\n\t\t\t\t\t/**\n\t\t\t\t\t * If cookie cache is enabled, it will disable the cache\n\t\t\t\t\t * and fetch the session from the database\n\t\t\t\t\t */\n\t\t\t\t\tdisableCookieCache: z.boolean().optional(),\n\t\t\t\t}),\n\t\t\t),\n\t\t\trequireHeaders: true,\n\t\t},\n\t\tasync (ctx) => {\n\t\t\ttry {\n\t\t\t\tconst sessionCookieToken = await ctx.getSignedCookie(\n\t\t\t\t\tctx.context.authCookies.sessionToken.name,\n\t\t\t\t\tctx.context.secret,\n\t\t\t\t);\n\t\t\t\tif (!sessionCookieToken) {\n\t\t\t\t\treturn ctx.json(null, {\n\t\t\t\t\t\tstatus: 401,\n\t\t\t\t\t});\n\t\t\t\t}\n\n\t\t\t\tconst sessionData = await ctx.getSignedCookie(\n\t\t\t\t\tctx.context.authCookies.sessionData.name,\n\t\t\t\t\tctx.context.secret,\n\t\t\t\t);\n\t\t\t\tconst dontRememberMe = await ctx.getSignedCookie(\n\t\t\t\t\tctx.context.authCookies.dontRememberToken.name,\n\t\t\t\t\tctx.context.secret,\n\t\t\t\t);\n\t\t\t\t/**\n\t\t\t\t * If session data is present in the cookie, return it\n\t\t\t\t */\n\t\t\t\tif (\n\t\t\t\t\tsessionData &&\n\t\t\t\t\tctx.context.options.session?.cookieCache?.enabled &&\n\t\t\t\t\t!ctx.query?.disableCookieCache\n\t\t\t\t) {\n\t\t\t\t\tconst session = JSON.parse(sessionData)?.session;\n\t\t\t\t\tif (session?.expiresAt > new Date()) {\n\t\t\t\t\t\treturn ctx.json(\n\t\t\t\t\t\t\tsession as {\n\t\t\t\t\t\t\t\tsession: InferSession<Option>;\n\t\t\t\t\t\t\t\tuser: InferUser<Option>;\n\t\t\t\t\t\t\t},\n\t\t\t\t\t\t);\n\t\t\t\t\t}\n\t\t\t\t}\n\n\t\t\t\tconst session =\n\t\t\t\t\tawait ctx.context.internalAdapter.findSession(sessionCookieToken);\n\n\t\t\t\tif (!session || session.session.expiresAt < new Date()) {\n\t\t\t\t\tdeleteSessionCookie(ctx);\n\t\t\t\t\tif (session) {\n\t\t\t\t\t\t/**\n\t\t\t\t\t\t * if session expired clean up the session\n\t\t\t\t\t\t */\n\t\t\t\t\t\tawait ctx.context.internalAdapter.deleteSession(session.session.id);\n\t\t\t\t\t}\n\t\t\t\t\treturn ctx.json(null, {\n\t\t\t\t\t\tstatus: 401,\n\t\t\t\t\t});\n\t\t\t\t}\n\n\t\t\t\t/**\n\t\t\t\t * We don't need to update the session if the user doesn't want to be remembered\n\t\t\t\t */\n\t\t\t\tif (dontRememberMe) {\n\t\t\t\t\treturn ctx.json(\n\t\t\t\t\t\tsession as unknown as {\n\t\t\t\t\t\t\tsession: InferSession<Option>;\n\t\t\t\t\t\t\tuser: InferUser<Option>;\n\t\t\t\t\t\t},\n\t\t\t\t\t);\n\t\t\t\t}\n\t\t\t\tconst expiresIn = ctx.context.sessionConfig.expiresIn;\n\t\t\t\tconst updateAge = ctx.context.sessionConfig.updateAge;\n\t\t\t\t/**\n\t\t\t\t * Calculate last updated date to throttle write updates to database\n\t\t\t\t * Formula: ({expiry date} - sessionMaxAge) + sessionUpdateAge\n\t\t\t\t *\n\t\t\t\t * e.g. ({expiry date} - 30 days) + 1 hour\n\t\t\t\t *\n\t\t\t\t * inspired by: https://github.com/nextauthjs/next-auth/blob/main/packages/core/src/lib/actions/session.ts\n\t\t\t\t */\n\t\t\t\tconst sessionIsDueToBeUpdatedDate =\n\t\t\t\t\tsession.session.expiresAt.valueOf() -\n\t\t\t\t\texpiresIn * 1000 +\n\t\t\t\t\tupdateAge * 1000;\n\t\t\t\tconst shouldBeUpdated = sessionIsDueToBeUpdatedDate <= Date.now();\n\n\t\t\t\tif (shouldBeUpdated) {\n\t\t\t\t\tconst updatedSession =\n\t\t\t\t\t\tawait ctx.context.internalAdapter.updateSession(\n\t\t\t\t\t\t\tsession.session.id,\n\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\texpiresAt: getDate(ctx.context.sessionConfig.expiresIn, \"sec\"),\n\t\t\t\t\t\t\t},\n\t\t\t\t\t\t);\n\t\t\t\t\tif (!updatedSession) {\n\t\t\t\t\t\t/**\n\t\t\t\t\t\t * Handle case where session update fails (e.g., concurrent deletion)\n\t\t\t\t\t\t */\n\t\t\t\t\t\tdeleteSessionCookie(ctx);\n\t\t\t\t\t\treturn ctx.json(null, { status: 401 });\n\t\t\t\t\t}\n\t\t\t\t\tconst maxAge =\n\t\t\t\t\t\t(updatedSession.expiresAt.valueOf() - Date.now()) / 1000;\n\t\t\t\t\tawait setSessionCookie(\n\t\t\t\t\t\tctx,\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\tsession: updatedSession,\n\t\t\t\t\t\t\tuser: session.user,\n\t\t\t\t\t\t},\n\t\t\t\t\t\tfalse,\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\tmaxAge,\n\t\t\t\t\t\t},\n\t\t\t\t\t);\n\t\t\t\t\treturn ctx.json({\n\t\t\t\t\t\tsession: updatedSession,\n\t\t\t\t\t\tuser: session.user,\n\t\t\t\t\t} as unknown as {\n\t\t\t\t\t\tsession: InferSession<Option>;\n\t\t\t\t\t\tuser: InferUser<Option>;\n\t\t\t\t\t});\n\t\t\t\t}\n\n\t\t\t\treturn ctx.json(\n\t\t\t\t\tsession as unknown as {\n\t\t\t\t\t\tsession: InferSession<Option>;\n\t\t\t\t\t\tuser: InferUser<Option>;\n\t\t\t\t\t},\n\t\t\t\t);\n\t\t\t} catch (error) {\n\t\t\t\tctx.context.logger.error(error);\n\t\t\t\treturn ctx.json(null, { status: 500 });\n\t\t\t}\n\t\t},\n\t);\n\nexport const getSessionFromCtx = async (ctx: Context<any, any>) => {\n\t//@ts-ignore\n\tconst session = await getSession()({\n\t\t...ctx,\n\t\t_flag: \"json\",\n\t\theaders: ctx.headers!,\n\t});\n\n\treturn session;\n};\n\nexport const sessionMiddleware = createAuthMiddleware(async (ctx) => {\n\tconst session = await getSessionFromCtx(ctx);\n\tif (!session?.session) {\n\t\tthrow new APIError(\"UNAUTHORIZED\");\n\t}\n\treturn {\n\t\tsession,\n\t};\n});\n\n/**\n * user active sessions list\n */\nexport const listSessions = <Option extends BetterAuthOptions>() =>\n\tcreateAuthEndpoint(\n\t\t\"/user/list-sessions\",\n\t\t{\n\t\t\tmethod: \"GET\",\n\t\t\tuse: [sessionMiddleware],\n\t\t\trequireHeaders: true,\n\t\t},\n\t\tasync (ctx) => {\n\t\t\tconst sessions = await ctx.context.internalAdapter.listSessions(\n\t\t\t\tctx.context.session.user.id,\n\t\t\t);\n\t\t\tconst activeSessions = sessions.filter((session) => {\n\t\t\t\treturn session.expiresAt > new Date();\n\t\t\t});\n\t\t\treturn ctx.json(\n\t\t\t\tactiveSessions as unknown as Prettify<InferSession<Option>>[],\n\t\t\t);\n\t\t},\n\t);\n\n/**\n * revoke a single session\n */\nexport const revokeSession = createAuthEndpoint(\n\t\"/user/revoke-session\",\n\t{\n\t\tmethod: \"POST\",\n\t\tbody: z.object({\n\t\t\tid: z.string(),\n\t\t}),\n\t\tuse: [sessionMiddleware],\n\t\trequireHeaders: true,\n\t},\n\tasync (ctx) => {\n\t\tconst id = ctx.body.id;\n\t\tconst findSession = await ctx.context.internalAdapter.findSession(id);\n\t\tif (!findSession) {\n\t\t\tthrow new APIError(\"BAD_REQUEST\", {\n\t\t\t\tmessage: \"Session not found\",\n\t\t\t});\n\t\t}\n\t\tif (findSession.session.userId !== ctx.context.session.user.id) {\n\t\t\tthrow new APIError(\"UNAUTHORIZED\");\n\t\t}\n\t\ttry {\n\t\t\tawait ctx.context.internalAdapter.deleteSession(id);\n\t\t} catch (error) {\n\t\t\tctx.context.logger.error(error);\n\t\t\tthrow new APIError(\"INTERNAL_SERVER_ERROR\");\n\t\t}\n\t\treturn ctx.json({\n\t\t\tstatus: true,\n\t\t});\n\t},\n);\n/**\n * revoke all user sessions\n */\nexport const revokeSessions = createAuthEndpoint(\n\t\"/user/revoke-sessions\",\n\t{\n\t\tmethod: \"POST\",\n\t\tuse: [sessionMiddleware],\n\t\trequireHeaders: true,\n\t},\n\tasync (ctx) => {\n\t\ttry {\n\t\t\tawait ctx.context.internalAdapter.deleteSessions(\n\t\t\t\tctx.context.session.user.id,\n\t\t\t);\n\t\t} catch (error) {\n\t\t\tctx.context.logger.error(error);\n\t\t\tthrow new APIError(\"INTERNAL_SERVER_ERROR\");\n\t\t}\n\t\treturn ctx.json({\n\t\t\tstatus: true,\n\t\t});\n\t},\n);\n","import { z } from \"zod\";\nimport { createAuthEndpoint } from \"../call\";\nimport { deleteSessionCookie } from \"../../cookies\";\nimport { APIError } from \"better-call\";\nimport { redirectURLMiddleware } from \"../middlewares/redirect\";\n\nexport const signOut = createAuthEndpoint(\n\t\"/sign-out\",\n\t{\n\t\tmethod: \"POST\",\n\t},\n\tasync (ctx) => {\n\t\tconst sessionCookieToken = await ctx.getSignedCookie(\n\t\t\tctx.context.authCookies.sessionToken.name,\n\t\t\tctx.context.secret,\n\t\t);\n\t\tif (!sessionCookieToken) {\n\t\t\tthrow new APIError(\"BAD_REQUEST\", {\n\t\t\t\tmessage: \"Session not found\",\n\t\t\t});\n\t\t}\n\t\tawait ctx.context.internalAdapter.deleteSession(sessionCookieToken);\n\t\tdeleteSessionCookie(ctx);\n\t\treturn ctx.json({\n\t\t\tsuccess: true,\n\t\t});\n\t},\n);\n","import { HIDE_METADATA } from \"../../utils/hide-metadata\";\nimport { createAuthEndpoint } from \"../call\";\n\nconst html = (errorCode: string = \"Unknown\") => `<!DOCTYPE html>\n<html lang=\"en\">\n<head>\n <meta charset=\"UTF-8\">\n <meta name=\"viewport\" content=\"width=device-width, initial-scale=1.0\">\n <title>Authentication Error</title>\n <style>\n :root {\n --bg-color: #f8f9fa;\n --text-color: #212529;\n --accent-color: #000000;\n --error-color: #dc3545;\n --border-color: #e9ecef;\n }\n body {\n font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, 'Helvetica Neue', Arial, sans-serif;\n background-color: var(--bg-color);\n color: var(--text-color);\n display: flex;\n justify-content: center;\n align-items: center;\n height: 100vh;\n margin: 0;\n line-height: 1.5;\n }\n .error-container {\n background-color: #ffffff;\n border-radius: 12px;\n box-shadow: 0 4px 6px rgba(0, 0, 0, 0.05);\n padding: 2.5rem;\n text-align: center;\n max-width: 90%;\n width: 400px;\n }\n h1 {\n color: var(--error-color);\n font-size: 1.75rem;\n margin-bottom: 1rem;\n font-weight: 600;\n }\n p {\n margin-bottom: 1.5rem;\n color: #495057;\n }\n .btn {\n background-color: var(--accent-color);\n color: #ffffff;\n text-decoration: none;\n padding: 0.75rem 1.5rem;\n border-radius: 6px;\n transition: all 0.3s ease;\n display: inline-block;\n font-weight: 500;\n border: 2px solid var(--accent-color);\n }\n .btn:hover {\n background-color: #131721;\n }\n .error-code {\n font-size: 0.875rem;\n color: #6c757d;\n margin-top: 1.5rem;\n padding-top: 1.5rem;\n border-top: 1px solid var(--border-color);\n }\n .icon {\n font-size: 3rem;\n margin-bottom: 1rem;\n }\n </style>\n</head>\n<body>\n <div class=\"error-container\">\n <div class=\"icon\">⚠️</div>\n <h1>Better Auth Error</h1>\n <p>We encountered an issue while processing your request. Please try again or contact the application owner if the problem persists.</p>\n <a href=\"/\" id=\"returnLink\" class=\"btn\">Return to Application</a>\n <div class=\"error-code\">Error Code: <span id=\"errorCode\">${errorCode}</span></div>\n </div>\n</body>\n</html>`;\n\nexport const error = createAuthEndpoint(\n\t\"/error\",\n\t{\n\t\tmethod: \"GET\",\n\t\tmetadata: HIDE_METADATA,\n\t},\n\tasync (c) => {\n\t\tconst query =\n\t\t\tnew URL(c.request?.url || \"\").searchParams.get(\"error\") || \"Unknown\";\n\t\treturn new Response(html(query), {\n\t\t\theaders: {\n\t\t\t\t\"Content-Type\": \"text/html\",\n\t\t\t},\n\t\t});\n\t},\n);\n","import { z, ZodObject, ZodOptional, ZodString } from \"zod\";\nimport { createAuthEndpoint } from \"../call\";\nimport { createEmailVerificationToken } from \"./email-verification\";\nimport { setSessionCookie } from \"../../cookies\";\nimport { APIError } from \"better-call\";\nimport type {\n\tAdditionalUserFieldsInput,\n\tBetterAuthOptions,\n\tInferSession,\n\tInferUser,\n\tUser,\n} from \"../../types\";\nimport type { toZod } from \"../../types/to-zod\";\nimport { parseUserInput } from \"../../db/schema\";\nimport { getDate } from \"../../utils/date\";\nimport { redirectURLMiddleware } from \"../middlewares/redirect\";\nimport { logger } from \"../../utils\";\n\nexport const signUpEmail = <O extends BetterAuthOptions>() =>\n\tcreateAuthEndpoint(\n\t\t\"/sign-up/email\",\n\t\t{\n\t\t\tmethod: \"POST\",\n\t\t\tquery: z\n\t\t\t\t.object({\n\t\t\t\t\tcurrentURL: z.string().optional(),\n\t\t\t\t})\n\t\t\t\t.optional(),\n\t\t\tbody: z.record(z.string(), z.any()) as unknown as ZodObject<{\n\t\t\t\tname: ZodString;\n\t\t\t\temail: ZodString;\n\t\t\t\tpassword: ZodString;\n\t\t\t\tcallbackURL: ZodOptional<ZodString>;\n\t\t\t}> &\n\t\t\t\ttoZod<AdditionalUserFieldsInput<O>>,\n\t\t\tuse: [redirectURLMiddleware],\n\t\t},\n\t\tasync (ctx) => {\n\t\t\tif (!ctx.context.options.emailAndPassword?.enabled) {\n\t\t\t\tthrow new APIError(\"BAD_REQUEST\", {\n\t\t\t\t\tmessage: \"Email and password sign up is not enabled\",\n\t\t\t\t});\n\t\t\t}\n\t\t\tconst body = ctx.body as any as User & {\n\t\t\t\tpassword: string;\n\t\t\t\tcallbackURL?: string;\n\t\t\t} & {\n\t\t\t\t[key: string]: any;\n\t\t\t};\n\t\t\tconst { name, email, password, image, callbackURL, ...additionalFields } =\n\t\t\t\tbody;\n\t\t\tconst isValidEmail = z.string().email().safeParse(email);\n\n\t\t\tif (!isValidEmail.success) {\n\t\t\t\tthrow new APIError(\"BAD_REQUEST\", {\n\t\t\t\t\tmessage: \"Invalid email\",\n\t\t\t\t});\n\t\t\t}\n\n\t\t\tconst minPasswordLength = ctx.context.password.config.minPasswordLength;\n\t\t\tif (password.length < minPasswordLength) {\n\t\t\t\tctx.context.logger.error(\"Password is too short\");\n\t\t\t\tthrow new APIError(\"BAD_REQUEST\", {\n\t\t\t\t\tmessage: \"Password is too short\",\n\t\t\t\t});\n\t\t\t}\n\n\t\t\tconst maxPasswordLength = ctx.context.password.config.maxPasswordLength;\n\t\t\tif (password.length > maxPasswordLength) {\n\t\t\t\tctx.context.logger.error(\"Password is too long\");\n\t\t\t\tthrow new APIError(\"BAD_REQUEST\", {\n\t\t\t\t\tmessage: \"Password is too long\",\n\t\t\t\t});\n\t\t\t}\n\t\t\tconst dbUser = await ctx.context.internalAdapter.findUserByEmail(email);\n\t\t\tif (dbUser?.user) {\n\t\t\t\tctx.context.logger.info(`Sign-up attempt for existing email: ${email}`);\n\t\t\t\tthrow new APIError(\"UNPROCESSABLE_ENTITY\", {\n\t\t\t\t\tmessage: \"User with this email already exists\",\n\t\t\t\t});\n\t\t\t}\n\n\t\t\tconst additionalData = parseUserInput(\n\t\t\t\tctx.context.options,\n\t\t\t\tadditionalFields as any,\n\t\t\t);\n\t\t\tlet createdUser: User;\n\t\t\ttry {\n\t\t\t\tcreatedUser = await ctx.context.internalAdapter.createUser({\n\t\t\t\t\temail: email.toLowerCase(),\n\t\t\t\t\tname,\n\t\t\t\t\timage,\n\t\t\t\t\t...additionalData,\n\t\t\t\t\temailVerified: false,\n\t\t\t\t});\n\t\t\t\tif (!createdUser) {\n\t\t\t\t\tthrow new APIError(\"BAD_REQUEST\", {\n\t\t\t\t\t\tmessage: \"Failed to create user\",\n\t\t\t\t\t});\n\t\t\t\t}\n\t\t\t} catch (e) {\n\t\t\t\tlogger.error(\"Failed to create user\", e);\n\t\t\t\tthrow new APIError(\"UNPROCESSABLE_ENTITY\", {\n\t\t\t\t\tmessage: \"Failed to create user\",\n\t\t\t\t\tdetails: e,\n\t\t\t\t});\n\t\t\t}\n\t\t\tif (!createdUser) {\n\t\t\t\tthrow new APIError(\"UNPROCESSABLE_ENTITY\", {\n\t\t\t\t\tmessage: \"Failed to create user\",\n\t\t\t\t});\n\t\t\t}\n\t\t\t/**\n\t\t\t * Link the account to the user\n\t\t\t */\n\t\t\tconst hash = await ctx.context.password.hash(password);\n\t\t\tawait ctx.context.internalAdapter.linkAccount({\n\t\t\t\tuserId: createdUser.id,\n\t\t\t\tproviderId: \"credential\",\n\t\t\t\taccountId: createdUser.id,\n\t\t\t\tpassword: hash,\n\t\t\t\texpiresAt: getDate(60 * 60 * 24 * 30, \"sec\"),\n\t\t\t});\n\t\t\tif (ctx.context.options.emailVerification?.sendOnSignUp) {\n\t\t\t\tconst token = await createEmailVerificationToken(\n\t\t\t\t\tctx.context.secret,\n\t\t\t\t\tcreatedUser.email,\n\t\t\t\t);\n\t\t\t\tconst url = `${\n\t\t\t\t\tctx.context.baseURL\n\t\t\t\t}/verify-email?token=${token}&callbackURL=${\n\t\t\t\t\tbody.callbackURL || ctx.query?.currentURL || \"/\"\n\t\t\t\t}`;\n\t\t\t\tawait ctx.context.options.emailVerification?.sendVerificationEmail?.(\n\t\t\t\t\tcreatedUser,\n\t\t\t\t\turl,\n\t\t\t\t\ttoken,\n\t\t\t\t);\n\t\t\t}\n\n\t\t\tif (\n\t\t\t\t!ctx.context.options.emailAndPassword.autoSignIn ||\n\t\t\t\tctx.context.options.emailAndPassword.requireEmailVerification\n\t\t\t) {\n\t\t\t\treturn ctx.json(\n\t\t\t\t\t{\n\t\t\t\t\t\tuser: createdUser as InferUser<O>,\n\t\t\t\t\t\tsession: null,\n\t\t\t\t\t},\n\t\t\t\t\t{\n\t\t\t\t\t\tbody: body.callbackURL\n\t\t\t\t\t\t\t? {\n\t\t\t\t\t\t\t\t\turl: body.callbackURL,\n\t\t\t\t\t\t\t\t\tredirect: true,\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t: {\n\t\t\t\t\t\t\t\t\tuser: createdUser,\n\t\t\t\t\t\t\t\t\tsession: null,\n\t\t\t\t\t\t\t\t},\n\t\t\t\t\t},\n\t\t\t\t);\n\t\t\t}\n\n\t\t\tconst session = await ctx.context.internalAdapter.createSession(\n\t\t\t\tcreatedUser.id,\n\t\t\t\tctx.request,\n\t\t\t);\n\t\t\tif (!session) {\n\t\t\t\tthrow new APIError(\"BAD_REQUEST\", {\n\t\t\t\t\tmessage: \"Failed to create session\",\n\t\t\t\t});\n\t\t\t}\n\t\t\tawait setSessionCookie(ctx, {\n\t\t\t\tsession,\n\t\t\t\tuser: createdUser,\n\t\t\t});\n\t\t\treturn ctx.json(\n\t\t\t\t{\n\t\t\t\t\tuser: createdUser as InferUser<O>,\n\t\t\t\t\tsession: session as InferSession<O>,\n\t\t\t\t},\n\t\t\t\t{\n\t\t\t\t\tbody: body.callbackURL\n\t\t\t\t\t\t? {\n\t\t\t\t\t\t\t\turl: body.callbackURL,\n\t\t\t\t\t\t\t\tredirect: true,\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t: {\n\t\t\t\t\t\t\t\tuser: createdUser,\n\t\t\t\t\t\t\t\tsession,\n\t\t\t\t\t\t\t},\n\t\t\t\t},\n\t\t\t);\n\t\t},\n\t);\n"]}
|
|
@@ -0,0 +1,84 @@
|
|
|
1
|
+
import{a as re}from"./chunk-57KKPQYR.js";import{h as C,n as Z}from"./chunk-UMXT2JXJ.js";import{b as h,c as oe}from"./chunk-L3RMKKWR.js";import{a as te,b as F,c as G}from"./chunk-4X5O2226.js";import{a as Q}from"./chunk-TUL3AUOB.js";import{h as X,i as ee,j as M}from"./chunk-CO5UG7AX.js";import{c as L,d as _}from"./chunk-4CY5SJAH.js";import{APIError as De,createRouter as ot,statusCode as rt}from"better-call";import{APIError as J}from"better-call";import{z as ie}from"zod";import{createEndpointCreator as qe,createMiddleware as se,createMiddlewareCreator as je}from"better-call";var ne=se(async()=>({})),B=je({use:[ne,se(async()=>({}))]}),p=qe({use:[ne]});var ae=B({body:ie.object({csrfToken:ie.string().optional()}).optional()},async e=>{if(e.request?.method!=="POST"||e.context.options.advanced?.disableCSRFCheck)return;let t=e.headers?.get("origin")||"";if(t){let d=new URL(t).origin;if(e.context.trustedOrigins.includes(d))return}let o=e.body?.csrfToken;if(!o)throw new J("UNAUTHORIZED",{message:"CSRF Token is required"});let s=await e.getSignedCookie(e.context.authCookies.csrfToken.name,e.context.secret),[r,n]=s?.split("!")||[null,null];if(!o||!r||!n||r!==o)throw new J("UNAUTHORIZED",{message:"Invalid CSRF Token"});let i=await M(e.context.secret,r);if(n!==i)throw e.setCookie(e.context.authCookies.csrfToken.name,"",{maxAge:0}),new J("UNAUTHORIZED",{message:"Invalid CSRF Token"})});import{APIError as O}from"better-call";import{generateCodeVerifier as Fe}from"oslo/oauth2";import{z as S}from"zod";import{APIError as Ve}from"better-call";var b=B(async e=>{let{body:t,query:o,context:s}=e,r=t?.callbackURL||o?.callbackURL||o?.redirectTo||t?.redirectTo,n=o?.currentURL,i=s.trustedOrigins,d=(c,a)=>{if(c?.startsWith("http")&&!i.some(w=>c.startsWith(w)))throw h.error(`Invalid ${a}: ${c}`),h.info(`If it's a valid URL, please add ${c} to trustedOrigins in your auth config
|
|
2
|
+
`,`Current list of trustedOrigins: ${i}`),new Ve("FORBIDDEN",{message:`Invalid ${a}`})};d(r,"callbackURL"),d(n,"currentURL")});import{TimeSpan as $e}from"oslo";import{createJWT as Ne,validateJWT as Me}from"oslo/jwt";import{z as I}from"zod";import{APIError as q}from"better-call";import{APIError as V}from"better-call";import{z as $}from"zod";var Y=()=>p("/get-session",{method:"GET",query:$.optional($.object({disableCookieCache:$.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 o=await e.getSignedCookie(e.context.authCookies.sessionData.name,e.context.secret),s=await e.getSignedCookie(e.context.authCookies.dontRememberToken.name,e.context.secret);if(o&&e.context.options.session?.cookieCache?.enabled&&!e.query?.disableCookieCache){let a=JSON.parse(o)?.session;if(a?.expiresAt>new Date)return e.json(a)}let r=await e.context.internalAdapter.findSession(t);if(!r||r.session.expiresAt<new Date)return _(e),r&&await e.context.internalAdapter.deleteSession(r.session.id),e.json(null,{status:401});if(s)return e.json(r);let n=e.context.sessionConfig.expiresIn,i=e.context.sessionConfig.updateAge;if(r.session.expiresAt.valueOf()-n*1e3+i*1e3<=Date.now()){let a=await e.context.internalAdapter.updateSession(r.session.id,{expiresAt:Q(e.context.sessionConfig.expiresIn,"sec")});if(!a)return _(e),e.json(null,{status:401});let l=(a.expiresAt.valueOf()-Date.now())/1e3;return await L(e,{session:a,user:r.user},!1,{maxAge:l}),e.json({session:a,user:r.user})}return e.json(r)}catch(t){return e.context.logger.error(t),e.json(null,{status:500})}}),K=async e=>await Y()({...e,_flag:"json",headers:e.headers}),E=B(async e=>{let t=await K(e);if(!t?.session)throw new V("UNAUTHORIZED");return{session:t}}),de=()=>p("/user/list-sessions",{method:"GET",use:[E],requireHeaders:!0},async e=>{let o=(await e.context.internalAdapter.listSessions(e.context.session.user.id)).filter(s=>s.expiresAt>new Date);return e.json(o)}),ce=p("/user/revoke-session",{method:"POST",body:$.object({id:$.string()}),use:[E],requireHeaders:!0},async e=>{let t=e.body.id,o=await e.context.internalAdapter.findSession(t);if(!o)throw new V("BAD_REQUEST",{message:"Session not found"});if(o.session.userId!==e.context.session.user.id)throw new V("UNAUTHORIZED");try{await e.context.internalAdapter.deleteSession(t)}catch(s){throw e.context.logger.error(s),new V("INTERNAL_SERVER_ERROR")}return e.json({status:!0})}),le=p("/user/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 V("INTERNAL_SERVER_ERROR")}return e.json({status:!0})});async function v(e,t,o){return await Ne("HS256",Buffer.from(e),{email:t.toLowerCase(),updateTo:o},{expiresIn:new $e(1,"h"),issuer:"better-auth",subject:"verify-email",audiences:[t],includeIssuedTimestamp:!0})}var ue=p("/send-verification-email",{method:"POST",query:I.object({currentURL:I.string().optional()}).optional(),body:I.object({email:I.string().email(),callbackURL:I.string().optional()}),use:[b]},async e=>{if(!e.context.options.emailVerification?.sendVerificationEmail)throw e.context.logger.error("Verification email isn't enabled."),new q("BAD_REQUEST",{message:"Verification email isn't enabled"});let{email:t}=e.body,o=await e.context.internalAdapter.findUserByEmail(t);if(!o)throw new q("BAD_REQUEST",{message:"User not found"});let s=await v(e.context.secret,t),r=`${e.context.baseURL}/verify-email?token=${s}&callbackURL=${e.body.callbackURL||e.query?.currentURL||"/"}`;return await e.context.options.emailVerification.sendVerificationEmail(o.user,r,s),e.json({status:!0})}),pe=p("/verify-email",{method:"GET",query:I.object({token:I.string(),callbackURL:I.string().optional()}),use:[b]},async e=>{let{token:t}=e.query,o;try{o=await Me("HS256",Buffer.from(e.context.secret),t)}catch(i){throw e.context.logger.error("Failed to verify email",i),new q("BAD_REQUEST",{message:"Invalid token"})}let r=I.object({email:I.string().email(),updateTo:I.string().optional()}).parse(o.payload);if(!await e.context.internalAdapter.findUserByEmail(r.email))throw new q("BAD_REQUEST",{message:"User not found"});if(r.updateTo){let i=await K(e);if(!i)throw e.query.callbackURL?e.redirect(`${e.query.callbackURL}?error=unauthorized`):new q("UNAUTHORIZED",{message:"Session not found"});if(i.user.email!==r.email)throw e.query.callbackURL?e.redirect(`${e.query.callbackURL}?error=unauthorized`):new q("UNAUTHORIZED",{message:"Invalid session"});let d=await e.context.internalAdapter.updateUserByEmail(r.email,{email:r.updateTo});if(await e.context.options.emailVerification?.sendVerificationEmail?.(d,`${e.context.baseURL}/verify-email?token=${t}`,t),e.query.callbackURL)throw e.redirect(e.query.callbackURL);return e.json({user:d,status:!0})}if(await e.context.internalAdapter.updateUserByEmail(r.email,{emailVerified:!0}),e.query.callbackURL)throw e.redirect(e.query.callbackURL);return e.json({user:null,status:!0})});var me=p("/sign-in/social",{method:"POST",requireHeaders:!0,query:S.object({currentURL:S.string().optional()}).optional(),body:S.object({callbackURL:S.string().optional(),provider:S.enum(Z)}),use:[b]},async e=>{let t=e.context.socialProviders.find(c=>c.id===e.body.provider);if(!t)throw e.context.logger.error("Provider not found. Make sure to add the provider in your auth config",{provider:e.body.provider}),new O("NOT_FOUND",{message:"Provider not found"});let o=e.context.authCookies,s=e.query?.currentURL?new URL(e.query?.currentURL):null,r=e.body.callbackURL?.startsWith("http")?e.body.callbackURL:`${s?.origin}${e.body.callbackURL||""}`,n=await F(r||s?.origin||e.context.options.baseURL);await e.setSignedCookie(o.state.name,n.hash,e.context.secret,o.state.options);let i=Fe();await e.setSignedCookie(o.pkCodeVerifier.name,i,e.context.secret,o.pkCodeVerifier.options);let d=await t.createAuthorizationURL({state:n.raw,codeVerifier:i,redirectURI:`${e.context.baseURL}/callback/${t.id}`});return e.json({url:d.toString(),state:n,codeVerifier:i,redirect:!0})}),fe=p("/sign-in/email",{method:"POST",body:S.object({email:S.string(),password:S.string(),callbackURL:S.string().optional(),dontRememberMe:S.boolean().default(!1).optional()}),use:[b]},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("BAD_REQUEST",{message:"Email and password is not enabled"});let{email:t,password:o}=e.body;if(!S.string().email().safeParse(t).success)throw new O("BAD_REQUEST",{message:"Invalid email"});if(!S.string().email().safeParse(t).success)throw new O("BAD_REQUEST",{message:"Invalid email"});let n=await e.context.internalAdapter.findUserByEmail(t,{includeAccounts:!0});if(!n)throw await e.context.password.hash(o),e.context.logger.error("User not found",{email:t}),new O("UNAUTHORIZED",{message:"Invalid email or password"});let i=n.accounts.find(l=>l.providerId==="credential");if(!i)throw e.context.logger.error("Credential account not found",{email:t}),new O("UNAUTHORIZED",{message:"Invalid email or password"});let d=i?.password;if(!d)throw e.context.logger.error("Password not found",{email:t}),new O("UNAUTHORIZED",{message:"Unexpected error"});if(!await e.context.password.verify(d,o))throw e.context.logger.error("Invalid password"),new O("UNAUTHORIZED",{message:"Invalid email or password"});if(e.context.options?.emailAndPassword?.requireEmailVerification&&!n.user.emailVerified){if(!e.context.options?.emailVerification?.sendVerificationEmail)throw h.error("Email verification is required but no email verification handler is provided"),new O("INTERNAL_SERVER_ERROR",{message:"Email is not verified."});let l=await v(e.context.secret,n.user.email),w=`${e.context.options.baseURL}/verify-email?token=${l}`;throw await e.context.options.emailVerification.sendVerificationEmail(n.user,w,l),e.context.logger.error("Email not verified",{email:t}),new O("FORBIDDEN",{message:"Email is not verified. Check your email for a verification link"})}let a=await e.context.internalAdapter.createSession(n.user.id,e.headers,e.body.dontRememberMe);if(!a)throw e.context.logger.error("Failed to create session"),new O("UNAUTHORIZED",{message:"Failed to create session"});return await L(e,{session:a,user:n.user},e.body.dontRememberMe),e.json({user:n.user,session:a,redirect:!!e.body.callbackURL,url:e.body.callbackURL})});import{z}from"zod";import{z as m}from"zod";var Zt=m.object({id:m.string(),providerId:m.string(),accountId:m.string(),userId:m.string(),accessToken:m.string().nullable().optional(),refreshToken:m.string().nullable().optional(),idToken:m.string().nullable().optional(),expiresAt:m.date().nullable().optional(),password:m.string().optional().nullable()}),we=m.object({id:m.string(),email:m.string().transform(e=>e.toLowerCase()),emailVerified:m.boolean().default(!1),name:m.string(),image:m.string().optional(),createdAt:m.date().default(new Date),updatedAt:m.date().default(new Date)}),Ht=m.object({id:m.string(),userId:m.string(),expiresAt:m.date(),ipAddress:m.string().optional(),userAgent:m.string().optional()}),zt=m.object({id:m.string(),value:m.string(),expiresAt:m.date(),identifier:m.string()});function Qe(e,t){let o={...t==="user"?e.user?.additionalFields:{},...t==="session"?e.session?.additionalFields:{}};for(let s of e.plugins||[])s.schema&&s.schema[t]&&(o={...o,...s.schema[t].fields});return o}function Ze(e,t){let o=t.action||"create",s=t.fields,r={};for(let n in s){if(n in e){if(s[n].input===!1){if(s[n].defaultValue){r[n]=s[n].defaultValue;continue}continue}r[n]=e[n];continue}if(s[n].defaultValue&&o==="create"){r[n]=s[n].defaultValue;continue}}return r}function H(e,t,o){let s=Qe(e,"user");return Ze(t||{},{fields:s,action:o})}import{isDevelopment as He}from"std-env";var ge=p("/callback/:id",{method:"GET",query:z.object({state:z.string(),code:z.string().optional(),error:z.string().optional()}),metadata:C},async e=>{if(e.query.error||!e.query.code){let T=G(e.query.state).data?.callbackURL||`${e.context.baseURL}/error`;throw e.context.logger.error(e.query.error,e.params.id),e.redirect(`${T}?error=${e.query.error||"oAuth_code_missing"}`)}let t=e.context.socialProviders.find(f=>f.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 o=G(e.query.state);if(!o.success)throw e.context.logger.error("Unable to parse state"),e.redirect(`${e.context.baseURL}/error?error=please_restart_the_process`);let{data:{callbackURL:s,currentURL:r,link:n}}=o,i=await e.getSignedCookie(e.context.authCookies.state.name,e.context.secret);if(!i)throw h.error("No stored state found"),e.redirect(`${e.context.baseURL}/error?error=please_restart_the_process`);if(!await te(e.query.state,i))throw h.error("OAuth state mismatch"),e.redirect(`${e.context.baseURL}/error?error=please_restart_the_process`);let c=await e.getSignedCookie(e.context.authCookies.pkCodeVerifier.name,e.context.secret),a;try{a=await t.validateAuthorizationCode({code:e.query.code,codeVerifier:c,redirectURI:`${e.context.baseURL}/callback/${t.id}`})}catch(f){throw e.context.logger.error(f),e.redirect(`${e.context.baseURL}/error?error=please_restart_the_process`)}let l=await t.getUserInfo(a).then(f=>f?.user),w=oe(),y=we.safeParse({...l,id:w});if(!l||y.success===!1)throw h.error("Unable to get user info",y.error),e.redirect(`${e.context.baseURL}/error?error=please_restart_the_process`);if(!s)throw h.error("No callback URL found"),e.redirect(`${e.context.baseURL}/error?error=please_restart_the_process`);if(n){if(n.email!==l.email.toLowerCase())return u("email_doesn't_match");if(!await e.context.internalAdapter.createAccount({userId:n.userId,providerId:t.id,accountId:l.id}))return u("unable_to_link_account");throw e.redirect(s||r||e.context.options.baseURL)}function u(f){throw e.redirect(`${r||s||`${e.context.baseURL}/error`}?error=${f}`)}let A=await e.context.internalAdapter.findUserByEmail(l.email,{includeAccounts:!0}).catch(f=>{throw h.error(`Better auth was unable to query your database.
|
|
3
|
+
Error: `,f),e.redirect(`${e.context.baseURL}/error?error=internal_server_error`)}),R=A?.user;if(A){let f=A.accounts.find(T=>T.providerId===t.id);if(f)await e.context.internalAdapter.updateAccount(f.id,{accessToken:a.accessToken,idToken:a.idToken,refreshToken:a.refreshToken,expiresAt:a.accessTokenExpiresAt});else{(!e.context.options.account?.accountLinking?.trustedProviders?.includes(t.id)&&!l.emailVerified||!e.context.options.account?.accountLinking?.enabled)&&(He&&h.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.`),u("account_not_linked"));try{await e.context.internalAdapter.linkAccount({providerId:t.id,accountId:l.id.toString(),id:`${t.id}:${l.id}`,userId:A.user.id,accessToken:a.accessToken,idToken:a.idToken,refreshToken:a.refreshToken,expiresAt:a.accessTokenExpiresAt})}catch(Be){h.error("Unable to link account",Be),u("unable_to_link_account")}}}else try{let f=l.emailVerified||!1;if(R=await e.context.internalAdapter.createOAuthUser({...y.data,emailVerified:f},{accessToken:a.accessToken,idToken:a.idToken,refreshToken:a.refreshToken,expiresAt:a.accessTokenExpiresAt,providerId:t.id,accountId:l.id.toString()}).then(T=>T?.user),!f&&R&&e.context.options.emailVerification?.sendOnSignUp){let T=await v(e.context.secret,R.email),D=`${e.context.baseURL}/verify-email?token=${T}&callbackURL=${s}`;await e.context.options.emailVerification?.sendVerificationEmail?.(R,D,T)}}catch(f){h.error("Unable to create user",f),u("unable_to_create_user")}if(!R)return u("unable_to_create_user");let g=await e.context.internalAdapter.createSession(R.id,e.request);throw g||u("unable_to_create_session"),await L(e,{session:g,user:R}),console.log({redirectingTO:s}),e.redirect(s)});import"zod";import{APIError as ze}from"better-call";var he=p("/sign-out",{method:"POST"},async e=>{let t=await e.getSignedCookie(e.context.authCookies.sessionToken.name,e.context.secret);if(!t)throw new ze("BAD_REQUEST",{message:"Session not found"});return await e.context.internalAdapter.deleteSession(t),_(e),e.json({success:!0})});import{z as P}from"zod";import{APIError as W}from"better-call";var ye=p("/forget-password",{method:"POST",body:P.object({email:P.string().email(),redirectTo:P.string()}),use:[b]},async e=>{if(!e.context.options.emailAndPassword?.sendResetPassword)throw e.context.logger.error("Reset password isn't enabled.Please pass an emailAndPassword.sendResetPasswordToken function in your auth config!"),new W("BAD_REQUEST",{message:"Reset password isn't enabled"});let{email:t,redirectTo:o}=e.body,s=await e.context.internalAdapter.findUserByEmail(t,{includeAccounts:!0});if(!s)return e.context.logger.error("Reset Password: User not found",{email:t}),e.json({status:!1},{body:{status:!0}});let r=60*60*1,n=new Date(Date.now()+1e3*(e.context.options.emailAndPassword.resetPasswordTokenExpiresIn||r)),i=e.context.uuid();await e.context.internalAdapter.createVerificationValue({value:s.user.id,identifier:`reset-password:${i}`,expiresAt:n});let d=`${e.context.baseURL}/reset-password/${i}?callbackURL=${o}`;return await e.context.options.emailAndPassword.sendResetPassword(s.user,d),e.json({status:!0})}),Re=p("/reset-password/:token",{method:"GET",query:P.object({callbackURL:P.string()}),use:[b]},async e=>{let{token:t}=e.params,o=e.query.callbackURL,s=o.startsWith("http")?o:`${e.context.options.baseURL}${o}`;if(!t||!o)throw e.redirect(`${e.context.baseURL}/error?error=INVALID_TOKEN`);let r=await e.context.internalAdapter.findVerificationValue(`reset-password:${t}`);throw!r||r.expiresAt<new Date?e.redirect(`${s}?error=INVALID_TOKEN`):e.redirect(`${s}${s.includes("?")?"&":"?"}token=${t}`)}),Ae=p("/reset-password",{query:P.optional(P.object({token:P.string().optional(),currentURL:P.string().optional()})),method:"POST",body:P.object({newPassword:P.string()})},async e=>{let t=e.query?.token||(e.query?.currentURL?new URL(e.query.currentURL).searchParams.get("token"):"");if(!t)throw new W("BAD_REQUEST",{message:"Token not found"});let{newPassword:o}=e.body,s=`reset-password:${t}`,r=await e.context.internalAdapter.findVerificationValue(s);if(!r||r.expiresAt<new Date)throw new W("BAD_REQUEST",{message:"Invalid token"});await e.context.internalAdapter.deleteVerificationValue(r.id);let n=r.value,i=await e.context.password.hash(o);if(!(await e.context.internalAdapter.findAccounts(n)).find(l=>l.providerId==="credential"))return await e.context.internalAdapter.createAccount({userId:n,providerId:"credential",password:i,accountId:e.context.uuid()}),e.json({status:!0});if(!await e.context.internalAdapter.updatePassword(n,i))throw new W("BAD_REQUEST",{message:"Failed to update password"});return e.json({status:!0})});import{z as k}from"zod";import{APIError as U}from"better-call";var be=()=>p("/user/update",{method:"POST",body:k.record(k.string(),k.any()),use:[E,b]},async e=>{let t=e.body;if(t.email)throw new U("BAD_REQUEST",{message:"You can't update email"});let{name:o,image:s,...r}=t,n=e.context.session;if(!s&&!o&&Object.keys(r).length===0)return e.json({user:n.user});let i=H(e.context.options,r,"update"),d=await e.context.internalAdapter.updateUserByEmail(n.user.email,{name:o,image:s,...i});return await L(e,{session:n.session,user:d}),e.json({user:d})}),ke=p("/user/change-password",{method:"POST",body:k.object({newPassword:k.string(),currentPassword:k.string(),revokeOtherSessions:k.boolean().optional()}),use:[E]},async e=>{let{newPassword:t,currentPassword:o,revokeOtherSessions:s}=e.body,r=e.context.session,n=e.context.password.config.minPasswordLength;if(t.length<n)throw e.context.logger.error("Password is too short"),new U("BAD_REQUEST",{message:"Password is too short"});let i=e.context.password.config.maxPasswordLength;if(t.length>i)throw e.context.logger.error("Password is too long"),new U("BAD_REQUEST",{message:"Password too long"});let c=(await e.context.internalAdapter.findAccounts(r.user.id)).find(w=>w.providerId==="credential"&&w.password);if(!c||!c.password)throw new U("BAD_REQUEST",{message:"User does not have a password"});let a=await e.context.password.hash(t);if(!await e.context.password.verify(c.password,o))throw new U("BAD_REQUEST",{message:"Incorrect password"});if(await e.context.internalAdapter.updateAccount(c.id,{password:a}),s){await e.context.internalAdapter.deleteSessions(r.user.id);let w=await e.context.internalAdapter.createSession(r.user.id,e.headers);if(!w)throw new U("INTERNAL_SERVER_ERROR",{message:"Unable to create session"});await L(e,{session:w,user:r.user})}return e.json(r.user)}),Ue=p("/user/set-password",{method:"POST",body:k.object({newPassword:k.string()}),metadata:{SERVER_ONLY:!0},use:[E]},async e=>{let{newPassword:t}=e.body,o=e.context.session,s=e.context.password.config.minPasswordLength;if(t.length<s)throw e.context.logger.error("Password is too short"),new U("BAD_REQUEST",{message:"Password is too short"});let r=e.context.password.config.maxPasswordLength;if(t.length>r)throw e.context.logger.error("Password is too long"),new U("BAD_REQUEST",{message:"Password too long"});let i=(await e.context.internalAdapter.findAccounts(o.user.id)).find(c=>c.providerId==="credential"&&c.password),d=await e.context.password.hash(t);if(!i)return await e.context.internalAdapter.linkAccount({userId:o.user.id,providerId:"credential",accountId:o.user.id,password:d}),e.json(o.user);throw new U("BAD_REQUEST",{message:"user already has a password"})}),Ee=p("/user/delete",{method:"POST",body:k.object({password:k.string()}),use:[E]},async e=>{let{password:t}=e.body,o=e.context.session,r=(await e.context.internalAdapter.findAccounts(o.user.id)).find(i=>i.providerId==="credential"&&i.password);if(!r||!r.password)throw new U("BAD_REQUEST",{message:"User does not have a password"});if(!await e.context.password.verify(r.password,t))throw new U("BAD_REQUEST",{message:"Incorrect password"});return await e.context.internalAdapter.deleteUser(o.user.id),await e.context.internalAdapter.deleteSessions(o.user.id),_(e),e.json(null)}),Se=p("/user/change-email",{method:"POST",query:k.object({currentURL:k.string().optional()}).optional(),body:k.object({newEmail:k.string().email(),callbackURL:k.string().optional()}),use:[E,b]},async e=>{if(!e.context.options.user?.changeEmail?.enabled)throw e.context.logger.error("Change email is disabled."),new U("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("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("BAD_REQUEST",{message:"Couldn't update your email"});if(e.context.session.user.emailVerified!==!0){let r=await e.context.internalAdapter.updateUserByEmail(e.context.session.user.email,{email:e.body.newEmail});return e.json({user:r,status:!0})}if(!e.context.options.user.changeEmail.sendChangeEmailVerification)throw e.context.logger.error("Verification email isn't enabled."),new U("BAD_REQUEST",{message:"Verification email isn't enabled"});let o=await v(e.context.secret,e.context.session.user.email,e.body.newEmail),s=`${e.context.baseURL}/verify-email?token=${o}&callbackURL=${e.body.callbackURL||e.query?.currentURL||"/"}`;return await e.context.options.user.changeEmail.sendChangeEmailVerification(e.context.session.user,e.body.newEmail,s,o),e.json({user:null,status:!0})});var Te=p("/csrf",{method:"GET",metadata:C},async e=>{let t=await e.getSignedCookie(e.context.authCookies.csrfToken.name,e.context.secret);if(t){let[n,i]=t.split("!")||[null,null];return e.json({csrfToken:n})}let o=X(32,ee("a-z","0-9","A-Z")),s=await M(e.context.secret,o),r=`${o}!${s}`;return await e.setSignedCookie(e.context.authCookies.csrfToken.name,r,e.context.secret,e.context.authCookies.csrfToken.options),e.json({csrfToken:o})});var We=(e="Unknown")=>`<!DOCTYPE html>
|
|
4
|
+
<html lang="en">
|
|
5
|
+
<head>
|
|
6
|
+
<meta charset="UTF-8">
|
|
7
|
+
<meta name="viewport" content="width=device-width, initial-scale=1.0">
|
|
8
|
+
<title>Authentication Error</title>
|
|
9
|
+
<style>
|
|
10
|
+
:root {
|
|
11
|
+
--bg-color: #f8f9fa;
|
|
12
|
+
--text-color: #212529;
|
|
13
|
+
--accent-color: #000000;
|
|
14
|
+
--error-color: #dc3545;
|
|
15
|
+
--border-color: #e9ecef;
|
|
16
|
+
}
|
|
17
|
+
body {
|
|
18
|
+
font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, 'Helvetica Neue', Arial, sans-serif;
|
|
19
|
+
background-color: var(--bg-color);
|
|
20
|
+
color: var(--text-color);
|
|
21
|
+
display: flex;
|
|
22
|
+
justify-content: center;
|
|
23
|
+
align-items: center;
|
|
24
|
+
height: 100vh;
|
|
25
|
+
margin: 0;
|
|
26
|
+
line-height: 1.5;
|
|
27
|
+
}
|
|
28
|
+
.error-container {
|
|
29
|
+
background-color: #ffffff;
|
|
30
|
+
border-radius: 12px;
|
|
31
|
+
box-shadow: 0 4px 6px rgba(0, 0, 0, 0.05);
|
|
32
|
+
padding: 2.5rem;
|
|
33
|
+
text-align: center;
|
|
34
|
+
max-width: 90%;
|
|
35
|
+
width: 400px;
|
|
36
|
+
}
|
|
37
|
+
h1 {
|
|
38
|
+
color: var(--error-color);
|
|
39
|
+
font-size: 1.75rem;
|
|
40
|
+
margin-bottom: 1rem;
|
|
41
|
+
font-weight: 600;
|
|
42
|
+
}
|
|
43
|
+
p {
|
|
44
|
+
margin-bottom: 1.5rem;
|
|
45
|
+
color: #495057;
|
|
46
|
+
}
|
|
47
|
+
.btn {
|
|
48
|
+
background-color: var(--accent-color);
|
|
49
|
+
color: #ffffff;
|
|
50
|
+
text-decoration: none;
|
|
51
|
+
padding: 0.75rem 1.5rem;
|
|
52
|
+
border-radius: 6px;
|
|
53
|
+
transition: all 0.3s ease;
|
|
54
|
+
display: inline-block;
|
|
55
|
+
font-weight: 500;
|
|
56
|
+
border: 2px solid var(--accent-color);
|
|
57
|
+
}
|
|
58
|
+
.btn:hover {
|
|
59
|
+
background-color: #131721;
|
|
60
|
+
}
|
|
61
|
+
.error-code {
|
|
62
|
+
font-size: 0.875rem;
|
|
63
|
+
color: #6c757d;
|
|
64
|
+
margin-top: 1.5rem;
|
|
65
|
+
padding-top: 1.5rem;
|
|
66
|
+
border-top: 1px solid var(--border-color);
|
|
67
|
+
}
|
|
68
|
+
.icon {
|
|
69
|
+
font-size: 3rem;
|
|
70
|
+
margin-bottom: 1rem;
|
|
71
|
+
}
|
|
72
|
+
</style>
|
|
73
|
+
</head>
|
|
74
|
+
<body>
|
|
75
|
+
<div class="error-container">
|
|
76
|
+
<div class="icon">\u26A0\uFE0F</div>
|
|
77
|
+
<h1>Better Auth Error</h1>
|
|
78
|
+
<p>We encountered an issue while processing your request. Please try again or contact the application owner if the problem persists.</p>
|
|
79
|
+
<a href="/" id="returnLink" class="btn">Return to Application</a>
|
|
80
|
+
<div class="error-code">Error Code: <span id="errorCode">${e}</span></div>
|
|
81
|
+
</div>
|
|
82
|
+
</body>
|
|
83
|
+
</html>`,Le=p("/error",{method:"GET",metadata:C},async e=>{let t=new URL(e.request?.url||"").searchParams.get("error")||"Unknown";return new Response(We(t),{headers:{"Content-Type":"text/html"}})});var Ie=p("/ok",{method:"GET",metadata:C},async e=>e.json({ok:!0}));import{z as j}from"zod";import{APIError as x}from"better-call";var Oe=()=>p("/sign-up/email",{method:"POST",query:j.object({currentURL:j.string().optional()}).optional(),body:j.record(j.string(),j.any()),use:[b]},async e=>{if(!e.context.options.emailAndPassword?.enabled)throw new x("BAD_REQUEST",{message:"Email and password sign up is not enabled"});let t=e.body,{name:o,email:s,password:r,image:n,callbackURL:i,...d}=t;if(!j.string().email().safeParse(s).success)throw new x("BAD_REQUEST",{message:"Invalid email"});let a=e.context.password.config.minPasswordLength;if(r.length<a)throw e.context.logger.error("Password is too short"),new x("BAD_REQUEST",{message:"Password is too short"});let l=e.context.password.config.maxPasswordLength;if(r.length>l)throw e.context.logger.error("Password is too long"),new x("BAD_REQUEST",{message:"Password is too long"});if((await e.context.internalAdapter.findUserByEmail(s))?.user)throw e.context.logger.info(`Sign-up attempt for existing email: ${s}`),new x("UNPROCESSABLE_ENTITY",{message:"User with this email already exists"});let y=H(e.context.options,d),u;try{if(u=await e.context.internalAdapter.createUser({email:s.toLowerCase(),name:o,image:n,...y,emailVerified:!1}),!u)throw new x("BAD_REQUEST",{message:"Failed to create user"})}catch(g){throw h.error("Failed to create user",g),new x("UNPROCESSABLE_ENTITY",{message:"Failed to create user",details:g})}if(!u)throw new x("UNPROCESSABLE_ENTITY",{message:"Failed to create user"});let A=await e.context.password.hash(r);if(await e.context.internalAdapter.linkAccount({userId:u.id,providerId:"credential",accountId:u.id,password:A,expiresAt:Q(60*60*24*30,"sec")}),e.context.options.emailVerification?.sendOnSignUp){let g=await v(e.context.secret,u.email),f=`${e.context.baseURL}/verify-email?token=${g}&callbackURL=${t.callbackURL||e.query?.currentURL||"/"}`;await e.context.options.emailVerification?.sendVerificationEmail?.(u,f,g)}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 R=await e.context.internalAdapter.createSession(u.id,e.request);if(!R)throw new x("BAD_REQUEST",{message:"Failed to create session"});return await L(e,{session:R,user:u}),e.json({user:u,session:R},{body:t.callbackURL?{url:t.callbackURL,redirect:!0}:{user:u,session:R}})});import{z as N}from"zod";import{APIError as Pe}from"better-call";import{generateCodeVerifier as Ge}from"oslo/oauth2";var ve=p("/user/list-accounts",{method:"GET",use:[E]},async e=>{let t=e.context.session,o=await e.context.internalAdapter.findAccounts(t.user.id);return e.json(o)}),xe=p("/user/link-social",{method:"POST",requireHeaders:!0,query:N.object({currentURL:N.string().optional()}).optional(),body:N.object({callbackURL:N.string().optional(),provider:N.enum(Z)}),use:[b,E]},async e=>{let t=e.context.session;if((await e.context.internalAdapter.findAccounts(t.user.id)).find(w=>w.providerId===e.body.provider))throw new Pe("BAD_REQUEST",{message:"Social Account is already linked."});let r=e.context.socialProviders.find(w=>w.id===e.body.provider);if(!r)throw e.context.logger.error("Provider not found. Make sure to add the provider in your auth config",{provider:e.body.provider}),new Pe("NOT_FOUND",{message:"Provider not found"});let n=e.context.authCookies,i=e.query?.currentURL?new URL(e.query?.currentURL):null,d=e.body.callbackURL?.startsWith("http")?e.body.callbackURL:`${i?.origin}${e.body.callbackURL||""}`,c=await F(d||i?.origin||e.context.options.baseURL,{email:t.user.email,userId:t.user.id});await e.setSignedCookie(n.state.name,c.hash,e.context.secret,n.state.options);let a=Ge();await e.setSignedCookie(n.pkCodeVerifier.name,a,e.context.secret,n.pkCodeVerifier.options);let l=await r.createAuthorizationURL({state:c.raw,codeVerifier:a,redirectURI:`${e.context.baseURL}/link-account/${r.id}`});return e.json({url:l.toString(),state:c,codeVerifier:a,redirect:!0})});function Je(e,t,o){let s=Date.now(),r=t*1e3;return s-o.lastRequest<r&&o.count>=e}function Ye(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 Ke(e,t){let o=Date.now(),s=t*1e3;return Math.ceil((e+s-o)/1e3)}function Xe(e,t){let o=t??"rateLimit",s=e.adapter;return{get:async r=>await s.findOne({model:o,where:[{field:"key",value:r}]}),set:async(r,n,i)=>{try{i?await s.update({model:t??"rateLimit",where:[{field:"key",value:r}],update:{count:n.count,lastRequest:n.lastRequest}}):await s.create({model:t??"rateLimit",data:{key:r,count:n.count,lastRequest:n.lastRequest}})}catch(d){h.error("Error setting rate limit",d)}}}}var Ce=new Map;function et(e){return e.rateLimit.storage==="secondary-storage"?{get:async o=>{let s=await e.options.secondaryStorage?.get(o);return s?JSON.parse(s):void 0},set:async(o,s)=>{await e.options.secondaryStorage?.set?.(o,JSON.stringify(s))}}:e.rateLimit.storage==="memory"?{async get(o){return Ce.get(o)},async set(o,s,r){Ce.set(o,s)}}:Xe(e,e.rateLimit.tableName)}async function _e(e,t){if(!t.rateLimit.enabled)return;let o=t.baseURL,s=e.url.replace(o,""),r=t.rateLimit.window,n=t.rateLimit.max,i=re(e)+s,c=tt().find(y=>y.pathMatcher(s));c&&(r=c.window,n=c.max);for(let y of t.options.plugins||[])if(y.rateLimit){let u=y.rateLimit.find(A=>A.pathMatcher(s));if(u){r=u.window,n=u.max;break}}if(t.rateLimit.customRules){let y=t.rateLimit.customRules[s];y&&(r=y.window,n=y.max)}let a=et(t),l=await a.get(i),w=Date.now();if(!l)await a.set(i,{key:i,count:1,lastRequest:w});else{let y=w-l.lastRequest;if(Je(n,r,l)){let u=Ke(l.lastRequest,r);return Ye(u)}else y>r*1e3?await a.set(i,{...l,count:1,lastRequest:w}):await a.set(i,{...l,count:l.count+1,lastRequest:w})}}function tt(){return[{pathMatcher(t){return t.startsWith("/sign-in")||t.startsWith("/sign-up")},window:10,max:3}]}import{APIError as rs}from"better-call";function st(e,t){let o=t.plugins?.reduce((d,c)=>({...d,...c.endpoints}),{}),s=t.plugins?.map(d=>d.middlewares?.map(c=>{let a=async l=>c.middleware({...l,context:{...e,...l.context}});return a.path=c.path,a.options=c.middleware.options,a.headers=c.middleware.headers,{path:c.path,middleware:a}})).filter(d=>d!==void 0).flat()||[],n={...{signInOAuth:me,callbackOAuth:ge,getCSRFToken:Te,getSession:Y(),signOut:he,signUpEmail:Oe(),signInEmail:fe,forgetPassword:ye,resetPassword:Ae,verifyEmail:pe,sendVerificationEmail:ue,changeEmail:Se,changePassword:ke,setPassword:Ue,updateUser:be(),deleteUser:Ee,forgetPasswordCallback:Re,listSessions:de(),revokeSession:ce,revokeSessions:le,linkSocialAccount:xe,listUserAccounts:ve},...o,ok:Ie,error:Le},i={};for(let[d,c]of Object.entries(n))i[d]=async(a={})=>{let l=await e;for(let u of t.plugins||[])if(u.hooks?.before){for(let A of u.hooks.before)if(A.matcher({...c,...a,context:l})){let g=await A.handler({...a,context:{...l,...a?.context}});g&&"context"in g&&(l={...l,...g.context})}}let w;try{w=await c({...a,context:{...l,...a.context}})}catch(u){if(u instanceof De){let A=t.plugins?.map(g=>{if(g.hooks?.after)return g.hooks.after}).filter(g=>g!==void 0).flat();if(!A?.length)throw u;let R=new Response(JSON.stringify(u.body),{status:rt[u.status],headers:u.headers});for(let g of A||[])if(g.matcher(a)){let T=Object.assign(a,{context:{...e,returned:R}}),D=await g.handler(T);D&&"response"in D&&(R=D.response)}return R}throw u}let y=w;for(let u of t.plugins||[])if(u.hooks?.after){for(let A of u.hooks.after)if(A.matcher(a)){let g=Object.assign(a,{context:{...e,returned:y}}),f=await A.handler(g);f&&"response"in f&&(y=f.response)}}return y},i[d].path=c.path,i[d].method=c.method,i[d].options=c.options,i[d].headers=c.headers;return{api:i,middlewares:s}}var Yr=(e,t)=>{let{api:o,middlewares:s}=st(e,t),r=new URL(e.baseURL).pathname;return ot(o,{extraContext:e,basePath:r,routerMiddleware:[{path:"/**",middleware:ae},...s],async onRequest(n){for(let i of e.options.plugins||[])if(i.onRequest){let d=await i.onRequest(n,e);if(d)return d}return _e(n,e)},async onResponse(n){for(let i of e.options.plugins||[])if(i.onResponse){let d=await i.onResponse(n,e);if(d)return d.response}return n},onError(n){if(t.onAPIError?.throw)throw n;if(t.onAPIError?.onError){t.onAPIError.onError(n,e);return}let i=t.logger?.verboseLogging?h:void 0;t.logger?.disabled!==!0&&(n instanceof De?(n.status==="INTERNAL_SERVER_ERROR"&&h.error(n),i?.error(n.message)):h?.error(n))}})};export{ne as a,B as b,p as c,ae as d,b as e,Y as f,K as g,E as h,de as i,ce as j,le as k,v as l,ue as m,pe as n,me as o,fe as p,we as q,ge as r,he as s,ye as t,Re as u,Ae as v,be as w,ke as x,Ue as y,Ee as z,Se as A,Te as B,Le as C,Ie as D,Oe as E,ve as F,xe as G,st as H,Yr as I,rs as J};
|
|
84
|
+
//# sourceMappingURL=chunk-3MYUOPUJ.js.map
|