@profullstack/threatcrush 0.13.61 → 0.13.62

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
@@ -17211,11 +17211,11 @@ function daemonError(error2) {
17211
17211
  }
17212
17212
  return new Error(error2 || "ipc error");
17213
17213
  }
17214
- var import_node_net, import_node_fs8, REQUEST_TIMEOUT_MS, IpcClient;
17214
+ var import_node_net2, import_node_fs8, REQUEST_TIMEOUT_MS, IpcClient;
17215
17215
  var init_ipc_client = __esm({
17216
17216
  "src/core/ipc-client.ts"() {
17217
17217
  "use strict";
17218
- import_node_net = require("net");
17218
+ import_node_net2 = require("net");
17219
17219
  import_node_fs8 = require("fs");
17220
17220
  init_paths();
17221
17221
  init_control_token();
@@ -17239,7 +17239,7 @@ var init_ipc_client = __esm({
17239
17239
  throw new Error(`threatcrushd socket not found at ${this.socketPath}`);
17240
17240
  }
17241
17241
  return new Promise((resolve8, reject) => {
17242
- const sock = (0, import_node_net.createConnection)(this.socketPath);
17242
+ const sock = (0, import_node_net2.createConnection)(this.socketPath);
17243
17243
  const timer = setTimeout(() => {
17244
17244
  sock.destroy();
17245
17245
  reject(new Error("ipc connect timeout"));
@@ -18271,12 +18271,12 @@ var init_cli_config = __esm({
18271
18271
 
18272
18272
  // src/tui/map.ts
18273
18273
  function isPublicAddress(ip) {
18274
- const v = (0, import_node_net2.isIP)(ip);
18274
+ const v = (0, import_node_net3.isIP)(ip);
18275
18275
  if (v === 4) return !PRIVATE_V4.some((r) => r.test(ip)) && Number(ip.split(".")[0]) < 224;
18276
18276
  if (v === 6) return !/^(::1?$|f[cd]|fe[89ab]|ff)/i.test(ip);
18277
18277
  return false;
18278
18278
  }
18279
- function localMapData(state, geo, hostname5, now = Date.now()) {
18279
+ function localMapData(state, geo, hostname6, now = Date.now()) {
18280
18280
  const by = /* @__PURE__ */ new Map();
18281
18281
  for (const e of state.events) {
18282
18282
  const ip = e.source_ip;
@@ -18300,7 +18300,7 @@ function localMapData(state, geo, hostname5, now = Date.now()) {
18300
18300
  const o = by.get(t.ip);
18301
18301
  if (o) o.count = Math.max(o.count, t.count);
18302
18302
  }
18303
- const servers = geo.self ? [{ id: "self", name: hostname5, ...geo.self, online: state.connection === "live" }] : [];
18303
+ const servers = geo.self ? [{ id: "self", name: hostname6, ...geo.self, online: state.connection === "live" }] : [];
18304
18304
  return { servers, origins: [...by.values()], windowMinutes: 0, generatedAt: new Date(now).toISOString() };
18305
18305
  }
18306
18306
  function sourceAddresses(state) {
@@ -18407,11 +18407,11 @@ function mapFooter(ui, theme) {
18407
18407
  background: theme.surface
18408
18408
  });
18409
18409
  }
18410
- var import_node_net2, PRIVATE_V4, GeoResolver, SEV, KITTY_ID, MapImageOverlay;
18410
+ var import_node_net3, PRIVATE_V4, GeoResolver, SEV, KITTY_ID, MapImageOverlay;
18411
18411
  var init_map = __esm({
18412
18412
  "src/tui/map.ts"() {
18413
18413
  "use strict";
18414
- import_node_net2 = require("net");
18414
+ import_node_net3 = require("net");
18415
18415
  init_dist();
18416
18416
  init_src();
18417
18417
  init_braille2();
@@ -23425,10 +23425,10 @@ var source_default = chalk;
23425
23425
 
23426
23426
  // src/index.ts
23427
23427
  var import_readline = __toESM(require("readline"));
23428
- var import_node_child_process24 = require("child_process");
23429
- var import_node_fs56 = require("fs");
23430
- var import_node_path43 = require("path");
23431
- var import_node_os17 = require("os");
23428
+ var import_node_child_process25 = require("child_process");
23429
+ var import_node_fs60 = require("fs");
23430
+ var import_node_path46 = require("path");
23431
+ var import_node_os18 = require("os");
23432
23432
 
23433
23433
  // src/commands/monitor.ts
23434
23434
  var import_node_fs11 = require("fs");
@@ -23569,6 +23569,9 @@ function banner() {
23569
23569
  `));
23570
23570
  }
23571
23571
 
23572
+ // src/core/log-parser.ts
23573
+ var import_node_net = require("net");
23574
+
23572
23575
  // src/core/crs/rules.generated.ts
23573
23576
  var CRS_RULES = [
23574
23577
  {
@@ -30260,6 +30263,29 @@ function parseAuthMessage(process11, message, timestamp, raw = message) {
30260
30263
  }
30261
30264
  };
30262
30265
  }
30266
+ var ACCEPTED_REGEX = /Accepted (\S+) for (\S+) from (\S+) port (\d+)(?: [^\s:]+:\s+(\S+)\s+(SHA256:[A-Za-z0-9+/=]+))?/;
30267
+ function parseAcceptedLogin(message) {
30268
+ const m = ACCEPTED_REGEX.exec(message);
30269
+ if (!m) return null;
30270
+ return {
30271
+ method: m[1],
30272
+ user: m[2],
30273
+ ip: m[3],
30274
+ port: Number(m[4]),
30275
+ ...m[5] ? { key_type: m[5] } : {},
30276
+ ...m[6] ? { fingerprint: m[6] } : {}
30277
+ };
30278
+ }
30279
+ var SSHD_PROCESS = /^sshd(?:-session|-auth)?$/;
30280
+ function isSshdProcess(process11) {
30281
+ return !!process11 && SSHD_PROCESS.test(process11);
30282
+ }
30283
+ function sshdPeerIp(message) {
30284
+ const v4 = /(?<![\d.])(\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3})(?![\d.])/.exec(message);
30285
+ const v6 = /(?:from|by|user \S+|for connection from)\s+\[?([0-9a-fA-F]*:[0-9a-fA-F:]+)\]?/.exec(message);
30286
+ const cand = [v4 && { at: v4.index, ip: v4[1] }, v6 && { at: v6.index, ip: v6[1] }].filter((c) => !!c && (0, import_node_net.isIP)(c.ip) !== 0).sort((a, b) => a.at - b.at);
30287
+ return cand[0]?.ip ?? null;
30288
+ }
30263
30289
  function classifySshAuth(entry) {
30264
30290
  const { ip, user, message } = entry.fields;
30265
30291
  if (/failed password/i.test(message)) {
@@ -30269,7 +30295,14 @@ function classifySshAuth(entry) {
30269
30295
  return { severity: "high", message: `Invalid SSH user: ${user || "unknown"} from ${ip || "unknown"}`, source_ip: ip };
30270
30296
  }
30271
30297
  if (/accepted/i.test(message)) {
30272
- return { severity: "info", message: `SSH login accepted for ${user || "unknown"}`, source_ip: ip };
30298
+ const login2 = parseAcceptedLogin(message);
30299
+ const sourceIp = ip ?? (login2 && (0, import_node_net.isIP)(login2.ip) ? login2.ip : void 0);
30300
+ return {
30301
+ severity: "info",
30302
+ message: `SSH login accepted for ${login2?.user || user || "unknown"}`,
30303
+ source_ip: sourceIp,
30304
+ ...login2 ? { details: { ssh_user: login2.user, auth_method: login2.method, port: login2.port, ...login2.key_type ? { key_type: login2.key_type } : {}, ...login2.fingerprint ? { fingerprint: login2.fingerprint } : {} } } : {}
30305
+ };
30273
30306
  }
30274
30307
  return null;
30275
30308
  }
@@ -30396,6 +30429,7 @@ function loadConfig(configPath) {
30396
30429
  update: parsed.update,
30397
30430
  threat_feeds: parsed.threat_feeds,
30398
30431
  privileged: parsed.privileged,
30432
+ lightning: parsed.lightning,
30399
30433
  storage: parsed.storage,
30400
30434
  // TOML's `[abuse-reporter]` parses to a hyphenated key; expose it under
30401
30435
  // the JS-friendly name the rest of the daemon reads.
@@ -41232,7 +41266,7 @@ var import_node_os12 = require("os");
41232
41266
  var import_node_fs26 = require("fs");
41233
41267
  var import_node_path22 = require("path");
41234
41268
  var import_node_child_process5 = require("child_process");
41235
- var import_node_net3 = require("net");
41269
+ var import_node_net4 = require("net");
41236
41270
  var API_URL5 = process.env.THREATCRUSH_API_URL || "https://threatcrush.com";
41237
41271
  var CONFIG_PATH3 = (0, import_node_path22.join)((0, import_node_os12.homedir)(), ".threatcrush", "config.json");
41238
41272
  function readConfig2() {
@@ -41361,7 +41395,7 @@ async function resolveServer(nameOrSlug, orgSlug) {
41361
41395
  var SSH_USER = /^[A-Za-z0-9_][A-Za-z0-9_.-]{0,63}$/;
41362
41396
  var SSH_HOST = /^(?=.{1,253}$)[A-Za-z0-9](?:[A-Za-z0-9-]{0,62}[A-Za-z0-9])?(?:\.[A-Za-z0-9](?:[A-Za-z0-9-]{0,62}[A-Za-z0-9])?)*\.?$/;
41363
41397
  function sshTargetError(options) {
41364
- if (!SSH_HOST.test(options.hostname) && (0, import_node_net3.isIP)(options.hostname) === 0) return `refusing unsafe hostname ${JSON.stringify(options.hostname)}`;
41398
+ if (!SSH_HOST.test(options.hostname) && (0, import_node_net4.isIP)(options.hostname) === 0) return `refusing unsafe hostname ${JSON.stringify(options.hostname)}`;
41365
41399
  if (!SSH_USER.test(options.username)) return `refusing unsafe ssh user ${JSON.stringify(options.username)}`;
41366
41400
  if (!Number.isInteger(options.port) || options.port < 1 || options.port > 65535) return `refusing port ${JSON.stringify(options.port)}`;
41367
41401
  return null;
@@ -41373,23 +41407,23 @@ function sshArgv(options) {
41373
41407
  return args;
41374
41408
  }
41375
41409
  async function sshConnect(options) {
41376
- const { hostname: hostname5, port, username, identity } = options;
41377
- if (!hostname5) {
41410
+ const { hostname: hostname6, port, username, identity } = options;
41411
+ if (!hostname6) {
41378
41412
  console.log(source_default.red(" No hostname available for this server.\n"));
41379
41413
  return;
41380
41414
  }
41381
41415
  const user = username || "root";
41382
- const problem = sshTargetError({ hostname: hostname5, username: user, port });
41416
+ const problem = sshTargetError({ hostname: hostname6, username: user, port });
41383
41417
  if (problem) {
41384
41418
  console.log(source_default.red(` ${problem}
41385
41419
  `));
41386
41420
  process.exitCode = 1;
41387
41421
  return;
41388
41422
  }
41389
- console.log(source_default.green(` Connecting to ${user}@${hostname5}:${port}...
41423
+ console.log(source_default.green(` Connecting to ${user}@${hostname6}:${port}...
41390
41424
  `));
41391
41425
  console.log(source_default.dim(" (Spawning SSH session \u2014 exit with Ctrl+D or type 'exit')\n"));
41392
- const sshArgs = sshArgv({ hostname: hostname5, username: user, port, identity });
41426
+ const sshArgs = sshArgv({ hostname: hostname6, username: user, port, identity });
41393
41427
  const ssh = (0, import_node_child_process5.spawn)("ssh", sshArgs, { stdio: "inherit" });
41394
41428
  ssh.on("error", (err) => {
41395
41429
  console.log(source_default.red(`
@@ -41408,21 +41442,21 @@ async function sshConnect(options) {
41408
41442
  }
41409
41443
 
41410
41444
  // src/commands/daemon.ts
41411
- var import_node_child_process17 = require("child_process");
41412
- var import_node_fs45 = require("fs");
41413
- var import_node_path35 = require("path");
41414
- var import_node_fs46 = require("fs");
41445
+ var import_node_child_process18 = require("child_process");
41446
+ var import_node_fs48 = require("fs");
41447
+ var import_node_path37 = require("path");
41448
+ var import_node_fs49 = require("fs");
41415
41449
 
41416
41450
  // src/daemon/index.ts
41417
- var import_node_fs44 = require("fs");
41418
- var import_node_child_process16 = require("child_process");
41419
- var import_node_os13 = require("os");
41420
- var import_node_path34 = require("path");
41451
+ var import_node_fs47 = require("fs");
41452
+ var import_node_child_process17 = require("child_process");
41453
+ var import_node_os14 = require("os");
41454
+ var import_node_path36 = require("path");
41421
41455
  var import_node_util4 = require("util");
41422
41456
  init_paths();
41423
41457
 
41424
41458
  // src/daemon/ipc-server.ts
41425
- var import_node_net4 = require("net");
41459
+ var import_node_net5 = require("net");
41426
41460
  var import_node_fs27 = require("fs");
41427
41461
  init_paths();
41428
41462
  init_control_token();
@@ -41436,6 +41470,10 @@ var EventBus = class extends import_node_events2.EventEmitter {
41436
41470
  this.emit("alert", event);
41437
41471
  }
41438
41472
  }
41473
+ /** A raw sshd line with a peer address; not an event, nothing is stored or uploaded. */
41474
+ sshdLine(line2) {
41475
+ this.emit("sshd", line2);
41476
+ }
41439
41477
  announceModule(name, status, detail) {
41440
41478
  this.emit("module", { name, status, detail });
41441
41479
  }
@@ -41484,7 +41522,7 @@ var IpcServer = class {
41484
41522
  }
41485
41523
  }
41486
41524
  return new Promise((resolve8, reject) => {
41487
- this.server = (0, import_node_net4.createServer)((sock) => this.handleClient(sock));
41525
+ this.server = (0, import_node_net5.createServer)((sock) => this.handleClient(sock));
41488
41526
  this.server.on("error", reject);
41489
41527
  this.server.listen(PATHS.socket, () => {
41490
41528
  const nodeFs = require("fs");
@@ -41803,9 +41841,14 @@ var LogWatcher = class {
41803
41841
  if (parsed.source === "auth") {
41804
41842
  const entry = parseAuthLog(line2);
41805
41843
  if (!entry) return;
41844
+ if (isSshdProcess(entry.fields.process)) {
41845
+ const peer = sshdPeerIp(entry.fields.message);
41846
+ if (peer) this.bus.sshdLine?.({ timestamp: entry.timestamp, message: entry.fields.message, ip: peer, raw: line2 });
41847
+ }
41806
41848
  const verdict = classifySshAuth(entry);
41807
41849
  if (!verdict) return;
41808
41850
  ({ severity, message, source_ip: sourceIp } = verdict);
41851
+ if (verdict.details) Object.assign(details, verdict.details);
41809
41852
  } else if (parsed.source === "nginx") {
41810
41853
  const entry = parseNginxLog(line2);
41811
41854
  if (!entry) return;
@@ -41881,9 +41924,17 @@ function sshEventFromJournal(entry) {
41881
41924
  category: "auth",
41882
41925
  severity: verdict.severity,
41883
41926
  message: verdict.message,
41884
- source_ip: verdict.source_ip
41927
+ source_ip: verdict.source_ip,
41928
+ ...verdict.details ? { details: verdict.details } : {}
41885
41929
  };
41886
41930
  }
41931
+ function sshdLineFromJournal(entry) {
41932
+ if (!isSshdRecord(entry) || typeof entry.MESSAGE !== "string") return null;
41933
+ const ip = sshdPeerIp(entry.MESSAGE);
41934
+ if (!ip) return null;
41935
+ const timestamp = realtimeToDate(entry.__REALTIME_TIMESTAMP) || /* @__PURE__ */ new Date();
41936
+ return { timestamp, message: entry.MESSAGE, ip, raw: entry.MESSAGE };
41937
+ }
41887
41938
  var JournalWatcher = class _JournalWatcher {
41888
41939
  constructor(bus2) {
41889
41940
  this.bus = bus2;
@@ -41950,6 +42001,8 @@ var JournalWatcher = class _JournalWatcher {
41950
42001
  child.stdout.setEncoding("utf-8");
41951
42002
  child.stdout.on("data", (chunk2) => {
41952
42003
  this.sshdBuffer = this.drain(this.sshdBuffer + chunk2, (entry) => {
42004
+ const line2 = sshdLineFromJournal(entry);
42005
+ if (line2) this.bus.sshdLine?.(line2);
41953
42006
  const event = sshEventFromJournal(entry);
41954
42007
  if (event) this.emit(event);
41955
42008
  });
@@ -42304,12 +42357,12 @@ var import_node_readline3 = require("readline");
42304
42357
  // src/core/threat-feeds/index.ts
42305
42358
  var import_node_fs31 = require("fs");
42306
42359
  var import_node_path23 = require("path");
42307
- var import_node_net6 = require("net");
42360
+ var import_node_net7 = require("net");
42308
42361
 
42309
42362
  // src/daemon/firewall/protected.ts
42310
42363
  var import_node_child_process8 = require("child_process");
42311
42364
  var import_node_fs30 = require("fs");
42312
- var import_node_net5 = require("net");
42365
+ var import_node_net6 = require("net");
42313
42366
  var DEFAULT_PROTECTED = [
42314
42367
  "127.0.0.0/8",
42315
42368
  "::1/128",
@@ -42353,7 +42406,7 @@ var SHARED_INFRASTRUCTURE = [
42353
42406
  "208.67.220.220/32"
42354
42407
  ];
42355
42408
  function ipToBytes(ip) {
42356
- const version = (0, import_node_net5.isIP)(ip);
42409
+ const version = (0, import_node_net6.isIP)(ip);
42357
42410
  if (version === 4) return v4ToBytes(ip);
42358
42411
  if (version === 6) return v6ToBytes(ip);
42359
42412
  return null;
@@ -42431,7 +42484,7 @@ function currentSshClient(env3 = process.env) {
42431
42484
  const source = env3.SSH_CLIENT || env3.SSH_CONNECTION;
42432
42485
  if (!source) return null;
42433
42486
  const ip = source.trim().split(/\s+/)[0];
42434
- return ip && (0, import_node_net5.isIP)(ip) ? ip : null;
42487
+ return ip && (0, import_node_net6.isIP)(ip) ? ip : null;
42435
42488
  }
42436
42489
  function establishedSshPeers() {
42437
42490
  const peers = /* @__PURE__ */ new Set();
@@ -42447,7 +42500,7 @@ function establishedSshPeers() {
42447
42500
  const peer = parts[4];
42448
42501
  if (!peer) continue;
42449
42502
  const ip = peer.slice(0, peer.lastIndexOf(":")).replace(/^\[|\]$/g, "");
42450
- if (ip && (0, import_node_net5.isIP)(ip)) peers.add(ip);
42503
+ if (ip && (0, import_node_net6.isIP)(ip)) peers.add(ip);
42451
42504
  }
42452
42505
  } catch {
42453
42506
  }
@@ -42456,7 +42509,7 @@ function establishedSshPeers() {
42456
42509
  function sshClientFromEnviron(environ) {
42457
42510
  for (const entry of environ.split("\0")) {
42458
42511
  const m = /^SSH_(?:CONNECTION|CLIENT)=(\S+)/.exec(entry);
42459
- if (m && (0, import_node_net5.isIP)(m[1])) return m[1];
42512
+ if (m && (0, import_node_net6.isIP)(m[1])) return m[1];
42460
42513
  }
42461
42514
  return null;
42462
42515
  }
@@ -42482,7 +42535,7 @@ function parseKeyLogins(text, skip = () => false) {
42482
42535
  const out = /* @__PURE__ */ new Map();
42483
42536
  for (const line2 of text.split("\n")) {
42484
42537
  const m = /^(\d+(?:\.\d+)?)\s.*Accepted publickey for \S+ from (\S+) port \d+ [^\s:]+(?:: \S+ (SHA256:\S+))?/.exec(line2);
42485
- if (!m || !(0, import_node_net5.isIP)(m[2])) continue;
42538
+ if (!m || !(0, import_node_net6.isIP)(m[2])) continue;
42486
42539
  if (m[3] && skip(m[3])) continue;
42487
42540
  const at = Math.round(Number(m[1]) * 1e3);
42488
42541
  if (at > (out.get(m[2]) ?? 0)) out.set(m[2], at);
@@ -42499,7 +42552,7 @@ function defaultGateways() {
42499
42552
  const out = (0, import_node_child_process8.execFileSync)("ip", args, { encoding: "utf-8", stdio: ["ignore", "pipe", "ignore"] });
42500
42553
  for (const line2 of out.split("\n")) {
42501
42554
  const match = line2.match(/\bvia\s+(\S+)/);
42502
- if (match && (0, import_node_net5.isIP)(match[1])) found.add(match[1]);
42555
+ if (match && (0, import_node_net6.isIP)(match[1])) found.add(match[1]);
42503
42556
  }
42504
42557
  } catch {
42505
42558
  }
@@ -42612,26 +42665,26 @@ function parseIpList(text, feed) {
42612
42665
  const out = /* @__PURE__ */ new Map();
42613
42666
  for (const line2 of text.split("\n")) {
42614
42667
  const ip = line2.trim();
42615
- if (ip && !ip.startsWith("#") && (0, import_node_net6.isIP)(ip)) out.set(ip, { malware: "unknown", threat: "botnet_cc", feed });
42668
+ if (ip && !ip.startsWith("#") && (0, import_node_net7.isIP)(ip)) out.set(ip, { malware: "unknown", threat: "botnet_cc", feed });
42616
42669
  }
42617
42670
  return out;
42618
42671
  }
42619
42672
  function stripPort(value) {
42620
42673
  const v6 = /^\[([^\]]+)\]:\d+$/.exec(value);
42621
42674
  const ip = v6 ? v6[1] : value.replace(/:\d+$/, "");
42622
- return (0, import_node_net6.isIP)(ip) ? ip : null;
42675
+ return (0, import_node_net7.isIP)(ip) ? ip : null;
42623
42676
  }
42624
42677
  function normalizeDomain(value) {
42625
42678
  const d = value.trim().toLowerCase().replace(/\.$/, "");
42626
- if (!d || d === "localhost" || (0, import_node_net6.isIP)(d) || !/^[a-z0-9_.-]+\.[a-z0-9-]{2,}$/.test(d)) return null;
42679
+ if (!d || d === "localhost" || (0, import_node_net7.isIP)(d) || !/^[a-z0-9_.-]+\.[a-z0-9-]{2,}$/.test(d)) return null;
42627
42680
  return d;
42628
42681
  }
42629
42682
  function allowedDomain(domain, allow) {
42630
42683
  return allow.some((a) => domain === a || domain.endsWith(`.${a}`));
42631
42684
  }
42632
42685
  function buildFeedSet(parts, allow, sources, now = /* @__PURE__ */ new Date()) {
42633
- const neverIps = [...DEFAULT_PROTECTED, ...SHARED_RANGES, ...allow.filter((a) => (0, import_node_net6.isIP)(a.split("/")[0]))];
42634
- const allowDomains = allow.filter((a) => !(0, import_node_net6.isIP)(a.split("/")[0])).map((a) => a.toLowerCase());
42686
+ const neverIps = [...DEFAULT_PROTECTED, ...SHARED_RANGES, ...allow.filter((a) => (0, import_node_net7.isIP)(a.split("/")[0]))];
42687
+ const allowDomains = allow.filter((a) => !(0, import_node_net7.isIP)(a.split("/")[0])).map((a) => a.toLowerCase());
42635
42688
  const ips = {};
42636
42689
  const domains = {};
42637
42690
  let skipped = 0;
@@ -43453,11 +43506,55 @@ function pagerdutyChannel(config) {
43453
43506
  };
43454
43507
  }
43455
43508
 
43509
+ // src/daemon/alerts/smshub.ts
43510
+ var import_node_os13 = require("os");
43511
+ var SEVERITY_RANK6 = { info: 0, low: 1, medium: 2, high: 3, critical: 4 };
43512
+ var DEDUPE_MS = 10 * 6e4;
43513
+ var MAX_PER_HOUR = 6;
43514
+ function smshubText(event, host = (0, import_node_os13.hostname)()) {
43515
+ const evidence = event.details?.evidence?.message;
43516
+ const text = `ThreatCrush ${event.severity.toUpperCase()} on ${host}: ${event.message}${evidence && !event.message.includes(evidence) ? ` | ${evidence}` : ""}`;
43517
+ return text.replace(/\s+/g, " ").slice(0, 600);
43518
+ }
43519
+ function smshubChannel(config, opts = {}) {
43520
+ const sent = /* @__PURE__ */ new Map();
43521
+ const recent = [];
43522
+ const now = opts.now ?? Date.now;
43523
+ const doFetch = opts.fetchImpl ?? fetch;
43524
+ return async (event) => {
43525
+ const key = config.api_key || (config.api_key_env ? process.env[config.api_key_env] : void 0) || process.env.SMSHUB_ALERT_API_KEY;
43526
+ if (!key) return;
43527
+ if ((SEVERITY_RANK6[event.severity] ?? 0) < (SEVERITY_RANK6[config.min_severity ?? "critical"] ?? 4)) return;
43528
+ if (config.fallback_only !== false && opts.cloudHealthy?.()) return;
43529
+ const message = smshubText(event);
43530
+ const at = now();
43531
+ const dedupe2 = `${event.details?.rule_id ?? event.module}|${event.source_ip ?? ""}|${event.details?.fingerprint ?? ""}`;
43532
+ if (at - (sent.get(dedupe2) ?? 0) < DEDUPE_MS) return;
43533
+ while (recent.length && recent[0] < at - 36e5) recent.shift();
43534
+ if (recent.length >= MAX_PER_HOUR) return;
43535
+ sent.set(dedupe2, at);
43536
+ recent.push(at);
43537
+ const base = (config.url || "https://smshub.dev").replace(/\/$/, "");
43538
+ try {
43539
+ const res = await doFetch(`${base}/api/v1/alerts`, {
43540
+ method: "POST",
43541
+ headers: { "X-API-Key": key, "Content-Type": "application/json", "User-Agent": "threatcrush-daemon" },
43542
+ body: JSON.stringify({ message, severity: event.severity === "critical" ? "critical" : "warning", ...config.to ? { to: config.to } : {} }),
43543
+ signal: AbortSignal.timeout(15e3)
43544
+ });
43545
+ opts.log?.(`[alerts] smshub ${res.ok ? "paged" : `failed HTTP ${res.status}`}: ${message.slice(0, 160)}`);
43546
+ } catch (err) {
43547
+ opts.log?.(`[alerts] smshub failed: ${err.message}`);
43548
+ }
43549
+ };
43550
+ }
43551
+
43456
43552
  // src/daemon/alerts/index.ts
43457
43553
  var AlertDispatcher = class {
43458
- constructor(bus2, config) {
43554
+ constructor(bus2, config, hooks = {}) {
43459
43555
  this.bus = bus2;
43460
43556
  this.config = config;
43557
+ this.hooks = hooks;
43461
43558
  this.bindChannels();
43462
43559
  bus2.on("alert", (event) => {
43463
43560
  void this.dispatch(event);
@@ -43465,6 +43562,7 @@ var AlertDispatcher = class {
43465
43562
  }
43466
43563
  bus;
43467
43564
  config;
43565
+ hooks;
43468
43566
  channels = [];
43469
43567
  rateLimits = /* @__PURE__ */ new Map();
43470
43568
  bindChannels() {
@@ -43484,6 +43582,9 @@ var AlertDispatcher = class {
43484
43582
  if (name === "discord" && typeof cfg.webhook_url === "string") {
43485
43583
  this.channels.push(discordChannel(cfg));
43486
43584
  }
43585
+ if (name === "smshub") {
43586
+ this.channels.push(smshubChannel(cfg, this.hooks));
43587
+ }
43487
43588
  if (name === "pagerduty" && typeof cfg.routing_key === "string") {
43488
43589
  this.channels.push(pagerdutyChannel(cfg));
43489
43590
  }
@@ -43531,13 +43632,13 @@ function slackChannel(webhookUrl) {
43531
43632
  // src/daemon/workers/runs-worker.ts
43532
43633
  var import_promises2 = require("dns/promises");
43533
43634
  var import_node_fs34 = require("fs");
43534
- var import_node_net8 = require("net");
43635
+ var import_node_net9 = require("net");
43535
43636
  var import_node_path25 = require("path");
43536
43637
  init_cli_config();
43537
43638
 
43538
43639
  // src/core/cloud-events.ts
43539
43640
  var import_node_crypto7 = require("crypto");
43540
- var import_node_net7 = require("net");
43641
+ var import_node_net8 = require("net");
43541
43642
  init_cli_config();
43542
43643
  function currentLink() {
43543
43644
  if (!hasSession()) return null;
@@ -43545,7 +43646,7 @@ function currentLink() {
43545
43646
  if (!cfg.server_id || !cfg.server_org_id) return null;
43546
43647
  return { serverId: cfg.server_id, orgId: cfg.server_org_id };
43547
43648
  }
43548
- var SEVERITY_RANK6 = {
43649
+ var SEVERITY_RANK7 = {
43549
43650
  info: 0,
43550
43651
  low: 1,
43551
43652
  medium: 2,
@@ -43605,7 +43706,7 @@ function detectionEvent(serverId, event) {
43605
43706
  title: title.slice(0, MAX_TITLE_CHARS) || event.module,
43606
43707
  rule_id: str2(rule_id) ?? event.module,
43607
43708
  description: str2(description),
43608
- source_ip: event.source_ip && (0, import_node_net7.isIP)(event.source_ip) ? event.source_ip : void 0,
43709
+ source_ip: event.source_ip && (0, import_node_net8.isIP)(event.source_ip) ? event.source_ip : void 0,
43609
43710
  username: str2(username) ?? str2(user),
43610
43711
  raw_metadata: trimMetadata({ module: event.module, category: event.category, ...rest }),
43611
43712
  detected_at: event.timestamp.toISOString()
@@ -43662,7 +43763,7 @@ var NOT_PUBLIC = [
43662
43763
  "ff00::/8"
43663
43764
  ];
43664
43765
  function isPublicTarget(ip) {
43665
- return (0, import_node_net8.isIP)(ip) !== 0 && !isProtected(ip, NOT_PUBLIC);
43766
+ return (0, import_node_net9.isIP)(ip) !== 0 && !isProtected(ip, NOT_PUBLIC);
43666
43767
  }
43667
43768
  async function pentestTargetError(rawUrl, resolveHost = async (h) => (await (0, import_promises2.lookup)(h, { all: true })).map((a) => a.address)) {
43668
43769
  let url;
@@ -43675,7 +43776,7 @@ async function pentestTargetError(rawUrl, resolveHost = async (h) => (await (0,
43675
43776
  const host = url.hostname.replace(/^\[|\]$/g, "");
43676
43777
  let addresses;
43677
43778
  try {
43678
- addresses = (0, import_node_net8.isIP)(host) ? [host] : await resolveHost(host);
43779
+ addresses = (0, import_node_net9.isIP)(host) ? [host] : await resolveHost(host);
43679
43780
  } catch (err) {
43680
43781
  return `cannot resolve ${host}: ${err.message}`;
43681
43782
  }
@@ -44002,6 +44103,7 @@ var CloudSync = class {
44002
44103
  retryAt = 0;
44003
44104
  link = null;
44004
44105
  lastProblem = "";
44106
+ lastOkAt = 0;
44005
44107
  onEvent = (event) => this.capture(event);
44006
44108
  start() {
44007
44109
  this.link = currentLink();
@@ -44034,6 +44136,10 @@ var CloudSync = class {
44034
44136
  get queued() {
44035
44137
  return this.spool.size;
44036
44138
  }
44139
+ /** Linked, and the dashboard accepted an upload or heartbeat in the last 3 minutes. */
44140
+ get healthy() {
44141
+ return !!this.link && !this.lastProblem && Date.now() - this.lastOkAt < 18e4;
44142
+ }
44037
44143
  /** Queue hardening results for upload (the CLI posts its own directly). */
44038
44144
  enqueueFindings(results) {
44039
44145
  const link = this.refreshLink();
@@ -44058,7 +44164,7 @@ var CloudSync = class {
44058
44164
  let out = null;
44059
44165
  if (event.module === "firewall-rules") {
44060
44166
  out = remediationEvent(link.serverId, event);
44061
- } else if ((event.module === "rule-engine" || !this.opts.ruleModules.has(event.module)) && event.details?.heartbeat !== true && SEVERITY_RANK6[event.severity] >= SEVERITY_RANK6[this.opts.minSeverity]) {
44167
+ } else if ((event.module === "rule-engine" || !this.opts.ruleModules.has(event.module)) && event.details?.heartbeat !== true && SEVERITY_RANK7[event.severity] >= SEVERITY_RANK7[this.opts.minSeverity]) {
44062
44168
  out = detectionEvent(link.serverId, event);
44063
44169
  }
44064
44170
  if (!out) return;
@@ -44106,6 +44212,7 @@ var CloudSync = class {
44106
44212
  this.backoffMs = 0;
44107
44213
  this.retryAt = 0;
44108
44214
  this.lastProblem = "";
44215
+ this.lastOkAt = Date.now();
44109
44216
  return "sent";
44110
44217
  }
44111
44218
  if (res.status === 401) {
@@ -44150,6 +44257,7 @@ var CloudSync = class {
44150
44257
  };
44151
44258
  try {
44152
44259
  const res = await cloudFetch("/api/ingest", { method: "POST", body: JSON.stringify({ events: [event] }) });
44260
+ if (res.ok) this.lastOkAt = Date.now();
44153
44261
  if (res.ok && this.retryAt > 0) {
44154
44262
  this.retryAt = 0;
44155
44263
  void this.flush();
@@ -44173,7 +44281,7 @@ var CloudSync = class {
44173
44281
  var import_node_crypto8 = require("crypto");
44174
44282
 
44175
44283
  // src/daemon/workers/abuse-evidence.ts
44176
- var import_node_net9 = require("net");
44284
+ var import_node_net10 = require("net");
44177
44285
  var NEVER_REPORT_RANGES = [
44178
44286
  ...DEFAULT_PROTECTED,
44179
44287
  "100.64.0.0/10",
@@ -44249,7 +44357,7 @@ function summarizeEvidence(events) {
44249
44357
  };
44250
44358
  }
44251
44359
  function isReportable(ip, evidence, config, now = Date.now()) {
44252
- if ((0, import_node_net9.isIP)(ip) === 0) return { reportable: false, reason: "not an IP address" };
44360
+ if ((0, import_node_net10.isIP)(ip) === 0) return { reportable: false, reason: "not an IP address" };
44253
44361
  if (isProtected(ip, config.neverReport)) {
44254
44362
  return { reportable: false, reason: "address is in a never-report range (private/CGNAT/reserved/allowlisted)" };
44255
44363
  }
@@ -44600,15 +44708,15 @@ var AbuseReporter = class {
44600
44708
  };
44601
44709
 
44602
44710
  // src/daemon/workers/remediation-consumer.ts
44603
- var import_node_net11 = require("net");
44711
+ var import_node_net12 = require("net");
44604
44712
  init_cli_config();
44605
44713
 
44606
44714
  // src/daemon/workers/allowlist-sync.ts
44607
- var import_node_net10 = require("net");
44715
+ var import_node_net11 = require("net");
44608
44716
  init_cli_config();
44609
44717
  function isAddressOrCidr(value) {
44610
44718
  const [network, prefix, extra] = value.split("/");
44611
- const family = (0, import_node_net10.isIP)(network);
44719
+ const family = (0, import_node_net11.isIP)(network);
44612
44720
  if (family === 0 || extra !== void 0) return false;
44613
44721
  if (prefix === void 0) return true;
44614
44722
  if (!/^\d{1,3}$/.test(prefix)) return false;
@@ -44619,7 +44727,7 @@ function isCloudAllowEntry(value) {
44619
44727
  if (!isAddressOrCidr(value)) return false;
44620
44728
  const [network, prefix] = value.split("/");
44621
44729
  if (prefix === void 0) return true;
44622
- return Number(prefix) >= CLOUD_MIN_PREFIX[(0, import_node_net10.isIP)(network)];
44730
+ return Number(prefix) >= CLOUD_MIN_PREFIX[(0, import_node_net11.isIP)(network)];
44623
44731
  }
44624
44732
  var AllowlistSync = class {
44625
44733
  constructor(manager, opts) {
@@ -44642,6 +44750,17 @@ var AllowlistSync = class {
44642
44750
  async sync() {
44643
44751
  const link = currentLink();
44644
44752
  if (!link) return;
44753
+ if (this.opts.onOrgSettings) {
44754
+ try {
44755
+ const res = await cloudFetch(`/api/orgs/${link.orgId}`);
44756
+ if (res.ok) {
44757
+ const data = await res.json();
44758
+ const v = data.organization?.block_tor_ssh;
44759
+ if (typeof v === "boolean") this.opts.onOrgSettings({ block_tor_ssh: v });
44760
+ }
44761
+ } catch {
44762
+ }
44763
+ }
44645
44764
  let entries;
44646
44765
  try {
44647
44766
  const res = await cloudFetch(`/api/orgs/${link.orgId}/allowlists`);
@@ -44657,7 +44776,7 @@ var AllowlistSync = class {
44657
44776
  if (entry.type !== "ip" && entry.type !== "cidr") continue;
44658
44777
  const value = String(entry.value ?? "").trim();
44659
44778
  if (isCloudAllowEntry(value)) wanted.add(value);
44660
- else if (isAddressOrCidr(value)) this.opts.log(`[cloud] org allowlist: ignoring ${value} (wider than /${CLOUD_MIN_PREFIX[(0, import_node_net10.isIP)(value.split("/")[0])]})`);
44779
+ else if (isAddressOrCidr(value)) this.opts.log(`[cloud] org allowlist: ignoring ${value} (wider than /${CLOUD_MIN_PREFIX[(0, import_node_net11.isIP)(value.split("/")[0])]})`);
44661
44780
  }
44662
44781
  const added2 = [];
44663
44782
  const protectedNow = new Set(this.manager.getProtected());
@@ -44765,7 +44884,7 @@ var RemediationConsumer = class {
44765
44884
  try {
44766
44885
  switch (action.action_type) {
44767
44886
  case "block": {
44768
- if ((0, import_node_net11.isIP)(target) === 0) return failed(`not an IP address: ${target}`);
44887
+ if ((0, import_node_net12.isIP)(target) === 0) return failed(`not an IP address: ${target}`);
44769
44888
  let ttlSeconds = this.manager.status().max_ban_seconds;
44770
44889
  if (action.expires_at) {
44771
44890
  const until = Date.parse(action.expires_at);
@@ -44784,7 +44903,7 @@ var RemediationConsumer = class {
44784
44903
  return { status: "executed", dry_run: result.entry?.dry_run === true, executed_at };
44785
44904
  }
44786
44905
  case "unblock": {
44787
- if ((0, import_node_net11.isIP)(target) === 0) return failed(`not an IP address: ${target}`);
44906
+ if ((0, import_node_net12.isIP)(target) === 0) return failed(`not an IP address: ${target}`);
44788
44907
  const wasBanned = this.manager.getBlocklist().some((b) => b.ip === target);
44789
44908
  const result = await this.manager.unban(target, {
44790
44909
  forget: true,
@@ -45089,7 +45208,7 @@ var AutoUpdate = class {
45089
45208
  var import_node_child_process11 = require("child_process");
45090
45209
  var import_node_fs38 = require("fs");
45091
45210
  var import_node_path29 = require("path");
45092
- var import_node_net12 = require("net");
45211
+ var import_node_net13 = require("net");
45093
45212
  init_backoff();
45094
45213
  var EGRESS_TABLE = "threatcrush_egress";
45095
45214
  var DEFAULT_REFRESH_MS = 36e5;
@@ -45108,8 +45227,8 @@ function threatFeedSettings(section) {
45108
45227
  };
45109
45228
  }
45110
45229
  function egressRuleset(ips) {
45111
- const v4 = ips.filter((ip) => (0, import_node_net12.isIP)(ip) === 4);
45112
- const v6 = ips.filter((ip) => (0, import_node_net12.isIP)(ip) === 6);
45230
+ const v4 = ips.filter((ip) => (0, import_node_net13.isIP)(ip) === 4);
45231
+ const v6 = ips.filter((ip) => (0, import_node_net13.isIP)(ip) === 6);
45113
45232
  const set = (name, type, items) => ` set ${name} { type ${type};${items.length ? ` elements = { ${items.join(", ")} }` : ""} }`;
45114
45233
  const chain = (name, hook) => [
45115
45234
  ` chain ${name} {`,
@@ -45134,7 +45253,7 @@ function splitAddr(addr) {
45134
45253
  const m = /^\[?(.+?)\]?:(\d+|\*)$/.exec(addr);
45135
45254
  if (!m) return null;
45136
45255
  const ip = m[1].replace(/%.*$/, "").replace(/^::ffff:/i, "");
45137
- return (0, import_node_net12.isIP)(ip) ? { ip, port: m[2] === "*" ? 0 : Number(m[2]) } : null;
45256
+ return (0, import_node_net13.isIP)(ip) ? { ip, port: m[2] === "*" ? 0 : Number(m[2]) } : null;
45138
45257
  }
45139
45258
  function parseSs(text) {
45140
45259
  const out = [];
@@ -45522,7 +45641,42 @@ function parseSudoMessage(message) {
45522
45641
 
45523
45642
  // src/daemon/workers/privilege-watch.ts
45524
45643
  function privilegeSettings(section) {
45525
- return { enabled: section?.enabled !== false, geo: section?.geo !== false, pollMs: 6e4 };
45644
+ return {
45645
+ enabled: section?.enabled !== false,
45646
+ geo: section?.geo !== false,
45647
+ pollMs: 6e4,
45648
+ expectedKeys: Array.isArray(section?.expected_keys) ? section.expected_keys.map(String).filter(Boolean) : [],
45649
+ watchFiles: true
45650
+ };
45651
+ }
45652
+ function keyIsExpected(fingerprint, comment, expected) {
45653
+ return expected.some((pattern) => {
45654
+ if (pattern.startsWith("SHA256:")) return pattern === fingerprint;
45655
+ const re = new RegExp(`^${pattern.split("*").map((p) => p.replace(/[.+?^${}()|[\]\\]/g, "\\$&")).join(".*")}$`, "i");
45656
+ return re.test(comment);
45657
+ });
45658
+ }
45659
+ var SELFTEST_KEY_COMMENT = "threatcrush-selftest";
45660
+ function classifyKeyAddition(change, expected) {
45661
+ if (change.details.rule_id !== "priv-authorized-key-added") return change;
45662
+ const fp = String(change.details.fingerprint ?? "");
45663
+ const comment = String(change.details.comment ?? "");
45664
+ const account = String(change.details.account ?? "?");
45665
+ if (comment.includes(SELFTEST_KEY_COMMENT)) {
45666
+ return {
45667
+ severity: "critical",
45668
+ message: `[TEST] ThreatCrush self-test: new SSH key for ${account} detected (${fp}, ${comment}). This is a test, nothing is wrong.`,
45669
+ details: { ...change.details, rule_id: "priv-authorized-key-selftest", selftest: true }
45670
+ };
45671
+ }
45672
+ if (keyIsExpected(fp, comment, expected)) {
45673
+ return { ...change, severity: "high", details: { ...change.details, expected: true } };
45674
+ }
45675
+ return {
45676
+ severity: "critical",
45677
+ message: `New SSH key added for ${account}: ${change.details.key_type ?? ""} ${fp}${comment ? ` "${comment}"` : " (no comment)"}, not an expected key; whoever holds it can log in`,
45678
+ details: { ...change.details, expected: false }
45679
+ };
45526
45680
  }
45527
45681
  var COUNTRY_NAMES = new Intl.DisplayNames(["en"], { type: "region" });
45528
45682
  function countryName(code) {
@@ -45620,6 +45774,8 @@ var PrivilegeWatch = class {
45620
45774
  run;
45621
45775
  now;
45622
45776
  warnedUnreadable = false;
45777
+ watchers = /* @__PURE__ */ new Map();
45778
+ debounce = null;
45623
45779
  onEvent = (event) => {
45624
45780
  void this.checkLogin(event);
45625
45781
  };
@@ -45634,9 +45790,11 @@ var PrivilegeWatch = class {
45634
45790
  this.opts.bus.on("event", this.onEvent);
45635
45791
  void this.backfillLogins();
45636
45792
  }
45793
+ if (this.opts.settings.watchFiles) this.watchKeyDirs();
45637
45794
  const timer = setInterval(() => {
45638
45795
  this.checkSnapshot();
45639
45796
  this.readSudoLedger();
45797
+ if (this.opts.settings.watchFiles) this.watchKeyDirs();
45640
45798
  }, this.opts.settings.pollMs);
45641
45799
  timer.unref?.();
45642
45800
  this.timers.push(timer);
@@ -45644,8 +45802,55 @@ var PrivilegeWatch = class {
45644
45802
  stop() {
45645
45803
  for (const t of this.timers) clearInterval(t);
45646
45804
  this.timers = [];
45805
+ for (const w of this.watchers.values()) {
45806
+ try {
45807
+ w.close();
45808
+ } catch {
45809
+ }
45810
+ }
45811
+ this.watchers.clear();
45812
+ if (this.debounce) clearTimeout(this.debounce);
45647
45813
  this.opts.bus.off("event", this.onEvent);
45648
45814
  }
45815
+ /**
45816
+ * inotify on every login account's ~/.ssh (and /root/.ssh): a write there
45817
+ * re-checks the snapshot within a second, not at the next minute's poll.
45818
+ * Re-run each poll so a directory created later is picked up.
45819
+ */
45820
+ watchKeyDirs() {
45821
+ const dirs = /* @__PURE__ */ new Set();
45822
+ for (const line2 of (this.io.readFile("/etc/passwd") ?? "").split("\n")) {
45823
+ const f = line2.split(":");
45824
+ if (f.length < 7) continue;
45825
+ const uid = Number(f[2]);
45826
+ const home = f[5];
45827
+ if (!home || home === "/" || uid !== 0 && /(nologin|\/false)$/.test(f[6].trim())) continue;
45828
+ dirs.add(`${home.replace(/\/$/, "")}/.ssh`);
45829
+ }
45830
+ for (const dir of dirs) {
45831
+ if (this.watchers.has(dir) || !this.io.exists(dir)) continue;
45832
+ try {
45833
+ const w = (0, import_node_fs39.watch)(dir, { persistent: false }, (_type2, name) => {
45834
+ if (name && !String(name).startsWith("authorized_keys")) return;
45835
+ if (this.debounce) clearTimeout(this.debounce);
45836
+ this.debounce = setTimeout(() => {
45837
+ this.debounce = null;
45838
+ this.checkSnapshot();
45839
+ }, 750);
45840
+ this.debounce.unref?.();
45841
+ });
45842
+ w.on("error", () => {
45843
+ try {
45844
+ w.close();
45845
+ } catch {
45846
+ }
45847
+ this.watchers.delete(dir);
45848
+ });
45849
+ this.watchers.set(dir, w);
45850
+ } catch {
45851
+ }
45852
+ }
45853
+ }
45649
45854
  emit(severity, message, details) {
45650
45855
  const event = { timestamp: this.now(), module: "privileged-access", category: "auth", severity, message, details };
45651
45856
  try {
@@ -45665,7 +45870,16 @@ var PrivilegeWatch = class {
45665
45870
  const keys = Object.values(next.keys).reduce((n, k) => n + Object.keys(k).length, 0);
45666
45871
  this.opts.log(`[privileged] baseline recorded: uid0 [${next.uid0.join(", ")}], ${Object.values(next.admin_groups).flat().length} admin-group member(s), ${Object.keys(next.sudoers).length} sudoers file(s), ${keys} authorized key(s)`);
45667
45872
  } else {
45668
- for (const change of diffSnapshots(prev, next)) this.emit(change.severity, change.message, change.details);
45873
+ for (const raw of diffSnapshots(prev, next)) {
45874
+ const change = classifyKeyAddition(raw, this.opts.settings.expectedKeys ?? []);
45875
+ if (change.details.rule_id === "priv-authorized-key-added" || change.details.rule_id === "priv-authorized-key-selftest") {
45876
+ this.opts.log(`[privileged] ${change.severity.toUpperCase()} ${change.message}`);
45877
+ }
45878
+ this.emit(change.severity, change.message, {
45879
+ ...change.details,
45880
+ evidence: { at: this.now().toISOString(), module: "privileged-access", message: change.message.slice(0, 500) }
45881
+ });
45882
+ }
45669
45883
  }
45670
45884
  try {
45671
45885
  writeJson(this.opts.snapshotPath, next);
@@ -45779,6 +45993,636 @@ var PrivilegeWatch = class {
45779
45993
  }
45780
45994
  };
45781
45995
 
45996
+ // src/daemon/workers/ssh-intrusion.ts
45997
+ var import_node_fs40 = require("fs");
45998
+ var import_node_path31 = require("path");
45999
+ var import_node_child_process13 = require("child_process");
46000
+
46001
+ // src/core/asn.ts
46002
+ var import_node_dns = require("dns");
46003
+ var import_node_net14 = require("net");
46004
+ var CI_ASNS = /* @__PURE__ */ new Set([8075, 36459, 8068, 8069, 12076]);
46005
+ var HOSTING_ASNS = /* @__PURE__ */ new Set([
46006
+ 15169,
46007
+ 396982,
46008
+ 19527,
46009
+ // Google, Google Cloud
46010
+ 16509,
46011
+ 14618,
46012
+ // Amazon / AWS
46013
+ 16276,
46014
+ // OVH
46015
+ 24940,
46016
+ 213230,
46017
+ // Hetzner
46018
+ 14061,
46019
+ // DigitalOcean
46020
+ 63949,
46021
+ // Linode / Akamai
46022
+ 20473,
46023
+ // Vultr (Choopa)
46024
+ 12876,
46025
+ // Scaleway
46026
+ 51167,
46027
+ // Contabo
46028
+ 31898,
46029
+ // Oracle Cloud
46030
+ 45102,
46031
+ // Alibaba
46032
+ 132203,
46033
+ 45090,
46034
+ // Tencent
46035
+ 36352,
46036
+ // ColoCrossing
46037
+ 53667,
46038
+ // FranTech / BuyVM
46039
+ 197540,
46040
+ // netcup
46041
+ 9009,
46042
+ // M247
46043
+ 60068,
46044
+ // Datacamp / CDN77
46045
+ 212238,
46046
+ // Datacamp
46047
+ 202425,
46048
+ // IP Volume
46049
+ 210644,
46050
+ // Aeza
46051
+ 49981,
46052
+ // WorldStream
46053
+ 62240,
46054
+ // Clouvider
46055
+ 136907,
46056
+ // Huawei Cloud
46057
+ 8100,
46058
+ // QuadraNet
46059
+ 46606,
46060
+ // Unified Layer
46061
+ 29802,
46062
+ // HVC
46063
+ 40021,
46064
+ // Contabo US / Nubes
46065
+ 398324,
46066
+ 399629
46067
+ // Censys and friends
46068
+ ]);
46069
+ var VPN_ASNS = /* @__PURE__ */ new Set([
46070
+ 9009,
46071
+ // M247 (most commercial VPN exits)
46072
+ 212238,
46073
+ 60068,
46074
+ // Datacamp (NordVPN, Proton, ...)
46075
+ 209854,
46076
+ // Surfshark
46077
+ 39351,
46078
+ // 31173 Services (Mullvad)
46079
+ 136787,
46080
+ // TEFINCOM (NordVPN)
46081
+ 147049
46082
+ // PacketHub (NordVPN)
46083
+ ]);
46084
+ var HOSTING_NAME = /hosting|server|datacenter|data center|data-center|cloud|colo|vps|dedicated|ovh|hetzner|digitalocean|linode|vultr|choopa|amazon|aws|google|microsoft|azure|oracle|alibaba|tencent|contabo|scaleway|leaseweb|ionos|kamatera|frantech|buyvm|racknerd|quadranet|psychz|m247|datacamp|cdn77|aeza|serverius|worldstream|ipvolume|clouvider|netcup|gcore|g-core|selectel|timeweb|hostinger|godaddy|incapsula|fastly/i;
46085
+ var VPN_NAME = /\bvpn\b|proton|mullvad|nordvpn|surfshark|expressvpn|private internet access|tefincom|packethub|31173 services|anonymi[sz]|privacy|proxy/i;
46086
+ function classifyAsn(info2) {
46087
+ if (!info2) return "unknown";
46088
+ if (CI_ASNS.has(info2.asn)) return "ci";
46089
+ if (VPN_ASNS.has(info2.asn) || VPN_NAME.test(info2.name)) return "vpn";
46090
+ if (HOSTING_ASNS.has(info2.asn) || HOSTING_NAME.test(info2.name)) return "hosting";
46091
+ return "unknown";
46092
+ }
46093
+ function cymruOriginName(ip) {
46094
+ const bytes = ipToBytes(ip);
46095
+ if (!bytes) return null;
46096
+ if (bytes.length === 4) return `${[...bytes].reverse().join(".")}.origin.asn.cymru.com`;
46097
+ const nibbles = [];
46098
+ for (const b of bytes) nibbles.push((b >> 4).toString(16), (b & 15).toString(16));
46099
+ return `${nibbles.reverse().join(".")}.origin6.asn.cymru.com`;
46100
+ }
46101
+ function parseCymruOrigin(txt) {
46102
+ const fields = txt.split("|").map((f) => f.trim());
46103
+ const asn = Number(fields[0]?.split(/\s+/)[0]);
46104
+ if (!Number.isInteger(asn) || asn <= 0) return null;
46105
+ return { asn, prefix: fields[1] || void 0, country: /^[A-Z]{2}$/.test(fields[2] ?? "") ? fields[2] : void 0 };
46106
+ }
46107
+ function parseCymruName(txt) {
46108
+ const fields = txt.split("|").map((f) => f.trim());
46109
+ return (fields[4] ?? "").slice(0, 120);
46110
+ }
46111
+ var AsnLookup = class {
46112
+ constructor(resolveTxt = (name) => import_node_dns.promises.resolveTxt(name), ttlMs = 24 * 36e5, now = Date.now) {
46113
+ this.resolveTxt = resolveTxt;
46114
+ this.ttlMs = ttlMs;
46115
+ this.now = now;
46116
+ }
46117
+ resolveTxt;
46118
+ ttlMs;
46119
+ now;
46120
+ cache = /* @__PURE__ */ new Map();
46121
+ async lookup(ip) {
46122
+ if ((0, import_node_net14.isIP)(ip) === 0) return null;
46123
+ const hit = this.cache.get(ip);
46124
+ if (hit && this.now() - hit.at < this.ttlMs) return hit.info;
46125
+ let info2 = null;
46126
+ try {
46127
+ const origin = cymruOriginName(ip);
46128
+ if (origin) {
46129
+ const rec = await withTimeout(this.resolveTxt(origin), 5e3);
46130
+ const parsed = parseCymruOrigin(rec.map((r) => r.join("")).find(Boolean) ?? "");
46131
+ if (parsed) {
46132
+ let name = "";
46133
+ try {
46134
+ const names = await withTimeout(this.resolveTxt(`AS${parsed.asn}.asn.cymru.com`), 5e3);
46135
+ name = parseCymruName(names.map((r) => r.join("")).find(Boolean) ?? "");
46136
+ } catch {
46137
+ }
46138
+ info2 = { asn: parsed.asn, name, country: parsed.country, prefix: parsed.prefix };
46139
+ }
46140
+ }
46141
+ } catch {
46142
+ info2 = null;
46143
+ }
46144
+ if (this.cache.size > 5e3) this.cache.clear();
46145
+ this.cache.set(ip, { at: this.now(), info: info2 });
46146
+ return info2;
46147
+ }
46148
+ };
46149
+ function withTimeout(p, ms) {
46150
+ return new Promise((resolve8, reject) => {
46151
+ const t = setTimeout(() => reject(new Error("timeout")), ms);
46152
+ p.then((v) => {
46153
+ clearTimeout(t);
46154
+ resolve8(v);
46155
+ }, (e) => {
46156
+ clearTimeout(t);
46157
+ reject(e);
46158
+ });
46159
+ });
46160
+ }
46161
+ function describeNetwork(info2, kind) {
46162
+ if (kind === "tor") return info2 ? `Tor exit, AS${info2.asn} ${info2.name}`.trim() : "Tor exit";
46163
+ if (!info2) return `unknown network (${kind})`;
46164
+ return `AS${info2.asn}${info2.name ? ` ${info2.name}` : ""} (${kind === "unknown" ? "ISP or unclassified" : kind})`;
46165
+ }
46166
+
46167
+ // src/daemon/workers/ssh-intrusion.ts
46168
+ var TOR_REALERT_MS = 10 * 6e4;
46169
+ var HOSTING_REALERT_MS = 24 * 36e5;
46170
+ var TOR_REMEDIATION = {
46171
+ action: "block",
46172
+ description: "Ban the Tor exit at once, for max_ban, even in dry_run and even after a successful login",
46173
+ enforce_in_dry_run: true,
46174
+ ban_on_login: true,
46175
+ override_operator_protection: true,
46176
+ max_ban: true
46177
+ };
46178
+ function parseKeyLoginsByFingerprint(text) {
46179
+ const out = /* @__PURE__ */ new Map();
46180
+ for (const line2 of text.split("\n")) {
46181
+ const m = /^(\d+(?:\.\d+)?)\s.*Accepted publickey for \S+ from (\S+) port \d+ \S+?:\s+\S+\s+(SHA256:[A-Za-z0-9+/=]+)/.exec(line2);
46182
+ if (!m) continue;
46183
+ const at = Math.round(Number(m[1]) * 1e3);
46184
+ const ips = out.get(m[3]) ?? /* @__PURE__ */ new Map();
46185
+ if (at > (ips.get(m[2]) ?? 0)) ips.set(m[2], at);
46186
+ out.set(m[3], ips);
46187
+ }
46188
+ return out;
46189
+ }
46190
+ function readJson2(path2) {
46191
+ try {
46192
+ return JSON.parse((0, import_node_fs40.readFileSync)(path2, "utf-8"));
46193
+ } catch {
46194
+ return null;
46195
+ }
46196
+ }
46197
+ function writeJson2(path2, value) {
46198
+ (0, import_node_fs40.mkdirSync)((0, import_node_path31.dirname)(path2), { recursive: true });
46199
+ (0, import_node_fs40.writeFileSync)(`${path2}.tmp`, JSON.stringify(value));
46200
+ (0, import_node_fs40.renameSync)(`${path2}.tmp`, path2);
46201
+ }
46202
+ var fsIO2 = {
46203
+ readFile: (p) => {
46204
+ try {
46205
+ return (0, import_node_fs40.readFileSync)(p, "utf-8");
46206
+ } catch {
46207
+ return null;
46208
+ }
46209
+ },
46210
+ readDir: (p) => {
46211
+ try {
46212
+ return (0, import_node_fs40.readdirSync)(p);
46213
+ } catch {
46214
+ return null;
46215
+ }
46216
+ },
46217
+ exists: (p) => (0, import_node_fs40.existsSync)(p)
46218
+ };
46219
+ function defaultRun4(cmd, args) {
46220
+ const res = (0, import_node_child_process13.spawnSync)(cmd, args, { encoding: "utf-8", timeout: 6e4, maxBuffer: 64 * 1024 * 1024, stdio: ["ignore", "pipe", "pipe"] });
46221
+ return res.status === 0 ? res.stdout : null;
46222
+ }
46223
+ var SshIntrusionWatch = class {
46224
+ constructor(opts) {
46225
+ this.opts = opts;
46226
+ this.now = opts.now ?? Date.now;
46227
+ this.asn = opts.asn ?? new AsnLookup();
46228
+ this.io = opts.io ?? fsIO2;
46229
+ this.run = opts.run ?? defaultRun4;
46230
+ }
46231
+ opts;
46232
+ now;
46233
+ asn;
46234
+ io;
46235
+ run;
46236
+ torAlerted = /* @__PURE__ */ new Map();
46237
+ hostingAlerted = /* @__PURE__ */ new Map();
46238
+ history = {};
46239
+ keyComments = { at: 0, byFp: /* @__PURE__ */ new Map() };
46240
+ baselineReady = false;
46241
+ onLine = (line2) => {
46242
+ this.checkTorLine(line2);
46243
+ };
46244
+ onEvent = (event) => {
46245
+ void this.checkKeyLogin(event);
46246
+ };
46247
+ start() {
46248
+ this.opts.tor.start();
46249
+ this.opts.manager.setTorExitCheck((ip) => this.opts.tor.has(ip));
46250
+ this.opts.bus.on("sshd", this.onLine);
46251
+ if (this.opts.keyLoginWatch !== false) {
46252
+ this.opts.bus.on("event", this.onEvent);
46253
+ this.loadHistory();
46254
+ }
46255
+ this.opts.log(`[ssh-intrusion] Tor SSH ban ${this.opts.manager.blockTorSsh ? "ON (enforced even in dry_run)" : "OFF (alert only)"}; key-login watch ${this.opts.keyLoginWatch === false ? "off" : "on"}`);
46256
+ }
46257
+ stop() {
46258
+ this.opts.tor.stop();
46259
+ this.opts.bus.off("sshd", this.onLine);
46260
+ this.opts.bus.off("event", this.onEvent);
46261
+ }
46262
+ emit(event) {
46263
+ try {
46264
+ insertEvent(event);
46265
+ } catch {
46266
+ }
46267
+ this.opts.bus.publish(event);
46268
+ }
46269
+ /** One sshd line: a Tor exit anywhere in it is an intrusion attempt. */
46270
+ checkTorLine(line2) {
46271
+ const ip = line2.ip;
46272
+ if (!this.opts.tor.has(ip)) return false;
46273
+ if (isProtected(ip, DEFAULT_PROTECTED) || this.opts.manager.isFleetAddress(ip)) return false;
46274
+ const at = this.now();
46275
+ const last = this.torAlerted.get(ip) ?? 0;
46276
+ const accepted = /Accepted \S+ for /.test(line2.message);
46277
+ if (!accepted && at - last < TOR_REALERT_MS) return false;
46278
+ this.torAlerted.set(ip, at);
46279
+ if (this.torAlerted.size > 1e4) this.torAlerted.clear();
46280
+ const ban = this.opts.manager.blockTorSsh;
46281
+ const user = /for (?:invalid user )?(\S+) from/.exec(line2.message)?.[1];
46282
+ const what = accepted ? `LOGGED IN${user ? ` as ${user}` : ""}` : "connection attempt";
46283
+ this.emit({
46284
+ timestamp: line2.timestamp,
46285
+ module: "ssh-intrusion",
46286
+ category: "auth",
46287
+ severity: accepted || ban ? "critical" : "high",
46288
+ message: `SSH from Tor exit ${ip} (${what})${ban ? ": banned" : ""}`,
46289
+ source_ip: ip,
46290
+ details: {
46291
+ rule_id: "ssh-from-tor",
46292
+ description: "Nobody we operate for uses SSH through Tor. A Tor login means a stolen key or password.",
46293
+ tor_exit: true,
46294
+ accepted,
46295
+ ...user ? { ssh_user: user } : {},
46296
+ ...ban ? { remediation: TOR_REMEDIATION } : {},
46297
+ evidence: { at: line2.timestamp.toISOString(), module: "ssh-guard", message: line2.raw.slice(0, 500) }
46298
+ }
46299
+ });
46300
+ return true;
46301
+ }
46302
+ loadHistory() {
46303
+ const saved = readJson2(this.opts.historyPath);
46304
+ if (saved) {
46305
+ this.history = saved;
46306
+ this.baselineReady = true;
46307
+ return;
46308
+ }
46309
+ const out = this.run("journalctl", ["_COMM=sshd", "_COMM=sshd-session", "--since=-30d", "-o", "short-unix", "--no-pager", "--grep", "Accepted publickey"]);
46310
+ const iso = (ms) => new Date(ms).toISOString();
46311
+ let pairs = 0;
46312
+ for (const [fp, ips] of parseKeyLoginsByFingerprint(out ?? "")) {
46313
+ for (const [ip, at] of ips) {
46314
+ if (this.opts.tor.has(ip)) continue;
46315
+ (this.history[fp] ??= {})[ip] = { first: iso(at), last: iso(at), count: 1 };
46316
+ pairs++;
46317
+ }
46318
+ }
46319
+ this.save();
46320
+ this.baselineReady = true;
46321
+ this.opts.log(`[ssh-intrusion] key-login baseline from the last 30 days: ${Object.keys(this.history).length} key(s), ${pairs} key/address pair(s)`);
46322
+ }
46323
+ save() {
46324
+ try {
46325
+ writeJson2(this.opts.historyPath, this.history);
46326
+ } catch (err) {
46327
+ this.opts.log(`[ssh-intrusion] could not save key-login history: ${err.message}`);
46328
+ }
46329
+ }
46330
+ /** Which account a key is authorized for, and its comment (cached 5 minutes). */
46331
+ keyInfo(fp) {
46332
+ if (this.now() - this.keyComments.at > 3e5) {
46333
+ const snap2 = takeSnapshot(this.io);
46334
+ const byFp = /* @__PURE__ */ new Map();
46335
+ for (const [user, keys] of Object.entries(snap2.keys)) {
46336
+ for (const [f, k] of Object.entries(keys)) if (!byFp.has(f)) byFp.set(f, { user, comment: k.comment });
46337
+ }
46338
+ this.keyComments = { at: this.now(), byFp };
46339
+ }
46340
+ return this.keyComments.byFp.get(fp) ?? null;
46341
+ }
46342
+ async checkKeyLogin(event) {
46343
+ if (event.module !== "ssh-guard" || !this.baselineReady) return null;
46344
+ const fp = event.details?.fingerprint;
46345
+ const ip = event.source_ip;
46346
+ if (typeof fp !== "string" || !ip || isProtected(ip, DEFAULT_PROTECTED)) return null;
46347
+ const seen = this.history[fp] ?? {};
46348
+ const isNew = !seen[ip];
46349
+ const nowIso = new Date(this.now()).toISOString();
46350
+ seen[ip] = { first: seen[ip]?.first ?? nowIso, last: nowIso, count: (seen[ip]?.count ?? 0) + 1 };
46351
+ this.history[fp] = seen;
46352
+ this.save();
46353
+ const tor = this.opts.tor.has(ip);
46354
+ const fleet = this.opts.manager.isFleetAddress(ip);
46355
+ if (fleet) return null;
46356
+ const key = this.keyInfo(fp);
46357
+ const automation = key ? isAutomationKeyComment(key.comment) : false;
46358
+ let info2 = null;
46359
+ try {
46360
+ info2 = await this.asn.lookup(ip);
46361
+ } catch {
46362
+ info2 = null;
46363
+ }
46364
+ const kind = tor ? "tor" : classifyAsn(info2);
46365
+ const network = describeNetwork(info2, kind);
46366
+ const user = typeof event.details?.ssh_user === "string" ? event.details.ssh_user : /accepted for (\S+)/i.exec(event.message)?.[1] ?? "unknown";
46367
+ const keyLabel = `${fp}${key?.comment ? ` (${key.comment})` : ""}`;
46368
+ const known = Object.keys(seen).filter((a) => a !== ip).length;
46369
+ const anonymous = kind === "hosting" || kind === "vpn" || kind === "tor";
46370
+ const hostingHit = !automation && anonymous;
46371
+ const pairKey = `${fp}|${ip}`;
46372
+ const hostingDue = hostingHit && this.now() - (this.hostingAlerted.get(pairKey) ?? 0) >= HOSTING_REALERT_MS;
46373
+ if (!isNew && !hostingDue) return null;
46374
+ if (tor && this.opts.manager.blockTorSsh) return null;
46375
+ let ruleId;
46376
+ let severity;
46377
+ let message;
46378
+ if (hostingHit) {
46379
+ this.hostingAlerted.set(pairKey, this.now());
46380
+ ruleId = "ssh-human-key-hosting-login";
46381
+ severity = "high";
46382
+ message = `SSH login as ${user} with a person's key from a ${kind === "vpn" ? "VPN/anonymizer" : kind === "tor" ? "Tor" : "hosting/cloud"} network: ${ip}, ${network}${isNew ? ", first time for this key" : ""}`;
46383
+ } else if (automation && kind === "ci") {
46384
+ ruleId = "ssh-key-new-ip";
46385
+ severity = "info";
46386
+ message = `SSH deploy key logged in as ${user} from a new CI address ${ip} (${network}), expected`;
46387
+ } else {
46388
+ ruleId = "ssh-key-new-ip";
46389
+ severity = "high";
46390
+ message = `SSH key logged in as ${user} from an address it never used: ${ip}, ${network}${known ? `; ${known} address(es) known for this key` : ""}`;
46391
+ }
46392
+ const out = {
46393
+ timestamp: event.timestamp,
46394
+ module: "ssh-intrusion",
46395
+ category: "auth",
46396
+ severity,
46397
+ message,
46398
+ details: {
46399
+ rule_id: ruleId,
46400
+ account: user,
46401
+ login_ip: ip,
46402
+ fingerprint: fp,
46403
+ key_comment: key?.comment ?? null,
46404
+ key_kind: automation ? "automation" : "person",
46405
+ network_kind: kind,
46406
+ ...info2 ? { asn: info2.asn, as_name: info2.name, as_country: info2.country } : {},
46407
+ first_time_for_key: isNew,
46408
+ known_addresses_for_key: known,
46409
+ evidence: { at: event.timestamp.toISOString(), module: "ssh-guard", message: `Accepted publickey for ${user} from ${ip} ${fp}` }
46410
+ }
46411
+ };
46412
+ this.emit(out);
46413
+ return out;
46414
+ }
46415
+ };
46416
+
46417
+ // src/daemon/workers/lightning-watch.ts
46418
+ var import_node_fs41 = require("fs");
46419
+ var DEFAULT_CLN_LOGS = [
46420
+ "/home/lightning/.lightning/cln.log",
46421
+ "/root/.lightning/cln.log",
46422
+ "/var/lib/clightning/cln.log",
46423
+ "/home/lightning/.lightning/bitcoin/cln.log"
46424
+ ];
46425
+ var CLOSE_RE = /^(\S+)\s+\S+\s+(\S+?)-chan#(\d+): State changed from CHANNELD_NORMAL to (CHANNELD_SHUTTING_DOWN|AWAITING_UNILATERAL|CLOSINGD_SIGEXCHANGE|CLOSINGD_COMPLETE)/;
46426
+ function parseChannelClose(line2) {
46427
+ const m = CLOSE_RE.exec(line2);
46428
+ if (!m) return null;
46429
+ const at = new Date(m[1]);
46430
+ return { at: Number.isNaN(at.getTime()) ? /* @__PURE__ */ new Date() : at, peer: m[2], channel: `${m[2].slice(0, 12)}\u2026#${m[3]}`, to: m[4], line: line2.slice(0, 500) };
46431
+ }
46432
+ var BURST_WINDOW_MS = 10 * 6e4;
46433
+ var BURST_REALERT_MS = 30 * 6e4;
46434
+ var ChannelCloseDetector = class {
46435
+ recent = [];
46436
+ lastBurst = 0;
46437
+ /** Events for one log line (none, a close, or a close and a burst). */
46438
+ feed(line2) {
46439
+ const close = parseChannelClose(line2);
46440
+ if (!close) return [];
46441
+ const t = close.at.getTime();
46442
+ this.recent = this.recent.filter((c) => t - c.at.getTime() < BURST_WINDOW_MS && c.channel !== close.channel);
46443
+ this.recent.push(close);
46444
+ const out = [{
46445
+ timestamp: close.at,
46446
+ severity: "high",
46447
+ message: `Lightning channel ${close.channel} closing (${close.to})`,
46448
+ details: { rule_id: "ln-channel-close", peer: close.peer, to_state: close.to, evidence: { at: close.at.toISOString(), module: "lightning", message: close.line } }
46449
+ }];
46450
+ if (this.recent.length >= 2 && t - this.lastBurst >= BURST_REALERT_MS) {
46451
+ this.lastBurst = t;
46452
+ out.push({
46453
+ timestamp: close.at,
46454
+ severity: "critical",
46455
+ message: `Lightning channel-close burst: ${this.recent.length} channels closing within 10 minutes (${this.recent.map((c) => c.channel).join(", ")}). If nobody here did this, the node is being drained.`,
46456
+ details: { rule_id: "ln-channel-close-burst", channels: this.recent.map((c) => c.channel), evidence: { at: close.at.toISOString(), module: "lightning", message: close.line } }
46457
+ });
46458
+ }
46459
+ return out;
46460
+ }
46461
+ };
46462
+ var LightningWatch = class {
46463
+ constructor(opts) {
46464
+ this.opts = opts;
46465
+ }
46466
+ opts;
46467
+ tails = [];
46468
+ timer = null;
46469
+ detector = new ChannelCloseDetector();
46470
+ start() {
46471
+ if (this.opts.enabled === false) return [];
46472
+ const found = [];
46473
+ for (const path2 of this.opts.paths?.length ? this.opts.paths : DEFAULT_CLN_LOGS) {
46474
+ if (!(0, import_node_fs41.existsSync)(path2)) continue;
46475
+ try {
46476
+ (0, import_node_fs41.accessSync)(path2, import_node_fs41.constants.R_OK);
46477
+ } catch {
46478
+ continue;
46479
+ }
46480
+ this.tails.push(new LogTail(path2));
46481
+ found.push(path2);
46482
+ }
46483
+ if (!found.length) return [];
46484
+ this.timer = setInterval(() => this.poll(), 2e3);
46485
+ this.timer.unref?.();
46486
+ this.opts.log(`[lightning] watching channel closes in ${found.join(", ")}`);
46487
+ return found;
46488
+ }
46489
+ stop() {
46490
+ if (this.timer) clearInterval(this.timer);
46491
+ this.timer = null;
46492
+ this.tails = [];
46493
+ }
46494
+ poll() {
46495
+ for (const tail of this.tails) {
46496
+ tail.poll((line2) => {
46497
+ for (const e of this.detector.feed(line2)) {
46498
+ const event = { module: "lightning", category: "system", ...e };
46499
+ try {
46500
+ insertEvent(event);
46501
+ } catch {
46502
+ }
46503
+ this.opts.bus.publish(event);
46504
+ }
46505
+ });
46506
+ }
46507
+ }
46508
+ };
46509
+
46510
+ // src/core/tor-exits.ts
46511
+ var import_node_fs42 = require("fs");
46512
+ var import_node_path32 = require("path");
46513
+ var import_node_net15 = require("net");
46514
+ var TOR_BULK_EXIT_LIST_URL = "https://check.torproject.org/torbulkexitlist";
46515
+ function parseTorExitList(text) {
46516
+ const out = /* @__PURE__ */ new Set();
46517
+ for (const raw of text.split("\n")) {
46518
+ const line2 = raw.trim();
46519
+ if (!line2 || line2.startsWith("#")) continue;
46520
+ const ip = line2.split(/\s+/)[0];
46521
+ if ((0, import_node_net15.isIP)(ip)) out.add(normalizeIp(ip));
46522
+ }
46523
+ return out;
46524
+ }
46525
+ function normalizeIp(ip) {
46526
+ const bare = ip.trim().replace(/^\[|\]$/g, "").replace(/%.*$/, "");
46527
+ const mapped = /^::ffff:(\d{1,3}(?:\.\d{1,3}){3})$/i.exec(bare);
46528
+ return mapped ? mapped[1] : bare.toLowerCase();
46529
+ }
46530
+ var TorExitList = class _TorExitList {
46531
+ constructor(opts) {
46532
+ this.opts = opts;
46533
+ this.url = opts.url ?? TOR_BULK_EXIT_LIST_URL;
46534
+ this.refreshMs = Math.max(15 * 6e4, opts.refreshMs ?? 36e5);
46535
+ this.fetchImpl = opts.fetchImpl ?? fetch;
46536
+ this.log = opts.log ?? (() => {
46537
+ });
46538
+ this.now = opts.now ?? Date.now;
46539
+ }
46540
+ opts;
46541
+ exits = /* @__PURE__ */ new Set();
46542
+ updatedAt = 0;
46543
+ timer = null;
46544
+ url;
46545
+ refreshMs;
46546
+ fetchImpl;
46547
+ log;
46548
+ now;
46549
+ /** Fewer than this many exits is a broken download, not the Tor network (it has ~1,000+). */
46550
+ static MIN_PLAUSIBLE = 100;
46551
+ /** Load the cache, then refresh now and every `refreshMs`. */
46552
+ start() {
46553
+ this.loadCache();
46554
+ void this.refresh();
46555
+ this.timer = setInterval(() => void this.refresh(), this.refreshMs);
46556
+ this.timer.unref?.();
46557
+ }
46558
+ stop() {
46559
+ if (this.timer) clearInterval(this.timer);
46560
+ this.timer = null;
46561
+ }
46562
+ has(ip) {
46563
+ if (!ip) return false;
46564
+ return this.exits.has(normalizeIp(ip));
46565
+ }
46566
+ get size() {
46567
+ return this.exits.size;
46568
+ }
46569
+ /** When the list in memory was downloaded (ms), 0 if never. */
46570
+ get updated() {
46571
+ return this.updatedAt;
46572
+ }
46573
+ /** Replace the list directly (tests, and the CLI reading the cache). */
46574
+ load(ips, at = this.now()) {
46575
+ this.exits = new Set([...ips].map(normalizeIp));
46576
+ this.updatedAt = at;
46577
+ }
46578
+ loadCache() {
46579
+ try {
46580
+ if (!(0, import_node_fs42.existsSync)(this.opts.cachePath)) return false;
46581
+ const parsed = parseTorExitList((0, import_node_fs42.readFileSync)(this.opts.cachePath, "utf-8"));
46582
+ if (parsed.size === 0) return false;
46583
+ this.load(parsed, (0, import_node_fs42.statSync)(this.opts.cachePath).mtimeMs);
46584
+ this.log(`[tor] loaded ${parsed.size} Tor exit addresses from cache (${new Date(this.updatedAt).toISOString()})`);
46585
+ return true;
46586
+ } catch (err) {
46587
+ this.log(`[tor] could not read the exit list cache: ${err.message}`);
46588
+ return false;
46589
+ }
46590
+ }
46591
+ async refresh() {
46592
+ let text;
46593
+ try {
46594
+ const res = await this.fetchImpl(this.url, {
46595
+ signal: AbortSignal.timeout(3e4),
46596
+ headers: { "User-Agent": "threatcrush-daemon (tor exit list)" }
46597
+ });
46598
+ if (!res.ok) {
46599
+ this.log(`[tor] exit list download failed: HTTP ${res.status}; keeping ${this.exits.size} cached`);
46600
+ return false;
46601
+ }
46602
+ text = await res.text();
46603
+ } catch (err) {
46604
+ this.log(`[tor] exit list download failed: ${err.message}; keeping ${this.exits.size} cached`);
46605
+ return false;
46606
+ }
46607
+ const parsed = parseTorExitList(text);
46608
+ if (parsed.size < _TorExitList.MIN_PLAUSIBLE) {
46609
+ this.log(`[tor] exit list download had only ${parsed.size} addresses; keeping ${this.exits.size} cached`);
46610
+ return false;
46611
+ }
46612
+ const before2 = this.exits.size;
46613
+ this.load(parsed);
46614
+ try {
46615
+ (0, import_node_fs42.mkdirSync)((0, import_node_path32.dirname)(this.opts.cachePath), { recursive: true });
46616
+ (0, import_node_fs42.writeFileSync)(`${this.opts.cachePath}.tmp`, [...parsed].join("\n") + "\n");
46617
+ (0, import_node_fs42.renameSync)(`${this.opts.cachePath}.tmp`, this.opts.cachePath);
46618
+ } catch (err) {
46619
+ this.log(`[tor] could not save the exit list cache: ${err.message}`);
46620
+ }
46621
+ if (before2 !== parsed.size || before2 === 0) this.log(`[tor] loaded ${parsed.size} Tor exit addresses from ${this.url}`);
46622
+ return true;
46623
+ }
46624
+ };
46625
+
45782
46626
  // src/daemon/rules/engine.ts
45783
46627
  var MAX_WINDOW_ENTRIES = 1e3;
45784
46628
  function live(window) {
@@ -45960,8 +46804,8 @@ var RuleEngine = class {
45960
46804
  };
45961
46805
 
45962
46806
  // src/daemon/rules/loader.ts
45963
- var import_node_fs40 = require("fs");
45964
- var import_node_path31 = require("path");
46807
+ var import_node_fs43 = require("fs");
46808
+ var import_node_path33 = require("path");
45965
46809
 
45966
46810
  // src/daemon/rules/default-rules.ts
45967
46811
  var AT_CRS_THRESHOLD = { field: "severity", operator: "regex", value: "^(high|critical)$" };
@@ -46431,11 +47275,11 @@ var RULES_DIR = "/etc/threatcrush/rules.d";
46431
47275
  function loadAllRules(customDir) {
46432
47276
  const rules = [...DEFAULT_RULES];
46433
47277
  const dir = customDir || RULES_DIR;
46434
- if ((0, import_node_fs40.existsSync)(dir)) {
46435
- const files = (0, import_node_fs40.readdirSync)(dir).filter((f) => f.endsWith(".json"));
47278
+ if ((0, import_node_fs43.existsSync)(dir)) {
47279
+ const files = (0, import_node_fs43.readdirSync)(dir).filter((f) => f.endsWith(".json"));
46436
47280
  for (const file of files) {
46437
47281
  try {
46438
- const raw = (0, import_node_fs40.readFileSync)((0, import_node_path31.join)(dir, file), "utf-8");
47282
+ const raw = (0, import_node_fs43.readFileSync)((0, import_node_path33.join)(dir, file), "utf-8");
46439
47283
  const parsed = JSON.parse(raw);
46440
47284
  const customRules = Array.isArray(parsed) ? parsed : [parsed];
46441
47285
  for (const rule of customRules) {
@@ -46466,24 +47310,24 @@ function loadAllRules(customDir) {
46466
47310
  }
46467
47311
 
46468
47312
  // src/daemon/firewall/adapters.ts
46469
- var import_node_child_process13 = require("child_process");
46470
- var import_node_fs41 = require("fs");
46471
- var import_node_path32 = require("path");
46472
- var import_node_net13 = require("net");
47313
+ var import_node_child_process14 = require("child_process");
47314
+ var import_node_fs44 = require("fs");
47315
+ var import_node_path34 = require("path");
47316
+ var import_node_net16 = require("net");
46473
47317
  function assertValidFirewallIp(ip) {
46474
- if ((0, import_node_net13.isIP)(ip) !== 4) {
47318
+ if ((0, import_node_net16.isIP)(ip) !== 4) {
46475
47319
  throw new Error(`Invalid IPv4 address: ${ip}`);
46476
47320
  }
46477
47321
  }
46478
47322
  function assertBannableIp(ip) {
46479
- if ((0, import_node_net13.isIP)(ip) === 0) {
47323
+ if ((0, import_node_net16.isIP)(ip) === 0) {
46480
47324
  throw new Error(`Invalid IP address: ${ip}`);
46481
47325
  }
46482
47326
  }
46483
47327
  function writeIfAbsent(path2, contents) {
46484
- (0, import_node_fs41.mkdirSync)((0, import_node_path32.dirname)(path2), { recursive: true });
47328
+ (0, import_node_fs44.mkdirSync)((0, import_node_path34.dirname)(path2), { recursive: true });
46485
47329
  try {
46486
- (0, import_node_fs41.writeFileSync)(path2, contents, { flag: "wx" });
47330
+ (0, import_node_fs44.writeFileSync)(path2, contents, { flag: "wx" });
46487
47331
  } catch (err) {
46488
47332
  if (err.code !== "EEXIST") throw err;
46489
47333
  }
@@ -46502,11 +47346,11 @@ var Fail2banAdapter = class {
46502
47346
  enforces = true;
46503
47347
  jailReady = false;
46504
47348
  isAvailable() {
46505
- const result = (0, import_node_child_process13.spawnSync)("fail2ban-client", ["ping"], { stdio: "pipe" });
47349
+ const result = (0, import_node_child_process14.spawnSync)("fail2ban-client", ["ping"], { stdio: "pipe" });
46506
47350
  return result.status === 0;
46507
47351
  }
46508
47352
  client(args) {
46509
- return (0, import_node_child_process13.execFileSync)("fail2ban-client", args, {
47353
+ return (0, import_node_child_process14.execFileSync)("fail2ban-client", args, {
46510
47354
  encoding: "utf-8",
46511
47355
  stdio: ["ignore", "pipe", "pipe"]
46512
47356
  });
@@ -46582,7 +47426,7 @@ var Fail2banAdapter = class {
46582
47426
  const status = this.client(["status", this.jail]);
46583
47427
  const line2 = status.split("\n").find((l) => /Banned IP list:/i.test(l));
46584
47428
  if (!line2) return [];
46585
- return line2.split(":").slice(1).join(":").trim().split(/\s+/).filter((s) => (0, import_node_net13.isIP)(s) !== 0);
47429
+ return line2.split(":").slice(1).join(":").trim().split(/\s+/).filter((s) => (0, import_node_net16.isIP)(s) !== 0);
46586
47430
  } catch {
46587
47431
  return [];
46588
47432
  }
@@ -46592,45 +47436,45 @@ var Fail2banAdapter = class {
46592
47436
  function parseBannedList(output) {
46593
47437
  const found = [];
46594
47438
  for (const match of output.matchAll(/['"]([^'"]+)['"]/g)) {
46595
- if ((0, import_node_net13.isIP)(match[1]) !== 0) found.push(match[1]);
47439
+ if ((0, import_node_net16.isIP)(match[1]) !== 0) found.push(match[1]);
46596
47440
  }
46597
47441
  if (found.length > 0) return found;
46598
- return output.replace(/[[\],]/g, " ").split(/\s+/).filter((s) => (0, import_node_net13.isIP)(s) !== 0);
47442
+ return output.replace(/[[\],]/g, " ").split(/\s+/).filter((s) => (0, import_node_net16.isIP)(s) !== 0);
46599
47443
  }
46600
47444
  var NftablesAdapter = class {
46601
47445
  name = "nftables";
46602
47446
  table = "threatcrush";
46603
47447
  set = "blocklist";
46604
47448
  isAvailable() {
46605
- const result = (0, import_node_child_process13.spawnSync)("nft", ["--version"], { stdio: "pipe" });
47449
+ const result = (0, import_node_child_process14.spawnSync)("nft", ["--version"], { stdio: "pipe" });
46606
47450
  return result.status === 0;
46607
47451
  }
46608
47452
  ensureSetup() {
46609
47453
  try {
46610
- (0, import_node_child_process13.execSync)(`nft list table inet ${this.table} 2>/dev/null`, { stdio: "pipe" });
47454
+ (0, import_node_child_process14.execSync)(`nft list table inet ${this.table} 2>/dev/null`, { stdio: "pipe" });
46611
47455
  } catch {
46612
- (0, import_node_child_process13.execSync)(`nft add table inet ${this.table}`);
46613
- (0, import_node_child_process13.execSync)(`nft add set inet ${this.table} ${this.set} '{ type ipv4_addr; flags timeout; }'`);
46614
- (0, import_node_child_process13.execSync)(`nft add chain inet ${this.table} input '{ type filter hook input priority -1; policy accept; }'`);
46615
- (0, import_node_child_process13.execSync)(`nft add rule inet ${this.table} input ip saddr @${this.set} drop`);
47456
+ (0, import_node_child_process14.execSync)(`nft add table inet ${this.table}`);
47457
+ (0, import_node_child_process14.execSync)(`nft add set inet ${this.table} ${this.set} '{ type ipv4_addr; flags timeout; }'`);
47458
+ (0, import_node_child_process14.execSync)(`nft add chain inet ${this.table} input '{ type filter hook input priority -1; policy accept; }'`);
47459
+ (0, import_node_child_process14.execSync)(`nft add rule inet ${this.table} input ip saddr @${this.set} drop`);
46616
47460
  }
46617
47461
  }
46618
47462
  async block(ip) {
46619
47463
  assertValidFirewallIp(ip);
46620
47464
  this.ensureSetup();
46621
- (0, import_node_child_process13.execSync)(`nft add element inet ${this.table} ${this.set} '{ ${ip} }'`);
47465
+ (0, import_node_child_process14.execSync)(`nft add element inet ${this.table} ${this.set} '{ ${ip} }'`);
46622
47466
  }
46623
47467
  async unblock(ip) {
46624
47468
  assertValidFirewallIp(ip);
46625
47469
  try {
46626
- (0, import_node_child_process13.execSync)(`nft delete element inet ${this.table} ${this.set} '{ ${ip} }'`);
47470
+ (0, import_node_child_process14.execSync)(`nft delete element inet ${this.table} ${this.set} '{ ${ip} }'`);
46627
47471
  } catch {
46628
47472
  }
46629
47473
  }
46630
47474
  async isBlocked(ip) {
46631
47475
  assertValidFirewallIp(ip);
46632
47476
  try {
46633
- const output = (0, import_node_child_process13.execSync)(`nft list set inet ${this.table} ${this.set}`, { encoding: "utf-8" });
47477
+ const output = (0, import_node_child_process14.execSync)(`nft list set inet ${this.table} ${this.set}`, { encoding: "utf-8" });
46634
47478
  return output.includes(ip);
46635
47479
  } catch {
46636
47480
  return false;
@@ -46638,7 +47482,7 @@ var NftablesAdapter = class {
46638
47482
  }
46639
47483
  async listBlocked() {
46640
47484
  try {
46641
- const output = (0, import_node_child_process13.execSync)(`nft list set inet ${this.table} ${this.set}`, { encoding: "utf-8" });
47485
+ const output = (0, import_node_child_process14.execSync)(`nft list set inet ${this.table} ${this.set}`, { encoding: "utf-8" });
46642
47486
  const match = output.match(/elements\s*=\s*\{([^}]*)\}/);
46643
47487
  if (!match) return [];
46644
47488
  return match[1].split(",").map((s) => s.trim().split(/\s/)[0]).filter(Boolean);
@@ -46651,34 +47495,34 @@ var IptablesAdapter = class {
46651
47495
  name = "iptables";
46652
47496
  chain = "THREATCRUSH";
46653
47497
  isAvailable() {
46654
- const result = (0, import_node_child_process13.spawnSync)("iptables", ["--version"], { stdio: "pipe" });
47498
+ const result = (0, import_node_child_process14.spawnSync)("iptables", ["--version"], { stdio: "pipe" });
46655
47499
  return result.status === 0;
46656
47500
  }
46657
47501
  ensureChain() {
46658
47502
  try {
46659
- (0, import_node_child_process13.execSync)(`iptables -n -L ${this.chain} 2>/dev/null`, { stdio: "pipe" });
47503
+ (0, import_node_child_process14.execSync)(`iptables -n -L ${this.chain} 2>/dev/null`, { stdio: "pipe" });
46660
47504
  } catch {
46661
- (0, import_node_child_process13.execSync)(`iptables -N ${this.chain}`);
46662
- (0, import_node_child_process13.execSync)(`iptables -I INPUT 1 -j ${this.chain}`);
47505
+ (0, import_node_child_process14.execSync)(`iptables -N ${this.chain}`);
47506
+ (0, import_node_child_process14.execSync)(`iptables -I INPUT 1 -j ${this.chain}`);
46663
47507
  }
46664
47508
  }
46665
47509
  async block(ip) {
46666
47510
  assertValidFirewallIp(ip);
46667
47511
  this.ensureChain();
46668
47512
  if (await this.isBlocked(ip)) return;
46669
- (0, import_node_child_process13.execSync)(`iptables -A ${this.chain} -s ${ip} -j DROP`);
47513
+ (0, import_node_child_process14.execSync)(`iptables -A ${this.chain} -s ${ip} -j DROP`);
46670
47514
  }
46671
47515
  async unblock(ip) {
46672
47516
  assertValidFirewallIp(ip);
46673
47517
  try {
46674
- (0, import_node_child_process13.execSync)(`iptables -D ${this.chain} -s ${ip} -j DROP`);
47518
+ (0, import_node_child_process14.execSync)(`iptables -D ${this.chain} -s ${ip} -j DROP`);
46675
47519
  } catch {
46676
47520
  }
46677
47521
  }
46678
47522
  async isBlocked(ip) {
46679
47523
  assertValidFirewallIp(ip);
46680
47524
  try {
46681
- const output = (0, import_node_child_process13.execSync)(`iptables -n -L ${this.chain}`, { encoding: "utf-8" });
47525
+ const output = (0, import_node_child_process14.execSync)(`iptables -n -L ${this.chain}`, { encoding: "utf-8" });
46682
47526
  return output.includes(ip);
46683
47527
  } catch {
46684
47528
  return false;
@@ -46686,7 +47530,7 @@ var IptablesAdapter = class {
46686
47530
  }
46687
47531
  async listBlocked() {
46688
47532
  try {
46689
- const output = (0, import_node_child_process13.execSync)(`iptables -n -L ${this.chain}`, { encoding: "utf-8" });
47533
+ const output = (0, import_node_child_process14.execSync)(`iptables -n -L ${this.chain}`, { encoding: "utf-8" });
46690
47534
  const ips = [];
46691
47535
  for (const line2 of output.split("\n")) {
46692
47536
  const match = line2.match(/DROP\s+all\s+--\s+(\d+\.\d+\.\d+\.\d+)/);
@@ -46742,22 +47586,22 @@ function detectFirewallAdapter(backend = "auto") {
46742
47586
  }
46743
47587
 
46744
47588
  // src/daemon/firewall/remediation.ts
46745
- var import_node_fs42 = require("fs");
46746
- var import_node_child_process14 = require("child_process");
46747
- var import_node_net14 = require("net");
47589
+ var import_node_fs45 = require("fs");
47590
+ var import_node_child_process15 = require("child_process");
47591
+ var import_node_net17 = require("net");
46748
47592
  init_paths();
46749
47593
  init_backoff();
46750
47594
 
46751
47595
  // src/daemon/firewall/crawlers.ts
46752
- var import_node_dns = require("dns");
47596
+ var import_node_dns2 = require("dns");
46753
47597
  var CRAWLER_DOMAINS = ["googlebot.com", "google.com", "search.msn.com", "applebot.apple.com"];
46754
47598
  var systemResolver = {
46755
- reverse: (ip) => import_node_dns.promises.reverse(ip),
46756
- lookup: async (host) => (await import_node_dns.promises.lookup(host, { all: true })).map((a) => a.address)
47599
+ reverse: (ip) => import_node_dns2.promises.reverse(ip),
47600
+ lookup: async (host) => (await import_node_dns2.promises.lookup(host, { all: true })).map((a) => a.address)
46757
47601
  };
46758
47602
  var TIMEOUT_MS2 = 2e3;
46759
47603
  var CACHE_MS = 6 * 36e5;
46760
- function withTimeout(p) {
47604
+ function withTimeout2(p) {
46761
47605
  return Promise.race([
46762
47606
  p,
46763
47607
  new Promise((_, reject) => setTimeout(() => reject(new Error("dns timeout")), TIMEOUT_MS2).unref())
@@ -46774,9 +47618,9 @@ function crawlerVerifier(resolver = systemResolver) {
46774
47618
  if (hit && hit.until > Date.now()) return hit.host;
46775
47619
  let host = null;
46776
47620
  try {
46777
- const names = await withTimeout(resolver.reverse(ip));
47621
+ const names = await withTimeout2(resolver.reverse(ip));
46778
47622
  for (const name of names.filter(inCrawlerDomain)) {
46779
- const addrs = await withTimeout(resolver.lookup(name));
47623
+ const addrs = await withTimeout2(resolver.lookup(name));
46780
47624
  if (addrs.includes(ip)) {
46781
47625
  host = name.replace(/\.$/, "");
46782
47626
  break;
@@ -46804,7 +47648,8 @@ var DEFAULT_CONFIG2 = {
46804
47648
  protect_current_ssh_client: true,
46805
47649
  protect_recent_operators: true,
46806
47650
  operator_memory_seconds: 30 * 86400,
46807
- spare_verified_crawlers: true
47651
+ spare_verified_crawlers: true,
47652
+ block_tor_ssh: true
46808
47653
  };
46809
47654
  var defaultDiscovery = {
46810
47655
  sshPeers: () => [currentSshClient(), ...establishedSshPeers()].filter((ip) => Boolean(ip)),
@@ -46813,19 +47658,19 @@ var defaultDiscovery = {
46813
47658
  const snapshot = takeSnapshot({
46814
47659
  readFile: (p) => {
46815
47660
  try {
46816
- return (0, import_node_fs42.readFileSync)(p, "utf-8");
47661
+ return (0, import_node_fs45.readFileSync)(p, "utf-8");
46817
47662
  } catch {
46818
47663
  return null;
46819
47664
  }
46820
47665
  },
46821
47666
  readDir: (p) => {
46822
47667
  try {
46823
- return (0, import_node_fs42.readdirSync)(p);
47668
+ return (0, import_node_fs45.readdirSync)(p);
46824
47669
  } catch {
46825
47670
  return null;
46826
47671
  }
46827
47672
  },
46828
- exists: (p) => (0, import_node_fs42.existsSync)(p)
47673
+ exists: (p) => (0, import_node_fs45.existsSync)(p)
46829
47674
  });
46830
47675
  const out = /* @__PURE__ */ new Set();
46831
47676
  for (const keys of Object.values(snapshot.keys)) {
@@ -46834,7 +47679,7 @@ var defaultDiscovery = {
46834
47679
  return out;
46835
47680
  },
46836
47681
  keyLoginJournal: (sinceSeconds) => new Promise((resolve8) => {
46837
- (0, import_node_child_process14.execFile)(
47682
+ (0, import_node_child_process15.execFile)(
46838
47683
  "journalctl",
46839
47684
  ["_COMM=sshd", "_COMM=sshd-session", `--since=-${Math.ceil(sinceSeconds / 86400)}d`, "-o", "short-unix", "--no-pager", "--grep", "Accepted publickey"],
46840
47685
  { maxBuffer: 32 * 1024 * 1024, timeout: 6e4 },
@@ -46842,7 +47687,7 @@ var defaultDiscovery = {
46842
47687
  );
46843
47688
  })
46844
47689
  };
46845
- var SEVERITY_RANK7 = {
47690
+ var SEVERITY_RANK8 = {
46846
47691
  info: 0,
46847
47692
  low: 1,
46848
47693
  medium: 2,
@@ -46899,16 +47744,56 @@ var RemediationManager = class {
46899
47744
  operators = {};
46900
47745
  expiryTimer = null;
46901
47746
  operatorTimer = null;
47747
+ /** True for a Tor exit address; such an address is never an operator. */
47748
+ isTorExit = () => false;
46902
47749
  /** Remembered operator addresses and when each was last seen. */
46903
47750
  getOperators() {
46904
47751
  return { ...this.operators };
46905
47752
  }
47753
+ /**
47754
+ * Teach the manager which addresses are Tor exits. They are never
47755
+ * remembered as operators and never protected as a live session: on dev2
47756
+ * the 2026-10-27 intruder logged in with a stolen key from Tor, which made
47757
+ * the exit an "operator" that nothing could ban for 30 days.
47758
+ */
47759
+ setTorExitCheck(check2) {
47760
+ this.isTorExit = check2;
47761
+ let dropped = 0;
47762
+ this.protectedList = this.protectedList.filter((a) => !(0, import_node_net17.isIP)(a) || !check2(a) || this.pinned.has(a) || this.config.allowlist.includes(a));
47763
+ for (const ip of Object.keys(this.operators)) {
47764
+ if (!check2(ip)) continue;
47765
+ delete this.operators[ip];
47766
+ this.protectedList = this.protectedList.filter((a) => a !== ip || this.pinned.has(a) || this.config.allowlist.includes(a));
47767
+ dropped++;
47768
+ }
47769
+ if (dropped) {
47770
+ this.logLine(`[firewall] forgot ${dropped} remembered operator address(es) that are Tor exits`);
47771
+ this.saveState();
47772
+ }
47773
+ }
47774
+ /** Tor SSH bans on (setting) — the cloud may change it unless config pinned it. */
47775
+ get blockTorSsh() {
47776
+ return this.config.enabled && this.config.block_tor_ssh;
47777
+ }
47778
+ setBlockTorSsh(on) {
47779
+ this.config.block_tor_ssh = on;
47780
+ }
47781
+ /**
47782
+ * Our own addresses: built-ins, shared infrastructure, gateways, the
47783
+ * operator's `[remediation] protected` and the dashboard's org allowlist
47784
+ * (Known IPs). Not remembered operators or live sessions.
47785
+ */
47786
+ isFleetAddress(ip) {
47787
+ return isProtected(ip, [...this.pinned, ...this.config.allowlist]);
47788
+ }
46906
47789
  /**
46907
47790
  * An address an operator really came from: never ban it, remember it, and
46908
47791
  * lift a ban that is already on it — the operator is the one who needs in.
46909
47792
  */
46910
47793
  noteOperator(ip, at, remember = true) {
46911
47794
  if (Date.now() - at > this.config.operator_memory_seconds * 1e3) return;
47795
+ if (this.isTorExit(ip) && !this.isFleetAddress(ip)) return;
47796
+ if (this.blocklist.some((b) => b.ip === ip && b.strict)) return;
46912
47797
  if (!this.protectedList.includes(ip)) this.protectedList.push(ip);
46913
47798
  if (!remember || !this.config.protect_recent_operators || isProtected(ip, DEFAULT_PROTECTED)) return;
46914
47799
  const known = this.operators[ip] ?? 0;
@@ -46958,17 +47843,21 @@ var RemediationManager = class {
46958
47843
  }
46959
47844
  async handleDetection(event) {
46960
47845
  if (!this.config.enabled) return;
46961
- const eventRank = SEVERITY_RANK7[event.severity] ?? 0;
46962
- const minRank = SEVERITY_RANK7[this.config.min_severity] ?? 3;
47846
+ const eventRank = SEVERITY_RANK8[event.severity] ?? 0;
47847
+ const minRank = SEVERITY_RANK8[this.config.min_severity] ?? 3;
46963
47848
  if (eventRank < minRank) return;
46964
- if (isSuccessfulAuth(event.message)) return;
47849
+ const remediation = event.details?.remediation;
47850
+ if (isSuccessfulAuth(event.message) && remediation?.ban_on_login !== true) return;
46965
47851
  if (event.details?.rule_id) {
46966
- const remediation = event.details?.remediation;
46967
47852
  if (remediation?.action !== "block") return;
46968
47853
  }
46969
47854
  const ip = event.source_ip;
46970
- if (!ip || (0, import_node_net14.isIP)(ip) === 0) return;
46971
- if (this.isAllowlisted(ip)) return;
47855
+ if (!ip || (0, import_node_net17.isIP)(ip) === 0) return;
47856
+ const strict = remediation?.override_operator_protection === true;
47857
+ if (strict ? this.isFleetAddress(ip) : this.isAllowlisted(ip)) {
47858
+ if (strict) this.logLine(`[remediation] not banning ${ip}: it is one of our own addresses (${event.message})`);
47859
+ return;
47860
+ }
46972
47861
  if (this.blocklist.some((b) => b.ip === ip)) return;
46973
47862
  if (this.config.spare_verified_crawlers) {
46974
47863
  const crawler = await this.verifyCrawler(ip);
@@ -46978,7 +47867,13 @@ var RemediationManager = class {
46978
47867
  }
46979
47868
  }
46980
47869
  const ruleId = event.details?.rule_id;
46981
- await this.ban(ip, event.message, { ruleId, source: "auto" });
47870
+ await this.ban(ip, event.message, {
47871
+ ruleId,
47872
+ source: "auto",
47873
+ enforceInDryRun: remediation?.enforce_in_dry_run === true,
47874
+ strict,
47875
+ ...remediation?.max_ban ? { ttlSeconds: this.config.max_ban_seconds } : {}
47876
+ });
46982
47877
  }
46983
47878
  /**
46984
47879
  * Ban `ip`. With no explicit TTL the length comes from the doubling ladder:
@@ -46986,8 +47881,8 @@ var RemediationManager = class {
46986
47881
  * 4th offence and so on, clamped to `max_ban_seconds`.
46987
47882
  */
46988
47883
  async ban(ip, reason, opts = {}) {
46989
- if ((0, import_node_net14.isIP)(ip) === 0) return { ok: false, error: `not an IP address: ${ip}` };
46990
- if (this.isAllowlisted(ip)) {
47884
+ if ((0, import_node_net17.isIP)(ip) === 0) return { ok: false, error: `not an IP address: ${ip}` };
47885
+ if (opts.strict ? this.isFleetAddress(ip) : this.isAllowlisted(ip)) {
46991
47886
  return { ok: false, error: `${ip} is protected and can never be blocked` };
46992
47887
  }
46993
47888
  const now = Date.now();
@@ -46995,7 +47890,8 @@ var RemediationManager = class {
46995
47890
  if (existing && !opts.ttlSeconds) {
46996
47891
  return { ok: false, error: `${ip} is already banned` };
46997
47892
  }
46998
- if (!this.config.dry_run) {
47893
+ const dryRun = this.config.dry_run && !(opts.enforceInDryRun && this.adapter.enforces !== false);
47894
+ if (!dryRun) {
46999
47895
  try {
47000
47896
  await this.adapter.block(ip);
47001
47897
  } catch (err) {
@@ -47028,14 +47924,19 @@ var RemediationManager = class {
47028
47924
  rule_id: opts.ruleId,
47029
47925
  blocked_at: now,
47030
47926
  expires_at: now + ttl * 1e3,
47031
- dry_run: this.config.dry_run,
47927
+ dry_run: dryRun,
47032
47928
  strikes: strike,
47033
- source: opts.source ?? "manual"
47929
+ source: opts.source ?? "manual",
47930
+ ...opts.strict ? { strict: true } : {}
47034
47931
  };
47932
+ if (opts.strict) {
47933
+ delete this.operators[ip];
47934
+ this.protectedList = this.protectedList.filter((a) => a !== ip || this.pinned.has(a) || this.config.allowlist.includes(a));
47935
+ }
47035
47936
  this.blocklist = this.blocklist.filter((b) => b.ip !== ip);
47036
47937
  this.blocklist.push(entry);
47037
47938
  this.saveState();
47038
- const mode = this.config.dry_run ? "[DRY-RUN] " : "";
47939
+ const mode = dryRun ? "[DRY-RUN] " : this.config.dry_run ? "[ENFORCED IN DRY-RUN] " : "";
47039
47940
  const label = `${mode}Banned ${ip} for ${formatDuration(ttl)} (offence #${strike}): ${reason}`;
47040
47941
  this.logLine(`[firewall] ${label}`);
47041
47942
  this.bus.publish({
@@ -47050,7 +47951,7 @@ var RemediationManager = class {
47050
47951
  rule_id: opts.ruleId,
47051
47952
  reason,
47052
47953
  origin: opts.origin,
47053
- dry_run: this.config.dry_run,
47954
+ dry_run: dryRun,
47054
47955
  ttl_seconds: ttl,
47055
47956
  strikes: strike,
47056
47957
  source: entry.source,
@@ -47133,10 +48034,13 @@ var RemediationManager = class {
47133
48034
  * Saying so up front beats a dashboard that looks armed and is not.
47134
48035
  */
47135
48036
  privilegeWarning() {
47136
- if (!this.config.enabled || this.config.dry_run) return void 0;
48037
+ if (!this.config.enabled) return void 0;
47137
48038
  if (this.adapter.enforces === false) return void 0;
47138
48039
  const uid = typeof process.getuid === "function" ? process.getuid() : 0;
47139
48040
  if (uid === 0) return void 0;
48041
+ if (this.config.dry_run) {
48042
+ return this.config.block_tor_ssh ? `daemon runs as uid ${uid}: the Tor SSH ban (enforced even in dry_run) cannot write ${this.adapter.name} rules` : void 0;
48043
+ }
47140
48044
  return `daemon runs as uid ${uid} and cannot write ${this.adapter.name} rules \u2014 bans will fail`;
47141
48045
  }
47142
48046
  addToAllowlist(ip) {
@@ -47165,10 +48069,11 @@ var RemediationManager = class {
47165
48069
  */
47166
48070
  async reconcile() {
47167
48071
  const now = Date.now();
47168
- const lifted = this.blocklist.filter((b) => this.isAllowlisted(b.ip));
48072
+ const guarded = (b) => b.strict ? this.isFleetAddress(b.ip) : this.isAllowlisted(b.ip);
48073
+ const lifted = this.blocklist.filter(guarded);
47169
48074
  for (const entry of lifted) this.logLine(`[firewall] reconcile: lifting ban on protected ${entry.ip}`);
47170
- const live2 = this.blocklist.filter((b) => b.expires_at > now && !this.isAllowlisted(b.ip));
47171
- const stale = this.blocklist.filter((b) => b.expires_at <= now || this.isAllowlisted(b.ip));
48075
+ const live2 = this.blocklist.filter((b) => b.expires_at > now && !guarded(b));
48076
+ const stale = this.blocklist.filter((b) => b.expires_at <= now || guarded(b));
47172
48077
  for (const entry of stale) {
47173
48078
  if (!entry.dry_run) {
47174
48079
  try {
@@ -47195,8 +48100,8 @@ var RemediationManager = class {
47195
48100
  }
47196
48101
  }
47197
48102
  }
47198
- if (this.config.dry_run) return;
47199
48103
  for (const entry of live2) {
48104
+ if (entry.dry_run) continue;
47200
48105
  if (applied?.includes(entry.ip)) continue;
47201
48106
  try {
47202
48107
  await this.adapter.block(entry.ip);
@@ -47253,7 +48158,8 @@ var RemediationManager = class {
47253
48158
  if (saved && typeof saved === "object" && this.config.protect_recent_operators) {
47254
48159
  const cutoff = Date.now() - this.config.operator_memory_seconds * 1e3;
47255
48160
  for (const [ip, at] of Object.entries(saved)) {
47256
- if (typeof at !== "number" || at < cutoff || !(0, import_node_net14.isIP)(ip)) continue;
48161
+ if (typeof at !== "number" || at < cutoff || !(0, import_node_net17.isIP)(ip)) continue;
48162
+ if (this.blocklist.some((b) => b.ip === ip && b.strict)) continue;
47257
48163
  this.operators[ip] = at;
47258
48164
  if (!this.protectedList.includes(ip)) this.protectedList.push(ip);
47259
48165
  }
@@ -47277,7 +48183,7 @@ var RemediationManager = class {
47277
48183
  }
47278
48184
  logLine(line2) {
47279
48185
  try {
47280
- (0, import_node_fs42.appendFileSync)(PATHS.logFile, `${(/* @__PURE__ */ new Date()).toISOString()} ${line2}
48186
+ (0, import_node_fs45.appendFileSync)(PATHS.logFile, `${(/* @__PURE__ */ new Date()).toISOString()} ${line2}
47281
48187
  `);
47282
48188
  } catch {
47283
48189
  }
@@ -47310,6 +48216,7 @@ function remediationSettings(section) {
47310
48216
  }
47311
48217
  const operatorMemory = parseDuration(section.operator_memory);
47312
48218
  if (operatorMemory) settings.operator_memory_seconds = operatorMemory;
48219
+ if (typeof section.block_tor_ssh === "boolean") settings.block_tor_ssh = section.block_tor_ssh;
47313
48220
  if (typeof section.spare_verified_crawlers === "boolean") {
47314
48221
  settings.spare_verified_crawlers = section.spare_verified_crawlers;
47315
48222
  }
@@ -47320,19 +48227,19 @@ function remediationSettings(section) {
47320
48227
  init_backoff();
47321
48228
 
47322
48229
  // src/daemon/watchdog-service.ts
47323
- var import_node_fs43 = require("fs");
47324
- var import_node_path33 = require("path");
48230
+ var import_node_fs46 = require("fs");
48231
+ var import_node_path35 = require("path");
47325
48232
  function defaultShareGid() {
47326
48233
  const isRoot4 = process.platform === "linux" && typeof process.getuid === "function" && process.getuid() === 0;
47327
48234
  if (!isRoot4) return void 0;
47328
48235
  try {
47329
- return (0, import_node_fs43.statSync)("/var/log/auth.log").gid;
48236
+ return (0, import_node_fs46.statSync)("/var/log/auth.log").gid;
47330
48237
  } catch {
47331
48238
  return void 0;
47332
48239
  }
47333
48240
  }
47334
48241
  function startWatchdog(opts) {
47335
- const dir = opts.config?.dir ?? (0, import_node_path33.join)(opts.stateDir, WATCHDOG_DIRNAME);
48242
+ const dir = opts.config?.dir ?? (0, import_node_path35.join)(opts.stateDir, WATCHDOG_DIRNAME);
47336
48243
  const base = { dir, logged: 0, answered: 0, errored: 0 };
47337
48244
  if (opts.config?.enabled === false) {
47338
48245
  opts.log("[watchdog] off ([watchdog] enabled = false)");
@@ -47426,7 +48333,7 @@ async function flushTelemetry(timeoutMs = 2e3) {
47426
48333
  }
47427
48334
 
47428
48335
  // src/core/node-runtime.ts
47429
- var import_node_child_process15 = require("child_process");
48336
+ var import_node_child_process16 = require("child_process");
47430
48337
  var MIN_DAEMON_NODE_MAJOR = 22;
47431
48338
  function nodeMajor(version) {
47432
48339
  const m = String(version ?? "").trim().replace(/^v/, "").match(/^(\d+)\./);
@@ -47440,23 +48347,23 @@ function daemonNodeProblem(version) {
47440
48347
  }
47441
48348
  function versionOfNode(path2) {
47442
48349
  if (path2 === process.execPath) return process.versions.node;
47443
- const res = (0, import_node_child_process15.spawnSync)(path2, ["-p", "process.versions.node"], { encoding: "utf-8", timeout: 5e3 });
48350
+ const res = (0, import_node_child_process16.spawnSync)(path2, ["-p", "process.versions.node"], { encoding: "utf-8", timeout: 5e3 });
47444
48351
  return res.status === 0 ? res.stdout.trim() : null;
47445
48352
  }
47446
48353
 
47447
48354
  // src/daemon/index.ts
47448
48355
  function readVersion2() {
47449
48356
  try {
47450
- const pkg = JSON.parse((0, import_node_fs44.readFileSync)((0, import_node_path34.join)(__dirname, "..", "package.json"), "utf-8"));
48357
+ const pkg = JSON.parse((0, import_node_fs47.readFileSync)((0, import_node_path36.join)(__dirname, "..", "package.json"), "utf-8"));
47451
48358
  return pkg.version || "0.0.0";
47452
48359
  } catch {
47453
48360
  return "0.0.0";
47454
48361
  }
47455
48362
  }
47456
48363
  async function runHardeningChecks() {
47457
- const { stdout } = await (0, import_node_util4.promisify)(import_node_child_process16.execFile)(
48364
+ const { stdout } = await (0, import_node_util4.promisify)(import_node_child_process17.execFile)(
47458
48365
  process.execPath,
47459
- [(0, import_node_path34.join)(__dirname, "index.js"), "harden", "--json", "--no-upload"],
48366
+ [(0, import_node_path36.join)(__dirname, "index.js"), "harden", "--json", "--no-upload"],
47460
48367
  { timeout: 12e4, maxBuffer: 4 * 1024 * 1024 }
47461
48368
  );
47462
48369
  const parsed = JSON.parse(stdout.slice(stdout.indexOf("{")));
@@ -47468,9 +48375,9 @@ async function runHardeningChecks() {
47468
48375
  return patches ? [...findings2, patches] : findings2;
47469
48376
  }
47470
48377
  async function runPatchCheck() {
47471
- const { stdout } = await (0, import_node_util4.promisify)(import_node_child_process16.execFile)(
48378
+ const { stdout } = await (0, import_node_util4.promisify)(import_node_child_process17.execFile)(
47472
48379
  process.execPath,
47473
- [(0, import_node_path34.join)(__dirname, "index.js"), "patches", "--json", "--no-upload"],
48380
+ [(0, import_node_path36.join)(__dirname, "index.js"), "patches", "--json", "--no-upload"],
47474
48381
  { timeout: 3e5, maxBuffer: 16 * 1024 * 1024 }
47475
48382
  );
47476
48383
  const parsed = JSON.parse(stdout.slice(stdout.indexOf("{")));
@@ -47478,7 +48385,7 @@ async function runPatchCheck() {
47478
48385
  }
47479
48386
  function logLine(line2) {
47480
48387
  try {
47481
- (0, import_node_fs44.appendFileSync)(PATHS.logFile, `${(/* @__PURE__ */ new Date()).toISOString()} ${line2}
48388
+ (0, import_node_fs47.appendFileSync)(PATHS.logFile, `${(/* @__PURE__ */ new Date()).toISOString()} ${line2}
47482
48389
  `);
47483
48390
  } catch {
47484
48391
  }
@@ -47503,9 +48410,9 @@ async function runDaemon() {
47503
48410
  logLine(`[daemon] starting threatcrushd v${version} mode=${PATHS.mode}`);
47504
48411
  const restartDaemon = () => {
47505
48412
  if (PATHS.mode === "system") {
47506
- (0, import_node_child_process16.spawn)("systemctl", ["restart", "threatcrushd"], { detached: true, stdio: "ignore" }).unref();
48413
+ (0, import_node_child_process17.spawn)("systemctl", ["restart", "threatcrushd"], { detached: true, stdio: "ignore" }).unref();
47507
48414
  } else {
47508
- (0, import_node_child_process16.spawn)(process.execPath, process.argv.slice(1), { detached: true, stdio: "ignore" }).unref();
48415
+ (0, import_node_child_process17.spawn)(process.execPath, process.argv.slice(1), { detached: true, stdio: "ignore" }).unref();
47509
48416
  setTimeout(() => process.exit(0), 500).unref();
47510
48417
  }
47511
48418
  };
@@ -47520,7 +48427,7 @@ async function runDaemon() {
47520
48427
  } catch (err) {
47521
48428
  logLine(`[daemon] state db unavailable: ${err.message}`);
47522
48429
  }
47523
- const config = loadConfig((0, import_node_fs44.existsSync)(PATHS.configFile) ? PATHS.configFile : void 0);
48430
+ const config = loadConfig((0, import_node_fs47.existsSync)(PATHS.configFile) ? PATHS.configFile : void 0);
47524
48431
  configureAttackDetection(config.detection);
47525
48432
  const retentionSeconds = parseDuration(config.storage?.event_retention) ?? DEFAULT_EVENT_RETENTION_SECONDS;
47526
48433
  const maxEvents = config.storage?.max_events ?? DEFAULT_MAX_EVENTS;
@@ -47584,7 +48491,7 @@ async function runDaemon() {
47584
48491
  const threatFeeds = new ThreatFeeds({
47585
48492
  settings: { ...feedSettings, allow: [...feedSettings.allow, ...remediation.getAllowlist()] },
47586
48493
  enforcing: !remediationStatus.dry_run && firewallAdapter.enforces !== false,
47587
- cachePath: (0, import_node_path34.join)(PATHS.stateDir, "threat-feeds.json"),
48494
+ cachePath: (0, import_node_path36.join)(PATHS.stateDir, "threat-feeds.json"),
47588
48495
  bus,
47589
48496
  log: logLine
47590
48497
  });
@@ -47592,13 +48499,35 @@ async function runDaemon() {
47592
48499
  const privilegeWatch = new PrivilegeWatch({
47593
48500
  settings: privilegeSettings(config.privileged),
47594
48501
  bus,
47595
- snapshotPath: (0, import_node_path34.join)(PATHS.stateDir, "privileges.json"),
47596
- loginsPath: (0, import_node_path34.join)(PATHS.stateDir, "login-countries.json"),
47597
- cursorPath: (0, import_node_path34.join)(PATHS.stateDir, "sudo-cursor.json"),
48502
+ snapshotPath: (0, import_node_path36.join)(PATHS.stateDir, "privileges.json"),
48503
+ loginsPath: (0, import_node_path36.join)(PATHS.stateDir, "login-countries.json"),
48504
+ cursorPath: (0, import_node_path36.join)(PATHS.stateDir, "sudo-cursor.json"),
47598
48505
  log: logLine
47599
48506
  });
47600
48507
  privilegeWatch.start();
47601
- new AlertDispatcher(bus, config);
48508
+ const torExits = new TorExitList({
48509
+ cachePath: (0, import_node_path36.join)(PATHS.stateDir, "tor-exits.txt"),
48510
+ url: config.remediation?.tor_exit_list_url,
48511
+ log: logLine
48512
+ });
48513
+ const sshIntrusion = new SshIntrusionWatch({
48514
+ bus,
48515
+ manager: remediation,
48516
+ tor: torExits,
48517
+ historyPath: (0, import_node_path36.join)(PATHS.stateDir, "key-logins.json"),
48518
+ keyLoginWatch: config.privileged?.key_login_watch !== false,
48519
+ log: logLine
48520
+ });
48521
+ sshIntrusion.start();
48522
+ const lightningWatch = new LightningWatch({
48523
+ bus,
48524
+ enabled: config.lightning?.enabled !== false,
48525
+ paths: Array.isArray(config.lightning?.log_paths) ? config.lightning.log_paths.map(String) : void 0,
48526
+ log: logLine
48527
+ });
48528
+ lightningWatch.start();
48529
+ let cloudSyncRef = null;
48530
+ new AlertDispatcher(bus, config, { cloudHealthy: () => cloudSyncRef?.healthy ?? false, log: logLine });
47602
48531
  const runsWorker = new RunsWorker(bus, {
47603
48532
  enabled: config.cloud?.enabled !== false && config.cloud?.runs === true,
47604
48533
  scanRoots: Array.isArray(config.cloud?.run_scan_paths) ? config.cloud.run_scan_paths.filter((p) => typeof p === "string") : [],
@@ -47620,14 +48549,15 @@ async function runDaemon() {
47620
48549
  cloudSync = new CloudSync({
47621
48550
  bus,
47622
48551
  version,
47623
- hostname: (0, import_node_os13.hostname)(),
48552
+ hostname: (0, import_node_os14.hostname)(),
47624
48553
  minSeverity,
47625
- spoolPath: (0, import_node_path34.join)(PATHS.stateDir, "cloud-spool.jsonl"),
48554
+ spoolPath: (0, import_node_path36.join)(PATHS.stateDir, "cloud-spool.jsonl"),
47626
48555
  log: logLine,
47627
48556
  ruleModules: new Set(ruleEngine.getRules().flatMap((rule) => rule.source_types)),
47628
48557
  runHardening: runHardeningChecks
47629
48558
  });
47630
48559
  cloudSync.start();
48560
+ cloudSyncRef = cloudSync;
47631
48561
  remediationConsumer = new RemediationConsumer(remediation, {
47632
48562
  log: logLine,
47633
48563
  restartDaemon,
@@ -47635,7 +48565,15 @@ async function runDaemon() {
47635
48565
  updateNow: () => autoUpdateRef ? autoUpdateRef.check({ force: true, restartDelayMs: 3e3 }) : Promise.resolve("updater not started")
47636
48566
  });
47637
48567
  remediationConsumer.start();
47638
- allowlistSync = new AllowlistSync(remediation, { log: logLine });
48568
+ const torPinned = typeof config.remediation?.block_tor_ssh === "boolean";
48569
+ allowlistSync = new AllowlistSync(remediation, {
48570
+ log: logLine,
48571
+ onOrgSettings: ({ block_tor_ssh }) => {
48572
+ if (torPinned || typeof block_tor_ssh !== "boolean" || block_tor_ssh === remediation.blockTorSsh) return;
48573
+ remediation.setBlockTorSsh(block_tor_ssh);
48574
+ logLine(`[ssh-intrusion] Tor SSH ban ${block_tor_ssh ? "ON" : "OFF"} (org setting from the dashboard)`);
48575
+ }
48576
+ });
47639
48577
  allowlistSync.start();
47640
48578
  const link = currentLink();
47641
48579
  logLine(link ? `[cloud] reporting as server ${link.serverId} (org ${link.orgId}), detections >= ${minSeverity}` : "[cloud] not linked; run `threatcrush login` and `threatcrush servers link` to report to the dashboard");
@@ -47646,8 +48584,8 @@ async function runDaemon() {
47646
48584
  const autoUpdate = autoUpdateRef = new AutoUpdate({
47647
48585
  version,
47648
48586
  settings: updateSettings(config.update),
47649
- pkgRoot: (0, import_node_path34.join)(__dirname, ".."),
47650
- statePath: (0, import_node_path34.join)(PATHS.stateDir, "auto-update.json"),
48587
+ pkgRoot: (0, import_node_path36.join)(__dirname, ".."),
48588
+ statePath: (0, import_node_path36.join)(PATHS.stateDir, "auto-update.json"),
47651
48589
  bus,
47652
48590
  log: logLine,
47653
48591
  restartDaemon
@@ -47702,6 +48640,14 @@ async function runDaemon() {
47702
48640
  privilegeWatch.stop();
47703
48641
  } catch {
47704
48642
  }
48643
+ try {
48644
+ sshIntrusion.stop();
48645
+ } catch {
48646
+ }
48647
+ try {
48648
+ lightningWatch.stop();
48649
+ } catch {
48650
+ }
47705
48651
  try {
47706
48652
  await ipc.stop();
47707
48653
  } catch {
@@ -47737,7 +48683,7 @@ var SYSTEM_SOCKET = "/var/run/threatcrush/threatcrushd.sock";
47737
48683
  function isRoot2() {
47738
48684
  return typeof process.getuid === "function" && process.getuid() === 0;
47739
48685
  }
47740
- var DAEMON_ENTRY = (0, import_node_path35.join)(__dirname, "daemon.js");
48686
+ var DAEMON_ENTRY = (0, import_node_path37.join)(__dirname, "daemon.js");
47741
48687
  async function daemonForeground() {
47742
48688
  await runDaemon();
47743
48689
  }
@@ -47758,7 +48704,7 @@ async function daemonStart() {
47758
48704
  return;
47759
48705
  }
47760
48706
  ensureRuntimeDirs();
47761
- if (!(0, import_node_fs45.existsSync)(DAEMON_ENTRY)) {
48707
+ if (!(0, import_node_fs48.existsSync)(DAEMON_ENTRY)) {
47762
48708
  console.log(source_default.red(` Daemon entry not found at ${DAEMON_ENTRY}.`));
47763
48709
  console.log(source_default.dim(" Reinstall with `threatcrush update` or `pnpm run build` in the cli package."));
47764
48710
  return;
@@ -47766,8 +48712,8 @@ async function daemonStart() {
47766
48712
  let out;
47767
48713
  let err;
47768
48714
  try {
47769
- out = (0, import_node_fs46.openSync)(PATHS.logFile, "a");
47770
- err = (0, import_node_fs46.openSync)(PATHS.logFile, "a");
48715
+ out = (0, import_node_fs49.openSync)(PATHS.logFile, "a");
48716
+ err = (0, import_node_fs49.openSync)(PATHS.logFile, "a");
47771
48717
  } catch (e) {
47772
48718
  const code = e.code;
47773
48719
  console.log(source_default.red(` \u2717 Cannot write daemon log at ${PATHS.logFile} (${code ?? "error"}).`));
@@ -47780,7 +48726,7 @@ async function daemonStart() {
47780
48726
  }
47781
48727
  return;
47782
48728
  }
47783
- const child = (0, import_node_child_process17.spawn)(process.execPath, [DAEMON_ENTRY], {
48729
+ const child = (0, import_node_child_process18.spawn)(process.execPath, [DAEMON_ENTRY], {
47784
48730
  detached: true,
47785
48731
  stdio: ["ignore", out, err],
47786
48732
  env: { ...process.env, THREATCRUSH_DAEMON: "1" }
@@ -47855,41 +48801,41 @@ async function waitForExit(pid, timeoutMs) {
47855
48801
  }
47856
48802
  async function releaseStaleSocket() {
47857
48803
  const deadline = Date.now() + 2e3;
47858
- while ((0, import_node_fs45.existsSync)(PATHS.socket) && Date.now() < deadline) {
48804
+ while ((0, import_node_fs48.existsSync)(PATHS.socket) && Date.now() < deadline) {
47859
48805
  await new Promise((r) => setTimeout(r, 50));
47860
48806
  }
47861
- if ((0, import_node_fs45.existsSync)(PATHS.socket)) {
48807
+ if ((0, import_node_fs48.existsSync)(PATHS.socket)) {
47862
48808
  try {
47863
- (0, import_node_fs45.unlinkSync)(PATHS.socket);
48809
+ (0, import_node_fs48.unlinkSync)(PATHS.socket);
47864
48810
  } catch {
47865
48811
  }
47866
48812
  }
47867
48813
  }
47868
48814
 
47869
48815
  // src/commands/service.ts
47870
- var import_node_child_process18 = require("child_process");
47871
- var import_node_fs47 = require("fs");
47872
- var import_node_path36 = require("path");
47873
- var import_node_os14 = require("os");
48816
+ var import_node_child_process19 = require("child_process");
48817
+ var import_node_fs50 = require("fs");
48818
+ var import_node_path38 = require("path");
48819
+ var import_node_os15 = require("os");
47874
48820
  var UNIT_PATH = "/etc/systemd/system/threatcrushd.service";
47875
48821
  var DAEMON_UNIT_NAME = "threatcrushd.service";
47876
48822
  function resolveTemplate() {
47877
- const templatePath = (0, import_node_path36.join)(__dirname, "systemd", "threatcrushd.service");
47878
- if (!(0, import_node_fs47.existsSync)(templatePath)) {
48823
+ const templatePath = (0, import_node_path38.join)(__dirname, "systemd", "threatcrushd.service");
48824
+ if (!(0, import_node_fs50.existsSync)(templatePath)) {
47879
48825
  throw new Error(`systemd unit template not found at ${templatePath}`);
47880
48826
  }
47881
- return (0, import_node_fs47.readFileSync)(templatePath, "utf-8");
48827
+ return (0, import_node_fs50.readFileSync)(templatePath, "utf-8");
47882
48828
  }
47883
48829
  function stableBinPath(binPath) {
47884
48830
  const stable = binPath.replace(/\/\.pnpm\/[^/]+\/node_modules\//, "/node_modules/");
47885
48831
  if (stable === binPath) return binPath;
47886
- return (0, import_node_fs47.existsSync)(stable) ? stable : binPath;
48832
+ return (0, import_node_fs50.existsSync)(stable) ? stable : binPath;
47887
48833
  }
47888
48834
  function resolveBinPath() {
47889
48835
  const arg = process.argv[1];
47890
- if (arg && (0, import_node_fs47.existsSync)(arg)) return stableBinPath(arg);
48836
+ if (arg && (0, import_node_fs50.existsSync)(arg)) return stableBinPath(arg);
47891
48837
  try {
47892
- return (0, import_node_child_process18.execSync)("command -v threatcrush", { encoding: "utf-8" }).trim();
48838
+ return (0, import_node_child_process19.execSync)("command -v threatcrush", { encoding: "utf-8" }).trim();
47893
48839
  } catch {
47894
48840
  return "threatcrush";
47895
48841
  }
@@ -47897,11 +48843,11 @@ function resolveBinPath() {
47897
48843
  function stableNodePath(execPath) {
47898
48844
  const stable = execPath.replace(/(\/installs\/node\/)[^/]+\//, "$1latest/");
47899
48845
  if (stable === execPath) return execPath;
47900
- return (0, import_node_fs47.existsSync)(stable) ? stable : execPath;
48846
+ return (0, import_node_fs50.existsSync)(stable) ? stable : execPath;
47901
48847
  }
47902
48848
  function looksLikeNodeScript(path2) {
47903
48849
  try {
47904
- const head = (0, import_node_fs47.readFileSync)(path2, "utf-8").slice(0, 120);
48850
+ const head = (0, import_node_fs50.readFileSync)(path2, "utf-8").slice(0, 120);
47905
48851
  return /^#!.*\bnode\b/.test(head);
47906
48852
  } catch {
47907
48853
  return false;
@@ -47928,20 +48874,20 @@ function isRoot3() {
47928
48874
  return typeof process.getuid === "function" && process.getuid() === 0;
47929
48875
  }
47930
48876
  function reexecWithSudo(args) {
47931
- if ((0, import_node_child_process18.spawnSync)("sudo", ["--version"], { stdio: "pipe" }).status !== 0) return false;
48877
+ if ((0, import_node_child_process19.spawnSync)("sudo", ["--version"], { stdio: "pipe" }).status !== 0) return false;
47932
48878
  console.log(source_default.dim(" This needs root \u2014 sudo will ask for your password.\n"));
47933
48879
  const bin = resolveBinPath();
47934
48880
  const argv = looksLikeNodeScript(bin) ? [stableNodePath(process.execPath), bin, ...args] : [bin, ...args];
47935
- const result = (0, import_node_child_process18.spawnSync)("sudo", argv, { stdio: "inherit" });
48881
+ const result = (0, import_node_child_process19.spawnSync)("sudo", argv, { stdio: "inherit" });
47936
48882
  return result.status === 0;
47937
48883
  }
47938
48884
  function callerHome() {
47939
48885
  const user = process.env.SUDO_USER;
47940
48886
  if (!user) return null;
47941
48887
  try {
47942
- const line2 = (0, import_node_child_process18.execSync)(`getent passwd ${user}`, { encoding: "utf-8" }).trim();
48888
+ const line2 = (0, import_node_child_process19.execSync)(`getent passwd ${user}`, { encoding: "utf-8" }).trim();
47943
48889
  const home = line2.split(":")[5];
47944
- return home && (0, import_node_fs47.existsSync)(home) ? home : null;
48890
+ return home && (0, import_node_fs50.existsSync)(home) ? home : null;
47945
48891
  } catch {
47946
48892
  return null;
47947
48893
  }
@@ -47949,13 +48895,13 @@ function callerHome() {
47949
48895
  function stopUserModeDaemon() {
47950
48896
  const home = callerHome();
47951
48897
  if (!home) return;
47952
- const runDir = (0, import_node_path36.join)(home, ".threatcrush", "run");
47953
- const pidFile = (0, import_node_path36.join)(runDir, "threatcrushd.pid");
47954
- const socket = (0, import_node_path36.join)(runDir, "threatcrushd.sock");
47955
- if (!(0, import_node_fs47.existsSync)(pidFile) && !(0, import_node_fs47.existsSync)(socket)) return;
48898
+ const runDir = (0, import_node_path38.join)(home, ".threatcrush", "run");
48899
+ const pidFile = (0, import_node_path38.join)(runDir, "threatcrushd.pid");
48900
+ const socket = (0, import_node_path38.join)(runDir, "threatcrushd.sock");
48901
+ if (!(0, import_node_fs50.existsSync)(pidFile) && !(0, import_node_fs50.existsSync)(socket)) return;
47956
48902
  let pid = null;
47957
48903
  try {
47958
- pid = Number.parseInt((0, import_node_fs47.readFileSync)(pidFile, "utf-8").trim(), 10);
48904
+ pid = Number.parseInt((0, import_node_fs50.readFileSync)(pidFile, "utf-8").trim(), 10);
47959
48905
  } catch {
47960
48906
  pid = null;
47961
48907
  }
@@ -47968,13 +48914,13 @@ function stopUserModeDaemon() {
47968
48914
  }
47969
48915
  for (const path2 of [socket, pidFile]) {
47970
48916
  try {
47971
- if ((0, import_node_fs47.existsSync)(path2)) (0, import_node_fs47.rmSync)(path2);
48917
+ if ((0, import_node_fs50.existsSync)(path2)) (0, import_node_fs50.rmSync)(path2);
47972
48918
  } catch {
47973
48919
  }
47974
48920
  }
47975
48921
  }
47976
48922
  function unitIsActive() {
47977
- const result = (0, import_node_child_process18.spawnSync)("systemctl", ["is-active", "--quiet", DAEMON_UNIT_NAME], { stdio: "pipe" });
48923
+ const result = (0, import_node_child_process19.spawnSync)("systemctl", ["is-active", "--quiet", DAEMON_UNIT_NAME], { stdio: "pipe" });
47978
48924
  return result.status === 0;
47979
48925
  }
47980
48926
  async function installServiceCommand() {
@@ -47985,8 +48931,8 @@ async function installServiceCommand() {
47985
48931
  return;
47986
48932
  }
47987
48933
  const noSystemd = systemdUnavailableReason({
47988
- hasSystemctl: (0, import_node_child_process18.spawnSync)("sh", ["-c", "command -v systemctl"], { stdio: "ignore" }).status === 0,
47989
- booted: (0, import_node_fs47.existsSync)("/run/systemd/system")
48934
+ hasSystemctl: (0, import_node_child_process19.spawnSync)("sh", ["-c", "command -v systemctl"], { stdio: "ignore" }).status === 0,
48935
+ booted: (0, import_node_fs50.existsSync)("/run/systemd/system")
47990
48936
  });
47991
48937
  if (noSystemd) {
47992
48938
  console.log(source_default.red(` \u2717 systemd isn't available here: ${noSystemd}.`));
@@ -48008,7 +48954,7 @@ async function installServiceCommand() {
48008
48954
  const isNodeScript = looksLikeNodeScript(binPath);
48009
48955
  let nodePath = stableNodePath(process.execPath);
48010
48956
  if (isNodeScript && nodeVersionDir(binPath)) {
48011
- binPath = (0, import_node_fs47.realpathSync)(binPath);
48957
+ binPath = (0, import_node_fs50.realpathSync)(binPath);
48012
48958
  nodePath = process.execPath;
48013
48959
  }
48014
48960
  if (isNodeScript) {
@@ -48021,9 +48967,9 @@ async function installServiceCommand() {
48021
48967
  }
48022
48968
  }
48023
48969
  const exec = execStartCommand(binPath, nodePath, isNodeScript);
48024
- const configDir = (0, import_node_path36.join)((0, import_node_os14.homedir)(), ".threatcrush");
48970
+ const configDir = (0, import_node_path38.join)((0, import_node_os15.homedir)(), ".threatcrush");
48025
48971
  const unit = renderUnit(resolveTemplate(), { exec, binPath, configDir });
48026
- (0, import_node_fs47.writeFileSync)(UNIT_PATH, unit, { mode: 420 });
48972
+ (0, import_node_fs50.writeFileSync)(UNIT_PATH, unit, { mode: 420 });
48027
48973
  console.log(source_default.green(` \u2713 Installed unit file: ${UNIT_PATH}`));
48028
48974
  console.log(source_default.dim(` ExecStart=${exec}`));
48029
48975
  const nodeDir = nodeVersionDir(nodePath);
@@ -48038,8 +48984,8 @@ async function installServiceCommand() {
48038
48984
  installLogrotate();
48039
48985
  stopUserModeDaemon();
48040
48986
  try {
48041
- (0, import_node_child_process18.execSync)("systemctl daemon-reload", { stdio: "inherit" });
48042
- (0, import_node_child_process18.execSync)(`systemctl enable --now ${DAEMON_UNIT_NAME}`, { stdio: "inherit" });
48987
+ (0, import_node_child_process19.execSync)("systemctl daemon-reload", { stdio: "inherit" });
48988
+ (0, import_node_child_process19.execSync)(`systemctl enable --now ${DAEMON_UNIT_NAME}`, { stdio: "inherit" });
48043
48989
  } catch (err) {
48044
48990
  console.log(source_default.yellow(` ! systemctl error: ${err.message}`));
48045
48991
  console.log(source_default.dim(` Logs: journalctl -u ${DAEMON_UNIT_NAME} -n 50`));
@@ -48076,9 +49022,9 @@ function renderLogrotate(logDir = "/var/log/threatcrush") {
48076
49022
  ].join("\n");
48077
49023
  }
48078
49024
  function installLogrotate() {
48079
- if (!(0, import_node_fs47.existsSync)((0, import_node_path36.dirname)(LOGROTATE_PATH))) return;
49025
+ if (!(0, import_node_fs50.existsSync)((0, import_node_path38.dirname)(LOGROTATE_PATH))) return;
48080
49026
  try {
48081
- (0, import_node_fs47.writeFileSync)(LOGROTATE_PATH, renderLogrotate(), { mode: 420 });
49027
+ (0, import_node_fs50.writeFileSync)(LOGROTATE_PATH, renderLogrotate(), { mode: 420 });
48082
49028
  console.log(source_default.green(` \u2713 Log rotation: ${LOGROTATE_PATH} (daily or 200M, keeps 7)`));
48083
49029
  } catch (err) {
48084
49030
  console.log(source_default.yellow(` ! Could not install log rotation: ${err.message}`));
@@ -48100,20 +49046,20 @@ function ensureSystemDirs(configDir) {
48100
49046
  ];
48101
49047
  let admGid2 = null;
48102
49048
  try {
48103
- admGid2 = (0, import_node_fs47.statSync)("/var/log/auth.log").gid;
49049
+ admGid2 = (0, import_node_fs50.statSync)("/var/log/auth.log").gid;
48104
49050
  } catch {
48105
49051
  }
48106
49052
  for (const { path: path2, groupWritable, sticky } of dirs) {
48107
49053
  try {
48108
- (0, import_node_fs47.mkdirSync)(path2, { recursive: true });
49054
+ (0, import_node_fs50.mkdirSync)(path2, { recursive: true });
48109
49055
  } catch {
48110
49056
  }
48111
49057
  try {
48112
49058
  if (groupWritable && admGid2 !== null) {
48113
- (0, import_node_fs47.chmodSync)(path2, sticky ? 1533 : 509);
48114
- (0, import_node_child_process18.execSync)(`chgrp adm ${path2}`, { stdio: "ignore" });
49059
+ (0, import_node_fs50.chmodSync)(path2, sticky ? 1533 : 509);
49060
+ (0, import_node_child_process19.execSync)(`chgrp adm ${path2}`, { stdio: "ignore" });
48115
49061
  } else {
48116
- (0, import_node_fs47.chmodSync)(path2, 493);
49062
+ (0, import_node_fs50.chmodSync)(path2, 493);
48117
49063
  }
48118
49064
  } catch {
48119
49065
  }
@@ -48133,29 +49079,29 @@ async function uninstallServiceCommand() {
48133
49079
  return;
48134
49080
  }
48135
49081
  try {
48136
- (0, import_node_child_process18.execSync)("systemctl stop threatcrushd.service", { stdio: "inherit" });
49082
+ (0, import_node_child_process19.execSync)("systemctl stop threatcrushd.service", { stdio: "inherit" });
48137
49083
  } catch {
48138
49084
  }
48139
49085
  try {
48140
- (0, import_node_child_process18.execSync)("systemctl disable threatcrushd.service", { stdio: "inherit" });
49086
+ (0, import_node_child_process19.execSync)("systemctl disable threatcrushd.service", { stdio: "inherit" });
48141
49087
  } catch {
48142
49088
  }
48143
49089
  try {
48144
- if ((0, import_node_fs47.existsSync)(UNIT_PATH)) {
48145
- (0, import_node_child_process18.execSync)(`rm -f ${UNIT_PATH}`);
49090
+ if ((0, import_node_fs50.existsSync)(UNIT_PATH)) {
49091
+ (0, import_node_child_process19.execSync)(`rm -f ${UNIT_PATH}`);
48146
49092
  console.log(source_default.green(` \u2713 Removed unit file: ${UNIT_PATH}`));
48147
49093
  }
48148
49094
  } catch {
48149
49095
  }
48150
49096
  try {
48151
- (0, import_node_child_process18.execSync)("systemctl daemon-reload", { stdio: "inherit" });
49097
+ (0, import_node_child_process19.execSync)("systemctl daemon-reload", { stdio: "inherit" });
48152
49098
  } catch {
48153
49099
  }
48154
49100
  console.log(source_default.green(" \u2713 threatcrushd service removed."));
48155
49101
  }
48156
49102
 
48157
49103
  // src/commands/save.ts
48158
- var import_node_fs48 = require("fs");
49104
+ var import_node_fs51 = require("fs");
48159
49105
  var import_toml5 = __toESM(require_toml());
48160
49106
  init_cli_config();
48161
49107
  init_paths();
@@ -48194,9 +49140,9 @@ async function saveCommand(opts = {}) {
48194
49140
  }
48195
49141
  const path2 = opts.config ?? PATHS.configFile;
48196
49142
  let config = {};
48197
- if ((0, import_node_fs48.existsSync)(path2)) {
49143
+ if ((0, import_node_fs51.existsSync)(path2)) {
48198
49144
  try {
48199
- config = import_toml5.default.parse((0, import_node_fs48.readFileSync)(path2, "utf-8"));
49145
+ config = import_toml5.default.parse((0, import_node_fs51.readFileSync)(path2, "utf-8"));
48200
49146
  } catch (err) {
48201
49147
  console.log(source_default.red(` \u2717 ${path2} is not valid TOML: ${err.message}
48202
49148
  `));
@@ -48309,8 +49255,8 @@ function welcomeCommand() {
48309
49255
  }
48310
49256
 
48311
49257
  // src/commands/properties.ts
48312
- var import_node_fs49 = require("fs");
48313
- var import_node_path37 = require("path");
49258
+ var import_node_fs52 = require("fs");
49259
+ var import_node_path39 = require("path");
48314
49260
  var import_node_readline4 = __toESM(require("readline"));
48315
49261
  init_cli_config();
48316
49262
  var API_URL6 = process.env.THREATCRUSH_API_URL || "https://threatcrush.com";
@@ -48640,8 +49586,8 @@ async function propertiesRunsCommand(opts) {
48640
49586
  }
48641
49587
  }
48642
49588
  function parseImportFile(path2) {
48643
- const ext = (0, import_node_path37.extname)(path2).toLowerCase();
48644
- const raw = (0, import_node_fs49.readFileSync)(path2, "utf-8");
49589
+ const ext = (0, import_node_path39.extname)(path2).toLowerCase();
49590
+ const raw = (0, import_node_fs52.readFileSync)(path2, "utf-8");
48645
49591
  if (ext === ".json") {
48646
49592
  const parsed = JSON.parse(raw);
48647
49593
  if (!Array.isArray(parsed)) throw new Error("JSON must be an array of objects");
@@ -48836,19 +49782,19 @@ async function rulesCommand(opts) {
48836
49782
  }
48837
49783
 
48838
49784
  // src/commands/harden.ts
48839
- var import_node_fs50 = require("fs");
48840
- var import_node_child_process19 = require("child_process");
49785
+ var import_node_fs53 = require("fs");
49786
+ var import_node_child_process20 = require("child_process");
48841
49787
  init_cli_config();
48842
49788
  function tryExec(cmd) {
48843
49789
  try {
48844
- return (0, import_node_child_process19.execSync)(cmd, { encoding: "utf-8", stdio: ["pipe", "pipe", "pipe"] });
49790
+ return (0, import_node_child_process20.execSync)(cmd, { encoding: "utf-8", stdio: ["pipe", "pipe", "pipe"] });
48845
49791
  } catch {
48846
49792
  return null;
48847
49793
  }
48848
49794
  }
48849
49795
  function tryRead(path2) {
48850
49796
  try {
48851
- return (0, import_node_fs50.readFileSync)(path2, "utf-8");
49797
+ return (0, import_node_fs53.readFileSync)(path2, "utf-8");
48852
49798
  } catch {
48853
49799
  return null;
48854
49800
  }
@@ -48952,8 +49898,8 @@ function checkSshWeakConfig() {
48952
49898
  };
48953
49899
  }
48954
49900
  function checkAutoUpdates() {
48955
- const unattended = (0, import_node_fs50.existsSync)("/etc/apt/apt.conf.d/20auto-upgrades") || (0, import_node_fs50.existsSync)("/etc/apt/apt.conf.d/50unattended-upgrades");
48956
- const dnfAuto = (0, import_node_fs50.existsSync)("/etc/dnf/automatic.conf");
49901
+ const unattended = (0, import_node_fs53.existsSync)("/etc/apt/apt.conf.d/20auto-upgrades") || (0, import_node_fs53.existsSync)("/etc/apt/apt.conf.d/50unattended-upgrades");
49902
+ const dnfAuto = (0, import_node_fs53.existsSync)("/etc/dnf/automatic.conf");
48957
49903
  if (unattended || dnfAuto) {
48958
49904
  return {
48959
49905
  key: "auto-updates",
@@ -49079,7 +50025,7 @@ function checkFail2ban() {
49079
50025
  explanation: "fail2ban is installed and running."
49080
50026
  };
49081
50027
  }
49082
- if ((0, import_node_fs50.existsSync)("/etc/fail2ban/fail2ban.conf")) {
50028
+ if ((0, import_node_fs53.existsSync)("/etc/fail2ban/fail2ban.conf")) {
49083
50029
  return {
49084
50030
  key: checkKey,
49085
50031
  status: "warn",
@@ -49265,9 +50211,9 @@ async function hardenCommand(opts) {
49265
50211
  }
49266
50212
 
49267
50213
  // src/core/patches/index.ts
49268
- var import_node_fs51 = require("fs");
49269
- var import_node_path38 = require("path");
49270
- var import_node_child_process20 = require("child_process");
50214
+ var import_node_fs54 = require("fs");
50215
+ var import_node_path40 = require("path");
50216
+ var import_node_child_process21 = require("child_process");
49271
50217
  var import_node_util5 = require("util");
49272
50218
 
49273
50219
  // src/core/patches/dpkg-version.ts
@@ -49327,7 +50273,7 @@ var STALE_AFTER_MS = 2 * 864e5;
49327
50273
  var SEVERITIES2 = ["info", "low", "medium", "high", "critical"];
49328
50274
  var RANK = { info: 0, low: 1, medium: 2, high: 3, critical: 4 };
49329
50275
  var defaultExec = async (file, args) => {
49330
- const { stdout } = await (0, import_node_util5.promisify)(import_node_child_process20.execFile)(file, args, {
50276
+ const { stdout } = await (0, import_node_util5.promisify)(import_node_child_process21.execFile)(file, args, {
49331
50277
  timeout: 12e4,
49332
50278
  maxBuffer: 32 * 1024 * 1024,
49333
50279
  env: { ...process.env, LC_ALL: "C" }
@@ -49426,9 +50372,9 @@ async function osvRecords(doFetch, ecosystem, source, version) {
49426
50372
  function newestReleaseMtime(dir) {
49427
50373
  try {
49428
50374
  let newest = 0;
49429
- for (const name of (0, import_node_fs51.readdirSync)(dir)) {
50375
+ for (const name of (0, import_node_fs54.readdirSync)(dir)) {
49430
50376
  if (!/Release$/.test(name)) continue;
49431
- newest = Math.max(newest, (0, import_node_fs51.statSync)((0, import_node_path38.join)(dir, name)).mtimeMs);
50377
+ newest = Math.max(newest, (0, import_node_fs54.statSync)((0, import_node_path40.join)(dir, name)).mtimeMs);
49432
50378
  }
49433
50379
  return newest > 0 ? new Date(newest) : null;
49434
50380
  } catch {
@@ -49445,7 +50391,7 @@ async function checkPatches(opts = {}) {
49445
50391
  let osText = opts.osRelease;
49446
50392
  if (osText === void 0) {
49447
50393
  try {
49448
- osText = (0, import_node_fs51.readFileSync)("/etc/os-release", "utf-8");
50394
+ osText = (0, import_node_fs54.readFileSync)("/etc/os-release", "utf-8");
49449
50395
  } catch {
49450
50396
  osText = "";
49451
50397
  }
@@ -49671,27 +50617,27 @@ async function patchesCommand(opts) {
49671
50617
  }
49672
50618
 
49673
50619
  // src/commands/feeds.ts
49674
- var import_node_net15 = require("net");
49675
- var import_node_path40 = require("path");
50620
+ var import_node_net18 = require("net");
50621
+ var import_node_path42 = require("path");
49676
50622
  init_paths();
49677
50623
 
49678
50624
  // src/commands/feeds-resolver.ts
49679
- var import_node_child_process21 = require("child_process");
49680
- var import_node_fs52 = require("fs");
49681
- var import_node_path39 = require("path");
50625
+ var import_node_child_process22 = require("child_process");
50626
+ var import_node_fs55 = require("fs");
50627
+ var import_node_path41 = require("path");
49682
50628
  var realIO = {
49683
- exists: (p) => (0, import_node_fs52.existsSync)(p),
50629
+ exists: (p) => (0, import_node_fs55.existsSync)(p),
49684
50630
  read: (p) => {
49685
50631
  try {
49686
- return (0, import_node_fs52.readFileSync)(p, "utf-8");
50632
+ return (0, import_node_fs55.readFileSync)(p, "utf-8");
49687
50633
  } catch {
49688
50634
  return null;
49689
50635
  }
49690
50636
  },
49691
- write: (p, c) => (0, import_node_fs52.writeFileSync)(p, c),
49692
- remove: (p) => (0, import_node_fs52.rmSync)(p, { force: true }),
50637
+ write: (p, c) => (0, import_node_fs55.writeFileSync)(p, c),
50638
+ remove: (p) => (0, import_node_fs55.rmSync)(p, { force: true }),
49693
50639
  run: (cmd, args) => {
49694
- const r = (0, import_node_child_process21.spawnSync)(cmd, args, { encoding: "utf-8", timeout: 3e4 });
50640
+ const r = (0, import_node_child_process22.spawnSync)(cmd, args, { encoding: "utf-8", timeout: 3e4 });
49695
50641
  return { code: r.status ?? 1, out: `${r.stdout ?? ""}${r.stderr ?? ""}`.trim() };
49696
50642
  }
49697
50643
  };
@@ -49699,17 +50645,17 @@ var APPARMOR_LOCAL = "/etc/apparmor.d/local/usr.sbin.unbound";
49699
50645
  var APPARMOR_PROFILE = "/etc/apparmor.d/usr.sbin.unbound";
49700
50646
  function hookContent(resolver, stateDir) {
49701
50647
  const head = "# Installed by `threatcrush feeds resolver install`; `threatcrush feeds resolver remove` takes it out.\n";
49702
- return resolver === "dnsmasq" ? `${head}addn-hosts=${(0, import_node_path39.join)(stateDir, RESOLVER_FILES.hosts)}
49703
- ` : `${head}include: "${(0, import_node_path39.join)(stateDir, RESOLVER_FILES.unbound)}"
50648
+ return resolver === "dnsmasq" ? `${head}addn-hosts=${(0, import_node_path41.join)(stateDir, RESOLVER_FILES.hosts)}
50649
+ ` : `${head}include: "${(0, import_node_path41.join)(stateDir, RESOLVER_FILES.unbound)}"
49704
50650
  `;
49705
50651
  }
49706
50652
  function apparmorRule(stateDir) {
49707
- return ` ${(0, import_node_path39.join)(stateDir, RESOLVER_FILES.unbound)} r, # threatcrush`;
50653
+ return ` ${(0, import_node_path41.join)(stateDir, RESOLVER_FILES.unbound)} r, # threatcrush`;
49708
50654
  }
49709
50655
  function detectResolvers(io = realIO) {
49710
50656
  const found = [];
49711
- if (io.exists((0, import_node_path39.dirname)(RESOLVER_HOOKS.dnsmasq)) && io.run("dnsmasq", ["--version"]).code === 0) found.push("dnsmasq");
49712
- if (io.exists((0, import_node_path39.dirname)(RESOLVER_HOOKS.unbound)) && io.run("unbound-checkconf", ["-h"]).code !== 127) found.push("unbound");
50657
+ if (io.exists((0, import_node_path41.dirname)(RESOLVER_HOOKS.dnsmasq)) && io.run("dnsmasq", ["--version"]).code === 0) found.push("dnsmasq");
50658
+ if (io.exists((0, import_node_path41.dirname)(RESOLVER_HOOKS.unbound)) && io.run("unbound-checkconf", ["-h"]).code !== 127) found.push("unbound");
49713
50659
  return found;
49714
50660
  }
49715
50661
  function check(resolver, io) {
@@ -49722,7 +50668,7 @@ function restartIfActive(resolver, io) {
49722
50668
  }
49723
50669
  function installHook(resolver, stateDir, io = realIO) {
49724
50670
  const hook = RESOLVER_HOOKS[resolver];
49725
- const file = (0, import_node_path39.join)(stateDir, resolver === "dnsmasq" ? RESOLVER_FILES.hosts : RESOLVER_FILES.unbound);
50671
+ const file = (0, import_node_path41.join)(stateDir, resolver === "dnsmasq" ? RESOLVER_FILES.hosts : RESOLVER_FILES.unbound);
49726
50672
  if (!io.exists(file)) io.write(file, resolver === "dnsmasq" ? hostsBlocklist([]) : unboundBlocklist([]));
49727
50673
  io.write(hook, hookContent(resolver, stateDir));
49728
50674
  if (resolver === "unbound" && io.exists(APPARMOR_LOCAL)) {
@@ -49783,8 +50729,8 @@ function resolverCommand(sub, stateDir, io = realIO) {
49783
50729
  }
49784
50730
  return failed ? 1 : 0;
49785
50731
  }
49786
- const hosts = io.read((0, import_node_path39.join)(stateDir, RESOLVER_FILES.hosts));
49787
- const unbound = io.read((0, import_node_path39.join)(stateDir, RESOLVER_FILES.unbound));
50732
+ const hosts = io.read((0, import_node_path41.join)(stateDir, RESOLVER_FILES.hosts));
50733
+ const unbound = io.read((0, import_node_path41.join)(stateDir, RESOLVER_FILES.unbound));
49788
50734
  console.log(` resolvers here: ${found.join(", ") || "none that can block (systemd-resolved only?)"}`);
49789
50735
  for (const r of ["dnsmasq", "unbound"]) {
49790
50736
  console.log(` ${r.padEnd(8)} hook ${io.exists(RESOLVER_HOOKS[r]) ? source_default.green("installed") : source_default.gray("not installed")}`);
@@ -49796,11 +50742,11 @@ function resolverCommand(sub, stateDir, io = realIO) {
49796
50742
  // src/commands/feeds.ts
49797
50743
  async function loadSet() {
49798
50744
  for (const dir of [SYSTEM_PATHS.stateDir, USER_PATHS.stateDir]) {
49799
- const path2 = (0, import_node_path40.join)(dir, "threat-feeds.json");
50745
+ const path2 = (0, import_node_path42.join)(dir, "threat-feeds.json");
49800
50746
  const set = readFeedCache(path2);
49801
50747
  if (set) return { set, from: path2 };
49802
50748
  }
49803
- const settings = threatFeedSettings(loadConfig((0, import_node_path40.join)(SYSTEM_PATHS.configDir, "threatcrushd.conf")).threat_feeds);
50749
+ const settings = threatFeedSettings(loadConfig((0, import_node_path42.join)(SYSTEM_PATHS.configDir, "threatcrushd.conf")).threat_feeds);
49804
50750
  return { set: await fetchFeeds(settings), from: "abuse.ch (live; no daemon cache readable)" };
49805
50751
  }
49806
50752
  async function feedsCommand(action, value, opts) {
@@ -49815,8 +50761,8 @@ async function feedsCommand(action, value, opts) {
49815
50761
  process.exitCode = 2;
49816
50762
  return;
49817
50763
  }
49818
- const ipHit = (0, import_node_net15.isIP)(value) ? matchIp(value, set) : null;
49819
- const domainHit = (0, import_node_net15.isIP)(value) ? null : matchDomain(value, set);
50764
+ const ipHit = (0, import_node_net18.isIP)(value) ? matchIp(value, set) : null;
50765
+ const domainHit = (0, import_node_net18.isIP)(value) ? null : matchDomain(value, set);
49820
50766
  const listed = ipHit ?? domainHit?.indicator ?? null;
49821
50767
  if (opts.json) {
49822
50768
  console.log(JSON.stringify({ value, listed: Boolean(listed), indicator: listed, matched: domainHit?.domain ?? (ipHit ? value : null), fetched_at: set.fetched_at }, null, 2));
@@ -49843,15 +50789,76 @@ async function feedsCommand(action, value, opts) {
49843
50789
  console.log(source_default.gray("\n Blocking egress needs [threat_feeds] block = true and [remediation] in enforce mode."));
49844
50790
  }
49845
50791
 
50792
+ // src/commands/tor.ts
50793
+ var import_node_fs56 = require("fs");
50794
+ var import_node_net19 = require("net");
50795
+ var import_node_path43 = require("path");
50796
+ init_paths();
50797
+ async function torCommand(action, value, opts) {
50798
+ let exits = /* @__PURE__ */ new Set();
50799
+ let from = "";
50800
+ let updated = null;
50801
+ for (const dir of [SYSTEM_PATHS.stateDir, USER_PATHS.stateDir]) {
50802
+ const path2 = (0, import_node_path43.join)(dir, "tor-exits.txt");
50803
+ try {
50804
+ if (!(0, import_node_fs56.existsSync)(path2)) continue;
50805
+ exits = parseTorExitList((0, import_node_fs56.readFileSync)(path2, "utf-8"));
50806
+ from = path2;
50807
+ updated = (0, import_node_fs56.statSync)(path2).mtime;
50808
+ break;
50809
+ } catch {
50810
+ }
50811
+ }
50812
+ if (!exits.size) {
50813
+ try {
50814
+ const res = await fetch(TOR_BULK_EXIT_LIST_URL, { signal: AbortSignal.timeout(2e4) });
50815
+ if (res.ok) {
50816
+ exits = parseTorExitList(await res.text());
50817
+ from = `${TOR_BULK_EXIT_LIST_URL} (live; no daemon cache readable)`;
50818
+ updated = /* @__PURE__ */ new Date();
50819
+ }
50820
+ } catch {
50821
+ }
50822
+ }
50823
+ const remediation = loadConfig((0, import_node_path43.join)(SYSTEM_PATHS.configDir, "threatcrushd.conf")).remediation;
50824
+ const ban = remediation?.block_tor_ssh !== false && remediation?.enabled !== false;
50825
+ if (action === "check") {
50826
+ if (!value || !(0, import_node_net19.isIP)(value)) {
50827
+ console.error("Usage: threatcrush tor check <ip>");
50828
+ process.exitCode = 2;
50829
+ return;
50830
+ }
50831
+ const listed = exits.has(normalizeIp(value));
50832
+ if (opts.json) console.log(JSON.stringify({ ip: value, tor_exit: listed, list_size: exits.size, from }, null, 2));
50833
+ else console.log(listed ? `${source_default.red("TOR EXIT")} ${value}` : `${source_default.green("not a Tor exit")} ${value}`);
50834
+ process.exitCode = listed ? 1 : 0;
50835
+ return;
50836
+ }
50837
+ const status = {
50838
+ exits: exits.size,
50839
+ from,
50840
+ updated_at: updated?.toISOString() ?? null,
50841
+ block_tor_ssh: ban,
50842
+ pinned_in_config: typeof remediation?.block_tor_ssh === "boolean"
50843
+ };
50844
+ if (opts.json) {
50845
+ console.log(JSON.stringify(status, null, 2));
50846
+ return;
50847
+ }
50848
+ console.log(`Tor exits known: ${source_default.bold(String(status.exits))}${status.updated_at ? ` (updated ${status.updated_at})` : ""}`);
50849
+ console.log(`Source: ${status.from || "none (daemon not running yet, and the list could not be fetched)"}`);
50850
+ console.log(`SSH from Tor: ${ban ? source_default.red("banned at once, for max_ban, even in dry_run") : source_default.yellow("alert only ([remediation] block_tor_ssh = false)")}${status.pinned_in_config ? " (set in threatcrushd.conf)" : " (default; the dashboard org setting can change it)"}`);
50851
+ }
50852
+
49846
50853
  // src/commands/reputation.ts
49847
- var import_node_os15 = require("os");
49848
- var import_node_fs53 = require("fs");
49849
- var import_node_path41 = require("path");
50854
+ var import_node_os16 = require("os");
50855
+ var import_node_fs57 = require("fs");
50856
+ var import_node_path44 = require("path");
49850
50857
  var API_URL7 = process.env.THREATCRUSH_API_URL || "https://threatcrush.com";
49851
- var CONFIG_PATH4 = (0, import_node_path41.join)((0, import_node_os15.homedir)(), ".threatcrush", "config.json");
50858
+ var CONFIG_PATH4 = (0, import_node_path44.join)((0, import_node_os16.homedir)(), ".threatcrush", "config.json");
49852
50859
  function readConfig3() {
49853
50860
  try {
49854
- return JSON.parse((0, import_node_fs53.readFileSync)(CONFIG_PATH4, "utf-8"));
50861
+ return JSON.parse((0, import_node_fs57.readFileSync)(CONFIG_PATH4, "utf-8"));
49855
50862
  } catch {
49856
50863
  return {};
49857
50864
  }
@@ -50039,7 +51046,7 @@ async function reputationSubscribeCommand(opts) {
50039
51046
  }
50040
51047
 
50041
51048
  // src/commands/privileged.ts
50042
- var import_node_fs54 = require("fs");
51049
+ var import_node_fs58 = require("fs");
50043
51050
  init_paths();
50044
51051
  var SEV2 = {
50045
51052
  critical: source_default.red.bold,
@@ -50052,19 +51059,19 @@ async function privilegedCommand(opts) {
50052
51059
  const snapshot = takeSnapshot({
50053
51060
  readFile: (p) => {
50054
51061
  try {
50055
- return (0, import_node_fs54.readFileSync)(p, "utf-8");
51062
+ return (0, import_node_fs58.readFileSync)(p, "utf-8");
50056
51063
  } catch {
50057
51064
  return null;
50058
51065
  }
50059
51066
  },
50060
51067
  readDir: (p) => {
50061
51068
  try {
50062
- return (0, import_node_fs54.readdirSync)(p);
51069
+ return (0, import_node_fs58.readdirSync)(p);
50063
51070
  } catch {
50064
51071
  return null;
50065
51072
  }
50066
51073
  },
50067
- exists: (p) => (0, import_node_fs54.existsSync)(p)
51074
+ exists: (p) => (0, import_node_fs58.existsSync)(p)
50068
51075
  });
50069
51076
  let events = [];
50070
51077
  let ledgerNote = "";
@@ -50246,7 +51253,7 @@ async function allowlistCommand(opts) {
50246
51253
  }
50247
51254
 
50248
51255
  // src/commands/abuse.ts
50249
- var import_node_fs55 = require("fs");
51256
+ var import_node_fs59 = require("fs");
50250
51257
  init_paths();
50251
51258
  function rows(records) {
50252
51259
  if (records.length === 0) {
@@ -50306,7 +51313,7 @@ function abuseRetractCommand(id, opts = {}) {
50306
51313
  );
50307
51314
  }
50308
51315
  function abuseStatusCommand(opts = {}) {
50309
- const config = loadConfig((0, import_node_fs55.existsSync)(PATHS.configFile) ? PATHS.configFile : void 0);
51316
+ const config = loadConfig((0, import_node_fs59.existsSync)(PATHS.configFile) ? PATHS.configFile : void 0);
50310
51317
  const cfg = resolveConfig(config.abuse_reporter);
50311
51318
  const hasKey2 = Boolean(cfg.keys.abuseipdb || cfg.keys.stopforumspam);
50312
51319
  const active2 = cfg.enabled && (cfg.dryRun || hasKey2);
@@ -50329,11 +51336,11 @@ function abuseStatusCommand(opts = {}) {
50329
51336
  init_paths();
50330
51337
 
50331
51338
  // src/upgrade.ts
50332
- var import_node_child_process22 = require("child_process");
51339
+ var import_node_child_process23 = require("child_process");
50333
51340
  var PACKAGE_MANAGERS = ["npm", "pnpm", "yarn", "bun"];
50334
51341
  var defaultRunner = (cmd) => {
50335
51342
  try {
50336
- return (0, import_node_child_process22.execSync)(cmd, { encoding: "utf-8", stdio: ["pipe", "pipe", "pipe"] });
51343
+ return (0, import_node_child_process23.execSync)(cmd, { encoding: "utf-8", stdio: ["pipe", "pipe", "pipe"] });
50337
51344
  } catch {
50338
51345
  return null;
50339
51346
  }
@@ -50474,9 +51481,9 @@ function installUserAgent(target = globalThis) {
50474
51481
  }
50475
51482
 
50476
51483
  // src/core/cloud-upload.ts
50477
- var import_node_child_process23 = require("child_process");
50478
- var import_node_os16 = require("os");
50479
- var import_node_path42 = require("path");
51484
+ var import_node_child_process24 = require("child_process");
51485
+ var import_node_os17 = require("os");
51486
+ var import_node_path45 = require("path");
50480
51487
  init_cli_config();
50481
51488
  function uploadDisabled(upload, env3 = process.env) {
50482
51489
  if (upload === false) return true;
@@ -50495,8 +51502,8 @@ function cleanUrl(raw) {
50495
51502
  return raw.split(/[?#]/)[0];
50496
51503
  }
50497
51504
  }
50498
- function repoTarget(path2, run = (args) => (0, import_node_child_process23.execFileSync)("git", args, { cwd: (0, import_node_path42.resolve)(path2), encoding: "utf8", stdio: ["ignore", "pipe", "ignore"], timeout: 5e3 }).trim()) {
50499
- const abs = (0, import_node_path42.resolve)(path2);
51505
+ function repoTarget(path2, run = (args) => (0, import_node_child_process24.execFileSync)("git", args, { cwd: (0, import_node_path45.resolve)(path2), encoding: "utf8", stdio: ["ignore", "pipe", "ignore"], timeout: 5e3 }).trim()) {
51506
+ const abs = (0, import_node_path45.resolve)(path2);
50500
51507
  try {
50501
51508
  const root = run(["rev-parse", "--show-toplevel"]);
50502
51509
  const sub = abs === root ? "." : abs.slice(root.length + 1);
@@ -50509,9 +51516,9 @@ function repoTarget(path2, run = (args) => (0, import_node_child_process23.execF
50509
51516
  const m = /^(?:[a-z+]+:\/\/)?(?:[^@/]+@)?([^/:]+)[:/](.+?)(?:\.git)?\/?$/i.exec(remote);
50510
51517
  if (m) return { target: `${m[1]}/${m[2]}`, root, sub };
50511
51518
  }
50512
- return { target: `${(0, import_node_os16.hostname)()}:${root}`, root, sub };
51519
+ return { target: `${(0, import_node_os17.hostname)()}:${root}`, root, sub };
50513
51520
  } catch {
50514
- return { target: `${(0, import_node_os16.hostname)()}:${abs}`, root: abs, sub: "." };
51521
+ return { target: `${(0, import_node_os17.hostname)()}:${abs}`, root: abs, sub: "." };
50515
51522
  }
50516
51523
  }
50517
51524
  async function uploadResult(result, opts) {
@@ -50868,25 +51875,25 @@ ${source_default.dim(" C R U S H")}
50868
51875
  var API_URL8 = process.env.THREATCRUSH_API_URL || "https://threatcrush.com";
50869
51876
  var PKG_NAME2 = "@profullstack/threatcrush";
50870
51877
  var DESKTOP_PKG_NAME = "@profullstack/threatcrush-desktop";
50871
- var INSTALL_CONFIG_PATH = (0, import_node_path43.join)((0, import_node_os17.homedir)(), ".threatcrush", "install.json");
51878
+ var INSTALL_CONFIG_PATH = (0, import_node_path46.join)((0, import_node_os18.homedir)(), ".threatcrush", "install.json");
50872
51879
  function detectPackageManager() {
50873
51880
  try {
50874
- const npmGlobal = (0, import_node_child_process24.execSync)("npm ls -g --depth=0 --json 2>/dev/null", { encoding: "utf-8" });
51881
+ const npmGlobal = (0, import_node_child_process25.execSync)("npm ls -g --depth=0 --json 2>/dev/null", { encoding: "utf-8" });
50875
51882
  if (npmGlobal.includes(PKG_NAME2)) return "npm";
50876
51883
  } catch {
50877
51884
  }
50878
51885
  try {
50879
- (0, import_node_child_process24.execSync)("pnpm --version", { stdio: "pipe" });
51886
+ (0, import_node_child_process25.execSync)("pnpm --version", { stdio: "pipe" });
50880
51887
  return "pnpm";
50881
51888
  } catch {
50882
51889
  }
50883
51890
  try {
50884
- (0, import_node_child_process24.execSync)("yarn --version", { stdio: "pipe" });
51891
+ (0, import_node_child_process25.execSync)("yarn --version", { stdio: "pipe" });
50885
51892
  return "yarn";
50886
51893
  } catch {
50887
51894
  }
50888
51895
  try {
50889
- (0, import_node_child_process24.execSync)("bun --version", { stdio: "pipe" });
51896
+ (0, import_node_child_process25.execSync)("bun --version", { stdio: "pipe" });
50890
51897
  return "bun";
50891
51898
  } catch {
50892
51899
  }
@@ -50894,14 +51901,14 @@ function detectPackageManager() {
50894
51901
  }
50895
51902
  function readInstallConfig() {
50896
51903
  try {
50897
- return JSON.parse((0, import_node_fs56.readFileSync)(INSTALL_CONFIG_PATH, "utf-8"));
51904
+ return JSON.parse((0, import_node_fs60.readFileSync)(INSTALL_CONFIG_PATH, "utf-8"));
50898
51905
  } catch {
50899
51906
  return {};
50900
51907
  }
50901
51908
  }
50902
51909
  function packageLooksInstalled(pm, pkgName) {
50903
51910
  try {
50904
- const output = (0, import_node_child_process24.execSync)(globalListCommand(pm, pkgName), {
51911
+ const output = (0, import_node_child_process25.execSync)(globalListCommand(pm, pkgName), {
50905
51912
  encoding: "utf-8",
50906
51913
  stdio: ["pipe", "pipe", "pipe"]
50907
51914
  });
@@ -51004,14 +52011,14 @@ async function promoteUnprivilegedDaemon() {
51004
52011
  function restartSystemdDaemon() {
51005
52012
  const asRoot = typeof process.getuid === "function" && process.getuid() === 0;
51006
52013
  const argv = asRoot ? ["systemctl", "restart", DAEMON_UNIT] : ["sudo", "systemctl", "restart", DAEMON_UNIT];
51007
- if (!asRoot && (0, import_node_child_process24.spawnSync)("sudo", ["--version"], { stdio: "pipe" }).status !== 0) return false;
52014
+ if (!asRoot && (0, import_node_child_process25.spawnSync)("sudo", ["--version"], { stdio: "pipe" }).status !== 0) return false;
51008
52015
  const [cmd, ...args] = argv;
51009
- if ((0, import_node_child_process24.spawnSync)(cmd, args, { stdio: "inherit" }).status !== 0) return false;
51010
- return (0, import_node_child_process24.spawnSync)("systemctl", ["is-active", "--quiet", DAEMON_UNIT], { stdio: "pipe" }).status === 0;
52016
+ if ((0, import_node_child_process25.spawnSync)(cmd, args, { stdio: "inherit" }).status !== 0) return false;
52017
+ return (0, import_node_child_process25.spawnSync)("systemctl", ["is-active", "--quiet", DAEMON_UNIT], { stdio: "pipe" }).status === 0;
51011
52018
  }
51012
52019
  function execQuiet(cmd) {
51013
52020
  try {
51014
- return (0, import_node_child_process24.execSync)(cmd, { encoding: "utf-8", stdio: ["pipe", "pipe", "pipe"] });
52021
+ return (0, import_node_child_process25.execSync)(cmd, { encoding: "utf-8", stdio: ["pipe", "pipe", "pipe"] });
51015
52022
  } catch {
51016
52023
  return null;
51017
52024
  }
@@ -51252,6 +52259,9 @@ program2.command("patches").description("List OS packages with a security update
51252
52259
  program2.command("feeds [action] [value]").description("Show the abuse.ch C2/malware list the daemon matches; `feeds check <ip|domain>` looks one up (exit 1 when listed); `feeds resolver install|remove|status` lets dnsmasq/unbound refuse the listed domains").option("--json", "Output as JSON").action(async (action, value, opts) => {
51253
52260
  await feedsCommand(action, value, opts);
51254
52261
  });
52262
+ program2.command("tor [action] [value]").description("Show the Tor exit list the daemon bans SSH from (count, age, whether the ban is on); `tor check <ip>` looks one up (exit 1 when it is an exit)").option("--json", "JSON output").action(async (action, value, opts) => {
52263
+ await torCommand(action, value, opts);
52264
+ });
51255
52265
  var reputationCmd = program2.command("reputation").description("Look IPs or domains up against the ThreatCrush community database (exit 1 when any is listed; several at once go as one bulk request); `reputation watch` alerts on changes, `reputation subscribe` starts a Reputation Pro payment through CoinPay").argument("[indicators...]", "IP addresses or domains to look up").option("--json", "Output as JSON").option("--org <id>", "Org to look up as (defaults to `orgs use`)").action(async (indicators, opts) => {
51256
52266
  if (!indicators?.length) {
51257
52267
  reputationCmd.help();
@@ -51304,7 +52314,7 @@ program2.command("uninstall-service").description("Remove the threatcrushd syste
51304
52314
  program2.command("logs").description("Tail daemon logs").action(async () => {
51305
52315
  console.log(LOGO2);
51306
52316
  const logPath2 = PATHS.logFile;
51307
- if (!(0, import_node_fs56.existsSync)(logPath2)) {
52317
+ if (!(0, import_node_fs60.existsSync)(logPath2)) {
51308
52318
  console.log(source_default.yellow(` No log file found at ${logPath2}`));
51309
52319
  console.log(source_default.dim(" Start the daemon first with `threatcrush start`\n"));
51310
52320
  return;
@@ -51312,7 +52322,7 @@ program2.command("logs").description("Tail daemon logs").action(async () => {
51312
52322
  console.log(source_default.green(` Tailing ${logPath2}...
51313
52323
  `));
51314
52324
  console.log(source_default.gray(" Press Ctrl+C to stop\n"));
51315
- (0, import_node_child_process24.execSync)(`tail -f ${logPath2}`, { stdio: "inherit" });
52325
+ (0, import_node_child_process25.execSync)(`tail -f ${logPath2}`, { stdio: "inherit" });
51316
52326
  });
51317
52327
  program2.command("update").description("Update ThreatCrush CLI and installed bundle").option("--cli", "Update CLI only").option("--modules", "Update modules only").option("--desktop", "Update desktop app too").action(async (opts) => {
51318
52328
  console.log(LOGO2);
@@ -51324,7 +52334,7 @@ program2.command("update").description("Update ThreatCrush CLI and installed bun
51324
52334
  for (const cmd of commands2) {
51325
52335
  console.log(source_default.green(` \u2192 ${cmd}
51326
52336
  `));
51327
- (0, import_node_child_process24.execSync)(cmd, { stdio: "inherit" });
52337
+ (0, import_node_child_process25.execSync)(cmd, { stdio: "inherit" });
51328
52338
  }
51329
52339
  console.log(source_default.green("\n \u2713 Modules updated successfully!\n"));
51330
52340
  await reportIfStillStale();
@@ -51349,7 +52359,7 @@ program2.command("update").description("Update ThreatCrush CLI and installed bun
51349
52359
  for (const cmd of commands) {
51350
52360
  console.log(source_default.green(` \u2192 ${cmd}
51351
52361
  `));
51352
- (0, import_node_child_process24.execSync)(cmd, { stdio: "inherit" });
52362
+ (0, import_node_child_process25.execSync)(cmd, { stdio: "inherit" });
51353
52363
  }
51354
52364
  console.log(source_default.green("\n \u2713 ThreatCrush updated successfully!\n"));
51355
52365
  if (installMode === "desktop") {
@@ -51400,7 +52410,7 @@ program2.command("remove").description("Uninstall ThreatCrush and the installed
51400
52410
  for (const cmd of commands) {
51401
52411
  console.log(source_default.green(` \u2192 ${cmd}
51402
52412
  `));
51403
- (0, import_node_child_process24.execSync)(cmd, { stdio: "inherit" });
52413
+ (0, import_node_child_process25.execSync)(cmd, { stdio: "inherit" });
51404
52414
  }
51405
52415
  console.log(source_default.green("\n \u2713 ThreatCrush has been uninstalled.\n"));
51406
52416
  console.log(source_default.dim(" We're sorry to see you go! \u{1F44B}\n"));
@@ -51477,10 +52487,10 @@ storeCmd.command("search <query>").description("Search for modules in the store"
51477
52487
  });
51478
52488
  storeCmd.command("publish <url>").description("Publish a module from a git URL or web URL").action(async (url) => {
51479
52489
  console.log(LOGO2);
51480
- const configPath = (0, import_node_path43.join)((0, import_node_os17.homedir)(), ".threatcrush", "config.json");
52490
+ const configPath = (0, import_node_path46.join)((0, import_node_os18.homedir)(), ".threatcrush", "config.json");
51481
52491
  let email = "";
51482
52492
  try {
51483
- const config = JSON.parse((0, import_node_fs56.readFileSync)(configPath, "utf-8"));
52493
+ const config = JSON.parse((0, import_node_fs60.readFileSync)(configPath, "utf-8"));
51484
52494
  email = config.email || "";
51485
52495
  } catch {
51486
52496
  }
@@ -51497,9 +52507,9 @@ storeCmd.command("publish <url>").description("Publish a module from a git URL o
51497
52507
  return;
51498
52508
  }
51499
52509
  try {
51500
- const dir = (0, import_node_path43.join)((0, import_node_os17.homedir)(), ".threatcrush");
51501
- if (!(0, import_node_fs56.existsSync)(dir)) (0, import_node_fs56.mkdirSync)(dir, { recursive: true });
51502
- (0, import_node_fs56.writeFileSync)(configPath, JSON.stringify({ email }, null, 2));
52510
+ const dir = (0, import_node_path46.join)((0, import_node_os18.homedir)(), ".threatcrush");
52511
+ if (!(0, import_node_fs60.existsSync)(dir)) (0, import_node_fs60.mkdirSync)(dir, { recursive: true });
52512
+ (0, import_node_fs60.writeFileSync)(configPath, JSON.stringify({ email }, null, 2));
51503
52513
  console.log(source_default.dim(` Saved email to ${configPath}`));
51504
52514
  } catch {
51505
52515
  }