easy-devops 1.2.0 → 1.3.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.
Files changed (132) hide show
  1. package/README.md +97 -6
  2. package/dist/ui/assets/index-B6zdwEnG.css +1 -0
  3. package/dist/ui/assets/index-Cy0oNmul.js +442 -0
  4. package/dist/ui/assets/socket-DwLPrgsr.js +1 -0
  5. package/dist/ui/assets/socket-K5ttLD2q.js +65 -0
  6. package/dist/ui/brand/apple-touch-icon.png +0 -0
  7. package/dist/ui/brand/favicon-16.png +0 -0
  8. package/dist/ui/brand/favicon-32.png +0 -0
  9. package/dist/ui/brand/favicon-light-16.png +0 -0
  10. package/dist/ui/brand/favicon-light-32.png +0 -0
  11. package/dist/ui/brand/favicon.ico +0 -0
  12. package/dist/ui/brand/icon-192.png +0 -0
  13. package/dist/ui/brand/icon-48.png +0 -0
  14. package/dist/ui/brand/icon-512.png +0 -0
  15. package/dist/ui/brand/icon-64-light.png +0 -0
  16. package/dist/ui/brand/icon-64.png +0 -0
  17. package/dist/ui/brand/logo-dark.png +0 -0
  18. package/dist/ui/brand/logo-light.png +0 -0
  19. package/dist/ui/brand/mark-dark.png +0 -0
  20. package/dist/ui/brand/mark-light.png +0 -0
  21. package/dist/ui/index.html +71 -0
  22. package/install.ps1 +188 -1
  23. package/install.sh +254 -29
  24. package/package.json +17 -5
  25. package/src/cli/dash.js +110 -0
  26. package/src/cli/index.js +237 -106
  27. package/src/cli/managers/domain-manager.js +60 -40
  28. package/src/cli/managers/ssl-manager.js +47 -330
  29. package/src/cli/menu.js +156 -0
  30. package/src/cli/menus/cleanup.js +205 -0
  31. package/src/cli/menus/dashboard.js +93 -2
  32. package/src/cli/menus/runtime.js +236 -0
  33. package/src/cli/menus/service.js +764 -0
  34. package/src/cli/menus/settings.js +176 -8
  35. package/src/cli/menus/uninstall.js +167 -0
  36. package/src/cli/menus/update.js +221 -65
  37. package/src/core/acme-challenge.js +273 -0
  38. package/src/core/cert-operations.js +189 -0
  39. package/src/{dashboard/lib → core}/cert-reader.js +2 -2
  40. package/src/core/cert-renewal.js +494 -0
  41. package/src/core/channels/discord.js +77 -0
  42. package/src/core/channels/telegram.js +120 -0
  43. package/src/core/cleanup.js +600 -0
  44. package/src/core/config.js +169 -2
  45. package/src/core/daemon/ipc.js +292 -0
  46. package/src/core/daemon/lock.js +294 -0
  47. package/src/core/daemon/run.js +241 -0
  48. package/src/core/daemon/stopRequest.js +162 -0
  49. package/src/core/db.js +44 -8
  50. package/src/core/deploy/apps.js +491 -0
  51. package/src/core/deploy/domainLink.js +200 -0
  52. package/src/core/deploy/engine.js +973 -0
  53. package/src/core/deploy/ezfile.js +361 -0
  54. package/src/core/deploy/github.js +239 -0
  55. package/src/core/deploy/githubApi.js +261 -0
  56. package/src/core/deploy/hookServer.js +325 -0
  57. package/src/core/deploy/hubCommands.js +267 -0
  58. package/src/core/deploy/launcher.js +57 -0
  59. package/src/core/deploy/status.js +91 -0
  60. package/src/core/deploy/store.js +398 -0
  61. package/src/core/domainNotifier.js +364 -0
  62. package/src/core/domains-db.js +234 -0
  63. package/src/core/events.js +222 -0
  64. package/src/core/hub/agent.js +842 -0
  65. package/src/core/hubLink.js +306 -0
  66. package/src/core/hubPermissions.js +430 -0
  67. package/src/core/installSource.js +162 -0
  68. package/src/core/jobs/bus.js +120 -0
  69. package/src/core/jobs/index.js +371 -0
  70. package/src/core/jobs/monitors.js +368 -0
  71. package/src/core/jobs/owner.js +217 -0
  72. package/src/core/jobs/revisionWatcher.js +106 -0
  73. package/src/core/nginx-apply.js +213 -0
  74. package/src/core/nginx-conf-generator.js +253 -17
  75. package/src/{dashboard/lib → core}/nginx-service.js +18 -9
  76. package/src/core/notifications/claim.js +214 -0
  77. package/src/core/notifications/dispatch.js +154 -0
  78. package/src/core/notifier.js +103 -0
  79. package/src/core/passwords.js +172 -0
  80. package/src/core/permissions.js +8 -4
  81. package/src/core/platform.js +709 -2
  82. package/src/core/probeCache.js +258 -0
  83. package/src/core/purge.js +372 -0
  84. package/src/core/runner.js +488 -0
  85. package/src/core/service/acl.js +226 -0
  86. package/src/core/service/dataDir.js +345 -0
  87. package/src/core/service/index.js +1128 -0
  88. package/src/core/service/legacy.js +218 -0
  89. package/src/core/service/runtime.js +446 -0
  90. package/src/core/service/runtimeUpdate.js +800 -0
  91. package/src/core/service/systemd.js +458 -0
  92. package/src/core/service/windowsPersonal.js +530 -0
  93. package/src/core/service/windowsService.js +576 -0
  94. package/src/core/service/winsw.js +260 -0
  95. package/src/core/setupCode.js +331 -0
  96. package/src/core/shell.js +128 -13
  97. package/src/core/ssl-issuer.js +627 -0
  98. package/src/core/updater.js +295 -0
  99. package/src/core/validators.js +99 -0
  100. package/src/dashboard/controllers/authController.js +316 -0
  101. package/src/dashboard/controllers/deploymentsController.js +479 -0
  102. package/src/dashboard/controllers/domainsController.js +403 -0
  103. package/src/dashboard/controllers/hubController.js +135 -0
  104. package/src/dashboard/controllers/nginxController.js +146 -0
  105. package/src/dashboard/controllers/processesController.js +368 -0
  106. package/src/dashboard/controllers/settingsController.js +503 -0
  107. package/src/dashboard/controllers/sslController.js +452 -0
  108. package/src/dashboard/lib/daemonBridge.js +163 -0
  109. package/src/dashboard/lib/localRequest.js +235 -0
  110. package/src/dashboard/lib/loginRateLimit.js +119 -0
  111. package/src/dashboard/lib/requireAuth.js +80 -0
  112. package/src/dashboard/public/img/icon.png +0 -0
  113. package/src/dashboard/public/img/icon_b.png +0 -0
  114. package/src/dashboard/public/js/app.js +595 -19
  115. package/src/dashboard/routes/auth.js +14 -33
  116. package/src/dashboard/routes/deployments.js +46 -0
  117. package/src/dashboard/routes/domains.js +20 -363
  118. package/src/dashboard/routes/hub.js +22 -0
  119. package/src/dashboard/routes/nginx.js +22 -146
  120. package/src/dashboard/routes/processes.js +29 -0
  121. package/src/dashboard/routes/settings.js +25 -232
  122. package/src/dashboard/routes/ssl.js +18 -276
  123. package/src/dashboard/server.js +279 -165
  124. package/src/dashboard/socketManager.js +246 -0
  125. package/src/dashboard/views/index.ejs +1 -0
  126. package/src/dashboard/views/partials/domain-form.ejs +64 -1
  127. package/src/dashboard/views/partials/login.ejs +69 -8
  128. package/src/dashboard/views/partials/processes-panel.ejs +261 -0
  129. package/src/dashboard/views/partials/settings-panel.ejs +549 -118
  130. package/src/dashboard/views/partials/sidebar.ejs +3 -1
  131. package/src/dashboard/lib/domains-db.js +0 -51
  132. /package/src/{dashboard/routes → core/channels}/.gitkeep +0 -0
