@xeplr/monitor 0.1.2 → 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.
- package/README.md +148 -99
- 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 +240 -0
- package/deploy/settings.cjs +93 -0
- package/package.json +28 -46
- 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/server.js +0 -19
- package/bin/users.js +0 -86
- package/deploy/monitor.env.example +0 -16
- package/deploy/nginx.conf.example +0 -17
- 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
|
@@ -0,0 +1,8 @@
|
|
|
1
|
+
// The server itself: memory in GB, CPU, disks and uptime — @xeplr/ui-monitor's
|
|
2
|
+
// ServerPage, on this app's API and sign-in. The page you land on.
|
|
3
|
+
import { ServerPage } from '@xeplr/ui-monitor'
|
|
4
|
+
import { monitor } from '../api/monitor.js'
|
|
5
|
+
|
|
6
|
+
export default function Home() {
|
|
7
|
+
return <ServerPage api={monitor} />
|
|
8
|
+
}
|
|
@@ -0,0 +1,9 @@
|
|
|
1
|
+
// The server's services: how each is doing, start / stop / restart / kill, and
|
|
2
|
+
// their logs live — @xeplr/ui-monitor's page, on this app's API and sign-in.
|
|
3
|
+
// Who may see, control or change what is the roles' (migrations-auth/0006).
|
|
4
|
+
import { MonitorPage } from '@xeplr/ui-monitor'
|
|
5
|
+
import { monitor } from '../api/monitor.js'
|
|
6
|
+
|
|
7
|
+
export default function Monitor() {
|
|
8
|
+
return <MonitorPage api={monitor} />
|
|
9
|
+
}
|
|
@@ -0,0 +1,56 @@
|
|
|
1
|
+
import { defineConfig, loadEnv } from 'vite'
|
|
2
|
+
import react from '@vitejs/plugin-react'
|
|
3
|
+
|
|
4
|
+
// EVERY API PREFIX THIS APP CALLS.
|
|
5
|
+
//
|
|
6
|
+
// A path missing from this list does NOT fail loudly — Vite falls through to
|
|
7
|
+
// the SPA and serves index.html, so the fetch succeeds and the JSON parse is
|
|
8
|
+
// what breaks: `Unexpected token '<'`. Adding a route to the backend is only
|
|
9
|
+
// half of shipping an endpoint; it has to be listed here too.
|
|
10
|
+
const API_PATHS = [
|
|
11
|
+
'/health',
|
|
12
|
+
'/whoami',
|
|
13
|
+
// The setup page and its status (@xeplr/setup, served by the API before
|
|
14
|
+
// sign-in): App settings asks /setup/status while the app restarts.
|
|
15
|
+
'/setup',
|
|
16
|
+
// Every data address lives under /api, so a PAGE path and a DATA path can
|
|
17
|
+
// never collide. Without that split, adding '/tasks' here shadowed the UI's
|
|
18
|
+
// own /tasks page — opening it showed raw JSON instead of the app.
|
|
19
|
+
'/api'
|
|
20
|
+
]
|
|
21
|
+
|
|
22
|
+
export default defineConfig(({ mode }) => {
|
|
23
|
+
// Prefix '' so plain names load, not just VITE_-prefixed ones. These are dev
|
|
24
|
+
// server settings, not values shipped to the browser.
|
|
25
|
+
const env = loadEnv(mode, process.cwd(), '')
|
|
26
|
+
|
|
27
|
+
// NO PORT LITERALS. A hardcoded fallback is a second answer to a question
|
|
28
|
+
// .env already answers, and it is the one that wins when the file is missing
|
|
29
|
+
// — exactly when you want to be told rather than quietly served elsewhere.
|
|
30
|
+
const port = Number(env.UI_PORT)
|
|
31
|
+
const authUrl = env.AUTH_URL
|
|
32
|
+
const apiUrl = env.API_URL
|
|
33
|
+
if (!port || !authUrl || !apiUrl) {
|
|
34
|
+
throw new Error('ui/.env must set UI_PORT, AUTH_URL and API_URL')
|
|
35
|
+
}
|
|
36
|
+
|
|
37
|
+
const proxy = {
|
|
38
|
+
// Only the real network calls (/auth/api/*), NOT bare /auth — that prefix
|
|
39
|
+
// is also used by client-side routes (/auth/login, /auth/profile), which
|
|
40
|
+
// must fall through to Vite's SPA index.html rather than the auth backend.
|
|
41
|
+
'/auth/api': authUrl
|
|
42
|
+
}
|
|
43
|
+
API_PATHS.forEach((p) => { proxy[p] = apiUrl })
|
|
44
|
+
|
|
45
|
+
return {
|
|
46
|
+
plugins: [react()],
|
|
47
|
+
// Force every import to THIS app's copy, so hook-using libraries don't
|
|
48
|
+
// load twice and break the rules of hooks in ways that read as impossible.
|
|
49
|
+
resolve: { dedupe: ['react', 'react-dom', 'react-router-dom', '@xeplr/ui-table', '@xeplr/ui-utils'] },
|
|
50
|
+
// 127.0.0.1, not 'localhost': Node resolves 'localhost' to IPv6 (::1)
|
|
51
|
+
// first, so the dev server listened on ::1 alone and a browser going to
|
|
52
|
+
// 127.0.0.1 was refused.
|
|
53
|
+
server: { host: '127.0.0.1', port, strictPort: true, proxy },
|
|
54
|
+
preview: { port, strictPort: true }
|
|
55
|
+
}
|
|
56
|
+
})
|
package/bin/server.js
DELETED
|
@@ -1,19 +0,0 @@
|
|
|
1
|
-
#!/usr/bin/env node
|
|
2
|
-
// The monitor on its own: `xeplr-monitor-server`, run by its systemd service
|
|
3
|
-
// (deploy/xeplr-monitor.service). Settings come from the environment; a
|
|
4
|
-
// missing required one stops it here, naming it.
|
|
5
|
-
var { checkEnv } = require('@xeplr/base-apis');
|
|
6
|
-
var monitor = require('../index');
|
|
7
|
-
|
|
8
|
-
checkEnv(monitor.requiredEnv, { appName: 'xeplr-monitor' }); // names each missing one and exits
|
|
9
|
-
|
|
10
|
-
monitor.start({
|
|
11
|
-
dataDir: process.env.MONITOR_DATA_DIR,
|
|
12
|
-
secret: process.env.MONITOR_SECRET,
|
|
13
|
-
allow: process.env.MONITOR_ALLOW,
|
|
14
|
-
sudo: process.env.MONITOR_SUDO,
|
|
15
|
-
port: process.env.MONITOR_PORT
|
|
16
|
-
}).catch(function(err) {
|
|
17
|
-
console.error('[xeplr-monitor] could not start:', err.message);
|
|
18
|
-
process.exit(1);
|
|
19
|
-
});
|
package/bin/users.js
DELETED
|
@@ -1,86 +0,0 @@
|
|
|
1
|
-
#!/usr/bin/env node
|
|
2
|
-
// WHO CAN SIGN IN — managed on the server only, never from the page.
|
|
3
|
-
//
|
|
4
|
-
// xeplr-monitor-users list
|
|
5
|
-
// xeplr-monitor-users add <email> [--name "Full name"] [--no-code]
|
|
6
|
-
// xeplr-monitor-users password <email>
|
|
7
|
-
// xeplr-monitor-users code <email> [--off] a new authenticator secret (or none)
|
|
8
|
-
// xeplr-monitor-users remove <email>
|
|
9
|
-
//
|
|
10
|
-
// Reads MONITOR_DATA_DIR. A password is typed, never passed as an argument
|
|
11
|
-
// (it would sit in the shell's history and in `ps`); MONITOR_NEW_PASSWORD is
|
|
12
|
-
// read instead when set, for a script.
|
|
13
|
-
var readline = require('readline');
|
|
14
|
-
var store = require('../lib/store');
|
|
15
|
-
var users = require('../lib/users');
|
|
16
|
-
|
|
17
|
-
var args = process.argv.slice(2);
|
|
18
|
-
var cmd = args[0];
|
|
19
|
-
var email = args[1];
|
|
20
|
-
function flag(name) { return args.indexOf(name) > -1; }
|
|
21
|
-
function option(name) { var i = args.indexOf(name); return i > -1 ? args[i + 1] : undefined; }
|
|
22
|
-
|
|
23
|
-
function ask(question) {
|
|
24
|
-
if (process.env.MONITOR_NEW_PASSWORD) return Promise.resolve(process.env.MONITOR_NEW_PASSWORD);
|
|
25
|
-
return new Promise(function(resolve) {
|
|
26
|
-
var rl = readline.createInterface({ input: process.stdin, output: process.stdout, terminal: true });
|
|
27
|
-
rl.stdoutMuted = true;
|
|
28
|
-
rl._writeToOutput = function(s) { if (!rl.stdoutMuted || /\n/.test(s)) rl.output.write(s.replace(/[^\n]/g, '')); };
|
|
29
|
-
process.stdout.write(question);
|
|
30
|
-
rl.question('', function(answer) { rl.close(); process.stdout.write('\n'); resolve(answer); });
|
|
31
|
-
});
|
|
32
|
-
}
|
|
33
|
-
|
|
34
|
-
async function newPassword() {
|
|
35
|
-
var p = await ask('Password (at least ' + users.MIN_PASSWORD + ' characters): ');
|
|
36
|
-
if (!process.env.MONITOR_NEW_PASSWORD) {
|
|
37
|
-
var again = await ask('Again: ');
|
|
38
|
-
if (again !== p) throw new Error('The two passwords are not the same');
|
|
39
|
-
}
|
|
40
|
-
return p;
|
|
41
|
-
}
|
|
42
|
-
|
|
43
|
-
function showCode(out) {
|
|
44
|
-
if (!out.secret) return console.log('No code asked for when signing in.');
|
|
45
|
-
console.log('\nAdd this to an authenticator app (Google Authenticator, 1Password, Authy):');
|
|
46
|
-
console.log(' secret: ' + out.secret);
|
|
47
|
-
console.log(' or open: ' + out.url + '\n');
|
|
48
|
-
}
|
|
49
|
-
|
|
50
|
-
async function main() {
|
|
51
|
-
store.open(process.env.MONITOR_DATA_DIR);
|
|
52
|
-
if (cmd === 'list') {
|
|
53
|
-
var list = users.list();
|
|
54
|
-
if (!list.length) return console.log('No users yet. Add one: xeplr-monitor-users add <email>');
|
|
55
|
-
list.forEach(function(u) { console.log(u.email + (u.name !== u.email ? ' (' + u.name + ')' : '') + (u.twoStep ? ' · code asked' : ' · password only')); });
|
|
56
|
-
return;
|
|
57
|
-
}
|
|
58
|
-
if (!email || ['add', 'password', 'code', 'remove'].indexOf(cmd) < 0) {
|
|
59
|
-
console.log('xeplr-monitor-users list | add <email> [--name "…"] [--no-code] | password <email> | code <email> [--off] | remove <email>');
|
|
60
|
-
process.exitCode = 1;
|
|
61
|
-
return;
|
|
62
|
-
}
|
|
63
|
-
if (cmd === 'add') {
|
|
64
|
-
var out = users.add(email, await newPassword(), { name: option('--name'), twoStep: !flag('--no-code') });
|
|
65
|
-
store.audit({ email: out.user.email, action: 'user-added', ok: true, by: 'server' });
|
|
66
|
-
console.log('Added ' + out.user.email + '.');
|
|
67
|
-
return showCode(out);
|
|
68
|
-
}
|
|
69
|
-
if (cmd === 'password') {
|
|
70
|
-
users.setPassword(email, await newPassword());
|
|
71
|
-
store.audit({ email: email, action: 'password-changed', ok: true, by: 'server' });
|
|
72
|
-
return console.log('Changed. Every session ' + email + ' had open is signed out.');
|
|
73
|
-
}
|
|
74
|
-
if (cmd === 'code') {
|
|
75
|
-
var c = users.setTwoStep(email, !flag('--off'));
|
|
76
|
-
store.audit({ email: email, action: flag('--off') ? 'code-off' : 'code-new', ok: true, by: 'server' });
|
|
77
|
-
return showCode(c);
|
|
78
|
-
}
|
|
79
|
-
if (cmd === 'remove') {
|
|
80
|
-
users.remove(email);
|
|
81
|
-
store.audit({ email: email, action: 'user-removed', ok: true, by: 'server' });
|
|
82
|
-
return console.log('Removed ' + email + '.');
|
|
83
|
-
}
|
|
84
|
-
}
|
|
85
|
-
|
|
86
|
-
main().catch(function(err) { console.error(err.message); process.exit(1); });
|
|
@@ -1,16 +0,0 @@
|
|
|
1
|
-
# /etc/xeplr-monitor/monitor.env — readable by root and xeplr-monitor only (chmod 640).
|
|
2
|
-
|
|
3
|
-
# Required. Where its users, services and audit log live. Absolute.
|
|
4
|
-
MONITOR_DATA_DIR=/var/lib/xeplr-monitor
|
|
5
|
-
|
|
6
|
-
# Required. Signs the sign-in cookie; at least 32 characters. Make one with:
|
|
7
|
-
# openssl rand -base64 48
|
|
8
|
-
MONITOR_SECRET=
|
|
9
|
-
|
|
10
|
-
# Required. What it may control, comma-separated; * matches anything.
|
|
11
|
-
# sudoers must allow the same (sudoers.example).
|
|
12
|
-
MONITOR_ALLOW=xeplr-*
|
|
13
|
-
|
|
14
|
-
# Optional.
|
|
15
|
-
# MONITOR_PORT=19400 (default 19400)
|
|
16
|
-
# MONITOR_SUDO=actions (actions | all | none — see the README)
|
|
@@ -1,17 +0,0 @@
|
|
|
1
|
-
# The monitor behind nginx, on its own name (https only). It listens on
|
|
2
|
-
# 127.0.0.1:19400; nginx is the only way in.
|
|
3
|
-
server {
|
|
4
|
-
listen 443 ssl http2;
|
|
5
|
-
server_name monitor.example.com;
|
|
6
|
-
# ssl_certificate / ssl_certificate_key: as for the other sites (certbot)
|
|
7
|
-
|
|
8
|
-
location / {
|
|
9
|
-
proxy_pass http://127.0.0.1:19400;
|
|
10
|
-
proxy_set_header Host $host;
|
|
11
|
-
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
|
|
12
|
-
proxy_set_header X-Forwarded-Proto $scheme;
|
|
13
|
-
# A live log is one long answer: no buffering, and kept open.
|
|
14
|
-
proxy_buffering off;
|
|
15
|
-
proxy_read_timeout 1h;
|
|
16
|
-
}
|
|
17
|
-
}
|
package/deploy/sudoers.example
DELETED
|
@@ -1,13 +0,0 @@
|
|
|
1
|
-
# /etc/sudoers.d/xeplr-monitor — install with:
|
|
2
|
-
# sudo install -m 440 sudoers.example /etc/sudoers.d/xeplr-monitor && sudo visudo -c
|
|
3
|
-
#
|
|
4
|
-
# The monitor's user may start, stop, restart and kill the xeplr-* services,
|
|
5
|
-
# without a password, and nothing else: not a shell, not another command.
|
|
6
|
-
# Keep the pattern the same as MONITOR_ALLOW. Add a line per extra pattern
|
|
7
|
-
# (e.g. postgresql) if MONITOR_ALLOW names one.
|
|
8
|
-
#
|
|
9
|
-
# Note: in sudoers a * also matches spaces, so this line alone would let
|
|
10
|
-
# "systemctl stop xeplr-x sshd" through. The monitor never sends that: it
|
|
11
|
-
# passes exactly one name, checked against [A-Za-z0-9@._:-] and MONITOR_ALLOW
|
|
12
|
-
# first (lib/systemd.js unitName, lib/services.js).
|
|
13
|
-
xeplr-monitor ALL=(root) NOPASSWD: /usr/bin/systemctl start xeplr-*, /usr/bin/systemctl stop xeplr-*, /usr/bin/systemctl restart xeplr-*, /usr/bin/systemctl kill --signal=SIGKILL xeplr-*
|
|
@@ -1,26 +0,0 @@
|
|
|
1
|
-
# The monitor itself, as a systemd service. Copy to
|
|
2
|
-
# /etc/systemd/system/xeplr-monitor.service, then:
|
|
3
|
-
# sudo systemctl daemon-reload && sudo systemctl enable --now xeplr-monitor
|
|
4
|
-
#
|
|
5
|
-
# It runs as its own user (xeplr-monitor), not root: sudoers (sudoers.example)
|
|
6
|
-
# lets that user start/stop/restart/kill the allowed services and nothing
|
|
7
|
-
# else; the systemd-journal group lets it read their logs.
|
|
8
|
-
[Unit]
|
|
9
|
-
Description=Xeplr Monitor (status, control and logs of this server's services)
|
|
10
|
-
After=network-online.target
|
|
11
|
-
|
|
12
|
-
[Service]
|
|
13
|
-
Type=simple
|
|
14
|
-
User=xeplr-monitor
|
|
15
|
-
Group=xeplr-monitor
|
|
16
|
-
SupplementaryGroups=systemd-journal
|
|
17
|
-
EnvironmentFile=/etc/xeplr-monitor/monitor.env
|
|
18
|
-
ExecStart=/usr/bin/env xeplr-monitor-server
|
|
19
|
-
Restart=always
|
|
20
|
-
RestartSec=3
|
|
21
|
-
# sudo needs to gain privileges, so NoNewPrivileges stays off; sudoers is the limit.
|
|
22
|
-
ProtectHome=true
|
|
23
|
-
PrivateTmp=true
|
|
24
|
-
|
|
25
|
-
[Install]
|
|
26
|
-
WantedBy=multi-user.target
|
package/index.js
DELETED
|
@@ -1,89 +0,0 @@
|
|
|
1
|
-
// @xeplr/monitor — see and control a server's services: status, start, stop,
|
|
2
|
-
// restart, kill, and their logs, live. Its own sign-in, its own files, no
|
|
3
|
-
// database: it is what you open when something else is down.
|
|
4
|
-
//
|
|
5
|
-
// Built on @xeplr/base-apis createApp (the gate, cookies, request lines through
|
|
6
|
-
// @xeplr/logs to stdout, so to the journal; 404 and errors) and @xeplr/utils (authenticator codes, the
|
|
7
|
-
// wrong-try lockout). Neither needs Redis or a database here.
|
|
8
|
-
//
|
|
9
|
-
// init(config) open the store, the secret, the allowed services
|
|
10
|
-
// router() the API (lib/router.js), for a host to mount behind session.gate
|
|
11
|
-
// start(config) init, then serve the API at /api and the page at /
|
|
12
|
-
var path = require('path');
|
|
13
|
-
var fs = require('fs');
|
|
14
|
-
var express = require('express');
|
|
15
|
-
var { createApp } = require('@xeplr/base-apis');
|
|
16
|
-
var store = require('./lib/store');
|
|
17
|
-
var session = require('./lib/session');
|
|
18
|
-
var services = require('./lib/services');
|
|
19
|
-
var systemd = require('./lib/systemd');
|
|
20
|
-
var { createRouter } = require('./lib/router');
|
|
21
|
-
|
|
22
|
-
// What a host must set. Spread into its env.required.js so a missing one
|
|
23
|
-
// fails at startup, naming it, rather than booting a monitor nobody can use.
|
|
24
|
-
var requiredEnv = ['MONITOR_DATA_DIR', 'MONITOR_SECRET', 'MONITOR_ALLOW'];
|
|
25
|
-
|
|
26
|
-
/**
|
|
27
|
-
* @param config { dataDir, secret, allow, sudo? }
|
|
28
|
-
* dataDir absolute folder for users.json, services.json, audit.ndjson, logs/ (MONITOR_DATA_DIR)
|
|
29
|
-
* secret at least 32 characters; signs the sign-in cookie (MONITOR_SECRET)
|
|
30
|
-
* allow the services it may control: ["xeplr-*"] or "xeplr-*,postgresql" (MONITOR_ALLOW)
|
|
31
|
-
* sudo 'actions' (default) | 'all' | 'none' (MONITOR_SUDO)
|
|
32
|
-
*/
|
|
33
|
-
function init(config) {
|
|
34
|
-
config = config || {};
|
|
35
|
-
store.open(config.dataDir);
|
|
36
|
-
session.setSecret(config.secret);
|
|
37
|
-
services.setAllowed(config.allow);
|
|
38
|
-
systemd.configure({ sudo: config.sudo || 'actions' });
|
|
39
|
-
}
|
|
40
|
-
|
|
41
|
-
function router() { return createRouter(); }
|
|
42
|
-
|
|
43
|
-
function headers(req, res, next) {
|
|
44
|
-
res.setHeader('X-Frame-Options', 'DENY');
|
|
45
|
-
res.setHeader('X-Content-Type-Options', 'nosniff');
|
|
46
|
-
res.setHeader('Referrer-Policy', 'no-referrer');
|
|
47
|
-
res.setHeader('Content-Security-Policy', "default-src 'self'; style-src 'self' 'unsafe-inline'; img-src 'self' data:; frame-ancestors 'none'");
|
|
48
|
-
next();
|
|
49
|
-
}
|
|
50
|
-
|
|
51
|
-
/** The page (built into public/), with every other path answered by index.html. */
|
|
52
|
-
function pageRouter(dir) {
|
|
53
|
-
var r = express.Router();
|
|
54
|
-
if (!fs.existsSync(path.join(dir, 'index.html'))) return r;
|
|
55
|
-
r.use(express.static(dir, { index: false, maxAge: '1h' }));
|
|
56
|
-
r.get(/^(?!\/api\/).*/, function(req, res) { res.setHeader('Cache-Control', 'no-cache'); res.sendFile(path.join(dir, 'index.html')); });
|
|
57
|
-
return r;
|
|
58
|
-
}
|
|
59
|
-
|
|
60
|
-
/**
|
|
61
|
-
* Serve it: the API at /api, the page everywhere else. → the http server,
|
|
62
|
-
* once listening on its port. nginx is its front door, as for every xeplr
|
|
63
|
-
* service.
|
|
64
|
-
*/
|
|
65
|
-
function start(config) {
|
|
66
|
-
config = config || {};
|
|
67
|
-
init(config);
|
|
68
|
-
// 0 is a port too (any free one); only a missing value takes the default.
|
|
69
|
-
var port = config.port === undefined || config.port === null || config.port === '' ? 19400 : Number(config.port);
|
|
70
|
-
var built = createApp(port, 'xeplr-monitor', {
|
|
71
|
-
// Its own sign-in: it must work when @xeplr/auth is down. The headers go in
|
|
72
|
-
// front of it, so a refused request carries them too (createApp's
|
|
73
|
-
// `middleware` runs only after the gate).
|
|
74
|
-
auth: { middleware: function(req, res, next) { headers(req, res, function() { session.gate(req, res, next); }); } },
|
|
75
|
-
corsOptions: { origin: false }, // same-site page only
|
|
76
|
-
log: config.log === false ? false : { logDir: path.join(config.dataDir, 'logs') },
|
|
77
|
-
routes: { '/api': router(), '/': pageRouter(config.publicDir || path.join(__dirname, 'public')) }
|
|
78
|
-
});
|
|
79
|
-
// Behind nginx on the same machine: req.secure and req.ip come from it.
|
|
80
|
-
built.app.set('trust proxy', 'loopback');
|
|
81
|
-
built.app.disable('x-powered-by');
|
|
82
|
-
return new Promise(function(resolve, reject) {
|
|
83
|
-
if (built.server.listening) return resolve(built.server);
|
|
84
|
-
built.server.once('listening', function() { resolve(built.server); });
|
|
85
|
-
built.server.once('error', reject);
|
|
86
|
-
});
|
|
87
|
-
}
|
|
88
|
-
|
|
89
|
-
module.exports = { init: init, router: router, start: start, requiredEnv: requiredEnv, gate: session.gate };
|
package/lib/router.js
DELETED
|
@@ -1,179 +0,0 @@
|
|
|
1
|
-
// THE MONITOR'S API — mounted at /api by bin/server.js (or by a host).
|
|
2
|
-
//
|
|
3
|
-
// POST /login { email, password, code? } → the user, and the cookie
|
|
4
|
-
// POST /logout
|
|
5
|
-
// GET /me who is signed in, and what may be added
|
|
6
|
-
// GET /services every watched service with its status and processes now
|
|
7
|
-
// POST /services { unit, label? } — watch one more
|
|
8
|
-
// PATCH /services/:unit { label?, unit? } — changed in place
|
|
9
|
-
// DELETE /services/:unit stop watching it (the service is not touched)
|
|
10
|
-
// POST /services/:unit/:action start | stop | restart | kill
|
|
11
|
-
// GET /services/:unit/logs ?lines=&since=&until=&grep=&level= — oldest first
|
|
12
|
-
// GET /services/:unit/logs/live the log as it is written (server-sent events)
|
|
13
|
-
// GET /audit ?limit= — who did what, newest first
|
|
14
|
-
//
|
|
15
|
-
// Everything but /login needs a signed-in user (lib/session.js); a change also
|
|
16
|
-
// needs the x-xeplr-monitor: 1 header. Every sign-in and every change goes to
|
|
17
|
-
// the audit log, refused ones included. Bodies are parsed, and errors answered
|
|
18
|
-
// as { error }, by @xeplr/base-apis createApp, which this is mounted in.
|
|
19
|
-
var express = require('express');
|
|
20
|
-
var RateLimiter = require('@xeplr/utils/lib/rateLimiter');
|
|
21
|
-
var session = require('./session');
|
|
22
|
-
var users = require('./users');
|
|
23
|
-
var services = require('./services');
|
|
24
|
-
var systemd = require('./systemd');
|
|
25
|
-
var store = require('./store');
|
|
26
|
-
|
|
27
|
-
var LIVE_PER_USER = 10;
|
|
28
|
-
// Wrong sign-ins: 5 for one email, or 20 from one address (any emails; several
|
|
29
|
-
// people share an office network), within 15 minutes, lock it until the 15
|
|
30
|
-
// minutes from the first are up. In memory: a restart clears it, which only
|
|
31
|
-
// ever helps whoever restarted it.
|
|
32
|
-
var LOCK_SECONDS = 15 * 60;
|
|
33
|
-
var FAILS = 5;
|
|
34
|
-
var FAILS_PER_ADDRESS = 20;
|
|
35
|
-
var HEARTBEAT_MS = 15000;
|
|
36
|
-
|
|
37
|
-
function createRouter() {
|
|
38
|
-
var r = express.Router();
|
|
39
|
-
var live = new Map(); // email -> open live logs
|
|
40
|
-
var perEmail = new RateLimiter({ windowInSeconds: LOCK_SECONDS, max: FAILS });
|
|
41
|
-
var perAddress = new RateLimiter({ windowInSeconds: LOCK_SECONDS, max: FAILS_PER_ADDRESS });
|
|
42
|
-
|
|
43
|
-
// An async handler: its result as JSON; its error to createApp's error handler ({ error }, its status).
|
|
44
|
-
function answer(fn) {
|
|
45
|
-
return function(req, res, next) {
|
|
46
|
-
Promise.resolve().then(function() { return fn(req, res); }).then(function(out) {
|
|
47
|
-
if (!res.headersSent) res.json(out === undefined ? { ok: true } : out);
|
|
48
|
-
}).catch(function(err) {
|
|
49
|
-
if (!res.headersSent) next(err);
|
|
50
|
-
});
|
|
51
|
-
};
|
|
52
|
-
}
|
|
53
|
-
function ipOf(req) { return req.ip || (req.socket && req.socket.remoteAddress) || null; }
|
|
54
|
-
function unitOf(req) { return services.get(systemd.unitName(req.params.unit)).unit; }
|
|
55
|
-
|
|
56
|
-
r.post('/login', answer(async function(req, res) {
|
|
57
|
-
var b = req.body || {};
|
|
58
|
-
var email = String(b.email || '').trim().toLowerCase();
|
|
59
|
-
var byEmail = 'monitor:email:' + email;
|
|
60
|
-
var byAddress = 'monitor:ip:' + ipOf(req);
|
|
61
|
-
var wait = Math.max(await perEmail.lockedFor(byEmail), await perAddress.lockedFor(byAddress));
|
|
62
|
-
if (wait) {
|
|
63
|
-
store.audit({ email: email, ip: ipOf(req), action: 'sign-in', ok: false, error: 'locked' });
|
|
64
|
-
var minutes = Math.ceil(wait / 60);
|
|
65
|
-
res.status(429).json({ error: 'Too many wrong tries. Try again in ' + minutes + ' minute' + (minutes === 1 ? '' : 's') });
|
|
66
|
-
return;
|
|
67
|
-
}
|
|
68
|
-
var out = users.check(email, b.password, b.code);
|
|
69
|
-
if (!out.user) {
|
|
70
|
-
// Asking for the code is not a wrong try; a wrong code is.
|
|
71
|
-
if (!(out.needsCode && !b.code)) {
|
|
72
|
-
await perEmail.fail(byEmail);
|
|
73
|
-
await perAddress.fail(byAddress);
|
|
74
|
-
store.audit({ email: email, ip: ipOf(req), action: 'sign-in', ok: false, error: out.problem });
|
|
75
|
-
}
|
|
76
|
-
res.status(401).json({ error: out.problem, needsCode: Boolean(out.needsCode) });
|
|
77
|
-
return;
|
|
78
|
-
}
|
|
79
|
-
await perEmail.reset(byEmail);
|
|
80
|
-
session.start(req, res, out.user);
|
|
81
|
-
store.audit({ email: out.user.email, ip: ipOf(req), action: 'sign-in', ok: true });
|
|
82
|
-
return { user: users.shown(out.user) };
|
|
83
|
-
}));
|
|
84
|
-
|
|
85
|
-
r.post('/logout', function(req, res) {
|
|
86
|
-
var u = session.read(session.cookieOf(req));
|
|
87
|
-
session.end(req, res);
|
|
88
|
-
if (u) store.audit({ email: u.email, ip: ipOf(req), action: 'sign-out', ok: true });
|
|
89
|
-
res.json({ ok: true });
|
|
90
|
-
});
|
|
91
|
-
|
|
92
|
-
r.use(session.required);
|
|
93
|
-
|
|
94
|
-
r.get('/me', function(req, res) {
|
|
95
|
-
res.json({ user: users.shown(req.user), allowed: services.allowedPatterns(), self: systemd.selfUnit() });
|
|
96
|
-
});
|
|
97
|
-
|
|
98
|
-
r.get('/services', answer(async function() {
|
|
99
|
-
var list = services.all();
|
|
100
|
-
var out = await Promise.all(list.map(async function(s) {
|
|
101
|
-
try {
|
|
102
|
-
var st = await systemd.status(s.unit);
|
|
103
|
-
return Object.assign({}, s, { status: st, processes: systemd.processes(st) });
|
|
104
|
-
} catch (e) { return Object.assign({}, s, { status: null, processes: [], statusError: e.message }); }
|
|
105
|
-
}));
|
|
106
|
-
systemd.forgetGone(new Set([].concat.apply([], out.map(function(s) { return s.processes.map(function(p) { return p.pid; }); }))));
|
|
107
|
-
return out;
|
|
108
|
-
}));
|
|
109
|
-
|
|
110
|
-
// A change, recorded whether it worked or not.
|
|
111
|
-
function change(action, fn) {
|
|
112
|
-
return answer(async function(req) {
|
|
113
|
-
var unit = req.params.unit || (req.body && req.body.unit) || null;
|
|
114
|
-
try {
|
|
115
|
-
var out = await fn(req);
|
|
116
|
-
store.audit({ email: req.user.email, ip: ipOf(req), action: action, unit: (out && out.unit) || unit, ok: true });
|
|
117
|
-
return out;
|
|
118
|
-
} catch (err) {
|
|
119
|
-
store.audit({ email: req.user.email, ip: ipOf(req), action: action, unit: unit, ok: false, error: err.message });
|
|
120
|
-
throw err;
|
|
121
|
-
}
|
|
122
|
-
});
|
|
123
|
-
}
|
|
124
|
-
|
|
125
|
-
r.post('/services', change('add', function(req) { return services.add(req.body || {}, req.user.email); }));
|
|
126
|
-
r.patch('/services/:unit', change('edit', function(req) { return services.edit(unitOf(req), req.body || {}, req.user.email); }));
|
|
127
|
-
r.delete('/services/:unit', change('remove', function(req) { services.remove(unitOf(req)); return { unit: req.params.unit }; }));
|
|
128
|
-
|
|
129
|
-
// The action is part of what is recorded, so its handler is made per request.
|
|
130
|
-
r.post('/services/:unit/:action', function(req, res, next) {
|
|
131
|
-
var action = req.params.action;
|
|
132
|
-
return change(action, async function() {
|
|
133
|
-
if (systemd.ACTIONS.indexOf(action) < 0) { var e = new Error('Unknown action "' + action + '": start, stop, restart or kill'); e.status = 400; throw e; }
|
|
134
|
-
var unit = unitOf(req);
|
|
135
|
-
if ((action === 'stop' || action === 'kill') && unit === systemd.selfUnit()) {
|
|
136
|
-
var own = new Error('This is the monitor itself: stopping it would leave nothing to start it again. Restart it instead'); own.status = 400; throw own;
|
|
137
|
-
}
|
|
138
|
-
return { unit: unit, status: await systemd.act(unit, action) };
|
|
139
|
-
})(req, res, next);
|
|
140
|
-
});
|
|
141
|
-
|
|
142
|
-
r.get('/services/:unit/logs', answer(async function(req) {
|
|
143
|
-
var q = req.query || {};
|
|
144
|
-
return { lines: await systemd.logs(unitOf(req), { lines: q.lines, since: q.since, until: q.until, grep: q.grep, level: q.level }) };
|
|
145
|
-
}));
|
|
146
|
-
|
|
147
|
-
r.get('/services/:unit/logs/live', function(req, res) {
|
|
148
|
-
var unit;
|
|
149
|
-
try { unit = unitOf(req); } catch (e) { return res.status(e.status || 400).json({ error: e.message }); }
|
|
150
|
-
var open = live.get(req.user.email) || 0;
|
|
151
|
-
if (open >= LIVE_PER_USER) return res.status(429).json({ error: 'You already have ' + LIVE_PER_USER + ' live logs open. Close one first' });
|
|
152
|
-
live.set(req.user.email, open + 1);
|
|
153
|
-
res.writeHead(200, { 'Content-Type': 'text/event-stream', 'Cache-Control': 'no-cache, no-transform', Connection: 'keep-alive', 'X-Accel-Buffering': 'no' });
|
|
154
|
-
res.write('event: ready\ndata: {}\n\n');
|
|
155
|
-
var stop = systemd.follow(unit, function(line) {
|
|
156
|
-
res.write('data: ' + JSON.stringify(line) + '\n\n');
|
|
157
|
-
}, function(problem) {
|
|
158
|
-
res.write('event: problem\ndata: ' + JSON.stringify({ error: problem }) + '\n\n');
|
|
159
|
-
});
|
|
160
|
-
var beat = setInterval(function() { res.write(': still here\n\n'); }, HEARTBEAT_MS);
|
|
161
|
-
if (beat.unref) beat.unref();
|
|
162
|
-
var closed = false;
|
|
163
|
-
req.on('close', function() {
|
|
164
|
-
if (closed) return;
|
|
165
|
-
closed = true;
|
|
166
|
-
clearInterval(beat);
|
|
167
|
-
stop();
|
|
168
|
-
live.set(req.user.email, Math.max((live.get(req.user.email) || 1) - 1, 0));
|
|
169
|
-
});
|
|
170
|
-
});
|
|
171
|
-
|
|
172
|
-
r.get('/audit', function(req, res) {
|
|
173
|
-
res.json({ entries: store.recentAudit(Math.min(Math.max(parseInt(req.query.limit, 10) || 200, 1), 2000)) });
|
|
174
|
-
});
|
|
175
|
-
|
|
176
|
-
return r;
|
|
177
|
-
}
|
|
178
|
-
|
|
179
|
-
module.exports = { createRouter: createRouter, FAILS: FAILS, FAILS_PER_ADDRESS: FAILS_PER_ADDRESS };
|
package/lib/services.js
DELETED
|
@@ -1,76 +0,0 @@
|
|
|
1
|
-
// THE SERVICES THE MONITOR WATCHES — added by hand, kept in services.json.
|
|
2
|
-
// A service is only ever controlled once it is on this list, and only if its
|
|
3
|
-
// unit matches MONITOR_ALLOW (e.g. "xeplr-*"): the list is what you chose to
|
|
4
|
-
// watch, the pattern is what the server owner allows at all. sudoers repeats
|
|
5
|
-
// the pattern, so even a bug here could not reach another unit.
|
|
6
|
-
var store = require('./store');
|
|
7
|
-
var systemd = require('./systemd');
|
|
8
|
-
|
|
9
|
-
var FILE = 'services.json';
|
|
10
|
-
var patterns = [];
|
|
11
|
-
|
|
12
|
-
function setAllowed(list) {
|
|
13
|
-
var p = (Array.isArray(list) ? list : String(list || '').split(',')).map(function(x) { return x.trim(); }).filter(Boolean);
|
|
14
|
-
if (!p.length) throw new Error('MONITOR_ALLOW is not set: the services the monitor may control, e.g. "xeplr-*" (comma-separated, * matches anything)');
|
|
15
|
-
patterns = p;
|
|
16
|
-
}
|
|
17
|
-
|
|
18
|
-
function allowedPatterns() { return patterns.slice(); }
|
|
19
|
-
|
|
20
|
-
function refuse(message, status) { var e = new Error(message); e.status = status || 400; return e; }
|
|
21
|
-
|
|
22
|
-
function all() { return store.read(FILE, []); }
|
|
23
|
-
|
|
24
|
-
/** One watched service by its unit, or a 404. */
|
|
25
|
-
function get(unit) {
|
|
26
|
-
var s = all().find(function(x) { return x.unit === unit; });
|
|
27
|
-
if (!s) throw refuse('"' + unit + '" is not one of the services the monitor watches', 404);
|
|
28
|
-
return s;
|
|
29
|
-
}
|
|
30
|
-
|
|
31
|
-
/** A unit checked: a proper name, allowed, and known to systemd. → its full name. */
|
|
32
|
-
async function checked(name) {
|
|
33
|
-
var unit = systemd.unitName(name);
|
|
34
|
-
if (!systemd.allowed(unit, patterns)) throw refuse(unit + ' is not allowed here. The monitor may control ' + patterns.join(', ') + ' (MONITOR_ALLOW)', 403);
|
|
35
|
-
var st = await systemd.status(unit);
|
|
36
|
-
if (!st.exists) throw refuse('systemd has no service called ' + unit + ' on this server', 404);
|
|
37
|
-
return unit;
|
|
38
|
-
}
|
|
39
|
-
|
|
40
|
-
/** Watch a service: { unit, label }. */
|
|
41
|
-
async function add(body, by) {
|
|
42
|
-
var unit = await checked(body && body.unit);
|
|
43
|
-
var list = all();
|
|
44
|
-
if (list.some(function(x) { return x.unit === unit; })) throw refuse(unit + ' is already on the list', 409);
|
|
45
|
-
var s = { unit: unit, label: String((body && body.label) || '').trim().slice(0, 80) || unit.replace(/\.service$/, ''), addedBy: by, addedAt: new Date().toISOString() };
|
|
46
|
-
list.push(s);
|
|
47
|
-
store.write(FILE, list);
|
|
48
|
-
return s;
|
|
49
|
-
}
|
|
50
|
-
|
|
51
|
-
/** Change a watched service in place: its label, or which unit it is. */
|
|
52
|
-
async function edit(unit, body, by) {
|
|
53
|
-
var list = all();
|
|
54
|
-
var s = list.find(function(x) { return x.unit === unit; });
|
|
55
|
-
if (!s) throw refuse('"' + unit + '" is not one of the services the monitor watches', 404);
|
|
56
|
-
if (body.unit !== undefined && systemd.unitName(body.unit) !== unit) {
|
|
57
|
-
var next = await checked(body.unit);
|
|
58
|
-
if (list.some(function(x) { return x.unit === next; })) throw refuse(next + ' is already on the list', 409);
|
|
59
|
-
s.unit = next;
|
|
60
|
-
}
|
|
61
|
-
if (body.label !== undefined) s.label = String(body.label).trim().slice(0, 80) || s.unit.replace(/\.service$/, '');
|
|
62
|
-
s.changedBy = by;
|
|
63
|
-
s.changedAt = new Date().toISOString();
|
|
64
|
-
store.write(FILE, list);
|
|
65
|
-
return s;
|
|
66
|
-
}
|
|
67
|
-
|
|
68
|
-
/** Stop watching a service. The service itself is not touched. */
|
|
69
|
-
function remove(unit) {
|
|
70
|
-
var list = all();
|
|
71
|
-
var left = list.filter(function(x) { return x.unit !== unit; });
|
|
72
|
-
if (left.length === list.length) throw refuse('"' + unit + '" is not one of the services the monitor watches', 404);
|
|
73
|
-
store.write(FILE, left);
|
|
74
|
-
}
|
|
75
|
-
|
|
76
|
-
module.exports = { setAllowed: setAllowed, allowedPatterns: allowedPatterns, all: all, get: get, add: add, edit: edit, remove: remove };
|