@xeplr/monitor 0.1.3 → 1.0.0

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 +177 -77
  34. package/deploy/settings.cjs +93 -0
  35. package/package.json +28 -47
  36. package/ui/.env +8 -0
  37. package/ui/README.md +29 -0
  38. package/ui/index.html +13 -0
  39. package/ui/package-lock.json +2094 -0
  40. package/ui/package.json +31 -0
  41. package/ui/pages.json +33 -0
  42. package/ui/public/logo-wide.svg +17 -0
  43. package/ui/public/logo.svg +10 -0
  44. package/ui/src/App.jsx +130 -0
  45. package/ui/src/api/monitor.js +6 -0
  46. package/ui/src/index.css +414 -0
  47. package/ui/src/main.jsx +27 -0
  48. package/ui/src/pages/Connections.jsx +9 -0
  49. package/ui/src/pages/Home.jsx +8 -0
  50. package/ui/src/pages/Monitor.jsx +9 -0
  51. package/ui/vite.config.js +56 -0
  52. package/bin/deploy.js +0 -181
  53. package/bin/server.js +0 -19
  54. package/bin/users.js +0 -86
  55. package/deploy/monitor.env.example +0 -16
  56. package/deploy/nginx.conf.example +0 -18
  57. package/deploy/sudoers.example +0 -13
  58. package/deploy/xeplr-monitor.service +0 -26
  59. package/index.js +0 -89
  60. package/lib/router.js +0 -179
  61. package/lib/services.js +0 -76
  62. package/lib/session.js +0 -78
  63. package/lib/store.js +0 -73
  64. package/lib/users.js +0 -119
  65. package/public/assets/index-BsBYpvNI.js +0 -18
  66. package/public/assets/index-DNZBwVTn.css +0 -1
  67. package/public/index.html +0 -15
