@manojkmfsi/monodog 1.0.23 → 1.0.24

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.
Files changed (62) hide show
  1. package/.turbo/turbo-build.log +1 -1
  2. package/CHANGELOG.md +6 -0
  3. package/dist/controllers/{commitController.js → commit-controller.js} +5 -4
  4. package/dist/controllers/{configController.js → config-controller.js} +3 -3
  5. package/dist/controllers/{healthController.js → health-controller.js} +3 -3
  6. package/dist/controllers/{packageController.js → package-controller.js} +6 -6
  7. package/dist/index.js +11 -236
  8. package/dist/middleware/dashboard-startup.js +122 -0
  9. package/dist/middleware/error-handler.js +43 -0
  10. package/dist/middleware/index.js +21 -0
  11. package/dist/middleware/security.js +78 -0
  12. package/dist/middleware/server-startup.js +111 -0
  13. package/dist/repositories/commit-repository.js +97 -0
  14. package/dist/repositories/dependency-repository.js +97 -0
  15. package/dist/repositories/index.js +18 -0
  16. package/dist/repositories/package-health-repository.js +65 -0
  17. package/dist/repositories/package-repository.js +126 -0
  18. package/dist/repositories/prisma-client.js +57 -0
  19. package/dist/routes/{commitRoutes.js → commit-routes.js} +2 -2
  20. package/dist/routes/{configRoutes.js → config-routes.js} +3 -3
  21. package/dist/routes/{healthRoutes.js → health-routes.js} +3 -3
  22. package/dist/routes/{packageRoutes.js → package-routes.js} +5 -5
  23. package/dist/services/{commitService.js → commit-service.js} +2 -2
  24. package/dist/services/{configService.js → config-service.js} +2 -40
  25. package/dist/services/{healthService.js → health-service.js} +11 -63
  26. package/dist/services/{packageService.js → package-service.js} +80 -54
  27. package/dist/types/git.js +11 -0
  28. package/dist/types/index.js +1 -0
  29. package/package.json +1 -1
  30. package/src/controllers/{commitController.ts → commit-controller.ts} +7 -5
  31. package/src/controllers/{configController.ts → config-controller.ts} +4 -3
  32. package/src/controllers/{healthController.ts → health-controller.ts} +4 -3
  33. package/src/controllers/{packageController.ts → package-controller.ts} +7 -6
  34. package/src/index.ts +9 -281
  35. package/src/middleware/dashboard-startup.ts +150 -0
  36. package/src/middleware/error-handler.ts +63 -0
  37. package/src/middleware/index.ts +18 -0
  38. package/src/middleware/security.ts +81 -0
  39. package/src/middleware/server-startup.ts +140 -0
  40. package/src/repositories/commit-repository.ts +107 -0
  41. package/src/repositories/dependency-repository.ts +109 -0
  42. package/src/repositories/index.ts +10 -0
  43. package/src/repositories/package-health-repository.ts +75 -0
  44. package/src/repositories/package-repository.ts +142 -0
  45. package/src/repositories/prisma-client.ts +25 -0
  46. package/src/routes/{commitRoutes.ts → commit-routes.ts} +1 -1
  47. package/src/routes/{configRoutes.ts → config-routes.ts} +1 -1
  48. package/src/routes/{healthRoutes.ts → health-routes.ts} +1 -1
  49. package/src/routes/{packageRoutes.ts → package-routes.ts} +1 -1
  50. package/src/services/{commitService.ts → commit-service.ts} +1 -1
  51. package/src/services/{configService.ts → config-service.ts} +22 -9
  52. package/src/services/{gitService.ts → git-service.ts} +4 -4
  53. package/src/services/{healthService.ts → health-service.ts} +17 -35
  54. package/src/services/package-service.ts +201 -0
  55. package/src/types/database.ts +57 -1
  56. package/src/types/git.ts +8 -8
  57. package/src/types/index.ts +1 -1
  58. package/dist/utils/db-utils.js +0 -227
  59. package/src/services/packageService.ts +0 -115
  60. package/src/types/monorepo-scanner.d.ts +0 -32
  61. package/src/utils/db-utils.ts +0 -220
  62. /package/dist/services/{gitService.js → git-service.js} +0 -0
@@ -1,4 +1,4 @@
1
1
 
