-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathserver.js
More file actions
297 lines (253 loc) · 12.2 KB
/
Copy pathserver.js
File metadata and controls
297 lines (253 loc) · 12.2 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
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
/**
* FleetTrack — Self-hosted device fleet monitor
* ──────────────────────────────────────────────
* npm install
* node server.js
*
* First run creates: admin / changeme — change it immediately.
* Put secrets in a .env file (see .env.example).
*/
// Load .env file if present (for local dev and Railway/Render)
require('dotenv').config();
const express = require('express');
const session = require('express-session');
const bcrypt = require('bcrypt');
const fs = require('fs');
const path = require('path');
const nodemailer = require('nodemailer');
const app = express();
const PORT = process.env.PORT || 3000;
// ── CONFIG ────────────────────────────────────────────────────
const CONFIG = {
// Minutes before a device is flagged offline
offlineThresholdMin: 5,
// How many location history points to keep per device
maxHistory: 100,
// Session secret — set SESSION_SECRET in .env
sessionSecret: process.env.SESSION_SECRET || 'change-this-secret-now',
// Agent API token — set API_TOKEN in .env, copy to agent scripts
apiToken: process.env.API_TOKEN || 'change-me-to-a-long-random-string',
email: {
enabled: process.env.SMTP_USER ? true : false,
from: process.env.SMTP_USER || 'you@gmail.com',
to: process.env.ALERT_TO || 'you@gmail.com',
smtp: {
host: 'smtp.gmail.com',
port: 587,
secure: false,
auth: {
user: process.env.SMTP_USER || '',
pass: process.env.SMTP_PASS || '',
},
},
},
};
// ── DATA PATHS ────────────────────────────────────────────────
const DATA_DIR = path.join(__dirname, 'data');
const DEV_FILE = path.join(DATA_DIR, 'devices.json');
const USERS_FILE = path.join(DATA_DIR, 'users.json');
const HIST_FILE = path.join(DATA_DIR, 'history.json');
if (!fs.existsSync(DATA_DIR)) fs.mkdirSync(DATA_DIR, { recursive: true });
// ── PERSISTENCE HELPERS ───────────────────────────────────────
const load = (file, def) => {
try { return fs.existsSync(file) ? JSON.parse(fs.readFileSync(file, 'utf8')) : def; }
catch(e) { return def; }
};
const save = (file, data) => {
try { fs.writeFileSync(file, JSON.stringify(data, null, 2)); }
catch(e) { console.error('Save error:', e.message); }
};
// ── STATE ─────────────────────────────────────────────────────
let devices = load(DEV_FILE, {});
let history = load(HIST_FILE, {}); // deviceId → [{lat,lon,ts}]
const alertedOffline = new Set();
// ── USERS ─────────────────────────────────────────────────────
async function ensureDefaultAdmin() {
const users = load(USERS_FILE, {});
if (Object.keys(users).length === 0) {
const hash = await bcrypt.hash('changeme', 12);
users['admin'] = { username: 'admin', passwordHash: hash, role: 'admin' };
save(USERS_FILE, users);
console.log('\n ⚠ Default admin: username=admin password=changeme');
console.log(' Change it immediately after first login!\n');
}
}
// ── MIDDLEWARE ────────────────────────────────────────────────
app.use(express.json());
app.use(express.urlencoded({ extended: true }));
app.use(session({
secret: CONFIG.sessionSecret,
resave: false,
saveUninitialized: false,
cookie: { httpOnly: true, maxAge: 8 * 60 * 60 * 1000, sameSite: 'lax' },
}));
// ── AUTH GUARDS ───────────────────────────────────────────────
const requireLogin = (req, res, next) =>
req.session?.user ? next() : res.redirect('/login');
const requireSession = (req, res, next) =>
req.session?.user ? next() : res.status(401).json({ error: 'Not authenticated' });
const requireToken = (req, res, next) =>
req.headers['x-api-token'] === CONFIG.apiToken
? next() : res.status(401).json({ error: 'Unauthorized' });
// ── AUTH ROUTES ───────────────────────────────────────────────
app.get('/login', (req, res) => {
if (req.session?.user) return res.redirect('/');
res.sendFile(path.join(__dirname, 'public', 'login.html'));
});
app.post('/login', async (req, res) => {
const { username, password } = req.body;
const users = load(USERS_FILE, {});
const user = users[username];
const dummy = '$2b$12$invalidhashfortimingprotection000000000000000000000';
const match = await bcrypt.compare(password || '', user ? user.passwordHash : dummy);
if (!user || !match) {
console.log(`[${new Date().toISOString()}] FAILED LOGIN: ${username}`);
return res.redirect('/login?error=1');
}
req.session.regenerate(err => {
if (err) return res.redirect('/login?error=1');
req.session.user = { username: user.username, role: user.role };
console.log(`[${new Date().toISOString()}] LOGIN: ${username}`);
res.redirect('/');
});
});
app.post('/logout', (req, res) => {
const who = req.session?.user?.username || 'unknown';
req.session.destroy(() => {
console.log(`[${new Date().toISOString()}] LOGOUT: ${who}`);
res.redirect('/login');
});
});
app.post('/api/change-password', requireSession, async (req, res) => {
const { currentPassword, newPassword } = req.body;
if (!newPassword || newPassword.length < 8)
return res.status(400).json({ error: 'Min 8 characters' });
const users = load(USERS_FILE, {});
const user = users[req.session.user.username];
if (!user) return res.status(404).json({ error: 'User not found' });
const match = await bcrypt.compare(currentPassword || '', user.passwordHash);
if (!match) return res.status(403).json({ error: 'Current password is incorrect' });
user.passwordHash = await bcrypt.hash(newPassword, 12);
save(USERS_FILE, users);
console.log(`[${new Date().toISOString()}] PASSWORD CHANGED: ${user.username}`);
res.json({ ok: true });
});
app.get('/api/me', requireSession, (req, res) => {
res.json({ username: req.session.user.username, role: req.session.user.role });
});
// ── DASHBOARD ─────────────────────────────────────────────────
app.get('/', requireLogin, (req, res) => {
res.sendFile(path.join(__dirname, 'public', 'index.html'));
});
// ── AGENT CHECK-IN ────────────────────────────────────────────
app.post('/checkin', requireToken, (req, res) => {
const { deviceId, name, os, battery, ipLocal, notes, lat, lon } = req.body;
if (!deviceId) return res.status(400).json({ error: 'deviceId required' });
const now = Date.now();
const ipWan = req.ip.replace('::ffff:', '');
const prev = devices[deviceId] || {};
// Parse and validate coordinates
const parsedLat = lat != null ? parseFloat(lat) : null;
const parsedLon = lon != null ? parseFloat(lon) : null;
const validLat = parsedLat !== null && !isNaN(parsedLat) && parsedLat >= -90 && parsedLat <= 90;
const validLon = parsedLon !== null && !isNaN(parsedLon) && parsedLon >= -180 && parsedLon <= 180;
const newLat = validLat ? parsedLat : (prev.lat || null);
const newLon = validLon ? parsedLon : (prev.lon || null);
devices[deviceId] = {
deviceId,
name: name || prev.name || deviceId,
os: os || prev.os || 'Unknown',
battery: battery != null ? Number(battery) : (prev.battery ?? null),
ipLocal: ipLocal || prev.ipLocal || null,
ipWan,
lat: newLat,
lon: newLon,
notes: notes || prev.notes || '',
lastSeen: now,
firstSeen: prev.firstSeen || now,
checkins: (prev.checkins || 0) + 1,
};
// Append to location history if we have valid coords
if (validLat && validLon) {
if (!history[deviceId]) history[deviceId] = [];
history[deviceId].push({ lat: parsedLat, lon: parsedLon, ts: now });
// Keep only last N points
if (history[deviceId].length > CONFIG.maxHistory)
history[deviceId] = history[deviceId].slice(-CONFIG.maxHistory);
save(HIST_FILE, history);
}
// Clear offline alert if device is back
if (alertedOffline.has(deviceId)) {
alertedOffline.delete(deviceId);
sendAlert(
`✅ Back Online: ${devices[deviceId].name}`,
`${devices[deviceId].name} is back online.\nTime: ${new Date().toISOString()}`
);
}
save(DEV_FILE, devices);
console.log(`[${new Date().toISOString()}] CHECK-IN: ${devices[deviceId].name} (${ipWan}) lat=${newLat} lon=${newLon}`);
res.json({ ok: true, serverTime: now });
});
// ── DEVICE API ────────────────────────────────────────────────
app.get('/api/devices', requireSession, (req, res) => {
const now = Date.now();
const threshold = CONFIG.offlineThresholdMin * 60 * 1000;
const list = Object.values(devices).map(d => ({
...d,
online: (now - d.lastSeen) < threshold,
secsAgo: Math.floor((now - d.lastSeen) / 1000),
minsAgo: Math.floor((now - d.lastSeen) / 60000),
})).sort((a, b) => a.online !== b.online ? (a.online ? -1 : 1) : b.lastSeen - a.lastSeen);
res.json(list);
});
// Location history for a single device
app.get('/api/history/:id', requireSession, (req, res) => {
res.json(history[req.params.id] || []);
});
app.delete('/api/devices/:id', requireSession, (req, res) => {
const { id } = req.params;
if (!devices[id]) return res.status(404).json({ error: 'Not found' });
const name = devices[id].name;
delete devices[id];
delete history[id];
save(DEV_FILE, devices);
save(HIST_FILE, history);
console.log(`[${new Date().toISOString()}] REMOVED: ${name}`);
res.json({ ok: true });
});
// ── OFFLINE CHECKER (every 60s) ───────────────────────────────
setInterval(() => {
const now = Date.now();
const threshold = CONFIG.offlineThresholdMin * 60 * 1000;
for (const d of Object.values(devices)) {
const offline = (now - d.lastSeen) >= threshold;
if (offline && !alertedOffline.has(d.deviceId)) {
alertedOffline.add(d.deviceId);
const mins = Math.floor((now - d.lastSeen) / 60000);
console.warn(`[ALERT] OFFLINE: ${d.name} — ${mins}min ago`);
sendAlert(
`⚠️ Offline: ${d.name}`,
`${d.name} hasn't checked in for ${mins} minutes.\nLast IP: ${d.ipWan}\nLast seen: ${new Date(d.lastSeen).toISOString()}`
);
}
}
}, 60 * 1000);
// ── EMAIL ─────────────────────────────────────────────────────
async function sendAlert(subject, body) {
if (!CONFIG.email.enabled) { console.log(`[ALERT — email off] ${subject}`); return; }
try {
await nodemailer.createTransport(CONFIG.email.smtp)
.sendMail({ from: CONFIG.email.from, to: CONFIG.email.to, subject, text: body });
console.log(`[ALERT SENT] ${subject}`);
} catch(e) { console.error(`[ALERT FAILED] ${e.message}`); }
}
// ── BOOT ─────────────────────────────────────────────────────
ensureDefaultAdmin().then(() => {
app.listen(PORT, () => {
console.log(`\n FleetTrack → http://localhost:${PORT}`);
console.log(` API Token : ${CONFIG.apiToken}`);
console.log(` Threshold : ${CONFIG.offlineThresholdMin} min`);
console.log(` Devices : ${Object.keys(devices).length}`);
console.log(` Email : ${CONFIG.email.enabled ? 'ON' : 'OFF'}\n`);
});
});