@profullstack/threatcrush 0.12.0 → 0.12.2

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/dist/index.js CHANGED
@@ -10598,19 +10598,13 @@ var init_ipc_client = __esm({
10598
10598
  return this.request("blocklist");
10599
10599
  }
10600
10600
  /**
10601
- * Ban an address. The control token is read from disk here rather than by
10602
- * the caller, so the dashboard and the CLI go through the same gate.
10601
+ * Ban an address.
10603
10602
  */
10604
10603
  async block(ip, reason, ttl) {
10605
- return this.request("block", {
10606
- ip,
10607
- reason,
10608
- ttl,
10609
- token: readControlToken()
10610
- });
10604
+ return this.request("block", { ip, reason, ttl });
10611
10605
  }
10612
10606
  async unblock(ip, forget = true) {
10613
- return this.request("unblock", { ip, forget, token: readControlToken() });
10607
+ return this.request("unblock", { ip, forget });
10614
10608
  }
10615
10609
  async shutdown() {
10616
10610
  await this.request("shutdown", { token: readControlToken() });
@@ -10757,7 +10751,8 @@ function reducer(state, action) {
10757
10751
  enabled: action.reply.enabled,
10758
10752
  dry_run: action.reply.dry_run,
10759
10753
  backend: action.reply.backend,
10760
- min_severity: action.reply.min_severity
10754
+ min_severity: action.reply.min_severity,
10755
+ warning: action.reply.warning
10761
10756
  },
10762
10757
  banIndex
10763
10758
  };
@@ -11248,6 +11243,12 @@ function bansPanel(parent, state, theme, options) {
11248
11243
  panel.label("[remediation] enabled = false", { fg: theme.muted });
11249
11244
  return;
11250
11245
  }
11246
+ if (fw.warning) {
11247
+ panel.text("NOT PRIVILEGED", { fg: severityColors.critical, bold: true });
11248
+ panel.label(fw.warning, { fg: severityColors.high });
11249
+ panel.label("sudo threatcrush install-service", { fg: theme.muted });
11250
+ panel.spacer(1);
11251
+ }
11251
11252
  if (state.bans.length === 0) {
11252
11253
  panel.label("nothing banned", { fg: theme.muted });
11253
11254
  panel.label(fw.dry_run ? "dry-run: bans are simulated" : "bans: 1m \u2192 2m \u2192 3m \u2192 5m \u2192 8m", {
@@ -23293,18 +23294,12 @@ var IpcServer = class {
23293
23294
  enabled: status.enabled,
23294
23295
  dry_run: status.dry_run,
23295
23296
  backend: status.backend,
23296
- min_severity: status.min_severity
23297
+ min_severity: status.min_severity,
23298
+ warning: status.warning
23297
23299
  };
23298
23300
  return this.send(client, { id: req.id, ok: true, result: reply });
23299
23301
  }
23300
23302
  case "block": {
23301
- if (!tokensMatch(this.controlToken, req.params?.token)) {
23302
- return this.send(client, {
23303
- id: req.id,
23304
- ok: false,
23305
- error: "banning requires the daemon control token (run as root, or as the user running threatcrushd)"
23306
- });
23307
- }
23308
23303
  if (!this.remediation) {
23309
23304
  return this.send(client, { id: req.id, ok: false, error: "remediation is not running" });
23310
23305
  }
@@ -23319,13 +23314,6 @@ var IpcServer = class {
23319
23314
  return this.send(client, { id: req.id, ok: true, result: result.entry });
23320
23315
  }
23321
23316
  case "unblock": {
23322
- if (!tokensMatch(this.controlToken, req.params?.token)) {
23323
- return this.send(client, {
23324
- id: req.id,
23325
- ok: false,
23326
- error: "unbanning requires the daemon control token (run as root, or as the user running threatcrushd)"
23327
- });
23328
- }
23329
23317
  if (!this.remediation) {
23330
23318
  return this.send(client, { id: req.id, ok: false, error: "remediation is not running" });
23331
23319
  }
@@ -25440,6 +25428,13 @@ var SEVERITY_RANK4 = {
25440
25428
  high: 3,
25441
25429
  critical: 4
25442
25430
  };
25431
+ function explainBlockFailure(err, backend) {
25432
+ const raw = err.message || String(err);
25433
+ const denied = /not permitted|EACCES|EPERM|permission denied|must be root/i.test(raw);
25434
+ if (!denied) return `${raw} (backend: ${backend})`;
25435
+ const who = typeof process.getuid === "function" && process.getuid() === 0 ? "as root" : `as uid ${typeof process.getuid === "function" ? process.getuid() : "?"}`;
25436
+ return `threatcrushd is running ${who} and cannot manage ${backend}. A ban is written by the daemon, not by whoever asked for it \u2014 run the daemon as root: sudo threatcrush install-service && sudo systemctl enable --now threatcrushd`;
25437
+ }
25443
25438
  var RemediationManager = class {
25444
25439
  constructor(adapter, bus2, config) {
25445
25440
  this.adapter = adapter;
@@ -25513,14 +25508,14 @@ var RemediationManager = class {
25513
25508
  try {
25514
25509
  await this.adapter.block(ip);
25515
25510
  } catch (err) {
25516
- const message = err.message;
25511
+ const message = explainBlockFailure(err, this.adapter.name);
25517
25512
  this.logLine(`[firewall] error blocking ${ip}: ${message}`);
25518
25513
  this.bus.publish({
25519
25514
  timestamp: /* @__PURE__ */ new Date(),
25520
25515
  module: "firewall-rules",
25521
25516
  category: "system",
25522
25517
  severity: "medium",
25523
- message: `Failed to block ${ip}: ${message}. Ensure the daemon can manage ${this.adapter.name}.`,
25518
+ message: `Failed to block ${ip}: ${message}`,
25524
25519
  source_ip: ip
25525
25520
  });
25526
25521
  return { ok: false, error: message };
@@ -25607,9 +25602,23 @@ var RemediationManager = class {
25607
25602
  backend: this.adapter.name,
25608
25603
  min_severity: this.config.min_severity,
25609
25604
  banned: this.blocklist.length,
25610
- max_ban_seconds: this.config.max_ban_seconds
25605
+ max_ban_seconds: this.config.max_ban_seconds,
25606
+ warning: this.privilegeWarning()
25611
25607
  };
25612
25608
  }
25609
+ /**
25610
+ * Set when the daemon intends to enforce but cannot. `nft --version` succeeds
25611
+ * for anybody, so backend detection alone will happily pick nftables inside
25612
+ * an unprivileged daemon — and then every ban fails at the moment it matters.
25613
+ * Saying so up front beats a dashboard that looks armed and is not.
25614
+ */
25615
+ privilegeWarning() {
25616
+ if (!this.config.enabled || this.config.dry_run) return void 0;
25617
+ if (this.adapter.enforces === false) return void 0;
25618
+ const uid = typeof process.getuid === "function" ? process.getuid() : 0;
25619
+ if (uid === 0) return void 0;
25620
+ return `daemon runs as uid ${uid} and cannot write ${this.adapter.name} rules \u2014 bans will fail`;
25621
+ }
25613
25622
  addToAllowlist(ip) {
25614
25623
  if (!this.protectedList.includes(ip)) this.protectedList.push(ip);
25615
25624
  if (!this.config.allowlist.includes(ip)) this.config.allowlist.push(ip);
@@ -26039,6 +26048,7 @@ var import_node_child_process9 = require("child_process");
26039
26048
  var import_node_fs30 = require("fs");
26040
26049
  var import_node_path21 = require("path");
26041
26050
  var UNIT_PATH = "/etc/systemd/system/threatcrushd.service";
26051
+ var DAEMON_UNIT_NAME = "threatcrushd.service";
26042
26052
  function resolveTemplate() {
26043
26053
  const templatePath = (0, import_node_path21.join)(__dirname, "systemd", "threatcrushd.service");
26044
26054
  if (!(0, import_node_fs30.existsSync)(templatePath)) {
@@ -26063,6 +26073,55 @@ function resolveBinPath() {
26063
26073
  function isRoot2() {
26064
26074
  return typeof process.getuid === "function" && process.getuid() === 0;
26065
26075
  }
26076
+ function reexecWithSudo(args) {
26077
+ if ((0, import_node_child_process9.spawnSync)("sudo", ["--version"], { stdio: "pipe" }).status !== 0) return false;
26078
+ console.log(source_default.dim(" This needs root. Re-running under sudo...\n"));
26079
+ const bin = resolveBinPath();
26080
+ const result = (0, import_node_child_process9.spawnSync)("sudo", [bin, ...args], { stdio: "inherit" });
26081
+ return result.status === 0;
26082
+ }
26083
+ function callerHome() {
26084
+ const user = process.env.SUDO_USER;
26085
+ if (!user) return null;
26086
+ try {
26087
+ const line = (0, import_node_child_process9.execSync)(`getent passwd ${user}`, { encoding: "utf-8" }).trim();
26088
+ const home = line.split(":")[5];
26089
+ return home && (0, import_node_fs30.existsSync)(home) ? home : null;
26090
+ } catch {
26091
+ return null;
26092
+ }
26093
+ }
26094
+ function stopUserModeDaemon() {
26095
+ const home = callerHome();
26096
+ if (!home) return;
26097
+ const runDir = (0, import_node_path21.join)(home, ".threatcrush", "run");
26098
+ const pidFile = (0, import_node_path21.join)(runDir, "threatcrushd.pid");
26099
+ const socket = (0, import_node_path21.join)(runDir, "threatcrushd.sock");
26100
+ if (!(0, import_node_fs30.existsSync)(pidFile) && !(0, import_node_fs30.existsSync)(socket)) return;
26101
+ let pid = null;
26102
+ try {
26103
+ pid = Number.parseInt((0, import_node_fs30.readFileSync)(pidFile, "utf-8").trim(), 10);
26104
+ } catch {
26105
+ pid = null;
26106
+ }
26107
+ if (pid && Number.isFinite(pid)) {
26108
+ try {
26109
+ process.kill(pid, "SIGTERM");
26110
+ console.log(source_default.dim(` Stopped the user-mode daemon (pid ${pid}).`));
26111
+ } catch {
26112
+ }
26113
+ }
26114
+ for (const path of [socket, pidFile]) {
26115
+ try {
26116
+ if ((0, import_node_fs30.existsSync)(path)) (0, import_node_fs30.rmSync)(path);
26117
+ } catch {
26118
+ }
26119
+ }
26120
+ }
26121
+ function unitIsActive() {
26122
+ const result = (0, import_node_child_process9.spawnSync)("systemctl", ["is-active", "--quiet", DAEMON_UNIT_NAME], { stdio: "pipe" });
26123
+ return result.status === 0;
26124
+ }
26066
26125
  async function installServiceCommand() {
26067
26126
  banner();
26068
26127
  if (process.platform !== "linux") {
@@ -26070,22 +26129,33 @@ async function installServiceCommand() {
26070
26129
  return;
26071
26130
  }
26072
26131
  if (!isRoot2()) {
26073
- console.log(source_default.red(" Must run as root (try `sudo threatcrush install-service`)."));
26132
+ if (reexecWithSudo(["install-service"])) return;
26133
+ console.log(source_default.red(" Needs root and sudo is unavailable or was declined."));
26134
+ console.log(source_default.dim(" Run this as root: threatcrush install-service"));
26074
26135
  return;
26075
26136
  }
26076
26137
  const unit = resolveTemplate().replace("{{BIN_PATH}}", resolveBinPath());
26077
26138
  (0, import_node_fs30.writeFileSync)(UNIT_PATH, unit, { mode: 420 });
26078
26139
  console.log(source_default.green(` \u2713 Installed unit file: ${UNIT_PATH}`));
26079
26140
  ensureSystemDirs();
26141
+ stopUserModeDaemon();
26080
26142
  try {
26081
26143
  (0, import_node_child_process9.execSync)("systemctl daemon-reload", { stdio: "inherit" });
26082
- (0, import_node_child_process9.execSync)("systemctl enable threatcrushd.service", { stdio: "inherit" });
26083
- console.log(source_default.green(" \u2713 Service enabled on boot."));
26084
- console.log(source_default.dim(" Start now with: systemctl start threatcrushd"));
26085
- console.log(source_default.dim(" View logs with: journalctl -u threatcrushd -f"));
26144
+ (0, import_node_child_process9.execSync)(`systemctl enable --now ${DAEMON_UNIT_NAME}`, { stdio: "inherit" });
26086
26145
  } catch (err) {
26087
26146
  console.log(source_default.yellow(` ! systemctl error: ${err.message}`));
26147
+ console.log(source_default.dim(` Logs: journalctl -u ${DAEMON_UNIT_NAME} -n 50`));
26148
+ return;
26149
+ }
26150
+ if (unitIsActive()) {
26151
+ console.log(source_default.green(" \u2713 Service enabled on boot and running now, as root."));
26152
+ console.log(source_default.dim(" It can write firewall rules, so bans from the dashboard will apply."));
26153
+ console.log(source_default.dim(` Logs: journalctl -u ${DAEMON_UNIT_NAME} -f`));
26154
+ } else {
26155
+ console.log(source_default.yellow(" ! The unit is installed but did not come up."));
26156
+ console.log(source_default.dim(` Logs: journalctl -u ${DAEMON_UNIT_NAME} -n 50`));
26088
26157
  }
26158
+ console.log();
26089
26159
  }
26090
26160
  function ensureSystemDirs() {
26091
26161
  const dirs = [
@@ -26127,7 +26197,9 @@ async function uninstallServiceCommand() {
26127
26197
  return;
26128
26198
  }
26129
26199
  if (!isRoot2()) {
26130
- console.log(source_default.red(" Must run as root (try `sudo threatcrush uninstall-service`)."));
26200
+ if (reexecWithSudo(["uninstall-service"])) return;
26201
+ console.log(source_default.red(" Needs root and sudo is unavailable or was declined."));
26202
+ console.log(source_default.dim(" Run this as root: threatcrush uninstall-service"));
26131
26203
  return;
26132
26204
  }
26133
26205
  try {
@@ -27487,9 +27559,24 @@ async function refreshDaemonAfterUpgrade() {
27487
27559
  });
27488
27560
  if (plan.action === "none") return;
27489
27561
  if (plan.action === "manual") {
27490
- console.log(source_default.yellow(" ! The daemon is managed by systemd and is still on the old build."));
27491
- console.log(source_default.dim(` Restart it with: ${plan.command}
27562
+ console.log(source_default.dim(" Restarting the systemd service onto the new build...\n"));
27563
+ const restarted = restartSystemdDaemon();
27564
+ if (!restarted) {
27565
+ console.log(source_default.yellow(" ! Could not restart the service; it is still on the old build."));
27566
+ console.log(source_default.dim(` Restart it with: ${plan.command}
27492
27567
  `));
27568
+ return;
27569
+ }
27570
+ const after2 = await liveDaemon();
27571
+ const stale = staleDaemonWarning(PKG_VERSION, after2.version);
27572
+ if (stale) {
27573
+ console.log(source_default.yellow(` ${stale[0]}`));
27574
+ for (const line of stale.slice(1)) console.log(source_default.dim(` ${line}`));
27575
+ console.log();
27576
+ } else {
27577
+ console.log(source_default.green(` \u2713 threatcrushd restarted on ${after2.version ?? PKG_VERSION}.
27578
+ `));
27579
+ }
27493
27580
  return;
27494
27581
  }
27495
27582
  console.log(source_default.dim(" Restarting threatcrushd onto the new build...\n"));
@@ -27504,6 +27591,30 @@ async function refreshDaemonAfterUpgrade() {
27504
27591
  console.log();
27505
27592
  }
27506
27593
  }
27594
+ async function promoteUnprivilegedDaemon() {
27595
+ const client = new IpcClient();
27596
+ let warning;
27597
+ try {
27598
+ await client.connect();
27599
+ warning = (await client.blocklist()).warning;
27600
+ } catch {
27601
+ return;
27602
+ } finally {
27603
+ client.close();
27604
+ }
27605
+ if (!warning) return;
27606
+ console.log(source_default.yellow(` ! ${warning}`));
27607
+ console.log(source_default.dim(" Auto-defence is on, so installing the system service to give it that privilege.\n"));
27608
+ await installServiceCommand();
27609
+ }
27610
+ function restartSystemdDaemon() {
27611
+ const asRoot = typeof process.getuid === "function" && process.getuid() === 0;
27612
+ const argv = asRoot ? ["systemctl", "restart", DAEMON_UNIT] : ["sudo", "systemctl", "restart", DAEMON_UNIT];
27613
+ if (!asRoot && (0, import_node_child_process12.spawnSync)("sudo", ["--version"], { stdio: "pipe" }).status !== 0) return false;
27614
+ const [cmd, ...args] = argv;
27615
+ if ((0, import_node_child_process12.spawnSync)(cmd, args, { stdio: "inherit" }).status !== 0) return false;
27616
+ return (0, import_node_child_process12.spawnSync)("systemctl", ["is-active", "--quiet", DAEMON_UNIT], { stdio: "pipe" }).status === 0;
27617
+ }
27507
27618
  function execQuiet(cmd) {
27508
27619
  try {
27509
27620
  return (0, import_node_child_process12.execSync)(cmd, { encoding: "utf-8", stdio: ["pipe", "pipe", "pipe"] });
@@ -27744,6 +27855,7 @@ program2.command("update").description("Update ThreatCrush CLI and installed bun
27744
27855
  }
27745
27856
  await reportIfStillStale();
27746
27857
  await refreshDaemonAfterUpgrade();
27858
+ await promoteUnprivilegedDaemon();
27747
27859
  console.log(source_default.dim(" If a `threatcrush monitor --tui` is open, quit and relaunch it.\n"));
27748
27860
  } catch (err) {
27749
27861
  console.log(source_default.red("\n \u2717 Update failed. Try manually:\n"));