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/CHANGELOG.md
ADDED
|
@@ -0,0 +1,28 @@
|
|
|
1
|
+
# Changelog
|
|
2
|
+
|
|
3
|
+
One version covers the hub and the agent. Newest first.
|
|
4
|
+
|
|
5
|
+
## 3.6.0
|
|
6
|
+
|
|
7
|
+
- `pulse-hub setup` now asks whether to set up email (Gmail address + App Password) for
|
|
8
|
+
invites and env-file backups. It defaults to no, and is also available as
|
|
9
|
+
`--gmail-address` / `--gmail-app-password`.
|
|
10
|
+
|
|
11
|
+
## 3.5.0
|
|
12
|
+
|
|
13
|
+
- The hub is now an installable npm package: `sudo npm install -g pulse-hub && sudo pulse-hub setup`.
|
|
14
|
+
- New `pulse-hub` command: `setup` (guided first-time setup, including Google sign-in and the
|
|
15
|
+
first admin), `upgrade` (database backup, health check, automatic rollback), `status`,
|
|
16
|
+
`doctor`, `seed-admins`, `logs`.
|
|
17
|
+
- The hub's config and data can live outside the code folder (`PULSE_ENV_FILE`,
|
|
18
|
+
`PULSE_DATA_DIR`); the npm install uses `/etc/pulse-hub/hub.env` and `/var/lib/pulse-hub`.
|
|
19
|
+
- The port and listen address are configurable (`PULSE_PORT`, `PULSE_HOST`).
|
|
20
|
+
- At startup the hub logs plain-language warnings about missing or inconsistent configuration.
|
|
21
|
+
- New `GET /healthz` endpoint reporting the running version.
|
|
22
|
+
- The database now uses Node's built-in SQLite (`node:sqlite`) instead of better-sqlite3, so
|
|
23
|
+
installing never downloads or compiles a native module. Requires **Node 22.16 or newer**
|
|
24
|
+
(Node 24 works). Existing `pulse.db` files are used as-is.
|
|
25
|
+
- `setup --import-from /opt/pulse-hub` moves an existing (workflow-deployed) hub's data into
|
|
26
|
+
the new install.
|
|
27
|
+
- Removed the AWS SSM deploy workflows (`deploy-hub.yml`, `deploy-hub-r2.yml`) and their
|
|
28
|
+
remote install scripts. The npm package replaces them.
|
package/LICENSE
ADDED
|
@@ -0,0 +1,5 @@
|
|
|
1
|
+
Copyright (c) 2026 tejasathalye. All rights reserved.
|
|
2
|
+
|
|
3
|
+
This software is published so it can be installed and run. No license is granted to copy,
|
|
4
|
+
modify, redistribute or sublicense it, other than installing and running unmodified copies
|
|
5
|
+
for your own use, unless the copyright holder gives written permission.
|
package/README.md
CHANGED
|
@@ -1,3 +1,87 @@
|
|
|
1
|
-
#
|
|
1
|
+
# Pulse
|
|
2
2
|
|
|
3
|
-
|
|
3
|
+
Lightweight, self-hosted server monitoring: one **hub** (dashboard, logins, history) and a
|
|
4
|
+
tiny **agent** on each server you want to watch. Agents only ever connect *out* to the hub —
|
|
5
|
+
no inbound ports, no third-party cloud, no Docker, no database server. Built for small boxes
|
|
6
|
+
(it runs comfortably on a 2 GB EC2 instance).
|
|
7
|
+
|
|
8
|
+
- Live CPU / memory / disk / network metrics with 7 days of history
|
|
9
|
+
- PM2, systemd and Docker container logs, streamed live
|
|
10
|
+
- Restart services and edit env files remotely, with encrypted version history
|
|
11
|
+
- Google sign-in, teams and fine-grained permissions, full audit log
|
|
12
|
+
- Agents update themselves when the hub is upgraded
|
|
13
|
+
|
|
14
|
+
## Install the hub
|
|
15
|
+
|
|
16
|
+
On a Linux server with systemd (Ubuntu, Debian, Amazon Linux…):
|
|
17
|
+
|
|
18
|
+
**1. Install Node.js 22 or newer** (skip if `node -v` already shows v22.16+):
|
|
19
|
+
|
|
20
|
+
```bash
|
|
21
|
+
curl -fsSL https://deb.nodesource.com/setup_22.x | sudo bash - # Ubuntu/Debian
|
|
22
|
+
sudo apt-get install -y nodejs
|
|
23
|
+
```
|
|
24
|
+
|
|
25
|
+
Install Node system-wide like this, not with nvm: the hub runs as its own service user, and
|
|
26
|
+
that user can't see a Node installed in your home folder.
|
|
27
|
+
|
|
28
|
+
**2. Install and set up Pulse:**
|
|
29
|
+
|
|
30
|
+
```bash
|
|
31
|
+
sudo npm install -g pulse-hub
|
|
32
|
+
sudo pulse-hub setup
|
|
33
|
+
```
|
|
34
|
+
|
|
35
|
+
`setup` asks for everything it needs: the hub's public URL, a Google OAuth client (it explains
|
|
36
|
+
how to create one, in about 3 minutes), and the email of the first admin. Then it creates the
|
|
37
|
+
service, starts it, and prints the nginx snippet to put in front of it.
|
|
38
|
+
|
|
39
|
+
**3. Put nginx in front** (setup prints the exact block for your URL), reload nginx, open your
|
|
40
|
+
public URL and sign in with Google.
|
|
41
|
+
|
|
42
|
+
**4. Monitor servers:** in the dashboard, go to **Account → Add instance** and run the command
|
|
43
|
+
it shows on each server, including the hub's own box if you want it monitored.
|
|
44
|
+
|
|
45
|
+
## Upgrade
|
|
46
|
+
|
|
47
|
+
```bash
|
|
48
|
+
sudo pulse-hub upgrade
|
|
49
|
+
```
|
|
50
|
+
|
|
51
|
+
This backs up the database, installs the latest version, restarts, and checks that the new
|
|
52
|
+
version is answering. If it isn't, it rolls back automatically to the previous version and
|
|
53
|
+
database. Agents pick up the new version on their own afterwards.
|
|
54
|
+
|
|
55
|
+
## Commands
|
|
56
|
+
|
|
57
|
+
| Command | What it does |
|
|
58
|
+
| --- | --- |
|
|
59
|
+
| `sudo pulse-hub setup` | First-time install, or re-run any time to repair/reconfigure |
|
|
60
|
+
| `sudo pulse-hub upgrade` | Upgrade to the latest version (`--version X.Y.Z` for a specific one) |
|
|
61
|
+
| `pulse-hub status` | Is it running, which version, is there a newer one |
|
|
62
|
+
| `sudo pulse-hub doctor` | Checks config and health and explains anything wrong |
|
|
63
|
+
| `sudo pulse-hub seed-admins` | Apply admin emails after editing the config |
|
|
64
|
+
| `sudo pulse-hub logs` | Follow the hub's logs |
|
|
65
|
+
|
|
66
|
+
## Where things live
|
|
67
|
+
|
|
68
|
+
| | |
|
|
69
|
+
| --- | --- |
|
|
70
|
+
| Config | `/etc/pulse-hub/hub.env`, then `sudo systemctl restart pulse-hub` |
|
|
71
|
+
| Data (SQLite) | `/var/lib/pulse-hub/pulse.db`, plus upgrade backups in `backups/` |
|
|
72
|
+
| Service | `pulse-hub.service`, runs as the `pulse-hub` user on `127.0.0.1:5080` |
|
|
73
|
+
|
|
74
|
+
Back up `/var/lib/pulse-hub` and `/etc/pulse-hub` and you have everything.
|
|
75
|
+
|
|
76
|
+
## Troubleshooting
|
|
77
|
+
|
|
78
|
+
Start with `sudo pulse-hub doctor`: it checks the service, the config, the Google sign-in
|
|
79
|
+
settings and whether an admin exists, and says what to do about each problem. For details,
|
|
80
|
+
use `sudo pulse-hub logs`.
|
|
81
|
+
|
|
82
|
+
- **"redirect_uri_mismatch" from Google**: the redirect URI in your Google OAuth client
|
|
83
|
+
must exactly match `PULSE_GOOGLE_REDIRECT_URI` in `/etc/pulse-hub/hub.env`
|
|
84
|
+
(`<public URL>/auth/google/callback`).
|
|
85
|
+
- **Signed in but "not allowed"**: add your email to `PULSE_SUPER_ADMIN_EMAILS` in the config,
|
|
86
|
+
then run `sudo pulse-hub seed-admins`.
|
|
87
|
+
- **Dashboard still shows the old version after upgrading**: hard-refresh the browser.
|
|
@@ -0,0 +1,52 @@
|
|
|
1
|
+
# Copy to backend/.env (gitignored, never commit) — or, for an npm-installed hub, this is
|
|
2
|
+
# /etc/pulse-hub/hub.env (written by `sudo pulse-hub setup`; PULSE_ENV_FILE points elsewhere). Loaded via dotenv on startup; a var
|
|
3
|
+
# already set another way (systemd Environment=, a shell export) always wins over this
|
|
4
|
+
# file. Sign-in is Google-only (password login was removed) — the three Google OAuth
|
|
5
|
+
# vars below are REQUIRED for anyone to be able to log in at all. Everything else is
|
|
6
|
+
# optional: with only the Google vars set, sessions default to 1 hour with an
|
|
7
|
+
# auto-generated signing key, no invite-by-email, and PULSE_SEED_ADMIN_EMAILS is how a
|
|
8
|
+
# fresh install gets its first user.
|
|
9
|
+
|
|
10
|
+
# ---- Sessions ----
|
|
11
|
+
PULSE_JWT_SECRET= # signing key for session tokens; unset = auto-generated into data/pulse.db
|
|
12
|
+
PULSE_SESSION_MAX_AGE_SECONDS=3600 # session lifetime in seconds
|
|
13
|
+
|
|
14
|
+
# ---- Env file editor (see docs/env-files.md) ----
|
|
15
|
+
PULSE_ENV_ENCRYPTION_KEY= # encrypts saved env-file versions at rest; unset = auto-generated into data/pulse.db (same file as the ciphertext, so set this to keep the key off the DB). Changing it makes old versions unreadable.
|
|
16
|
+
|
|
17
|
+
# ---- Google OAuth (required — this is the only way to sign in; see "Invite emails" below for invite sending) ----
|
|
18
|
+
PULSE_GOOGLE_CLIENT_ID= # OAuth 2.0 Web application client ID
|
|
19
|
+
PULSE_GOOGLE_CLIENT_SECRET= # OAuth 2.0 client secret
|
|
20
|
+
PULSE_GOOGLE_REDIRECT_URI=https://your-hub-domain.example/auth/google/callback # must exactly match the client's authorized redirect URI
|
|
21
|
+
|
|
22
|
+
# ---- Invite emails ----
|
|
23
|
+
# One shared Gmail account sends every invite, regardless of who clicks "invite" — not a
|
|
24
|
+
# per-user OAuth consent flow. Enable 2-Step Verification on that account, then create an
|
|
25
|
+
# App Password (https://myaccount.google.com/apppasswords) and use it here, not the
|
|
26
|
+
# account's real password.
|
|
27
|
+
PULSE_GMAIL_ADDRESS= # the shared Gmail account's address, e.g. pulse@example.com
|
|
28
|
+
PULSE_GMAIL_APP_PASSWORD= # that account's 16-character App Password
|
|
29
|
+
PULSE_PUBLIC_URL=https://your-hub-domain.example # hub's public base URL, used to build invite email links (no trailing slash)
|
|
30
|
+
|
|
31
|
+
# ---- Seed allowed emails ----
|
|
32
|
+
# On a fresh install this is how you get your FIRST user — there is no default
|
|
33
|
+
# admin/admin account anymore, and the invite flow needs an existing user to send one.
|
|
34
|
+
PULSE_SEED_ADMIN_EMAILS=alice@example.com,bob@example.com # comma-separated emails allowed to sign in with Google without an invite; run `npm run seed-admins` after editing
|
|
35
|
+
|
|
36
|
+
# ---- Roles: initial/additional super admins ----
|
|
37
|
+
# super_admin is Pulse's top role (see CLAUDE.md's "Auth model" / roles) — can manage
|
|
38
|
+
# every user's role (admin <-> viewer) and remove anyone but another super_admin. It is
|
|
39
|
+
# NEVER assignable from the Team page UI; the only way in is this env var followed by
|
|
40
|
+
# `npm run seed-admins` (creates the user if new, promotes them if already known — safe
|
|
41
|
+
# to re-run any time you add someone here). Every other pre-existing user becomes a
|
|
42
|
+
# plain 'admin' the first time a hub upgrades onto roles, so nobody loses access
|
|
43
|
+
# silently — see backend/lib/db.js's role migration.
|
|
44
|
+
PULSE_SUPER_ADMIN_EMAILS=alice@example.com # comma-separated; run `npm run seed-admins` after editing
|
|
45
|
+
|
|
46
|
+
# How long audit-log rows are kept before the hourly prune deletes them (days).
|
|
47
|
+
PULSE_AUDIT_RETENTION_DAYS=180
|
|
48
|
+
|
|
49
|
+
# ---- Network ----
|
|
50
|
+
# Where the hub listens. Keep 127.0.0.1 and put nginx in front of it.
|
|
51
|
+
PULSE_HOST=127.0.0.1
|
|
52
|
+
PULSE_PORT=5080
|
|
@@ -0,0 +1,9 @@
|
|
|
1
|
+
{
|
|
2
|
+
"name": "pulse-agent",
|
|
3
|
+
"private": true,
|
|
4
|
+
"version": "0.0.0-overwritten-at-bundle-time",
|
|
5
|
+
"description": "Minimal manifest shipped inside /agent-bundle.tar.gz as package.json — deliberately excludes hub-only runtime deps (e.g. nodemailer, pdfkit) and all frontend devDependencies from the real package.json one level up, so a monitored box only ever installs what agent.js/lib/*.js actually require. See lib/bundle-version.js and routes/static.js's /agent-bundle.tar.gz handler. The \"version\" field above is cosmetic/unused on disk — routes/static.js overwrites it with the real package.json's version at bundle-build time, so every installed agent reports the actual deployed version. Don't hand-edit it expecting it to matter.",
|
|
6
|
+
"dependencies": {
|
|
7
|
+
"ws": "^8.18.0"
|
|
8
|
+
}
|
|
9
|
+
}
|
package/backend/agent.js
ADDED
|
@@ -0,0 +1,372 @@
|
|
|
1
|
+
const fs = require('fs');
|
|
2
|
+
const path = require('path');
|
|
3
|
+
const WebSocket = require('ws');
|
|
4
|
+
const {
|
|
5
|
+
getSystemMetrics,
|
|
6
|
+
getPm2Processes,
|
|
7
|
+
getDockerContainers,
|
|
8
|
+
getSystemdUnits,
|
|
9
|
+
checkDockerAvailable,
|
|
10
|
+
checkSystemdAvailable,
|
|
11
|
+
} = require('./lib/metrics');
|
|
12
|
+
const {
|
|
13
|
+
getFilteredRecords,
|
|
14
|
+
getFilteredDockerRecords,
|
|
15
|
+
getFilteredJournalRecords,
|
|
16
|
+
createTailer,
|
|
17
|
+
createDockerTailer,
|
|
18
|
+
createJournalTailer,
|
|
19
|
+
} = require('./lib/logs');
|
|
20
|
+
const { computeBundleVersion, readPackageJson } = require('./lib/bundle-version');
|
|
21
|
+
const { selfUpdate } = require('./lib/self-update');
|
|
22
|
+
const { readEnvFile, writeEnvFile, restartUnit } = require('./lib/env-files');
|
|
23
|
+
|
|
24
|
+
const CONFIG_FILE = path.join(__dirname, 'agent.config.json');
|
|
25
|
+
const IDLE_INTERVAL_MS = 5 * 60 * 1000;
|
|
26
|
+
const RECONNECT_MIN_MS = 2000;
|
|
27
|
+
const RECONNECT_MAX_MS = 30000;
|
|
28
|
+
|
|
29
|
+
function loadConfig() {
|
|
30
|
+
let fileConfig = {};
|
|
31
|
+
try {
|
|
32
|
+
fileConfig = JSON.parse(fs.readFileSync(CONFIG_FILE, 'utf-8'));
|
|
33
|
+
} catch (e) {}
|
|
34
|
+
const hubUrl = process.env.PULSE_HUB_URL || fileConfig.hubUrl;
|
|
35
|
+
const instanceId = process.env.PULSE_INSTANCE_ID || fileConfig.instanceId;
|
|
36
|
+
const token = process.env.PULSE_TOKEN || fileConfig.token;
|
|
37
|
+
if (!hubUrl || !instanceId || !token) {
|
|
38
|
+
console.error(
|
|
39
|
+
'Missing agent config. Provide agent.config.json (see agent.config.example.json) or PULSE_HUB_URL/PULSE_INSTANCE_ID/PULSE_TOKEN env vars.',
|
|
40
|
+
);
|
|
41
|
+
process.exit(1);
|
|
42
|
+
}
|
|
43
|
+
// Optional — lets the hub's Groups feature match this instance without an admin
|
|
44
|
+
// enumerating it explicitly (see CLAUDE.md's "Auth model" / Groups). Set via
|
|
45
|
+
// install-agent.sh's --tag flag (agent.config.json's "tags" array) or PULSE_TAGS
|
|
46
|
+
// (comma-separated). Re-sent on every hello, so it stays in sync on reconnect.
|
|
47
|
+
const tags = process.env.PULSE_TAGS
|
|
48
|
+
? process.env.PULSE_TAGS.split(',')
|
|
49
|
+
.map((t) => t.trim())
|
|
50
|
+
.filter(Boolean)
|
|
51
|
+
: Array.isArray(fileConfig.tags)
|
|
52
|
+
? fileConfig.tags
|
|
53
|
+
: [];
|
|
54
|
+
return { hubUrl, instanceId, token, tags };
|
|
55
|
+
}
|
|
56
|
+
|
|
57
|
+
const { hubUrl, instanceId, token, tags } = loadConfig();
|
|
58
|
+
// Staleness signal for the hub's self-update check — see maybeAutoUpdateSelf in
|
|
59
|
+
// ws/agent-relay.js and .claude/rules/version-bump-policy.md. Not shown to a person.
|
|
60
|
+
const AGENT_BUNDLE_HASH = computeBundleVersion(__dirname);
|
|
61
|
+
// Human-facing semver, read from whichever package.json ships alongside this agent
|
|
62
|
+
// (see lib/bundle-version.js's readPackageJson) — shown in the hub's UI.
|
|
63
|
+
const AGENT_APP_VERSION = (readPackageJson(__dirname) || {}).version || 'unknown';
|
|
64
|
+
// Tells the hub which optional request types this build understands, so it can say "update
|
|
65
|
+
// this agent" instead of waiting out a timeout for a frame an older agent silently ignores.
|
|
66
|
+
const AGENT_CAPABILITIES = ['env-files', 'restart-agent'];
|
|
67
|
+
// How often to re-scan for new/removed/changed services between metrics pushes. Without
|
|
68
|
+
// this the process list only refreshed on the (up to 5 minute) idle metrics push, so a
|
|
69
|
+
// freshly deployed service looked "missing" until the agent was restarted.
|
|
70
|
+
const DISCOVERY_INTERVAL_MS = 30 * 1000;
|
|
71
|
+
|
|
72
|
+
// Last-resort guards: a monitoring agent that dies on one bad frame or a stray rejected
|
|
73
|
+
// promise leaves the box unmonitored. Log and keep going; but if errors are arriving in a
|
|
74
|
+
// storm the process state is probably bad, so exit and let the supervisor start it clean.
|
|
75
|
+
const recentFatals = [];
|
|
76
|
+
function survive(kind, err) {
|
|
77
|
+
console.error(`${kind}:`, err && err.stack ? err.stack : err);
|
|
78
|
+
const now = Date.now();
|
|
79
|
+
recentFatals.push(now);
|
|
80
|
+
while (recentFatals.length && now - recentFatals[0] > 60 * 1000) recentFatals.shift();
|
|
81
|
+
if (recentFatals.length > 10) {
|
|
82
|
+
console.error('Too many unexpected errors in the last minute — exiting for a clean restart.');
|
|
83
|
+
process.exit(1);
|
|
84
|
+
}
|
|
85
|
+
}
|
|
86
|
+
process.on('uncaughtException', (e) => survive('uncaughtException', e));
|
|
87
|
+
process.on('unhandledRejection', (e) => survive('unhandledRejection', e));
|
|
88
|
+
|
|
89
|
+
let ws = null;
|
|
90
|
+
let discoveryTimer = null;
|
|
91
|
+
let lastProcessFingerprint = null;
|
|
92
|
+
let updating = false;
|
|
93
|
+
let metricsTimer = null;
|
|
94
|
+
let reconnectDelay = RECONNECT_MIN_MS;
|
|
95
|
+
const activeTails = new Map(); // key `${app}:${stream}` -> tailer handle
|
|
96
|
+
|
|
97
|
+
function send(frame) {
|
|
98
|
+
if (ws && ws.readyState === WebSocket.OPEN) ws.send(JSON.stringify(frame));
|
|
99
|
+
}
|
|
100
|
+
|
|
101
|
+
function pushMetrics() {
|
|
102
|
+
send({ type: 'metrics', ts: Date.now(), ...getSystemMetrics() });
|
|
103
|
+
}
|
|
104
|
+
|
|
105
|
+
function scheduleMetrics(intervalMs) {
|
|
106
|
+
if (metricsTimer) clearInterval(metricsTimer);
|
|
107
|
+
metricsTimer = setInterval(pushMetrics, intervalMs);
|
|
108
|
+
}
|
|
109
|
+
|
|
110
|
+
// Identity + state of every service the agent can see (no cpu/memory, which change
|
|
111
|
+
// constantly). A change means something was deployed, removed, stopped or restarted.
|
|
112
|
+
function processFingerprint() {
|
|
113
|
+
const systemd = checkSystemdAvailable();
|
|
114
|
+
return [
|
|
115
|
+
...getPm2Processes().map((p) => `pm2:${p.name}:${p.status}`),
|
|
116
|
+
...getDockerContainers().map((c) => `docker:${c.name}:${c.status}`),
|
|
117
|
+
...(systemd.ok ? getSystemdUnits().map((u) => `systemd:${u.name}`) : []),
|
|
118
|
+
]
|
|
119
|
+
.sort()
|
|
120
|
+
.join('\n');
|
|
121
|
+
}
|
|
122
|
+
|
|
123
|
+
// Cheap poll that pushes a full metrics frame as soon as the service set changes, so new
|
|
124
|
+
// services show up (and become selectable on the Logs page) without waiting for the next
|
|
125
|
+
// scheduled push or an agent restart.
|
|
126
|
+
function checkForNewServices() {
|
|
127
|
+
if (!ws || ws.readyState !== WebSocket.OPEN) return;
|
|
128
|
+
try {
|
|
129
|
+
const fp = processFingerprint();
|
|
130
|
+
if (lastProcessFingerprint !== null && fp !== lastProcessFingerprint) pushMetrics();
|
|
131
|
+
lastProcessFingerprint = fp;
|
|
132
|
+
} catch (e) {
|
|
133
|
+
// Discovery must never take the agent down.
|
|
134
|
+
}
|
|
135
|
+
}
|
|
136
|
+
|
|
137
|
+
function scheduleDiscovery() {
|
|
138
|
+
if (discoveryTimer) clearInterval(discoveryTimer);
|
|
139
|
+
lastProcessFingerprint = null; // first tick after (re)connect just records a baseline
|
|
140
|
+
discoveryTimer = setInterval(checkForNewServices, DISCOVERY_INTERVAL_MS);
|
|
141
|
+
}
|
|
142
|
+
|
|
143
|
+
// Operator-triggered (hub's restart-agent route). Exits cleanly and relies on the
|
|
144
|
+
// supervisor (systemd Restart=always, installed by install-agent.sh; or PM2) to start a
|
|
145
|
+
// fresh process — which also picks up OS group changes (docker, systemd-journal) that a
|
|
146
|
+
// running process never sees.
|
|
147
|
+
function performRestart() {
|
|
148
|
+
console.log('Restart requested by hub — exiting so the supervisor restarts this agent.');
|
|
149
|
+
stopAllTails();
|
|
150
|
+
setTimeout(() => process.exit(0), 200);
|
|
151
|
+
}
|
|
152
|
+
|
|
153
|
+
function resolveLogFile(app, stream) {
|
|
154
|
+
const proc = getPm2Processes().find((p) => p.name === app);
|
|
155
|
+
if (!proc) return null;
|
|
156
|
+
return stream === 'err' ? proc.err_log : proc.out_log;
|
|
157
|
+
}
|
|
158
|
+
|
|
159
|
+
function resolveDockerContainer(app) {
|
|
160
|
+
const container = getDockerContainers().find((c) => c.name === app);
|
|
161
|
+
return container ? container.containerId : null;
|
|
162
|
+
}
|
|
163
|
+
|
|
164
|
+
// Only ever hand journalctl a unit name that's in the agent's own live list — the name
|
|
165
|
+
// arrives over the wire from the hub.
|
|
166
|
+
function resolveSystemdUnit(app) {
|
|
167
|
+
const unit = getSystemdUnits().find((u) => u.name === app);
|
|
168
|
+
return unit ? unit.name : null;
|
|
169
|
+
}
|
|
170
|
+
|
|
171
|
+
function handleGetLogs(msg) {
|
|
172
|
+
let all;
|
|
173
|
+
if (msg.kind === 'systemd') {
|
|
174
|
+
all = getFilteredJournalRecords(resolveSystemdUnit(msg.app), msg.search, msg.level);
|
|
175
|
+
} else if (msg.kind === 'docker') {
|
|
176
|
+
const containerId = resolveDockerContainer(msg.app);
|
|
177
|
+
all = getFilteredDockerRecords(containerId, msg.stream, msg.search, msg.level);
|
|
178
|
+
} else {
|
|
179
|
+
const filePath = resolveLogFile(msg.app, msg.stream);
|
|
180
|
+
all = getFilteredRecords(filePath, msg.search, msg.level);
|
|
181
|
+
}
|
|
182
|
+
const records = all.slice(msg.offset || 0, (msg.offset || 0) + (msg.limit || 20));
|
|
183
|
+
send({ type: 'logs_chunk', requestId: msg.requestId, records, total: all.length });
|
|
184
|
+
}
|
|
185
|
+
|
|
186
|
+
function handleTailLogs(msg) {
|
|
187
|
+
const key = `${msg.kind}:${msg.app}:${msg.stream}`;
|
|
188
|
+
stopTail(key);
|
|
189
|
+
const search = msg.search,
|
|
190
|
+
level = msg.level;
|
|
191
|
+
function matches(record) {
|
|
192
|
+
if (level && String(record.level) !== String(level)) return false;
|
|
193
|
+
if (search && !JSON.stringify(record).toLowerCase().includes(search.toLowerCase()))
|
|
194
|
+
return false;
|
|
195
|
+
return true;
|
|
196
|
+
}
|
|
197
|
+
const onRecord = (record) =>
|
|
198
|
+
send({ type: 'log_line', app: msg.app, stream: msg.stream, kind: msg.kind, record });
|
|
199
|
+
let tailer;
|
|
200
|
+
if (msg.kind === 'systemd')
|
|
201
|
+
tailer = createJournalTailer(resolveSystemdUnit(msg.app), matches, onRecord);
|
|
202
|
+
else if (msg.kind === 'docker')
|
|
203
|
+
tailer = createDockerTailer(resolveDockerContainer(msg.app), msg.stream, matches, onRecord);
|
|
204
|
+
else tailer = createTailer(resolveLogFile(msg.app, msg.stream), matches, onRecord);
|
|
205
|
+
activeTails.set(key, tailer);
|
|
206
|
+
}
|
|
207
|
+
|
|
208
|
+
function stopTail(key) {
|
|
209
|
+
const existing = activeTails.get(key);
|
|
210
|
+
if (existing) {
|
|
211
|
+
existing.stop();
|
|
212
|
+
activeTails.delete(key);
|
|
213
|
+
}
|
|
214
|
+
}
|
|
215
|
+
|
|
216
|
+
function stopAllTails() {
|
|
217
|
+
for (const key of activeTails.keys()) stopTail(key);
|
|
218
|
+
}
|
|
219
|
+
|
|
220
|
+
// Request/response frames for the env-file editor (see lib/env-files.js,
|
|
221
|
+
// docs/env-files.md): every one is answered with exactly one 'rpc_result' carrying the
|
|
222
|
+
// hub's requestId, success or failure — a failure must never throw out of here and take
|
|
223
|
+
// the agent down.
|
|
224
|
+
async function handleRpc(msg, fn) {
|
|
225
|
+
try {
|
|
226
|
+
const result = await fn();
|
|
227
|
+
send({ type: 'rpc_result', requestId: msg.requestId, ...result, ok: true });
|
|
228
|
+
} catch (e) {
|
|
229
|
+
send({
|
|
230
|
+
type: 'rpc_result',
|
|
231
|
+
requestId: msg.requestId,
|
|
232
|
+
ok: false,
|
|
233
|
+
code: e.code || 'ERROR',
|
|
234
|
+
error: e.message || String(e),
|
|
235
|
+
});
|
|
236
|
+
}
|
|
237
|
+
}
|
|
238
|
+
|
|
239
|
+
// Triggered by the hub, never automatically — see lib/self-update.js. A failure here
|
|
240
|
+
// must never take the agent down: it logs and keeps running the code already loaded in
|
|
241
|
+
// memory, so a bad bundle doesn't leave this box unmonitored.
|
|
242
|
+
async function performSelfUpdate() {
|
|
243
|
+
if (updating) {
|
|
244
|
+
console.log('Self-update already in progress, ignoring duplicate request.');
|
|
245
|
+
return;
|
|
246
|
+
}
|
|
247
|
+
updating = true;
|
|
248
|
+
console.log(
|
|
249
|
+
'Self-update requested by hub — downloading and installing the current agent bundle...',
|
|
250
|
+
);
|
|
251
|
+
try {
|
|
252
|
+
await selfUpdate({ hubUrl, instanceId, token, installDir: __dirname });
|
|
253
|
+
console.log(
|
|
254
|
+
'Self-update succeeded — exiting so systemd restarts this service with the new code.',
|
|
255
|
+
);
|
|
256
|
+
process.exit(0);
|
|
257
|
+
} catch (e) {
|
|
258
|
+
console.error('Self-update failed, continuing to run the current version:', e.message);
|
|
259
|
+
updating = false;
|
|
260
|
+
}
|
|
261
|
+
}
|
|
262
|
+
|
|
263
|
+
function connect() {
|
|
264
|
+
ws = new WebSocket(hubUrl);
|
|
265
|
+
|
|
266
|
+
ws.on('open', () => {
|
|
267
|
+
send({
|
|
268
|
+
type: 'hello',
|
|
269
|
+
instanceId,
|
|
270
|
+
token,
|
|
271
|
+
bundleHash: AGENT_BUNDLE_HASH,
|
|
272
|
+
appVersion: AGENT_APP_VERSION,
|
|
273
|
+
tags,
|
|
274
|
+
capabilities: AGENT_CAPABILITIES,
|
|
275
|
+
});
|
|
276
|
+
});
|
|
277
|
+
|
|
278
|
+
ws.on('message', (raw) => {
|
|
279
|
+
let msg;
|
|
280
|
+
try {
|
|
281
|
+
msg = JSON.parse(raw);
|
|
282
|
+
} catch (e) {
|
|
283
|
+
return;
|
|
284
|
+
}
|
|
285
|
+
try {
|
|
286
|
+
handleFrame(msg);
|
|
287
|
+
} catch (e) {
|
|
288
|
+
console.error(`Error handling '${msg && msg.type}' frame:`, e && e.message);
|
|
289
|
+
}
|
|
290
|
+
});
|
|
291
|
+
|
|
292
|
+
function handleFrame(msg) {
|
|
293
|
+
if (msg.type === 'hello_ack') {
|
|
294
|
+
reconnectDelay = RECONNECT_MIN_MS;
|
|
295
|
+
pushMetrics();
|
|
296
|
+
scheduleMetrics(IDLE_INTERVAL_MS);
|
|
297
|
+
scheduleDiscovery();
|
|
298
|
+
} else if (msg.type === 'hello_reject') {
|
|
299
|
+
// Don't exit: a rejection can be transient (hub mid-deploy/migration) and exiting just
|
|
300
|
+
// makes the supervisor respawn us in a tight loop. The socket closes and the normal
|
|
301
|
+
// backoff reconnect (max 30s) retries; a genuinely bad token is fixed by reinstalling.
|
|
302
|
+
console.error('Hub rejected this agent (will keep retrying):', msg.reason);
|
|
303
|
+
} else if (msg.type === 'set_interval') {
|
|
304
|
+
scheduleMetrics(msg.ms);
|
|
305
|
+
} else if (msg.type === 'get_logs') {
|
|
306
|
+
handleGetLogs(msg);
|
|
307
|
+
} else if (msg.type === 'tail_logs') {
|
|
308
|
+
handleTailLogs(msg);
|
|
309
|
+
} else if (msg.type === 'stop_tail') {
|
|
310
|
+
stopTail(`${msg.kind}:${msg.app}:${msg.stream}`);
|
|
311
|
+
} else if (msg.type === 'self_update') {
|
|
312
|
+
performSelfUpdate();
|
|
313
|
+
} else if (msg.type === 'restart_agent') {
|
|
314
|
+
performRestart();
|
|
315
|
+
} else if (msg.type === 'env_read') {
|
|
316
|
+
handleRpc(msg, () => readEnvFile(msg.path));
|
|
317
|
+
} else if (msg.type === 'env_write') {
|
|
318
|
+
handleRpc(msg, () => writeEnvFile(msg.path, msg.content, msg.baseHash));
|
|
319
|
+
} else if (msg.type === 'service_restart') {
|
|
320
|
+
handleRpc(msg, () => restartUnit(msg.kind, msg.name));
|
|
321
|
+
}
|
|
322
|
+
}
|
|
323
|
+
|
|
324
|
+
ws.on('close', () => {
|
|
325
|
+
stopAllTails();
|
|
326
|
+
if (metricsTimer) {
|
|
327
|
+
clearInterval(metricsTimer);
|
|
328
|
+
metricsTimer = null;
|
|
329
|
+
}
|
|
330
|
+
if (discoveryTimer) {
|
|
331
|
+
clearInterval(discoveryTimer);
|
|
332
|
+
discoveryTimer = null;
|
|
333
|
+
}
|
|
334
|
+
scheduleReconnect();
|
|
335
|
+
});
|
|
336
|
+
|
|
337
|
+
ws.on('error', () => {}); // 'close' fires after 'error'; reconnect handled there
|
|
338
|
+
}
|
|
339
|
+
|
|
340
|
+
function scheduleReconnect() {
|
|
341
|
+
setTimeout(connect, reconnectDelay);
|
|
342
|
+
reconnectDelay = Math.min(reconnectDelay * 2, RECONNECT_MAX_MS);
|
|
343
|
+
}
|
|
344
|
+
|
|
345
|
+
connect();
|
|
346
|
+
console.log(
|
|
347
|
+
`Pulse agent starting — instance "${instanceId}", hub ${hubUrl}, v${AGENT_APP_VERSION} (bundle ${AGENT_BUNDLE_HASH})`,
|
|
348
|
+
);
|
|
349
|
+
|
|
350
|
+
const systemdCheck = checkSystemdAvailable();
|
|
351
|
+
if (systemdCheck.state === 'ok') {
|
|
352
|
+
console.log(
|
|
353
|
+
`systemd journal readable — ${getSystemdUnits().length} running service(s) visible to this agent.`,
|
|
354
|
+
);
|
|
355
|
+
} else if (systemdCheck.state === 'unreadable') {
|
|
356
|
+
console.log(
|
|
357
|
+
`systemd journal not readable by OS user '${systemdCheck.user}' — service logs won't be available. Fix: sudo usermod -aG systemd-journal ${systemdCheck.user} && sudo systemctl restart pulse-agent`,
|
|
358
|
+
);
|
|
359
|
+
} else {
|
|
360
|
+
console.log("systemd/journalctl not found — service logs won't be available.");
|
|
361
|
+
}
|
|
362
|
+
|
|
363
|
+
const dockerCheck = checkDockerAvailable();
|
|
364
|
+
if (dockerCheck.ok) {
|
|
365
|
+
console.log(
|
|
366
|
+
`Docker detected — ${getDockerContainers().length} container(s) visible to this agent.`,
|
|
367
|
+
);
|
|
368
|
+
} else {
|
|
369
|
+
console.log(
|
|
370
|
+
`Docker not usable from this agent (${dockerCheck.error}) — container logs won't be available. If this box runs Docker, make sure this agent's OS user is in the 'docker' group (or is root).`,
|
|
371
|
+
);
|
|
372
|
+
}
|
|
@@ -0,0 +1,76 @@
|
|
|
1
|
+
// Permissions-v2 migration CLI (see .claude/plans/permissions-v2-implementation.md §7).
|
|
2
|
+
// The migration itself runs automatically at hub startup; this script is for looking at it
|
|
3
|
+
// BEFORE it happens, and for re-checking parity afterwards while the legacy tables exist.
|
|
4
|
+
//
|
|
5
|
+
// npm run authz-migrate -- --dry-run report what the migration would do + parity result
|
|
6
|
+
// npm run authz-migrate -- --verify re-run the parity check against an already-migrated DB
|
|
7
|
+
//
|
|
8
|
+
// Neither mode touches the live database: it is copied (VACUUM INTO) to a temp file first
|
|
9
|
+
// and everything runs against the copy. Exit code 0 = ok, 1 = parity failure, 2 = usage /
|
|
10
|
+
// nothing to do.
|
|
11
|
+
|
|
12
|
+
const fs = require('fs');
|
|
13
|
+
const os = require('os');
|
|
14
|
+
const path = require('path');
|
|
15
|
+
const paths = require('./lib/paths');
|
|
16
|
+
require('dotenv').config({ path: paths.ENV_FILE });
|
|
17
|
+
|
|
18
|
+
const args = process.argv.slice(2);
|
|
19
|
+
const dryRun = args.includes('--dry-run');
|
|
20
|
+
const verifyOnly = args.includes('--verify');
|
|
21
|
+
const asJson = args.includes('--json');
|
|
22
|
+
|
|
23
|
+
if (dryRun === verifyOnly) {
|
|
24
|
+
console.error('Usage: node authz-migrate.js (--dry-run | --verify) [--json]');
|
|
25
|
+
process.exit(2);
|
|
26
|
+
}
|
|
27
|
+
|
|
28
|
+
const liveFile = process.env.PULSE_DB_FILE || path.join(paths.DATA_DIR, 'pulse.db');
|
|
29
|
+
if (!fs.existsSync(liveFile)) {
|
|
30
|
+
console.error(`No database at ${liveFile} — nothing to migrate.`);
|
|
31
|
+
process.exit(2);
|
|
32
|
+
}
|
|
33
|
+
|
|
34
|
+
// Snapshot the live DB into a throwaway directory, then point lib/db.js at the copy.
|
|
35
|
+
const scratchDir = fs.mkdtempSync(path.join(os.tmpdir(), 'pulse-authz-'));
|
|
36
|
+
const copyFile = path.join(scratchDir, 'pulse.db');
|
|
37
|
+
const Database = require('./lib/sqlite');
|
|
38
|
+
const live = new Database(liveFile, { fileMustExist: true });
|
|
39
|
+
live.exec(`VACUUM INTO '${copyFile.replace(/'/g, "''")}'`);
|
|
40
|
+
live.close();
|
|
41
|
+
process.env.PULSE_DB_FILE = copyFile;
|
|
42
|
+
|
|
43
|
+
function cleanup() {
|
|
44
|
+
try {
|
|
45
|
+
require('./lib/db').db.close();
|
|
46
|
+
} catch (e) {}
|
|
47
|
+
fs.rmSync(scratchDir, { recursive: true, force: true });
|
|
48
|
+
}
|
|
49
|
+
|
|
50
|
+
const { runMigration, formatReport, MigrationParityError } = require('./lib/authz/migrate');
|
|
51
|
+
|
|
52
|
+
let exitCode = 0;
|
|
53
|
+
try {
|
|
54
|
+
const report = runMigration({ dryRun, verifyOnly });
|
|
55
|
+
if (asJson) console.log(JSON.stringify(report, null, 2));
|
|
56
|
+
else console.log(formatReport(report));
|
|
57
|
+
if (report.status === 'already-migrated') {
|
|
58
|
+
console.log('This database is already migrated; use --verify to re-check parity.');
|
|
59
|
+
exitCode = 2;
|
|
60
|
+
} else if (report.status === 'not-migrated') {
|
|
61
|
+
console.log('Run --dry-run to preview the migration.');
|
|
62
|
+
exitCode = 2;
|
|
63
|
+
}
|
|
64
|
+
} catch (err) {
|
|
65
|
+
if (err instanceof MigrationParityError) {
|
|
66
|
+
if (asJson) console.log(JSON.stringify({ status: 'parity-failed', diffs: err.diffs }, null, 2));
|
|
67
|
+
else console.error(`${err.message}\n${require('./lib/authz/migrate').formatDiffs(err.diffs)}`);
|
|
68
|
+
exitCode = 1;
|
|
69
|
+
} else {
|
|
70
|
+
console.error(err);
|
|
71
|
+
exitCode = 1;
|
|
72
|
+
}
|
|
73
|
+
} finally {
|
|
74
|
+
cleanup();
|
|
75
|
+
}
|
|
76
|
+
process.exit(exitCode);
|