easy-devops 1.1.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.
Files changed (34) hide show
  1. package/README.md +2 -2
  2. package/package.json +6 -3
  3. package/src/cli/index.js +13 -1
  4. package/src/cli/menus/dashboard.js +1 -1
  5. package/src/core/channels/discord.js +77 -0
  6. package/src/core/channels/telegram.js +120 -0
  7. package/src/core/db.js +8 -1
  8. package/src/core/domainNotifier.js +298 -0
  9. package/src/core/events.js +130 -0
  10. package/src/core/notifier.js +73 -0
  11. package/src/core/shell.js +59 -7
  12. package/src/dashboard/controllers/authController.js +29 -0
  13. package/src/dashboard/controllers/domainsController.js +416 -0
  14. package/src/dashboard/controllers/nginxController.js +128 -0
  15. package/src/dashboard/controllers/settingsController.js +335 -0
  16. package/src/dashboard/controllers/sslController.js +291 -0
  17. package/src/dashboard/public/img/icon.png +0 -0
  18. package/src/dashboard/public/img/icon_b.png +0 -0
  19. package/src/dashboard/public/js/app.js +234 -2
  20. package/src/dashboard/routes/auth.js +12 -22
  21. package/src/dashboard/routes/domains.js +11 -363
  22. package/src/dashboard/routes/nginx.js +13 -146
  23. package/src/dashboard/routes/settings.js +16 -189
  24. package/src/dashboard/routes/ssl.js +9 -276
  25. package/src/dashboard/server.js +24 -27
  26. package/src/dashboard/socketManager.js +282 -0
  27. package/src/dashboard/views/index.ejs +52 -0
  28. package/src/dashboard/views/partials/domain-form.ejs +64 -1
  29. package/src/dashboard/views/partials/domains-panel.ejs +4 -0
  30. package/src/dashboard/views/partials/login.ejs +1 -1
  31. package/src/dashboard/views/partials/logs-panel.ejs +67 -0
  32. package/src/dashboard/views/partials/settings-panel.ejs +263 -87
  33. package/src/dashboard/views/partials/sidebar.ejs +3 -1
  34. /package/src/{dashboard/routes → core/channels}/.gitkeep +0 -0
@@ -1,194 +1,21 @@
1
1
  import express from 'express';
2
- import { spawn } from 'child_process';
3
- import fs from 'fs/promises';
4
- import path from 'path';
5
- import os from 'os';
6
- import { loadConfig, saveConfig } from '../../core/config.js';
7
- import { validatePort, validateEmail } from '../../core/validators.js';
8
- import { run } from '../../core/shell.js';
9
- import { checkPermissionsConfigured } from '../../core/permissions.js';
10
-
11
- // Run a bash command with sudo -S (password read from stdin — no terminal needed)
12
- function runSudoS(bashCmd, password) {
13
- return new Promise((resolve) => {
14
- const child = spawn('sudo', ['-S', 'bash', '-c', bashCmd], {
15
- stdio: ['pipe', 'pipe', 'pipe'],
16
- });
17
- let stdout = '', stderr = '';
18
- child.stdout.on('data', d => { stdout += d; });
19
- child.stderr.on('data', d => { stderr += d; });
20
- child.stdin.write(password + '\n');
21
- child.stdin.end();
22
- child.on('close', code => resolve({ success: code === 0, stdout: stdout.trim(), stderr: stderr.trim() }));
23
- child.on('error', err => resolve({ success: false, stdout: '', stderr: err.message }));
24
- });
25
- }
2
+ import SettingsController from '../controllers/settingsController.js';
26
3
 
27
4
  const router = express.Router();
