@xeplr/monitor 0.1.3 → 1.0.1

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 +193 -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,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); });
package/deploy/install.sh CHANGED
@@ -1,123 +1,234 @@
1
- # THE MONITOR, INSTALLED OR UPDATED ON A SERVER — run as root, by
2
- # `xeplr-monitor-deploy` over SSH (bin/deploy.js puts the XM_* values above
3
- # this file and sends both on SSH's input, so nothing is a file or an argument
4
- # on the server). Safe to run again: it updates in place and keeps the sign-in
5
- # secret, so nobody is signed out by a re-deploy.
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
6
  #
7
- # XM_VERSION the @xeplr/monitor version to install
8
- # XM_ALLOW the services it may control (MONITOR_ALLOW), comma-separated
9
- # XM_PORT its port; nginx forwards to it
10
- # XM_EMAIL the user to add, or whose password to change
11
- # XM_NAME that user's name (optional)
12
- # XM_PASSWORD their new password; empty keeps an existing user's
13
- # XM_DOMAIN its own web address for nginx; empty leaves nginx alone
14
- # XM_CERTBOT 1 to get an https certificate for XM_DOMAIN with certbot
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
15
22
  set -euo pipefail
16
23
 
17
24
  say() { printf ' %s\n' "$*"; }
25
+ export NPM_CONFIG_UPDATE_NOTIFIER=false NPM_CONFIG_FUND=false
18
26
  stop() { printf '\n Stopped: %s\n' "$*" >&2; exit 1; }
19
27
 
20
- DATA=/var/lib/xeplr-monitor
21
- ETC=/etc/xeplr-monitor
22
- ENV_FILE=$ETC/monitor.env
28
+ APP=/opt/xeplr-monitor
29
+ SHARED=$APP/shared
30
+ ENV_FILE=$SHARED/production.env
31
+ VAR=/var/lib/xeplr-monitor
23
32
  USER_NAME=xeplr-monitor
24
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
+
25
51
  # ── what the server must already have ────────────────────────────────────
26
52
  command -v systemctl >/dev/null || stop "systemd is not here: the monitor controls systemd services"
27
53
  NODE=$(command -v node || true)
28
54
  [ -n "$NODE" ] || stop "Node.js is not installed (20 or newer is needed)"
29
55
  [ "$("$NODE" -p 'process.versions.node.split(".")[0]')" -ge 20 ] || stop "Node.js $("$NODE" -v) is too old: 20 or newer is needed"
30
56
  command -v npm >/dev/null || stop "npm is not installed"
57
+ command -v tar >/dev/null || stop "tar is not installed"
31
58
  SYSTEMCTL=$(command -v systemctl)
32
59
 
33
- # ── its own user, which reads the journal ────────────────────────────────
34
- if ! id "$USER_NAME" >/dev/null 2>&1; then
35
- useradd -r -m -d "$DATA" -s /usr/sbin/nologin "$USER_NAME"
36
- say "User $USER_NAME made"
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
37
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"; }
38
75
  usermod -aG systemd-journal "$USER_NAME"
39
- mkdir -p "$DATA" && chown "$USER_NAME:$USER_NAME" "$DATA" && chmod 700 "$DATA"
40
76
 
