easy-devops 1.2.0 → 1.2.1

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.
@@ -1,368 +1,16 @@
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';
14
3
 
15
4
  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
- });
5
+ const controller = new DomainsController();
6
+
7
+ router.get('/', (req, res, next) => controller.list(req, res, next));
8
+ router.post('/', (req, res, next) => controller.create(req, res, next));
9
+ router.put('/:name', (req, res, next) => controller.update(req, res, next));
10
+ router.delete('/:name', (req, res, next) => controller.delete(req, res, next));
11
+ router.put('/:name/toggle', (req, res, next) => controller.toggle(req, res, next));
12
+ router.post('/:name/reload', (req, res, next) => controller.reload(req, res, next));
13
+ router.get('/:name/notifications', (req, res, next) => controller.getNotifications(req, res, next));
14
+ router.put('/:name/notifications', (req, res, next) => controller.updateNotifications(req, res, next));
367
15
 
368
16
  export default router;
@@ -1,151 +1,18 @@
1
1
  import express from 'express';
2
- import {
3
- getStatus,
4
- reload,
5
- restart,
6
- start,
7
- stop,
8
- test,
9
- listConfigs,
10
- getConfig,
11
- saveConfig,
12
- getLogs,
13
- NginxNotFoundError,
14
- NginxConfigError,
15
- InvalidFilenameError,
16
- } from '../lib/nginx-service.js';
2
+ import NginxController from '../controllers/nginxController.js';
17
3
 
18
4
  const router = express.Router();
19
-
20
- // ─── Error Handler Helper ─────────────────────────────────────────────────────
21
-
22
- function handleError(err, res) {
23
- if (err instanceof NginxNotFoundError) {
24
- return res.status(503).json({ error: 'nginx not installed' });
25
- }
26
- if (err instanceof NginxConfigError) {
27
- return res.status(400).json({ success: false, output: err.output });
28
- }
29
- if (err instanceof InvalidFilenameError) {
30
- return res.status(400).json({ error: 'Invalid filename' });
31
- }
32
- if (err.code === 'ENOENT') {
33
- return res.status(404).json({ error: 'Config file not found' });
34
- }
35
- return res.status(500).json({ error: 'Internal server error' });
36
- }
37
-
38
- // ─── US1: GET /api/nginx/status ───────────────────────────────────────────────
39
-
40
- router.get('/status', async (req, res) => {
41
- try {
42
- const status = await getStatus();
43
- res.json(status);
44
- } catch (err) {
45
- handleError(err, res);
46
- }
47
- });
48
-
49
- // ─── US2: POST /api/nginx/reload ─────────────────────────────────────────────
50
-
51
- router.post('/reload', async (req, res) => {
52
- try {
53
- const result = await reload();
54
- res.json(result);
55
- } catch (err) {
56
- handleError(err, res);
57
- }
58
- });
59
-
60
- // ─── US2: POST /api/nginx/restart ────────────────────────────────────────────
61
-
62
- router.post('/restart', async (req, res) => {
63
- try {
64
- const result = await restart();
65
- res.json(result);
66
- } catch (err) {
67
- handleError(err, res);
68
- }
69
- });
70
-
71
- // ─── US1: POST /api/nginx/start ──────────────────────────────────────────────
72
-
73
- router.post('/start', async (req, res) => {
74
- try {
75
- const result = await start();
76
- res.json(result);
77
- } catch (err) {
78
- handleError(err, res);
79
- }
80
- });
81
-
82
- // ─── US1: POST /api/nginx/stop ───────────────────────────────────────────────
83
-
84
- router.post('/stop', async (req, res) => {
85
- try {
86
- const result = await stop();
87
- res.json(result);
88
- } catch (err) {
89
- handleError(err, res);
90
- }
91
- });
92
-
93
- // ─── US3: POST /api/nginx/test ───────────────────────────────────────────────
94
-
95
- router.post('/test', async (req, res) => {
96
- try {
97
- const result = await test();
98
- res.json(result);
99
- } catch (err) {
100
- handleError(err, res);
101
- }
102
- });
103
-
104
- // ─── US4: GET /api/nginx/configs ─────────────────────────────────────────────
105
-
106
- router.get('/configs', async (req, res) => {
107
- try {
108
- const configs = await listConfigs();
109
- res.json(configs);
110
- } catch (err) {
111
- handleError(err, res);
112
- }
113
- });
114
-
115
- // ─── US4: GET /api/nginx/config/:filename ────────────────────────────────────
116
-
117
- router.get('/config/:filename', async (req, res) => {
118
- try {
119
- const result = await getConfig(req.params.filename);
120
- res.json(result);
121
- } catch (err) {
122
- handleError(err, res);
123
- }
124
- });
125
-
126
- // ─── US4: POST /api/nginx/config/:filename ───────────────────────────────────
127
-
128
- router.post('/config/:filename', async (req, res) => {
129
- if (typeof req.body.content !== 'string') {
130
- return res.status(400).json({ error: 'content must be a string' });
131
- }
132
- try {
133
- const result = await saveConfig(req.params.filename, req.body.content);
134
- res.json(result);
135
- } catch (err) {
136
- handleError(err, res);
137
- }
138
- });
139
-
140
- // ─── US5: GET /api/nginx/logs ────────────────────────────────────────────────
141
-
142
- router.get('/logs', async (req, res) => {
143
- try {
144
- const result = await getLogs(100);
145
- res.json(result);
146
- } catch (err) {
147
- handleError(err, res);
148
- }
149
- });
5
+ const controller = new NginxController();
6
+
7
+ router.get('/status', (req, res, next) => controller.status(req, res, next));
8
+ router.post('/reload', (req, res, next) => controller.reload(req, res, next));
9
+ router.post('/restart', (req, res, next) => controller.restart(req, res, next));
10
+ router.post('/start', (req, res, next) => controller.start(req, res, next));
11
+ router.post('/stop', (req, res, next) => controller.stop(req, res, next));
12
+ router.post('/test', (req, res, next) => controller.test(req, res, next));
13
+ router.get('/configs', (req, res, next) => controller.listConfigs(req, res, next));
14
+ router.get('/config/:filename', (req, res, next) => controller.getConfig(req, res, next));
15
+ router.post('/config/:filename', (req, res, next) => controller.saveConfig(req, res, next));
16
+ router.get('/logs', (req, res, next) => controller.getLogs(req, res, next));
150
17
 
151
18
  export default router;