28
-
29
- // ─── GET /api/settings ─────────────────────────────────────────────────────
30
-
31
- router.get('/settings', (req, res) => {
32
- try {
33
- const config = loadConfig();
34
- // Never return the password (write-only field)
35
- const { dashboardPort, nginxDir, sslDir, acmeEmail } = config;
36
- res.json({
37
- dashboardPort,
38
- nginxDir,
39
- sslDir,
40
- acmeEmail,
41
- platform: process.platform === 'win32' ? 'win32' : 'linux',
42
- });
43
- } catch (err) {
44
- res.status(500).json({ error: 'Internal server error' });
45
- }
46
- });
47
-
48
- // ─── POST /api/settings ────────────────────────────────────────────────────
49
-
50
- router.post('/settings', (req, res) => {
51
- try {
52
- const { dashboardPort, dashboardPassword, nginxDir, sslDir, acmeEmail } = req.body;
53
-
54
- // Validate port if provided
55
- if (dashboardPort !== undefined) {
56
- const portError = validatePort(parseInt(dashboardPort, 10));
57
- if (portError) return res.status(400).json({ error: portError });
58
- }
59
-
60
- // Validate password if provided
61
- if (dashboardPassword !== undefined && typeof dashboardPassword !== 'string') {
62
- return res.status(400).json({ error: 'Password must be a string' });
63
- }
64
-
65
- // Validate directories if provided
66
- if (nginxDir !== undefined && (typeof nginxDir !== 'string' || nginxDir.trim() === '')) {
67
- return res.status(400).json({ error: 'Nginx directory must be a non-empty string' });
68
- }
69
- if (sslDir !== undefined && (typeof sslDir !== 'string' || sslDir.trim() === '')) {
70
- return res.status(400).json({ error: 'SSL directory must be a non-empty string' });
71
- }
72
-
73
- // Validate email if provided
74
- if (acmeEmail !== undefined) {
75
- const emailError = validateEmail(acmeEmail);
76
- if (emailError) return res.status(400).json({ error: emailError });
77
- }
78
-
79
- // Load current config and merge updates
80
- const currentConfig = loadConfig();
81
- const updates = {};
82
-
83
- if (dashboardPort !== undefined) {
84
- updates.dashboardPort = parseInt(dashboardPort, 10);
85
- }
86
- if (dashboardPassword !== undefined) {
87
- updates.dashboardPassword = dashboardPassword;
88
- }
89
- if (nginxDir !== undefined) {
90
- updates.nginxDir = nginxDir.trim();
91
- }
92
- if (sslDir !== undefined) {
93
- updates.sslDir = sslDir.trim();
94
- }
95
- if (acmeEmail !== undefined) {
96
- updates.acmeEmail = acmeEmail.trim();
97
- }
98
-
99
- const newConfig = { ...currentConfig, ...updates };
100
- saveConfig(newConfig);
101
-
102
- res.json({ success: true });
103
- } catch (err) {
104
- res.status(500).json({ error: 'Internal server error' });
105
- }
106
- });
107
-
108
- // ─── GET /api/settings/permissions ────────────────────────────────────────────
109
-
110
- router.get('/settings/permissions', async (req, res) => {
111
- if (process.platform === 'win32') return res.json({ configured: true });
112
- try {
113
- const configured = await checkPermissionsConfigured();
114
- res.json({ configured });
115
- } catch {
116
- res.json({ configured: false });
117
- }
118
- });
119
-
120
- // ─── POST /api/settings/permissions/setup ─────────────────────────────────────
121
-
122
- router.post('/settings/permissions/setup', async (req, res) => {
123
- if (process.platform === 'win32') {
124
- return res.status(400).json({ error: 'Not applicable on Windows' });
125
- }
126
-
127
- const { password } = req.body ?? {};
128
- if (!password || typeof password !== 'string') {
129
- return res.status(400).json({ error: 'Password is required' });
130
- }
131
-
132
- // Resolve nginx binary path
133
- const whichResult = await run('which nginx');
134
- if (!whichResult.success || !whichResult.stdout.trim()) {
135
- return res.status(500).json({ error: 'nginx not found. Is nginx installed?' });
136
- }
137
- const nginxPath = whichResult.stdout.trim().split('\n')[0].trim();
138
- const user = os.userInfo().username;
139
-
140
- // Build sudoers rules with the detected nginx path
141
- const sudoRules = [
142
- '/usr/bin/systemctl start nginx',
143
- '/usr/bin/systemctl stop nginx',
144
- '/usr/bin/systemctl reload nginx',
145
- '/usr/bin/systemctl restart nginx',
146
- '/usr/bin/systemctl',
147
- nginxPath,
148
- `${nginxPath} -t`,
149
- `${nginxPath} -s reload`,
150
- `${nginxPath} -s stop`,
151
- `${nginxPath} -s quit`,
152
- '/usr/bin/certbot',
153
- '/usr/bin/mkdir',
154
- '/usr/bin/cp',
155
- '/usr/bin/chmod',
156
- '/usr/bin/chown',
157
- '/usr/bin/tee',
158
- ].join(', ');
159
-
160
- const sudoersContent = `${user} ALL=(ALL) NOPASSWD: ${sudoRules}\n`;
161
-
162
- // Write content to a temp file (no sudo needed for /tmp)
163
- const tmpFile = path.join('/tmp', `easy-devops-sudoers-${Date.now()}`);
164
- try {
165
- await fs.writeFile(tmpFile, sudoersContent, { mode: 0o600 });
166
- } catch (err) {
167
- return res.status(500).json({ error: 'Failed to write temp file', output: err.message });
168
- }
169
-
170
- // Run all setup steps in a single sudo -S invocation
171
- const setupCmd = [
172
- `mkdir -p /etc/easy-devops /var/log/easy-devops`,
173
- `chown ${user}:${user} /etc/easy-devops /var/log/easy-devops`,
174
- `chown -R ${user}:${user} /etc/nginx/conf.d 2>/dev/null || true`,
175
- `cp '${tmpFile}' /etc/sudoers.d/easy-devops`,
176
- `chmod 440 /etc/sudoers.d/easy-devops`,
177
- ].join(' && ');
178
-
179
- const result = await runSudoS(setupCmd, password);
180
- await fs.unlink(tmpFile).catch(() => {});
181
-
182
- if (!result.success) {
183
- const output = result.stderr || result.stdout;
184
- const wrongPassword = output.includes('incorrect password') || output.includes('Sorry, try again') || output.includes('3 incorrect');
185
- return res.status(wrongPassword ? 401 : 500).json({
186
- error: wrongPassword ? 'Incorrect password' : 'Setup failed',
187
- output,
188
- });
189
- }
190
-
191
- res.json({ success: true });
192
- });
5
+ const controller = new SettingsController();
6
+
7
+ router.get('/settings', (req, res, next) => controller.get(req, res, next));
8
+ router.post('/settings', (req, res, next) => controller.update(req, res, next));
9
+ router.get('/settings/permissions', (req, res, next) => controller.getPermissions(req, res, next));
10
+ router.post('/settings/permissions/setup', (req, res, next) => controller.setupPermissions(req, res, next));
11
+ router.get('/settings/backup', (req, res, next) => controller.backup(req, res, next));
12
+ router.post('/settings/restore', (req, res, next) => controller.restore(req, res, next));
13
+
14
+ // Notification channel CRUD
15
+ router.get('/settings/channels', (req, res, next) => controller.getChannels(req, res, next));
16
+ router.post('/settings/channels', (req, res, next) => controller.createChannel(req, res, next));
17
+ router.put('/settings/channels/:id', (req, res, next) => controller.updateChannel(req, res, next));
18
+ router.delete('/settings/channels/:id', (req, res, next) => controller.deleteChannel(req, res, next));
19
+ router.post('/settings/channels/:id/test', (req, res, next) => controller.testChannel(req, res, next));
193
20
 
