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,14 +1,11 @@
1
1
  import { createServer } from 'http';
2
- import http from 'http';
3
2
  import { createRequire } from 'module';
4
- import { spawn } from 'child_process';
5
3
  import express from 'express';
6
4
  import { fileURLToPath } from 'url';
7
5
  import path from 'path';
8
6
  import os from 'os';
9
7
  import crypto from 'crypto';
10
8
  import session from 'express-session';
11
- import { Server as SocketIO } from 'socket.io';
12
9
  import { loadConfig } from '../core/config.js';
13
10
  import { dbGet, dbSet } from '../core/db.js';
14
11
  import authRouter from './routes/auth.js';
@@ -16,8 +13,7 @@ import domainsRouter from './routes/domains.js';
16
13
  import sslRouter from './routes/ssl.js';
17
14
  import nginxRouter from './routes/nginx.js';
18
15
  import settingsRouter from './routes/settings.js';
19
- import { getStatus } from './lib/nginx-service.js';
20
- import { listAllCerts } from './lib/cert-reader.js';
16
+ import { initSocket } from './socketManager.js';
21
17
 
22
18
  const require = createRequire(import.meta.url);
23
19
  const FileStore = require('session-file-store')(session);
@@ -67,156 +63,7 @@ app.use((req, res) => res.render('index'));
67
63
  // ─── HTTP server + Socket.io ──────────────────────────────────────────────────
68
64
 
69
65
  const httpServer = createServer(app);
