@xeplr/monitor 0.1.2 → 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.
Files changed (66) hide show
  1. package/README.md +148 -99
  2. package/api/README.md +71 -0
  3. package/api/app.js +46 -0
  4. package/api/bin/auth.js +37 -0
  5. package/api/bin/www +72 -0
  6. package/api/db/setup.js +10 -0
  7. package/api/env.required.js +37 -0
  8. package/api/lib/host.js +188 -0
  9. package/api/lib/jobs.js +83 -0
  10. package/api/lib/services.js +67 -0
  11. package/api/lib/stats.js +362 -0
  12. package/{lib → api/lib}/systemd.js +75 -14
  13. package/api/migrations/0001_monitor.sql +43 -0
  14. package/api/migrations/0002_backup_connections.sql +26 -0
  15. package/api/migrations/0003_settings_audit.sql +18 -0
  16. package/api/migrations/0004_monitor_stats.sql +73 -0
  17. package/api/migrations/README.md +9 -0
  18. package/api/migrations-auth/0006_monitor.sql +56 -0
  19. package/api/migrations-auth/0007_monitor_home.sql +42 -0
  20. package/api/migrations-auth/0008_backups.sql +44 -0
  21. package/api/migrations-auth/0009_app_settings.sql +44 -0
  22. package/api/migrations-auth/0010_monitor_history.sql +22 -0
  23. package/api/models/index.js +18 -0
  24. package/api/package-lock.json +2839 -0
  25. package/api/package.json +39 -0
  26. package/api/production.env.example +61 -0
  27. package/api/routes/appSettings.js +73 -0
  28. package/api/routes/index.js +47 -0
  29. package/api/routes/monitor.js +196 -0
  30. package/api/setup.schema.js +166 -0
  31. package/deploy/control.sh +27 -0
  32. package/deploy/deploy.js +183 -0
  33. package/deploy/install.sh +240 -0
  34. package/deploy/settings.cjs +93 -0
  35. package/package.json +28 -46
  36. package/ui/.env +8 -0
  37. package/ui/README.md +29 -0
  38. package/ui/index.html +13 -0
  39. package/ui/package-lock.json +2094 -0
  40. package/ui/package.json +31 -0
  41. package/ui/pages.json +33 -0
  42. package/ui/public/logo-wide.svg +17 -0
  43. package/ui/public/logo.svg +10 -0
  44. package/ui/src/App.jsx +130 -0
  45. package/ui/src/api/monitor.js +6 -0
  46. package/ui/src/index.css +414 -0
  47. package/ui/src/main.jsx +27 -0
  48. package/ui/src/pages/Connections.jsx +9 -0
  49. package/ui/src/pages/Home.jsx +8 -0
  50. package/ui/src/pages/Monitor.jsx +9 -0
  51. package/ui/vite.config.js +56 -0
  52. package/bin/server.js +0 -19
  53. package/bin/users.js +0 -86
  54. package/deploy/monitor.env.example +0 -16
  55. package/deploy/nginx.conf.example +0 -17
  56. package/deploy/sudoers.example +0 -13
  57. package/deploy/xeplr-monitor.service +0 -26
  58. package/index.js +0 -89
  59. package/lib/router.js +0 -179
  60. package/lib/services.js +0 -76
  61. package/lib/session.js +0 -78
  62. package/lib/store.js +0 -73
  63. package/lib/users.js +0 -119
  64. package/public/assets/index-BsBYpvNI.js +0 -18
  65. package/public/assets/index-DNZBwVTn.css +0 -1
  66. package/public/index.html +0 -15
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 };