41
- # ── the package ──────────────────────────────────────────────────────────
42
- say "Installing @xeplr/monitor@$XM_VERSION"
43
- npm install -g --no-fund --no-audit --no-update-notifier --loglevel=error "@xeplr/monitor@$XM_VERSION" >/dev/null
44
- ROOT="$(npm root -g)/@xeplr/monitor"
45
- [ -f "$ROOT/bin/server.js" ] || stop "the package did not install into $ROOT"
77
+ # ── the Node its services run on: one THEIR user can run ─────────────────
78
+ # The services run as $USER_NAME, not as whoever runs this. A Node from nvm
79
+ # lives in that person's home (/root/.nvm/…), which $USER_NAME cannot enter:
80
+ # systemd then fails every start with "Permission denied" (status 203/EXEC).
81
+ # So the Node found above is used only if $USER_NAME can run it; else the
82
+ # server's own (/usr/bin, /usr/local/bin). Checked before anything changes,
83
+ # so a refusal leaves the running install as it was.
84
+ SERVICE_NODE=""
85
+ for candidate in "$NODE" /usr/bin/node /usr/local/bin/node; do
86
+ [ -x "$candidate" ] || continue
87
+ major=$(sudo -u "$USER_NAME" "$candidate" -p 'process.versions.node.split(".")[0]' 2>/dev/null || true)
88
+ if [ -n "$major" ] && [ "$major" -ge 20 ]; then SERVICE_NODE=$candidate; break; fi
89
+ done
90
+ [ -n "$SERVICE_NODE" ] || stop "the monitor's services run as $USER_NAME, which cannot run Node.js at $NODE (in a home folder, e.g. from nvm) and there is no Node.js 20+ at /usr/bin or /usr/local/bin. Install Node.js system-wide (e.g. NodeSource's package), then run this again — the running install was not changed"
91
+ [ "$SERVICE_NODE" = "$NODE" ] || say "Services run on $SERVICE_NODE ($NODE is in a home folder $USER_NAME cannot enter)"
92
+ mkdir -p "$VAR/logs" "$VAR/data" "$SHARED" "$APP/releases"
93
+ chown -R "$USER_NAME:$USER_NAME" "$VAR" && chmod 750 "$VAR"
94
+
95
+ # ── this release: the source, its packages, the page built ───────────────
96
+ REL=$APP/releases/$(date -u +%Y%m%d%H%M%S)
97
+ mkdir -p "$REL"
98
+ # The copy the installer runs from; nothing is fetched.
99
+ [ -n "${XM_SOURCE_DIR:-}" ] && [ -d "$XM_SOURCE_DIR" ] || stop "no source folder to install from (run deploy/deploy.js)"
100
+ tar -C "$XM_SOURCE_DIR" --exclude=node_modules --exclude=.git -cf - . | tar -xf - -C "$REL" \
101
+ || stop "could not copy the source from $XM_SOURCE_DIR"
102
+ say "Source: $XM_SOURCE_DIR"
103
+ [ -f "$REL/api/bin/www" ] && [ -f "$REL/ui/package.json" ] || stop "that source is not xeplr-monitor (no api/bin/www or ui/)"
104
+ say "Installing packages (api, ui)"
105
+ (cd "$REL/api" && npm ci --no-fund --no-audit --no-update-notifier --loglevel=error >/dev/null)
106
+ (cd "$REL/ui" && npm ci --no-fund --no-audit --no-update-notifier --loglevel=error >/dev/null && npx vite build --logLevel error >/dev/null)
107
+ [ -f "$REL/ui/dist/index.html" ] || stop "the page did not build"
108
+ chown -R "$USER_NAME:$USER_NAME" "$REL"
46
109
 
47
- # ── settings: the secret is made once and kept ───────────────────────────
48
- mkdir -p "$ETC"
110
+ # ── settings: written once, kept after; secrets made here, never asked ───
111
+ # Through the app's own schema (api/setup.schema.js, @xeplr/setup): what is
112
+ # missing after this is asked on the setup page, never a failed deploy.
49
113
  touch "$ENV_FILE"
50
- if ! grep -q '^MONITOR_SECRET=.\{32,\}' "$ENV_FILE"; then
51
- sed -i '/^MONITOR_SECRET=/d' "$ENV_FILE"
52
- echo "MONITOR_SECRET=$("$NODE" -e 'process.stdout.write(require("crypto").randomBytes(48).toString("base64"))')" >> "$ENV_FILE"
53
- say "Sign-in secret made (kept on later deploys)"
114
+ # The answers go to this one process only, not to every command after it.
115
+ SETUP_NEEDED=0
116
+ env XM_ENV_FILE="$ENV_FILE" XM_AUTH_PORT="$AUTH_PORT" XM_API_PORT="$API_PORT" XM_VAR="$VAR" \
117
+ XM_DOMAIN="$XM_DOMAIN" XM_CERTBOT="$XM_CERTBOT" \
118
+ XM_DB_HOST="$XM_DB_HOST" XM_DB_PORT="$XM_DB_PORT" XM_DB_USER="$XM_DB_USER" XM_DB_PASSWORD="$XM_DB_PASSWORD" \
119
+ XM_REDIS_HOST="$XM_REDIS_HOST" XM_REDIS_PORT="$XM_REDIS_PORT" XM_REDIS_PASSWORD="$XM_REDIS_PASSWORD" \
120
+ XM_ADMIN_EMAIL="$XM_ADMIN_EMAIL" XM_ADMIN_PASSWORD="$XM_ADMIN_PASSWORD" \
121
+ "$NODE" "$REL/deploy/settings.cjs" "$REL/api" || { [ $? -eq 3 ] && SETUP_NEEDED=1; } || stop "the settings could not be written"
122
+ # THE APP OWNS ITS SETTINGS: the setup page and App settings (Super Admin)
123
+ # rewrite this file — atomically, a temp file beside it renamed over it — so
124
+ # the service user owns the file and its folder. Nobody else reads either.
125
+ chown "$USER_NAME:$USER_NAME" "$SHARED" "$ENV_FILE" && chmod 700 "$SHARED" && chmod 600 "$ENV_FILE"
126
+ [ ! -f "$SHARED/FIRST_LOGIN" ] || chown "$USER_NAME:$USER_NAME" "$SHARED/FIRST_LOGIN"
127
+
128
+ # ── the databases, the sign-in tables and the permissions ────────────────
129
+ run_api() { (cd "$REL/api" && sudo -u "$USER_NAME" env NODE_ENV=production node_modules/.bin/dotenv -e "$ENV_FILE" -- "$@"); }
130
+ if [ "$SETUP_NEEDED" = 1 ]; then
131
+ say "Databases: after the setup page (the API and the sign-in service make theirs when they start)"
132
+ else
133
+ say "Databases: creating any that are missing, then the sign-in migrations"
134
+ 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 \
135
+ || stop "could not reach or create the sign-in database (is Postgres running, and may that user create databases?)"
136
+ run_api node_modules/.bin/xeplr-migrate create-db --connectionName api --connection-env XEPLR_MONITOR_CONNECTION --db-env DB_API >/dev/null \
137
+ || stop "could not create the app's database"
138
+ run_api node_modules/.bin/xeplr-auth-migrate up --connection-env AUTH_DB_CONNECTION_INFO_ENCRYPTED >/dev/null \
139
+ || stop "the sign-in migrations failed"
54
140
  fi