194
21
  export default router;
@@ -1,281 +1,14 @@
1
1
  import express from 'express';
2
- import { listAllCerts } from '../lib/cert-reader.js';
3
- import { issueCert, renewCert } from '../../cli/managers/ssl-manager.js';
4
- import { loadConfig } from '../../core/config.js';
5
- import { promises as dns } from 'dns';
2
+ import SslController from '../controllers/sslController.js';
6
3
 
7
4
  const router = express.Router();
8
-
9
- // ─── In-memory DNS challenge state ────────────────────────────────────────────
10
- // Keyed by domain name. Entries are cleaned up when the ACME process exits
11
- // or when cancelled. Entries older than 10 minutes are forcibly removed.
12
-
13
- const pendingDnsChallenges = new Map();
14
-
15
- setInterval(() => {
16
- const now = Date.now();
17
- for (const [domain, state] of pendingDnsChallenges) {
18
- if (now - state.createdAt > 10 * 60 * 1000) {
19
- state.confirmDeferred.reject(new Error('DNS challenge timed out after 10 minutes'));
20
- pendingDnsChallenges.delete(domain);
21
- }
22
- }
23
- }, 60000);
24
-
25
- // ─── POST /api/ssl/create ─────────────────────────────────────────────────────
26
-
27
- router.post('/create', async (req, res) => {
28
- const { domain, www = false, validationMethod = 'http', email = null } = req.body ?? {};
29
-
30
- if (!domain || typeof domain !== 'string' || !domain.trim()) {
31
- return res.status(400).json({ error: 'domain is required' });
32
- }
33
-
34
- const domainKey = domain.trim();
35
- const config = loadConfig();
36
- const acmeEmail = email || config.acmeEmail;
37
-
38
- if (validationMethod === 'dns') {
39
- // Two-phase flow: spawn ACME process, wait for TXT record, respond 202, pause until confirm.
40
- let confirmResolve, confirmReject;
41
- const confirmPromise = new Promise((resolve, reject) => {
42
- confirmResolve = resolve;
43
- confirmReject = reject;
44
- });
45
-
46
- let resultResolve;
47
- const resultPromise = new Promise((resolve) => { resultResolve = resolve; });
48
-
49
- // Track whether a response has already been sent (202 from onDnsChallenge)
50
- let responseSent = false;
51
-
52
- const onDnsChallenge = async (txtName, txtValue) => {
53
- responseSent = true;
54
- pendingDnsChallenges.set(domainKey, {
55
- domain: domainKey,
56
- txtName,
57
- txtValue,
58
- confirmDeferred: { resolve: confirmResolve, reject: confirmReject },
59
- resultPromise,
60
- createdAt: Date.now(),
61
- });
62
-
63
- res.status(202).json({
64
- status: 'waiting_dns',
65
- domain: domainKey,
66
- txtName,
67
- txtValue,
68
- hint: 'Add a DNS TXT record with the name and value above, then call POST /api/ssl/create-confirm',
69
- });
70
-
71
- // Pause until user calls /create-confirm (resolves) or /create-cancel (rejects)
72
- await confirmPromise;
73
- };
74
-
75
- // Run issueCert in the background — it will call onDnsChallenge which sends 202 and pauses.
76
- issueCert(domainKey, { www: !!www, validationMethod: 'dns', email: acmeEmail, onDnsChallenge })
77
- .then(result => {
78
- resultResolve(result);
79
- pendingDnsChallenges.delete(domainKey);
80
- if (!responseSent) {
81
- responseSent = true;
82
- if (result.success) {
83
- return res.json({ success: true, certPath: result.certPath, keyPath: result.keyPath });
84
- }
85
- const { step } = result.error ?? {};
86
- if (step === 'email configuration') {
87
- return res.status(400).json({ error: 'email_required', hint: 'Configure acmeEmail in settings or provide email parameter.' });
88
- }
89
- return res.status(500).json({ success: false, error: result.error });
90
- }
91
- })
92
- .catch(err => {
93
- const errResult = {
94
- success: false,
95
- certPath: null,
96
- keyPath: null,
97
- error: {
98
- step: 'certificate issuance',
99
- cause: err.message,
100
- consequence: 'Unexpected error during DNS certificate issuance.',
101
- nginxRunning: true,
102
- configSaved: false,
103
- },
104
- };
105
- resultResolve(errResult);
106
- pendingDnsChallenges.delete(domainKey);
107
- if (!responseSent) {
108
- responseSent = true;
109
- return res.status(500).json({ success: false, error: errResult.error });
110
- }
111
- });
112
-
113
- // The response is sent either by onDnsChallenge (202) or by the .then()/.catch() above.
114
- return;
115
- }
116
-
117
- // HTTP validation path (synchronous — responds when complete)
118
- const result = await issueCert(domainKey, { www: !!www, validationMethod: 'http', email: acmeEmail });
119
-
120
- if (result.success) {
121
- return res.json({ success: true, certPath: result.certPath, keyPath: result.keyPath });
122
- }
123
-
124
- const { step } = result.error;
125
- if (step === 'email configuration') {
126
- return res.status(400).json({
127
- error: 'email_required',
128
- hint: 'Configure acmeEmail in settings or provide email parameter.',
129
- });
130
- }
131
- if (step === 'port 80 check') {
132
- return res.status(409).json({
133
- error: 'port_busy',
134
- detail: result.error.cause,
135
- hint: 'Stop the process using port 80 and try again.',
136
- });
137
- }
138
- return res.status(500).json({ success: false, error: result.error });
139
- });
140
-
141
- // ─── POST /api/ssl/create-confirm ────────────────────────────────────────────
142
-
143
- router.post('/create-confirm', async (req, res) => {
144
- const { domain } = req.body ?? {};
145
- const domainKey = domain?.trim();
146
- const state = domainKey ? pendingDnsChallenges.get(domainKey) : null;
147
-
148
- if (!state) {
149
- return res.status(404).json({
150
- error: 'no_pending_challenge',
151
- hint: 'No DNS challenge is pending for this domain. Start a new certificate issuance.',
152
- });
153
- }
154
-
155
- try {
156
- const records = await dns.resolveTxt(`_acme-challenge.${domainKey}`);
157
- const flatRecords = records.flat();
158
-
159
- const found = flatRecords.includes(state.txtValue);
160
- if (!found) {
161
- return res.status(400).json({
162
- error: 'dns_not_propagated',
163
- hint: 'The expected TXT record value was not found. Make sure you added the correct TXT record and wait a few minutes for DNS propagation.',
164
- expected: state.txtValue,
165
- found: flatRecords,
166
- });
167
- }
168
- } catch (err) {
169
- return res.status(400).json({
170
- error: 'dns_lookup_failed',
171
- hint: 'Failed to lookup the expected TXT record. Make sure you added the correct TXT record.',
172
- detail: err.message,
173
- });
174
- }
175
- // Signal issueCert() to continue with the ACME process
176
- await state.confirmDeferred.resolve();
177
-
178
- // Wait for the ACME process to complete
179
- const result = await state.resultPromise;
180
- pendingDnsChallenges.delete(domainKey);
181
-
182
- if (result.success) {
183
- return res.json({ success: true, certPath: result.certPath, keyPath: result.keyPath });
184
- }
185
- return res.status(500).json({ success: false, error: result.error });
186
- });
187
-
188
- // ─── POST /api/ssl/create-cancel ─────────────────────────────────────────────
189
-
190
- router.post('/create-cancel', async (req, res) => {
191
- const { domain } = req.body ?? {};
192
- const domainKey = domain?.trim();
193
- const state = domainKey ? pendingDnsChallenges.get(domainKey) : null;
194
-
195
- if (!state) {
196
- return res.status(404).json({
197
- error: 'no_pending_challenge',
198
- hint: 'No DNS challenge is pending for this domain.',
199
- });
200
- }
201
-
202
- // Reject the deferred — issueCert() will return a failure result
203
- state.confirmDeferred.reject(new Error('cancelled by user'));
204
- pendingDnsChallenges.delete(domainKey);
205
-
206
- return res.json({ cancelled: true });
207
- });
208
-
209
- // ─── GET /api/ssl ─────────────────────────────────────────────────────────────
210
-
211
- router.get('/', async (req, res) => {
212
- const certs = await listAllCerts();
213
- res.json(certs);
214
- });
215
-
216
- // ─── POST /api/ssl/renew/:domain ─────────────────────────────────────────────
217
-
218
- router.post('/renew/:domain', async (req, res) => {
219
- const domain = req.params.domain;
220
- const config = loadConfig();
221
-
222
- if (!config.acmeEmail) {
223
- return res.status(400).json({
224
- error: 'email_required',
225
- hint: 'Configure acmeEmail in settings first.',
226
- });
227
- }
228
-
229
- const certs = await listAllCerts();
230
- const found = certs.find(cert => cert.domain === domain);
231
- if (!found) {
232
- return res.status(404).json({ error: `Domain '${domain}' not found` });
233
- }
234
-
235
- const result = await renewCert(domain, { validationMethod: 'http', email: config.acmeEmail });
236
-
237
- if (result.success) {
238
- return res.json({ success: true, certPath: result.certPath, keyPath: result.keyPath });
239
- }
240
-
241
- const { step } = result.error;
242
- if (step === 'port 80 check') {
243
- return res.status(409).json({
244
- error: 'port_busy',
245
- detail: result.error.cause,
246
- hint: 'Stop the process using port 80 and try again.',
247
- });
248
- }
249
- return res.status(500).json({ success: false, error: result.error });
250
- });
251
-
252
- // ─── POST /api/ssl/renew-all ─────────────────────────────────────────────────
253
-
254
- router.post('/renew-all', async (req, res) => {
255
- const config = loadConfig();
256
-
257
- if (!config.acmeEmail) {
258
- return res.status(400).json({
259
- error: 'email_required',
260
- hint: 'Configure acmeEmail in settings first.',
261
- });
262
- }
263
-
264
- const certs = await listAllCerts();
265
- const expiring = certs.filter(c => c.daysLeft !== null && c.daysLeft < 30);
266
- const results = [];
267
-
268
- for (const cert of expiring) {
269
- const result = await renewCert(cert.domain, { validationMethod: 'http', email: config.acmeEmail });
270
- results.push({
271
- domain: cert.domain,
272
- success: result.success,
273
- certPath: result.certPath,
274
- keyPath: result.keyPath,
275
- });
276
- }
277
-
278
- res.json(results);
279
- });
5
+ const controller = new SslController();
6
+
7
+ router.post('/create', (req, res, next) => controller.create(req, res, next));
8
+ router.post('/create-confirm', (req, res, next) => controller.createConfirm(req, res, next));
9
+ router.post('/create-cancel', (req, res, next) => controller.createCancel(req, res, next));
10
+ router.get('/', (req, res, next) => controller.list(req, res, next));
11
+ router.post('/renew/:domain', (req, res, next) => controller.renew(req, res, next));
12
+ router.post('/renew-all', (req, res, next) => controller.renewAll(req, res, next));
280
13
 