2
- > @manojkmfsi/monodog@1.0.23 build /home/runner/work/monodog/monodog/packages/monoapp
2
+ > @manojkmfsi/monodog@1.0.24 build /home/runner/work/monodog/monodog/packages/monoapp
3
3
  > rm -rf dist && tsc
4
4
 
package/CHANGELOG.md CHANGED
@@ -1,5 +1,11 @@
1
1
  # @manojkmfsi/monoapp
2
2
 
3
+ ## 1.0.24
4
+
5
+ ### Patch Changes
6
+
7
+ - added separate folder for middleware, kebab case filename
8
+
3
9
  ## 1.0.23
4
10
 
5
11
  ### Patch Changes
@@ -1,23 +1,24 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
3
  exports.getCommitsByPath = void 0;
4
- const commitService_1 = require("../services/commitService");
4
+ const commit_service_1 = require("../services/commit-service");
5
5
  const getCommitsByPath = async (_req, res) => {
6
6
  try {
7
7
  const { packagePath } = _req.params;
8
8
  const decodedPath = decodeURIComponent(packagePath);
9
9
  console.log('Fetching commits for path:', decodedPath);
10
10
  console.log('Current working directory:', process.cwd());
11
- const commits = await (0, commitService_1.getCommitsByPathService)(decodedPath);
11
+ const commits = await (0, commit_service_1.getCommitsByPathService)(decodedPath);
12
12
  console.log(`Successfully fetched ${commits.length} commits for ${decodedPath}`);
13
13
  res.json(commits);
14
14
  }
15
15
  catch (error) {
16
+ const err = error;
16
17
  console.error('Error fetching commit details:', error);
17
18
  res.status(500).json({
18
19
  error: 'Failed to fetch commit details',
19
- message: error.message,
20
- stack: process.env.NODE_ENV === 'development' ? error.stack : undefined,
20
+ message: err?.message,
21
+ stack: process.env.NODE_ENV === 'development' ? err?.stack : undefined,
21
22
  });
22
23
  }
23
24
  };
@@ -1,12 +1,12 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
3
  exports.updateConfigFile = exports.getConfigurationFiles = void 0;
4
- const configService_1 = require("../services/configService");
4
+ const config_service_1 = require("../services/config-service");
5
5
  const getConfigurationFiles = async (_req, res) => {
6
6
  try {
7
7
  const rootDir = _req.app.locals.rootPath;
8
8
  console.log('Monorepo root directory:', rootDir);
9
- const configFiles = await (0, configService_1.getConfigurationFilesService)(rootDir);
9
+ const configFiles = await (0, config_service_1.getConfigurationFilesService)(rootDir);
10
10
  res.json(configFiles);
11
11
  }
12
12
  catch (error) {
@@ -29,7 +29,7 @@ const updateConfigFile = async (_req, res) => {
29
29
  });
30
30
  }
31
31
  const rootDir = _req.app.locals.rootPath;
32
- const result = await (0, configService_1.updateConfigFileService)(id, rootDir, content);
32
+ const result = await (0, config_service_1.updateConfigFileService)(id, rootDir, content);
33
33
  res.json(result);
34
34
  }