55
- setting() { sed -i "/^$1=/d" "$ENV_FILE"; echo "$1=$2" >> "$ENV_FILE"; }
56
- setting MONITOR_DATA_DIR "$DATA"
57
- setting MONITOR_ALLOW "$XM_ALLOW"
58
- setting MONITOR_PORT "$XM_PORT"
59
- chown root:"$USER_NAME" "$ENV_FILE" && chmod 640 "$ENV_FILE"
60
141
 
61
- # ── sudoers: start, stop, restart and kill the allowed services, nothing else
142
+ # ── the one command sudoers allows: deploy/control.sh
143
+ # It checks the action and the name itself, so sudoers names the command
144
+ # alone — no wildcard, which newer sudo (sudo-rs) refuses anyway.
145
+ CONTROL=/usr/local/libexec/xeplr-monitor-control
146
+ mkdir -p /usr/local/libexec
147
+ sed -e "s|__SYSTEMCTL__|$SYSTEMCTL|" "$REL/deploy/control.sh" > "$CONTROL.new"
148
+ chown root:root "$CONTROL.new" && chmod 755 "$CONTROL.new" && mv -f "$CONTROL.new" "$CONTROL"
62
149
  SUDOERS_TMP=$(mktemp)
63
150
  {
64
- echo "# Made by xeplr-monitor-deploy from MONITOR_ALLOW=$XM_ALLOW. Changed by the next deploy."
65
- IFS=',' read -ra PATTERNS <<< "$XM_ALLOW"
66
- for raw in "${PATTERNS[@]}"; do
67
- p=$(echo "$raw" | tr -d '[:space:]')
68
- [ -n "$p" ] || continue
69
- echo "$USER_NAME ALL=(root) NOPASSWD: $SYSTEMCTL start $p, $SYSTEMCTL stop $p, $SYSTEMCTL restart $p, $SYSTEMCTL kill --signal=SIGKILL $p"
70
- done
151
+ echo "# Made by xeplr-monitor's deploy. Changed by the next deploy."
152
+ echo "# $CONTROL checks the action and the service name; roles in the app decide who may."
153
+ echo "$USER_NAME ALL=(root) NOPASSWD: $CONTROL"
71
154
  } > "$SUDOERS_TMP"
72
- visudo -cqf "$SUDOERS_TMP" || { rm -f "$SUDOERS_TMP"; stop "the sudoers lines for MONITOR_ALLOW=$XM_ALLOW are not valid"; }
155
+ visudo -cqf "$SUDOERS_TMP" || { rm -f "$SUDOERS_TMP"; stop "visudo refused the sudoers line for $CONTROL"; }
73
156
  install -m 440 "$SUDOERS_TMP" /etc/sudoers.d/xeplr-monitor && rm -f "$SUDOERS_TMP"
74
-
75
- # ── it must be able to ask systemd as its own user (needs D-Bus) ─────────
76
157
  sudo -u "$USER_NAME" "$SYSTEMCTL" show -p Version >/dev/null 2>&1 \
77
158
  || stop "$USER_NAME cannot ask systemd (no D-Bus?). Install and start dbus, then deploy again"
