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.
@@ -0,0 +1,128 @@
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 '../lib/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
+ async getLogs(req, res, next) {
119
+ try {
120
+ const result = await getLogs(100);
121
+ res.json(result);
122
+ } catch (err) {
123
+ this.handleError(err, res);
124
+ }
125
+ }
126
+ }
127
+
128
+ export default NginxController;
@@ -0,0 +1,335 @@
1
+ import fs from 'fs/promises';
2
+ import path from 'path';
3
+ import os from 'os';
4
+ import crypto from 'crypto';
5
+ import { loadConfig, saveConfig } from '../../core/config.js';
6
+ import { validatePort, validateEmail } from '../../core/validators.js';
7
+ import { run, runWithStdin } from '../../core/shell.js';
8
+ import { checkPermissionsConfigured } from '../../core/permissions.js';
9
+ import { dbGet, dbSet } from '../../core/db.js';
10
+ import { loadChannels, saveChannels, sendNotification } from '../../core/notifier.js';
11
+
12
+ class SettingsController {
13
+ get(req, res) {
14
+ try {
15
+ const config = loadConfig();
16
+ const { dashboardPort, nginxDir, sslDir, acmeEmail } = config;
17
+ res.json({
18
+ dashboardPort,
19
+ nginxDir,
20
+ sslDir,
21
+ acmeEmail,
22
+ platform: process.platform === 'win32' ? 'win32' : 'linux',
23
+ });
24
+ } catch (err) {
25
+ res.status(500).json({ error: 'Internal server error' });
26
+ }
27
+ }
28
+
29
+ update(req, res) {
30
+ try {
31
+ const { dashboardPort, dashboardPassword, nginxDir, sslDir, acmeEmail } = req.body;
32
+
33
+ if (dashboardPort !== undefined) {
34
+ const portError = validatePort(parseInt(dashboardPort, 10));
35
+ if (portError) return res.status(400).json({ error: portError });
36
+ }
37
+
38
+ if (dashboardPassword !== undefined && typeof dashboardPassword !== 'string') {
39
+ return res.status(400).json({ error: 'Password must be a string' });
40
+ }
41
+
42
+ if (nginxDir !== undefined && (typeof nginxDir !== 'string' || nginxDir.trim() === '')) {
43
+ return res.status(400).json({ error: 'Nginx directory must be a non-empty string' });
44
+ }
45
+ if (sslDir !== undefined && (typeof sslDir !== 'string' || sslDir.trim() === '')) {
46
+ return res.status(400).json({ error: 'SSL directory must be a non-empty string' });
47
+ }
48
+
49
+ if (acmeEmail !== undefined) {
50
+ const emailError = validateEmail(acmeEmail);
51
+ if (emailError) return res.status(400).json({ error: emailError });
52
+ }
53
+
54
+ const currentConfig = loadConfig();
55
+ const updates = {};
56
+
57
+ if (dashboardPort !== undefined) updates.dashboardPort = parseInt(dashboardPort, 10);
58
+ if (dashboardPassword !== undefined) updates.dashboardPassword = dashboardPassword;
59
+ if (nginxDir !== undefined) updates.nginxDir = nginxDir.trim();
60
+ if (sslDir !== undefined) updates.sslDir = sslDir.trim();
61
+ if (acmeEmail !== undefined) updates.acmeEmail = acmeEmail.trim();
62
+
63
+ saveConfig({ ...currentConfig, ...updates });
64
+ res.json({ success: true });
65
+ } catch (err) {
66
+ res.status(500).json({ error: 'Internal server error' });
67
+ }
68
+ }
69
+
70
+ async getPermissions(req, res) {
71
+ if (process.platform === 'win32') return res.json({ configured: true });
72
+ try {
73
+ const configured = await checkPermissionsConfigured();
74
+ res.json({ configured });
75
+ } catch {
76
+ res.json({ configured: false });
77
+ }
78
+ }
79
+
80
+ async setupPermissions(req, res) {
81
+ if (process.platform === 'win32') {
82
+ return res.status(400).json({ error: 'Not applicable on Windows' });
83
+ }
84
+
85
+ const { password } = req.body ?? {};
86
+ if (!password || typeof password !== 'string') {
87
+ return res.status(400).json({ error: 'Password is required' });
88
+ }
89
+
90
+ const whichResult = await run('which nginx');
91
+ if (!whichResult.success || !whichResult.stdout.trim()) {
92
+ return res.status(500).json({ error: 'nginx not found. Is nginx installed?' });
93
+ }
94
+ const nginxPath = whichResult.stdout.trim().split('\n')[0].trim();
95
+ const user = os.userInfo().username;
96
+
97
+ const sudoRules = [
98
+ '/usr/bin/systemctl start nginx',
99
+ '/usr/bin/systemctl stop nginx',
100
+ '/usr/bin/systemctl reload nginx',
101
+ '/usr/bin/systemctl restart nginx',
102
+ '/usr/bin/systemctl',
103
+ nginxPath,
104
+ `${nginxPath} -t`,
105
+ `${nginxPath} -s reload`,
106
+ `${nginxPath} -s stop`,
107
+ `${nginxPath} -s quit`,
108
+ '/usr/bin/certbot',
109
+ '/usr/bin/mkdir',
110
+ '/usr/bin/cp',
111
+ '/usr/bin/chmod',
112
+ '/usr/bin/chown',
113
+ '/usr/bin/tee',
114
+ ].join(', ');
115
+
116
+ const sudoersContent = `${user} ALL=(ALL) NOPASSWD: ${sudoRules}\n`;
117
+
118
+ const tmpFile = path.join('/tmp', `easy-devops-sudoers-${Date.now()}`);
119
+ try {
120
+ await fs.writeFile(tmpFile, sudoersContent, { mode: 0o600 });
121
+ } catch (err) {
122
+ return res.status(500).json({ error: 'Failed to write temp file', output: err.message });
123
+ }
124
+
125
+ const setupCmd = [
126
+ `mkdir -p /etc/easy-devops /var/log/easy-devops`,
127
+ `chown ${user}:${user} /etc/easy-devops /var/log/easy-devops`,
128
+ `chown -R ${user}:${user} /etc/nginx/conf.d 2>/dev/null || true`,
129
+ `cp '${tmpFile}' /etc/sudoers.d/easy-devops`,
130
+ `chmod 440 /etc/sudoers.d/easy-devops`,
131
+ ].join(' && ');
132
+
133
+ const result = await runWithStdin('sudo', ['-S', 'bash', '-c', setupCmd], password + '\n');
134
+ await fs.unlink(tmpFile).catch(() => {});
135
+
136
+ if (!result.success) {
137
+ const output = result.stderr || result.stdout;
138
+ const wrongPassword = output.includes('incorrect password') || output.includes('Sorry, try again') || output.includes('3 incorrect');
139
+ return res.status(wrongPassword ? 401 : 500).json({
140
+ error: wrongPassword ? 'Incorrect password' : 'Setup failed',
141
+ output,
142
+ });
143
+ }
144
+
145
+ res.json({ success: true });
146
+ }
147
+
148
+ backup(req, res) {
149
+ try {
150
+ const config = loadConfig();
151
+ const domains = dbGet('domains') || [];
152
+ const { dashboardPassword: _pw, ...safeConfig } = config;
153
+ const backup = {
154
+ version: 1,
155
+ exportedAt: new Date().toISOString(),
156
+ config: safeConfig,
157
+ domains,
158
+ };
159
+ res.setHeader('Content-Disposition', `attachment; filename="easy-devops-backup-${Date.now()}.json"`);
160
+ res.setHeader('Content-Type', 'application/json');
161
+ res.json(backup);
162
+ } catch (err) {
163
+ res.status(500).json({ error: 'Export failed' });
164
+ }
165
+ }
166
+
167
+ restore(req, res) {
168
+ try {
169
+ const { config, domains } = req.body ?? {};
170
+ if (!config || typeof config !== 'object') {
171
+ return res.status(400).json({ error: 'Invalid backup: missing config' });
172
+ }
173
+ const current = loadConfig();
174
+ const merged = { ...current, ...config, dashboardPassword: current.dashboardPassword };
175
+ saveConfig(merged);
176
+ if (Array.isArray(domains)) {
177
+ dbSet('domains', domains);
178
+ }
179
+ res.json({ success: true });
180
+ } catch (err) {
181
+ res.status(500).json({ error: 'Restore failed' });
182
+ }
183
+ }
184
+
185
+ // ── Notification Channel CRUD ─────────────────────────────────────────────
186
+
187
+ /**
188
+ * GET /api/settings/channels
189
+ * Returns the full channel list.
190
+ */
191
+ getChannels(req, res) {
192
+ try {
193
+ res.json(loadChannels());
194
+ } catch (err) {
195
+ res.status(500).json({ error: 'Internal server error' });
196
+ }
197
+ }
198
+
199
+ /**
200
+ * POST /api/settings/channels
201
+ * Creates a new named channel.
202
+ */
203
+ createChannel(req, res) {
204
+ try {
205
+ const { name, type, webhookUrl, botToken, chatId, message } = req.body ?? {};
206
+
207
+ if (!name || typeof name !== 'string' || !name.trim()) {
208
+ return res.status(400).json({ error: 'Channel name is required' });
209
+ }
210
+ if (!['discord', 'telegram'].includes(type)) {
211
+ return res.status(400).json({ error: 'Channel type must be discord or telegram' });
212
+ }
213
+ if (type === 'discord' && (!webhookUrl || !webhookUrl.trim())) {
214
+ return res.status(400).json({ error: 'Discord channels require a webhookUrl' });
215
+ }
216
+ if (type === 'telegram') {
217
+ if (!botToken || !botToken.trim()) {
218
+ return res.status(400).json({ error: 'Telegram channels require a botToken' });
219
+ }
220
+ if (!chatId || !chatId.trim()) {
221
+ return res.status(400).json({ error: 'Telegram channels require a chatId' });
222
+ }
223
+ }
224
+
225
+ const channel = {
226
+ id: crypto.randomUUID(),
227
+ name: name.trim(),
228
+ type,
229
+ ...(type === 'discord' ? { webhookUrl: webhookUrl.trim() } : {}),
230
+ ...(type === 'telegram' ? { botToken: botToken.trim(), chatId: chatId.trim() } : {}),
231
+ ...(message && message.trim() ? { message: message.trim() } : {}),
232
+ };
233
+
234
+ const channels = loadChannels();
235
+ channels.push(channel);
236
+ saveChannels(channels);
237
+
238
+ res.status(201).json(channel);
239
+ } catch (err) {
240
+ res.status(500).json({ error: 'Internal server error' });
241
+ }
242
+ }
243
+
244
+ /**
245
+ * PUT /api/settings/channels/:id
246
+ * Updates name and/or credentials for an existing channel.
247
+ * Type is immutable after creation.
248
+ */
249
+ updateChannel(req, res) {
250
+ try {
251
+ const { id } = req.params;
252
+ const channels = loadChannels();
253
+ const idx = channels.findIndex((ch) => ch.id === id);
254
+ if (idx === -1) return res.status(404).json({ error: 'Channel not found' });
255
+
256
+ const existing = channels[idx];
257
+ const { name, webhookUrl, botToken, chatId, message } = req.body ?? {};
258
+
259
+ const updated = { ...existing };
260
+ if (name !== undefined) {
261
+ if (!name.trim()) return res.status(400).json({ error: 'Channel name cannot be empty' });
262
+ updated.name = name.trim();
263
+ }
264
+ if (existing.type === 'discord' && webhookUrl !== undefined) {
265
+ updated.webhookUrl = webhookUrl.trim();
266
+ }
267
+ if (existing.type === 'telegram') {
268
+ if (botToken !== undefined) updated.botToken = botToken.trim();
269
+ if (chatId !== undefined) updated.chatId = chatId.trim();
270
+ }
271
+
272
+ // Handle message field - allow clearing by setting to empty string
273
+ if (message !== undefined) {
274
+ if (message && message.trim()) {
275
+ updated.message = message.trim();
276
+ } else {
277
+ delete updated.message;
278
+ }
279
+ }
280
+
281
+ channels[idx] = updated;
282
+ saveChannels(channels);
283
+ res.json(updated);
284
+ } catch (err) {
285
+ res.status(500).json({ error: 'Internal server error' });
286
+ }
287
+ }
288
+
289
+ /**
290
+ * DELETE /api/settings/channels/:id
291
+ */
292
+ deleteChannel(req, res) {
293
+ try {
294
+ const { id } = req.params;
295
+ const channels = loadChannels();
296
+ const idx = channels.findIndex((ch) => ch.id === id);
297
+ if (idx === -1) return res.status(404).json({ error: 'Channel not found' });
298
+
299
+ channels.splice(idx, 1);
300
+ saveChannels(channels);
301
+ res.json({ deleted: id });
302
+ } catch (err) {
303
+ res.status(500).json({ error: 'Internal server error' });
304
+ }
305
+ }
306
+
307
+ /**
308
+ * POST /api/settings/channels/:id/test
309
+ * Sends a test notification to a single channel.
310
+ */
311
+ async testChannel(req, res) {
312
+ try {
313
+ const { id } = req.params;
314
+ const channels = loadChannels();
315
+ if (!channels.find((ch) => ch.id === id)) {
316
+ return res.status(404).json({ error: 'Channel not found' });
317
+ }
318
+
319
+ await sendNotification(
320
+ {
321
+ type: 'test',
322
+ message: 'Test notification from Easy DevOps. This channel is working correctly.',
323
+ timestamp: new Date().toISOString(),
324
+ },
325
+ [id]
326
+ );
327
+
328
+ res.json({ success: true });
329
+ } catch (err) {
330
+ res.status(500).json({ error: err.message || 'Failed to send test notification' });
331
+ }
332
+ }
333
+ }
334
+
335
+ export default SettingsController;