@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.
Files changed (67) hide show
  1. package/README.md +138 -125
  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 +177 -77
  34. package/deploy/settings.cjs +93 -0
  35. package/package.json +28 -47
  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/deploy.js +0 -181
  53. package/bin/server.js +0 -19
  54. package/bin/users.js +0 -86
  55. package/deploy/monitor.env.example +0 -16
  56. package/deploy/nginx.conf.example +0 -18
  57. package/deploy/sudoers.example +0 -13
  58. package/deploy/xeplr-monitor.service +0 -26
  59. package/index.js +0 -89
  60. package/lib/router.js +0 -179
  61. package/lib/services.js +0 -76
  62. package/lib/session.js +0 -78
  63. package/lib/store.js +0 -73
  64. package/lib/users.js +0 -119
  65. package/public/assets/index-BsBYpvNI.js +0 -18
  66. package/public/assets/index-DNZBwVTn.css +0 -1
  67. package/public/index.html +0 -15
@@ -0,0 +1,8 @@
1
+ // The server itself: memory in GB, CPU, disks and uptime — @xeplr/ui-monitor's
2
+ // ServerPage, on this app's API and sign-in. The page you land on.
3
+ import { ServerPage } from '@xeplr/ui-monitor'
4
+ import { monitor } from '../api/monitor.js'
5
+
6
+ export default function Home() {
7
+ return <ServerPage api={monitor} />
8
+ }
@@ -0,0 +1,9 @@
1
+ // The server's services: how each is doing, start / stop / restart / kill, and
2
+ // their logs live — @xeplr/ui-monitor's page, on this app's API and sign-in.
3
+ // Who may see, control or change what is the roles' (migrations-auth/0006).
4
+ import { MonitorPage } from '@xeplr/ui-monitor'
5
+ import { monitor } from '../api/monitor.js'
6
+
7
+ export default function Monitor() {
8
+ return <MonitorPage api={monitor} />
9
+ }
@@ -0,0 +1,56 @@
1
+ import { defineConfig, loadEnv } from 'vite'
2
+ import react from '@vitejs/plugin-react'
3
+
4
+ // EVERY API PREFIX THIS APP CALLS.
5
+ //
6
+ // A path missing from this list does NOT fail loudly — Vite falls through to
7
+ // the SPA and serves index.html, so the fetch succeeds and the JSON parse is
8
+ // what breaks: `Unexpected token '<'`. Adding a route to the backend is only
9
+ // half of shipping an endpoint; it has to be listed here too.
10
+ const API_PATHS = [
11
+ '/health',
12
+ '/whoami',
13
+ // The setup page and its status (@xeplr/setup, served by the API before
14
+ // sign-in): App settings asks /setup/status while the app restarts.
15
+ '/setup',
16
+ // Every data address lives under /api, so a PAGE path and a DATA path can
17
+ // never collide. Without that split, adding '/tasks' here shadowed the UI's
18
+ // own /tasks page — opening it showed raw JSON instead of the app.
19
+ '/api'
20
+ ]
21
+
22
+ export default defineConfig(({ mode }) => {
23
+ // Prefix '' so plain names load, not just VITE_-prefixed ones. These are dev
24
+ // server settings, not values shipped to the browser.
25
+ const env = loadEnv(mode, process.cwd(), '')
26
+
27
+ // NO PORT LITERALS. A hardcoded fallback is a second answer to a question
28
+ // .env already answers, and it is the one that wins when the file is missing
29
+ // — exactly when you want to be told rather than quietly served elsewhere.
30
+ const port = Number(env.UI_PORT)
31
+ const authUrl = env.AUTH_URL
32
+ const apiUrl = env.API_URL
33
+ if (!port || !authUrl || !apiUrl) {
34
+ throw new Error('ui/.env must set UI_PORT, AUTH_URL and API_URL')
35
+ }
36
+
37
+ const proxy = {
38
+ // Only the real network calls (/auth/api/*), NOT bare /auth — that prefix
39
+ // is also used by client-side routes (/auth/login, /auth/profile), which
40
+ // must fall through to Vite's SPA index.html rather than the auth backend.
41
+ '/auth/api': authUrl
42
+ }
43
+ API_PATHS.forEach((p) => { proxy[p] = apiUrl })
44
+
45
+ return {
46
+ plugins: [react()],
47
+ // Force every import to THIS app's copy, so hook-using libraries don't
48
+ // load twice and break the rules of hooks in ways that read as impossible.
49
+ resolve: { dedupe: ['react', 'react-dom', 'react-router-dom', '@xeplr/ui-table', '@xeplr/ui-utils'] },
50
+ // 127.0.0.1, not 'localhost': Node resolves 'localhost' to IPv6 (::1)
51
+ // first, so the dev server listened on ::1 alone and a browser going to
52
+ // 127.0.0.1 was refused.
53
+ server: { host: '127.0.0.1', port, strictPort: true, proxy },
54
+ preview: { port, strictPort: true }
55
+ }
56
+ })
package/bin/deploy.js DELETED
@@ -1,181 +0,0 @@
1
- #!/usr/bin/env node
2
- // DEPLOY THE MONITOR TO A SERVER, FROM YOUR LAPTOP — over SSH, asking for
3
- // what it needs as it goes. Nothing is stored: not in the repository, not on
4
- // your laptop. The sign-in secret is made on the server; your password is
5
- // typed (hidden) and goes only to the server, on SSH's input.
6
- //
7
- // npx -p @xeplr/monitor xeplr-monitor-deploy
8
- // npx -p @xeplr/monitor xeplr-monitor-deploy --host testbi.xeplr.com --user ubuntu --key ~/.ssh/testbi.pem
9
- //
10
- // Anything not given as an argument is asked. The password is always asked
11
- // (or read from MONITOR_NEW_PASSWORD, for a script), never an argument: it
12
- // would sit in the shell's history and in `ps`.
13
- //
14
- // What runs on the server is deploy/install.sh, as root through `sudo -n`, so
15
- // the SSH login needs passwordless sudo (as BI's deploy login has). Running it
16
- // again updates in place.
17
- var fs = require('fs');
18
- var os = require('os');
19
- var path = require('path');
20
- var readline = require('readline');
21
- var { spawn } = require('child_process');
22
- var users = require('../lib/users');
23
- var pkg = require('../package.json');
24
-
25
- var OPTIONS = {
26
- host: 'The server (a host name, an IP, or a name from ~/.ssh/config)',
27
- user: 'The SSH login (blank: as ~/.ssh/config or your own name says)',
28
- 'ssh-port': 'The SSH port',
29
- key: 'The private key file (blank: ssh-agent or ~/.ssh/config)',
30
- allow: 'The services it may control, comma-separated (* matches anything)',
31
- port: 'Its port on the server (nginx forwards to it)',
32
- domain: 'Its own web address for nginx, e.g. monitor.xeplr.com (blank: leave nginx alone)',
33
- certbot: 'Get an https certificate for it with certbot now? (y/n)',
34
- email: 'Your email, to sign in with',
35
- name: 'Your name (optional)',
36
- version: 'The @xeplr/monitor version to install'
37
- };
38
- var DEFAULTS = { 'ssh-port': '22', allow: 'xeplr-*', port: '19400', certbot: 'y', version: pkg.version };
39
-
40
- function parseArgs(argv) {
41
- var out = {};
42
- for (var i = 0; i < argv.length; i++) {
43
- var m = /^--([a-z-]+)(?:=(.*))?$/.exec(argv[i]);
44
- if (!m) throw new Error('Not an option: ' + argv[i] + '. Options: ' + Object.keys(OPTIONS).map(function(k) { return '--' + k; }).join(' '));
45
- if (m[1] === 'help') { out.help = true; continue; }
46
- if (m[1] === 'yes') { out.yes = true; continue; }
47
- if (!OPTIONS[m[1]]) throw new Error('Unknown option --' + m[1]);
48
- out[m[1]] = m[2] !== undefined ? m[2] : argv[++i];
49
- }
50
- return out;
51
- }
52
-
53
- // Answers are read as lines into a queue, so a line typed (or pasted, or
54
- // piped) before its question is asked is kept for it, not dropped. While a
55
- // password is asked, what is typed is not echoed.
56
- var rl = null;
57
- var lines = [];
58
- var waiting = null;
59
- var ended = false;
60
- var hidden = false;
61
- function lineReader() {
62
- if (rl) return rl;
63
- rl = readline.createInterface({ input: process.stdin, output: process.stdout, terminal: Boolean(process.stdin.isTTY) });
64
- var write = rl._writeToOutput;
65
- rl._writeToOutput = function(s) { if (!hidden) write.call(rl, s); };
66
- rl.on('line', function(l) { if (waiting) { var w = waiting; waiting = null; w(l); } else lines.push(l); });
67
- rl.on('close', function() { ended = true; if (waiting) { var w = waiting; waiting = null; w(''); } });
68
- return rl;
69
- }
70
- function nextLine(prompt) {
71
- lineReader();
72
- process.stdout.write(prompt);
73
- if (lines.length) { var l = lines.shift(); if (!process.stdin.isTTY) process.stdout.write('\n'); return Promise.resolve(l); }
74
- if (ended) { process.stdout.write('\n'); return Promise.resolve(''); }
75
- return new Promise(function(resolve) { waiting = function(l) { if (!process.stdin.isTTY) process.stdout.write('\n'); resolve(l); }; });
76
- }
77
- function ask(question, fallback) {
78
- return nextLine(' ' + question + (fallback ? ' [' + fallback + ']' : '') + ': ').then(function(a) { return a.trim() || fallback || ''; });
79
- }
80
- function askHidden(question) {
81
- if (process.env.MONITOR_NEW_PASSWORD !== undefined) return Promise.resolve(process.env.MONITOR_NEW_PASSWORD);
82
- hidden = true;
83
- return nextLine(' ' + question + ': ').then(function(a) {
84
- hidden = false;
85
- if (process.stdin.isTTY) process.stdout.write('\n');
86
- return a;
87
- });
88
- }
89
-
90
- /** A value as one bash word: 'it'\''s'. */
91
- function quote(v) { return "'" + String(v).replace(/'/g, "'\\''") + "'"; }
92
-
93
- async function gather(given) {
94
- var v = Object.assign({}, given);
95
- console.log('\n Deploy the Xeplr Monitor to a server. Press Enter to take the value in brackets.\n');
96
- for (var k of ['host', 'user', 'ssh-port', 'key', 'allow', 'port', 'domain']) {
97
- if (v[k] === undefined) v[k] = await ask(OPTIONS[k], DEFAULTS[k]);
98
- }
99
- if (!v.host) throw new Error('A server is needed');
100
- if (v.key) {
101
- v.key = v.key.replace(/^~(?=\/)/, os.homedir());
102
- if (!fs.existsSync(v.key)) throw new Error('No key file at ' + v.key);
103
- }
104
- if (!/^\d+$/.test(v.port) || !/^\d+$/.test(v['ssh-port'])) throw new Error('Ports are numbers');
105
- if (!/^[A-Za-z0-9@._:*,\s-]+$/.test(v.allow)) throw new Error('The services to control are names and * only, comma-separated: ' + v.allow);
106
- if (v.domain && !/^[A-Za-z0-9.-]+$/.test(v.domain)) throw new Error('Not a web address: ' + v.domain);
107
- if (v.domain && v.certbot === undefined) v.certbot = await ask(OPTIONS.certbot, DEFAULTS.certbot);
108
- if (v.email === undefined) v.email = await ask(OPTIONS.email);
109
- if (!/^[^\s@]+@[^\s@]+$/.test(v.email || '')) throw new Error('An email is needed, to sign in with');
110
- if (v.name === undefined) v.name = await ask(OPTIONS.name);
111
- if (v.version === undefined) v.version = DEFAULTS.version;
112
- v.password = await askHidden('Password, at least ' + users.MIN_PASSWORD + ' characters (blank: keep it, if you are already a user)');
113
- if (v.password) {
114
- if (v.password.length < users.MIN_PASSWORD) throw new Error('The password must be at least ' + users.MIN_PASSWORD + ' characters');
115
- if (process.env.MONITOR_NEW_PASSWORD === undefined && (await askHidden('Again')) !== v.password) throw new Error('The two passwords are not the same');
116
- }
117
- return v;
118
- }
119
-
120
- function summary(v) {
121
- return [
122
- ' Server ' + (v.user ? v.user + '@' : '') + v.host + (v['ssh-port'] !== '22' ? ':' + v['ssh-port'] : '') + (v.key ? ' (key ' + v.key + ')' : ''),
123
- ' Installs @xeplr/monitor@' + v.version + ', port ' + v.port,
124
- ' Controls ' + v.allow,
125
- ' nginx ' + (v.domain ? v.domain + (/^y/i.test(v.certbot) ? ', with an https certificate (certbot)' : ', http only') : 'left alone'),
126
- ' User ' + v.email + (v.password ? ' (password set)' : ' (password kept)')
127
- ].join('\n');
128
- }
129
-
130
- function deploy(v) {
131
- var script = [
132
- 'XM_VERSION=' + quote(v.version),
133
- 'XM_ALLOW=' + quote(v.allow),
134
- 'XM_PORT=' + quote(v.port),
135
- 'XM_EMAIL=' + quote(v.email),
136
- 'XM_NAME=' + quote(v.name || ''),
137
- 'XM_PASSWORD=' + quote(v.password || ''),
138
- 'XM_DOMAIN=' + quote(v.domain || ''),
139
- 'XM_CERTBOT=' + quote(v.domain && /^y/i.test(v.certbot) ? '1' : '0'),
140
- fs.readFileSync(path.join(__dirname, '..', 'deploy', 'install.sh'), 'utf8')
141
- ].join('\n');
142
- var args = ['-p', v['ssh-port'], '-o', 'BatchMode=yes', '-o', 'StrictHostKeyChecking=accept-new'];
143
- if (v.key) args.push('-i', v.key);
144
- args.push((v.user ? v.user + '@' : '') + v.host, 'sudo -n bash -s');
145
- return new Promise(function(resolve, reject) {
146
- var child = spawn('ssh', args, { stdio: ['pipe', 'inherit', 'pipe'] });
147
- var err = '';
148
- child.stderr.on('data', function(c) { err += c; process.stderr.write(c); });
149
- child.on('error', function(e) { reject(new Error(e.code === 'ENOENT' ? 'ssh is not installed here' : e.message)); });
150
- child.on('close', function(code) {
151
- if (!code) return resolve();
152
- if (/a password is required|a terminal is required/.test(err)) return reject(new Error('The SSH login needs passwordless sudo on the server'));
153
- if (/Permission denied|Host key verification failed|Could not resolve|Connection refused|timed out/.test(err)) return reject(new Error('Could not sign in to the server over SSH'));
154
- reject(new Error('The install stopped (see above)'));
155
- });
156
- child.stdin.end(script);
157
- });
158
- }
159
-
160
- async function main() {
161
- var given = parseArgs(process.argv.slice(2));
162
- if (given.help) {
163
- console.log('xeplr-monitor-deploy [options]: anything not given is asked; the password is always asked.\n');
164
- Object.keys(OPTIONS).forEach(function(k) { console.log(' --' + k.padEnd(10) + OPTIONS[k] + (DEFAULTS[k] ? ' (default ' + DEFAULTS[k] + ')' : '')); });
165
- console.log(' --yes deploy without asking to confirm');
166
- return;
167
- }
168
- var v = await gather(given);
169
- console.log('\n' + summary(v) + '\n');
170
- if (!given.yes && !/^y/i.test(await ask('Deploy? (y/n)', 'n'))) { console.log(' Nothing done.'); return; }
171
- console.log('');
172
- await deploy(v);
173
- if (v.domain) console.log('\n Open ' + (/^y/i.test(v.certbot) ? 'https://' : 'http://') + v.domain + ' and sign in. Keep port ' + v.port + ' closed in the firewall: nginx is the way in.');
174
- else console.log('\n Point nginx at port ' + v.port + ' (deploy/nginx.conf.example), or deploy again with --domain.');
175
- }
176
-
177
- main().then(function() { if (rl) rl.close(); }).catch(function(err) {
178
- if (rl) rl.close();
179
- console.error('\n ' + err.message);
180
- process.exit(1);
181
- });
package/bin/server.js DELETED
@@ -1,19 +0,0 @@
1
- #!/usr/bin/env node
2
- // The monitor on its own: `xeplr-monitor-server`, run by its systemd service
3
- // (deploy/xeplr-monitor.service). Settings come from the environment; a
4
- // missing required one stops it here, naming it.
5
- var { checkEnv } = require('@xeplr/base-apis');
6
- var monitor = require('../index');
7
-
8
- checkEnv(monitor.requiredEnv, { appName: 'xeplr-monitor' }); // names each missing one and exits
9
-
10
- monitor.start({
11
- dataDir: process.env.MONITOR_DATA_DIR,
12
- secret: process.env.MONITOR_SECRET,
13
- allow: process.env.MONITOR_ALLOW,
14
- sudo: process.env.MONITOR_SUDO,
15
- port: process.env.MONITOR_PORT
16
- }).catch(function(err) {
17
- console.error('[xeplr-monitor] could not start:', err.message);
18
- process.exit(1);
19
- });
package/bin/users.js DELETED
@@ -1,86 +0,0 @@
1
- #!/usr/bin/env node
2
- // WHO CAN SIGN IN — managed on the server only, never from the page.
3
- //
4
- // xeplr-monitor-users list
5
- // xeplr-monitor-users add <email> [--name "Full name"] [--no-code]
6
- // xeplr-monitor-users password <email>
7
- // xeplr-monitor-users code <email> [--off] a new authenticator secret (or none)
8
- // xeplr-monitor-users remove <email>
9
- //
10
- // Reads MONITOR_DATA_DIR. A password is typed, never passed as an argument
11
- // (it would sit in the shell's history and in `ps`); MONITOR_NEW_PASSWORD is
12
- // read instead when set, for a script.
13
- var readline = require('readline');
14
- var store = require('../lib/store');
15
- var users = require('../lib/users');
16
-
17
- var args = process.argv.slice(2);
18
- var cmd = args[0];
19
- var email = args[1];
20
- function flag(name) { return args.indexOf(name) > -1; }
21
- function option(name) { var i = args.indexOf(name); return i > -1 ? args[i + 1] : undefined; }
22
-
23
- function ask(question) {
24
- if (process.env.MONITOR_NEW_PASSWORD) return Promise.resolve(process.env.MONITOR_NEW_PASSWORD);
25
- return new Promise(function(resolve) {
26
- var rl = readline.createInterface({ input: process.stdin, output: process.stdout, terminal: true });
27
- rl.stdoutMuted = true;
28
- rl._writeToOutput = function(s) { if (!rl.stdoutMuted || /\n/.test(s)) rl.output.write(s.replace(/[^\n]/g, '')); };
29
- process.stdout.write(question);
30
- rl.question('', function(answer) { rl.close(); process.stdout.write('\n'); resolve(answer); });
31
- });
32
- }
33
-
34
- async function newPassword() {
35
- var p = await ask('Password (at least ' + users.MIN_PASSWORD + ' characters): ');
36
- if (!process.env.MONITOR_NEW_PASSWORD) {
37
- var again = await ask('Again: ');
38
- if (again !== p) throw new Error('The two passwords are not the same');
39
- }
40
- return p;
41
- }
42
-
43
- function showCode(out) {
44
- if (!out.secret) return console.log('No code asked for when signing in.');
45
- console.log('\nAdd this to an authenticator app (Google Authenticator, 1Password, Authy):');
46
- console.log(' secret: ' + out.secret);
47
- console.log(' or open: ' + out.url + '\n');
48
- }
49
-
50
- async function main() {
51
- store.open(process.env.MONITOR_DATA_DIR);
52
- if (cmd === 'list') {
53
- var list = users.list();
54
- if (!list.length) return console.log('No users yet. Add one: xeplr-monitor-users add <email>');
55
- list.forEach(function(u) { console.log(u.email + (u.name !== u.email ? ' (' + u.name + ')' : '') + (u.twoStep ? ' · code asked' : ' · password only')); });
56
- return;
57
- }
58
- if (!email || ['add', 'password', 'code', 'remove'].indexOf(cmd) < 0) {
59
- console.log('xeplr-monitor-users list | add <email> [--name "…"] [--no-code] | password <email> | code <email> [--off] | remove <email>');
60
- process.exitCode = 1;
61
- return;
62
- }
63
- if (cmd === 'add') {
64
- var out = users.add(email, await newPassword(), { name: option('--name'), twoStep: !flag('--no-code') });
65
- store.audit({ email: out.user.email, action: 'user-added', ok: true, by: 'server' });
66
- console.log('Added ' + out.user.email + '.');
67
- return showCode(out);
68
- }
69
- if (cmd === 'password') {
70
- users.setPassword(email, await newPassword());
71
- store.audit({ email: email, action: 'password-changed', ok: true, by: 'server' });
72
- return console.log('Changed. Every session ' + email + ' had open is signed out.');
73
- }
74
- if (cmd === 'code') {
75
- var c = users.setTwoStep(email, !flag('--off'));
76
- store.audit({ email: email, action: flag('--off') ? 'code-off' : 'code-new', ok: true, by: 'server' });
77
- return showCode(c);
78
- }
79
- if (cmd === 'remove') {
80
- users.remove(email);
81
- store.audit({ email: email, action: 'user-removed', ok: true, by: 'server' });
82
- return console.log('Removed ' + email + '.');
83
- }
84
- }
85
-
86
- main().catch(function(err) { console.error(err.message); process.exit(1); });
@@ -1,16 +0,0 @@
1
- # /etc/xeplr-monitor/monitor.env — readable by root and xeplr-monitor only (chmod 640).
2
-
3
- # Required. Where its users, services and audit log live. Absolute.
4
- MONITOR_DATA_DIR=/var/lib/xeplr-monitor
5
-
6
- # Required. Signs the sign-in cookie; at least 32 characters. Make one with:
7
- # openssl rand -base64 48
8
- MONITOR_SECRET=
9
-
10
- # Required. What it may control, comma-separated; * matches anything.
11
- # sudoers must allow the same (sudoers.example).
12
- MONITOR_ALLOW=xeplr-*
13
-
14
- # Optional.
15
- # MONITOR_PORT=19400 (default 19400)
16
- # MONITOR_SUDO=actions (actions | all | none — see the README)
@@ -1,18 +0,0 @@
1
- # The monitor behind nginx, on its own name (https only). nginx forwards to
2
- # its port; keep that port closed in the firewall, so nginx is the way in.
3
- # xeplr-monitor-deploy --domain writes this site for you.
4
- server {
5
- listen 443 ssl http2;
6
- server_name monitor.example.com;
7
- # ssl_certificate / ssl_certificate_key: as for the other sites (certbot)
8
-
9
- location / {
10
- proxy_pass http://127.0.0.1:19400;
11
- proxy_set_header Host $host;
12
- proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
13
- proxy_set_header X-Forwarded-Proto $scheme;
14
- # A live log is one long answer: no buffering, and kept open.
15
- proxy_buffering off;
16
- proxy_read_timeout 1h;
17
- }
18
- }
@@ -1,13 +0,0 @@
1
- # /etc/sudoers.d/xeplr-monitor — install with:
2
- # sudo install -m 440 sudoers.example /etc/sudoers.d/xeplr-monitor && sudo visudo -c
3
- #
4
- # The monitor's user may start, stop, restart and kill the xeplr-* services,
5
- # without a password, and nothing else: not a shell, not another command.
6
- # Keep the pattern the same as MONITOR_ALLOW. Add a line per extra pattern
7
- # (e.g. postgresql) if MONITOR_ALLOW names one.
8
- #
9
- # Note: in sudoers a * also matches spaces, so this line alone would let
10
- # "systemctl stop xeplr-x sshd" through. The monitor never sends that: it
11
- # passes exactly one name, checked against [A-Za-z0-9@._:-] and MONITOR_ALLOW
12
- # first (lib/systemd.js unitName, lib/services.js).
13
- xeplr-monitor ALL=(root) NOPASSWD: /usr/bin/systemctl start xeplr-*, /usr/bin/systemctl stop xeplr-*, /usr/bin/systemctl restart xeplr-*, /usr/bin/systemctl kill --signal=SIGKILL xeplr-*
@@ -1,26 +0,0 @@
1
- # The monitor itself, as a systemd service. Copy to
2
- # /etc/systemd/system/xeplr-monitor.service, then:
3
- # sudo systemctl daemon-reload && sudo systemctl enable --now xeplr-monitor
4
- #
5
- # It runs as its own user (xeplr-monitor), not root: sudoers (sudoers.example)
6
- # lets that user start/stop/restart/kill the allowed services and nothing
7
- # else; the systemd-journal group lets it read their logs.
8
- [Unit]
9
- Description=Xeplr Monitor (status, control and logs of this server's services)
10
- After=network-online.target
11
-
12
- [Service]
13
- Type=simple
14
- User=xeplr-monitor
15
- Group=xeplr-monitor
16
- SupplementaryGroups=systemd-journal
17
- EnvironmentFile=/etc/xeplr-monitor/monitor.env
18
- ExecStart=/usr/bin/env xeplr-monitor-server
19
- Restart=always
20
- RestartSec=3
21
- # sudo needs to gain privileges, so NoNewPrivileges stays off; sudoers is the limit.
22
- ProtectHome=true
23
- PrivateTmp=true
24
-
25
- [Install]
26
- WantedBy=multi-user.target
package/index.js DELETED
@@ -1,89 +0,0 @@
1
- // @xeplr/monitor — see and control a server's services: status, start, stop,
2
- // restart, kill, and their logs, live. Its own sign-in, its own files, no
3
- // database: it is what you open when something else is down.
4
- //
5
- // Built on @xeplr/base-apis createApp (the gate, cookies, request lines through
6
- // @xeplr/logs to stdout, so to the journal; 404 and errors) and @xeplr/utils (authenticator codes, the
7
- // wrong-try lockout). Neither needs Redis or a database here.
8
- //
9
- // init(config) open the store, the secret, the allowed services
10
- // router() the API (lib/router.js), for a host to mount behind session.gate
11
- // start(config) init, then serve the API at /api and the page at /
12
- var path = require('path');
13
- var fs = require('fs');
14
- var express = require('express');
15
- var { createApp } = require('@xeplr/base-apis');
16
- var store = require('./lib/store');
17
- var session = require('./lib/session');
18
- var services = require('./lib/services');
19
- var systemd = require('./lib/systemd');
20
- var { createRouter } = require('./lib/router');
21
-
22
- // What a host must set. Spread into its env.required.js so a missing one
23
- // fails at startup, naming it, rather than booting a monitor nobody can use.
24
- var requiredEnv = ['MONITOR_DATA_DIR', 'MONITOR_SECRET', 'MONITOR_ALLOW'];
25
-
26
- /**
27
- * @param config { dataDir, secret, allow, sudo? }
28
- * dataDir absolute folder for users.json, services.json, audit.ndjson, logs/ (MONITOR_DATA_DIR)
29
- * secret at least 32 characters; signs the sign-in cookie (MONITOR_SECRET)
30
- * allow the services it may control: ["xeplr-*"] or "xeplr-*,postgresql" (MONITOR_ALLOW)
31
- * sudo 'actions' (default) | 'all' | 'none' (MONITOR_SUDO)
32
- */
33
- function init(config) {
34
- config = config || {};
35
- store.open(config.dataDir);
36
- session.setSecret(config.secret);
37
- services.setAllowed(config.allow);
38
- systemd.configure({ sudo: config.sudo || 'actions' });
39
- }
40
-
41
- function router() { return createRouter(); }
42
-
43
- function headers(req, res, next) {
44
- res.setHeader('X-Frame-Options', 'DENY');
45
- res.setHeader('X-Content-Type-Options', 'nosniff');
46
- res.setHeader('Referrer-Policy', 'no-referrer');
47
- res.setHeader('Content-Security-Policy', "default-src 'self'; style-src 'self' 'unsafe-inline'; img-src 'self' data:; frame-ancestors 'none'");
48
- next();
49
- }
50
-
51
- /** The page (built into public/), with every other path answered by index.html. */
52
- function pageRouter(dir) {
53
- var r = express.Router();
54
- if (!fs.existsSync(path.join(dir, 'index.html'))) return r;
55
- r.use(express.static(dir, { index: false, maxAge: '1h' }));
56
- r.get(/^(?!\/api\/).*/, function(req, res) { res.setHeader('Cache-Control', 'no-cache'); res.sendFile(path.join(dir, 'index.html')); });
57
- return r;
58
- }
59
-
60
- /**
61
- * Serve it: the API at /api, the page everywhere else. → the http server,
62
- * once listening on its port. nginx is its front door, as for every xeplr
63
- * service.
64
- */
65
- function start(config) {
66
- config = config || {};
67
- init(config);
68
- // 0 is a port too (any free one); only a missing value takes the default.
69
- var port = config.port === undefined || config.port === null || config.port === '' ? 19400 : Number(config.port);
70
- var built = createApp(port, 'xeplr-monitor', {
71
- // Its own sign-in: it must work when @xeplr/auth is down. The headers go in
72
- // front of it, so a refused request carries them too (createApp's
73
- // `middleware` runs only after the gate).
74
- auth: { middleware: function(req, res, next) { headers(req, res, function() { session.gate(req, res, next); }); } },
75
- corsOptions: { origin: false }, // same-site page only
76
- log: config.log === false ? false : { logDir: path.join(config.dataDir, 'logs') },
77
- routes: { '/api': router(), '/': pageRouter(config.publicDir || path.join(__dirname, 'public')) }
78
- });
79
- // Behind nginx on the same machine: req.secure and req.ip come from it.
80
- built.app.set('trust proxy', 'loopback');
81
- built.app.disable('x-powered-by');
82
- return new Promise(function(resolve, reject) {
83
- if (built.server.listening) return resolve(built.server);
84
- built.server.once('listening', function() { resolve(built.server); });
85
- built.server.once('error', reject);
86
- });
87
- }
88
-
89
- module.exports = { init: init, router: router, start: start, requiredEnv: requiredEnv, gate: session.gate };