@xeplr/monitor 0.1.3 → 1.0.0
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.
- package/README.md +138 -125
- package/api/README.md +71 -0
- package/api/app.js +46 -0
- package/api/bin/auth.js +37 -0
- package/api/bin/www +72 -0
- package/api/db/setup.js +10 -0
- package/api/env.required.js +37 -0
- package/api/lib/host.js +188 -0
- package/api/lib/jobs.js +83 -0
- package/api/lib/services.js +67 -0
- package/api/lib/stats.js +362 -0
- package/{lib → api/lib}/systemd.js +75 -14
- package/api/migrations/0001_monitor.sql +43 -0
- package/api/migrations/0002_backup_connections.sql +26 -0
- package/api/migrations/0003_settings_audit.sql +18 -0
- package/api/migrations/0004_monitor_stats.sql +73 -0
- package/api/migrations/README.md +9 -0
- package/api/migrations-auth/0006_monitor.sql +56 -0
- package/api/migrations-auth/0007_monitor_home.sql +42 -0
- package/api/migrations-auth/0008_backups.sql +44 -0
- package/api/migrations-auth/0009_app_settings.sql +44 -0
- package/api/migrations-auth/0010_monitor_history.sql +22 -0
- package/api/models/index.js +18 -0
- package/api/package-lock.json +2839 -0
- package/api/package.json +39 -0
- package/api/production.env.example +61 -0
- package/api/routes/appSettings.js +73 -0
- package/api/routes/index.js +47 -0
- package/api/routes/monitor.js +196 -0
- package/api/setup.schema.js +166 -0
- package/deploy/control.sh +27 -0
- package/deploy/deploy.js +183 -0
- package/deploy/install.sh +177 -77
- package/deploy/settings.cjs +93 -0
- package/package.json +28 -47
- package/ui/.env +8 -0
- package/ui/README.md +29 -0
- package/ui/index.html +13 -0
- package/ui/package-lock.json +2094 -0
- package/ui/package.json +31 -0
- package/ui/pages.json +33 -0
- package/ui/public/logo-wide.svg +17 -0
- package/ui/public/logo.svg +10 -0
- package/ui/src/App.jsx +130 -0
- package/ui/src/api/monitor.js +6 -0
- package/ui/src/index.css +414 -0
- package/ui/src/main.jsx +27 -0
- package/ui/src/pages/Connections.jsx +9 -0
- package/ui/src/pages/Home.jsx +8 -0
- package/ui/src/pages/Monitor.jsx +9 -0
- package/ui/vite.config.js +56 -0
- package/bin/deploy.js +0 -181
- package/bin/server.js +0 -19
- package/bin/users.js +0 -86
- package/deploy/monitor.env.example +0 -16
- package/deploy/nginx.conf.example +0 -18
- package/deploy/sudoers.example +0 -13
- package/deploy/xeplr-monitor.service +0 -26
- package/index.js +0 -89
- package/lib/router.js +0 -179
- package/lib/services.js +0 -76
- package/lib/session.js +0 -78
- package/lib/store.js +0 -73
- package/lib/users.js +0 -119
- package/public/assets/index-BsBYpvNI.js +0 -18
- package/public/assets/index-DNZBwVTn.css +0 -1
- package/public/index.html +0 -15
package/lib/router.js
DELETED
|
@@ -1,179 +0,0 @@
|
|
|
1
|
-
// THE MONITOR'S API — mounted at /api by bin/server.js (or by a host).
|
|
2
|
-
//
|
|
3
|
-
// POST /login { email, password, code? } → the user, and the cookie
|
|
4
|
-
// POST /logout
|
|
5
|
-
// GET /me who is signed in, and what may be added
|
|
6
|
-
// GET /services every watched service with its status and processes now
|
|
7
|
-
// POST /services { unit, label? } — watch one more
|
|
8
|
-
// PATCH /services/:unit { label?, unit? } — changed in place
|
|
9
|
-
// DELETE /services/:unit stop watching it (the service is not touched)
|
|
10
|
-
// POST /services/:unit/:action start | stop | restart | kill
|
|
11
|
-
// GET /services/:unit/logs ?lines=&since=&until=&grep=&level= — oldest first
|
|
12
|
-
// GET /services/:unit/logs/live the log as it is written (server-sent events)
|
|
13
|
-
// GET /audit ?limit= — who did what, newest first
|
|
14
|
-
//
|
|
15
|
-
// Everything but /login needs a signed-in user (lib/session.js); a change also
|
|
16
|
-
// needs the x-xeplr-monitor: 1 header. Every sign-in and every change goes to
|
|
17
|
-
// the audit log, refused ones included. Bodies are parsed, and errors answered
|
|
18
|
-
// as { error }, by @xeplr/base-apis createApp, which this is mounted in.
|
|
19
|
-
var express = require('express');
|
|
20
|
-
var RateLimiter = require('@xeplr/utils/lib/rateLimiter');
|
|
21
|
-
var session = require('./session');
|
|
22
|
-
var users = require('./users');
|
|
23
|
-
var services = require('./services');
|
|
24
|
-
var systemd = require('./systemd');
|
|
25
|
-
var store = require('./store');
|
|
26
|
-
|
|
27
|
-
var LIVE_PER_USER = 10;
|
|
28
|
-
// Wrong sign-ins: 5 for one email, or 20 from one address (any emails; several
|
|
29
|
-
// people share an office network), within 15 minutes, lock it until the 15
|
|
30
|
-
// minutes from the first are up. In memory: a restart clears it, which only
|
|
31
|
-
// ever helps whoever restarted it.
|
|
32
|
-
var LOCK_SECONDS = 15 * 60;
|
|
33
|
-
var FAILS = 5;
|
|
34
|
-
var FAILS_PER_ADDRESS = 20;
|
|
35
|
-
var HEARTBEAT_MS = 15000;
|
|
36
|
-
|
|
37
|
-
function createRouter() {
|
|
38
|
-
var r = express.Router();
|
|
39
|
-
var live = new Map(); // email -> open live logs
|
|
40
|
-
var perEmail = new RateLimiter({ windowInSeconds: LOCK_SECONDS, max: FAILS });
|
|
41
|
-
var perAddress = new RateLimiter({ windowInSeconds: LOCK_SECONDS, max: FAILS_PER_ADDRESS });
|
|
42
|
-
|
|
43
|
-
// An async handler: its result as JSON; its error to createApp's error handler ({ error }, its status).
|
|
44
|
-
function answer(fn) {
|
|
45
|
-
return function(req, res, next) {
|
|
46
|
-
Promise.resolve().then(function() { return fn(req, res); }).then(function(out) {
|
|
47
|
-
if (!res.headersSent) res.json(out === undefined ? { ok: true } : out);
|
|
48
|
-
}).catch(function(err) {
|
|
49
|
-
if (!res.headersSent) next(err);
|
|
50
|
-
});
|
|
51
|
-
};
|
|
52
|
-
}
|
|
53
|
-
function ipOf(req) { return req.ip || (req.socket && req.socket.remoteAddress) || null; }
|
|
54
|
-
function unitOf(req) { return services.get(systemd.unitName(req.params.unit)).unit; }
|
|
55
|
-
|
|
56
|
-
r.post('/login', answer(async function(req, res) {
|
|
57
|
-
var b = req.body || {};
|
|
58
|
-
var email = String(b.email || '').trim().toLowerCase();
|
|
59
|
-
var byEmail = 'monitor:email:' + email;
|
|
60
|
-
var byAddress = 'monitor:ip:' + ipOf(req);
|
|
61
|
-
var wait = Math.max(await perEmail.lockedFor(byEmail), await perAddress.lockedFor(byAddress));
|
|
62
|
-
if (wait) {
|
|
63
|
-
store.audit({ email: email, ip: ipOf(req), action: 'sign-in', ok: false, error: 'locked' });
|
|
64
|
-
var minutes = Math.ceil(wait / 60);
|
|
65
|
-
res.status(429).json({ error: 'Too many wrong tries. Try again in ' + minutes + ' minute' + (minutes === 1 ? '' : 's') });
|
|
66
|
-
return;
|
|
67
|
-
}
|
|
68
|
-
var out = users.check(email, b.password, b.code);
|
|
69
|
-
if (!out.user) {
|
|
70
|
-
// Asking for the code is not a wrong try; a wrong code is.
|
|
71
|
-
if (!(out.needsCode && !b.code)) {
|
|
72
|
-
await perEmail.fail(byEmail);
|
|
73
|
-
await perAddress.fail(byAddress);
|
|
74
|
-
store.audit({ email: email, ip: ipOf(req), action: 'sign-in', ok: false, error: out.problem });
|
|
75
|
-
}
|
|
76
|
-
res.status(401).json({ error: out.problem, needsCode: Boolean(out.needsCode) });
|
|
77
|
-
return;
|
|
78
|
-
}
|
|
79
|
-
await perEmail.reset(byEmail);
|
|
80
|
-
session.start(req, res, out.user);
|
|
81
|
-
store.audit({ email: out.user.email, ip: ipOf(req), action: 'sign-in', ok: true });
|
|
82
|
-
return { user: users.shown(out.user) };
|
|
83
|
-
}));
|
|
84
|
-
|
|
85
|
-
r.post('/logout', function(req, res) {
|
|
86
|
-
var u = session.read(session.cookieOf(req));
|
|
87
|
-
session.end(req, res);
|
|
88
|
-
if (u) store.audit({ email: u.email, ip: ipOf(req), action: 'sign-out', ok: true });
|
|
89
|
-
res.json({ ok: true });
|
|
90
|
-
});
|
|
91
|
-
|
|
92
|
-
r.use(session.required);
|
|
93
|
-
|
|
94
|
-
r.get('/me', function(req, res) {
|
|
95
|
-
res.json({ user: users.shown(req.user), allowed: services.allowedPatterns(), self: systemd.selfUnit() });
|
|
96
|
-
});
|
|
97
|
-
|
|
98
|
-
r.get('/services', answer(async function() {
|
|
99
|
-
var list = services.all();
|
|
100
|
-
var out = await Promise.all(list.map(async function(s) {
|
|
101
|
-
try {
|
|
102
|
-
var st = await systemd.status(s.unit);
|
|
103
|
-
return Object.assign({}, s, { status: st, processes: systemd.processes(st) });
|
|
104
|
-
} catch (e) { return Object.assign({}, s, { status: null, processes: [], statusError: e.message }); }
|
|
105
|
-
}));
|
|
106
|
-
systemd.forgetGone(new Set([].concat.apply([], out.map(function(s) { return s.processes.map(function(p) { return p.pid; }); }))));
|
|
107
|
-
return out;
|
|
108
|
-
}));
|
|
109
|
-
|
|
110
|
-
// A change, recorded whether it worked or not.
|
|
111
|
-
function change(action, fn) {
|
|
112
|
-
return answer(async function(req) {
|
|
113
|
-
var unit = req.params.unit || (req.body && req.body.unit) || null;
|
|
114
|
-
try {
|
|
115
|
-
var out = await fn(req);
|
|
116
|
-
store.audit({ email: req.user.email, ip: ipOf(req), action: action, unit: (out && out.unit) || unit, ok: true });
|
|
117
|
-
return out;
|
|
118
|
-
} catch (err) {
|
|
119
|
-
store.audit({ email: req.user.email, ip: ipOf(req), action: action, unit: unit, ok: false, error: err.message });
|
|
120
|
-
throw err;
|
|
121
|
-
}
|
|
122
|
-
});
|
|
123
|
-
}
|
|
124
|
-
|
|
125
|
-
r.post('/services', change('add', function(req) { return services.add(req.body || {}, req.user.email); }));
|
|
126
|
-
r.patch('/services/:unit', change('edit', function(req) { return services.edit(unitOf(req), req.body || {}, req.user.email); }));
|
|
127
|
-
r.delete('/services/:unit', change('remove', function(req) { services.remove(unitOf(req)); return { unit: req.params.unit }; }));
|
|
128
|
-
|
|
129
|
-
// The action is part of what is recorded, so its handler is made per request.
|
|
130
|
-
r.post('/services/:unit/:action', function(req, res, next) {
|
|
131
|
-
var action = req.params.action;
|
|
132
|
-
return change(action, async function() {
|
|
133
|
-
if (systemd.ACTIONS.indexOf(action) < 0) { var e = new Error('Unknown action "' + action + '": start, stop, restart or kill'); e.status = 400; throw e; }
|
|
134
|
-
var unit = unitOf(req);
|
|
135
|
-
if ((action === 'stop' || action === 'kill') && unit === systemd.selfUnit()) {
|
|
136
|
-
var own = new Error('This is the monitor itself: stopping it would leave nothing to start it again. Restart it instead'); own.status = 400; throw own;
|
|
137
|
-
}
|
|
138
|
-
return { unit: unit, status: await systemd.act(unit, action) };
|
|
139
|
-
})(req, res, next);
|
|
140
|
-
});
|
|
141
|
-
|
|
142
|
-
r.get('/services/:unit/logs', answer(async function(req) {
|
|
143
|
-
var q = req.query || {};
|
|
144
|
-
return { lines: await systemd.logs(unitOf(req), { lines: q.lines, since: q.since, until: q.until, grep: q.grep, level: q.level }) };
|
|
145
|
-
}));
|
|
146
|
-
|
|
147
|
-
r.get('/services/:unit/logs/live', function(req, res) {
|
|
148
|
-
var unit;
|
|
149
|
-
try { unit = unitOf(req); } catch (e) { return res.status(e.status || 400).json({ error: e.message }); }
|
|
150
|
-
var open = live.get(req.user.email) || 0;
|
|
151
|
-
if (open >= LIVE_PER_USER) return res.status(429).json({ error: 'You already have ' + LIVE_PER_USER + ' live logs open. Close one first' });
|
|
152
|
-
live.set(req.user.email, open + 1);
|
|
153
|
-
res.writeHead(200, { 'Content-Type': 'text/event-stream', 'Cache-Control': 'no-cache, no-transform', Connection: 'keep-alive', 'X-Accel-Buffering': 'no' });
|
|
154
|
-
res.write('event: ready\ndata: {}\n\n');
|
|
155
|
-
var stop = systemd.follow(unit, function(line) {
|
|
156
|
-
res.write('data: ' + JSON.stringify(line) + '\n\n');
|
|
157
|
-
}, function(problem) {
|
|
158
|
-
res.write('event: problem\ndata: ' + JSON.stringify({ error: problem }) + '\n\n');
|
|
159
|
-
});
|
|
160
|
-
var beat = setInterval(function() { res.write(': still here\n\n'); }, HEARTBEAT_MS);
|
|
161
|
-
if (beat.unref) beat.unref();
|
|
162
|
-
var closed = false;
|
|
163
|
-
req.on('close', function() {
|
|
164
|
-
if (closed) return;
|
|
165
|
-
closed = true;
|
|
166
|
-
clearInterval(beat);
|
|
167
|
-
stop();
|
|
168
|
-
live.set(req.user.email, Math.max((live.get(req.user.email) || 1) - 1, 0));
|
|
169
|
-
});
|
|
170
|
-
});
|
|
171
|
-
|
|
172
|
-
r.get('/audit', function(req, res) {
|
|
173
|
-
res.json({ entries: store.recentAudit(Math.min(Math.max(parseInt(req.query.limit, 10) || 200, 1), 2000)) });
|
|
174
|
-
});
|
|
175
|
-
|
|
176
|
-
return r;
|
|
177
|
-
}
|
|
178
|
-
|
|
179
|
-
module.exports = { createRouter: createRouter, FAILS: FAILS, FAILS_PER_ADDRESS: FAILS_PER_ADDRESS };
|
package/lib/services.js
DELETED
|
@@ -1,76 +0,0 @@
|
|
|
1
|
-
// THE SERVICES THE MONITOR WATCHES — added by hand, kept in services.json.
|
|
2
|
-
// A service is only ever controlled once it is on this list, and only if its
|
|
3
|
-
// unit matches MONITOR_ALLOW (e.g. "xeplr-*"): the list is what you chose to
|
|
4
|
-
// watch, the pattern is what the server owner allows at all. sudoers repeats
|
|
5
|
-
// the pattern, so even a bug here could not reach another unit.
|
|
6
|
-
var store = require('./store');
|
|
7
|
-
var systemd = require('./systemd');
|
|
8
|
-
|
|
9
|
-
var FILE = 'services.json';
|
|
10
|
-
var patterns = [];
|
|
11
|
-
|
|
12
|
-
function setAllowed(list) {
|
|
13
|
-
var p = (Array.isArray(list) ? list : String(list || '').split(',')).map(function(x) { return x.trim(); }).filter(Boolean);
|
|
14
|
-
if (!p.length) throw new Error('MONITOR_ALLOW is not set: the services the monitor may control, e.g. "xeplr-*" (comma-separated, * matches anything)');
|
|
15
|
-
patterns = p;
|
|
16
|
-
}
|
|
17
|
-
|
|
18
|
-
function allowedPatterns() { return patterns.slice(); }
|
|
19
|
-
|
|
20
|
-
function refuse(message, status) { var e = new Error(message); e.status = status || 400; return e; }
|
|
21
|
-
|
|
22
|
-
function all() { return store.read(FILE, []); }
|
|
23
|
-
|
|
24
|
-
/** One watched service by its unit, or a 404. */
|
|
25
|
-
function get(unit) {
|
|
26
|
-
var s = all().find(function(x) { return x.unit === unit; });
|
|
27
|
-
if (!s) throw refuse('"' + unit + '" is not one of the services the monitor watches', 404);
|
|
28
|
-
return s;
|
|
29
|
-
}
|
|
30
|
-
|
|
31
|
-
/** A unit checked: a proper name, allowed, and known to systemd. → its full name. */
|
|
32
|
-
async function checked(name) {
|
|
33
|
-
var unit = systemd.unitName(name);
|
|
34
|
-
if (!systemd.allowed(unit, patterns)) throw refuse(unit + ' is not allowed here. The monitor may control ' + patterns.join(', ') + ' (MONITOR_ALLOW)', 403);
|
|
35
|
-
var st = await systemd.status(unit);
|
|
36
|
-
if (!st.exists) throw refuse('systemd has no service called ' + unit + ' on this server', 404);
|
|
37
|
-
return unit;
|
|
38
|
-
}
|
|
39
|
-
|
|
40
|
-
/** Watch a service: { unit, label }. */
|
|
41
|
-
async function add(body, by) {
|
|
42
|
-
var unit = await checked(body && body.unit);
|
|
43
|
-
var list = all();
|
|
44
|
-
if (list.some(function(x) { return x.unit === unit; })) throw refuse(unit + ' is already on the list', 409);
|
|
45
|
-
var s = { unit: unit, label: String((body && body.label) || '').trim().slice(0, 80) || unit.replace(/\.service$/, ''), addedBy: by, addedAt: new Date().toISOString() };
|
|
46
|
-
list.push(s);
|
|
47
|
-
store.write(FILE, list);
|
|
48
|
-
return s;
|
|
49
|
-
}
|
|
50
|
-
|
|
51
|
-
/** Change a watched service in place: its label, or which unit it is. */
|
|
52
|
-
async function edit(unit, body, by) {
|
|
53
|
-
var list = all();
|
|
54
|
-
var s = list.find(function(x) { return x.unit === unit; });
|
|
55
|
-
if (!s) throw refuse('"' + unit + '" is not one of the services the monitor watches', 404);
|
|
56
|
-
if (body.unit !== undefined && systemd.unitName(body.unit) !== unit) {
|
|
57
|
-
var next = await checked(body.unit);
|
|
58
|
-
if (list.some(function(x) { return x.unit === next; })) throw refuse(next + ' is already on the list', 409);
|
|
59
|
-
s.unit = next;
|
|
60
|
-
}
|
|
61
|
-
if (body.label !== undefined) s.label = String(body.label).trim().slice(0, 80) || s.unit.replace(/\.service$/, '');
|
|
62
|
-
s.changedBy = by;
|
|
63
|
-
s.changedAt = new Date().toISOString();
|
|
64
|
-
store.write(FILE, list);
|
|
65
|
-
return s;
|
|
66
|
-
}
|
|
67
|
-
|
|
68
|
-
/** Stop watching a service. The service itself is not touched. */
|
|
69
|
-
function remove(unit) {
|
|
70
|
-
var list = all();
|
|
71
|
-
var left = list.filter(function(x) { return x.unit !== unit; });
|
|
72
|
-
if (left.length === list.length) throw refuse('"' + unit + '" is not one of the services the monitor watches', 404);
|
|
73
|
-
store.write(FILE, left);
|
|
74
|
-
}
|
|
75
|
-
|
|
76
|
-
module.exports = { setAllowed: setAllowed, allowedPatterns: allowedPatterns, all: all, get: get, add: add, edit: edit, remove: remove };
|
package/lib/session.js
DELETED
|
@@ -1,78 +0,0 @@
|
|
|
1
|
-
// SIGNED-IN SESSIONS — a signed cookie, nothing stored. The cookie holds the
|
|
2
|
-
// email, when it expires and the user's sessionVersion; it is signed with
|
|
3
|
-
// MONITOR_SECRET, so it cannot be made or changed without it. A changed
|
|
4
|
-
// password bumps sessionVersion, which signs that user out everywhere.
|
|
5
|
-
//
|
|
6
|
-
// Cookie: httpOnly (no script reads it), SameSite=Strict (another site cannot
|
|
7
|
-
// send it), Secure behind https. Every request that changes something must
|
|
8
|
-
// also carry the header x-xeplr-monitor: 1, which a form on another site
|
|
9
|
-
// cannot add.
|
|
10
|
-
var crypto = require('crypto');
|
|
11
|
-
var users = require('./users');
|
|
12
|
-
|
|
13
|
-
var COOKIE = 'xeplr_monitor';
|
|
14
|
-
var HOURS = 12;
|
|
15
|
-
var secret = null;
|
|
16
|
-
|
|
17
|
-
function setSecret(s) {
|
|
18
|
-
if (!s) throw new Error('MONITOR_SECRET is not set: it signs the monitor\'s sign-in cookies');
|
|
19
|
-
if (String(s).length < 32) throw new Error('MONITOR_SECRET must be at least 32 characters (it is ' + String(s).length + ')');
|
|
20
|
-
secret = String(s);
|
|
21
|
-
}
|
|
22
|
-
|
|
23
|
-
function sign(body) { return crypto.createHmac('sha256', secret).update(body).digest('base64url'); }
|
|
24
|
-
|
|
25
|
-
/** A new session's cookie value for a user. */
|
|
26
|
-
function issue(u, now) {
|
|
27
|
-
var body = Buffer.from(JSON.stringify({ e: u.email, x: (now || Date.now()) + HOURS * 3600000, v: u.sessionVersion || 1 })).toString('base64url');
|
|
28
|
-
return body + '.' + sign(body);
|
|
29
|
-
}
|
|
30
|
-
|
|
31
|
-
/** The signed-in user a cookie value belongs to, or null. */
|
|
32
|
-
function read(value, now) {
|
|
33
|
-
if (!value || value.indexOf('.') < 0) return null;
|
|
34
|
-
var parts = value.split('.');
|
|
35
|
-
var want = Buffer.from(sign(parts[0]));
|
|
36
|
-
var got = Buffer.from(parts[1] || '');
|
|
37
|
-
if (want.length !== got.length || !crypto.timingSafeEqual(want, got)) return null;
|
|
38
|
-
var data;
|
|
39
|
-
try { data = JSON.parse(Buffer.from(parts[0], 'base64url').toString('utf8')); } catch (e) { return null; }
|
|
40
|
-
if (!data || data.x < (now || Date.now())) return null;
|
|
41
|
-
var u = users.find(data.e);
|
|
42
|
-
if (!u || (u.sessionVersion || 1) !== data.v) return null;
|
|
43
|
-
return u;
|
|
44
|
-
}
|
|
45
|
-
|
|
46
|
-
// Cookies are parsed by createApp's cookie-parser (@xeplr/base-apis).
|
|
47
|
-
function cookieOf(req) { return (req.cookies && req.cookies[COOKIE]) || null; }
|
|
48
|
-
|
|
49
|
-
function setCookie(req, res, value, maxAgeSeconds) {
|
|
50
|
-
res.cookie(COOKIE, value, { path: '/', httpOnly: true, sameSite: 'strict', secure: Boolean(req.secure), maxAge: maxAgeSeconds * 1000 });
|
|
51
|
-
}
|
|
52
|
-
|
|
53
|
-
function start(req, res, u) { setCookie(req, res, issue(u), HOURS * 3600); }
|
|
54
|
-
function end(req, res) { setCookie(req, res, '', 0); }
|
|
55
|
-
|
|
56
|
-
/** Express middleware: the signed-in user on req.user, else 401. Changes need the monitor's own header. */
|
|
57
|
-
function required(req, res, next) {
|
|
58
|
-
if (req.user && req.monitorChecked) return next(); // already checked by gate() in front
|
|
59
|
-
var u = read(cookieOf(req));
|
|
60
|
-
if (!u) return res.status(401).json({ error: 'Sign in first' });
|
|
61
|
-
if (req.method !== 'GET' && req.headers['x-xeplr-monitor'] !== '1') return res.status(403).json({ error: 'Missing the x-xeplr-monitor header' });
|
|
62
|
-
req.user = u;
|
|
63
|
-
req.monitorChecked = true;
|
|
64
|
-
next();
|
|
65
|
-
}
|
|
66
|
-
|
|
67
|
-
/**
|
|
68
|
-
* createApp's gate (`auth: { middleware }`): every /api route needs a signed-in
|
|
69
|
-
* user except sign-in and sign-out. The page itself is public: it is what you
|
|
70
|
-
* sign in on.
|
|
71
|
-
*/
|
|
72
|
-
function gate(req, res, next) {
|
|
73
|
-
var p = req.path;
|
|
74
|
-
if (p.indexOf('/api/') !== 0 || p === '/api/login' || p === '/api/logout') return next();
|
|
75
|
-
return required(req, res, next);
|
|
76
|
-
}
|
|
77
|
-
|
|
78
|
-
module.exports = { setSecret: setSecret, issue: issue, read: read, cookieOf: cookieOf, start: start, end: end, required: required, gate: gate, COOKIE: COOKIE };
|
package/lib/store.js
DELETED
|
@@ -1,73 +0,0 @@
|
|
|
1
|
-
// THE MONITOR'S OWN FILES — no database. The monitor is what you open when
|
|
2
|
-
// something is down, Postgres included, so it keeps everything it needs in
|
|
3
|
-
// plain files under MONITOR_DATA_DIR:
|
|
4
|
-
//
|
|
5
|
-
// users.json who can sign in (lib/users.js)
|
|
6
|
-
// services.json the services it watches, each one added by hand
|
|
7
|
-
// audit.ndjson every sign-in and every action, one line each, appended
|
|
8
|
-
//
|
|
9
|
-
// The folder is required and must be absolute: a relative one resolves
|
|
10
|
-
// against wherever the process was started, so the same install would read a
|
|
11
|
-
// different user list depending on the working directory.
|
|
12
|
-
var fs = require('fs');
|
|
13
|
-
var path = require('path');
|
|
14
|
-
|
|
15
|
-
var dir = null;
|
|
16
|
-
|
|
17
|
-
/** Set the folder, refusing a missing or relative one. Made if it is not there. */
|
|
18
|
-
function open(dataDir) {
|
|
19
|
-
if (!dataDir) throw new Error('MONITOR_DATA_DIR is not set: the folder that holds the monitor\'s users, services and audit log');
|
|
20
|
-
if (!path.isAbsolute(dataDir)) throw new Error('MONITOR_DATA_DIR must be an absolute path (it is "' + dataDir + '")');
|
|
21
|
-
fs.mkdirSync(dataDir, { recursive: true, mode: 0o700 });
|
|
22
|
-
dir = dataDir;
|
|
23
|
-
return dir;
|
|
24
|
-
}
|
|
25
|
-
|
|
26
|
-
function where(name) {
|
|
27
|
-
if (!dir) throw new Error('The monitor\'s store is not open: call store.open(MONITOR_DATA_DIR) first');
|
|
28
|
-
return path.join(dir, name);
|
|
29
|
-
}
|
|
30
|
-
|
|
31
|
-
/** A JSON file's content, or `fallback` when it does not exist yet. */
|
|
32
|
-
function read(name, fallback) {
|
|
33
|
-
var file = where(name);
|
|
34
|
-
if (!fs.existsSync(file)) return fallback;
|
|
35
|
-
return JSON.parse(fs.readFileSync(file, 'utf8'));
|
|
36
|
-
}
|
|
37
|
-
|
|
38
|
-
/** Write a JSON file whole: to a temporary file, then renamed, so a crash never leaves half of one. */
|
|
39
|
-
function write(name, value) {
|
|
40
|
-
var file = where(name);
|
|
41
|
-
var tmp = file + '.' + process.pid + '.tmp';
|
|
42
|
-
fs.writeFileSync(tmp, JSON.stringify(value, null, 2) + '\n', { mode: 0o600 });
|
|
43
|
-
fs.renameSync(tmp, file);
|
|
44
|
-
}
|
|
45
|
-
|
|
46
|
-
/** One line added to the audit log. Never throws: an action that worked is not undone by a full disk. */
|
|
47
|
-
function audit(entry) {
|
|
48
|
-
try {
|
|
49
|
-
fs.appendFileSync(where('audit.ndjson'), JSON.stringify(Object.assign({ at: new Date().toISOString() }, entry)) + '\n', { mode: 0o600 });
|
|
50
|
-
} catch (e) {
|
|
51
|
-
console.error('[xeplr-monitor] could not write the audit log:', e.message);
|
|
52
|
-
}
|
|
53
|
-
}
|
|
54
|
-
|
|
55
|
-
/** The newest `limit` audit lines, newest first. Reads the end of the file only. */
|
|
56
|
-
function recentAudit(limit) {
|
|
57
|
-
var file = where('audit.ndjson');
|
|
58
|
-
if (!fs.existsSync(file)) return [];
|
|
59
|
-
var size = fs.statSync(file).size;
|
|
60
|
-
var want = Math.min(size, 1024 * 1024);
|
|
61
|
-
var fd = fs.openSync(file, 'r');
|
|
62
|
-
var buf = Buffer.alloc(want);
|
|
63
|
-
try { fs.readSync(fd, buf, 0, want, size - want); } finally { fs.closeSync(fd); }
|
|
64
|
-
var lines = buf.toString('utf8').split('\n').filter(Boolean);
|
|
65
|
-
if (want < size) lines.shift(); // the first line was cut in half
|
|
66
|
-
var out = [];
|
|
67
|
-
for (var i = lines.length - 1; i >= 0 && out.length < limit; i--) {
|
|
68
|
-
try { out.push(JSON.parse(lines[i])); } catch (e) { /* a line being written */ }
|
|
69
|
-
}
|
|
70
|
-
return out;
|
|
71
|
-
}
|
|
72
|
-
|
|
73
|
-
module.exports = { open: open, read: read, write: write, audit: audit, recentAudit: recentAudit };
|
package/lib/users.js
DELETED
|
@@ -1,119 +0,0 @@
|
|
|
1
|
-
// WHO CAN SIGN IN — the monitor's own list, in users.json, independent of
|
|
2
|
-
// every app it controls. If BI's auth service is the thing that is down, a
|
|
3
|
-
// monitor that signed in through it could not be used to restart it.
|
|
4
|
-
//
|
|
5
|
-
// Users are added on the server, never from the web page
|
|
6
|
-
// (bin/users.js: xeplr-monitor-users add <email>). Passwords are kept as
|
|
7
|
-
// scrypt hashes; a one-time code from an authenticator app is asked for too
|
|
8
|
-
// when the user has one (the default for a new user).
|
|
9
|
-
var crypto = require('crypto');
|
|
10
|
-
var store = require('./store');
|
|
11
|
-
var totp = require('@xeplr/utils/lib/totp');
|
|
12
|
-
|
|
13
|
-
var FILE = 'users.json';
|
|
14
|
-
var SCRYPT = { N: 16384, r: 8, p: 1, keylen: 64 };
|
|
15
|
-
var MIN_PASSWORD = 12;
|
|
16
|
-
|
|
17
|
-
function all() { return store.read(FILE, []); }
|
|
18
|
-
function save(list) { store.write(FILE, list); }
|
|
19
|
-
function clean(email) { return String(email || '').trim().toLowerCase(); }
|
|
20
|
-
|
|
21
|
-
function hash(password) {
|
|
22
|
-
var salt = crypto.randomBytes(16);
|
|
23
|
-
var key = crypto.scryptSync(password, salt, SCRYPT.keylen, { N: SCRYPT.N, r: SCRYPT.r, p: SCRYPT.p });
|
|
24
|
-
return ['scrypt', SCRYPT.N, SCRYPT.r, SCRYPT.p, salt.toString('base64'), key.toString('base64')].join('$');
|
|
25
|
-
}
|
|
26
|
-
|
|
27
|
-
function matches(password, stored) {
|
|
28
|
-
var parts = String(stored || '').split('$');
|
|
29
|
-
if (parts[0] !== 'scrypt' || parts.length !== 6) return false;
|
|
30
|
-
var want = Buffer.from(parts[5], 'base64');
|
|
31
|
-
var got = crypto.scryptSync(String(password), Buffer.from(parts[4], 'base64'), want.length, { N: +parts[1], r: +parts[2], p: +parts[3] });
|
|
32
|
-
return crypto.timingSafeEqual(want, got);
|
|
33
|
-
}
|
|
34
|
-
|
|
35
|
-
function passwordProblem(password) {
|
|
36
|
-
if (String(password || '').length < MIN_PASSWORD) return 'The password must be at least ' + MIN_PASSWORD + ' characters';
|
|
37
|
-
return null;
|
|
38
|
-
}
|
|
39
|
-
|
|
40
|
-
// Checked against when the email is unknown, so a wrong email takes as long
|
|
41
|
-
// as a wrong password and the timing does not say which emails exist.
|
|
42
|
-
var DUMMY = hash(crypto.randomBytes(16).toString('hex'));
|
|
43
|
-
|
|
44
|
-
/** What a page may see of a user. */
|
|
45
|
-
function shown(u) {
|
|
46
|
-
return { email: u.email, name: u.name || u.email, twoStep: Boolean(u.totp), createdAt: u.createdAt };
|
|
47
|
-
}
|
|
48
|
-
|
|
49
|
-
function list() { return all().map(shown); }
|
|
50
|
-
|
|
51
|
-
function find(email) {
|
|
52
|
-
email = clean(email);
|
|
53
|
-
return all().find(function(u) { return u.email === email; }) || null;
|
|
54
|
-
}
|
|
55
|
-
|
|
56
|
-
/** Add a user. → { user, secret, url } — the secret only when a code is asked for. */
|
|
57
|
-
function add(email, password, opts) {
|
|
58
|
-
opts = opts || {};
|
|
59
|
-
email = clean(email);
|
|
60
|
-
if (!/^[^@\s]+@[^@\s]+$/.test(email)) throw new Error('"' + email + '" is not an email address');
|
|
61
|
-
var bad = passwordProblem(password);
|
|
62
|
-
if (bad) throw new Error(bad);
|
|
63
|
-
var users = all();
|
|
64
|
-
if (users.some(function(u) { return u.email === email; })) throw new Error(email + ' is already a user');
|
|
65
|
-
var secret = opts.twoStep === false ? null : totp.newSecret();
|
|
66
|
-
var u = { email: email, name: opts.name || email, hash: hash(password), totp: secret, sessionVersion: 1, createdAt: new Date().toISOString() };
|
|
67
|
-
users.push(u);
|
|
68
|
-
save(users);
|
|
69
|
-
return { user: shown(u), secret: secret, url: secret ? totp.otpauthUrl(secret, email, 'Xeplr Monitor') : null };
|
|
70
|
-
}
|
|
71
|
-
|
|
72
|
-
function remove(email) {
|
|
73
|
-
email = clean(email);
|
|
74
|
-
var users = all();
|
|
75
|
-
var left = users.filter(function(u) { return u.email !== email; });
|
|
76
|
-
if (left.length === users.length) throw new Error(email + ' is not a user');
|
|
77
|
-
save(left);
|
|
78
|
-
}
|
|
79
|
-
|
|
80
|
-
/** Change a password. Every session that user has open is signed out. */
|
|
81
|
-
function setPassword(email, password) {
|
|
82
|
-
var bad = passwordProblem(password);
|
|
83
|
-
if (bad) throw new Error(bad);
|
|
84
|
-
return change(email, function(u) { u.hash = hash(password); u.sessionVersion = (u.sessionVersion || 1) + 1; });
|
|
85
|
-
}
|
|
86
|
-
|
|
87
|
-
/** A new authenticator secret (or none). Every session that user has open is signed out. */
|
|
88
|
-
function setTwoStep(email, on) {
|
|
89
|
-
var secret = on ? totp.newSecret() : null;
|
|
90
|
-
change(email, function(u) { u.totp = secret; u.sessionVersion = (u.sessionVersion || 1) + 1; });
|
|
91
|
-
return { secret: secret, url: secret ? totp.otpauthUrl(secret, clean(email), 'Xeplr Monitor') : null };
|
|
92
|
-
}
|
|
93
|
-
|
|
94
|
-
function change(email, fn) {
|
|
95
|
-
email = clean(email);
|
|
96
|
-
var users = all();
|
|
97
|
-
var u = users.find(function(x) { return x.email === email; });
|
|
98
|
-
if (!u) throw new Error(email + ' is not a user');
|
|
99
|
-
fn(u);
|
|
100
|
-
save(users);
|
|
101
|
-
return shown(u);
|
|
102
|
-
}
|
|
103
|
-
|
|
104
|
-
/**
|
|
105
|
-
* Check a sign-in. → { user } or { problem, needsCode? }. One message for a
|
|
106
|
-
* wrong email or a wrong password, so the page does not say which emails exist.
|
|
107
|
-
*/
|
|
108
|
-
function check(email, password, code) {
|
|
109
|
-
var u = find(email);
|
|
110
|
-
var ok = matches(password, u ? u.hash : DUMMY) && Boolean(u);
|
|
111
|
-
if (!ok) return { problem: 'Wrong email or password' };
|
|
112
|
-
if (u.totp) {
|
|
113
|
-
if (!code) return { problem: 'Enter the code from your authenticator app', needsCode: true };
|
|
114
|
-
if (!totp.verify(u.totp, code)) return { problem: 'That code is not right. Codes change every 30 seconds', needsCode: true };
|
|
115
|
-
}
|
|
116
|
-
return { user: u };
|
|
117
|
-
}
|
|
118
|
-
|
|
119
|
-
module.exports = { list: list, find: find, add: add, remove: remove, setPassword: setPassword, setTwoStep: setTwoStep, check: check, shown: shown, MIN_PASSWORD: MIN_PASSWORD };
|