@xeplr/monitor 0.0.0-stage → 0.1.2

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.
@@ -0,0 +1,76 @@
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 ADDED
@@ -0,0 +1,78 @@
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 ADDED
@@ -0,0 +1,73 @@
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/systemd.js ADDED
@@ -0,0 +1,326 @@
1
+ // SYSTEMD — how the monitor sees and controls a service. The apps already run
2
+ // as systemd services on the servers (xeplr-bi-api, -auth, -jobs; testbi's
3
+ // xeplr-bi-dev-*), so the monitor starts nothing itself: it asks systemctl,
4
+ // the same way the deploy does, and reads the journal, where their output goes.
5
+ //
6
+ // No shell is ever involved: every call is execFile/spawn with an argument
7
+ // list, and a unit name is checked against UNIT before it reaches one. Only
8
+ // start, stop, restart and kill change anything.
9
+ //
10
+ // sudo: 'actions' (the default) runs those four through `sudo -n`, which the
11
+ // sudoers file in deploy/ allows for the allowed services only; 'all' reads
12
+ // the journal through sudo too; 'none' runs everything as the monitor's own
13
+ // user (root, or a user in the systemd-journal group that has polkit rights).
14
+ var { execFile, spawn } = require('child_process');
15
+ var fs = require('fs');
16
+
17
+ var UNIT = /^[A-Za-z0-9][A-Za-z0-9@._:-]{0,200}$/;
18
+ var ACTIONS = ['start', 'stop', 'restart', 'kill'];
19
+ var ACTION_LIMIT_MS = 2 * 60 * 1000; // a stop waits for the service's own stop timeout (90s by default)
20
+ var READ_LIMIT_MS = 30 * 1000;
21
+ var MAX_LINES = 5000;
22
+ var PROPS = ['Id', 'Description', 'LoadState', 'ActiveState', 'SubState', 'Result', 'MainPID', 'NRestarts',
23
+ 'ActiveEnterTimestamp', 'InactiveEnterTimestamp', 'ExecMainStatus', 'MemoryCurrent', 'CPUUsageNSec', 'UnitFileState', 'Restart',
24
+ // what runs it, and what it may use
25
+ 'ExecStart', 'WorkingDirectory', 'User', 'FragmentPath', 'ControlGroup',
26
+ 'MemoryPeak', 'MemoryMax', 'MemoryHigh', 'MemorySwapCurrent', 'TasksCurrent', 'TasksMax'];
27
+ var MAX_PROCESSES = 200;
28
+ var TICKS = 100; // USER_HZ: /proc counts CPU time in 1/100 s on every Linux the monitor runs on
29
+
30
+ var cfg = { sudo: 'actions', systemctl: 'systemctl', journalctl: 'journalctl' };
31
+
32
+ function configure(o) {
33
+ o = o || {};
34
+ if (o.sudo && ['actions', 'all', 'none'].indexOf(o.sudo) < 0) throw new Error('MONITOR_SUDO must be actions, all or none (it is "' + o.sudo + '")');
35
+ cfg = Object.assign({}, cfg, o);
36
+ // Running as root, sudo adds nothing.
37
+ if (process.getuid && process.getuid() === 0) cfg.sudo = 'none';
38
+ return cfg;
39
+ }
40
+
41
+ function refuse(message, status) { var e = new Error(message); e.status = status || 400; return e; }
42
+
43
+ /** A unit's full name ("xeplr-bi-api" → "xeplr-bi-api.service"), or an error naming what is wrong. */
44
+ function unitName(name) {
45
+ var n = String(name || '').trim();
46
+ if (!UNIT.test(n)) throw refuse('"' + n + '" is not a service name: letters, digits and @ . _ : - only');
47
+ return /\.(service|socket|timer|target|path|mount)$/.test(n) ? n : n + '.service';
48
+ }
49
+
50
+ /** Whether a unit matches one of the allowed patterns ("xeplr-*"; * matches anything). */
51
+ function allowed(unit, patterns) {
52
+ return (patterns || []).some(function(p) {
53
+ var re = new RegExp('^' + p.trim().replace(/[.+?^${}()|[\]\\]/g, '\\$&').replace(/\*/g, '.*') + '$');
54
+ return re.test(unit) || re.test(unit.replace(/\.service$/, ''));
55
+ });
56
+ }
57
+
58
+ function run(bin, args, useSudo, limitMs) {
59
+ return new Promise(function(resolve, reject) {
60
+ var file = useSudo ? 'sudo' : bin;
61
+ var argv = useSudo ? ['-n', bin].concat(args) : args;
62
+ execFile(file, argv, { timeout: limitMs, maxBuffer: 64 * 1024 * 1024, killSignal: 'SIGKILL' }, function(err, stdout, stderr) {
63
+ if (err) {
64
+ var said = String(stderr || '').trim() || err.message;
65
+ if (err.killed) said = 'No answer within ' + Math.round(limitMs / 1000) + ' seconds';
66
+ else if (/a password is required|sudo: a terminal is required/.test(said)) said = 'sudo refused: the monitor\'s user may not run "' + bin + ' ' + args.join(' ') + '" without a password. See deploy/sudoers.example';
67
+ else if (err.code === 'ENOENT') said = file + ' is not installed here: the monitor controls systemd services, on Linux';
68
+ return reject(Object.assign(new Error(said), { status: 502, stdout: stdout }));
69
+ }
70
+ resolve(String(stdout));
71
+ });
72
+ });
73
+ }
74
+
75
+ function number(v) {
76
+ if (v === undefined || v === '' || v === '[not set]' || v === '18446744073709551615') return null;
77
+ var n = Number(v);
78
+ return Number.isFinite(n) ? n : null;
79
+ }
80
+
81
+ // Asked for as --timestamp=unix ("@1762871581"), so the server's time zone
82
+ // never has to be guessed from "Tue 2026-11-11 16:53:01 IST".
83
+ function when(v) {
84
+ if (!v || v === 'n/a' || v === '0') return null;
85
+ var m = /^@(\d+)/.exec(v);
86
+ if (m) return Number(m[1]) ? new Date(Number(m[1]) * 1000).toISOString() : null;
87
+ var d = new Date(v.replace(/^\w{3} /, ''));
88
+ return isNaN(d) ? v : d.toISOString();
89
+ }
90
+
91
+ // CPU % needs two readings: the last one per unit (and per process), so each
92
+ // poll says how busy it was since the one before. Above 100 means more than
93
+ // one core.
94
+ var lastCpu = new Map();
95
+
96
+ function cpuPercent(map, key, used, at) {
97
+ var prev = map.get(key);
98
+ if (used === null) return null;
99
+ if (prev && at - prev.at < 1000) return prev.percent;
100
+ var percent = prev && used >= prev.used ? Math.round((used - prev.used) / (at - prev.at) * 1000) / 10 : null;
101
+ map.set(key, { used: used, at: at, percent: percent });
102
+ return percent;
103
+ }
104
+
105
+ /**
106
+ * The commands a unit runs, from systemctl's ExecStart:
107
+ * "{ path=/usr/bin/node ; argv[]=/usr/bin/node server.js ; ignore_errors=no ; … }".
108
+ * The same line `ps` shows, so nothing here is more private than that.
109
+ */
110
+ function commandsOf(v) {
111
+ var out = [];
112
+ var re = /path=([^ ;]+) ; argv\[\]=(.*?) ; (?:ignore_errors|flags)=/g;
113
+ var m;
114
+ while ((m = re.exec(v || ''))) out.push({ path: m[1], command: m[2] });
115
+ return out;
116
+ }
117
+
118
+ /** What systemd says about a unit now. */
119
+ async function status(unit) {
120
+ var out = await run(cfg.systemctl, ['show', unit, '--no-pager', '--timestamp=unix', '--property=' + PROPS.join(',')], false, READ_LIMIT_MS);
121
+ var p = {};
122
+ out.split('\n').forEach(function(line) { var i = line.indexOf('='); if (i > 0) p[line.slice(0, i)] = line.slice(i + 1); });
123
+ var active = p.ActiveState || 'unknown';
124
+ var nsec = number(p.CPUUsageNSec);
125
+ return {
126
+ unit: unit,
127
+ description: p.Description || '',
128
+ exists: p.LoadState !== 'not-found',
129
+ loadState: p.LoadState || null,
130
+ state: active, // active | inactive | failed | activating | deactivating | reloading
131
+ subState: p.SubState || null, // running | exited | dead | auto-restart | …
132
+ result: p.Result || null, // success, or why it last ended (exit-code, signal, timeout, oom-kill …)
133
+ pid: number(p.MainPID) || null,
134
+ restarts: number(p.NRestarts),
135
+ since: active === 'active' || active === 'activating' ? when(p.ActiveEnterTimestamp) : when(p.InactiveEnterTimestamp),
136
+ exitStatus: number(p.ExecMainStatus),
137
+ memoryBytes: number(p.MemoryCurrent),
138
+ memoryPeakBytes: number(p.MemoryPeak), // systemd 255+; null before
139
+ memoryMaxBytes: number(p.MemoryMax), // null: no limit
140
+ memoryHighBytes: number(p.MemoryHigh),
141
+ swapBytes: number(p.MemorySwapCurrent),
142
+ cpuSeconds: nsec === null ? null : Math.round(nsec / 1e7) / 100,
143
+ cpuPercent: active === 'active' ? cpuPercent(lastCpu, unit, nsec === null ? null : nsec / 1e6, Date.now()) : null,
144
+ tasks: number(p.TasksCurrent), // threads, every process together
145
+ tasksMax: number(p.TasksMax),
146
+ enabled: p.UnitFileState || null,
147
+ restartPolicy: p.Restart || null,
148
+ runs: {
149
+ commands: commandsOf(p.ExecStart),
150
+ workingDirectory: p.WorkingDirectory && p.WorkingDirectory !== '!' ? p.WorkingDirectory.replace(/^!/, '') : null,
151
+ user: p.User || 'root',
152
+ unitFile: p.FragmentPath || null
153
+ },
154
+ cgroup: p.ControlGroup || null
155
+ };
156
+ }
157
+
158
+ /** start | stop | restart | kill (SIGKILL to every process of it). */
159
+ async function act(unit, action) {
160
+ if (ACTIONS.indexOf(action) < 0) throw refuse('Unknown action "' + action + '": start, stop, restart or kill');
161
+ var args = action === 'kill' ? ['kill', '--signal=SIGKILL', unit] : [action, unit];
162
+ try {
163
+ await run(cfg.systemctl, args, cfg.sudo !== 'none', ACTION_LIMIT_MS);
164
+ } catch (err) {
165
+ // systemd 255 (Ubuntu 24.04) kills the service, then says it could not
166
+ // signal its "auxiliary processes" even when it has none. Done is done:
167
+ // when the service really went down, the kill worked.
168
+ if (action !== 'kill' || !/auxiliary processes/.test(err.message)) throw err;
169
+ var after = await status(unit);
170
+ if (after.state === 'active' && after.subState === 'running') throw err;
171
+ return after;
172
+ }
173
+ return status(unit);
174
+ }
175
+
176
+ // ── its processes ─────────────────────────────────────────────────────────
177
+ var lastProcCpu = new Map();
178
+ var bootAt = null;
179
+
180
+ function readText(file) { try { return fs.readFileSync(file, 'utf8'); } catch (e) { return null; } }
181
+
182
+ /** Every pid in a cgroup and the ones under it (cgroup v2, or v1's systemd tree). */
183
+ function pidsIn(cgroup) {
184
+ var roots = ['/sys/fs/cgroup' + cgroup, '/sys/fs/cgroup/systemd' + cgroup];
185
+ for (var i = 0; i < roots.length; i++) {
186
+ if (readText(roots[i] + '/cgroup.procs') === null) continue;
187
+ var pids = [];
188
+ (function walk(dir, depth) {
189
+ (readText(dir + '/cgroup.procs') || '').split('\n').forEach(function(x) { if (x) pids.push(Number(x)); });
190
+ if (depth > 4) return;
191
+ var kids = [];
192
+ try { kids = fs.readdirSync(dir, { withFileTypes: true }); } catch (e) { /* none */ }
193
+ kids.forEach(function(k) { if (k.isDirectory()) walk(dir + '/' + k.name, depth + 1); });
194
+ })(roots[i], 0);
195
+ return pids;
196
+ }
197
+ return [];
198
+ }
199
+
200
+ /** One process from /proc: what it runs, its memory, CPU and threads. null once it is gone. */
201
+ function processOf(pid, at) {
202
+ var stat = readText('/proc/' + pid + '/stat');
203
+ if (!stat) return null;
204
+ // The name is in brackets and may hold spaces or brackets itself: the fields start after the last ")".
205
+ var f = stat.slice(stat.lastIndexOf(')') + 2).split(' ');
206
+ var status = readText('/proc/' + pid + '/status') || '';
207
+ var kb = function(key) { var m = new RegExp('^' + key + ':\\s+(\\d+) kB', 'm').exec(status); return m ? Number(m[1]) * 1024 : null; };
208
+ var cmd = (readText('/proc/' + pid + '/cmdline') || '').split('\0').filter(Boolean).join(' ');
209
+ var name = stat.slice(stat.indexOf('(') + 1, stat.lastIndexOf(')'));
210
+ if (bootAt === null) { var b = /^btime (\d+)/m.exec(readText('/proc/stat') || ''); bootAt = b ? Number(b[1]) * 1000 : 0; }
211
+ var cpuMs = (Number(f[11]) + Number(f[12])) * 1000 / TICKS;
212
+ return {
213
+ pid: pid,
214
+ parent: Number(f[1]),
215
+ name: name,
216
+ command: cmd || '[' + name + ']',
217
+ state: f[0], // R running, S sleeping, D waiting on disk, Z zombie
218
+ memoryBytes: kb('VmRSS'),
219
+ swapBytes: kb('VmSwap'),
220
+ threads: Number(f[17]),
221
+ cpuSeconds: Math.round(cpuMs / 10) / 100,
222
+ cpuPercent: cpuPercent(lastProcCpu, pid + ':' + f[19], cpuMs, at),
223
+ startedAt: bootAt ? new Date(bootAt + Number(f[19]) * 1000 / TICKS).toISOString() : null
224
+ };
225
+ }
226
+
227
+ /**
228
+ * Every process of a unit, the main one first, then by memory, from the
229
+ * status already read (its cgroup and main pid). Read from the cgroup and
230
+ * /proc, which any user may read: no sudo. Linux only; elsewhere an empty list.
231
+ */
232
+ function processes(st) {
233
+ var at = Date.now();
234
+ var list = st && st.cgroup ? pidsIn(st.cgroup).slice(0, MAX_PROCESSES).map(function(pid) { return processOf(pid, at); }).filter(Boolean) : [];
235
+ list.sort(function(a, b) { return (b.pid === st.pid) - (a.pid === st.pid) || (b.memoryBytes || 0) - (a.memoryBytes || 0); });
236
+ return list;
237
+ }
238
+
239
+ /** Forget the CPU readings of processes that are gone. */
240
+ function forgetGone(alive) {
241
+ lastProcCpu.forEach(function(v, key) { if (!alive.has(Number(key.split(':')[0]))) lastProcCpu.delete(key); });
242
+ }
243
+
244
+ var LEVELS = { 0: 'error', 1: 'error', 2: 'error', 3: 'error', 4: 'warn', 5: 'info', 6: 'info', 7: 'debug' };
245
+
246
+ /** One journal entry (journalctl -o json) as a log line. */
247
+ function lineOf(e) {
248
+ var msg = e.MESSAGE;
249
+ if (Array.isArray(msg)) msg = Buffer.from(msg).toString('utf8'); // not valid UTF-8 as sent: journalctl gives the bytes
250
+ return {
251
+ at: new Date(Math.floor(Number(e.__REALTIME_TIMESTAMP) / 1000)).toISOString(),
252
+ level: LEVELS[e.PRIORITY] || 'info',
253
+ pid: e._PID ? Number(e._PID) : null,
254
+ from: e.SYSLOG_IDENTIFIER || e._COMM || null,
255
+ message: msg === undefined || msg === null ? '' : String(msg),
256
+ cursor: e.__CURSOR
257
+ };
258
+ }
259
+
260
+ function parse(out) {
261
+ var rows = [];
262
+ out.split('\n').forEach(function(l) { if (!l) return; try { rows.push(lineOf(JSON.parse(l))); } catch (e) { /* not a journal entry */ } });
263
+ return rows;
264
+ }
265
+
266
+ /**
267
+ * A unit's log lines, oldest first: the last `lines` of them (at most
268
+ * MAX_LINES), between `since` and `until` when given, only those containing
269
+ * `grep` (any case) and at `level` or worse.
270
+ */
271
+ async function logs(unit, o) {
272
+ o = o || {};
273
+ var lines = Math.min(Math.max(parseInt(o.lines, 10) || 200, 1), MAX_LINES);
274
+ var filtered = Boolean(o.grep || o.level);
275
+ // A filter is applied here, not by journalctl (whose --grep is not in every
276
+ // build), so read further back to still find `lines` matches.
277
+ var args = ['-u', unit, '-o', 'json', '--no-pager', '-n', String(filtered ? MAX_LINES * 4 : lines)];
278
+ if (o.since) args.push('--since', stamp(o.since, 'since'));
279
+ if (o.until) args.push('--until', stamp(o.until, 'until'));
280
+ var rows = parse(await run(cfg.journalctl, args, cfg.sudo === 'all', READ_LIMIT_MS));
281
+ if (o.grep) { var g = String(o.grep).toLowerCase(); rows = rows.filter(function(r) { return r.message.toLowerCase().indexOf(g) > -1; }); }
282
+ if (o.level) { var worst = rank(o.level); rows = rows.filter(function(r) { return rank(r.level) <= worst; }); }
283
+ return rows.slice(-lines);
284
+ }
285
+
286
+ function rank(level) { return { error: 0, warn: 1, info: 2, debug: 3 }[level] === undefined ? 3 : { error: 0, warn: 1, info: 2, debug: 3 }[level]; }
287
+
288
+ /** A time journalctl takes: an ISO time, made "YYYY-MM-DD HH:MM:SS" (UTC, said so). */
289
+ function stamp(v, name) {
290
+ var d = new Date(v);
291
+ if (isNaN(d)) throw refuse(name + ' is not a time: "' + v + '"');
292
+ return d.toISOString().replace('T', ' ').slice(0, 19) + ' UTC';
293
+ }
294
+
295
+ /**
296
+ * Follow a unit's log as it is written: `onLine(line)` for each new line.
297
+ * → stop(). The journalctl process ends with stop() — a page that closes its
298
+ * log ends what it was reading.
299
+ */
300
+ function follow(unit, onLine, onEnd) {
301
+ var argv = ['-u', unit, '-o', 'json', '--no-pager', '-f', '-n', '0'];
302
+ var child = cfg.sudo === 'all' ? spawn('sudo', ['-n', cfg.journalctl].concat(argv)) : spawn(cfg.journalctl, argv);
303
+ var rest = '';
304
+ child.stdout.on('data', function(chunk) {
305
+ var text = rest + chunk.toString('utf8');
306
+ var parts = text.split('\n');
307
+ rest = parts.pop();
308
+ parts.forEach(function(l) { if (!l) return; try { onLine(lineOf(JSON.parse(l))); } catch (e) { /* not a journal entry */ } });
309
+ });
310
+ var errText = '';
311
+ child.stderr.on('data', function(c) { errText += c.toString('utf8'); });
312
+ child.on('error', function(e) { if (onEnd) onEnd(e.message); });
313
+ child.on('close', function(code) { if (onEnd && code) onEnd(errText.trim() || 'journalctl ended (' + code + ')'); });
314
+ return function stop() { try { child.kill('SIGTERM'); } catch (e) { /* already gone */ } };
315
+ }
316
+
317
+ /** The unit this process itself runs in (from its cgroup), or null — so the monitor never stops itself. */
318
+ function selfUnit() {
319
+ try {
320
+ var cg = fs.readFileSync('/proc/self/cgroup', 'utf8');
321
+ var m = cg.match(/\/([^/\n]+\.service)(\n|$|\/)/);
322
+ return m ? m[1] : null;
323
+ } catch (e) { return null; }
324
+ }
325
+
326
+ module.exports = { configure: configure, unitName: unitName, allowed: allowed, status: status, act: act, processes: processes, forgetGone: forgetGone, commandsOf: commandsOf, logs: logs, follow: follow, selfUnit: selfUnit, lineOf: lineOf, ACTIONS: ACTIONS, MAX_LINES: MAX_LINES };
package/lib/users.js ADDED
@@ -0,0 +1,119 @@
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 };