281
14
  export default router;
@@ -1,16 +1,22 @@
1
1
  import { createServer } from 'http';
2
+ import { createRequire } from 'module';
2
3
  import express from 'express';
3
4
  import { fileURLToPath } from 'url';
4
5
  import path from 'path';
6
+ import os from 'os';
7
+ import crypto from 'crypto';
5
8
  import session from 'express-session';
6
- import { Server as SocketIO } from 'socket.io';
7
9
  import { loadConfig } from '../core/config.js';
10
+ import { dbGet, dbSet } from '../core/db.js';
8
11
  import authRouter from './routes/auth.js';
9
12
  import domainsRouter from './routes/domains.js';
10
13
  import sslRouter from './routes/ssl.js';
11
14
  import nginxRouter from './routes/nginx.js';
12
15
  import settingsRouter from './routes/settings.js';
13
- import { getStatus } from './lib/nginx-service.js';
16
+ import { initSocket } from './socketManager.js';
17
+
18
+ const require = createRequire(import.meta.url);
19
+ const FileStore = require('session-file-store')(session);
14
20
 
15
21
  const __dirname = path.dirname(fileURLToPath(import.meta.url));
16
22
 
@@ -20,12 +26,25 @@ const app = express();
20
26
  app.set('view engine', 'ejs');