@@ -0,0 +1,39 @@
1
+ {
2
+ "name": "@xeplr-monitor/api",
3
+ "version": "1.0.0",
4
+ "private": true,
5
+ "license": "UNLICENSED",
6
+ "description": "xeplr-monitor backend — @xeplr/base-apis app.",
7
+ "main": "app.js",
8
+ "scripts": {
9
+ "check-env": "dotenv -e development.env -- xeplr-check-env",
10
+ "setup": "npm run db:create && npm run db:create:api && npm run migrate:auth",
11
+ "db:encrypt": "xeplr encrypt",
12
+ "db:create": "dotenv -e development.env -- xeplr-migrate create-db --connectionName auth --connection-env AUTH_DB_CONNECTION_INFO_ENCRYPTED --db-env AUTH_DB_NAME",
13
+ "db:create:api": "dotenv -e development.env -- xeplr-migrate create-db --connectionName api --connection-env XEPLR_MONITOR_CONNECTION --db-env DB_API",
14
+ "migrate:auth": "dotenv -e development.env -- xeplr-auth-migrate up --connection-env AUTH_DB_CONNECTION_INFO_ENCRYPTED",
15
+ "migrate:up": "dotenv -e development.env -- xeplr-migrate up --dir ./migrations --connectionName api --connection-env XEPLR_MONITOR_CONNECTION",
16
+ "start-auth": "node ./bin/auth.js",
17
+ "start-api": "node ./bin/www",
18
+ "test": "node --test test/*.test.cjs"
19
+ },
20
+ "dependencies": {
21
+ "@aws-sdk/client-s3": "^3.1168.0",
22
+ "@aws-sdk/lib-storage": "^3.1168.0",
23
+ "@xeplr/actions": "^2.2.4",
24
+ "@xeplr/auth": "^1.3.0",
25
+ "@xeplr/backups": "^0.1.1",
26
+ "@xeplr/base-apis": "^3.1.3",
27
+ "@xeplr/db": "^1.1.0",
28
+ "@xeplr/jobs": "^3.2.0",
29
+ "@xeplr/setup": "^0.2.0",
30
+ "@xeplr/utils": "^1.0.11",
31
+ "dotenv": "^17.4.2",
32
+ "express": "^5.2.0",
33
+ "mysql2": "^3.24.6"
34
+ },
35
+ "devDependencies": {
36
+ "@xeplr/cli": "^0.1.8",
37
+ "dotenv-cli": "^8.0.0"
38
+ }
39
+ }
@@ -0,0 +1,61 @@
1
+ # xeplr-monitor API — PRODUCTION settings: every name, no values. The installer
2
+ # (deploy/deploy.js, run on the server) writes the real file on the server, at
3
+ # /opt/xeplr-monitor/shared/production.env, making the secrets there and
4
+ # keeping them on later deploys; the services read it (EnvironmentFile).
5
+ # Never committed (.gitignore).
6
+
7
+ NODE_ENV=production
8
+ # Absolute: a relative folder depends on where the process started.
9
+ LOG_DIR=/var/lib/xeplr-monitor/logs
10
+
11
+ # ── Ports: one per process on this server ──
12
+ XEPLR_MONITOR_PORT=19402
13
+ AUTH_PORT=19401
14
+
15
+ # Blank or missing values are not a failed deploy: api/setup.schema.js makes
16
+ # the secrets, encrypts the login from DB_HOST/DB_PASSWORD (then clears the
17
+ # password), and the API's setup page (/setup, code in SETUP_CODE) asks for the rest.
18
+
19
+ # ── Databases (same server, one login, encrypted with ENCRYPTION_KEY) ──
20
+ # Only to make the two logins below:
21
+ DB_HOST=
22
+ DB_PORT=5432
23
+ DB_USER=
24
+ DB_PASSWORD=
25
+ ENCRYPTION_KEY=
26
+ XEPLR_MONITOR_CONNECTION=
27
+ AUTH_DB_CONNECTION_INFO_ENCRYPTED=
28
+ DB_API=xeplr_monitor_api
29
+ AUTH_DB_NAME=xeplr_monitor_auth
30
+ # The backup jobs' own database (@xeplr/jobs).
31
+ DB_JOBS=xeplr_monitor_jobs
32
+ # Where a dump is written before it goes to S3 (absolute; deleted after).
33
+ XEPLR_DATA_DIR=/var/lib/xeplr-monitor/data
34
+
35
+ # ── Redis (sign-in sessions and permissions) ──
36
+ REDIS_HOST=127.0.0.1
37
+ REDIS_PORT=6379
38
+ REDIS_PASSWORD=
39
+ REDIS_PREFIX=xeplr-monitor:
40
+
41
+ # ── Sign-in ──
42
+ AUTH_JWT_SECRET=
43
+ # Where THIS server reaches the sign-in service (not the public address).
44
+ AUTH_URL=http://127.0.0.1:19401
45
+ XEPLR_AUTH_MIGRATIONS=./migrations-auth,./node_modules/@xeplr/jobs/migrations-auth,./node_modules/@xeplr/backups/migrations-auth
46
+ AUTH_SUPER_ADMIN_EMAIL=
47
+ AUTH_SUPER_ADMIN_PASSWORD=
48
+ AUTH_TENANT_HEADER=none
49
+ AUTH_REGISTER_ROLES=Viewer
50
+
51
+ # ── Public addresses (what people's browsers open) ──
52
+ # The links below are built from it when unset.
53
+ SERVER_NAME=monitor.example.com
54
+ AUTH_ACTIVATION_URL=https://monitor.example.com/auth/activate
55
+ AUTH_INVITE_URL=https://monitor.example.com/auth/accept-invite
56
+ AUTH_RESET_URL=https://monitor.example.com/auth/reset-password
57
+
58
+ # ── How the monitor controls services ──
59
+ # The one command sudoers allows (deploy/control.sh, installed by the deploy).
60
+ MONITOR_CONTROL_COMMAND=/usr/local/libexec/xeplr-monitor-control
61
+ # MONITOR_SUDO=actions (actions | all | none — how it asks systemd; see the README)
@@ -0,0 +1,73 @@
1
+ // THE APP'S OWN SETTINGS (settings menu → App settings) — the install's env
2
+ // file seen and changed after setup; the app restarts into the change.
3
+ //
4
+ // GET /api/app-settings every setting, grouped Core / each feature;
5
+ // secrets only "set"
6
+ // POST /api/app-settings/check { values } — refusals + the live database
7
+ // login check, nothing written
8
+ // POST /api/app-settings { values } — save, audit, answer, restart (exit 75)
9
+ //
10
+ // SUPER ADMIN ONLY, twice over: requireApi (the apis rows of
11
+ // migrations-auth/0009, mapped to Super Admin alone, scope 'system') and the
12
+ // role itself checked here (superAdminOnly below) — this route rewrites the
13
+ // whole install's settings for everyone on it.
14
+ //
15
+ // WHAT may be changed is @xeplr/setup's settingsRouter and the schema
16
+ // (setup.schema.js): the same refusals and checks as the setup page. What
17
+ // lives here: who may, and the audit row (settings_audit, migrations/0003) —
18
+ // setting NAMES only, never values. A change that cannot be recorded is not
19
+ // saved: the library puts the file back.
20
+ var express = require('express');
21
+ var crypto = require('crypto');
22
+ var setup = require('@xeplr/setup');
23
+ var { requireApi } = require('@xeplr/base-apis');
24
+
25
+ var SUPER_ADMIN = 'Super Admin';
26
+ function superAdminOnly(req, res, next) {
27
+ var roles = (req.access && req.access.roles) || (req.user && req.user.roles) || [];
28
+ if (roles.indexOf(SUPER_ADMIN) !== -1) return next();
29
+ res.status(403).json({ code: 'SYSTEM_SCOPE', error: 'Only the Super Admin can see or change the app\'s settings.' });
30
+ }
31
+
32
+ var API = {
33
+ view: 'View app settings',
34
+ check: 'Check app settings',
35
+ save: 'Save app settings'
36
+ };
37
+
38
+ /** One audit row. Install-wide: no tenant columns. */
39
+ async function audit(change, req) {
40
+ var knex = await require('../db/setup');
41
+ await knex('settings_audit').insert({
42
+ id: crypto.randomBytes(12).toString('hex'),
43
+ userId: (req.user && req.user.id) || null,
44
+ userEmail: (req.user && req.user.email) || change.who || null,
45
+ names: JSON.stringify(change.names),
46
+ changedAt: new Date(change.at)
47
+ });
48
+ }
49
+
50
+ /**
51
+ * @param {object} cfg setup.schema.js config() + { env } (the env as bin/www found it)
52
+ * @param {object} [opts] { envFile, onRestart, restartDelayMs } — tests only
53
+ */
54
+ module.exports = function appSettingsRoutes(cfg, opts) {
55
+ opts = opts || {};
56
+ var router = express.Router();
57
+ if (!cfg) return router; // built without setup (a test app): no settings screen
58
+ var handler = setup.settingsRouter({
59
+ schema: cfg.schema,
60
+ envFile: opts.envFile || cfg.envFile,
61
+ env: cfg.env,
62
+ // RestartSec=3 in deploy/install.sh's units, then migrations and the boot.
63
+ restartSeconds: 20,
64
+ restartDelayMs: opts.restartDelayMs,
65
+ onRestart: opts.onRestart,
66
+ onChange: audit
67
+ });
68
+ router.get('/', requireApi(API.view), superAdminOnly, handler);
69
+ router.post('/check', requireApi(API.check), superAdminOnly, handler);
70
+ router.post('/', requireApi(API.save), superAdminOnly, handler);
71
+ return router;
72
+ };
73
+ module.exports.API = API;
@@ -0,0 +1,47 @@
1
+ var express = require('express');
2
+
3
+ var router = express.Router();
4
+
5
+ // PUBLIC — listed in app.js's auth.publicPaths. Whatever polls this has never
6
+ // signed in, so it has no token to send. It reports liveness and nothing else.
7
+ router.get('/health', function(req, res) {
8
+ res.json({ status: 'ok' });
9
+ });
10
+
11
+ // GATED, like everything not named public.
12
+ router.get('/', function(req, res) {
13
+ res.json({ service: 'api', status: 'running', name: 'xeplr-monitor-api' });
14
+ });
15
+
16
+ // Who is calling, and what they are allowed to reach. Both were put on the
17
+ // request by the auth gate, so this makes no call of its own.
18
+ router.get('/whoami', function(req, res) {
19
+ res.json({ user: req.user, roles: (req.access || {}).roles || [] });
20
+ });
21
+
22
+ // ── the monitor ──────────────────────────────────────────────────────────
23
+ //
24
+ // MOUNTED UNDER /api, and that prefix matters: the UI's dev server forwards
25
+ // /api to this API and serves every other path as a page.
26
+ //
27
+ // The server's services — their state, processes and logs, and start / stop /
28
+ // restart / kill (routes/monitor.js).
29
+ // The logins the backups use (@xeplr/backups' router): the Backup connections
30
+ // page and the jobs' dropdowns. Each route checked by this app's requireApi;
31
+ // each change in the monitor's audit log, by the connection's name.
32
+ var { requireApi } = require('@xeplr/base-apis');
33
+ var services = require('../lib/services');
34
+ router.use('/api/monitor/connections', require('@xeplr/backups').router({
35
+ requireApi: requireApi,
36
+ audit: function(e) { return services.audit({ email: e.email, ip: e.ip, action: e.action, unit: 'connection: ' + e.name, ok: e.ok, error: e.error }); }
37
+ }));
38
+ router.use('/api/monitor', require('./monitor'));
39
+
40
+ // The backup jobs (@xeplr/jobs, lib/jobs.js): /api/jobs, /api/job-occurrences,
41
+ // /api/actions — the Jobs page of @xeplr/ui-jobs. Each operation checked
42
+ // against jobs' own apis rows (node_modules/@xeplr/jobs/migrations-auth).
43
+ router.use('/api', require('@xeplr/jobs').router({
44
+ auth: { list: requireApi('List jobs'), getById: requireApi('Get job'), save: requireApi('Save job'), delete: requireApi('Delete job') }
45
+ }));
46
+
47
+ module.exports = router;
@@ -0,0 +1,196 @@
1
+ // THE MONITOR'S ROUTES — at /api/monitor, behind createApp's auth gate.
2
+ //
3
+ // GET /settings the API's own unit (which it will not stop or kill)
4
+ // GET /host the server itself: memory, CPU, disks, uptime (the Home page)
5
+ // GET /services every watched service with its status and processes now
6
+ // POST /services { unit, label? } — watch one more
7
+ // PATCH /services/:unit { label?, unit? } — changed in place
8
+ // DELETE /services/:unit stop watching it (the service is not touched)
9
+ // POST /services/:unit/:action start | stop | restart | kill
10
+ // GET /services/:unit/logs ?lines=&since=&until=&grep=&level= — oldest first
11
+ // GET /services/:unit/logs/live the log as it is written (server-sent events)
12
+ // GET /audit ?limit= — who did what, newest first
13
+ // GET /services/:unit/history ?from=&to= — memory, CPU, spikes, log counts, requests over time
14
+ // GET /history ?from=&to= — the server's memory and CPU over time
15
+ // GET /traffic ?unit=&from=&to=&limit= — requests by address, the busiest first
16
+ //
17
+ // The history is what lib/stats.js recorded each minute (the monitor-sample
18
+ // job); its reads are stoppable — leaving the page cancels them in Postgres.
19
+ //
20
+ // Each route checks its own permission (requireApi): the names are the `apis`
21
+ // rows in migrations-auth/0006_monitor.sql, granted to roles there. Every
22
+ // change is written to monitor_audit, refused ones included.
23
+ var express = require('express');
24
+ var { requireApi } = require('@xeplr/base-apis');
25
+ var systemd = require('../lib/systemd');
26
+ var services = require('../lib/services');
27
+ var host = require('../lib/host');
28
+ var stats = require('../lib/stats');
29
+ var { stoppable } = require('@xeplr/base-apis').genericController;
30
+
31
+ // The `apis` rows these routes are checked against — the same names as
32
+ // migrations-auth/0006_monitor.sql. Changing one here means changing it there.
33
+ var API = {
34
+ settings: 'View monitor settings',
35
+ host: 'View server statistics',
36
+ list: 'List monitored services',
37
+ logs: 'Read service logs',
38
+ live: 'Follow service logs live',
39
+ control: 'Start, stop, restart or kill a service',
40
+ add: 'Add a monitored service',
41
+ edit: 'Edit a monitored service',
42
+ remove: 'Remove a monitored service',
43
+ audit: 'Read the monitor audit log',
44
+ history: 'View service history',
45
+ serverHistory: 'View server history',
46
+ traffic: 'View service requests'
47
+ };
48
+
49
+ // A read of the history on one held connection: the person leaving the page
50
+ // cancels it in Postgres; Postgres ends it at the time limit regardless.
51
+ function history(fn) {
52
+ return async function(req, res, next) {
53
+ var stopper = null;
54
+ try {
55
+ stopper = await stoppable(req, res, require('../models').MonitoredService.knex(), 30000);
56
+ var out = await fn(req, stopper);
57
+ if (!res.headersSent) res.json(out);
58
+ } catch (err) {
59
+ if (stopper && stopper.stopped()) return; // nobody is waiting
60
+ if (!res.headersSent) next(err);
61
+ } finally {
62
+ if (stopper) await stopper.release();
63
+ }
64
+ };
65
+ }
66
+
67
+ // How it asks systemd, read once at startup.
68
+ // MONITOR_CONTROL_COMMAND: the root-owned command sudoers allows (the deploy
69
+ // installs deploy/control.sh there); unset in development, where systemctl is
70
+ // asked directly.
71
+ systemd.configure({ sudo: process.env.MONITOR_SUDO || 'actions', control: process.env.MONITOR_CONTROL_COMMAND || null });
72
+
73
+ var LIVE_PER_USER = 10;
74
+ var HEARTBEAT_MS = 15000;
75
+
76
+ var router = express.Router();
77
+ var live = new Map(); // who -> open live logs
78
+
79
+ function who(req) { return (req.user && (req.user.email || req.user.id)) || 'unknown'; }
80
+ function ipOf(req) { return req.ip || (req.socket && req.socket.remoteAddress) || null; }
81
+
82
+ // An async handler: its result as JSON; its error to createApp's error handler ({ error }, its status).
83
+ function answer(fn) {
84
+ return function(req, res, next) {
85
+ Promise.resolve().then(function() { return fn(req, res); }).then(function(out) {
86
+ if (!res.headersSent) res.json(out === undefined ? { ok: true } : out);
87
+ }).catch(function(err) { if (!res.headersSent) next(err); });
88
+ };
89
+ }
90
+
91
+ // A change, recorded in the audit log whether it worked or not.
92
+ function change(action, fn) {
93
+ return answer(async function(req) {
94
+ var unit = req.params.unit || (req.body && req.body.unit) || null;
95
+ try {
96
+ var out = await fn(req);
97
+ await services.audit({ email: who(req), ip: ipOf(req), action: action, unit: (out && out.unit) || unit, ok: true });
98
+ return out;
99
+ } catch (err) {
100
+ await services.audit({ email: who(req), ip: ipOf(req), action: action, unit: unit, ok: false, error: err.message });
101
+ throw err;
102
+ }
103
+ });
104
+ }
105
+
106
+ async function unitOf(req) { return (await services.get(systemd.unitName(req.params.unit))).unit; }
107
+
108
+ router.get('/settings', requireApi(API.settings), function(req, res) {
109
+ res.json({ self: systemd.selfUnit() });
110
+ });
111
+
112
+ router.get('/host', requireApi(API.host), function(req, res) {
113
+ res.json(host.stats());
114
+ });
115
+
116
+ router.get('/services', requireApi(API.list), answer(async function() {
117
+ var list = await services.all();
118
+ var out = await Promise.all(list.map(async function(s) {
119
+ var row = { unit: s.unit, label: s.label, addedBy: s.addedBy };
120
+ try {
121
+ var st = await systemd.status(s.unit);
122
+ return Object.assign(row, { status: st, processes: systemd.processes(st) });
123
+ } catch (e) { return Object.assign(row, { status: null, processes: [], statusError: e.message }); }
124
+ }));
125
+ systemd.forgetGone(new Set([].concat.apply([], out.map(function(s) { return s.processes.map(function(p) { return p.pid; }); }))));
126
+ return out;
127
+ }));
128
+
129
+ router.post('/services', requireApi(API.add), change('add', function(req) { return services.add(req.body || {}, who(req)); }));
130
+ router.patch('/services/:unit', requireApi(API.edit), change('edit', async function(req) { return services.edit(await unitOf(req), req.body || {}); }));
131
+ router.delete('/services/:unit', requireApi(API.remove), change('remove', async function(req) { await services.remove(await unitOf(req)); return { unit: req.params.unit }; }));
132
+
133
+ // The action is part of what is recorded, so its handler is made per request.
134
+ router.post('/services/:unit/:action', requireApi(API.control), function(req, res, next) {
135
+ var action = req.params.action;
136
+ return change(action, async function() {
137
+ if (systemd.ACTIONS.indexOf(action) < 0) { var e = new Error('Unknown action "' + action + '": start, stop, restart or kill'); e.status = 400; throw e; }
138
+ var unit = await unitOf(req);
139
+ if ((action === 'stop' || action === 'kill') && unit === systemd.selfUnit()) {
140
+ var own = new Error('This is the monitor\'s own API: stopping it would leave nothing to start it again. Restart it instead'); own.status = 400; throw own;
141
+ }
142
+ return { unit: unit, status: await systemd.act(unit, action) };
143
+ })(req, res, next);
144
+ });
145
+
146
+ router.get('/services/:unit/logs', requireApi(API.logs), answer(async function(req) {
147
+ var q = req.query || {};
148
+ return { lines: await systemd.logs(await unitOf(req), { lines: q.lines, since: q.since, until: q.until, grep: q.grep, level: q.level }) };
149
+ }));
150
+
151
+ // Server-sent events over a plain GET: the page reads it with fetch (it must
152
+ // send its sign-in token, which EventSource cannot), one `data:` line per log
153
+ // line. Closing the request ends the journalctl reading it.
154
+ router.get('/services/:unit/logs/live', requireApi(API.live), answer(async function(req, res) {
155
+ var unit = await unitOf(req);
156
+ var me = who(req);
157
+ var open = live.get(me) || 0;
158
+ if (open >= LIVE_PER_USER) { var e = new Error('You already have ' + LIVE_PER_USER + ' live logs open. Close one first'); e.status = 429; throw e; }
159
+ live.set(me, open + 1);
160
+ res.writeHead(200, { 'Content-Type': 'text/event-stream', 'Cache-Control': 'no-cache, no-transform', Connection: 'keep-alive', 'X-Accel-Buffering': 'no' });
161
+ res.write('event: ready\ndata: {}\n\n');
162
+ var stop = systemd.follow(unit, function(line) {
163
+ res.write('data: ' + JSON.stringify(line) + '\n\n');
164
+ }, function(problem) {
165
+ res.write('event: problem\ndata: ' + JSON.stringify({ error: problem }) + '\n\n');
166
+ });
167
+ var beat = setInterval(function() { res.write(': still here\n\n'); }, HEARTBEAT_MS);
168
+ if (beat.unref) beat.unref();
169
+ var closed = false;
170
+ req.on('close', function() {
171
+ if (closed) return;
172
+ closed = true;
173
+ clearInterval(beat);
174
+ stop();
175
+ live.set(me, Math.max((live.get(me) || 1) - 1, 0));
176
+ });
177
+ }));
178
+
179
+ router.get('/services/:unit/history', requireApi(API.history), history(async function(req, stopper) {
180
+ return stats.serviceHistory(stopper, await unitOf(req), req.query);
181
+ }));
182
+
183
+ router.get('/history', requireApi(API.serverHistory), history(function(req, stopper) {
184
+ return stats.serverHistory(stopper, req.query);
185
+ }));
186
+
187
+ router.get('/traffic', requireApi(API.traffic), history(function(req, stopper) {
188
+ return stats.traffic(stopper, req.query);
189
+ }));
190
+
191
+ router.get('/audit', requireApi(API.audit), answer(async function(req) {
192
+ return { entries: await services.recentAudit(req.query.limit) };
193
+ }));
194
+
195
+ router.API = API;
196
+ module.exports = router;
@@ -0,0 +1,166 @@
1
+ /**
2
+ * EVERY SETTING THIS APP NEEDS, AND HOW EACH ONE GETS A VALUE (@xeplr/setup).
3
+ *
4
+ * So that a deploy never fails because of a setting:
5
+ * - what can be generated (ENCRYPTION_KEY, AUTH_JWT_SECRET, the first Super
6
+ * Admin's password) or worked out (the encrypted database logins, the
7
+ * links in emails, AUTH_URL) is written into the env file by the app;
8
+ * - what only a person knows (the database server and password, the
9
+ * database names, the data folder, the Super Admin's email) is asked ONCE
10
+ * on the app's own setup page — http://<api>/setup, behind the one-time
11
+ * code in api/SETUP_CODE — when it is missing (bin/www);
12
+ * - a feature whose settings are missing is OFF, the app runs:
13
+ * email SMTP_* (when EMAIL_PROVIDER is smtp) — without it nobody but
14
+ * the Super Admin can get in (no invites, resets, activations).
15
+ *
16
+ * After setup the same schema is the Super Admin's App settings page
17
+ * (routes/appSettings.js, @xeplr/ui-setup in the UI).
18
+ *
19
+ * The lists come from env.required.js — every library's own requiredEnv —
20
+ * so a requirement a library adds shows up here with nothing to re-type.
21
+ *
22
+ * deploy/settings.cjs (run by deploy/install.sh as root) writes the deploy's
23
+ * answers into the same env file and calls prepare() with this schema, so the
24
+ * deploy and the setup page fill settings the same way.
25
+ *
26
+ * config(apiDir, env) → { schema, envFile, codeFile, title }
27
+ */
28
+ var fs = require('fs');
29
+ var path = require('path');
30
+ var setup = require('@xeplr/setup');
31
+
32
+ // The ONE database login, encrypted into each of these (`xeplr encrypt`
33
+ // writes the same two).
34
+ var CONNECTIONS = ['XEPLR_MONITOR_CONNECTION', 'AUTH_DB_CONNECTION_INFO_ENCRYPTED'];
35
+ var DATABASES = ['DB_API', 'AUTH_DB_NAME', 'DB_JOBS'];
36
+ var SMTP = ['SMTP_HOST', 'SMTP_USER', 'SMTP_PASS', 'SMTP_FROM'];
37
+
38
+ function notExample(v) { return /@example\.(com|org)$/.test(v) ? 'still the example address' : null; }
39
+
40
+ /** https://SERVER_NAME — the address people open. */
41
+ function publicUrl(v) { return 'https://' + v.SERVER_NAME; }
42
+
43
+ /** The database login, encrypted with this install's key; one encryption for both settings. */
44
+ function encryptedLogin(encrypt) {
45
+ var made = {};
46
+ return function(v) {
47
+ var login = JSON.stringify([v.DB_HOST, v.DB_PORT, v.DB_USER, v.DB_PASSWORD, v.ENCRYPTION_KEY]);
48
+ if (!made[login]) made[login] = encrypt(JSON.stringify({
49
+ host: v.DB_HOST,
50
+ port: parseInt(v.DB_PORT || '5432', 10),
51
+ user: v.DB_USER || 'postgres',
52
+ password: v.DB_PASSWORD || ''
53
+ }), v.ENCRYPTION_KEY);
54
+ return made[login];
55
+ };
56
+ }
57
+
58
+ function about(encrypt, decrypt) {
59
+ var a = {
60
+ ENCRYPTION_KEY: { kind: 'generated', generate: 'hex', secret: true, label: 'Encryption key',
61
+ locked: 'Encrypts the stored database logins: a new key would make every one of them unreadable.' },
62
+ AUTH_JWT_SECRET: { kind: 'generated', generate: 'hex', secret: true, label: 'Sign-in token secret',
63
+ locked: 'Signs every sign-in: made once and kept.' },
64
+ AUTH_SUPER_ADMIN_PASSWORD: { kind: 'generated', generate: 'password', secret: true, label: 'Super Admin password',
65
+ locked: 'Used once, to make the first Super Admin. Change the password from the account menu instead.',
66
+ // Never printed: a deploy's output ends up in logs.
67
+ note: { file: 'FIRST_LOGIN', label: 'The first sign-in', text: function(pw, v) {
68
+ return 'Super Admin: ' + (v.AUTH_SUPER_ADMIN_EMAIL || '(AUTH_SUPER_ADMIN_EMAIL)') + '\n' +
69
+ 'Password: ' + pw + '\n\nChange it after the first login, then delete this file.\n';
70
+ } } },
71
+
72
+ DB_HOST: { input: true, label: 'Database server', help: 'The Postgres server every database of this app lives on, e.g. 127.0.0.1.' },
73
+ DB_PORT: { input: true, optional: true, label: 'Database port', help: 'Empty means 5432.' },
74
+ DB_USER: { input: true, optional: true, label: 'Database user', help: 'Empty means postgres. It must be allowed to create databases.' },
75
+ DB_PASSWORD: { input: true, secret: true, optional: true, label: 'Database password', help: 'Encrypted into the app\'s connections; the plain text is not kept.' },
76
+
77
+ SERVER_NAME: { input: true, label: 'Domain', help: 'The address people open, e.g. app.yourcompany.com — the links in emails are built from it.' },
78
+ AUTH_ACTIVATION_URL: { kind: 'derived', from: ['SERVER_NAME'], derive: function(v) { return publicUrl(v) + '/auth/activate'; }, label: 'Activation link' },
79
+ AUTH_INVITE_URL: { kind: 'derived', from: ['SERVER_NAME'], derive: function(v) { return publicUrl(v) + '/auth/accept-invite'; }, label: 'Invite link' },
80
+ AUTH_RESET_URL: { kind: 'derived', from: ['SERVER_NAME'], derive: function(v) { return publicUrl(v) + '/auth/reset-password'; }, label: 'Password reset link' },
81
+
82
+ // Where THIS server reaches the sign-in service (not the public address).
83
+ AUTH_URL: { kind: 'derived', from: ['AUTH_PORT'], derive: function(v) { return 'http://127.0.0.1:' + v.AUTH_PORT; }, label: 'Sign-in service address' },
84
+ XEPLR_MONITOR_PORT: { label: 'API port', help: 'The port this API listens on (the setup page is on it too).' },
85
+ AUTH_PORT: { label: 'Sign-in service port' },
86
+
87
+ // Fixed for this app when it was generated — not questions for a person.
88
+ REDIS_PREFIX: { kind: 'derived', from: [], derive: function() { return 'xeplr-monitor:'; }, label: 'Redis key prefix',
89
+ locked: 'Keeps this app\'s sign-in keys apart from other apps on the same Redis.' },
90
+ AUTH_TENANT_HEADER: { kind: 'derived', from: [], derive: function() { return 'none'; }, label: 'Company header for roles', locked: 'Part of how this app was generated.' },
91
+ AUTH_REGISTER_ROLES: { kind: 'derived', from: [], derive: function() { return 'Viewer'; }, label: 'Role of a new sign-up' },
92
+ XEPLR_AUTH_MIGRATIONS: { kind: 'derived', from: [],
93
+ derive: function() { return './migrations-auth,./node_modules/@xeplr/jobs/migrations-auth,./node_modules/@xeplr/backups/migrations-auth'; },
94
+ label: 'Sign-in permission files', locked: 'The permission files this app ships, in order.' },
95
+
96
+ XEPLR_DATA_DIR: { where: 'path', label: 'Data folder', help: 'Absolute path, e.g. /var/lib/xeplr-monitor/data — where a backup is written before it goes to S3.' },
97
+ REDIS_HOST: { optional: true, label: 'Redis server', help: 'Where sign-in keeps its sessions. Empty means localhost.' },
98
+ REDIS_PORT: { optional: true, label: 'Redis port', help: 'Empty means 6379.' },
99
+ REDIS_PASSWORD: { optional: true, secret: true, label: 'Redis password' },
100
+ // The root-owned command sudoers allows (deploy/control.sh).
101
+ MONITOR_CONTROL_COMMAND: { optional: true, label: 'Service control command', locked: 'Installed by the deploy as the one command sudoers allows.' },
102
+ LOG_DIR: { optional: true, label: 'Log folder', help: 'Empty means ./logs.' },
103
+
104
+ AUTH_SUPER_ADMIN_EMAIL: { label: 'Super Admin email', help: 'Who signs in first.', validate: notExample },
105
+ SMTP_HOST: { label: 'Mail server', help: 'Activation, invite and reset emails go out through it.' },
106
+ SMTP_USER: { label: 'Mail user' },
107
+ SMTP_PASS: { label: 'Mail password', secret: true },
108
+ SMTP_FROM: { label: 'Mail from address', validate: notExample }
109
+ };
110
+ var login = encrypt ? encryptedLogin(encrypt) : null;
111
+ CONNECTIONS.forEach(function(name) {
112
+ a[name] = { kind: 'derived', secret: true, from: ['DB_HOST'], uses: ['DB_PORT', 'DB_USER', 'DB_PASSWORD'], clears: ['DB_PASSWORD'],
113
+ derive: login || function() { throw new Error('cannot encrypt the database login: @xeplr/utils is not installed'); },
114
+ // Set, but can this install's key read it? (setup.verify, bin/www)
115
+ verify: decrypt ? function(v, env) {
116
+ return Promise.resolve(decrypt(v, env.ENCRYPTION_KEY)).then(function(text) {
117
+ var l = JSON.parse(text);
118
+ return l && l.host ? null : 'holds no database server';
119
+ }, function() { return 'cannot be read with this ENCRYPTION_KEY — give the database login again'; });
120
+ } : undefined,
121
+ label: 'Database login (' + name + ')' };
122
+ });
123
+ DATABASES.forEach(function(name) { a[name] = { where: 'database', label: 'Database name (' + name + ')' }; });
124
+ return a;
125
+ }
126
+
127
+ /** The schema for an env as it stands (mail is asked only when it goes out over SMTP). */
128
+ function schemaFor(env, required, encrypt, decrypt) {
129
+ var core = required.concat(CONNECTIONS, ['AUTH_INVITE_URL', 'LOG_DIR']);
130
+ var lists = { core: core };
131
+ if ((env.EMAIL_PROVIDER || 'smtp') === 'smtp') lists.email = SMTP;
132
+ return setup.fromRequired(lists, about(encrypt, decrypt), {
133
+ features: { email: { label: 'Email', help: 'Without it only the Super Admin can get in: invites, activations and password resets each send a link.' } },
134
+ checks: [setup.checks.postgres({ label: 'Database login' })]
135
+ });
136
+ }
137
+
138
+ /**
139
+ * This process's schema and env file. Deployed (deploy/install.sh), the
140
+ * settings are /opt/xeplr-monitor/shared/production.env — outside every
141
+ * release, read by the systemd units (EnvironmentFile) — and the setup code
142
+ * and FIRST_LOGIN sit beside it. Otherwise <api>/<NODE_ENV>.env.
143
+ */
144
+ function envFileFor(apiDir, env) {
145
+ var name = (env.NODE_ENV || 'development') + '.env';
146
+ // <root>/releases/<release>/api → <root>/shared
147
+ var releases = path.dirname(path.dirname(path.resolve(apiDir)));
148
+ var shared = path.join(path.dirname(releases), 'shared', name);
149
+ if (path.basename(releases) === 'releases' && fs.existsSync(shared)) return shared;
150
+ return path.join(apiDir, name);
151
+ }
152
+
153
+ function config(apiDir, env, opts) {
154
+ opts = opts || {};
155
+ env = env || process.env;
156
+ var crypto = opts.crypto || require('@xeplr/utils/isomorphic/crypto');
157
+ var envFile = envFileFor(apiDir, env);
158
+ return {
159
+ schema: schemaFor(env, opts.required || require('./env.required.js'), crypto.encrypt, crypto.decrypt),
160
+ envFile: envFile,
161
+ codeFile: path.join(path.dirname(envFile), 'SETUP_CODE'),
162
+ title: 'xeplr-monitor'
163
+ };
164
+ }
165
+
166
+ module.exports = { config: config, schemaFor: schemaFor, envFileFor: envFileFor, CONNECTIONS: CONNECTIONS };
@@ -0,0 +1,27 @@
1
+ #!/bin/bash
2
+ # XEPLR-MONITOR'S ONE PRIVILEGED COMMAND — installed by the deploy as
3
+ # /usr/local/libexec/xeplr-monitor-control (root-owned, 755), the only thing
4
+ # sudoers lets the monitor's user run as root:
5
+ #
6
+ # xeplr-monitor ALL=(root) NOPASSWD: /usr/local/libexec/xeplr-monitor-control
7
+ #
8
+ # xeplr-monitor-control start|stop|restart|kill <unit>
9
+ #
10
+ # It checks its arguments itself, so sudoers needs no wildcard (newer sudo,
11
+ # sudo-rs, refuses one in arguments; classic sudo's `*` also matched spaces).
12
+ # Exactly two arguments; one action of four; one unit name of plain characters;
13
+ # then systemctl, by its full path (the deploy puts it in below), with `--`
14
+ # before the name. Which services a person may control is decided by their
15
+ # roles in the app, not here.
16
+ set -euo pipefail
17
+
18
+ SYSTEMCTL='__SYSTEMCTL__'
19
+
20
+ [ $# -eq 2 ] || { echo "usage: xeplr-monitor-control start|stop|restart|kill <unit>" >&2; exit 64; }
21
+ action=$1
22
+ unit=$2
23
+ case "$action" in start|stop|restart|kill) ;; *) echo "not an action: $action" >&2; exit 64 ;; esac
24
+ [[ "$unit" =~ ^[A-Za-z0-9][A-Za-z0-9@._:-]{0,200}$ ]] || { echo "not a service name: $unit" >&2; exit 64; }
25
+
26
+ if [ "$action" = kill ]; then exec "$SYSTEMCTL" kill --signal=SIGKILL -- "$unit"; fi
27
+ exec "$SYSTEMCTL" "$action" -- "$unit"