@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
@@ -0,0 +1,183 @@
1
+ #!/usr/bin/env node
2
+ // INSTALL OR UPDATE XEPLR-MONITOR ON THIS SERVER — run on the server itself,
3
+ // signed in there the usual way. There is no remote deploy: the installer
4
+ // installs the machine it runs on, from the copy it runs from (what npx
5
+ // fetched from npm, or a checkout), and fetches nothing a second time.
6
+ //
7
+ // npx -y @xeplr/monitor install here, asking what it needs
8
+ // npx -y @xeplr/monitor@latest --update a new version, nothing asked
9
+ // node deploy/deploy.js [--update] the same, from a checkout
10
+ //
11
+ // It asks for what it needs as it goes and stores nothing but the app's own
12
+ // settings file. Secrets are made on the server; passwords are typed (hidden)
13
+ // and go only to deploy/install.sh, on its input — never arguments, which
14
+ // would sit in the shell's history and in `ps`. The questions are
15
+ // @xeplr/cli's (the same prompt the app was made with).
16
+ //
17
+ // install.sh runs as root: run this as root, or sudo asks its password once,
18
+ // first — before any question, so the install never stops for it.
19
+ var fs = require('fs');
20
+ var os = require('os');
21
+ var path = require('path');
22
+ var { spawn, spawnSync } = require('child_process');
23
+ var { createSession } = require('@xeplr/cli/lib/prompt');
24
+
25
+ var OPTIONS = {
26
+ ports: 'Its ports: the first of three (sign-in is +1, the API +2)?',
27
+ 'db-host': 'Postgres host (blank: keep the login set before, or ask on the setup page)?',
28
+ 'db-port': 'Postgres port?',
29
+ 'db-user': 'Postgres user (one that may create databases)?',
30
+ 'redis-host': 'Redis host?',
31
+ 'redis-port': 'Redis port?',
32
+ 'admin-email': 'Super Admin email, to sign in with?',
33
+ domain: 'Its own web address, e.g. monitor.xeplr.com (for nginx and the links in its emails)?'
34
+ };
35
+ var DEFAULTS = { ports: '19400', 'db-port': '5432', 'db-user': 'postgres', 'redis-host': '127.0.0.1', 'redis-port': '6379' };
36
+
37
+ /** This installer's own folder: the whole app, as git or npx put it here. */
38
+ var SELF = path.resolve(__dirname, '..');
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] + ' (--help lists them)');
45
+ if (m[1] === 'help' || m[1] === 'yes' || m[1] === 'no-certbot' || m[1] === 'update') { out[m[1]] = true; continue; }
46
+ if (m[1] === 'certbot') { out.certbot = m[2] !== undefined ? m[2] : 'y'; continue; }
47
+ if (OPTIONS[m[1]] === undefined) throw new Error('Unknown option --' + m[1] + ' (--help lists them)');
48
+ out[m[1]] = m[2] !== undefined ? m[2] : argv[++i];
49
+ }
50
+ return out;
51
+ }
52
+
53
+ // The Super Admin password is substituted into SQL by the sign-in migrations,
54
+ // so the characters that would break that are refused — @xeplr/cli's rule.
55
+ function adminPasswordProblem(v) {
56
+ if (v.length < 8) return 'At least 8 characters.';
57
+ if (/["'\s$#]/.test(v)) return 'No quotes, spaces, $ or # — it is substituted into SQL.';
58
+ return null;
59
+ }
60
+
61
+ /** A value as one bash word: 'it'\''s'. */
62
+ function quote(v) { return "'" + String(v).replace(/'/g, "'\\''") + "'"; }
63
+
64
+ async function gather(given, session) {
65
+ var v = Object.assign({}, given);
66
+ var askFor = async function(k, validate) {
67
+ if (v[k] === undefined) v[k] = await session.ask(' ' + OPTIONS[k], { default: DEFAULTS[k], validate: validate });
68
+ };
69
+ session.say('\n Install xeplr-monitor on this server (' + os.hostname() + '). Enter takes the value in brackets.\n');
70
+ await askFor('ports', function(x) { return /^\d{4,5}$/.test(x) ? true : 'A port number.'; });
71
+
72
+ session.say('\n The database and Redis it uses (on this server, or reachable from it).');
73
+ await askFor('db-host');
74
+ if (v['db-host']) {
75
+ await askFor('db-port', function(x) { return /^\d+$/.test(x) ? true : 'A number.'; });
76
+ await askFor('db-user');
77
+ v.dbPassword = process.env.XM_DB_PASSWORD !== undefined ? process.env.XM_DB_PASSWORD : await session.askSecret(' Postgres password?');
78
+ }
79
+ await askFor('redis-host');
80
+ await askFor('redis-port', function(x) { return /^\d+$/.test(x) ? true : 'A number.'; });
81
+ v.redisPassword = process.env.XM_REDIS_PASSWORD !== undefined ? process.env.XM_REDIS_PASSWORD : await session.askSecret(' Redis password (blank: none, or keep)?');
82
+
83
+ session.say('\n Who signs in first. More people are added in the app (Admin).');
84
+ await askFor('admin-email', function(x) { return /^[^@\s]+@[^@\s]+\.[^@\s]+$/.test(x) ? true : 'That is not an email address.'; });
85
+ v.adminPassword = process.env.XM_ADMIN_PASSWORD;
86
+ if (v.adminPassword === undefined) {
87
+ for (;;) {
88
+ v.adminPassword = await session.askSecret(' Super Admin password (blank: keep the one set before)?');
89
+ var problem = v.adminPassword ? adminPasswordProblem(v.adminPassword) : null;
90
+ if (problem) { session.say(' ' + problem); continue; }
91
+ if (v.adminPassword && (await session.askSecret(' Again?')) !== v.adminPassword) { session.say(' The two are not the same.'); continue; }
92
+ break;
93
+ }
94
+ } else if (v.adminPassword && adminPasswordProblem(v.adminPassword)) throw new Error('XM_ADMIN_PASSWORD: ' + adminPasswordProblem(v.adminPassword));
95
+
96
+ await askFor('domain', function(x) { return !x || /^[A-Za-z0-9.-]+$/.test(x) ? true : 'A web address like monitor.xeplr.com.'; });
97
+ if (!v.domain) session.say(' No web address: on a first install the monitor opens its setup page and asks for one before anyone can sign in.');
98
+ if (v.domain && v.certbot === undefined && !v['no-certbot']) v.certbot = (await session.confirm(' Get an https certificate for it with certbot now?', true)) ? 'y' : 'n';
99
+ return v;
100
+ }
101
+
102
+ function version() { return require('../package.json').version; }
103
+
104
+ function summary(v) {
105
+ var p = Number(v.ports);
106
+ return [
107
+ ' Server this one (' + os.hostname() + ')',
108
+ ' Installs xeplr-monitor ' + version() + ' from ' + SELF,
109
+ ' Runs sign-in on ' + (p + 1) + ', the API on ' + (p + 2) + ' (xeplr-monitor-auth, xeplr-monitor-api)',
110
+ ' Postgres ' + (v['db-host'] ? v['db-user'] + '@' + v['db-host'] + ':' + v['db-port'] + ' (password set)' : 'the login set before, or the setup page'),
111
+ ' Redis ' + v['redis-host'] + ':' + v['redis-port'],
112
+ ' nginx ' + (v.domain ? v.domain + (/^y/i.test(v.certbot || '') ? ', https (certbot)' : ', http only') : 'left alone'),
113
+ ' Admin ' + v['admin-email'] + (v.adminPassword ? ' (password set)' : ' (password kept)')
114
+ ].join('\n');
115
+ }
116
+
117
+ function isRoot() { return typeof process.getuid === 'function' && process.getuid() === 0; }
118
+
119
+ /** Root for the install, asked once and first: sudo reads the terminal itself, before the questions take stdin. */
120
+ function sudoFirst() {
121
+ if (isRoot()) return;
122
+ var r = spawnSync('sudo', ['-v'], { stdio: 'inherit' });
123
+ if (r.error && r.error.code === 'ENOENT') throw new Error('sudo is not installed: run this as root');
124
+ if (r.status !== 0) throw new Error('The install needs root: sudo was refused');
125
+ }
126
+
127
+ /** install.sh as root, with the values above it, on bash's input (never arguments). */
128
+ function install(values) {
129
+ var input = Object.keys(values).map(function(k) { return k + '=' + quote(values[k]); }).join('\n') + '\n' +
130
+ fs.readFileSync(path.join(__dirname, 'install.sh'), 'utf8');
131
+ var cmd = isRoot() ? 'bash' : 'sudo';
132
+ var args = isRoot() ? ['-s'] : ['-n', 'bash', '-s'];
133
+ return new Promise(function(resolve, reject) {
134
+ var child = spawn(cmd, args, { stdio: ['pipe', 'inherit', 'inherit'] });
135
+ child.on('error', function(e) { reject(new Error(e.message)); });
136
+ child.on('close', function(code) { code ? reject(new Error('The install stopped (see above)')) : resolve(); });
137
+ child.stdin.end(input);
138
+ });
139
+ }
140
+
141
+ /** The answers as install.sh's XM_* values. */
142
+ function valuesOf(v) {
143
+ return {
144
+ XM_SOURCE_DIR: SELF, XM_PORT_BASE: v.ports,
145
+ XM_DB_HOST: v['db-host'] || '', XM_DB_PORT: v['db-port'] || '', XM_DB_USER: v['db-user'] || '', XM_DB_PASSWORD: v.dbPassword || '',
146
+ XM_REDIS_HOST: v['redis-host'], XM_REDIS_PORT: v['redis-port'], XM_REDIS_PASSWORD: v.redisPassword || '',
147
+ XM_ADMIN_EMAIL: v['admin-email'], XM_ADMIN_PASSWORD: v.adminPassword || '',
148
+ XM_DOMAIN: v.domain || '', XM_CERTBOT: v.domain && /^y/i.test(v.certbot || '') ? '1' : '0'
149
+ };
150
+ }
151
+
152
+ async function main() {
153
+ var given = parseArgs(process.argv.slice(2));
154
+ if (given.help) {
155
+ console.log('xeplr-monitor install [options] — run on the server it installs. Anything not given is asked; passwords are always\nasked (or XM_DB_PASSWORD, XM_REDIS_PASSWORD, XM_ADMIN_PASSWORD in the environment, for a script).\n');
156
+ Object.keys(OPTIONS).forEach(function(k) { console.log(' --' + k.padEnd(12) + OPTIONS[k].replace(/\?$/, '') + (DEFAULTS[k] ? ' (default ' + DEFAULTS[k] + ')' : '')); });
157
+ console.log(' --certbot / --no-certbot, --yes (install without asking to confirm)');
158
+ console.log(' --update install this copy as the new version and restart; asks nothing');
159
+ return;
160
+ }
161
+ if (process.platform !== 'linux') throw new Error('Run this on the server it installs: the monitor runs on Linux with systemd');
162
+ sudoFirst();
163
+ if (given.update) {
164
+ console.log('\n Updating this server to xeplr-monitor ' + version() + ' from ' + SELF + '. Everything else stays as it is.\n');
165
+ await install({ XM_UPDATE: '1', XM_SOURCE_DIR: SELF });
166
+ console.log('\n Updated.');
167
+ return;
168
+ }
169
+ var session = createSession();
170
+ try {
171
+ var v = await gather(given, session);
172
+ session.say('\n' + summary(v) + '\n');
173
+ if (!given.yes && !(await session.confirm(' Install?', false))) { session.say(' Nothing done.'); return; }
174
+ session.say('');
175
+ await install(valuesOf(v));
176
+ var site = v.domain ? (/^y/i.test(v.certbot || '') ? 'https://' : 'http://') + v.domain : null;
177
+ session.say('\n ' + (site ? 'Open ' + site + ' and sign in as ' + v['admin-email'] + '.' : 'Point nginx at it (README), or install again with --domain.') + ' Keep its ports closed in the firewall: nginx is the way in.');
178
+ } finally {
179
+ session.close();
180
+ }
181
+ }
182
+
183
+ main().catch(function(err) { console.error('\n ' + err.message); process.exit(1); });
@@ -0,0 +1,240 @@
1
+ # XEPLR-MONITOR, INSTALLED OR UPDATED ON THIS SERVER — run as root by
2
+ # deploy/deploy.js on the server itself: it puts the XM_* values above this
3
+ # file and sends both on bash's input, so no value is ever a file or a
4
+ # command-line argument. Safe to run again: it installs a new release beside the old
5
+ # one, keeps the settings (and so every secret and sign-in), and switches over.
6
+ #
7
+ # XM_UPDATE 1: only install this version and restart — every other value
8
+ # is read from the settings the first deploy wrote; nginx and its
9
+ # certificate are left alone
10
+ # XM_SOURCE_DIR the app's source, a folder on this server: the copy the
11
+ # installer itself runs from (what npx fetched, or a checkout)
12
+ # XM_PORT_BASE ui slot; the sign-in service is +1, the API +2 (19400 → 19401, 19402)
13
+ # XM_DB_HOST, XM_DB_PORT, XM_DB_USER, XM_DB_PASSWORD
14
+ # the Postgres it uses (a user that may create databases);
15
+ # all empty keeps the connection a previous deploy wrote — or,
16
+ # on a first deploy, leaves it to the app's setup page
17
+ # XM_REDIS_HOST, XM_REDIS_PORT, XM_REDIS_PASSWORD
18
+ # XM_ADMIN_EMAIL, XM_ADMIN_PASSWORD
19
+ # the Super Admin; an empty password keeps the one written before
20
+ # XM_DOMAIN its web address for nginx; empty leaves nginx alone
21
+ # XM_CERTBOT 1 to get an https certificate for XM_DOMAIN with certbot
22
+ set -euo pipefail
23
+
24
+ say() { printf ' %s\n' "$*"; }
25
+ export NPM_CONFIG_UPDATE_NOTIFIER=false NPM_CONFIG_FUND=false
26
+ stop() { printf '\n Stopped: %s\n' "$*" >&2; exit 1; }
27
+
28
+ APP=/opt/xeplr-monitor
29
+ SHARED=$APP/shared
30
+ ENV_FILE=$SHARED/production.env
31
+ VAR=/var/lib/xeplr-monitor
32
+ USER_NAME=xeplr-monitor
33
+
34
+ # An update asks nothing: what the first deploy was told is in its settings.
35
+ if [ "${XM_UPDATE:-0}" = 1 ]; then
36
+ [ -s "$ENV_FILE" ] || stop "xeplr-monitor is not installed here yet: the first deploy needs the full questions (run it without --update)"
37
+ setting_of() { sed -n "s/^$1=//p" "$ENV_FILE" | tail -1; }
38
+ XM_PORT_BASE=$(( $(setting_of AUTH_PORT) - 1 ))
39
+ XM_ADMIN_EMAIL=$(setting_of AUTH_SUPER_ADMIN_EMAIL)
40
+ XM_REDIS_HOST=$(setting_of REDIS_HOST)
41
+ XM_REDIS_PORT=$(setting_of REDIS_PORT)
42
+ # Empty: settings.cjs keeps the database login, the passwords and the
43
+ # public address it already has; the nginx step below is skipped.
44
+ XM_DB_HOST= XM_DB_PORT= XM_DB_USER= XM_DB_PASSWORD= XM_REDIS_PASSWORD= XM_ADMIN_PASSWORD= XM_DOMAIN= XM_CERTBOT=0
45
+ [ -n "$XM_ADMIN_EMAIL" ] || [ -s "$SHARED/SETUP_CODE" ] || stop "the settings in $ENV_FILE are incomplete: run the full deploy (without --update)"
46
+ say "Updating: the settings, nginx and its certificate stay as they are"
47
+ fi
48
+ AUTH_PORT=$((XM_PORT_BASE + 1))
49
+ API_PORT=$((XM_PORT_BASE + 2))
50
+
51
+ # ── what the server must already have ────────────────────────────────────
52
+ command -v systemctl >/dev/null || stop "systemd is not here: the monitor controls systemd services"
53
+ NODE=$(command -v node || true)
54
+ [ -n "$NODE" ] || stop "Node.js is not installed (20 or newer is needed)"
55
+ [ "$("$NODE" -p 'process.versions.node.split(".")[0]')" -ge 20 ] || stop "Node.js $("$NODE" -v) is too old: 20 or newer is needed"
56
+ command -v npm >/dev/null || stop "npm is not installed"
57
+ command -v tar >/dev/null || stop "tar is not installed"
58
+ SYSTEMCTL=$(command -v systemctl)
59
+
60
+ # ── the dump programs the backup jobs run (pg_dump, mysqldump) ───────────
61
+ # Installed when missing, from the server's own packages. A failure here does
62
+ # not stop the deploy: the backups would fail and say which program is missing.
63
+ if ! command -v pg_dump >/dev/null || ! command -v mysqldump >/dev/null; then
64
+ if command -v apt-get >/dev/null; then
65
+ say "Installing the database dump programs (postgresql-client, default-mysql-client)"
66
+ DEBIAN_FRONTEND=noninteractive apt-get install -y -qq postgresql-client default-mysql-client >/dev/null 2>&1 \
67
+ || say " could not install them: backups will fail until pg_dump and mysqldump are installed"
68
+ else
69
+ say " pg_dump / mysqldump are missing and this is not apt: install them for the backups"
70
+ fi
71
+ fi
72
+
73
+ # ── its own user, which reads the journal ────────────────────────────────
74
+ id "$USER_NAME" >/dev/null 2>&1 || { useradd -r -m -d "$VAR" -s /usr/sbin/nologin "$USER_NAME"; say "User $USER_NAME made"; }
75
+ usermod -aG systemd-journal "$USER_NAME"
76
+ mkdir -p "$VAR/logs" "$VAR/data" "$SHARED" "$APP/releases"
77
+ chown -R "$USER_NAME:$USER_NAME" "$VAR" && chmod 750 "$VAR"
78
+
79
+ # ── this release: the source, its packages, the page built ───────────────
80
+ REL=$APP/releases/$(date -u +%Y%m%d%H%M%S)
81
+ mkdir -p "$REL"
82
+ # The copy the installer runs from; nothing is fetched.
83
+ [ -n "${XM_SOURCE_DIR:-}" ] && [ -d "$XM_SOURCE_DIR" ] || stop "no source folder to install from (run deploy/deploy.js)"
84
+ tar -C "$XM_SOURCE_DIR" --exclude=node_modules --exclude=.git -cf - . | tar -xf - -C "$REL" \
85
+ || stop "could not copy the source from $XM_SOURCE_DIR"
86
+ say "Source: $XM_SOURCE_DIR"
87
+ [ -f "$REL/api/bin/www" ] && [ -f "$REL/ui/package.json" ] || stop "that source is not xeplr-monitor (no api/bin/www or ui/)"
88
+ say "Installing packages (api, ui)"
89
+ (cd "$REL/api" && npm ci --no-fund --no-audit --no-update-notifier --loglevel=error >/dev/null)
90
+ (cd "$REL/ui" && npm ci --no-fund --no-audit --no-update-notifier --loglevel=error >/dev/null && npx vite build --logLevel error >/dev/null)
91
+ [ -f "$REL/ui/dist/index.html" ] || stop "the page did not build"
92
+ chown -R "$USER_NAME:$USER_NAME" "$REL"
93
+
94
+ # ── settings: written once, kept after; secrets made here, never asked ───
95
+ # Through the app's own schema (api/setup.schema.js, @xeplr/setup): what is
96
+ # missing after this is asked on the setup page, never a failed deploy.
97
+ touch "$ENV_FILE"
98
+ # The answers go to this one process only, not to every command after it.
99
+ SETUP_NEEDED=0
100
+ env XM_ENV_FILE="$ENV_FILE" XM_AUTH_PORT="$AUTH_PORT" XM_API_PORT="$API_PORT" XM_VAR="$VAR" \
101
+ XM_DOMAIN="$XM_DOMAIN" XM_CERTBOT="$XM_CERTBOT" \
102
+ XM_DB_HOST="$XM_DB_HOST" XM_DB_PORT="$XM_DB_PORT" XM_DB_USER="$XM_DB_USER" XM_DB_PASSWORD="$XM_DB_PASSWORD" \
103
+ XM_REDIS_HOST="$XM_REDIS_HOST" XM_REDIS_PORT="$XM_REDIS_PORT" XM_REDIS_PASSWORD="$XM_REDIS_PASSWORD" \
104
+ XM_ADMIN_EMAIL="$XM_ADMIN_EMAIL" XM_ADMIN_PASSWORD="$XM_ADMIN_PASSWORD" \
105
+ "$NODE" "$REL/deploy/settings.cjs" "$REL/api" || { [ $? -eq 3 ] && SETUP_NEEDED=1; } || stop "the settings could not be written"
106
+ # THE APP OWNS ITS SETTINGS: the setup page and App settings (Super Admin)
107
+ # rewrite this file — atomically, a temp file beside it renamed over it — so
108
+ # the service user owns the file and its folder. Nobody else reads either.
109
+ chown "$USER_NAME:$USER_NAME" "$SHARED" "$ENV_FILE" && chmod 700 "$SHARED" && chmod 600 "$ENV_FILE"
110
+ [ ! -f "$SHARED/FIRST_LOGIN" ] || chown "$USER_NAME:$USER_NAME" "$SHARED/FIRST_LOGIN"
111
+
112
+ # ── the databases, the sign-in tables and the permissions ────────────────
113
+ run_api() { (cd "$REL/api" && sudo -u "$USER_NAME" env NODE_ENV=production node_modules/.bin/dotenv -e "$ENV_FILE" -- "$@"); }
114
+ if [ "$SETUP_NEEDED" = 1 ]; then
115
+ say "Databases: after the setup page (the API and the sign-in service make theirs when they start)"
116
+ else
117
+ say "Databases: creating any that are missing, then the sign-in migrations"
118
+ run_api node_modules/.bin/xeplr-migrate create-db --connectionName auth --connection-env AUTH_DB_CONNECTION_INFO_ENCRYPTED --db-env AUTH_DB_NAME >/dev/null \
119
+ || stop "could not reach or create the sign-in database (is Postgres running, and may that user create databases?)"
120
+ run_api node_modules/.bin/xeplr-migrate create-db --connectionName api --connection-env XEPLR_MONITOR_CONNECTION --db-env DB_API >/dev/null \
121
+ || stop "could not create the app's database"
122
+ run_api node_modules/.bin/xeplr-auth-migrate up --connection-env AUTH_DB_CONNECTION_INFO_ENCRYPTED >/dev/null \
123
+ || stop "the sign-in migrations failed"
124
+ fi
125
+
126
+ # ── the one command sudoers allows: deploy/control.sh
127
+ # It checks the action and the name itself, so sudoers names the command
128
+ # alone — no wildcard, which newer sudo (sudo-rs) refuses anyway.
129
+ CONTROL=/usr/local/libexec/xeplr-monitor-control
130
+ mkdir -p /usr/local/libexec
131
+ sed -e "s|__SYSTEMCTL__|$SYSTEMCTL|" "$REL/deploy/control.sh" > "$CONTROL.new"
132
+ chown root:root "$CONTROL.new" && chmod 755 "$CONTROL.new" && mv -f "$CONTROL.new" "$CONTROL"
133
+ SUDOERS_TMP=$(mktemp)
134
+ {
135
+ echo "# Made by xeplr-monitor's deploy. Changed by the next deploy."
136
+ echo "# $CONTROL checks the action and the service name; roles in the app decide who may."
137
+ echo "$USER_NAME ALL=(root) NOPASSWD: $CONTROL"
138
+ } > "$SUDOERS_TMP"
139
+ visudo -cqf "$SUDOERS_TMP" || { rm -f "$SUDOERS_TMP"; stop "visudo refused the sudoers line for $CONTROL"; }
140
+ install -m 440 "$SUDOERS_TMP" /etc/sudoers.d/xeplr-monitor && rm -f "$SUDOERS_TMP"
141
+ sudo -u "$USER_NAME" "$SYSTEMCTL" show -p Version >/dev/null 2>&1 \
142
+ || stop "$USER_NAME cannot ask systemd (no D-Bus?). Install and start dbus, then deploy again"
143
+
144
+ # ── switch to this release, and the two services ─────────────────────────
145
+ ln -sfn "$REL" "$APP/current"
146
+ unit() { # name, description, command (run in current/api), extra lines
147
+ cat > "/etc/systemd/system/$1.service" <<UNIT
148
+ # Made by xeplr-monitor's deploy. Changed by the next deploy.
149
+ [Unit]
150
+ Description=$2
151
+ After=network-online.target postgresql.service redis-server.service
152
+
153
+ [Service]
154
+ Type=simple
155
+ User=$USER_NAME
156
+ Group=$USER_NAME
157
+ WorkingDirectory=$APP/current/api
158
+ EnvironmentFile=$ENV_FILE
159
+ ExecStart=$3
160
+ Restart=always
161
+ RestartSec=3
162
+ PrivateTmp=true
163
+ $4
164
+
165
+ [Install]
166
+ WantedBy=multi-user.target
167
+ UNIT
168
+ }
169
+ # Restart=always is also how settings take effect: the setup page and App
170
+ # settings exit 75 after writing $ENV_FILE, and systemd starts them again.
171
+ unit xeplr-monitor-auth "xeplr-monitor: sign-in (@xeplr/auth)" "$NODE $APP/current/api/bin/auth.js" ""
172
+ # The API controls services: the journal group reads their logs; sudo needs
173
+ # to gain privileges, so NoNewPrivileges stays off — sudoers is the limit.
174
+ unit xeplr-monitor-api "xeplr-monitor: the API (services, logs, start/stop)" "$NODE $APP/current/api/bin/www" "SupplementaryGroups=systemd-journal"
175
+ systemctl daemon-reload
176
+ systemctl enable xeplr-monitor-auth xeplr-monitor-api >/dev/null 2>&1
177
+ systemctl restart xeplr-monitor-auth xeplr-monitor-api
178
+
179
+ # ── check both answer ─────────────────────────────────────────────────────
180
+ answers() { "$NODE" -e 'fetch(process.argv[1]).then(r => console.log(r.status)).catch(() => console.log(""))' "$1"; }
181
+ CHECK="auth api"; [ "$SETUP_NEEDED" = 1 ] && CHECK="api" # sign-in waits for setup, listening on nothing
182
+ for name in $CHECK; do
183
+ url="http://127.0.0.1:$AUTH_PORT/auth/api/login"; [ "$name" = api ] && url="http://127.0.0.1:$API_PORT/health"
184
+ got=""
185
+ for _ in $(seq 1 60); do got=$(answers "$url"); [ -n "$got" ] && [ "$got" != "502" ] && break; sleep 1; done
186
+ [ -n "$got" ] || { journalctl -u "xeplr-monitor-$name" -n 25 --no-pager >&2; stop "xeplr-monitor-$name did not answer (its log is above)"; }
187
+ done
188
+ if [ "$SETUP_NEEDED" = 1 ]; then
189
+ say "SETUP PAGE: the API on $API_PORT asks for the rest — open https://<domain>/setup (or http://127.0.0.1:$API_PORT/setup"
190
+ say " over an SSH tunnel); the one-time code is in $SHARED/SETUP_CODE. Sign-in starts once it is saved."
191
+ else
192
+ say "Running: sign-in on $AUTH_PORT, the API on $API_PORT"
193
+ fi
194
+
195
+ # Old releases: the newest three are kept, to switch back to by hand.
196
+ ls -1dt "$APP"/releases/*/ | tail -n +4 | xargs -r rm -rf
197
+
198
+ # ── nginx, when asked ────────────────────────────────────────────────────
199
+ if [ -n "$XM_DOMAIN" ]; then
200
+ command -v nginx >/dev/null || stop "nginx is not installed, so $XM_DOMAIN was not set up (the monitor itself is running)"
201
+ if [ -d /etc/nginx/sites-available ]; then SITE=/etc/nginx/sites-available/xeplr-monitor; LINK=/etc/nginx/sites-enabled/xeplr-monitor
202
+ else SITE=/etc/nginx/conf.d/xeplr-monitor.conf; LINK=""; fi
203
+ # The page from ui/dist; /auth/api to the sign-in service; /api, /health and
204
+ # /whoami to the API. certbot adds https to this file; a re-deploy writes it
205
+ # afresh and runs certbot again.
206
+ cat > "$SITE" <<NGINX
207
+ # Made by xeplr-monitor's deploy. Changed by the next deploy.
208
+ server {
209
+ listen 80;
210
+ server_name $XM_DOMAIN;
211
+ root $APP/current/ui/dist;
212
+
213
+ location /auth/api/ { proxy_pass http://127.0.0.1:$AUTH_PORT; proxy_set_header Host \$host; proxy_set_header X-Forwarded-For \$proxy_add_x_forwarded_for; proxy_set_header X-Forwarded-Proto \$scheme; }
214
+ location /api/ {
215
+ proxy_pass http://127.0.0.1:$API_PORT;
216
+ proxy_set_header Host \$host;
217
+ proxy_set_header X-Forwarded-For \$proxy_add_x_forwarded_for;
218
+ proxy_set_header X-Forwarded-Proto \$scheme;
219
+ # A live log is one long answer: no buffering, and kept open.
220
+ proxy_buffering off;
221
+ proxy_read_timeout 1h;
222
+ }
223
+ location = /health { proxy_pass http://127.0.0.1:$API_PORT; }
224
+ location = /whoami { proxy_pass http://127.0.0.1:$API_PORT; }
225
+ # The setup page and /setup/status (asked by App settings while the app restarts).
226
+ location /setup { proxy_pass http://127.0.0.1:$API_PORT; proxy_set_header Host \$host; proxy_set_header X-Forwarded-Proto \$scheme; }
227
+ location / { try_files \$uri /index.html; }
228
+ }
229
+ NGINX
230
+ [ -z "$LINK" ] || ln -sf "$SITE" "$LINK"
231
+ nginx -t -q || stop "nginx refused the new site ($SITE)"
232
+ systemctl reload nginx
233
+ say "nginx: $XM_DOMAIN"
234
+ if [ "$XM_CERTBOT" = "1" ]; then
235
+ command -v certbot >/dev/null || stop "certbot is not installed, so $XM_DOMAIN has no https yet"
236
+ certbot --nginx -d "$XM_DOMAIN" --non-interactive --agree-tos --redirect -m "$XM_ADMIN_EMAIL" >/dev/null
237
+ say "https: certificate for $XM_DOMAIN"
238
+ fi
239
+ fi
240
+ say "Done"
@@ -0,0 +1,93 @@
1
+ // THE SERVER'S production.env — written by deploy/install.sh, on the server,
2
+ // through the same schema and prepare() as the app's own setup page
3
+ // (api/setup.schema.js, @xeplr/setup).
4
+ //
5
+ // node deploy/settings.cjs <release>/api (values from XM_* in the environment)
6
+ // exit 0: complete · exit 3: the setup page must ask for the rest · else: failed
7
+ //
8
+ // The deploy's answers are written in (a re-deploy with a changed answer
9
+ // changes it); then prepare() fills what can be made or worked out and never
10
+ // overwrites a set value:
11
+ // ENCRYPTION_KEY, AUTH_JWT_SECRET made the first time, kept after (remaking
12
+ // them would sign everyone out and make the stored database
13
+ // login unreadable)
14
+ // the database login encrypted from DB_HOST / DB_PORT / DB_USER /
15
+ // DB_PASSWORD when this deploy gives them (the password is
16
+ // then cleared from the file); otherwise kept
17
+ // the Super Admin password this deploy's, else the one written before, else
18
+ // generated into FIRST_LOGIN beside the file (never printed)
19
+ // Anything still missing (a first deploy with no database login) is not an
20
+ // error: the API serves its setup page and asks for it (exit 3).
21
+ var fs = require('fs');
22
+ var path = require('path');
23
+
24
+ var apiDir = path.resolve(process.argv[2]);
25
+ var file = process.env.XM_ENV_FILE;
26
+ // From the release's own packages: the same @xeplr/setup the app runs.
27
+ var setup = require(path.join(apiDir, 'node_modules', '@xeplr', 'setup'));
28
+ var schema = require(path.join(apiDir, 'setup.schema.js')).config(apiDir, { NODE_ENV: 'production' }).schema;
29
+
30
+ function need(name) {
31
+ var v = process.env[name];
32
+ if (v === undefined || v === '') throw new Error(name + ' is empty');
33
+ return v;
34
+ }
35
+
36
+ async function main() {
37
+ if (!file) throw new Error('XM_ENV_FILE is empty');
38
+ if (!fs.existsSync(file)) fs.writeFileSync(file, '', { mode: 0o600 });
39
+ var was = setup.envFile.readEnv(file).values;
40
+ var e = process.env;
41
+ var site = e.XM_DOMAIN ? (e.XM_CERTBOT === '1' ? 'https://' : 'http://') + e.XM_DOMAIN : null;
42
+ var values = {
43
+ NODE_ENV: 'production',
44
+ LOG_DIR: path.join(need('XM_VAR'), 'logs'),
45
+ XEPLR_MONITOR_PORT: need('XM_API_PORT'),
46
+ AUTH_PORT: need('XM_AUTH_PORT'),
47
+ AUTH_URL: 'http://127.0.0.1:' + need('XM_AUTH_PORT'),
48
+ DB_API: 'xeplr_monitor_api',
49
+ // The backup jobs' own database (@xeplr/jobs), and where a dump is written
50
+ // before it goes to S3 (and is then deleted).
51
+ DB_JOBS: 'xeplr_monitor_jobs',
52
+ XEPLR_DATA_DIR: path.join(need('XM_VAR'), 'data'),
53
+ AUTH_DB_NAME: 'xeplr_monitor_auth',
54
+ REDIS_HOST: e.XM_REDIS_HOST || '127.0.0.1',
55
+ REDIS_PORT: e.XM_REDIS_PORT || '6379',
56
+ // The root-owned command sudoers allows (deploy/control.sh, installed by install.sh).
57
+ MONITOR_CONTROL_COMMAND: '/usr/local/libexec/xeplr-monitor-control'
58
+ };
59
+ // Which permission files the release ships: rewritten every deploy, so a
60
+ // release that adds one reaches installs made before it.
61
+ values.XEPLR_AUTH_MIGRATIONS = schema.byName.XEPLR_AUTH_MIGRATIONS.derive({});
62
+ if (e.XM_REDIS_PASSWORD) values.REDIS_PASSWORD = e.XM_REDIS_PASSWORD;
63
+ if (e.XM_ADMIN_EMAIL) values.AUTH_SUPER_ADMIN_EMAIL = e.XM_ADMIN_EMAIL;
64
+ if (e.XM_ADMIN_PASSWORD) values.AUTH_SUPER_ADMIN_PASSWORD = e.XM_ADMIN_PASSWORD;
65
+ if (site) {
66
+ values.SERVER_NAME = e.XM_DOMAIN;
67
+ values.AUTH_ACTIVATION_URL = site + '/auth/activate';
68
+ values.AUTH_INVITE_URL = site + '/auth/accept-invite';
69
+ values.AUTH_RESET_URL = site + '/auth/reset-password';
70
+ }
71
+ if (e.XM_DB_HOST) {
72
+ // A new login: both connections are worked out again from it, together.
73
+ Object.assign(values, { DB_HOST: e.XM_DB_HOST, DB_PORT: e.XM_DB_PORT || '5432', DB_USER: e.XM_DB_USER || '', DB_PASSWORD: e.XM_DB_PASSWORD || '' });
74
+ values.XEPLR_MONITOR_CONNECTION = '';
75
+ values.AUTH_DB_CONNECTION_INFO_ENCRYPTED = '';
76
+ }
77
+ // No longer a setting: any service can be watched; roles decide who may.
78
+ if ('MONITOR_ALLOW' in was) values.MONITOR_ALLOW = '';
79
+ setup.envFile.setValues(file, values);
80
+
81
+ var out = await setup.prepare(file, schema);
82
+ var now = setup.envFile.readEnv(file).values;
83
+ var left = setup.missing(schema, now);
84
+ console.log(' Settings written (' + (was.ENCRYPTION_KEY ? 'secrets kept' : 'secrets made') +
85
+ (e.XM_DB_HOST ? ', database login set' : (was.XEPLR_MONITOR_CONNECTION ? ', database login kept' : '')) +
86
+ (out.filled.length ? '; filled: ' + out.filled.map(function(f) { return f.split(' ')[0]; }).join(', ') : '') + ')');
87
+ if (left.core.length) {
88
+ console.log(' Still needed, asked on the setup page: ' + left.core.join(', '));
89
+ process.exit(3);
90
+ }
91
+ }
92
+
93
+ main().catch(function(err) { console.error(' ' + err.message); process.exit(1); });
package/package.json CHANGED
@@ -1,63 +1,45 @@
1
1
  {
2
2
  "name": "@xeplr/monitor",
3
- "version": "0.1.2",
4
- "description": "See and control a server's services: status, start, stop, restart, kill, and their logs live. Its own sign-in, no database",
5
- "main": "index.js",
6
- "files": [
7
- "index.js",
8
- "lib/",
9
- "bin/",
10
- "deploy/",
11
- "public/"
12
- ],
13
- "bin": {
14
- "xeplr-monitor-server": "./bin/server.js",
15
- "xeplr-monitor-users": "./bin/users.js"
16
- },
17
- "exports": {
18
- ".": "./index.js",
19
- "./package.json": "./package.json"
3
+ "version": "1.0.0",
4
+ "description": "See a server and control its systemd services from a web page: how each is doing, start / stop / restart / kill, live logs, memory, CPU, requests and errors over time, database backups to S3. A xeplr app: run `npx @xeplr/monitor` on the server to install it there.",
5
+ "license": "MIT",
6
+ "repository": {
7
+ "type": "git",
8
+ "url": "https://github.com/Xeplr/xeplr-monitor"
20
9
  },
10
+ "homepage": "https://github.com/Xeplr/xeplr-monitor#readme",
21
11
  "keywords": [
22
12
  "monitor",
23
13
  "systemd",
24
- "journalctl",
14
+ "server",
25
15
  "logs",
26
- "restart",
27
- "ops"
16
+ "xeplr"
28
17
  ],
29
- "author": "xeplr",
30
- "license": "MIT",
31
- "repository": {
32
- "type": "git",
33
- "url": "https://github.com/Xeplr/xeplr-monitor"
18
+ "bin": {
19
+ "xeplr-monitor": "deploy/deploy.js"
34
20
  },
21
+ "files": [
22
+ "deploy/",
23
+ "api/",
24
+ "ui/",
25
+ "!api/test/",
26
+ "!api/*.env",
27
+ "!api/logs/",
28
+ "!ui/dist/",
29
+ "README.md",
30
+ "LICENSE"
31
+ ],
35
32
  "publishConfig": {
36
33
  "access": "public"
37
34
  },
38
- "engines": {
39
- "node": ">=20"
35
+ "scripts": {
36
+ "install-here": "node deploy/deploy.js",
37
+ "test": "npm --prefix api test"
40
38
  },
41
39
  "dependencies": {
42
- "@xeplr/base-apis": "^3.0.3",
43
- "@xeplr/utils": "^2.0.1",
44
- "express": "^5.3.0"
45
- },
46
- "scripts": {
47
- "test": "node --test test/*.test.js",
48
- "build": "vite build --config ui/vite.config.js",
49
- "dev:page": "vite --config ui/vite.config.js",
50
- "prepack": "npm run build"
40
+ "@xeplr/cli": "^0.3.8"
51
41
  },
52
- "devDependencies": {
53
- "@tanstack/react-table": "^8.21.3",
54
- "@vitejs/plugin-react": "^5.2.0",
55
- "@xeplr/ui-monitor": "^0.1.1",
56
- "@xeplr/ui-table": "^1.1.3",
57
- "@xeplr/ui-utils": "^1.1.8",
58
- "react": "^19.3.1",
59
- "react-dom": "^19.3.1",
60
- "react-router-dom": "^7.18.5",
61
- "vite": "^7.3.7"
42
+ "engines": {
43
+ "node": ">=20"
62
44
  }
63
45
  }
package/ui/.env ADDED
@@ -0,0 +1,8 @@
1
+ # xeplr-monitor UI — dev port and the services it talks to.
2
+ #
3
+ # Read by vite.config.js, so no port is written in code. Change a number here
4
+ # and the dev server and every proxy target follow.
5
+
6
+ UI_PORT=19400
7
+ AUTH_URL=http://localhost:19401
8
+ API_URL=http://localhost:19402
package/ui/README.md ADDED
@@ -0,0 +1,29 @@
1
+ # xeplr-monitor — ui
2
+
3
+ The React app (Vite): `@xeplr/ui-account` for sign-in and the app shell, and the Home and Monitor pages from `@xeplr/ui-monitor` (`ServerPage`, `MonitorPage`).
4
+
5
+ ```bash
6
+ npm run dev # http://localhost:19400
7
+ npm run build # → dist/
8
+ ```
9
+
10
+ `.env` holds the port and where the sign-in service and the API are; `vite.config.js` proxies `/auth/api` to sign-in and `/api` (and `/health`, `/whoami`) to the API. In production nginx does the same (the deploy writes it).
11
+
12
+ ## Layout
13
+
14
+ | Path | What |
15
+ |---|---|
16
+ | `src/main.jsx` | `ThemeProvider` (required — the theme's colours exist only inside it) and `AccessProvider` |
17
+ | `src/App.jsx` | routes (`/` opens Home), the side rail (`drawerItems`: Home, Monitor) and the settings menu (Admin, App settings) — **by key**, never by label |
18
+ | `/settings/app` (in `src/App.jsx`) | **App settings** — `@xeplr/ui-setup`'s `AppSettingsPage` on `/api/app-settings`, Super Admin only (menu row `App settings`, `api/migrations-auth/0009`). Asks `/setup/status` (proxied, and routed by nginx) while the app restarts |
19
+ | `src/api/monitor.js` | `createMonitorApi({ fetch: authFetch, stream: authEventStream })` — every call with the sign-in token |
20
+ | `src/pages/Home.jsx` | `@xeplr/ui-monitor`'s `ServerPage` on that API: the server itself |
21
+ | `src/pages/Monitor.jsx` | `@xeplr/ui-monitor`'s `MonitorPage` on that API |
22
+
23
+ ## Rules
24
+
25
+ - `authFetch` returns the **parsed body**, not a Response — no `.json()`.
26
+ - A side-rail item needs an **icon** (a collapsed rail shows icons only) and its key must exist as a menu row (`Home` in `api/migrations-auth/0007`, `Monitor` in `0006`), or it is dropped silently. Give it its **`path`** too: that is how the rail marks the page you are on.
27
+ - **`pages.json` lists every route.** Home and Monitor are `webOnly`: written by hand, since the server's numbers, services, processes and live logs are not forms. The pre-commit hook (`.githooks/pre-commit`, set up by `npm install` here) prints that on every commit, with `xeplr-factory pages` (`@xeplr/ui-factory`, a dev dependency for that only).
28
+ - Phones: below 640px the rail becomes a bar across the top (`@xeplr/ui-account`) and the Monitor page stacks its list above the selected service; its tables scroll inside their own box.
29
+ - Set page backgrounds on a container inside the theme, never on `body`.