@@ -0,0 +1,403 @@
1
+ import fs from 'fs/promises';
2
+ import path from 'path';
3
+ import { run } from '../../core/shell.js';
4
+ import { loadConfig } from '../../core/config.js';
5
+ import { getDomains, saveDomains, findDomain, createDomain, DOMAIN_DEFAULTS } from '../../core/domains-db.js';
6
+ import { writeConfWithTest } from '../../core/nginx-apply.js';
7
+ import { getCertExpiry } from '../../core/cert-reader.js';
8
+ import { isWindows, nginxTestCmd, nginxReloadCmd, isNginxTestOk, hasBackslashPath } from '../../core/platform.js';
9
+ import {
10
+ validateDomainName, validatePort, validateUpstreamType,
11
+ validateMaxBodySize,
12
+ } from '../../core/validators.js';
13
+ import { getDomainNotifConfig, saveDomainNotifConfig } from '../../core/domainNotifier.js';
14
+
15
+ /**
16
+ * Maps a failed writeConfWithTest() result to an API error body, preserving
17
+ * the Linux permissions hint that the old inline checks surfaced.
18
+ * @param {{ error: string|null, output: string }} applied
19
+ */
20
+ function applyErrorResponse(applied) {
21
+ const output = applied.output || '';
22
+ if (!isWindows && output.includes('password is required')) {
23
+ return {
24
+ error: 'Linux permissions not configured. Open Settings → Setup Linux Permissions.',
25
+ output,
26
+ };
27
+ }
28
+ return { error: 'nginx config test failed', details: applied.error, output };
29
+ }
30
+
31
+ class DomainsController {
32
+ async list(req, res, next) {
33
+ try {
34
+ const domains = getDomains();
35
+ const result = await Promise.all(
36
+ domains.map(async (domain) => {
37
+ const { expiry, daysLeft } = await getCertExpiry(domain.name);
38
+ const notifications = getDomainNotifConfig(domain.name);
39
+ // Report-only: existing configs are never rewritten automatically.
40
+ // Saving the domain regenerates it through the shared apply, which
41
+ // writes forward-slash paths and clears the warning.
42
+ const sslPathWarning = Boolean(
43
+ isWindows &&
44
+ domain.ssl?.enabled &&
45
+ (hasBackslashPath(domain.ssl.certPath) || hasBackslashPath(domain.ssl.keyPath))
46
+ );
47
+ return { ...domain, certExpiry: expiry, daysLeft, notifications, sslPathWarning };
48
+ })
49
+ );
50
+ res.json(result);
51
+ } catch (error) {
52
+ next(error);
53
+ }
54
+ }
55
+
56
+ async create(req, res, next) {
57
+ try {
58
+ const body = req.body ?? {};
59
+
60
+ // Validate required fields
61
+ const nameError = validateDomainName(body.name);
62
+ if (nameError) {
63
+ return res.status(400).json({ error: nameError });
64
+ }
65
+
66
+ // Port validation is skipped when backendHost is a full external URL
67
+ const backendIsUrl = /^https?:\/\//i.test(body.backendHost ?? '');
68
+ if (!backendIsUrl) {
69
+ const portError = validatePort(body.port);
70
+ if (portError) {
71
+ return res.status(400).json({ error: portError });
72
+ }
73
+ }
74
+
75
+ // Validate optional fields
76
+ const upstreamError = validateUpstreamType(body.upstreamType);
77
+ if (upstreamError) {
78
+ return res.status(400).json({ error: upstreamError });
79
+ }
80
+
81
+ const maxSizeError = validateMaxBodySize(body.performance?.maxBodySize);
82
+ if (maxSizeError) {
83
+ return res.status(400).json({ error: maxSizeError });
84
+ }
85
+
86
+ // Check for duplicate
87
+ if (findDomain(body.name)) {
88
+ return res.status(409).json({ error: `Domain already exists: ${body.name}` });
89
+ }
90
+
91
+ // Build domain object with defaults
92
+ const domain = createDomain({
93
+ name: body.name,
94
+ port: Number(body.port),
95
+ backendHost: body.backendHost ?? DOMAIN_DEFAULTS.backendHost,
96
+ upstreamType: body.upstreamType ?? DOMAIN_DEFAULTS.upstreamType,
97
+ www: body.www ?? false,
98
+ ssl: {
99
+ enabled: body.ssl?.enabled ?? false,
100
+ certPath: body.ssl?.certPath ?? '',
101
+ keyPath: body.ssl?.keyPath ?? '',
102
+ redirect: body.ssl?.redirect ?? true,
103
+ hsts: body.ssl?.hsts ?? false,
104
+ hstsMaxAge: body.ssl?.hstsMaxAge ?? DOMAIN_DEFAULTS.ssl.hstsMaxAge,
105
+ },
106
+ performance: {
107
+ maxBodySize: body.performance?.maxBodySize ?? DOMAIN_DEFAULTS.performance.maxBodySize,
108
+ readTimeout: body.performance?.readTimeout ?? DOMAIN_DEFAULTS.performance.readTimeout,
109
+ connectTimeout: body.performance?.connectTimeout ?? DOMAIN_DEFAULTS.performance.connectTimeout,
110
+ proxyBuffers: body.performance?.proxyBuffers ?? false,
111
+ gzip: body.performance?.gzip ?? true,
112
+ gzipTypes: body.performance?.gzipTypes ?? DOMAIN_DEFAULTS.performance.gzipTypes,
113
+ },
114
+ security: {
115
+ rateLimit: body.security?.rateLimit ?? false,
116
+ rateLimitRate: body.security?.rateLimitRate ?? DOMAIN_DEFAULTS.security.rateLimitRate,
117
+ rateLimitBurst: body.security?.rateLimitBurst ?? DOMAIN_DEFAULTS.security.rateLimitBurst,
118
+ securityHeaders: body.security?.securityHeaders ?? false,
119
+ custom404: body.security?.custom404 ?? false,
120
+ custom50x: body.security?.custom50x ?? false,
121
+ },
122
+ advanced: {
123
+ accessLog: body.advanced?.accessLog ?? true,
124
+ customLocations: body.advanced?.customLocations ?? '',
125
+ },
126
+ wildcard: body.wildcard ?? false,
127
+ enabled: true,
128
+ });
129
+
130
+ // Cert existence check (FR-001): prevent saving a config that references non-existent cert files
131
+ if (domain.ssl.enabled && domain.ssl.certPath) {
132
+ try {
133
+ await fs.access(domain.ssl.certPath, fs.constants.F_OK);
134
+ } catch {
135
+ return res.status(422).json({
136
+ error: 'cert_missing',
137
+ certPath: domain.ssl.certPath,
138
+ keyPath: domain.ssl.keyPath,
139
+ hint: 'The SSL certificate files do not exist at the configured paths. Create the certificate first, or disable SSL.',
140
+ });
141
+ }
142
+ }
143
+
144
+ // Shared core apply: writes, tests via isNginxTestOk(), and on Windows
145
+ // retries once with escaped backslash cert paths before rolling back.
146
+ const applied = await writeConfWithTest(domain);
147
+ if (!applied.ok) {
148
+ return res.status(500).json(applyErrorResponse(applied));
149
+ }
150
+
151
+ const domains = getDomains();
152
+ domains.push(domain);
153
+ saveDomains(domains);
154
+
155
+ // Save per-domain notification config if provided
156
+ if (body.notifications && typeof body.notifications === 'object') {
157
+ try {
158
+ saveDomainNotifConfig(domain.name, body.notifications);
159
+ } catch { /* ignore validation errors — fall back to defaults */ }
160
+ }
161
+
162
+ res.status(201).json({ ...domain, notifications: getDomainNotifConfig(domain.name) });
163
+ } catch (error) {
164
+ next(error);
165
+ }
166
+ }
167
+
168
+ async update(req, res, next) {
169
+ try {
170
+ const { name } = req.params;
171
+ const existing = findDomain(name);
172
+ if (!existing) {
173
+ return res.status(404).json({ error: `Domain not found: ${name}` });
174
+ }
175
+
176
+ const body = req.body ?? {};
177
+
178
+ // Validate port if provided (skip when backendHost is a full external URL)
179
+ const backendIsUrl = /^https?:\/\//i.test(body.backendHost ?? existing.backendHost ?? '');
180
+ if (body.port !== undefined && !backendIsUrl) {
181
+ const portError = validatePort(body.port);
182
+ if (portError) {
183
+ return res.status(400).json({ error: portError });
184
+ }
185
+ body.port = Number(body.port);
186
+ }
187
+
188
+ // Validate upstreamType if provided
189
+ if (body.upstreamType !== undefined) {
190
+ const upstreamError = validateUpstreamType(body.upstreamType);
191
+ if (upstreamError) {
192
+ return res.status(400).json({ error: upstreamError });
193
+ }
194
+ }
195
+
196
+ // name is immutable — merge everything except name, configFile, and notifications
197
+ const { name: _ignored, configFile: _cf, notifications, ...updates } = body;
198
+
199
+ // Deep merge nested objects
200
+ const updatedDomain = {
201
+ ...existing,
202
+ ...updates,
203
+ ssl: { ...existing.ssl, ...updates.ssl },
204
+ performance: { ...existing.performance, ...updates.performance },
205
+ security: { ...existing.security, ...updates.security },
206
+ advanced: { ...existing.advanced, ...updates.advanced },
207
+ wildcard: updates.wildcard ?? existing.wildcard ?? false,
208
+ updatedAt: new Date().toISOString(),
209
+ };
210
+
211
+ // Shared core apply — snapshots the current file and restores it exactly
212
+ // if every attempt fails, so no .bak juggling is needed here.
213
+ const applied = await writeConfWithTest(updatedDomain);
214
+ if (!applied.ok) {
215
+ return res.status(500).json(applyErrorResponse(applied));
216
+ }
217
+
218
+ const domains = getDomains();
219
+ const idx = domains.findIndex((d) => d.name === name);
220
+ domains[idx] = updatedDomain;
221
+ saveDomains(domains);
222
+
223
+ // Save per-domain notification config if provided
224
+ if (notifications && typeof notifications === 'object') {
225
+ try {
226
+ saveDomainNotifConfig(name, notifications);
227
+ } catch { /* ignore validation errors — keep existing config */ }
228
+ }
229
+
230
+ res.json({ ...updatedDomain, notifications: getDomainNotifConfig(name) });
231
+ } catch (error) {
232
+ next(error);
233
+ }
234
+ }
235
+
236
+ async delete(req, res, next) {
237
+ try {
238
+ const { name } = req.params;
239
+ const deleteCert = req.query.deleteCert === 'true';
240
+ const domain = findDomain(name);
241
+ if (!domain) {
242
+ return res.status(404).json({ error: `Domain not found: ${name}` });
243
+ }
244
+
245
+ // Delete nginx conf file
246
+ if (domain.configFile) {
247
+ try {
248
+ await fs.unlink(domain.configFile);
249
+ } catch (err) {
250
+ if (err.code !== 'ENOENT') {
251
+ return res.status(500).json({ error: 'Failed to delete conf file', details: err.message });
252
+ }
253
+ }
254
+ }
255
+
256
+ // Optionally delete the SSL certificate directory for this domain
257
+ if (deleteCert && domain.ssl?.enabled) {
258
+ const { sslDir } = loadConfig();
259
+ const certDir = path.join(sslDir, name);
260
+ try {
261
+ await fs.rm(certDir, { recursive: true, force: true });
262
+ } catch { /* ignore — cert dir may not exist */ }
263
+ }
264
+
265
+ const domains = getDomains().filter((d) => d.name !== name);
266
+ saveDomains(domains);
267
+
268
+ res.json({ deleted: name, certDeleted: deleteCert && domain.ssl?.enabled });
269
+ } catch (error) {
270
+ next(error);
271
+ }
272
+ }
273
+
274
+ async toggle(req, res, next) {
275
+ try {
276
+ const { name } = req.params;
277
+ const domain = findDomain(name);
278
+ if (!domain) {
279
+ return res.status(404).json({ error: `Domain not found: ${name}` });
280
+ }
281
+
282
+ const { nginxDir } = loadConfig();
283
+ const isEnabled = domain.enabled !== false;
284
+ const confPath = domain.configFile;
285
+
286
+ if (!confPath) {
287
+ return res.status(400).json({ error: 'Domain has no config file path stored' });
288
+ }
289
+
290
+ // Normalise paths regardless of current stored extension
291
+ const basePath = confPath.replace(/\.disabled$/, '');
292
+ const enabledPath = basePath;
293
+ const disabledPath = `${basePath}.disabled`;
294
+
295
+ if (isEnabled) {
296
+ // Disable: rename .conf → .conf.disabled, then reload nginx
297
+ try {
298
+ await fs.rename(enabledPath, disabledPath);
299
+ } catch (err) {
300
+ return res.status(500).json({ error: 'Failed to rename config file', details: err.message });
301
+ }
302
+
303
+ const domains = getDomains();
304
+ const idx = domains.findIndex(d => d.name === name);
305
+ domains[idx] = { ...domain, enabled: false, configFile: disabledPath, updatedAt: new Date().toISOString() };
306
+ saveDomains(domains);
307
+
308
+ // Reload so nginx stops serving this domain
309
+ await run(isWindows ? nginxReloadCmd(nginxDir) : 'sudo -n /usr/bin/systemctl reload nginx', { cwd: nginxDir });
310
+
311
+ return res.json({ enabled: false });
312
+ } else {
313
+ // Enable: rename .conf.disabled → .conf, test, reload
314
+ try {
315
+ await fs.rename(disabledPath, enabledPath);
316
+ } catch (err) {
317
+ return res.status(500).json({ error: 'Failed to rename config file', details: err.message });
318
+ }
319
+
320
+ const testCmd = isWindows ? nginxTestCmd(nginxDir) : 'nginx -t';
321
+ const testResult = await run(testCmd, { cwd: nginxDir });
322
+ if (!isNginxTestOk(testResult)) {
323
+ // Roll back rename
324
+ await fs.rename(enabledPath, disabledPath).catch(() => {});
325
+ const output = testResult.stderr || testResult.stdout;
326
+ const error = !isWindows && output.includes('password is required')
327
+ ? 'Linux permissions not configured. Open Settings → Setup Linux Permissions.'
328
+ : 'nginx config test failed';
329
+ return res.status(500).json({ error, output });
330
+ }
331
+
332
+ const domains = getDomains();
333
+ const idx = domains.findIndex(d => d.name === name);
334
+ domains[idx] = { ...domain, enabled: true, configFile: enabledPath, updatedAt: new Date().toISOString() };
335
+ saveDomains(domains);
336
+
337
+ await run(isWindows ? nginxReloadCmd(nginxDir) : 'sudo -n /usr/bin/systemctl reload nginx', { cwd: nginxDir });
338
+
339
+ return res.json({ enabled: true });
340
+ }
341
+ } catch (error) {
342
+ next(error);
343
+ }
344
+ }
345
+
346
+ async reload(req, res, next) {
347
+ try {
348
+ const { name } = req.params;
349
+ if (!findDomain(name)) {
350
+ return res.status(404).json({ error: `Domain not found: ${name}` });
351
+ }
352
+
353
+ const { nginxDir } = loadConfig();
354
+
355
+ const testCmd = isWindows ? nginxTestCmd(nginxDir) : 'nginx -t';
356
+ const testResult = await run(testCmd, { cwd: nginxDir });
357
+ if (!isNginxTestOk(testResult)) {
358
+ const output = testResult.stderr || testResult.stdout;
359
+ const error = !isWindows && output.includes('password is required')
360
+ ? 'Linux permissions not configured. Open Settings → Setup Linux Permissions.'
361
+ : 'nginx config test failed';
362
+ return res.status(500).json({ error, output });
363
+ }
364
+
365
+ const reloadCmd = isWindows ? nginxReloadCmd(nginxDir) : 'sudo -n /usr/bin/systemctl reload nginx';
366
+ const reloadResult = await run(reloadCmd, { cwd: nginxDir });
367
+ if (!reloadResult.success) {
368
+ const output = reloadResult.stderr || reloadResult.stdout;
369
+ const error = !isWindows && output.includes('password is required')
370
+ ? 'Linux permissions not configured. Open Settings → Setup Linux Permissions.'
371
+ : 'nginx reload failed';
372
+ return res.status(500).json({ error, output });
373
+ }
374
+
375
+ res.json({ message: 'nginx reloaded successfully' });
376
+ } catch (error) {
377
+ next(error);
378
+ }
379
+ }
380
+
381
+ async getNotifications(req, res, next) {
382
+ try {
383
+ const config = getDomainNotifConfig(req.params.name);
384
+ res.json(config);
385
+ } catch (error) {
386
+ next(error);
387
+ }
388
+ }
389
+
390
+ async updateNotifications(req, res, next) {
391
+ try {
392
+ saveDomainNotifConfig(req.params.name, req.body ?? {});
393
+ res.json(getDomainNotifConfig(req.params.name));
394
+ } catch (error) {
395
+ if (error.message?.startsWith('Invalid') || error.message?.startsWith('Config') || error.message?.startsWith('Entry')) {
396
+ return res.status(400).json({ error: error.message });
397
+ }
398
+ next(error);
399
+ }
400
+ }
401
+ }
402
+
403
+ export default DomainsController;
@@ -0,0 +1,135 @@
1
+ // src/dashboard/controllers/hubController.js
2
+ //
3
+ // Thin HTTP layer over core/hubLink.js. All link parsing, persistence and
4
+ // permission logic lives in core so a future CLI menu can reuse it — this
5
+ // controller only translates between HTTP and that module.
6
+ //
7
+ // The hub issues connection strings; this server never generates them.
8
+
9
+ import {
10
+ parseConnectionString,
11
+ saveHubLink,
12
+ clearHubLink,
13
+ saveHubPermissions,
14
+ getLinkStatus,
15
+ } from '../../core/hubLink.js';
16
+ import { PERMISSION_TREE, COMING_SOON_PERMISSION_IDS } from '../../core/hubPermissions.js';
17
+ import { getDataDir, isDevDataDir, isDefaultDataDir } from '../../core/platform.js';
18
+ import { inspect } from '../../core/daemon/lock.js';
19
+ import { stopHubAgent, initHubAgent, getHubAgentStatus, pushPermissions } from '../../core/hub/agent.js';
20
+
21
+ // POST /api/hub/connect
22
+ // Body: { connectionString: 'ezops://hubUrl|serverId|secret' }
23
+ // Saves the pasted link, then starts the agent. Nothing connects until a
24
+ // valid string has been saved.
25
+ export function connectAgent(req, res) {
26
+ const parsed = parseConnectionString(req.body?.connectionString);
27
+ if (!parsed.ok) return res.status(400).json({ error: parsed.error });
28
+
29
+ const saved = saveHubLink(parsed.link);
30
+ if (!saved.ok) return res.status(400).json({ error: saved.error });
31
+
32
+ // The agent belongs to whichever process owns the background jobs. Starting
33
+ // one HERE while a daemon is running produced two sockets with the same
34
+ // serverId, and the hub keeps only one per server — so they evicted each
35
+ // other every few seconds, for ever.
36
+ //
37
+ // saveHubLink() bumps the revision counter, which the daemon's watcher picks
38
+ // up within a few seconds and reconciles its own agent against. So the
39
+ // correct action in that case is to do nothing more.
40
+ const daemon = inspect();
41
+
42
+ if (daemon.running) {
43
+ return res.json({
44
+ ok: true,
45
+ status: hubStatusPayload(),
46
+ agentOwner: 'daemon',
47
+ detail: `The background service (pid ${daemon.lock?.pid}) owns the Hub connection `
48
+ + 'and will pick up the new pairing within a few seconds.',
49
+ });
50
+ }
51
+
52
+ // No daemon: this dashboard is the job owner, so it holds the agent.
53
+ // initHubAgent() is idempotent, but stopping first keeps the intent explicit.
54
+ stopHubAgent();
55
+ initHubAgent();
56
+
57
+ return res.json({ ok: true, status: hubStatusPayload(), agentOwner: 'dashboard' });
58
+ }
59
+
60
+ // DELETE /api/hub/link
61
+ // Unlinks from the hub: stops the agent and clears stored link + permissions.
62
+ export function unlinkHub(req, res) {
63
+ // Stopping a local agent is always safe: if the daemon owns it, there is no
64
+ // socket here to stop. clearHubLink() bumps the revision, which is how the
65
+ // daemon learns to drop its own.
66
+ stopHubAgent();
67
+ clearHubLink();
68
+
69
+ const daemon = inspect();
70
+ return res.json({
71
+ ok: true,
72
+ ...(daemon.running
73
+ ? {
74
+ agentOwner: 'daemon',
75
+ detail: 'The background service will drop its Hub connection within a few seconds.',
76
+ }
77
+ : {}),
78
+ });
79
+ }
80
+
81
+ // GET /api/hub/status
82
+ // Returns the link state plus the agent's live connection status.
83
+ export function hubStatus(req, res) {
84
+ return res.json(hubStatusPayload());
85
+ }
86
+
87
+ // PUT /api/hub/permissions
88
+ // Body: { reloadNginx?: boolean, manageDomains?: boolean, manageSSL?: boolean }
89
+ export function updatePermissions(req, res) {
90
+ const permissions = saveHubPermissions(req.body ?? {});
91
+
92
+ // Push the new state to the Hub immediately so its UI greys out actions
93
+ // without waiting for a poll. Non-fatal: the agent may not be connected.
94
+ try {
95
+ pushPermissions();
96
+ } catch { /* not linked, or socket down */ }
97
+
98
+ return res.json({ permissions, tree: PERMISSION_TREE, comingSoon: COMING_SOON_PERMISSION_IDS });
99
+ }
100
+
101
+ /**
102
+ * Builds the status response. Deliberately omits the secret — it is only ever
103
+ * shown once by the hub, and is never echoed back by this API.
104
+ */
105
+ function hubStatusPayload() {
106
+ const link = getLinkStatus();
107
+ const agent = getHubAgentStatus();
108
+
109
+ return {
110
+ linked: link.linked,
111
+ hubUrl: link.hubUrl,
112
+ serverId: link.serverId,
113
+ permissions: link.permissions,
114
+ // The catalog travels with the status so the UI never hard-codes it.
115
+ tree: PERMISSION_TREE,
116
+ comingSoon: COMING_SOON_PERMISSION_IDS,
117
+ connected: agent.connected,
118
+ status: agent.status,
119
+ lastError: agent.lastError,
120
+ attempts: agent.attempts,
121
+ // Which database this dashboard — and therefore this agent — is actually
122
+ // using. A non-default directory means a CLI and a dashboard can be editing
123
+ // two separate domain lists with no visible sign of it, so the path is
124
+ // shown to make that obvious instead of looking like a sync bug.
125
+ //
126
+ // The two flags answer different questions, and conflating them was a bug:
127
+ // defaultDataDir — is this the ordinary location? A service install
128
+ // passes EASY_DEVOPS_DATA_DIR and is still ordinary.
129
+ // devDataDir — is this a DEVELOPMENT run (staging certificates,
130
+ // `-dev` names)? Only `--dev`/EZ_DEV or `.dev-data`.
131
+ dataDir: getDataDir(),
132
+ defaultDataDir: isDefaultDataDir(getDataDir()),
133
+ devDataDir: isDevDataDir(),
134
+ };
135
+ }
@@ -0,0 +1,146 @@
1
+ import {
2
+ getStatus,
3
+ reload,
4
+ restart,
5
+ start,
6
+ stop,
7
+ test,
8
+ listConfigs,
9
+ getConfig,
10
+ saveConfig,
11
+ getLogs,
12
+ NginxNotFoundError,
13
+ NginxConfigError,
14
+ InvalidFilenameError,
15
+ } from '../../core/nginx-service.js';
16
+
17
+ class NginxController {
18
+ handleError(err, res) {
19
+ if (err instanceof NginxNotFoundError) {
20
+ return res.status(503).json({ error: 'nginx not installed' });
21
+ }
22
+ if (err instanceof NginxConfigError) {
23
+ return res.status(400).json({ success: false, output: err.output });
24
+ }
25
+ if (err instanceof InvalidFilenameError) {
26
+ return res.status(400).json({ error: 'Invalid filename' });
27
+ }
28
+ if (err.code === 'ENOENT') {
29
+ return res.status(404).json({ error: 'Config file not found' });
30
+ }
31
+ return res.status(500).json({ error: 'Internal server error' });
32
+ }
33
+
34
+ async status(req, res, next) {
35
+ try {
36
+ const status = await getStatus();
37
+ res.json(status);
38
+ } catch (err) {
39
+ this.handleError(err, res);
40
+ }
41
+ }
42
+
43
+ async reload(req, res, next) {
44
+ try {
45
+ const result = await reload();
46
+ res.json(result);
47
+ } catch (err) {
48
+ this.handleError(err, res);
49
+ }
50
+ }
51
+
52
+ async restart(req, res, next) {
53
+ try {
54
+ const result = await restart();
55
+ res.json(result);
56
+ } catch (err) {
57
+ this.handleError(err, res);
58
+ }
59
+ }
60
+
61
+ async start(req, res, next) {
62
+ try {
63
+ const result = await start();
64
+ res.json(result);
65
+ } catch (err) {
66
+ this.handleError(err, res);
67
+ }
68
+ }
69
+
70
+ async stop(req, res, next) {
71
+ try {
72
+ const result = await stop();
73
+ res.json(result);
74
+ } catch (err) {
75
+ this.handleError(err, res);
76
+ }
77
+ }
78
+
79
+ async test(req, res, next) {
80
+ try {
81
+ const result = await test();
82
+ res.json(result);
83
+ } catch (err) {
84
+ this.handleError(err, res);
85
+ }
86
+ }
87
+
88
+ async listConfigs(req, res, next) {
89
+ try {
90
+ const configs = await listConfigs();
91
+ res.json(configs);
92
+ } catch (err) {
93
+ this.handleError(err, res);
94
+ }
95
+ }
96
+
97
+ async getConfig(req, res, next) {
98
+ try {
99
+ const result = await getConfig(req.params.filename);
100
+ res.json(result);
101
+ } catch (err) {
102
+ this.handleError(err, res);
103
+ }
104
+ }
105
+
106
+ async saveConfig(req, res, next) {
107
+ try {
108
+ if (typeof req.body.content !== 'string') {
109
+ return res.status(400).json({ error: 'content must be a string' });
110
+ }
111
+ const result = await saveConfig(req.params.filename, req.body.content);
112
+ res.json(result);
113
+ } catch (err) {
114
+ this.handleError(err, res);
115
+ }
116
+ }
117
+
118
+ /**
119
+ * GET /api/nginx/logs?file=error|access&lines=N
120
+ *
121
+ * Both parameters are additive: the previous endpoint took none and always
122
+ * returned 100 lines of the ERROR log, which is what the defaults still do.
123
+ * The access log was simply unreachable before — the contract has always
124
+ * described this endpoint as "access/error lines", so the gap was here.
125
+ *
126
+ * `file` is echoed back so a client cannot mistake which log it is showing.
127
+ */
128
+ async getLogs(req, res, next) {
129
+ try {
130
+ const which = req.query?.file === 'access' ? 'access' : 'error';
131
+
132
+ // Clamped rather than rejected, matching the clamp in core/runner.js for
133
+ // process logs: an out-of-range number is a client bug, not a reason to
134
+ // show the operator an error instead of their logs.
135
+ const requested = Number(req.query?.lines);
136
+ const lines = Math.max(1, Math.min(5000, Number.isFinite(requested) ? requested : 100));
137
+
138
+ const result = await getLogs(lines, which);
139
+ res.json({ ...result, file: which });
140
+ } catch (err) {
141
+ this.handleError(err, res);
142
+ }
143
+ }
144
+ }
145
+
146
+ export default NginxController;