21
27
  app.set('views', path.join(__dirname, 'views'));
22
28
 
23
- app.use(express.json());
29
+ app.use(express.json({ limit: '1mb' }));
30
+
31
+ // ─── Session secret — generated once, persisted in SQLite ────────────────────
32
+ let sessionSecret = dbGet('session_secret');
33
+ if (!sessionSecret) {
34
+ sessionSecret = crypto.randomBytes(32).toString('hex');
35
+ dbSet('session_secret', sessionSecret);
36
+ }
37
+
38
+ // Sessions stored on disk so they survive restarts
39
+ const SESSION_DIR = process.platform === 'win32'
40
+ ? path.join(process.env.APPDATA || os.homedir(), 'easy-devops', 'sessions')
41
+ : path.join(os.homedir(), '.config', 'easy-devops', 'sessions');
24
42
 
25
43
  app.use(session({
26
- secret: 'easy-devops-secret',
44
+ secret: sessionSecret,
27
45
  resave: false,
28
46
  saveUninitialized: false,
47
+ store: new FileStore({ path: SESSION_DIR, retries: 1, logFn() {} }),
29
48
  cookie: { httpOnly: true },
30
49
  }));
31
50
 
@@ -44,29 +63,7 @@ app.use((req, res) => res.render('index'));
44
63
  // ─── HTTP server + Socket.io ──────────────────────────────────────────────────
45
64
 
46
65
  const httpServer = createServer(app);
47
- const io = new SocketIO(httpServer);
48
-
49
- let connectedClients = 0;
50
-
51
- async function emitNginxStatus(target) {
52
- try {
53
- const status = await getStatus();
54
- target.emit('nginx:status', status);
55
- } catch (err) {
56
- target.emit('nginx:status', { running: false, version: null, pid: null, error: err.message });
57
- }
58
- }
59
-
60
- io.on('connection', (socket) => {
61
- connectedClients++;
62
- emitNginxStatus(socket);
63
- socket.on('disconnect', () => { connectedClients--; });
64
- });
65
-
66
- // Broadcast nginx status to all clients every 5 seconds
67
- setInterval(() => {
68
- if (connectedClients > 0) emitNginxStatus(io);
69
- }, 5000);
66
+ initSocket(httpServer);
70
67
 
71
68
  // ─── Start ────────────────────────────────────────────────────────────────────
72
69