78
159
 
79
- # ── the systemd service: node and the server by their full paths ─────────
80
- UNIT=/etc/systemd/system/xeplr-monitor.service
81
- sed "s#^ExecStart=.*#ExecStart=$NODE $ROOT/bin/server.js#" "$ROOT/deploy/xeplr-monitor.service" > "$UNIT"
82
- # Node under a home folder (nvm) must stay readable to the service.
83
- case "$NODE" in /home/*|/root/*) sed -i 's/^ProtectHome=true/ProtectHome=read-only/' "$UNIT" ;; esac
160
+ # ── switch to this release, and the two services ─────────────────────────
161
+ ln -sfn "$REL" "$APP/current"
162
+ unit() { # name, description, command (run in current/api), extra lines
163
+ cat > "/etc/systemd/system/$1.service" <<UNIT
164
+ # Made by xeplr-monitor's deploy. Changed by the next deploy.
165
+ [Unit]
166
+ Description=$2
167
+ After=network-online.target postgresql.service redis-server.service
168
+
169
+ [Service]
170
+ Type=simple
171
+ User=$USER_NAME
172
+ Group=$USER_NAME
173
+ WorkingDirectory=$APP/current/api
174
+ EnvironmentFile=$ENV_FILE
175
+ ExecStart=$3
176
+ Restart=always
177
+ RestartSec=3
178
+ PrivateTmp=true
179
+ $4
180
+
181
+ [Install]
182
+ WantedBy=multi-user.target
183
+ UNIT
184
+ }
185
+ # Restart=always is also how settings take effect: the setup page and App
186
+ # settings exit 75 after writing $ENV_FILE, and systemd starts them again.
187
+ unit xeplr-monitor-auth "xeplr-monitor: sign-in (@xeplr/auth)" "$SERVICE_NODE $APP/current/api/bin/auth.js" ""
188
+ # The API controls services: the journal group reads their logs; sudo needs
189
+ # to gain privileges, so NoNewPrivileges stays off — sudoers is the limit.
190
+ unit xeplr-monitor-api "xeplr-monitor: the API (services, logs, start/stop)" "$SERVICE_NODE $APP/current/api/bin/www" "SupplementaryGroups=systemd-journal"
84
191
  systemctl daemon-reload
85
- systemctl enable xeplr-monitor >/dev/null 2>&1
192
+ systemctl enable xeplr-monitor-auth xeplr-monitor-api >/dev/null 2>&1
193
+ systemctl restart xeplr-monitor-auth xeplr-monitor-api
86
194
 
87
- # ── the user ─────────────────────────────────────────────────────────────
88
- users() { sudo -u "$USER_NAME" env MONITOR_DATA_DIR="$DATA" MONITOR_NEW_PASSWORD="$XM_PASSWORD" "$NODE" "$ROOT/bin/users.js" "$@"; }
89
- if users list | awk '{print tolower($1)}' | grep -qxF "$(printf '%s' "$XM_EMAIL" | tr '[:upper:]' '[:lower:]')"; then
90
- if [ -n "$XM_PASSWORD" ]; then users password "$XM_EMAIL" >/dev/null; say "Password changed for $XM_EMAIL (signed out everywhere)"
91
- else say "$XM_EMAIL is already a user: password kept"; fi
195
+ # ── check both answer ─────────────────────────────────────────────────────
196
+ answers() { "$NODE" -e 'fetch(process.argv[1]).then(r => console.log(r.status)).catch(() => console.log(""))' "$1"; }
197
+ CHECK="auth api"; [ "$SETUP_NEEDED" = 1 ] && CHECK="api" # sign-in waits for setup, listening on nothing
198
+ for name in $CHECK; do
199
+ url="http://127.0.0.1:$AUTH_PORT/auth/api/login"; [ "$name" = api ] && url="http://127.0.0.1:$API_PORT/health"
200
+ got=""
201
+ for _ in $(seq 1 60); do got=$(answers "$url"); [ -n "$got" ] && [ "$got" != "502" ] && break; sleep 1; done
202
+ [ -n "$got" ] || { journalctl -u "xeplr-monitor-$name" -n 25 --no-pager >&2; stop "xeplr-monitor-$name did not answer (its log is above)"; }
203
+ done
204
+ if [ "$SETUP_NEEDED" = 1 ]; then
205
+ 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"
206
+ say " over an SSH tunnel); the one-time code is in $SHARED/SETUP_CODE. Sign-in starts once it is saved."
92
207
  else
93
- [ -n "$XM_PASSWORD" ] || stop "$XM_EMAIL is not a user yet: a password is needed"
94
- if [ -n "$XM_NAME" ]; then users add "$XM_EMAIL" --name "$XM_NAME"; else users add "$XM_EMAIL"; fi
208
+ say "Running: sign-in on $AUTH_PORT, the API on $API_PORT"
95
209
  fi
96
210
 
97
- # ── start it, and check it answers ───────────────────────────────────────
98
- systemctl restart xeplr-monitor
99
- answer=""
100
- for _ in $(seq 1 20); do
101
- answer=$("$NODE" -e 'fetch("http://127.0.0.1:" + process.argv[1] + "/api/me").then(r => console.log(r.status)).catch(() => console.log(""))' "$XM_PORT")
102
- [ "$answer" = "401" ] && break
103
- sleep 0.5
104
- done
105
- [ "$answer" = "401" ] || { journalctl -u xeplr-monitor -n 20 --no-pager >&2; stop "the monitor did not answer on port $XM_PORT (its log is above)"; }
106
- say "Running on port $XM_PORT"
211
+ # Old releases: the newest three are kept, to switch back to by hand.
212
+ ls -1dt "$APP"/releases/*/ | tail -n +4 | xargs -r rm -rf
107
213
 