70
- const io = new SocketIO(httpServer);
71
-
72
- let connectedClients = 0;
73
-
74
- async function emitNginxStatus(target) {
75
- try {
76
- const status = await getStatus();
77
- target.emit('nginx:status', status);
78
- // Emit notification if nginx is down
79
- if (!status.running) {
80
- target.emit('notification:new', {
81
- id: 'nginx-down',
82
- type: 'nginx_down',
83
- severity: 'danger',
84
- message: 'Nginx is not running',
85
- timestamp: Date.now(),
86
- });
87
- }
88
- } catch (err) {
89
- target.emit('nginx:status', { running: false, version: null, pid: null, error: err.message });
90
- }
91
- }
92
-
93
- // ─── Cert expiry notifications ────────────────────────────────────────────────
94
- async function emitCertNotifications(target) {
95
- try {
96
- const certs = await listAllCerts();
97
- for (const cert of certs) {
98
- if (cert.daysLeft !== null && cert.daysLeft < 30) {
99
- const severity = cert.daysLeft < 10 ? 'danger' : 'warning';
100
- target.emit('notification:new', {
101
- id: `cert-expiry-${cert.domain}`,
102
- type: 'cert_expiry',
103
- severity,
104
- message: `SSL cert for ${cert.domain} expires in ${cert.daysLeft} day${cert.daysLeft === 1 ? '' : 's'}`,
105
- domain: cert.domain,
106
- timestamp: Date.now(),
107
- });
108
- }
109
- }
110
- } catch { /* non-fatal */ }
111
- }
112
-
113
- // ─── Domain health checks ─────────────────────────────────────────────────────
114
- function checkDomainHealth(host, port) {
115
- return new Promise((resolve) => {
116
- const req = http.request({ host, port: Number(port), path: '/', method: 'HEAD', timeout: 5000 }, (res) => {
117
- resolve({ up: true, status: res.statusCode });
118
- res.resume();
119
- });
120
- req.on('timeout', () => { req.destroy(); resolve({ up: false }); });
121
- req.on('error', () => resolve({ up: false }));
122
- req.end();
123
- });
124
- }
125
-
126
- async function emitDomainHealth(target) {
127
- try {
128
- const domains = dbGet('domains') || [];
129
- const results = await Promise.all(
130
- domains.map(async (d) => {
131
- const host = d.backendHost || '127.0.0.1';
132
- const port = d.port || 80;
133
- // Skip external URL backends
134
- if (typeof host === 'string' && host.startsWith('http')) return { name: d.name, up: null };
135
- const { up } = await checkDomainHealth(host, port);
136
- return { name: d.name, up };
137
- })
138
- );
139
- target.emit('domain:health', results);
140
- } catch { /* non-fatal */ }
141
- }
142
-
143
- // ─── Live log streaming ───────────────────────────────────────────────────────
144
- const activeTails = new Map(); // socketId → { process, logFile }
145
-
146
- function getLogPath(logFile) {
147
- const { nginxDir } = loadConfig();
148
- const file = logFile === 'access' ? 'access.log' : 'error.log';
149
- // Linux standard path first, fall back to nginxDir/logs/
150
- if (process.platform !== 'win32') {
151
- return `/var/log/nginx/${file}`;
152
- }
153
- return path.join(nginxDir, 'logs', file);
154
- }
155
-
156
- function startTail(socket, logFile) {
157
- // Kill any existing tail for this socket
158
- stopTail(socket.id);
159
-
160
- const logPath = getLogPath(logFile);
161
- const args = process.platform === 'win32'
162
- ? ['Get-Content', '-Path', logPath, '-Wait', '-Tail', '50']
163
- : ['-n', '50', '-f', logPath];
164
- const cmd = process.platform === 'win32' ? 'powershell' : 'tail';
165
-
166
- const child = spawn(cmd, args, { stdio: ['ignore', 'pipe', 'ignore'] });
167
- let buf = '';
168
- child.stdout.on('data', (chunk) => {
169
- buf += chunk.toString();
170
- const lines = buf.split('\n');
171
- buf = lines.pop(); // keep incomplete line in buffer
172
- for (const line of lines) {
173
- if (line.trim()) socket.emit('logs:line', { line: line.trim(), logFile });
174
- }
175
- });
176
- child.on('error', () => {});
177
- child.on('close', () => { activeTails.delete(socket.id); });
178
- activeTails.set(socket.id, { process: child, logFile });
179
- }
180
-
181
- function stopTail(socketId) {
182
- const entry = activeTails.get(socketId);
183
- if (entry) {
184
- try { entry.process.kill(); } catch {}
185
- activeTails.delete(socketId);
186
- }
187
- }
188
-
189
- io.on('connection', (socket) => {
190
- connectedClients++;
191
- emitNginxStatus(socket);
192
- emitCertNotifications(socket);
193
-
194
- socket.on('logs:subscribe', ({ logFile }) => startTail(socket, logFile || 'error'));
195
- socket.on('logs:unsubscribe', () => stopTail(socket.id));
196
-
197
- // Send initial domain health on connect
198
- emitDomainHealth(socket);
199
-
200
- socket.on('disconnect', () => {
201
- connectedClients--;
202
- stopTail(socket.id);
203
- });
204
- });
205
-
206
- // Poll domain health every 60 seconds
207
- setInterval(() => {
208
- if (connectedClients > 0) emitDomainHealth(io);
209
- }, 60_000);
210
-
211
- // Broadcast nginx status to all clients every 5 seconds
212
- setInterval(() => {
213
- if (connectedClients > 0) emitNginxStatus(io);
214
- }, 5000);
215
-
216
- // Check cert expiry every 12 hours
217
- setInterval(() => {
218
- if (connectedClients > 0) emitCertNotifications(io);
219
- }, 12 * 60 * 60 * 1000);
66
+ initSocket(httpServer);
220
67
 
221
68
  // ─── Start ────────────────────────────────────────────────────────────────────
222
69
 
