@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.
- package/README.md +138 -125
- package/api/README.md +71 -0
- package/api/app.js +46 -0
- package/api/bin/auth.js +37 -0
- package/api/bin/www +72 -0
- package/api/db/setup.js +10 -0
- package/api/env.required.js +37 -0
- package/api/lib/host.js +188 -0
- package/api/lib/jobs.js +83 -0
- package/api/lib/services.js +67 -0
- package/api/lib/stats.js +362 -0
- package/{lib → api/lib}/systemd.js +75 -14
- package/api/migrations/0001_monitor.sql +43 -0
- package/api/migrations/0002_backup_connections.sql +26 -0
- package/api/migrations/0003_settings_audit.sql +18 -0
- package/api/migrations/0004_monitor_stats.sql +73 -0
- package/api/migrations/README.md +9 -0
- package/api/migrations-auth/0006_monitor.sql +56 -0
- package/api/migrations-auth/0007_monitor_home.sql +42 -0
- package/api/migrations-auth/0008_backups.sql +44 -0
- package/api/migrations-auth/0009_app_settings.sql +44 -0
- package/api/migrations-auth/0010_monitor_history.sql +22 -0
- package/api/models/index.js +18 -0
- package/api/package-lock.json +2839 -0
- package/api/package.json +39 -0
- package/api/production.env.example +61 -0
- package/api/routes/appSettings.js +73 -0
- package/api/routes/index.js +47 -0
- package/api/routes/monitor.js +196 -0
- package/api/setup.schema.js +166 -0
- package/deploy/control.sh +27 -0
- package/deploy/deploy.js +183 -0
- package/deploy/install.sh +193 -77
- package/deploy/settings.cjs +93 -0
- package/package.json +28 -47
- package/ui/.env +8 -0
- package/ui/README.md +29 -0
- package/ui/index.html +13 -0
- package/ui/package-lock.json +2094 -0
- package/ui/package.json +31 -0
- package/ui/pages.json +33 -0
- package/ui/public/logo-wide.svg +17 -0
- package/ui/public/logo.svg +10 -0
- package/ui/src/App.jsx +130 -0
- package/ui/src/api/monitor.js +6 -0
- package/ui/src/index.css +414 -0
- package/ui/src/main.jsx +27 -0
- package/ui/src/pages/Connections.jsx +9 -0
- package/ui/src/pages/Home.jsx +8 -0
- package/ui/src/pages/Monitor.jsx +9 -0
- package/ui/vite.config.js +56 -0
- package/bin/deploy.js +0 -181
- package/bin/server.js +0 -19
- package/bin/users.js +0 -86
- package/deploy/monitor.env.example +0 -16
- package/deploy/nginx.conf.example +0 -18
- package/deploy/sudoers.example +0 -13
- package/deploy/xeplr-monitor.service +0 -26
- package/index.js +0 -89
- package/lib/router.js +0 -179
- package/lib/services.js +0 -76
- package/lib/session.js +0 -78
- package/lib/store.js +0 -73
- package/lib/users.js +0 -119
- package/public/assets/index-BsBYpvNI.js +0 -18
- package/public/assets/index-DNZBwVTn.css +0 -1
- package/public/index.html +0 -15
package/README.md
CHANGED
|
@@ -1,183 +1,196 @@
|
|
|
1
|
-
#
|
|
1
|
+
# xeplr-monitor
|
|
2
2
|
|
|
3
|
-
See and control
|
|
3
|
+
See a server and control its services from a web page. **Home** shows the machine itself: memory in GB (total, used, cache & buffers, free, available, swap, and a bar of how it divides up), CPU (in use, cores, load), every disk (used and free, a bar each), uptime, OS and kernel, and what needs a look. **Monitor** shows each service: whether each one is running and how it is doing (memory against its limit, CPU, threads, every process of it, restarts, why it last stopped, what command it runs), start, stop, restart or kill it, and read its log, live or for a time range, with a search box. **Over time**, for 30 days: each service's memory (with spikes between readings), CPU, requests, response times and its log's warnings and errors, the server's memory and CPU, and the busiest addresses (the Requests tab).
|
|
4
4
|
|
|
5
|
-
It is
|
|
5
|
+
It is a xeplr app, made with [`@xeplr/cli`](https://www.npmjs.com/package/@xeplr/cli): sign-in, users, roles and the permission catalog are [`@xeplr/auth`](https://www.npmjs.com/package/@xeplr/auth) with its own database; the monitor's own tables are in a second database through [`@xeplr/db`](https://www.npmjs.com/package/@xeplr/db); the page is [`@xeplr/ui-monitor`](https://www.npmjs.com/package/@xeplr/ui-monitor) inside a [`@xeplr/ui-account`](https://www.npmjs.com/package/@xeplr/ui-account) shell.
|
|
6
6
|
|
|
7
|
-
|
|
8
|
-
-
|
|
9
|
-
|
|
7
|
+
```
|
|
8
|
+
xeplr-monitor/
|
|
9
|
+
├─ api/ the API (routes/monitor.js) and the sign-in service → api/README.md
|
|
10
|
+
├─ ui/ the React app: the Home and Monitor pages → ui/README.md
|
|
11
|
+
├─ deploy/ deploy.js (the installer: asks, then runs install.sh as root) — run on the server itself
|
|
12
|
+
└─ CLAUDE.md how to change this app
|
|
13
|
+
```
|
|
10
14
|
|
|
11
|
-
|
|
15
|
+
**What it needs to be running:** PostgreSQL and Redis. If either is down, sign-in is too, so the monitor cannot be used to restart those two; everything else it can.
|
|
12
16
|
|
|
13
17
|
## How it works
|
|
14
18
|
|
|
15
|
-
|
|
19
|
+
The apps on our servers run as systemd services (`xeplr-bi-api`, `-auth`, `-jobs`; testbi's `xeplr-bi-dev-*`). The monitor starts nothing itself: it asks `systemctl`, the same way the deploy does, and reads the journal.
|
|
16
20
|
|
|
17
21
|
```
|
|
18
|
-
browser ──https──▶ nginx
|
|
19
|
-
|
|
20
|
-
|
|
21
|
-
|
|
22
|
+
browser ──https──▶ nginx ─┬─ /auth/api/ ─▶ xeplr-monitor-auth (sign-in, port 19401)
|
|
23
|
+
├─ /api/ ─▶ xeplr-monitor-api (port 19402, its own user)
|
|
24
|
+
│ ├─ systemctl show status (no sudo)
|
|
25
|
+
│ ├─ sudo -n xeplr-monitor-control start|stop|restart|kill <unit>
|
|
26
|
+
│ ├─ journalctl -u … -o json [-f] logs (systemd-journal group)
|
|
27
|
+
│ └─ /sys/fs/cgroup, /proc its processes
|
|
28
|
+
└─ / ─▶ ui/dist (the page)
|
|
22
29
|
```
|
|
23
30
|
|
|
24
|
-
-
|
|
25
|
-
- Names are checked (`[A-Za-z0-9@._:-]`) before they reach a command. No shell is ever used
|
|
26
|
-
- **Stop and kill refuse the monitor's own service**, which it finds from its cgroup.
|
|
27
|
-
- A live log is one `journalctl -f`
|
|
28
|
-
- Every
|
|
31
|
+
- **Any systemd service on the server** can be added (a row in `monitor_services`) and, once added, controlled. **Who may is decided by roles** (below), not by a pattern: give the control group only to people trusted with every service, `sshd` and Postgres included. **sudoers allows one command and nothing else**: `/usr/local/libexec/xeplr-monitor-control` (`deploy/control.sh`, root-owned), which takes exactly an action of the four and one plain service name and only then runs `systemctl`. No wildcard in sudoers: newer sudo (`sudo-rs`, Ubuntu's default) refuses one in command arguments, and in classic sudo a `*` also matched spaces.
|
|
32
|
+
- Names are checked (`[A-Za-z0-9@._:-]`) before they reach a command. No shell is ever used.
|
|
33
|
+
- **Stop and kill refuse the monitor's own API service**, which it finds from its cgroup. Restart is allowed.
|
|
34
|
+
- A live log is one `journalctl -f` per open log, ended when the page closes it. At most 10 per person.
|
|
35
|
+
- Every change, refused ones too, is a row in `monitor_audit`: who, from where, what, on which service, whether it worked.
|
|
36
|
+
|
|
37
|
+
## Who may do what
|
|
38
|
+
|
|
39
|
+
Each route checks its own permission (`requireApi` from `@xeplr/base-apis`) against the `apis` rows in `api/migrations-auth/0006_monitor.sql`. Starting grants, changed in the app under **Admin**:
|
|
40
|
+
|
|
41
|
+
| Group | Routes | Roles |
|
|
42
|
+
|---|---|---|
|
|
43
|
+
| `monitor:view` | Home (the server itself), settings, the services with their status and processes, logs, live logs | Super Admin, CompanyAdmin, Admin, Editor, Creator, Viewer |
|
|
44
|
+
| `monitor:control` | start, stop, restart, kill | Super Admin, CompanyAdmin, Admin, Editor |
|
|
45
|
+
| `monitor:manage` | add, edit, remove a watched service | Super Admin, CompanyAdmin, Admin |
|
|
46
|
+
| `monitor:audit` | the audit log | Super Admin, CompanyAdmin, Admin |
|
|
47
|
+
|
|
48
|
+
A route somebody's roles do not include answers 403, and the page says so.
|
|
29
49
|
|
|
30
|
-
|
|
50
|
+
**App settings** (the settings menu, top right) is **Super Admin only**: `settings:app`, three `system`-scope APIs (`api/migrations-auth/0009_app_settings.sql`) that no other role — CompanyAdmin included — is ever given, because they rewrite the whole install. Every setting in `production.env`, changed in place (`@xeplr/ui-setup` on `/api/app-settings`, `@xeplr/setup` `settingsRouter`): secrets show only *set*, `ENCRYPTION_KEY` and `AUTH_JWT_SECRET` can never be changed there, a new database login is signed in to before anything is written, each change is recorded in `settings_audit` (who, when, which names — never values), and both services restart into it (exit 75, `Restart=always`).
|
|
31
51
|
|
|
32
|
-
|
|
52
|
+
## How a service is doing
|
|
53
|
+
|
|
54
|
+
Read without sudo, every time the list is asked for (the page asks every 5 seconds):
|
|
33
55
|
|
|
34
56
|
| | From |
|
|
35
57
|
|---|---|
|
|
36
|
-
| State, since when, why it last ended, exit code, restarts
|
|
37
|
-
| **What runs it**:
|
|
38
|
-
| **Memory** now,
|
|
39
|
-
| **CPU %** since the last reading
|
|
58
|
+
| State, since when, why it last ended, exit code, restarts | `systemctl show`: `ActiveState`, `SubState`, `Result`, `ExecMainStatus`, `NRestarts` |
|
|
59
|
+
| **What runs it**: command line, working folder, user, unit file | `ExecStart`, `WorkingDirectory`, `User`, `FragmentPath` — the command `ps` shows; an environment file's contents are never read |
|
|
60
|
+
| **Memory** now, peak, limit, swap | `MemoryCurrent`, `MemoryPeak` (systemd 255+), `MemoryMax`, `MemoryHigh`, `MemorySwapCurrent` |
|
|
61
|
+
| **CPU %** since the last reading | `CPUUsageNSec`, two readings apart (above 100% is more than one core) |
|
|
40
62
|
| Threads, against `TasksMax` | `TasksCurrent` |
|
|
41
|
-
| **Every process
|
|
63
|
+
| **Every process**: pid, parent, command, memory, swap, CPU %, threads, state, running since | the unit's cgroup, then `/proc/<pid>/stat`, `status`, `cmdline` (at most 200, main first) |
|
|
64
|
+
|
|
65
|
+
The page turns these into a **needs a look** list: memory at 90% of its limit or past `MemoryHigh`, restarts, swap in use, threads near their cap, CPU at 90%+, processes stuck on disk or network (`D`) or zombies (`Z`).
|
|
42
66
|
|
|
43
|
-
|
|
67
|
+
## Over time: the history
|
|
44
68
|
|
|
45
|
-
|
|
69
|
+
Every minute the monitor records a reading of each watched service and of the server, and counts what each service's log said since the last minute. Kept 30 days. `api/lib/stats.js`, tables in `api/migrations/0004_monitor_stats.sql`:
|
|
46
70
|
|
|
47
|
-
|
|
|
71
|
+
| Table | One row per | What |
|
|
48
72
|
|---|---|---|
|
|
49
|
-
| `
|
|
50
|
-
| `
|
|
51
|
-
| `
|
|
52
|
-
| `
|
|
53
|
-
| `
|
|
73
|
+
| `monitor_samples` | service, minute | state, memory, **its peak (`MemoryPeak`) and `spikeBytes` when the peak rose that minute** (a spike between two readings), limit, swap, CPU % over the minute, threads, restarts |
|
|
74
|
+
| `monitor_server_samples` | minute | memory total, used, available, cache & buffers, swap used, CPU %, load |
|
|
75
|
+
| `monitor_log_counts` | service, minute | log lines, warnings (priority 4), errors (0–3) |
|
|
76
|
+
| `monitor_hits` | service, minute, method, address, status | requests, total and slowest time |
|
|
77
|
+
| `monitor_log_reads` | service | where its last read of the journal stopped (the cursor) |
|
|
54
78
|
|
|
55
|
-
|
|
79
|
+
**Who records it: two system jobs of `@xeplr/jobs`** (`api/lib/jobs.js`, `keepSchedule`), no timer of the app's own. They show on the Jobs page, where they can be run or paused, never edited or deleted:
|
|
80
|
+
- **Monitor: record a reading** (`monitor-sample`, every minute): `systemctl show` for each service (CPU over the minute is worked out from this job's own last reading, not from the page's 5-second look), `/proc/meminfo` and `/proc/stat` for the server, and each service's journal from its cursor (`journalctl --after-cursor`, streamed, at most the last hour after a gap). One service failing does not stop the others; the run's output names it.
|
|
81
|
+
- **Monitor: remove old readings** (`monitor-prune`, daily at 03:30): rows older than 30 days, and the record job's own runs older than a day (1,440 runs a day would fill the Jobs page).
|
|
56
82
|
|
|
57
|
-
|
|
83
|
+
**Requests come from each service's own log**: the line `@xeplr/logs` writes for every answered request, `← GET /reports/8fe1a7…/rows 400 73ms` — every xeplr app writes it. The address keeps its path without the query string (a token in one is never stored), and ids become `:id` (hex of 16+, UUIDs, long mixed tokens) or `:n` (numbers), so one address is one row. A service's first 1,000 addresses in a read are kept apart; more count as `(other)`.
|
|
58
84
|
|
|
59
|
-
|
|
60
|
-
npx -p @xeplr/monitor xeplr-monitor-deploy
|
|
61
|
-
```
|
|
85
|
+
Read back, by `monitor:view` (`migrations-auth/0010`):
|
|
62
86
|
|
|
63
|
-
|
|
87
|
+
| Route | Answers |
|
|
88
|
+
|---|---|
|
|
89
|
+
| `GET /api/monitor/services/:unit/history?from=&to=` | per step: memory (highest, average), spike, limit, swap, CPU (highest, average), threads, restarts, readings not running; log lines, warnings, errors; requests, failed (5xx), refused (4xx), average and slowest time |
|
|
90
|
+
| `GET /api/monitor/history?from=&to=` | the server per step: memory total, used (highest, average), least available, cache, swap, CPU, load |
|
|
91
|
+
| `GET /api/monitor/traffic?unit=&from=&to=&limit=` | requests by address over the range, busiest first (at most 1,000) |
|
|
64
92
|
|
|
65
|
-
|
|
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.
|
|
93
|
+
The step fits the range — a minute up to 2 hours, 5 minutes up to a day, 30 minutes up to a week, 2 hours beyond — and each keeps its highest value, so a spike is never averaged away. At most 30 days at a time (the default is the last hour). **Every read is stoppable**: it runs on one held connection (`@xeplr/base-apis` `stoppable`), so closing the page cancels it in Postgres (`pg_cancel_backend`), and Postgres ends it after 30 seconds regardless.
|
|
68
94
|
|
|
69
|
-
|
|
95
|
+
## Database backups
|
|
70
96
|
|
|
71
|
-
|
|
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.
|
|
97
|
+
Backups are [`@xeplr/backups`](https://github.com/Xeplr/xeplr-backups) — the same package any xeplr app can mount — run by this app's `@xeplr/jobs` (`api/lib/jobs.js`). A **job** (`@xeplr/jobs`, the **Jobs** page from `@xeplr/ui-jobs`) backs up one app's databases together: pick a database server, tick its databases, pick an S3 bucket, set the schedule (a cron expression, e.g. `0 2 * * *`), save. Each database is backed up in turn; one failing does not stop the others, and the run fails naming each that did. Run now, the run history and retries are the Jobs page's. For each database, a run (`backup-database`):
|
|
78
98
|
|
|
79
|
-
|
|
99
|
+
1. `db-dump` (`@xeplr/actions`): `pg_dump -Fc` or `mysqldump --single-transaction` into `XEPLR_DATA_DIR`, never through a shell, the password in the program's environment;
|
|
100
|
+
2. `s3-upload`: the file to `s3://<bucket>/<folder>/<server>/<engine>/<database>/<file>` in 16 MB parts, with a SHA-256 checksum (Object Lock needs one);
|
|
101
|
+
3. the local file is deleted, whether the upload worked or not.
|
|
80
102
|
|
|
81
|
-
|
|
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
|
-
```
|
|
103
|
+
**The logins** are on the **Backup connections** page (`ConnectionsPage`, admins only): a database connection is a **server login** (Postgres or MySQL: host, port, user, password) — the job picks the database, from a list read live from that server — and an S3 connection is a bucket, its region, a folder (`backups` or inside it) and an access key. Passwords and keys are encrypted with `ENCRYPTION_KEY` (`@xeplr/utils`) in `backup_connections`, never sent back to a browser, and never in a job: a job holds the connection's id, and the login is filled in only for the run (`resolveConnection`). A connection a job still uses cannot be removed.
|
|
86
104
|
|
|
87
|
-
|
|
105
|
+
**The S3 key should only be able to write**: `s3:PutObject` and `s3:AbortMultipartUpload` on `arn:aws:s3:::<bucket>/backups/*`, from the server's IP only, over HTTPS — nothing to list, read or delete. Old backups go by the bucket's lifecycle rule, and Object Lock keeps each one for its first days even from an admin.
|
|
88
106
|
|
|
89
|
-
|
|
107
|
+
**Folders** (`backup-folder`): a job names folders of **the monitor's own data folder** (`XEPLR_DATA_DIR/xeplr-monitor/…`), comma separated (blank: all of it), and patterns to leave out (`node_modules, *.log`). Each is archived with `tar -czf` (`@xeplr/actions`' `folder-archive`, never through a shell) and uploaded to `<folder>/<server>/xeplr-monitor/folders/<folder>/<name>-<time>.tar.gz`, then deleted locally. A path outside the data folder, `../`, or a link pointing out is refused, and the folder's own `backups/` and `tmp/` are never archived. **An app backs up only its own files**: another app's folders are backed up by that app, mounting `@xeplr/backups` itself.
|
|
90
108
|
|
|
91
|
-
|
|
109
|
+
A file that changes while it is read (a log being written) does not fail the run: `tar` says so, and the run's output keeps the warning.
|
|
92
110
|
|
|
93
|
-
|
|
111
|
+
The deploy installs `pg_dump` and `mysqldump` (`postgresql-client`, `default-mysql-client`) when missing. `pg_dump` must be at least as new as the Postgres it backs up.
|
|
112
|
+
|
|
113
|
+
## Install on a server
|
|
114
|
+
|
|
115
|
+
Run on the server itself, signed in to it as usual. It is on npm as [`@xeplr/monitor`](https://www.npmjs.com/package/@xeplr/monitor), so the server needs to reach npm and nothing else:
|
|
94
116
|
|
|
95
117
|
```bash
|
|
96
|
-
|
|
97
|
-
sudo useradd -r -m -d /var/lib/xeplr-monitor -s /usr/sbin/nologin xeplr-monitor
|
|
98
|
-
sudo npm install -g @xeplr/monitor # puts xeplr-monitor-server and xeplr-monitor-users on PATH
|
|
99
|
-
D=$(npm root -g)/@xeplr/monitor/deploy
|
|
100
|
-
|
|
101
|
-
# 2. settings
|
|
102
|
-
sudo mkdir -p /etc/xeplr-monitor
|
|
103
|
-
sudo cp $D/monitor.env.example /etc/xeplr-monitor/monitor.env
|
|
104
|
-
sudo editor /etc/xeplr-monitor/monitor.env # set MONITOR_SECRET; check MONITOR_ALLOW
|
|
105
|
-
sudo chgrp xeplr-monitor /etc/xeplr-monitor/monitor.env && sudo chmod 640 /etc/xeplr-monitor/monitor.env
|
|
106
|
-
|
|
107
|
-
# 3. what it may do: sudoers for the actions; it reads logs as a member of systemd-journal
|
|
108
|
-
sudo install -m 440 $D/sudoers.example /etc/sudoers.d/xeplr-monitor && sudo visudo -c
|
|
109
|
-
|
|
110
|
-
# 4. the first user (asks for a password, then prints the authenticator secret)
|
|
111
|
-
sudo -u xeplr-monitor env MONITOR_DATA_DIR=/var/lib/xeplr-monitor xeplr-monitor-users add you@xeplr.com --name "Your name"
|
|
112
|
-
|
|
113
|
-
# 5. run it, and put nginx in front
|
|
114
|
-
sudo cp $D/xeplr-monitor.service /etc/systemd/system/
|
|
115
|
-
sudo systemctl daemon-reload && sudo systemctl enable --now xeplr-monitor
|
|
116
|
-
# nginx: see deploy/nginx.conf.example (https, proxy_buffering off for live logs)
|
|
118
|
+
npx -y @xeplr/monitor
|
|
117
119
|
```
|
|
118
120
|
|
|
119
|
-
|
|
121
|
+
There is no remote deploy: the installer installs the machine it runs on, from the copy npx fetched, and fetches nothing else. From a checkout of this repository, `npm install && node deploy/deploy.js` does the same with that checkout.
|
|
122
|
+
|
|
123
|
+
What the server needs first: Linux with systemd and D-Bus, Node.js 20+ and npm **installed system-wide** (`/usr/bin` or `/usr/local/bin`, e.g. NodeSource's package — the services run as their own `xeplr-monitor` user, which cannot run a Node from someone's home folder such as nvm's; the installer uses the system one and stops before changing anything when there is none), Postgres and Redis (on it or reachable from it), and nginx + certbot for a web address. The installer runs `deploy/install.sh` as root: run it as root, or `sudo` asks its password once — before any question, so the install never stops for it.
|
|
124
|
+
|
|
125
|
+
It asks for what it needs as it goes and stores nothing but the app's own settings file:
|
|
120
126
|
|
|
121
|
-
|
|
127
|
+
- **Its ports** (19400: sign-in on 19401, the API on 19402).
|
|
128
|
+
- **Postgres and Redis** it uses: host, port, user, and the passwords (hidden). The Postgres user must be allowed to create databases. An empty database host keeps the login set before — or, on a first install, leaves it to the setup page.
|
|
129
|
+
- **The Super Admin:** email and password (hidden, twice; empty keeps the one set before). More people are added in the app.
|
|
130
|
+
- **Its web address** for nginx (optional), with an https certificate from certbot.
|
|
122
131
|
|
|
123
|
-
|
|
132
|
+
Then it shows what it will do, asks to confirm, and runs `deploy/install.sh` as root with the answers on its input: no value is a file or a command-line argument. The install:
|
|
124
133
|
|
|
125
|
-
|
|
134
|
+
1. makes the `xeplr-monitor` user (in `systemd-journal`) and `/var/lib/xeplr-monitor/logs`;
|
|
135
|
+
2. puts the release in `/opt/xeplr-monitor/releases/<time>`: a copy of the package the installer runs from (without `node_modules` and `.git`), `npm ci` in `api/` and `ui/`, and the page built;
|
|
136
|
+
3. writes `/opt/xeplr-monitor/shared/production.env` (`deploy/settings.cjs`, through the app's own `api/setup.schema.js` and `@xeplr/setup` `prepare()`; owned by the `xeplr-monitor` user, 600, because App settings rewrites it): **`ENCRYPTION_KEY` and `AUTH_JWT_SECRET` are made on the server the first time and kept on every later install**, so nobody is signed out; the database login is encrypted with `@xeplr/utils` and its plain password cleared; an empty Super Admin password on a first install is generated into `shared/FIRST_LOGIN` (never printed). **A missing answer does not fail the install**: with no database login (or no web address for the email links) the API comes up on its **setup page** — `https://<domain>/setup`, or `http://127.0.0.1:19402/setup` on the server, behind the one-time code in `shared/SETUP_CODE` — asks for the rest, and restarts into the app; sign-in waits meanwhile;
|
|
137
|
+
4. creates the two databases if missing and runs the sign-in migrations (users, roles, the monitor's permissions) — after the setup page, the API and the sign-in service make theirs when they start;
|
|
138
|
+
5. installs the control command and writes `/etc/sudoers.d/xeplr-monitor` naming that command alone (checked with `visudo` first), then checks the monitor's user can ask systemd (D-Bus);
|
|
139
|
+
6. switches `/opt/xeplr-monitor/current` to the new release and (re)starts `xeplr-monitor-auth` and `xeplr-monitor-api`, checking both answer — or shows their last log lines;
|
|
140
|
+
7. keeps the newest three releases;
|
|
141
|
+
8. with a web address: writes the nginx site, checks it with `nginx -t`, reloads, and runs certbot when asked.
|
|
142
|
+
|
|
143
|
+
### Updating to a new version
|
|
126
144
|
|
|
127
145
|
```bash
|
|
128
|
-
xeplr
|
|
129
|
-
xeplr-monitor-users add <email> [--name "…"] [--no-code]
|
|
130
|
-
xeplr-monitor-users password <email> # signs that user out everywhere
|
|
131
|
-
xeplr-monitor-users code <email> [--off] # a new authenticator secret, or none
|
|
132
|
-
xeplr-monitor-users remove <email>
|
|
146
|
+
npx -y @xeplr/monitor@latest --update
|
|
133
147
|
```
|
|
134
148
|
|
|
135
|
-
|
|
136
|
-
|
|
137
|
-
- **Passwords:** scrypt hashes, at least 12 characters.
|
|
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.
|
|
139
|
-
- **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.
|
|
140
|
-
- **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.
|
|
141
|
-
- **Request header:** every request that changes something must also carry `x-xeplr-monitor: 1`, which a form on another site cannot add.
|
|
149
|
+
The version is the one npx fetched: `@latest`, or `@xeplr/monitor@1.2.0` for a particular one (`@latest` matters: without it npx may run a copy it already has). Everything else is read from the settings the first install wrote, which are kept as they are, and **nginx and its certificate are left alone**. It installs the new release, runs any new migrations, and restarts the two services, checking both answer. It asks nothing and does not stop to confirm. Before a first install it refuses and says so. To change an answer (a password, the address), run the full install again, or use **App settings** (Super Admin).
|
|
142
150
|
|
|
143
|
-
|
|
151
|
+
### Every answer as an argument
|
|
144
152
|
|
|
145
|
-
|
|
153
|
+
Every value except the passwords can be given as an argument (`--help` lists them); the passwords can come from `XM_DB_PASSWORD`, `XM_REDIS_PASSWORD`, `XM_ADMIN_PASSWORD` for a script. It stops, saying why, when sudo is refused, Node.js 20+ or npm is missing, Postgres refuses, systemd or D-Bus is missing, sudoers is invalid, a service does not answer, or nginx refuses the site.
|
|
146
154
|
|
|
147
|
-
|
|
155
|
+
Keep the ports closed in the firewall (our security group allows only 22, 80 and 443): nginx is the way in.
|
|
148
156
|
|
|
149
|
-
|
|
157
|
+
## Run it locally
|
|
150
158
|
|
|
151
|
-
|
|
152
|
-
|---|---|---|
|
|
153
|
-
| POST | `/login` | `{ email, password, code? }` → `{ user }` and the cookie. 401 `{ error, needsCode }` asks for the code; 429 means locked. |
|
|
154
|
-
| POST | `/logout` | |
|
|
155
|
-
| GET | `/me` | `{ user, allowed, self }`: who is signed in, what may be added, and the monitor's own service. |
|
|
156
|
-
| 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`). |
|
|
157
|
-
| POST | `/services` | `{ unit, label? }`. Refused if the name is not allowed (403) or systemd has no such service (404). |
|
|
158
|
-
| PATCH | `/services/:unit` | `{ label?, unit? }`, changed in place. |
|
|
159
|
-
| DELETE | `/services/:unit` | Stops watching it. The service itself is not touched. |
|
|
160
|
-
| 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. |
|
|
161
|
-
| 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. |
|
|
162
|
-
| GET | `/services/:unit/logs/live` | Server-sent events: one `data:` line per new log line, a heartbeat every 15 seconds. |
|
|
163
|
-
| GET | `/audit` | `?limit=` → `{ entries }`, newest first. |
|
|
164
|
-
|
|
165
|
-
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.
|
|
166
|
-
|
|
167
|
-
## Development
|
|
159
|
+
Needs **PostgreSQL** and **Redis** running. The controls work only on Linux with systemd; on a Mac the page runs and says so.
|
|
168
160
|
|
|
169
161
|
```bash
|
|
170
|
-
|
|
171
|
-
|
|
172
|
-
|
|
162
|
+
cd api && cp production.env.example development.env
|
|
163
|
+
# in development.env: NODE_ENV=development, LOG_DIR=./logs,
|
|
164
|
+
# ENCRYPTION_KEY and AUTH_JWT_SECRET (each: openssl rand -hex 32),
|
|
165
|
+
# AUTH_SUPER_ADMIN_EMAIL / _PASSWORD, the AUTH_*_URL addresses on http://localhost:19400
|
|
166
|
+
npm install && npm run db:encrypt && npm run setup
|
|
167
|
+
npm run start-auth # sign-in http://localhost:19401
|
|
168
|
+
npm run start-api # the API http://localhost:19402
|
|
169
|
+
cd ../ui && npm install && npm run dev # the app http://localhost:19400
|
|
173
170
|
```
|
|
174
171
|
|
|
175
|
-
|
|
172
|
+
Open http://localhost:19400 and sign in as the Super Admin.
|
|
173
|
+
|
|
174
|
+
## Tests
|
|
176
175
|
|
|
177
176
|
```bash
|
|
178
|
-
|
|
179
|
-
-v "$PWD":/app --tmpfs /run --tmpfs /run/lock <an ubuntu image with systemd, sudo, dbus and node>
|
|
180
|
-
docker exec -w /app xm sh -c 'node --test test/*.test.js'
|
|
177
|
+
cd api && npm test
|
|
181
178
|
```
|
|
182
179
|
|
|
183
|
-
|
|
180
|
+
- `test/apiRoleMappings.test.cjs` — the auth catalog built from `migrations-auth`: every route `routes/monitor.js` checks has its `apis` row, every row a group, every group a role besides Super Admin, and the Monitor menu row is the key the side rail uses.
|
|
181
|
+
- `test/systemd.test.cjs` — `lib/systemd` against a real systemd: a small unit written into `/run/systemd/system`, then read (what runs it, memory against its limit, CPU %, its processes), followed, searched, restarted, killed, stopped and started; and `deploy/control.sh` through sudo — refusing a name that is not plain, an option, another action, a second name — then starting, restarting, killing and stopping a service; and `test/host.test.cjs` — the Home page's numbers: memory the way `free` counts it, CPU use from two readings, and on Linux the same figures as `free -b` and `df` on that machine. Needs Linux with systemd and passwordless sudo — GitHub's ubuntu runners have both, so CI runs it; elsewhere it is skipped and says why.
|
|
182
|
+
|
|
183
|
+
- `test/stats.test.cjs` — the history: request lines (ids out, query strings dropped), counts per minute, CPU over the minute and spikes, journal lines; on a real Postgres, a read written with its cursor and the next started from it, the three routes (steps, the spike kept, permission, 30-day limit), pruning, and **leaving the page stops the query in Postgres** (gone from `pg_stat_activity`); on Linux with systemd, a real service's log read from journald, counted, and never counted twice.
|
|
184
|
+
|
|
185
|
+
**systemd 255** (Ubuntu 24.04) kills a service and then reports it could not signal its "auxiliary processes", even when it has none. A kill is treated as done when the service really went down.
|
|
186
|
+
|
|
187
|
+
## Rules this app follows
|
|
188
|
+
|
|
189
|
+
| Rule | Why |
|
|
190
|
+
|---|---|
|
|
191
|
+
| Every route checks its own permission, and has its `apis` row, group and role grants in `migrations-auth`, in the same change. | The catalog is the only place that says who can reach a URL. |
|
|
192
|
+
| sudoers allows one command, which takes one action and one plain name. | No wildcard, no shell, nothing else run as root. |
|
|
193
|
+
| The monitor's tables are real tables (`monitor_services`, `monitor_audit`). | Who watched what and who did what are queries. |
|
|
194
|
+
| No setting for where data lives is defaulted; folders are absolute. | A wrong-but-present value reads as empty data, not as an error. |
|
|
195
|
+
| **`REDIS_PREFIX`** is `xeplr-monitor:`. | Apps sharing a Redis would otherwise serve each other's sessions. |
|
|
196
|
+
| Every data address is under **`/api`**. | A page and a data path never collide. |
|
package/api/README.md
ADDED
|
@@ -0,0 +1,71 @@
|
|
|
1
|
+
# xeplr-monitor — api
|
|
2
|
+
|
|
3
|
+
The API (`@xeplr/base-apis`) with the monitor's routes, and the sign-in service (`@xeplr/auth`).
|
|
4
|
+
|
|
5
|
+
## Commands
|
|
6
|
+
|
|
7
|
+
| Command | Does |
|
|
8
|
+
|---|---|
|
|
9
|
+
| `npm run setup` | create both databases (`xeplr_monitor_auth`, `xeplr_monitor_api`), the sign-in tables, permissions and menus |
|
|
10
|
+
| `npm run start-auth` | the sign-in service, port 19401 — refuses to start without Redis or `REDIS_PREFIX` |
|
|
11
|
+
| `npm run start-api` | the API, port 19402 — runs `migrations/` on start |
|
|
12
|
+
| `npm run migrate:auth` | apply new `migrations-auth/*.sql`, then restart sign-in |
|
|
13
|
+
| `npm run db:encrypt` | redo the encrypted database connection |
|
|
14
|
+
| `npm run check-env` | check every required setting is present |
|
|
15
|
+
| `npm test` | the auth catalog test, and the real-systemd test (Linux) |
|
|
16
|
+
|
|
17
|
+
## Routes — `/api/monitor`, behind the auth gate
|
|
18
|
+
|
|
19
|
+
Each checks its own permission with `requireApi(name)`; the names are the `apis` rows in `migrations-auth/0006_monitor.sql`.
|
|
20
|
+
|
|
21
|
+
| Method | Path | Permission (`apis` row) | |
|
|
22
|
+
|---|---|---|---|
|
|
23
|
+
| GET | `/settings` | View monitor settings | `{ self }`: the API's own unit, which it will not stop or kill |
|
|
24
|
+
| GET | `/host` | View server statistics | the server itself (the Home page): `linux`, `host { name, os, kernel, arch, uptimeSeconds }`, `memory` in bytes, counted the way `free` counts it (`totalBytes`, `usedBytes`, `freeBytes`, `availableBytes`, `buffersBytes`, `cacheBytes`, `sharedBytes`, `swapTotalBytes`, `swapUsedBytes`), `cpu { cores, model, load, usePercent }`, `disks [{ device, mount, type, totalBytes, usedBytes, availableBytes }]` — from `/proc` and `statfs`, no sudo (`lib/host.js`) |
|
|
25
|
+
| GET | `/services` | List monitored services | every watched service with `status` and `processes` (see the root README) |
|
|
26
|
+
| POST | `/services` | Add a monitored service | `{ unit, label? }` — any systemd service on the server; 404 no such service, 409 already there |
|
|
27
|
+
| PATCH | `/services/:unit` | Edit a monitored service | `{ label?, unit? }`, changed in place |
|
|
28
|
+
| DELETE | `/services/:unit` | Remove a monitored service | stops watching it; the service is not touched |
|
|
29
|
+
| POST | `/services/:unit/start` \| `stop` \| `restart` \| `kill` | Start, stop, restart or kill a service | → `{ unit, status }` afterwards |
|
|
30
|
+
| GET | `/services/:unit/logs` | Read service logs | `?lines=` (max 5000) `&since=&until=` (ISO) `&grep=` `&level=warn\|error` → `{ lines }`, oldest first |
|
|
31
|
+
| GET | `/services/:unit/logs/live` | Follow service logs live | server-sent events; read with `authEventStream` (`EventSource` cannot send the token) |
|
|
32
|
+
| GET | `/audit` | Read the monitor audit log | `?limit=` → `{ entries }`, newest first |
|
|
33
|
+
|
|
34
|
+
Errors come back as `{ error }` with their status (`createApp`'s handler).
|
|
35
|
+
|
|
36
|
+
## Layout
|
|
37
|
+
|
|
38
|
+
| Path | What |
|
|
39
|
+
|---|---|
|
|
40
|
+
| `development.env` | every setting, for development — never committed (make it from `production.env.example`; see the root README) |
|
|
41
|
+
| `env.required.js` | the settings that must be present; the API refuses to start and names any that are missing |
|
|
42
|
+
| `app.js` | the Express app: the auth gate, and the routes |
|
|
43
|
+
| `routes/index.js` | `/health` (public), `/whoami`, and `/api/monitor` |
|
|
44
|
+
| `routes/monitor.js` | the monitor's routes, each with `requireApi` |
|
|
45
|
+
| `lib/systemd.js` | status, processes, start/stop/restart/kill, logs, following — `systemctl`, `journalctl`, cgroups and `/proc`, never a shell |
|
|
46
|
+
| `lib/host.js` | the server itself: memory, CPU, disks, uptime |
|
|
47
|
+
| `lib/services.js` | the watched services (`monitor_services`) and the audit log (`monitor_audit`) |
|
|
48
|
+
| `models/` | `MonitoredService`, `MonitorAudit` (`@xeplr/db` `BaseModel`) |
|
|
49
|
+
| `migrations/` | the monitor's tables |
|
|
50
|
+
| `migrations-auth/` | the Monitor menu row, the `apis` rows, their groups and role grants |
|
|
51
|
+
| `test/` | `npm test` |
|
|
52
|
+
|
|
53
|
+
## Settings to know
|
|
54
|
+
|
|
55
|
+
Every one is described in `setup.schema.js` (`@xeplr/setup`): generated (`ENCRYPTION_KEY`, `AUTH_JWT_SECRET`, the first Super Admin password → `FIRST_LOGIN`), worked out (the two encrypted logins from `DB_HOST`/`DB_PORT`/`DB_USER`/`DB_PASSWORD`, the email links from `SERVER_NAME`, `AUTH_URL`, `REDIS_PREFIX`), or asked. Core missing → `bin/www` serves the setup page (`/setup`, code in `SETUP_CODE` beside the env file) and `bin/auth.js` waits; mail (`SMTP_*`) missing → only email is off. After setup, **App settings** (`routes/appSettings.js`, Super Admin only, audited in `settings_audit`, `migrations/0003`) changes them; `bin/auth.js` restarts on the change (`restartOnChange`). Deployed, the file is `/opt/xeplr-monitor/shared/production.env` (`setup.schema.js` finds it from the release layout).
|
|
56
|
+
|
|
57
|
+
|
|
58
|
+
| Setting | |
|
|
59
|
+
|---|---|
|
|
60
|
+
| `MONITOR_CONTROL_COMMAND` | in production, `/usr/local/libexec/xeplr-monitor-control` (the deploy sets it): the one command sudoers allows. Unset in development, where `systemctl` is asked directly |
|
|
61
|
+
| `MONITOR_SUDO` | optional: `actions` (default) runs start/stop/restart/kill through `sudo -n`; `all` reads the journal through sudo too; `none` for root or polkit rights |
|
|
62
|
+
| `REDIS_PREFIX` | **required, unique to this app** (`xeplr-monitor:`) |
|
|
63
|
+
| `DB_HOST`, `DB_PORT`, `DB_USER`, `DB_PASSWORD` | only to make the encrypted logins below (setup page, App settings, the deploy); the password is cleared once encrypted |
|
|
64
|
+
| `SERVER_NAME` | the web address — the email links are built from it when unset |
|
|
65
|
+
| `REDIS_HOST`, `REDIS_PORT`, `REDIS_PASSWORD` | where Redis is |
|
|
66
|
+
| `XEPLR_MONITOR_CONNECTION`, `AUTH_DB_CONNECTION_INFO_ENCRYPTED` | the database, encrypted — `npm run db:encrypt` |
|
|
67
|
+
| `DB_API`, `AUTH_DB_NAME` | the two database names — never guessed |
|
|
68
|
+
| `LOG_DIR` | absolute in production (`/var/lib/xeplr-monitor/logs`) |
|
|
69
|
+
| `AUTH_SUPER_ADMIN_EMAIL` / `_PASSWORD` | the first account — created once, when the sign-in database is first set up |
|
|
70
|
+
| `AUTH_ACTIVATION_URL`, `AUTH_INVITE_URL`, `AUTH_RESET_URL` | the UI pages the emailed links open |
|
|
71
|
+
| `AUTH_REGISTER_ROLES` | the role a new sign-up gets (`Viewer`). Registration needs email (`EMAIL_PROVIDER`); without it, people are added by an admin |
|
package/api/app.js
ADDED
|
@@ -0,0 +1,46 @@
|
|
|
1
|
+
var createApp = require('@xeplr/base-apis/express');
|
|
2
|
+
// ./routes is required in buildApp, not here: it builds @xeplr/jobs' router,
|
|
3
|
+
// which needs the jobs connection — there is none in setup mode.
|
|
4
|
+
var appSettings = require('./routes/appSettings');
|
|
5
|
+
|
|
6
|
+
// No `|| 19402` fallback — the port is required in env.required.js, so a
|
|
7
|
+
// default could only ever fire in a process that skipped that check.
|
|
8
|
+
var port = process.env.XEPLR_MONITOR_PORT;
|
|
9
|
+
|
|
10
|
+
module.exports = buildApp;
|
|
11
|
+
module.exports.setupMode = setupMode;
|
|
12
|
+
|
|
13
|
+
/**
|
|
14
|
+
* Core settings missing (bin/www): NO app — the setup page on this port,
|
|
15
|
+
* served by @xeplr/setup through createApp. → { setupMode: true, ready }
|
|
16
|
+
*/
|
|
17
|
+
function setupMode(setupConfig, invalid) {
|
|
18
|
+
return createApp(port, 'xeplr-monitor_api', { setup: Object.assign({}, setupConfig, { invalid: invalid || [] }) });
|
|
19
|
+
}
|
|
20
|
+
|
|
21
|
+
/**
|
|
22
|
+
* @param {object} [extraRoutes] { '<mountPath>': router }
|
|
23
|
+
* @param {object} [opts] { setup: setup.schema.js config() + { env } } — bin/www
|
|
24
|
+
*/
|
|
25
|
+
function buildApp(extraRoutes, opts) {
|
|
26
|
+
opts = opts || {};
|
|
27
|
+
return createApp(port, 'xeplr-monitor_api', {
|
|
28
|
+
// GET /setup/status (before the gate): which features are off for which
|
|
29
|
+
// setting. bin/www already decided this is not setup mode.
|
|
30
|
+
setup: opts.setup,
|
|
31
|
+
// Every route needs a valid token, checked against the auth service at
|
|
32
|
+
// AUTH_URL. This app names no `middleware` of its own — it takes the
|
|
33
|
+
// framework's gate rather than writing one. Each monitor route then checks
|
|
34
|
+
// its own permission (requireApi, routes/monitor.js).
|
|
35
|
+
auth: {
|
|
36
|
+
// The only exception, and it earns it: a health check has no token to
|
|
37
|
+
// send. Prefixes, so '/health' also covers '/health/anything'.
|
|
38
|
+
publicPaths: ['/health']
|
|
39
|
+
},
|
|
40
|
+
// Absolute in production (the deploy sets it); ./logs only in development.
|
|
41
|
+
log: { logDir: process.env.LOG_DIR || './logs' },
|
|
42
|
+
// /api/app-settings: the Super Admin's App settings page — the env file
|
|
43
|
+
// seen and changed; the app restarts into it (routes/appSettings.js).
|
|
44
|
+
routes: Object.assign({}, extraRoutes || {}, { '/api/app-settings': appSettings(opts.setup), '/': require('./routes') })
|
|
45
|
+
});
|
|
46
|
+
}
|
package/api/bin/auth.js
ADDED
|
@@ -0,0 +1,37 @@
|
|
|
1
|
+
#!/usr/bin/env node
|
|
2
|
+
|
|
3
|
+
// THE SIGN-IN SERVICE — @xeplr/auth does the work; this is its entry point
|
|
4
|
+
// for this app, so it loads its settings the same way bin/www does
|
|
5
|
+
// (<NODE_ENV>.env beside it) and follows the same setup.
|
|
6
|
+
require('dotenv').config({ path: require('path').join(__dirname, '..', (process.env.NODE_ENV || 'development') + '.env') });
|
|
7
|
+
|
|
8
|
+
var path = require('path');
|
|
9
|
+
var setup = require('@xeplr/setup');
|
|
10
|
+
var setupConfig = require('../setup.schema.js').config(path.join(__dirname, '..'));
|
|
11
|
+
|
|
12
|
+
// While the app is being set up (core settings missing — the API serves the
|
|
13
|
+
// setup page) this waits instead of crash-looping, and exits 75 once the env
|
|
14
|
+
// file is complete, so the service manager starts it again.
|
|
15
|
+
var waiting = setup.waitForSetup(setupConfig.schema, process.env, { envFile: setupConfig.envFile, appName: 'auth' });
|
|
16
|
+
|
|
17
|
+
// A change on the App settings page (routes/appSettings.js) restarts this
|
|
18
|
+
// service too: exit 75 when a setting in the env file changes. In production
|
|
19
|
+
// only — there a service manager (deploy/install.sh's xeplr-monitor-auth unit, Restart=always) starts
|
|
20
|
+
// it again; locally nothing would.
|
|
21
|
+
if (!waiting && process.env.NODE_ENV === 'production') {
|
|
22
|
+
setup.restartOnChange({ envFile: setupConfig.envFile, schema: setupConfig.schema, appName: 'auth' });
|
|
23
|
+
}
|
|
24
|
+
|
|
25
|
+
async function start() {
|
|
26
|
+
// The sign-in database, made when missing — after the setup page nobody is
|
|
27
|
+
// there to run `npm run setup`. Then @xeplr/auth migrates it itself.
|
|
28
|
+
var made = await require('@xeplr/db').ensureDatabaseFor(process.env.AUTH_DB_CONNECTION_INFO_ENCRYPTED, process.env.AUTH_DB_NAME);
|
|
29
|
+
if (made && made.created) console.log('[auth] made database ' + process.env.AUTH_DB_NAME);
|
|
30
|
+
await require('@xeplr/auth').boot();
|
|
31
|
+
if (process.send) process.send({ status: 'ready' });
|
|
32
|
+
}
|
|
33
|
+
|
|
34
|
+
if (!waiting) start().catch(function(err) {
|
|
35
|
+
console.error('[auth] startup failed:', err.stack || err.message);
|
|
36
|
+
process.exit(1);
|
|
37
|
+
});
|
package/api/bin/www
ADDED
|
@@ -0,0 +1,72 @@
|
|
|
1
|
+
#!/usr/bin/env node
|
|
2
|
+
|
|
3
|
+
require('dotenv').config({ path: require('path').join(__dirname, '..', (process.env.NODE_ENV || 'development') + '.env') });
|
|
4
|
+
|
|
5
|
+
var path = require('path');
|
|
6
|
+
var setup = require('@xeplr/setup');
|
|
7
|
+
|
|
8
|
+
// A MISSING SETTING NEVER STOPS THIS PROCESS (@xeplr/setup, setup.schema.js).
|
|
9
|
+
// Core settings missing, or set but unusable (an encrypted login this
|
|
10
|
+
// ENCRYPTION_KEY cannot read) → SETUP MODE: no app, no migrations — the setup
|
|
11
|
+
// page on this API's port (/setup, behind the one-time code in SETUP_CODE
|
|
12
|
+
// beside the env file), which writes the env file and exits 75 so systemd
|
|
13
|
+
// starts this again as the app. Locally, `npm run db:encrypt` fills the
|
|
14
|
+
// database login from the terminal instead.
|
|
15
|
+
// Only a feature's settings missing (email) → the app runs with it off.
|
|
16
|
+
var setupConfig = require('../setup.schema.js').config(path.join(__dirname, '..'));
|
|
17
|
+
var bootEnv = Object.assign({}, process.env);
|
|
18
|
+
var envState = require('@xeplr/base-apis').checkEnv(require('../env.required.js'), { appName: 'api', setup: setupConfig.schema });
|
|
19
|
+
|
|
20
|
+
var { resolveConfig } = require('@xeplr/db');
|
|
21
|
+
var { up } = require('@xeplr/db').sqlMigrator;
|
|
22
|
+
|
|
23
|
+
async function start() {
|
|
24
|
+
// Set, but unusable? Core values this process cannot use mean setup mode too.
|
|
25
|
+
var invalid = envState.setupMode ? [] : (await setup.verify(setupConfig.schema, process.env)).filter(function(p) { return !p.feature; });
|
|
26
|
+
if (envState.setupMode || invalid.length) {
|
|
27
|
+
if (!envState.setupMode) console.warn('[api] ' + invalid.map(function(p) { return p.name + ': ' + p.reason; }).join('; ') + ' — starting in setup mode');
|
|
28
|
+
var ready = await require('../app').setupMode(setupConfig, invalid).ready;
|
|
29
|
+
console.warn('[api] SETUP MODE on port ' + process.env.XEPLR_MONITOR_PORT + ': open /setup — the code is in ' + ready.codeFile);
|
|
30
|
+
return;
|
|
31
|
+
}
|
|
32
|
+
|
|
33
|
+
// WHICH PRODUCT THIS IS. Fixed here, at boot — never from a request.
|
|
34
|
+
require('@xeplr/db').registerApplication('xeplr-monitor');
|
|
35
|
+
|
|
36
|
+
// Name the connection before anything uses it — the migrator resolves by
|
|
37
|
+
// name from a registry that getConnection does not populate.
|
|
38
|
+
var resolved = await resolveConfig('api', process.env.XEPLR_MONITOR_CONNECTION);
|
|
39
|
+
|
|
40
|
+
// This app's database, made when missing — after the setup page nobody runs
|
|
41
|
+
// the installer's create-db step (the login needs CREATEDB).
|
|
42
|
+
var made = await require('@xeplr/db').ensureDatabaseFor(resolved, process.env.DB_API);
|
|
43
|
+
if (made && made.created) console.log('[api] made database ' + process.env.DB_API);
|
|
44
|
+
|
|
45
|
+
// Migrations run ON BOOT, so starting the API is the only thing anyone has
|
|
46
|
+
// to remember. Already-applied ones are skipped.
|
|
47
|
+
//
|
|
48
|
+
// This app's tables (migrations/: the monitor's services and audit log).
|
|
49
|
+
var result = await up({
|
|
50
|
+
db: process.env.DB_API,
|
|
51
|
+
dir: path.join(__dirname, '..', 'migrations'),
|
|
52
|
+
connectionName: 'api'
|
|
53
|
+
});
|
|
54
|
+
console.log(result.migrations.length
|
|
55
|
+
? '[api] ran ' + result.migrations.length + ' migrations'
|
|
56
|
+
: '[api] migrations up to date');
|
|
57
|
+
|
|
58
|
+
// AWAITED before the app is built: the models have no connection at all
|
|
59
|
+
// until this has finished.
|
|
60
|
+
await require('../db/setup');
|
|
61
|
+
|
|
62
|
+
// BACKUPS — @xeplr/jobs in its own database (DB_JOBS) with @xeplr/backups'
|
|
63
|
+
// actions: the jobs set on the Jobs page, run on their schedules (lib/jobs.js).
|
|
64
|
+
await require('../lib/jobs').start();
|
|
65
|
+
|
|
66
|
+
require('../app')(null, { setup: Object.assign({}, setupConfig, { env: bootEnv }) });
|
|
67
|
+
}
|
|
68
|
+
|
|
69
|
+
start().catch(function(err) {
|
|
70
|
+
console.error('[api] startup failed:', err.stack || err.message);
|
|
71
|
+
process.exit(1);
|
|
72
|
+
});
|
package/api/db/setup.js
ADDED
|
@@ -0,0 +1,10 @@
|
|
|
1
|
+
// One call: decrypt the connection, connect to this app's own database, and
|
|
2
|
+
// wire the models to it. Exports the connection promise, awaited by callers
|
|
3
|
+
// that need it ready.
|
|
4
|
+
var { getConnection } = require('@xeplr/db');
|
|
5
|
+
|
|
6
|
+
// No `|| 'xeplr_monitor_api'` fallback. DB_API is required at startup
|
|
7
|
+
// (env.required.js), so a default could only ever fire in a process that
|
|
8
|
+
// skipped that check — and silently connecting to a database nobody named is
|
|
9
|
+
// exactly what the check exists to prevent.
|
|
10
|
+
module.exports = getConnection(process.env.DB_API, process.env.XEPLR_MONITOR_CONNECTION);
|