@aventoapp/framework 0.1.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/index.js +6 -0
- package/dist/index.js.map +7 -0
- package/dist/native/index.js +2522 -0
- package/dist/native/index.js.map +7 -0
- package/dist/server/index.js +2776 -0
- package/dist/server/index.js.map +7 -0
- package/dist/server/workflow/index.js +537 -0
- package/dist/server/workflow/index.js.map +7 -0
- package/dist/shared/index.js +62 -0
- package/dist/shared/index.js.map +7 -0
- package/dist/web/index.js +7323 -0
- package/dist/web/index.js.map +7 -0
- package/package.json +81 -0
- package/schemas/Workflow.json +14 -0
- package/schemas/WorkflowHistory.json +22 -0
- package/schemas/WorkflowInstance.json +16 -0
- package/schemas/WorkflowState.json +18 -0
- package/schemas/WorkflowTransition.json +27 -0
- package/src/index.js +8 -0
- package/src/native/components/NativeAuthProvider.jsx +249 -0
- package/src/native/components/NativeDetail.jsx +270 -0
- package/src/native/components/NativeForm.jsx +543 -0
- package/src/native/components/NativeGrid.jsx +90 -0
- package/src/native/components/NativeJsonGrid.jsx +213 -0
- package/src/native/components/NativeJsonView.jsx +454 -0
- package/src/native/components/NativeJsonViewContext.js +17 -0
- package/src/native/components/NativeShell.jsx +68 -0
- package/src/native/components/NativeViewComponent.jsx +351 -0
- package/src/native/extensions/NativeExtensionRegistry.js +81 -0
- package/src/native/hooks/useNativeStore.js +72 -0
- package/src/native/index.js +15 -0
- package/src/native/layouts/NativeStackLayout.jsx +30 -0
- package/src/native/layouts/NativeTabLayout.jsx +96 -0
- package/src/native/storage.js +13 -0
- package/src/native/stores/NativeBaseStore.js +348 -0
- package/src/native/stores/NativeStoreContext.jsx +53 -0
- package/src/server/ai/capabilities-routes.js +106 -0
- package/src/server/ai/index.js +1 -0
- package/src/server/cache/MemoryCache.js +153 -0
- package/src/server/cache/index.js +2 -0
- package/src/server/cache/middleware.js +12 -0
- package/src/server/db/index.js +14 -0
- package/src/server/db/mongo.js +137 -0
- package/src/server/db/postgres.js +144 -0
- package/src/server/index.js +38 -0
- package/src/server/middleware/auth.js +682 -0
- package/src/server/middleware/can-flags.js +132 -0
- package/src/server/middleware/entityRoles.js +105 -0
- package/src/server/middleware/index.js +58 -0
- package/src/server/middleware/permissions.js +240 -0
- package/src/server/middleware/tenant.js +203 -0
- package/src/server/realtime/EventBus.js +45 -0
- package/src/server/realtime/WebSocketServer.js +105 -0
- package/src/server/realtime/index.js +3 -0
- package/src/server/realtime/middleware.js +18 -0
- package/src/server/services/email-templates.js +157 -0
- package/src/server/services/email.js +78 -0
- package/src/server/services/index.js +15 -0
- package/src/server/services/storage.js +119 -0
- package/src/server/utils/index.js +16 -0
- package/src/server/utils/paginate.js +65 -0
- package/src/server/utils/query-builder.js +293 -0
- package/src/server/utils/route-loader.js +61 -0
- package/src/server/workflow/WorkflowEngine.js +494 -0
- package/src/server/workflow/index.js +2 -0
- package/src/server/workflow/workflow-routes.js +174 -0
- package/src/shared/index.js +10 -0
- package/src/shared/utils/field-accessor.js +108 -0
- package/src/shared/utils/index.js +7 -0
- package/src/shared/utils/validation-utils.js +83 -0
- package/src/web/components/AppRouter/AppRouter.jsx +130 -0
- package/src/web/components/AppRouter/index.js +1 -0
- package/src/web/components/AppShell/AppShell.jsx +101 -0
- package/src/web/components/AppShell/DefaultUserMenu.jsx +54 -0
- package/src/web/components/AppShell/ShellConfig.js +53 -0
- package/src/web/components/AppShell/index.js +3 -0
- package/src/web/components/AuthProvider.jsx +426 -0
- package/src/web/components/CardList/CardList.jsx +272 -0
- package/src/web/components/CardList/index.js +2 -0
- package/src/web/components/DetailView/DetailView.jsx +281 -0
- package/src/web/components/DetailView/index.js +2 -0
- package/src/web/components/Form/Form.jsx +300 -0
- package/src/web/components/Form/FormField.jsx +226 -0
- package/src/web/components/Form/index.js +3 -0
- package/src/web/components/Grid/Grid.jsx +304 -0
- package/src/web/components/Grid/index.js +2 -0
- package/src/web/components/IconRegistry/IconRegistry.jsx +127 -0
- package/src/web/components/IconRegistry/index.js +1 -0
- package/src/web/components/JsonView/JsonView.jsx +647 -0
- package/src/web/components/JsonView/ViewComponent.jsx +1045 -0
- package/src/web/components/JsonView/ViewToolbar.jsx +141 -0
- package/src/web/components/JsonView/index.js +14 -0
- package/src/web/components/JsonView/layouts/SingleLayout.jsx +41 -0
- package/src/web/components/JsonView/layouts/SplitLayout.jsx +122 -0
- package/src/web/components/JsonView/layouts/TabLayout.jsx +112 -0
- package/src/web/components/JsonView/layouts/index.js +8 -0
- package/src/web/components/Layout.jsx +265 -0
- package/src/web/components/MobileLayout/MobileLayout.jsx +385 -0
- package/src/web/components/MobileLayout/index.js +1 -0
- package/src/web/components/Navigation/Navigation.jsx +248 -0
- package/src/web/components/Navigation/index.js +1 -0
- package/src/web/components/NotificationProvider.jsx +55 -0
- package/src/web/components/Pagination/InfiniteScroll.jsx +82 -0
- package/src/web/components/Pagination/Pagination.jsx +73 -0
- package/src/web/components/Pagination/index.js +8 -0
- package/src/web/components/SimpleList/SimpleList.jsx +177 -0
- package/src/web/components/SimpleList/index.js +2 -0
- package/src/web/components/TenantProvider.jsx +121 -0
- package/src/web/components/WorkflowActions/WorkflowActions.jsx +71 -0
- package/src/web/components/WorkflowActions/index.js +1 -0
- package/src/web/components/WorkflowField/WorkflowField.jsx +176 -0
- package/src/web/components/WorkflowField/index.js +2 -0
- package/src/web/components/WorkflowField/workflowColors.js +32 -0
- package/src/web/components/auth/DevTenantSelector.jsx +90 -0
- package/src/web/components/auth/ForgotPasswordForm.jsx +94 -0
- package/src/web/components/auth/RegisterForm.jsx +168 -0
- package/src/web/components/auth/ResetPasswordForm.jsx +121 -0
- package/src/web/components/auth/VerifyEmailView.jsx +85 -0
- package/src/web/components/auth/index.js +5 -0
- package/src/web/components/index.js +39 -0
- package/src/web/components/layouts/CardListLayout.jsx +68 -0
- package/src/web/components/layouts/FullscreenLayout.jsx +30 -0
- package/src/web/components/layouts/MobileStackLayout.jsx +28 -0
- package/src/web/components/layouts/WizardLayout.jsx +86 -0
- package/src/web/components/layouts/index.js +4 -0
- package/src/web/components/mobile/Badge.jsx +105 -0
- package/src/web/components/mobile/BadgeThemeEditor.jsx +104 -0
- package/src/web/components/mobile/EmptyState.jsx +30 -0
- package/src/web/components/mobile/QuickActionButton.jsx +77 -0
- package/src/web/components/mobile/ServerAutocomplete.jsx +123 -0
- package/src/web/components/mobile/StarRating.jsx +42 -0
- package/src/web/components/mobile/StatCard.jsx +65 -0
- package/src/web/components/mobile/index.js +7 -0
- package/src/web/extensions/ExtensionRegistry.js +79 -0
- package/src/web/extensions/index.js +7 -0
- package/src/web/hooks/index.js +15 -0
- package/src/web/hooks/useApi.js +76 -0
- package/src/web/hooks/useAuth.js +37 -0
- package/src/web/hooks/useDebouncedSave.js +158 -0
- package/src/web/hooks/useIsMobile.js +14 -0
- package/src/web/hooks/useOfflineQueue.js +99 -0
- package/src/web/hooks/useSelectionModel.js +143 -0
- package/src/web/hooks/useServerAutocomplete.js +146 -0
- package/src/web/hooks/useStore.js +107 -0
- package/src/web/hooks/useSubscription.js +130 -0
- package/src/web/hooks/useTenant.js +39 -0
- package/src/web/hooks/useTenantResolver.js +65 -0
- package/src/web/hooks/useUndoRedo.js +77 -0
- package/src/web/hooks/useViews.js +113 -0
- package/src/web/hooks/useWorkflow.js +190 -0
- package/src/web/index.js +117 -0
- package/src/web/stores/BaseStore.js +439 -0
- package/src/web/stores/StoreContext.jsx +93 -0
- package/src/web/stores/index.js +3 -0
- package/src/web/theme/index.js +3 -0
- package/src/web/theme/mui-theme.js +228 -0
- package/src/web/utils/formatTimeAgo.js +22 -0
- package/src/web/utils/index.js +1 -0
- package/src/web/views/ViewRegistry.js +235 -0
- package/src/web/views/index.js +2 -0
|
@@ -0,0 +1,2776 @@
|
|
|
1
|
+
var __defProp = Object.defineProperty;
|
|
2
|
+
var __export = (target, all) => {
|
|
3
|
+
for (var name in all)
|
|
4
|
+
__defProp(target, name, { get: all[name], enumerable: true });
|
|
5
|
+
};
|
|
6
|
+
|
|
7
|
+
// src/server/middleware/index.js
|
|
8
|
+
var middleware_exports = {};
|
|
9
|
+
__export(middleware_exports, {
|
|
10
|
+
assertTenant: () => assertTenant,
|
|
11
|
+
attachCanFlags: () => attachCanFlags,
|
|
12
|
+
comparePassword: () => comparePassword,
|
|
13
|
+
computeCanFlags: () => computeCanFlags,
|
|
14
|
+
configurePassport: () => configurePassport,
|
|
15
|
+
createForgotPasswordHandler: () => createForgotPasswordHandler,
|
|
16
|
+
createLoginHandler: () => createLoginHandler,
|
|
17
|
+
createPermissionChecker: () => createPermissionChecker,
|
|
18
|
+
createRefreshHandler: () => createRefreshHandler,
|
|
19
|
+
createRegisterHandler: () => createRegisterHandler,
|
|
20
|
+
createResetPasswordHandler: () => createResetPasswordHandler,
|
|
21
|
+
createTenantListHandler: () => createTenantListHandler,
|
|
22
|
+
createTenantLookupHandler: () => createTenantLookupHandler,
|
|
23
|
+
createVerifyEmailHandler: () => createVerifyEmailHandler,
|
|
24
|
+
ensureEntityRolesTable: () => ensureEntityRolesTable,
|
|
25
|
+
generateRefreshToken: () => generateRefreshToken,
|
|
26
|
+
generateSecureToken: () => generateSecureToken,
|
|
27
|
+
generateToken: () => generateToken,
|
|
28
|
+
generateTokenExpiry: () => generateTokenExpiry,
|
|
29
|
+
getTenantId: () => getTenantId,
|
|
30
|
+
hasAllRoles: () => hasAllRoles,
|
|
31
|
+
hasAnyPermission: () => hasAnyPermission,
|
|
32
|
+
hasAnyRole: () => hasAnyRole,
|
|
33
|
+
hasEntityRole: () => hasEntityRole,
|
|
34
|
+
hasPermission: () => hasPermission,
|
|
35
|
+
hashPassword: () => hashPassword,
|
|
36
|
+
initAuth: () => initAuth,
|
|
37
|
+
isValidUUID: () => isValidUUID,
|
|
38
|
+
optionalAuth: () => optionalAuth,
|
|
39
|
+
requireAdmin: () => requireAdmin,
|
|
40
|
+
requireAllRoles: () => requireAllRoles,
|
|
41
|
+
requireAuth: () => requireAuth,
|
|
42
|
+
requireEntityRoleOr: () => requireEntityRoleOr,
|
|
43
|
+
requireOwnership: () => requireOwnership,
|
|
44
|
+
requirePermission: () => requirePermission,
|
|
45
|
+
requireRoles: () => requireRoles,
|
|
46
|
+
requireTenant: () => requireTenant,
|
|
47
|
+
tenantMiddleware: () => tenantMiddleware,
|
|
48
|
+
verifyToken: () => verifyToken
|
|
49
|
+
});
|
|
50
|
+
|
|
51
|
+
// src/server/middleware/tenant.js
|
|
52
|
+
import jwt from "jsonwebtoken";
|
|
53
|
+
function isValidUUID(str) {
|
|
54
|
+
const uuidRegex = /^[0-9a-f]{8}-[0-9a-f]{4}-[1-5][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i;
|
|
55
|
+
return uuidRegex.test(str);
|
|
56
|
+
}
|
|
57
|
+
function tenantMiddleware(options = {}) {
|
|
58
|
+
const {
|
|
59
|
+
jwtSecret = process.env.JWT_SECRET || "avento-secret-change-me",
|
|
60
|
+
headerName = "X-Tenant-ID",
|
|
61
|
+
required = true,
|
|
62
|
+
getTenantInfo = null
|
|
63
|
+
// Optional async function to fetch full tenant details
|
|
64
|
+
} = options;
|
|
65
|
+
return async (req, res, next) => {
|
|
66
|
+
let tenantId = null;
|
|
67
|
+
let tenantName = null;
|
|
68
|
+
const authHeader = req.headers.authorization;
|
|
69
|
+
if (authHeader && authHeader.startsWith("Bearer ")) {
|
|
70
|
+
try {
|
|
71
|
+
const token = authHeader.substring(7);
|
|
72
|
+
const decoded = jwt.verify(token, jwtSecret);
|
|
73
|
+
if (decoded.tenant_id) {
|
|
74
|
+
tenantId = decoded.tenant_id;
|
|
75
|
+
tenantName = decoded.tenant_name || null;
|
|
76
|
+
}
|
|
77
|
+
} catch (err) {
|
|
78
|
+
if (process.env.DEBUG) {
|
|
79
|
+
console.log("[Tenant] JWT decode failed:", err.message);
|
|
80
|
+
}
|
|
81
|
+
}
|
|
82
|
+
}
|
|
83
|
+
if (!tenantId && req.headers[headerName.toLowerCase()]) {
|
|
84
|
+
tenantId = req.headers[headerName.toLowerCase()];
|
|
85
|
+
}
|
|
86
|
+
if (tenantId && !isValidUUID(tenantId)) {
|
|
87
|
+
return res.status(400).json({
|
|
88
|
+
error: "Invalid tenant ID format",
|
|
89
|
+
message: "Tenant ID must be a valid UUID"
|
|
90
|
+
});
|
|
91
|
+
}
|
|
92
|
+
if (required && !tenantId) {
|
|
93
|
+
return res.status(401).json({
|
|
94
|
+
error: "Tenant required",
|
|
95
|
+
message: "Request must include tenant context via JWT or X-Tenant-ID header"
|
|
96
|
+
});
|
|
97
|
+
}
|
|
98
|
+
if (tenantId && getTenantInfo) {
|
|
99
|
+
try {
|
|
100
|
+
const tenantInfo = await getTenantInfo(tenantId);
|
|
101
|
+
if (!tenantInfo) {
|
|
102
|
+
return res.status(404).json({
|
|
103
|
+
error: "Tenant not found",
|
|
104
|
+
message: `Tenant with ID ${tenantId} does not exist`
|
|
105
|
+
});
|
|
106
|
+
}
|
|
107
|
+
req.tenant = tenantInfo;
|
|
108
|
+
} catch (err) {
|
|
109
|
+
console.error("[Tenant] Error fetching tenant info:", err);
|
|
110
|
+
return res.status(500).json({
|
|
111
|
+
error: "Tenant lookup failed",
|
|
112
|
+
message: "Unable to verify tenant"
|
|
113
|
+
});
|
|
114
|
+
}
|
|
115
|
+
} else {
|
|
116
|
+
req.tenant = tenantId ? {
|
|
117
|
+
id: tenantId,
|
|
118
|
+
name: tenantName
|
|
119
|
+
} : null;
|
|
120
|
+
}
|
|
121
|
+
next();
|
|
122
|
+
};
|
|
123
|
+
}
|
|
124
|
+
function requireTenant() {
|
|
125
|
+
return (req, res, next) => {
|
|
126
|
+
if (!req.tenant || !req.tenant.id) {
|
|
127
|
+
return res.status(401).json({
|
|
128
|
+
error: "Tenant required",
|
|
129
|
+
message: "This endpoint requires tenant context"
|
|
130
|
+
});
|
|
131
|
+
}
|
|
132
|
+
next();
|
|
133
|
+
};
|
|
134
|
+
}
|
|
135
|
+
function getTenantId(req) {
|
|
136
|
+
return req.tenant?.id || null;
|
|
137
|
+
}
|
|
138
|
+
function assertTenant(req) {
|
|
139
|
+
if (!req.tenant || !req.tenant.id) {
|
|
140
|
+
const error = new Error("Tenant context required");
|
|
141
|
+
error.status = 401;
|
|
142
|
+
throw error;
|
|
143
|
+
}
|
|
144
|
+
return req.tenant;
|
|
145
|
+
}
|
|
146
|
+
function createTenantLookupHandler(findTenantBySlug) {
|
|
147
|
+
return async (req, res) => {
|
|
148
|
+
try {
|
|
149
|
+
const { slug } = req.params;
|
|
150
|
+
if (!slug) {
|
|
151
|
+
return res.status(400).json({
|
|
152
|
+
error: "Validation error",
|
|
153
|
+
message: "Tenant slug is required"
|
|
154
|
+
});
|
|
155
|
+
}
|
|
156
|
+
const tenant = await findTenantBySlug(slug);
|
|
157
|
+
if (!tenant) {
|
|
158
|
+
return res.status(404).json({
|
|
159
|
+
error: "Not found",
|
|
160
|
+
message: "Tenant not found"
|
|
161
|
+
});
|
|
162
|
+
}
|
|
163
|
+
res.json({
|
|
164
|
+
id: tenant.id,
|
|
165
|
+
name: tenant.name,
|
|
166
|
+
slug: tenant.slug,
|
|
167
|
+
settings: {
|
|
168
|
+
allowSelfRegistration: tenant.settings?.allowSelfRegistration || false,
|
|
169
|
+
requireEmailVerification: tenant.settings?.requireEmailVerification || false
|
|
170
|
+
}
|
|
171
|
+
});
|
|
172
|
+
} catch (err) {
|
|
173
|
+
console.error("[Tenant] Lookup error:", err);
|
|
174
|
+
res.status(500).json({
|
|
175
|
+
error: "Lookup failed",
|
|
176
|
+
message: "An unexpected error occurred"
|
|
177
|
+
});
|
|
178
|
+
}
|
|
179
|
+
};
|
|
180
|
+
}
|
|
181
|
+
function createTenantListHandler(listTenants) {
|
|
182
|
+
return async (req, res) => {
|
|
183
|
+
if (process.env.NODE_ENV === "production") {
|
|
184
|
+
return res.status(404).json({ error: "Not found" });
|
|
185
|
+
}
|
|
186
|
+
try {
|
|
187
|
+
const tenants = await listTenants();
|
|
188
|
+
res.json(tenants.map((t) => ({
|
|
189
|
+
id: t.id,
|
|
190
|
+
name: t.name,
|
|
191
|
+
slug: t.slug
|
|
192
|
+
})));
|
|
193
|
+
} catch (err) {
|
|
194
|
+
console.error("[Tenant] List error:", err);
|
|
195
|
+
res.status(500).json({
|
|
196
|
+
error: "List failed",
|
|
197
|
+
message: "An unexpected error occurred"
|
|
198
|
+
});
|
|
199
|
+
}
|
|
200
|
+
};
|
|
201
|
+
}
|
|
202
|
+
|
|
203
|
+
// src/server/services/email-templates.js
|
|
204
|
+
var FONT_STACK = "-apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif";
|
|
205
|
+
function htmlToText(html) {
|
|
206
|
+
return html.replace(/<a\s[^>]*href="([^"]*)"[^>]*>([\s\S]*?)<\/a>/gi, (_, url, label) => {
|
|
207
|
+
const trimmed = label.replace(/<[^>]+>/g, "").trim();
|
|
208
|
+
return trimmed === url ? url : `${trimmed} (${url})`;
|
|
209
|
+
}).replace(/<[^>]+>/g, "").replace(/[ \t]+/g, " ").replace(/\n{3,}/g, "\n\n").trim();
|
|
210
|
+
}
|
|
211
|
+
function emailButton(url, label, brandColor = "#2e7d32") {
|
|
212
|
+
return `<table role="presentation" cellpadding="0" cellspacing="0" border="0" style="margin: 28px auto;">
|
|
213
|
+
<tr>
|
|
214
|
+
<td align="center" style="border-radius: 6px; background-color: ${brandColor};">
|
|
215
|
+
<a href="${url}" target="_blank" style="display: inline-block; padding: 14px 32px; font-family: ${FONT_STACK}; font-size: 16px; font-weight: 600; color: #ffffff; text-decoration: none; border-radius: 6px;">${label}</a>
|
|
216
|
+
</td>
|
|
217
|
+
</tr>
|
|
218
|
+
</table>`;
|
|
219
|
+
}
|
|
220
|
+
function renderEmail({ branding, title, preheader = "", body }) {
|
|
221
|
+
const {
|
|
222
|
+
appName = "App",
|
|
223
|
+
brandColor = "#2e7d32",
|
|
224
|
+
logoUrl,
|
|
225
|
+
appUrl,
|
|
226
|
+
footerText
|
|
227
|
+
} = branding;
|
|
228
|
+
const logoHtml = logoUrl ? `<img src="${logoUrl}" alt="${appName}" style="height: 32px; margin-right: 10px; vertical-align: middle;" />` : "";
|
|
229
|
+
const appNameHtml = appUrl ? `<a href="${appUrl}" style="color: #ffffff; text-decoration: none; font-family: ${FONT_STACK}; font-size: 20px; font-weight: 700; vertical-align: middle;">${appName}</a>` : `<span style="font-family: ${FONT_STACK}; font-size: 20px; font-weight: 700; vertical-align: middle;">${appName}</span>`;
|
|
230
|
+
const footer = footerText || `© ${(/* @__PURE__ */ new Date()).getFullYear()} ${appName}`;
|
|
231
|
+
const preheaderHtml = preheader ? `<div style="display: none; max-height: 0; overflow: hidden; mso-hide: all;">${preheader}</div>` : "";
|
|
232
|
+
const html = `<!DOCTYPE html>
|
|
233
|
+
<html lang="en">
|
|
234
|
+
<head>
|
|
235
|
+
<meta charset="utf-8" />
|
|
236
|
+
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
|
|
237
|
+
<title>${title}</title>
|
|
238
|
+
</head>
|
|
239
|
+
<body style="margin: 0; padding: 0; background-color: #f4f4f7; font-family: ${FONT_STACK};">
|
|
240
|
+
${preheaderHtml}
|
|
241
|
+
<table role="presentation" cellpadding="0" cellspacing="0" border="0" width="100%" style="background-color: #f4f4f7;">
|
|
242
|
+
<tr>
|
|
243
|
+
<td align="center" style="padding: 24px 16px;">
|
|
244
|
+
<!-- Card -->
|
|
245
|
+
<table role="presentation" cellpadding="0" cellspacing="0" border="0" style="max-width: 600px; width: 100%; border-radius: 8px; overflow: hidden; box-shadow: 0 1px 4px rgba(0,0,0,0.1);">
|
|
246
|
+
<!-- Header -->
|
|
247
|
+
<tr>
|
|
248
|
+
<td style="background-color: ${brandColor}; padding: 20px 24px; text-align: center; color: #ffffff;">
|
|
249
|
+
${logoHtml}${appNameHtml}
|
|
250
|
+
</td>
|
|
251
|
+
</tr>
|
|
252
|
+
<!-- Content -->
|
|
253
|
+
<tr>
|
|
254
|
+
<td style="background-color: #ffffff; padding: 32px 24px; font-family: ${FONT_STACK}; font-size: 16px; line-height: 1.5; color: #333333;">
|
|
255
|
+
${body}
|
|
256
|
+
</td>
|
|
257
|
+
</tr>
|
|
258
|
+
<!-- Footer -->
|
|
259
|
+
<tr>
|
|
260
|
+
<td style="background-color: #f0f0f3; padding: 16px 24px; text-align: center; font-family: ${FONT_STACK}; font-size: 13px; color: #888888;">
|
|
261
|
+
${footer}
|
|
262
|
+
</td>
|
|
263
|
+
</tr>
|
|
264
|
+
</table>
|
|
265
|
+
</td>
|
|
266
|
+
</tr>
|
|
267
|
+
</table>
|
|
268
|
+
</body>
|
|
269
|
+
</html>`;
|
|
270
|
+
const text = htmlToText(body);
|
|
271
|
+
return { html, text };
|
|
272
|
+
}
|
|
273
|
+
function passwordResetEmail(branding, { resetUrl, expiryHours = 1 }) {
|
|
274
|
+
const expiryLabel = expiryHours === 1 ? "1 hour" : `${expiryHours} hours`;
|
|
275
|
+
const body = `
|
|
276
|
+
<p style="margin: 0 0 16px;">You requested a password reset. Click the button below to set a new password:</p>
|
|
277
|
+
${emailButton(resetUrl, "Reset Password", branding.brandColor)}
|
|
278
|
+
<p style="margin: 16px 0 0; font-size: 14px; color: #666666;">This link expires in ${expiryLabel}. If you didn't request this, you can safely ignore this email.</p>
|
|
279
|
+
<p style="margin: 16px 0 0; font-size: 13px; color: #999999; word-break: break-all;">Or copy this link: ${resetUrl}</p>`;
|
|
280
|
+
return renderEmail({
|
|
281
|
+
branding,
|
|
282
|
+
title: "Reset your password",
|
|
283
|
+
preheader: `Reset your ${branding.appName || "account"} password`,
|
|
284
|
+
body
|
|
285
|
+
});
|
|
286
|
+
}
|
|
287
|
+
function emailVerificationEmail(branding, { verifyUrl }) {
|
|
288
|
+
const body = `
|
|
289
|
+
<p style="margin: 0 0 16px;">Welcome! Please verify your email address by clicking the button below:</p>
|
|
290
|
+
${emailButton(verifyUrl, "Verify Email", branding.brandColor)}
|
|
291
|
+
<p style="margin: 16px 0 0; font-size: 14px; color: #666666;">If you didn't create an account, you can safely ignore this email.</p>
|
|
292
|
+
<p style="margin: 16px 0 0; font-size: 13px; color: #999999; word-break: break-all;">Or copy this link: ${verifyUrl}</p>`;
|
|
293
|
+
return renderEmail({
|
|
294
|
+
branding,
|
|
295
|
+
title: "Verify your email address",
|
|
296
|
+
preheader: `Verify your ${branding.appName || ""} email`,
|
|
297
|
+
body
|
|
298
|
+
});
|
|
299
|
+
}
|
|
300
|
+
|
|
301
|
+
// src/server/middleware/auth.js
|
|
302
|
+
import passport from "passport";
|
|
303
|
+
import passportJwt from "passport-jwt";
|
|
304
|
+
import jwt2 from "jsonwebtoken";
|
|
305
|
+
import bcrypt from "bcrypt";
|
|
306
|
+
import crypto from "crypto";
|
|
307
|
+
var { Strategy: JwtStrategy, ExtractJwt } = passportJwt;
|
|
308
|
+
var DEFAULT_OPTIONS = {
|
|
309
|
+
jwtSecret: process.env.JWT_SECRET || "avento-secret-change-me",
|
|
310
|
+
jwtExpiry: process.env.JWT_EXPIRY || "24h",
|
|
311
|
+
refreshExpiry: process.env.JWT_REFRESH_EXPIRY || "7d",
|
|
312
|
+
saltRounds: 10
|
|
313
|
+
};
|
|
314
|
+
function configurePassport(options = {}) {
|
|
315
|
+
const opts = { ...DEFAULT_OPTIONS, ...options };
|
|
316
|
+
const jwtOptions = {
|
|
317
|
+
jwtFromRequest: ExtractJwt.fromAuthHeaderAsBearerToken(),
|
|
318
|
+
secretOrKey: opts.jwtSecret,
|
|
319
|
+
passReqToCallback: true
|
|
320
|
+
};
|
|
321
|
+
passport.use(new JwtStrategy(jwtOptions, async (req, payload, done) => {
|
|
322
|
+
try {
|
|
323
|
+
if (!payload.user_id) {
|
|
324
|
+
return done(null, false, { message: "Invalid token payload" });
|
|
325
|
+
}
|
|
326
|
+
if (payload.exp && Date.now() >= payload.exp * 1e3) {
|
|
327
|
+
return done(null, false, { message: "Token expired" });
|
|
328
|
+
}
|
|
329
|
+
const user = {
|
|
330
|
+
id: payload.user_id,
|
|
331
|
+
email: payload.email,
|
|
332
|
+
roles: payload.roles || [],
|
|
333
|
+
tenant_id: payload.tenant_id,
|
|
334
|
+
tenant_name: payload.tenant_name
|
|
335
|
+
};
|
|
336
|
+
return done(null, user);
|
|
337
|
+
} catch (err) {
|
|
338
|
+
return done(err, false);
|
|
339
|
+
}
|
|
340
|
+
}));
|
|
341
|
+
return passport;
|
|
342
|
+
}
|
|
343
|
+
function initAuth(app, options = {}) {
|
|
344
|
+
configurePassport(options);
|
|
345
|
+
app.use(passport.initialize());
|
|
346
|
+
}
|
|
347
|
+
function requireAuth() {
|
|
348
|
+
return (req, res, next) => {
|
|
349
|
+
passport.authenticate("jwt", { session: false }, (err, user, info) => {
|
|
350
|
+
if (err) {
|
|
351
|
+
return res.status(500).json({
|
|
352
|
+
error: "Authentication error",
|
|
353
|
+
message: err.message
|
|
354
|
+
});
|
|
355
|
+
}
|
|
356
|
+
if (!user) {
|
|
357
|
+
return res.status(401).json({
|
|
358
|
+
error: "Unauthorized",
|
|
359
|
+
message: info?.message || "Authentication required"
|
|
360
|
+
});
|
|
361
|
+
}
|
|
362
|
+
req.user = user;
|
|
363
|
+
if (user.tenant_id && !req.tenant) {
|
|
364
|
+
req.tenant = {
|
|
365
|
+
id: user.tenant_id,
|
|
366
|
+
name: user.tenant_name
|
|
367
|
+
};
|
|
368
|
+
}
|
|
369
|
+
next();
|
|
370
|
+
})(req, res, next);
|
|
371
|
+
};
|
|
372
|
+
}
|
|
373
|
+
function optionalAuth() {
|
|
374
|
+
return (req, res, next) => {
|
|
375
|
+
passport.authenticate("jwt", { session: false }, (err, user) => {
|
|
376
|
+
if (user) {
|
|
377
|
+
req.user = user;
|
|
378
|
+
if (user.tenant_id && !req.tenant) {
|
|
379
|
+
req.tenant = {
|
|
380
|
+
id: user.tenant_id,
|
|
381
|
+
name: user.tenant_name
|
|
382
|
+
};
|
|
383
|
+
}
|
|
384
|
+
}
|
|
385
|
+
next();
|
|
386
|
+
})(req, res, next);
|
|
387
|
+
};
|
|
388
|
+
}
|
|
389
|
+
function generateToken(user, tenantId, tenantName, options = {}) {
|
|
390
|
+
const opts = { ...DEFAULT_OPTIONS, ...options };
|
|
391
|
+
const payload = {
|
|
392
|
+
user_id: user.id,
|
|
393
|
+
email: user.email,
|
|
394
|
+
roles: user.roles || [],
|
|
395
|
+
tenant_id: tenantId,
|
|
396
|
+
tenant_name: tenantName
|
|
397
|
+
};
|
|
398
|
+
return jwt2.sign(payload, opts.jwtSecret, {
|
|
399
|
+
expiresIn: opts.jwtExpiry
|
|
400
|
+
});
|
|
401
|
+
}
|
|
402
|
+
function generateRefreshToken(userId, options = {}) {
|
|
403
|
+
const opts = { ...DEFAULT_OPTIONS, ...options };
|
|
404
|
+
return jwt2.sign(
|
|
405
|
+
{ user_id: userId, type: "refresh" },
|
|
406
|
+
opts.jwtSecret,
|
|
407
|
+
{ expiresIn: opts.refreshExpiry }
|
|
408
|
+
);
|
|
409
|
+
}
|
|
410
|
+
function verifyToken(token, options = {}) {
|
|
411
|
+
const opts = { ...DEFAULT_OPTIONS, ...options };
|
|
412
|
+
try {
|
|
413
|
+
return jwt2.verify(token, opts.jwtSecret);
|
|
414
|
+
} catch (err) {
|
|
415
|
+
return null;
|
|
416
|
+
}
|
|
417
|
+
}
|
|
418
|
+
async function hashPassword(password, options = {}) {
|
|
419
|
+
const opts = { ...DEFAULT_OPTIONS, ...options };
|
|
420
|
+
return bcrypt.hash(password, opts.saltRounds);
|
|
421
|
+
}
|
|
422
|
+
async function comparePassword(password, hash) {
|
|
423
|
+
return bcrypt.compare(password, hash);
|
|
424
|
+
}
|
|
425
|
+
function createLoginHandler(findUserByEmail, options = {}) {
|
|
426
|
+
const { getTenantSettings } = options;
|
|
427
|
+
return async (req, res) => {
|
|
428
|
+
try {
|
|
429
|
+
const { email, password, tenant_id } = req.body;
|
|
430
|
+
if (!email || !password) {
|
|
431
|
+
return res.status(400).json({
|
|
432
|
+
error: "Validation error",
|
|
433
|
+
message: "Email and password are required"
|
|
434
|
+
});
|
|
435
|
+
}
|
|
436
|
+
const user = await findUserByEmail(email, tenant_id);
|
|
437
|
+
if (!user) {
|
|
438
|
+
return res.status(401).json({
|
|
439
|
+
error: "Authentication failed",
|
|
440
|
+
message: "Invalid email or password"
|
|
441
|
+
});
|
|
442
|
+
}
|
|
443
|
+
const isValid = await comparePassword(password, user.password_hash);
|
|
444
|
+
if (!isValid) {
|
|
445
|
+
return res.status(401).json({
|
|
446
|
+
error: "Authentication failed",
|
|
447
|
+
message: "Invalid email or password"
|
|
448
|
+
});
|
|
449
|
+
}
|
|
450
|
+
if (getTenantSettings && !user.email_verified_at) {
|
|
451
|
+
try {
|
|
452
|
+
const settings = await getTenantSettings(user.tenant_id);
|
|
453
|
+
if (settings?.requireEmailVerification) {
|
|
454
|
+
return res.status(403).json({
|
|
455
|
+
error: "Email not verified",
|
|
456
|
+
message: "Please verify your email address before logging in"
|
|
457
|
+
});
|
|
458
|
+
}
|
|
459
|
+
} catch (err) {
|
|
460
|
+
console.error("[Auth] Error checking tenant settings:", err);
|
|
461
|
+
}
|
|
462
|
+
}
|
|
463
|
+
const token = generateToken(user, user.tenant_id, user.tenant_name, options);
|
|
464
|
+
const refreshToken = generateRefreshToken(user.id, options);
|
|
465
|
+
res.json({
|
|
466
|
+
token,
|
|
467
|
+
refreshToken,
|
|
468
|
+
user: {
|
|
469
|
+
id: user.id,
|
|
470
|
+
email: user.email,
|
|
471
|
+
roles: user.roles
|
|
472
|
+
},
|
|
473
|
+
tenant: {
|
|
474
|
+
id: user.tenant_id,
|
|
475
|
+
name: user.tenant_name
|
|
476
|
+
}
|
|
477
|
+
});
|
|
478
|
+
} catch (err) {
|
|
479
|
+
console.error("[Auth] Login error:", err);
|
|
480
|
+
res.status(500).json({
|
|
481
|
+
error: "Login failed",
|
|
482
|
+
message: "An unexpected error occurred"
|
|
483
|
+
});
|
|
484
|
+
}
|
|
485
|
+
};
|
|
486
|
+
}
|
|
487
|
+
function generateSecureToken(bytes = 32) {
|
|
488
|
+
return crypto.randomBytes(bytes).toString("hex");
|
|
489
|
+
}
|
|
490
|
+
function generateTokenExpiry(hours = 1) {
|
|
491
|
+
return new Date(Date.now() + hours * 60 * 60 * 1e3).toISOString();
|
|
492
|
+
}
|
|
493
|
+
function createRefreshHandler(findUserById, options = {}) {
|
|
494
|
+
return async (req, res) => {
|
|
495
|
+
try {
|
|
496
|
+
const { refreshToken } = req.body;
|
|
497
|
+
if (!refreshToken) {
|
|
498
|
+
return res.status(400).json({
|
|
499
|
+
error: "Validation error",
|
|
500
|
+
message: "Refresh token is required"
|
|
501
|
+
});
|
|
502
|
+
}
|
|
503
|
+
const decoded = verifyToken(refreshToken, options);
|
|
504
|
+
if (!decoded || decoded.type !== "refresh") {
|
|
505
|
+
return res.status(401).json({
|
|
506
|
+
error: "Invalid token",
|
|
507
|
+
message: "Invalid or expired refresh token"
|
|
508
|
+
});
|
|
509
|
+
}
|
|
510
|
+
const user = await findUserById(decoded.user_id);
|
|
511
|
+
if (!user) {
|
|
512
|
+
return res.status(401).json({
|
|
513
|
+
error: "User not found",
|
|
514
|
+
message: "User no longer exists"
|
|
515
|
+
});
|
|
516
|
+
}
|
|
517
|
+
const token = generateToken(user, user.tenant_id, user.tenant_name, options);
|
|
518
|
+
res.json({ token });
|
|
519
|
+
} catch (err) {
|
|
520
|
+
console.error("[Auth] Refresh error:", err);
|
|
521
|
+
res.status(500).json({
|
|
522
|
+
error: "Refresh failed",
|
|
523
|
+
message: "An unexpected error occurred"
|
|
524
|
+
});
|
|
525
|
+
}
|
|
526
|
+
};
|
|
527
|
+
}
|
|
528
|
+
function isValidEmail(email) {
|
|
529
|
+
return /^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(email);
|
|
530
|
+
}
|
|
531
|
+
function createRegisterHandler(callbacks, options = {}) {
|
|
532
|
+
const {
|
|
533
|
+
findUserByEmail,
|
|
534
|
+
createUser,
|
|
535
|
+
getTenantSettings,
|
|
536
|
+
createToken
|
|
537
|
+
} = callbacks;
|
|
538
|
+
const {
|
|
539
|
+
emailService,
|
|
540
|
+
appUrl = "",
|
|
541
|
+
passwordMinLength = 8,
|
|
542
|
+
emailBranding
|
|
543
|
+
} = options;
|
|
544
|
+
return async (req, res) => {
|
|
545
|
+
try {
|
|
546
|
+
const { email, password, first_name, last_name } = req.body;
|
|
547
|
+
const tenantId = req.tenant?.id;
|
|
548
|
+
if (!email || !password || !first_name || !last_name) {
|
|
549
|
+
return res.status(400).json({
|
|
550
|
+
error: "Validation error",
|
|
551
|
+
message: "Email, password, first name, and last name are required"
|
|
552
|
+
});
|
|
553
|
+
}
|
|
554
|
+
if (!isValidEmail(email)) {
|
|
555
|
+
return res.status(400).json({
|
|
556
|
+
error: "Validation error",
|
|
557
|
+
message: "Invalid email format"
|
|
558
|
+
});
|
|
559
|
+
}
|
|
560
|
+
if (password.length < passwordMinLength) {
|
|
561
|
+
return res.status(400).json({
|
|
562
|
+
error: "Validation error",
|
|
563
|
+
message: `Password must be at least ${passwordMinLength} characters`
|
|
564
|
+
});
|
|
565
|
+
}
|
|
566
|
+
if (!tenantId) {
|
|
567
|
+
return res.status(400).json({
|
|
568
|
+
error: "Validation error",
|
|
569
|
+
message: "Tenant context is required for registration"
|
|
570
|
+
});
|
|
571
|
+
}
|
|
572
|
+
const settings = await getTenantSettings(tenantId);
|
|
573
|
+
if (!settings?.allowSelfRegistration) {
|
|
574
|
+
return res.status(403).json({
|
|
575
|
+
error: "Registration disabled",
|
|
576
|
+
message: "Self-registration is not allowed for this tenant"
|
|
577
|
+
});
|
|
578
|
+
}
|
|
579
|
+
const existingUser = await findUserByEmail(email, tenantId);
|
|
580
|
+
if (existingUser) {
|
|
581
|
+
return res.status(409).json({
|
|
582
|
+
error: "User exists",
|
|
583
|
+
message: "An account with this email already exists"
|
|
584
|
+
});
|
|
585
|
+
}
|
|
586
|
+
const passwordHash = await hashPassword(password);
|
|
587
|
+
const user = await createUser({
|
|
588
|
+
email,
|
|
589
|
+
password_hash: passwordHash,
|
|
590
|
+
first_name,
|
|
591
|
+
last_name,
|
|
592
|
+
tenant_id: tenantId,
|
|
593
|
+
roles: ["user"]
|
|
594
|
+
});
|
|
595
|
+
if (settings.requireEmailVerification) {
|
|
596
|
+
const tokenValue = generateSecureToken();
|
|
597
|
+
await createToken({
|
|
598
|
+
tenant_id: tenantId,
|
|
599
|
+
user_id: user.id,
|
|
600
|
+
token: tokenValue,
|
|
601
|
+
type: "email_verification",
|
|
602
|
+
expires_at: generateTokenExpiry(24)
|
|
603
|
+
});
|
|
604
|
+
if (emailService) {
|
|
605
|
+
const verifyUrl = `${appUrl}/verify-email?token=${tokenValue}`;
|
|
606
|
+
if (emailBranding) {
|
|
607
|
+
const { html, text } = emailVerificationEmail(emailBranding, { verifyUrl });
|
|
608
|
+
await emailService.sendMail({
|
|
609
|
+
to: email,
|
|
610
|
+
subject: "Verify your email address",
|
|
611
|
+
html,
|
|
612
|
+
text
|
|
613
|
+
});
|
|
614
|
+
} else {
|
|
615
|
+
await emailService.sendMail({
|
|
616
|
+
to: email,
|
|
617
|
+
subject: "Verify your email address",
|
|
618
|
+
html: `<p>Welcome! Please verify your email by clicking the link below:</p><p><a href="${verifyUrl}">${verifyUrl}</a></p>`,
|
|
619
|
+
text: `Welcome! Please verify your email by visiting: ${verifyUrl}`
|
|
620
|
+
});
|
|
621
|
+
}
|
|
622
|
+
}
|
|
623
|
+
return res.status(201).json({
|
|
624
|
+
success: true,
|
|
625
|
+
message: "Registration successful. Please check your email to verify your account.",
|
|
626
|
+
requiresVerification: true
|
|
627
|
+
});
|
|
628
|
+
}
|
|
629
|
+
const token = generateToken(user, tenantId, req.tenant?.name, options);
|
|
630
|
+
const refreshTokenValue = generateRefreshToken(user.id, options);
|
|
631
|
+
res.status(201).json({
|
|
632
|
+
success: true,
|
|
633
|
+
token,
|
|
634
|
+
refreshToken: refreshTokenValue,
|
|
635
|
+
user: {
|
|
636
|
+
id: user.id,
|
|
637
|
+
email: user.email,
|
|
638
|
+
roles: user.roles,
|
|
639
|
+
first_name: user.first_name || first_name || "",
|
|
640
|
+
last_name: user.last_name || last_name || ""
|
|
641
|
+
},
|
|
642
|
+
tenant: {
|
|
643
|
+
id: tenantId,
|
|
644
|
+
name: req.tenant?.name
|
|
645
|
+
}
|
|
646
|
+
});
|
|
647
|
+
} catch (err) {
|
|
648
|
+
console.error("[Auth] Register error:", err);
|
|
649
|
+
res.status(500).json({
|
|
650
|
+
error: "Registration failed",
|
|
651
|
+
message: "An unexpected error occurred"
|
|
652
|
+
});
|
|
653
|
+
}
|
|
654
|
+
};
|
|
655
|
+
}
|
|
656
|
+
function createForgotPasswordHandler(callbacks, options = {}) {
|
|
657
|
+
const {
|
|
658
|
+
findUserByEmail,
|
|
659
|
+
createToken,
|
|
660
|
+
invalidateExistingTokens
|
|
661
|
+
} = callbacks;
|
|
662
|
+
const {
|
|
663
|
+
emailService,
|
|
664
|
+
appUrl = "",
|
|
665
|
+
tokenExpiryHours = 1,
|
|
666
|
+
emailBranding
|
|
667
|
+
} = options;
|
|
668
|
+
return async (req, res) => {
|
|
669
|
+
try {
|
|
670
|
+
const { email } = req.body;
|
|
671
|
+
const tenantId = req.tenant?.id;
|
|
672
|
+
if (!email) {
|
|
673
|
+
return res.status(400).json({
|
|
674
|
+
error: "Validation error",
|
|
675
|
+
message: "Email is required"
|
|
676
|
+
});
|
|
677
|
+
}
|
|
678
|
+
const genericResponse = {
|
|
679
|
+
success: true,
|
|
680
|
+
message: "If an account exists with that email, a password reset link has been sent"
|
|
681
|
+
};
|
|
682
|
+
if (!tenantId) {
|
|
683
|
+
return res.json(genericResponse);
|
|
684
|
+
}
|
|
685
|
+
const user = await findUserByEmail(email, tenantId);
|
|
686
|
+
if (!user) {
|
|
687
|
+
return res.json(genericResponse);
|
|
688
|
+
}
|
|
689
|
+
if (invalidateExistingTokens) {
|
|
690
|
+
await invalidateExistingTokens(user.id, "password_reset");
|
|
691
|
+
}
|
|
692
|
+
const tokenValue = generateSecureToken();
|
|
693
|
+
await createToken({
|
|
694
|
+
tenant_id: tenantId,
|
|
695
|
+
user_id: user.id,
|
|
696
|
+
token: tokenValue,
|
|
697
|
+
type: "password_reset",
|
|
698
|
+
expires_at: generateTokenExpiry(tokenExpiryHours)
|
|
699
|
+
});
|
|
700
|
+
if (emailService) {
|
|
701
|
+
const resetUrl = `${appUrl}/reset-password?token=${tokenValue}`;
|
|
702
|
+
if (emailBranding) {
|
|
703
|
+
const { html, text } = passwordResetEmail(emailBranding, { resetUrl, expiryHours: tokenExpiryHours });
|
|
704
|
+
await emailService.sendMail({
|
|
705
|
+
to: email,
|
|
706
|
+
subject: "Reset your password",
|
|
707
|
+
html,
|
|
708
|
+
text
|
|
709
|
+
});
|
|
710
|
+
} else {
|
|
711
|
+
await emailService.sendMail({
|
|
712
|
+
to: email,
|
|
713
|
+
subject: "Reset your password",
|
|
714
|
+
html: `<p>You requested a password reset. Click the link below to set a new password:</p><p><a href="${resetUrl}">${resetUrl}</a></p><p>This link expires in ${tokenExpiryHours} hour(s).</p>`,
|
|
715
|
+
text: `You requested a password reset. Visit this link to set a new password: ${resetUrl}
|
|
716
|
+
|
|
717
|
+
This link expires in ${tokenExpiryHours} hour(s).`
|
|
718
|
+
});
|
|
719
|
+
}
|
|
720
|
+
}
|
|
721
|
+
res.json(genericResponse);
|
|
722
|
+
} catch (err) {
|
|
723
|
+
console.error("[Auth] Forgot password error:", err);
|
|
724
|
+
res.status(500).json({
|
|
725
|
+
error: "Request failed",
|
|
726
|
+
message: "An unexpected error occurred"
|
|
727
|
+
});
|
|
728
|
+
}
|
|
729
|
+
};
|
|
730
|
+
}
|
|
731
|
+
function createResetPasswordHandler(callbacks, options = {}) {
|
|
732
|
+
const {
|
|
733
|
+
findValidToken,
|
|
734
|
+
updateUserPassword,
|
|
735
|
+
markTokenUsed
|
|
736
|
+
} = callbacks;
|
|
737
|
+
const { passwordMinLength = 8 } = options;
|
|
738
|
+
return async (req, res) => {
|
|
739
|
+
try {
|
|
740
|
+
const { token, password } = req.body;
|
|
741
|
+
if (!token || !password) {
|
|
742
|
+
return res.status(400).json({
|
|
743
|
+
error: "Validation error",
|
|
744
|
+
message: "Token and new password are required"
|
|
745
|
+
});
|
|
746
|
+
}
|
|
747
|
+
if (password.length < passwordMinLength) {
|
|
748
|
+
return res.status(400).json({
|
|
749
|
+
error: "Validation error",
|
|
750
|
+
message: `Password must be at least ${passwordMinLength} characters`
|
|
751
|
+
});
|
|
752
|
+
}
|
|
753
|
+
const tokenRecord = await findValidToken(token, "password_reset");
|
|
754
|
+
if (!tokenRecord) {
|
|
755
|
+
return res.status(400).json({
|
|
756
|
+
error: "Invalid token",
|
|
757
|
+
message: "This reset link is invalid or has expired"
|
|
758
|
+
});
|
|
759
|
+
}
|
|
760
|
+
const passwordHash = await hashPassword(password);
|
|
761
|
+
await updateUserPassword(tokenRecord.user_id, passwordHash);
|
|
762
|
+
await markTokenUsed(tokenRecord.id);
|
|
763
|
+
res.json({
|
|
764
|
+
success: true,
|
|
765
|
+
message: "Password has been reset successfully"
|
|
766
|
+
});
|
|
767
|
+
} catch (err) {
|
|
768
|
+
console.error("[Auth] Reset password error:", err);
|
|
769
|
+
res.status(500).json({
|
|
770
|
+
error: "Reset failed",
|
|
771
|
+
message: "An unexpected error occurred"
|
|
772
|
+
});
|
|
773
|
+
}
|
|
774
|
+
};
|
|
775
|
+
}
|
|
776
|
+
function createVerifyEmailHandler(callbacks) {
|
|
777
|
+
const {
|
|
778
|
+
findValidToken,
|
|
779
|
+
markUserEmailVerified,
|
|
780
|
+
markTokenUsed
|
|
781
|
+
} = callbacks;
|
|
782
|
+
return async (req, res) => {
|
|
783
|
+
try {
|
|
784
|
+
const token = req.body.token || req.query.token;
|
|
785
|
+
if (!token) {
|
|
786
|
+
return res.status(400).json({
|
|
787
|
+
error: "Validation error",
|
|
788
|
+
message: "Verification token is required"
|
|
789
|
+
});
|
|
790
|
+
}
|
|
791
|
+
const tokenRecord = await findValidToken(token, "email_verification");
|
|
792
|
+
if (!tokenRecord) {
|
|
793
|
+
return res.status(400).json({
|
|
794
|
+
error: "Invalid token",
|
|
795
|
+
message: "This verification link is invalid or has expired"
|
|
796
|
+
});
|
|
797
|
+
}
|
|
798
|
+
await markUserEmailVerified(tokenRecord.user_id);
|
|
799
|
+
await markTokenUsed(tokenRecord.id);
|
|
800
|
+
res.json({
|
|
801
|
+
success: true,
|
|
802
|
+
message: "Email verified successfully. You can now log in."
|
|
803
|
+
});
|
|
804
|
+
} catch (err) {
|
|
805
|
+
console.error("[Auth] Verify email error:", err);
|
|
806
|
+
res.status(500).json({
|
|
807
|
+
error: "Verification failed",
|
|
808
|
+
message: "An unexpected error occurred"
|
|
809
|
+
});
|
|
810
|
+
}
|
|
811
|
+
};
|
|
812
|
+
}
|
|
813
|
+
|
|
814
|
+
// src/server/middleware/permissions.js
|
|
815
|
+
function hasAnyRole(userRoles, requiredRoles) {
|
|
816
|
+
if (!userRoles || !Array.isArray(userRoles))
|
|
817
|
+
return false;
|
|
818
|
+
if (!requiredRoles || requiredRoles.length === 0)
|
|
819
|
+
return true;
|
|
820
|
+
return requiredRoles.some((role) => userRoles.includes(role));
|
|
821
|
+
}
|
|
822
|
+
function hasAllRoles(userRoles, requiredRoles) {
|
|
823
|
+
if (!userRoles || !Array.isArray(userRoles))
|
|
824
|
+
return false;
|
|
825
|
+
if (!requiredRoles || requiredRoles.length === 0)
|
|
826
|
+
return true;
|
|
827
|
+
return requiredRoles.every((role) => userRoles.includes(role));
|
|
828
|
+
}
|
|
829
|
+
function requireRoles(...roles) {
|
|
830
|
+
return (req, res, next) => {
|
|
831
|
+
if (!req.user) {
|
|
832
|
+
return res.status(401).json({
|
|
833
|
+
error: "Unauthorized",
|
|
834
|
+
message: "Authentication required"
|
|
835
|
+
});
|
|
836
|
+
}
|
|
837
|
+
if (!hasAnyRole(req.user.roles, roles)) {
|
|
838
|
+
return res.status(403).json({
|
|
839
|
+
error: "Forbidden",
|
|
840
|
+
message: `This action requires one of the following roles: ${roles.join(", ")}`
|
|
841
|
+
});
|
|
842
|
+
}
|
|
843
|
+
next();
|
|
844
|
+
};
|
|
845
|
+
}
|
|
846
|
+
function requireAllRoles(...roles) {
|
|
847
|
+
return (req, res, next) => {
|
|
848
|
+
if (!req.user) {
|
|
849
|
+
return res.status(401).json({
|
|
850
|
+
error: "Unauthorized",
|
|
851
|
+
message: "Authentication required"
|
|
852
|
+
});
|
|
853
|
+
}
|
|
854
|
+
if (!hasAllRoles(req.user.roles, roles)) {
|
|
855
|
+
return res.status(403).json({
|
|
856
|
+
error: "Forbidden",
|
|
857
|
+
message: `This action requires all of the following roles: ${roles.join(", ")}`
|
|
858
|
+
});
|
|
859
|
+
}
|
|
860
|
+
next();
|
|
861
|
+
};
|
|
862
|
+
}
|
|
863
|
+
function requireAdmin() {
|
|
864
|
+
return requireRoles("admin");
|
|
865
|
+
}
|
|
866
|
+
function hasPermission(userPermissions, requiredPermission) {
|
|
867
|
+
if (!userPermissions || !Array.isArray(userPermissions))
|
|
868
|
+
return false;
|
|
869
|
+
return userPermissions.includes(requiredPermission);
|
|
870
|
+
}
|
|
871
|
+
function hasAnyPermission(userPermissions, requiredPermissions) {
|
|
872
|
+
if (!requiredPermissions || requiredPermissions.length === 0)
|
|
873
|
+
return true;
|
|
874
|
+
if (!userPermissions || !Array.isArray(userPermissions))
|
|
875
|
+
return false;
|
|
876
|
+
return requiredPermissions.some((p) => userPermissions.includes(p));
|
|
877
|
+
}
|
|
878
|
+
function requirePermission(permission) {
|
|
879
|
+
return (req, res, next) => {
|
|
880
|
+
if (!req.user) {
|
|
881
|
+
return res.status(401).json({ error: "Unauthorized", message: "Authentication required" });
|
|
882
|
+
}
|
|
883
|
+
if (!hasPermission(req.user.permissions, permission)) {
|
|
884
|
+
return res.status(403).json({ error: "Forbidden", message: "Insufficient permissions" });
|
|
885
|
+
}
|
|
886
|
+
next();
|
|
887
|
+
};
|
|
888
|
+
}
|
|
889
|
+
function createPermissionChecker(schemaPermissions) {
|
|
890
|
+
return {
|
|
891
|
+
/**
|
|
892
|
+
* Check if user can perform operation.
|
|
893
|
+
* Checks user.permissions first, then user.roles (backward compat).
|
|
894
|
+
*/
|
|
895
|
+
canPerform(user, operation) {
|
|
896
|
+
const allowedList = schemaPermissions[operation];
|
|
897
|
+
if (!allowedList)
|
|
898
|
+
return false;
|
|
899
|
+
if (user?.permissions?.length && allowedList.some((p) => user.permissions.includes(p)))
|
|
900
|
+
return true;
|
|
901
|
+
return hasAnyRole(user?.roles, allowedList);
|
|
902
|
+
},
|
|
903
|
+
/**
|
|
904
|
+
* Middleware for checking read permission
|
|
905
|
+
*/
|
|
906
|
+
canRead() {
|
|
907
|
+
return this._createMiddleware("read");
|
|
908
|
+
},
|
|
909
|
+
/**
|
|
910
|
+
* Middleware for checking create permission
|
|
911
|
+
*/
|
|
912
|
+
canCreate() {
|
|
913
|
+
return this._createMiddleware("create");
|
|
914
|
+
},
|
|
915
|
+
/**
|
|
916
|
+
* Middleware for checking update permission
|
|
917
|
+
*/
|
|
918
|
+
canUpdate() {
|
|
919
|
+
return this._createMiddleware("update");
|
|
920
|
+
},
|
|
921
|
+
/**
|
|
922
|
+
* Middleware for checking delete permission
|
|
923
|
+
*/
|
|
924
|
+
canDelete() {
|
|
925
|
+
return this._createMiddleware("delete");
|
|
926
|
+
},
|
|
927
|
+
/**
|
|
928
|
+
* Create middleware for a specific operation.
|
|
929
|
+
* Checks user.permissions first, then user.roles (backward compat).
|
|
930
|
+
*/
|
|
931
|
+
_createMiddleware(operation) {
|
|
932
|
+
const allowedList = schemaPermissions[operation] || [];
|
|
933
|
+
return (req, res, next) => {
|
|
934
|
+
if (!req.user) {
|
|
935
|
+
return res.status(401).json({
|
|
936
|
+
error: "Unauthorized",
|
|
937
|
+
message: "Authentication required"
|
|
938
|
+
});
|
|
939
|
+
}
|
|
940
|
+
const hasAccess = req.user.permissions?.some((p) => allowedList.includes(p)) || hasAnyRole(req.user.roles, allowedList);
|
|
941
|
+
if (!hasAccess) {
|
|
942
|
+
return res.status(403).json({
|
|
943
|
+
error: "Forbidden",
|
|
944
|
+
message: `You don't have permission to ${operation} this resource`
|
|
945
|
+
});
|
|
946
|
+
}
|
|
947
|
+
next();
|
|
948
|
+
};
|
|
949
|
+
}
|
|
950
|
+
};
|
|
951
|
+
}
|
|
952
|
+
function requireOwnership(getOwnerId) {
|
|
953
|
+
return async (req, res, next) => {
|
|
954
|
+
if (!req.user) {
|
|
955
|
+
return res.status(401).json({
|
|
956
|
+
error: "Unauthorized",
|
|
957
|
+
message: "Authentication required"
|
|
958
|
+
});
|
|
959
|
+
}
|
|
960
|
+
if (req.user.roles?.includes("admin")) {
|
|
961
|
+
return next();
|
|
962
|
+
}
|
|
963
|
+
try {
|
|
964
|
+
const ownerId = await getOwnerId(req);
|
|
965
|
+
if (ownerId !== req.user.id) {
|
|
966
|
+
return res.status(403).json({
|
|
967
|
+
error: "Forbidden",
|
|
968
|
+
message: "You can only access your own resources"
|
|
969
|
+
});
|
|
970
|
+
}
|
|
971
|
+
next();
|
|
972
|
+
} catch (err) {
|
|
973
|
+
console.error("[Permissions] Ownership check error:", err);
|
|
974
|
+
return res.status(500).json({
|
|
975
|
+
error: "Permission check failed",
|
|
976
|
+
message: "Unable to verify resource ownership"
|
|
977
|
+
});
|
|
978
|
+
}
|
|
979
|
+
};
|
|
980
|
+
}
|
|
981
|
+
|
|
982
|
+
// src/server/middleware/can-flags.js
|
|
983
|
+
function computeCanFlags(user, schema, record = null, availableTransitions = []) {
|
|
984
|
+
const perms = user?.permissions || [];
|
|
985
|
+
const roles = user?.roles || [];
|
|
986
|
+
const prefix = schema?._meta?.permissionPrefix;
|
|
987
|
+
const ownerField = schema?._meta?.ownershipField;
|
|
988
|
+
const schemaPerms = schema?.permissions || {};
|
|
989
|
+
function isOwner() {
|
|
990
|
+
if (!ownerField || !record || !user?.id)
|
|
991
|
+
return false;
|
|
992
|
+
return String(record[ownerField]) === String(user.id);
|
|
993
|
+
}
|
|
994
|
+
function hasLegacyAccess(op) {
|
|
995
|
+
const allowed = schemaPerms[op];
|
|
996
|
+
if (!allowed || allowed.length === 0)
|
|
997
|
+
return true;
|
|
998
|
+
return roles.some((r) => allowed.includes(r));
|
|
999
|
+
}
|
|
1000
|
+
function canOp(op) {
|
|
1001
|
+
if (perms.length > 0) {
|
|
1002
|
+
if (perms.includes(`${prefix}.${op}.any`))
|
|
1003
|
+
return true;
|
|
1004
|
+
if (perms.includes(`${prefix}.${op}.own`) && isOwner())
|
|
1005
|
+
return true;
|
|
1006
|
+
if (perms.includes(`${prefix}.${op}`))
|
|
1007
|
+
return true;
|
|
1008
|
+
const schemaList = schemaPerms[op] || [];
|
|
1009
|
+
if (schemaList.length > 0 && schemaList.some((p) => perms.includes(p)))
|
|
1010
|
+
return true;
|
|
1011
|
+
return false;
|
|
1012
|
+
}
|
|
1013
|
+
return hasLegacyAccess(op);
|
|
1014
|
+
}
|
|
1015
|
+
const flags = {
|
|
1016
|
+
read: canOp("read"),
|
|
1017
|
+
create: canOp("create"),
|
|
1018
|
+
update: canOp("update"),
|
|
1019
|
+
delete: canOp("delete")
|
|
1020
|
+
};
|
|
1021
|
+
if (perms.length > 0) {
|
|
1022
|
+
for (const field of schema?.fields || []) {
|
|
1023
|
+
if (field.permission) {
|
|
1024
|
+
const fp = field.permission;
|
|
1025
|
+
const canRead = flags.read && perms.includes(`${fp}.read`);
|
|
1026
|
+
const canWrite = flags.update && perms.includes(`${fp}.write`);
|
|
1027
|
+
if (!canRead || !canWrite) {
|
|
1028
|
+
flags[field.name] = { read: canRead, write: canWrite };
|
|
1029
|
+
}
|
|
1030
|
+
}
|
|
1031
|
+
}
|
|
1032
|
+
}
|
|
1033
|
+
for (const action of schema?._meta?.actions || []) {
|
|
1034
|
+
if (action.permission) {
|
|
1035
|
+
if (perms.length > 0) {
|
|
1036
|
+
flags[action.name] = perms.includes(action.permission);
|
|
1037
|
+
} else {
|
|
1038
|
+
flags[action.name] = flags.update;
|
|
1039
|
+
}
|
|
1040
|
+
}
|
|
1041
|
+
}
|
|
1042
|
+
if (availableTransitions.length > 0) {
|
|
1043
|
+
flags._transitions = availableTransitions.map((t) => t.name || t.action);
|
|
1044
|
+
}
|
|
1045
|
+
return flags;
|
|
1046
|
+
}
|
|
1047
|
+
function attachCanFlags(schema) {
|
|
1048
|
+
return (req, res, next) => {
|
|
1049
|
+
const originalJson = res.json.bind(res);
|
|
1050
|
+
res.json = (data) => {
|
|
1051
|
+
if (data && typeof data === "object" && !Array.isArray(data) && !data.error) {
|
|
1052
|
+
const flags = computeCanFlags(req.user, schema, data);
|
|
1053
|
+
return originalJson({ ...data, _can: flags });
|
|
1054
|
+
}
|
|
1055
|
+
return originalJson(data);
|
|
1056
|
+
};
|
|
1057
|
+
next();
|
|
1058
|
+
};
|
|
1059
|
+
}
|
|
1060
|
+
|
|
1061
|
+
// src/server/middleware/entityRoles.js
|
|
1062
|
+
async function ensureEntityRolesTable(db) {
|
|
1063
|
+
await db.query(`
|
|
1064
|
+
CREATE TABLE IF NOT EXISTS user_entity_roles (
|
|
1065
|
+
id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
|
|
1066
|
+
tenant_id UUID NOT NULL REFERENCES tenants(id),
|
|
1067
|
+
user_id UUID NOT NULL REFERENCES users(id) ON DELETE CASCADE,
|
|
1068
|
+
entity_type TEXT NOT NULL,
|
|
1069
|
+
entity_id UUID NOT NULL,
|
|
1070
|
+
role TEXT NOT NULL,
|
|
1071
|
+
created_at TIMESTAMPTZ NOT NULL DEFAULT NOW(),
|
|
1072
|
+
created_by UUID REFERENCES users(id),
|
|
1073
|
+
UNIQUE (tenant_id, user_id, entity_type, entity_id, role)
|
|
1074
|
+
)
|
|
1075
|
+
`);
|
|
1076
|
+
await db.query(`
|
|
1077
|
+
CREATE INDEX IF NOT EXISTS idx_uer_user_id ON user_entity_roles (user_id)
|
|
1078
|
+
`);
|
|
1079
|
+
await db.query(`
|
|
1080
|
+
CREATE INDEX IF NOT EXISTS idx_uer_entity ON user_entity_roles (entity_type, entity_id)
|
|
1081
|
+
`);
|
|
1082
|
+
}
|
|
1083
|
+
async function hasEntityRole(db, tenantId, userId, entityType, entityId, roles) {
|
|
1084
|
+
const result = await db.query(
|
|
1085
|
+
`SELECT 1 FROM user_entity_roles
|
|
1086
|
+
WHERE tenant_id = $1
|
|
1087
|
+
AND user_id = $2
|
|
1088
|
+
AND entity_type = $3
|
|
1089
|
+
AND entity_id = $4
|
|
1090
|
+
AND role = ANY($5)
|
|
1091
|
+
LIMIT 1`,
|
|
1092
|
+
[tenantId, userId, entityType, entityId, roles]
|
|
1093
|
+
);
|
|
1094
|
+
return result.rows.length > 0;
|
|
1095
|
+
}
|
|
1096
|
+
function requireEntityRoleOr(entityType, getEntityId, ...globalRoles) {
|
|
1097
|
+
return async (req, res, next) => {
|
|
1098
|
+
try {
|
|
1099
|
+
const userRoles = req.user?.roles || [];
|
|
1100
|
+
if (globalRoles.some((r) => userRoles.includes(r))) {
|
|
1101
|
+
return next();
|
|
1102
|
+
}
|
|
1103
|
+
const entityId = await getEntityId(req);
|
|
1104
|
+
if (!entityId) {
|
|
1105
|
+
return res.status(403).json({ error: "Insufficient permissions" });
|
|
1106
|
+
}
|
|
1107
|
+
const has = await hasEntityRole(
|
|
1108
|
+
req.db,
|
|
1109
|
+
req.tenant.id,
|
|
1110
|
+
req.user.id,
|
|
1111
|
+
entityType,
|
|
1112
|
+
entityId,
|
|
1113
|
+
[entityType.toUpperCase() + "_MAINTAINER"]
|
|
1114
|
+
// convention: COURSE_MAINTAINER, etc.
|
|
1115
|
+
);
|
|
1116
|
+
if (has)
|
|
1117
|
+
return next();
|
|
1118
|
+
return res.status(403).json({ error: "Insufficient permissions" });
|
|
1119
|
+
} catch (err) {
|
|
1120
|
+
console.error("[requireEntityRoleOr] Error:", err);
|
|
1121
|
+
return res.status(500).json({ error: "Permission check failed" });
|
|
1122
|
+
}
|
|
1123
|
+
};
|
|
1124
|
+
}
|
|
1125
|
+
|
|
1126
|
+
// src/server/db/index.js
|
|
1127
|
+
var db_exports = {};
|
|
1128
|
+
__export(db_exports, {
|
|
1129
|
+
MongoConnection: () => MongoConnection,
|
|
1130
|
+
PostgresConnection: () => PostgresConnection,
|
|
1131
|
+
createMongoConnection: () => createMongoConnection,
|
|
1132
|
+
createPostgresConnection: () => createPostgresConnection,
|
|
1133
|
+
getMongoConnection: () => getMongoConnection,
|
|
1134
|
+
getPostgresConnection: () => getPostgresConnection,
|
|
1135
|
+
mongoose: () => mongoose
|
|
1136
|
+
});
|
|
1137
|
+
|
|
1138
|
+
// src/server/db/postgres.js
|
|
1139
|
+
import pg from "pg";
|
|
1140
|
+
var { Pool } = pg;
|
|
1141
|
+
var PostgresConnection = class {
|
|
1142
|
+
constructor(config = {}) {
|
|
1143
|
+
this.config = {
|
|
1144
|
+
host: config.host || process.env.POSTGRES_HOST || "localhost",
|
|
1145
|
+
port: config.port || process.env.POSTGRES_PORT || 5432,
|
|
1146
|
+
database: config.database || process.env.POSTGRES_DB || "avento",
|
|
1147
|
+
user: config.user || process.env.POSTGRES_USER || "postgres",
|
|
1148
|
+
password: config.password || process.env.POSTGRES_PASSWORD || "",
|
|
1149
|
+
max: config.maxConnections || 20,
|
|
1150
|
+
idleTimeoutMillis: config.idleTimeout || 3e4,
|
|
1151
|
+
connectionTimeoutMillis: config.connectionTimeout || 2e3
|
|
1152
|
+
};
|
|
1153
|
+
if (config.keepAlive) {
|
|
1154
|
+
this.config.keepAlive = true;
|
|
1155
|
+
if (config.keepAliveInitialDelayMillis != null) {
|
|
1156
|
+
this.config.keepAliveInitialDelayMillis = config.keepAliveInitialDelayMillis;
|
|
1157
|
+
}
|
|
1158
|
+
}
|
|
1159
|
+
this.pool = null;
|
|
1160
|
+
}
|
|
1161
|
+
/**
|
|
1162
|
+
* Initialize the connection pool
|
|
1163
|
+
*/
|
|
1164
|
+
async connect() {
|
|
1165
|
+
if (this.pool) {
|
|
1166
|
+
return this.pool;
|
|
1167
|
+
}
|
|
1168
|
+
this.pool = new Pool(this.config);
|
|
1169
|
+
try {
|
|
1170
|
+
const client = await this.pool.connect();
|
|
1171
|
+
client.release();
|
|
1172
|
+
console.log(`[Postgres] Connected to ${this.config.host}:${this.config.port}/${this.config.database}`);
|
|
1173
|
+
} catch (err) {
|
|
1174
|
+
console.error("[Postgres] Connection failed:", err.message);
|
|
1175
|
+
throw err;
|
|
1176
|
+
}
|
|
1177
|
+
this.pool.on("error", (err) => {
|
|
1178
|
+
console.error("[Postgres] Unexpected error on idle client:", err);
|
|
1179
|
+
});
|
|
1180
|
+
return this.pool;
|
|
1181
|
+
}
|
|
1182
|
+
/**
|
|
1183
|
+
* Execute a query
|
|
1184
|
+
* @param {string} text - SQL query
|
|
1185
|
+
* @param {Array} params - Query parameters
|
|
1186
|
+
* @returns {Promise<Object>} Query result
|
|
1187
|
+
*/
|
|
1188
|
+
async query(text, params = []) {
|
|
1189
|
+
if (!this.pool) {
|
|
1190
|
+
await this.connect();
|
|
1191
|
+
}
|
|
1192
|
+
const start = Date.now();
|
|
1193
|
+
const result = await this.pool.query(text, params);
|
|
1194
|
+
const duration = Date.now() - start;
|
|
1195
|
+
if (process.env.DEBUG_SQL) {
|
|
1196
|
+
console.log("[Postgres] Query:", { text, params, duration: `${duration}ms`, rows: result.rowCount });
|
|
1197
|
+
}
|
|
1198
|
+
return result;
|
|
1199
|
+
}
|
|
1200
|
+
/**
|
|
1201
|
+
* Get a client from the pool for transactions
|
|
1202
|
+
* @returns {Promise<Object>} Client with release() method
|
|
1203
|
+
*/
|
|
1204
|
+
async getClient() {
|
|
1205
|
+
if (!this.pool) {
|
|
1206
|
+
await this.connect();
|
|
1207
|
+
}
|
|
1208
|
+
return this.pool.connect();
|
|
1209
|
+
}
|
|
1210
|
+
/**
|
|
1211
|
+
* Execute a transaction
|
|
1212
|
+
* @param {Function} callback - Async function receiving client
|
|
1213
|
+
* @returns {Promise<any>} Result from callback
|
|
1214
|
+
*/
|
|
1215
|
+
async transaction(callback) {
|
|
1216
|
+
const client = await this.getClient();
|
|
1217
|
+
try {
|
|
1218
|
+
await client.query("BEGIN");
|
|
1219
|
+
const result = await callback(client);
|
|
1220
|
+
await client.query("COMMIT");
|
|
1221
|
+
return result;
|
|
1222
|
+
} catch (err) {
|
|
1223
|
+
await client.query("ROLLBACK");
|
|
1224
|
+
throw err;
|
|
1225
|
+
} finally {
|
|
1226
|
+
client.release();
|
|
1227
|
+
}
|
|
1228
|
+
}
|
|
1229
|
+
/**
|
|
1230
|
+
* Close all connections
|
|
1231
|
+
*/
|
|
1232
|
+
async disconnect() {
|
|
1233
|
+
if (this.pool) {
|
|
1234
|
+
await this.pool.end();
|
|
1235
|
+
this.pool = null;
|
|
1236
|
+
console.log("[Postgres] Disconnected");
|
|
1237
|
+
}
|
|
1238
|
+
}
|
|
1239
|
+
};
|
|
1240
|
+
var defaultConnection = null;
|
|
1241
|
+
function getPostgresConnection(config) {
|
|
1242
|
+
if (!defaultConnection) {
|
|
1243
|
+
defaultConnection = new PostgresConnection(config);
|
|
1244
|
+
}
|
|
1245
|
+
return defaultConnection;
|
|
1246
|
+
}
|
|
1247
|
+
function createPostgresConnection(config) {
|
|
1248
|
+
return new PostgresConnection(config);
|
|
1249
|
+
}
|
|
1250
|
+
|
|
1251
|
+
// src/server/db/mongo.js
|
|
1252
|
+
import mongoose from "mongoose";
|
|
1253
|
+
var MongoConnection = class {
|
|
1254
|
+
constructor(config = {}) {
|
|
1255
|
+
this.config = {
|
|
1256
|
+
host: config.host || process.env.MONGO_HOST || "localhost",
|
|
1257
|
+
port: config.port || process.env.MONGO_PORT || 27017,
|
|
1258
|
+
database: config.database || process.env.MONGO_DB || "avento",
|
|
1259
|
+
user: config.user || process.env.MONGO_USER || "",
|
|
1260
|
+
password: config.password || process.env.MONGO_PASSWORD || "",
|
|
1261
|
+
options: config.options || {}
|
|
1262
|
+
};
|
|
1263
|
+
this.connection = null;
|
|
1264
|
+
}
|
|
1265
|
+
/**
|
|
1266
|
+
* Build MongoDB connection URI
|
|
1267
|
+
*/
|
|
1268
|
+
_buildUri() {
|
|
1269
|
+
const { host, port, database, user, password } = this.config;
|
|
1270
|
+
if (user && password) {
|
|
1271
|
+
return `mongodb://${encodeURIComponent(user)}:${encodeURIComponent(password)}@${host}:${port}/${database}`;
|
|
1272
|
+
}
|
|
1273
|
+
return `mongodb://${host}:${port}/${database}`;
|
|
1274
|
+
}
|
|
1275
|
+
/**
|
|
1276
|
+
* Connect to MongoDB
|
|
1277
|
+
*/
|
|
1278
|
+
async connect() {
|
|
1279
|
+
if (this.connection && this.connection.readyState === 1) {
|
|
1280
|
+
return this.connection;
|
|
1281
|
+
}
|
|
1282
|
+
const uri = this.config.uri || this._buildUri();
|
|
1283
|
+
const options = {
|
|
1284
|
+
maxPoolSize: 10,
|
|
1285
|
+
serverSelectionTimeoutMS: 5e3,
|
|
1286
|
+
socketTimeoutMS: 45e3,
|
|
1287
|
+
...this.config.options
|
|
1288
|
+
};
|
|
1289
|
+
try {
|
|
1290
|
+
this.connection = await mongoose.connect(uri, options);
|
|
1291
|
+
console.log(`[MongoDB] Connected to ${this.config.host}:${this.config.port}/${this.config.database}`);
|
|
1292
|
+
mongoose.connection.on("error", (err) => {
|
|
1293
|
+
console.error("[MongoDB] Connection error:", err);
|
|
1294
|
+
});
|
|
1295
|
+
mongoose.connection.on("disconnected", () => {
|
|
1296
|
+
console.log("[MongoDB] Disconnected");
|
|
1297
|
+
});
|
|
1298
|
+
return this.connection;
|
|
1299
|
+
} catch (err) {
|
|
1300
|
+
console.error("[MongoDB] Connection failed:", err.message);
|
|
1301
|
+
throw err;
|
|
1302
|
+
}
|
|
1303
|
+
}
|
|
1304
|
+
/**
|
|
1305
|
+
* Get the Mongoose connection
|
|
1306
|
+
*/
|
|
1307
|
+
getConnection() {
|
|
1308
|
+
return mongoose.connection;
|
|
1309
|
+
}
|
|
1310
|
+
/**
|
|
1311
|
+
* Get or create a model (with tenant scoping support)
|
|
1312
|
+
* @param {string} name - Model name
|
|
1313
|
+
* @param {Object} schema - Mongoose schema definition
|
|
1314
|
+
* @param {Object} options - Schema options
|
|
1315
|
+
*/
|
|
1316
|
+
createModel(name, schemaDefinition, options = {}) {
|
|
1317
|
+
const tenantedSchema = {
|
|
1318
|
+
tenant_id: {
|
|
1319
|
+
type: mongoose.Schema.Types.ObjectId,
|
|
1320
|
+
required: true,
|
|
1321
|
+
index: true
|
|
1322
|
+
},
|
|
1323
|
+
...schemaDefinition
|
|
1324
|
+
};
|
|
1325
|
+
const schema = new mongoose.Schema(tenantedSchema, {
|
|
1326
|
+
timestamps: { createdAt: "created_at", updatedAt: "updated_at" },
|
|
1327
|
+
...options
|
|
1328
|
+
});
|
|
1329
|
+
schema.index({ tenant_id: 1, created_at: -1 });
|
|
1330
|
+
return mongoose.model(name, schema);
|
|
1331
|
+
}
|
|
1332
|
+
/**
|
|
1333
|
+
* Disconnect from MongoDB
|
|
1334
|
+
*/
|
|
1335
|
+
async disconnect() {
|
|
1336
|
+
if (mongoose.connection.readyState !== 0) {
|
|
1337
|
+
await mongoose.disconnect();
|
|
1338
|
+
this.connection = null;
|
|
1339
|
+
console.log("[MongoDB] Disconnected");
|
|
1340
|
+
}
|
|
1341
|
+
}
|
|
1342
|
+
};
|
|
1343
|
+
var defaultConnection2 = null;
|
|
1344
|
+
function getMongoConnection(config) {
|
|
1345
|
+
if (!defaultConnection2) {
|
|
1346
|
+
defaultConnection2 = new MongoConnection(config);
|
|
1347
|
+
}
|
|
1348
|
+
return defaultConnection2;
|
|
1349
|
+
}
|
|
1350
|
+
function createMongoConnection(config) {
|
|
1351
|
+
return new MongoConnection(config);
|
|
1352
|
+
}
|
|
1353
|
+
|
|
1354
|
+
// src/server/utils/index.js
|
|
1355
|
+
var utils_exports = {};
|
|
1356
|
+
__export(utils_exports, {
|
|
1357
|
+
QueryBuilder: () => QueryBuilder,
|
|
1358
|
+
createQueryBuilder: () => createQueryBuilder,
|
|
1359
|
+
defineRoute: () => defineRoute,
|
|
1360
|
+
getSqlPagination: () => getSqlPagination,
|
|
1361
|
+
mountGeneratedRoutes: () => mountGeneratedRoutes,
|
|
1362
|
+
paginatedResponse: () => paginatedResponse,
|
|
1363
|
+
parsePaginationParams: () => parsePaginationParams,
|
|
1364
|
+
query: () => query
|
|
1365
|
+
});
|
|
1366
|
+
|
|
1367
|
+
// src/server/utils/query-builder.js
|
|
1368
|
+
var QueryBuilder = class {
|
|
1369
|
+
constructor(db, tenantId) {
|
|
1370
|
+
if (!tenantId) {
|
|
1371
|
+
throw new Error("QueryBuilder requires tenantId for multi-tenant isolation");
|
|
1372
|
+
}
|
|
1373
|
+
this.db = db;
|
|
1374
|
+
this.tenantId = tenantId;
|
|
1375
|
+
this._table = null;
|
|
1376
|
+
this._select = ["*"];
|
|
1377
|
+
this._where = [];
|
|
1378
|
+
this._whereParams = [];
|
|
1379
|
+
this._orderBy = [];
|
|
1380
|
+
this._limit = null;
|
|
1381
|
+
this._offset = null;
|
|
1382
|
+
this._joins = [];
|
|
1383
|
+
}
|
|
1384
|
+
/**
|
|
1385
|
+
* Set the table to query
|
|
1386
|
+
*/
|
|
1387
|
+
table(tableName) {
|
|
1388
|
+
this._table = tableName;
|
|
1389
|
+
return this;
|
|
1390
|
+
}
|
|
1391
|
+
/**
|
|
1392
|
+
* Set columns to select
|
|
1393
|
+
*/
|
|
1394
|
+
select(...columns) {
|
|
1395
|
+
this._select = columns.length > 0 ? columns : ["*"];
|
|
1396
|
+
return this;
|
|
1397
|
+
}
|
|
1398
|
+
/**
|
|
1399
|
+
* Add WHERE condition
|
|
1400
|
+
*/
|
|
1401
|
+
where(column, operator, value) {
|
|
1402
|
+
if (value === void 0) {
|
|
1403
|
+
value = operator;
|
|
1404
|
+
operator = "=";
|
|
1405
|
+
}
|
|
1406
|
+
this._whereParams.push(value);
|
|
1407
|
+
this._where.push(`${column} ${operator} $${this._whereParams.length + 1}`);
|
|
1408
|
+
return this;
|
|
1409
|
+
}
|
|
1410
|
+
/**
|
|
1411
|
+
* Add WHERE IN condition
|
|
1412
|
+
*/
|
|
1413
|
+
whereIn(column, values) {
|
|
1414
|
+
if (!Array.isArray(values) || values.length === 0) {
|
|
1415
|
+
return this;
|
|
1416
|
+
}
|
|
1417
|
+
const placeholders = values.map((_, i) => `$${this._whereParams.length + i + 2}`);
|
|
1418
|
+
this._whereParams.push(...values);
|
|
1419
|
+
this._where.push(`${column} IN (${placeholders.join(", ")})`);
|
|
1420
|
+
return this;
|
|
1421
|
+
}
|
|
1422
|
+
/**
|
|
1423
|
+
* Add WHERE NULL condition
|
|
1424
|
+
*/
|
|
1425
|
+
whereNull(column) {
|
|
1426
|
+
this._where.push(`${column} IS NULL`);
|
|
1427
|
+
return this;
|
|
1428
|
+
}
|
|
1429
|
+
/**
|
|
1430
|
+
* Add WHERE NOT NULL condition
|
|
1431
|
+
*/
|
|
1432
|
+
whereNotNull(column) {
|
|
1433
|
+
this._where.push(`${column} IS NOT NULL`);
|
|
1434
|
+
return this;
|
|
1435
|
+
}
|
|
1436
|
+
/**
|
|
1437
|
+
* Add ORDER BY clause
|
|
1438
|
+
*/
|
|
1439
|
+
orderBy(column, direction = "ASC") {
|
|
1440
|
+
this._orderBy.push(`${column} ${direction.toUpperCase()}`);
|
|
1441
|
+
return this;
|
|
1442
|
+
}
|
|
1443
|
+
/**
|
|
1444
|
+
* Set LIMIT
|
|
1445
|
+
*/
|
|
1446
|
+
limit(count) {
|
|
1447
|
+
this._limit = count;
|
|
1448
|
+
return this;
|
|
1449
|
+
}
|
|
1450
|
+
/**
|
|
1451
|
+
* Set OFFSET
|
|
1452
|
+
*/
|
|
1453
|
+
offset(count) {
|
|
1454
|
+
this._offset = count;
|
|
1455
|
+
return this;
|
|
1456
|
+
}
|
|
1457
|
+
/**
|
|
1458
|
+
* Add JOIN clause
|
|
1459
|
+
*/
|
|
1460
|
+
join(table, condition, type = "INNER") {
|
|
1461
|
+
this._joins.push(`${type} JOIN ${table} ON ${condition}`);
|
|
1462
|
+
return this;
|
|
1463
|
+
}
|
|
1464
|
+
/**
|
|
1465
|
+
* Build SELECT query
|
|
1466
|
+
*/
|
|
1467
|
+
_buildSelect() {
|
|
1468
|
+
if (!this._table) {
|
|
1469
|
+
throw new Error("Table name is required");
|
|
1470
|
+
}
|
|
1471
|
+
const parts = [`SELECT ${this._select.join(", ")} FROM ${this._table}`];
|
|
1472
|
+
if (this._joins.length > 0) {
|
|
1473
|
+
parts.push(this._joins.join(" "));
|
|
1474
|
+
}
|
|
1475
|
+
const whereConditions = [`${this._table}.tenant_id = $1`, ...this._where];
|
|
1476
|
+
parts.push(`WHERE ${whereConditions.join(" AND ")}`);
|
|
1477
|
+
if (this._orderBy.length > 0) {
|
|
1478
|
+
parts.push(`ORDER BY ${this._orderBy.join(", ")}`);
|
|
1479
|
+
}
|
|
1480
|
+
if (this._limit !== null) {
|
|
1481
|
+
parts.push(`LIMIT ${this._limit}`);
|
|
1482
|
+
}
|
|
1483
|
+
if (this._offset !== null) {
|
|
1484
|
+
parts.push(`OFFSET ${this._offset}`);
|
|
1485
|
+
}
|
|
1486
|
+
return {
|
|
1487
|
+
text: parts.join(" "),
|
|
1488
|
+
params: [this.tenantId, ...this._whereParams]
|
|
1489
|
+
};
|
|
1490
|
+
}
|
|
1491
|
+
/**
|
|
1492
|
+
* Execute SELECT and return all rows
|
|
1493
|
+
*/
|
|
1494
|
+
async get() {
|
|
1495
|
+
const query2 = this._buildSelect();
|
|
1496
|
+
const result = await this.db.query(query2.text, query2.params);
|
|
1497
|
+
return result.rows;
|
|
1498
|
+
}
|
|
1499
|
+
/**
|
|
1500
|
+
* Execute SELECT and return first row
|
|
1501
|
+
*/
|
|
1502
|
+
async first() {
|
|
1503
|
+
this._limit = 1;
|
|
1504
|
+
const rows = await this.get();
|
|
1505
|
+
return rows[0] || null;
|
|
1506
|
+
}
|
|
1507
|
+
/**
|
|
1508
|
+
* Execute SELECT and return count
|
|
1509
|
+
*/
|
|
1510
|
+
async count() {
|
|
1511
|
+
const originalSelect = this._select;
|
|
1512
|
+
this._select = ["COUNT(*) as count"];
|
|
1513
|
+
const query2 = this._buildSelect();
|
|
1514
|
+
const result = await this.db.query(query2.text, query2.params);
|
|
1515
|
+
this._select = originalSelect;
|
|
1516
|
+
return parseInt(result.rows[0]?.count || 0, 10);
|
|
1517
|
+
}
|
|
1518
|
+
/**
|
|
1519
|
+
* Find by ID (with tenant scoping)
|
|
1520
|
+
*/
|
|
1521
|
+
async find(id) {
|
|
1522
|
+
return this.where("id", id).first();
|
|
1523
|
+
}
|
|
1524
|
+
/**
|
|
1525
|
+
* Insert a new record
|
|
1526
|
+
*/
|
|
1527
|
+
async insert(data) {
|
|
1528
|
+
if (!this._table) {
|
|
1529
|
+
throw new Error("Table name is required");
|
|
1530
|
+
}
|
|
1531
|
+
const dataWithTenant = { tenant_id: this.tenantId, ...data };
|
|
1532
|
+
const columns = Object.keys(dataWithTenant);
|
|
1533
|
+
const values = Object.values(dataWithTenant);
|
|
1534
|
+
const placeholders = columns.map((_, i) => `$${i + 1}`);
|
|
1535
|
+
const query2 = `
|
|
1536
|
+
INSERT INTO ${this._table} (${columns.join(", ")})
|
|
1537
|
+
VALUES (${placeholders.join(", ")})
|
|
1538
|
+
RETURNING *
|
|
1539
|
+
`;
|
|
1540
|
+
const result = await this.db.query(query2, values);
|
|
1541
|
+
return result.rows[0];
|
|
1542
|
+
}
|
|
1543
|
+
/**
|
|
1544
|
+
* Update records
|
|
1545
|
+
*/
|
|
1546
|
+
async update(data) {
|
|
1547
|
+
if (!this._table) {
|
|
1548
|
+
throw new Error("Table name is required");
|
|
1549
|
+
}
|
|
1550
|
+
const dataWithTimestamp = { ...data, updated_at: /* @__PURE__ */ new Date() };
|
|
1551
|
+
const columns = Object.keys(dataWithTimestamp);
|
|
1552
|
+
const values = Object.values(dataWithTimestamp);
|
|
1553
|
+
const setClause = columns.map((col, i) => `${col} = $${i + 2}`).join(", ");
|
|
1554
|
+
const whereConditions = [`tenant_id = $1`, ...this._where];
|
|
1555
|
+
const query2 = `
|
|
1556
|
+
UPDATE ${this._table}
|
|
1557
|
+
SET ${setClause}
|
|
1558
|
+
WHERE ${whereConditions.join(" AND ")}
|
|
1559
|
+
RETURNING *
|
|
1560
|
+
`;
|
|
1561
|
+
const adjustedWhereParams = this._whereParams.map(
|
|
1562
|
+
(_, i) => this._where[i].replace(
|
|
1563
|
+
/\$(\d+)/g,
|
|
1564
|
+
(match, num) => `$${parseInt(num) + columns.length}`
|
|
1565
|
+
)
|
|
1566
|
+
);
|
|
1567
|
+
const result = await this.db.query(query2, [this.tenantId, ...values, ...this._whereParams]);
|
|
1568
|
+
return result.rows;
|
|
1569
|
+
}
|
|
1570
|
+
/**
|
|
1571
|
+
* Delete records
|
|
1572
|
+
*/
|
|
1573
|
+
async delete() {
|
|
1574
|
+
if (!this._table) {
|
|
1575
|
+
throw new Error("Table name is required");
|
|
1576
|
+
}
|
|
1577
|
+
const whereConditions = [`tenant_id = $1`, ...this._where];
|
|
1578
|
+
const query2 = `
|
|
1579
|
+
DELETE FROM ${this._table}
|
|
1580
|
+
WHERE ${whereConditions.join(" AND ")}
|
|
1581
|
+
RETURNING *
|
|
1582
|
+
`;
|
|
1583
|
+
const result = await this.db.query(query2, [this.tenantId, ...this._whereParams]);
|
|
1584
|
+
return result.rows;
|
|
1585
|
+
}
|
|
1586
|
+
};
|
|
1587
|
+
function createQueryBuilder(db, req) {
|
|
1588
|
+
if (!req.tenant || !req.tenant.id) {
|
|
1589
|
+
throw new Error("Request must have tenant context");
|
|
1590
|
+
}
|
|
1591
|
+
return new QueryBuilder(db, req.tenant.id);
|
|
1592
|
+
}
|
|
1593
|
+
function query(db, tenantId) {
|
|
1594
|
+
return new QueryBuilder(db, tenantId);
|
|
1595
|
+
}
|
|
1596
|
+
|
|
1597
|
+
// src/server/utils/paginate.js
|
|
1598
|
+
function parsePaginationParams(req) {
|
|
1599
|
+
const page = parseInt(req.query.page) || 1;
|
|
1600
|
+
const requestedPageSize = parseInt(req.query.pageSize) || 25;
|
|
1601
|
+
const pageSize = Math.min(requestedPageSize, 100);
|
|
1602
|
+
return {
|
|
1603
|
+
page,
|
|
1604
|
+
pageSize,
|
|
1605
|
+
offset: (page - 1) * pageSize,
|
|
1606
|
+
sort: req.query.sort || null,
|
|
1607
|
+
sortDirection: req.query.sortDirection || "asc"
|
|
1608
|
+
};
|
|
1609
|
+
}
|
|
1610
|
+
function paginatedResponse(data, total, page, pageSize) {
|
|
1611
|
+
const totalPages = Math.ceil(total / pageSize);
|
|
1612
|
+
return {
|
|
1613
|
+
data,
|
|
1614
|
+
pagination: {
|
|
1615
|
+
page,
|
|
1616
|
+
pageSize,
|
|
1617
|
+
total,
|
|
1618
|
+
totalPages,
|
|
1619
|
+
hasNext: page < totalPages,
|
|
1620
|
+
hasPrev: page > 1
|
|
1621
|
+
}
|
|
1622
|
+
};
|
|
1623
|
+
}
|
|
1624
|
+
function getSqlPagination(params) {
|
|
1625
|
+
return {
|
|
1626
|
+
limit: params.pageSize,
|
|
1627
|
+
offset: params.offset
|
|
1628
|
+
};
|
|
1629
|
+
}
|
|
1630
|
+
|
|
1631
|
+
// src/server/utils/route-loader.js
|
|
1632
|
+
function mountGeneratedRoutes(app, routesModule, basePath = "/api") {
|
|
1633
|
+
const routes = routesModule.routes || [];
|
|
1634
|
+
if (!Array.isArray(routes)) {
|
|
1635
|
+
console.warn("[RouteLoader] routes module does not export a routes array");
|
|
1636
|
+
return;
|
|
1637
|
+
}
|
|
1638
|
+
for (const route of routes) {
|
|
1639
|
+
if (!route.path || !route.router) {
|
|
1640
|
+
console.warn("[RouteLoader] Invalid route definition:", route);
|
|
1641
|
+
continue;
|
|
1642
|
+
}
|
|
1643
|
+
const fullPath = `${basePath}${route.path}`;
|
|
1644
|
+
app.use(fullPath, route.router);
|
|
1645
|
+
console.log(`[RouteLoader] Mounted ${fullPath}`);
|
|
1646
|
+
}
|
|
1647
|
+
console.log(`[RouteLoader] Loaded ${routes.length} route(s)`);
|
|
1648
|
+
}
|
|
1649
|
+
function defineRoute(path3, router) {
|
|
1650
|
+
return { path: path3, router };
|
|
1651
|
+
}
|
|
1652
|
+
|
|
1653
|
+
// src/server/workflow/index.js
|
|
1654
|
+
var workflow_exports = {};
|
|
1655
|
+
__export(workflow_exports, {
|
|
1656
|
+
WorkflowEngine: () => WorkflowEngine,
|
|
1657
|
+
createWorkflowRoutes: () => createWorkflowRoutes
|
|
1658
|
+
});
|
|
1659
|
+
|
|
1660
|
+
// src/server/workflow/WorkflowEngine.js
|
|
1661
|
+
var WorkflowEngine = class {
|
|
1662
|
+
constructor(db) {
|
|
1663
|
+
this.db = db;
|
|
1664
|
+
}
|
|
1665
|
+
/**
|
|
1666
|
+
* Create a new workflow instance for an entity
|
|
1667
|
+
* @param {string} tenantId - Tenant UUID
|
|
1668
|
+
* @param {string} workflowId - Workflow UUID (or name to look up)
|
|
1669
|
+
* @param {string} entityType - Entity type (e.g., 'Deal')
|
|
1670
|
+
* @param {string} entityId - Entity UUID
|
|
1671
|
+
* @returns {Object} Created workflow instance
|
|
1672
|
+
*/
|
|
1673
|
+
async createInstance(tenantId, workflowId, entityType, entityId) {
|
|
1674
|
+
let workflow;
|
|
1675
|
+
const isUuid = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i.test(workflowId);
|
|
1676
|
+
if (isUuid) {
|
|
1677
|
+
const result = await this.db.query(
|
|
1678
|
+
`SELECT w.id, ws.id as initial_state_id, ws.name as initial_state
|
|
1679
|
+
FROM workflows w
|
|
1680
|
+
JOIN workflow_states ws ON ws.workflow_id = w.id AND ws.is_initial = true
|
|
1681
|
+
WHERE w.id = $1 AND w.tenant_id = $2 AND w.is_active = true`,
|
|
1682
|
+
[workflowId, tenantId]
|
|
1683
|
+
);
|
|
1684
|
+
workflow = result.rows[0];
|
|
1685
|
+
} else {
|
|
1686
|
+
const result = await this.db.query(
|
|
1687
|
+
`SELECT w.id, ws.id as initial_state_id, ws.name as initial_state
|
|
1688
|
+
FROM workflows w
|
|
1689
|
+
JOIN workflow_states ws ON ws.workflow_id = w.id AND ws.is_initial = true
|
|
1690
|
+
WHERE w.name = $1 AND w.tenant_id = $2 AND w.is_active = true`,
|
|
1691
|
+
[workflowId, tenantId]
|
|
1692
|
+
);
|
|
1693
|
+
workflow = result.rows[0];
|
|
1694
|
+
}
|
|
1695
|
+
if (!workflow) {
|
|
1696
|
+
throw new Error(`Workflow '${workflowId}' not found or has no initial state`);
|
|
1697
|
+
}
|
|
1698
|
+
const existingResult = await this.db.query(
|
|
1699
|
+
`SELECT id FROM workflow_instances
|
|
1700
|
+
WHERE entity_type = $1 AND entity_id = $2 AND tenant_id = $3`,
|
|
1701
|
+
[entityType, entityId, tenantId]
|
|
1702
|
+
);
|
|
1703
|
+
if (existingResult.rows[0]) {
|
|
1704
|
+
throw new Error("Workflow instance already exists for this entity");
|
|
1705
|
+
}
|
|
1706
|
+
const instanceResult = await this.db.query(
|
|
1707
|
+
`INSERT INTO workflow_instances
|
|
1708
|
+
(tenant_id, workflow_id, current_state_id, entity_type, entity_id, started_at)
|
|
1709
|
+
VALUES ($1, $2, $3, $4, $5, NOW())
|
|
1710
|
+
RETURNING *`,
|
|
1711
|
+
[tenantId, workflow.id, workflow.initial_state_id, entityType, entityId]
|
|
1712
|
+
);
|
|
1713
|
+
const instance = instanceResult.rows[0];
|
|
1714
|
+
await this.db.query(
|
|
1715
|
+
`INSERT INTO workflow_histories
|
|
1716
|
+
(tenant_id, instance_id, to_state_id, transitioned_at, notes)
|
|
1717
|
+
VALUES ($1, $2, $3, NOW(), $4)`,
|
|
1718
|
+
[tenantId, instance.id, workflow.initial_state_id, "Workflow initialized"]
|
|
1719
|
+
);
|
|
1720
|
+
return {
|
|
1721
|
+
...instance,
|
|
1722
|
+
current_state: workflow.initial_state
|
|
1723
|
+
};
|
|
1724
|
+
}
|
|
1725
|
+
/**
|
|
1726
|
+
* Get available transitions for a workflow instance based on user roles/permissions.
|
|
1727
|
+
* @param {string} tenantId - Tenant UUID
|
|
1728
|
+
* @param {string} instanceId - Workflow instance UUID
|
|
1729
|
+
* @param {string[]|{roles:string[],permissions:string[]}} userContext
|
|
1730
|
+
* Array of role names (backward compat) OR { roles, permissions } object
|
|
1731
|
+
* @param {Object} [entityData] - Optional entity data for condition evaluation
|
|
1732
|
+
* @returns {Object[]} Available transitions
|
|
1733
|
+
*/
|
|
1734
|
+
async getAvailableTransitions(tenantId, instanceId, userContext, entityData = null) {
|
|
1735
|
+
const userRoles = Array.isArray(userContext) ? userContext : userContext?.roles || [];
|
|
1736
|
+
const userPermissions = Array.isArray(userContext) ? [] : userContext?.permissions || [];
|
|
1737
|
+
const instanceResult = await this.db.query(
|
|
1738
|
+
`SELECT wi.current_state_id, wi.workflow_id, wi.entity_type, wi.entity_id
|
|
1739
|
+
FROM workflow_instances wi
|
|
1740
|
+
WHERE wi.id = $1 AND wi.tenant_id = $2`,
|
|
1741
|
+
[instanceId, tenantId]
|
|
1742
|
+
);
|
|
1743
|
+
if (!instanceResult.rows[0]) {
|
|
1744
|
+
throw new Error("Workflow instance not found");
|
|
1745
|
+
}
|
|
1746
|
+
const { current_state_id, workflow_id } = instanceResult.rows[0];
|
|
1747
|
+
const transitionsResult = await this.db.query(
|
|
1748
|
+
`SELECT wt.id, wt.name, wt.description, wt.roles, wt.condition, wt.requires, wt.order,
|
|
1749
|
+
ts.id as to_state_id,
|
|
1750
|
+
ts.name as target_state,
|
|
1751
|
+
ts.label as target_state_label,
|
|
1752
|
+
ts.color as target_state_color
|
|
1753
|
+
FROM workflow_transitions wt
|
|
1754
|
+
JOIN workflow_states ts ON wt.to_state_id = ts.id
|
|
1755
|
+
WHERE wt.from_state_id = $1 AND wt.workflow_id = $2 AND wt.tenant_id = $3
|
|
1756
|
+
ORDER BY wt.order ASC, wt.name ASC`,
|
|
1757
|
+
[current_state_id, workflow_id, tenantId]
|
|
1758
|
+
);
|
|
1759
|
+
const roleFilteredTransitions = transitionsResult.rows.filter((transition) => {
|
|
1760
|
+
const allowedRoles = transition.roles || [];
|
|
1761
|
+
const allowedPerms = transition.permissions || [];
|
|
1762
|
+
if (allowedRoles.length === 0 && allowedPerms.length === 0)
|
|
1763
|
+
return true;
|
|
1764
|
+
if (allowedPerms.length > 0 && userPermissions.some((p) => allowedPerms.includes(p)))
|
|
1765
|
+
return true;
|
|
1766
|
+
if (allowedRoles.length > 0 && userRoles.some((r) => allowedRoles.includes(r)))
|
|
1767
|
+
return true;
|
|
1768
|
+
return false;
|
|
1769
|
+
});
|
|
1770
|
+
const conditionFilteredTransitions = roleFilteredTransitions.filter((transition) => {
|
|
1771
|
+
return this.evaluateCondition(transition.condition, entityData);
|
|
1772
|
+
});
|
|
1773
|
+
return conditionFilteredTransitions.map((t) => ({
|
|
1774
|
+
ruleId: t.id,
|
|
1775
|
+
id: t.id,
|
|
1776
|
+
name: t.name || t.target_state_label,
|
|
1777
|
+
action: t.name || t.target_state_label,
|
|
1778
|
+
description: t.description,
|
|
1779
|
+
targetState: t.target_state,
|
|
1780
|
+
targetStateLabel: t.target_state_label,
|
|
1781
|
+
targetStateColor: t.target_state_color,
|
|
1782
|
+
condition: t.condition,
|
|
1783
|
+
// Pass to client for UI evaluation hints
|
|
1784
|
+
requires: t.requires || []
|
|
1785
|
+
// Fields that must be non-empty for this transition
|
|
1786
|
+
}));
|
|
1787
|
+
}
|
|
1788
|
+
/**
|
|
1789
|
+
* Execute a workflow transition
|
|
1790
|
+
* @param {string} tenantId - Tenant UUID
|
|
1791
|
+
* @param {string} instanceId - Workflow instance UUID
|
|
1792
|
+
* @param {string} ruleId - Transition rule UUID to execute
|
|
1793
|
+
* @param {string} userId - User UUID performing the transition
|
|
1794
|
+
* @param {string} [comment] - Optional comment
|
|
1795
|
+
* @param {Object} [entitySnapshot] - Optional entity data snapshot
|
|
1796
|
+
* @returns {Object} Transition result
|
|
1797
|
+
*/
|
|
1798
|
+
async executeTransition(tenantId, instanceId, ruleId, userId, comment, entitySnapshot = null) {
|
|
1799
|
+
const instanceResult = await this.db.query(
|
|
1800
|
+
`SELECT wi.id, wi.current_state_id, wi.workflow_id
|
|
1801
|
+
FROM workflow_instances wi
|
|
1802
|
+
WHERE wi.id = $1 AND wi.tenant_id = $2`,
|
|
1803
|
+
[instanceId, tenantId]
|
|
1804
|
+
);
|
|
1805
|
+
if (!instanceResult.rows[0]) {
|
|
1806
|
+
throw new Error("Workflow instance not found");
|
|
1807
|
+
}
|
|
1808
|
+
const instance = instanceResult.rows[0];
|
|
1809
|
+
const transitionResult = await this.db.query(
|
|
1810
|
+
`SELECT wt.id, wt.from_state_id, wt.to_state_id, wt.name,
|
|
1811
|
+
wt.requires, wt.condition,
|
|
1812
|
+
fs.name as from_state,
|
|
1813
|
+
ts.name as to_state,
|
|
1814
|
+
ts.label as to_state_label,
|
|
1815
|
+
ts.color as to_state_color,
|
|
1816
|
+
ts.is_final,
|
|
1817
|
+
wi.entity_type, wi.entity_id
|
|
1818
|
+
FROM workflow_transitions wt
|
|
1819
|
+
JOIN workflow_states fs ON wt.from_state_id = fs.id
|
|
1820
|
+
JOIN workflow_states ts ON wt.to_state_id = ts.id
|
|
1821
|
+
JOIN workflow_instances wi ON wi.id = $2
|
|
1822
|
+
WHERE wt.id = $1 AND wt.workflow_id = $3 AND wt.tenant_id = $4`,
|
|
1823
|
+
[ruleId, instanceId, instance.workflow_id, tenantId]
|
|
1824
|
+
);
|
|
1825
|
+
if (!transitionResult.rows[0]) {
|
|
1826
|
+
throw new Error("Workflow transition not found");
|
|
1827
|
+
}
|
|
1828
|
+
const transition = transitionResult.rows[0];
|
|
1829
|
+
if (transition.from_state_id !== instance.current_state_id) {
|
|
1830
|
+
throw new Error(
|
|
1831
|
+
`Transition state '${transition.from_state}' does not match current state`
|
|
1832
|
+
);
|
|
1833
|
+
}
|
|
1834
|
+
if (transition.requires && entitySnapshot) {
|
|
1835
|
+
const requires = Array.isArray(transition.requires) ? transition.requires : JSON.parse(transition.requires);
|
|
1836
|
+
const missing = requires.filter((f) => {
|
|
1837
|
+
const v = entitySnapshot[f];
|
|
1838
|
+
return v === null || v === void 0 || v === "";
|
|
1839
|
+
});
|
|
1840
|
+
if (missing.length > 0) {
|
|
1841
|
+
throw new Error(`Transition blocked: required fields missing: ${missing.join(", ")}`);
|
|
1842
|
+
}
|
|
1843
|
+
}
|
|
1844
|
+
if (transition.condition && entitySnapshot) {
|
|
1845
|
+
if (!this.evaluateCondition(transition.condition, entitySnapshot)) {
|
|
1846
|
+
throw new Error("Transition blocked: condition not met");
|
|
1847
|
+
}
|
|
1848
|
+
}
|
|
1849
|
+
const previousStateId = instance.current_state_id;
|
|
1850
|
+
await this.db.query("BEGIN");
|
|
1851
|
+
try {
|
|
1852
|
+
await this.db.query(
|
|
1853
|
+
`UPDATE workflow_instances
|
|
1854
|
+
SET current_state_id = $1,
|
|
1855
|
+
completed_at = $2,
|
|
1856
|
+
updated_at = NOW()
|
|
1857
|
+
WHERE id = $3 AND tenant_id = $4`,
|
|
1858
|
+
[
|
|
1859
|
+
transition.to_state_id,
|
|
1860
|
+
transition.is_final ? /* @__PURE__ */ new Date() : null,
|
|
1861
|
+
instanceId,
|
|
1862
|
+
tenantId
|
|
1863
|
+
]
|
|
1864
|
+
);
|
|
1865
|
+
const entityTable = this.toEntityTableName(transition.entity_type || instance.entity_type);
|
|
1866
|
+
await this.db.query(
|
|
1867
|
+
`UPDATE ${entityTable} SET workflow_state = $1 WHERE id = $2 AND tenant_id = $3`,
|
|
1868
|
+
[transition.to_state, transition.entity_id || instance.entity_id, tenantId]
|
|
1869
|
+
).catch(() => {
|
|
1870
|
+
});
|
|
1871
|
+
await this.db.query(
|
|
1872
|
+
`INSERT INTO workflow_histories
|
|
1873
|
+
(tenant_id, instance_id, from_state_id, to_state_id, transition_id,
|
|
1874
|
+
transitioned_at, transitioned_by, notes, entity_snapshot)
|
|
1875
|
+
VALUES ($1, $2, $3, $4, $5, NOW(), $6, $7, $8)`,
|
|
1876
|
+
[
|
|
1877
|
+
tenantId,
|
|
1878
|
+
instanceId,
|
|
1879
|
+
previousStateId,
|
|
1880
|
+
transition.to_state_id,
|
|
1881
|
+
ruleId,
|
|
1882
|
+
userId,
|
|
1883
|
+
comment || null,
|
|
1884
|
+
entitySnapshot ? JSON.stringify(entitySnapshot) : null
|
|
1885
|
+
]
|
|
1886
|
+
);
|
|
1887
|
+
await this.db.query("COMMIT");
|
|
1888
|
+
return {
|
|
1889
|
+
success: true,
|
|
1890
|
+
previousState: transition.from_state,
|
|
1891
|
+
newState: transition.to_state,
|
|
1892
|
+
newStateLabel: transition.to_state_label,
|
|
1893
|
+
newStateColor: transition.to_state_color,
|
|
1894
|
+
action: transition.name,
|
|
1895
|
+
isFinal: transition.is_final
|
|
1896
|
+
};
|
|
1897
|
+
} catch (err) {
|
|
1898
|
+
await this.db.query("ROLLBACK");
|
|
1899
|
+
throw err;
|
|
1900
|
+
}
|
|
1901
|
+
}
|
|
1902
|
+
/**
|
|
1903
|
+
* Derive entity table name from entity type using the same convention as codegen.
|
|
1904
|
+
* e.g. 'Deal' → 'deals', 'ContactNote' → 'contact_notes'
|
|
1905
|
+
*/
|
|
1906
|
+
toEntityTableName(entityType) {
|
|
1907
|
+
const snake = entityType.replace(/([A-Z])/g, "_$1").toLowerCase().replace(/^_/, "");
|
|
1908
|
+
if (/([sxz]|[sc]h)$/.test(snake))
|
|
1909
|
+
return snake + "es";
|
|
1910
|
+
if (/[^aeiou]y$/.test(snake))
|
|
1911
|
+
return snake.slice(0, -1) + "ies";
|
|
1912
|
+
return snake + "s";
|
|
1913
|
+
}
|
|
1914
|
+
/**
|
|
1915
|
+
* Get a workflow instance with state info
|
|
1916
|
+
* @param {string} tenantId - Tenant UUID
|
|
1917
|
+
* @param {string} instanceId - Workflow instance UUID
|
|
1918
|
+
* @returns {Object} Instance with workflow and state details
|
|
1919
|
+
*/
|
|
1920
|
+
async getInstance(tenantId, instanceId) {
|
|
1921
|
+
const result = await this.db.query(
|
|
1922
|
+
`SELECT wi.*,
|
|
1923
|
+
w.name as workflow_name,
|
|
1924
|
+
w.entity_type as workflow_entity_type,
|
|
1925
|
+
ws.name as current_state,
|
|
1926
|
+
ws.label as current_state_label,
|
|
1927
|
+
ws.color as current_state_color,
|
|
1928
|
+
ws.is_final as is_current_state_final
|
|
1929
|
+
FROM workflow_instances wi
|
|
1930
|
+
JOIN workflows w ON wi.workflow_id = w.id
|
|
1931
|
+
JOIN workflow_states ws ON wi.current_state_id = ws.id
|
|
1932
|
+
WHERE wi.id = $1 AND wi.tenant_id = $2`,
|
|
1933
|
+
[instanceId, tenantId]
|
|
1934
|
+
);
|
|
1935
|
+
if (!result.rows[0]) {
|
|
1936
|
+
throw new Error("Workflow instance not found");
|
|
1937
|
+
}
|
|
1938
|
+
return result.rows[0];
|
|
1939
|
+
}
|
|
1940
|
+
/**
|
|
1941
|
+
* Get workflow instance by entity
|
|
1942
|
+
* @param {string} tenantId - Tenant UUID
|
|
1943
|
+
* @param {string} entityType - Entity type
|
|
1944
|
+
* @param {string} entityId - Entity UUID
|
|
1945
|
+
* @returns {Object|null} Instance or null if not found
|
|
1946
|
+
*/
|
|
1947
|
+
async getInstanceByEntity(tenantId, entityType, entityId) {
|
|
1948
|
+
const result = await this.db.query(
|
|
1949
|
+
`SELECT wi.*,
|
|
1950
|
+
w.name as workflow_name,
|
|
1951
|
+
ws.name as current_state,
|
|
1952
|
+
ws.label as current_state_label,
|
|
1953
|
+
ws.color as current_state_color,
|
|
1954
|
+
ws.is_final as is_current_state_final
|
|
1955
|
+
FROM workflow_instances wi
|
|
1956
|
+
JOIN workflows w ON wi.workflow_id = w.id
|
|
1957
|
+
JOIN workflow_states ws ON wi.current_state_id = ws.id
|
|
1958
|
+
WHERE wi.entity_type = $1 AND wi.entity_id = $2 AND wi.tenant_id = $3`,
|
|
1959
|
+
[entityType, entityId, tenantId]
|
|
1960
|
+
);
|
|
1961
|
+
return result.rows[0] || null;
|
|
1962
|
+
}
|
|
1963
|
+
/**
|
|
1964
|
+
* Get transition history for a workflow instance
|
|
1965
|
+
* @param {string} tenantId - Tenant UUID
|
|
1966
|
+
* @param {string} instanceId - Workflow instance UUID
|
|
1967
|
+
* @returns {Object[]} History entries
|
|
1968
|
+
*/
|
|
1969
|
+
async getHistory(tenantId, instanceId) {
|
|
1970
|
+
const result = await this.db.query(
|
|
1971
|
+
`SELECT wh.*,
|
|
1972
|
+
fs.name as from_state,
|
|
1973
|
+
fs.label as from_state_label,
|
|
1974
|
+
fs.color as from_state_color,
|
|
1975
|
+
ts.name as to_state,
|
|
1976
|
+
ts.label as to_state_label,
|
|
1977
|
+
ts.color as to_state_color,
|
|
1978
|
+
wt.name as transition_name,
|
|
1979
|
+
u.name as performed_by_name,
|
|
1980
|
+
u.email as performed_by_email
|
|
1981
|
+
FROM workflow_histories wh
|
|
1982
|
+
LEFT JOIN workflow_states fs ON wh.from_state_id = fs.id
|
|
1983
|
+
JOIN workflow_states ts ON wh.to_state_id = ts.id
|
|
1984
|
+
LEFT JOIN workflow_transitions wt ON wh.transition_id = wt.id
|
|
1985
|
+
LEFT JOIN users u ON wh.transitioned_by::uuid = u.id
|
|
1986
|
+
WHERE wh.instance_id = $1 AND wh.tenant_id = $2
|
|
1987
|
+
ORDER BY wh.transitioned_at DESC`,
|
|
1988
|
+
[instanceId, tenantId]
|
|
1989
|
+
);
|
|
1990
|
+
return result.rows.map((h) => ({
|
|
1991
|
+
id: h.id,
|
|
1992
|
+
fromState: h.from_state,
|
|
1993
|
+
fromStateLabel: h.from_state_label,
|
|
1994
|
+
fromStateColor: h.from_state_color,
|
|
1995
|
+
toState: h.to_state,
|
|
1996
|
+
toStateLabel: h.to_state_label,
|
|
1997
|
+
toStateColor: h.to_state_color,
|
|
1998
|
+
transitionName: h.transition_name,
|
|
1999
|
+
transitionedAt: h.transitioned_at,
|
|
2000
|
+
transitionedBy: h.performed_by_name || h.performed_by_email || h.transitioned_by,
|
|
2001
|
+
notes: h.notes,
|
|
2002
|
+
entitySnapshot: h.entity_snapshot
|
|
2003
|
+
}));
|
|
2004
|
+
}
|
|
2005
|
+
/**
|
|
2006
|
+
* Get all states for a workflow
|
|
2007
|
+
* @param {string} tenantId - Tenant UUID
|
|
2008
|
+
* @param {string} workflowId - Workflow UUID
|
|
2009
|
+
* @returns {Object[]} Workflow states
|
|
2010
|
+
*/
|
|
2011
|
+
async getWorkflowStates(tenantId, workflowId) {
|
|
2012
|
+
const result = await this.db.query(
|
|
2013
|
+
`SELECT id, name, label, description, color, is_initial, is_final, "order"
|
|
2014
|
+
FROM workflow_states
|
|
2015
|
+
WHERE workflow_id = $1 AND tenant_id = $2
|
|
2016
|
+
ORDER BY "order" ASC, name ASC`,
|
|
2017
|
+
[workflowId, tenantId]
|
|
2018
|
+
);
|
|
2019
|
+
return result.rows;
|
|
2020
|
+
}
|
|
2021
|
+
/**
|
|
2022
|
+
* Get all transitions for a workflow
|
|
2023
|
+
* @param {string} tenantId - Tenant UUID
|
|
2024
|
+
* @param {string} workflowId - Workflow UUID
|
|
2025
|
+
* @returns {Object[]} Workflow transitions
|
|
2026
|
+
*/
|
|
2027
|
+
async getWorkflowTransitions(tenantId, workflowId) {
|
|
2028
|
+
const result = await this.db.query(
|
|
2029
|
+
`SELECT wt.*,
|
|
2030
|
+
fs.name as from_state_name,
|
|
2031
|
+
fs.label as from_state_label,
|
|
2032
|
+
ts.name as to_state_name,
|
|
2033
|
+
ts.label as to_state_label
|
|
2034
|
+
FROM workflow_transitions wt
|
|
2035
|
+
JOIN workflow_states fs ON wt.from_state_id = fs.id
|
|
2036
|
+
JOIN workflow_states ts ON wt.to_state_id = ts.id
|
|
2037
|
+
WHERE wt.workflow_id = $1 AND wt.tenant_id = $2
|
|
2038
|
+
ORDER BY fs.order, wt.order, wt.name`,
|
|
2039
|
+
[workflowId, tenantId]
|
|
2040
|
+
);
|
|
2041
|
+
return result.rows;
|
|
2042
|
+
}
|
|
2043
|
+
/**
|
|
2044
|
+
* Evaluate a rule condition
|
|
2045
|
+
* @param {string|null} condition - JavaScript expression or null
|
|
2046
|
+
* @param {Object|null} entityData - Entity data for evaluation
|
|
2047
|
+
* @returns {boolean} Whether condition passes
|
|
2048
|
+
*/
|
|
2049
|
+
evaluateCondition(condition, entityData) {
|
|
2050
|
+
if (!condition) {
|
|
2051
|
+
return true;
|
|
2052
|
+
}
|
|
2053
|
+
if (!entityData) {
|
|
2054
|
+
return true;
|
|
2055
|
+
}
|
|
2056
|
+
try {
|
|
2057
|
+
const fn = new Function("entity", `return ${condition}`);
|
|
2058
|
+
return !!fn(entityData);
|
|
2059
|
+
} catch (err) {
|
|
2060
|
+
console.error("[WorkflowEngine] Condition evaluation error:", err);
|
|
2061
|
+
return false;
|
|
2062
|
+
}
|
|
2063
|
+
}
|
|
2064
|
+
};
|
|
2065
|
+
var WorkflowEngine_default = WorkflowEngine;
|
|
2066
|
+
|
|
2067
|
+
// src/server/workflow/workflow-routes.js
|
|
2068
|
+
import express from "express";
|
|
2069
|
+
function createWorkflowRoutes() {
|
|
2070
|
+
const router = express.Router();
|
|
2071
|
+
router.post("/initialize", async (req, res) => {
|
|
2072
|
+
try {
|
|
2073
|
+
const { workflowId, entityType, entityId } = req.body;
|
|
2074
|
+
if (!workflowId || !entityType || !entityId) {
|
|
2075
|
+
return res.status(400).json({
|
|
2076
|
+
error: "workflowId, entityType, and entityId are required"
|
|
2077
|
+
});
|
|
2078
|
+
}
|
|
2079
|
+
const engine = new WorkflowEngine(req.db);
|
|
2080
|
+
const instance = await engine.createInstance(
|
|
2081
|
+
req.tenant.id,
|
|
2082
|
+
workflowId,
|
|
2083
|
+
entityType,
|
|
2084
|
+
entityId
|
|
2085
|
+
);
|
|
2086
|
+
res.status(201).json({
|
|
2087
|
+
instanceId: instance.id,
|
|
2088
|
+
workflowId: instance.workflow_id,
|
|
2089
|
+
currentState: instance.current_state,
|
|
2090
|
+
entityType,
|
|
2091
|
+
entityId
|
|
2092
|
+
});
|
|
2093
|
+
} catch (err) {
|
|
2094
|
+
if (err.message.includes("already exists")) {
|
|
2095
|
+
return res.status(409).json({ error: err.message });
|
|
2096
|
+
}
|
|
2097
|
+
if (err.message.includes("not found")) {
|
|
2098
|
+
return res.status(404).json({ error: err.message });
|
|
2099
|
+
}
|
|
2100
|
+
console.error("[Workflow] Initialize error:", err);
|
|
2101
|
+
res.status(500).json({ error: "Failed to initialize workflow" });
|
|
2102
|
+
}
|
|
2103
|
+
});
|
|
2104
|
+
router.get("/by-entity/:entityType/:entityId", async (req, res) => {
|
|
2105
|
+
try {
|
|
2106
|
+
const { entityType, entityId } = req.params;
|
|
2107
|
+
const engine = new WorkflowEngine(req.db);
|
|
2108
|
+
const instance = await engine.getInstanceByEntity(
|
|
2109
|
+
req.tenant.id,
|
|
2110
|
+
entityType,
|
|
2111
|
+
entityId
|
|
2112
|
+
);
|
|
2113
|
+
if (!instance) {
|
|
2114
|
+
return res.status(404).json({ error: "Workflow instance not found" });
|
|
2115
|
+
}
|
|
2116
|
+
res.json(instance);
|
|
2117
|
+
} catch (err) {
|
|
2118
|
+
console.error("[Workflow] Get by entity error:", err);
|
|
2119
|
+
res.status(500).json({ error: "Failed to get workflow instance" });
|
|
2120
|
+
}
|
|
2121
|
+
});
|
|
2122
|
+
router.get("/:instanceId", async (req, res) => {
|
|
2123
|
+
try {
|
|
2124
|
+
const engine = new WorkflowEngine(req.db);
|
|
2125
|
+
const instance = await engine.getInstance(req.tenant.id, req.params.instanceId);
|
|
2126
|
+
res.json(instance);
|
|
2127
|
+
} catch (err) {
|
|
2128
|
+
if (err.message === "Workflow instance not found") {
|
|
2129
|
+
return res.status(404).json({ error: err.message });
|
|
2130
|
+
}
|
|
2131
|
+
console.error("[Workflow] Get instance error:", err);
|
|
2132
|
+
res.status(500).json({ error: "Failed to get workflow instance" });
|
|
2133
|
+
}
|
|
2134
|
+
});
|
|
2135
|
+
router.get("/:instanceId/transitions", async (req, res) => {
|
|
2136
|
+
try {
|
|
2137
|
+
const engine = new WorkflowEngine(req.db);
|
|
2138
|
+
const userContext = {
|
|
2139
|
+
roles: req.user?.roles || [],
|
|
2140
|
+
permissions: req.user?.permissions || []
|
|
2141
|
+
};
|
|
2142
|
+
const transitions = await engine.getAvailableTransitions(
|
|
2143
|
+
req.tenant.id,
|
|
2144
|
+
req.params.instanceId,
|
|
2145
|
+
userContext
|
|
2146
|
+
);
|
|
2147
|
+
res.json({ transitions });
|
|
2148
|
+
} catch (err) {
|
|
2149
|
+
if (err.message === "Workflow instance not found") {
|
|
2150
|
+
return res.status(404).json({ error: err.message });
|
|
2151
|
+
}
|
|
2152
|
+
console.error("[Workflow] Get transitions error:", err);
|
|
2153
|
+
res.status(500).json({ error: "Failed to get transitions" });
|
|
2154
|
+
}
|
|
2155
|
+
});
|
|
2156
|
+
router.post("/:instanceId/transition", async (req, res) => {
|
|
2157
|
+
try {
|
|
2158
|
+
const { ruleId, comment } = req.body;
|
|
2159
|
+
if (!ruleId) {
|
|
2160
|
+
return res.status(400).json({ error: "ruleId is required" });
|
|
2161
|
+
}
|
|
2162
|
+
const engine = new WorkflowEngine(req.db);
|
|
2163
|
+
const result = await engine.executeTransition(
|
|
2164
|
+
req.tenant.id,
|
|
2165
|
+
req.params.instanceId,
|
|
2166
|
+
ruleId,
|
|
2167
|
+
req.user?.id,
|
|
2168
|
+
comment
|
|
2169
|
+
);
|
|
2170
|
+
res.json(result);
|
|
2171
|
+
} catch (err) {
|
|
2172
|
+
if (err.message.includes("not found") || err.message.includes("does not match")) {
|
|
2173
|
+
return res.status(400).json({ error: err.message });
|
|
2174
|
+
}
|
|
2175
|
+
console.error("[Workflow] Execute transition error:", err);
|
|
2176
|
+
res.status(500).json({ error: "Failed to execute transition" });
|
|
2177
|
+
}
|
|
2178
|
+
});
|
|
2179
|
+
router.get("/:instanceId/history", async (req, res) => {
|
|
2180
|
+
try {
|
|
2181
|
+
const engine = new WorkflowEngine(req.db);
|
|
2182
|
+
const history = await engine.getHistory(req.tenant.id, req.params.instanceId);
|
|
2183
|
+
res.json({ history });
|
|
2184
|
+
} catch (err) {
|
|
2185
|
+
console.error("[Workflow] Get history error:", err);
|
|
2186
|
+
res.status(500).json({ error: "Failed to get workflow history" });
|
|
2187
|
+
}
|
|
2188
|
+
});
|
|
2189
|
+
return router;
|
|
2190
|
+
}
|
|
2191
|
+
var workflow_routes_default = createWorkflowRoutes;
|
|
2192
|
+
|
|
2193
|
+
// src/server/services/index.js
|
|
2194
|
+
var services_exports = {};
|
|
2195
|
+
__export(services_exports, {
|
|
2196
|
+
ConsoleEmailService: () => ConsoleEmailService,
|
|
2197
|
+
EmailService: () => EmailService,
|
|
2198
|
+
SmtpEmailService: () => SmtpEmailService,
|
|
2199
|
+
createEmailService: () => createEmailService,
|
|
2200
|
+
createStorageService: () => createStorageService,
|
|
2201
|
+
emailButton: () => emailButton,
|
|
2202
|
+
emailVerificationEmail: () => emailVerificationEmail,
|
|
2203
|
+
passwordResetEmail: () => passwordResetEmail,
|
|
2204
|
+
renderEmail: () => renderEmail
|
|
2205
|
+
});
|
|
2206
|
+
|
|
2207
|
+
// src/server/services/email.js
|
|
2208
|
+
var EmailService = class {
|
|
2209
|
+
async sendMail({ to, subject, html, text }) {
|
|
2210
|
+
throw new Error("sendMail must be implemented by subclass");
|
|
2211
|
+
}
|
|
2212
|
+
};
|
|
2213
|
+
var ConsoleEmailService = class extends EmailService {
|
|
2214
|
+
async sendMail({ to, subject, html, text }) {
|
|
2215
|
+
console.log("\n========== EMAIL ==========");
|
|
2216
|
+
console.log(`To: ${to}`);
|
|
2217
|
+
console.log(`Subject: ${subject}`);
|
|
2218
|
+
console.log(`Body: ${text || html}`);
|
|
2219
|
+
console.log("===========================\n");
|
|
2220
|
+
return { success: true, provider: "console" };
|
|
2221
|
+
}
|
|
2222
|
+
};
|
|
2223
|
+
var SmtpEmailService = class extends EmailService {
|
|
2224
|
+
constructor(config) {
|
|
2225
|
+
super();
|
|
2226
|
+
this.config = config;
|
|
2227
|
+
this.transporter = null;
|
|
2228
|
+
}
|
|
2229
|
+
async _getTransporter() {
|
|
2230
|
+
if (!this.transporter) {
|
|
2231
|
+
const nodemailer = await import("nodemailer");
|
|
2232
|
+
this.transporter = nodemailer.default.createTransport({
|
|
2233
|
+
host: this.config.host,
|
|
2234
|
+
port: this.config.port || 587,
|
|
2235
|
+
secure: this.config.secure || false,
|
|
2236
|
+
auth: this.config.auth ? {
|
|
2237
|
+
user: this.config.auth.user,
|
|
2238
|
+
pass: this.config.auth.pass
|
|
2239
|
+
} : void 0
|
|
2240
|
+
});
|
|
2241
|
+
}
|
|
2242
|
+
return this.transporter;
|
|
2243
|
+
}
|
|
2244
|
+
async sendMail({ to, subject, html, text }) {
|
|
2245
|
+
const transporter = await this._getTransporter();
|
|
2246
|
+
const result = await transporter.sendMail({
|
|
2247
|
+
from: this.config.from || "noreply@example.com",
|
|
2248
|
+
to,
|
|
2249
|
+
subject,
|
|
2250
|
+
html,
|
|
2251
|
+
text
|
|
2252
|
+
});
|
|
2253
|
+
return { success: true, provider: "smtp", messageId: result.messageId };
|
|
2254
|
+
}
|
|
2255
|
+
};
|
|
2256
|
+
function createEmailService(config = {}) {
|
|
2257
|
+
if (config.host) {
|
|
2258
|
+
return new SmtpEmailService(config);
|
|
2259
|
+
}
|
|
2260
|
+
return new ConsoleEmailService();
|
|
2261
|
+
}
|
|
2262
|
+
|
|
2263
|
+
// src/server/services/storage.js
|
|
2264
|
+
import fs from "fs";
|
|
2265
|
+
import path from "path";
|
|
2266
|
+
async function createStorageService(options = {}) {
|
|
2267
|
+
const uploadsDir = options.uploadsDir;
|
|
2268
|
+
const r2Config = {
|
|
2269
|
+
accountId: options.r2?.accountId || process.env.R2_ACCOUNT_ID,
|
|
2270
|
+
accessKeyId: options.r2?.accessKeyId || process.env.R2_ACCESS_KEY_ID,
|
|
2271
|
+
secretAccessKey: options.r2?.secretAccessKey || process.env.R2_SECRET_ACCESS_KEY,
|
|
2272
|
+
bucketName: options.r2?.bucketName || process.env.R2_BUCKET_NAME,
|
|
2273
|
+
publicUrl: options.r2?.publicUrl || process.env.R2_PUBLIC_URL
|
|
2274
|
+
};
|
|
2275
|
+
const r2Enabled = !!(r2Config.bucketName && r2Config.accessKeyId);
|
|
2276
|
+
let s3, PutObjectCommand, DeleteObjectCommand;
|
|
2277
|
+
if (r2Enabled) {
|
|
2278
|
+
const sdk = await import("@aws-sdk/client-s3");
|
|
2279
|
+
PutObjectCommand = sdk.PutObjectCommand;
|
|
2280
|
+
DeleteObjectCommand = sdk.DeleteObjectCommand;
|
|
2281
|
+
s3 = new sdk.S3Client({
|
|
2282
|
+
region: "auto",
|
|
2283
|
+
endpoint: `https://${r2Config.accountId}.r2.cloudflarestorage.com`,
|
|
2284
|
+
credentials: {
|
|
2285
|
+
accessKeyId: r2Config.accessKeyId,
|
|
2286
|
+
secretAccessKey: r2Config.secretAccessKey
|
|
2287
|
+
}
|
|
2288
|
+
});
|
|
2289
|
+
}
|
|
2290
|
+
async function put(key, buffer, contentType) {
|
|
2291
|
+
if (r2Enabled) {
|
|
2292
|
+
await s3.send(new PutObjectCommand({
|
|
2293
|
+
Bucket: r2Config.bucketName,
|
|
2294
|
+
Key: key,
|
|
2295
|
+
Body: buffer,
|
|
2296
|
+
ContentType: contentType
|
|
2297
|
+
}));
|
|
2298
|
+
return `${r2Config.publicUrl}/${key}`;
|
|
2299
|
+
}
|
|
2300
|
+
const filePath = path.join(uploadsDir, key);
|
|
2301
|
+
const dir = path.dirname(filePath);
|
|
2302
|
+
if (!fs.existsSync(dir))
|
|
2303
|
+
fs.mkdirSync(dir, { recursive: true });
|
|
2304
|
+
fs.writeFileSync(filePath, buffer);
|
|
2305
|
+
return `/uploads/${key}`;
|
|
2306
|
+
}
|
|
2307
|
+
async function del(key) {
|
|
2308
|
+
if (r2Enabled) {
|
|
2309
|
+
await s3.send(new DeleteObjectCommand({
|
|
2310
|
+
Bucket: r2Config.bucketName,
|
|
2311
|
+
Key: key
|
|
2312
|
+
}));
|
|
2313
|
+
return;
|
|
2314
|
+
}
|
|
2315
|
+
try {
|
|
2316
|
+
const filePath = path.join(uploadsDir, key);
|
|
2317
|
+
if (fs.existsSync(filePath))
|
|
2318
|
+
fs.unlinkSync(filePath);
|
|
2319
|
+
} catch {
|
|
2320
|
+
}
|
|
2321
|
+
}
|
|
2322
|
+
function getUrl(key) {
|
|
2323
|
+
if (r2Enabled) {
|
|
2324
|
+
return `${r2Config.publicUrl}/${key}`;
|
|
2325
|
+
}
|
|
2326
|
+
return `/uploads/${key}`;
|
|
2327
|
+
}
|
|
2328
|
+
return { put, del, getUrl, isR2Enabled: r2Enabled };
|
|
2329
|
+
}
|
|
2330
|
+
|
|
2331
|
+
// src/server/realtime/index.js
|
|
2332
|
+
var realtime_exports = {};
|
|
2333
|
+
__export(realtime_exports, {
|
|
2334
|
+
EventBus: () => EventBus,
|
|
2335
|
+
attachWebSocketServer: () => attachWebSocketServer,
|
|
2336
|
+
createRealtimeMiddleware: () => createRealtimeMiddleware
|
|
2337
|
+
});
|
|
2338
|
+
|
|
2339
|
+
// src/server/realtime/EventBus.js
|
|
2340
|
+
import { EventEmitter } from "events";
|
|
2341
|
+
var EventBus = class extends EventEmitter {
|
|
2342
|
+
constructor() {
|
|
2343
|
+
super();
|
|
2344
|
+
this.setMaxListeners(0);
|
|
2345
|
+
}
|
|
2346
|
+
/**
|
|
2347
|
+
* Emit an event on a channel, scoped to a tenant.
|
|
2348
|
+
* @param {string} channel
|
|
2349
|
+
* @param {string} tenantId
|
|
2350
|
+
* @param {*} payload
|
|
2351
|
+
*/
|
|
2352
|
+
broadcast(channel, tenantId, payload) {
|
|
2353
|
+
const key = `${tenantId}:${channel}`;
|
|
2354
|
+
this.emit(key, { channel, tenantId, payload });
|
|
2355
|
+
}
|
|
2356
|
+
/**
|
|
2357
|
+
* Subscribe to events on a channel for a specific tenant.
|
|
2358
|
+
* @param {string} channel
|
|
2359
|
+
* @param {string} tenantId
|
|
2360
|
+
* @param {Function} callback - receives { channel, tenantId, payload }
|
|
2361
|
+
*/
|
|
2362
|
+
subscribe(channel, tenantId, callback) {
|
|
2363
|
+
const key = `${tenantId}:${channel}`;
|
|
2364
|
+
this.on(key, callback);
|
|
2365
|
+
}
|
|
2366
|
+
/**
|
|
2367
|
+
* Unsubscribe from a channel.
|
|
2368
|
+
* @param {string} channel
|
|
2369
|
+
* @param {string} tenantId
|
|
2370
|
+
* @param {Function} callback
|
|
2371
|
+
*/
|
|
2372
|
+
unsubscribe(channel, tenantId, callback) {
|
|
2373
|
+
const key = `${tenantId}:${channel}`;
|
|
2374
|
+
this.off(key, callback);
|
|
2375
|
+
}
|
|
2376
|
+
};
|
|
2377
|
+
|
|
2378
|
+
// src/server/realtime/WebSocketServer.js
|
|
2379
|
+
import { WebSocketServer as WsServer } from "ws";
|
|
2380
|
+
function attachWebSocketServer(httpServer, { verifyToken: verifyToken2, eventBus }) {
|
|
2381
|
+
const wss = new WsServer({ server: httpServer, path: "/ws" });
|
|
2382
|
+
const HEARTBEAT_INTERVAL = 3e4;
|
|
2383
|
+
const heartbeat = setInterval(() => {
|
|
2384
|
+
for (const ws of wss.clients) {
|
|
2385
|
+
if (ws.isAlive === false) {
|
|
2386
|
+
ws.terminate();
|
|
2387
|
+
continue;
|
|
2388
|
+
}
|
|
2389
|
+
ws.isAlive = false;
|
|
2390
|
+
ws.ping();
|
|
2391
|
+
}
|
|
2392
|
+
}, HEARTBEAT_INTERVAL);
|
|
2393
|
+
wss.on("close", () => clearInterval(heartbeat));
|
|
2394
|
+
wss.on("connection", async (ws, req) => {
|
|
2395
|
+
ws.isAlive = true;
|
|
2396
|
+
ws.on("pong", () => {
|
|
2397
|
+
ws.isAlive = true;
|
|
2398
|
+
});
|
|
2399
|
+
const url = new URL(req.url, "http://localhost");
|
|
2400
|
+
const token = url.searchParams.get("token");
|
|
2401
|
+
if (!token) {
|
|
2402
|
+
ws.close(4001, "Missing token");
|
|
2403
|
+
return;
|
|
2404
|
+
}
|
|
2405
|
+
let identity;
|
|
2406
|
+
try {
|
|
2407
|
+
identity = await verifyToken2(token);
|
|
2408
|
+
} catch {
|
|
2409
|
+
identity = null;
|
|
2410
|
+
}
|
|
2411
|
+
if (!identity || !identity.userId || !identity.tenantId) {
|
|
2412
|
+
ws.close(4003, "Invalid token");
|
|
2413
|
+
return;
|
|
2414
|
+
}
|
|
2415
|
+
const { userId, tenantId } = identity;
|
|
2416
|
+
ws.userId = userId;
|
|
2417
|
+
ws.tenantId = tenantId;
|
|
2418
|
+
const subscriptions = /* @__PURE__ */ new Map();
|
|
2419
|
+
ws.on("message", (raw) => {
|
|
2420
|
+
let msg;
|
|
2421
|
+
try {
|
|
2422
|
+
msg = JSON.parse(raw.toString());
|
|
2423
|
+
} catch {
|
|
2424
|
+
return;
|
|
2425
|
+
}
|
|
2426
|
+
if (msg.type === "subscribe" && msg.channel) {
|
|
2427
|
+
if (subscriptions.has(msg.channel))
|
|
2428
|
+
return;
|
|
2429
|
+
const listener = (event) => {
|
|
2430
|
+
if (ws.readyState === ws.OPEN) {
|
|
2431
|
+
ws.send(JSON.stringify({
|
|
2432
|
+
type: "event",
|
|
2433
|
+
channel: event.channel,
|
|
2434
|
+
payload: event.payload
|
|
2435
|
+
}));
|
|
2436
|
+
}
|
|
2437
|
+
};
|
|
2438
|
+
subscriptions.set(msg.channel, listener);
|
|
2439
|
+
eventBus.subscribe(msg.channel, tenantId, listener);
|
|
2440
|
+
}
|
|
2441
|
+
if (msg.type === "unsubscribe" && msg.channel) {
|
|
2442
|
+
const listener = subscriptions.get(msg.channel);
|
|
2443
|
+
if (listener) {
|
|
2444
|
+
eventBus.unsubscribe(msg.channel, tenantId, listener);
|
|
2445
|
+
subscriptions.delete(msg.channel);
|
|
2446
|
+
}
|
|
2447
|
+
}
|
|
2448
|
+
});
|
|
2449
|
+
ws.on("close", () => {
|
|
2450
|
+
for (const [channel, listener] of subscriptions) {
|
|
2451
|
+
eventBus.unsubscribe(channel, tenantId, listener);
|
|
2452
|
+
}
|
|
2453
|
+
subscriptions.clear();
|
|
2454
|
+
});
|
|
2455
|
+
});
|
|
2456
|
+
return wss;
|
|
2457
|
+
}
|
|
2458
|
+
|
|
2459
|
+
// src/server/realtime/middleware.js
|
|
2460
|
+
function createRealtimeMiddleware(eventBus) {
|
|
2461
|
+
return (req, res, next) => {
|
|
2462
|
+
req.broadcast = (channel, payload) => {
|
|
2463
|
+
const tenantId = req.tenant?.id;
|
|
2464
|
+
if (tenantId) {
|
|
2465
|
+
eventBus.broadcast(channel, tenantId, payload);
|
|
2466
|
+
}
|
|
2467
|
+
};
|
|
2468
|
+
next();
|
|
2469
|
+
};
|
|
2470
|
+
}
|
|
2471
|
+
|
|
2472
|
+
// src/server/cache/index.js
|
|
2473
|
+
var cache_exports = {};
|
|
2474
|
+
__export(cache_exports, {
|
|
2475
|
+
MemoryCache: () => MemoryCache,
|
|
2476
|
+
createCache: () => createCache,
|
|
2477
|
+
createCacheMiddleware: () => createCacheMiddleware,
|
|
2478
|
+
getCache: () => getCache
|
|
2479
|
+
});
|
|
2480
|
+
|
|
2481
|
+
// src/server/cache/MemoryCache.js
|
|
2482
|
+
var MemoryCache = class {
|
|
2483
|
+
constructor(config = {}) {
|
|
2484
|
+
this.maxSize = config.maxSize || 1e3;
|
|
2485
|
+
this.defaultTTL = config.defaultTTL || 300;
|
|
2486
|
+
this.debug = config.debug || !!process.env.DEBUG_CACHE;
|
|
2487
|
+
this.store = /* @__PURE__ */ new Map();
|
|
2488
|
+
this.hits = 0;
|
|
2489
|
+
this.misses = 0;
|
|
2490
|
+
}
|
|
2491
|
+
/**
|
|
2492
|
+
* Get a value by key. Returns undefined if missing or expired.
|
|
2493
|
+
* Refreshes LRU position on hit.
|
|
2494
|
+
* @param {string} key
|
|
2495
|
+
* @returns {*} The cached value or undefined
|
|
2496
|
+
*/
|
|
2497
|
+
get(key) {
|
|
2498
|
+
const entry = this.store.get(key);
|
|
2499
|
+
if (!entry) {
|
|
2500
|
+
this.misses++;
|
|
2501
|
+
if (this.debug)
|
|
2502
|
+
console.log(`[Cache] MISS ${key}`);
|
|
2503
|
+
return void 0;
|
|
2504
|
+
}
|
|
2505
|
+
if (entry.expiresAt < Date.now()) {
|
|
2506
|
+
this.store.delete(key);
|
|
2507
|
+
this.misses++;
|
|
2508
|
+
if (this.debug)
|
|
2509
|
+
console.log(`[Cache] EXPIRED ${key}`);
|
|
2510
|
+
return void 0;
|
|
2511
|
+
}
|
|
2512
|
+
this.store.delete(key);
|
|
2513
|
+
this.store.set(key, entry);
|
|
2514
|
+
this.hits++;
|
|
2515
|
+
if (this.debug)
|
|
2516
|
+
console.log(`[Cache] HIT ${key}`);
|
|
2517
|
+
return entry.value;
|
|
2518
|
+
}
|
|
2519
|
+
/**
|
|
2520
|
+
* Store a value with optional TTL override.
|
|
2521
|
+
* @param {string} key
|
|
2522
|
+
* @param {*} value
|
|
2523
|
+
* @param {Object} [options]
|
|
2524
|
+
* @param {number} [options.ttl] TTL in seconds (overrides defaultTTL)
|
|
2525
|
+
*/
|
|
2526
|
+
set(key, value, options = {}) {
|
|
2527
|
+
const ttl = options.ttl ?? this.defaultTTL;
|
|
2528
|
+
if (this.store.has(key)) {
|
|
2529
|
+
this.store.delete(key);
|
|
2530
|
+
}
|
|
2531
|
+
if (this.store.size >= this.maxSize) {
|
|
2532
|
+
const oldest = this.store.keys().next().value;
|
|
2533
|
+
this.store.delete(oldest);
|
|
2534
|
+
if (this.debug)
|
|
2535
|
+
console.log(`[Cache] EVICT ${oldest}`);
|
|
2536
|
+
}
|
|
2537
|
+
this.store.set(key, {
|
|
2538
|
+
value,
|
|
2539
|
+
expiresAt: Date.now() + ttl * 1e3
|
|
2540
|
+
});
|
|
2541
|
+
if (this.debug)
|
|
2542
|
+
console.log(`[Cache] SET ${key} (ttl=${ttl}s)`);
|
|
2543
|
+
}
|
|
2544
|
+
/**
|
|
2545
|
+
* Delete a single key.
|
|
2546
|
+
* @param {string} key
|
|
2547
|
+
* @returns {boolean} True if the key existed
|
|
2548
|
+
*/
|
|
2549
|
+
del(key) {
|
|
2550
|
+
const existed = this.store.delete(key);
|
|
2551
|
+
if (this.debug && existed)
|
|
2552
|
+
console.log(`[Cache] DEL ${key}`);
|
|
2553
|
+
return existed;
|
|
2554
|
+
}
|
|
2555
|
+
/**
|
|
2556
|
+
* Delete all keys that start with the given prefix.
|
|
2557
|
+
* @param {string} pattern - Prefix string to match
|
|
2558
|
+
* @returns {number} Number of keys deleted
|
|
2559
|
+
*/
|
|
2560
|
+
bust(pattern) {
|
|
2561
|
+
let count = 0;
|
|
2562
|
+
for (const key of this.store.keys()) {
|
|
2563
|
+
if (key.startsWith(pattern)) {
|
|
2564
|
+
this.store.delete(key);
|
|
2565
|
+
count++;
|
|
2566
|
+
}
|
|
2567
|
+
}
|
|
2568
|
+
if (this.debug && count > 0)
|
|
2569
|
+
console.log(`[Cache] BUST "${pattern}" (${count} keys)`);
|
|
2570
|
+
return count;
|
|
2571
|
+
}
|
|
2572
|
+
/**
|
|
2573
|
+
* Clear all entries and reset counters.
|
|
2574
|
+
*/
|
|
2575
|
+
clear() {
|
|
2576
|
+
this.store.clear();
|
|
2577
|
+
this.hits = 0;
|
|
2578
|
+
this.misses = 0;
|
|
2579
|
+
if (this.debug)
|
|
2580
|
+
console.log("[Cache] CLEAR");
|
|
2581
|
+
}
|
|
2582
|
+
/**
|
|
2583
|
+
* Get cache statistics.
|
|
2584
|
+
* @returns {{ size: number, hits: number, misses: number, hitRate: string }}
|
|
2585
|
+
*/
|
|
2586
|
+
stats() {
|
|
2587
|
+
const total = this.hits + this.misses;
|
|
2588
|
+
return {
|
|
2589
|
+
size: this.store.size,
|
|
2590
|
+
maxSize: this.maxSize,
|
|
2591
|
+
hits: this.hits,
|
|
2592
|
+
misses: this.misses,
|
|
2593
|
+
hitRate: total > 0 ? (this.hits / total * 100).toFixed(1) + "%" : "0%"
|
|
2594
|
+
};
|
|
2595
|
+
}
|
|
2596
|
+
};
|
|
2597
|
+
var defaultCache = null;
|
|
2598
|
+
function getCache(config) {
|
|
2599
|
+
if (!defaultCache) {
|
|
2600
|
+
defaultCache = new MemoryCache(config);
|
|
2601
|
+
}
|
|
2602
|
+
return defaultCache;
|
|
2603
|
+
}
|
|
2604
|
+
function createCache(config) {
|
|
2605
|
+
return new MemoryCache(config);
|
|
2606
|
+
}
|
|
2607
|
+
|
|
2608
|
+
// src/server/cache/middleware.js
|
|
2609
|
+
function createCacheMiddleware(cache) {
|
|
2610
|
+
return (req, res, next) => {
|
|
2611
|
+
req.cache = cache;
|
|
2612
|
+
next();
|
|
2613
|
+
};
|
|
2614
|
+
}
|
|
2615
|
+
|
|
2616
|
+
// src/server/ai/index.js
|
|
2617
|
+
var ai_exports = {};
|
|
2618
|
+
__export(ai_exports, {
|
|
2619
|
+
createCapabilitiesRoutes: () => createCapabilitiesRoutes
|
|
2620
|
+
});
|
|
2621
|
+
|
|
2622
|
+
// src/server/ai/capabilities-routes.js
|
|
2623
|
+
import fs2 from "fs";
|
|
2624
|
+
import path2 from "path";
|
|
2625
|
+
import { Router } from "express";
|
|
2626
|
+
function createCapabilitiesRoutes(options = {}) {
|
|
2627
|
+
const router = Router();
|
|
2628
|
+
const indexPath = options.indexPath || path2.resolve(process.cwd(), "server/ai/capabilities/capabilities.index.json");
|
|
2629
|
+
const capabilitiesDir = path2.dirname(indexPath);
|
|
2630
|
+
let index = null;
|
|
2631
|
+
const manifestCache = /* @__PURE__ */ new Map();
|
|
2632
|
+
function loadIndex() {
|
|
2633
|
+
if (!fs2.existsSync(indexPath))
|
|
2634
|
+
return null;
|
|
2635
|
+
try {
|
|
2636
|
+
return JSON.parse(fs2.readFileSync(indexPath, "utf-8"));
|
|
2637
|
+
} catch {
|
|
2638
|
+
return null;
|
|
2639
|
+
}
|
|
2640
|
+
}
|
|
2641
|
+
index = loadIndex();
|
|
2642
|
+
router.get("/", (req, res) => {
|
|
2643
|
+
if (!index) {
|
|
2644
|
+
index = loadIndex();
|
|
2645
|
+
}
|
|
2646
|
+
if (!index) {
|
|
2647
|
+
return res.status(503).json({
|
|
2648
|
+
error: "Capabilities not available",
|
|
2649
|
+
message: "Run `avento generate` to produce capability manifests"
|
|
2650
|
+
});
|
|
2651
|
+
}
|
|
2652
|
+
res.json(index);
|
|
2653
|
+
});
|
|
2654
|
+
router.get("/:serviceId", (req, res) => {
|
|
2655
|
+
const { serviceId } = req.params;
|
|
2656
|
+
if (manifestCache.has(serviceId)) {
|
|
2657
|
+
return res.json(manifestCache.get(serviceId));
|
|
2658
|
+
}
|
|
2659
|
+
if (!index)
|
|
2660
|
+
index = loadIndex();
|
|
2661
|
+
if (!index) {
|
|
2662
|
+
return res.status(503).json({ error: "Capabilities not available" });
|
|
2663
|
+
}
|
|
2664
|
+
const entry = index.services.find((s) => s.service_id === serviceId);
|
|
2665
|
+
if (!entry) {
|
|
2666
|
+
return res.status(404).json({
|
|
2667
|
+
error: "Service not found",
|
|
2668
|
+
service_id: serviceId,
|
|
2669
|
+
available: index.services.map((s) => s.service_id)
|
|
2670
|
+
});
|
|
2671
|
+
}
|
|
2672
|
+
const manifestPath = path2.join(capabilitiesDir, entry.file);
|
|
2673
|
+
if (!fs2.existsSync(manifestPath)) {
|
|
2674
|
+
return res.status(404).json({
|
|
2675
|
+
error: "Capability manifest file not found",
|
|
2676
|
+
expected: manifestPath
|
|
2677
|
+
});
|
|
2678
|
+
}
|
|
2679
|
+
try {
|
|
2680
|
+
const manifest = JSON.parse(fs2.readFileSync(manifestPath, "utf-8"));
|
|
2681
|
+
manifestCache.set(serviceId, manifest);
|
|
2682
|
+
res.json(manifest);
|
|
2683
|
+
} catch (e) {
|
|
2684
|
+
res.status(500).json({
|
|
2685
|
+
error: "Failed to parse capability manifest",
|
|
2686
|
+
message: e.message
|
|
2687
|
+
});
|
|
2688
|
+
}
|
|
2689
|
+
});
|
|
2690
|
+
return router;
|
|
2691
|
+
}
|
|
2692
|
+
var capabilities_routes_default = createCapabilitiesRoutes;
|
|
2693
|
+
export {
|
|
2694
|
+
ConsoleEmailService,
|
|
2695
|
+
EmailService,
|
|
2696
|
+
EventBus,
|
|
2697
|
+
MemoryCache,
|
|
2698
|
+
MongoConnection,
|
|
2699
|
+
PostgresConnection,
|
|
2700
|
+
QueryBuilder,
|
|
2701
|
+
SmtpEmailService,
|
|
2702
|
+
WorkflowEngine,
|
|
2703
|
+
ai_exports as ai,
|
|
2704
|
+
assertTenant,
|
|
2705
|
+
attachCanFlags,
|
|
2706
|
+
attachWebSocketServer,
|
|
2707
|
+
cache_exports as cache,
|
|
2708
|
+
comparePassword,
|
|
2709
|
+
computeCanFlags,
|
|
2710
|
+
configurePassport,
|
|
2711
|
+
createCache,
|
|
2712
|
+
createCacheMiddleware,
|
|
2713
|
+
createCapabilitiesRoutes,
|
|
2714
|
+
createEmailService,
|
|
2715
|
+
createForgotPasswordHandler,
|
|
2716
|
+
createLoginHandler,
|
|
2717
|
+
createMongoConnection,
|
|
2718
|
+
createPermissionChecker,
|
|
2719
|
+
createPostgresConnection,
|
|
2720
|
+
createQueryBuilder,
|
|
2721
|
+
createRealtimeMiddleware,
|
|
2722
|
+
createRefreshHandler,
|
|
2723
|
+
createRegisterHandler,
|
|
2724
|
+
createResetPasswordHandler,
|
|
2725
|
+
createStorageService,
|
|
2726
|
+
createTenantListHandler,
|
|
2727
|
+
createTenantLookupHandler,
|
|
2728
|
+
createVerifyEmailHandler,
|
|
2729
|
+
createWorkflowRoutes,
|
|
2730
|
+
db_exports as db,
|
|
2731
|
+
defineRoute,
|
|
2732
|
+
emailButton,
|
|
2733
|
+
emailVerificationEmail,
|
|
2734
|
+
ensureEntityRolesTable,
|
|
2735
|
+
generateRefreshToken,
|
|
2736
|
+
generateSecureToken,
|
|
2737
|
+
generateToken,
|
|
2738
|
+
generateTokenExpiry,
|
|
2739
|
+
getCache,
|
|
2740
|
+
getMongoConnection,
|
|
2741
|
+
getPostgresConnection,
|
|
2742
|
+
getSqlPagination,
|
|
2743
|
+
getTenantId,
|
|
2744
|
+
hasAllRoles,
|
|
2745
|
+
hasAnyPermission,
|
|
2746
|
+
hasAnyRole,
|
|
2747
|
+
hasEntityRole,
|
|
2748
|
+
hasPermission,
|
|
2749
|
+
hashPassword,
|
|
2750
|
+
initAuth,
|
|
2751
|
+
isValidUUID,
|
|
2752
|
+
middleware_exports as middleware,
|
|
2753
|
+
mongoose,
|
|
2754
|
+
mountGeneratedRoutes,
|
|
2755
|
+
optionalAuth,
|
|
2756
|
+
paginatedResponse,
|
|
2757
|
+
parsePaginationParams,
|
|
2758
|
+
passwordResetEmail,
|
|
2759
|
+
query,
|
|
2760
|
+
realtime_exports as realtime,
|
|
2761
|
+
renderEmail,
|
|
2762
|
+
requireAdmin,
|
|
2763
|
+
requireAllRoles,
|
|
2764
|
+
requireAuth,
|
|
2765
|
+
requireEntityRoleOr,
|
|
2766
|
+
requireOwnership,
|
|
2767
|
+
requirePermission,
|
|
2768
|
+
requireRoles,
|
|
2769
|
+
requireTenant,
|
|
2770
|
+
services_exports as services,
|
|
2771
|
+
tenantMiddleware,
|
|
2772
|
+
utils_exports as utils,
|
|
2773
|
+
verifyToken,
|
|
2774
|
+
workflow_exports as workflow
|
|
2775
|
+
};
|
|
2776
|
+
//# sourceMappingURL=index.js.map
|