@@ -0,0 +1,282 @@
1
+ import http from 'http';
2
+ import { spawn } from 'child_process';
3
+ import path from 'path';
4
+ import { Server as SocketIO } from 'socket.io';
5
+
6
+ import { getStatus } from './lib/nginx-service.js';
7
+ import { listAllCerts } from './lib/cert-reader.js';
8
+ import { loadConfig } from '../core/config.js';
9
+ import { dbGet } from '../core/db.js';
10
+ import {
11
+ createNginxDownEvent,
12
+ createNginxRecoveredEvent,
13
+ createDomainDownEvent,
14
+ createDomainRecoveredEvent,
15
+ } from '../core/events.js';
16
+ import { sendNotification } from '../core/notifier.js';
17
+ import {
18
+ getEffectiveChannelIds,
19
+ getAllDomainChannelIds,
20
+ shouldSendNotification,
21
+ } from '../core/domainNotifier.js';
22
+
23
+ let connectedClients = 0;
24
+ const activeTails = new Map();
25
+
26
+ /**
27
+ * Emit nginx status and handle notification state transitions.
28
+ * Uses state tracking to prevent spam and support recovery notifications.
29
+ */
30
+ async function emitNginxStatus(target) {
31
+ try {
32
+ const status = await getStatus();
33
+ target.emit('nginx:status', status);
34
+
35
+ const currentStatus = status.running ? 'up' : 'down';
36
+ const decision = shouldSendNotification(null, 'nginx_down', currentStatus);
37
+
38
+ if (decision.shouldNotify) {
39
+ let event;
40
+ if (decision.reason === 'recovery') {
41
+ event = createNginxRecoveredEvent();
42
+ } else {
43
+ event = createNginxDownEvent();
44
+ }
45
+
46
+ console.log(`[socketManager] Sending nginx notification: ${decision.reason}`);
47
+ target.emit('notification:new', event);
48
+
49
+ // External channel routing (fire-and-forget, isolated)
50
+ try {
51
+ const channels = getAllDomainChannelIds('nginx_down');
52
+ await sendNotification(event, channels);
53
+ } catch (err) {
54
+ console.error('[socketManager] sendNotification failed:', err.message);
55
+ }
56
+ }
57
+ } catch (err) {
58
+ target.emit('nginx:status', { running: false, version: null, pid: null, error: err.message });
59
+ }
60
+ }
61
+
62
+ /**
63
+ * Emit cert expiry notifications.
64
+ * Note: Cert expiry doesn't use state tracking because it's a time-based event,
65
+ * not a state transition. We notify whenever a cert is expiring, regardless of
66
+ * whether we notified before.
67
+ */
68
+ async function emitCertNotifications(target) {
69
+ try {
70
+ const certs = await listAllCerts();
71
+ for (const cert of certs) {
72
+ if (cert.daysLeft !== null && cert.daysLeft < 30) {
73
+ const event = {
74
+ id: `cert-expiry-${cert.domain}-${Date.now()}`,
75
+ type: 'cert_expiry',
76
+ severity: cert.daysLeft < 10 ? 'danger' : 'warning',
77
+ message: `🔒 SSL cert for ${cert.domain} expires in ${cert.daysLeft} day${cert.daysLeft === 1 ? '' : 's'}`,
78
+ domain: cert.domain,
79
+ timestamp: Date.now(),
80
+ };
81
+ target.emit('notification:new', event);
82
+
83
+ // External channel routing (fire-and-forget, isolated)
84
+ try {
85
+ const channels = getEffectiveChannelIds(cert.domain, 'cert_expiry');
86
+ await sendNotification(event, channels);
87
+ } catch (err) {
88
+ console.error('[socketManager] sendNotification failed:', err.message);
89
+ }
90
+ }
91
+ }
92
+ } catch {
93
+ /* non-fatal */
94
+ }
95
+ }
96
+
97
+ /**
98
+ * Check if a domain backend is responding.
99
+ */
100
+ function checkDomainHealth(host, port) {
101
+ return new Promise((resolve) => {
102
+ const req = http.request(
103
+ {
104
+ host,
105
+ port: Number(port),
106
+ path: '/',
107
+ method: 'HEAD',
108
+ timeout: 5000,
109
+ },
110
+ (res) => {
111
+ resolve({ up: true, status: res.statusCode });
112
+ res.resume();
113
+ }
114
+ );
115
+ req.on('timeout', () => {
116
+ req.destroy();
117
+ resolve({ up: false });
118
+ });
119
+ req.on('error', () => resolve({ up: false }));
120
+ req.end();
121
+ });
122
+ }
123
+
124
+ /**
125
+ * Emit domain health status and handle notification state transitions.
126
+ * Uses state tracking to:
127
+ * 1. Prevent spam (don't re-notify if already down)
128
+ * 2. Send recovery notifications when domain comes back up
129
+ */
130
+ async function emitDomainHealth(target) {
131
+ try {
132
+ const domains = dbGet('domains') || [];
133
+ const results = await Promise.all(
134
+ domains.map(async (d) => {
135
+ const host = d.backendHost || '127.0.0.1';
136
+ const port = d.port || 80;
137
+
138
+ // Skip external URL backends
139
+ if (typeof host === 'string' && host.startsWith('http')) return { name: d.name, up: null };
140
+
141
+ const { up } = await checkDomainHealth(host, port);
142
+ return { name: d.name, up, port, host };
143
+ })
144
+ );
145
+
146
+ target.emit('domain:health', results);
147
+
148
+ // Process state transitions for each domain
149
+ for (const result of results) {
150
+ if (result.up === null) continue; // Skip external URL backends
151
+
152
+ const currentStatus = result.up ? 'up' : 'down';
153
+ const decision = shouldSendNotification(result.name, 'domain_health', currentStatus);
154
+
155
+ if (decision.shouldNotify) {
156
+ let event;
157
+ if (decision.reason === 'recovery') {
158
+ event = createDomainRecoveredEvent(result.name, result.port);
159
+ } else {
160
+ event = createDomainDownEvent(result.name, result.port);
161
+ }
162
+
163
+ console.log(`[socketManager] Sending domain health notification for ${result.name}: ${decision.reason}`);
164
+ target.emit('notification:new', event);
165
+
166
+ try {
167
+ const channelIds = getEffectiveChannelIds(result.name, 'domain_health');
168
+ await sendNotification(event, channelIds);
169
+ } catch (err) {
170
+ console.error('[socketManager] domain health sendNotification failed:', err.message);
171
+ }
172
+ }
173
+ }
174
+ } catch (err) {
175
+ console.error('[socketManager] emitDomainHealth error:', err.message);
176
+ }
177
+ }
178
+
179
+ /**
180
+ * Get the path to a log file.
181
+ */
182
+ function getLogPath(logFile) {
183
+ const { nginxDir } = loadConfig();
184
+ const file = logFile === 'access' ? 'access.log' : 'error.log';
185
+
186
+ // Linux standard path first, fall back to nginxDir/logs/
187
+ if (process.platform !== 'win32') {
188
+ return `/var/log/nginx/${file}`;
189
+ }
190
+ return path.join(nginxDir, 'logs', file);
191
+ }
192
+
193
+ /**
194
+ * Start tailing a log file for a socket.
195
+ */
196
+ function startTail(socket, logFile) {
197
+ // Kill any existing tail for this socket
198
+ stopTail(socket.id);
199
+
200
+ const logPath = getLogPath(logFile);
201
+ const args = process.platform === 'win32'
202
+ ? ['Get-Content', '-Path', logPath, '-Wait', '-Tail', '50']
203
+ : ['-n', '50', '-f', logPath];
204
+ const cmd = process.platform === 'win32' ? 'powershell' : 'tail';
205
+
206
+ const child = spawn(cmd, args, {
207
+ stdio: ['ignore', 'pipe', 'ignore'],
208
+ windowsHide: true,
209
+ });
210
+
211
+ let buf = '';
212
+ child.stdout.on('data', (chunk) => {
213
+ buf += chunk.toString();
214
+ const lines = buf.split('\n');
215
+ buf = lines.pop(); // keep incomplete line in buffer
216
+ for (const line of lines) {
217
+ if (line.trim()) socket.emit('logs:line', { line: line.trim(), logFile });
218
+ }
219
+ });
220
+
221
+ child.on('error', () => {});
222
+ child.on('close', () => {
223
+ activeTails.delete(socket.id);
224
+ });
225
+
226
+ activeTails.set(socket.id, { process: child, logFile });
227
+ }
228
+
229
+ /**
230
+ * Stop tailing a log file for a socket.
231
+ */
232
+ function stopTail(socketId) {
233
+ const entry = activeTails.get(socketId);
234
+ if (entry) {
235
+ try {
236
+ entry.process.kill();
237
+ } catch {}
238
+ activeTails.delete(socketId);
239
+ }
240
+ }
241
+
242
+ /**
243
+ * Initialize the Socket.IO server.
244
+ */
245
+ function initSocket(httpServer) {
246
+ const io = new SocketIO(httpServer);
247
+
248
+ io.on('connection', (socket) => {
249
+ connectedClients++;
250
+
251
+ emitNginxStatus(socket);
252
+ emitCertNotifications(socket);
253
+
254
+ socket.on('logs:subscribe', ({ logFile }) => startTail(socket, logFile || 'error'));
255
+ socket.on('logs:unsubscribe', () => stopTail(socket.id));
256
+
257
+ // Send initial domain health on connect
258
+ emitDomainHealth(socket);
259
+
260
+ socket.on('disconnect', () => {
261
+ connectedClients--;
262
+ stopTail(socket.id);
263
+ });
264
+ });
265
+
266
+ // Poll domain health every 60 seconds
267
+ setInterval(() => {
268
+ if (connectedClients > 0) emitDomainHealth(io);
269
+ }, 60_000);
270
+
271
+ // Broadcast nginx status to all clients every 5 seconds
272
+ setInterval(() => {
273
+ if (connectedClients > 0) emitNginxStatus(io);
274
+ }, 5000);
275
+
276
+ // Check cert expiry every 12 hours
277
+ setInterval(() => {
278
+ if (connectedClients > 0) emitCertNotifications(io);
279
+ }, 12 * 60 * 60 * 1000);
280
+ }
281
+
282
+ export { initSocket };
@@ -324,7 +324,7 @@ Wildcard SSL requires DNS-01 validation.
324
324
  </div>