35
35
  catch (error) {
@@ -1,10 +1,10 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
3
  exports.refreshHealth = exports.getPackagesHealth = void 0;
4
- const healthService_1 = require("../services/healthService");
4
+ const health_service_1 = require("../services/health-service");
5
5
  const getPackagesHealth = async (_req, res) => {
6
6
  try {
7
- const health = await (0, healthService_1.getHealthSummaryService)();
7
+ const health = await (0, health_service_1.getHealthSummaryService)();
8
8
  res.json(health);
9
9
  }
10
10
  catch (error) {
@@ -17,7 +17,7 @@ const getPackagesHealth = async (_req, res) => {
17
17
  exports.getPackagesHealth = getPackagesHealth;
18
18
  const refreshHealth = async (_req, res) => {
19
19
  try {
20
- const health = await (0, healthService_1.healthRefreshService)(_req.app.locals.rootPath);
20
+ const health = await (0, health_service_1.healthRefreshService)(_req.app.locals.rootPath);
21
21
  res.json(health);
22
22
  }
23
23
  catch (error) {
@@ -1,11 +1,11 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
3
  exports.updatePackageConfig = exports.getPackageDetail = exports.refreshPackages = exports.getPackages = void 0;
4
- const configService_1 = require("../services/configService");
5
- const packageService_1 = require("../services/packageService");
4
+ const config_service_1 = require("../services/config-service");
5
+ const package_service_1 = require("../services/package-service");
6
6
  const getPackages = async (_req, res) => {
7
7
  try {
8
- const transformedPackages = await (0, packageService_1.getPackagesService)(_req.app.locals.rootPath);
8
+ const transformedPackages = await (0, package_service_1.getPackagesService)(_req.app.locals.rootPath);
9
9
  res.json(transformedPackages);
10
10
  }
11
11
  catch (error) {
@@ -16,7 +16,7 @@ exports.getPackages = getPackages;
16
16
  const refreshPackages = async (_req, res) => {
17
17
  console.log('Refreshing packages from source...' + _req.app.locals.rootPath);
18
18
  try {
19
- const packages = await (0, packageService_1.refreshPackagesService)(_req.app.locals.rootPath);
19
+ const packages = await (0, package_service_1.refreshPackagesService)(_req.app.locals.rootPath);
20
20
  res.json(packages);
21
21
  }
22
22
  catch (error) {
@@ -27,7 +27,7 @@ exports.refreshPackages = refreshPackages;
27
27
  const getPackageDetail = async (_req, res) => {
28
28
  const { name } = _req.params;
29
29
  try {
30
- const packageDetail = await (0, packageService_1.getPackageDetailService)(name);
30
+ const packageDetail = await (0, package_service_1.getPackageDetailService)(name);
31
31
  res.json(packageDetail);
32
32
  }
33
33
  catch (error) {
@@ -46,7 +46,7 @@ const updatePackageConfig = async (req, res) => {
46
46
  }
47
47
  console.log('Updating package configuration for:', packageName);
48
48
  console.log('Package path:', packagePath);
49
- const updatedPackage = await (0, configService_1.updatePackageConfigurationService)(packagePath, packageName, config);
49
+ const updatedPackage = await (0, config_service_1.updatePackageConfigurationService)(packagePath, packageName, config);
50
50
  return res.json({
51
51
  success: true,
52
52
  message: 'Package configuration updated successfully',
package/dist/index.js CHANGED
@@ -1,238 +1,13 @@
1
1
  "use strict";
2
- var __importDefault = (this && this.__importDefault) || function (mod) {
3
- return (mod && mod.__esModule) ? mod : { "default": mod };
4
- };
2
+ /**
3
+ * Monodog Application Entry Point
4
+ *
5
+ * This file exports the main server and dashboard startup functions
6
+ * All middleware, security, and error handling logic has been moved to separate files
7
+ */
5
8
  Object.defineProperty(exports, "__esModule", { value: true });
6
- exports.startServer = startServer;
7
- exports.serveDashboard = serveDashboard;
8
- const express_1 = __importDefault(require("express"));
9
- const cors_1 = __importDefault(require("cors"));
10
- const path_1 = __importDefault(require("path"));
11
- const body_parser_1 = require("body-parser");
12
- const helmet_1 = __importDefault(require("helmet"));
13
- const config_loader_1 = require("./config-loader");
14
- const packageRoutes_1 = __importDefault(require("./routes/packageRoutes"));
15
- const commitRoutes_1 = __importDefault(require("./routes/commitRoutes"));
16
- const healthRoutes_1 = __importDefault(require("./routes/healthRoutes"));
17
- const configRoutes_1 = __importDefault(require("./routes/configRoutes"));
18
- // Security constants
19
- const PORT_MIN = 1024;
20
- const PORT_MAX = 65535;
21
- // Validate port number
22
- function validatePort(port) {
23
- const portNum = typeof port === 'string' ? parseInt(port, 10) : port;
24
- if (isNaN(portNum) || portNum < PORT_MIN || portNum > PORT_MAX) {
25
- throw new Error(`Port must be between ${PORT_MIN} and ${PORT_MAX}`);
26
- }
27
- return portNum;
28
- }
29
- // Global error handler
30
- const errorHandler = (err, req, res, _next) => {
31
- const status = err.status || err.statusCode || 500;
32
- console.error('[ERROR]', {
33
- status,
34
- method: req.method,
35
- path: req.path,
36
- message: err.message,
37
- });
38
- res.status(status).json({
39
- error: 'Internal server error'
40
- });
41
- };
42
- // The main function exported and called by the CLI
43
- function startServer(rootPath) {
44
- try {
45
- const port = config_loader_1.appConfig.server.port;
46
- const host = config_loader_1.appConfig.server.host;
47
- const validatedPort = validatePort(port);
48
- const app = (0, express_1.default)();
49
- // Set request timeout (30 seconds)
50
- app.use((req, res, next) => {
51
- req.setTimeout(30000);
52
- res.setTimeout(30000);
53
- next();
54
- });
55
- app.locals.rootPath = rootPath;
56
- // Security middleware with CSP allowing API calls
57
- const apiHost = host === '0.0.0.0' ? 'localhost' : host;
58
- const apiUrl = process.env.API_URL || `http://${apiHost}:${validatedPort}`;
59
- const dashboardHost = config_loader_1.appConfig.dashboard.host === '0.0.0.0' ? 'localhost' : config_loader_1.appConfig.dashboard.host;
60
- const dashboardUrl = `http://${dashboardHost}:${config_loader_1.appConfig.dashboard.port}`;
61
- app.use((0, helmet_1.default)({
62
- contentSecurityPolicy: {
63
- directives: {
64
- defaultSrc: ["'self'"],
65
- connectSrc: ["'self'", apiUrl, 'http://localhost:*', 'http://127.0.0.1:*'],
66
- scriptSrc: ["'self'"],
67
- imgSrc: ["'self'", 'data:', 'https:'],
68
- },
69
- },
70
- }));
71
- app.use((0, cors_1.default)({
72
- origin: process.env.CORS_ORIGIN || dashboardUrl,
73
- credentials: true,
74
- methods: ['GET', 'POST', 'PUT', 'DELETE', 'OPTIONS'],
75
- allowedHeaders: ['Content-Type', 'Authorization'],
76
- }));
77
- app.use((0, body_parser_1.json)({ limit: '1mb' }));
78
- // Request logging middleware (safe version)
79
- app.use((_req, _res, next) => {
80
- console.log(`[${new Date().toISOString()}] ${_req.method} ${_req.path}`);
81
- next();
82
- });
83
- app.use('/api/packages', packageRoutes_1.default);
84
- // Get commit details
85
- app.use('/api/commits/', commitRoutes_1.default);
86
- // Health check endpoint
87
- app.use('/api/health/', healthRoutes_1.default);
88
- // Configuration endpoint
89
- app.use('/api/config/', configRoutes_1.default);
90
- // 404 handler
91
- app.use('*', (_, res) => {
92
- res.status(404).json({
93
- error: 'Endpoint not found',
94
- timestamp: Date.now(),
95
- });
96
- });
97
- // Global error handler (must be last)
98
- app.use(errorHandler);
99
- const server = app.listen(validatedPort, host, () => {
100
- console.log(`Backend server running on http://${host}:${validatedPort}`);
101
- console.log(`API endpoints available:`);
102
- console.log(` - GET /api/health`);
103
- console.log(` - GET /api/packages/refresh`);
104
- console.log(` - GET /api/packages`);
105
- console.log(` - GET /api/packages/:name`);
106
- console.log(` - PUT /api/packages/update-config`);
107
- console.log(` - GET /api/commits/:packagePath`);
108
- console.log(` - GET /api/health/packages`);
109
- console.log(` - PUT /api/config/files/:id`);
110
- console.log(` - GET /api/config/files`);
111
- });
112
- server.on('error', (err) => {
113
- // Handle common errors like EADDRINUSE (port already in use)
114
- if (err.code === 'EADDRINUSE') {
115
- console.error(`Error: Port ${validatedPort} is already in use. Please specify a different port.`);
116
- process.exit(1);
117
- }
118
- else if (err.code === 'EACCES') {
119
- console.error(`Error: Permission denied to listen on port ${validatedPort}. Use a port above 1024.`);
120
- process.exit(1);
121
- }
122
- else {
123
- console.error('Server failed to start:', err.message);
124
- process.exit(1);
125
- }
126
- });
127
- // Graceful shutdown
128
- process.on('SIGTERM', () => {
129
- console.log('SIGTERM signal received: closing HTTP server');
130
- server.close(() => {
131
- console.log('HTTP server closed');
132
- process.exit(0);
133
- });
134
- });
135
- }
136
- catch (error) {
137
- console.error('Failed to start server:', error.message);
138
- process.exit(1);
139
- }
140
- }
141
- function serveDashboard(rootPath) {
142
- try {
143
- const port = config_loader_1.appConfig.dashboard.port;
144
- const host = config_loader_1.appConfig.dashboard.host;
145
- const validatedPort = validatePort(port);
146
- const app = (0, express_1.default)();
147
- // Security middleware
148
- const serverHost = config_loader_1.appConfig.server.host === '0.0.0.0' ? 'localhost' : config_loader_1.appConfig.server.host;
149
- const apiUrl = process.env.API_URL || `http://${serverHost}:${config_loader_1.appConfig.server.port}`;
150
- app.use((0, helmet_1.default)({
151
- contentSecurityPolicy: {
152
- directives: {
153
- defaultSrc: ["'self'"],
154
- connectSrc: ["'self'", apiUrl, 'http://localhost:*', 'http://127.0.0.1:*'],
155
- scriptSrc: ["'self'"],
156
- imgSrc: ["'self'", 'data:', 'https:'],
157
- },
158
- },
159
- }));
160
- // Strict CORS for dashboard
161
- app.use((0, cors_1.default)({
162
- origin: false, // Don't allow any origin for static assets
163
- }));
164
- // Set request timeout
165
- app.use((req, res, next) => {
166
- req.setTimeout(30000);
167
- res.setTimeout(30000);
168
- next();
169
- });
170
- app.get('/env-config.js', (req, res) => {
171
- res.setHeader('Content-Type', 'application/javascript');
172
- res.setHeader('Cache-Control', 'private, no-cache, no-store, must-revalidate');
173
- const serverHost = config_loader_1.appConfig.server.host === '0.0.0.0' ? 'localhost' : config_loader_1.appConfig.server.host;
174
- const apiUrl = process.env.API_URL || `http://${serverHost}:${config_loader_1.appConfig.server.port}`;
175
- res.send(`window.ENV = { API_URL: "${apiUrl}" };`);
176
- });
177
- // This code makes sure that any request that does not matches a static file
178
- // in the build folder, will just serve index.html. Client side routing is
179
- // going to make sure that the correct content will be loaded.
180
- app.use((req, res, next) => {
181
- if (/(.ico|.js|.css|.jpg|.png|.map|.woff|.woff2|.ttf)$/i.test(req.path)) {
182
- next();
183
- }
184
- else {
185
- res.header('Cache-Control', 'private, no-cache, no-store, must-revalidate');
186
- res.header('Expires', '-1');
187
- res.header('Pragma', 'no-cache');
188
- res.sendFile('index.html', {
189
- root: path_1.default.resolve(__dirname, '..', 'monodog-dashboard', 'dist'),
190
- }, (err) => {
191
- if (err) {
192
- console.error('Error serving index.html:', err.message);
193
- res.status(500).json({ error: 'Internal server error' });
194
- }
195
- });
196
- }
197
- });
198
- const staticPath = path_1.default.join(__dirname, '..', 'monodog-dashboard', 'dist');
199
- console.log('Serving static files from:', staticPath);
200
- app.use(express_1.default.static(staticPath, {
201
- maxAge: '1d',
202
- etag: false,
203
- dotfiles: 'deny', // Don't serve dot files
204
- }));
205
- // Global error handler
206
- app.use(errorHandler);
207
- const server = app.listen(validatedPort, host, () => {
208
- console.log(`Dashboard listening on http://${host}:${validatedPort}`);
209
- console.log('Press Ctrl+C to quit.');
210
- });
211
- server.on('error', (err) => {
212
- if (err.code === 'EADDRINUSE') {
213
- console.error(`Error: Port ${validatedPort} is already in use.`);
214
- process.exit(1);
215
- }
216
- else if (err.code === 'EACCES') {
217
- console.error(`Error: Permission denied to listen on port ${validatedPort}.`);
218
- process.exit(1);
219
- }
220
- else {
221
- console.error('Server failed to start:', err.message);
222
- process.exit(1);
223
- }
224
- });
225
- // Graceful shutdown
226
- process.on('SIGTERM', () => {
227
- console.log('SIGTERM signal received: closing dashboard server');
228
- server.close(() => {
229
- console.log('Dashboard server closed');
230
- process.exit(0);
231
- });
232
- });
233
- }
234
- catch (error) {
235
- console.error('Failed to start dashboard:', error.message);
236
- process.exit(1);
237
- }
238
- }
9
+ exports.serveDashboard = exports.startServer = void 0;
10
+ var server_startup_1 = require("./middleware/server-startup");
11
+ Object.defineProperty(exports, "startServer", { enumerable: true, get: function () { return server_startup_1.startServer; } });
12
+ var dashboard_startup_1 = require("./middleware/dashboard-startup");
13
+ Object.defineProperty(exports, "serveDashboard", { enumerable: true, get: function () { return dashboard_startup_1.serveDashboard; } });
@@ -0,0 +1,122 @@
1
+ "use strict";
2
+ /**
3
+ * Dashboard server startup logic
4
+ */
5
+ var __importDefault = (this && this.__importDefault) || function (mod) {
6
+ return (mod && mod.__esModule) ? mod : { "default": mod };
7
+ };
8
+ Object.defineProperty(exports, "__esModule", { value: true });
9
+ exports.serveDashboard = serveDashboard;
10
+ const express_1 = __importDefault(require("express"));
11
+ const path_1 = __importDefault(require("path"));
12
+ const config_loader_1 = require("../config-loader");
13
+ const error_handler_1 = require("./error-handler");
14
+ const security_1 = require("./security");
15
+ // Security constants
16
+ const PORT_MIN = 1024;
17
+ const PORT_MAX = 65535;
18
+ /**
19
+ * Validate port number
20
+ */
21
+ function validatePort(port) {
22
+ const portNum = typeof port === 'string' ? parseInt(port, 10) : port;
23
+ if (isNaN(portNum) || portNum < PORT_MIN || portNum > PORT_MAX) {
24
+ throw new Error(`Port must be between ${PORT_MIN} and ${PORT_MAX}`);
25
+ }
26
+ return portNum;
27
+ }
28
+ /**
29
+ * Create Express app for dashboard with middleware
30
+ */
31
+ function createDashboardApp() {
32
+ const app = (0, express_1.default)();
33
+ // Timeout middleware
34
+ app.use((0, security_1.createTimeoutMiddleware)());
35
+ // Security setup
36
+ const serverHost = config_loader_1.appConfig.server.host === '0.0.0.0'
37
+ ? 'localhost'
38
+ : config_loader_1.appConfig.server.host;
39
+ const apiUrl = (0, security_1.buildApiUrl)(serverHost, config_loader_1.appConfig.server.port);
40
+ app.use((0, security_1.createHelmetMiddleware)(apiUrl));
41
+ app.use((0, security_1.createDashboardCorsMiddleware)());
42
+ // Environment config endpoint
43
+ app.get('/env-config.js', (_req, res) => {
44
+ res.setHeader('Content-Type', 'application/javascript');
45
+ res.setHeader('Cache-Control', 'private, no-cache, no-store, must-revalidate');
46
+ res.send(`window.ENV = { API_URL: "${apiUrl}" };`);
47
+ });
48
+ // Request logging
49
+ app.use(error_handler_1.requestLogger);
50
+ // SPA routing: serve index.html for non-static routes
51
+ app.use((_req, _res, next) => {
52
+ if (/(.ico|.js|.css|.jpg|.png|.map|.woff|.woff2|.ttf)$/i.test(_req.path)) {
53
+ next();
54
+ }
55
+ else {
56
+ _res.header('Cache-Control', 'private, no-cache, no-store, must-revalidate');
57
+ _res.header('Expires', '-1');
58
+ _res.header('Pragma', 'no-cache');
59
+ _res.sendFile('index.html', {
60
+ root: path_1.default.resolve(__dirname, '..', '..', 'monodog-dashboard', 'dist'),
61
+ }, (err) => {
62
+ if (err) {
63
+ console.error('Error serving index.html:', err?.message);
64
+ _res.status(500).json({ error: 'Internal server error' });
65
+ }
66
+ });
67
+ }
68
+ });
69
+ // Static files
70
+ const staticPath = path_1.default.join(__dirname, '..', '..', 'monodog-dashboard', 'dist');
71
+ console.log('Serving static files from:', staticPath);
72
+ app.use(express_1.default.static(staticPath, {
73
+ maxAge: '1d',
74
+ etag: false,
75
+ dotfiles: 'deny',
76
+ }));
77
+ // Global error handler (must be last)
78
+ app.use(error_handler_1.errorHandler);
79
+ return app;
80
+ }
81
+ /**
82
+ * Start the dashboard server
83
+ */
84
+ function serveDashboard(rootPath) {
85
+ try {
86
+ const port = config_loader_1.appConfig.dashboard.port;
87
+ const host = config_loader_1.appConfig.dashboard.host;
88
+ const validatedPort = validatePort(port);
89
+ const app = createDashboardApp();
90
+ const server = app.listen(validatedPort, host, () => {
91
+ console.log(`Dashboard listening on http://${host}:${validatedPort}`);
92
+ console.log('Press Ctrl+C to quit.');
93
+ });
94
+ server.on('error', (err) => {
95
+ if (err.code === 'EADDRINUSE') {
96
+ console.error(`Error: Port ${validatedPort} is already in use.`);
97
+ process.exit(1);
98
+ }
99
+ else if (err.code === 'EACCES') {
100
+ console.error(`Error: Permission denied to listen on port ${validatedPort}.`);
101
+ process.exit(1);
102
+ }
103
+ else {
104
+ console.error('Server failed to start:', err.message);
105
+ process.exit(1);
106
+ }
107
+ });
108
+ // Graceful shutdown
109
+ process.on('SIGTERM', () => {
110
+ console.log('SIGTERM signal received: closing dashboard server');
111
+ server.close(() => {
112
+ console.log('Dashboard server closed');
113
+ process.exit(0);
114
+ });
115
+ });
116
+ }
117
+ catch (error) {
118
+ const err = error;
119
+ console.error('Failed to start dashboard:', err?.message || String(error));
120
+ process.exit(1);
121
+ }
122
+ }
@@ -0,0 +1,43 @@
1
+ "use strict";
2
+ /**
3
+ * Error handling middleware for Express
4
+ */
5
+ Object.defineProperty(exports, "__esModule", { value: true });
6
+ exports.requestLogger = exports.notFoundHandler = exports.errorHandler = void 0;
7
+ /**
8
+ * Global error handler middleware
9
+ * Must be registered last in the middleware chain
10
+ */
11
+ const errorHandler = (err, req, res, _next) => {
12
+ const status = err.status || err.statusCode || 500;
13
+ console.error('[ERROR]', {
14
+ status,
15
+ method: req.method,
16
+ path: req.path,
17
+ message: err.message,
18
+ timestamp: new Date().toISOString(),
19
+ });
20
+ res.status(status).json({
21
+ error: 'Internal server error',
22
+ timestamp: Date.now(),
23
+ });
24
+ };
25
+ exports.errorHandler = errorHandler;
26
+ /**
27
+ * 404 Not Found handler
28
+ */
29
+ const notFoundHandler = (_req, res) => {
30
+ res.status(404).json({
31
+ error: 'Endpoint not found',
32
+ timestamp: Date.now(),
33
+ });
34
+ };
35
+ exports.notFoundHandler = notFoundHandler;
36
+ /**
37
+ * Request logging middleware
38
+ */
39
+ const requestLogger = (req, _res, next) => {
40
+ console.log(`[${new Date().toISOString()}] ${req.method} ${req.path}`);
41
+ next();
42
+ };
43
+ exports.requestLogger = requestLogger;
@@ -0,0 +1,21 @@
1
+ "use strict";
2
+ /**
3
+ * Middleware exports
4
+ */
5
+ Object.defineProperty(exports, "__esModule", { value: true });
6
+ exports.serveDashboard = exports.startServer = exports.buildDashboardUrl = exports.buildApiUrl = exports.createTimeoutMiddleware = exports.createDashboardCorsMiddleware = exports.createApiCorsMiddleware = exports.createHelmetMiddleware = exports.requestLogger = exports.notFoundHandler = exports.errorHandler = void 0;
7
+ var error_handler_1 = require("./error-handler");
8
+ Object.defineProperty(exports, "errorHandler", { enumerable: true, get: function () { return error_handler_1.errorHandler; } });
9
+ Object.defineProperty(exports, "notFoundHandler", { enumerable: true, get: function () { return error_handler_1.notFoundHandler; } });
10
+ Object.defineProperty(exports, "requestLogger", { enumerable: true, get: function () { return error_handler_1.requestLogger; } });
11
+ var security_1 = require("./security");
12
+ Object.defineProperty(exports, "createHelmetMiddleware", { enumerable: true, get: function () { return security_1.createHelmetMiddleware; } });
13
+ Object.defineProperty(exports, "createApiCorsMiddleware", { enumerable: true, get: function () { return security_1.createApiCorsMiddleware; } });
14
+ Object.defineProperty(exports, "createDashboardCorsMiddleware", { enumerable: true, get: function () { return security_1.createDashboardCorsMiddleware; } });
15
+ Object.defineProperty(exports, "createTimeoutMiddleware", { enumerable: true, get: function () { return security_1.createTimeoutMiddleware; } });
16
+ Object.defineProperty(exports, "buildApiUrl", { enumerable: true, get: function () { return security_1.buildApiUrl; } });
17
+ Object.defineProperty(exports, "buildDashboardUrl", { enumerable: true, get: function () { return security_1.buildDashboardUrl; } });
18
+ var server_startup_1 = require("./server-startup");
19
+ Object.defineProperty(exports, "startServer", { enumerable: true, get: function () { return server_startup_1.startServer; } });
20
+ var dashboard_startup_1 = require("./dashboard-startup");
21
+ Object.defineProperty(exports, "serveDashboard", { enumerable: true, get: function () { return dashboard_startup_1.serveDashboard; } });
@@ -0,0 +1,78 @@
1
+ "use strict";
2
+ /**
3
+ * Security middleware and configuration
4
+ */
5
+ var __importDefault = (this && this.__importDefault) || function (mod) {
6
+ return (mod && mod.__esModule) ? mod : { "default": mod };
7
+ };
8
+ Object.defineProperty(exports, "__esModule", { value: true });
9
+ exports.createHelmetMiddleware = createHelmetMiddleware;
10
+ exports.createApiCorsMiddleware = createApiCorsMiddleware;
11
+ exports.createDashboardCorsMiddleware = createDashboardCorsMiddleware;
12
+ exports.createTimeoutMiddleware = createTimeoutMiddleware;
13
+ exports.buildApiUrl = buildApiUrl;
14
+ exports.buildDashboardUrl = buildDashboardUrl;
15
+ const helmet_1 = __importDefault(require("helmet"));
16
+ const cors_1 = __importDefault(require("cors"));
17
+ /**
18
+ * Create Helmet security middleware with Content Security Policy
19
+ */
20
+ function createHelmetMiddleware(apiUrl) {
21
+ return (0, helmet_1.default)({
22
+ contentSecurityPolicy: {
23
+ directives: {
24
+ defaultSrc: ["'self'"],
25
+ connectSrc: ["'self'", apiUrl, 'http://localhost:*', 'http://127.0.0.1:*'],
26
+ scriptSrc: ["'self'"],
27
+ imgSrc: ["'self'", 'data:', 'https:'],
28
+ },
29
+ },
30
+ });
31
+ }
32
+ /**
33
+ * Create CORS middleware for API server
34
+ */
35
+ function createApiCorsMiddleware(dashboardUrl) {
36
+ const corsOptions = {
37
+ origin: process.env.CORS_ORIGIN || dashboardUrl,
38
+ credentials: true,
39
+ methods: ['GET', 'POST', 'PUT', 'DELETE', 'OPTIONS'],
40
+ allowedHeaders: ['Content-Type', 'Authorization'],
41
+ };
42
+ return (0, cors_1.default)(corsOptions);
43
+ }
44
+ /**
45
+ * Create CORS middleware for dashboard (no cross-origin)
46
+ */
47
+ function createDashboardCorsMiddleware() {
48
+ const corsOptions = {
49
+ origin: false, // Don't allow any origin for static assets
50
+ };
51
+ return (0, cors_1.default)(corsOptions);
52
+ }
53
+ /**
54
+ * Request timeout middleware (30 seconds)
55
+ */
56
+ function createTimeoutMiddleware() {
57
+ return (req, res, next) => {
58
+ req.setTimeout(30000);
59
+ res.setTimeout(30000);
60
+ next();
61
+ };
62
+ }
63
+ /**
64
+ * Build API URL based on config
65
+ */
66
+ function buildApiUrl(host, port) {
67
+ const apiHost = host === '0.0.0.0' ? 'localhost' : host;
68
+ return process.env.API_URL || `http://${apiHost}:${port}`;
69
+ }
70
+ /**
71
+ * Build dashboard URL based on config
72
+ */
73
+ function buildDashboardUrl(config) {
74
+ const dashboardHost = config.dashboard.host === '0.0.0.0'
75
+ ? 'localhost'
76
+ : config.dashboard.host;
77
+ return `http://${dashboardHost}:${config.dashboard.port}`;
78
+ }