pulse-hub 0.0.0-stage → 3.6.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/CHANGELOG.md +28 -0
- package/LICENSE +5 -0
- package/README.md +86 -2
- package/backend/.env.example +52 -0
- package/backend/agent-package.json +9 -0
- package/backend/agent.config.example.json +6 -0
- package/backend/agent.js +372 -0
- package/backend/authz-migrate.js +76 -0
- package/backend/cli.js +1021 -0
- package/backend/config.js +120 -0
- package/backend/emails/env-backup.html +52 -0
- package/backend/emails/invite.html +53 -0
- package/backend/install-agent.sh +181 -0
- package/backend/lib/agent-rpc.js +72 -0
- package/backend/lib/async-route.js +17 -0
- package/backend/lib/audit.js +134 -0
- package/backend/lib/auth-google.js +78 -0
- package/backend/lib/authz/bootstrap.js +35 -0
- package/backend/lib/authz/catalog.js +291 -0
- package/backend/lib/authz/delegation.js +104 -0
- package/backend/lib/authz/effective.js +104 -0
- package/backend/lib/authz/engine.js +251 -0
- package/backend/lib/authz/index.js +134 -0
- package/backend/lib/authz/legacy-oracle.js +195 -0
- package/backend/lib/authz/migrate.js +871 -0
- package/backend/lib/authz/mutate.js +87 -0
- package/backend/lib/authz/preview.js +327 -0
- package/backend/lib/authz/scope.js +282 -0
- package/backend/lib/authz/templates.js +103 -0
- package/backend/lib/authz-store.js +535 -0
- package/backend/lib/bundle-version.js +71 -0
- package/backend/lib/config-check.js +100 -0
- package/backend/lib/crypto-helpers.js +15 -0
- package/backend/lib/db.js +984 -0
- package/backend/lib/env-backup.js +306 -0
- package/backend/lib/env-crypto.js +52 -0
- package/backend/lib/env-files.js +235 -0
- package/backend/lib/env-mask.js +131 -0
- package/backend/lib/gmail-send.js +234 -0
- package/backend/lib/http-helpers.js +48 -0
- package/backend/lib/instance-registry.js +34 -0
- package/backend/lib/invite-helpers.js +83 -0
- package/backend/lib/invites.js +160 -0
- package/backend/lib/jwt.js +59 -0
- package/backend/lib/logs.js +244 -0
- package/backend/lib/metrics.js +249 -0
- package/backend/lib/migrate-legacy.js +106 -0
- package/backend/lib/paths.js +17 -0
- package/backend/lib/relay-state.js +564 -0
- package/backend/lib/self-update.js +68 -0
- package/backend/lib/session.js +48 -0
- package/backend/lib/sqlite.js +197 -0
- package/backend/lib/static-files.js +86 -0
- package/backend/middleware/authz.js +65 -0
- package/backend/middleware/session-gate.js +38 -0
- package/backend/public/assets/favicon.ico +0 -0
- package/backend/public/assets/favicon.svg +6 -0
- package/backend/public/assets/index.css +1 -0
- package/backend/public/assets/index.js +111 -0
- package/backend/public/assets/inter-cyrillic-ext-wght-normal.woff2 +0 -0
- package/backend/public/assets/inter-cyrillic-wght-normal.woff2 +0 -0
- package/backend/public/assets/inter-greek-ext-wght-normal.woff2 +0 -0
- package/backend/public/assets/inter-greek-wght-normal.woff2 +0 -0
- package/backend/public/assets/inter-latin-ext-wght-normal.woff2 +0 -0
- package/backend/public/assets/inter-latin-wght-normal.woff2 +0 -0
- package/backend/public/assets/inter-vietnamese-wght-normal.woff2 +0 -0
- package/backend/public/index.html +25 -0
- package/backend/routes/access.js +123 -0
- package/backend/routes/audit.js +41 -0
- package/backend/routes/auth.js +207 -0
- package/backend/routes/env-files.js +943 -0
- package/backend/routes/instances.js +555 -0
- package/backend/routes/invites-public.js +91 -0
- package/backend/routes/invites.js +121 -0
- package/backend/routes/logs.js +68 -0
- package/backend/routes/metrics.js +76 -0
- package/backend/routes/policies.js +240 -0
- package/backend/routes/static.js +100 -0
- package/backend/routes/teams.js +221 -0
- package/backend/routes/users.js +100 -0
- package/backend/seed-admins.js +68 -0
- package/backend/server.js +106 -0
- package/backend/ws/agent-relay.js +159 -0
- package/package.json +95 -4
package/backend/cli.js
ADDED
|
@@ -0,0 +1,1021 @@
|
|
|
1
|
+
#!/usr/bin/env node
|
|
2
|
+
// `pulse-hub` — the command installed by `npm install -g pulse-hub`. See docs/install.md.
|
|
3
|
+
//
|
|
4
|
+
// pulse-hub setup first-time install on this box (or re-run safely to repair/reconfigure)
|
|
5
|
+
// pulse-hub upgrade install a newer version from npm; DB backup + automatic rollback
|
|
6
|
+
// pulse-hub status service state, running version, latest available version
|
|
7
|
+
// pulse-hub doctor check config + service health, explain what's wrong
|
|
8
|
+
// pulse-hub seed-admins create/promote the admin emails listed in the env file
|
|
9
|
+
// pulse-hub logs follow the hub's logs (journalctl)
|
|
10
|
+
// pulse-hub start run the hub in the foreground (what the systemd unit runs)
|
|
11
|
+
//
|
|
12
|
+
// "Packaged mode": unlike `npm run hub` in a dev checkout (state in backend/.env and
|
|
13
|
+
// backend/data/), the npm-installed hub keeps its state OUTSIDE the package folder,
|
|
14
|
+
// because `npm install -g pulse-hub@<newer>` replaces that folder on every upgrade:
|
|
15
|
+
// config /etc/pulse-hub/hub.env (PULSE_ENV_FILE)
|
|
16
|
+
// data /var/lib/pulse-hub/ (PULSE_DATA_DIR — pulse.db, backups/)
|
|
17
|
+
// Both can be overridden by setting those env vars; lib/paths.js reads them.
|
|
18
|
+
//
|
|
19
|
+
// Plain Node + the hub's own deps only. Every step that changes the system checks its
|
|
20
|
+
// own result and says what failed (lessons in docs/deploy.md).
|
|
21
|
+
'use strict';
|
|
22
|
+
|
|
23
|
+
const fs = require('fs');
|
|
24
|
+
const path = require('path');
|
|
25
|
+
const http = require('http');
|
|
26
|
+
const readline = require('readline');
|
|
27
|
+
const { spawnSync, spawn } = require('child_process');
|
|
28
|
+
|
|
29
|
+
const BACKEND_DIR = __dirname;
|
|
30
|
+
const PACKAGE_JSON = path.join(BACKEND_DIR, '..', 'package.json');
|
|
31
|
+
const PACKAGE_NAME = 'pulse-hub';
|
|
32
|
+
|
|
33
|
+
const DEFAULTS = {
|
|
34
|
+
envFile: '/etc/pulse-hub/hub.env',
|
|
35
|
+
dataDir: '/var/lib/pulse-hub',
|
|
36
|
+
user: 'pulse-hub',
|
|
37
|
+
unit: 'pulse-hub',
|
|
38
|
+
unitFile: '/etc/systemd/system/pulse-hub.service',
|
|
39
|
+
legacyDir: '/opt/pulse-hub',
|
|
40
|
+
};
|
|
41
|
+
// Must match lib/sqlite.js's own check (the database uses Node's built-in node:sqlite).
|
|
42
|
+
// Duplicated as plain values, not required from there: requiring lib/sqlite.js on an
|
|
43
|
+
// old Node throws, and the CLI wants to report that nicely instead.
|
|
44
|
+
const MIN_NODE = '22.16.0';
|
|
45
|
+
function nodeIsSupported(version = process.versions.node) {
|
|
46
|
+
const [maj, min] = version.split('.').map(Number);
|
|
47
|
+
if (maj === 22) return min >= 16;
|
|
48
|
+
if (maj === 23) return min >= 8;
|
|
49
|
+
return maj > 22;
|
|
50
|
+
}
|
|
51
|
+
const NODE_TOO_OLD = `Node.js ${process.versions.node} is too old — Pulse needs ${MIN_NODE} or newer (it uses Node's built-in SQLite). Install Node 22 or 24 system-wide, then: sudo npm install -g pulse-hub`;
|
|
52
|
+
const BACKUPS_TO_KEEP = 5;
|
|
53
|
+
const HEALTH_WAIT_MS = 45 * 1000;
|
|
54
|
+
|
|
55
|
+
// Applied before anything requires lib/paths.js (server.js, seed-admins.js do).
|
|
56
|
+
process.env.PULSE_ENV_FILE = process.env.PULSE_ENV_FILE || DEFAULTS.envFile;
|
|
57
|
+
process.env.PULSE_DATA_DIR = process.env.PULSE_DATA_DIR || DEFAULTS.dataDir;
|
|
58
|
+
const ENV_FILE = process.env.PULSE_ENV_FILE;
|
|
59
|
+
const DATA_DIR = process.env.PULSE_DATA_DIR;
|
|
60
|
+
const DB_FILE = path.join(DATA_DIR, 'pulse.db');
|
|
61
|
+
const BACKUP_DIR = path.join(DATA_DIR, 'backups');
|
|
62
|
+
|
|
63
|
+
// ---------------------------------------------------------------- output helpers
|
|
64
|
+
|
|
65
|
+
const useColor = process.stdout.isTTY && !process.env.NO_COLOR;
|
|
66
|
+
const paint = (code) => (s) => (useColor ? `\x1b[${code}m${s}\x1b[0m` : s);
|
|
67
|
+
const bold = paint('1');
|
|
68
|
+
const green = paint('32');
|
|
69
|
+
const yellow = paint('33');
|
|
70
|
+
const red = paint('31');
|
|
71
|
+
const dim = paint('2');
|
|
72
|
+
|
|
73
|
+
const ok = (msg) => console.log(`${green('✓')} ${msg}`);
|
|
74
|
+
const warn = (msg) => console.log(`${yellow('!')} ${msg}`);
|
|
75
|
+
const bad = (msg) => console.log(`${red('✗')} ${msg}`);
|
|
76
|
+
const step = (msg) => console.log(`\n${bold('==')} ${bold(msg)}`);
|
|
77
|
+
|
|
78
|
+
class CliError extends Error {}
|
|
79
|
+
const fail = (msg) => {
|
|
80
|
+
throw new CliError(msg);
|
|
81
|
+
};
|
|
82
|
+
|
|
83
|
+
// ---------------------------------------------------------------- small utilities
|
|
84
|
+
|
|
85
|
+
function run(cmd, args, opts = {}) {
|
|
86
|
+
const r = spawnSync(cmd, args, { encoding: 'utf-8', ...opts });
|
|
87
|
+
return {
|
|
88
|
+
ok: r.status === 0 && !r.error,
|
|
89
|
+
status: r.status,
|
|
90
|
+
stdout: (r.stdout || '').trim(),
|
|
91
|
+
stderr: (r.stderr || '').trim(),
|
|
92
|
+
error: r.error,
|
|
93
|
+
};
|
|
94
|
+
}
|
|
95
|
+
|
|
96
|
+
function mustRun(cmd, args, what, opts = {}) {
|
|
97
|
+
const r = run(cmd, args, opts);
|
|
98
|
+
if (!r.ok) {
|
|
99
|
+
fail(
|
|
100
|
+
`${what} failed (${cmd} ${args.join(' ')}): ${r.stderr || r.error?.message || `exit ${r.status}`}`,
|
|
101
|
+
);
|
|
102
|
+
}
|
|
103
|
+
return r;
|
|
104
|
+
}
|
|
105
|
+
|
|
106
|
+
function installedVersion() {
|
|
107
|
+
return JSON.parse(fs.readFileSync(PACKAGE_JSON, 'utf-8')).version;
|
|
108
|
+
}
|
|
109
|
+
|
|
110
|
+
function parseSemver(v) {
|
|
111
|
+
const m = /^v?(\d+)\.(\d+)\.(\d+)/.exec(String(v || '').trim());
|
|
112
|
+
return m ? [Number(m[1]), Number(m[2]), Number(m[3])] : null;
|
|
113
|
+
}
|
|
114
|
+
|
|
115
|
+
function compareSemver(a, b) {
|
|
116
|
+
const pa = parseSemver(a);
|
|
117
|
+
const pb = parseSemver(b);
|
|
118
|
+
if (!pa || !pb) return 0;
|
|
119
|
+
for (let i = 0; i < 3; i++) if (pa[i] !== pb[i]) return pa[i] - pb[i];
|
|
120
|
+
return 0;
|
|
121
|
+
}
|
|
122
|
+
|
|
123
|
+
function npmBin() {
|
|
124
|
+
// Prefer the npm that ships next to the node running us — `sudo` often has a reduced
|
|
125
|
+
// PATH where plain `npm` isn't found even though node was.
|
|
126
|
+
const sibling = path.join(path.dirname(process.execPath), 'npm');
|
|
127
|
+
return fs.existsSync(sibling) ? sibling : 'npm';
|
|
128
|
+
}
|
|
129
|
+
|
|
130
|
+
function latestPublishedVersion() {
|
|
131
|
+
const r = run(npmBin(), ['view', PACKAGE_NAME, 'version'], { timeout: 20 * 1000 });
|
|
132
|
+
return r.ok && parseSemver(r.stdout) ? r.stdout : null;
|
|
133
|
+
}
|
|
134
|
+
|
|
135
|
+
function readEnvFile() {
|
|
136
|
+
try {
|
|
137
|
+
return require('dotenv').parse(fs.readFileSync(ENV_FILE));
|
|
138
|
+
} catch (e) {
|
|
139
|
+
return null;
|
|
140
|
+
}
|
|
141
|
+
}
|
|
142
|
+
|
|
143
|
+
function hubAddress(env) {
|
|
144
|
+
const e = env || readEnvFile() || {};
|
|
145
|
+
const port = Number(e.PULSE_PORT || process.env.PULSE_PORT) || 5080;
|
|
146
|
+
let host = (e.PULSE_HOST || process.env.PULSE_HOST || '127.0.0.1').trim();
|
|
147
|
+
if (host === '0.0.0.0' || host === '::') host = '127.0.0.1';
|
|
148
|
+
return { host, port };
|
|
149
|
+
}
|
|
150
|
+
|
|
151
|
+
function getHealth({ host, port }, timeoutMs = 3000) {
|
|
152
|
+
return new Promise((resolve) => {
|
|
153
|
+
const req = http.get({ host, port, path: '/healthz', timeout: timeoutMs }, (res) => {
|
|
154
|
+
let body = '';
|
|
155
|
+
res.on('data', (c) => (body += c));
|
|
156
|
+
res.on('end', () => {
|
|
157
|
+
try {
|
|
158
|
+
resolve(res.statusCode === 200 ? JSON.parse(body) : null);
|
|
159
|
+
} catch (e) {
|
|
160
|
+
resolve(null);
|
|
161
|
+
}
|
|
162
|
+
});
|
|
163
|
+
});
|
|
164
|
+
req.on('timeout', () => req.destroy());
|
|
165
|
+
req.on('error', () => resolve(null));
|
|
166
|
+
});
|
|
167
|
+
}
|
|
168
|
+
|
|
169
|
+
async function waitForHealth(addr, wantVersion, timeoutMs = HEALTH_WAIT_MS) {
|
|
170
|
+
const deadline = Date.now() + timeoutMs;
|
|
171
|
+
let last = null;
|
|
172
|
+
while (Date.now() < deadline) {
|
|
173
|
+
last = await getHealth(addr);
|
|
174
|
+
if (last && last.ok && (!wantVersion || last.version === wantVersion)) return last;
|
|
175
|
+
await new Promise((r) => setTimeout(r, 1500));
|
|
176
|
+
}
|
|
177
|
+
return last;
|
|
178
|
+
}
|
|
179
|
+
|
|
180
|
+
function isRoot() {
|
|
181
|
+
return typeof process.getuid === 'function' && process.getuid() === 0;
|
|
182
|
+
}
|
|
183
|
+
|
|
184
|
+
function requireRoot(cmd) {
|
|
185
|
+
if (process.platform !== 'linux')
|
|
186
|
+
fail(`\`pulse-hub ${cmd}\` sets up a Linux systemd service — run it on the server, not here.`);
|
|
187
|
+
if (!isRoot()) fail(`\`pulse-hub ${cmd}\` needs root. Run: sudo pulse-hub ${cmd}`);
|
|
188
|
+
if (!run('systemctl', ['--version']).ok)
|
|
189
|
+
fail('systemctl was not found — this command needs a systemd-based Linux.');
|
|
190
|
+
}
|
|
191
|
+
|
|
192
|
+
function userExists(user) {
|
|
193
|
+
return run('id', ['-u', user]).ok;
|
|
194
|
+
}
|
|
195
|
+
|
|
196
|
+
function fixOwnership(user) {
|
|
197
|
+
// Anything run as root against the DB (seed-admins, backups, an import) can create
|
|
198
|
+
// root-owned pulse.db-wal/-shm files the service user then can't write. Always hand
|
|
199
|
+
// the whole data dir back to the service user afterwards.
|
|
200
|
+
if (fs.existsSync(DATA_DIR) && userExists(user)) {
|
|
201
|
+
mustRun('chown', ['-R', `${user}:${user}`, DATA_DIR], 'Fixing data directory ownership');
|
|
202
|
+
}
|
|
203
|
+
}
|
|
204
|
+
|
|
205
|
+
function serviceActive(unit = DEFAULTS.unit) {
|
|
206
|
+
return run('systemctl', ['is-active', '--quiet', unit]).ok;
|
|
207
|
+
}
|
|
208
|
+
|
|
209
|
+
function printRecentLogs(unit = DEFAULTS.unit) {
|
|
210
|
+
const r = run('journalctl', ['-u', unit, '--no-pager', '-n', '40']);
|
|
211
|
+
if (r.stdout) console.log(dim(r.stdout));
|
|
212
|
+
}
|
|
213
|
+
|
|
214
|
+
function parseArgs(argv) {
|
|
215
|
+
const out = { _: [] };
|
|
216
|
+
for (let i = 0; i < argv.length; i++) {
|
|
217
|
+
const a = argv[i];
|
|
218
|
+
if (!a.startsWith('--')) {
|
|
219
|
+
out._.push(a);
|
|
220
|
+
continue;
|
|
221
|
+
}
|
|
222
|
+
const eq = a.indexOf('=');
|
|
223
|
+
const key = (eq === -1 ? a.slice(2) : a.slice(2, eq)).replace(/-([a-z])/g, (_, c) =>
|
|
224
|
+
c.toUpperCase(),
|
|
225
|
+
);
|
|
226
|
+
if (eq !== -1) out[key] = a.slice(eq + 1);
|
|
227
|
+
else if (argv[i + 1] !== undefined && !argv[i + 1].startsWith('--')) out[key] = argv[++i];
|
|
228
|
+
else out[key] = true;
|
|
229
|
+
}
|
|
230
|
+
return out;
|
|
231
|
+
}
|
|
232
|
+
|
|
233
|
+
// ---------------------------------------------------------------- env file editing
|
|
234
|
+
|
|
235
|
+
function quoteEnvValue(v) {
|
|
236
|
+
return /^[A-Za-z0-9_@.,:/+\-=]*$/.test(v)
|
|
237
|
+
? v
|
|
238
|
+
: `"${v.replace(/\\/g, '\\\\').replace(/"/g, '\\"')}"`;
|
|
239
|
+
}
|
|
240
|
+
|
|
241
|
+
// Replace KEY=... lines in place (keeping comments/order/everything else), append any
|
|
242
|
+
// key that isn't there yet.
|
|
243
|
+
function updateEnvFile(file, updates) {
|
|
244
|
+
const lines = fs.existsSync(file) ? fs.readFileSync(file, 'utf-8').split('\n') : [];
|
|
245
|
+
const seen = new Set();
|
|
246
|
+
// Every occurrence is rewritten, not just the first — dotenv lets a later duplicate
|
|
247
|
+
// line win, so editing only the first would silently not take effect.
|
|
248
|
+
const next = lines.map((line) => {
|
|
249
|
+
const m = /^\s*(?:export\s+)?([A-Z0-9_]+)\s*=/.exec(line);
|
|
250
|
+
if (m && Object.prototype.hasOwnProperty.call(updates, m[1])) {
|
|
251
|
+
seen.add(m[1]);
|
|
252
|
+
return `${m[1]}=${quoteEnvValue(updates[m[1]])}`;
|
|
253
|
+
}
|
|
254
|
+
return line;
|
|
255
|
+
});
|
|
256
|
+
const missing = Object.keys(updates).filter((k) => !seen.has(k));
|
|
257
|
+
if (missing.length) {
|
|
258
|
+
if (next.length && next[next.length - 1] !== '') next.push('');
|
|
259
|
+
for (const k of missing) next.push(`${k}=${quoteEnvValue(updates[k])}`);
|
|
260
|
+
}
|
|
261
|
+
fs.writeFileSync(file, next.join('\n').replace(/\n*$/, '\n'));
|
|
262
|
+
}
|
|
263
|
+
|
|
264
|
+
function envTemplate() {
|
|
265
|
+
return `# Pulse hub configuration — read by the pulse-hub systemd service.
|
|
266
|
+
# After editing: sudo systemctl restart pulse-hub (then: sudo pulse-hub doctor)
|
|
267
|
+
# Every available option, with explanations: ${path.join(BACKEND_DIR, '.env.example')}
|
|
268
|
+
|
|
269
|
+
# The hub's public address, as people open it in a browser (no trailing slash),
|
|
270
|
+
# e.g. https://example.com/monitor
|
|
271
|
+
PULSE_PUBLIC_URL=
|
|
272
|
+
|
|
273
|
+
# ---- Google sign-in (required: the only way to log in) ----
|
|
274
|
+
# Create a "Web application" OAuth client at https://console.cloud.google.com/apis/credentials
|
|
275
|
+
# and register PULSE_GOOGLE_REDIRECT_URI as an authorized redirect URI.
|
|
276
|
+
PULSE_GOOGLE_CLIENT_ID=
|
|
277
|
+
PULSE_GOOGLE_CLIENT_SECRET=
|
|
278
|
+
PULSE_GOOGLE_REDIRECT_URI=
|
|
279
|
+
|
|
280
|
+
# ---- Admins ----
|
|
281
|
+
# Full-access (root) admins, comma-separated Google account emails.
|
|
282
|
+
# Apply changes with: sudo pulse-hub seed-admins
|
|
283
|
+
PULSE_SUPER_ADMIN_EMAILS=
|
|
284
|
+
# Emails allowed to sign in without an invite (no special permissions), comma-separated.
|
|
285
|
+
PULSE_SEED_ADMIN_EMAILS=
|
|
286
|
+
|
|
287
|
+
# ---- Email (optional: invites + env-file backups) ----
|
|
288
|
+
# A Gmail account with 2-Step Verification and an App Password
|
|
289
|
+
# (https://myaccount.google.com/apppasswords) — not the account's real password.
|
|
290
|
+
PULSE_GMAIL_ADDRESS=
|
|
291
|
+
PULSE_GMAIL_APP_PASSWORD=
|
|
292
|
+
|
|
293
|
+
# ---- Network ----
|
|
294
|
+
# Where the hub listens. Keep 127.0.0.1 and put nginx in front of it.
|
|
295
|
+
PULSE_HOST=127.0.0.1
|
|
296
|
+
PULSE_PORT=5080
|
|
297
|
+
`;
|
|
298
|
+
}
|
|
299
|
+
|
|
300
|
+
// ---------------------------------------------------------------- prompts
|
|
301
|
+
|
|
302
|
+
// One prompter for the whole command (lazily created), so no input is lost between
|
|
303
|
+
// questions. Lines are queued as they arrive: readline's own rl.question() silently drops
|
|
304
|
+
// any line that comes in before its question is asked (pasted or piped answers), and
|
|
305
|
+
// never settles at all if input ends — which once made setup quit half-way with exit 0.
|
|
306
|
+
let prompter = null;
|
|
307
|
+
const INPUT_ENDED =
|
|
308
|
+
'Setup stopped: input ended before every question was answered. Re-run `sudo pulse-hub setup` ' +
|
|
309
|
+
'(safe to re-run), or pass the values as flags with --non-interactive.';
|
|
310
|
+
|
|
311
|
+
function getPrompter() {
|
|
312
|
+
if (prompter) return prompter;
|
|
313
|
+
const rl = readline.createInterface({
|
|
314
|
+
input: process.stdin,
|
|
315
|
+
output: process.stdout,
|
|
316
|
+
terminal: true,
|
|
317
|
+
});
|
|
318
|
+
const queue = [];
|
|
319
|
+
const waiters = [];
|
|
320
|
+
let closed = false;
|
|
321
|
+
let muted = false;
|
|
322
|
+
const origWrite = rl._writeToOutput.bind(rl);
|
|
323
|
+
rl._writeToOutput = (str) => {
|
|
324
|
+
if (!muted) origWrite(str);
|
|
325
|
+
else if (str.includes('\n')) origWrite('\n');
|
|
326
|
+
};
|
|
327
|
+
rl.on('line', (line) => {
|
|
328
|
+
const w = waiters.shift();
|
|
329
|
+
if (w) w.resolve(line);
|
|
330
|
+
else queue.push(line);
|
|
331
|
+
});
|
|
332
|
+
rl.on('close', () => {
|
|
333
|
+
closed = true;
|
|
334
|
+
while (waiters.length) waiters.shift().reject(new CliError(INPUT_ENDED));
|
|
335
|
+
});
|
|
336
|
+
rl.on('SIGINT', () => {
|
|
337
|
+
process.stdout.write('\n');
|
|
338
|
+
process.exit(130);
|
|
339
|
+
});
|
|
340
|
+
const ask = (q, { secret = false, def = '' } = {}) => {
|
|
341
|
+
const label = def ? `${q} ${dim(`[${def}]`)}: ` : `${q}: `;
|
|
342
|
+
const finish = (line) => {
|
|
343
|
+
muted = false;
|
|
344
|
+
return line.trim() || def;
|
|
345
|
+
};
|
|
346
|
+
rl.setPrompt(label);
|
|
347
|
+
rl.prompt();
|
|
348
|
+
if (queue.length) {
|
|
349
|
+
// Already echoed by readline when it arrived; just end the prompt line.
|
|
350
|
+
process.stdout.write('\n');
|
|
351
|
+
return Promise.resolve(finish(queue.shift()));
|
|
352
|
+
}
|
|
353
|
+
if (closed) return Promise.reject(new CliError(INPUT_ENDED));
|
|
354
|
+
muted = secret;
|
|
355
|
+
return new Promise((resolve, reject) =>
|
|
356
|
+
waiters.push({ resolve: (line) => resolve(finish(line)), reject }),
|
|
357
|
+
);
|
|
358
|
+
};
|
|
359
|
+
prompter = {
|
|
360
|
+
ask,
|
|
361
|
+
close: () => {
|
|
362
|
+
rl.close();
|
|
363
|
+
prompter = null;
|
|
364
|
+
},
|
|
365
|
+
};
|
|
366
|
+
return prompter;
|
|
367
|
+
}
|
|
368
|
+
|
|
369
|
+
async function askUntil(prompter, q, validate, opts) {
|
|
370
|
+
for (;;) {
|
|
371
|
+
const v = await prompter.ask(q, opts);
|
|
372
|
+
const problem = validate(v);
|
|
373
|
+
if (!problem) return v;
|
|
374
|
+
warn(problem);
|
|
375
|
+
}
|
|
376
|
+
}
|
|
377
|
+
|
|
378
|
+
const validUrl = (v) =>
|
|
379
|
+
/^https?:\/\/[^\s/]+/i.test(v) ? null : 'Enter a full URL starting with https:// (or http://).';
|
|
380
|
+
const validEmails = (v) =>
|
|
381
|
+
v && v.split(',').every((e) => /^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(e.trim()))
|
|
382
|
+
? null
|
|
383
|
+
: 'Enter a valid email (comma-separate several).';
|
|
384
|
+
const notEmpty = (v) => (v ? null : 'This value is required.');
|
|
385
|
+
|
|
386
|
+
// ---------------------------------------------------------------- setup
|
|
387
|
+
|
|
388
|
+
async function cmdSetup(args) {
|
|
389
|
+
requireRoot('setup');
|
|
390
|
+
const user = args.user || DEFAULTS.user;
|
|
391
|
+
const interactive = process.stdin.isTTY && !args.nonInteractive && !args.yes;
|
|
392
|
+
|
|
393
|
+
console.log(bold(`Pulse hub v${installedVersion()} — setup`));
|
|
394
|
+
console.log(
|
|
395
|
+
dim(`config ${ENV_FILE} data ${DATA_DIR} service ${DEFAULTS.unit}.service (user ${user})`),
|
|
396
|
+
);
|
|
397
|
+
|
|
398
|
+
step('Checking Node.js');
|
|
399
|
+
if (!nodeIsSupported()) fail(NODE_TOO_OLD);
|
|
400
|
+
if (/^\/(root|home)\//.test(process.execPath)) {
|
|
401
|
+
fail(
|
|
402
|
+
`Node is installed under a home directory (${process.execPath}), e.g. via nvm — the ${user} service user can't run it. ` +
|
|
403
|
+
'Install Node system-wide (NodeSource or your distro package), then reinstall: sudo npm install -g pulse-hub',
|
|
404
|
+
);
|
|
405
|
+
}
|
|
406
|
+
ok(`node ${process.versions.node} at ${process.execPath}`);
|
|
407
|
+
|
|
408
|
+
step('Service user and folders');
|
|
409
|
+
if (!userExists(user)) {
|
|
410
|
+
const nologin =
|
|
411
|
+
['/usr/sbin/nologin', '/sbin/nologin', '/bin/false'].find((p) => fs.existsSync(p)) ||
|
|
412
|
+
'/bin/false';
|
|
413
|
+
mustRun(
|
|
414
|
+
'useradd',
|
|
415
|
+
['--system', '--home-dir', DATA_DIR, '--no-create-home', '--shell', nologin, user],
|
|
416
|
+
`Creating user ${user}`,
|
|
417
|
+
);
|
|
418
|
+
ok(`created system user ${user}`);
|
|
419
|
+
} else {
|
|
420
|
+
ok(`user ${user} exists`);
|
|
421
|
+
}
|
|
422
|
+
fs.mkdirSync(DATA_DIR, { recursive: true, mode: 0o700 });
|
|
423
|
+
fs.chmodSync(DATA_DIR, 0o700);
|
|
424
|
+
const envDir = path.dirname(ENV_FILE);
|
|
425
|
+
fs.mkdirSync(envDir, { recursive: true, mode: 0o750 });
|
|
426
|
+
ok(`${DATA_DIR} and ${envDir} ready`);
|
|
427
|
+
|
|
428
|
+
// An old workflow/manual install (/opt/pulse-hub, same unit name) — its data would otherwise
|
|
429
|
+
// be silently replaced in the UI by a brand-new empty hub once our unit file overwrites
|
|
430
|
+
// its unit. Never deleted either way; only copied.
|
|
431
|
+
step('Existing data');
|
|
432
|
+
const legacyRoot = args.importFrom || DEFAULTS.legacyDir;
|
|
433
|
+
const legacyData = path.join(legacyRoot, 'backend', 'data');
|
|
434
|
+
const legacyEnv = path.join(legacyRoot, 'backend', '.env');
|
|
435
|
+
const haveDb = fs.existsSync(DB_FILE);
|
|
436
|
+
const legacyDb = fs.existsSync(path.join(legacyData, 'pulse.db'));
|
|
437
|
+
let doImport = false;
|
|
438
|
+
if (haveDb) {
|
|
439
|
+
ok(`using existing database ${DB_FILE}`);
|
|
440
|
+
if (args.importFrom)
|
|
441
|
+
warn(`--import-from ignored: ${DB_FILE} already exists (never overwritten).`);
|
|
442
|
+
} else if (args.importFrom) {
|
|
443
|
+
if (!legacyDb) fail(`--import-from ${legacyRoot}: no database at ${legacyData}/pulse.db`);
|
|
444
|
+
doImport = true;
|
|
445
|
+
} else if (legacyDb && !args.fresh) {
|
|
446
|
+
if (!interactive) {
|
|
447
|
+
fail(
|
|
448
|
+
`Found an existing Pulse install at ${legacyRoot}. Re-run with --import-from ${legacyRoot} to move its data ` +
|
|
449
|
+
'(users, servers, history, settings) into this install, or --fresh to start empty.',
|
|
450
|
+
);
|
|
451
|
+
}
|
|
452
|
+
const answer = await getPrompter().ask(
|
|
453
|
+
`Found an existing Pulse install at ${legacyRoot}. Import its data (users, servers, history)? (Y/n)`,
|
|
454
|
+
);
|
|
455
|
+
doImport = !/^n/i.test(answer);
|
|
456
|
+
} else {
|
|
457
|
+
ok('fresh install — a new database will be created on first start');
|
|
458
|
+
}
|
|
459
|
+
if (doImport) {
|
|
460
|
+
if (serviceActive()) {
|
|
461
|
+
mustRun(
|
|
462
|
+
'systemctl',
|
|
463
|
+
['stop', DEFAULTS.unit],
|
|
464
|
+
'Stopping the old hub before copying its database',
|
|
465
|
+
);
|
|
466
|
+
ok('stopped the old hub so its database is copied in a consistent state');
|
|
467
|
+
}
|
|
468
|
+
fs.cpSync(legacyData, DATA_DIR, { recursive: true });
|
|
469
|
+
ok(`copied ${legacyData} → ${DATA_DIR} (original left in place)`);
|
|
470
|
+
if (!fs.existsSync(ENV_FILE) && fs.existsSync(legacyEnv)) {
|
|
471
|
+
fs.copyFileSync(legacyEnv, ENV_FILE);
|
|
472
|
+
ok(`copied ${legacyEnv} → ${ENV_FILE}`);
|
|
473
|
+
}
|
|
474
|
+
}
|
|
475
|
+
|
|
476
|
+
step('Configuration');
|
|
477
|
+
if (!fs.existsSync(ENV_FILE)) {
|
|
478
|
+
fs.writeFileSync(ENV_FILE, envTemplate());
|
|
479
|
+
ok(`created ${ENV_FILE}`);
|
|
480
|
+
} else {
|
|
481
|
+
ok(`keeping existing ${ENV_FILE}`);
|
|
482
|
+
}
|
|
483
|
+
await fillConfig(args, interactive);
|
|
484
|
+
// Both the file AND its directory need the service group: a root:root 0750 directory
|
|
485
|
+
// makes the file unreachable, and dotenv fails silently on that — the hub would start
|
|
486
|
+
// with no config at all (caught in end-to-end testing).
|
|
487
|
+
mustRun('chown', [`root:${user}`, envDir, ENV_FILE], 'Setting config ownership');
|
|
488
|
+
fs.chmodSync(envDir, 0o750);
|
|
489
|
+
fs.chmodSync(ENV_FILE, 0o640);
|
|
490
|
+
ok(`${ENV_FILE} is root-writable, readable by ${user} only`);
|
|
491
|
+
|
|
492
|
+
const env = readEnvFile() || {};
|
|
493
|
+
if ((env.PULSE_SUPER_ADMIN_EMAILS || env.PULSE_SEED_ADMIN_EMAILS || '').trim()) {
|
|
494
|
+
step('Admin accounts');
|
|
495
|
+
runSeedAdmins();
|
|
496
|
+
}
|
|
497
|
+
fixOwnership(user);
|
|
498
|
+
|
|
499
|
+
step('systemd service');
|
|
500
|
+
writeUnitFile(user);
|
|
501
|
+
mustRun('systemctl', ['daemon-reload'], 'systemctl daemon-reload');
|
|
502
|
+
mustRun('systemctl', ['enable', DEFAULTS.unit], `Enabling ${DEFAULTS.unit}`);
|
|
503
|
+
// restart, not start: a re-run must replace an already-running (possibly old) process.
|
|
504
|
+
mustRun('systemctl', ['restart', DEFAULTS.unit], `Starting ${DEFAULTS.unit}`);
|
|
505
|
+
const addr = hubAddress(env);
|
|
506
|
+
const health = await waitForHealth(addr, installedVersion());
|
|
507
|
+
if (!serviceActive() || !health) {
|
|
508
|
+
bad(`${DEFAULTS.unit} did not come up on ${addr.host}:${addr.port}. Recent logs:`);
|
|
509
|
+
printRecentLogs();
|
|
510
|
+
fail(
|
|
511
|
+
'Setup finished configuring but the hub is not answering — see the logs above, fix, then re-run `sudo pulse-hub setup`.',
|
|
512
|
+
);
|
|
513
|
+
}
|
|
514
|
+
ok(`hub v${health.version} is running on ${addr.host}:${addr.port}`);
|
|
515
|
+
|
|
516
|
+
printConfigFindings(env);
|
|
517
|
+
printNextSteps(env, addr);
|
|
518
|
+
}
|
|
519
|
+
|
|
520
|
+
async function fillConfig(args, interactive) {
|
|
521
|
+
const env = readEnvFile() || {};
|
|
522
|
+
const updates = {};
|
|
523
|
+
const flagMap = {
|
|
524
|
+
publicUrl: 'PULSE_PUBLIC_URL',
|
|
525
|
+
googleClientId: 'PULSE_GOOGLE_CLIENT_ID',
|
|
526
|
+
googleClientSecret: 'PULSE_GOOGLE_CLIENT_SECRET',
|
|
527
|
+
adminEmail: 'PULSE_SUPER_ADMIN_EMAILS',
|
|
528
|
+
gmailAddress: 'PULSE_GMAIL_ADDRESS',
|
|
529
|
+
gmailAppPassword: 'PULSE_GMAIL_APP_PASSWORD',
|
|
530
|
+
port: 'PULSE_PORT',
|
|
531
|
+
};
|
|
532
|
+
for (const [flag, key] of Object.entries(flagMap)) {
|
|
533
|
+
if (typeof args[flag] === 'string' && args[flag].trim()) updates[key] = args[flag].trim();
|
|
534
|
+
}
|
|
535
|
+
const current = (k) => (updates[k] ?? env[k] ?? '').trim();
|
|
536
|
+
|
|
537
|
+
if (interactive) {
|
|
538
|
+
const prompter = getPrompter();
|
|
539
|
+
try {
|
|
540
|
+
if (!current('PULSE_PUBLIC_URL')) {
|
|
541
|
+
console.log(
|
|
542
|
+
`\nThe hub's public address — what people type in the browser, e.g. ${dim('https://example.com/monitor')}`,
|
|
543
|
+
);
|
|
544
|
+
updates.PULSE_PUBLIC_URL = (await askUntil(prompter, 'Public URL', validUrl)).replace(
|
|
545
|
+
/\/+$/,
|
|
546
|
+
'',
|
|
547
|
+
);
|
|
548
|
+
}
|
|
549
|
+
if (!current('PULSE_GOOGLE_CLIENT_ID') || !current('PULSE_GOOGLE_CLIENT_SECRET')) {
|
|
550
|
+
const redirect = `${current('PULSE_PUBLIC_URL').replace(/\/+$/, '')}/auth/google/callback`;
|
|
551
|
+
console.log(`
|
|
552
|
+
${bold('Google sign-in')} — Pulse logs people in with their Google account. It needs a
|
|
553
|
+
free OAuth client from Google Cloud (about 3 minutes):
|
|
554
|
+
1. Open ${bold('https://console.cloud.google.com/apis/credentials')} (create a project if asked)
|
|
555
|
+
2. If prompted, set up the OAuth consent screen first (External is fine; add your email)
|
|
556
|
+
3. ${bold('Create credentials → OAuth client ID')}, application type ${bold('Web application')}
|
|
557
|
+
4. Under ${bold('Authorized redirect URIs')} add exactly:
|
|
558
|
+
${green(redirect)}
|
|
559
|
+
5. Paste the client ID and secret below.`);
|
|
560
|
+
updates.PULSE_GOOGLE_CLIENT_ID = await askUntil(prompter, 'Google client ID', notEmpty, {
|
|
561
|
+
def: current('PULSE_GOOGLE_CLIENT_ID'),
|
|
562
|
+
});
|
|
563
|
+
updates.PULSE_GOOGLE_CLIENT_SECRET = await askUntil(
|
|
564
|
+
prompter,
|
|
565
|
+
'Google client secret (hidden)',
|
|
566
|
+
notEmpty,
|
|
567
|
+
{
|
|
568
|
+
secret: true,
|
|
569
|
+
},
|
|
570
|
+
);
|
|
571
|
+
}
|
|
572
|
+
if (!current('PULSE_SUPER_ADMIN_EMAILS')) {
|
|
573
|
+
console.log(
|
|
574
|
+
'\nThe Google account email(s) of the first admin(s) — full access, can invite everyone else.',
|
|
575
|
+
);
|
|
576
|
+
updates.PULSE_SUPER_ADMIN_EMAILS = await askUntil(prompter, 'Admin email', validEmails);
|
|
577
|
+
}
|
|
578
|
+
// Optional: only offered while email is unconfigured, and skipped if declined (default).
|
|
579
|
+
if (!current('PULSE_GMAIL_ADDRESS') && !current('PULSE_GMAIL_APP_PASSWORD')) {
|
|
580
|
+
console.log(`
|
|
581
|
+
${bold('Email (optional)')} — lets Pulse email invites to new users and send env-file backups.
|
|
582
|
+
Without it, new users can only be added with ${bold('pulse-hub seed-admins')}. It uses a Gmail account with
|
|
583
|
+
2-Step Verification and an App Password (${bold('https://myaccount.google.com/apppasswords')}),
|
|
584
|
+
not the account's real password. You can also set it up later in ${ENV_FILE}.`);
|
|
585
|
+
const answer = await prompter.ask('Set up email now? (y/N)');
|
|
586
|
+
if (/^y/i.test(answer)) {
|
|
587
|
+
updates.PULSE_GMAIL_ADDRESS = await askUntil(
|
|
588
|
+
prompter,
|
|
589
|
+
'Gmail address',
|
|
590
|
+
(v) => (validEmails(v) || v.includes(',') ? 'Enter a single email address.' : null),
|
|
591
|
+
);
|
|
592
|
+
updates.PULSE_GMAIL_APP_PASSWORD = (
|
|
593
|
+
await askUntil(prompter, 'App password (hidden)', notEmpty, { secret: true })
|
|
594
|
+
).replace(/\s+/g, '');
|
|
595
|
+
}
|
|
596
|
+
}
|
|
597
|
+
} finally {
|
|
598
|
+
prompter.close();
|
|
599
|
+
}
|
|
600
|
+
}
|
|
601
|
+
|
|
602
|
+
// The redirect URI is always derivable from the public URL — fill it unless the
|
|
603
|
+
// operator deliberately set something else.
|
|
604
|
+
const pub = current('PULSE_PUBLIC_URL').replace(/\/+$/, '');
|
|
605
|
+
if (pub && (!current('PULSE_GOOGLE_REDIRECT_URI') || updates.PULSE_PUBLIC_URL)) {
|
|
606
|
+
updates.PULSE_GOOGLE_REDIRECT_URI = `${pub}/auth/google/callback`;
|
|
607
|
+
}
|
|
608
|
+
|
|
609
|
+
if (Object.keys(updates).length) {
|
|
610
|
+
updateEnvFile(ENV_FILE, updates);
|
|
611
|
+
ok(`saved ${Object.keys(updates).join(', ')}`);
|
|
612
|
+
}
|
|
613
|
+
}
|
|
614
|
+
|
|
615
|
+
function writeUnitFile(user) {
|
|
616
|
+
const unit = `# Written by \`pulse-hub setup\` — re-run it rather than editing by hand.
|
|
617
|
+
[Unit]
|
|
618
|
+
Description=Pulse monitoring hub
|
|
619
|
+
After=network-online.target
|
|
620
|
+
Wants=network-online.target
|
|
621
|
+
|
|
622
|
+
[Service]
|
|
623
|
+
Type=simple
|
|
624
|
+
User=${user}
|
|
625
|
+
Group=${user}
|
|
626
|
+
Environment=NODE_ENV=production
|
|
627
|
+
Environment=PULSE_ENV_FILE=${ENV_FILE}
|
|
628
|
+
Environment=PULSE_DATA_DIR=${DATA_DIR}
|
|
629
|
+
ExecStart=${process.execPath} ${path.join(BACKEND_DIR, 'cli.js')} start
|
|
630
|
+
Restart=always
|
|
631
|
+
RestartSec=5
|
|
632
|
+
NoNewPrivileges=true
|
|
633
|
+
|
|
634
|
+
[Install]
|
|
635
|
+
WantedBy=multi-user.target
|
|
636
|
+
`;
|
|
637
|
+
fs.writeFileSync(DEFAULTS.unitFile, unit);
|
|
638
|
+
ok(`wrote ${DEFAULTS.unitFile}`);
|
|
639
|
+
}
|
|
640
|
+
|
|
641
|
+
function runSeedAdmins() {
|
|
642
|
+
const r = spawnSync(process.execPath, [path.join(BACKEND_DIR, 'seed-admins.js')], {
|
|
643
|
+
stdio: 'inherit',
|
|
644
|
+
env: process.env,
|
|
645
|
+
});
|
|
646
|
+
if (r.status !== 0) fail('seed-admins failed (see output above).');
|
|
647
|
+
}
|
|
648
|
+
|
|
649
|
+
function printConfigFindings(env) {
|
|
650
|
+
const { checkConfig } = require('./lib/config-check');
|
|
651
|
+
const findings = checkConfig(env);
|
|
652
|
+
if (!findings.length) return;
|
|
653
|
+
step('Configuration notes');
|
|
654
|
+
for (const f of findings) {
|
|
655
|
+
if (f.level === 'error') bad(f.message);
|
|
656
|
+
else warn(f.message);
|
|
657
|
+
}
|
|
658
|
+
}
|
|
659
|
+
|
|
660
|
+
function printNextSteps(env, addr) {
|
|
661
|
+
const pub = (env.PULSE_PUBLIC_URL || '').replace(/\/+$/, '');
|
|
662
|
+
let subpath = '/';
|
|
663
|
+
try {
|
|
664
|
+
subpath = pub ? new URL(pub).pathname.replace(/\/+$/, '') + '/' : '/';
|
|
665
|
+
} catch (e) {
|
|
666
|
+
/* keep / */
|
|
667
|
+
}
|
|
668
|
+
step('Next steps');
|
|
669
|
+
console.log(`1. Point nginx at the hub (inside your HTTPS server block), then reload nginx:
|
|
670
|
+
${dim(` location ${subpath} {
|
|
671
|
+
proxy_pass http://${addr.host}:${addr.port}/;
|
|
672
|
+
proxy_http_version 1.1;
|
|
673
|
+
proxy_set_header Upgrade $http_upgrade;
|
|
674
|
+
proxy_set_header Connection "upgrade";
|
|
675
|
+
proxy_set_header Host $host;
|
|
676
|
+
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
|
|
677
|
+
proxy_set_header X-Forwarded-Proto $scheme;
|
|
678
|
+
proxy_buffering off;
|
|
679
|
+
proxy_read_timeout 1h;${subpath !== '/' ? `\n proxy_redirect / ${subpath};` : ''}
|
|
680
|
+
}`)}
|
|
681
|
+
2. Open ${bold(pub || '<your public URL>')} and sign in with Google as the admin email.
|
|
682
|
+
3. To monitor this box too: Account → Add instance, and run the command it prints.
|
|
683
|
+
|
|
684
|
+
Later: ${bold('sudo pulse-hub upgrade')} for new versions, ${bold('sudo pulse-hub doctor')} if anything looks wrong.`);
|
|
685
|
+
}
|
|
686
|
+
|
|
687
|
+
// ---------------------------------------------------------------- upgrade
|
|
688
|
+
|
|
689
|
+
async function cmdUpgrade(args) {
|
|
690
|
+
requireRoot('upgrade');
|
|
691
|
+
const current = installedVersion();
|
|
692
|
+
let spec;
|
|
693
|
+
let target;
|
|
694
|
+
if (args.from) {
|
|
695
|
+
// Install from a local tarball (`npm pack` output) — for testing a release before
|
|
696
|
+
// publishing it, or for boxes without registry access.
|
|
697
|
+
const tgz = path.resolve(String(args.from));
|
|
698
|
+
if (!fs.existsSync(tgz)) fail(`No such file: ${tgz}`);
|
|
699
|
+
const r = mustRun(
|
|
700
|
+
'tar',
|
|
701
|
+
['-xOzf', tgz, 'package/package.json'],
|
|
702
|
+
'Reading the tarball’s version',
|
|
703
|
+
);
|
|
704
|
+
target = JSON.parse(r.stdout).version;
|
|
705
|
+
spec = tgz;
|
|
706
|
+
} else {
|
|
707
|
+
target =
|
|
708
|
+
typeof args.version === 'string' ? args.version.replace(/^v/, '') : latestPublishedVersion();
|
|
709
|
+
if (!target)
|
|
710
|
+
fail(
|
|
711
|
+
'Could not reach the npm registry to find the latest version (check outbound HTTPS), or pass --version X.Y.Z.',
|
|
712
|
+
);
|
|
713
|
+
spec = `${PACKAGE_NAME}@${target}`;
|
|
714
|
+
}
|
|
715
|
+
|
|
716
|
+
console.log(`Installed: v${current} Target: v${target}`);
|
|
717
|
+
if (compareSemver(target, current) <= 0 && !args.force) {
|
|
718
|
+
if (target === current) ok('Already up to date.');
|
|
719
|
+
else warn(`v${target} is older than what's installed — pass --force to downgrade.`);
|
|
720
|
+
return;
|
|
721
|
+
}
|
|
722
|
+
const user = args.user || DEFAULTS.user;
|
|
723
|
+
const addr = hubAddress();
|
|
724
|
+
|
|
725
|
+
step('Backing up the database and current version');
|
|
726
|
+
const backup = await backupDatabase(current);
|
|
727
|
+
ok(backup ? `saved ${backup}` : 'no database yet — nothing to back up');
|
|
728
|
+
// A copy of the installed package, so rollback never depends on the registry (or on the
|
|
729
|
+
// old version having come from it at all — e.g. it was installed with --from).
|
|
730
|
+
const pkgBackup = packCurrentVersion(current);
|
|
731
|
+
ok(`saved ${pkgBackup}`);
|
|
732
|
+
fixOwnership(user);
|
|
733
|
+
|
|
734
|
+
step(`Installing ${PACKAGE_NAME} v${target}`);
|
|
735
|
+
const inst = spawnSync(npmBin(), ['install', '-g', '--no-audit', '--no-fund', spec], {
|
|
736
|
+
stdio: 'inherit',
|
|
737
|
+
});
|
|
738
|
+
if (inst.status !== 0) fail(`npm install failed — nothing changed, still on v${current}.`);
|
|
739
|
+
const nowInstalled = installedVersion();
|
|
740
|
+
if (nowInstalled !== target)
|
|
741
|
+
fail(`npm finished but v${nowInstalled} is installed instead of v${target}.`);
|
|
742
|
+
ok(`v${target} installed`);
|
|
743
|
+
|
|
744
|
+
step('Restarting');
|
|
745
|
+
mustRun('systemctl', ['restart', DEFAULTS.unit], `Restarting ${DEFAULTS.unit}`);
|
|
746
|
+
const health = await waitForHealth(addr, target);
|
|
747
|
+
if (health && health.version === target && serviceActive()) {
|
|
748
|
+
ok(`hub v${target} is running`);
|
|
749
|
+
console.log(
|
|
750
|
+
`\n${green('Upgrade complete.')} If the dashboard looks unchanged, hard-refresh the browser.`,
|
|
751
|
+
);
|
|
752
|
+
return;
|
|
753
|
+
}
|
|
754
|
+
|
|
755
|
+
bad(`v${target} did not come up healthy. Recent logs:`);
|
|
756
|
+
printRecentLogs();
|
|
757
|
+
step(`Rolling back to v${current}`);
|
|
758
|
+
run('systemctl', ['stop', DEFAULTS.unit]);
|
|
759
|
+
if (backup) {
|
|
760
|
+
restoreDatabase(backup);
|
|
761
|
+
ok(`database restored from ${backup}`);
|
|
762
|
+
}
|
|
763
|
+
fixOwnership(user);
|
|
764
|
+
const rb = spawnSync(npmBin(), ['install', '-g', '--no-audit', '--no-fund', pkgBackup], {
|
|
765
|
+
stdio: 'inherit',
|
|
766
|
+
});
|
|
767
|
+
if (rb.status !== 0)
|
|
768
|
+
fail(
|
|
769
|
+
`Rollback install of v${current} failed — install it manually: sudo npm install -g ${pkgBackup}`,
|
|
770
|
+
);
|
|
771
|
+
mustRun('systemctl', ['restart', DEFAULTS.unit], `Restarting ${DEFAULTS.unit}`);
|
|
772
|
+
const back = await waitForHealth(addr, current);
|
|
773
|
+
if (back)
|
|
774
|
+
fail(
|
|
775
|
+
`Rolled back: v${current} is running again. v${target} was not kept — see the logs above.`,
|
|
776
|
+
);
|
|
777
|
+
fail(`Rolled back to v${current} but it isn't answering either — run: sudo pulse-hub doctor`);
|
|
778
|
+
}
|
|
779
|
+
|
|
780
|
+
function packCurrentVersion(version) {
|
|
781
|
+
fs.mkdirSync(BACKUP_DIR, { recursive: true, mode: 0o700 });
|
|
782
|
+
const pkgRoot = path.join(BACKEND_DIR, '..');
|
|
783
|
+
const r = run(
|
|
784
|
+
npmBin(),
|
|
785
|
+
['pack', pkgRoot, '--pack-destination', BACKUP_DIR, '--ignore-scripts', '--silent'],
|
|
786
|
+
{ timeout: 120 * 1000 },
|
|
787
|
+
);
|
|
788
|
+
const dest = path.join(BACKUP_DIR, `${PACKAGE_NAME}-${version}.tgz`);
|
|
789
|
+
if (!r.ok || !fs.existsSync(dest)) {
|
|
790
|
+
fail(
|
|
791
|
+
`Could not save a copy of v${version} for rollback (${r.stderr || r.stdout}) — upgrade aborted, nothing changed.`,
|
|
792
|
+
);
|
|
793
|
+
}
|
|
794
|
+
// Only the version being upgraded FROM is ever needed; drop older copies.
|
|
795
|
+
for (const f of fs.readdirSync(BACKUP_DIR)) {
|
|
796
|
+
if (/^pulse-hub-.*\.tgz$/.test(f) && f !== path.basename(dest)) {
|
|
797
|
+
fs.rmSync(path.join(BACKUP_DIR, f), { force: true });
|
|
798
|
+
}
|
|
799
|
+
}
|
|
800
|
+
return dest;
|
|
801
|
+
}
|
|
802
|
+
|
|
803
|
+
async function backupDatabase(version) {
|
|
804
|
+
if (!fs.existsSync(DB_FILE)) return null;
|
|
805
|
+
fs.mkdirSync(BACKUP_DIR, { recursive: true, mode: 0o700 });
|
|
806
|
+
const stamp = new Date().toISOString().replace(/[:.]/g, '-');
|
|
807
|
+
const dest = path.join(BACKUP_DIR, `pulse-v${version}-${stamp}.db`);
|
|
808
|
+
const Database = require('./lib/sqlite');
|
|
809
|
+
// Online backup: consistent even while the hub keeps writing.
|
|
810
|
+
const db = new Database(DB_FILE, { fileMustExist: true });
|
|
811
|
+
try {
|
|
812
|
+
await db.backup(dest);
|
|
813
|
+
} finally {
|
|
814
|
+
db.close();
|
|
815
|
+
}
|
|
816
|
+
if (!fs.existsSync(dest) || fs.statSync(dest).size === 0)
|
|
817
|
+
fail(`Database backup to ${dest} failed — upgrade aborted, nothing changed.`);
|
|
818
|
+
const old = fs
|
|
819
|
+
.readdirSync(BACKUP_DIR)
|
|
820
|
+
.filter((f) => /^pulse-v.*\.db$/.test(f))
|
|
821
|
+
.map((f) => ({ f, t: fs.statSync(path.join(BACKUP_DIR, f)).mtimeMs }))
|
|
822
|
+
.sort((a, b) => b.t - a.t)
|
|
823
|
+
.slice(BACKUPS_TO_KEEP);
|
|
824
|
+
for (const { f } of old) fs.rmSync(path.join(BACKUP_DIR, f), { force: true });
|
|
825
|
+
return dest;
|
|
826
|
+
}
|
|
827
|
+
|
|
828
|
+
function restoreDatabase(backup) {
|
|
829
|
+
for (const suffix of ['-wal', '-shm']) fs.rmSync(DB_FILE + suffix, { force: true });
|
|
830
|
+
fs.copyFileSync(backup, DB_FILE);
|
|
831
|
+
}
|
|
832
|
+
|
|
833
|
+
// ---------------------------------------------------------------- status / doctor
|
|
834
|
+
|
|
835
|
+
async function cmdStatus() {
|
|
836
|
+
const current = installedVersion();
|
|
837
|
+
const health = await getHealth(hubAddress());
|
|
838
|
+
const latest = latestPublishedVersion();
|
|
839
|
+
console.log(`installed v${current}`);
|
|
840
|
+
console.log(`service ${serviceActive() ? green('active') : red('not running')}`);
|
|
841
|
+
console.log(`responding ${health ? `v${health.version}` : red('no')}`);
|
|
842
|
+
if (latest) {
|
|
843
|
+
const newer = compareSemver(latest, current) > 0;
|
|
844
|
+
console.log(
|
|
845
|
+
`latest v${latest}${newer ? yellow(' ← update available: sudo pulse-hub upgrade') : ''}`,
|
|
846
|
+
);
|
|
847
|
+
} else {
|
|
848
|
+
console.log(`latest ${dim('unknown (registry unreachable)')}`);
|
|
849
|
+
}
|
|
850
|
+
}
|
|
851
|
+
|
|
852
|
+
async function cmdDoctor() {
|
|
853
|
+
let errors = 0;
|
|
854
|
+
const e = (m) => {
|
|
855
|
+
errors++;
|
|
856
|
+
bad(m);
|
|
857
|
+
};
|
|
858
|
+
console.log(bold(`Pulse hub v${installedVersion()} — doctor\n`));
|
|
859
|
+
|
|
860
|
+
if (nodeIsSupported()) ok(`node ${process.versions.node}`);
|
|
861
|
+
else e(NODE_TOO_OLD);
|
|
862
|
+
|
|
863
|
+
let env = null;
|
|
864
|
+
if (!fs.existsSync(ENV_FILE)) {
|
|
865
|
+
e(`no config file at ${ENV_FILE} — run: sudo pulse-hub setup`);
|
|
866
|
+
} else {
|
|
867
|
+
env = readEnvFile();
|
|
868
|
+
if (!env) {
|
|
869
|
+
e(`can't read ${ENV_FILE}${isRoot() ? '' : ' — re-run with sudo for full checks'}`);
|
|
870
|
+
} else {
|
|
871
|
+
ok(`config ${ENV_FILE}`);
|
|
872
|
+
// The hub runs as the service user, and dotenv ignores an unreadable file silently.
|
|
873
|
+
if (isRoot() && userExists(DEFAULTS.user) && run('runuser', ['--help']).ok) {
|
|
874
|
+
const readable = run('runuser', ['-u', DEFAULTS.user, '--', 'test', '-r', ENV_FILE]).ok;
|
|
875
|
+
if (!readable)
|
|
876
|
+
e(
|
|
877
|
+
`the ${DEFAULTS.user} service can't read ${ENV_FILE} — re-run: sudo pulse-hub setup (fixes ownership)`,
|
|
878
|
+
);
|
|
879
|
+
}
|
|
880
|
+
if (fs.statSync(ENV_FILE).mode & 0o004)
|
|
881
|
+
warn(`${ENV_FILE} is world-readable (holds secrets) — sudo chmod 640 ${ENV_FILE}`);
|
|
882
|
+
}
|
|
883
|
+
}
|
|
884
|
+
|
|
885
|
+
if (fs.existsSync(DATA_DIR)) {
|
|
886
|
+
ok(`data ${DATA_DIR}`);
|
|
887
|
+
} else {
|
|
888
|
+
e(`no data directory at ${DATA_DIR} — run: sudo pulse-hub setup`);
|
|
889
|
+
}
|
|
890
|
+
|
|
891
|
+
if (process.platform === 'linux') {
|
|
892
|
+
if (!fs.existsSync(DEFAULTS.unitFile))
|
|
893
|
+
e(`no systemd unit at ${DEFAULTS.unitFile} — run: sudo pulse-hub setup`);
|
|
894
|
+
else if (!serviceActive()) e(`${DEFAULTS.unit} is not running — check: sudo pulse-hub logs`);
|
|
895
|
+
else ok(`${DEFAULTS.unit} service is active`);
|
|
896
|
+
}
|
|
897
|
+
|
|
898
|
+
const addr = hubAddress(env || {});
|
|
899
|
+
const health = await getHealth(addr);
|
|
900
|
+
if (!health) e(`hub not answering on ${addr.host}:${addr.port}/healthz`);
|
|
901
|
+
else if (health.version !== installedVersion())
|
|
902
|
+
e(
|
|
903
|
+
`hub answering as v${health.version} but v${installedVersion()} is installed — restart it: sudo systemctl restart ${DEFAULTS.unit}`,
|
|
904
|
+
);
|
|
905
|
+
else ok(`hub answering on ${addr.host}:${addr.port} (v${health.version})`);
|
|
906
|
+
|
|
907
|
+
if (env) {
|
|
908
|
+
const { checkConfig } = require('./lib/config-check');
|
|
909
|
+
for (const f of checkConfig(env)) {
|
|
910
|
+
if (f.level === 'error') e(f.message);
|
|
911
|
+
else warn(f.message);
|
|
912
|
+
}
|
|
913
|
+
}
|
|
914
|
+
|
|
915
|
+
if (fs.existsSync(DB_FILE)) {
|
|
916
|
+
try {
|
|
917
|
+
const Database = require('./lib/sqlite');
|
|
918
|
+
const db = new Database(DB_FILE, { readonly: true, fileMustExist: true });
|
|
919
|
+
const cols = db
|
|
920
|
+
.prepare('PRAGMA table_info(users)')
|
|
921
|
+
.all()
|
|
922
|
+
.map((c) => c.name);
|
|
923
|
+
const roots = cols.includes('is_root')
|
|
924
|
+
? db.prepare('SELECT COUNT(*) AS n FROM users WHERE is_root = 1').get().n
|
|
925
|
+
: 0;
|
|
926
|
+
db.close();
|
|
927
|
+
if (roots > 0) ok(`${roots} admin account(s) with full access`);
|
|
928
|
+
else
|
|
929
|
+
e(
|
|
930
|
+
'no full-access admin yet — set PULSE_SUPER_ADMIN_EMAILS in the config, then: sudo pulse-hub seed-admins',
|
|
931
|
+
);
|
|
932
|
+
} catch (err) {
|
|
933
|
+
warn(
|
|
934
|
+
`couldn't inspect the database (${err.message})${isRoot() ? '' : ' — re-run with sudo'}`,
|
|
935
|
+
);
|
|
936
|
+
}
|
|
937
|
+
}
|
|
938
|
+
|
|
939
|
+
const latest = latestPublishedVersion();
|
|
940
|
+
if (latest && compareSemver(latest, installedVersion()) > 0)
|
|
941
|
+
warn(`v${latest} is available — sudo pulse-hub upgrade`);
|
|
942
|
+
|
|
943
|
+
console.log(
|
|
944
|
+
errors ? `\n${red(`${errors} problem(s) found.`)}` : `\n${green('Everything looks good.')}`,
|
|
945
|
+
);
|
|
946
|
+
if (errors) process.exitCode = 1;
|
|
947
|
+
}
|
|
948
|
+
|
|
949
|
+
// ---------------------------------------------------------------- dispatch
|
|
950
|
+
|
|
951
|
+
const HELP = `${bold('pulse-hub')} — self-hosted server monitoring hub (v${installedVersion()})
|
|
952
|
+
|
|
953
|
+
Usage: pulse-hub <command> [options]
|
|
954
|
+
|
|
955
|
+
setup Install/repair the hub service on this box (asks for anything missing)
|
|
956
|
+
--public-url URL --google-client-id ID --google-client-secret S
|
|
957
|
+
--admin-email a@b.c --gmail-address a@gmail.com --gmail-app-password P
|
|
958
|
+
--port N --import-from DIR --fresh --non-interactive
|
|
959
|
+
upgrade Upgrade to the latest version (DB backup, automatic rollback)
|
|
960
|
+
--version X.Y.Z --from file.tgz --force
|
|
961
|
+
status Service state and installed/running/latest versions
|
|
962
|
+
doctor Check configuration and health, and explain any problems
|
|
963
|
+
seed-admins Create/promote the emails in PULSE_SUPER_ADMIN_EMAILS / PULSE_SEED_ADMIN_EMAILS
|
|
964
|
+
logs Follow the hub's logs
|
|
965
|
+
start Run the hub in the foreground (used by the systemd service)
|
|
966
|
+
version Print the installed version
|
|
967
|
+
|
|
968
|
+
Config: ${ENV_FILE} Data: ${DATA_DIR}
|
|
969
|
+
Docs: ${path.join(BACKEND_DIR, '..', 'README.md')}`;
|
|
970
|
+
|
|
971
|
+
async function main() {
|
|
972
|
+
const args = parseArgs(process.argv.slice(2));
|
|
973
|
+
const cmd = args._[0] || 'help';
|
|
974
|
+
switch (cmd) {
|
|
975
|
+
case 'start':
|
|
976
|
+
if (!nodeIsSupported()) fail(NODE_TOO_OLD);
|
|
977
|
+
require('./server').startServer();
|
|
978
|
+
return;
|
|
979
|
+
case 'setup':
|
|
980
|
+
return cmdSetup(args);
|
|
981
|
+
case 'upgrade':
|
|
982
|
+
case 'update':
|
|
983
|
+
return cmdUpgrade(args);
|
|
984
|
+
case 'status':
|
|
985
|
+
return cmdStatus();
|
|
986
|
+
case 'doctor':
|
|
987
|
+
return cmdDoctor();
|
|
988
|
+
case 'seed-admins':
|
|
989
|
+
if (isRoot() && !fs.existsSync(ENV_FILE))
|
|
990
|
+
fail(`No config at ${ENV_FILE} — run: sudo pulse-hub setup`);
|
|
991
|
+
runSeedAdmins();
|
|
992
|
+
if (isRoot()) fixOwnership(args.user || DEFAULTS.user);
|
|
993
|
+
return;
|
|
994
|
+
case 'logs':
|
|
995
|
+
spawn('journalctl', ['-u', DEFAULTS.unit, '-f', '-n', '100'], { stdio: 'inherit' });
|
|
996
|
+
return;
|
|
997
|
+
case 'version':
|
|
998
|
+
case '--version':
|
|
999
|
+
case '-v':
|
|
1000
|
+
console.log(installedVersion());
|
|
1001
|
+
return;
|
|
1002
|
+
case 'help':
|
|
1003
|
+
case '--help':
|
|
1004
|
+
case '-h':
|
|
1005
|
+
console.log(HELP);
|
|
1006
|
+
return;
|
|
1007
|
+
default:
|
|
1008
|
+
console.error(`Unknown command: ${cmd}\n`);
|
|
1009
|
+
console.log(HELP);
|
|
1010
|
+
process.exitCode = 2;
|
|
1011
|
+
}
|
|
1012
|
+
}
|
|
1013
|
+
|
|
1014
|
+
main().catch((err) => {
|
|
1015
|
+
if (err instanceof CliError) {
|
|
1016
|
+
console.error(`\n${red('✗')} ${err.message}`);
|
|
1017
|
+
} else {
|
|
1018
|
+
console.error(err);
|
|
1019
|
+
}
|
|
1020
|
+
process.exit(1);
|
|
1021
|
+
});
|