325
325
 
326
326
  <!-- Accordion Section: Advanced -->
327
- <div>
327
+ <div class="border-b border-border">
328
328
  <div @click="toggleSection('advanced')" class="flex items-center justify-between p-5 cursor-pointer hover:bg-black/5 dark:hover:bg-white/5 transition-colors group">
329
329
  <span class="form-label !mb-0 group-hover:text-foreground transition-colors">Advanced</span>
330
330
  <svg class="w-4 h-4 text-muted transition-transform duration-200" :class="{ 'rotate-180': sections.advanced }" fill="none" viewBox="0 0 24 24" stroke="currentColor"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M19 9l-7 7-7-7" /></svg>
@@ -350,6 +350,69 @@ placeholder="location /api/v2 {&#10; proxy_pass http://localhost:8080;&#10;}"></
350
350
  </div>
351
351
  </div>
352
352
 
353
+ <!-- Accordion Section: Notifications (edit mode only) -->
354
+ <div v-if="domains.editingName">
355
+ <div @click="toggleSection('notifications')" class="flex items-center justify-between p-5 cursor-pointer hover:bg-black/5 dark:hover:bg-white/5 transition-colors group">
356
+ <span class="form-label !mb-0 group-hover:text-foreground transition-colors">Notifications</span>
357
+ <svg class="w-4 h-4 text-muted transition-transform duration-200" :class="{ 'rotate-180': sections.notifications }" fill="none" viewBox="0 0 24 24" stroke="currentColor"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M19 9l-7 7-7-7" /></svg>
358
+ </div>
359
+ <div v-show="sections.notifications" class="p-6 pt-4 space-y-5 border-t border-border/50" style="background: rgba(0,0,0,0.1)">
360
+
361
+ <!-- No channels configured -->
362
+ <div v-if="channels.list.length === 0" class="p-4 border border-border/50 rounded-[12px] text-center">
363
+ <p class="text-muted text-[13px]">No channels configured —
364
+ <button type="button" @click="navigateTo('settings')" class="text-primary underline">go to Settings</button>
365
+ to add one first.</p>
366
+ </div>
367
+
368
+ <template v-else>
369
+
370
+ <!-- Port / Health -->
371
+ <div class="space-y-3">
372
+ <div class="flex items-center gap-4">
373
+ <label class="relative inline-flex items-center cursor-pointer flex-shrink-0">
374
+ <input type="checkbox" v-model="domains.form.notifications.domain_health.enabled" class="sr-only peer" />
375
+ <div class="w-8 h-4 bg-black/20 dark:bg-white/10 border border-border peer-focus:outline-none rounded-full peer peer-checked:after:translate-x-full after:content-[''] after:absolute after:top-[2px] after:left-[2px] after:bg-white after:rounded-full after:h-3 after:w-3 after:transition-all peer-checked:bg-primary"></div>
376
+ </label>
377
+ <span class="text-[13px] font-bold text-foreground">Port / Health check</span>
378
+ </div>
379
+ <div v-if="domains.form.notifications.domain_health.enabled" class="pl-10 flex flex-wrap gap-2">
380
+ <label v-for="ch in channels.list" :key="ch.id"
381
+ class="flex items-center gap-2 cursor-pointer px-3 py-1.5 rounded-[8px] border border-border/50 hover:border-primary/50 transition-colors text-[12px]">
382
+ <input type="checkbox" :value="ch.id" v-model="domains.form.notifications.domain_health.channelIds" class="w-3.5 h-3.5 text-primary" />
383
+ <span class="font-medium">{{ ch.name }}</span>
384
+ <span class="text-muted text-[10px] opacity-70">({{ ch.type }})</span>
385
+ </label>
386
+ </div>
387
+ </div>
388
+
389
+ <div class="border-t border-border/50"></div>
390
+
391
+ <!-- SSL / Certificate expiry -->
392
+ <div class="space-y-3">
393
+ <div class="flex items-center gap-4">
394
+ <label class="relative inline-flex items-center cursor-pointer flex-shrink-0">
395
+ <input type="checkbox" v-model="domains.form.notifications.cert_expiry.enabled" class="sr-only peer" />
396
+ <div class="w-8 h-4 bg-black/20 dark:bg-white/10 border border-border peer-focus:outline-none rounded-full peer peer-checked:after:translate-x-full after:content-[''] after:absolute after:top-[2px] after:left-[2px] after:bg-white after:rounded-full after:h-3 after:w-3 after:transition-all peer-checked:bg-primary"></div>
397
+ </label>
398
+ <span class="text-[13px] font-bold text-foreground">SSL / Certificate expiry</span>
399
+ </div>
400
+ <div v-if="domains.form.notifications.cert_expiry.enabled" class="pl-10 flex flex-wrap gap-2">
401
+ <label v-for="ch in channels.list" :key="ch.id"
402
+ class="flex items-center gap-2 cursor-pointer px-3 py-1.5 rounded-[8px] border border-border/50 hover:border-primary/50 transition-colors text-[12px]">
403
+ <input type="checkbox" :value="ch.id" v-model="domains.form.notifications.cert_expiry.channelIds" class="w-3.5 h-3.5 text-primary" />
404
+ <span class="font-medium">{{ ch.name }}</span>
405
+ <span class="text-muted text-[10px] opacity-70">({{ ch.type }})</span>
406
+ </label>
407
+ </div>
408
+ </div>
409
+
410
+
411
+ </template>
412
+
413
+ </div>
414
+ </div>
415
+
353
416
  </div>
354
417
  </div>
355
418
  </div>
@@ -74,7 +74,7 @@
74
74
  "
75
75
  onmouseover="this.style.transform='scale(1.05)'"
76
76
  onmouseout="this.style.transform='scale(1)'">
77
- <img src="/img/icon.png" alt="Easy DevOps" style="width: 72px; height: 72px; object-fit: contain;" />
77
+ <img src="/img/icon_b.png" alt="Easy DevOps" style="width: 72px; height: 72px; object-fit: contain;" />
78
78
  </div>
79
79
  <h1 style="
80
80
  font-size: 26px;