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
@@ -1,39 +1,20 @@
1
+ /**
2
+ * The only public router.
3
+ *
4
+ * Everything here exists so a client can obtain a session in the first place,
5
+ * so it cannot sit behind requireAuth. Each endpoint carries its own guard
6
+ * instead: login is rate limited and refuses an unset password, and setup is
7
+ * refused once a password exists.
8
+ */
1
9
  import { Router } from 'express';
2
- import rateLimit from 'express-rate-limit';
3
- import { loadConfig } from '../../core/config.js';
10
+ import AuthController from '../controllers/authController.js';
4
11
 
5
12
  const router = Router();
13
+ const controller = new AuthController();
6
14
 
7
- const loginLimiter = rateLimit({
8
- windowMs: 15 * 60 * 1000, // 15 minutes
9
- max: 10,
10
- standardHeaders: true,
11
- legacyHeaders: false,
12
- message: { ok: false, error: 'Too many login attempts. Try again in 15 minutes.' },
13
- });
14
-
15
- router.post('/login', loginLimiter, (req, res) => {
16
- const { password } = req.body;
17
- const { dashboardPassword } = loadConfig();
18
- if (password === dashboardPassword) {
19
- req.session.authenticated = true;
20
- res.json({ ok: true });
21
- } else {
22
- res.status(401).json({ ok: false, error: 'Invalid password' });
23
- }
24
- });
25
-
26
- router.get('/auth', (req, res) => {
27
- if (req.session.authenticated === true) {
28
- res.json({ authenticated: true });
29
- } else {
30
- res.json({ authenticated: false });
31
- }
32
- });
33
-
34
- router.post('/logout', (req, res) => {
35
- req.session.destroy();
36
- res.json({ ok: true });
37
- });
15
+ router.post('/login', (req, res, next) => controller.login(req, res, next));
16
+ router.post('/setup', (req, res, next) => controller.setup(req, res, next));
17
+ router.get('/auth', (req, res, next) => controller.check(req, res, next));
18
+ router.post('/logout', (req, res, next) => controller.logout(req, res, next));
38
19
 
39
20
  export default router;
@@ -0,0 +1,46 @@
1
+ import express from 'express';
2
+ import DeploymentsController from '../controllers/deploymentsController.js';
3
+ import { requireAuth } from '../lib/requireAuth.js';
4
+
5
+ const router = express.Router();
6
+ const controller = new DeploymentsController();
7
+
8
+ /**
9
+ * These routes fetch code from a repository and run its build and start
10
+ * commands on this machine. They are behind the shared session gate like
11
+ * everything else, and that is not optional: without it, anything that can
12
+ * reach the dashboard port could run commands here.
13
+ *
14
+ * The deploy hook that CI calls is NOT one of these routes. It is a separate,
15
+ * opt-in listener with its own per-app token (core/deploy/hookServer.js), so
16
+ * that nothing on the dashboard has to be public for a GitHub Action to work.
17
+ */
18
+ router.use(requireAuth);
19
+
20
+ // The hook settings come first so "hook" is never read as an app id.
21
+ // (apps.js also refuses to create an app with that name.)
22
+ router.get('/hook', (req, res, next) => controller.hook(req, res, next));
23
+ router.put('/hook', (req, res, next) => controller.updateHook(req, res, next));
24
+
25
+ router.get('/', (req, res, next) => controller.list(req, res, next));
26
+ router.post('/', (req, res, next) => controller.create(req, res, next));
27
+
28
+ router.get('/:id', (req, res, next) => controller.get(req, res, next));
29
+ router.put('/:id', (req, res, next) => controller.update(req, res, next));
30
+ router.delete('/:id', (req, res, next) => controller.remove(req, res, next));
31
+
32
+ router.put('/:id/domain', (req, res, next) => controller.linkDomain(req, res, next));
33
+ router.delete('/:id/domain', (req, res, next) => controller.unlinkDomain(req, res, next));
34
+ router.post('/:id/move', (req, res, next) => controller.move(req, res, next));
35
+
36
+ router.post('/:id/deploy', (req, res, next) => controller.deploy(req, res, next));
37
+ router.post('/:id/rollback', (req, res, next) => controller.rollback(req, res, next));
38
+ router.get('/:id/runs/:runId', (req, res, next) => controller.run(req, res, next));
39
+
40
+ router.post('/:id/hook-token', (req, res, next) => controller.hookToken(req, res, next));
41
+ router.delete('/:id/hook-token', (req, res, next) => controller.revokeHookToken(req, res, next));
42
+ router.post('/:id/deploy-key', (req, res, next) => controller.deployKey(req, res, next));
43
+ router.get('/:id/github', (req, res, next) => controller.github(req, res, next));
44
+ router.post('/:id/github/apply', (req, res, next) => controller.githubApply(req, res, next));
45
+
46
+ export default router;
@@ -1,368 +1,25 @@
1
1
  import express from 'express';
