@xeplr/monitor 0.1.3 → 1.0.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (67) hide show
  1. package/README.md +138 -125
  2. package/api/README.md +71 -0
  3. package/api/app.js +46 -0
  4. package/api/bin/auth.js +37 -0
  5. package/api/bin/www +72 -0
  6. package/api/db/setup.js +10 -0
  7. package/api/env.required.js +37 -0
  8. package/api/lib/host.js +188 -0
  9. package/api/lib/jobs.js +83 -0
  10. package/api/lib/services.js +67 -0
  11. package/api/lib/stats.js +362 -0
  12. package/{lib → api/lib}/systemd.js +75 -14
  13. package/api/migrations/0001_monitor.sql +43 -0
  14. package/api/migrations/0002_backup_connections.sql +26 -0
  15. package/api/migrations/0003_settings_audit.sql +18 -0
  16. package/api/migrations/0004_monitor_stats.sql +73 -0
  17. package/api/migrations/README.md +9 -0
  18. package/api/migrations-auth/0006_monitor.sql +56 -0
  19. package/api/migrations-auth/0007_monitor_home.sql +42 -0
  20. package/api/migrations-auth/0008_backups.sql +44 -0
  21. package/api/migrations-auth/0009_app_settings.sql +44 -0
  22. package/api/migrations-auth/0010_monitor_history.sql +22 -0
  23. package/api/models/index.js +18 -0
  24. package/api/package-lock.json +2839 -0
  25. package/api/package.json +39 -0
  26. package/api/production.env.example +61 -0
  27. package/api/routes/appSettings.js +73 -0
  28. package/api/routes/index.js +47 -0
  29. package/api/routes/monitor.js +196 -0
  30. package/api/setup.schema.js +166 -0
  31. package/deploy/control.sh +27 -0
  32. package/deploy/deploy.js +183 -0
  33. package/deploy/install.sh +193 -77
  34. package/deploy/settings.cjs +93 -0
  35. package/package.json +28 -47
  36. package/ui/.env +8 -0
  37. package/ui/README.md +29 -0
  38. package/ui/index.html +13 -0
  39. package/ui/package-lock.json +2094 -0
  40. package/ui/package.json +31 -0
  41. package/ui/pages.json +33 -0
  42. package/ui/public/logo-wide.svg +17 -0
  43. package/ui/public/logo.svg +10 -0
  44. package/ui/src/App.jsx +130 -0
  45. package/ui/src/api/monitor.js +6 -0
  46. package/ui/src/index.css +414 -0
  47. package/ui/src/main.jsx +27 -0
  48. package/ui/src/pages/Connections.jsx +9 -0
  49. package/ui/src/pages/Home.jsx +8 -0
  50. package/ui/src/pages/Monitor.jsx +9 -0
  51. package/ui/vite.config.js +56 -0
  52. package/bin/deploy.js +0 -181
  53. package/bin/server.js +0 -19
  54. package/bin/users.js +0 -86
  55. package/deploy/monitor.env.example +0 -16
  56. package/deploy/nginx.conf.example +0 -18
  57. package/deploy/sudoers.example +0 -13
  58. package/deploy/xeplr-monitor.service +0 -26
  59. package/index.js +0 -89
  60. package/lib/router.js +0 -179
  61. package/lib/services.js +0 -76
  62. package/lib/session.js +0 -78
  63. package/lib/store.js +0 -73
  64. package/lib/users.js +0 -119
  65. package/public/assets/index-BsBYpvNI.js +0 -18
  66. package/public/assets/index-DNZBwVTn.css +0 -1
  67. package/public/index.html +0 -15
package/README.md CHANGED
@@ -1,183 +1,196 @@
1
- # @xeplr/monitor
1
+ # xeplr-monitor
2
2
 
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.
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 what you open when something is down, so it depends on nothing else:
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
- - **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).
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
- The page itself is [`@xeplr/ui-monitor`](https://github.com/Xeplr/xeplr-ui-monitor), built into `public/` and served by this package.
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
- 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.
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 ──▶ 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
+ 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
- - 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.
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
- ## How healthy a service is
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
- All from systemd and `/proc`, read without sudo, every time the list is asked for (the page asks every 5 seconds):
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 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 |
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** 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 |
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
- 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`).
67
+ ## Over time: the history
44
68
 
45
- ## Settings
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
- | Variable | Required | What |
71
+ | Table | One row per | What |
48
72
  |---|---|---|
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). |
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
- 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`.
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
- ## Deploy to a server, from your laptop
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
- ```bash
60
- npx -p @xeplr/monitor xeplr-monitor-deploy
61
- ```
85
+ Read back, by `monitor:view` (`migrations-auth/0010`):
62
86
 
63
- It asks for what it needs, as it goes, and stores nothing: not in this (public) repository, not on your laptop.
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
- - **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.
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
- 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:
95
+ ## Database backups
70
96
 
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.
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
- 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):
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
- ```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
- ```
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
- 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.
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
- Keep the monitor's port closed in the firewall: nginx is the way in.
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
- ## Install on a server by hand
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
- What the deploy does, step by step:
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
- # 1. its own user, its folder, the package
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
- 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`.
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
- The server needs D-Bus (`systemctl` uses it as a non-root user). Every standard Ubuntu server has it.
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
- ## Users
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
- Users are managed on the server only. The page cannot add a user, so a stolen session cannot add another.
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-monitor-users list
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
- 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.
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
- ## The audit log
151
+ ### Every answer as an argument
144
152
 
145
- `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**.
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
- ## API
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
- Mounted at `/api`. Everything except `/login` needs a signed-in user.
157
+ ## Run it locally
150
158
 
151
- | Method | Path | |
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
- npm test # users, sessions, codes, the API over HTTP; the systemd test on Linux
171
- npm run build # the page into public/ from @xeplr/ui-monitor
172
- XEPLR_UI_MONITOR_SRC=../xeplr-ui-monitor/src/index.js npm run build # from a local checkout of it
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
- `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:
172
+ Open http://localhost:19400 and sign in as the Super Admin.
173
+
174
+ ## Tests
176
175
 
177
176
  ```bash
178
- docker run -d --name xm --privileged --cgroupns=host -v /sys/fs/cgroup:/sys/fs/cgroup:rw \
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
- **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.
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
+ }
@@ -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
+ });
@@ -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);