modelence 0.5.12 → 0.5.13-dev.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/client.d.ts +17 -1
- package/dist/client.js +1 -1
- package/dist/client.js.map +1 -1
- package/dist/package-4ZTUD7K2.js +3 -0
- package/dist/package-4ZTUD7K2.js.map +1 -0
- package/dist/server.d.ts +9 -0
- package/dist/server.js +12 -5
- package/dist/server.js.map +1 -1
- package/package.json +1 -1
- package/dist/package-MYWZ4U2C.js +0 -3
- package/dist/package-MYWZ4U2C.js.map +0 -1
package/dist/client.d.ts
CHANGED
|
@@ -91,7 +91,23 @@ declare function verifyEmail(options: {
|
|
|
91
91
|
*
|
|
92
92
|
*/
|
|
93
93
|
declare function logout(): Promise<void>;
|
|
94
|
+
/**
|
|
95
|
+
* Send reset password token.
|
|
96
|
+
* @param options.email - The email of the user.
|
|
97
|
+
*/
|
|
98
|
+
declare function sendResetPasswordToken(options: {
|
|
99
|
+
email: string;
|
|
100
|
+
}): Promise<void>;
|
|
101
|
+
/**
|
|
102
|
+
* Reset password.
|
|
103
|
+
* @param options.token - The password reset token.
|
|
104
|
+
* @param options.password - The new password.
|
|
105
|
+
*/
|
|
106
|
+
declare function resetPassword(options: {
|
|
107
|
+
token: string;
|
|
108
|
+
password: string;
|
|
109
|
+
}): Promise<void>;
|
|
94
110
|
|
|
95
111
|
declare const AppProvider: any;
|
|
96
112
|
|
|
97
|
-
export { AppProvider, type MethodArgs, type UserInfo, callMethod, getConfig, loginWithPassword, logout, renderApp, signupWithPassword, useSession, verifyEmail };
|
|
113
|
+
export { AppProvider, type MethodArgs, type UserInfo, callMethod, getConfig, loginWithPassword, logout, renderApp, resetPassword, sendResetPasswordToken, signupWithPassword, useSession, verifyEmail };
|
package/dist/client.js
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import {b as b$1}from'./chunk-DN5SVAO2.js';import {a}from'./chunk-R7MPLJMA.js';import A,{useState,useEffect}from'react';import {create}from'zustand';import {z as z$1}from'zod';import {jsx}from'react/jsx-runtime';import O from'react-dom/client';function u(){let e=localStorage.getItem("modelence.session");try{return e?JSON.parse(e):null}catch(r){return console.error("Error parsing session from localStorage",r),null}}function m(e){localStorage.setItem("modelence.session",JSON.stringify(e));}var g=(e,r)=>{throw new Error(`Error calling method '${r}': ${e.toString()}`)};function w(e){g=e;}function h(e,r){return g(e,r)}async function n(e,r={}){try{return await
|
|
1
|
+
import {b as b$1}from'./chunk-DN5SVAO2.js';import {a}from'./chunk-R7MPLJMA.js';import A,{useState,useEffect}from'react';import {create}from'zustand';import {z as z$1}from'zod';import {jsx}from'react/jsx-runtime';import O from'react-dom/client';function u(){let e=localStorage.getItem("modelence.session");try{return e?JSON.parse(e):null}catch(r){return console.error("Error parsing session from localStorage",r),null}}function m(e){localStorage.setItem("modelence.session",JSON.stringify(e));}var g=(e,r)=>{throw new Error(`Error calling method '${r}': ${e.toString()}`)};function w(e){g=e;}function h(e,r){return g(e,r)}async function n(e,r={}){try{return await k(`/api/_internal/method/${e}`,r)}catch(o){throw h(o,e),o}}async function k(e,r){let o=await fetch(e,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({args:r,authToken:u()?.authToken,clientInfo:{screenWidth:window.screen.width,screenHeight:window.screen.height,windowWidth:window.innerWidth,windowHeight:window.innerHeight,pixelRatio:window.devicePixelRatio,orientation:window.screen.orientation?.type}})});if(!o.ok){let i=await o.text();throw new Error(i)}let t=await o.text(),s=t?JSON.parse(t):void 0;if(!s)throw new Error("Invalid response from server");return b$1(s.data,s.typeMap)}var y={};function T(e){return y[e]?.value}function S(e){y=e;}var c=create(e=>({user:null,setUser:r=>e({user:r})})),E=false,H=a.seconds(30);async function x(){if(E)return;E=true;let{configs:e,session:r,user:o}=await n("_system.session.init");S(e),m(r);let t=o?Object.freeze(z$1.object({id:z$1.string(),handle:z$1.string()}).parse(o)):null;c.getState().setUser(t),await P();}async function P(){await n("_system.session.heartbeat"),setTimeout(P,H);}function d(e){c.getState().setUser(e);}function I(){return {user:c(r=>r.user)}}var R=false;function l({children:e,loadingElement:r}){let[o,t]=useState(true);return useEffect(()=>{async function s(){R||(R=true,await x(),t(false));}s();},[]),o?r??jsx("div",{children:"Loading..."}):e}function W({loadingElement:e,routesElement:r,favicon:o,errorHandler:t}){if(t&&w(t),window.addEventListener("unload",()=>{}),O.createRoot(document.getElementById("root")).render(jsx(A.StrictMode,{children:jsx(C,{loadingElement:e,children:r})})),o){let s=document.querySelector("link[rel~='icon']");if(s)s.href=o;else {let i=document.createElement("link");i.rel="icon",i.href=o,document.head.appendChild(i);}}}async function b(e){let{email:r,password:o}=e;await n("_system.user.signupWithPassword",{email:r,password:o});}async function J(e){let{email:r,password:o}=e,{user:t}=await n("_system.user.loginWithPassword",{email:r,password:o});return d(t),t}async function j(e){let{token:r}=e;await n("_system.user.verifyEmail",{token:r});}async function z(){await n("_system.user.logout"),d(null);}async function K(e){let{email:r}=e;await n("_system.user.sendResetPasswordToken",{email:r});}async function $(e){let{token:r,password:o}=e;await n("_system.user.resetPassword",{token:r,password:o});}var C="useClient"in A?A.useClient(l):l;export{C as AppProvider,n as callMethod,T as getConfig,J as loginWithPassword,z as logout,W as renderApp,$ as resetPassword,K as sendResetPasswordToken,b as signupWithPassword,I as useSession,j as verifyEmail};//# sourceMappingURL=client.js.map
|
|
2
2
|
//# sourceMappingURL=client.js.map
|
package/dist/client.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/client/localStorage.ts","../src/client/errorHandler.ts","../src/client/method.ts","../src/config/client.ts","../src/client/session.ts","../src/client/AppProvider.tsx","../src/client/renderApp.tsx","../src/auth/client/index.ts","../src/client.ts"],"names":["getLocalStorageSession","sessionJson","e","setLocalStorageSession","session","errorHandler","error","methodName","setErrorHandler","handler","handleError","callMethod","args","call","endpoint","response","text","result","reviveResponseTypes","config","getConfig","key","_setConfig","configs","useSessionStore","create","set","user","isInitialized","SESSION_HEARTBEAT_INTERVAL","time","initSession","parsedUser","z","loopSessionHeartbeat","setCurrentUser","useSession","state","AppProvider","children","loadingElement","isLoading","setIsLoading","useState","useEffect","initConfig","jsx","renderApp","routesElement","favicon","ReactDOM","React","link","newLink","signupWithPassword","options","email","password","loginWithPassword","verifyEmail","token","logout"],"mappings":"oPAAO,SAASA,CAAAA,EAAyB,CACvC,IAAMC,CAAAA,CAAc,YAAA,CAAa,QAAQ,mBAAmB,CAAA,CAC5D,GAAI,CACF,OAAOA,CAAAA,CAAc,IAAA,CAAK,KAAA,CAAMA,CAAW,EAAI,IACjD,CAAA,MAASC,CAAAA,CAAG,CACV,OAAA,OAAA,CAAQ,KAAA,CAAM,yCAAA,CAA2CA,CAAC,EACnD,IACT,CACF,CAEO,SAASC,EAAuBC,CAAAA,CAAiB,CACtD,YAAA,CAAa,OAAA,CAAQ,oBAAqB,IAAA,CAAK,SAAA,CAAUA,CAAO,CAAC,EACnE,CCVA,IAAIC,CAAAA,CAA6B,CAACC,CAAAA,CAAOC,CAAAA,GAAe,CACtD,MAAM,IAAI,KAAA,CAAM,CAAA,sBAAA,EAAyBA,CAAU,CAAA,GAAA,EAAMD,EAAM,QAAA,EAAU,CAAA,CAAE,CAC7E,CAAA,CAEO,SAASE,CAAAA,CAAgBC,CAAAA,CAAuB,CACrDJ,CAAAA,CAAeI,EACjB,CAEO,SAASC,EAAYJ,CAAAA,CAAcC,CAAAA,CAAoB,CAC5D,OAAOF,EAAaC,CAAAA,CAAOC,CAAU,CACvC,CCGA,eAAsBI,CAAAA,CAAwBJ,CAAAA,CAAoBK,CAAAA,CAAmB,EAAC,CAAe,CACnG,GAAI,CACF,OAAO,MAAMC,CAAAA,CAAQ,CAAA,sBAAA,EAAyBN,CAAU,GAAIK,CAAI,CAClE,CAAA,MAASN,CAAAA,CAAO,CACd,MAAAI,CAAAA,CAAYJ,CAAAA,CAAgBC,CAAU,CAAA,CAChCD,CACR,CACF,CAEA,eAAeO,CAAAA,CAAkBC,CA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,CAAO,EACnC,CAGF,CACF,CCrBA,eAAsBC,CAAAA,CAAmBC,CAAAA,CAA8C,CACrF,GAAM,CAAE,KAAA,CAAAC,CAAAA,CAAO,QAAA,CAAAC,CAAS,EAAIF,CAAAA,CAC5B,MAAM5C,CAAAA,CAAW,iCAAA,CAAmC,CAAE,KAAA,CAAA6C,CAAAA,CAAO,QAAA,CAAAC,CAAS,CAAC,EACzE,CAYA,eAAsBC,EAAkBH,CAAAA,CAA8C,CACpF,GAAM,CAAE,MAAAC,CAAAA,CAAO,QAAA,CAAAC,CAAS,CAAA,CAAIF,EACtB,CAAE,IAAA,CAAA5B,CAAK,CAAA,CAAI,MAAMhB,CAAAA,CAA+B,gCAAA,CAAkC,CAAE,MAAA6C,CAAAA,CAAO,QAAA,CAAAC,CAAS,CAAC,EAC3G,OAAAtB,CAAAA,CAAeR,CAAI,CAAA,CACZA,CACT,CAWA,eAAsBgC,CAAAA,CAAYJ,CAAAA,CAA4B,CAC5D,GAAM,CAAE,KAAA,CAAAK,CAAM,CAAA,CAAIL,CAAAA,CAClB,MAAM5C,CAAAA,CAA+B,2BAA4B,CAAE,KAAA,CAAAiD,CAAM,CAAC,EAC5E,CAMA,eAAsBC,CAAAA,EAAS,CAC7B,MAAMlD,CAAAA,CAAW,qBAAqB,CAAA,CACtCwB,EAAe,IAAI,EACrB,CCvDO,IAAMG,EAAc,WAAA,GAAea,CAAAA,CAEtCA,CAAAA,CAAM,SAAA,CAAUb,CAAmB,CAAA,CACnCA","file":"client.js","sourcesContent":["export function getLocalStorageSession() {\n const sessionJson = localStorage.getItem('modelence.session');\n try {\n return sessionJson ? JSON.parse(sessionJson) : null;\n } catch (e) {\n console.error('Error parsing session from localStorage', e);\n return null;\n }\n}\n\nexport function setLocalStorageSession(session: object) {\n localStorage.setItem('modelence.session', JSON.stringify(session));\n}\n","export type ErrorHandler = (error: Error, methodName: string) => void;\n\nlet errorHandler: ErrorHandler = (error, methodName) => {\n throw new Error(`Error calling method '${methodName}': ${error.toString()}`);\n};\n\nexport function setErrorHandler(handler: ErrorHandler) {\n errorHandler = handler;\n}\n\nexport function handleError(error: Error, methodName: string) {\n return errorHandler(error, methodName);\n}\n","/*\n The \"use client\" directive is specifically for the Next.js layout component, which is rendered on the server by default.\n Because of this, we are explicitly marking it as a client component, so we can render this component on the client\n and properly initialize config on the client side.\n \n While this is specific to Next.js, it is simply ignored outside of Next.js and should not cause errors.\n*/\n\"use client\";\n\nimport { getLocalStorageSession } from './localStorage';\nimport { handleError } from './errorHandler';\nimport { reviveResponseTypes } from '../methods/serialize';\n\nexport type MethodArgs = Record<string, unknown>;\n\nexport async function callMethod<T = unknown>(methodName: string, args: MethodArgs = {}): Promise<T> {\n try {\n return await call<T>(`/api/_internal/method/${methodName}`, args);\n } catch (error) {\n handleError(error as Error, methodName);\n throw error;\n }\n}\n\nasync function call<T = unknown>(endpoint: string, args: MethodArgs): Promise<T> {\n const response = await fetch(endpoint, {\n method: 'POST',\n headers: {\n 'Content-Type': 'application/json',\n },\n body: JSON.stringify({\n args,\n authToken: getLocalStorageSession()?.authToken,\n clientInfo: {\n screenWidth: window.screen.width,\n screenHeight: window.screen.height,\n windowWidth: window.innerWidth,\n windowHeight: window.innerHeight,\n pixelRatio: window.devicePixelRatio,\n orientation: window.screen.orientation?.type\n }\n }),\n });\n\n if (!response.ok) {\n const error = await response.text();\n throw new Error(error);\n }\n\n const text = await response.text();\n const result = text ? JSON.parse(text) : undefined;\n if (!result) {\n throw new Error('Invalid response from server');\n }\n\n return reviveResponseTypes(result.data, result.typeMap);\n}\n","import { AppConfig, ConfigKey, Configs } from './types';\n\nlet config: Record<ConfigKey, AppConfig> = {};\n\n/**\n * @sidebarTitle getConfig (client)\n * \n * @param key\n * @returns \n */\nexport function getConfig(key: ConfigKey) {\n return config[key]?.value;\n}\n\nexport function _setConfig(configs: Configs) {\n config = configs;\n}\n","import { create } from 'zustand';\nimport { z } from 'zod';\nimport { callMethod } from './method';\nimport { _setConfig } from '../config/client';\nimport { setLocalStorageSession } from './localStorage';\nimport { time } from '../time';\nimport { Configs } from '../config/types';\n\ntype User = {\n id: string;\n handle: string;\n};\n\ntype SessionStore = {\n user: User | null;\n setUser: (user: User | null) => void;\n};\n\nexport const useSessionStore = create<SessionStore>((set) => ({\n user: null,\n setUser: (user) => set({ user }),\n}));\n\nlet isInitialized = false;\nconst SESSION_HEARTBEAT_INTERVAL = time.seconds(30);\n\nexport async function initSession() {\n if (isInitialized) {\n return;\n }\n\n isInitialized = true;\n\n const { configs, session, user } = await callMethod<{ configs: Configs, session: object, user: object }>('_system.session.init');\n _setConfig(configs);\n setLocalStorageSession(session);\n \n const parsedUser = user ? Object.freeze(z.object({\n id: z.string(),\n handle: z.string(),\n }).parse(user)) : null;\n\n useSessionStore.getState().setUser(parsedUser);\n\n await loopSessionHeartbeat();\n}\n\nasync function loopSessionHeartbeat() {\n await callMethod('_system.session.heartbeat');\n setTimeout(loopSessionHeartbeat, SESSION_HEARTBEAT_INTERVAL);\n}\n\nexport function setCurrentUser(user: User | null) {\n useSessionStore.getState().setUser(user);\n}\n\n/**\n * `useSession` is a hook that returns the current user, and in the future will also return other details about the current session.\n * \n * @example\n * ```ts\n * import { useSession } from 'modelence/client';\n * \n * function MyComponent() {\n * const { user } = useSession();\n * return <div>{user?.handle}</div>;\n * }\n * ```\n */\nexport function useSession() {\n const user = useSessionStore(state => state.user);\n return { user };\n}\n","/*\n The \"use client\" directive is specifically for the Next.js layout component, which is rendered on the server by default.\n Because of this, we are explicitly marking it as a client component, so we can render this component on the client\n and properly initialize config on the client side.\n \n While this is specific to Next.js, it is simply ignored outside of Next.js and should not cause errors.\n*/\n\"use client\";\n\nimport React, { useState, useEffect, ReactNode } from 'react';\nimport { initSession } from './session';\n\ninterface AppProviderProps {\n children: ReactNode;\n loadingElement?: ReactNode;\n}\n\nlet isInitialized = false;\n\nexport function AppProvider({ children, loadingElement }: AppProviderProps) {\n const [isLoading, setIsLoading] = useState(true);\n\n useEffect(() => {\n async function initConfig() {\n if (isInitialized) {\n return;\n }\n\n isInitialized = true;\n\n await initSession();\n setIsLoading(false);\n }\n\n initConfig();\n }, []);\n\n if (isLoading) {\n return loadingElement ?? <div>Loading...</div>;\n }\n\n return children;\n}\n","import React from 'react';\nimport ReactDOM from 'react-dom/client';\nimport { AppProvider } from '../client';\nimport { setErrorHandler, ErrorHandler } from './errorHandler';\n\nexport function renderApp({ loadingElement, routesElement, favicon, errorHandler }: {\n loadingElement: React.ReactNode,\n routesElement: React.ReactNode,\n favicon?: string,\n errorHandler?: ErrorHandler\n}) {\n if (errorHandler) {\n setErrorHandler(errorHandler);\n }\n\n window.addEventListener('unload', () => {\n // The presence of any 'unload' event handler, even empty,\n // prevents bfcache in most browsers\n });\n\n ReactDOM.createRoot(document.getElementById('root')!).render(\n <React.StrictMode>\n <AppProvider loadingElement={loadingElement}>\n {routesElement}\n </AppProvider>\n </React.StrictMode>\n );\n\n if (favicon) {\n const link = document.querySelector(\"link[rel~='icon']\") as HTMLLinkElement;\n if (!link) {\n const newLink = document.createElement('link');\n newLink.rel = 'icon';\n newLink.href = favicon;\n document.head.appendChild(newLink);\n } else {\n link.href = favicon;\n }\n }\n}\n","import { setCurrentUser } from '../../client/session';\nimport { callMethod } from '../../client/method';\n\nexport type UserInfo = {\n id: string;\n handle: string;\n};\n\n/**\n * Sign up a new user with an email and password.\n * \n * @example\n * ```ts\n * await signupWithPassword({ email: 'test@example.com', password: '12345678' });\n * ```\n * @param options.email - The email of the user.\n * @param options.password - The password of the user.\n */\nexport async function signupWithPassword(options: { email: string, password: string }) {\n const { email, password } = options;\n await callMethod('_system.user.signupWithPassword', { email, password });\n}\n\n/**\n * Login a user with an email and password.\n * \n * @example\n * ```ts\n * await loginWithPassword({ email: 'test@example.com', password: '12345678' });\n * ```\n * @param options.email - The email of the user.\n * @param options.password - The password of the user.\n */\nexport async function loginWithPassword(options: { email: string, password: string }) {\n const { email, password } = options;\n const { user } = await callMethod<{ user: UserInfo }>('_system.user.loginWithPassword', { email, password });\n setCurrentUser(user);\n return user;\n}\n\n/**\n * Verify user's email with a verification token.\n * \n * @example\n * ```ts\n * await verifyEmail({ token: 'verification-token' });\n * ```\n * @param options.token - The email verification token.\n */\nexport async function verifyEmail(options: { token: string }) {\n const { token } = options;\n await callMethod<{ user: UserInfo }>('_system.user.verifyEmail', { token });\n}\n\n/**\n * Logout the current user.\n * \n */\nexport async function logout() {\n await callMethod('_system.user.logout');\n setCurrentUser(null);\n}\n","import React from 'react';\n\nimport { AppProvider as OriginalAppProvider } from './client/AppProvider';\n\nexport { getConfig } from './config/client';\n\nexport const AppProvider = 'useClient' in React\n // @ts-ignore: React.useClient only exists in Next.js\n ? React.useClient(OriginalAppProvider)\n : OriginalAppProvider;\n\nexport { renderApp } from './client/renderApp';\nexport { callMethod, type MethodArgs } from './client/method';\nexport { useSession } from './client/session';\nexport { signupWithPassword, loginWithPassword, verifyEmail, logout, type UserInfo } from './auth/client';\n"]}
|
|
1
|
+
{"version":3,"sources":["../src/client/localStorage.ts","../src/client/errorHandler.ts","../src/client/method.ts","../src/config/client.ts","../src/client/session.ts","../src/client/AppProvider.tsx","../src/client/renderApp.tsx","../src/auth/client/index.ts","../src/client.ts"],"names":["getLocalStorageSession","sessionJson","e","setLocalStorageSession","session","errorHandler","error","methodName","setErrorHandler","handler","handleError","callMethod","args","call","endpoint","response","text","result","reviveResponseTypes","config","getConfig","key","_setConfig","configs","useSessionStore","create","set","user","isInitialized","SESSION_HEARTBEAT_INTERVAL","time","initSession","parsedUser","z","loopSessionHeartbeat","setCurrentUser","useSession","state","AppProvider","children","loadingElement","isLoading","setIsLoading","useState","useEffect","initConfig","jsx","renderApp","routesElement","favicon","ReactDOM","React","link","newLink","signupWithPassword","options","email","password","loginWithPassword","verifyEmail","token","logout","sendResetPasswordToken","resetPassword"],"mappings":"oPAAO,SAASA,CAAAA,EAAyB,CACvC,IAAMC,EAAc,YAAA,CAAa,OAAA,CAAQ,mBAAmB,CAAA,CAC5D,GAAI,CACF,O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CAAE,KAAA,CAAA6C,CAAAA,CAAO,SAAAC,CAAS,CAAC,EAC3G,OAAAtB,CAAAA,CAAeR,CAAI,CAAA,CACZA,CACT,CAWA,eAAsBgC,EAAYJ,CAAAA,CAA4B,CAC5D,GAAM,CAAE,MAAAK,CAAM,CAAA,CAAIL,CAAAA,CAClB,MAAM5C,EAA+B,0BAAA,CAA4B,CAAE,KAAA,CAAAiD,CAAM,CAAC,EAC5E,CAMA,eAAsBC,CAAAA,EAAS,CAC7B,MAAMlD,CAAAA,CAAW,qBAAqB,CAAA,CACtCwB,EAAe,IAAI,EACrB,CAMA,eAAsB2B,EAAuBP,CAAAA,CAA4B,CACvE,GAAM,CAAE,KAAA,CAAAC,CAAM,CAAA,CAAID,CAAAA,CAClB,MAAM5C,CAAAA,CAAW,sCAAuC,CACtD,KAAA,CAAA6C,CACF,CAAC,EACH,CAOA,eAAsBO,CAAAA,CAAcR,CAAAA,CAA8C,CAChF,GAAM,CAAE,KAAA,CAAAK,CAAAA,CAAO,SAAAH,CAAS,CAAA,CAAIF,CAAAA,CAC5B,MAAM5C,EAAW,4BAAA,CAA8B,CAC7C,KAAA,CAAAiD,CAAAA,CACA,SAAAH,CACF,CAAC,EACH,KC/EanB,CAAAA,CAAc,WAAA,GAAea,EAEtCA,CAAAA,CAAM,SAAA,CAAUb,CAAmB,CAAA,CACnCA","file":"client.js","sourcesContent":["export function getLocalStorageSession() {\n const sessionJson = localStorage.getItem('modelence.session');\n try {\n return sessionJson ? JSON.parse(sessionJson) : null;\n } catch (e) {\n console.error('Error parsing session from localStorage', e);\n return null;\n }\n}\n\nexport function setLocalStorageSession(session: object) {\n localStorage.setItem('modelence.session', JSON.stringify(session));\n}\n","export type ErrorHandler = (error: Error, methodName: string) => void;\n\nlet errorHandler: ErrorHandler = (error, methodName) => {\n throw new Error(`Error calling method '${methodName}': ${error.toString()}`);\n};\n\nexport function setErrorHandler(handler: ErrorHandler) {\n errorHandler = handler;\n}\n\nexport function handleError(error: Error, methodName: string) {\n return errorHandler(error, methodName);\n}\n","/*\n The \"use client\" directive is specifically for the Next.js layout component, which is rendered on the server by default.\n Because of this, we are explicitly marking it as a client component, so we can render this component on the client\n and properly initialize config on the client side.\n \n While this is specific to Next.js, it is simply ignored outside of Next.js and should not cause errors.\n*/\n\"use client\";\n\nimport { getLocalStorageSession } from './localStorage';\nimport { handleError } from './errorHandler';\nimport { reviveResponseTypes } from '../methods/serialize';\n\nexport type MethodArgs = Record<string, unknown>;\n\nexport async function callMethod<T = unknown>(methodName: string, args: MethodArgs = {}): Promise<T> {\n try {\n return await call<T>(`/api/_internal/method/${methodName}`, args);\n } catch (error) {\n handleError(error as Error, methodName);\n throw error;\n }\n}\n\nasync function call<T = unknown>(endpoint: string, args: MethodArgs): Promise<T> {\n const response = await fetch(endpoint, {\n method: 'POST',\n headers: {\n 'Content-Type': 'application/json',\n },\n body: JSON.stringify({\n args,\n authToken: getLocalStorageSession()?.authToken,\n clientInfo: {\n screenWidth: window.screen.width,\n screenHeight: window.screen.height,\n windowWidth: window.innerWidth,\n windowHeight: window.innerHeight,\n pixelRatio: window.devicePixelRatio,\n orientation: window.screen.orientation?.type\n }\n }),\n });\n\n if (!response.ok) {\n const error = await response.text();\n throw new Error(error);\n }\n\n const text = await response.text();\n const result = text ? JSON.parse(text) : undefined;\n if (!result) {\n throw new Error('Invalid response from server');\n }\n\n return reviveResponseTypes(result.data, result.typeMap);\n}\n","import { AppConfig, ConfigKey, Configs } from './types';\n\nlet config: Record<ConfigKey, AppConfig> = {};\n\n/**\n * @sidebarTitle getConfig (client)\n * \n * @param key\n * @returns \n */\nexport function getConfig(key: ConfigKey) {\n return config[key]?.value;\n}\n\nexport function _setConfig(configs: Configs) {\n config = configs;\n}\n","import { create } from 'zustand';\nimport { z } from 'zod';\nimport { callMethod } from './method';\nimport { _setConfig } from '../config/client';\nimport { setLocalStorageSession } from './localStorage';\nimport { time } from '../time';\nimport { Configs } from '../config/types';\n\ntype User = {\n id: string;\n handle: string;\n};\n\ntype SessionStore = {\n user: User | null;\n setUser: (user: User | null) => void;\n};\n\nexport const useSessionStore = create<SessionStore>((set) => ({\n user: null,\n setUser: (user) => set({ user }),\n}));\n\nlet isInitialized = false;\nconst SESSION_HEARTBEAT_INTERVAL = time.seconds(30);\n\nexport async function initSession() {\n if (isInitialized) {\n return;\n }\n\n isInitialized = true;\n\n const { configs, session, user } = await callMethod<{ configs: Configs, session: object, user: object }>('_system.session.init');\n _setConfig(configs);\n setLocalStorageSession(session);\n \n const parsedUser = user ? Object.freeze(z.object({\n id: z.string(),\n handle: z.string(),\n }).parse(user)) : null;\n\n useSessionStore.getState().setUser(parsedUser);\n\n await loopSessionHeartbeat();\n}\n\nasync function loopSessionHeartbeat() {\n await callMethod('_system.session.heartbeat');\n setTimeout(loopSessionHeartbeat, SESSION_HEARTBEAT_INTERVAL);\n}\n\nexport function setCurrentUser(user: User | null) {\n useSessionStore.getState().setUser(user);\n}\n\n/**\n * `useSession` is a hook that returns the current user, and in the future will also return other details about the current session.\n * \n * @example\n * ```ts\n * import { useSession } from 'modelence/client';\n * \n * function MyComponent() {\n * const { user } = useSession();\n * return <div>{user?.handle}</div>;\n * }\n * ```\n */\nexport function useSession() {\n const user = useSessionStore(state => state.user);\n return { user };\n}\n","/*\n The \"use client\" directive is specifically for the Next.js layout component, which is rendered on the server by default.\n Because of this, we are explicitly marking it as a client component, so we can render this component on the client\n and properly initialize config on the client side.\n \n While this is specific to Next.js, it is simply ignored outside of Next.js and should not cause errors.\n*/\n\"use client\";\n\nimport React, { useState, useEffect, ReactNode } from 'react';\nimport { initSession } from './session';\n\ninterface AppProviderProps {\n children: ReactNode;\n loadingElement?: ReactNode;\n}\n\nlet isInitialized = false;\n\nexport function AppProvider({ children, loadingElement }: AppProviderProps) {\n const [isLoading, setIsLoading] = useState(true);\n\n useEffect(() => {\n async function initConfig() {\n if (isInitialized) {\n return;\n }\n\n isInitialized = true;\n\n await initSession();\n setIsLoading(false);\n }\n\n initConfig();\n }, []);\n\n if (isLoading) {\n return loadingElement ?? <div>Loading...</div>;\n }\n\n return children;\n}\n","import React from 'react';\nimport ReactDOM from 'react-dom/client';\nimport { AppProvider } from '../client';\nimport { setErrorHandler, ErrorHandler } from './errorHandler';\n\nexport function renderApp({ loadingElement, routesElement, favicon, errorHandler }: {\n loadingElement: React.ReactNode,\n routesElement: React.ReactNode,\n favicon?: string,\n errorHandler?: ErrorHandler\n}) {\n if (errorHandler) {\n setErrorHandler(errorHandler);\n }\n\n window.addEventListener('unload', () => {\n // The presence of any 'unload' event handler, even empty,\n // prevents bfcache in most browsers\n });\n\n ReactDOM.createRoot(document.getElementById('root')!).render(\n <React.StrictMode>\n <AppProvider loadingElement={loadingElement}>\n {routesElement}\n </AppProvider>\n </React.StrictMode>\n );\n\n if (favicon) {\n const link = document.querySelector(\"link[rel~='icon']\") as HTMLLinkElement;\n if (!link) {\n const newLink = document.createElement('link');\n newLink.rel = 'icon';\n newLink.href = favicon;\n document.head.appendChild(newLink);\n } else {\n link.href = favicon;\n }\n }\n}\n","import { setCurrentUser } from '../../client/session';\nimport { callMethod } from '../../client/method';\n\nexport type UserInfo = {\n id: string;\n handle: string;\n};\n\n/**\n * Sign up a new user with an email and password.\n * \n * @example\n * ```ts\n * await signupWithPassword({ email: 'test@example.com', password: '12345678' });\n * ```\n * @param options.email - The email of the user.\n * @param options.password - The password of the user.\n */\nexport async function signupWithPassword(options: { email: string, password: string }) {\n const { email, password } = options;\n await callMethod('_system.user.signupWithPassword', { email, password });\n}\n\n/**\n * Login a user with an email and password.\n * \n * @example\n * ```ts\n * await loginWithPassword({ email: 'test@example.com', password: '12345678' });\n * ```\n * @param options.email - The email of the user.\n * @param options.password - The password of the user.\n */\nexport async function loginWithPassword(options: { email: string, password: string }) {\n const { email, password } = options;\n const { user } = await callMethod<{ user: UserInfo }>('_system.user.loginWithPassword', { email, password });\n setCurrentUser(user);\n return user;\n}\n\n/**\n * Verify user's email with a verification token.\n * \n * @example\n * ```ts\n * await verifyEmail({ token: 'verification-token' });\n * ```\n * @param options.token - The email verification token.\n */\nexport async function verifyEmail(options: { token: string }) {\n const { token } = options;\n await callMethod<{ user: UserInfo }>('_system.user.verifyEmail', { token });\n}\n\n/**\n * Logout the current user.\n * \n */\nexport async function logout() {\n await callMethod('_system.user.logout');\n setCurrentUser(null);\n}\n\n/**\n * Send reset password token.\n * @param options.email - The email of the user. \n */\nexport async function sendResetPasswordToken(options: { email: string }) {\n const { email } = options;\n await callMethod('_system.user.sendResetPasswordToken', {\n email,\n });\n}\n\n/**\n * Reset password.\n * @param options.token - The password reset token.\n * @param options.password - The new password.\n */\nexport async function resetPassword(options: { token: string, password: string }) {\n const { token, password } = options;\n await callMethod('_system.user.resetPassword', {\n token,\n password,\n });\n}\n","import React from 'react';\n\nimport { AppProvider as OriginalAppProvider } from './client/AppProvider';\n\nexport { getConfig } from './config/client';\n\nexport const AppProvider = 'useClient' in React\n // @ts-ignore: React.useClient only exists in Next.js\n ? React.useClient(OriginalAppProvider)\n : OriginalAppProvider;\n\nexport { renderApp } from './client/renderApp';\nexport { callMethod, type MethodArgs } from './client/method';\nexport { useSession } from './client/session';\nexport {\n signupWithPassword,\n loginWithPassword,\n verifyEmail,\n logout,\n sendResetPasswordToken,\n resetPassword,\n type UserInfo,\n} from './auth/client';\n"]}
|
|
@@ -0,0 +1,3 @@
|
|
|
1
|
+
var s="module",i="modelence",o="0.5.13-dev.0",p="The Node.js Framework for Real-Time MongoDB Apps",r="dist/index.js",n="dist/global.d.ts",d={".":"./dist/index.js","./client":"./dist/client.js","./server":"./dist/server.js","./telemetry":"./dist/telemetry.js","./mongodb":"./dist/mongo.js"},c=["dist","dist/bin"],l={modelence:"./dist/bin/modelence.js"},a={build:"tsup",dev:"tsup --watch",prepublishOnly:"npm run build",test:'echo "Error: no test specified" && exit 1',postversion:"git push && git push --tags"},m={type:"git",url:"git+https://github.com/modelence/modelence.git"},u="Modelence",g="SEE LICENSE IN LICENSE",y={url:"https://github.com/modelence/modelence/issues"},h="https://modelence.com",b={"@types/archiver":"^6.0.3","@types/bcrypt":"^5.0.2","@types/cookie-parser":"^1.4.9","@types/express":"^5.0.0","@types/fs-extra":"^11.0.4","@types/node":"^22.5.1","@types/passport-google-oauth20":"^2.0.16","@types/react":"^19.0.0","@types/react-dom":"^19.0.1","@typescript-eslint/eslint-plugin":"^8.17.0","@typescript-eslint/parser":"^8.17.0",react:"^19.0.0","react-dom":"^19.0.0"},v={"@modelence/types":"^1.0.3","@vitejs/plugin-react":"^4.3.4",archiver:"^7.0.1",bcrypt:"^5.1.1",commander:"^12.0.0","cookie-parser":"^1.4.7",dotenv:"^16.4.5","elastic-apm-node":"^4.8.0",express:"^4.21.0","fs-extra":"^11.2.0",jiti:"^2.4.2",mongodb:"^6.8.1",open:"^10.1.0",passport:"^0.7.0","passport-google-oauth20":"^2.0.0",tsup:"^8.3.6",tsx:"^4.19.3",typescript:"^5.7.2",vite:"^6.0.3","vite-plugin-eslint":"^1.8.1",winston:"^3.15.0","winston-elasticsearch":"^0.19.0",zod:"^3.23.8",zustand:"^5.0.2"},j={react:">=18.0.0","react-dom":">=18.0.0"},x={type:s,name:i,version:o,description:p,main:r,types:n,exports:d,files:c,bin:l,scripts:a,repository:m,author:u,license:g,bugs:y,homepage:h,devDependencies:b,dependencies:v,peerDependencies:j};
|
|
2
|
+
export{u as author,l as bin,y as bugs,x as default,v as dependencies,p as description,b as devDependencies,d as exports,c as files,h as homepage,g as license,r as main,i as name,j as peerDependencies,m as repository,a as scripts,s as type,n as types,o as version};//# sourceMappingURL=package-4ZTUD7K2.js.map
|
|
3
|
+
//# sourceMappingURL=package-4ZTUD7K2.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../package.json"],"names":["type","name","version","description","main","types","exports","files","bin","scripts","repository","author","license","bugs","homepage","devDependencies","dependencies","peerDependencies","package_default"],"mappings":"AACE,IAAAA,CAAAA,CAAQ,SACRC,CAAAA,CAAQ,WAAA,CACRC,EAAW,cAA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ACR,GAAA,CAAO,SAAA,CACP,WAAc,QAAA,CACd,IAAA,CAAQ,SACR,oBAAA,CAAsB,QAAA,CACtB,QAAW,SAAA,CACX,uBAAA,CAAyB,UACzB,GAAA,CAAO,SAAA,CACP,QAAW,QACb,CAAA,CACAC,EAAoB,CAClB,KAAA,CAAS,WACT,WAAA,CAAa,UACf,EAlFFC,CAAAA,CAAA,CACE,KAAAlB,CAAAA,CACA,IAAA,CAAAC,EACA,OAAA,CAAAC,CAAAA,CACA,YAAAC,CAAAA,CACA,IAAA,CAAAC,EACA,KAAA,CAAAC,CAAAA,CACA,QAAAC,CAAAA,CAOA,KAAA,CAAAC,EAIA,GAAA,CAAAC,CAAAA,CAGA,QAAAC,CAAAA,CAOA,UAAA,CAAAC,EAIA,MAAA,CAAAC,CAAAA,CACA,QAAAC,CAAAA,CACA,IAAA,CAAAC,EAGA,QAAA,CAAAC,CAAAA,CACA,gBAAAC,CAAAA,CAeA,YAAA,CAAAC,CAAAA,CA0BA,gBAAA,CAAAC,CAIF","file":"package-4ZTUD7K2.js","sourcesContent":["{\n \"type\": \"module\",\n \"name\": \"modelence\",\n \"version\": \"0.5.13-dev.0\",\n \"description\": \"The Node.js Framework for Real-Time MongoDB Apps\",\n \"main\": \"dist/index.js\",\n \"types\": \"dist/global.d.ts\",\n \"exports\": {\n \".\": \"./dist/index.js\",\n \"./client\": \"./dist/client.js\",\n \"./server\": \"./dist/server.js\",\n \"./telemetry\": \"./dist/telemetry.js\",\n \"./mongodb\": \"./dist/mongo.js\"\n },\n \"files\": [\n \"dist\",\n \"dist/bin\"\n ],\n \"bin\": {\n \"modelence\": \"./dist/bin/modelence.js\"\n },\n \"scripts\": {\n \"build\": \"tsup\",\n \"dev\": \"tsup --watch\",\n \"prepublishOnly\": \"npm run build\",\n \"test\": \"echo \\\"Error: no test specified\\\" && exit 1\",\n \"postversion\": \"git push && git push --tags\"\n },\n \"repository\": {\n \"type\": \"git\",\n \"url\": \"git+https://github.com/modelence/modelence.git\"\n },\n \"author\": \"Modelence\",\n \"license\": \"SEE LICENSE IN LICENSE\",\n \"bugs\": {\n \"url\": \"https://github.com/modelence/modelence/issues\"\n },\n \"homepage\": \"https://modelence.com\",\n \"devDependencies\": {\n \"@types/archiver\": \"^6.0.3\",\n \"@types/bcrypt\": \"^5.0.2\",\n \"@types/cookie-parser\": \"^1.4.9\",\n \"@types/express\": \"^5.0.0\",\n \"@types/fs-extra\": \"^11.0.4\",\n \"@types/node\": \"^22.5.1\",\n \"@types/passport-google-oauth20\": \"^2.0.16\",\n \"@types/react\": \"^19.0.0\",\n \"@types/react-dom\": \"^19.0.1\",\n \"@typescript-eslint/eslint-plugin\": \"^8.17.0\",\n \"@typescript-eslint/parser\": \"^8.17.0\",\n \"react\": \"^19.0.0\",\n \"react-dom\": \"^19.0.0\"\n },\n \"dependencies\": {\n \"@modelence/types\": \"^1.0.3\",\n \"@vitejs/plugin-react\": \"^4.3.4\",\n \"archiver\": \"^7.0.1\",\n \"bcrypt\": \"^5.1.1\",\n \"commander\": \"^12.0.0\",\n \"cookie-parser\": \"^1.4.7\",\n \"dotenv\": \"^16.4.5\",\n \"elastic-apm-node\": \"^4.8.0\",\n \"express\": \"^4.21.0\",\n \"fs-extra\": \"^11.2.0\",\n \"jiti\": \"^2.4.2\",\n \"mongodb\": \"^6.8.1\",\n \"open\": \"^10.1.0\",\n \"passport\": \"^0.7.0\",\n \"passport-google-oauth20\": \"^2.0.0\",\n \"tsup\": \"^8.3.6\",\n \"tsx\": \"^4.19.3\",\n \"typescript\": \"^5.7.2\",\n \"vite\": \"^6.0.3\",\n \"vite-plugin-eslint\": \"^1.8.1\",\n \"winston\": \"^3.15.0\",\n \"winston-elasticsearch\": \"^0.19.0\",\n \"zod\": \"^3.23.8\",\n \"zustand\": \"^5.0.2\"\n },\n \"peerDependencies\": {\n \"react\": \">=18.0.0\",\n \"react-dom\": \">=18.0.0\"\n }\n}\n"]}
|
package/dist/server.d.ts
CHANGED
|
@@ -425,6 +425,15 @@ type EmailConfig = {
|
|
|
425
425
|
}) => string;
|
|
426
426
|
redirectUrl?: string;
|
|
427
427
|
};
|
|
428
|
+
passwordReset?: {
|
|
429
|
+
subject?: string;
|
|
430
|
+
template?: (props: {
|
|
431
|
+
name: string;
|
|
432
|
+
email: string;
|
|
433
|
+
resetUrl: string;
|
|
434
|
+
}) => string;
|
|
435
|
+
redirectUrl?: string;
|
|
436
|
+
};
|
|
428
437
|
emailVerifiedRedirectUrl?: string;
|
|
429
438
|
};
|
|
430
439
|
|
package/dist/server.js
CHANGED
|
@@ -1,11 +1,18 @@
|
|
|
1
|
-
import {a as a$3}from'./chunk-DN5SVAO2.js';import {d,a as a$4}from'./chunk-C3UESBRX.js';import {a as a$1}from'./chunk-R7MPLJMA.js';import {b,e,d as d$
|
|
2
|
-
`).map(r=>r.trim().toLowerCase()).filter(r=>r.length>0),n=new Date,i=500;for(let r=0;r<o.length;r+=i){let s=o.slice(r,r+i);try{await
|
|
1
|
+
import {a as a$3}from'./chunk-DN5SVAO2.js';import {d as d$1,a as a$4}from'./chunk-C3UESBRX.js';import {a as a$1}from'./chunk-R7MPLJMA.js';import {b as b$1,e,d as d$2,c,f as f$1,g as g$1,a as a$2,h as h$1,j,k as k$1}from'./chunk-2QLNYYBR.js';export{a as getConfig}from'./chunk-2QLNYYBR.js';import pt from'dotenv';import mo from'fs/promises';import Ut from'os';import ne from'path';import {randomBytes}from'crypto';import {ObjectId,MongoClient}from'mongodb';export{ObjectId}from'mongodb';import E,{z as z$1}from'zod';import vt from'bcrypt';import {createServer,defineConfig,loadConfigFromFile}from'vite';import Kt from'@vitejs/plugin-react';import Gt from'fs';import se,{Router}from'express';import ie from'passport';import {Strategy}from'passport-google-oauth20';import ro from'cookie-parser';import io from'http';var ge=new Map,M={authenticated:null,unauthenticated:null};function we(t,e){M.authenticated=e.authenticated,M.unauthenticated=e.unauthenticated;for(let[o,n]of Object.entries(t))ge.set(o,n);}function N(){return M.unauthenticated?[M.unauthenticated]:[]}function ye(){return M.authenticated?[M.authenticated]:[]}function be(t,e){let o=e.find(n=>!gt(t,n));if(o)throw new Error(`Access denied - missing permission: '${o}'`)}function gt(t,e){for(let o of t){let n=ge.get(o);if(n&&n.permissions.includes(e))return true}return false}var g=class{constructor(e,{stores:o=[],queries:n={},mutations:i={},routes:r=[],cronJobs:s={},configSchema:c={},rateLimits:u=[]}){this.name=e,this.stores=o,this.queries=n,this.mutations=i,this.routes=r,this.cronJobs=s,this.configSchema=c,this.rateLimits=u;}};var f=class{constructor(e,o){this.name=e,this.schema=o.schema,this.methods=o.methods,this.indexes=o.indexes;}getName(){return this.name}getSchema(){return this.schema}init(e){if(this.collection)throw new Error(`Collection ${this.name} is already initialized`);this.client=e,this.collection=this.client.db().collection(this.name);}async createIndexes(){this.indexes.length>0&&await this.requireCollection().createIndexes(this.indexes);}wrapDocument(e){return this.methods?Object.create(null,Object.getOwnPropertyDescriptors({...e,...this.methods})):e}getSelector(e){return typeof e=="string"?{_id:new ObjectId(e)}:e instanceof ObjectId?{_id:e}:e}requireCollection(){if(!this.collection)throw new Error(`Collection ${this.name} is not provisioned`);return this.collection}requireClient(){if(!this.client)throw new Error("Database is not connected");return this.client}async findOne(e,o){let n=await this.requireCollection().findOne(e,o);return n?this.wrapDocument(n):null}async requireOne(e,o,n){let i=await this.findOne(e,o);if(!i)throw n?n():new Error(`Record not found in ${this.name}`);return i}find(e,o){let n=this.requireCollection().find(e);return o?.sort&&n.sort(o.sort),o?.limit&&n.limit(o.limit),o?.skip&&n.skip(o.skip),n}async findById(e){let o=typeof e=="string"?{_id:new ObjectId(e)}:{_id:e};return await this.findOne(o)}async requireById(e,o){let n=await this.findById(e);if(!n)throw o?o():new Error(`Record with id ${e} not found in ${this.name}`);return n}countDocuments(e){return this.requireCollection().countDocuments(e)}async fetch(e,o){return (await this.find(e,o).toArray()).map(this.wrapDocument.bind(this))}async insertOne(e){return await this.requireCollection().insertOne(e)}async insertMany(e){return await this.requireCollection().insertMany(e)}async updateOne(e,o){return await this.requireCollection().updateOne(this.getSelector(e),o)}async upsertOne(e,o){return await this.requireCollection().updateOne(this.getSelector(e),o,{upsert:true})}async updateMany(e,o,n){return await this.requireCollection().updateMany(e,o,n)}async upsertMany(e,o){return await this.requireCollection().updateMany(e,o,{upsert:true})}async deleteOne(e){return await this.requireCollection().deleteOne(e)}async deleteMany(e){return await this.requireCollection().deleteMany(e)}aggregate(e,o){return this.requireCollection().aggregate(e,o)}bulkWrite(e){return this.requireCollection().bulkWrite(e)}getDatabase(){return this.requireClient().db()}rawCollection(){return this.requireCollection()}async renameFrom(e,o){let n=this.getDatabase();if(!this.collection||!n)throw new Error(`Store ${this.name} is not provisioned`);if((await n.listCollections({name:e}).toArray()).length===0)throw new Error(`Collection ${e} not found`);if((await n.listCollections({name:this.name}).toArray()).length>0)throw new Error(`Collection ${this.name} already exists`);await n.collection(e).rename(this.name,o);}};var wt=z$1.string.bind(z$1),yt=z$1.number.bind(z$1),bt=z$1.date.bind(z$1),Et=z$1.boolean.bind(z$1),Ct=z$1.array.bind(z$1),xt=z$1.object.bind(z$1),St=z$1.enum.bind(z$1),a={string:wt,number:yt,date:bt,boolean:Et,array:Ct,object:xt,enum:St,objectId(){return z$1.instanceof(ObjectId)},userId(){return z$1.instanceof(ObjectId)},ref(t){return z$1.instanceof(ObjectId)},union:z$1.union.bind(z$1),infer(t){return {}}};var _=new f("_modelenceSessions",{schema:{authToken:a.string(),createdAt:a.date(),expiresAt:a.date(),userId:a.userId().nullable()},indexes:[{key:{authToken:1},unique:true},{key:{expiresAt:1}}]});async function Ee(t){let e=t?await _.findOne({authToken:t}):null;return e?{authToken:String(e.authToken),expiresAt:new Date(e.expiresAt),userId:e.userId??null}:await K()}async function Ce(t,e){await _.updateOne({authToken:t},{$set:{userId:e}});}async function xe(t){await _.updateOne({authToken:t},{$set:{userId:null}});}async function K(t=null){let e=randomBytes(32).toString("base64url"),o=Date.now(),n=new Date(o+a$1.days(7));return await _.insertOne({authToken:e,createdAt:new Date(o),expiresAt:n,userId:t}),{authToken:e,expiresAt:n,userId:t}}async function Dt(t){let e=Date.now(),o=new Date(e+a$1.days(7));await _.updateOne({authToken:t.authToken},{$set:{lastActiveDate:new Date(e),expiresAt:o}});}var Se=new g("_system.session",{stores:[_],mutations:{init:async function(t,{session:e,user:o}){return {session:e,user:o,configs:b$1()}},heartbeat:async function(t,{session:e}){e&&await Dt(e);}}});var d=new f("_modelenceUsers",{schema:{handle:a.string(),emails:a.array(a.object({address:a.string(),verified:a.boolean()})).optional(),createdAt:a.date(),authMethods:a.object({password:a.object({hash:a.string()}).optional(),google:a.object({id:a.string()}).optional()})},indexes:[{key:{handle:1},unique:true,collation:{locale:"en",strength:2}}]}),k=new f("_modelenceDisposableEmailDomains",{schema:{domain:a.string(),addedAt:a.date()},indexes:[{key:{domain:1},unique:true}]}),T=new f("_modelenceEmailVerificationTokens",{schema:{userId:a.objectId(),email:a.string().optional(),token:a.string(),createdAt:a.date(),expiresAt:a.date()},indexes:[{key:{token:1},unique:true},{key:{expiresAt:1},expireAfterSeconds:0}]}),x=new f("_modelenceResetPasswordTokens",{schema:{userId:a.objectId(),token:a.string(),createdAt:a.date(),expiresAt:a.date()},indexes:[{key:{token:1},unique:true},{key:{expiresAt:1},expireAfterSeconds:0}]});async function Re(t){let e=t.toLowerCase().trim().split("@");if(e.length!==2)return false;let o=e[1];return !!await k.findOne({domain:o})}var De={interval:a$1.days(1),async handler(){let t=await fetch("https://disposable.github.io/disposable-email-domains/domains.txt");if(!t.ok)throw new Error(`HTTP ${t.status}: ${t.statusText}`);let o=(await t.text()).split(`
|
|
2
|
+
`).map(r=>r.trim().toLowerCase()).filter(r=>r.length>0),n=new Date,i=500;for(let r=0;r<o.length;r+=i){let s=o.slice(r,r+i);try{await k.insertMany(s.map(c=>({domain:c,addedAt:n})));}catch(c){c.name==="MongoBulkWriteError"&&c.result?.nInserted;}}}};var G=Object.freeze({});function Me(t){G=Object.freeze(Object.assign({},G,t));}function h(){return G}function Mt(){return typeof window!="object"}function S(){if(!Mt())throw new Error("This function can only be called on the server")}function J(t){return t.replace(/<[^>]*>/g,"").replace(/\s+/g," ").trim()}function _e({name:t,email:e,verificationUrl:o}){return `
|
|
3
3
|
<p>Hi${t?` ${t}`:""},</p>
|
|
4
4
|
<p>Please verify your email address ${e} by clicking the link below:</p>
|
|
5
5
|
<p><a href="${o}">${o}</a></p>
|
|
6
6
|
<p>If you did not request this, please ignore this email.</p>
|
|
7
|
-
`}async function Me(t){let e=g().emailVerifiedRedirectUrl||"/";try{let o=z.string().parse(t.query.token),n=await _.findOne({token:o,expiresAt:{$gt:new Date}});if(!n)throw new Error("Invalid or expired verification token");if(!await m.findOne({_id:n.userId}))throw new Error("User not found");let r=n.email;if(!r)throw new Error("Email not found in token");if((await m.updateOne({_id:n.userId,"emails.address":r,"emails.verified":{$ne:!0}},{$set:{"emails.$.verified":!0}})).matchedCount===0)throw await m.findOne({_id:n.userId,"emails.address":r})?new Error("Email is already verified"):new Error("Email address not found for this user");await _.deleteOne({_id:n._id});}catch(o){if(o instanceof Error)return console.error("Error verifying email:",o),{status:301,redirect:`${e}?status=error&message=${encodeURIComponent(o.message)}`}}return {status:301,redirect:`${e}?status=verified`}}async function N({userId:t,email:e,baseUrl:o=process.env.MODELENCE_SITE_URL}){if(g().provider){let n=g().provider,i=randomBytes(32).toString("hex"),r=new Date(Date.now()+a$1.hours(24));await _.insertOne({userId:t,email:e,token:i,createdAt:new Date,expiresAt:r});let s=`${o}/api/_internal/auth/verify-email?token=${i}`,d=(g()?.verification?.template||Re)({name:"",email:e,verificationUrl:s}),l=De(d);await n?.sendEmail({to:e,from:g()?.from||"noreply@modelence.com",subject:g()?.verification?.subject||"Verify your email address",text:l,html:d});}}async function Te(t,{user:e,session:o,connectionInfo:n}){if(!o)throw new Error("Session is not initialized");let i=n?.ip;i&&await S({bucket:"signin",type:"ip",value:i});let r=z.string().email().parse(t.email),s=z.string().parse(t.password),c=await m.findOne({"emails.address":r},{collation:{locale:"en",strength:2}}),d=c?.authMethods?.password?.hash;if(!d)throw ve();if(!c.emails?.find(y=>y.address===r)?.verified&&g()?.provider){if(i)try{await S({bucket:"verification",type:"user",value:c._id.toString()});}catch{throw new Error("Your email address hasn't been verified yet. Please use the verification email we've send earlier to your inbox.")}throw await N({userId:c?._id,email:r,baseUrl:n?.baseUrl}),new Error("Your email address hasn't been verified yet. We've sent a new verification email to your inbox.")}if(!await Rt.compare(s,d))throw ve();return await we(o.authToken,c._id),{user:{id:c._id,handle:c.handle}}}async function Oe(t,{user:e,session:o}){if(!o)throw new Error("Session is not initialized");await be(o.authToken);}function ve(){return new Error("Incorrect email/password combination")}async function Ie(t,{user:e}){if(!e)throw new Error("Not authenticated");let o=await m.requireById(e.id);return {handle:o.handle,emails:o.emails,authMethods:Object.keys(o.authMethods||{})}}var I=new f("_modelenceRateLimits",{schema:{bucket:a.string(),type:a.enum(["ip","user"]),value:a.string(),windowMs:a.number(),windowStart:a.date(),windowCount:a.number(),prevWindowCount:a.number(),expiresAt:a.date()},indexes:[{key:{bucket:1,type:1,value:1,windowMs:1},unique:true},{key:{expiresAt:1},expireAfterSeconds:0}]});var K=[];function ke(t){if(K.length>0)throw new Error("Duplicate call to initRateLimits - already initialized");K=t;}async function S(t){let{bucket:e,type:o,value:n}=t,i=K.filter(r=>r.bucket===e&&r.type===o);for(let r of i)await Mt(r,n);}async function Mt(t,e,o){let n=()=>new d(`Rate limit exceeded for ${t.bucket}`),i=await I.findOne({bucket:t.bucket,type:t.type,value:e,windowMs:t.window}),r=Date.now(),s=Math.floor(r/t.window)*t.window,{count:c,modifier:d$1}=i?_t(i,s,r):{count:0,modifier:{$setOnInsert:{windowStart:new Date(s),windowCount:1,prevWindowCount:0,expiresAt:new Date(s+t.window+t.window)}}};if(c>=t.limit)throw n();await I.upsertOne({bucket:t.bucket,type:t.type,value:e,windowMs:t.window},d$1);}function _t(t,e,o){let n=e-t.windowMs;if(t.windowStart.getTime()===e){let i=t.windowCount,r=t.prevWindowCount,s=1-(o-e)/t.windowMs;return {count:Math.round(i+r*s),modifier:{$inc:{windowCount:1},$setOnInsert:{windowStart:new Date(e),prevWindowCount:0,expiresAt:new Date(e+t.windowMs+t.windowMs)}}}}if(t.windowStart.getTime()===n){let i=1-(o-e)/t.windowMs;return {count:Math.round(t.windowCount*i),modifier:{$set:{windowStart:new Date(e),windowCount:1,prevWindowCount:t.windowCount,expiresAt:new Date(e+t.windowMs+t.windowMs)}}}}return {count:0,modifier:{$set:{windowStart:new Date(e),windowCount:1,prevWindowCount:0,expiresAt:new Date(e+t.windowMs+t.windowMs)}}}}async function Le(t,{user:e,connectionInfo:o}){let n=z.string().email().parse(t.email),i=z.string().min(8,{message:"Password must contain at least 8 characters"}).parse(t.password),r=o?.ip;if(r&&await S({bucket:"signupAttempt",type:"ip",value:r}),await Ce(n))throw new Error("Please use a permanent email address");let s=await m.findOne({"emails.address":n},{collation:{locale:"en",strength:2}});if(s){let l=s.emails?.find(E=>E.address===n);throw new Error(`User with email already exists: ${l?.address}`)}r&&await S({bucket:"signup",type:"ip",value:r});let c=await Rt.hash(i,10),d=await m.insertOne({handle:n,emails:[{address:n,verified:false}],createdAt:new Date,authMethods:{password:{hash:c}}});return await N({userId:d?.insertedId,email:n,baseUrl:o?.baseUrl}),d.insertedId}var Pe=new h("_system.user",{stores:[m,O,_],queries:{getOwnProfile:Ie},mutations:{signupWithPassword:Le,loginWithPassword:Te,logout:Oe},cronJobs:{updateDisposableEmailList:xe},rateLimits:[{bucket:"signup",type:"ip",window:a$1.minutes(15),limit:20},{bucket:"signup",type:"ip",window:a$1.days(1),limit:200},{bucket:"signupAttempt",type:"ip",window:a$1.minutes(15),limit:50},{bucket:"signupAttempt",type:"ip",window:a$1.days(1),limit:500},{bucket:"signin",type:"ip",window:a$1.minutes(15),limit:50},{bucket:"signin",type:"ip",window:a$1.days(1),limit:500},{bucket:"verification",type:"user",window:a$1.minutes(15),limit:3},{bucket:"verification",type:"user",window:a$1.days(1),limit:10}],configSchema:{"auth.email.enabled":{type:"boolean",isPublic:true,default:true},"auth.email.from":{type:"string",isPublic:false,default:""},"auth.email.verification":{type:"boolean",isPublic:true,default:false},"auth.google.enabled":{type:"boolean",isPublic:true,default:false},"auth.google.clientId":{type:"string",isPublic:false,default:""},"auth.google.clientSecret":{type:"secret",isPublic:false,default:""}},routes:[{path:"/api/_internal/auth/verify-email",handlers:{get:Me}}]});async function je({configSchema:t,cronJobsMetadata:e,stores:o}){let n=process.env.MODELENCE_CONTAINER_ID;if(!n)throw new Error("Unable to connect to Modelence Cloud: MODELENCE_CONTAINER_ID is not set");try{let i=Object.values(o).map(s=>({name:s.getName(),schema:s.getSchema(),collections:[s.getName()]})),r=await G("/api/connect","POST",{hostname:Tt.hostname(),containerId:n,dataModels:i,configSchema:t,cronJobsMetadata:e});if(r.status==="error")throw new Error(r.error);return console.log("Successfully connected to Modelence Cloud"),r}catch(i){throw console.error("Unable to connect to Modelence Cloud:",i),i}}async function $e(){return await G("/api/configs","GET")}async function Ne(){return await G("/api/sync","POST",{containerId:process.env.MODELENCE_CONTAINER_ID})}async function G(t,e,o){let{MODELENCE_SERVICE_ENDPOINT:n,MODELENCE_SERVICE_TOKEN:i}=process.env;if(!n)throw new Error("Unable to connect to Modelence Cloud: MODELENCE_SERVICE_ENDPOINT is not set");let r=await fetch(`${n}${t}`,{method:e,headers:{Authorization:`Bearer ${i}`,...o?{"Content-Type":"application/json"}:{}},body:o?JSON.stringify(o):void 0});if(!r.ok){let s=await r.text();try{let c=JSON.parse(s);throw new Error(`Unable to connect to Modelence Cloud: HTTP status: ${r.status}, ${c?.error}`)}catch{throw new Error(`Unable to connect to Modelence Cloud: HTTP status: ${r.status}, ${s}`)}}return await r.json()}var Z=false,Ot=a$1.seconds(10);function Ue(){setInterval(async()=>{if(!Z){Z=true;try{await Ne();}catch(t){console.error("Error syncing status",t);}try{await It();}catch(t){console.error("Error syncing config",t);}Z=false;}},Ot);}async function It(){let{configs:t}=await $e();c(t);}var kt=a$1.minutes(1),At=a$1.seconds(10),D={},Q,k=new f("_modelenceCronJobs",{schema:{alias:a.string(),lastStartDate:a.date().optional(),lock:a.object({containerId:a.string(),acquireDate:a.date()}).optional()},indexes:[{key:{alias:1},unique:true,background:true}]});function qe(t,{description:e="",interval:o,timeout:n=kt,handler:i}){if(D[t])throw new Error(`Duplicate cron job declaration: '${t}' already exists`);if(Q)throw new Error(`Unable to add a cron job - cron jobs have already been initialized: [${t}]`);if(o<a$1.seconds(5))throw new Error(`Cron job interval should not be less than 5 second [${t}]`);if(n>a$1.days(1))throw new Error(`Cron job timeout should not be longer than 1 day [${t}]`);D[t]={alias:t,params:{description:e,interval:o,timeout:n},handler:i,state:{isRunning:false}};}async function Be(){if(Q)throw new Error("Cron jobs already started");let t=Object.keys(D);if(t.length>0){let e={alias:{$in:t}},o=await k.findOne({...e,"lock.containerId":{$exists:true}});await Promise.all(t.map(r=>k.upsertOne({alias:r},{$set:{lock:{containerId:process.env.MODELENCE_CONTAINER_ID||"unknown",acquireDate:new Date}}}))),o&&await Lt(At);let n=await k.fetch(e),i=Date.now();n.forEach(r=>{let s=D[r.alias];s&&(s.state.scheduledRunTs=r.lastStartDate?r.lastStartDate.getTime()+s.params.interval:i);}),Object.values(D).forEach(r=>{r.state.scheduledRunTs||(r.state.scheduledRunTs=i);}),Q=setInterval(Pt,a$1.seconds(1));}}function Lt(t){return new Promise(e=>setTimeout(e,t))}async function Pt(){let t=Date.now();Object.values(D).forEach(async e=>{let{params:o,state:n}=e;if(n.isRunning){n.startTs&&n.startTs+o.timeout<t&&(n.isRunning=false);return}n.scheduledRunTs&&n.scheduledRunTs<=t&&await jt(e);});}async function jt(t){let{alias:e,params:o,handler:n,state:i}=t;i.isRunning=true,i.startTs=Date.now();let r=j("cron",`cron:${e}`);n().then(()=>{Je(i,o),r.end("success");}).catch(s=>{Je(i,o),k$1(s),r.end("error"),console.error(`Error in cron job '${e}':`,s);}),await k.updateOne({alias:e},{$set:{lastStartDate:new Date(i.startTs)}});}function Je(t,e){t.scheduledRunTs=t.startTs?t.startTs+e.interval:Date.now(),t.startTs=void 0,t.isRunning=false;}function ze(){return Object.values(D).map(({alias:t,params:e})=>({alias:t,description:e.description,interval:e.interval,timeout:e.timeout}))}var Fe=new h("_system.cron",{stores:[k]});var w=null;async function Ve(){if(w)return w;let t=A();if(!t)throw new Error("MongoDB URI is not set");w=new MongoClient(t,{maxPoolSize:20});try{return await w.connect(),await w.db("admin").command({ping:1}),console.log("Pinged your deployment. You successfully connected to MongoDB!"),w}catch(e){throw console.error(e),w=null,e}}function A(){let t=a$2("_system.mongodbUri");return t?String(t):void 0}function We(){return w}var Y={};function X(t,e){return x(),Ze(t),U("query",t,e)}function He(t,e){return x(),Ze(t),U("mutation",t,e)}function Ke(t,e){return x(),Qe(t),U("query",t,e)}function Ge(t,e){return x(),Qe(t),U("mutation",t,e)}function Ze(t){if(t.toLowerCase().startsWith("_system."))throw new Error(`Method name cannot start with a reserved prefix: '_system.' (${t})`)}function Qe(t){if(!t.toLowerCase().startsWith("_system."))throw new Error(`System method name must start with a prefix: '_system.' (${t})`)}function U(t,e,o){if(x(),Y[e])throw new Error(`Method with name '${e}' is already defined.`);let n=typeof o=="function"?o:o.handler,i=typeof o=="function"?[]:o.permissions??[];Y[e]={type:t,name:e,handler:n,permissions:i};}async function Ye(t,e,o){x();let n=Y[t];if(!n)throw new Error(`Method with name '${t}' is not defined.`);let{type:i,handler:r}=n,s=j("method",`method:${t}`,{type:i,args:e}),c;try{ge(o.roles,n.permissions),c=await r(e,o);}catch(d){throw s.end("error"),d}return s.end(),c}var J=new f("_modelenceMigrations",{schema:{version:a.number(),appliedAt:a.date()},indexes:[{key:{version:1},unique:true}]});async function Xe(t){if(t.length===0)return;let e=t.map(({version:r})=>r),o=await J.fetch({version:{$in:e}}),n=new Set(o.map(({version:r})=>r)),i=t.filter(({version:r})=>!n.has(r));if(i.length!==0){console.log(`Running migrations (${i.length})...`);for(let{version:r,description:s,handler:c}of i)console.log(`Running migration v${r}: ${s}`),await J.insertOne({version:r,appliedAt:new Date}),await c(),console.log(`Migration v${r} complete`);}}var et=new h("_system.migration",{stores:[J]});var tt=new h("_system.rateLimit",{stores:[I]});var te=class{async init(){this.config=await Ft(),this.isDev()&&(console.log("Starting Vite dev server..."),this.viteServer=await createServer({...defineConfig(this.config),server:{middlewareMode:true},root:"./src/client"}));}middlewares(){if(this.isDev())return this.viteServer?.middlewares??[];let e=[ne.static("./.modelence/build/client")];return this.config?.publicDir&&e.push(ne.static(this.config.publicDir)),e}handler(e,o){if(this.isDev())try{o.sendFile("index.html",{root:"./src/client"});}catch(n){console.error("Error serving index.html:",n),o.status(500).send("Internal Server Error");}else o.sendFile("index.html",{root:"./.modelence/build/client"});}isDev(){return process.env.NODE_ENV!=="production"}};async function zt(){let t=process.cwd();try{return (await loadConfigFromFile({command:"serve",mode:"development"},void 0,t))?.config||{}}catch(e){return console.warn("Could not load vite config:",e),{}}}async function Ft(){let t=process.cwd(),e=await zt(),o=[".eslintrc.js",".eslintrc.json",".eslintrc","eslint.config.js",".eslintrc.yml",".eslintrc.yaml"].find(i=>Bt.existsSync(ee.join(t,i))),n=[qt(),Vt()];if(o){let i=(await import('vite-plugin-eslint')).default;n.push(i({failOnError:false,include:["src/**/*.js","src/**/*.jsx","src/**/*.ts","src/**/*.tsx"],cwd:t,overrideConfigFile:ee.resolve(t,o)}));}return {plugins:n,root:t,build:{outDir:".modelence/build/client",emptyOutDir:true},server:{proxy:{"/api":"http://localhost:4000"},headers:{"Cache-Control":"no-store, no-cache, must-revalidate, proxy-revalidate, max-age=0",Pragma:"no-cache",Expires:"0"},hmr:{port:0}},resolve:{alias:{"@":ee.resolve(t,"src")}},publicDir:e.publicDir}}function Vt(){return {name:"modelence-asset-handler",async transform(t,e){if(/\.(png|jpe?g|gif|svg|mpwebm|ogg|mp3|wav|flac|aac)$/.test(e))return process.env.NODE_ENV==="development",t},async generateBundle(t,e){}}}var nt=new te;async function rt(t,e){let{authToken:o}=await W(e);t.cookie("authToken",o,{httpOnly:true,secure:process.env.NODE_ENV==="production",sameSite:"strict"}),t.status(301),t.redirect("/");}async function Kt(t,e){let o=t.user,n=await m.findOne({"authMethods.google.id":o.id});if(n){await rt(e,n._id);return}let i=o.emails[0]&&o.emails[0]?.value;if(i||e.status(400).json({error:"Email address is required for Google authentication."}),await m.findOne({"emails.address":i},{collation:{locale:"en",strength:2}})){e.status(400).json({error:"User with this email already exists. Please log in instead."});return}let s=await m.insertOne({handle:i,emails:[{address:i,verified:true}],createdAt:new Date,authMethods:{google:{id:o.id}}});await rt(e,s.insertedId);}function Gt(){let t=Router(),e=!!a$2("_system.user.auth.google.enabled"),o=String(a$2("_system.user.auth.google.clientId")),n=String(a$2("_system.user.auth.google.clientSecret"));return !e||!o||!n||(oe.use(new Strategy({clientID:o,clientSecret:n,callbackURL:"/api/_internal/auth/google/callback",proxy:true},(i,r,s,c)=>c(null,s))),t.get("/api/_internal/auth/google",oe.authenticate("google",{scope:["profile","email"],session:false})),t.get("/api/_internal/auth/google/callback",oe.authenticate("google",{session:false}),Kt)),t}var it=Gt;function st(t){return async(e,o)=>{try{let n=await t({query:e.query,body:e.body,params:e.params,headers:e.headers,cookies:e.cookies,req:e});o.status(n.status||200),n.redirect&&o.redirect(n.redirect),n.headers&&Object.entries(n.headers).forEach(([i,r])=>{o.setHeader(i,r);}),o.send(n.data);}catch(n){n instanceof a$4?o.status(n.status).send(n.message):(console.error(`Error in route handler: ${e.path}`),console.error(n),o.status(500).send(String(n)));}}}async function at(t){let e=await ye(t),o=e.userId?await m.findOne({_id:new ObjectId(e.userId)}):null,n=o?{id:o._id.toString(),handle:o.handle}:null,i=n?he():$();return {user:n,session:e,roles:i}}function eo(t,e){for(let o of e)for(let n of o.routes){let{path:i,handlers:r}=n;Object.entries(r).forEach(([s,c])=>{t[s](i,st(c));});}}async function ct(t,{combinedModules:e}){let o=ne();o.use(ne.json()),o.use(ne.urlencoded({extended:true})),o.use(Qt()),o.use(oe.initialize()),o.use(it()),o.post("/api/_internal/method/:methodName(*)",async(r,s)=>{let{methodName:c}=r.params,d=await to(r);try{let l=await Ye(c,r.body.args,d);s.json({data:l,typeMap:a$3(l)});}catch(l){if(console.error(`Error in method ${c}:`,l),l instanceof a$4)s.status(l.status).send(l.message);else if(l instanceof Error&&l?.constructor?.name==="ZodError"&&"errors"in l){let y=l.flatten(),q=Object.entries(y.fieldErrors).map(([B,z])=>`${B}: ${(z??[]).join(", ")}`).join("; "),L=y.formErrors.join("; "),v=[q,L].filter(Boolean).join("; ");s.status(400).send(v);}else s.status(500).send(l instanceof Error?l.message:String(l));}}),eo(o,e),await t.init(),t.middlewares&&o.use(t.middlewares()),o.all("*",(r,s)=>t.handler(r,s)),process.on("unhandledRejection",(r,s)=>{console.error("Unhandled Promise Rejection:"),console.error(r instanceof Error?r.stack:r),console.error("Promise:",s);}),process.on("uncaughtException",r=>{console.error("Uncaught Exception:"),console.error(r.stack),console.trace("Full application stack:");});let n=Yt.createServer(o),i=process.env.PORT||3e3;n.listen(i,()=>{h$1("Application started",{source:"app"}),console.log(`
|
|
7
|
+
`}async function Te(t){let e=process.env.MODELENCE_SITE_URL,o=h().emailVerifiedRedirectUrl||e||"/";try{let n=z$1.string().parse(t.query.token),i=await T.findOne({token:n,expiresAt:{$gt:new Date}});if(!i)throw new Error("Invalid or expired verification token");if(!await d.findOne({_id:i.userId}))throw new Error("User not found");let s=i.email;if(!s)throw new Error("Email not found in token");if((await d.updateOne({_id:i.userId,"emails.address":s,"emails.verified":{$ne:!0}},{$set:{"emails.$.verified":!0}})).matchedCount===0)throw await d.findOne({_id:i.userId,"emails.address":s})?new Error("Email is already verified"):new Error("Email address not found for this user");await T.deleteOne({_id:i._id});}catch(n){if(n instanceof Error)return console.error("Error verifying email:",n),{status:301,redirect:`${o}?status=error&message=${encodeURIComponent(n.message)}`}}return {status:301,redirect:`${o}?status=verified`}}async function q({userId:t,email:e,baseUrl:o=process.env.MODELENCE_SITE_URL}){if(h().provider){let n=h().provider,i=randomBytes(32).toString("hex"),r=new Date(Date.now()+a$1.hours(24));await T.insertOne({userId:t,email:e,token:i,createdAt:new Date,expiresAt:r});let s=`${o}/api/_internal/auth/verify-email?token=${i}`,u=(h()?.verification?.template||_e)({name:"",email:e,verificationUrl:s}),l=J(u);await n?.sendEmail({to:e,from:h()?.from||"noreply@modelence.com",subject:h()?.verification?.subject||"Verify your email address",text:l,html:u});}}async function Ie(t,{user:e,session:o,connectionInfo:n}){if(!o)throw new Error("Session is not initialized");let i=n?.ip;i&&await R({bucket:"signin",type:"ip",value:i});let r=z$1.string().email().parse(t.email),s=z$1.string().parse(t.password),c=await d.findOne({"emails.address":r},{collation:{locale:"en",strength:2}}),u=c?.authMethods?.password?.hash;if(!u)throw Oe();if(!c.emails?.find(w=>w.address===r)?.verified&&h()?.provider){if(i)try{await R({bucket:"verification",type:"user",value:c._id.toString()});}catch{throw new Error("Your email address hasn't been verified yet. Please use the verification email we've send earlier to your inbox.")}throw await q({userId:c?._id,email:r,baseUrl:n?.baseUrl}),new Error("Your email address hasn't been verified yet. We've sent a new verification email to your inbox.")}if(!await vt.compare(s,u))throw Oe();return await Ce(o.authToken,c._id),{user:{id:c._id,handle:c.handle}}}async function ke(t,{user:e,session:o}){if(!o)throw new Error("Session is not initialized");await xe(o.authToken);}function Oe(){return new Error("Incorrect email/password combination")}async function Ae(t,{user:e}){if(!e)throw new Error("Not authenticated");let o=await d.requireById(e.id);return {handle:o.handle,emails:o.emails,authMethods:Object.keys(o.authMethods||{})}}var A=new f("_modelenceRateLimits",{schema:{bucket:a.string(),type:a.enum(["ip","user"]),value:a.string(),windowMs:a.number(),windowStart:a.date(),windowCount:a.number(),prevWindowCount:a.number(),expiresAt:a.date()},indexes:[{key:{bucket:1,type:1,value:1,windowMs:1},unique:true},{key:{expiresAt:1},expireAfterSeconds:0}]});var Z=[];function Pe(t){if(Z.length>0)throw new Error("Duplicate call to initRateLimits - already initialized");Z=t;}async function R(t){let{bucket:e,type:o,value:n}=t,i=Z.filter(r=>r.bucket===e&&r.type===o);for(let r of i)await Ot(r,n);}async function Ot(t,e,o){let n=()=>new d$1(`Rate limit exceeded for ${t.bucket}`),i=await A.findOne({bucket:t.bucket,type:t.type,value:e,windowMs:t.window}),r=Date.now(),s=Math.floor(r/t.window)*t.window,{count:c,modifier:u}=i?It(i,s,r):{count:0,modifier:{$setOnInsert:{windowStart:new Date(s),windowCount:1,prevWindowCount:0,expiresAt:new Date(s+t.window+t.window)}}};if(c>=t.limit)throw n();await A.upsertOne({bucket:t.bucket,type:t.type,value:e,windowMs:t.window},u);}function It(t,e,o){let n=e-t.windowMs;if(t.windowStart.getTime()===e){let i=t.windowCount,r=t.prevWindowCount,s=1-(o-e)/t.windowMs;return {count:Math.round(i+r*s),modifier:{$inc:{windowCount:1},$setOnInsert:{windowStart:new Date(e),prevWindowCount:0,expiresAt:new Date(e+t.windowMs+t.windowMs)}}}}if(t.windowStart.getTime()===n){let i=1-(o-e)/t.windowMs;return {count:Math.round(t.windowCount*i),modifier:{$set:{windowStart:new Date(e),windowCount:1,prevWindowCount:t.windowCount,expiresAt:new Date(e+t.windowMs+t.windowMs)}}}}return {count:0,modifier:{$set:{windowStart:new Date(e),windowCount:1,prevWindowCount:0,expiresAt:new Date(e+t.windowMs+t.windowMs)}}}}async function Ue(t,{user:e,connectionInfo:o}){let n=z$1.string().email().parse(t.email),i=z$1.string().min(8,{message:"Password must contain at least 8 characters"}).parse(t.password),r=o?.ip;if(r&&await R({bucket:"signupAttempt",type:"ip",value:r}),await Re(n))throw new Error("Please use a permanent email address");let s=await d.findOne({"emails.address":n},{collation:{locale:"en",strength:2}});if(s){let l=s.emails?.find(y=>y.address===n);throw new Error(`User with email already exists: ${l?.address}`)}r&&await R({bucket:"signup",type:"ip",value:r});let c=await vt.hash(i,10),u=await d.insertOne({handle:n,emails:[{address:n,verified:false}],createdAt:new Date,authMethods:{password:{hash:c}}});return await q({userId:u?.insertedId,email:n,baseUrl:o?.baseUrl}),u.insertedId}function Lt({email:t,resetUrl:e}){return `
|
|
8
|
+
<p>Hi,</p>
|
|
9
|
+
<p>We received a request to reset your password for ${t}.</p>
|
|
10
|
+
<p>Click the link below to reset your password:</p>
|
|
11
|
+
<p><a href="${e}">${e}</a></p>
|
|
12
|
+
<p>This link will expire in 1 hour.</p>
|
|
13
|
+
<p>If you did not request this password reset, please ignore this email.</p>
|
|
14
|
+
`}async function je(t,{connectionInfo:e}){let o=z$1.string().email().parse(t.email),n=await d.findOne({"emails.address":o},{collation:{locale:"en",strength:2}});if(!n)return {success:true,message:"If an account with that email exists, a password reset link has been sent"};if(!n.authMethods?.password)return {success:true,message:"If an account with that email exists, a password reset link has been sent"};let i=h().provider;if(!i)throw new Error("Email provider is not configured");let r=randomBytes(32).toString("hex"),s=new Date(Date.now()+a$1.hours(1));await x.insertOne({userId:n._id,token:r,createdAt:new Date,expiresAt:s});let c=process.env.MODELENCE_SITE_URL||e?.baseUrl,l=`${h().passwordReset?.redirectUrl||c}?token=${r}`,w=(h()?.passwordReset?.template||Lt)({email:o,resetUrl:l,name:""}),v=J(w);return await i.sendEmail({to:o,from:h()?.from||"noreply@modelence.com",subject:h()?.passwordReset?.subject||"Reset your password",text:v,html:w}),{success:true,message:"If an account with that email exists, a password reset link has been sent"}}async function $e(t,{}){let e=z$1.string().parse(t.token),o=z$1.string().min(8,{message:"Password must contain at least 8 characters"}).parse(t.password),n=await x.findOne({token:e});if(!n)throw new Error("Invalid or expired reset token");if(n.expiresAt<new Date)throw await x.deleteOne({token:e}),new Error("Reset token has expired");let i=await d.findOne({_id:n.userId});if(!i)throw new Error("User not found");let r=await vt.hash(o,10);return await d.updateOne({_id:i._id},{$set:{"authMethods.password.hash":r}}),await x.deleteOne({token:e}),{success:true,message:"Password has been reset successfully"}}var Ne=new g("_system.user",{stores:[d,k,T,x],queries:{getOwnProfile:Ae},mutations:{signupWithPassword:Ue,loginWithPassword:Ie,logout:ke,sendResetPasswordToken:je,resetPassword:$e},cronJobs:{updateDisposableEmailList:De},rateLimits:[{bucket:"signup",type:"ip",window:a$1.minutes(15),limit:20},{bucket:"signup",type:"ip",window:a$1.days(1),limit:200},{bucket:"signupAttempt",type:"ip",window:a$1.minutes(15),limit:50},{bucket:"signupAttempt",type:"ip",window:a$1.days(1),limit:500},{bucket:"signin",type:"ip",window:a$1.minutes(15),limit:50},{bucket:"signin",type:"ip",window:a$1.days(1),limit:500},{bucket:"verification",type:"user",window:a$1.minutes(15),limit:3},{bucket:"verification",type:"user",window:a$1.days(1),limit:10}],configSchema:{"auth.email.enabled":{type:"boolean",isPublic:true,default:true},"auth.email.from":{type:"string",isPublic:false,default:""},"auth.email.verification":{type:"boolean",isPublic:true,default:false},"auth.google.enabled":{type:"boolean",isPublic:true,default:false},"auth.google.clientId":{type:"string",isPublic:false,default:""},"auth.google.clientSecret":{type:"secret",isPublic:false,default:""}},routes:[{path:"/api/_internal/auth/verify-email",handlers:{get:Te}}]});async function Je({configSchema:t,cronJobsMetadata:e,stores:o}){let n=process.env.MODELENCE_CONTAINER_ID;if(!n)throw new Error("Unable to connect to Modelence Cloud: MODELENCE_CONTAINER_ID is not set");try{let i=Object.values(o).map(s=>({name:s.getName(),schema:s.getSchema(),collections:[s.getName()]})),r=await Y("/api/connect","POST",{hostname:Ut.hostname(),containerId:n,dataModels:i,configSchema:t,cronJobsMetadata:e});if(r.status==="error")throw new Error(r.error);return console.log("Successfully connected to Modelence Cloud"),r}catch(i){throw console.error("Unable to connect to Modelence Cloud:",i),i}}async function qe(){return await Y("/api/configs","GET")}async function Be(){return await Y("/api/sync","POST",{containerId:process.env.MODELENCE_CONTAINER_ID})}async function Y(t,e,o){let{MODELENCE_SERVICE_ENDPOINT:n,MODELENCE_SERVICE_TOKEN:i}=process.env;if(!n)throw new Error("Unable to connect to Modelence Cloud: MODELENCE_SERVICE_ENDPOINT is not set");let r=await fetch(`${n}${t}`,{method:e,headers:{Authorization:`Bearer ${i}`,...o?{"Content-Type":"application/json"}:{}},body:o?JSON.stringify(o):void 0});if(!r.ok){let s=await r.text();try{let c=JSON.parse(s);throw new Error(`Unable to connect to Modelence Cloud: HTTP status: ${r.status}, ${c?.error}`)}catch{throw new Error(`Unable to connect to Modelence Cloud: HTTP status: ${r.status}, ${s}`)}}return await r.json()}var X=false,jt=a$1.seconds(10);function ze(){setInterval(async()=>{if(!X){X=true;try{await Be();}catch(t){console.error("Error syncing status",t);}try{await $t();}catch(t){console.error("Error syncing config",t);}X=false;}},jt);}async function $t(){let{configs:t}=await qe();c(t);}var Nt=a$1.minutes(1),Jt=a$1.seconds(10),D={},ee,P=new f("_modelenceCronJobs",{schema:{alias:a.string(),lastStartDate:a.date().optional(),lock:a.object({containerId:a.string(),acquireDate:a.date()}).optional()},indexes:[{key:{alias:1},unique:true,background:true}]});function Ve(t,{description:e="",interval:o,timeout:n=Nt,handler:i}){if(D[t])throw new Error(`Duplicate cron job declaration: '${t}' already exists`);if(ee)throw new Error(`Unable to add a cron job - cron jobs have already been initialized: [${t}]`);if(o<a$1.seconds(5))throw new Error(`Cron job interval should not be less than 5 second [${t}]`);if(n>a$1.days(1))throw new Error(`Cron job timeout should not be longer than 1 day [${t}]`);D[t]={alias:t,params:{description:e,interval:o,timeout:n},handler:i,state:{isRunning:false}};}async function We(){if(ee)throw new Error("Cron jobs already started");let t=Object.keys(D);if(t.length>0){let e={alias:{$in:t}},o=await P.findOne({...e,"lock.containerId":{$exists:true}});await Promise.all(t.map(r=>P.upsertOne({alias:r},{$set:{lock:{containerId:process.env.MODELENCE_CONTAINER_ID||"unknown",acquireDate:new Date}}}))),o&&await qt(Jt);let n=await P.fetch(e),i=Date.now();n.forEach(r=>{let s=D[r.alias];s&&(s.state.scheduledRunTs=r.lastStartDate?r.lastStartDate.getTime()+s.params.interval:i);}),Object.values(D).forEach(r=>{r.state.scheduledRunTs||(r.state.scheduledRunTs=i);}),ee=setInterval(Bt,a$1.seconds(1));}}function qt(t){return new Promise(e=>setTimeout(e,t))}async function Bt(){let t=Date.now();Object.values(D).forEach(async e=>{let{params:o,state:n}=e;if(n.isRunning){n.startTs&&n.startTs+o.timeout<t&&(n.isRunning=false);return}n.scheduledRunTs&&n.scheduledRunTs<=t&&await zt(e);});}async function zt(t){let{alias:e,params:o,handler:n,state:i}=t;i.isRunning=true,i.startTs=Date.now();let r=j("cron",`cron:${e}`);n().then(()=>{Fe(i,o),r.end("success");}).catch(s=>{Fe(i,o),k$1(s),r.end("error"),console.error(`Error in cron job '${e}':`,s);}),await P.updateOne({alias:e},{$set:{lastStartDate:new Date(i.startTs)}});}function Fe(t,e){t.scheduledRunTs=t.startTs?t.startTs+e.interval:Date.now(),t.startTs=void 0,t.isRunning=false;}function He(){return Object.values(D).map(({alias:t,params:e})=>({alias:t,description:e.description,interval:e.interval,timeout:e.timeout}))}var Ke=new g("_system.cron",{stores:[P]});var b=null;async function Ge(){if(b)return b;let t=L();if(!t)throw new Error("MongoDB URI is not set");b=new MongoClient(t,{maxPoolSize:20});try{return await b.connect(),await b.db("admin").command({ping:1}),console.log("Pinged your deployment. You successfully connected to MongoDB!"),b}catch(e){throw console.error(e),b=null,e}}function L(){let t=a$2("_system.mongodbUri");return t?String(t):void 0}function Ze(){return b}var te={};function oe(t,e){return S(),et(t),B("query",t,e)}function Qe(t,e){return S(),et(t),B("mutation",t,e)}function Ye(t,e){return S(),tt(t),B("query",t,e)}function Xe(t,e){return S(),tt(t),B("mutation",t,e)}function et(t){if(t.toLowerCase().startsWith("_system."))throw new Error(`Method name cannot start with a reserved prefix: '_system.' (${t})`)}function tt(t){if(!t.toLowerCase().startsWith("_system."))throw new Error(`System method name must start with a prefix: '_system.' (${t})`)}function B(t,e,o){if(S(),te[e])throw new Error(`Method with name '${e}' is already defined.`);let n=typeof o=="function"?o:o.handler,i=typeof o=="function"?[]:o.permissions??[];te[e]={type:t,name:e,handler:n,permissions:i};}async function ot(t,e,o){S();let n=te[t];if(!n)throw new Error(`Method with name '${t}' is not defined.`);let{type:i,handler:r}=n,s=j("method",`method:${t}`,{type:i,args:e}),c;try{be(o.roles,n.permissions),c=await r(e,o);}catch(u){throw s.end("error"),u}return s.end(),c}var z=new f("_modelenceMigrations",{schema:{version:a.number(),appliedAt:a.date()},indexes:[{key:{version:1},unique:true}]});async function nt(t){if(t.length===0)return;let e=t.map(({version:r})=>r),o=await z.fetch({version:{$in:e}}),n=new Set(o.map(({version:r})=>r)),i=t.filter(({version:r})=>!n.has(r));if(i.length!==0){console.log(`Running migrations (${i.length})...`);for(let{version:r,description:s,handler:c}of i)console.log(`Running migration v${r}: ${s}`),await z.insertOne({version:r,appliedAt:new Date}),await c(),console.log(`Migration v${r} complete`);}}var rt=new g("_system.migration",{stores:[z]});var it=new g("_system.rateLimit",{stores:[A]});var re=class{async init(){this.config=await Qt(),this.isDev()&&(console.log("Starting Vite dev server..."),this.viteServer=await createServer({...defineConfig(this.config),server:{middlewareMode:true},root:"./src/client"}));}middlewares(){if(this.isDev())return this.viteServer?.middlewares??[];let e=[se.static("./.modelence/build/client")];return this.config?.publicDir&&e.push(se.static(this.config.publicDir)),e}handler(e,o){if(this.isDev())try{o.sendFile("index.html",{root:"./src/client"});}catch(n){console.error("Error serving index.html:",n),o.status(500).send("Internal Server Error");}else o.sendFile("index.html",{root:"./.modelence/build/client"});}isDev(){return process.env.NODE_ENV!=="production"}};async function Zt(){let t=process.cwd();try{return (await loadConfigFromFile({command:"serve",mode:"development"},void 0,t))?.config||{}}catch(e){return console.warn("Could not load vite config:",e),{}}}async function Qt(){let t=process.cwd(),e=await Zt(),o=[".eslintrc.js",".eslintrc.json",".eslintrc","eslint.config.js",".eslintrc.yml",".eslintrc.yaml"].find(i=>Gt.existsSync(ne.join(t,i))),n=[Kt(),Yt()];if(o){let i=(await import('vite-plugin-eslint')).default;n.push(i({failOnError:false,include:["src/**/*.js","src/**/*.jsx","src/**/*.ts","src/**/*.tsx"],cwd:t,overrideConfigFile:ne.resolve(t,o)}));}return {plugins:n,root:t,build:{outDir:".modelence/build/client",emptyOutDir:true},server:{proxy:{"/api":"http://localhost:4000"},headers:{"Cache-Control":"no-store, no-cache, must-revalidate, proxy-revalidate, max-age=0",Pragma:"no-cache",Expires:"0"},hmr:{port:0}},resolve:{alias:{"@":ne.resolve(t,"src")}},publicDir:e.publicDir}}function Yt(){return {name:"modelence-asset-handler",async transform(t,e){if(/\.(png|jpe?g|gif|svg|mpwebm|ogg|mp3|wav|flac|aac)$/.test(e))return process.env.NODE_ENV==="development",t},async generateBundle(t,e){}}}var at=new re;async function ct(t,e){let{authToken:o}=await K(e);t.cookie("authToken",o,{httpOnly:true,secure:process.env.NODE_ENV==="production",sameSite:"strict"}),t.status(301),t.redirect("/");}async function to(t,e){let o=t.user,n=await d.findOne({"authMethods.google.id":o.id});if(n){await ct(e,n._id);return}let i=o.emails[0]&&o.emails[0]?.value;if(i||e.status(400).json({error:"Email address is required for Google authentication."}),await d.findOne({"emails.address":i},{collation:{locale:"en",strength:2}})){e.status(400).json({error:"User with this email already exists. Please log in instead."});return}let s=await d.insertOne({handle:i,emails:[{address:i,verified:true}],createdAt:new Date,authMethods:{google:{id:o.id}}});await ct(e,s.insertedId);}function oo(){let t=Router(),e=!!a$2("_system.user.auth.google.enabled"),o=String(a$2("_system.user.auth.google.clientId")),n=String(a$2("_system.user.auth.google.clientSecret"));return !e||!o||!n||(ie.use(new Strategy({clientID:o,clientSecret:n,callbackURL:"/api/_internal/auth/google/callback",proxy:true},(i,r,s,c)=>c(null,s))),t.get("/api/_internal/auth/google",ie.authenticate("google",{scope:["profile","email"],session:false})),t.get("/api/_internal/auth/google/callback",ie.authenticate("google",{session:false}),to)),t}var lt=oo;function mt(t){return async(e,o)=>{try{let n=await t({query:e.query,body:e.body,params:e.params,headers:e.headers,cookies:e.cookies,req:e});o.status(n.status||200),n.redirect&&o.redirect(n.redirect),n.headers&&Object.entries(n.headers).forEach(([i,r])=>{o.setHeader(i,r);}),o.send(n.data);}catch(n){n instanceof a$4?o.status(n.status).send(n.message):(console.error(`Error in route handler: ${e.path}`),console.error(n),o.status(500).send(String(n)));}}}async function dt(t){let e=await Ee(t),o=e.userId?await d.findOne({_id:new ObjectId(e.userId)}):null,n=o?{id:o._id.toString(),handle:o.handle}:null,i=n?ye():N();return {user:n,session:e,roles:i}}function ao(t,e){for(let o of e)for(let n of o.routes){let{path:i,handlers:r}=n;Object.entries(r).forEach(([s,c])=>{t[s](i,mt(c));});}}async function ut(t,{combinedModules:e}){let o=se();o.use(se.json()),o.use(se.urlencoded({extended:true})),o.use(ro()),o.use(ie.initialize()),o.use(lt()),o.post("/api/_internal/method/:methodName(*)",async(r,s)=>{let{methodName:c}=r.params,u=await co(r);try{let l=await ot(c,r.body.args,u);s.json({data:l,typeMap:a$3(l)});}catch(l){if(console.error(`Error in method ${c}:`,l),l instanceof a$4)s.status(l.status).send(l.message);else if(l instanceof Error&&l?.constructor?.name==="ZodError"&&"errors"in l){let w=l.flatten(),v=Object.entries(w.fieldErrors).map(([F,V])=>`${F}: ${(V??[]).join(", ")}`).join("; "),U=w.formErrors.join("; "),O=[v,U].filter(Boolean).join("; ");s.status(400).send(O);}else s.status(500).send(l instanceof Error?l.message:String(l));}}),ao(o,e),await t.init(),t.middlewares&&o.use(t.middlewares()),o.all("*",(r,s)=>t.handler(r,s)),process.on("unhandledRejection",(r,s)=>{console.error("Unhandled Promise Rejection:"),console.error(r instanceof Error?r.stack:r),console.error("Promise:",s);}),process.on("uncaughtException",r=>{console.error("Uncaught Exception:"),console.error(r.stack),console.trace("Full application stack:");});let n=io.createServer(o),i=process.env.PORT||3e3;n.listen(i,()=>{h$1("Application started",{source:"app"}),console.log(`
|
|
8
15
|
Application started on http://localhost:${i}
|
|
9
|
-
`);});}async function
|
|
10
|
-
export{
|
|
16
|
+
`);});}async function co(t){let e=E.string().nullish().transform(r=>r??null).parse(t.cookies.authToken||t.body.authToken),o=E.object({screenWidth:E.number(),screenHeight:E.number(),windowWidth:E.number(),windowHeight:E.number(),pixelRatio:E.number(),orientation:E.string().nullable()}).parse(t.body.clientInfo),n={ip:lo(t),userAgent:t.get("user-agent"),acceptLanguage:t.get("accept-language"),referrer:t.get("referrer"),baseUrl:t.protocol+"://"+t.get("host")};if(!!L()){let{session:r,user:s,roles:c}=await dt(e);return {clientInfo:o,connectionInfo:n,session:r,user:s,roles:c}}return {clientInfo:o,connectionInfo:n,session:null,user:null,roles:N()}}function lo(t){let e=t.headers["x-forwarded-for"];if(e)return (Array.isArray(e)?e[0]:e.split(",")[0]).trim();let o=t.ip||t.socket?.remoteAddress;if(o)return o.startsWith("::ffff:")?o.substring(7):o}async function fo({modules:t=[],roles:e$1={},defaultRoles:o={},server:n=at,migrations:i=[],email:r={}}){pt.config(),pt.config({path:".modelence.env"});let s=!!process.env.MODELENCE_SERVICE_ENDPOINT,c$1=process.env.MODELENCE_CRON_ENABLED==="true";Do().then(()=>{}).catch(()=>{});let u=[Ne,Se,Ke,rt,it],l=[...u,...t];e(),go(u),ho(t),we(e$1,o);let y=bo(l);d$2(y);let w=wo(l);c$1&&Eo(l);let v=yo(l);if(Pe(v),s){let{configs:O,environmentId:F,appAlias:V,environmentAlias:ft,telemetry:ht}=await Je({configSchema:y,cronJobsMetadata:c$1?He():void 0,stores:w});c(O),f$1({environmentId:F,appAlias:V,environmentAlias:ft,telemetry:ht});}else c(Ro(y));Me(r);let U=L();if(U&&(await Ge(),Co(w)),c$1&&await nt(i),U)for(let O of w)O.createIndexes();s&&(await g$1(),ze()),c$1&&We().catch(console.error),await ut(n,{combinedModules:l});}function ho(t){for(let e of t){for(let[o,n]of Object.entries(e.queries))oe(`${e.name}.${o}`,n);for(let[o,n]of Object.entries(e.mutations))Qe(`${e.name}.${o}`,n);}}function go(t){for(let e of t){for(let[o,n]of Object.entries(e.queries))Ye(`${e.name}.${o}`,n);for(let[o,n]of Object.entries(e.mutations))Xe(`${e.name}.${o}`,n);}}function wo(t){return t.flatMap(e=>e.stores)}function yo(t){return t.flatMap(e=>e.rateLimits)}function bo(t){let e={};for(let o of t)for(let[n,i]of Object.entries(o.configSchema)){let r=`${o.name}.${n}`;if(r in e)throw new Error(`Duplicate config schema key: ${r} (${o.name})`);e[r]=i;}return e}function Eo(t){for(let e of t)for(let[o,n]of Object.entries(e.cronJobs))Ve(`${e.name}.${o}`,n);}function Co(t){let e=Ze();if(!e)throw new Error("Failed to initialize stores: MongoDB client not initialized");for(let o of t)o.init(e);}var xo={MONGODB_URI:"_system.mongodbUri",MODELENCE_AUTH_GOOGLE_ENABLED:"_system.user.auth.google.enabled",MODELENCE_AUTH_GOOGLE_CLIENT_ID:"_system.user.auth.google.clientId",MODELENCE_AUTH_GOOGLE_CLIENT_SECRET:"_system.user.auth.google.clientSecret",MODELENCE_EMAIL_RESEND_API_KEY:"_system.email.resend.apiKey",MODELENCE_EMAIL_AWS_SES_REGION:"_system.email.awsSes.region",MODELENCE_EMAIL_AWS_SES_ACCESS_KEY_ID:"_system.email.awsSes.accessKeyId",MODELENCE_EMAIL_AWS_SES_SECRET_ACCESS_KEY:"_system.email.awsSes.secretAccessKey",MODELENCE_EMAIL_SMTP_HOST:"_system.email.smtp.host",MODELENCE_EMAIL_SMTP_PORT:"_system.email.smtp.port",MODELENCE_EMAIL_SMTP_USER:"_system.email.smtp.user",MODELENCE_EMAIL_SMTP_PASS:"_system.email.smtp.pass",GOOGLE_AUTH_ENABLED:"_system.user.auth.google.enabled",GOOGLE_AUTH_CLIENT_ID:"_system.user.auth.google.clientId",GOOGLE_AUTH_CLIENT_SECRET:"_system.user.auth.google.clientSecret"};function So(t,e){if(e==="number"){let o=Number(t);if(isNaN(o))throw new Error(`Invalid number value for config: ${t}`);return o}if(e==="boolean"){if(t.toLowerCase()==="true")return true;if(t.toLowerCase()==="false")return false;throw new Error(`Invalid boolean value for config: ${t}`)}return t}function Ro(t){let e=[];for(let[o,n]of Object.entries(xo)){let i=process.env[o],r=t[n];if(i){let s=r?.type??"string";e.push({key:n,type:s,value:So(i,s)});}}return e}async function Do(){if(process.env.MODELENCE_TRACKING_ENABLED!=="false"){let e=process.env.MODELENCE_SERVICE_ENDPOINT??"https://cloud.modelence.com",o=process.env.MODELENCE_ENVIRONMENT_ID,n=await Mo(),i=await import('./package-4ZTUD7K2.js');await fetch(`${e}/api/track/app-start`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({projectName:n.name,version:i.default.version,localHostname:Ut.hostname(),environmentId:o})});}}async function Mo(){try{let t=ne.join(process.cwd(),"package.json"),e=await mo.readFile(t,"utf-8");return {name:JSON.parse(e).name||"unknown"}}catch{return {name:"unknown"}}}
|
|
17
|
+
export{g as Module,f as Store,R as consumeRateLimit,oe as createQuery,d as dbUsers,a as schema,fo as startApp};//# sourceMappingURL=server.js.map
|
|
11
18
|
//# sourceMappingURL=server.js.map
|
package/dist/server.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/auth/role.ts","../src/app/module.ts","../src/data/store.ts","../src/data/types.ts","../src/auth/session.ts","../src/auth/db.ts","../src/auth/disposableEmails.ts","../src/app/emailConfig.ts","../src/utils/index.ts","../src/auth/templates/emailVerficationTemplate.ts","../src/auth/verification.ts","../src/auth/login.ts","../src/auth/profile.ts","../src/rate-limit/db.ts","../src/rate-limit/rules.ts","../src/auth/signup.ts","../src/auth/user.ts","../src/app/backendApi.ts","../src/config/sync.ts","../src/cron/jobs.ts","../src/db/client.ts","../src/methods/index.ts","../src/migration/db.ts","../src/migration/index.ts","../src/rate-limit/index.ts","../src/viteServer.ts","../src/auth/providers/google.ts","../src/routes/handler.ts","../src/auth/index.ts","../src/app/server.ts","../src/app/index.ts"],"names":["roleMap","defaultRoles","initRoles","roles","_defaultRoles","name","definition","getUnauthenticatedRoles","getDefaultAuthenticatedRoles","requireAccess","requiredPermissions","missingPermission","permission","hasPermission","role","Module","stores","queries","mutations","routes","cronJobs","configSchema","rateLimits","Store","options","client","document","selector","ObjectId","query","errorHandler","result","cursor","id","idSelector","documents","update","pipeline","operations","oldName","db","schemaString","z","schemaNumber","schemaDate","schemaBoolean","schemaArray","schemaObject","schemaEnum","schema","collection","sessionsCollection","obtainSession","authToken","existingSession","createSession","setSessionUser","userId","clearSessionUser","randomBytes","now","expiresAt","time","processSessionHeartbeat","session","newExpiresAt","session_default","args","user","getPublicConfigs","usersCollection","dbDisposableEmailDomains","emailVerificationTokensCollection","isDisposableEmail","email","emailParts","domain","updateDisposableEmailListCron","response","domains","batchSize","i","batch","error","emailConfig","setEmailConfig","newEmailConfig","getEmailConfig","isServer","requireServer","htmlToText","html","emailVerificationTemplate","verificationUrl","handleVerifyEmail","params","emailVerifiedRedirectUrl","token","tokenDoc","sendVerificationEmail","baseUrl","emailProvider","verificationToken","htmlTemplate","textContent","handleLoginWithPassword","connectionInfo","ip","consumeRateLimit","password","userDoc","passwordHash","incorrectCredentialsError","e","bcrypt","handleLogout","getOwnProfile","_args","profile","dbRateLimits","allRules","initRateLimits","bucket","type","value","rules","rule","checkRateLimitRule","createError","createRateLimitError","RateLimitError","record","currentWindowStart","count","modifier","getCount","prevWindowStart","currentWindowCount","prevWindowCount","prevWindowWeight","weight","handleSignupWithPassword","existingUser","existingEmail","hash","user_default","connectCloudBackend","cronJobsMetadata","containerId","dataModels","store","data","callApi","os","fetchConfigs","syncStatus","endpoint","method","payload","MODELENCE_SERVICE_ENDPOINT","MODELENCE_SERVICE_TOKEN","json","isSyncing","SYNC_INTERVAL","startConfigSync","syncConfig","configs","loadConfigs","DEFAULT_TIMEOUT","LOCK_TRANSFER_DELAY","cronJobsInterval","cronJobsCollection","defineCronJob","alias","description","interval","timeout","handler","startCronJobs","aliasList","aliasSelector","existingLockedRecord","sleep","cronJobRecords","job","tickCronJobs","ms","resolve","state","startCronJob","transaction","startTransaction","handleCronJobCompletion","err","captureError","getCronJobsMetadata","jobs_default","connect","mongodbUri","getMongodbUri","MongoClient","getConfig","getClient","methods","createQuery","methodDef","validateMethodName","_createMethodInternal","createMutation","_createSystemQuery","validateSystemMethodName","_createSystemMutation","permissions","runMethod","context","dbMigrations","runMigrations","migrations","versions","version","existingVersions","existingVersionSet","pendingMigrations","migration_default","rate_limit_default","ViteServer","createServer","defineConfig","staticFolders","express","req","res","loadUserViteConfig","appDir","loadConfigFromFile","userConfig","eslintConfigFile","file","fs","path","plugins","reactPlugin","modelenceAssetPlugin","eslintPlugin","code","bundle","viteServer","authenticateUser","handleGoogleAuthenticationCallback","googleUser","googleEmail","newUser","getRouter","googleAuthRouter","Router","googleEnabled","googleClientId","googleClientSecret","passport","GoogleStrategy","accessToken","refreshToken","done","google_default","createRouteHandler","key","ModelenceError","authenticate","registerModuleRoutes","app","modules","module","route","handlers","startServer","server","combinedModules","cookieParser","methodName","getCallContext","getResponseTypeMap","flattened","fieldMessages","errors","formMessages","allMessages","reason","promise","httpServer","http","port","logInfo","val","clientInfo","getClientIp","forwardedFor","directIp","startApp","dotenv","hasRemoteBackend","isCronEnabled","trackAppStart","systemModules","markAppStarted","initSystemMethods","initCustomMethods","getConfigSchema","setSchema","getStores","defineCronJobs","getRateLimits","environmentId","appAlias","environmentAlias","telemetry","setMetadata","getLocalConfigs","initStores","initMetrics","merged","absoluteKey","cronAlias","cronJobParams","localConfigMap","formatLocalConfigValue","numValue","envVar","configKey","configSchemaEntry","serviceEndpoint","appDetails","getAppDetails","modelencePackageJson","packageJsonPath","packageJsonContent"],"mappings":"0xBAEA,IAAMA,EAAAA,CAAU,IAAI,IACdC,CAAAA,CAA6B,CACjC,cAAe,IAAA,CACf,eAAA,CAAiB,IACnB,CAAA,CAEO,SAASC,EAAAA,CAAUC,CAAAA,CAAqCC,EAAqC,CAClGH,CAAAA,CAAa,cAAgBG,CAAAA,CAAc,aAAA,CAC3CH,CAAAA,CAAa,eAAA,CAAkBG,EAAc,eAAA,CAE7C,IAAA,GAAW,CAACC,CAAAA,CAAMC,CAAU,IAAK,MAAA,CAAO,OAAA,CAAQH,CAAK,CAAA,CACnDH,GAAQ,GAAA,CAAIK,CAAAA,CAAMC,CAAU,EAEhC,CAEO,SAASC,CAAAA,EAA0B,CACxC,OAAON,CAAAA,CAAa,gBAAkB,CAAC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,GAAA,CAAI,0BAAA,EAA8B,6BAAA,CAC5DlB,CAAAA,CAAgB,OAAA,CAAQ,IAAI,wBAAA,CAE5BmB,CAAAA,CAAa,MAAMC,EAAAA,EAAc,CACjCC,CAAAA,CAAuB,MAAM,OAAO,uBAAoB,CAAA,CAE9D,MAAM,KAAA,CAAM,CAAA,EAAGH,CAAe,CAAA,oBAAA,CAAA,CAAwB,CACpD,MAAA,CAAQ,MAAA,CACR,OAAA,CAAS,CACP,eAAgB,kBAClB,CAAA,CACA,IAAA,CAAM,IAAA,CAAK,SAAA,CAAU,CACnB,YAAaC,CAAAA,CAAW,IAAA,CACxB,OAAA,CAASE,CAAAA,CAAqB,OAAA,CAAQ,OAAA,CACtC,cAAenL,EAAAA,CAAG,QAAA,EAAS,CAC3B,aAAA,CAAA8J,CACF,CAAC,CACH,CAAC,EACH,CACF,CAEA,eAAeoB,EAAAA,EAAgB,CAC7B,GAAI,CACF,IAAME,CAAAA,CAAkB9F,EAAAA,CAAK,IAAA,CAAK,QAAQ,GAAA,EAAI,CAAG,cAAc,CAAA,CACzD+F,CAAAA,CAAqB,MAAMhG,GAAG,QAAA,CAAS+F,CAAAA,CAAiB,OAAO,CAAA,CAGrE,OAAO,CACL,KAHkB,IAAA,CAAK,KAAA,CAAMC,CAAkB,CAAA,CAG7B,IAAA,EAAQ,SAC5B,CACF,CAAA,KAAgB,CACd,OAAO,CACL,IAAA,CAAM,SACR,CACF,CACF","file":"server.js","sourcesContent":["import { RoleDefinition, Role, DefaultRoles, Permission } from './types';\n\nconst roleMap = new Map<Role, RoleDefinition>();\nconst defaultRoles: DefaultRoles = {\n authenticated: null,\n unauthenticated: null,\n};\n\nexport function initRoles(roles: Record<Role, RoleDefinition>, _defaultRoles: Record<string, Role>) {\n defaultRoles.authenticated = _defaultRoles.authenticated;\n defaultRoles.unauthenticated = _defaultRoles.unauthenticated;\n\n for (const [name, definition] of Object.entries(roles)) {\n roleMap.set(name, definition);\n }\n}\n\nexport function getUnauthenticatedRoles() {\n return defaultRoles.unauthenticated ? [defaultRoles.unauthenticated] : [];\n}\n\nexport function getDefaultAuthenticatedRoles() {\n return defaultRoles.authenticated ? [defaultRoles.authenticated] : [];\n}\n\nexport function hasAccess(roles: Role[], requiredPermissions: Permission[]) {\n return requiredPermissions.every(permission => hasPermission(roles, permission));\n}\n\nexport function requireAccess(roles: Role[], requiredPermissions: Permission[]) {\n const missingPermission = requiredPermissions.find(permission => !hasPermission(roles, permission));\n\n if (missingPermission) {\n throw new Error(`Access denied - missing permission: '${missingPermission}'`);\n }\n}\n\nexport function hasPermission(roles: Role[], permission: Permission) {\n for (const role of roles) {\n const definition = roleMap.get(role);\n\n if (definition && definition.permissions.includes(permission)) {\n return true;\n }\n }\n\n return false;\n}\n","import { ConfigSchema } from '../config/types';\nimport { CronJobInputParams } from '../cron/types';\nimport { Store } from '../data/store';\nimport { MethodDefinition } from '../methods/types';\nimport { RouteDefinition } from '../routes/types';\nimport { RateLimitRule } from '../rate-limit/types';\n\n/** Array of Store instances that will be provisioned when the module is loaded */\ntype Stores = Store<any, any>[];\n\n/** Record of query methods that can be called from the client */\ntype Queries = Record<string, MethodDefinition<any>>;\n\n/** Record of mutation methods that can be called from the client */\ntype Mutations = Record<string, MethodDefinition<any>>;\n\n/**\n * The Module class is a core building block of a Modelence application that encapsulates related functionality.\n * Modules can contain stores, queries, mutations, routes, cron jobs and configurations.\n * \n * @category Module\n * \n * @example\n * ```ts\n * const todoModule = new Module('todo', {\n * stores: [dbTodos],\n * queries: {\n * async getAll() {\n * // Fetch and return all Todo items\n * }\n * },\n * mutations: {\n * async create({ title }, { user }) {\n * // Create a new Todo item\n * }\n * }\n * });\n * ```\n */\nexport class Module {\n /** @internal */\n public readonly name: string;\n\n /** @internal */\n public readonly stores: Stores;\n\n /** @internal */\n public readonly queries: Queries;\n\n /** @internal */\n public readonly mutations: Mutations;\n\n /** @internal */\n public readonly routes: RouteDefinition[];\n\n /** @internal */\n public readonly cronJobs: Record<string, CronJobInputParams>;\n\n /** @internal */\n public readonly configSchema: ConfigSchema;\n\n /** @internal */\n public readonly rateLimits: RateLimitRule[];\n\n /**\n * Creates a new Module instance\n * \n * @param name - The unique name of the module.\n * This name is used to namespace queries, mutations,\n * cron jobs and configuration values with a prefix (e.g. \"todo.create\")\n * \n * @param options - Module configuration options\n */\n constructor(\n name: string,\n { \n stores = [], \n queries = {}, \n mutations = {},\n routes = [],\n cronJobs = {},\n configSchema = {},\n rateLimits = []\n }: { \n stores?: Store<any, any>[],\n queries?: Queries,\n mutations?: Mutations,\n routes?: RouteDefinition[],\n cronJobs?: Record<string, CronJobInputParams>,\n configSchema?: ConfigSchema,\n rateLimits?: RateLimitRule[]\n }\n ) {\n this.name = name;\n this.stores = stores;\n this.queries = queries;\n this.mutations = mutations;\n this.routes = routes;\n this.cronJobs = cronJobs;\n this.configSchema = configSchema;\n this.rateLimits = rateLimits;\n }\n}\n","import {\n AggregateOptions,\n AggregationCursor,\n Collection,\n DeleteResult,\n Document,\n IndexDescription,\n InsertOneResult,\n MongoClient,\n UpdateResult,\n Filter,\n WithId,\n OptionalUnlessRequiredId,\n FindOptions,\n UpdateFilter,\n ObjectId,\n BulkWriteResult,\n AnyBulkWriteOperation,\n InsertManyResult,\n Db,\n ClientSession,\n} from 'mongodb';\n\nimport { ModelSchema, InferDocumentType } from './types';\n\n/**\n * The Store class provides a type-safe interface for MongoDB collections with built-in schema validation and helper methods.\n * \n * @category Store\n * @typeParam TSchema - The document schema type\n * @typeParam TMethods - Custom methods that will be added to documents\n * \n * @example\n * ```ts\n * const dbTodos = new Store('todos', {\n * schema: {\n * title: schema.string(),\n * completed: schema.boolean(),\n * dueDate: schema.date().optional(),\n * userId: schema.userId(),\n * },\n * methods: {\n * isOverdue() {\n * return this.dueDate < new Date();\n * }\n * }\n * });\n * ```\n */\nexport class Store<\n TSchema extends ModelSchema,\n TMethods extends Record<string, (this: WithId<InferDocumentType<TSchema>> & TMethods, ...args: Parameters<any>) => any>\n> {\n /** @internal */\n readonly _type!: InferDocumentType<TSchema>;\n /** @internal */\n readonly _rawDoc!: WithId<this['_type']>;\n /** @internal */\n readonly _doc!: this['_rawDoc'] & TMethods;\n \n readonly Doc!: this['_doc'];\n\n private name: string;\n private readonly schema: TSchema;\n private readonly methods?: TMethods;\n private readonly indexes: IndexDescription[];\n private collection?: Collection<this['_type']>;\n private client?: MongoClient;\n\n /**\n * Creates a new Store instance\n * \n * @param name - The collection name in MongoDB\n * @param options - Store configuration\n */\n constructor(\n name: string,\n options: {\n /** Document schema using Modelence schema types */\n schema: TSchema;\n /** Custom methods to add to documents */\n methods?: TMethods;\n /** MongoDB indexes to create */\n indexes: IndexDescription[];\n }\n ) {\n this.name = name;\n this.schema = options.schema;\n this.methods = options.methods;\n this.indexes = options.indexes;\n }\n\n getName() {\n return this.name;\n }\n\n /** @internal */\n getSchema() {\n return this.schema;\n }\n\n /** @internal */\n init(client: MongoClient) {\n if (this.collection) {\n throw new Error(`Collection ${this.name} is already initialized`);\n }\n\n this.client = client;\n this.collection = this.client.db().collection<this['_type']>(this.name);\n }\n\n /** @internal */\n async createIndexes() {\n if (this.indexes.length > 0) {\n await this.requireCollection().createIndexes(this.indexes);\n }\n }\n\n private wrapDocument(document: this['_rawDoc']): this['_doc'] {\n if (!this.methods) {\n return document as unknown as this['_doc'];\n }\n\n const result = Object.create(\n null,\n Object.getOwnPropertyDescriptors({\n ...document,\n ...this.methods\n })\n );\n\n return result as this['_doc'];\n }\n\n /**\n * For convenience, to also allow directy passing a string or ObjectId as the selector\n */\n private getSelector(selector: Filter<this['_type']> | string | ObjectId) {\n if (typeof selector === 'string') {\n return { _id: new ObjectId(selector) } as Filter<this['_type']>;\n }\n\n if (selector instanceof ObjectId) {\n return { _id: selector } as Filter<this['_type']>;\n }\n\n return selector;\n }\n\n /** @internal */\n requireCollection() {\n if (!this.collection) {\n throw new Error(`Collection ${this.name} is not provisioned`);\n }\n\n return this.collection;\n }\n\n /** @internal */\n requireClient() {\n if (!this.client) {\n throw new Error(`Database is not connected`);\n }\n\n return this.client;\n }\n\n async findOne(\n query: Filter<this['_type']>, \n options?: FindOptions\n ) {\n const document = await this.requireCollection().findOne<this['_rawDoc']>(query, options);\n return document ? this.wrapDocument(document) : null;\n }\n\n async requireOne(\n query: Filter<this['_type']>, \n options?: FindOptions,\n errorHandler?: () => Error\n ): Promise<this['_doc']> {\n \n const result = await this.findOne(query, options);\n if (!result) {\n throw errorHandler ? errorHandler() : new Error(`Record not found in ${this.name}`);\n }\n return result;\n }\n\n private find(query: Filter<this['_type']>, options?: { sort?: Document, limit?: number, skip?: number }) {\n const cursor = this.requireCollection().find(query);\n if (options?.sort) {\n cursor.sort(options.sort);\n }\n if (options?.limit) {\n cursor.limit(options.limit);\n }\n if (options?.skip) {\n cursor.skip(options.skip);\n }\n return cursor;\n }\n\n /**\n * Fetches a single document by its ID\n * \n * @param id - The ID of the document to find\n * @returns The document, or null if not found\n */\n async findById(id: string | ObjectId): Promise<this['_doc'] | null> {\n const idSelector = typeof id === 'string' ? { _id: new ObjectId(id) } : { _id: id };\n return await this.findOne(idSelector as Filter<this['_type']>);\n }\n\n /**\n * Fetches a single document by its ID, or throws an error if not found\n * \n * @param id - The ID of the document to find\n * @param errorHandler - Optional error handler to return a custom error if the document is not found\n * @returns The document\n */\n async requireById(id: string | ObjectId, errorHandler?: () => Error): Promise<this['_doc']> {\n const result = await this.findById(id);\n if (!result) {\n throw errorHandler ? errorHandler() : new Error(`Record with id ${id} not found in ${this.name}`);\n }\n return result;\n }\n\n /**\n * Counts the number of documents that match a query\n * \n * @param query - The query to filter documents\n * @returns The number of documents that match the query\n */\n countDocuments(query: Filter<this['_type']>): Promise<number> {\n return this.requireCollection().countDocuments(query);\n }\n\n /**\n * Fetches multiple documents, equivalent to Node.js MongoDB driver's `find` and `toArray` methods combined.\n * \n * @param query - The query to filter documents\n * @param options - Options\n * @returns The documents\n */\n async fetch(query: Filter<this['_type']>, options?: { sort?: Document, limit?: number, skip?: number }): Promise<this['_doc'][]> {\n const cursor = this.find(query, options)\n return (await cursor.toArray()).map(this.wrapDocument.bind(this));\n }\n\n /**\n * Inserts a single document\n * \n * @param document - The document to insert\n * @returns The result of the insert operation\n */\n async insertOne(document: OptionalUnlessRequiredId<this['_type']>): Promise<InsertOneResult> {\n return await this.requireCollection().insertOne(document);\n }\n\n /**\n * Inserts multiple documents\n * \n * @param documents - The documents to insert\n * @returns The result of the insert operation\n */\n async insertMany(documents: OptionalUnlessRequiredId<this['_type']>[]): Promise<InsertManyResult> {\n return await this.requireCollection().insertMany(documents);\n }\n\n /**\n * Updates a single document\n * \n * @param selector - The selector to find the document to update\n * @param update - The update to apply to the document\n * @returns The result of the update operation\n */\n async updateOne(selector: Filter<this['_type']> | string | ObjectId, update: UpdateFilter<this['_type']>): Promise<UpdateResult> {\n return await this.requireCollection().updateOne(this.getSelector(selector), update);\n }\n\n /**\n * Updates a single document, or inserts it if it doesn't exist\n * \n * @param selector - The selector to find the document to update\n * @param update - The MongoDB modifier to apply to the document\n * @returns The result of the update operation\n */\n async upsertOne(selector: Filter<this['_type']> | string | ObjectId, update: UpdateFilter<this['_type']>): Promise<UpdateResult> {\n return await this.requireCollection().updateOne(this.getSelector(selector), update, { upsert: true });\n }\n\n /**\n * Updates multiple documents\n * \n * @param selector - The selector to find the documents to update\n * @param update - The MongoDB modifier to apply to the documents\n * @returns The result of the update operation\n */\n async updateMany(\n selector: Filter<this['_type']>, \n update: UpdateFilter<this['_type']>, \n options?: { session?: ClientSession }\n ): Promise<UpdateResult> {\n return await this.requireCollection().updateMany(selector, update, options);\n }\n\n /**\n * Updates multiple documents, or inserts them if they don't exist\n * \n * @param selector - The selector to find the documents to update\n * @param update - The MongoDB modifier to apply to the documents\n * @returns The result of the update operation\n */\n async upsertMany(selector: Filter<this['_type']>, update: UpdateFilter<this['_type']>): Promise<UpdateResult> {\n return await this.requireCollection().updateMany(selector, update, { upsert: true });\n }\n\n /**\n * Deletes a single document\n * \n * @param selector - The selector to find the document to delete\n * @returns The result of the delete operation\n */\n async deleteOne(selector: Filter<this['_type']>): Promise<DeleteResult> {\n return await this.requireCollection().deleteOne(selector);\n }\n\n /**\n * Deletes multiple documents\n * \n * @param selector - The selector to find the documents to delete\n * @returns The result of the delete operation\n */\n async deleteMany(selector: Filter<this['_type']>): Promise<DeleteResult> {\n return await this.requireCollection().deleteMany(selector);\n }\n\n /**\n * Aggregates documents using MongoDB's aggregation framework\n * \n * @param pipeline - The aggregation pipeline\n * @param options - Optional options\n * @returns The aggregation cursor\n */\n aggregate(pipeline: Document[], options?: AggregateOptions): AggregationCursor<Document> {\n return this.requireCollection().aggregate(pipeline, options);\n }\n\n /**\n * Performs a bulk write operation on the collection\n * \n * @param operations - The operations to perform\n * @returns The result of the bulk write operation\n */\n bulkWrite(operations: AnyBulkWriteOperation<this['_type']>[]): Promise<BulkWriteResult> {\n return this.requireCollection().bulkWrite(operations);\n }\n\n /**\n * Returns the raw MongoDB database instance for advanced operations\n * @returns The MongoDB database instance\n * @throws Error if the store is not provisioned\n */\n getDatabase() {\n return this.requireClient().db();\n }\n\n /**\n * Returns the raw MongoDB collection instance for advanced operations\n * @returns The MongoDB collection instance\n * @throws Error if the store is not provisioned\n */\n rawCollection() {\n return this.requireCollection();\n }\n\n /**\n * Renames an existing collection to this store's name, used for migrations\n * @param oldName - The previous name of the collection\n * @throws Error if the old collection doesn't exist or if this store's collection already exists\n */\n async renameFrom(oldName: string, options?: { session?: ClientSession }) {\n const db = this.getDatabase();\n\n if (!this.collection || !db) {\n throw new Error(`Store ${this.name} is not provisioned`);\n }\n\n const oldCollections = await db.listCollections({ name: oldName }).toArray();\n if (oldCollections.length === 0) {\n throw new Error(`Collection ${oldName} not found`);\n }\n\n const newCollections = await db.listCollections({ name: this.name }).toArray();\n if (newCollections.length > 0) {\n throw new Error(`Collection ${this.name} already exists`);\n }\n\n const existingCollection = db.collection<this['_type']>(oldName);\n\n await existingCollection.rename(this.name, options);\n }\n}\n","import { ObjectId } from 'mongodb';\nimport { z } from 'zod';\nimport { Store } from './store';\n\ntype ObjectTypeDefinition = {\n [key: string]: SchemaTypeDefinition;\n};\n\ntype SingularSchemaTypeDefinition = z.ZodType | ObjectTypeDefinition; // ReturnType<typeof schema[keyof typeof schema]>;\n\ntype SchemaTypeDefinition = SingularSchemaTypeDefinition | Array<SingularSchemaTypeDefinition>;\n\nexport type ModelSchema = {\n [key: string]: SchemaTypeDefinition;\n};\n\nconst schemaString: typeof z.string = z.string.bind(z);\n\nconst schemaNumber: typeof z.number = z.number.bind(z);\n\nconst schemaDate: typeof z.date = z.date.bind(z);\n\nconst schemaBoolean: typeof z.boolean = z.boolean.bind(z);\n\nconst schemaArray: typeof z.array = z.array.bind(z);\n\nconst schemaObject: typeof z.object = z.object.bind(z);\n\nconst schemaEnum: typeof z.enum = z.enum.bind(z);\n\nexport const schema = {\n string: schemaString,\n number: schemaNumber,\n date: schemaDate,\n boolean: schemaBoolean,\n array: schemaArray,\n object: schemaObject,\n enum: schemaEnum,\n objectId(): z.ZodType<ObjectId> {\n return z.instanceof(ObjectId);\n },\n userId(): z.ZodType<ObjectId> {\n return z.instanceof(ObjectId);\n },\n ref(collection: string | Store<any, any>): z.ZodType<ObjectId> {\n return z.instanceof(ObjectId);\n },\n union: z.union.bind(z),\n infer<T extends SchemaTypeDefinition>(schema: T): InferDocumentType<T> {\n return {} as InferDocumentType<T>;\n }\n} as const;\n\nexport type InferDocumentType<T extends SchemaTypeDefinition> = {\n [K in keyof T as T[K] extends z.ZodOptional<any> ? K : never]?: (T[K] extends z.ZodType ? z.infer<T[K]> : never);\n} & {\n [K in keyof T as T[K] extends z.ZodOptional<any> ? never : K]:\n T[K] extends z.ZodType ? z.infer<T[K]> :\n T[K] extends Array<infer ElementType extends SchemaTypeDefinition> ? Array<InferDocumentType<ElementType>> :\n T[K] extends ObjectTypeDefinition ? InferDocumentType<T[K]> :\n never;\n};\n\nexport namespace schema {\n export type infer<T extends SchemaTypeDefinition> = InferDocumentType<T>;\n}\n","import { randomBytes } from 'crypto';\nimport { ObjectId } from 'mongodb';\nimport { Module } from '../app/module';\nimport { getPublicConfigs } from '../config/server';\nimport { Store } from '../data/store';\nimport { schema } from '../data/types';\nimport { time } from '../time';\nimport { Session } from './types';\n\nexport const sessionsCollection = new Store('_modelenceSessions', {\n schema: {\n authToken: schema.string(),\n createdAt: schema.date(),\n expiresAt: schema.date(),\n userId: schema.userId().nullable(),\n },\n indexes: [\n { key: { authToken: 1 }, unique: true },\n { key: { expiresAt: 1 }},\n ]\n // TODO: add TTL index on expiresAt\n});\n\nexport async function obtainSession(authToken: string | null): Promise<Session> {\n const existingSession = authToken ? await sessionsCollection.findOne({ authToken }) : null;\n\n if (existingSession) {\n return {\n authToken: String(existingSession.authToken),\n expiresAt: new Date(existingSession.expiresAt),\n userId: existingSession.userId ?? null,\n }\n }\n\n return await createSession();\n}\n\nexport async function setSessionUser(authToken: string, userId: ObjectId) {\n await sessionsCollection.updateOne({ authToken }, {\n $set: { userId }\n });\n}\n\nexport async function clearSessionUser(authToken: string) {\n await sessionsCollection.updateOne({ authToken }, {\n $set: { userId: null }\n });\n}\n\nexport async function createSession(userId: ObjectId | null = null): Promise<Session> {\n // TODO: add rate-limiting and captcha handling\n\n const authToken = randomBytes(32).toString('base64url');\n const now = Date.now();\n const expiresAt = new Date(now + time.days(7));\n\n await sessionsCollection.insertOne({\n authToken,\n createdAt: new Date(now),\n expiresAt,\n userId,\n });\n\n return {\n authToken,\n expiresAt,\n userId,\n };\n}\n\nasync function processSessionHeartbeat(session: Session) {\n const now = Date.now();\n const newExpiresAt = new Date(now + time.days(7));\n\n await sessionsCollection.updateOne({ authToken: session.authToken }, {\n $set: {\n lastActiveDate: new Date(now),\n expiresAt: newExpiresAt\n }\n });\n}\n\nexport default new Module('_system.session', {\n stores: [sessionsCollection],\n mutations: {\n init: async function(args, { session, user }) {\n // TODO: mark or track app load somewhere\n \n return {\n session,\n user,\n configs: getPublicConfigs(),\n };\n },\n heartbeat: async function(args, { session }) {\n // Session might not exist if there is no database/authentication setup\n if (session) {\n await processSessionHeartbeat(session);\n }\n }\n },\n});\n","import { schema } from '../data/types';\nimport { Store } from '../data/store';\n\n/**\n * Database collection for storing user accounts with authentication methods and profile information.\n * \n * This is where **signupWithPassword** automatically creates new users.\n * \n * @example\n * ```typescript\n * // Find user by email\n * const user = await dbUsers.findOne(\n * { 'emails.address': 'john@example.com' }\n * );\n * ```\n * \n */\nexport const usersCollection = new Store('_modelenceUsers', {\n schema: {\n handle: schema.string(),\n emails: schema.array(schema.object({\n address: schema.string(),\n verified: schema.boolean(),\n })).optional(),\n createdAt: schema.date(),\n authMethods: schema.object({\n password: schema.object({\n hash: schema.string(),\n }).optional(),\n google: schema.object({\n id: schema.string(),\n }).optional(),\n }),\n },\n indexes: [\n {\n key: { handle: 1 },\n unique: true,\n collation: { locale: 'en', strength: 2 } // Case-insensitive\n },\n ]\n});\n\nexport const dbDisposableEmailDomains = new Store('_modelenceDisposableEmailDomains', {\n schema: {\n domain: schema.string(),\n addedAt: schema.date(),\n },\n indexes: [\n {\n key: { domain: 1 },\n unique: true\n }\n ]\n});\n\nexport const emailVerificationTokensCollection = new Store('_modelenceEmailVerificationTokens', {\n schema: {\n userId: schema.objectId(),\n email: schema.string().optional(),\n token: schema.string(),\n createdAt: schema.date(),\n expiresAt: schema.date(),\n },\n indexes: [\n {\n key: { token: 1 },\n unique: true\n },\n {\n key: { expiresAt: 1 },\n expireAfterSeconds: 0\n }\n ]\n});\n","import { time } from '../time';\nimport { dbDisposableEmailDomains } from './db';\n\nexport async function isDisposableEmail(email: string): Promise<boolean> {\n const emailParts = email.toLowerCase().trim().split('@');\n if (emailParts.length !== 2) {\n return false;\n }\n \n const domain = emailParts[1];\n const result = await dbDisposableEmailDomains.findOne({ domain });\n return Boolean(result);\n}\n\nexport const updateDisposableEmailListCron = {\n interval: time.days(1),\n async handler() {\n const response = await fetch('https://disposable.github.io/disposable-email-domains/domains.txt');\n \n if (!response.ok) {\n throw new Error(`HTTP ${response.status}: ${response.statusText}`);\n }\n \n const domainsText = await response.text();\n \n const domains = domainsText\n .split('\\n')\n .map(domain => domain.trim().toLowerCase())\n .filter(domain => domain.length > 0);\n \n const now = new Date();\n \n // Insert domains in batches to avoid overwhelming the database\n const batchSize = 500;\n for (let i = 0; i < domains.length; i += batchSize) {\n const batch = domains.slice(i, i + batchSize);\n \n try {\n await dbDisposableEmailDomains.insertMany(\n batch.map(domain => ({\n domain,\n addedAt: now,\n }))\n );\n } catch (error: any) {\n // MongoDB throws BulkWriteError when some documents are duplicates\n if (error.name === 'MongoBulkWriteError' && error.result?.nInserted) {\n // console.warn(`Error inserting batch starting at index ${i}:`, error.message);\n }\n }\n }\n }\n}\n","import { EmailProvider } from \"@modelence/types\";\n\nexport type EmailConfig = {\n provider?: EmailProvider;\n from?: string;\n verification?: {\n subject?: string;\n template?: (props: {\n name: string;\n email: string;\n verificationUrl: string;\n }) => string;\n redirectUrl?: string;\n };\n // @deprecated use verification.redirectUrl instead\n emailVerifiedRedirectUrl?: string;\n};\n\nlet emailConfig: EmailConfig = Object.freeze({});\n\nexport function setEmailConfig(newEmailConfig: EmailConfig) {\n emailConfig = Object.freeze(Object.assign({}, emailConfig, newEmailConfig));\n}\n\nexport function getEmailConfig() {\n return emailConfig;\n}\n","export function isServer() {\n return typeof window !== 'object';\n}\n\nexport function requireServer() {\n if (!isServer()) {\n throw new Error('This function can only be called on the server');\n }\n}\n\nexport function htmlToText(html: string) {\n return html.replace(/<[^>]*>/g, '').replace(/\\s+/g, ' ').trim()\n}\n","export function emailVerificationTemplate({ name, email, verificationUrl }: { name?: string; email: string; verificationUrl: string }) {\n return `\n <p>Hi${name ? ` ${name}` : ''},</p>\n <p>Please verify your email address ${email} by clicking the link below:</p>\n <p><a href=\"${verificationUrl}\">${verificationUrl}</a></p>\n <p>If you did not request this, please ignore this email.</p>\n `;\n}\n","import { z } from 'zod';\n\nimport { usersCollection, emailVerificationTokensCollection } from './db';\nimport { ObjectId, RouteParams, RouteResponse } from '@/server';\nimport { getEmailConfig } from '@/app/emailConfig';\nimport { randomBytes } from 'crypto';\nimport { time } from '@/time';\nimport { htmlToText } from '@/utils';\nimport { emailVerificationTemplate } from './templates/emailVerficationTemplate';\n\nexport async function handleVerifyEmail(params: RouteParams): Promise<RouteResponse> {\n const emailVerifiedRedirectUrl = getEmailConfig().emailVerifiedRedirectUrl || '/';\n try {\n const token = z.string().parse(params.query.token);\n // Find token in database\n const tokenDoc = await emailVerificationTokensCollection.findOne({\n token,\n expiresAt: { $gt: new Date() }\n });\n\n if (!tokenDoc) {\n throw new Error('Invalid or expired verification token');\n }\n\n // Find user by token's userId\n const userDoc = await usersCollection.findOne({ _id: tokenDoc.userId });\n\n if (!userDoc) {\n throw new Error('User not found');\n }\n\n const email = tokenDoc.email;\n\n if (!email) {\n throw new Error('Email not found in token');\n }\n\n // Mark the specific email as verified atomically\n const updateResult = await usersCollection.updateOne(\n { \n _id: tokenDoc.userId,\n 'emails.address': email,\n 'emails.verified': { $ne: true }\n },\n { $set: { 'emails.$.verified': true } }\n );\n\n if (updateResult.matchedCount === 0) {\n // Check if email exists but is already verified\n const existingUser = await usersCollection.findOne({\n _id: tokenDoc.userId,\n 'emails.address': email\n });\n \n if (existingUser) {\n throw new Error('Email is already verified');\n } else {\n throw new Error('Email address not found for this user');\n }\n }\n\n // Delete the used token\n await emailVerificationTokensCollection.deleteOne({ _id: tokenDoc._id });\n } catch (error) {\n if (error instanceof Error) {\n console.error('Error verifying email:', error);\n return {\n status: 301,\n redirect: `${emailVerifiedRedirectUrl}?status=error&message=${encodeURIComponent(error.message)}`,\n };\n }\n }\n\n return {\n status: 301,\n redirect: `${emailVerifiedRedirectUrl}?status=verified`,\n };\n}\n\nexport async function sendVerificationEmail({\n userId,\n email,\n baseUrl = process.env.MODELENCE_SITE_URL\n}: {\n userId: ObjectId;\n email: string;\n baseUrl?: string;\n}) {\n if (getEmailConfig().provider) {\n const emailProvider = getEmailConfig().provider;\n\n // Generate verification token\n const verificationToken = randomBytes(32).toString('hex');\n const expiresAt = new Date(Date.now() + time.hours(24));\n\n // Store token in database\n await emailVerificationTokensCollection.insertOne({\n userId,\n email,\n token: verificationToken,\n createdAt: new Date(),\n expiresAt,\n });\n \n const verificationUrl = `${baseUrl}/api/_internal/auth/verify-email?token=${verificationToken}`;\n \n const template = getEmailConfig()?.verification?.template || emailVerificationTemplate;\n // TODO: we should have also the name on this step\n const htmlTemplate = template({ name: '', email, verificationUrl });\n const textContent = htmlToText(htmlTemplate);\n \n await emailProvider?.sendEmail({\n to: email,\n from: getEmailConfig()?.from || 'noreply@modelence.com',\n subject: getEmailConfig()?.verification?.subject || 'Verify your email address',\n text: textContent,\n html: htmlTemplate,\n });\n }\n}\n","import bcrypt from 'bcrypt';\nimport { z } from 'zod';\n\nimport { Args, Context } from '../methods/types';\nimport { usersCollection } from './db';\nimport { clearSessionUser, setSessionUser } from './session';\nimport { sendVerificationEmail } from './verification';\nimport { getEmailConfig } from '@/app/emailConfig';\nimport { consumeRateLimit } from '@/server';\n\nexport async function handleLoginWithPassword(args: Args, { user, session, connectionInfo }: Context) {\n if (!session) {\n throw new Error('Session is not initialized');\n }\n\n const ip = connectionInfo?.ip;\n if (ip) {\n await consumeRateLimit({\n bucket: 'signin',\n type: 'ip',\n value: ip,\n });\n }\n\n const email = z.string().email().parse(args.email);\n const password = z.string().parse(args.password);\n\n // TODO: add rate limiting by email (and perhaps IP address overall)\n\n if (user) {\n // TODO: handle cases where a user is already logged in\n }\n\n const userDoc = await usersCollection.findOne(\n { 'emails.address': email },\n { collation: { locale: 'en', strength: 2 } }\n );\n\n const passwordHash = userDoc?.authMethods?.password?.hash;\n if (!passwordHash) {\n throw incorrectCredentialsError();\n }\n\n const emailDoc = userDoc.emails?.find(e => e.address === email);\n\n if (!emailDoc?.verified && getEmailConfig()?.provider) {\n if (ip) {\n try {\n await consumeRateLimit({\n bucket: 'verification',\n type: 'user',\n value: userDoc._id.toString(),\n });\n } catch {\n throw new Error(\"Your email address hasn't been verified yet. Please use the verification email we've send earlier to your inbox.\");\n }\n }\n\n await sendVerificationEmail({\n userId: userDoc?._id,\n email,\n baseUrl: connectionInfo?.baseUrl,\n });\n throw new Error(\"Your email address hasn't been verified yet. We've sent a new verification email to your inbox.\");\n }\n\n const isValidPassword = await bcrypt.compare(password, passwordHash);\n if (!isValidPassword) {\n throw incorrectCredentialsError();\n }\n\n await setSessionUser(session.authToken, userDoc._id);\n\n return {\n user: {\n id: userDoc._id,\n handle: userDoc.handle,\n }\n }\n}\n\nexport async function handleLogout(args: Args, { user, session }: Context) {\n if (!session) {\n throw new Error('Session is not initialized');\n }\n\n await clearSessionUser(session.authToken);\n}\n\n/*\n It is important to return the same exact error both in case the email\n or password is incorrect so that the client cannot tell the difference,\n otherwise it would allow for an enumeration attack.\n*/\nfunction incorrectCredentialsError() {\n return new Error('Incorrect email/password combination');\n}\n","import { usersCollection } from './db';\nimport { Args, Context } from '../methods/types';\n\nexport async function getOwnProfile(_args: Args, { user }: Context) {\n if (!user) {\n throw new Error('Not authenticated');\n }\n\n const profile = await usersCollection.requireById(user.id);\n\n return {\n handle: profile.handle,\n emails: profile.emails,\n authMethods: Object.keys(profile.authMethods || {}),\n };\n}\n","import { Store } from '../data/store';\nimport { schema } from '../data/types';\n\n/**\n * Two-bucket sliding window approximation to track rate limits.\n * This is a trade-off between storage and accuracy.\n * We're not keeping exact event logs, so we can't track the exact number of events in a window.\n * Instead, we're adding a weighted average from the previous window to the current window.\n */\nexport const dbRateLimits = new Store('_modelenceRateLimits', {\n schema: {\n bucket: schema.string(),\n type: schema.enum(['ip', 'user']),\n value: schema.string(),\n windowMs: schema.number(),\n\n windowStart: schema.date(),\n windowCount: schema.number(),\n prevWindowCount: schema.number(),\n\n expiresAt: schema.date(),\n },\n indexes: [\n { key: { bucket: 1, type: 1, value: 1, windowMs: 1 }, unique: true },\n { key: { expiresAt: 1 }, expireAfterSeconds: 0 },\n ]\n});\n","import { RateLimitRule, RateLimitType } from './types';\nimport { dbRateLimits } from './db';\nimport { RateLimitError } from '../error';\n\nlet allRules: Array<RateLimitRule> = [];\n\nexport function initRateLimits(rateLimits: RateLimitRule[]) {\n if (allRules.length > 0) {\n throw new Error('Duplicate call to initRateLimits - already initialized');\n }\n\n allRules = rateLimits;\n}\n\n/**\n * This function will check all rate limit rules on the specified bucket and type,\n * throw an error if any of them are exceeded and increase the count of the rate limit record.\n * \n * @category Rate Limits\n * \n * @example\n * ```ts\n * await consumeRateLimit({ bucket: 'api', type: 'ip', value: '127.0.0.1' });\n * ```\n * @param options.bucket - The bucket for the rate limit.\n * @param options.type - The type of the rate limit.\n * @param options.value - The value for the rate limit.\n */\nexport async function consumeRateLimit(\n options: { bucket: string, type: RateLimitType, value: string }\n) {\n const { bucket, type, value } = options;\n const rules = allRules.filter(rule => rule.bucket === bucket && rule.type === type);\n\n for (const rule of rules) {\n await checkRateLimitRule(rule, value);\n }\n}\n\n// Two-bucket sliding window approximation to track rate limits.\nasync function checkRateLimitRule(rule: RateLimitRule, value: string, createError?: () => Error) {\n const createRateLimitError = () => {\n return createError ? createError() : new RateLimitError(`Rate limit exceeded for ${rule.bucket}`);\n };\n\n const record = await dbRateLimits.findOne({\n bucket: rule.bucket,\n type: rule.type,\n value,\n windowMs: rule.window,\n });\n\n const now = Date.now();\n const currentWindowStart = Math.floor(now / rule.window) * rule.window;\n\n const { count, modifier } = record\n ? getCount(record, currentWindowStart, now)\n : {\n count: 0,\n modifier: {\n $setOnInsert: {\n windowStart: new Date(currentWindowStart),\n windowCount: 1,\n prevWindowCount: 0,\n expiresAt: new Date(currentWindowStart + rule.window + rule.window),\n }\n }\n };\n\n if (count >= rule.limit) {\n throw createRateLimitError();\n }\n\n /*\n Always use upsert, because there is a small chance the document might be auto-removed\n based on the expiration TTL index in between the check and the update\n */\n await dbRateLimits.upsertOne(\n { bucket: rule.bucket, type: rule.type, value, windowMs: rule.window }, \n modifier\n );\n}\n\nfunction getCount(record: typeof dbRateLimits['Doc'], currentWindowStart: number, now: number) {\n const prevWindowStart = currentWindowStart - record.windowMs;\n \n if (record.windowStart.getTime() === currentWindowStart) {\n const currentWindowCount = record.windowCount;\n const prevWindowCount = record.prevWindowCount;\n const prevWindowWeight = 1 - (now - currentWindowStart) / record.windowMs;\n return {\n count: Math.round(currentWindowCount + prevWindowCount * prevWindowWeight),\n modifier: {\n $inc: { windowCount: 1 },\n $setOnInsert: {\n windowStart: new Date(currentWindowStart),\n prevWindowCount: 0,\n expiresAt: new Date(currentWindowStart + record.windowMs + record.windowMs),\n }\n }\n };\n }\n \n if (record.windowStart.getTime() === prevWindowStart) {\n const weight = 1 - (now - currentWindowStart) / record.windowMs;\n return {\n count: Math.round(record.windowCount * weight),\n modifier: {\n $set: {\n windowStart: new Date(currentWindowStart),\n windowCount: 1,\n prevWindowCount: record.windowCount,\n expiresAt: new Date(currentWindowStart + record.windowMs + record.windowMs),\n }\n }\n };\n }\n \n return {\n count: 0,\n modifier: {\n $set: {\n windowStart: new Date(currentWindowStart),\n windowCount: 1,\n prevWindowCount: 0,\n expiresAt: new Date(currentWindowStart + record.windowMs + record.windowMs),\n }\n }\n };\n}\n","import { z } from 'zod';\nimport bcrypt from 'bcrypt';\n\nimport { Args, Context } from '../methods/types';\nimport { usersCollection } from './db';\nimport { isDisposableEmail } from './disposableEmails';\nimport { consumeRateLimit } from '../rate-limit/rules';\nimport { sendVerificationEmail } from './verification';\n\nexport async function handleSignupWithPassword(args: Args, { user, connectionInfo }: Context) {\n const email = z.string().email().parse(args.email);\n const password = z.string()\n .min(8, { message: 'Password must contain at least 8 characters' })\n .parse(args.password);\n\n const ip = connectionInfo?.ip;\n if (ip) {\n await consumeRateLimit({\n bucket: 'signupAttempt',\n type: 'ip',\n value: ip,\n });\n }\n\n if (await isDisposableEmail(email)) {\n throw new Error('Please use a permanent email address');\n }\n\n // TODO: captcha check\n\n if (user) {\n // TODO: handle cases where a user is already logged in\n }\n\n const existingUser = await usersCollection.findOne(\n { 'emails.address': email },\n { collation: { locale: 'en', strength: 2 } }\n );\n\n if (existingUser) {\n const existingEmail = existingUser.emails?.find(e => e.address === email);\n throw new Error(`User with email already exists: ${existingEmail?.address}`);\n }\n\n if (ip) {\n await consumeRateLimit({\n bucket: 'signup',\n type: 'ip',\n value: ip,\n });\n }\n\n // Hash password with bcrypt (salt is automatically generated)\n const hash = await bcrypt.hash(password, 10);\n\n const result = await usersCollection.insertOne({\n handle: email,\n emails: [{\n address: email,\n verified: false,\n }],\n createdAt: new Date(),\n authMethods: {\n password: {\n hash,\n }\n }\n });\n\n await sendVerificationEmail({\n userId: result?.insertedId,\n email,\n baseUrl: connectionInfo?.baseUrl,\n });\n \n\n return result.insertedId;\n}\n","import { randomBytes } from 'crypto';\n\nimport { Module } from '../app/module';\nimport { time } from '../time';\nimport {\n dbDisposableEmailDomains,\n emailVerificationTokensCollection,\n usersCollection\n} from './db';\nimport { updateDisposableEmailListCron } from './disposableEmails';\nimport { handleLoginWithPassword, handleLogout } from './login';\nimport { getOwnProfile } from './profile';\nimport { handleSignupWithPassword } from './signup';\nimport { handleVerifyEmail } from './verification';\n\nasync function createGuestUser() {\n // TODO: add rate-limiting and captcha handling\n\n const guestId = randomBytes(9)\n .toString('base64')\n .replace(/[+/]/g, c => c === '+' ? 'a' : 'b');\n\n const handle = `guest_${guestId}`;\n // TODO: re-try on handle collision\n\n const result = await usersCollection.insertOne({\n handle,\n createdAt: new Date(),\n authMethods: {},\n });\n\n return result.insertedId;\n}\n\nexport default new Module('_system.user', {\n stores: [\n usersCollection,\n dbDisposableEmailDomains,\n emailVerificationTokensCollection,\n ],\n queries: {\n getOwnProfile,\n },\n mutations: {\n signupWithPassword: handleSignupWithPassword,\n loginWithPassword: handleLoginWithPassword,\n logout: handleLogout,\n },\n cronJobs: {\n updateDisposableEmailList: updateDisposableEmailListCron\n },\n rateLimits: [{\n bucket: 'signup',\n type: 'ip',\n window: time.minutes(15),\n limit: 20,\n }, {\n bucket: 'signup',\n type: 'ip',\n window: time.days(1),\n limit: 200,\n }, {\n bucket: 'signupAttempt',\n type: 'ip',\n window: time.minutes(15),\n limit: 50,\n }, {\n bucket: 'signupAttempt',\n type: 'ip',\n window: time.days(1),\n limit: 500,\n }, {\n bucket: 'signin',\n type: 'ip',\n window: time.minutes(15),\n limit: 50,\n }, {\n bucket: 'signin',\n type: 'ip',\n window: time.days(1),\n limit: 500,\n }, {\n bucket: 'verification',\n type: 'user',\n window: time.minutes(15),\n limit: 3,\n }, {\n bucket: 'verification',\n type: 'user',\n window: time.days(1),\n limit: 10,\n }],\n configSchema: {\n 'auth.email.enabled': {\n type: 'boolean',\n isPublic: true,\n default: true,\n },\n 'auth.email.from': {\n type: 'string',\n isPublic: false,\n default: '',\n },\n 'auth.email.verification': {\n type: 'boolean',\n isPublic: true,\n default: false,\n },\n 'auth.google.enabled': {\n type: 'boolean',\n isPublic: true,\n default: false,\n },\n 'auth.google.clientId': {\n type: 'string',\n isPublic: false,\n default: '',\n },\n 'auth.google.clientSecret': {\n type: 'secret',\n isPublic: false,\n default: '',\n },\n },\n routes: [\n {\n path: '/api/_internal/auth/verify-email',\n handlers: {\n get: handleVerifyEmail\n },\n }\n ],\n});\n","import os from 'os';\nimport { ConfigSchema } from '../config/types';\nimport { CronJobMetadata } from '../cron/types';\nimport { Store } from '../data/store';\nimport { AppConfig } from '../config/types';\n\ntype CloudBackendConnectOkResponse = {\n status: 'ok';\n configs: AppConfig[];\n environmentId: string;\n appAlias: string;\n environmentAlias: string;\n telemetry: {\n isEnabled: boolean;\n serviceName: string;\n };\n};\n\ntype CloudBackendConnectErrorResponse = {\n status: 'error';\n error: string;\n}\n\nexport type CloudBackendConnectResponse = CloudBackendConnectOkResponse | CloudBackendConnectErrorResponse;\n\nexport async function connectCloudBackend(\n { configSchema, cronJobsMetadata, stores }: { \n configSchema?: ConfigSchema, \n cronJobsMetadata?: CronJobMetadata[], \n stores: Store<any, any>[] \n }\n): Promise<CloudBackendConnectOkResponse> {\n const containerId = process.env.MODELENCE_CONTAINER_ID;\n if (!containerId) {\n throw new Error('Unable to connect to Modelence Cloud: MODELENCE_CONTAINER_ID is not set');\n }\n\n try {\n const dataModels = Object.values(stores).map(store => {\n return {\n name: store.getName(),\n schema: store.getSchema(),\n collections: [store.getName()]\n };\n });\n\n const data = await callApi('/api/connect', 'POST', {\n hostname: os.hostname(),\n containerId,\n dataModels,\n configSchema,\n cronJobsMetadata,\n });\n\n if (data.status === 'error') {\n throw new Error(data.error);\n }\n\n console.log('Successfully connected to Modelence Cloud');\n\n return data;\n } catch (error) {\n console.error('Unable to connect to Modelence Cloud:', error);\n throw error;\n }\n}\n\nexport async function fetchConfigs() {\n const data = await callApi('/api/configs', 'GET');\n return data;\n}\n\nexport async function syncStatus() {\n const data = await callApi('/api/sync', 'POST', {\n containerId: process.env.MODELENCE_CONTAINER_ID\n });\n return data;\n}\n\nasync function callApi(endpoint: string, method: string, payload?: object) {\n const { MODELENCE_SERVICE_ENDPOINT, MODELENCE_SERVICE_TOKEN } = process.env;\n\n if (!MODELENCE_SERVICE_ENDPOINT) {\n throw new Error('Unable to connect to Modelence Cloud: MODELENCE_SERVICE_ENDPOINT is not set');\n }\n\n const response = await fetch(`${MODELENCE_SERVICE_ENDPOINT}${endpoint}`, {\n method,\n headers: {\n 'Authorization': `Bearer ${MODELENCE_SERVICE_TOKEN}`,\n ...(payload ? { 'Content-Type': 'application/json' } : {})\n },\n body: payload ? JSON.stringify(payload) : undefined\n });\n\n if (!response.ok) {\n const data = await response.text();\n try {\n const json = JSON.parse(data);\n throw new Error(`Unable to connect to Modelence Cloud: HTTP status: ${response.status}, ${json?.error}`);\n } catch (error) {\n throw new Error(`Unable to connect to Modelence Cloud: HTTP status: ${response.status}, ${data}`);\n }\n }\n\n return await response.json();\n}\n","import { time } from '../time';\nimport { fetchConfigs, syncStatus } from '../app/backendApi';\nimport { loadConfigs } from './server';\n\nlet isSyncing = false;\n\nconst SYNC_INTERVAL = time.seconds(10);\n\nexport function startConfigSync() {\n setInterval(async() => {\n if (isSyncing) {\n return;\n }\n \n isSyncing = true;\n\n // TODO: move this sync outside of config\n try {\n await syncStatus();\n } catch (error) {\n console.error('Error syncing status', error);\n }\n \n try {\n await syncConfig();\n } catch (error) {\n console.error('Error syncing config', error);\n }\n \n isSyncing = false; \n }, SYNC_INTERVAL);\n}\n\nasync function syncConfig() {\n const { configs } = await fetchConfigs();\n loadConfigs(configs);\n}\n","// import { Worker, isMainThread, parentPort, workerData } from 'worker_threads';\n\nimport { time } from '../time';\nimport { CronJob, CronJobInputParams } from './types';\nimport { startTransaction, captureError } from '@/telemetry';\nimport { Module } from '../app/module';\nimport { schema } from '../data/types';\nimport { Store } from '../data/store';\n\nconst DEFAULT_TIMEOUT = time.minutes(1);\n\n/**\n * Each cron instance acquires locks for the jobs it runs. If there was a pre-existing lock,\n * the lock is transferred to the new instance, but there is a delay to give the previous instance\n * a chance to see the new lock and gracefully finish remaining jobs.\n */\nconst LOCK_TRANSFER_DELAY = time.seconds(10);\n\nconst cronJobs: Record<string, CronJob> = {};\nlet cronJobsInterval: NodeJS.Timeout;\n\nconst cronJobsCollection = new Store('_modelenceCronJobs', {\n schema: {\n alias: schema.string(),\n lastStartDate: schema.date().optional(),\n lock: schema.object({\n containerId: schema.string(),\n acquireDate: schema.date(),\n }).optional(),\n },\n indexes: [\n { key: { alias: 1 }, unique: true, background: true },\n ]\n});\n\n// TODO: allow changing interval and timeout with cron jobconfigs\nexport function defineCronJob(\n alias: CronJob['alias'],\n { description = '', interval, timeout = DEFAULT_TIMEOUT, handler }: CronJobInputParams,\n) {\n if (cronJobs[alias]) {\n throw new Error(`Duplicate cron job declaration: '${alias}' already exists`);\n }\n\n if (cronJobsInterval) {\n throw new Error(`Unable to add a cron job - cron jobs have already been initialized: [${alias}]`);\n }\n\n if (interval < time.seconds(5)) {\n throw new Error(`Cron job interval should not be less than 5 second [${alias}]`);\n }\n\n if (timeout > time.days(1)) {\n throw new Error(`Cron job timeout should not be longer than 1 day [${alias}]`);\n }\n\n cronJobs[alias] = {\n alias,\n params: { description, interval, timeout },\n handler,\n state: {\n isRunning: false,\n }\n };\n}\n\nexport async function startCronJobs() {\n if (cronJobsInterval) {\n throw new Error('Cron jobs already started');\n }\n\n const aliasList = Object.keys(cronJobs);\n if (aliasList.length > 0) {\n const aliasSelector = { alias: { $in: aliasList } };\n\n const existingLockedRecord = await cronJobsCollection.findOne({\n ...aliasSelector,\n 'lock.containerId': { $exists: true }\n });\n\n // TODO: handle different application versions with different parameters for the same job alias\n\n await Promise.all(aliasList.map(alias => \n cronJobsCollection.upsertOne(\n { alias },\n {\n $set: {\n lock: {\n containerId: process.env.MODELENCE_CONTAINER_ID || 'unknown',\n acquireDate: new Date(),\n }\n }\n }\n )\n ));\n\n if (existingLockedRecord) {\n await sleep(LOCK_TRANSFER_DELAY);\n }\n\n const cronJobRecords = await cronJobsCollection.fetch(aliasSelector);\n const now = Date.now();\n cronJobRecords.forEach((record) => {\n const job = cronJobs[record.alias];\n if (!job) {\n return;\n }\n job.state.scheduledRunTs = record.lastStartDate ? record.lastStartDate.getTime() + job.params.interval : now;\n });\n Object.values(cronJobs).forEach((job) => {\n if (!job.state.scheduledRunTs) {\n job.state.scheduledRunTs = now;\n }\n });\n\n cronJobsInterval = setInterval(tickCronJobs, time.seconds(1));\n }\n}\n\nfunction sleep(ms: number) {\n return new Promise((resolve) => setTimeout(resolve, ms));\n}\n\nasync function tickCronJobs() {\n // TODO: periodically check if the locks are still there\n\n const now = Date.now();\n Object.values(cronJobs).forEach(async (job) => {\n const { params, state } = job;\n if (state.isRunning) {\n if (state.startTs && state.startTs + params.timeout < now) {\n // TODO: log cron trace timeout error\n state.isRunning = false;\n }\n return;\n }\n\n // TODO: limit the number of jobs running concurrently\n\n if (state.scheduledRunTs && state.scheduledRunTs <= now) {\n await startCronJob(job);\n }\n });\n}\n\nasync function startCronJob(job: CronJob) {\n const { alias, params, handler, state } = job;\n state.isRunning = true;\n state.startTs = Date.now();\n const transaction = startTransaction('cron', `cron:${alias}`);\n // TODO: enforce job timeout\n handler().then(() => {\n handleCronJobCompletion(state, params);\n transaction.end('success');\n }).catch((err) => {\n handleCronJobCompletion(state, params);\n captureError(err);\n transaction.end('error');\n console.error(`Error in cron job '${alias}':`, err);\n });\n await cronJobsCollection.updateOne({ alias }, {\n $set: {\n lastStartDate: new Date(state.startTs),\n }\n });\n}\n\nfunction handleCronJobCompletion(state: CronJob['state'], params: CronJob['params']) {\n state.scheduledRunTs = state.startTs ? state.startTs + params.interval : Date.now();\n state.startTs = undefined;\n state.isRunning = false;\n}\n\nexport function getCronJobsMetadata() {\n return Object.values(cronJobs).map(({ alias, params }) => ({\n alias,\n description: params.description,\n interval: params.interval,\n timeout: params.timeout,\n }));\n}\n\nexport default new Module('_system.cron', {\n stores: [cronJobsCollection],\n});\n\n// const runCronJob = () => {\n// const worker = new Worker(filePath, {\n// workerData: {},\n// execArgv: ['--loader', 'tsx'],\n// });\n\n// const timeoutId = setTimeout(() => {\n// worker.terminate();\n// console.error(`Cron job '${alias}' timed out after ${timeout}ms`);\n// }, timeout);\n\n// worker.on('message', (message) => {\n// if (message === 'done') {\n// clearTimeout(timeoutId);\n// worker.terminate();\n// }\n// });\n\n// worker.on('error', (err) => {\n// clearTimeout(timeoutId);\n// console.error(`Error in cron job '${alias}':`, err);\n// });\n\n// worker.on('exit', (code) => {\n// console.error(`Cron job '${alias}' exited with code ${code}`);\n// setTimeout(runCronJob, interval);\n// });\n// };\n","import { MongoClient, ServerApiVersion } from 'mongodb';\nimport { getConfig } from '../config/server';\n\nlet client: MongoClient | null = null;\n\nexport async function connect() {\n if (client) return client;\n\n const mongodbUri = getMongodbUri();\n if (!mongodbUri) {\n throw new Error('MongoDB URI is not set');\n }\n\n client = new MongoClient(mongodbUri, {\n maxPoolSize: 20\n });\n\n try {\n // Connect the client to the server\n await client.connect();\n // Send a ping to confirm a successful connection\n await client.db(\"admin\").command({ ping: 1 });\n console.log(\"Pinged your deployment. You successfully connected to MongoDB!\");\n return client;\n } catch (err) {\n console.error(err);\n client = null;\n throw err;\n }\n}\n\nexport function getMongodbUri() {\n const value = getConfig('_system.mongodbUri');\n return value ? String(value) : undefined;\n}\n\nexport function getClient() {\n return client;\n}\n\n// export async function closeConnection() {\n// if (client) {\n// await client.close();\n// client = null;\n// }\n// }\n","import { requireServer } from '../utils';\nimport { startTransaction } from '@/telemetry';\nimport { requireAccess } from '../auth/role';\nimport { Method, MethodDefinition, MethodType, Args, Context } from './types';\n\nconst methods: Record<string, Method<any>> = {};\n\nexport function createQuery<T extends any[]>(name: string, methodDef: MethodDefinition<T>) {\n requireServer();\n validateMethodName(name);\n return _createMethodInternal('query', name, methodDef);\n}\n\nexport function createMutation<T extends any[]>(name: string, methodDef: MethodDefinition<T>) {\n requireServer();\n validateMethodName(name);\n return _createMethodInternal('mutation', name, methodDef);\n}\n\nexport function _createSystemQuery<T extends any[]>(name: string, methodDef: MethodDefinition<T>) {\n requireServer();\n validateSystemMethodName(name);\n return _createMethodInternal('query', name, methodDef);\n}\n\nexport function _createSystemMutation<T extends any[]>(name: string, methodDef: MethodDefinition<T>) {\n requireServer();\n validateSystemMethodName(name);\n return _createMethodInternal('mutation', name, methodDef);\n}\n\nfunction validateMethodName(name: string) {\n if (name.toLowerCase().startsWith('_system.')) {\n throw new Error(`Method name cannot start with a reserved prefix: '_system.' (${name})`);\n }\n}\n\nfunction validateSystemMethodName(name: string) {\n if (!name.toLowerCase().startsWith('_system.')) {\n throw new Error(`System method name must start with a prefix: '_system.' (${name})`);\n }\n}\n\nfunction _createMethodInternal<T extends any>(type: MethodType, name: string, methodDef: MethodDefinition<T>) {\n requireServer();\n\n if (methods[name]) {\n throw new Error(`Method with name '${name}' is already defined.`);\n }\n\n const handler = typeof methodDef === 'function' ? methodDef : methodDef.handler;\n const permissions = typeof methodDef === 'function' ? [] : methodDef.permissions ?? [];\n methods[name] = { type, name, handler, permissions };\n}\n\nexport async function runMethod(name: string, args: Args, context: Context) {\n requireServer();\n\n const method = methods[name];\n if (!method) {\n throw new Error(`Method with name '${name}' is not defined.`);\n }\n const { type, handler } = method;\n\n const transaction = startTransaction('method', `method:${name}`, { type, args });\n\n let response;\n try {\n requireAccess(context.roles, method.permissions);\n response = await handler(args, context);\n } catch (error) {\n // TODO: log error and associate it with the transaction\n transaction.end('error');\n throw error;\n }\n\n transaction.end();\n\n return response;\n}\n","import { Store } from '../data/store';\nimport { schema } from '../data/types';\n\nexport const dbMigrations = new Store('_modelenceMigrations', {\n schema: {\n version: schema.number(),\n appliedAt: schema.date(),\n },\n indexes: [\n { key: { version: 1 }, unique: true },\n ],\n});\n","import { Module } from '../app/module';\nimport { dbMigrations } from './db';\n\nexport type MigrationScript = {\n version: number,\n description: string,\n handler: () => Promise<void>,\n}\n\nexport async function runMigrations(migrations: MigrationScript[]) {\n if (migrations.length === 0) {\n return;\n }\n\n const versions = migrations.map(({ version }) => version);\n\n const existingVersions = await dbMigrations.fetch({ version: { $in: versions } });\n const existingVersionSet = new Set(existingVersions.map(({ version }) => version));\n const pendingMigrations = migrations.filter(({ version }) => !existingVersionSet.has(version));\n\n if (pendingMigrations.length === 0) {\n return;\n }\n\n console.log(`Running migrations (${pendingMigrations.length})...`);\n for (const { version, description, handler } of pendingMigrations) {\n console.log(`Running migration v${version}: ${description}`);\n // TODO: adjust to handle multiple containers and race conditions\n await dbMigrations.insertOne({ version, appliedAt: new Date() });\n await handler();\n console.log(`Migration v${version} complete`);\n }\n}\n\nexport default new Module('_system.migration', {\n stores: [dbMigrations]\n});\n","import { Module } from '../app/module';\nimport { dbRateLimits } from './db';\n\nexport default new Module('_system.rateLimit', {\n stores: [dbRateLimits],\n});\n","import { createServer, defineConfig, ViteDevServer, loadConfigFromFile, UserConfig } from 'vite';\nimport reactPlugin from '@vitejs/plugin-react';\nimport path from 'path';\nimport fs from 'fs';\nimport express from 'express';\nimport { AppServer, ExpressMiddleware } from '@modelence/types';\n\nclass ViteServer implements AppServer {\n private viteServer?: ViteDevServer;\n private config?: UserConfig;\n\n async init() {\n this.config = await getConfig();\n if (this.isDev()) {\n console.log('Starting Vite dev server...');\n this.viteServer = await createServer({\n ...defineConfig(this.config),\n server: {\n middlewareMode: true,\n },\n root: './src/client'\n }); \n }\n }\n\n middlewares(): ExpressMiddleware[] {\n if (this.isDev()) {\n return (this.viteServer?.middlewares ?? []) as ExpressMiddleware[];\n }\n \n const staticFolders = [express.static('./.modelence/build/client')];\n if (this.config?.publicDir) {\n staticFolders.push(express.static(this.config.publicDir));\n }\n return staticFolders;\n }\n\n handler(req: express.Request, res: express.Response) {\n if (this.isDev()) {\n try {\n res.sendFile('index.html', { root: './src/client' });\n } catch (e) {\n console.error('Error serving index.html:', e);\n res.status(500).send('Internal Server Error');\n }\n } else {\n res.sendFile('index.html', { root: './.modelence/build/client' });\n }\n }\n\n private isDev() {\n return process.env.NODE_ENV !== 'production';\n }\n}\n\nasync function loadUserViteConfig() {\n const appDir = process.cwd();\n \n try {\n const result = await loadConfigFromFile({ command: 'serve', mode: 'development' }, undefined, appDir);\n return result?.config || {};\n } catch (error) {\n console.warn(`Could not load vite config:`, error);\n return {};\n }\n}\n\nasync function getConfig() {\n const appDir = process.cwd();\n const userConfig = await loadUserViteConfig();\n\n const eslintConfigFile = [\n '.eslintrc.js',\n '.eslintrc.json',\n '.eslintrc',\n 'eslint.config.js',\n '.eslintrc.yml',\n '.eslintrc.yaml'\n ].find(file => fs.existsSync(path.join(appDir, file)));\n\n const plugins = [reactPlugin(), modelenceAssetPlugin()];\n\n if (eslintConfigFile) {\n const eslintPlugin = (await import('vite-plugin-eslint')).default;\n plugins.push(\n eslintPlugin({\n failOnError: false,\n include: ['src/**/*.js', 'src/**/*.jsx', 'src/**/*.ts', 'src/**/*.tsx'],\n cwd: appDir,\n overrideConfigFile: path.resolve(appDir, eslintConfigFile)\n })\n );\n }\n\n return {\n plugins,\n root: appDir,\n build: {\n outDir: '.modelence/build/client',\n emptyOutDir: true\n },\n server: {\n proxy: {\n '/api': 'http://localhost:4000'\n },\n headers: {\n 'Cache-Control': 'no-store, no-cache, must-revalidate, proxy-revalidate, max-age=0',\n 'Pragma': 'no-cache',\n 'Expires': '0'\n },\n hmr: {\n port: 0,\n },\n },\n resolve: {\n alias: {\n '@': path.resolve(appDir, 'src')\n }\n },\n publicDir: userConfig.publicDir,\n };\n}\n\nfunction modelenceAssetPlugin() {\n return {\n name: 'modelence-asset-handler',\n async transform(code: string, id: string) {\n const assetRegex = /\\.(png|jpe?g|gif|svg|mpwebm|ogg|mp3|wav|flac|aac)$/;\n if (assetRegex.test(id)) {\n if (process.env.NODE_ENV === 'development') {\n return code;\n }\n // TODO: Upload to CDN\n // return `export default \"${cdnUrl}\"`;\n return code;\n }\n },\n async generateBundle(options: any, bundle: any) {\n // Handle asset URLs in the final bundle\n }\n };\n}\n\nexport const viteServer = new ViteServer();\n","import { getConfig } from \"@/server\";\nimport { Router, type Request, type Response } from \"express\";\nimport { ObjectId } from \"mongodb\";\nimport passport from \"passport\";\nimport { Strategy as GoogleStrategy } from \"passport-google-oauth20\";\nimport { usersCollection } from \"../db\";\nimport { createSession } from \"../session\";\n\ninterface GoogleUser {\n id: string;\n displayName: string;\n emails: { value: string; }[];\n photos: { value: string }[];\n}\n\nasync function authenticateUser(res: Response, userId: ObjectId) {\n const { authToken } = await createSession(userId);\n\n res.cookie(\"authToken\", authToken, {\n httpOnly: true,\n secure: process.env.NODE_ENV === \"production\",\n sameSite: \"strict\",\n });\n res.status(301);\n res.redirect(\"/\");\n}\n\n\nasync function handleGoogleAuthenticationCallback(req: Request, res: Response) {\n const googleUser = req.user as GoogleUser;\n\n const existingUser = await usersCollection.findOne(\n { 'authMethods.google.id': googleUser.id },\n );\n\n if (existingUser) {\n await authenticateUser(res, existingUser._id);\n \n return;\n }\n\n const googleEmail = googleUser.emails[0] && googleUser.emails[0]?.value;\n\n if (!googleEmail) {\n res.status(400).json({\n error: \"Email address is required for Google authentication.\",\n });\n }\n\n const existingUserByEmail = await usersCollection.findOne(\n { 'emails.address': googleEmail, },\n { collation: { locale: 'en', strength: 2 } },\n );\n\n // TODO: check if the email is verified\n if (existingUserByEmail) {\n // TODO: handle case with an HTML page\n res.status(400).json({\n error: \"User with this email already exists. Please log in instead.\",\n });\n return;\n }\n\n // If the user does not exist, create a new user\n const newUser = await usersCollection.insertOne({\n handle: googleEmail,\n emails: [{\n address: googleEmail,\n verified: true, // Google email is considered verified\n }],\n createdAt: new Date(),\n authMethods: {\n google: {\n id: googleUser.id,\n },\n },\n });\n\n await authenticateUser(res, newUser.insertedId);\n}\n\nfunction getRouter() {\n const googleAuthRouter = Router();\n const googleEnabled = Boolean(getConfig('_system.user.auth.google.enabled'));\n const googleClientId = String(getConfig('_system.user.auth.google.clientId'));\n const googleClientSecret = String(getConfig('_system.user.auth.google.clientSecret'));\n if (!googleEnabled || !googleClientId || !googleClientSecret) {\n return googleAuthRouter;\n }\n\n passport.use(new GoogleStrategy({\n clientID: googleClientId,\n clientSecret: googleClientSecret,\n callbackURL: '/api/_internal/auth/google/callback',\n proxy: true,\n }, (accessToken, refreshToken, profile, done) => {\n return done(null, profile);\n }));\n\n googleAuthRouter.get(\"/api/_internal/auth/google\", passport.authenticate(\"google\", {\n scope: [\"profile\", \"email\"],\n session: false,\n }));\n\n googleAuthRouter.get(\n \"/api/_internal/auth/google/callback\",\n passport.authenticate(\"google\", { session: false }),\n handleGoogleAuthenticationCallback,\n );\n\n return googleAuthRouter;\n}\n\nexport default getRouter;\n","import { Request, Response } from 'express';\nimport { RouteHandler, ExpressHandler } from './types';\nimport { ModelenceError } from '../error';\n\n// TODO: Use cookies for authentication and automatically add session/user to context if accessing from browser\n\nexport function createRouteHandler(handler: RouteHandler): ExpressHandler {\n return async (req: Request, res: Response) => {\n try {\n const response = await handler({\n query: req.query as Record<string, string>,\n body: req.body,\n params: req.params,\n headers: req.headers as Record<string, string>,\n cookies: req.cookies,\n req,\n });\n\n res.status(response.status || 200);\n\n if (response.redirect) {\n res.redirect(response.redirect);\n }\n\n if (response.headers) {\n Object.entries(response.headers).forEach(([key, value]) => {\n res.setHeader(key, value);\n });\n }\n\n res.send(response.data);\n } catch (error) {\n if (error instanceof ModelenceError) {\n res.status(error.status).send(error.message);\n } else {\n console.error(`Error in route handler: ${req.path}`);\n console.error(error);\n res.status(500).send(String(error));\n }\n }\n };\n}\n","import { ObjectId } from 'mongodb';\n\nimport { obtainSession } from './session';\nimport { usersCollection } from './db';\nimport { getDefaultAuthenticatedRoles, getUnauthenticatedRoles } from './role';\nimport { Role, Session, UserInfo } from './types';\n\nexport async function authenticate(authToken: string | null): Promise<{ session: Session, user: UserInfo | null, roles: Role[] }> {\n const session = await obtainSession(authToken);\n\n const userDoc = session.userId ? await usersCollection.findOne({ _id: new ObjectId(session.userId) }) : null;\n const user = userDoc ? {\n id: userDoc._id.toString(),\n handle: userDoc.handle,\n } : null;\n\n const roles = user ? getDefaultAuthenticatedRoles() : getUnauthenticatedRoles();\n\n return {\n user,\n session,\n roles,\n };\n}\n","import googleAuthRouter from '@/auth/providers/google';\nimport { runMethod } from '@/methods';\nimport { getResponseTypeMap } from '@/methods/serialize';\nimport { createRouteHandler } from '@/routes/handler';\nimport { HttpMethod } from '@/server';\nimport { logInfo } from '@/telemetry';\nimport cookieParser from 'cookie-parser';\nimport express, { Request, Response } from 'express';\nimport http from 'http';\nimport passport from 'passport';\nimport z from 'zod';\nimport { AppServer } from '../../../types';\nimport { authenticate } from '../auth';\nimport { getUnauthenticatedRoles } from '../auth/role';\nimport { getMongodbUri } from '../db/client';\nimport { ModelenceError } from '../error';\nimport { Module } from './module';\nimport { ConnectionInfo } from '@/methods/types';\n\nfunction registerModuleRoutes(app: express.Application, modules: Module[]) {\n for (const module of modules) {\n for (const route of module.routes) {\n const { path, handlers } = route;\n\n Object.entries(handlers).forEach(([method, handler]) => {\n app[method as HttpMethod](path, createRouteHandler(handler));\n });\n }\n }\n}\n\nexport async function startServer(server: AppServer, { combinedModules }: { combinedModules: Module[] }) {\n const app = express();\n\n app.use(express.json());\n app.use(express.urlencoded({ extended: true }));\n app.use(cookieParser());\n\n app.use(passport.initialize());\n\n app.use(googleAuthRouter());\n\n app.post('/api/_internal/method/:methodName(*)', async (req: Request, res: Response) => {\n const { methodName } = req.params;\n const context = await getCallContext(req);\n\n try {\n const result = await runMethod(methodName, req.body.args, context);\n res.json({\n data: result,\n typeMap: getResponseTypeMap(result),\n });\n } catch (error) {\n // TODO: introduce error codes and handle them differently\n // TODO: support multiple errors\n\n // TODO: add an option to silence these error console logs, especially when Elastic logs are configured\n console.error(`Error in method ${methodName}:`, error);\n\n if (error instanceof ModelenceError) {\n res.status(error.status).send(error.message);\n } else if (error instanceof Error && error?.constructor?.name === 'ZodError' && 'errors' in error) {\n const zodError = error as z.ZodError;\n const flattened = zodError.flatten();\n const fieldMessages = Object.entries(flattened.fieldErrors)\n .map(([key, errors]) => `${key}: ${(errors ?? []).join(', ')}`)\n .join('; ');\n const formMessages = flattened.formErrors.join('; ');\n const allMessages = [fieldMessages, formMessages].filter(Boolean).join('; ');\n res.status(400).send(allMessages);\n } else {\n res.status(500).send(error instanceof Error ? error.message : String(error));\n }\n }\n });\n\n registerModuleRoutes(app, combinedModules);\n\n await server.init();\n\n if (server.middlewares) {\n app.use(server.middlewares());\n }\n\n app.all('*', (req: Request, res: Response) => {\n return server.handler(req, res);\n });\n\n process.on('unhandledRejection', (reason, promise) => {\n console.error('Unhandled Promise Rejection:');\n console.error(reason instanceof Error ? reason.stack : reason);\n console.error('Promise:', promise);\n });\n \n // Global uncaught exceptions\n process.on('uncaughtException', (error) => {\n console.error('Uncaught Exception:');\n console.error(error.stack); // This gives you the full stack trace\n console.trace('Full application stack:'); // Additional context\n });\n\n const httpServer = http.createServer(app);\n const port = process.env.PORT || 3000;\n httpServer.listen(port, () => {\n logInfo(`Application started`, { source: 'app' });\n console.log(`\\nApplication started on http://localhost:${port}\\n`);\n });\n}\n\nasync function getCallContext(req: Request) {\n const authToken = z.string().nullish().transform(val => val ?? null).parse(req.cookies.authToken || req.body.authToken);\n\n const clientInfo = z.object({\n screenWidth: z.number(),\n screenHeight: z.number(),\n windowWidth: z.number(),\n windowHeight: z.number(),\n pixelRatio: z.number(),\n orientation: z.string().nullable(),\n }).parse(req.body.clientInfo);\n\n const connectionInfo: ConnectionInfo = {\n ip: getClientIp(req),\n userAgent: req.get('user-agent'),\n acceptLanguage: req.get('accept-language'),\n referrer: req.get('referrer'),\n baseUrl: req.protocol + '://' + req.get('host'),\n };\n\n const hasDatabase = Boolean(getMongodbUri());\n if (hasDatabase) {\n const { session, user, roles } = await authenticate(authToken);\n return {\n clientInfo,\n connectionInfo,\n session,\n user,\n roles,\n };\n }\n\n return {\n clientInfo,\n connectionInfo,\n session: null,\n user: null,\n roles: getUnauthenticatedRoles(),\n };\n}\n\nfunction getClientIp(req: Request): string | undefined {\n // On Heroku and other proxies, X-Forwarded-For contains the real client IP\n const forwardedFor = req.headers['x-forwarded-for'];\n if (forwardedFor) {\n const firstIp = Array.isArray(forwardedFor) ? forwardedFor[0] : forwardedFor.split(',')[0];\n return firstIp.trim();\n }\n\n const directIp = req.ip || req.socket?.remoteAddress;\n if (directIp) {\n // Remove IPv6-to-IPv4 mapping prefix\n return directIp.startsWith('::ffff:') ? directIp.substring(7) : directIp;\n }\n \n return undefined;\n}\n","import dotenv from 'dotenv';\nimport fs from 'fs/promises';\nimport os from 'os';\nimport path from 'path';\n\nimport { AppServer, EmailProvider } from '@modelence/types';\nimport { initRoles } from '../auth/role';\nimport sessionModule from '../auth/session';\nimport { RoleDefinition } from '../auth/types';\nimport userModule from '../auth/user';\nimport { loadConfigs, setSchema } from '../config/server';\nimport { startConfigSync } from '../config/sync';\nimport { AppConfig, ConfigSchema, ConfigType } from '../config/types';\nimport cronModule, { defineCronJob, getCronJobsMetadata, startCronJobs } from '../cron/jobs';\nimport { Store } from '../data/store';\nimport { connect, getClient, getMongodbUri } from '../db/client';\nimport { _createSystemMutation, _createSystemQuery, createMutation, createQuery } from '../methods';\nimport { MigrationScript, default as migrationModule, runMigrations } from '../migration';\nimport rateLimitModule from '../rate-limit';\nimport { initRateLimits } from '../rate-limit/rules';\nimport { viteServer } from '../viteServer';\nimport { connectCloudBackend } from './backendApi';\nimport { initMetrics } from './metrics';\nimport { Module } from './module';\nimport { startServer } from './server';\nimport { markAppStarted, setMetadata } from './state';\nimport { EmailConfig, setEmailConfig } from './emailConfig';\n\nexport type AppOptions = {\n modules?: Module[],\n server?: AppServer,\n email?: EmailConfig,\n roles?: Record<string, RoleDefinition>,\n defaultRoles?: Record<string, string>,\n migrations?: Array<MigrationScript>\n}\n\nexport async function startApp(\n { modules = [], roles = {}, defaultRoles = {}, server = viteServer, migrations = [], email = {} }: AppOptions\n) {\n dotenv.config();\n \n dotenv.config({ path: '.modelence.env' });\n\n const hasRemoteBackend = Boolean(process.env.MODELENCE_SERVICE_ENDPOINT);\n const isCronEnabled = process.env.MODELENCE_CRON_ENABLED === 'true';\n\n trackAppStart().then(() => {\n // Do nothing\n }).catch(() => {\n // Silently ignore tracking errors to not disrupt app startup\n });\n\n // TODO: verify that user modules don't start with `_system.` prefix\n const systemModules = [userModule, sessionModule, cronModule, migrationModule, rateLimitModule];\n const combinedModules = [...systemModules, ...modules];\n\n markAppStarted();\n\n initSystemMethods(systemModules);\n initCustomMethods(modules);\n\n initRoles(roles, defaultRoles);\n\n const configSchema = getConfigSchema(combinedModules);\n setSchema(configSchema);\n const stores = getStores(combinedModules);\n\n if (isCronEnabled) {\n defineCronJobs(combinedModules);\n }\n\n const rateLimits = getRateLimits(combinedModules);\n initRateLimits(rateLimits);\n\n if (hasRemoteBackend) {\n const { configs, environmentId, appAlias, environmentAlias, telemetry } = await connectCloudBackend({\n configSchema,\n cronJobsMetadata: isCronEnabled ? getCronJobsMetadata() : undefined,\n stores\n });\n loadConfigs(configs);\n setMetadata({ environmentId, appAlias, environmentAlias, telemetry });\n } else {\n loadConfigs(getLocalConfigs(configSchema));\n }\n\n setEmailConfig(email);\n\n const mongodbUri = getMongodbUri();\n if (mongodbUri) {\n await connect();\n initStores(stores);\n }\n\n if (isCronEnabled) {\n await runMigrations(migrations);\n }\n\n if (mongodbUri) {\n for (const store of stores) {\n store.createIndexes();\n }\n }\n\n if (hasRemoteBackend) {\n await initMetrics();\n startConfigSync();\n }\n\n if (isCronEnabled) {\n startCronJobs().catch(console.error);\n }\n\n await startServer(server, { combinedModules });\n}\n\nfunction initCustomMethods(modules: Module[]) {\n for (const module of modules) {\n for (const [key, handler] of Object.entries(module.queries)) {\n createQuery(`${module.name}.${key}`, handler);\n }\n for (const [key, handler] of Object.entries(module.mutations)) {\n createMutation(`${module.name}.${key}`, handler);\n }\n }\n}\n\nfunction initSystemMethods(modules: Module[]) {\n for (const module of modules) {\n for (const [key, handler] of Object.entries(module.queries)) {\n _createSystemQuery(`${module.name}.${key}`, handler);\n }\n for (const [key, handler] of Object.entries(module.mutations)) {\n _createSystemMutation(`${module.name}.${key}`, handler);\n }\n }\n}\n\nfunction getStores(modules: Module[]) {\n return modules.flatMap(module => module.stores);\n}\n\nfunction getRateLimits(modules: Module[]) {\n return modules.flatMap(module => module.rateLimits);\n}\n\nfunction getConfigSchema(modules: Module[]): ConfigSchema {\n const merged: ConfigSchema = {};\n\n for (const module of modules) {\n for (const [key, value] of Object.entries(module.configSchema)) {\n const absoluteKey = `${module.name}.${key}`;\n if (absoluteKey in merged) {\n throw new Error(\n `Duplicate config schema key: ${absoluteKey} (${module.name})`\n );\n }\n\n merged[absoluteKey] = value;\n }\n }\n\n return merged;\n}\n\nfunction defineCronJobs(modules: Module[]) {\n for (const module of modules) {\n for (const [cronAlias, cronJobParams] of Object.entries(module.cronJobs)) {\n defineCronJob(`${module.name}.${cronAlias}`, cronJobParams);\n }\n }\n}\n\nfunction initStores(stores: Store<any, any>[]) {\n const client = getClient();\n if (!client) {\n throw new Error('Failed to initialize stores: MongoDB client not initialized');\n }\n\n for (const store of stores) {\n store.init(client);\n }\n}\n\nconst localConfigMap = {\n MONGODB_URI: '_system.mongodbUri',\n MODELENCE_AUTH_GOOGLE_ENABLED: '_system.user.auth.google.enabled',\n MODELENCE_AUTH_GOOGLE_CLIENT_ID: '_system.user.auth.google.clientId',\n MODELENCE_AUTH_GOOGLE_CLIENT_SECRET: '_system.user.auth.google.clientSecret',\n MODELENCE_EMAIL_RESEND_API_KEY: '_system.email.resend.apiKey',\n MODELENCE_EMAIL_AWS_SES_REGION: '_system.email.awsSes.region',\n MODELENCE_EMAIL_AWS_SES_ACCESS_KEY_ID: '_system.email.awsSes.accessKeyId',\n MODELENCE_EMAIL_AWS_SES_SECRET_ACCESS_KEY: '_system.email.awsSes.secretAccessKey',\n MODELENCE_EMAIL_SMTP_HOST: '_system.email.smtp.host',\n MODELENCE_EMAIL_SMTP_PORT: '_system.email.smtp.port',\n MODELENCE_EMAIL_SMTP_USER: '_system.email.smtp.user',\n MODELENCE_EMAIL_SMTP_PASS: '_system.email.smtp.pass',\n // deprecated\n GOOGLE_AUTH_ENABLED: '_system.user.auth.google.enabled',\n GOOGLE_AUTH_CLIENT_ID: '_system.user.auth.google.clientId',\n GOOGLE_AUTH_CLIENT_SECRET: '_system.user.auth.google.clientSecret',\n};\n\nfunction formatLocalConfigValue(value: string, type: ConfigType): string | number | boolean {\n if (type === 'number') {\n const numValue = Number(value);\n if (isNaN(numValue)) {\n throw new Error(`Invalid number value for config: ${value}`);\n }\n return numValue;\n }\n if (type === 'boolean') {\n if (value.toLowerCase() === 'true') {\n return true;\n }\n if (value.toLowerCase() === 'false') {\n return false;\n }\n throw new Error(`Invalid boolean value for config: ${value}`);\n }\n return value;\n}\n\nfunction getLocalConfigs(configSchema: ConfigSchema): AppConfig[] {\n const configs: AppConfig[] = [];\n\n for (const [envVar, configKey] of Object.entries(localConfigMap)) {\n const value = process.env[envVar];\n const configSchemaEntry = configSchema[configKey];\n if (value) {\n const type = configSchemaEntry?.type ?? 'string';\n configs.push({\n key: configKey,\n type: type,\n value: formatLocalConfigValue(value, type),\n });\n }\n }\n\n return configs;\n}\n\nasync function trackAppStart() {\n const isTrackingEnabled = process.env.MODELENCE_TRACKING_ENABLED !== 'false';\n\n if (isTrackingEnabled) {\n const serviceEndpoint = process.env.MODELENCE_SERVICE_ENDPOINT ?? 'https://cloud.modelence.com';\n const environmentId = process.env.MODELENCE_ENVIRONMENT_ID;\n \n const appDetails = await getAppDetails();\n const modelencePackageJson = await import('../../package.json');\n \n await fetch(`${serviceEndpoint}/api/track/app-start`, {\n method: 'POST',\n headers: {\n 'Content-Type': 'application/json'\n },\n body: JSON.stringify({\n projectName: appDetails.name,\n version: modelencePackageJson.default.version,\n localHostname: os.hostname(),\n environmentId\n })\n });\n }\n}\n\nasync function getAppDetails() {\n try {\n const packageJsonPath = path.join(process.cwd(), 'package.json');\n const packageJsonContent = await fs.readFile(packageJsonPath, 'utf-8');\n const packageJson = JSON.parse(packageJsonContent);\n \n return {\n name: packageJson.name || 'unknown'\n };\n } catch (error) {\n return {\n name: 'unknown'\n };\n }\n}\n"]}
|
|
1
|
+
{"version":3,"sources":["../src/auth/role.ts","../src/app/module.ts","../src/data/store.ts","../src/data/types.ts","../src/auth/session.ts","../src/auth/db.ts","../src/auth/disposableEmails.ts","../src/app/emailConfig.ts","../src/utils/index.ts","../src/auth/templates/emailVerficationTemplate.ts","../src/auth/verification.ts","../src/auth/login.ts","../src/auth/profile.ts","../src/rate-limit/db.ts","../src/rate-limit/rules.ts","../src/auth/signup.ts","../src/auth/resetPassword.ts","../src/auth/user.ts","../src/app/backendApi.ts","../src/config/sync.ts","../src/cron/jobs.ts","../src/db/client.ts","../src/methods/index.ts","../src/migration/db.ts","../src/migration/index.ts","../src/rate-limit/index.ts","../src/viteServer.ts","../src/auth/providers/google.ts","../src/routes/handler.ts","../src/auth/index.ts","../src/app/server.ts","../src/app/index.ts"],"names":["roleMap","defaultRoles","initRoles","roles","_defaultRoles","name","definition","getUnauthenticatedRoles","getDefaultAuthenticatedRoles","requireAccess","requiredPermissions","missingPermission","permission","hasPermission","role","Module","stores","queries","mutations","routes","cronJobs","configSchema","rateLimits","Store","options","client","document","selector","ObjectId","query","errorHandler","result","cursor","id","idSelector","documents","update","pipeline","operations","oldName","db","schemaString","z","schemaNumber","schemaDate","schemaBoolean","schemaArray","schemaObject","schemaEnum","schema","collection","sessionsCollection","obtainSession","authToken","existingSession","createSession","setSessionUser","userId","clearSessionUser","randomBytes","now","expiresAt","time","processSessionHeartbeat","session","newExpiresAt","session_default","args","user","getPublicConfigs","usersCollection","dbDisposableEmailDomains","emailVerificationTokensCollection","resetPasswordTokensCollection","isDisposableEmail","email","emailParts","domain","updateDisposableEmailListCron","response","domains","batchSize","i","batch","error","emailConfig","setEmailConfig","newEmailConfig","getEmailConfig","isServer","requireServer","htmlToText","html","emailVerificationTemplate","verificationUrl","handleVerifyEmail","params","baseUrl","emailVerifiedRedirectUrl","token","tokenDoc","sendVerificationEmail","emailProvider","verificationToken","htmlTemplate","textContent","handleLoginWithPassword","connectionInfo","ip","consumeRateLimit","password","userDoc","passwordHash","incorrectCredentialsError","e","bcrypt","handleLogout","getOwnProfile","_args","profile","dbRateLimits","allRules","initRateLimits","bucket","type","value","rules","rule","checkRateLimitRule","createError","createRateLimitError","RateLimitError","record","currentWindowStart","count","modifier","getCount","prevWindowStart","currentWindowCount","prevWindowCount","prevWindowWeight","weight","handleSignupWithPassword","existingUser","existingEmail","hash","defaultPasswordResetTemplate","resetUrl","handleSendResetPasswordToken","resetToken","handleResetPassword","resetTokenDoc","user_default","connectCloudBackend","cronJobsMetadata","containerId","dataModels","store","data","callApi","os","fetchConfigs","syncStatus","endpoint","method","payload","MODELENCE_SERVICE_ENDPOINT","MODELENCE_SERVICE_TOKEN","json","isSyncing","SYNC_INTERVAL","startConfigSync","syncConfig","configs","loadConfigs","DEFAULT_TIMEOUT","LOCK_TRANSFER_DELAY","cronJobsInterval","cronJobsCollection","defineCronJob","alias","description","interval","timeout","handler","startCronJobs","aliasList","aliasSelector","existingLockedRecord","sleep","cronJobRecords","job","tickCronJobs","ms","resolve","state","startCronJob","transaction","startTransaction","handleCronJobCompletion","err","captureError","getCronJobsMetadata","jobs_default","connect","mongodbUri","getMongodbUri","MongoClient","getConfig","getClient","methods","createQuery","methodDef","validateMethodName","_createMethodInternal","createMutation","_createSystemQuery","validateSystemMethodName","_createSystemMutation","permissions","runMethod","context","dbMigrations","runMigrations","migrations","versions","version","existingVersions","existingVersionSet","pendingMigrations","migration_default","rate_limit_default","ViteServer","createServer","defineConfig","staticFolders","express","req","res","loadUserViteConfig","appDir","loadConfigFromFile","userConfig","eslintConfigFile","file","fs","path","plugins","reactPlugin","modelenceAssetPlugin","eslintPlugin","code","bundle","viteServer","authenticateUser","handleGoogleAuthenticationCallback","googleUser","googleEmail","newUser","getRouter","googleAuthRouter","Router","googleEnabled","googleClientId","googleClientSecret","passport","GoogleStrategy","accessToken","refreshToken","done","google_default","createRouteHandler","key","ModelenceError","authenticate","registerModuleRoutes","app","modules","module","route","handlers","startServer","server","combinedModules","cookieParser","methodName","getCallContext","getResponseTypeMap","flattened","fieldMessages","errors","formMessages","allMessages","reason","promise","httpServer","http","port","logInfo","val","clientInfo","getClientIp","forwardedFor","directIp","startApp","dotenv","hasRemoteBackend","isCronEnabled","trackAppStart","systemModules","markAppStarted","initSystemMethods","initCustomMethods","getConfigSchema","setSchema","getStores","defineCronJobs","getRateLimits","environmentId","appAlias","environmentAlias","telemetry","setMetadata","getLocalConfigs","initStores","initMetrics","merged","absoluteKey","cronAlias","cronJobParams","localConfigMap","formatLocalConfigValue","numValue","envVar","configKey","configSchemaEntry","serviceEndpoint","appDetails","getAppDetails","modelencePackageJson","packageJsonPath","packageJsonContent"],"mappings":"6yBAEA,IAAMA,EAAAA,CAAU,IAAI,IACdC,CAAAA,CAA6B,CACjC,cAAe,IAAA,CACf,eAAA,CAAiB,IACnB,CAAA,CAEO,SAASC,EAAAA,CAAUC,CAAAA,CAAqCC,EAAqC,CAClGH,CAAAA,CAAa,cAAgBG,CAAAA,CAAc,aAAA,CAC3CH,EAAa,eAAA,CAAkBG,CAAAA,CAAc,gBAE7C,I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9C,CACrB,IAAM4B,EAAkB,OAAA,CAAQ,GAAA,CAAI,0BAAA,EAA8B,6BAAA,CAC5DlB,CAAAA,CAAgB,OAAA,CAAQ,IAAI,wBAAA,CAE5BmB,CAAAA,CAAa,MAAMC,EAAAA,EAAc,CACjCC,CAAAA,CAAuB,MAAM,OAAO,uBAAoB,CAAA,CAE9D,MAAM,KAAA,CAAM,CAAA,EAAGH,CAAe,CAAA,oBAAA,CAAA,CAAwB,CACpD,MAAA,CAAQ,MAAA,CACR,OAAA,CAAS,CACP,eAAgB,kBAClB,CAAA,CACA,IAAA,CAAM,IAAA,CAAK,SAAA,CAAU,CACnB,YAAaC,CAAAA,CAAW,IAAA,CACxB,OAAA,CAASE,CAAAA,CAAqB,OAAA,CAAQ,OAAA,CACtC,cAAenL,EAAAA,CAAG,QAAA,EAAS,CAC3B,aAAA,CAAA8J,CACF,CAAC,CACH,CAAC,EACH,CACF,CAEA,eAAeoB,EAAAA,EAAgB,CAC7B,GAAI,CACF,IAAME,CAAAA,CAAkB9F,EAAAA,CAAK,IAAA,CAAK,QAAQ,GAAA,EAAI,CAAG,cAAc,CAAA,CACzD+F,CAAAA,CAAqB,MAAMhG,GAAG,QAAA,CAAS+F,CAAAA,CAAiB,OAAO,CAAA,CAGrE,OAAO,CACL,KAHkB,IAAA,CAAK,KAAA,CAAMC,CAAkB,CAAA,CAG7B,IAAA,EAAQ,SAC5B,CACF,CAAA,KAAgB,CACd,OAAO,CACL,IAAA,CAAM,SACR,CACF,CACF","file":"server.js","sourcesContent":["import { RoleDefinition, Role, DefaultRoles, Permission } from './types';\n\nconst roleMap = new Map<Role, RoleDefinition>();\nconst defaultRoles: DefaultRoles = {\n authenticated: null,\n unauthenticated: null,\n};\n\nexport function initRoles(roles: Record<Role, RoleDefinition>, _defaultRoles: Record<string, Role>) {\n defaultRoles.authenticated = _defaultRoles.authenticated;\n defaultRoles.unauthenticated = _defaultRoles.unauthenticated;\n\n for (const [name, definition] of Object.entries(roles)) {\n roleMap.set(name, definition);\n }\n}\n\nexport function getUnauthenticatedRoles() {\n return defaultRoles.unauthenticated ? [defaultRoles.unauthenticated] : [];\n}\n\nexport function getDefaultAuthenticatedRoles() {\n return defaultRoles.authenticated ? [defaultRoles.authenticated] : [];\n}\n\nexport function hasAccess(roles: Role[], requiredPermissions: Permission[]) {\n return requiredPermissions.every(permission => hasPermission(roles, permission));\n}\n\nexport function requireAccess(roles: Role[], requiredPermissions: Permission[]) {\n const missingPermission = requiredPermissions.find(permission => !hasPermission(roles, permission));\n\n if (missingPermission) {\n throw new Error(`Access denied - missing permission: '${missingPermission}'`);\n }\n}\n\nexport function hasPermission(roles: Role[], permission: Permission) {\n for (const role of roles) {\n const definition = roleMap.get(role);\n\n if (definition && definition.permissions.includes(permission)) {\n return true;\n }\n }\n\n return false;\n}\n","import { ConfigSchema } from '../config/types';\nimport { CronJobInputParams } from '../cron/types';\nimport { Store } from '../data/store';\nimport { MethodDefinition } from '../methods/types';\nimport { RouteDefinition } from '../routes/types';\nimport { RateLimitRule } from '../rate-limit/types';\n\n/** Array of Store instances that will be provisioned when the module is loaded */\ntype Stores = Store<any, any>[];\n\n/** Record of query methods that can be called from the client */\ntype Queries = Record<string, MethodDefinition<any>>;\n\n/** Record of mutation methods that can be called from the client */\ntype Mutations = Record<string, MethodDefinition<any>>;\n\n/**\n * The Module class is a core building block of a Modelence application that encapsulates related functionality.\n * Modules can contain stores, queries, mutations, routes, cron jobs and configurations.\n * \n * @category Module\n * \n * @example\n * ```ts\n * const todoModule = new Module('todo', {\n * stores: [dbTodos],\n * queries: {\n * async getAll() {\n * // Fetch and return all Todo items\n * }\n * },\n * mutations: {\n * async create({ title }, { user }) {\n * // Create a new Todo item\n * }\n * }\n * });\n * ```\n */\nexport class Module {\n /** @internal */\n public readonly name: string;\n\n /** @internal */\n public readonly stores: Stores;\n\n /** @internal */\n public readonly queries: Queries;\n\n /** @internal */\n public readonly mutations: Mutations;\n\n /** @internal */\n public readonly routes: RouteDefinition[];\n\n /** @internal */\n public readonly cronJobs: Record<string, CronJobInputParams>;\n\n /** @internal */\n public readonly configSchema: ConfigSchema;\n\n /** @internal */\n public readonly rateLimits: RateLimitRule[];\n\n /**\n * Creates a new Module instance\n * \n * @param name - The unique name of the module.\n * This name is used to namespace queries, mutations,\n * cron jobs and configuration values with a prefix (e.g. \"todo.create\")\n * \n * @param options - Module configuration options\n */\n constructor(\n name: string,\n { \n stores = [], \n queries = {}, \n mutations = {},\n routes = [],\n cronJobs = {},\n configSchema = {},\n rateLimits = []\n }: { \n stores?: Store<any, any>[],\n queries?: Queries,\n mutations?: Mutations,\n routes?: RouteDefinition[],\n cronJobs?: Record<string, CronJobInputParams>,\n configSchema?: ConfigSchema,\n rateLimits?: RateLimitRule[]\n }\n ) {\n this.name = name;\n this.stores = stores;\n this.queries = queries;\n this.mutations = mutations;\n this.routes = routes;\n this.cronJobs = cronJobs;\n this.configSchema = configSchema;\n this.rateLimits = rateLimits;\n }\n}\n","import {\n AggregateOptions,\n AggregationCursor,\n Collection,\n DeleteResult,\n Document,\n IndexDescription,\n InsertOneResult,\n MongoClient,\n UpdateResult,\n Filter,\n WithId,\n OptionalUnlessRequiredId,\n FindOptions,\n UpdateFilter,\n ObjectId,\n BulkWriteResult,\n AnyBulkWriteOperation,\n InsertManyResult,\n Db,\n ClientSession,\n} from 'mongodb';\n\nimport { ModelSchema, InferDocumentType } from './types';\n\n/**\n * The Store class provides a type-safe interface for MongoDB collections with built-in schema validation and helper methods.\n * \n * @category Store\n * @typeParam TSchema - The document schema type\n * @typeParam TMethods - Custom methods that will be added to documents\n * \n * @example\n * ```ts\n * const dbTodos = new Store('todos', {\n * schema: {\n * title: schema.string(),\n * completed: schema.boolean(),\n * dueDate: schema.date().optional(),\n * userId: schema.userId(),\n * },\n * methods: {\n * isOverdue() {\n * return this.dueDate < new Date();\n * }\n * }\n * });\n * ```\n */\nexport class Store<\n TSchema extends ModelSchema,\n TMethods extends Record<string, (this: WithId<InferDocumentType<TSchema>> & TMethods, ...args: Parameters<any>) => any>\n> {\n /** @internal */\n readonly _type!: InferDocumentType<TSchema>;\n /** @internal */\n readonly _rawDoc!: WithId<this['_type']>;\n /** @internal */\n readonly _doc!: this['_rawDoc'] & TMethods;\n \n readonly Doc!: this['_doc'];\n\n private name: string;\n private readonly schema: TSchema;\n private readonly methods?: TMethods;\n private readonly indexes: IndexDescription[];\n private collection?: Collection<this['_type']>;\n private client?: MongoClient;\n\n /**\n * Creates a new Store instance\n * \n * @param name - The collection name in MongoDB\n * @param options - Store configuration\n */\n constructor(\n name: string,\n options: {\n /** Document schema using Modelence schema types */\n schema: TSchema;\n /** Custom methods to add to documents */\n methods?: TMethods;\n /** MongoDB indexes to create */\n indexes: IndexDescription[];\n }\n ) {\n this.name = name;\n this.schema = options.schema;\n this.methods = options.methods;\n this.indexes = options.indexes;\n }\n\n getName() {\n return this.name;\n }\n\n /** @internal */\n getSchema() {\n return this.schema;\n }\n\n /** @internal */\n init(client: MongoClient) {\n if (this.collection) {\n throw new Error(`Collection ${this.name} is already initialized`);\n }\n\n this.client = client;\n this.collection = this.client.db().collection<this['_type']>(this.name);\n }\n\n /** @internal */\n async createIndexes() {\n if (this.indexes.length > 0) {\n await this.requireCollection().createIndexes(this.indexes);\n }\n }\n\n private wrapDocument(document: this['_rawDoc']): this['_doc'] {\n if (!this.methods) {\n return document as unknown as this['_doc'];\n }\n\n const result = Object.create(\n null,\n Object.getOwnPropertyDescriptors({\n ...document,\n ...this.methods\n })\n );\n\n return result as this['_doc'];\n }\n\n /**\n * For convenience, to also allow directy passing a string or ObjectId as the selector\n */\n private getSelector(selector: Filter<this['_type']> | string | ObjectId) {\n if (typeof selector === 'string') {\n return { _id: new ObjectId(selector) } as Filter<this['_type']>;\n }\n\n if (selector instanceof ObjectId) {\n return { _id: selector } as Filter<this['_type']>;\n }\n\n return selector;\n }\n\n /** @internal */\n requireCollection() {\n if (!this.collection) {\n throw new Error(`Collection ${this.name} is not provisioned`);\n }\n\n return this.collection;\n }\n\n /** @internal */\n requireClient() {\n if (!this.client) {\n throw new Error(`Database is not connected`);\n }\n\n return this.client;\n }\n\n async findOne(\n query: Filter<this['_type']>, \n options?: FindOptions\n ) {\n const document = await this.requireCollection().findOne<this['_rawDoc']>(query, options);\n return document ? this.wrapDocument(document) : null;\n }\n\n async requireOne(\n query: Filter<this['_type']>, \n options?: FindOptions,\n errorHandler?: () => Error\n ): Promise<this['_doc']> {\n \n const result = await this.findOne(query, options);\n if (!result) {\n throw errorHandler ? errorHandler() : new Error(`Record not found in ${this.name}`);\n }\n return result;\n }\n\n private find(query: Filter<this['_type']>, options?: { sort?: Document, limit?: number, skip?: number }) {\n const cursor = this.requireCollection().find(query);\n if (options?.sort) {\n cursor.sort(options.sort);\n }\n if (options?.limit) {\n cursor.limit(options.limit);\n }\n if (options?.skip) {\n cursor.skip(options.skip);\n }\n return cursor;\n }\n\n /**\n * Fetches a single document by its ID\n * \n * @param id - The ID of the document to find\n * @returns The document, or null if not found\n */\n async findById(id: string | ObjectId): Promise<this['_doc'] | null> {\n const idSelector = typeof id === 'string' ? { _id: new ObjectId(id) } : { _id: id };\n return await this.findOne(idSelector as Filter<this['_type']>);\n }\n\n /**\n * Fetches a single document by its ID, or throws an error if not found\n * \n * @param id - The ID of the document to find\n * @param errorHandler - Optional error handler to return a custom error if the document is not found\n * @returns The document\n */\n async requireById(id: string | ObjectId, errorHandler?: () => Error): Promise<this['_doc']> {\n const result = await this.findById(id);\n if (!result) {\n throw errorHandler ? errorHandler() : new Error(`Record with id ${id} not found in ${this.name}`);\n }\n return result;\n }\n\n /**\n * Counts the number of documents that match a query\n * \n * @param query - The query to filter documents\n * @returns The number of documents that match the query\n */\n countDocuments(query: Filter<this['_type']>): Promise<number> {\n return this.requireCollection().countDocuments(query);\n }\n\n /**\n * Fetches multiple documents, equivalent to Node.js MongoDB driver's `find` and `toArray` methods combined.\n * \n * @param query - The query to filter documents\n * @param options - Options\n * @returns The documents\n */\n async fetch(query: Filter<this['_type']>, options?: { sort?: Document, limit?: number, skip?: number }): Promise<this['_doc'][]> {\n const cursor = this.find(query, options)\n return (await cursor.toArray()).map(this.wrapDocument.bind(this));\n }\n\n /**\n * Inserts a single document\n * \n * @param document - The document to insert\n * @returns The result of the insert operation\n */\n async insertOne(document: OptionalUnlessRequiredId<this['_type']>): Promise<InsertOneResult> {\n return await this.requireCollection().insertOne(document);\n }\n\n /**\n * Inserts multiple documents\n * \n * @param documents - The documents to insert\n * @returns The result of the insert operation\n */\n async insertMany(documents: OptionalUnlessRequiredId<this['_type']>[]): Promise<InsertManyResult> {\n return await this.requireCollection().insertMany(documents);\n }\n\n /**\n * Updates a single document\n * \n * @param selector - The selector to find the document to update\n * @param update - The update to apply to the document\n * @returns The result of the update operation\n */\n async updateOne(selector: Filter<this['_type']> | string | ObjectId, update: UpdateFilter<this['_type']>): Promise<UpdateResult> {\n return await this.requireCollection().updateOne(this.getSelector(selector), update);\n }\n\n /**\n * Updates a single document, or inserts it if it doesn't exist\n * \n * @param selector - The selector to find the document to update\n * @param update - The MongoDB modifier to apply to the document\n * @returns The result of the update operation\n */\n async upsertOne(selector: Filter<this['_type']> | string | ObjectId, update: UpdateFilter<this['_type']>): Promise<UpdateResult> {\n return await this.requireCollection().updateOne(this.getSelector(selector), update, { upsert: true });\n }\n\n /**\n * Updates multiple documents\n * \n * @param selector - The selector to find the documents to update\n * @param update - The MongoDB modifier to apply to the documents\n * @returns The result of the update operation\n */\n async updateMany(\n selector: Filter<this['_type']>, \n update: UpdateFilter<this['_type']>, \n options?: { session?: ClientSession }\n ): Promise<UpdateResult> {\n return await this.requireCollection().updateMany(selector, update, options);\n }\n\n /**\n * Updates multiple documents, or inserts them if they don't exist\n * \n * @param selector - The selector to find the documents to update\n * @param update - The MongoDB modifier to apply to the documents\n * @returns The result of the update operation\n */\n async upsertMany(selector: Filter<this['_type']>, update: UpdateFilter<this['_type']>): Promise<UpdateResult> {\n return await this.requireCollection().updateMany(selector, update, { upsert: true });\n }\n\n /**\n * Deletes a single document\n * \n * @param selector - The selector to find the document to delete\n * @returns The result of the delete operation\n */\n async deleteOne(selector: Filter<this['_type']>): Promise<DeleteResult> {\n return await this.requireCollection().deleteOne(selector);\n }\n\n /**\n * Deletes multiple documents\n * \n * @param selector - The selector to find the documents to delete\n * @returns The result of the delete operation\n */\n async deleteMany(selector: Filter<this['_type']>): Promise<DeleteResult> {\n return await this.requireCollection().deleteMany(selector);\n }\n\n /**\n * Aggregates documents using MongoDB's aggregation framework\n * \n * @param pipeline - The aggregation pipeline\n * @param options - Optional options\n * @returns The aggregation cursor\n */\n aggregate(pipeline: Document[], options?: AggregateOptions): AggregationCursor<Document> {\n return this.requireCollection().aggregate(pipeline, options);\n }\n\n /**\n * Performs a bulk write operation on the collection\n * \n * @param operations - The operations to perform\n * @returns The result of the bulk write operation\n */\n bulkWrite(operations: AnyBulkWriteOperation<this['_type']>[]): Promise<BulkWriteResult> {\n return this.requireCollection().bulkWrite(operations);\n }\n\n /**\n * Returns the raw MongoDB database instance for advanced operations\n * @returns The MongoDB database instance\n * @throws Error if the store is not provisioned\n */\n getDatabase() {\n return this.requireClient().db();\n }\n\n /**\n * Returns the raw MongoDB collection instance for advanced operations\n * @returns The MongoDB collection instance\n * @throws Error if the store is not provisioned\n */\n rawCollection() {\n return this.requireCollection();\n }\n\n /**\n * Renames an existing collection to this store's name, used for migrations\n * @param oldName - The previous name of the collection\n * @throws Error if the old collection doesn't exist or if this store's collection already exists\n */\n async renameFrom(oldName: string, options?: { session?: ClientSession }) {\n const db = this.getDatabase();\n\n if (!this.collection || !db) {\n throw new Error(`Store ${this.name} is not provisioned`);\n }\n\n const oldCollections = await db.listCollections({ name: oldName }).toArray();\n if (oldCollections.length === 0) {\n throw new Error(`Collection ${oldName} not found`);\n }\n\n const newCollections = await db.listCollections({ name: this.name }).toArray();\n if (newCollections.length > 0) {\n throw new Error(`Collection ${this.name} already exists`);\n }\n\n const existingCollection = db.collection<this['_type']>(oldName);\n\n await existingCollection.rename(this.name, options);\n }\n}\n","import { ObjectId } from 'mongodb';\nimport { z } from 'zod';\nimport { Store } from './store';\n\ntype ObjectTypeDefinition = {\n [key: string]: SchemaTypeDefinition;\n};\n\ntype SingularSchemaTypeDefinition = z.ZodType | ObjectTypeDefinition; // ReturnType<typeof schema[keyof typeof schema]>;\n\ntype SchemaTypeDefinition = SingularSchemaTypeDefinition | Array<SingularSchemaTypeDefinition>;\n\nexport type ModelSchema = {\n [key: string]: SchemaTypeDefinition;\n};\n\nconst schemaString: typeof z.string = z.string.bind(z);\n\nconst schemaNumber: typeof z.number = z.number.bind(z);\n\nconst schemaDate: typeof z.date = z.date.bind(z);\n\nconst schemaBoolean: typeof z.boolean = z.boolean.bind(z);\n\nconst schemaArray: typeof z.array = z.array.bind(z);\n\nconst schemaObject: typeof z.object = z.object.bind(z);\n\nconst schemaEnum: typeof z.enum = z.enum.bind(z);\n\nexport const schema = {\n string: schemaString,\n number: schemaNumber,\n date: schemaDate,\n boolean: schemaBoolean,\n array: schemaArray,\n object: schemaObject,\n enum: schemaEnum,\n objectId(): z.ZodType<ObjectId> {\n return z.instanceof(ObjectId);\n },\n userId(): z.ZodType<ObjectId> {\n return z.instanceof(ObjectId);\n },\n ref(collection: string | Store<any, any>): z.ZodType<ObjectId> {\n return z.instanceof(ObjectId);\n },\n union: z.union.bind(z),\n infer<T extends SchemaTypeDefinition>(schema: T): InferDocumentType<T> {\n return {} as InferDocumentType<T>;\n }\n} as const;\n\nexport type InferDocumentType<T extends SchemaTypeDefinition> = {\n [K in keyof T as T[K] extends z.ZodOptional<any> ? K : never]?: (T[K] extends z.ZodType ? z.infer<T[K]> : never);\n} & {\n [K in keyof T as T[K] extends z.ZodOptional<any> ? never : K]:\n T[K] extends z.ZodType ? z.infer<T[K]> :\n T[K] extends Array<infer ElementType extends SchemaTypeDefinition> ? Array<InferDocumentType<ElementType>> :\n T[K] extends ObjectTypeDefinition ? InferDocumentType<T[K]> :\n never;\n};\n\nexport namespace schema {\n export type infer<T extends SchemaTypeDefinition> = InferDocumentType<T>;\n}\n","import { randomBytes } from 'crypto';\nimport { ObjectId } from 'mongodb';\nimport { Module } from '../app/module';\nimport { getPublicConfigs } from '../config/server';\nimport { Store } from '../data/store';\nimport { schema } from '../data/types';\nimport { time } from '../time';\nimport { Session } from './types';\n\nexport const sessionsCollection = new Store('_modelenceSessions', {\n schema: {\n authToken: schema.string(),\n createdAt: schema.date(),\n expiresAt: schema.date(),\n userId: schema.userId().nullable(),\n },\n indexes: [\n { key: { authToken: 1 }, unique: true },\n { key: { expiresAt: 1 }},\n ]\n // TODO: add TTL index on expiresAt\n});\n\nexport async function obtainSession(authToken: string | null): Promise<Session> {\n const existingSession = authToken ? await sessionsCollection.findOne({ authToken }) : null;\n\n if (existingSession) {\n return {\n authToken: String(existingSession.authToken),\n expiresAt: new Date(existingSession.expiresAt),\n userId: existingSession.userId ?? null,\n }\n }\n\n return await createSession();\n}\n\nexport async function setSessionUser(authToken: string, userId: ObjectId) {\n await sessionsCollection.updateOne({ authToken }, {\n $set: { userId }\n });\n}\n\nexport async function clearSessionUser(authToken: string) {\n await sessionsCollection.updateOne({ authToken }, {\n $set: { userId: null }\n });\n}\n\nexport async function createSession(userId: ObjectId | null = null): Promise<Session> {\n // TODO: add rate-limiting and captcha handling\n\n const authToken = randomBytes(32).toString('base64url');\n const now = Date.now();\n const expiresAt = new Date(now + time.days(7));\n\n await sessionsCollection.insertOne({\n authToken,\n createdAt: new Date(now),\n expiresAt,\n userId,\n });\n\n return {\n authToken,\n expiresAt,\n userId,\n };\n}\n\nasync function processSessionHeartbeat(session: Session) {\n const now = Date.now();\n const newExpiresAt = new Date(now + time.days(7));\n\n await sessionsCollection.updateOne({ authToken: session.authToken }, {\n $set: {\n lastActiveDate: new Date(now),\n expiresAt: newExpiresAt\n }\n });\n}\n\nexport default new Module('_system.session', {\n stores: [sessionsCollection],\n mutations: {\n init: async function(args, { session, user }) {\n // TODO: mark or track app load somewhere\n \n return {\n session,\n user,\n configs: getPublicConfigs(),\n };\n },\n heartbeat: async function(args, { session }) {\n // Session might not exist if there is no database/authentication setup\n if (session) {\n await processSessionHeartbeat(session);\n }\n }\n },\n});\n","import { schema } from '../data/types';\nimport { Store } from '../data/store';\n\n/**\n * Database collection for storing user accounts with authentication methods and profile information.\n * \n * This is where **signupWithPassword** automatically creates new users.\n * \n * @example\n * ```typescript\n * // Find user by email\n * const user = await dbUsers.findOne(\n * { 'emails.address': 'john@example.com' }\n * );\n * ```\n * \n */\nexport const usersCollection = new Store('_modelenceUsers', {\n schema: {\n handle: schema.string(),\n emails: schema.array(schema.object({\n address: schema.string(),\n verified: schema.boolean(),\n })).optional(),\n createdAt: schema.date(),\n authMethods: schema.object({\n password: schema.object({\n hash: schema.string(),\n }).optional(),\n google: schema.object({\n id: schema.string(),\n }).optional(),\n }),\n },\n indexes: [\n {\n key: { handle: 1 },\n unique: true,\n collation: { locale: 'en', strength: 2 } // Case-insensitive\n },\n ]\n});\n\nexport const dbDisposableEmailDomains = new Store('_modelenceDisposableEmailDomains', {\n schema: {\n domain: schema.string(),\n addedAt: schema.date(),\n },\n indexes: [\n {\n key: { domain: 1 },\n unique: true\n }\n ]\n});\n\nexport const emailVerificationTokensCollection = new Store('_modelenceEmailVerificationTokens', {\n schema: {\n userId: schema.objectId(),\n email: schema.string().optional(),\n token: schema.string(),\n createdAt: schema.date(),\n expiresAt: schema.date(),\n },\n indexes: [\n {\n key: { token: 1 },\n unique: true\n },\n {\n key: { expiresAt: 1 },\n expireAfterSeconds: 0\n }\n ]\n});\n\nexport const resetPasswordTokensCollection = new Store('_modelenceResetPasswordTokens', {\n schema: {\n userId: schema.objectId(),\n token: schema.string(),\n createdAt: schema.date(),\n expiresAt: schema.date(),\n },\n indexes: [\n {\n key: { token: 1 },\n unique: true\n },\n {\n key: { expiresAt: 1 },\n expireAfterSeconds: 0\n }\n ]\n});\n","import { time } from '../time';\nimport { dbDisposableEmailDomains } from './db';\n\nexport async function isDisposableEmail(email: string): Promise<boolean> {\n const emailParts = email.toLowerCase().trim().split('@');\n if (emailParts.length !== 2) {\n return false;\n }\n \n const domain = emailParts[1];\n const result = await dbDisposableEmailDomains.findOne({ domain });\n return Boolean(result);\n}\n\nexport const updateDisposableEmailListCron = {\n interval: time.days(1),\n async handler() {\n const response = await fetch('https://disposable.github.io/disposable-email-domains/domains.txt');\n \n if (!response.ok) {\n throw new Error(`HTTP ${response.status}: ${response.statusText}`);\n }\n \n const domainsText = await response.text();\n \n const domains = domainsText\n .split('\\n')\n .map(domain => domain.trim().toLowerCase())\n .filter(domain => domain.length > 0);\n \n const now = new Date();\n \n // Insert domains in batches to avoid overwhelming the database\n const batchSize = 500;\n for (let i = 0; i < domains.length; i += batchSize) {\n const batch = domains.slice(i, i + batchSize);\n \n try {\n await dbDisposableEmailDomains.insertMany(\n batch.map(domain => ({\n domain,\n addedAt: now,\n }))\n );\n } catch (error: any) {\n // MongoDB throws BulkWriteError when some documents are duplicates\n if (error.name === 'MongoBulkWriteError' && error.result?.nInserted) {\n // console.warn(`Error inserting batch starting at index ${i}:`, error.message);\n }\n }\n }\n }\n}\n","import { EmailProvider } from \"@modelence/types\";\n\nexport type EmailConfig = {\n provider?: EmailProvider;\n from?: string;\n verification?: {\n subject?: string;\n template?: (props: {\n name: string;\n email: string;\n verificationUrl: string;\n }) => string;\n redirectUrl?: string;\n };\n passwordReset?: {\n subject?: string;\n template?: (props: {\n name: string;\n email: string;\n resetUrl: string;\n }) => string;\n redirectUrl?: string;\n };\n // @deprecated use verification.redirectUrl instead\n emailVerifiedRedirectUrl?: string;\n};\n\nlet emailConfig: EmailConfig = Object.freeze({});\n\nexport function setEmailConfig(newEmailConfig: EmailConfig) {\n emailConfig = Object.freeze(Object.assign({}, emailConfig, newEmailConfig));\n}\n\nexport function getEmailConfig() {\n return emailConfig;\n}\n","export function isServer() {\n return typeof window !== 'object';\n}\n\nexport function requireServer() {\n if (!isServer()) {\n throw new Error('This function can only be called on the server');\n }\n}\n\nexport function htmlToText(html: string) {\n return html.replace(/<[^>]*>/g, '').replace(/\\s+/g, ' ').trim()\n}\n","export function emailVerificationTemplate({ name, email, verificationUrl }: { name?: string; email: string; verificationUrl: string }) {\n return `\n <p>Hi${name ? ` ${name}` : ''},</p>\n <p>Please verify your email address ${email} by clicking the link below:</p>\n <p><a href=\"${verificationUrl}\">${verificationUrl}</a></p>\n <p>If you did not request this, please ignore this email.</p>\n `;\n}\n","import { z } from 'zod';\n\nimport { usersCollection, emailVerificationTokensCollection } from './db';\nimport { ObjectId, RouteParams, RouteResponse } from '@/server';\nimport { getEmailConfig } from '@/app/emailConfig';\nimport { randomBytes } from 'crypto';\nimport { time } from '@/time';\nimport { htmlToText } from '@/utils';\nimport { emailVerificationTemplate } from './templates/emailVerficationTemplate';\n\nexport async function handleVerifyEmail(params: RouteParams): Promise<RouteResponse> {\n const baseUrl = process.env.MODELENCE_SITE_URL;\n const emailVerifiedRedirectUrl = getEmailConfig().emailVerifiedRedirectUrl || baseUrl || '/';\n try {\n const token = z.string().parse(params.query.token);\n // Find token in database\n const tokenDoc = await emailVerificationTokensCollection.findOne({\n token,\n expiresAt: { $gt: new Date() }\n });\n\n if (!tokenDoc) {\n throw new Error('Invalid or expired verification token');\n }\n\n // Find user by token's userId\n const userDoc = await usersCollection.findOne({ _id: tokenDoc.userId });\n\n if (!userDoc) {\n throw new Error('User not found');\n }\n\n const email = tokenDoc.email;\n\n if (!email) {\n throw new Error('Email not found in token');\n }\n\n // Mark the specific email as verified atomically\n const updateResult = await usersCollection.updateOne(\n { \n _id: tokenDoc.userId,\n 'emails.address': email,\n 'emails.verified': { $ne: true }\n },\n { $set: { 'emails.$.verified': true } }\n );\n\n if (updateResult.matchedCount === 0) {\n // Check if email exists but is already verified\n const existingUser = await usersCollection.findOne({\n _id: tokenDoc.userId,\n 'emails.address': email\n });\n \n if (existingUser) {\n throw new Error('Email is already verified');\n } else {\n throw new Error('Email address not found for this user');\n }\n }\n\n // Delete the used token\n await emailVerificationTokensCollection.deleteOne({ _id: tokenDoc._id });\n } catch (error) {\n if (error instanceof Error) {\n console.error('Error verifying email:', error);\n return {\n status: 301,\n redirect: `${emailVerifiedRedirectUrl}?status=error&message=${encodeURIComponent(error.message)}`,\n };\n }\n }\n\n return {\n status: 301,\n redirect: `${emailVerifiedRedirectUrl}?status=verified`,\n };\n}\n\nexport async function sendVerificationEmail({\n userId,\n email,\n baseUrl = process.env.MODELENCE_SITE_URL\n}: {\n userId: ObjectId;\n email: string;\n baseUrl?: string;\n}) {\n if (getEmailConfig().provider) {\n const emailProvider = getEmailConfig().provider;\n\n // Generate verification token\n const verificationToken = randomBytes(32).toString('hex');\n const expiresAt = new Date(Date.now() + time.hours(24));\n\n // Store token in database\n await emailVerificationTokensCollection.insertOne({\n userId,\n email,\n token: verificationToken,\n createdAt: new Date(),\n expiresAt,\n });\n \n const verificationUrl = `${baseUrl}/api/_internal/auth/verify-email?token=${verificationToken}`;\n \n const template = getEmailConfig()?.verification?.template || emailVerificationTemplate;\n // TODO: we should have also the name on this step\n const htmlTemplate = template({ name: '', email, verificationUrl });\n const textContent = htmlToText(htmlTemplate);\n \n await emailProvider?.sendEmail({\n to: email,\n from: getEmailConfig()?.from || 'noreply@modelence.com',\n subject: getEmailConfig()?.verification?.subject || 'Verify your email address',\n text: textContent,\n html: htmlTemplate,\n });\n }\n}\n","import bcrypt from 'bcrypt';\nimport { z } from 'zod';\n\nimport { Args, Context } from '../methods/types';\nimport { usersCollection } from './db';\nimport { clearSessionUser, setSessionUser } from './session';\nimport { sendVerificationEmail } from './verification';\nimport { getEmailConfig } from '@/app/emailConfig';\nimport { consumeRateLimit } from '@/server';\n\nexport async function handleLoginWithPassword(args: Args, { user, session, connectionInfo }: Context) {\n if (!session) {\n throw new Error('Session is not initialized');\n }\n\n const ip = connectionInfo?.ip;\n if (ip) {\n await consumeRateLimit({\n bucket: 'signin',\n type: 'ip',\n value: ip,\n });\n }\n\n const email = z.string().email().parse(args.email);\n const password = z.string().parse(args.password);\n\n // TODO: add rate limiting by email (and perhaps IP address overall)\n\n if (user) {\n // TODO: handle cases where a user is already logged in\n }\n\n const userDoc = await usersCollection.findOne(\n { 'emails.address': email },\n { collation: { locale: 'en', strength: 2 } }\n );\n\n const passwordHash = userDoc?.authMethods?.password?.hash;\n if (!passwordHash) {\n throw incorrectCredentialsError();\n }\n\n const emailDoc = userDoc.emails?.find(e => e.address === email);\n\n if (!emailDoc?.verified && getEmailConfig()?.provider) {\n if (ip) {\n try {\n await consumeRateLimit({\n bucket: 'verification',\n type: 'user',\n value: userDoc._id.toString(),\n });\n } catch {\n throw new Error(\"Your email address hasn't been verified yet. Please use the verification email we've send earlier to your inbox.\");\n }\n }\n\n await sendVerificationEmail({\n userId: userDoc?._id,\n email,\n baseUrl: connectionInfo?.baseUrl,\n });\n throw new Error(\"Your email address hasn't been verified yet. We've sent a new verification email to your inbox.\");\n }\n\n const isValidPassword = await bcrypt.compare(password, passwordHash);\n if (!isValidPassword) {\n throw incorrectCredentialsError();\n }\n\n await setSessionUser(session.authToken, userDoc._id);\n\n return {\n user: {\n id: userDoc._id,\n handle: userDoc.handle,\n }\n }\n}\n\nexport async function handleLogout(args: Args, { user, session }: Context) {\n if (!session) {\n throw new Error('Session is not initialized');\n }\n\n await clearSessionUser(session.authToken);\n}\n\n/*\n It is important to return the same exact error both in case the email\n or password is incorrect so that the client cannot tell the difference,\n otherwise it would allow for an enumeration attack.\n*/\nfunction incorrectCredentialsError() {\n return new Error('Incorrect email/password combination');\n}\n","import { usersCollection } from './db';\nimport { Args, Context } from '../methods/types';\n\nexport async function getOwnProfile(_args: Args, { user }: Context) {\n if (!user) {\n throw new Error('Not authenticated');\n }\n\n const profile = await usersCollection.requireById(user.id);\n\n return {\n handle: profile.handle,\n emails: profile.emails,\n authMethods: Object.keys(profile.authMethods || {}),\n };\n}\n","import { Store } from '../data/store';\nimport { schema } from '../data/types';\n\n/**\n * Two-bucket sliding window approximation to track rate limits.\n * This is a trade-off between storage and accuracy.\n * We're not keeping exact event logs, so we can't track the exact number of events in a window.\n * Instead, we're adding a weighted average from the previous window to the current window.\n */\nexport const dbRateLimits = new Store('_modelenceRateLimits', {\n schema: {\n bucket: schema.string(),\n type: schema.enum(['ip', 'user']),\n value: schema.string(),\n windowMs: schema.number(),\n\n windowStart: schema.date(),\n windowCount: schema.number(),\n prevWindowCount: schema.number(),\n\n expiresAt: schema.date(),\n },\n indexes: [\n { key: { bucket: 1, type: 1, value: 1, windowMs: 1 }, unique: true },\n { key: { expiresAt: 1 }, expireAfterSeconds: 0 },\n ]\n});\n","import { RateLimitRule, RateLimitType } from './types';\nimport { dbRateLimits } from './db';\nimport { RateLimitError } from '../error';\n\nlet allRules: Array<RateLimitRule> = [];\n\nexport function initRateLimits(rateLimits: RateLimitRule[]) {\n if (allRules.length > 0) {\n throw new Error('Duplicate call to initRateLimits - already initialized');\n }\n\n allRules = rateLimits;\n}\n\n/**\n * This function will check all rate limit rules on the specified bucket and type,\n * throw an error if any of them are exceeded and increase the count of the rate limit record.\n * \n * @category Rate Limits\n * \n * @example\n * ```ts\n * await consumeRateLimit({ bucket: 'api', type: 'ip', value: '127.0.0.1' });\n * ```\n * @param options.bucket - The bucket for the rate limit.\n * @param options.type - The type of the rate limit.\n * @param options.value - The value for the rate limit.\n */\nexport async function consumeRateLimit(\n options: { bucket: string, type: RateLimitType, value: string }\n) {\n const { bucket, type, value } = options;\n const rules = allRules.filter(rule => rule.bucket === bucket && rule.type === type);\n\n for (const rule of rules) {\n await checkRateLimitRule(rule, value);\n }\n}\n\n// Two-bucket sliding window approximation to track rate limits.\nasync function checkRateLimitRule(rule: RateLimitRule, value: string, createError?: () => Error) {\n const createRateLimitError = () => {\n return createError ? createError() : new RateLimitError(`Rate limit exceeded for ${rule.bucket}`);\n };\n\n const record = await dbRateLimits.findOne({\n bucket: rule.bucket,\n type: rule.type,\n value,\n windowMs: rule.window,\n });\n\n const now = Date.now();\n const currentWindowStart = Math.floor(now / rule.window) * rule.window;\n\n const { count, modifier } = record\n ? getCount(record, currentWindowStart, now)\n : {\n count: 0,\n modifier: {\n $setOnInsert: {\n windowStart: new Date(currentWindowStart),\n windowCount: 1,\n prevWindowCount: 0,\n expiresAt: new Date(currentWindowStart + rule.window + rule.window),\n }\n }\n };\n\n if (count >= rule.limit) {\n throw createRateLimitError();\n }\n\n /*\n Always use upsert, because there is a small chance the document might be auto-removed\n based on the expiration TTL index in between the check and the update\n */\n await dbRateLimits.upsertOne(\n { bucket: rule.bucket, type: rule.type, value, windowMs: rule.window }, \n modifier\n );\n}\n\nfunction getCount(record: typeof dbRateLimits['Doc'], currentWindowStart: number, now: number) {\n const prevWindowStart = currentWindowStart - record.windowMs;\n \n if (record.windowStart.getTime() === currentWindowStart) {\n const currentWindowCount = record.windowCount;\n const prevWindowCount = record.prevWindowCount;\n const prevWindowWeight = 1 - (now - currentWindowStart) / record.windowMs;\n return {\n count: Math.round(currentWindowCount + prevWindowCount * prevWindowWeight),\n modifier: {\n $inc: { windowCount: 1 },\n $setOnInsert: {\n windowStart: new Date(currentWindowStart),\n prevWindowCount: 0,\n expiresAt: new Date(currentWindowStart + record.windowMs + record.windowMs),\n }\n }\n };\n }\n \n if (record.windowStart.getTime() === prevWindowStart) {\n const weight = 1 - (now - currentWindowStart) / record.windowMs;\n return {\n count: Math.round(record.windowCount * weight),\n modifier: {\n $set: {\n windowStart: new Date(currentWindowStart),\n windowCount: 1,\n prevWindowCount: record.windowCount,\n expiresAt: new Date(currentWindowStart + record.windowMs + record.windowMs),\n }\n }\n };\n }\n \n return {\n count: 0,\n modifier: {\n $set: {\n windowStart: new Date(currentWindowStart),\n windowCount: 1,\n prevWindowCount: 0,\n expiresAt: new Date(currentWindowStart + record.windowMs + record.windowMs),\n }\n }\n };\n}\n","import { z } from 'zod';\nimport bcrypt from 'bcrypt';\n\nimport { Args, Context } from '../methods/types';\nimport { usersCollection } from './db';\nimport { isDisposableEmail } from './disposableEmails';\nimport { consumeRateLimit } from '../rate-limit/rules';\nimport { sendVerificationEmail } from './verification';\n\nexport async function handleSignupWithPassword(args: Args, { user, connectionInfo }: Context) {\n const email = z.string().email().parse(args.email);\n const password = z.string()\n .min(8, { message: 'Password must contain at least 8 characters' })\n .parse(args.password);\n\n const ip = connectionInfo?.ip;\n if (ip) {\n await consumeRateLimit({\n bucket: 'signupAttempt',\n type: 'ip',\n value: ip,\n });\n }\n\n if (await isDisposableEmail(email)) {\n throw new Error('Please use a permanent email address');\n }\n\n // TODO: captcha check\n\n if (user) {\n // TODO: handle cases where a user is already logged in\n }\n\n const existingUser = await usersCollection.findOne(\n { 'emails.address': email },\n { collation: { locale: 'en', strength: 2 } }\n );\n\n if (existingUser) {\n const existingEmail = existingUser.emails?.find(e => e.address === email);\n throw new Error(`User with email already exists: ${existingEmail?.address}`);\n }\n\n if (ip) {\n await consumeRateLimit({\n bucket: 'signup',\n type: 'ip',\n value: ip,\n });\n }\n\n // Hash password with bcrypt (salt is automatically generated)\n const hash = await bcrypt.hash(password, 10);\n\n const result = await usersCollection.insertOne({\n handle: email,\n emails: [{\n address: email,\n verified: false,\n }],\n createdAt: new Date(),\n authMethods: {\n password: {\n hash,\n }\n }\n });\n\n await sendVerificationEmail({\n userId: result?.insertedId,\n email,\n baseUrl: connectionInfo?.baseUrl,\n });\n \n\n return result.insertedId;\n}\n","import { z } from 'zod';\nimport bcrypt from 'bcrypt';\nimport { randomBytes } from 'crypto';\n\nimport { Args, Context } from '@/methods/types';\nimport { usersCollection, resetPasswordTokensCollection } from './db';\nimport { getEmailConfig } from '@/app/emailConfig';\nimport { time } from '@/time';\nimport { htmlToText } from '@/utils';\n\nfunction defaultPasswordResetTemplate({ email, resetUrl }: { email: string; resetUrl: string }) {\n return `\n <p>Hi,</p>\n <p>We received a request to reset your password for ${email}.</p>\n <p>Click the link below to reset your password:</p>\n <p><a href=\"${resetUrl}\">${resetUrl}</a></p>\n <p>This link will expire in 1 hour.</p>\n <p>If you did not request this password reset, please ignore this email.</p>\n `;\n}\n\nexport async function handleSendResetPasswordToken(args: Args, { connectionInfo }: Context) {\n const email = z.string().email().parse(args.email);\n\n // Find user by email\n const userDoc = await usersCollection.findOne(\n { 'emails.address': email },\n { collation: { locale: 'en', strength: 2 } }\n );\n\n if (!userDoc) {\n // For security, don't reveal if email exists or not\n return { success: true, message: 'If an account with that email exists, a password reset link has been sent' };\n }\n\n // Check if user has password auth method\n if (!userDoc.authMethods?.password) {\n return { success: true, message: 'If an account with that email exists, a password reset link has been sent' };\n }\n\n const emailProvider = getEmailConfig().provider;\n if (!emailProvider) {\n throw new Error('Email provider is not configured');\n }\n\n // Generate reset token\n const resetToken = randomBytes(32).toString('hex');\n const expiresAt = new Date(Date.now() + time.hours(1)); // 1 hour expiry\n\n // Store reset token\n await resetPasswordTokensCollection.insertOne({\n userId: userDoc._id,\n token: resetToken,\n createdAt: new Date(),\n expiresAt,\n });\n\n // Build reset URL\n const baseUrl = process.env.MODELENCE_SITE_URL || connectionInfo?.baseUrl;\n const verificationUrl = getEmailConfig().passwordReset?.redirectUrl || baseUrl;\n const resetUrl = `${verificationUrl}?token=${resetToken}`;\n\n // Send email\n const template = getEmailConfig()?.passwordReset?.template || defaultPasswordResetTemplate;\n const htmlTemplate = template({ email, resetUrl, name: '' });\n const textContent = htmlToText(htmlTemplate);\n\n await emailProvider.sendEmail({\n to: email,\n from: getEmailConfig()?.from || 'noreply@modelence.com',\n subject: getEmailConfig()?.passwordReset?.subject || 'Reset your password',\n text: textContent,\n html: htmlTemplate,\n });\n\n return { success: true, message: 'If an account with that email exists, a password reset link has been sent' };\n}\n\nexport async function handleResetPassword(args: Args, { }: Context) {\n const token = z.string().parse(args.token);\n const password = z.string()\n .min(8, { message: 'Password must contain at least 8 characters' })\n .parse(args.password);\n\n // Find the reset token\n const resetTokenDoc = await resetPasswordTokensCollection.findOne({ token });\n if (!resetTokenDoc) {\n throw new Error('Invalid or expired reset token');\n }\n\n // Check if token is expired\n if (resetTokenDoc.expiresAt < new Date()) {\n await resetPasswordTokensCollection.deleteOne({ token });\n throw new Error('Reset token has expired');\n }\n\n // Find the user\n const userDoc = await usersCollection.findOne({ _id: resetTokenDoc.userId });\n if (!userDoc) {\n throw new Error('User not found');\n }\n\n // Hash the new password\n const hash = await bcrypt.hash(password, 10);\n\n // Update user's password\n await usersCollection.updateOne(\n { _id: userDoc._id },\n {\n $set: {\n 'authMethods.password.hash': hash\n }\n }\n );\n\n // Delete the used reset token\n await resetPasswordTokensCollection.deleteOne({ token });\n\n return { success: true, message: 'Password has been reset successfully' };\n}\n","import { randomBytes } from 'crypto';\n\nimport { Module } from '../app/module';\nimport { time } from '../time';\nimport {\n dbDisposableEmailDomains,\n emailVerificationTokensCollection,\n resetPasswordTokensCollection,\n usersCollection\n} from './db';\nimport { updateDisposableEmailListCron } from './disposableEmails';\nimport { handleLoginWithPassword, handleLogout } from './login';\nimport { getOwnProfile } from './profile';\nimport { handleSignupWithPassword } from './signup';\nimport { handleVerifyEmail } from './verification';\nimport { handleResetPassword, handleSendResetPasswordToken } from './resetPassword';\n\nasync function createGuestUser() {\n // TODO: add rate-limiting and captcha handling\n\n const guestId = randomBytes(9)\n .toString('base64')\n .replace(/[+/]/g, c => c === '+' ? 'a' : 'b');\n\n const handle = `guest_${guestId}`;\n // TODO: re-try on handle collision\n\n const result = await usersCollection.insertOne({\n handle,\n createdAt: new Date(),\n authMethods: {},\n });\n\n return result.insertedId;\n}\n\nexport default new Module('_system.user', {\n stores: [\n usersCollection,\n dbDisposableEmailDomains,\n emailVerificationTokensCollection,\n resetPasswordTokensCollection,\n ],\n queries: {\n getOwnProfile,\n },\n mutations: {\n signupWithPassword: handleSignupWithPassword,\n loginWithPassword: handleLoginWithPassword,\n logout: handleLogout,\n sendResetPasswordToken: handleSendResetPasswordToken,\n resetPassword: handleResetPassword,\n },\n cronJobs: {\n updateDisposableEmailList: updateDisposableEmailListCron\n },\n rateLimits: [{\n bucket: 'signup',\n type: 'ip',\n window: time.minutes(15),\n limit: 20,\n }, {\n bucket: 'signup',\n type: 'ip',\n window: time.days(1),\n limit: 200,\n }, {\n bucket: 'signupAttempt',\n type: 'ip',\n window: time.minutes(15),\n limit: 50,\n }, {\n bucket: 'signupAttempt',\n type: 'ip',\n window: time.days(1),\n limit: 500,\n }, {\n bucket: 'signin',\n type: 'ip',\n window: time.minutes(15),\n limit: 50,\n }, {\n bucket: 'signin',\n type: 'ip',\n window: time.days(1),\n limit: 500,\n }, {\n bucket: 'verification',\n type: 'user',\n window: time.minutes(15),\n limit: 3,\n }, {\n bucket: 'verification',\n type: 'user',\n window: time.days(1),\n limit: 10,\n }],\n configSchema: {\n 'auth.email.enabled': {\n type: 'boolean',\n isPublic: true,\n default: true,\n },\n 'auth.email.from': {\n type: 'string',\n isPublic: false,\n default: '',\n },\n 'auth.email.verification': {\n type: 'boolean',\n isPublic: true,\n default: false,\n },\n 'auth.google.enabled': {\n type: 'boolean',\n isPublic: true,\n default: false,\n },\n 'auth.google.clientId': {\n type: 'string',\n isPublic: false,\n default: '',\n },\n 'auth.google.clientSecret': {\n type: 'secret',\n isPublic: false,\n default: '',\n },\n },\n routes: [\n {\n path: '/api/_internal/auth/verify-email',\n handlers: {\n get: handleVerifyEmail\n },\n }\n ],\n});\n","import os from 'os';\nimport { ConfigSchema } from '../config/types';\nimport { CronJobMetadata } from '../cron/types';\nimport { Store } from '../data/store';\nimport { AppConfig } from '../config/types';\n\ntype CloudBackendConnectOkResponse = {\n status: 'ok';\n configs: AppConfig[];\n environmentId: string;\n appAlias: string;\n environmentAlias: string;\n telemetry: {\n isEnabled: boolean;\n serviceName: string;\n };\n};\n\ntype CloudBackendConnectErrorResponse = {\n status: 'error';\n error: string;\n}\n\nexport type CloudBackendConnectResponse = CloudBackendConnectOkResponse | CloudBackendConnectErrorResponse;\n\nexport async function connectCloudBackend(\n { configSchema, cronJobsMetadata, stores }: { \n configSchema?: ConfigSchema, \n cronJobsMetadata?: CronJobMetadata[], \n stores: Store<any, any>[] \n }\n): Promise<CloudBackendConnectOkResponse> {\n const containerId = process.env.MODELENCE_CONTAINER_ID;\n if (!containerId) {\n throw new Error('Unable to connect to Modelence Cloud: MODELENCE_CONTAINER_ID is not set');\n }\n\n try {\n const dataModels = Object.values(stores).map(store => {\n return {\n name: store.getName(),\n schema: store.getSchema(),\n collections: [store.getName()]\n };\n });\n\n const data = await callApi('/api/connect', 'POST', {\n hostname: os.hostname(),\n containerId,\n dataModels,\n configSchema,\n cronJobsMetadata,\n });\n\n if (data.status === 'error') {\n throw new Error(data.error);\n }\n\n console.log('Successfully connected to Modelence Cloud');\n\n return data;\n } catch (error) {\n console.error('Unable to connect to Modelence Cloud:', error);\n throw error;\n }\n}\n\nexport async function fetchConfigs() {\n const data = await callApi('/api/configs', 'GET');\n return data;\n}\n\nexport async function syncStatus() {\n const data = await callApi('/api/sync', 'POST', {\n containerId: process.env.MODELENCE_CONTAINER_ID\n });\n return data;\n}\n\nasync function callApi(endpoint: string, method: string, payload?: object) {\n const { MODELENCE_SERVICE_ENDPOINT, MODELENCE_SERVICE_TOKEN } = process.env;\n\n if (!MODELENCE_SERVICE_ENDPOINT) {\n throw new Error('Unable to connect to Modelence Cloud: MODELENCE_SERVICE_ENDPOINT is not set');\n }\n\n const response = await fetch(`${MODELENCE_SERVICE_ENDPOINT}${endpoint}`, {\n method,\n headers: {\n 'Authorization': `Bearer ${MODELENCE_SERVICE_TOKEN}`,\n ...(payload ? { 'Content-Type': 'application/json' } : {})\n },\n body: payload ? JSON.stringify(payload) : undefined\n });\n\n if (!response.ok) {\n const data = await response.text();\n try {\n const json = JSON.parse(data);\n throw new Error(`Unable to connect to Modelence Cloud: HTTP status: ${response.status}, ${json?.error}`);\n } catch (error) {\n throw new Error(`Unable to connect to Modelence Cloud: HTTP status: ${response.status}, ${data}`);\n }\n }\n\n return await response.json();\n}\n","import { time } from '../time';\nimport { fetchConfigs, syncStatus } from '../app/backendApi';\nimport { loadConfigs } from './server';\n\nlet isSyncing = false;\n\nconst SYNC_INTERVAL = time.seconds(10);\n\nexport function startConfigSync() {\n setInterval(async() => {\n if (isSyncing) {\n return;\n }\n \n isSyncing = true;\n\n // TODO: move this sync outside of config\n try {\n await syncStatus();\n } catch (error) {\n console.error('Error syncing status', error);\n }\n \n try {\n await syncConfig();\n } catch (error) {\n console.error('Error syncing config', error);\n }\n \n isSyncing = false; \n }, SYNC_INTERVAL);\n}\n\nasync function syncConfig() {\n const { configs } = await fetchConfigs();\n loadConfigs(configs);\n}\n","// import { Worker, isMainThread, parentPort, workerData } from 'worker_threads';\n\nimport { time } from '../time';\nimport { CronJob, CronJobInputParams } from './types';\nimport { startTransaction, captureError } from '@/telemetry';\nimport { Module } from '../app/module';\nimport { schema } from '../data/types';\nimport { Store } from '../data/store';\n\nconst DEFAULT_TIMEOUT = time.minutes(1);\n\n/**\n * Each cron instance acquires locks for the jobs it runs. If there was a pre-existing lock,\n * the lock is transferred to the new instance, but there is a delay to give the previous instance\n * a chance to see the new lock and gracefully finish remaining jobs.\n */\nconst LOCK_TRANSFER_DELAY = time.seconds(10);\n\nconst cronJobs: Record<string, CronJob> = {};\nlet cronJobsInterval: NodeJS.Timeout;\n\nconst cronJobsCollection = new Store('_modelenceCronJobs', {\n schema: {\n alias: schema.string(),\n lastStartDate: schema.date().optional(),\n lock: schema.object({\n containerId: schema.string(),\n acquireDate: schema.date(),\n }).optional(),\n },\n indexes: [\n { key: { alias: 1 }, unique: true, background: true },\n ]\n});\n\n// TODO: allow changing interval and timeout with cron jobconfigs\nexport function defineCronJob(\n alias: CronJob['alias'],\n { description = '', interval, timeout = DEFAULT_TIMEOUT, handler }: CronJobInputParams,\n) {\n if (cronJobs[alias]) {\n throw new Error(`Duplicate cron job declaration: '${alias}' already exists`);\n }\n\n if (cronJobsInterval) {\n throw new Error(`Unable to add a cron job - cron jobs have already been initialized: [${alias}]`);\n }\n\n if (interval < time.seconds(5)) {\n throw new Error(`Cron job interval should not be less than 5 second [${alias}]`);\n }\n\n if (timeout > time.days(1)) {\n throw new Error(`Cron job timeout should not be longer than 1 day [${alias}]`);\n }\n\n cronJobs[alias] = {\n alias,\n params: { description, interval, timeout },\n handler,\n state: {\n isRunning: false,\n }\n };\n}\n\nexport async function startCronJobs() {\n if (cronJobsInterval) {\n throw new Error('Cron jobs already started');\n }\n\n const aliasList = Object.keys(cronJobs);\n if (aliasList.length > 0) {\n const aliasSelector = { alias: { $in: aliasList } };\n\n const existingLockedRecord = await cronJobsCollection.findOne({\n ...aliasSelector,\n 'lock.containerId': { $exists: true }\n });\n\n // TODO: handle different application versions with different parameters for the same job alias\n\n await Promise.all(aliasList.map(alias => \n cronJobsCollection.upsertOne(\n { alias },\n {\n $set: {\n lock: {\n containerId: process.env.MODELENCE_CONTAINER_ID || 'unknown',\n acquireDate: new Date(),\n }\n }\n }\n )\n ));\n\n if (existingLockedRecord) {\n await sleep(LOCK_TRANSFER_DELAY);\n }\n\n const cronJobRecords = await cronJobsCollection.fetch(aliasSelector);\n const now = Date.now();\n cronJobRecords.forEach((record) => {\n const job = cronJobs[record.alias];\n if (!job) {\n return;\n }\n job.state.scheduledRunTs = record.lastStartDate ? record.lastStartDate.getTime() + job.params.interval : now;\n });\n Object.values(cronJobs).forEach((job) => {\n if (!job.state.scheduledRunTs) {\n job.state.scheduledRunTs = now;\n }\n });\n\n cronJobsInterval = setInterval(tickCronJobs, time.seconds(1));\n }\n}\n\nfunction sleep(ms: number) {\n return new Promise((resolve) => setTimeout(resolve, ms));\n}\n\nasync function tickCronJobs() {\n // TODO: periodically check if the locks are still there\n\n const now = Date.now();\n Object.values(cronJobs).forEach(async (job) => {\n const { params, state } = job;\n if (state.isRunning) {\n if (state.startTs && state.startTs + params.timeout < now) {\n // TODO: log cron trace timeout error\n state.isRunning = false;\n }\n return;\n }\n\n // TODO: limit the number of jobs running concurrently\n\n if (state.scheduledRunTs && state.scheduledRunTs <= now) {\n await startCronJob(job);\n }\n });\n}\n\nasync function startCronJob(job: CronJob) {\n const { alias, params, handler, state } = job;\n state.isRunning = true;\n state.startTs = Date.now();\n const transaction = startTransaction('cron', `cron:${alias}`);\n // TODO: enforce job timeout\n handler().then(() => {\n handleCronJobCompletion(state, params);\n transaction.end('success');\n }).catch((err) => {\n handleCronJobCompletion(state, params);\n captureError(err);\n transaction.end('error');\n console.error(`Error in cron job '${alias}':`, err);\n });\n await cronJobsCollection.updateOne({ alias }, {\n $set: {\n lastStartDate: new Date(state.startTs),\n }\n });\n}\n\nfunction handleCronJobCompletion(state: CronJob['state'], params: CronJob['params']) {\n state.scheduledRunTs = state.startTs ? state.startTs + params.interval : Date.now();\n state.startTs = undefined;\n state.isRunning = false;\n}\n\nexport function getCronJobsMetadata() {\n return Object.values(cronJobs).map(({ alias, params }) => ({\n alias,\n description: params.description,\n interval: params.interval,\n timeout: params.timeout,\n }));\n}\n\nexport default new Module('_system.cron', {\n stores: [cronJobsCollection],\n});\n\n// const runCronJob = () => {\n// const worker = new Worker(filePath, {\n// workerData: {},\n// execArgv: ['--loader', 'tsx'],\n// });\n\n// const timeoutId = setTimeout(() => {\n// worker.terminate();\n// console.error(`Cron job '${alias}' timed out after ${timeout}ms`);\n// }, timeout);\n\n// worker.on('message', (message) => {\n// if (message === 'done') {\n// clearTimeout(timeoutId);\n// worker.terminate();\n// }\n// });\n\n// worker.on('error', (err) => {\n// clearTimeout(timeoutId);\n// console.error(`Error in cron job '${alias}':`, err);\n// });\n\n// worker.on('exit', (code) => {\n// console.error(`Cron job '${alias}' exited with code ${code}`);\n// setTimeout(runCronJob, interval);\n// });\n// };\n","import { MongoClient, ServerApiVersion } from 'mongodb';\nimport { getConfig } from '../config/server';\n\nlet client: MongoClient | null = null;\n\nexport async function connect() {\n if (client) return client;\n\n const mongodbUri = getMongodbUri();\n if (!mongodbUri) {\n throw new Error('MongoDB URI is not set');\n }\n\n client = new MongoClient(mongodbUri, {\n maxPoolSize: 20\n });\n\n try {\n // Connect the client to the server\n await client.connect();\n // Send a ping to confirm a successful connection\n await client.db(\"admin\").command({ ping: 1 });\n console.log(\"Pinged your deployment. You successfully connected to MongoDB!\");\n return client;\n } catch (err) {\n console.error(err);\n client = null;\n throw err;\n }\n}\n\nexport function getMongodbUri() {\n const value = getConfig('_system.mongodbUri');\n return value ? String(value) : undefined;\n}\n\nexport function getClient() {\n return client;\n}\n\n// export async function closeConnection() {\n// if (client) {\n// await client.close();\n// client = null;\n// }\n// }\n","import { requireServer } from '../utils';\nimport { startTransaction } from '@/telemetry';\nimport { requireAccess } from '../auth/role';\nimport { Method, MethodDefinition, MethodType, Args, Context } from './types';\n\nconst methods: Record<string, Method<any>> = {};\n\nexport function createQuery<T extends any[]>(name: string, methodDef: MethodDefinition<T>) {\n requireServer();\n validateMethodName(name);\n return _createMethodInternal('query', name, methodDef);\n}\n\nexport function createMutation<T extends any[]>(name: string, methodDef: MethodDefinition<T>) {\n requireServer();\n validateMethodName(name);\n return _createMethodInternal('mutation', name, methodDef);\n}\n\nexport function _createSystemQuery<T extends any[]>(name: string, methodDef: MethodDefinition<T>) {\n requireServer();\n validateSystemMethodName(name);\n return _createMethodInternal('query', name, methodDef);\n}\n\nexport function _createSystemMutation<T extends any[]>(name: string, methodDef: MethodDefinition<T>) {\n requireServer();\n validateSystemMethodName(name);\n return _createMethodInternal('mutation', name, methodDef);\n}\n\nfunction validateMethodName(name: string) {\n if (name.toLowerCase().startsWith('_system.')) {\n throw new Error(`Method name cannot start with a reserved prefix: '_system.' (${name})`);\n }\n}\n\nfunction validateSystemMethodName(name: string) {\n if (!name.toLowerCase().startsWith('_system.')) {\n throw new Error(`System method name must start with a prefix: '_system.' (${name})`);\n }\n}\n\nfunction _createMethodInternal<T extends any>(type: MethodType, name: string, methodDef: MethodDefinition<T>) {\n requireServer();\n\n if (methods[name]) {\n throw new Error(`Method with name '${name}' is already defined.`);\n }\n\n const handler = typeof methodDef === 'function' ? methodDef : methodDef.handler;\n const permissions = typeof methodDef === 'function' ? [] : methodDef.permissions ?? [];\n methods[name] = { type, name, handler, permissions };\n}\n\nexport async function runMethod(name: string, args: Args, context: Context) {\n requireServer();\n\n const method = methods[name];\n if (!method) {\n throw new Error(`Method with name '${name}' is not defined.`);\n }\n const { type, handler } = method;\n\n const transaction = startTransaction('method', `method:${name}`, { type, args });\n\n let response;\n try {\n requireAccess(context.roles, method.permissions);\n response = await handler(args, context);\n } catch (error) {\n // TODO: log error and associate it with the transaction\n transaction.end('error');\n throw error;\n }\n\n transaction.end();\n\n return response;\n}\n","import { Store } from '../data/store';\nimport { schema } from '../data/types';\n\nexport const dbMigrations = new Store('_modelenceMigrations', {\n schema: {\n version: schema.number(),\n appliedAt: schema.date(),\n },\n indexes: [\n { key: { version: 1 }, unique: true },\n ],\n});\n","import { Module } from '../app/module';\nimport { dbMigrations } from './db';\n\nexport type MigrationScript = {\n version: number,\n description: string,\n handler: () => Promise<void>,\n}\n\nexport async function runMigrations(migrations: MigrationScript[]) {\n if (migrations.length === 0) {\n return;\n }\n\n const versions = migrations.map(({ version }) => version);\n\n const existingVersions = await dbMigrations.fetch({ version: { $in: versions } });\n const existingVersionSet = new Set(existingVersions.map(({ version }) => version));\n const pendingMigrations = migrations.filter(({ version }) => !existingVersionSet.has(version));\n\n if (pendingMigrations.length === 0) {\n return;\n }\n\n console.log(`Running migrations (${pendingMigrations.length})...`);\n for (const { version, description, handler } of pendingMigrations) {\n console.log(`Running migration v${version}: ${description}`);\n // TODO: adjust to handle multiple containers and race conditions\n await dbMigrations.insertOne({ version, appliedAt: new Date() });\n await handler();\n console.log(`Migration v${version} complete`);\n }\n}\n\nexport default new Module('_system.migration', {\n stores: [dbMigrations]\n});\n","import { Module } from '../app/module';\nimport { dbRateLimits } from './db';\n\nexport default new Module('_system.rateLimit', {\n stores: [dbRateLimits],\n});\n","import { createServer, defineConfig, ViteDevServer, loadConfigFromFile, UserConfig } from 'vite';\nimport reactPlugin from '@vitejs/plugin-react';\nimport path from 'path';\nimport fs from 'fs';\nimport express from 'express';\nimport { AppServer, ExpressMiddleware } from '@modelence/types';\n\nclass ViteServer implements AppServer {\n private viteServer?: ViteDevServer;\n private config?: UserConfig;\n\n async init() {\n this.config = await getConfig();\n if (this.isDev()) {\n console.log('Starting Vite dev server...');\n this.viteServer = await createServer({\n ...defineConfig(this.config),\n server: {\n middlewareMode: true,\n },\n root: './src/client'\n }); \n }\n }\n\n middlewares(): ExpressMiddleware[] {\n if (this.isDev()) {\n return (this.viteServer?.middlewares ?? []) as ExpressMiddleware[];\n }\n \n const staticFolders = [express.static('./.modelence/build/client')];\n if (this.config?.publicDir) {\n staticFolders.push(express.static(this.config.publicDir));\n }\n return staticFolders;\n }\n\n handler(req: express.Request, res: express.Response) {\n if (this.isDev()) {\n try {\n res.sendFile('index.html', { root: './src/client' });\n } catch (e) {\n console.error('Error serving index.html:', e);\n res.status(500).send('Internal Server Error');\n }\n } else {\n res.sendFile('index.html', { root: './.modelence/build/client' });\n }\n }\n\n private isDev() {\n return process.env.NODE_ENV !== 'production';\n }\n}\n\nasync function loadUserViteConfig() {\n const appDir = process.cwd();\n \n try {\n const result = await loadConfigFromFile({ command: 'serve', mode: 'development' }, undefined, appDir);\n return result?.config || {};\n } catch (error) {\n console.warn(`Could not load vite config:`, error);\n return {};\n }\n}\n\nasync function getConfig() {\n const appDir = process.cwd();\n const userConfig = await loadUserViteConfig();\n\n const eslintConfigFile = [\n '.eslintrc.js',\n '.eslintrc.json',\n '.eslintrc',\n 'eslint.config.js',\n '.eslintrc.yml',\n '.eslintrc.yaml'\n ].find(file => fs.existsSync(path.join(appDir, file)));\n\n const plugins = [reactPlugin(), modelenceAssetPlugin()];\n\n if (eslintConfigFile) {\n const eslintPlugin = (await import('vite-plugin-eslint')).default;\n plugins.push(\n eslintPlugin({\n failOnError: false,\n include: ['src/**/*.js', 'src/**/*.jsx', 'src/**/*.ts', 'src/**/*.tsx'],\n cwd: appDir,\n overrideConfigFile: path.resolve(appDir, eslintConfigFile)\n })\n );\n }\n\n return {\n plugins,\n root: appDir,\n build: {\n outDir: '.modelence/build/client',\n emptyOutDir: true\n },\n server: {\n proxy: {\n '/api': 'http://localhost:4000'\n },\n headers: {\n 'Cache-Control': 'no-store, no-cache, must-revalidate, proxy-revalidate, max-age=0',\n 'Pragma': 'no-cache',\n 'Expires': '0'\n },\n hmr: {\n port: 0,\n },\n },\n resolve: {\n alias: {\n '@': path.resolve(appDir, 'src')\n }\n },\n publicDir: userConfig.publicDir,\n };\n}\n\nfunction modelenceAssetPlugin() {\n return {\n name: 'modelence-asset-handler',\n async transform(code: string, id: string) {\n const assetRegex = /\\.(png|jpe?g|gif|svg|mpwebm|ogg|mp3|wav|flac|aac)$/;\n if (assetRegex.test(id)) {\n if (process.env.NODE_ENV === 'development') {\n return code;\n }\n // TODO: Upload to CDN\n // return `export default \"${cdnUrl}\"`;\n return code;\n }\n },\n async generateBundle(options: any, bundle: any) {\n // Handle asset URLs in the final bundle\n }\n };\n}\n\nexport const viteServer = new ViteServer();\n","import { getConfig } from \"@/server\";\nimport { Router, type Request, type Response } from \"express\";\nimport { ObjectId } from \"mongodb\";\nimport passport from \"passport\";\nimport { Strategy as GoogleStrategy } from \"passport-google-oauth20\";\nimport { usersCollection } from \"../db\";\nimport { createSession } from \"../session\";\n\ninterface GoogleUser {\n id: string;\n displayName: string;\n emails: { value: string; }[];\n photos: { value: string }[];\n}\n\nasync function authenticateUser(res: Response, userId: ObjectId) {\n const { authToken } = await createSession(userId);\n\n res.cookie(\"authToken\", authToken, {\n httpOnly: true,\n secure: process.env.NODE_ENV === \"production\",\n sameSite: \"strict\",\n });\n res.status(301);\n res.redirect(\"/\");\n}\n\n\nasync function handleGoogleAuthenticationCallback(req: Request, res: Response) {\n const googleUser = req.user as GoogleUser;\n\n const existingUser = await usersCollection.findOne(\n { 'authMethods.google.id': googleUser.id },\n );\n\n if (existingUser) {\n await authenticateUser(res, existingUser._id);\n \n return;\n }\n\n const googleEmail = googleUser.emails[0] && googleUser.emails[0]?.value;\n\n if (!googleEmail) {\n res.status(400).json({\n error: \"Email address is required for Google authentication.\",\n });\n }\n\n const existingUserByEmail = await usersCollection.findOne(\n { 'emails.address': googleEmail, },\n { collation: { locale: 'en', strength: 2 } },\n );\n\n // TODO: check if the email is verified\n if (existingUserByEmail) {\n // TODO: handle case with an HTML page\n res.status(400).json({\n error: \"User with this email already exists. Please log in instead.\",\n });\n return;\n }\n\n // If the user does not exist, create a new user\n const newUser = await usersCollection.insertOne({\n handle: googleEmail,\n emails: [{\n address: googleEmail,\n verified: true, // Google email is considered verified\n }],\n createdAt: new Date(),\n authMethods: {\n google: {\n id: googleUser.id,\n },\n },\n });\n\n await authenticateUser(res, newUser.insertedId);\n}\n\nfunction getRouter() {\n const googleAuthRouter = Router();\n const googleEnabled = Boolean(getConfig('_system.user.auth.google.enabled'));\n const googleClientId = String(getConfig('_system.user.auth.google.clientId'));\n const googleClientSecret = String(getConfig('_system.user.auth.google.clientSecret'));\n if (!googleEnabled || !googleClientId || !googleClientSecret) {\n return googleAuthRouter;\n }\n\n passport.use(new GoogleStrategy({\n clientID: googleClientId,\n clientSecret: googleClientSecret,\n callbackURL: '/api/_internal/auth/google/callback',\n proxy: true,\n }, (accessToken, refreshToken, profile, done) => {\n return done(null, profile);\n }));\n\n googleAuthRouter.get(\"/api/_internal/auth/google\", passport.authenticate(\"google\", {\n scope: [\"profile\", \"email\"],\n session: false,\n }));\n\n googleAuthRouter.get(\n \"/api/_internal/auth/google/callback\",\n passport.authenticate(\"google\", { session: false }),\n handleGoogleAuthenticationCallback,\n );\n\n return googleAuthRouter;\n}\n\nexport default getRouter;\n","import { Request, Response } from 'express';\nimport { RouteHandler, ExpressHandler } from './types';\nimport { ModelenceError } from '../error';\n\n// TODO: Use cookies for authentication and automatically add session/user to context if accessing from browser\n\nexport function createRouteHandler(handler: RouteHandler): ExpressHandler {\n return async (req: Request, res: Response) => {\n try {\n const response = await handler({\n query: req.query as Record<string, string>,\n body: req.body,\n params: req.params,\n headers: req.headers as Record<string, string>,\n cookies: req.cookies,\n req,\n });\n\n res.status(response.status || 200);\n\n if (response.redirect) {\n res.redirect(response.redirect);\n }\n\n if (response.headers) {\n Object.entries(response.headers).forEach(([key, value]) => {\n res.setHeader(key, value);\n });\n }\n\n res.send(response.data);\n } catch (error) {\n if (error instanceof ModelenceError) {\n res.status(error.status).send(error.message);\n } else {\n console.error(`Error in route handler: ${req.path}`);\n console.error(error);\n res.status(500).send(String(error));\n }\n }\n };\n}\n","import { ObjectId } from 'mongodb';\n\nimport { obtainSession } from './session';\nimport { usersCollection } from './db';\nimport { getDefaultAuthenticatedRoles, getUnauthenticatedRoles } from './role';\nimport { Role, Session, UserInfo } from './types';\n\nexport async function authenticate(authToken: string | null): Promise<{ session: Session, user: UserInfo | null, roles: Role[] }> {\n const session = await obtainSession(authToken);\n\n const userDoc = session.userId ? await usersCollection.findOne({ _id: new ObjectId(session.userId) }) : null;\n const user = userDoc ? {\n id: userDoc._id.toString(),\n handle: userDoc.handle,\n } : null;\n\n const roles = user ? getDefaultAuthenticatedRoles() : getUnauthenticatedRoles();\n\n return {\n user,\n session,\n roles,\n };\n}\n","import googleAuthRouter from '@/auth/providers/google';\nimport { runMethod } from '@/methods';\nimport { getResponseTypeMap } from '@/methods/serialize';\nimport { createRouteHandler } from '@/routes/handler';\nimport { HttpMethod } from '@/server';\nimport { logInfo } from '@/telemetry';\nimport cookieParser from 'cookie-parser';\nimport express, { Request, Response } from 'express';\nimport http from 'http';\nimport passport from 'passport';\nimport z from 'zod';\nimport { AppServer } from '../../../types';\nimport { authenticate } from '../auth';\nimport { getUnauthenticatedRoles } from '../auth/role';\nimport { getMongodbUri } from '../db/client';\nimport { ModelenceError } from '../error';\nimport { Module } from './module';\nimport { ConnectionInfo } from '@/methods/types';\n\nfunction registerModuleRoutes(app: express.Application, modules: Module[]) {\n for (const module of modules) {\n for (const route of module.routes) {\n const { path, handlers } = route;\n\n Object.entries(handlers).forEach(([method, handler]) => {\n app[method as HttpMethod](path, createRouteHandler(handler));\n });\n }\n }\n}\n\nexport async function startServer(server: AppServer, { combinedModules }: { combinedModules: Module[] }) {\n const app = express();\n\n app.use(express.json());\n app.use(express.urlencoded({ extended: true }));\n app.use(cookieParser());\n\n app.use(passport.initialize());\n\n app.use(googleAuthRouter());\n\n app.post('/api/_internal/method/:methodName(*)', async (req: Request, res: Response) => {\n const { methodName } = req.params;\n const context = await getCallContext(req);\n\n try {\n const result = await runMethod(methodName, req.body.args, context);\n res.json({\n data: result,\n typeMap: getResponseTypeMap(result),\n });\n } catch (error) {\n // TODO: introduce error codes and handle them differently\n // TODO: support multiple errors\n\n // TODO: add an option to silence these error console logs, especially when Elastic logs are configured\n console.error(`Error in method ${methodName}:`, error);\n\n if (error instanceof ModelenceError) {\n res.status(error.status).send(error.message);\n } else if (error instanceof Error && error?.constructor?.name === 'ZodError' && 'errors' in error) {\n const zodError = error as z.ZodError;\n const flattened = zodError.flatten();\n const fieldMessages = Object.entries(flattened.fieldErrors)\n .map(([key, errors]) => `${key}: ${(errors ?? []).join(', ')}`)\n .join('; ');\n const formMessages = flattened.formErrors.join('; ');\n const allMessages = [fieldMessages, formMessages].filter(Boolean).join('; ');\n res.status(400).send(allMessages);\n } else {\n res.status(500).send(error instanceof Error ? error.message : String(error));\n }\n }\n });\n\n registerModuleRoutes(app, combinedModules);\n\n await server.init();\n\n if (server.middlewares) {\n app.use(server.middlewares());\n }\n\n app.all('*', (req: Request, res: Response) => {\n return server.handler(req, res);\n });\n\n process.on('unhandledRejection', (reason, promise) => {\n console.error('Unhandled Promise Rejection:');\n console.error(reason instanceof Error ? reason.stack : reason);\n console.error('Promise:', promise);\n });\n \n // Global uncaught exceptions\n process.on('uncaughtException', (error) => {\n console.error('Uncaught Exception:');\n console.error(error.stack); // This gives you the full stack trace\n console.trace('Full application stack:'); // Additional context\n });\n\n const httpServer = http.createServer(app);\n const port = process.env.PORT || 3000;\n httpServer.listen(port, () => {\n logInfo(`Application started`, { source: 'app' });\n console.log(`\\nApplication started on http://localhost:${port}\\n`);\n });\n}\n\nasync function getCallContext(req: Request) {\n const authToken = z.string().nullish().transform(val => val ?? null).parse(req.cookies.authToken || req.body.authToken);\n\n const clientInfo = z.object({\n screenWidth: z.number(),\n screenHeight: z.number(),\n windowWidth: z.number(),\n windowHeight: z.number(),\n pixelRatio: z.number(),\n orientation: z.string().nullable(),\n }).parse(req.body.clientInfo);\n\n const connectionInfo: ConnectionInfo = {\n ip: getClientIp(req),\n userAgent: req.get('user-agent'),\n acceptLanguage: req.get('accept-language'),\n referrer: req.get('referrer'),\n baseUrl: req.protocol + '://' + req.get('host'),\n };\n\n const hasDatabase = Boolean(getMongodbUri());\n if (hasDatabase) {\n const { session, user, roles } = await authenticate(authToken);\n return {\n clientInfo,\n connectionInfo,\n session,\n user,\n roles,\n };\n }\n\n return {\n clientInfo,\n connectionInfo,\n session: null,\n user: null,\n roles: getUnauthenticatedRoles(),\n };\n}\n\nfunction getClientIp(req: Request): string | undefined {\n // On Heroku and other proxies, X-Forwarded-For contains the real client IP\n const forwardedFor = req.headers['x-forwarded-for'];\n if (forwardedFor) {\n const firstIp = Array.isArray(forwardedFor) ? forwardedFor[0] : forwardedFor.split(',')[0];\n return firstIp.trim();\n }\n\n const directIp = req.ip || req.socket?.remoteAddress;\n if (directIp) {\n // Remove IPv6-to-IPv4 mapping prefix\n return directIp.startsWith('::ffff:') ? directIp.substring(7) : directIp;\n }\n \n return undefined;\n}\n","import dotenv from 'dotenv';\nimport fs from 'fs/promises';\nimport os from 'os';\nimport path from 'path';\n\nimport { AppServer, EmailProvider } from '@modelence/types';\nimport { initRoles } from '../auth/role';\nimport sessionModule from '../auth/session';\nimport { RoleDefinition } from '../auth/types';\nimport userModule from '../auth/user';\nimport { loadConfigs, setSchema } from '../config/server';\nimport { startConfigSync } from '../config/sync';\nimport { AppConfig, ConfigSchema, ConfigType } from '../config/types';\nimport cronModule, { defineCronJob, getCronJobsMetadata, startCronJobs } from '../cron/jobs';\nimport { Store } from '../data/store';\nimport { connect, getClient, getMongodbUri } from '../db/client';\nimport { _createSystemMutation, _createSystemQuery, createMutation, createQuery } from '../methods';\nimport { MigrationScript, default as migrationModule, runMigrations } from '../migration';\nimport rateLimitModule from '../rate-limit';\nimport { initRateLimits } from '../rate-limit/rules';\nimport { viteServer } from '../viteServer';\nimport { connectCloudBackend } from './backendApi';\nimport { initMetrics } from './metrics';\nimport { Module } from './module';\nimport { startServer } from './server';\nimport { markAppStarted, setMetadata } from './state';\nimport { EmailConfig, setEmailConfig } from './emailConfig';\n\nexport type AppOptions = {\n modules?: Module[],\n server?: AppServer,\n email?: EmailConfig,\n roles?: Record<string, RoleDefinition>,\n defaultRoles?: Record<string, string>,\n migrations?: Array<MigrationScript>\n}\n\nexport async function startApp(\n { modules = [], roles = {}, defaultRoles = {}, server = viteServer, migrations = [], email = {} }: AppOptions\n) {\n dotenv.config();\n \n dotenv.config({ path: '.modelence.env' });\n\n const hasRemoteBackend = Boolean(process.env.MODELENCE_SERVICE_ENDPOINT);\n const isCronEnabled = process.env.MODELENCE_CRON_ENABLED === 'true';\n\n trackAppStart().then(() => {\n // Do nothing\n }).catch(() => {\n // Silently ignore tracking errors to not disrupt app startup\n });\n\n // TODO: verify that user modules don't start with `_system.` prefix\n const systemModules = [userModule, sessionModule, cronModule, migrationModule, rateLimitModule];\n const combinedModules = [...systemModules, ...modules];\n\n markAppStarted();\n\n initSystemMethods(systemModules);\n initCustomMethods(modules);\n\n initRoles(roles, defaultRoles);\n\n const configSchema = getConfigSchema(combinedModules);\n setSchema(configSchema);\n const stores = getStores(combinedModules);\n\n if (isCronEnabled) {\n defineCronJobs(combinedModules);\n }\n\n const rateLimits = getRateLimits(combinedModules);\n initRateLimits(rateLimits);\n\n if (hasRemoteBackend) {\n const { configs, environmentId, appAlias, environmentAlias, telemetry } = await connectCloudBackend({\n configSchema,\n cronJobsMetadata: isCronEnabled ? getCronJobsMetadata() : undefined,\n stores\n });\n loadConfigs(configs);\n setMetadata({ environmentId, appAlias, environmentAlias, telemetry });\n } else {\n loadConfigs(getLocalConfigs(configSchema));\n }\n\n setEmailConfig(email);\n\n const mongodbUri = getMongodbUri();\n if (mongodbUri) {\n await connect();\n initStores(stores);\n }\n\n if (isCronEnabled) {\n await runMigrations(migrations);\n }\n\n if (mongodbUri) {\n for (const store of stores) {\n store.createIndexes();\n }\n }\n\n if (hasRemoteBackend) {\n await initMetrics();\n startConfigSync();\n }\n\n if (isCronEnabled) {\n startCronJobs().catch(console.error);\n }\n\n await startServer(server, { combinedModules });\n}\n\nfunction initCustomMethods(modules: Module[]) {\n for (const module of modules) {\n for (const [key, handler] of Object.entries(module.queries)) {\n createQuery(`${module.name}.${key}`, handler);\n }\n for (const [key, handler] of Object.entries(module.mutations)) {\n createMutation(`${module.name}.${key}`, handler);\n }\n }\n}\n\nfunction initSystemMethods(modules: Module[]) {\n for (const module of modules) {\n for (const [key, handler] of Object.entries(module.queries)) {\n _createSystemQuery(`${module.name}.${key}`, handler);\n }\n for (const [key, handler] of Object.entries(module.mutations)) {\n _createSystemMutation(`${module.name}.${key}`, handler);\n }\n }\n}\n\nfunction getStores(modules: Module[]) {\n return modules.flatMap(module => module.stores);\n}\n\nfunction getRateLimits(modules: Module[]) {\n return modules.flatMap(module => module.rateLimits);\n}\n\nfunction getConfigSchema(modules: Module[]): ConfigSchema {\n const merged: ConfigSchema = {};\n\n for (const module of modules) {\n for (const [key, value] of Object.entries(module.configSchema)) {\n const absoluteKey = `${module.name}.${key}`;\n if (absoluteKey in merged) {\n throw new Error(\n `Duplicate config schema key: ${absoluteKey} (${module.name})`\n );\n }\n\n merged[absoluteKey] = value;\n }\n }\n\n return merged;\n}\n\nfunction defineCronJobs(modules: Module[]) {\n for (const module of modules) {\n for (const [cronAlias, cronJobParams] of Object.entries(module.cronJobs)) {\n defineCronJob(`${module.name}.${cronAlias}`, cronJobParams);\n }\n }\n}\n\nfunction initStores(stores: Store<any, any>[]) {\n const client = getClient();\n if (!client) {\n throw new Error('Failed to initialize stores: MongoDB client not initialized');\n }\n\n for (const store of stores) {\n store.init(client);\n }\n}\n\nconst localConfigMap = {\n MONGODB_URI: '_system.mongodbUri',\n MODELENCE_AUTH_GOOGLE_ENABLED: '_system.user.auth.google.enabled',\n MODELENCE_AUTH_GOOGLE_CLIENT_ID: '_system.user.auth.google.clientId',\n MODELENCE_AUTH_GOOGLE_CLIENT_SECRET: '_system.user.auth.google.clientSecret',\n MODELENCE_EMAIL_RESEND_API_KEY: '_system.email.resend.apiKey',\n MODELENCE_EMAIL_AWS_SES_REGION: '_system.email.awsSes.region',\n MODELENCE_EMAIL_AWS_SES_ACCESS_KEY_ID: '_system.email.awsSes.accessKeyId',\n MODELENCE_EMAIL_AWS_SES_SECRET_ACCESS_KEY: '_system.email.awsSes.secretAccessKey',\n MODELENCE_EMAIL_SMTP_HOST: '_system.email.smtp.host',\n MODELENCE_EMAIL_SMTP_PORT: '_system.email.smtp.port',\n MODELENCE_EMAIL_SMTP_USER: '_system.email.smtp.user',\n MODELENCE_EMAIL_SMTP_PASS: '_system.email.smtp.pass',\n // deprecated\n GOOGLE_AUTH_ENABLED: '_system.user.auth.google.enabled',\n GOOGLE_AUTH_CLIENT_ID: '_system.user.auth.google.clientId',\n GOOGLE_AUTH_CLIENT_SECRET: '_system.user.auth.google.clientSecret',\n};\n\nfunction formatLocalConfigValue(value: string, type: ConfigType): string | number | boolean {\n if (type === 'number') {\n const numValue = Number(value);\n if (isNaN(numValue)) {\n throw new Error(`Invalid number value for config: ${value}`);\n }\n return numValue;\n }\n if (type === 'boolean') {\n if (value.toLowerCase() === 'true') {\n return true;\n }\n if (value.toLowerCase() === 'false') {\n return false;\n }\n throw new Error(`Invalid boolean value for config: ${value}`);\n }\n return value;\n}\n\nfunction getLocalConfigs(configSchema: ConfigSchema): AppConfig[] {\n const configs: AppConfig[] = [];\n\n for (const [envVar, configKey] of Object.entries(localConfigMap)) {\n const value = process.env[envVar];\n const configSchemaEntry = configSchema[configKey];\n if (value) {\n const type = configSchemaEntry?.type ?? 'string';\n configs.push({\n key: configKey,\n type: type,\n value: formatLocalConfigValue(value, type),\n });\n }\n }\n\n return configs;\n}\n\nasync function trackAppStart() {\n const isTrackingEnabled = process.env.MODELENCE_TRACKING_ENABLED !== 'false';\n\n if (isTrackingEnabled) {\n const serviceEndpoint = process.env.MODELENCE_SERVICE_ENDPOINT ?? 'https://cloud.modelence.com';\n const environmentId = process.env.MODELENCE_ENVIRONMENT_ID;\n \n const appDetails = await getAppDetails();\n const modelencePackageJson = await import('../../package.json');\n \n await fetch(`${serviceEndpoint}/api/track/app-start`, {\n method: 'POST',\n headers: {\n 'Content-Type': 'application/json'\n },\n body: JSON.stringify({\n projectName: appDetails.name,\n version: modelencePackageJson.default.version,\n localHostname: os.hostname(),\n environmentId\n })\n });\n }\n}\n\nasync function getAppDetails() {\n try {\n const packageJsonPath = path.join(process.cwd(), 'package.json');\n const packageJsonContent = await fs.readFile(packageJsonPath, 'utf-8');\n const packageJson = JSON.parse(packageJsonContent);\n \n return {\n name: packageJson.name || 'unknown'\n };\n } catch (error) {\n return {\n name: 'unknown'\n };\n }\n}\n"]}
|
package/package.json
CHANGED
package/dist/package-MYWZ4U2C.js
DELETED
|
@@ -1,3 +0,0 @@
|
|
|
1
|
-
var s="module",i="modelence",o="0.5.12",p="The Node.js Framework for Real-Time MongoDB Apps",r="dist/index.js",n="dist/global.d.ts",d={".":"./dist/index.js","./client":"./dist/client.js","./server":"./dist/server.js","./telemetry":"./dist/telemetry.js","./mongodb":"./dist/mongo.js"},c=["dist","dist/bin"],l={modelence:"./dist/bin/modelence.js"},a={build:"tsup",dev:"tsup --watch",prepublishOnly:"npm run build",test:'echo "Error: no test specified" && exit 1',postversion:"git push && git push --tags"},m={type:"git",url:"git+https://github.com/modelence/modelence.git"},u="Modelence",g="SEE LICENSE IN LICENSE",y={url:"https://github.com/modelence/modelence/issues"},h="https://modelence.com",b={"@types/archiver":"^6.0.3","@types/bcrypt":"^5.0.2","@types/cookie-parser":"^1.4.9","@types/express":"^5.0.0","@types/fs-extra":"^11.0.4","@types/node":"^22.5.1","@types/passport-google-oauth20":"^2.0.16","@types/react":"^19.0.0","@types/react-dom":"^19.0.1","@typescript-eslint/eslint-plugin":"^8.17.0","@typescript-eslint/parser":"^8.17.0",react:"^19.0.0","react-dom":"^19.0.0"},v={"@modelence/types":"^1.0.3","@vitejs/plugin-react":"^4.3.4",archiver:"^7.0.1",bcrypt:"^5.1.1",commander:"^12.0.0","cookie-parser":"^1.4.7",dotenv:"^16.4.5","elastic-apm-node":"^4.8.0",express:"^4.21.0","fs-extra":"^11.2.0",jiti:"^2.4.2",mongodb:"^6.8.1",open:"^10.1.0",passport:"^0.7.0","passport-google-oauth20":"^2.0.0",tsup:"^8.3.6",tsx:"^4.19.3",typescript:"^5.7.2",vite:"^6.0.3","vite-plugin-eslint":"^1.8.1",winston:"^3.15.0","winston-elasticsearch":"^0.19.0",zod:"^3.23.8",zustand:"^5.0.2"},j={react:">=18.0.0","react-dom":">=18.0.0"},x={type:s,name:i,version:o,description:p,main:r,types:n,exports:d,files:c,bin:l,scripts:a,repository:m,author:u,license:g,bugs:y,homepage:h,devDependencies:b,dependencies:v,peerDependencies:j};
|
|
2
|
-
export{u as author,l as bin,y as bugs,x as default,v as dependencies,p as description,b as devDependencies,d as exports,c as files,h as homepage,g as license,r as main,i as name,j as peerDependencies,m as repository,a as scripts,s as type,n as types,o as version};//# sourceMappingURL=package-MYWZ4U2C.js.map
|
|
3
|
-
//# sourceMappingURL=package-MYWZ4U2C.js.map
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"sources":["../package.json"],"names":["type","name","version","description","main","types","exports","files","bin","scripts","repository","author","license","bugs","homepage","devDependencies","dependencies","peerDependencies","package_default"],"mappings":"AACE,IAAAA,CAAAA,CAAQ,SACRC,CAAAA,CAAQ,WAAA,CACRC,EAAW,QAAA,CACXC,CAAAA,CAAe,mDACfC,CAAAA,CAAQ,eAAA,CACRC,EAAS,kBAAA,CACTC,CAAAA,CAAW,CACT,GAAA,CAAK,iBAAA,CACL,WAAY,kBAAA,CACZ,UAAA,CAAY,mBACZ,aAAA,CAAe,qBAAA,CACf,YAAa,iBACf,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AAS,WACT,WAAA,CAAa,UACf,EAlFFC,CAAAA,CAAA,CACE,KAAAlB,CAAAA,CACA,IAAA,CAAAC,EACA,OAAA,CAAAC,CAAAA,CACA,YAAAC,CAAAA,CACA,IAAA,CAAAC,EACA,KAAA,CAAAC,CAAAA,CACA,QAAAC,CAAAA,CAOA,KAAA,CAAAC,EAIA,GAAA,CAAAC,CAAAA,CAGA,QAAAC,CAAAA,CAOA,UAAA,CAAAC,EAIA,MAAA,CAAAC,CAAAA,CACA,QAAAC,CAAAA,CACA,IAAA,CAAAC,EAGA,QAAA,CAAAC,CAAAA,CACA,gBAAAC,CAAAA,CAeA,YAAA,CAAAC,CAAAA,CA0BA,gBAAA,CAAAC,CAIF","file":"package-MYWZ4U2C.js","sourcesContent":["{\n \"type\": \"module\",\n \"name\": \"modelence\",\n \"version\": \"0.5.12\",\n \"description\": \"The Node.js Framework for Real-Time MongoDB Apps\",\n \"main\": \"dist/index.js\",\n \"types\": \"dist/global.d.ts\",\n \"exports\": {\n \".\": \"./dist/index.js\",\n \"./client\": \"./dist/client.js\",\n \"./server\": \"./dist/server.js\",\n \"./telemetry\": \"./dist/telemetry.js\",\n \"./mongodb\": \"./dist/mongo.js\"\n },\n \"files\": [\n \"dist\",\n \"dist/bin\"\n ],\n \"bin\": {\n \"modelence\": \"./dist/bin/modelence.js\"\n },\n \"scripts\": {\n \"build\": \"tsup\",\n \"dev\": \"tsup --watch\",\n \"prepublishOnly\": \"npm run build\",\n \"test\": \"echo \\\"Error: no test specified\\\" && exit 1\",\n \"postversion\": \"git push && git push --tags\"\n },\n \"repository\": {\n \"type\": \"git\",\n \"url\": \"git+https://github.com/modelence/modelence.git\"\n },\n \"author\": \"Modelence\",\n \"license\": \"SEE LICENSE IN LICENSE\",\n \"bugs\": {\n \"url\": \"https://github.com/modelence/modelence/issues\"\n },\n \"homepage\": \"https://modelence.com\",\n \"devDependencies\": {\n \"@types/archiver\": \"^6.0.3\",\n \"@types/bcrypt\": \"^5.0.2\",\n \"@types/cookie-parser\": \"^1.4.9\",\n \"@types/express\": \"^5.0.0\",\n \"@types/fs-extra\": \"^11.0.4\",\n \"@types/node\": \"^22.5.1\",\n \"@types/passport-google-oauth20\": \"^2.0.16\",\n \"@types/react\": \"^19.0.0\",\n \"@types/react-dom\": \"^19.0.1\",\n \"@typescript-eslint/eslint-plugin\": \"^8.17.0\",\n \"@typescript-eslint/parser\": \"^8.17.0\",\n \"react\": \"^19.0.0\",\n \"react-dom\": \"^19.0.0\"\n },\n \"dependencies\": {\n \"@modelence/types\": \"^1.0.3\",\n \"@vitejs/plugin-react\": \"^4.3.4\",\n \"archiver\": \"^7.0.1\",\n \"bcrypt\": \"^5.1.1\",\n \"commander\": \"^12.0.0\",\n \"cookie-parser\": \"^1.4.7\",\n \"dotenv\": \"^16.4.5\",\n \"elastic-apm-node\": \"^4.8.0\",\n \"express\": \"^4.21.0\",\n \"fs-extra\": \"^11.2.0\",\n \"jiti\": \"^2.4.2\",\n \"mongodb\": \"^6.8.1\",\n \"open\": \"^10.1.0\",\n \"passport\": \"^0.7.0\",\n \"passport-google-oauth20\": \"^2.0.0\",\n \"tsup\": \"^8.3.6\",\n \"tsx\": \"^4.19.3\",\n \"typescript\": \"^5.7.2\",\n \"vite\": \"^6.0.3\",\n \"vite-plugin-eslint\": \"^1.8.1\",\n \"winston\": \"^3.15.0\",\n \"winston-elasticsearch\": \"^0.19.0\",\n \"zod\": \"^3.23.8\",\n \"zustand\": \"^5.0.2\"\n },\n \"peerDependencies\": {\n \"react\": \">=18.0.0\",\n \"react-dom\": \">=18.0.0\"\n }\n}\n"]}
|