2
- import fs from 'fs/promises';
3
- import path from 'path';
4
- import { run } from '../../core/shell.js';
5
- import { loadConfig } from '../../core/config.js';
6
- import { getDomains, saveDomains, findDomain, createDomain, DOMAIN_DEFAULTS } from '../lib/domains-db.js';
7
- import { generateConf, getDefaultCertPaths } from '../lib/nginx-conf-generator.js';
8
- import { getCertExpiry } from '../lib/cert-reader.js';
9
- import { isWindows, nginxTestCmd, nginxReloadCmd, isNginxTestOk } from '../../core/platform.js';
10
- import {
11
- validateDomainName, validatePort, validateUpstreamType,
12
- validateMaxBodySize, validatePositiveInteger,
13
- } from '../../core/validators.js';
2
+ import DomainsController from '../controllers/domainsController.js';
3
+ import { requireAuth } from '../lib/requireAuth.js';
14
4
 
15
5
  const router = express.Router();
16
-
17
- // ─── GET /api/domains ─────────────────────────────────────────────────────────
18
-
19
- router.get('/', async (_req, res) => {
20
- const domains = getDomains();
21
- const result = await Promise.all(
22
- domains.map(async (domain) => {
23
- const { expiry, daysLeft } = await getCertExpiry(domain.name);
24
- return { ...domain, certExpiry: expiry, daysLeft };
25
- })
26
- );
27
- res.json(result);
28
- });
29
-
30
- // ─── POST /api/domains ────────────────────────────────────────────────────────
31
-
32
- router.post('/', async (req, res) => {
33
- const body = req.body ?? {};
34
-
35
- // Validate required fields
36
- const nameError = validateDomainName(body.name);
37
- if (nameError) {
38
- return res.status(400).json({ error: nameError });
39
- }
40
-
41
- // Port validation is skipped when backendHost is a full external URL
42
- const backendIsUrl = /^https?:\/\//i.test(body.backendHost ?? '');
43
- if (!backendIsUrl) {
44
- const portError = validatePort(body.port);
45
- if (portError) {
46
- return res.status(400).json({ error: portError });
47
- }
48
- }
49
-
50
- // Validate optional fields
51
- const upstreamError = validateUpstreamType(body.upstreamType);
52
- if (upstreamError) {
53
- return res.status(400).json({ error: upstreamError });
54
- }
55
-
56
- const maxSizeError = validateMaxBodySize(body.performance?.maxBodySize);
57
- if (maxSizeError) {
58
- return res.status(400).json({ error: maxSizeError });
59
- }
60
-
61
- // Check for duplicate
62
- if (findDomain(body.name)) {
63
- return res.status(409).json({ error: `Domain already exists: ${body.name}` });
64
- }
65
-
66
- // Build domain object with defaults
67
- const domain = createDomain({
68
- name: body.name,
69
- port: Number(body.port),
70
- backendHost: body.backendHost ?? DOMAIN_DEFAULTS.backendHost,
71
- upstreamType: body.upstreamType ?? DOMAIN_DEFAULTS.upstreamType,
72
- www: body.www ?? false,
73
- ssl: {
74
- enabled: body.ssl?.enabled ?? false,
75
- certPath: body.ssl?.certPath ?? '',
76
- keyPath: body.ssl?.keyPath ?? '',
77
- redirect: body.ssl?.redirect ?? true,
78
- hsts: body.ssl?.hsts ?? false,
79
- hstsMaxAge: body.ssl?.hstsMaxAge ?? DOMAIN_DEFAULTS.ssl.hstsMaxAge,
80
- },
81
- performance: {
82
- maxBodySize: body.performance?.maxBodySize ?? DOMAIN_DEFAULTS.performance.maxBodySize,
83
- readTimeout: body.performance?.readTimeout ?? DOMAIN_DEFAULTS.performance.readTimeout,
84
- connectTimeout: body.performance?.connectTimeout ?? DOMAIN_DEFAULTS.performance.connectTimeout,
85
- proxyBuffers: body.performance?.proxyBuffers ?? false,
86
- gzip: body.performance?.gzip ?? true,
87
- gzipTypes: body.performance?.gzipTypes ?? DOMAIN_DEFAULTS.performance.gzipTypes,
88
- },
89
- security: {
90
- rateLimit: body.security?.rateLimit ?? false,
91
- rateLimitRate: body.security?.rateLimitRate ?? DOMAIN_DEFAULTS.security.rateLimitRate,
92
- rateLimitBurst: body.security?.rateLimitBurst ?? DOMAIN_DEFAULTS.security.rateLimitBurst,
93
- securityHeaders: body.security?.securityHeaders ?? false,
94
- custom404: body.security?.custom404 ?? false,
95
- custom50x: body.security?.custom50x ?? false,
96
- },
97
- advanced: {
98
- accessLog: body.advanced?.accessLog ?? true,
99
- customLocations: body.advanced?.customLocations ?? '',
100
- },
101
- wildcard: body.wildcard ?? false,
102
- enabled: true,
103
- });
104
-
105
- // Cert existence check (FR-001): prevent saving a config that references non-existent cert files
106
- if (domain.ssl.enabled && domain.ssl.certPath) {
107
- try {
108
- await fs.access(domain.ssl.certPath, fs.constants.F_OK);
109
- } catch {
110
- return res.status(422).json({
111
- error: 'cert_missing',
112
- certPath: domain.ssl.certPath,
113
- keyPath: domain.ssl.keyPath,
114
- hint: 'The SSL certificate files do not exist at the configured paths. Create the certificate first, or disable SSL.',
115
- });
116
- }
117
- }
118
-
119
- const { nginxDir } = loadConfig();
120
-
121
- try {
122
- await generateConf(domain);
123
- } catch (err) {
124
- return res.status(500).json({ error: 'Failed to write nginx conf', details: err.message });
125
- }
126
-
127
- const testCmd = isWindows ? nginxTestCmd(nginxDir) : 'nginx -t';
128
- const testResult = await run(testCmd, { cwd: nginxDir });
129
- if (!isNginxTestOk(testResult)) {
130
- try { await fs.unlink(domain.configFile); } catch { /* ignore */ }
131
- const output = testResult.stderr || testResult.stdout;
132
- const error = !isWindows && output.includes('password is required')
133
- ? 'Linux permissions not configured. Open Settings → Setup Linux Permissions.'
134
- : 'nginx config test failed';
135
- return res.status(500).json({ error, output });
136
- }
137
-
138
- const domains = getDomains();
139
- domains.push(domain);
140
- saveDomains(domains);
141
-
142
- res.status(201).json(domain);
143
- });
144
-
145
- // ─── PUT /api/domains/:name ───────────────────────────────────────────────────
146
-
147
- router.put('/:name', async (req, res) => {
148
- const { name } = req.params;
149
- const existing = findDomain(name);
150
- if (!existing) {
151
- return res.status(404).json({ error: `Domain not found: ${name}` });
152
- }
153
-
154
- const body = req.body ?? {};
155
-
156
- // Validate port if provided (skip when backendHost is a full external URL)
157
- const backendIsUrl = /^https?:\/\//i.test(body.backendHost ?? existing.backendHost ?? '');
158
- if (body.port !== undefined && !backendIsUrl) {
159
- const portError = validatePort(body.port);
160
- if (portError) {
161
- return res.status(400).json({ error: portError });
162
- }
163
- body.port = Number(body.port);
164
- }
165
-
166
- // Validate upstreamType if provided
167
- if (body.upstreamType !== undefined) {
168
- const upstreamError = validateUpstreamType(body.upstreamType);
169
- if (upstreamError) {
170
- return res.status(400).json({ error: upstreamError });
171
- }
172
- }
173
-
174
- // name is immutable — merge everything except name and configFile
175
- const { name: _ignored, configFile: _cf, ...updates } = body;
176
-
177
- // Deep merge nested objects
178
- const updatedDomain = {
179
- ...existing,
180
- ...updates,
181
- ssl: { ...existing.ssl, ...updates.ssl },
182
- performance: { ...existing.performance, ...updates.performance },
183
- security: { ...existing.security, ...updates.security },
184
- advanced: { ...existing.advanced, ...updates.advanced },
185
- wildcard: updates.wildcard ?? existing.wildcard ?? false,
186
- updatedAt: new Date().toISOString(),
187
- };
188
-
189
- const { nginxDir } = loadConfig();
190
- const bakPath = existing.configFile ? `${existing.configFile}.bak` : null;
191
-
192
- // Backup existing conf
193
- if (bakPath && existing.configFile) {
194
- try {
195
- await fs.copyFile(existing.configFile, bakPath);
196
- } catch { /* file absent — skip backup */ }
197
- }
198
-
199
- try {
200
- await generateConf(updatedDomain);
201
- } catch (err) {
202
- if (bakPath) {
203
- try { await fs.copyFile(bakPath, existing.configFile); } catch { /* ignore restore failure */ }
204
- }
205
- return res.status(500).json({ error: 'Failed to write nginx conf', details: err.message });
206
- }
207
-
208
- const testCmd = isWindows ? nginxTestCmd(nginxDir) : 'nginx -t';
209
- const testResult = await run(testCmd, { cwd: nginxDir });
210
- if (!isNginxTestOk(testResult)) {
211
- if (bakPath) {
212
- try { await fs.rename(bakPath, existing.configFile); } catch { /* ignore */ }
213
- }
214
- const output = testResult.stderr || testResult.stdout;
215
- const error = !isWindows && output.includes('password is required')
216
- ? 'Linux permissions not configured. Open Settings → Setup Linux Permissions.'
217
- : 'nginx config test failed';
218
- return res.status(500).json({ error, output });
219
- }
220
-
221
- const domains = getDomains();
222
- const idx = domains.findIndex((d) => d.name === name);
223
- domains[idx] = updatedDomain;
224
- saveDomains(domains);
225
-
226
- res.json(updatedDomain);
227
- });
228
-
229
- // ─── DELETE /api/domains/:name ────────────────────────────────────────────────
230
-
231
- router.delete('/:name', async (req, res) => {
232
- const { name } = req.params;
233
- const deleteCert = req.query.deleteCert === 'true';
234
- const domain = findDomain(name);
235
- if (!domain) {
236
- return res.status(404).json({ error: `Domain not found: ${name}` });
237
- }
238
-
239
- // Delete nginx conf file
240
- if (domain.configFile) {
241
- try {
242
- await fs.unlink(domain.configFile);
243
- } catch (err) {
244
- if (err.code !== 'ENOENT') {
245
- return res.status(500).json({ error: 'Failed to delete conf file', details: err.message });
246
- }
247
- }
248
- }
249
-
250
- // Optionally delete the SSL certificate directory for this domain
251
- if (deleteCert && domain.ssl?.enabled) {
252
- const { sslDir } = loadConfig();
253
- const certDir = path.join(sslDir, name);
254
- try {
255
- await fs.rm(certDir, { recursive: true, force: true });
256
- } catch { /* ignore — cert dir may not exist */ }
257
- }
258
-
259
- const domains = getDomains().filter((d) => d.name !== name);
260
- saveDomains(domains);
261
-
262
- res.json({ deleted: name, certDeleted: deleteCert && domain.ssl?.enabled });
263
- });
264
-
265
- // ─── PUT /api/domains/:name/toggle ───────────────────────────────────────────
266
-
267
- router.put('/:name/toggle', async (req, res) => {
268
- const { name } = req.params;
269
- const domain = findDomain(name);
270
- if (!domain) {
271
- return res.status(404).json({ error: `Domain not found: ${name}` });
272
- }
273
-
274
- const { nginxDir } = loadConfig();
275
- const isEnabled = domain.enabled !== false;
276
- const confPath = domain.configFile;
277
-
278
- if (!confPath) {
279
- return res.status(400).json({ error: 'Domain has no config file path stored' });
280
- }
281
-
282
- // Normalise paths regardless of current stored extension
283
- const basePath = confPath.replace(/\.disabled$/, '');
284
- const enabledPath = basePath;
285
- const disabledPath = `${basePath}.disabled`;
286
-
287
- if (isEnabled) {
288
- // Disable: rename .conf → .conf.disabled, then reload nginx
289
- try {
290
- await fs.rename(enabledPath, disabledPath);
291
- } catch (err) {
292
- return res.status(500).json({ error: 'Failed to rename config file', details: err.message });
293
- }
294
-
295
- const domains = getDomains();
296
- const idx = domains.findIndex(d => d.name === name);
297
- domains[idx] = { ...domain, enabled: false, configFile: disabledPath, updatedAt: new Date().toISOString() };
298
- saveDomains(domains);
299
-
300
- // Reload so nginx stops serving this domain
301
- await run(isWindows ? nginxReloadCmd(nginxDir) : 'sudo -n /usr/bin/systemctl reload nginx', { cwd: nginxDir });
302
-
303
- return res.json({ enabled: false });
304
- } else {
305
- // Enable: rename .conf.disabled → .conf, test, reload
306
- try {
307
- await fs.rename(disabledPath, enabledPath);
308
- } catch (err) {
309
- return res.status(500).json({ error: 'Failed to rename config file', details: err.message });
310
- }
311
-
312
- const testCmd = isWindows ? nginxTestCmd(nginxDir) : 'nginx -t';
313
- const testResult = await run(testCmd, { cwd: nginxDir });
314
- if (!isNginxTestOk(testResult)) {
315
- // Roll back rename
316
- await fs.rename(enabledPath, disabledPath).catch(() => {});
317
- const output = testResult.stderr || testResult.stdout;
318
- const error = !isWindows && output.includes('password is required')
319
- ? 'Linux permissions not configured. Open Settings → Setup Linux Permissions.'
320
- : 'nginx config test failed';
321
- return res.status(500).json({ error, output });
322
- }
323
-
324
- const domains = getDomains();
325
- const idx = domains.findIndex(d => d.name === name);
326
- domains[idx] = { ...domain, enabled: true, configFile: enabledPath, updatedAt: new Date().toISOString() };
327
- saveDomains(domains);
328
-
329
- await run(isWindows ? nginxReloadCmd(nginxDir) : 'sudo -n /usr/bin/systemctl reload nginx', { cwd: nginxDir });
330
-
331
- return res.json({ enabled: true });
332
- }
333
- });
334
-
335
- // ─── POST /api/domains/:name/reload ──────────────────────────────────────────
336
-
337
- router.post('/:name/reload', async (req, res) => {
338
- const { name } = req.params;
339
- if (!findDomain(name)) {
340
- return res.status(404).json({ error: `Domain not found: ${name}` });
341
- }
342
-
343
- const { nginxDir } = loadConfig();
344
-
345
- const testCmd = isWindows ? nginxTestCmd(nginxDir) : 'nginx -t';
346
- const testResult = await run(testCmd, { cwd: nginxDir });
347
- if (!isNginxTestOk(testResult)) {
348
- const output = testResult.stderr || testResult.stdout;
349
- const error = !isWindows && output.includes('password is required')
350
- ? 'Linux permissions not configured. Open Settings → Setup Linux Permissions.'
351
- : 'nginx config test failed';
352
- return res.status(500).json({ error, output });
353
- }
354
-
355
- const reloadCmd = isWindows ? nginxReloadCmd(nginxDir) : 'sudo -n /usr/bin/systemctl reload nginx';
356
- const reloadResult = await run(reloadCmd, { cwd: nginxDir });
357
- if (!reloadResult.success) {
358
- const output = reloadResult.stderr || reloadResult.stdout;
359
- const error = !isWindows && output.includes('password is required')
360
- ? 'Linux permissions not configured. Open Settings → Setup Linux Permissions.'
361
- : 'nginx reload failed';
362
- return res.status(500).json({ error, output });
363
- }
364
-
365
- res.json({ message: 'nginx reloaded successfully' });
366
- });
6
+ const controller = new DomainsController();
7
+
8
+ /**
9
+ * Every route below requires a dashboard session. See lib/requireAuth.js —
10
+ * this is the single gate, and removing it exposes these endpoints to anyone
11
+ * who can reach the dashboard port.
12
+ */
13
+ router.use(requireAuth);
14
+
15
+
16
+ router.get('/', (req, res, next) => controller.list(req, res, next));
17
+ router.post('/', (req, res, next) => controller.create(req, res, next));
18
+ router.put('/:name', (req, res, next) => controller.update(req, res, next));
19
+ router.delete('/:name', (req, res, next) => controller.delete(req, res, next));
20
+ router.put('/:name/toggle', (req, res, next) => controller.toggle(req, res, next));
21
+ router.post('/:name/reload', (req, res, next) => controller.reload(req, res, next));
22
+ router.get('/:name/notifications', (req, res, next) => controller.getNotifications(req, res, next));
23
+ router.put('/:name/notifications', (req, res, next) => controller.updateNotifications(req, res, next));
367
24
 
368
25
  export default router;
@@ -0,0 +1,22 @@
1
+ // src/dashboard/routes/hub.js
2
+ import { Router } from 'express';
3
+ import {
4
+ connectAgent,
5
+ unlinkHub,
6
+ hubStatus,
7
+ updatePermissions,
8
+ } from '../controllers/hubController.js';
9
+ import { requireAuth } from '../lib/requireAuth.js';
10
+
11
+ const router = Router();
12
+
13
+ // The shared gate — see lib/requireAuth.js.
14
+ router.use(requireAuth);
15
+
16
+ // The hub generates connection strings; this server only consumes them.
17
+ router.post('/connect', connectAgent);
18
+ router.delete('/link', unlinkHub);
19
+ router.get('/status', hubStatus);
20
+ router.put('/permissions', updatePermissions);
21
+
22
+ export default router;