@xeplr/monitor 0.0.0-stage → 0.1.2

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/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Xeplr
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md CHANGED
@@ -1,3 +1,147 @@
1
- # Temporary Holding Version
1
+ # @xeplr/monitor
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ See and control a server's services from a web page: whether each one is running and how healthy it is (memory against its limit, CPU, threads, every process of it, restarts, why it last stopped, and what command it runs). Start, stop, restart or kill it, and read its log, either live as it is written or for a time range, with a search box.
4
+
5
+ It is what you open when something is down, so it depends on nothing else:
6
+
7
+ - **Its own sign-in.** It does not use `@xeplr/auth`. If BI's auth service is the one that crashed, a monitor that signed in through it could not be used to restart it.
8
+ - **No database.** Users, the services it watches and its audit log are plain files in one folder. It keeps working when Postgres is down.
9
+ - **Built on the xeplr packages, none of which needs a running service here:** `@xeplr/base-apis` `createApp` (the gate, cookies, request lines through `@xeplr/logs` to stdout and so to the journal, where the monitor can show its own log; in production only 4xx and 5xx; 404s and errors as `{ error }`) and `@xeplr/utils` (`totp` for authenticator codes, `RateLimiter` as the wrong-try lockout, kept in memory, not Redis).
10
+
11
+ The page itself is [`@xeplr/ui-monitor`](https://github.com/Xeplr/xeplr-ui-monitor), built into `public/` and served by this package.
12
+
13
+ ## How it works
14
+
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
+
17
+ ```
18
+ browser ──https──▶ nginx ──▶ xeplr-monitor (port 19400, its own user)
19
+ ├─ systemctl show status (no sudo)
20
+ ├─ sudo -n systemctl start|stop|restart|kill (sudoers: xeplr-* only)
21
+ └─ journalctl -u … -o json [-f] (systemd-journal group)
22
+ ```
23
+
24
+ - A service is controlled only once someone has **added it** to the monitor's list, and only if its name matches **`MONITOR_ALLOW`** (e.g. `xeplr-*`). sudoers allows the same names and nothing else.
25
+ - Names are checked (`[A-Za-z0-9@._:-]`) before they reach a command. No shell is ever used: every command gets its arguments as a list.
26
+ - **Stop and kill refuse the monitor's own service**, which it finds from its cgroup. Stopping it would leave nothing to start it again. Restart is allowed.
27
+ - A live log is one `journalctl -f` process per open log. It ends when the page closes the log. Each user can have at most 10 open.
28
+ - Every command has a time limit: 2 minutes for an action (a stop waits for the service's own stop timeout), 30 seconds for a read.
29
+
30
+ ## How healthy a service is
31
+
32
+ All from systemd and `/proc`, read without sudo, every time the list is asked for (the page asks every 5 seconds):
33
+
34
+ | | From |
35
+ |---|---|
36
+ | State, since when, why it last ended, exit code, restarts by itself | `systemctl show`: `ActiveState`, `SubState`, `Result`, `ExecMainStatus`, `NRestarts` |
37
+ | **What runs it**: the command line, working folder, user, unit file | `ExecStart`, `WorkingDirectory`, `User`, `FragmentPath`. The same command `ps` shows; the environment file's contents are never read |
38
+ | **Memory** now, its peak, its limit (`MemoryMax`, `MemoryHigh`), swap | `MemoryCurrent`, `MemoryPeak` (systemd 255+), `MemorySwapCurrent` |
39
+ | **CPU %** since the last reading, and CPU seconds in all | `CPUUsageNSec`, two readings apart. Above 100% means more than one core |
40
+ | Threads, against `TasksMax` | `TasksCurrent` |
41
+ | **Every process** of it: pid, parent, command, memory (RSS), swap, CPU %, threads, state, running since | the unit's cgroup (`cgroup.procs`, child cgroups too), then `/proc/<pid>/stat`, `status`, `cmdline`. At most 200, the main one first, then by memory |
42
+
43
+ The page turns these into a short **needs a look** list for a running service: memory at 90% of its limit or past `MemoryHigh`, restarts, swap in use, threads near their cap, CPU at 90% or more, processes stuck waiting on disk or network (`D`) or left as zombies (`Z`).
44
+
45
+ ## Settings
46
+
47
+ | Variable | Required | What |
48
+ |---|---|---|
49
+ | `MONITOR_DATA_DIR` | **yes** | The folder for `users.json`, `services.json` and `audit.ndjson`. **Must be absolute**: a relative path would read a different user list depending on where the process was started. Created with mode 700 if missing. |
50
+ | `MONITOR_SECRET` | **yes** | Signs the sign-in cookie. At least 32 characters (`openssl rand -base64 48`). Changing it signs everyone out. |
51
+ | `MONITOR_ALLOW` | **yes** | Which services may be added and controlled, comma-separated; `*` matches anything: `xeplr-*` or `xeplr-*,postgresql`. Keep sudoers the same. |
52
+ | `MONITOR_PORT` | no | Default 19400. |
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). |
54
+
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`.
56
+
57
+ ## Install on a server
58
+
59
+ ```bash
60
+ # 1. its own user, its folder, the package
61
+ sudo useradd -r -m -d /var/lib/xeplr-monitor -s /usr/sbin/nologin xeplr-monitor
62
+ sudo npm install -g @xeplr/monitor # puts xeplr-monitor-server and xeplr-monitor-users on PATH
63
+ D=$(npm root -g)/@xeplr/monitor/deploy
64
+
65
+ # 2. settings
66
+ sudo mkdir -p /etc/xeplr-monitor
67
+ sudo cp $D/monitor.env.example /etc/xeplr-monitor/monitor.env
68
+ sudo editor /etc/xeplr-monitor/monitor.env # set MONITOR_SECRET; check MONITOR_ALLOW
69
+ sudo chgrp xeplr-monitor /etc/xeplr-monitor/monitor.env && sudo chmod 640 /etc/xeplr-monitor/monitor.env
70
+
71
+ # 3. what it may do: sudoers for the actions; it reads logs as a member of systemd-journal
72
+ sudo install -m 440 $D/sudoers.example /etc/sudoers.d/xeplr-monitor && sudo visudo -c
73
+
74
+ # 4. the first user (asks for a password, then prints the authenticator secret)
75
+ sudo -u xeplr-monitor env MONITOR_DATA_DIR=/var/lib/xeplr-monitor xeplr-monitor-users add you@xeplr.com --name "Your name"
76
+
77
+ # 5. run it, and put nginx in front
78
+ sudo cp $D/xeplr-monitor.service /etc/systemd/system/
79
+ sudo systemctl daemon-reload && sudo systemctl enable --now xeplr-monitor
80
+ # nginx: see deploy/nginx.conf.example (https, proxy_buffering off for live logs)
81
+ ```
82
+
83
+ Then open the site, sign in, and add the services by their systemd names: `xeplr-bi-dev-api`, `xeplr-bi-dev-auth`, `xeplr-bi-dev-jobs`.
84
+
85
+ The server needs D-Bus (`systemctl` uses it as a non-root user). Every standard Ubuntu server has it.
86
+
87
+ ## Users
88
+
89
+ Users are managed on the server only. The page cannot add a user, so a stolen session cannot add another.
90
+
91
+ ```bash
92
+ xeplr-monitor-users list
93
+ xeplr-monitor-users add <email> [--name "…"] [--no-code]
94
+ xeplr-monitor-users password <email> # signs that user out everywhere
95
+ xeplr-monitor-users code <email> [--off] # a new authenticator secret, or none
96
+ xeplr-monitor-users remove <email>
97
+ ```
98
+
99
+ 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.
100
+
101
+ - **Passwords:** scrypt hashes, at least 12 characters.
102
+ - **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.
103
+ - **Wrong tries:** 5 for one email within 15 minutes lock that email until the 15 minutes from its first wrong try are up. 20 from one address (any emails) lock the address the same way. A right password clears the email's count, not the address's. (`RateLimiter` from `@xeplr/utils`, in memory.) A wrong email and a wrong password get the same answer and take the same time, so the page doesn't reveal which emails exist.
104
+ - **Sessions:** a signed cookie (HMAC-SHA256 with `MONITOR_SECRET`) that lasts 12 hours. It is `HttpOnly`, `SameSite=Strict`, and `Secure` behind https. A changed password or code signs out that user's open sessions.
105
+ - **Request header:** every request that changes something must also carry `x-xeplr-monitor: 1`, which a form on another site cannot add.
106
+
107
+ ## The audit log
108
+
109
+ `audit.ndjson` gets one line per sign-in, per change and per user change made on the server, with who, from which address, what, on which service, and whether it worked. Refused attempts are included. The page shows the newest 300 under **Audit log**.
110
+
111
+ ## API
112
+
113
+ Mounted at `/api`. Everything except `/login` needs a signed-in user.
114
+
115
+ | Method | Path | |
116
+ |---|---|---|
117
+ | POST | `/login` | `{ email, password, code? }` → `{ user }` and the cookie. 401 `{ error, needsCode }` asks for the code; 429 means locked. |
118
+ | POST | `/logout` | |
119
+ | GET | `/me` | `{ user, allowed, self }`: who is signed in, what may be added, and the monitor's own service. |
120
+ | GET | `/services` | Every watched service with `status` (`state`, `subState`, `result`, `pid`, `restarts`, `since`, `exitStatus`, `memoryBytes`, `memoryPeakBytes`, `memoryMaxBytes`, `memoryHighBytes`, `swapBytes`, `cpuSeconds`, `cpuPercent`, `tasks`, `tasksMax`, `enabled`, `restartPolicy`, `runs: { commands: [{ path, command }], workingDirectory, user, unitFile }`) and `processes` (`pid`, `parent`, `name`, `command`, `state`, `memoryBytes`, `swapBytes`, `threads`, `cpuSeconds`, `cpuPercent`, `startedAt`). |
121
+ | POST | `/services` | `{ unit, label? }`. Refused if the name is not allowed (403) or systemd has no such service (404). |
122
+ | PATCH | `/services/:unit` | `{ label?, unit? }`, changed in place. |
123
+ | DELETE | `/services/:unit` | Stops watching it. The service itself is not touched. |
124
+ | POST | `/services/:unit/start` \| `stop` \| `restart` \| `kill` | → `{ unit, status }` afterwards. Kill sends SIGKILL to every process of it; systemd starts it again if it is set to restart. |
125
+ | GET | `/services/:unit/logs` | `?lines=` (max 5000) `&since=&until=` (ISO times) `&grep=` (any case) `&level=warn\|error` → `{ lines: [{ at, level, pid, from, message, cursor }] }`, oldest first. |
126
+ | GET | `/services/:unit/logs/live` | Server-sent events: one `data:` line per new log line, a heartbeat every 15 seconds. |
127
+ | GET | `/audit` | `?limit=` → `{ entries }`, newest first. |
128
+
129
+ Run the whole monitor with `start(config)`. A host built on `createApp` can mount the API itself instead: `init(config)`, then `auth: { middleware: monitor.gate }` and `routes: { '/api': monitor.router() }`. The router needs `createApp`'s body and cookie parsing.
130
+
131
+ ## Development
132
+
133
+ ```bash
134
+ npm test # users, sessions, codes, the API over HTTP; the systemd test on Linux
135
+ npm run build # the page into public/ from @xeplr/ui-monitor
136
+ XEPLR_UI_MONITOR_SRC=../xeplr-ui-monitor/src/index.js npm run build # from a local checkout of it
137
+ ```
138
+
139
+ `test/systemd.test.js` controls a real service. It writes a small unit into `/run/systemd/system`, then adds, starts, follows, searches, restarts, kills, stops and edits it over HTTP. It needs Linux with systemd and passwordless sudo: GitHub's ubuntu runners have both, so CI runs it. Elsewhere it is skipped and says why. To run it on a Mac, use a systemd container:
140
+
141
+ ```bash
142
+ docker run -d --name xm --privileged --cgroupns=host -v /sys/fs/cgroup:/sys/fs/cgroup:rw \
143
+ -v "$PWD":/app --tmpfs /run --tmpfs /run/lock <an ubuntu image with systemd, sudo, dbus and node>
144
+ docker exec -w /app xm sh -c 'node --test test/*.test.js'
145
+ ```
146
+
147
+ **systemd 255** (Ubuntu 24.04) kills the service and then reports that it could not signal its "auxiliary processes", even when it has none. The monitor treats a kill as done when the service really went down, and reports the error otherwise.
package/bin/server.js ADDED
@@ -0,0 +1,19 @@
1
+ #!/usr/bin/env node
2
+ // The monitor on its own: `xeplr-monitor-server`, run by its systemd service
3
+ // (deploy/xeplr-monitor.service). Settings come from the environment; a
4
+ // missing required one stops it here, naming it.
5
+ var { checkEnv } = require('@xeplr/base-apis');
6
+ var monitor = require('../index');
7
+
8
+ checkEnv(monitor.requiredEnv, { appName: 'xeplr-monitor' }); // names each missing one and exits
9
+
10
+ monitor.start({
11
+ dataDir: process.env.MONITOR_DATA_DIR,
12
+ secret: process.env.MONITOR_SECRET,
13
+ allow: process.env.MONITOR_ALLOW,
14
+ sudo: process.env.MONITOR_SUDO,
15
+ port: process.env.MONITOR_PORT
16
+ }).catch(function(err) {
17
+ console.error('[xeplr-monitor] could not start:', err.message);
18
+ process.exit(1);
19
+ });
package/bin/users.js ADDED
@@ -0,0 +1,86 @@
1
+ #!/usr/bin/env node
2
+ // WHO CAN SIGN IN — managed on the server only, never from the page.
3
+ //
4
+ // xeplr-monitor-users list
5
+ // xeplr-monitor-users add <email> [--name "Full name"] [--no-code]
6
+ // xeplr-monitor-users password <email>
7
+ // xeplr-monitor-users code <email> [--off] a new authenticator secret (or none)
8
+ // xeplr-monitor-users remove <email>
9
+ //
10
+ // Reads MONITOR_DATA_DIR. A password is typed, never passed as an argument
11
+ // (it would sit in the shell's history and in `ps`); MONITOR_NEW_PASSWORD is
12
+ // read instead when set, for a script.
13
+ var readline = require('readline');
14
+ var store = require('../lib/store');
15
+ var users = require('../lib/users');
16
+
17
+ var args = process.argv.slice(2);
18
+ var cmd = args[0];
19
+ var email = args[1];
20
+ function flag(name) { return args.indexOf(name) > -1; }
21
+ function option(name) { var i = args.indexOf(name); return i > -1 ? args[i + 1] : undefined; }
22
+
23
+ function ask(question) {
24
+ if (process.env.MONITOR_NEW_PASSWORD) return Promise.resolve(process.env.MONITOR_NEW_PASSWORD);
25
+ return new Promise(function(resolve) {
26
+ var rl = readline.createInterface({ input: process.stdin, output: process.stdout, terminal: true });
27
+ rl.stdoutMuted = true;
28
+ rl._writeToOutput = function(s) { if (!rl.stdoutMuted || /\n/.test(s)) rl.output.write(s.replace(/[^\n]/g, '')); };
29
+ process.stdout.write(question);
30
+ rl.question('', function(answer) { rl.close(); process.stdout.write('\n'); resolve(answer); });
31
+ });
32
+ }
33
+
34
+ async function newPassword() {
35
+ var p = await ask('Password (at least ' + users.MIN_PASSWORD + ' characters): ');
36
+ if (!process.env.MONITOR_NEW_PASSWORD) {
37
+ var again = await ask('Again: ');
38
+ if (again !== p) throw new Error('The two passwords are not the same');
39
+ }
40
+ return p;
41
+ }
42
+
43
+ function showCode(out) {
44
+ if (!out.secret) return console.log('No code asked for when signing in.');
45
+ console.log('\nAdd this to an authenticator app (Google Authenticator, 1Password, Authy):');
46
+ console.log(' secret: ' + out.secret);
47
+ console.log(' or open: ' + out.url + '\n');
48
+ }
49
+
50
+ async function main() {
51
+ store.open(process.env.MONITOR_DATA_DIR);
52
+ if (cmd === 'list') {
53
+ var list = users.list();
54
+ if (!list.length) return console.log('No users yet. Add one: xeplr-monitor-users add <email>');
55
+ list.forEach(function(u) { console.log(u.email + (u.name !== u.email ? ' (' + u.name + ')' : '') + (u.twoStep ? ' · code asked' : ' · password only')); });
56
+ return;
57
+ }
58
+ if (!email || ['add', 'password', 'code', 'remove'].indexOf(cmd) < 0) {
59
+ console.log('xeplr-monitor-users list | add <email> [--name "…"] [--no-code] | password <email> | code <email> [--off] | remove <email>');
60
+ process.exitCode = 1;
61
+ return;
62
+ }
63
+ if (cmd === 'add') {
64
+ var out = users.add(email, await newPassword(), { name: option('--name'), twoStep: !flag('--no-code') });
65
+ store.audit({ email: out.user.email, action: 'user-added', ok: true, by: 'server' });
66
+ console.log('Added ' + out.user.email + '.');
67
+ return showCode(out);
68
+ }
69
+ if (cmd === 'password') {
70
+ users.setPassword(email, await newPassword());
71
+ store.audit({ email: email, action: 'password-changed', ok: true, by: 'server' });
72
+ return console.log('Changed. Every session ' + email + ' had open is signed out.');
73
+ }
74
+ if (cmd === 'code') {
75
+ var c = users.setTwoStep(email, !flag('--off'));
76
+ store.audit({ email: email, action: flag('--off') ? 'code-off' : 'code-new', ok: true, by: 'server' });
77
+ return showCode(c);
78
+ }
79
+ if (cmd === 'remove') {
80
+ users.remove(email);
81
+ store.audit({ email: email, action: 'user-removed', ok: true, by: 'server' });
82
+ return console.log('Removed ' + email + '.');
83
+ }
84
+ }
85
+
86
+ main().catch(function(err) { console.error(err.message); process.exit(1); });
@@ -0,0 +1,16 @@
1
+ # /etc/xeplr-monitor/monitor.env — readable by root and xeplr-monitor only (chmod 640).
2
+
3
+ # Required. Where its users, services and audit log live. Absolute.
4
+ MONITOR_DATA_DIR=/var/lib/xeplr-monitor
5
+
6
+ # Required. Signs the sign-in cookie; at least 32 characters. Make one with:
7
+ # openssl rand -base64 48
8
+ MONITOR_SECRET=
9
+
10
+ # Required. What it may control, comma-separated; * matches anything.
11
+ # sudoers must allow the same (sudoers.example).
12
+ MONITOR_ALLOW=xeplr-*
13
+
14
+ # Optional.
15
+ # MONITOR_PORT=19400 (default 19400)
16
+ # MONITOR_SUDO=actions (actions | all | none — see the README)
@@ -0,0 +1,17 @@
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.
3
+ server {
4
+ listen 443 ssl http2;
5
+ server_name monitor.example.com;
6
+ # ssl_certificate / ssl_certificate_key: as for the other sites (certbot)
7
+
8
+ location / {
9
+ proxy_pass http://127.0.0.1:19400;
10
+ proxy_set_header Host $host;
11
+ proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
12
+ proxy_set_header X-Forwarded-Proto $scheme;
13
+ # A live log is one long answer: no buffering, and kept open.
14
+ proxy_buffering off;
15
+ proxy_read_timeout 1h;
16
+ }
17
+ }
@@ -0,0 +1,13 @@
1
+ # /etc/sudoers.d/xeplr-monitor — install with:
2
+ # sudo install -m 440 sudoers.example /etc/sudoers.d/xeplr-monitor && sudo visudo -c
3
+ #
4
+ # The monitor's user may start, stop, restart and kill the xeplr-* services,
5
+ # without a password, and nothing else: not a shell, not another command.
6
+ # Keep the pattern the same as MONITOR_ALLOW. Add a line per extra pattern
7
+ # (e.g. postgresql) if MONITOR_ALLOW names one.
8
+ #
9
+ # Note: in sudoers a * also matches spaces, so this line alone would let
10
+ # "systemctl stop xeplr-x sshd" through. The monitor never sends that: it
11
+ # passes exactly one name, checked against [A-Za-z0-9@._:-] and MONITOR_ALLOW
12
+ # first (lib/systemd.js unitName, lib/services.js).
13
+ xeplr-monitor ALL=(root) NOPASSWD: /usr/bin/systemctl start xeplr-*, /usr/bin/systemctl stop xeplr-*, /usr/bin/systemctl restart xeplr-*, /usr/bin/systemctl kill --signal=SIGKILL xeplr-*
@@ -0,0 +1,26 @@
1
+ # The monitor itself, as a systemd service. Copy to
2
+ # /etc/systemd/system/xeplr-monitor.service, then:
3
+ # sudo systemctl daemon-reload && sudo systemctl enable --now xeplr-monitor
4
+ #
5
+ # It runs as its own user (xeplr-monitor), not root: sudoers (sudoers.example)
6
+ # lets that user start/stop/restart/kill the allowed services and nothing
7
+ # else; the systemd-journal group lets it read their logs.
8
+ [Unit]
9
+ Description=Xeplr Monitor (status, control and logs of this server's services)
10
+ After=network-online.target
11
+
12
+ [Service]
13
+ Type=simple
14
+ User=xeplr-monitor
15
+ Group=xeplr-monitor
16
+ SupplementaryGroups=systemd-journal
17
+ EnvironmentFile=/etc/xeplr-monitor/monitor.env
18
+ ExecStart=/usr/bin/env xeplr-monitor-server
19
+ Restart=always
20
+ RestartSec=3
21
+ # sudo needs to gain privileges, so NoNewPrivileges stays off; sudoers is the limit.
22
+ ProtectHome=true
23
+ PrivateTmp=true
24
+
25
+ [Install]
26
+ WantedBy=multi-user.target
package/index.js ADDED
@@ -0,0 +1,89 @@
1
+ // @xeplr/monitor — see and control a server's services: status, start, stop,
2
+ // restart, kill, and their logs, live. Its own sign-in, its own files, no
3
+ // database: it is what you open when something else is down.
4
+ //
5
+ // Built on @xeplr/base-apis createApp (the gate, cookies, request lines through
6
+ // @xeplr/logs to stdout, so to the journal; 404 and errors) and @xeplr/utils (authenticator codes, the
7
+ // wrong-try lockout). Neither needs Redis or a database here.
8
+ //
9
+ // init(config) open the store, the secret, the allowed services
10
+ // router() the API (lib/router.js), for a host to mount behind session.gate
11
+ // start(config) init, then serve the API at /api and the page at /
12
+ var path = require('path');
13
+ var fs = require('fs');
14
+ var express = require('express');
15
+ var { createApp } = require('@xeplr/base-apis');
16
+ var store = require('./lib/store');
17
+ var session = require('./lib/session');
18
+ var services = require('./lib/services');
19
+ var systemd = require('./lib/systemd');
20
+ var { createRouter } = require('./lib/router');
21
+
22
+ // What a host must set. Spread into its env.required.js so a missing one
23
+ // fails at startup, naming it, rather than booting a monitor nobody can use.
24
+ var requiredEnv = ['MONITOR_DATA_DIR', 'MONITOR_SECRET', 'MONITOR_ALLOW'];
25
+
26
+ /**
27
+ * @param config { dataDir, secret, allow, sudo? }
28
+ * dataDir absolute folder for users.json, services.json, audit.ndjson, logs/ (MONITOR_DATA_DIR)
29
+ * secret at least 32 characters; signs the sign-in cookie (MONITOR_SECRET)
30
+ * allow the services it may control: ["xeplr-*"] or "xeplr-*,postgresql" (MONITOR_ALLOW)
31
+ * sudo 'actions' (default) | 'all' | 'none' (MONITOR_SUDO)
32
+ */
33
+ function init(config) {
34
+ config = config || {};
35
+ store.open(config.dataDir);
36
+ session.setSecret(config.secret);
37
+ services.setAllowed(config.allow);
38
+ systemd.configure({ sudo: config.sudo || 'actions' });
39
+ }
40
+
41
+ function router() { return createRouter(); }
42
+
43
+ function headers(req, res, next) {
44
+ res.setHeader('X-Frame-Options', 'DENY');
45
+ res.setHeader('X-Content-Type-Options', 'nosniff');
46
+ res.setHeader('Referrer-Policy', 'no-referrer');
47
+ res.setHeader('Content-Security-Policy', "default-src 'self'; style-src 'self' 'unsafe-inline'; img-src 'self' data:; frame-ancestors 'none'");
48
+ next();
49
+ }
50
+
51
+ /** The page (built into public/), with every other path answered by index.html. */
52
+ function pageRouter(dir) {
53
+ var r = express.Router();
54
+ if (!fs.existsSync(path.join(dir, 'index.html'))) return r;
55
+ r.use(express.static(dir, { index: false, maxAge: '1h' }));
56
+ r.get(/^(?!\/api\/).*/, function(req, res) { res.setHeader('Cache-Control', 'no-cache'); res.sendFile(path.join(dir, 'index.html')); });
57
+ return r;
58
+ }
59
+
60
+ /**
61
+ * Serve it: the API at /api, the page everywhere else. → the http server,
62
+ * once listening on its port. nginx is its front door, as for every xeplr
63
+ * service.
64
+ */
65
+ function start(config) {
66
+ config = config || {};
67
+ init(config);
68
+ // 0 is a port too (any free one); only a missing value takes the default.
69
+ var port = config.port === undefined || config.port === null || config.port === '' ? 19400 : Number(config.port);
70
+ var built = createApp(port, 'xeplr-monitor', {
71
+ // Its own sign-in: it must work when @xeplr/auth is down. The headers go in
72
+ // front of it, so a refused request carries them too (createApp's
73
+ // `middleware` runs only after the gate).
74
+ auth: { middleware: function(req, res, next) { headers(req, res, function() { session.gate(req, res, next); }); } },
75
+ corsOptions: { origin: false }, // same-site page only
76
+ log: config.log === false ? false : { logDir: path.join(config.dataDir, 'logs') },
77
+ routes: { '/api': router(), '/': pageRouter(config.publicDir || path.join(__dirname, 'public')) }
78
+ });
79
+ // Behind nginx on the same machine: req.secure and req.ip come from it.
80
+ built.app.set('trust proxy', 'loopback');
81
+ built.app.disable('x-powered-by');
82
+ return new Promise(function(resolve, reject) {
83
+ if (built.server.listening) return resolve(built.server);
84
+ built.server.once('listening', function() { resolve(built.server); });
85
+ built.server.once('error', reject);
86
+ });
87
+ }
88
+
89
+ module.exports = { init: init, router: router, start: start, requiredEnv: requiredEnv, gate: session.gate };
package/lib/router.js ADDED
@@ -0,0 +1,179 @@
1
+ // THE MONITOR'S API — mounted at /api by bin/server.js (or by a host).
2
+ //
3
+ // POST /login { email, password, code? } → the user, and the cookie
4
+ // POST /logout
5
+ // GET /me who is signed in, and what may be added
6
+ // GET /services every watched service with its status and processes now
7
+ // POST /services { unit, label? } — watch one more
8
+ // PATCH /services/:unit { label?, unit? } — changed in place
9
+ // DELETE /services/:unit stop watching it (the service is not touched)
10
+ // POST /services/:unit/:action start | stop | restart | kill
11
+ // GET /services/:unit/logs ?lines=&since=&until=&grep=&level= — oldest first
12
+ // GET /services/:unit/logs/live the log as it is written (server-sent events)
13
+ // GET /audit ?limit= — who did what, newest first
14
+ //
15
+ // Everything but /login needs a signed-in user (lib/session.js); a change also
16
+ // needs the x-xeplr-monitor: 1 header. Every sign-in and every change goes to
17
+ // the audit log, refused ones included. Bodies are parsed, and errors answered
18
+ // as { error }, by @xeplr/base-apis createApp, which this is mounted in.
19
+ var express = require('express');
20
+ var RateLimiter = require('@xeplr/utils/lib/rateLimiter');
21
+ var session = require('./session');
22
+ var users = require('./users');
23
+ var services = require('./services');
24
+ var systemd = require('./systemd');
25
+ var store = require('./store');
26
+
27
+ var LIVE_PER_USER = 10;
28
+ // Wrong sign-ins: 5 for one email, or 20 from one address (any emails; several
29
+ // people share an office network), within 15 minutes, lock it until the 15
30
+ // minutes from the first are up. In memory: a restart clears it, which only
31
+ // ever helps whoever restarted it.
32
+ var LOCK_SECONDS = 15 * 60;
33
+ var FAILS = 5;
34
+ var FAILS_PER_ADDRESS = 20;
35
+ var HEARTBEAT_MS = 15000;
36
+
37
+ function createRouter() {
38
+ var r = express.Router();
39
+ var live = new Map(); // email -> open live logs
40
+ var perEmail = new RateLimiter({ windowInSeconds: LOCK_SECONDS, max: FAILS });
41
+ var perAddress = new RateLimiter({ windowInSeconds: LOCK_SECONDS, max: FAILS_PER_ADDRESS });
42
+
43
+ // An async handler: its result as JSON; its error to createApp's error handler ({ error }, its status).
44
+ function answer(fn) {
45
+ return function(req, res, next) {
46
+ Promise.resolve().then(function() { return fn(req, res); }).then(function(out) {
47
+ if (!res.headersSent) res.json(out === undefined ? { ok: true } : out);
48
+ }).catch(function(err) {
49
+ if (!res.headersSent) next(err);
50
+ });
51
+ };
52
+ }
53
+ function ipOf(req) { return req.ip || (req.socket && req.socket.remoteAddress) || null; }
54
+ function unitOf(req) { return services.get(systemd.unitName(req.params.unit)).unit; }
55
+
56
+ r.post('/login', answer(async function(req, res) {
57
+ var b = req.body || {};
58
+ var email = String(b.email || '').trim().toLowerCase();
59
+ var byEmail = 'monitor:email:' + email;
60
+ var byAddress = 'monitor:ip:' + ipOf(req);
61
+ var wait = Math.max(await perEmail.lockedFor(byEmail), await perAddress.lockedFor(byAddress));
62
+ if (wait) {
63
+ store.audit({ email: email, ip: ipOf(req), action: 'sign-in', ok: false, error: 'locked' });
64
+ var minutes = Math.ceil(wait / 60);
65
+ res.status(429).json({ error: 'Too many wrong tries. Try again in ' + minutes + ' minute' + (minutes === 1 ? '' : 's') });
66
+ return;
67
+ }
68
+ var out = users.check(email, b.password, b.code);
69
+ if (!out.user) {
70
+ // Asking for the code is not a wrong try; a wrong code is.
71
+ if (!(out.needsCode && !b.code)) {
72
+ await perEmail.fail(byEmail);
73
+ await perAddress.fail(byAddress);
74
+ store.audit({ email: email, ip: ipOf(req), action: 'sign-in', ok: false, error: out.problem });
75
+ }
76
+ res.status(401).json({ error: out.problem, needsCode: Boolean(out.needsCode) });
77
+ return;
78
+ }
79
+ await perEmail.reset(byEmail);
80
+ session.start(req, res, out.user);
81
+ store.audit({ email: out.user.email, ip: ipOf(req), action: 'sign-in', ok: true });
82
+ return { user: users.shown(out.user) };
83
+ }));
84
+
85
+ r.post('/logout', function(req, res) {
86
+ var u = session.read(session.cookieOf(req));
87
+ session.end(req, res);
88
+ if (u) store.audit({ email: u.email, ip: ipOf(req), action: 'sign-out', ok: true });
89
+ res.json({ ok: true });
90
+ });
91
+
92
+ r.use(session.required);
93
+
94
+ r.get('/me', function(req, res) {
95
+ res.json({ user: users.shown(req.user), allowed: services.allowedPatterns(), self: systemd.selfUnit() });
96
+ });
97
+
98
+ r.get('/services', answer(async function() {
99
+ var list = services.all();
100
+ var out = await Promise.all(list.map(async function(s) {
101
+ try {
102
+ var st = await systemd.status(s.unit);
103
+ return Object.assign({}, s, { status: st, processes: systemd.processes(st) });
104
+ } catch (e) { return Object.assign({}, s, { status: null, processes: [], statusError: e.message }); }
105
+ }));
106
+ systemd.forgetGone(new Set([].concat.apply([], out.map(function(s) { return s.processes.map(function(p) { return p.pid; }); }))));
107
+ return out;
108
+ }));
109
+
110
+ // A change, recorded whether it worked or not.
111
+ function change(action, fn) {
112
+ return answer(async function(req) {
113
+ var unit = req.params.unit || (req.body && req.body.unit) || null;
114
+ try {
115
+ var out = await fn(req);
116
+ store.audit({ email: req.user.email, ip: ipOf(req), action: action, unit: (out && out.unit) || unit, ok: true });
117
+ return out;
118
+ } catch (err) {
119
+ store.audit({ email: req.user.email, ip: ipOf(req), action: action, unit: unit, ok: false, error: err.message });
120
+ throw err;
121
+ }
122
+ });
123
+ }
124
+
125
+ r.post('/services', change('add', function(req) { return services.add(req.body || {}, req.user.email); }));
126
+ r.patch('/services/:unit', change('edit', function(req) { return services.edit(unitOf(req), req.body || {}, req.user.email); }));
127
+ r.delete('/services/:unit', change('remove', function(req) { services.remove(unitOf(req)); return { unit: req.params.unit }; }));
128
+
129
+ // The action is part of what is recorded, so its handler is made per request.
130
+ r.post('/services/:unit/:action', function(req, res, next) {
131
+ var action = req.params.action;
132
+ return change(action, async function() {
133
+ if (systemd.ACTIONS.indexOf(action) < 0) { var e = new Error('Unknown action "' + action + '": start, stop, restart or kill'); e.status = 400; throw e; }
134
+ var unit = unitOf(req);
135
+ if ((action === 'stop' || action === 'kill') && unit === systemd.selfUnit()) {
136
+ var own = new Error('This is the monitor itself: stopping it would leave nothing to start it again. Restart it instead'); own.status = 400; throw own;
137
+ }
138
+ return { unit: unit, status: await systemd.act(unit, action) };
139
+ })(req, res, next);
140
+ });
141
+
142
+ r.get('/services/:unit/logs', answer(async function(req) {
143
+ var q = req.query || {};
144
+ return { lines: await systemd.logs(unitOf(req), { lines: q.lines, since: q.since, until: q.until, grep: q.grep, level: q.level }) };
145
+ }));
146
+
147
+ r.get('/services/:unit/logs/live', function(req, res) {
148
+ var unit;
149
+ try { unit = unitOf(req); } catch (e) { return res.status(e.status || 400).json({ error: e.message }); }
150
+ var open = live.get(req.user.email) || 0;
151
+ if (open >= LIVE_PER_USER) return res.status(429).json({ error: 'You already have ' + LIVE_PER_USER + ' live logs open. Close one first' });
152
+ live.set(req.user.email, open + 1);
153
+ res.writeHead(200, { 'Content-Type': 'text/event-stream', 'Cache-Control': 'no-cache, no-transform', Connection: 'keep-alive', 'X-Accel-Buffering': 'no' });
154
+ res.write('event: ready\ndata: {}\n\n');
155
+ var stop = systemd.follow(unit, function(line) {
156
+ res.write('data: ' + JSON.stringify(line) + '\n\n');
157
+ }, function(problem) {
158
+ res.write('event: problem\ndata: ' + JSON.stringify({ error: problem }) + '\n\n');
159
+ });
160
+ var beat = setInterval(function() { res.write(': still here\n\n'); }, HEARTBEAT_MS);
161
+ if (beat.unref) beat.unref();
162
+ var closed = false;
163
+ req.on('close', function() {
164
+ if (closed) return;
165
+ closed = true;
166
+ clearInterval(beat);
167
+ stop();
168
+ live.set(req.user.email, Math.max((live.get(req.user.email) || 1) - 1, 0));
169
+ });
170
+ });
171
+
172
+ r.get('/audit', function(req, res) {
173
+ res.json({ entries: store.recentAudit(Math.min(Math.max(parseInt(req.query.limit, 10) || 200, 1), 2000)) });
174
+ });
175
+
176
+ return r;
177
+ }
178
+
179
+ module.exports = { createRouter: createRouter, FAILS: FAILS, FAILS_PER_ADDRESS: FAILS_PER_ADDRESS };