pulse-hub 0.0.0-stage → 3.5.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (84) hide show
  1. package/CHANGELOG.md +22 -0
  2. package/LICENSE +5 -0
  3. package/README.md +86 -2
  4. package/backend/.env.example +52 -0
  5. package/backend/agent-package.json +9 -0
  6. package/backend/agent.config.example.json +6 -0
  7. package/backend/agent.js +372 -0
  8. package/backend/authz-migrate.js +76 -0
  9. package/backend/cli.js +999 -0
  10. package/backend/config.js +120 -0
  11. package/backend/emails/env-backup.html +52 -0
  12. package/backend/emails/invite.html +53 -0
  13. package/backend/install-agent.sh +181 -0
  14. package/backend/lib/agent-rpc.js +72 -0
  15. package/backend/lib/async-route.js +17 -0
  16. package/backend/lib/audit.js +134 -0
  17. package/backend/lib/auth-google.js +78 -0
  18. package/backend/lib/authz/bootstrap.js +35 -0
  19. package/backend/lib/authz/catalog.js +291 -0
  20. package/backend/lib/authz/delegation.js +104 -0
  21. package/backend/lib/authz/effective.js +104 -0
  22. package/backend/lib/authz/engine.js +251 -0
  23. package/backend/lib/authz/index.js +134 -0
  24. package/backend/lib/authz/legacy-oracle.js +195 -0
  25. package/backend/lib/authz/migrate.js +871 -0
  26. package/backend/lib/authz/mutate.js +87 -0
  27. package/backend/lib/authz/preview.js +327 -0
  28. package/backend/lib/authz/scope.js +282 -0
  29. package/backend/lib/authz/templates.js +103 -0
  30. package/backend/lib/authz-store.js +535 -0
  31. package/backend/lib/bundle-version.js +71 -0
  32. package/backend/lib/config-check.js +100 -0
  33. package/backend/lib/crypto-helpers.js +15 -0
  34. package/backend/lib/db.js +984 -0
  35. package/backend/lib/env-backup.js +306 -0
  36. package/backend/lib/env-crypto.js +52 -0
  37. package/backend/lib/env-files.js +235 -0
  38. package/backend/lib/env-mask.js +131 -0
  39. package/backend/lib/gmail-send.js +234 -0
  40. package/backend/lib/http-helpers.js +48 -0
  41. package/backend/lib/instance-registry.js +34 -0
  42. package/backend/lib/invite-helpers.js +83 -0
  43. package/backend/lib/invites.js +160 -0
  44. package/backend/lib/jwt.js +59 -0
  45. package/backend/lib/logs.js +244 -0
  46. package/backend/lib/metrics.js +249 -0
  47. package/backend/lib/migrate-legacy.js +106 -0
  48. package/backend/lib/paths.js +17 -0
  49. package/backend/lib/relay-state.js +564 -0
  50. package/backend/lib/self-update.js +68 -0
  51. package/backend/lib/session.js +48 -0
  52. package/backend/lib/sqlite.js +197 -0
  53. package/backend/lib/static-files.js +86 -0
  54. package/backend/middleware/authz.js +65 -0
  55. package/backend/middleware/session-gate.js +38 -0
  56. package/backend/public/assets/favicon.ico +0 -0
  57. package/backend/public/assets/favicon.svg +6 -0
  58. package/backend/public/assets/index.css +1 -0
  59. package/backend/public/assets/index.js +111 -0
  60. package/backend/public/assets/inter-cyrillic-ext-wght-normal.woff2 +0 -0
  61. package/backend/public/assets/inter-cyrillic-wght-normal.woff2 +0 -0
  62. package/backend/public/assets/inter-greek-ext-wght-normal.woff2 +0 -0
  63. package/backend/public/assets/inter-greek-wght-normal.woff2 +0 -0
  64. package/backend/public/assets/inter-latin-ext-wght-normal.woff2 +0 -0
  65. package/backend/public/assets/inter-latin-wght-normal.woff2 +0 -0
  66. package/backend/public/assets/inter-vietnamese-wght-normal.woff2 +0 -0
  67. package/backend/public/index.html +26 -0
  68. package/backend/routes/access.js +123 -0
  69. package/backend/routes/audit.js +41 -0
  70. package/backend/routes/auth.js +207 -0
  71. package/backend/routes/env-files.js +943 -0
  72. package/backend/routes/instances.js +555 -0
  73. package/backend/routes/invites-public.js +91 -0
  74. package/backend/routes/invites.js +121 -0
  75. package/backend/routes/logs.js +68 -0
  76. package/backend/routes/metrics.js +76 -0
  77. package/backend/routes/policies.js +240 -0
  78. package/backend/routes/static.js +100 -0
  79. package/backend/routes/teams.js +221 -0
  80. package/backend/routes/users.js +100 -0
  81. package/backend/seed-admins.js +68 -0
  82. package/backend/server.js +106 -0
  83. package/backend/ws/agent-relay.js +159 -0
  84. package/package.json +95 -4
