-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathserver.js
More file actions
163 lines (147 loc) · 4.72 KB
/
Copy pathserver.js
File metadata and controls
163 lines (147 loc) · 4.72 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
const express = require('express');
const si = require('systeminformation');
const crypto = require('crypto');
const path = require('path');
const fs = require('fs');
// Carrega variáveis do .env (KEY=valor, uma por linha) sem sobrescrever o ambiente
try {
const env = fs.readFileSync(path.join(__dirname, '.env'), 'utf8');
for (const line of env.split('\n')) {
const m = line.match(/^\s*([A-Z_][A-Z0-9_]*)\s*=\s*(.*?)\s*$/);
if (m && !(m[1] in process.env)) process.env[m[1]] = m[2];
}
} catch { /* sem .env, usa só o ambiente */ }
const PORT = process.env.PORT || 3000;
// Defina SM_PASSWORD no ambiente para proteger o acesso (recomendado em produção)
const PASSWORD = process.env.SM_PASSWORD || '';
const app = express();
app.use(express.json());
// ---- Autenticação simples por token (opcional, ativada via SM_PASSWORD) ----
const sessions = new Set();
function isAuthed(req) {
if (!PASSWORD) return true;
const token = req.headers['x-auth-token'] || req.query.token;
return token && sessions.has(token);
}
app.post('/api/login', (req, res) => {
if (!PASSWORD) return res.json({ token: 'open' });
const { password } = req.body || {};
if (password === PASSWORD) {
const token = crypto.randomBytes(24).toString('hex');
sessions.add(token);
return res.json({ token });
}
res.status(401).json({ error: 'Senha incorreta' });
});
app.get('/api/auth-required', (req, res) => {
res.json({ required: !!PASSWORD });
});
function requireAuth(req, res, next) {
if (isAuthed(req)) return next();
res.status(401).json({ error: 'Não autenticado' });
}
// ---- Coleta de dados ----
async function collectStats() {
const [cpu, mem, load, procs, fs, osInfo, users, time, net] = await Promise.all([
si.cpu(),
si.mem(),
si.currentLoad(),
si.processes(),
si.fsSize(),
si.osInfo(),
si.users(),
si.time(),
si.networkStats()
]);
// Agrupa processos por usuário
const byUser = {};
for (const p of procs.list) {
const user = p.user || 'desconhecido';
if (!byUser[user]) {
byUser[user] = { user, cpu: 0, memRss: 0, count: 0, processes: [] };
}
byUser[user].cpu += p.cpu;
byUser[user].memRss += p.memRss || 0; // KB
byUser[user].count += 1;
byUser[user].processes.push({
pid: p.pid,
name: p.name,
cpu: +p.cpu.toFixed(1),
memPercent: +p.mem.toFixed(1),
memRss: p.memRss || 0,
state: p.state,
started: p.started,
command: (p.command || '').slice(0, 120)
});
}
// Ordena processos de cada usuário por CPU e usuários por memória
const usersList = Object.values(byUser).map(u => ({
...u,
cpu: +u.cpu.toFixed(1),
processes: u.processes.sort((a, b) => b.cpu - a.cpu)
})).sort((a, b) => b.memRss - a.memRss);
return {
timestamp: Date.now(),
os: { distro: osInfo.distro, release: osInfo.release, hostname: osInfo.hostname },
uptime: time.uptime,
cpu: {
brand: cpu.brand,
cores: cpu.cores,
load: +load.currentLoad.toFixed(1),
perCore: load.cpus.map(c => +c.load.toFixed(1))
},
memory: {
total: mem.total,
used: mem.active,
free: mem.available,
swapTotal: mem.swaptotal,
swapUsed: mem.swapused
},
disks: fs.map(d => ({ fs: d.fs, mount: d.mount, size: d.size, used: d.used, usePercent: d.use })),
network: net.map(n => ({ iface: n.iface, rxSec: n.rx_sec, txSec: n.tx_sec })),
loggedUsers: users.map(u => ({ user: u.user, tty: u.tty, ip: u.ip, date: u.date, time: u.time })),
totalProcesses: procs.all,
running: procs.running,
sleeping: procs.sleeping,
users: usersList
};
}
app.get('/api/stats', requireAuth, async (req, res) => {
try {
res.json(await collectStats());
} catch (err) {
res.status(500).json({ error: err.message });
}
});
// Stream em tempo real via Server-Sent Events (atualiza a cada 3s)
app.get('/api/stream', requireAuth, (req, res) => {
res.set({
'Content-Type': 'text/event-stream',
'Cache-Control': 'no-cache',
Connection: 'keep-alive'
});
res.flushHeaders();
let active = true;
const send = async () => {
if (!active) return;
try {
const stats = await collectStats();
res.write(`data: ${JSON.stringify(stats)}\n\n`);
} catch (e) {
res.write(`event: error\ndata: ${JSON.stringify({ error: e.message })}\n\n`);
}
};
send();
const interval = setInterval(send, 3000);
req.on('close', () => {
active = false;
clearInterval(interval);
});
});
app.use(express.static(path.join(__dirname, 'public')));
app.listen(PORT, () => {
console.log(`Server Manager rodando em http://localhost:${PORT}`);
if (!PASSWORD) {
console.log('AVISO: sem senha definida. Em produção use: SM_PASSWORD=suasenha node server.js');
}
});