108
214
  # ── nginx, when asked ────────────────────────────────────────────────────
109
215
  if [ -n "$XM_DOMAIN" ]; then
110
216
  command -v nginx >/dev/null || stop "nginx is not installed, so $XM_DOMAIN was not set up (the monitor itself is running)"
111
217
  if [ -d /etc/nginx/sites-available ]; then SITE=/etc/nginx/sites-available/xeplr-monitor; LINK=/etc/nginx/sites-enabled/xeplr-monitor
112
218
  else SITE=/etc/nginx/conf.d/xeplr-monitor.conf; LINK=""; fi
113
- # certbot adds the https part to this file; a re-deploy writes it afresh and runs certbot again.
219
+ # The page from ui/dist; /auth/api to the sign-in service; /api, /health and
220
+ # /whoami to the API. certbot adds https to this file; a re-deploy writes it
221
+ # afresh and runs certbot again.
114
222
  cat > "$SITE" <<NGINX
115
- # Made by xeplr-monitor-deploy. Changed by the next deploy.
223
+ # Made by xeplr-monitor's deploy. Changed by the next deploy.
116
224
  server {
117
225
  listen 80;
118
226
  server_name $XM_DOMAIN;
119
- location / {
120
- proxy_pass http://127.0.0.1:$XM_PORT;
227
+ root $APP/current/ui/dist;
228
+
229
+ 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; }
230
+ location /api/ {
231
+ proxy_pass http://127.0.0.1:$API_PORT;
121
232
  proxy_set_header Host \$host;
122
233
  proxy_set_header X-Forwarded-For \$proxy_add_x_forwarded_for;
123
234
  proxy_set_header X-Forwarded-Proto \$scheme;
@@ -125,15 +236,20 @@ server {
125
236
  proxy_buffering off;
126
237
  proxy_read_timeout 1h;
127
238
  }
239
+ location = /health { proxy_pass http://127.0.0.1:$API_PORT; }
240
+ location = /whoami { proxy_pass http://127.0.0.1:$API_PORT; }
241
+ # The setup page and /setup/status (asked by App settings while the app restarts).
242
+ location /setup { proxy_pass http://127.0.0.1:$API_PORT; proxy_set_header Host \$host; proxy_set_header X-Forwarded-Proto \$scheme; }
243
+ location / { try_files \$uri /index.html; }
128
244
  }
129
245
  NGINX
130
246
  [ -z "$LINK" ] || ln -sf "$SITE" "$LINK"
131
247
  nginx -t -q || stop "nginx refused the new site ($SITE)"
132
248
  systemctl reload nginx
133
- say "nginx: $XM_DOMAIN → port $XM_PORT"
249
+ say "nginx: $XM_DOMAIN"
134
250
  if [ "$XM_CERTBOT" = "1" ]; then
135
251
  command -v certbot >/dev/null || stop "certbot is not installed, so $XM_DOMAIN has no https yet"
136
- certbot --nginx -d "$XM_DOMAIN" --non-interactive --agree-tos --redirect -m "$XM_EMAIL" >/dev/null
252
+ certbot --nginx -d "$XM_DOMAIN" --non-interactive --agree-tos --redirect -m "$XM_ADMIN_EMAIL" >/dev/null
137
253
  say "https: certificate for $XM_DOMAIN"
138
254
  fi
139
255
  fi
@@ -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); });