@@ -0,0 +1,120 @@
1
+ const path = require('path');
2
+ const crypto = require('crypto');
3
+ const { computeBundleVersion, readPackageJson } = require('./lib/bundle-version');
4
+ const db = require('./lib/db');
5
+
6
+ // lib/db.js already creates data/ and pulse.db (with a migration pass over any legacy
7
+ // flat files) as a side effect of being required, above.
8
+
9
+ // PULSE_PORT / PULSE_HOST let an operator move the hub off 127.0.0.1:5080 (e.g. a box
10
+ // where 5080 is taken). Loopback stays the default: the hub is meant to sit behind nginx.
11
+ const PORT = (() => {
12
+ const parsed = Number(process.env.PULSE_PORT);
13
+ return Number.isInteger(parsed) && parsed > 0 && parsed < 65536 ? parsed : 5080;
14
+ })();
15
+ const HOST = (process.env.PULSE_HOST || '').trim() || '127.0.0.1';
16
+ // Configurable via backend/.env (see .env.example) so an operator can loosen/tighten
17
+ // session length without a code change. Falls back to the historical 1 hour when unset
18
+ // or not a valid positive number.
19
+ const SESSION_MAX_AGE_SECONDS = (() => {
20
+ const parsed = Number(process.env.PULSE_SESSION_MAX_AGE_SECONDS);
21
+ return Number.isFinite(parsed) && parsed > 0 ? parsed : 60 * 60;
22
+ })();
23
+ const SESSION_MAX_AGE_MS = SESSION_MAX_AGE_SECONDS * 1000;
24
+
25
+ // This module lives directly in backend/, so __dirname is always the hub's own
26
+ // directory — other modules (e.g. routes/static.js building the agent-bundle tarball,
27
+ // or serving install-agent.sh) should resolve paths off BACKEND_DIR rather than their
28
+ // own __dirname, which would point at their subdirectory instead.
29
+ const BACKEND_DIR = __dirname;
30
+ const PUBLIC_DIR = path.join(__dirname, 'public');
31
+
32
+ const HISTORY_RETENTION_MS = 7 * 24 * 60 * 60 * 1000;
33
+ const HISTORY_PRUNE_INTERVAL_MS = 60 * 60 * 1000; // hourly
34
+ // An instance whose agent has never connected even once (e.g. the install command was
35
+ // generated but never run) is deleted after this long — same spirit as invite expiry.
36
+ const NEVER_CONNECTED_TTL_MS = 24 * 60 * 60 * 1000;
37
+ const IDLE_METRICS_INTERVAL_MS = 5 * 60 * 1000;
38
+ const LOG_REQUEST_TIMEOUT_MS = 8000;
39
+ const HEARTBEAT_INTERVAL_MS = 30 * 1000;
40
+ const INSTANCES_BROADCAST_INTERVAL_MS = 10000;
41
+
42
+ // Absolute base URL for links that are opened outside the app (invite emails) — there's
43
+ // no "current page" to resolve a relative path against there, and inferring the origin
44
+ // from a request Host header would be spoofable, so this is configured explicitly
45
+ // (alongside the PULSE_GOOGLE_* vars — see lib/auth-google.js and docs/deploy.md for
46
+ // where it's set). e.g. "https://example.com/monitor" (no trailing slash).
47
+ // Normalized: trimmed, no trailing slashes, and a collapsed duplicate scheme (a pasted
48
+ // "https://https://host" would otherwise end up verbatim in invite links). A bare
49
+ // "host" with no scheme is left alone — set the scheme explicitly in .env.
50
+ const PULSE_PUBLIC_URL = (process.env.PULSE_PUBLIC_URL || '')
51
+ .trim()
52
+ .replace(/^(https?:\/\/)(?:https?:\/\/)+/i, '$1')
53
+ .replace(/\/+$/, '');
54
+
55
+ // Deliberately excludes the real package.json/package-lock.json one level up (repo
56
+ // root) — that manifest also carries hub-only runtime deps (nodemailer, pdfkit, ...) and every
57
+ // frontend devDependency, none of which agent.js/lib/*.js need. agent-package.json is
58
+ // the minimal, hand-maintained stand-in shipped as package.json instead — see
59
+ // routes/static.js's agent-bundle tarball construction.
60
+ //
61
+ // Named lib/ files explicitly (matching lib/bundle-version.js's own
62
+ // AGENT_RELEVANT_FILES list) rather than shipping the whole lib/ directory — lib/ also
63
+ // holds hub-only modules (lib/db.js and friends) that open the SQLite database and have
64
+ // no business running on a monitored box.
65
+ const AGENT_BUNDLE_FILES = [
66
+ 'agent.js',
67
+ 'agent.config.example.json',
68
+ 'lib/metrics.js',
69
+ 'lib/logs.js',
70
+ 'lib/env-files.js',
71
+ 'lib/bundle-version.js',
72
+ 'lib/self-update.js',
73
+ ];
74
+ // Longer than LOG_REQUEST_TIMEOUT_MS: a service restart waits for the unit to come back up.
75
+ const ENV_RPC_TIMEOUT_MS = 15 * 1000;
76
+ const SERVICE_RESTART_TIMEOUT_MS = 75 * 1000;
77
+ // What this hub would currently ship via /agent-bundle.tar.gz, as a short content hash —
78
+ // see lib/bundle-version.js for why this is scoped to just the agent-relevant files
79
+ // instead of a whole-repo identifier (a hub-only deploy must never look like an agent
80
+ // update to every connected instance). Purely a staleness signal — never shown to a
81
+ // person, see APP_VERSION below for that. See .claude/rules/version-bump-policy.md.
82
+ const HUB_BUNDLE_HASH = computeBundleVersion(BACKEND_DIR);
83
+
84
+ // The human-facing semver — root package.json's "version", the single source of truth
85
+ // (see .claude/rules/version-bump-policy.md and show-app-version-in-ui.md). Deliberately
86
+ // NOT used for update-staleness detection (see HUB_BUNDLE_HASH above and
87
+ // lib/bundle-version.js) — a person can go a while without bumping this, which would
88
+ // otherwise silently stop the self-update mechanism from ever firing.
89
+ const APP_VERSION = (readPackageJson(BACKEND_DIR) || {}).version || 'unknown';
90
+
91
+ // Prefer an operator-supplied secret (backend/.env) so it survives a fresh data/pulse.db
92
+ // (e.g. a restore) and can be the same across multiple hub processes; falls back to one
93
+ // generated on first boot and persisted in SQLite, same as before PULSE_JWT_SECRET
94
+ // existed.
95
+ const SESSION_SECRET =
96
+ process.env.PULSE_JWT_SECRET ||
97
+ db.getOrCreateSetting('session_secret', () => crypto.randomBytes(32).toString('hex'));
98
+
99
+ module.exports = {
100
+ PORT,
101
+ HOST,
102
+ SESSION_MAX_AGE_SECONDS,
103
+ SESSION_MAX_AGE_MS,
104
+ BACKEND_DIR,
105
+ PUBLIC_DIR,
106
+ HISTORY_RETENTION_MS,
107
+ HISTORY_PRUNE_INTERVAL_MS,
108
+ NEVER_CONNECTED_TTL_MS,
109
+ IDLE_METRICS_INTERVAL_MS,
110
+ LOG_REQUEST_TIMEOUT_MS,
111
+ ENV_RPC_TIMEOUT_MS,
112
+ SERVICE_RESTART_TIMEOUT_MS,
113
+ HEARTBEAT_INTERVAL_MS,
114
+ INSTANCES_BROADCAST_INTERVAL_MS,
115
+ PULSE_PUBLIC_URL,
116
+ AGENT_BUNDLE_FILES,
117
+ HUB_BUNDLE_HASH,
118
+ APP_VERSION,
119
+ SESSION_SECRET,
120
+ };
@@ -0,0 +1,52 @@
1
+ <!doctype html>
2
+ <html>
3
+ <body style="margin:0;padding:0;background:#f4f4f5;font-family:-apple-system,BlinkMacSystemFont,'Segoe UI',Roboto,Helvetica,Arial,sans-serif;">
4
+ <table role="presentation" width="100%" cellpadding="0" cellspacing="0" style="background:#f4f4f5;padding:40px 16px;">
5
+ <tr><td align="center">
6
+ <table role="presentation" width="480" cellpadding="0" cellspacing="0" style="max-width:480px;width:100%;background:#ffffff;border:1px solid #e4e4e7;border-radius:16px;overflow:hidden;">
7
+ <tr><td style="padding:32px 32px 0 32px;">
8
+ <span style="display:inline-block;background:#059669;color:#ffffff;font-size:12px;font-weight:700;letter-spacing:0.04em;text-transform:uppercase;padding:4px 10px;border-radius:999px;">Pulse</span>
9
+ </td></tr>
10
+ <tr><td style="padding:20px 32px 0 32px;">
11
+ <h1 style="margin:0;font-size:21px;line-height:1.4;color:#18181b;font-weight:700;">
12
+ {{headline}}
13
+ </h1>
14
+ </td></tr>
15
+ <tr><td style="padding:16px 32px 0 32px;">
16
+ <table role="presentation" cellpadding="0" cellspacing="0" style="background:#f4f4f5;border-radius:10px;width:100%;">
17
+ <tr>
18
+ <td style="padding:12px 16px;">
19
+ <div style="font-size:11px;font-weight:600;letter-spacing:0.04em;text-transform:uppercase;color:#71717a;">Server</div>
20
+ <div style="margin-top:2px;font-size:14px;font-weight:600;color:#18181b;">{{instanceLabel}}</div>
21
+ <div style="margin-top:10px;font-size:11px;font-weight:600;letter-spacing:0.04em;text-transform:uppercase;color:#71717a;">File</div>
22
+ <div style="margin-top:2px;font-size:14px;font-weight:600;color:#18181b;">{{fileLabel}}</div>
23
+ <div style="margin-top:2px;font-family:ui-monospace,SFMono-Regular,Menlo,monospace;font-size:12px;color:#71717a;">{{filePath}}</div>
24
+ <div style="margin-top:10px;font-size:11px;font-weight:600;letter-spacing:0.04em;text-transform:uppercase;color:#71717a;">{{actorLabel}}</div>
25
+ <div style="margin-top:2px;font-size:14px;font-weight:600;color:#18181b;">{{actor}}</div>
26
+ <div style="margin-top:2px;font-size:12px;color:#71717a;">{{changeSummary}}</div>
27
+ </td>
28
+ </tr>
29
+ </table>
30
+ </td></tr>
31
+ <tr><td style="padding:16px 32px 0 32px;">
32
+ <p style="margin:0;font-size:14px;line-height:1.6;color:#52525b;">
33
+ {{introText}}
34
+ </p>
35
+ </td></tr>
36
+ <tr><td style="padding:16px 32px 0 32px;">
37
+ <p style="margin:0;font-size:13px;line-height:1.6;color:#71717a;background:#fef9c3;border-radius:10px;padding:12px 14px;">
38
+ The PDF is password-protected. The password is deliberately not in this email
39
+ &mdash; ask whoever manages this server's env files for it.
40
+ </p>
41
+ </td></tr>
42
+ <tr><td style="padding:24px 32px 28px 32px;border-top:1px solid #e4e4e7;margin-top:24px;">
43
+ <p style="margin:16px 0 0 0;font-size:12px;line-height:1.6;color:#a1a1aa;">
44
+ This file contains secrets. Treat the attachment the same way you'd treat the
45
+ original env file.
46
+ </p>
47
+ </td></tr>
48
+ </table>
49
+ </td></tr>
50
+ </table>
51
+ </body>
52
+ </html>
@@ -0,0 +1,53 @@
1
+ <!doctype html>
2
+ <html>
3
+ <body style="margin:0;padding:0;background:#f4f4f5;font-family:-apple-system,BlinkMacSystemFont,'Segoe UI',Roboto,Helvetica,Arial,sans-serif;">
4
+ <table role="presentation" width="100%" cellpadding="0" cellspacing="0" style="background:#f4f4f5;padding:40px 16px;">
5
+ <tr><td align="center">
6
+ <table role="presentation" width="480" cellpadding="0" cellspacing="0" style="max-width:480px;width:100%;background:#ffffff;border:1px solid #e4e4e7;border-radius:16px;overflow:hidden;">
7
+ <tr><td style="padding:32px 32px 0 32px;">
8
+ <span style="display:inline-block;background:#059669;color:#ffffff;font-size:12px;font-weight:700;letter-spacing:0.04em;text-transform:uppercase;padding:4px 10px;border-radius:999px;">Pulse</span>
9
+ </td></tr>
10
+ <tr><td style="padding:20px 32px 0 32px;">
11
+ <h1 style="margin:0;font-size:21px;line-height:1.4;color:#18181b;font-weight:700;">
12
+ You've been invited to a Pulse monitoring hub
13
+ </h1>
14
+ </td></tr>
15
+ <tr><td style="padding:16px 32px 0 32px;">
16
+ <table role="presentation" cellpadding="0" cellspacing="0" style="background:#f4f4f5;border-radius:10px;width:100%;">
17
+ <tr>
18
+ <td style="padding:12px 16px;">
19
+ <div style="font-size:11px;font-weight:600;letter-spacing:0.04em;text-transform:uppercase;color:#71717a;">Invited by</div>
20
+ <div style="margin-top:2px;font-size:14px;font-weight:600;color:#18181b;">{{invitedByLabel}}</div>
21
+ </td>
22
+ </tr>
23
+ </table>
24
+ </td></tr>
25
+ <tr><td style="padding:16px 32px 0 32px;">
26
+ <p style="margin:0;font-size:14px;line-height:1.6;color:#52525b;">
27
+ Pulse is a self-hosted server monitoring dashboard. Accept the invite below to get access.
28
+ </p>
29
+ </td></tr>
30
+ <tr><td style="padding:24px 32px 0 32px;" align="center">
31
+ <a href="{{inviteLink}}" style="display:inline-block;background:#059669;color:#ffffff;font-size:14px;font-weight:600;text-decoration:none;padding:12px 28px;border-radius:999px;">
32
+ Accept invite
33
+ </a>
34
+ </td></tr>
35
+ <tr><td style="padding:20px 32px 0 32px;">
36
+ <p style="margin:0;font-size:12px;line-height:1.6;color:#a1a1aa;">
37
+ This link expires in {{expiryLabel}}. If the button above doesn't work, copy and paste this URL:<br>
38
+ <a href="{{inviteLink}}" style="color:#71717a;word-break:break-all;">{{inviteLink}}</a>
39
+ </p>
40
+ </td></tr>
41
+ <tr><td style="padding:24px 32px 28px 32px;border-top:1px solid #e4e4e7;margin-top:24px;">
42
+ <p style="margin:16px 0 8px 0;font-size:12px;line-height:1.6;color:#a1a1aa;">
43
+ Having trouble with this invite, or didn't expect it?
44
+ </p>
45
+ <a href="{{resendLink}}" style="display:inline-block;font-size:12px;font-weight:600;color:#059669;text-decoration:underline;">
46
+ Let {{invitedByLabel}} know
47
+ </a>
48
+ </td></tr>
49
+ </table>
50
+ </td></tr>
51
+ </table>
52
+ </body>
53
+ </html>
@@ -0,0 +1,181 @@
1
+ #!/usr/bin/env bash
2
+ # Pulse agent installer.
3
+ #
4
+ # Run this on any server you want to add to an already-running Pulse hub. Get the
5
+ # --hub/--id/--token values from the hub's Account page ("Add instance") — it prints
6
+ # the exact command to paste here, with these already filled in.
7
+ #
8
+ # Usage:
9
+ # curl -fsSL https://<hub-domain>/monitor/install-agent.sh | sudo bash -s -- \
10
+ # --hub https://<hub-domain>/monitor --id <instanceId> --token <token>
11
+ #
12
+ # Optional flags:
13
+ # --dir <path> install location (default: /opt/pulse-agent)
14
+ # --user <name> OS user to run the agent as (default: $SUDO_USER, falls back to root)
15
+ # Must be the same user PM2 runs under on this box, or the agent
16
+ # won't see any PM2 processes/logs. If this box also runs Docker
17
+ # containers you want logs from, this user needs to be in the
18
+ # `docker` group (or be root) too. Likewise, to read systemd
19
+ # service logs (journalctl) the user needs root or the
20
+ # `systemd-journal` group — this script adds a non-root user to
21
+ # it automatically.
22
+ # --tag <tags> comma-separated labels (e.g. --tag web-tier,prod) this instance
23
+ # reports to the hub on every connect. Labels are descriptive only -
24
+ # they never grant anyone access. Access tags (what a policy's tag
25
+ # scope matches) are set separately on the hub by someone holding
26
+ # the "Manage access tags" permission.
27
+
28
+ set -euo pipefail
29
+
30
+ HUB_BASE=""
31
+ INSTANCE_ID=""
32
+ TOKEN=""
33
+ INSTALL_DIR="/opt/pulse-agent"
34
+ SERVICE_USER="${SUDO_USER:-root}"
35
+ USER_EXPLICIT=false
36
+ TAGS=""
37
+
38
+ while [[ $# -gt 0 ]]; do
39
+ case "$1" in
40
+ --hub) HUB_BASE="$2"; shift 2 ;;
41
+ --id) INSTANCE_ID="$2"; shift 2 ;;
42
+ --token) TOKEN="$2"; shift 2 ;;
43
+ --dir) INSTALL_DIR="$2"; shift 2 ;;
44
+ --user) SERVICE_USER="$2"; USER_EXPLICIT=true; shift 2 ;;
45
+ --tag) TAGS="$2"; shift 2 ;;
46
+ *) echo "Unknown argument: $1" >&2; exit 1 ;;
47
+ esac
48
+ done
49
+
50
+ if [[ -z "$HUB_BASE" || -z "$INSTANCE_ID" || -z "$TOKEN" ]]; then
51
+ echo "Usage: install-agent.sh --hub <https://hub-domain/monitor> --id <instanceId> --token <token> [--dir /opt/pulse-agent] [--user someuser]" >&2
52
+ exit 1
53
+ fi
54
+
55
+ if [[ $EUID -ne 0 ]]; then
56
+ echo "Run as root (needed to install a systemd service) — try again with sudo." >&2
57
+ exit 1
58
+ fi
59
+
60
+ HUB_BASE="${HUB_BASE%/}" # strip a trailing slash if present
61
+ if [[ "$HUB_BASE" == https://* ]]; then
62
+ WS_URL="wss://${HUB_BASE#https://}/agent-ws"
63
+ elif [[ "$HUB_BASE" == http://* ]]; then
64
+ WS_URL="ws://${HUB_BASE#http://}/agent-ws"
65
+ else
66
+ echo "--hub must start with http:// or https://" >&2
67
+ exit 1
68
+ fi
69
+
70
+ # If --user wasn't given explicitly, try to detect which OS user actually runs PM2
71
+ # (each user has their own PM2 daemon, so root or $SUDO_USER often isn't it) rather
72
+ # than silently defaulting to a user with no visibility into that PM2 instance.
73
+ if [[ "$USER_EXPLICIT" == false ]]; then
74
+ DETECTED_PM2_USER="$(ps -eo user:32,args --no-headers 2>/dev/null | grep 'PM2 ' | grep -v grep | awk '{print $1}' | sort -u | head -1 || true)"
75
+ if [[ -n "$DETECTED_PM2_USER" && "$DETECTED_PM2_USER" != "$SERVICE_USER" ]]; then
76
+ echo "Detected PM2 running as OS user '$DETECTED_PM2_USER' (different from the default" >&2
77
+ echo "'$SERVICE_USER') — installing the agent as '$DETECTED_PM2_USER' instead. Pass" >&2
78
+ echo "--user <name> explicitly to override this." >&2
79
+ SERVICE_USER="$DETECTED_PM2_USER"
80
+ elif [[ -z "$DETECTED_PM2_USER" && "$SERVICE_USER" == "root" ]]; then
81
+ echo "Warning: no --user given, running as root, and no PM2 daemon was detected on" >&2
82
+ echo "this box yet. If PM2 runs (or will run) under a different OS user, pass" >&2
83
+ echo "--user <that-user> or the agent won't see its processes or logs." >&2
84
+ fi
85
+ fi
86
+
87
+ if ! command -v node >/dev/null 2>&1; then
88
+ if command -v apt-get >/dev/null 2>&1; then
89
+ echo "Installing Node.js (via NodeSource)..."
90
+ curl -fsSL https://deb.nodesource.com/setup_lts.x | bash -
91
+ apt-get install -y nodejs
92
+ else
93
+ echo "Node.js isn't installed and this isn't an apt-based system — install Node.js" >&2
94
+ echo "manually (v18+), then re-run this script." >&2
95
+ exit 1
96
+ fi
97
+ fi
98
+
99
+ echo "Downloading agent from hub ($HUB_BASE)..."
100
+ mkdir -p "$INSTALL_DIR"
101
+ curl -fsSL "$HUB_BASE/agent-bundle.tar.gz?instance=$INSTANCE_ID&token=$TOKEN" | tar xz -C "$INSTALL_DIR"
102
+
103
+ cd "$INSTALL_DIR"
104
+ npm install --omit=dev --no-audit --no-fund
105
+
106
+ # Turn "web-tier,prod" into a JSON array [ "web-tier", "prod" ] — no jq dependency, just
107
+ # split on comma, trim whitespace, quote, join.
108
+ TAGS_JSON="[]"
109
+ if [[ -n "$TAGS" ]]; then
110
+ IFS=',' read -ra TAG_ARR <<< "$TAGS"
111
+ TAGS_JSON="["
112
+ for i in "${!TAG_ARR[@]}"; do
113
+ t="$(echo "${TAG_ARR[$i]}" | xargs)" # trim whitespace
114
+ [[ -z "$t" ]] && continue
115
+ [[ "$TAGS_JSON" != "[" ]] && TAGS_JSON+=","
116
+ TAGS_JSON+="\"$t\""
117
+ done
118
+ TAGS_JSON+="]"
119
+ fi
120
+
121
+ cat > "$INSTALL_DIR/agent.config.json" <<CONFIG
122
+ {
123
+ "hubUrl": "$WS_URL",
124
+ "instanceId": "$INSTANCE_ID",
125
+ "token": "$TOKEN",
126
+ "tags": $TAGS_JSON
127
+ }
128
+ CONFIG
129
+ chmod 600 "$INSTALL_DIR/agent.config.json"
130
+ chown -R "$SERVICE_USER" "$INSTALL_DIR"
131
+
132
+ # Lets the agent read other services' journal entries (Logs page -> systemd units). Takes
133
+ # effect when the service is (re)started below. Skipped for root and on boxes without the group.
134
+ if [[ "$SERVICE_USER" != "root" ]] && getent group systemd-journal >/dev/null 2>&1; then
135
+ usermod -aG systemd-journal "$SERVICE_USER" || echo "Warning: couldn't add '$SERVICE_USER' to systemd-journal — systemd service logs may be unavailable." >&2
136
+ fi
137
+
138
+ if systemctl list-unit-files pulse-agent.service >/dev/null 2>&1 && [ -f /etc/systemd/system/pulse-agent.service ]; then
139
+ # Re-running this script (new token, new hub after a domain move, etc.) must not
140
+ # leave the OLD process running with its OLD agent.config.json in memory — `enable
141
+ # --now` on an already-running service is a no-op for the "start" half, so without
142
+ # an explicit stop first, overwriting the unit/config file alone would silently do
143
+ # nothing until someone thought to restart it by hand. Same lesson already applied
144
+ # for the hub's own service (`restart`, not `start` — see docs/deploy.md).
145
+ echo "Existing pulse-agent.service found — stopping and disabling before reinstalling..."
146
+ systemctl stop pulse-agent || true
147
+ systemctl disable pulse-agent || true
148
+ fi
149
+
150
+ NODE_BIN="$(command -v node)"
151
+ cat > /etc/systemd/system/pulse-agent.service <<SERVICE
152
+ [Unit]
153
+ Description=Pulse monitoring agent
154
+ After=network-online.target
155
+ Wants=network-online.target
156
+ # Never give up restarting: the default start limit (5 starts / 10s) would leave the unit
157
+ # permanently failed after a brief crash loop, unmonitored until someone notices.
158
+ StartLimitIntervalSec=0
159
+
160
+ [Service]
161
+ Type=simple
162
+ User=$SERVICE_USER
163
+ WorkingDirectory=$INSTALL_DIR
164
+ ExecStart=$NODE_BIN agent.js
165
+ Restart=always
166
+ RestartSec=5
167
+ # Make the OOM killer pick almost anything else first on a small box.
168
+ OOMScoreAdjust=-500
169
+
170
+ [Install]
171
+ WantedBy=multi-user.target
172
+ SERVICE
173
+
174
+ systemctl daemon-reload
175
+ systemctl enable --now pulse-agent
176
+
177
+ echo ""
178
+ echo "Pulse agent installed and running as user '$SERVICE_USER'."
179
+ echo " Status: systemctl status pulse-agent"
180
+ echo " Logs: journalctl -u pulse-agent -f"
181
+ echo "Check the hub's Account page — this instance should show as connected within a few seconds."
@@ -0,0 +1,72 @@
1
+ // Shared plumbing for hub -> agent RPC routes (env-file editor, service restarts): the
2
+ // "is the agent ready" checks, the uniform { ok:false, code, error } failure shape, and the
3
+ // write-ahead-audited service restart used by both restart endpoints.
4
+ //
5
+ // Agent-side failures (offline, permission denied, conflict, ...) come back as HTTP 200 with
6
+ // `{ ok:false, code, error }` — the same convention as POST .../update-agent — so the
7
+ // frontend's useApiAction toasts them uniformly.
8
+
9
+ const config = require('../config');
10
+ const audit = require('./audit');
11
+ const { sendJson } = require('./http-helpers');
12
+ const { requestAgent, isAgentConnected, agentHasCapability } = require('./relay-state');
13
+
14
+ // Checks the agent can be asked at all. Returns true to proceed, or false after having
15
+ // written the response.
16
+ function requireReadyAgent(res, instanceId) {
17
+ if (!isAgentConnected(instanceId)) {
18
+ sendJson(res, 200, { ok: false, code: 'OFFLINE', error: 'Instance is offline.' });
19
+ return false;
20
+ }
21
+ if (!agentHasCapability(instanceId, 'env-files')) {
22
+ sendJson(res, 200, {
23
+ ok: false,
24
+ code: 'AGENT_OUTDATED',
25
+ error:
26
+ 'This instance\'s agent is too old for env files — use "Update agent" on the Servers page, then try again.',
27
+ });
28
+ return false;
29
+ }
30
+ return true;
31
+ }
32
+
33
+ function sendAgentFailure(res, r) {
34
+ sendJson(res, 200, {
35
+ ok: false,
36
+ code: r.code || 'ERROR',
37
+ error: r.error || 'The agent reported an error.',
38
+ });
39
+ }
40
+
41
+ // Restarts a unit on an instance. The caller has already authorized service.restart for this
42
+ // exact (instance, service) and picked the unit from a registered env entry — this never
43
+ // takes a unit name straight from a request. Write-ahead audit: an 'attempted' row before
44
+ // the agent is asked, a second row with the outcome after.
45
+ async function restartService(req, res, { instanceId, kind, name, envFileId }) {
46
+ if (!requireReadyAgent(res, instanceId)) return;
47
+ const token = audit.attempt(
48
+ {
49
+ action: 'service.restart',
50
+ targetType: 'service',
51
+ targetId: name,
52
+ instanceId,
53
+ summary: `Restart ${name}`,
54
+ metadata: { kind, envFileId: envFileId || null },
55
+ },
56
+ req,
57
+ );
58
+ const r = await requestAgent(
59
+ instanceId,
60
+ { type: 'service_restart', kind, name },
61
+ config.SERVICE_RESTART_TIMEOUT_MS,
62
+ );
63
+ if (!r.ok) {
64
+ audit.finish(token, 'failed', `Restart ${name} failed: ${r.code || 'ERROR'}`);
65
+ sendAgentFailure(res, r);
66
+ return;
67
+ }
68
+ audit.finish(token, 'succeeded', `Restarted ${name}`, { active: !!r.active });
69
+ sendJson(res, 200, { ok: true, active: !!r.active, state: r.state || 'unknown' });
70
+ }
71
+
72
+ module.exports = { requireReadyAgent, sendAgentFailure, restartService };
@@ -0,0 +1,17 @@
1
+ // Express 4 does not catch a rejected promise from an async handler: the request would hang
2
+ // and, on current Node, the unhandled rejection would take the whole hub down. Wrap every
3
+ // async route so a thrown error (an audit write that failed, a bad row, ...) becomes a 500.
4
+ const { sendJson } = require('./http-helpers');
5
+
6
+ function asyncRoute(handler) {
7
+ return (req, res, next) => {
8
+ // new Promise(...) so a synchronous throw is caught the same way as a rejection.
9
+ new Promise((resolve) => resolve(handler(req, res, next))).catch((e) => {
10
+ console.error(`[${req.method} ${req.path}]`, e);
11
+ if (!res.headersSent) sendJson(res, 500, { error: 'Internal error.' });
12
+ else res.end();
13
+ });
14
+ };
15
+ }
16
+
17
+ module.exports = { asyncRoute };
@@ -0,0 +1,134 @@
1
+ // Audit log recording and management (see authz-store.js for the table; the log is
2
+ // append-only — a trigger rejects UPDATE, and prune() is the only DELETE).
3
+ //
4
+ // * record() — one row. Called inside a caller's db.transaction() it commits or rolls back
5
+ // with the mutation, because it shares the same SQLite handle.
6
+ // * attempt() / finish() — write-ahead for operations that leave the database (agent RPCs):
7
+ // an 'attempted' row is written BEFORE the effect, and a second row with the
8
+ // same request_id records how it ended.
9
+ const crypto = require('crypto');
10
+ const { recordAudit, queryAudit, pruneAuditLog } = require('./authz-store');
11
+
12
+ // Keys whose values are never stored: anything that could carry a secret or file content.
13
+ const SENSITIVE_KEY_RE = /(content|value|secret|passw|token|credential)/i;
14
+ const SENSITIVE_EXACT_RE = /^(key|auth|authorization|cookie)$/i;
15
+ const MAX_STRING = 500;
16
+
17
+ function isSensitiveKey(key) {
18
+ return SENSITIVE_KEY_RE.test(key) || SENSITIVE_EXACT_RE.test(key);
19
+ }
20
+
21
+ // Belt and braces: callers never pass secrets, but anything that looks like one is replaced
22
+ // and long strings are truncated, recursively (arrays included).
23
+ function scrubMetadata(obj) {
24
+ if (obj === null || obj === undefined) return obj;
25
+ if (typeof obj === 'string') {
26
+ return obj.length > MAX_STRING ? obj.slice(0, MAX_STRING) + '…' : obj;
27
+ }
28
+ if (Array.isArray(obj)) return obj.map(scrubMetadata);
29
+ if (typeof obj !== 'object') return obj;
30
+ const scrubbed = {};
31
+ for (const [key, val] of Object.entries(obj)) {
32
+ scrubbed[key] = isSensitiveKey(key) ? '***' : scrubMetadata(val);
33
+ }
34
+ return scrubbed;
35
+ }
36
+
37
+ function actorOf(actor, req) {
38
+ if (actor) return { id: actor.id || null, label: actor.email || actor.label || null };
39
+ if (req && req.sessionUser) return { id: req.sessionUser.id, label: req.sessionUser.email };
40
+ return { id: null, label: null };
41
+ }
42
+
43
+ function record(params, req) {
44
+ const {
45
+ action,
46
+ targetType = null,
47
+ targetId = null,
48
+ instanceId = null,
49
+ outcome, // 'succeeded' | 'failed' | 'denied' | 'attempted'
50
+ summary = null,
51
+ metadata = null,
52
+ actor = null,
53
+ } = params;
54
+ const who = actorOf(actor, req);
55
+ recordAudit({
56
+ actorUserId: who.id,
57
+ actorLabel: who.label,
58
+ action,
59
+ targetType,
60
+ targetId,
61
+ instanceId,
62
+ outcome,
63
+ summary,
64
+ metadata: scrubMetadata(metadata),
65
+ requestId: (req && req.id) || null,
66
+ ipAddress: (req && req.ip) || null,
67
+ });
68
+ }
69
+
70
+ // Write-ahead for RPCs: writes the 'attempted' row now and returns a token for finish().
71
+ // Throws if the row cannot be written — callers treat that as "do not proceed" (an
72
+ // operation we cannot record must not happen).
73
+ function attempt(params, req) {
74
+ const { action, targetType = null, targetId = null, instanceId = null } = params;
75
+ const who = actorOf(params.actor, req);
76
+ const requestId = (req && req.id) || crypto.randomUUID();
77
+ const ipAddress = (req && req.ip) || null;
78
+ recordAudit({
79
+ actorUserId: who.id,
80
+ actorLabel: who.label,
81
+ action,
82
+ targetType,
83
+ targetId,
84
+ instanceId,
85
+ outcome: 'attempted',
86
+ summary: params.summary || null,
87
+ metadata: scrubMetadata(params.metadata || null),
88
+ requestId,
89
+ ipAddress,
90
+ });
91
+ return { requestId, ipAddress, actor: who, action, targetType, targetId, instanceId };
92
+ }
93
+
94
+ // Second row of a write-ahead pair (same request_id, same actor/target as the attempt).
95
+ function finish(token, outcome, summary, metadata) {
96
+ recordAudit({
97
+ actorUserId: token.actor.id,
98
+ actorLabel: token.actor.label,
99
+ action: token.action,
100
+ targetType: token.targetType,
101
+ targetId: token.targetId,
102
+ instanceId: token.instanceId,
103
+ outcome,
104
+ summary: summary || null,
105
+ metadata: scrubMetadata(metadata || null),
106
+ requestId: token.requestId,
107
+ ipAddress: token.ipAddress,
108
+ });
109
+ }
110
+
111
+ // Query audit log
112
+ function query(filters) {
113
+ const rows = queryAudit(filters);
114
+ return rows.map((r) => ({
115
+ ...r,
116
+ metadata: r.metadata ? JSON.parse(r.metadata) : null,
117
+ }));
118
+ }
119
+
120
+ // Prune old audit logs (configurable retention)
121
+ function prune() {
122
+ const retentionDays = parseInt(process.env.PULSE_AUDIT_RETENTION_DAYS || '180', 10);
123
+ const beforeTs = Date.now() - retentionDays * 24 * 60 * 60 * 1000;
124
+ pruneAuditLog(beforeTs);
125
+ }
126
+
127
+ module.exports = {
128
+ record,
129
+ attempt,
130
+ finish,
131
+ query,
132
+ prune,
133
+ scrubMetadata,
134
+ };