@xeplr/monitor 0.1.1 → 0.1.3

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.
package/README.md CHANGED
@@ -15,7 +15,7 @@ The page itself is [`@xeplr/ui-monitor`](https://github.com/Xeplr/xeplr-ui-monit
15
15
  On the servers, every app already runs as a systemd service: `xeplr-bi-api`, `xeplr-bi-auth`, `xeplr-bi-jobs`, and testbi's `xeplr-bi-dev-*`. The monitor starts nothing itself. It asks `systemctl` the same way the deploy does, and reads the journal, where the services' output goes.
16
16
 
17
17
  ```
18
- browser ──https──▶ nginx ──▶ xeplr-monitor (127.0.0.1:19400, its own user)
18
+ browser ──https──▶ nginx ──▶ xeplr-monitor (port 19400, its own user)
19
19
  ├─ systemctl show status (no sudo)
20
20
  ├─ sudo -n systemctl start|stop|restart|kill (sudoers: xeplr-* only)
21
21
  └─ journalctl -u … -o json [-f] (systemd-journal group)
@@ -50,12 +50,47 @@ The page turns these into a short **needs a look** list for a running service: m
50
50
  | `MONITOR_SECRET` | **yes** | Signs the sign-in cookie. At least 32 characters (`openssl rand -base64 48`). Changing it signs everyone out. |
51
51
  | `MONITOR_ALLOW` | **yes** | Which services may be added and controlled, comma-separated; `*` matches anything: `xeplr-*` or `xeplr-*,postgresql`. Keep sudoers the same. |
52
52
  | `MONITOR_PORT` | no | Default 19400. |
53
- | `MONITOR_HOST` | no | Default `127.0.0.1`, so only nginx on the same machine reaches it. |
54
53
  | `MONITOR_SUDO` | no | `actions` (default): start, stop, restart and kill go through `sudo -n`. `all`: reading the journal does too. `none`: nothing does (root, or polkit rights). |
55
54
 
56
55
  There are no defaults for where data lives. A missing required setting stops the server at startup and names it. `requiredEnv` is exported, so a host can add it to its own `env.required.js`.
57
56
 
58
- ## Install on a server
57
+ ## Deploy to a server, from your laptop
58
+
59
+ ```bash
60
+ npx -p @xeplr/monitor xeplr-monitor-deploy
61
+ ```
62
+
63
+ It asks for what it needs, as it goes, and stores nothing: not in this (public) repository, not on your laptop.
64
+
65
+ - **The server:** host (or a name from `~/.ssh/config`), SSH login, port, private key file (blank uses ssh-agent or `~/.ssh/config`). The same SSH access BI's deploy uses; the login needs **passwordless sudo**.
66
+ - **The monitor:** the services it may control (`MONITOR_ALLOW`, default `xeplr-*`), its port (19400), and optionally its own web address for nginx, with an https certificate from certbot.
67
+ - **You:** email, name, and a password, typed hidden, twice. Blank keeps the password of a user who already exists.
68
+
69
+ Then it shows what it will do, asks to confirm, and runs `deploy/install.sh` on the server as root, sent on SSH's input, so no value is ever a file or a command-line argument there. The install:
70
+
71
+ 1. makes the `xeplr-monitor` user (in `systemd-journal`) and `/var/lib/xeplr-monitor` (700);
72
+ 2. installs `@xeplr/monitor` of the same version as the command (`--version` to choose);
73
+ 3. writes `/etc/xeplr-monitor/monitor.env` (640). **`MONITOR_SECRET` is made on the server the first time and kept on every later deploy**, so a re-deploy signs nobody out;
74
+ 4. writes `/etc/sudoers.d/xeplr-monitor` from `MONITOR_ALLOW`, checked with `visudo` first;
75
+ 5. checks the monitor's user can ask systemd (D-Bus), writes the systemd unit with node's full path, enables it;
76
+ 6. adds you, printing the authenticator secret to add to your phone, or changes your password;
77
+ 7. restarts it and checks it answers on its port; with a web address, writes the nginx site, checks it with `nginx -t`, reloads, and runs certbot when asked.
78
+
79
+ Run it again to update: same questions, Enter keeps the values in brackets. Everything can also be given as arguments, so a re-deploy is one line; only the password is never an argument (it would sit in the shell history and in `ps`; `MONITOR_NEW_PASSWORD` is read for a script):
80
+
81
+ ```bash
82
+ npx -p @xeplr/monitor xeplr-monitor-deploy --host testbi.xeplr.com --user ubuntu --key ~/.ssh/testbi.pem \
83
+ --allow 'xeplr-*' --domain monitor.xeplr.com --certbot y --email you@xeplr.com --name "Your name"
84
+ npx -p @xeplr/monitor xeplr-monitor-deploy --help
85
+ ```
86
+
87
+ It stops, saying why, when: SSH sign-in fails, the login has no passwordless sudo, Node.js 20+ or npm is missing, `systemd` or D-Bus is not there, the sudoers lines are invalid, a new user has no password, the monitor does not answer after starting (its last log lines are shown), or nginx refuses the site.
88
+
89
+ Keep the monitor's port closed in the firewall: nginx is the way in.
90
+
91
+ ## Install on a server by hand
92
+
93
+ What the deploy does, step by step:
59
94
 
60
95
  ```bash
61
96
  # 1. its own user, its folder, the package
@@ -97,7 +132,7 @@ xeplr-monitor-users code <email> [--off] # a new authenticator secret, or n
97
132
  xeplr-monitor-users remove <email>
98
133
  ```
99
134
 
100
- Run them as the monitor's user, with `MONITOR_DATA_DIR` set. A password is typed, never passed as an argument, because it would be left in the shell's history and in `ps`. `MONITOR_NEW_PASSWORD` is read instead when set, for a script.
135
+ Run them on the server as the monitor's user, with `MONITOR_DATA_DIR` set. `xeplr-monitor-deploy` runs `add` or `password` for you. A password is typed, never passed as an argument, because it would be left in the shell's history and in `ps`. `MONITOR_NEW_PASSWORD` is read instead when set, for a script.
101
136
 
102
137
  - **Passwords:** scrypt hashes, at least 12 characters.
103
138
  - **Codes:** a new user gets a six-digit code from an authenticator app by default (RFC 6238, 30 seconds; one step either side is accepted). `--no-code` turns that off.
package/bin/deploy.js ADDED
@@ -0,0 +1,181 @@
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 CHANGED
@@ -12,8 +12,7 @@ monitor.start({
12
12
  secret: process.env.MONITOR_SECRET,
13
13
  allow: process.env.MONITOR_ALLOW,
14
14
  sudo: process.env.MONITOR_SUDO,
15
- port: process.env.MONITOR_PORT,
16
- host: process.env.MONITOR_HOST
15
+ port: process.env.MONITOR_PORT
17
16
  }).catch(function(err) {
18
17
  console.error('[xeplr-monitor] could not start:', err.message);
19
18
  process.exit(1);
package/bin/users.js CHANGED
File without changes
@@ -0,0 +1,140 @@
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.
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
15
+ set -euo pipefail
16
+
17
+ say() { printf ' %s\n' "$*"; }
18
+ stop() { printf '\n Stopped: %s\n' "$*" >&2; exit 1; }
19
+
20
+ DATA=/var/lib/xeplr-monitor
21
+ ETC=/etc/xeplr-monitor
22
+ ENV_FILE=$ETC/monitor.env
23
+ USER_NAME=xeplr-monitor
24
+
25
+ # ── what the server must already have ────────────────────────────────────
26
+ command -v systemctl >/dev/null || stop "systemd is not here: the monitor controls systemd services"
27
+ NODE=$(command -v node || true)
28
+ [ -n "$NODE" ] || stop "Node.js is not installed (20 or newer is needed)"
29
+ [ "$("$NODE" -p 'process.versions.node.split(".")[0]')" -ge 20 ] || stop "Node.js $("$NODE" -v) is too old: 20 or newer is needed"
30
+ command -v npm >/dev/null || stop "npm is not installed"
31
+ SYSTEMCTL=$(command -v systemctl)
32
+
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"
37
+ fi
38
+ usermod -aG systemd-journal "$USER_NAME"
39
+ mkdir -p "$DATA" && chown "$USER_NAME:$USER_NAME" "$DATA" && chmod 700 "$DATA"
40
+
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"
46
+
47
+ # ── settings: the secret is made once and kept ───────────────────────────
48
+ mkdir -p "$ETC"
49
+ 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)"
54
+ 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
+
61
+ # ── sudoers: start, stop, restart and kill the allowed services, nothing else
62
+ SUDOERS_TMP=$(mktemp)
63
+ {
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
71
+ } > "$SUDOERS_TMP"
72
+ visudo -cqf "$SUDOERS_TMP" || { rm -f "$SUDOERS_TMP"; stop "the sudoers lines for MONITOR_ALLOW=$XM_ALLOW are not valid"; }
73
+ 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
+ sudo -u "$USER_NAME" "$SYSTEMCTL" show -p Version >/dev/null 2>&1 \
77
+ || stop "$USER_NAME cannot ask systemd (no D-Bus?). Install and start dbus, then deploy again"
78
+
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
84
+ systemctl daemon-reload
85
+ systemctl enable xeplr-monitor >/dev/null 2>&1
86
+
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
92
+ 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
95
+ fi
96
+
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"
107
+
108
+ # ── nginx, when asked ────────────────────────────────────────────────────
109
+ if [ -n "$XM_DOMAIN" ]; then
110
+ command -v nginx >/dev/null || stop "nginx is not installed, so $XM_DOMAIN was not set up (the monitor itself is running)"
111
+ if [ -d /etc/nginx/sites-available ]; then SITE=/etc/nginx/sites-available/xeplr-monitor; LINK=/etc/nginx/sites-enabled/xeplr-monitor
112
+ 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.
114
+ cat > "$SITE" <<NGINX
115
+ # Made by xeplr-monitor-deploy. Changed by the next deploy.
116
+ server {
117
+ listen 80;
118
+ server_name $XM_DOMAIN;
119
+ location / {
120
+ proxy_pass http://127.0.0.1:$XM_PORT;
121
+ proxy_set_header Host \$host;
122
+ proxy_set_header X-Forwarded-For \$proxy_add_x_forwarded_for;
123
+ proxy_set_header X-Forwarded-Proto \$scheme;
124
+ # A live log is one long answer: no buffering, and kept open.
125
+ proxy_buffering off;
126
+ proxy_read_timeout 1h;
127
+ }
128
+ }
129
+ NGINX
130
+ [ -z "$LINK" ] || ln -sf "$SITE" "$LINK"
131
+ nginx -t -q || stop "nginx refused the new site ($SITE)"
132
+ systemctl reload nginx
133
+ say "nginx: $XM_DOMAIN → port $XM_PORT"
134
+ if [ "$XM_CERTBOT" = "1" ]; then
135
+ 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
137
+ say "https: certificate for $XM_DOMAIN"
138
+ fi
139
+ fi
140
+ say "Done"
@@ -13,5 +13,4 @@ MONITOR_ALLOW=xeplr-*
13
13
 
14
14
  # Optional.
15
15
  # MONITOR_PORT=19400 (default 19400)
16
- # MONITOR_HOST=127.0.0.1 (default: only nginx on this machine reaches it)
17
16
  # MONITOR_SUDO=actions (actions | all | none — see the README)
@@ -1,5 +1,6 @@
1
- # The monitor behind nginx, on its own name (https only). It listens on
2
- # 127.0.0.1:19400; nginx is the only way in.
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.
3
4
  server {
4
5
  listen 443 ssl http2;
5
6
  server_name monitor.example.com;
package/index.js CHANGED
@@ -59,8 +59,8 @@ function pageRouter(dir) {
59
59
 
60
60
  /**
61
61
  * Serve it: the API at /api, the page everywhere else. → the http server,
62
- * once listening. Listens on 127.0.0.1 unless told otherwise: nginx is its
63
- * front door.
62
+ * once listening on its port. nginx is its front door, as for every xeplr
63
+ * service.
64
64
  */
65
65
  function start(config) {
66
66
  config = config || {};
@@ -68,7 +68,6 @@ function start(config) {
68
68
  // 0 is a port too (any free one); only a missing value takes the default.
69
69
  var port = config.port === undefined || config.port === null || config.port === '' ? 19400 : Number(config.port);
70
70
  var built = createApp(port, 'xeplr-monitor', {
71
- host: config.host || '127.0.0.1',
72
71
  // Its own sign-in: it must work when @xeplr/auth is down. The headers go in
73
72
  // front of it, so a refused request carries them too (createApp's
74
73
  // `middleware` runs only after the gate).
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@xeplr/monitor",
3
- "version": "0.1.1",
3
+ "version": "0.1.3",
4
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
5
  "main": "index.js",
6
6
  "files": [
@@ -12,7 +12,8 @@
12
12
  ],
13
13
  "bin": {
14
14
  "xeplr-monitor-server": "./bin/server.js",
15
- "xeplr-monitor-users": "./bin/users.js"
15
+ "xeplr-monitor-users": "./bin/users.js",
16
+ "xeplr-monitor-deploy": "./bin/deploy.js"
16
17
  },
17
18
  "exports": {
18
19
  ".": "./index.js",
@@ -39,7 +40,7 @@
39
40
  "node": ">=20"
40
41
  },
41
42
  "dependencies": {
42
- "@xeplr/base-apis": "^3.0.2",
43
+ "@xeplr/base-apis": "^3.0.3",
43
44
  "@xeplr/utils": "^2.0.1",
44
45
  "express": "^5.3.0"
45
46
  },