@profullstack/threatcrush 0.13.61 → 0.13.63

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
  }
@@ -30376,36 +30409,63 @@ var DEFAULT_CONFIG = {
30376
30409
  config_dir: DEFAULT_CONFDIR
30377
30410
  }
30378
30411
  };
30379
- function loadConfig(configPath) {
30412
+ function loadConfig(configPath, onError) {
30380
30413
  const path2 = configPath || DEFAULT_CONFIG_PATH;
30381
30414
  if (!(0, import_node_fs5.existsSync)(path2)) {
30382
30415
  return { ...DEFAULT_CONFIG };
30383
30416
  }
30384
30417
  try {
30385
- const raw = (0, import_node_fs5.readFileSync)(path2, "utf-8");
30386
- const parsed = import_toml.default.parse(raw);
30387
- return {
30388
- daemon: { ...DEFAULT_CONFIG.daemon, ...parsed.daemon },
30389
- api: { ...DEFAULT_CONFIG.api, ...parsed.api },
30390
- alerts: parsed.alerts || {},
30391
- modules: { ...DEFAULT_CONFIG.modules, ...parsed.modules },
30392
- remediation: parsed.remediation,
30393
- detection: parsed.detection,
30394
- cloud: parsed.cloud,
30395
- watchdog: parsed.watchdog,
30396
- update: parsed.update,
30397
- threat_feeds: parsed.threat_feeds,
30398
- privileged: parsed.privileged,
30399
- storage: parsed.storage,
30400
- // TOML's `[abuse-reporter]` parses to a hyphenated key; expose it under
30401
- // the JS-friendly name the rest of the daemon reads.
30402
- abuse_reporter: parsed["abuse-reporter"] ?? parsed.abuse_reporter,
30403
- license: parsed.license
30404
- };
30405
- } catch {
30418
+ return parseConfigText((0, import_node_fs5.readFileSync)(path2, "utf-8"));
30419
+ } catch (err) {
30420
+ onError?.(err);
30406
30421
  return { ...DEFAULT_CONFIG };
30407
30422
  }
30408
30423
  }
30424
+ function parseConfigText(raw) {
30425
+ const parsed = import_toml.default.parse(raw);
30426
+ return {
30427
+ daemon: { ...DEFAULT_CONFIG.daemon, ...parsed.daemon },
30428
+ api: { ...DEFAULT_CONFIG.api, ...parsed.api },
30429
+ alerts: parsed.alerts || {},
30430
+ modules: { ...DEFAULT_CONFIG.modules, ...parsed.modules },
30431
+ remediation: parsed.remediation,
30432
+ detection: parsed.detection,
30433
+ cloud: parsed.cloud,
30434
+ watchdog: parsed.watchdog,
30435
+ update: parsed.update,
30436
+ threat_feeds: parsed.threat_feeds,
30437
+ privileged: parsed.privileged,
30438
+ lightning: parsed.lightning,
30439
+ storage: parsed.storage,
30440
+ // TOML's `[abuse-reporter]` parses to a hyphenated key; expose it under
30441
+ // the JS-friendly name the rest of the daemon reads.
30442
+ abuse_reporter: parsed["abuse-reporter"] ?? parsed.abuse_reporter,
30443
+ license: parsed.license
30444
+ };
30445
+ }
30446
+ function loadDaemonConfig(configPath, lastGoodPath) {
30447
+ if (!(0, import_node_fs5.existsSync)(configPath)) return { config: { ...DEFAULT_CONFIG }, usedLastGood: false };
30448
+ let raw = "";
30449
+ try {
30450
+ raw = (0, import_node_fs5.readFileSync)(configPath, "utf-8");
30451
+ const config = parseConfigText(raw);
30452
+ try {
30453
+ (0, import_node_fs5.mkdirSync)((0, import_node_path4.dirname)(lastGoodPath), { recursive: true });
30454
+ (0, import_node_fs5.writeFileSync)(lastGoodPath, raw, { mode: 384 });
30455
+ } catch {
30456
+ }
30457
+ return { config, usedLastGood: false };
30458
+ } catch (err) {
30459
+ const error2 = `${configPath} is not valid TOML: ${err.message.split("\n")[0]}`;
30460
+ try {
30461
+ if ((0, import_node_fs5.existsSync)(lastGoodPath)) {
30462
+ return { config: parseConfigText((0, import_node_fs5.readFileSync)(lastGoodPath, "utf-8")), error: error2, usedLastGood: true };
30463
+ }
30464
+ } catch {
30465
+ }
30466
+ return { config: { ...DEFAULT_CONFIG }, error: error2, usedLastGood: false };
30467
+ }
30468
+ }
30409
30469
  function loadModuleConfigs(confDir) {
30410
30470
  const dir = confDir || DEFAULT_CONFDIR;
30411
30471
  const configs = /* @__PURE__ */ new Map();
@@ -41232,7 +41292,7 @@ var import_node_os12 = require("os");
41232
41292
  var import_node_fs26 = require("fs");
41233
41293
  var import_node_path22 = require("path");
41234
41294
  var import_node_child_process5 = require("child_process");
41235
- var import_node_net3 = require("net");
41295
+ var import_node_net4 = require("net");
41236
41296
  var API_URL5 = process.env.THREATCRUSH_API_URL || "https://threatcrush.com";
41237
41297
  var CONFIG_PATH3 = (0, import_node_path22.join)((0, import_node_os12.homedir)(), ".threatcrush", "config.json");
41238
41298
  function readConfig2() {
@@ -41361,7 +41421,7 @@ async function resolveServer(nameOrSlug, orgSlug) {
41361
41421
  var SSH_USER = /^[A-Za-z0-9_][A-Za-z0-9_.-]{0,63}$/;
41362
41422
  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
41423
  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)}`;
41424
+ if (!SSH_HOST.test(options.hostname) && (0, import_node_net4.isIP)(options.hostname) === 0) return `refusing unsafe hostname ${JSON.stringify(options.hostname)}`;
41365
41425
  if (!SSH_USER.test(options.username)) return `refusing unsafe ssh user ${JSON.stringify(options.username)}`;
41366
41426
  if (!Number.isInteger(options.port) || options.port < 1 || options.port > 65535) return `refusing port ${JSON.stringify(options.port)}`;
41367
41427
  return null;
@@ -41373,23 +41433,23 @@ function sshArgv(options) {
41373
41433
  return args;
41374
41434
  }
41375
41435
  async function sshConnect(options) {
41376
- const { hostname: hostname5, port, username, identity } = options;
41377
- if (!hostname5) {
41436
+ const { hostname: hostname6, port, username, identity } = options;
41437
+ if (!hostname6) {
41378
41438
  console.log(source_default.red(" No hostname available for this server.\n"));
41379
41439
  return;
41380
41440
  }
41381
41441
  const user = username || "root";
41382
- const problem = sshTargetError({ hostname: hostname5, username: user, port });
41442
+ const problem = sshTargetError({ hostname: hostname6, username: user, port });
41383
41443
  if (problem) {
41384
41444
  console.log(source_default.red(` ${problem}
41385
41445
  `));
41386
41446
  process.exitCode = 1;
41387
41447
  return;
41388
41448
  }
41389
- console.log(source_default.green(` Connecting to ${user}@${hostname5}:${port}...
41449
+ console.log(source_default.green(` Connecting to ${user}@${hostname6}:${port}...
41390
41450
  `));
41391
41451
  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 });
41452
+ const sshArgs = sshArgv({ hostname: hostname6, username: user, port, identity });
41393
41453
  const ssh = (0, import_node_child_process5.spawn)("ssh", sshArgs, { stdio: "inherit" });
41394
41454
  ssh.on("error", (err) => {
41395
41455
  console.log(source_default.red(`
@@ -41408,21 +41468,21 @@ async function sshConnect(options) {
41408
41468
  }
41409
41469
 
41410
41470
  // 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");
41471
+ var import_node_child_process18 = require("child_process");
41472
+ var import_node_fs48 = require("fs");
41473
+ var import_node_path37 = require("path");
41474
+ var import_node_fs49 = require("fs");
41415
41475
 
41416
41476
  // 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");
41477
+ var import_node_fs47 = require("fs");
41478
+ var import_node_child_process17 = require("child_process");
41479
+ var import_node_os14 = require("os");
41480
+ var import_node_path36 = require("path");
41421
41481
  var import_node_util4 = require("util");
41422
41482
  init_paths();
41423
41483
 
41424
41484
  // src/daemon/ipc-server.ts
41425
- var import_node_net4 = require("net");
41485
+ var import_node_net5 = require("net");
41426
41486
  var import_node_fs27 = require("fs");
41427
41487
  init_paths();
41428
41488
  init_control_token();
@@ -41436,6 +41496,10 @@ var EventBus = class extends import_node_events2.EventEmitter {
41436
41496
  this.emit("alert", event);
41437
41497
  }
41438
41498
  }
41499
+ /** A raw sshd line with a peer address; not an event, nothing is stored or uploaded. */
41500
+ sshdLine(line2) {
41501
+ this.emit("sshd", line2);
41502
+ }
41439
41503
  announceModule(name, status, detail) {
41440
41504
  this.emit("module", { name, status, detail });
41441
41505
  }
@@ -41484,7 +41548,7 @@ var IpcServer = class {
41484
41548
  }
41485
41549
  }
41486
41550
  return new Promise((resolve8, reject) => {
41487
- this.server = (0, import_node_net4.createServer)((sock) => this.handleClient(sock));
41551
+ this.server = (0, import_node_net5.createServer)((sock) => this.handleClient(sock));
41488
41552
  this.server.on("error", reject);
41489
41553
  this.server.listen(PATHS.socket, () => {
41490
41554
  const nodeFs = require("fs");
@@ -41803,9 +41867,14 @@ var LogWatcher = class {
41803
41867
  if (parsed.source === "auth") {
41804
41868
  const entry = parseAuthLog(line2);
41805
41869
  if (!entry) return;
41870
+ if (isSshdProcess(entry.fields.process)) {
41871
+ const peer = sshdPeerIp(entry.fields.message);
41872
+ if (peer) this.bus.sshdLine?.({ timestamp: entry.timestamp, message: entry.fields.message, ip: peer, raw: line2 });
41873
+ }
41806
41874
  const verdict = classifySshAuth(entry);
41807
41875
  if (!verdict) return;
41808
41876
  ({ severity, message, source_ip: sourceIp } = verdict);
41877
+ if (verdict.details) Object.assign(details, verdict.details);
41809
41878
  } else if (parsed.source === "nginx") {
41810
41879
  const entry = parseNginxLog(line2);
41811
41880
  if (!entry) return;
@@ -41881,9 +41950,17 @@ function sshEventFromJournal(entry) {
41881
41950
  category: "auth",
41882
41951
  severity: verdict.severity,
41883
41952
  message: verdict.message,
41884
- source_ip: verdict.source_ip
41953
+ source_ip: verdict.source_ip,
41954
+ ...verdict.details ? { details: verdict.details } : {}
41885
41955
  };
41886
41956
  }
41957
+ function sshdLineFromJournal(entry) {
41958
+ if (!isSshdRecord(entry) || typeof entry.MESSAGE !== "string") return null;
41959
+ const ip = sshdPeerIp(entry.MESSAGE);
41960
+ if (!ip) return null;
41961
+ const timestamp = realtimeToDate(entry.__REALTIME_TIMESTAMP) || /* @__PURE__ */ new Date();
41962
+ return { timestamp, message: entry.MESSAGE, ip, raw: entry.MESSAGE };
41963
+ }
41887
41964
  var JournalWatcher = class _JournalWatcher {
41888
41965
  constructor(bus2) {
41889
41966
  this.bus = bus2;
@@ -41950,6 +42027,8 @@ var JournalWatcher = class _JournalWatcher {
41950
42027
  child.stdout.setEncoding("utf-8");
41951
42028
  child.stdout.on("data", (chunk2) => {
41952
42029
  this.sshdBuffer = this.drain(this.sshdBuffer + chunk2, (entry) => {
42030
+ const line2 = sshdLineFromJournal(entry);
42031
+ if (line2) this.bus.sshdLine?.(line2);
41953
42032
  const event = sshEventFromJournal(entry);
41954
42033
  if (event) this.emit(event);
41955
42034
  });
@@ -42304,12 +42383,12 @@ var import_node_readline3 = require("readline");
42304
42383
  // src/core/threat-feeds/index.ts
42305
42384
  var import_node_fs31 = require("fs");
42306
42385
  var import_node_path23 = require("path");
42307
- var import_node_net6 = require("net");
42386
+ var import_node_net7 = require("net");
42308
42387
 
42309
42388
  // src/daemon/firewall/protected.ts
42310
42389
  var import_node_child_process8 = require("child_process");
42311
42390
  var import_node_fs30 = require("fs");
42312
- var import_node_net5 = require("net");
42391
+ var import_node_net6 = require("net");
42313
42392
  var DEFAULT_PROTECTED = [
42314
42393
  "127.0.0.0/8",
42315
42394
  "::1/128",
@@ -42353,7 +42432,7 @@ var SHARED_INFRASTRUCTURE = [
42353
42432
  "208.67.220.220/32"
42354
42433
  ];
42355
42434
  function ipToBytes(ip) {
42356
- const version = (0, import_node_net5.isIP)(ip);
42435
+ const version = (0, import_node_net6.isIP)(ip);
42357
42436
  if (version === 4) return v4ToBytes(ip);
42358
42437
  if (version === 6) return v6ToBytes(ip);
42359
42438
  return null;
@@ -42431,7 +42510,7 @@ function currentSshClient(env3 = process.env) {
42431
42510
  const source = env3.SSH_CLIENT || env3.SSH_CONNECTION;
42432
42511
  if (!source) return null;
42433
42512
  const ip = source.trim().split(/\s+/)[0];
42434
- return ip && (0, import_node_net5.isIP)(ip) ? ip : null;
42513
+ return ip && (0, import_node_net6.isIP)(ip) ? ip : null;
42435
42514
  }
42436
42515
  function establishedSshPeers() {
42437
42516
  const peers = /* @__PURE__ */ new Set();
@@ -42447,7 +42526,7 @@ function establishedSshPeers() {
42447
42526
  const peer = parts[4];
42448
42527
  if (!peer) continue;
42449
42528
  const ip = peer.slice(0, peer.lastIndexOf(":")).replace(/^\[|\]$/g, "");
42450
- if (ip && (0, import_node_net5.isIP)(ip)) peers.add(ip);
42529
+ if (ip && (0, import_node_net6.isIP)(ip)) peers.add(ip);
42451
42530
  }
42452
42531
  } catch {
42453
42532
  }
@@ -42456,7 +42535,7 @@ function establishedSshPeers() {
42456
42535
  function sshClientFromEnviron(environ) {
42457
42536
  for (const entry of environ.split("\0")) {
42458
42537
  const m = /^SSH_(?:CONNECTION|CLIENT)=(\S+)/.exec(entry);
42459
- if (m && (0, import_node_net5.isIP)(m[1])) return m[1];
42538
+ if (m && (0, import_node_net6.isIP)(m[1])) return m[1];
42460
42539
  }
42461
42540
  return null;
42462
42541
  }
@@ -42482,7 +42561,7 @@ function parseKeyLogins(text, skip = () => false) {
42482
42561
  const out = /* @__PURE__ */ new Map();
42483
42562
  for (const line2 of text.split("\n")) {
42484
42563
  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;
42564
+ if (!m || !(0, import_node_net6.isIP)(m[2])) continue;
42486
42565
  if (m[3] && skip(m[3])) continue;
42487
42566
  const at = Math.round(Number(m[1]) * 1e3);
42488
42567
  if (at > (out.get(m[2]) ?? 0)) out.set(m[2], at);
@@ -42499,7 +42578,7 @@ function defaultGateways() {
42499
42578
  const out = (0, import_node_child_process8.execFileSync)("ip", args, { encoding: "utf-8", stdio: ["ignore", "pipe", "ignore"] });
42500
42579
  for (const line2 of out.split("\n")) {
42501
42580
  const match = line2.match(/\bvia\s+(\S+)/);
42502
- if (match && (0, import_node_net5.isIP)(match[1])) found.add(match[1]);
42581
+ if (match && (0, import_node_net6.isIP)(match[1])) found.add(match[1]);
42503
42582
  }
42504
42583
  } catch {
42505
42584
  }
@@ -42612,26 +42691,26 @@ function parseIpList(text, feed) {
42612
42691
  const out = /* @__PURE__ */ new Map();
42613
42692
  for (const line2 of text.split("\n")) {
42614
42693
  const ip = line2.trim();
42615
- if (ip && !ip.startsWith("#") && (0, import_node_net6.isIP)(ip)) out.set(ip, { malware: "unknown", threat: "botnet_cc", feed });
42694
+ if (ip && !ip.startsWith("#") && (0, import_node_net7.isIP)(ip)) out.set(ip, { malware: "unknown", threat: "botnet_cc", feed });
42616
42695
  }
42617
42696
  return out;
42618
42697
  }
42619
42698
  function stripPort(value) {
42620
42699
  const v6 = /^\[([^\]]+)\]:\d+$/.exec(value);
42621
42700
  const ip = v6 ? v6[1] : value.replace(/:\d+$/, "");
42622
- return (0, import_node_net6.isIP)(ip) ? ip : null;
42701
+ return (0, import_node_net7.isIP)(ip) ? ip : null;
42623
42702
  }
42624
42703
  function normalizeDomain(value) {
42625
42704
  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;
42705
+ if (!d || d === "localhost" || (0, import_node_net7.isIP)(d) || !/^[a-z0-9_.-]+\.[a-z0-9-]{2,}$/.test(d)) return null;
42627
42706
  return d;
42628
42707
  }
42629
42708
  function allowedDomain(domain, allow) {
42630
42709
  return allow.some((a) => domain === a || domain.endsWith(`.${a}`));
42631
42710
  }
42632
42711
  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());
42712
+ const neverIps = [...DEFAULT_PROTECTED, ...SHARED_RANGES, ...allow.filter((a) => (0, import_node_net7.isIP)(a.split("/")[0]))];
42713
+ const allowDomains = allow.filter((a) => !(0, import_node_net7.isIP)(a.split("/")[0])).map((a) => a.toLowerCase());
42635
42714
  const ips = {};
42636
42715
  const domains = {};
42637
42716
  let skipped = 0;
@@ -43453,11 +43532,55 @@ function pagerdutyChannel(config) {
43453
43532
  };
43454
43533
  }
43455
43534
 
43535
+ // src/daemon/alerts/smshub.ts
43536
+ var import_node_os13 = require("os");
43537
+ var SEVERITY_RANK6 = { info: 0, low: 1, medium: 2, high: 3, critical: 4 };
43538
+ var DEDUPE_MS = 10 * 6e4;
43539
+ var MAX_PER_HOUR = 6;
43540
+ function smshubText(event, host = (0, import_node_os13.hostname)()) {
43541
+ const evidence = event.details?.evidence?.message;
43542
+ const text = `ThreatCrush ${event.severity.toUpperCase()} on ${host}: ${event.message}${evidence && !event.message.includes(evidence) ? ` | ${evidence}` : ""}`;
43543
+ return text.replace(/\s+/g, " ").slice(0, 600);
43544
+ }
43545
+ function smshubChannel(config, opts = {}) {
43546
+ const sent = /* @__PURE__ */ new Map();
43547
+ const recent = [];
43548
+ const now = opts.now ?? Date.now;
43549
+ const doFetch = opts.fetchImpl ?? fetch;
43550
+ return async (event) => {
43551
+ const key = config.api_key || (config.api_key_env ? process.env[config.api_key_env] : void 0) || process.env.SMSHUB_ALERT_API_KEY;
43552
+ if (!key) return;
43553
+ if ((SEVERITY_RANK6[event.severity] ?? 0) < (SEVERITY_RANK6[config.min_severity ?? "critical"] ?? 4)) return;
43554
+ if (config.fallback_only !== false && opts.cloudHealthy?.()) return;
43555
+ const message = smshubText(event);
43556
+ const at = now();
43557
+ const dedupe2 = `${event.details?.rule_id ?? event.module}|${event.source_ip ?? ""}|${event.details?.fingerprint ?? ""}`;
43558
+ if (at - (sent.get(dedupe2) ?? 0) < DEDUPE_MS) return;
43559
+ while (recent.length && recent[0] < at - 36e5) recent.shift();
43560
+ if (recent.length >= MAX_PER_HOUR) return;
43561
+ sent.set(dedupe2, at);
43562
+ recent.push(at);
43563
+ const base = (config.url || "https://smshub.dev").replace(/\/$/, "");
43564
+ try {
43565
+ const res = await doFetch(`${base}/api/v1/alerts`, {
43566
+ method: "POST",
43567
+ headers: { "X-API-Key": key, "Content-Type": "application/json", "User-Agent": "threatcrush-daemon" },
43568
+ body: JSON.stringify({ message, severity: event.severity === "critical" ? "critical" : "warning", ...config.to ? { to: config.to } : {} }),
43569
+ signal: AbortSignal.timeout(15e3)
43570
+ });
43571
+ opts.log?.(`[alerts] smshub ${res.ok ? "paged" : `failed HTTP ${res.status}`}: ${message.slice(0, 160)}`);
43572
+ } catch (err) {
43573
+ opts.log?.(`[alerts] smshub failed: ${err.message}`);
43574
+ }
43575
+ };
43576
+ }
43577
+
43456
43578
  // src/daemon/alerts/index.ts
43457
43579
  var AlertDispatcher = class {
43458
- constructor(bus2, config) {
43580
+ constructor(bus2, config, hooks = {}) {
43459
43581
  this.bus = bus2;
43460
43582
  this.config = config;
43583
+ this.hooks = hooks;
43461
43584
  this.bindChannels();
43462
43585
  bus2.on("alert", (event) => {
43463
43586
  void this.dispatch(event);
@@ -43465,6 +43588,7 @@ var AlertDispatcher = class {
43465
43588
  }
43466
43589
  bus;
43467
43590
  config;
43591
+ hooks;
43468
43592
  channels = [];
43469
43593
  rateLimits = /* @__PURE__ */ new Map();
43470
43594
  bindChannels() {
@@ -43484,6 +43608,9 @@ var AlertDispatcher = class {
43484
43608
  if (name === "discord" && typeof cfg.webhook_url === "string") {
43485
43609
  this.channels.push(discordChannel(cfg));
43486
43610
  }
43611
+ if (name === "smshub") {
43612
+ this.channels.push(smshubChannel(cfg, this.hooks));
43613
+ }
43487
43614
  if (name === "pagerduty" && typeof cfg.routing_key === "string") {
43488
43615
  this.channels.push(pagerdutyChannel(cfg));
43489
43616
  }
@@ -43531,13 +43658,13 @@ function slackChannel(webhookUrl) {
43531
43658
  // src/daemon/workers/runs-worker.ts
43532
43659
  var import_promises2 = require("dns/promises");
43533
43660
  var import_node_fs34 = require("fs");
43534
- var import_node_net8 = require("net");
43661
+ var import_node_net9 = require("net");
43535
43662
  var import_node_path25 = require("path");
43536
43663
  init_cli_config();
43537
43664
 
43538
43665
  // src/core/cloud-events.ts
43539
43666
  var import_node_crypto7 = require("crypto");
43540
- var import_node_net7 = require("net");
43667
+ var import_node_net8 = require("net");
43541
43668
  init_cli_config();
43542
43669
  function currentLink() {
43543
43670
  if (!hasSession()) return null;
@@ -43545,7 +43672,7 @@ function currentLink() {
43545
43672
  if (!cfg.server_id || !cfg.server_org_id) return null;
43546
43673
  return { serverId: cfg.server_id, orgId: cfg.server_org_id };
43547
43674
  }
43548
- var SEVERITY_RANK6 = {
43675
+ var SEVERITY_RANK7 = {
43549
43676
  info: 0,
43550
43677
  low: 1,
43551
43678
  medium: 2,
@@ -43605,7 +43732,7 @@ function detectionEvent(serverId, event) {
43605
43732
  title: title.slice(0, MAX_TITLE_CHARS) || event.module,
43606
43733
  rule_id: str2(rule_id) ?? event.module,
43607
43734
  description: str2(description),
43608
- source_ip: event.source_ip && (0, import_node_net7.isIP)(event.source_ip) ? event.source_ip : void 0,
43735
+ source_ip: event.source_ip && (0, import_node_net8.isIP)(event.source_ip) ? event.source_ip : void 0,
43609
43736
  username: str2(username) ?? str2(user),
43610
43737
  raw_metadata: trimMetadata({ module: event.module, category: event.category, ...rest }),
43611
43738
  detected_at: event.timestamp.toISOString()
@@ -43662,7 +43789,7 @@ var NOT_PUBLIC = [
43662
43789
  "ff00::/8"
43663
43790
  ];
43664
43791
  function isPublicTarget(ip) {
43665
- return (0, import_node_net8.isIP)(ip) !== 0 && !isProtected(ip, NOT_PUBLIC);
43792
+ return (0, import_node_net9.isIP)(ip) !== 0 && !isProtected(ip, NOT_PUBLIC);
43666
43793
  }
43667
43794
  async function pentestTargetError(rawUrl, resolveHost = async (h) => (await (0, import_promises2.lookup)(h, { all: true })).map((a) => a.address)) {
43668
43795
  let url;
@@ -43675,7 +43802,7 @@ async function pentestTargetError(rawUrl, resolveHost = async (h) => (await (0,
43675
43802
  const host = url.hostname.replace(/^\[|\]$/g, "");
43676
43803
  let addresses;
43677
43804
  try {
43678
- addresses = (0, import_node_net8.isIP)(host) ? [host] : await resolveHost(host);
43805
+ addresses = (0, import_node_net9.isIP)(host) ? [host] : await resolveHost(host);
43679
43806
  } catch (err) {
43680
43807
  return `cannot resolve ${host}: ${err.message}`;
43681
43808
  }
@@ -44002,6 +44129,7 @@ var CloudSync = class {
44002
44129
  retryAt = 0;
44003
44130
  link = null;
44004
44131
  lastProblem = "";
44132
+ lastOkAt = 0;
44005
44133
  onEvent = (event) => this.capture(event);
44006
44134
  start() {
44007
44135
  this.link = currentLink();
@@ -44034,6 +44162,10 @@ var CloudSync = class {
44034
44162
  get queued() {
44035
44163
  return this.spool.size;
44036
44164
  }
44165
+ /** Linked, and the dashboard accepted an upload or heartbeat in the last 3 minutes. */
44166
+ get healthy() {
44167
+ return !!this.link && !this.lastProblem && Date.now() - this.lastOkAt < 18e4;
44168
+ }
44037
44169
  /** Queue hardening results for upload (the CLI posts its own directly). */
44038
44170
  enqueueFindings(results) {
44039
44171
  const link = this.refreshLink();
@@ -44058,7 +44190,7 @@ var CloudSync = class {
44058
44190
  let out = null;
44059
44191
  if (event.module === "firewall-rules") {
44060
44192
  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]) {
44193
+ } 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
44194
  out = detectionEvent(link.serverId, event);
44063
44195
  }
44064
44196
  if (!out) return;
@@ -44106,6 +44238,7 @@ var CloudSync = class {
44106
44238
  this.backoffMs = 0;
44107
44239
  this.retryAt = 0;
44108
44240
  this.lastProblem = "";
44241
+ this.lastOkAt = Date.now();
44109
44242
  return "sent";
44110
44243
  }
44111
44244
  if (res.status === 401) {
@@ -44150,6 +44283,7 @@ var CloudSync = class {
44150
44283
  };
44151
44284
  try {
44152
44285
  const res = await cloudFetch("/api/ingest", { method: "POST", body: JSON.stringify({ events: [event] }) });
44286
+ if (res.ok) this.lastOkAt = Date.now();
44153
44287
  if (res.ok && this.retryAt > 0) {
44154
44288
  this.retryAt = 0;
44155
44289
  void this.flush();
@@ -44173,7 +44307,7 @@ var CloudSync = class {
44173
44307
  var import_node_crypto8 = require("crypto");
44174
44308
 
44175
44309
  // src/daemon/workers/abuse-evidence.ts
44176
- var import_node_net9 = require("net");
44310
+ var import_node_net10 = require("net");
44177
44311
  var NEVER_REPORT_RANGES = [
44178
44312
  ...DEFAULT_PROTECTED,
44179
44313
  "100.64.0.0/10",
@@ -44249,7 +44383,7 @@ function summarizeEvidence(events) {
44249
44383
  };
44250
44384
  }
44251
44385
  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" };
44386
+ if ((0, import_node_net10.isIP)(ip) === 0) return { reportable: false, reason: "not an IP address" };
44253
44387
  if (isProtected(ip, config.neverReport)) {
44254
44388
  return { reportable: false, reason: "address is in a never-report range (private/CGNAT/reserved/allowlisted)" };
44255
44389
  }
@@ -44600,15 +44734,15 @@ var AbuseReporter = class {
44600
44734
  };
44601
44735
 
44602
44736
  // src/daemon/workers/remediation-consumer.ts
44603
- var import_node_net11 = require("net");
44737
+ var import_node_net12 = require("net");
44604
44738
  init_cli_config();
44605
44739
 
44606
44740
  // src/daemon/workers/allowlist-sync.ts
44607
- var import_node_net10 = require("net");
44741
+ var import_node_net11 = require("net");
44608
44742
  init_cli_config();
44609
44743
  function isAddressOrCidr(value) {
44610
44744
  const [network, prefix, extra] = value.split("/");
44611
- const family = (0, import_node_net10.isIP)(network);
44745
+ const family = (0, import_node_net11.isIP)(network);
44612
44746
  if (family === 0 || extra !== void 0) return false;
44613
44747
  if (prefix === void 0) return true;
44614
44748
  if (!/^\d{1,3}$/.test(prefix)) return false;
@@ -44619,7 +44753,7 @@ function isCloudAllowEntry(value) {
44619
44753
  if (!isAddressOrCidr(value)) return false;
44620
44754
  const [network, prefix] = value.split("/");
44621
44755
  if (prefix === void 0) return true;
44622
- return Number(prefix) >= CLOUD_MIN_PREFIX[(0, import_node_net10.isIP)(network)];
44756
+ return Number(prefix) >= CLOUD_MIN_PREFIX[(0, import_node_net11.isIP)(network)];
44623
44757
  }
44624
44758
  var AllowlistSync = class {
44625
44759
  constructor(manager, opts) {
@@ -44642,6 +44776,17 @@ var AllowlistSync = class {
44642
44776
  async sync() {
44643
44777
  const link = currentLink();
44644
44778
  if (!link) return;
44779
+ if (this.opts.onOrgSettings) {
44780
+ try {
44781
+ const res = await cloudFetch(`/api/orgs/${link.orgId}`);
44782
+ if (res.ok) {
44783
+ const data = await res.json();
44784
+ const v = data.organization?.block_tor_ssh;
44785
+ if (typeof v === "boolean") this.opts.onOrgSettings({ block_tor_ssh: v });
44786
+ }
44787
+ } catch {
44788
+ }
44789
+ }
44645
44790
  let entries;
44646
44791
  try {
44647
44792
  const res = await cloudFetch(`/api/orgs/${link.orgId}/allowlists`);
@@ -44657,7 +44802,7 @@ var AllowlistSync = class {
44657
44802
  if (entry.type !== "ip" && entry.type !== "cidr") continue;
44658
44803
  const value = String(entry.value ?? "").trim();
44659
44804
  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])]})`);
44805
+ 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
44806
  }
44662
44807
  const added2 = [];
44663
44808
  const protectedNow = new Set(this.manager.getProtected());
@@ -44765,7 +44910,7 @@ var RemediationConsumer = class {
44765
44910
  try {
44766
44911
  switch (action.action_type) {
44767
44912
  case "block": {
44768
- if ((0, import_node_net11.isIP)(target) === 0) return failed(`not an IP address: ${target}`);
44913
+ if ((0, import_node_net12.isIP)(target) === 0) return failed(`not an IP address: ${target}`);
44769
44914
  let ttlSeconds = this.manager.status().max_ban_seconds;
44770
44915
  if (action.expires_at) {
44771
44916
  const until = Date.parse(action.expires_at);
@@ -44784,7 +44929,7 @@ var RemediationConsumer = class {
44784
44929
  return { status: "executed", dry_run: result.entry?.dry_run === true, executed_at };
44785
44930
  }
44786
44931
  case "unblock": {
44787
- if ((0, import_node_net11.isIP)(target) === 0) return failed(`not an IP address: ${target}`);
44932
+ if ((0, import_node_net12.isIP)(target) === 0) return failed(`not an IP address: ${target}`);
44788
44933
  const wasBanned = this.manager.getBlocklist().some((b) => b.ip === target);
44789
44934
  const result = await this.manager.unban(target, {
44790
44935
  forget: true,
@@ -45089,7 +45234,7 @@ var AutoUpdate = class {
45089
45234
  var import_node_child_process11 = require("child_process");
45090
45235
  var import_node_fs38 = require("fs");
45091
45236
  var import_node_path29 = require("path");
45092
- var import_node_net12 = require("net");
45237
+ var import_node_net13 = require("net");
45093
45238
  init_backoff();
45094
45239
  var EGRESS_TABLE = "threatcrush_egress";
45095
45240
  var DEFAULT_REFRESH_MS = 36e5;
@@ -45108,8 +45253,8 @@ function threatFeedSettings(section) {
45108
45253
  };
45109
45254
  }
45110
45255
  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);
45256
+ const v4 = ips.filter((ip) => (0, import_node_net13.isIP)(ip) === 4);
45257
+ const v6 = ips.filter((ip) => (0, import_node_net13.isIP)(ip) === 6);
45113
45258
  const set = (name, type, items) => ` set ${name} { type ${type};${items.length ? ` elements = { ${items.join(", ")} }` : ""} }`;
45114
45259
  const chain = (name, hook) => [
45115
45260
  ` chain ${name} {`,
@@ -45134,7 +45279,7 @@ function splitAddr(addr) {
45134
45279
  const m = /^\[?(.+?)\]?:(\d+|\*)$/.exec(addr);
45135
45280
  if (!m) return null;
45136
45281
  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;
45282
+ return (0, import_node_net13.isIP)(ip) ? { ip, port: m[2] === "*" ? 0 : Number(m[2]) } : null;
45138
45283
  }
45139
45284
  function parseSs(text) {
45140
45285
  const out = [];
@@ -45522,7 +45667,42 @@ function parseSudoMessage(message) {
45522
45667
 
45523
45668
  // src/daemon/workers/privilege-watch.ts
45524
45669
  function privilegeSettings(section) {
45525
- return { enabled: section?.enabled !== false, geo: section?.geo !== false, pollMs: 6e4 };
45670
+ return {
45671
+ enabled: section?.enabled !== false,
45672
+ geo: section?.geo !== false,
45673
+ pollMs: 6e4,
45674
+ expectedKeys: Array.isArray(section?.expected_keys) ? section.expected_keys.map(String).filter(Boolean) : [],
45675
+ watchFiles: true
45676
+ };
45677
+ }
45678
+ function keyIsExpected(fingerprint, comment, expected) {
45679
+ return expected.some((pattern) => {
45680
+ if (pattern.startsWith("SHA256:")) return pattern === fingerprint;
45681
+ const re = new RegExp(`^${pattern.split("*").map((p) => p.replace(/[.+?^${}()|[\]\\]/g, "\\$&")).join(".*")}$`, "i");
45682
+ return re.test(comment);
45683
+ });
45684
+ }
45685
+ var SELFTEST_KEY_COMMENT = "threatcrush-selftest";
45686
+ function classifyKeyAddition(change, expected) {
45687
+ if (change.details.rule_id !== "priv-authorized-key-added") return change;
45688
+ const fp = String(change.details.fingerprint ?? "");
45689
+ const comment = String(change.details.comment ?? "");
45690
+ const account = String(change.details.account ?? "?");
45691
+ if (comment.includes(SELFTEST_KEY_COMMENT)) {
45692
+ return {
45693
+ severity: "critical",
45694
+ message: `[TEST] ThreatCrush self-test: new SSH key for ${account} detected (${fp}, ${comment}). This is a test, nothing is wrong.`,
45695
+ details: { ...change.details, rule_id: "priv-authorized-key-selftest", selftest: true }
45696
+ };
45697
+ }
45698
+ if (keyIsExpected(fp, comment, expected)) {
45699
+ return { ...change, severity: "high", details: { ...change.details, expected: true } };
45700
+ }
45701
+ return {
45702
+ severity: "critical",
45703
+ 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`,
45704
+ details: { ...change.details, expected: false }
45705
+ };
45526
45706
  }
45527
45707
  var COUNTRY_NAMES = new Intl.DisplayNames(["en"], { type: "region" });
45528
45708
  function countryName(code) {
@@ -45620,6 +45800,8 @@ var PrivilegeWatch = class {
45620
45800
  run;
45621
45801
  now;
45622
45802
  warnedUnreadable = false;
45803
+ watchers = /* @__PURE__ */ new Map();
45804
+ debounce = null;
45623
45805
  onEvent = (event) => {
45624
45806
  void this.checkLogin(event);
45625
45807
  };
@@ -45634,9 +45816,11 @@ var PrivilegeWatch = class {
45634
45816
  this.opts.bus.on("event", this.onEvent);
45635
45817
  void this.backfillLogins();
45636
45818
  }
45819
+ if (this.opts.settings.watchFiles) this.watchKeyDirs();
45637
45820
  const timer = setInterval(() => {
45638
45821
  this.checkSnapshot();
45639
45822
  this.readSudoLedger();
45823
+ if (this.opts.settings.watchFiles) this.watchKeyDirs();
45640
45824
  }, this.opts.settings.pollMs);
45641
45825
  timer.unref?.();
45642
45826
  this.timers.push(timer);
@@ -45644,8 +45828,55 @@ var PrivilegeWatch = class {
45644
45828
  stop() {
45645
45829
  for (const t of this.timers) clearInterval(t);
45646
45830
  this.timers = [];
45831
+ for (const w of this.watchers.values()) {
45832
+ try {
45833
+ w.close();
45834
+ } catch {
45835
+ }
45836
+ }
45837
+ this.watchers.clear();
45838
+ if (this.debounce) clearTimeout(this.debounce);
45647
45839
  this.opts.bus.off("event", this.onEvent);
45648
45840
  }
45841
+ /**
45842
+ * inotify on every login account's ~/.ssh (and /root/.ssh): a write there
45843
+ * re-checks the snapshot within a second, not at the next minute's poll.
45844
+ * Re-run each poll so a directory created later is picked up.
45845
+ */
45846
+ watchKeyDirs() {
45847
+ const dirs = /* @__PURE__ */ new Set();
45848
+ for (const line2 of (this.io.readFile("/etc/passwd") ?? "").split("\n")) {
45849
+ const f = line2.split(":");
45850
+ if (f.length < 7) continue;
45851
+ const uid = Number(f[2]);
45852
+ const home = f[5];
45853
+ if (!home || home === "/" || uid !== 0 && /(nologin|\/false)$/.test(f[6].trim())) continue;
45854
+ dirs.add(`${home.replace(/\/$/, "")}/.ssh`);
45855
+ }
45856
+ for (const dir of dirs) {
45857
+ if (this.watchers.has(dir) || !this.io.exists(dir)) continue;
45858
+ try {
45859
+ const w = (0, import_node_fs39.watch)(dir, { persistent: false }, (_type2, name) => {
45860
+ if (name && !String(name).startsWith("authorized_keys")) return;
45861
+ if (this.debounce) clearTimeout(this.debounce);
45862
+ this.debounce = setTimeout(() => {
45863
+ this.debounce = null;
45864
+ this.checkSnapshot();
45865
+ }, 750);
45866
+ this.debounce.unref?.();
45867
+ });
45868
+ w.on("error", () => {
45869
+ try {
45870
+ w.close();
45871
+ } catch {
45872
+ }
45873
+ this.watchers.delete(dir);
45874
+ });
45875
+ this.watchers.set(dir, w);
45876
+ } catch {
45877
+ }
45878
+ }
45879
+ }
45649
45880
  emit(severity, message, details) {
45650
45881
  const event = { timestamp: this.now(), module: "privileged-access", category: "auth", severity, message, details };
45651
45882
  try {
@@ -45665,7 +45896,16 @@ var PrivilegeWatch = class {
45665
45896
  const keys = Object.values(next.keys).reduce((n, k) => n + Object.keys(k).length, 0);
45666
45897
  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
45898
  } else {
45668
- for (const change of diffSnapshots(prev, next)) this.emit(change.severity, change.message, change.details);
45899
+ for (const raw of diffSnapshots(prev, next)) {
45900
+ const change = classifyKeyAddition(raw, this.opts.settings.expectedKeys ?? []);
45901
+ if (change.details.rule_id === "priv-authorized-key-added" || change.details.rule_id === "priv-authorized-key-selftest") {
45902
+ this.opts.log(`[privileged] ${change.severity.toUpperCase()} ${change.message}`);
45903
+ }
45904
+ this.emit(change.severity, change.message, {
45905
+ ...change.details,
45906
+ evidence: { at: this.now().toISOString(), module: "privileged-access", message: change.message.slice(0, 500) }
45907
+ });
45908
+ }
45669
45909
  }
45670
45910
  try {
45671
45911
  writeJson(this.opts.snapshotPath, next);
@@ -45779,6 +46019,636 @@ var PrivilegeWatch = class {
45779
46019
  }
45780
46020
  };
45781
46021
 
46022
+ // src/daemon/workers/ssh-intrusion.ts
46023
+ var import_node_fs40 = require("fs");
46024
+ var import_node_path31 = require("path");
46025
+ var import_node_child_process13 = require("child_process");
46026
+
46027
+ // src/core/asn.ts
46028
+ var import_node_dns = require("dns");
46029
+ var import_node_net14 = require("net");
46030
+ var CI_ASNS = /* @__PURE__ */ new Set([8075, 36459, 8068, 8069, 12076]);
46031
+ var HOSTING_ASNS = /* @__PURE__ */ new Set([
46032
+ 15169,
46033
+ 396982,
46034
+ 19527,
46035
+ // Google, Google Cloud
46036
+ 16509,
46037
+ 14618,
46038
+ // Amazon / AWS
46039
+ 16276,
46040
+ // OVH
46041
+ 24940,
46042
+ 213230,
46043
+ // Hetzner
46044
+ 14061,
46045
+ // DigitalOcean
46046
+ 63949,
46047
+ // Linode / Akamai
46048
+ 20473,
46049
+ // Vultr (Choopa)
46050
+ 12876,
46051
+ // Scaleway
46052
+ 51167,
46053
+ // Contabo
46054
+ 31898,
46055
+ // Oracle Cloud
46056
+ 45102,
46057
+ // Alibaba
46058
+ 132203,
46059
+ 45090,
46060
+ // Tencent
46061
+ 36352,
46062
+ // ColoCrossing
46063
+ 53667,
46064
+ // FranTech / BuyVM
46065
+ 197540,
46066
+ // netcup
46067
+ 9009,
46068
+ // M247
46069
+ 60068,
46070
+ // Datacamp / CDN77
46071
+ 212238,
46072
+ // Datacamp
46073
+ 202425,
46074
+ // IP Volume
46075
+ 210644,
46076
+ // Aeza
46077
+ 49981,
46078
+ // WorldStream
46079
+ 62240,
46080
+ // Clouvider
46081
+ 136907,
46082
+ // Huawei Cloud
46083
+ 8100,
46084
+ // QuadraNet
46085
+ 46606,
46086
+ // Unified Layer
46087
+ 29802,
46088
+ // HVC
46089
+ 40021,
46090
+ // Contabo US / Nubes
46091
+ 398324,
46092
+ 399629
46093
+ // Censys and friends
46094
+ ]);
46095
+ var VPN_ASNS = /* @__PURE__ */ new Set([
46096
+ 9009,
46097
+ // M247 (most commercial VPN exits)
46098
+ 212238,
46099
+ 60068,
46100
+ // Datacamp (NordVPN, Proton, ...)
46101
+ 209854,
46102
+ // Surfshark
46103
+ 39351,
46104
+ // 31173 Services (Mullvad)
46105
+ 136787,
46106
+ // TEFINCOM (NordVPN)
46107
+ 147049
46108
+ // PacketHub (NordVPN)
46109
+ ]);
46110
+ 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;
46111
+ var VPN_NAME = /\bvpn\b|proton|mullvad|nordvpn|surfshark|expressvpn|private internet access|tefincom|packethub|31173 services|anonymi[sz]|privacy|proxy/i;
46112
+ function classifyAsn(info2) {
46113
+ if (!info2) return "unknown";
46114
+ if (CI_ASNS.has(info2.asn)) return "ci";
46115
+ if (VPN_ASNS.has(info2.asn) || VPN_NAME.test(info2.name)) return "vpn";
46116
+ if (HOSTING_ASNS.has(info2.asn) || HOSTING_NAME.test(info2.name)) return "hosting";
46117
+ return "unknown";
46118
+ }
46119
+ function cymruOriginName(ip) {
46120
+ const bytes = ipToBytes(ip);
46121
+ if (!bytes) return null;
46122
+ if (bytes.length === 4) return `${[...bytes].reverse().join(".")}.origin.asn.cymru.com`;
46123
+ const nibbles = [];
46124
+ for (const b of bytes) nibbles.push((b >> 4).toString(16), (b & 15).toString(16));
46125
+ return `${nibbles.reverse().join(".")}.origin6.asn.cymru.com`;
46126
+ }
46127
+ function parseCymruOrigin(txt) {
46128
+ const fields = txt.split("|").map((f) => f.trim());
46129
+ const asn = Number(fields[0]?.split(/\s+/)[0]);
46130
+ if (!Number.isInteger(asn) || asn <= 0) return null;
46131
+ return { asn, prefix: fields[1] || void 0, country: /^[A-Z]{2}$/.test(fields[2] ?? "") ? fields[2] : void 0 };
46132
+ }
46133
+ function parseCymruName(txt) {
46134
+ const fields = txt.split("|").map((f) => f.trim());
46135
+ return (fields[4] ?? "").slice(0, 120);
46136
+ }
46137
+ var AsnLookup = class {
46138
+ constructor(resolveTxt = (name) => import_node_dns.promises.resolveTxt(name), ttlMs = 24 * 36e5, now = Date.now) {
46139
+ this.resolveTxt = resolveTxt;
46140
+ this.ttlMs = ttlMs;
46141
+ this.now = now;
46142
+ }
46143
+ resolveTxt;
46144
+ ttlMs;
46145
+ now;
46146
+ cache = /* @__PURE__ */ new Map();
46147
+ async lookup(ip) {
46148
+ if ((0, import_node_net14.isIP)(ip) === 0) return null;
46149
+ const hit = this.cache.get(ip);
46150
+ if (hit && this.now() - hit.at < this.ttlMs) return hit.info;
46151
+ let info2 = null;
46152
+ try {
46153
+ const origin = cymruOriginName(ip);
46154
+ if (origin) {
46155
+ const rec = await withTimeout(this.resolveTxt(origin), 5e3);
46156
+ const parsed = parseCymruOrigin(rec.map((r) => r.join("")).find(Boolean) ?? "");
46157
+ if (parsed) {
46158
+ let name = "";
46159
+ try {
46160
+ const names = await withTimeout(this.resolveTxt(`AS${parsed.asn}.asn.cymru.com`), 5e3);
46161
+ name = parseCymruName(names.map((r) => r.join("")).find(Boolean) ?? "");
46162
+ } catch {
46163
+ }
46164
+ info2 = { asn: parsed.asn, name, country: parsed.country, prefix: parsed.prefix };
46165
+ }
46166
+ }
46167
+ } catch {
46168
+ info2 = null;
46169
+ }
46170
+ if (this.cache.size > 5e3) this.cache.clear();
46171
+ this.cache.set(ip, { at: this.now(), info: info2 });
46172
+ return info2;
46173
+ }
46174
+ };
46175
+ function withTimeout(p, ms) {
46176
+ return new Promise((resolve8, reject) => {
46177
+ const t = setTimeout(() => reject(new Error("timeout")), ms);
46178
+ p.then((v) => {
46179
+ clearTimeout(t);
46180
+ resolve8(v);
46181
+ }, (e) => {
46182
+ clearTimeout(t);
46183
+ reject(e);
46184
+ });
46185
+ });
46186
+ }
46187
+ function describeNetwork(info2, kind) {
46188
+ if (kind === "tor") return info2 ? `Tor exit, AS${info2.asn} ${info2.name}`.trim() : "Tor exit";
46189
+ if (!info2) return `unknown network (${kind})`;
46190
+ return `AS${info2.asn}${info2.name ? ` ${info2.name}` : ""} (${kind === "unknown" ? "ISP or unclassified" : kind})`;
46191
+ }
46192
+
46193
+ // src/daemon/workers/ssh-intrusion.ts
46194
+ var TOR_REALERT_MS = 10 * 6e4;
46195
+ var HOSTING_REALERT_MS = 24 * 36e5;
46196
+ var TOR_REMEDIATION = {
46197
+ action: "block",
46198
+ description: "Ban the Tor exit at once, for max_ban, even in dry_run and even after a successful login",
46199
+ enforce_in_dry_run: true,
46200
+ ban_on_login: true,
46201
+ override_operator_protection: true,
46202
+ max_ban: true
46203
+ };
46204
+ function parseKeyLoginsByFingerprint(text) {
46205
+ const out = /* @__PURE__ */ new Map();
46206
+ for (const line2 of text.split("\n")) {
46207
+ const m = /^(\d+(?:\.\d+)?)\s.*Accepted publickey for \S+ from (\S+) port \d+ \S+?:\s+\S+\s+(SHA256:[A-Za-z0-9+/=]+)/.exec(line2);
46208
+ if (!m) continue;
46209
+ const at = Math.round(Number(m[1]) * 1e3);
46210
+ const ips = out.get(m[3]) ?? /* @__PURE__ */ new Map();
46211
+ if (at > (ips.get(m[2]) ?? 0)) ips.set(m[2], at);
46212
+ out.set(m[3], ips);
46213
+ }
46214
+ return out;
46215
+ }
46216
+ function readJson2(path2) {
46217
+ try {
46218
+ return JSON.parse((0, import_node_fs40.readFileSync)(path2, "utf-8"));
46219
+ } catch {
46220
+ return null;
46221
+ }
46222
+ }
46223
+ function writeJson2(path2, value) {
46224
+ (0, import_node_fs40.mkdirSync)((0, import_node_path31.dirname)(path2), { recursive: true });
46225
+ (0, import_node_fs40.writeFileSync)(`${path2}.tmp`, JSON.stringify(value));
46226
+ (0, import_node_fs40.renameSync)(`${path2}.tmp`, path2);
46227
+ }
46228
+ var fsIO2 = {
46229
+ readFile: (p) => {
46230
+ try {
46231
+ return (0, import_node_fs40.readFileSync)(p, "utf-8");
46232
+ } catch {
46233
+ return null;
46234
+ }
46235
+ },
46236
+ readDir: (p) => {
46237
+ try {
46238
+ return (0, import_node_fs40.readdirSync)(p);
46239
+ } catch {
46240
+ return null;
46241
+ }
46242
+ },
46243
+ exists: (p) => (0, import_node_fs40.existsSync)(p)
46244
+ };
46245
+ function defaultRun4(cmd, args) {
46246
+ const res = (0, import_node_child_process13.spawnSync)(cmd, args, { encoding: "utf-8", timeout: 6e4, maxBuffer: 64 * 1024 * 1024, stdio: ["ignore", "pipe", "pipe"] });
46247
+ return res.status === 0 ? res.stdout : null;
46248
+ }
46249
+ var SshIntrusionWatch = class {
46250
+ constructor(opts) {
46251
+ this.opts = opts;
46252
+ this.now = opts.now ?? Date.now;
46253
+ this.asn = opts.asn ?? new AsnLookup();
46254
+ this.io = opts.io ?? fsIO2;
46255
+ this.run = opts.run ?? defaultRun4;
46256
+ }
46257
+ opts;
46258
+ now;
46259
+ asn;
46260
+ io;
46261
+ run;
46262
+ torAlerted = /* @__PURE__ */ new Map();
46263
+ hostingAlerted = /* @__PURE__ */ new Map();
46264
+ history = {};
46265
+ keyComments = { at: 0, byFp: /* @__PURE__ */ new Map() };
46266
+ baselineReady = false;
46267
+ onLine = (line2) => {
46268
+ this.checkTorLine(line2);
46269
+ };
46270
+ onEvent = (event) => {
46271
+ void this.checkKeyLogin(event);
46272
+ };
46273
+ start() {
46274
+ this.opts.tor.start();
46275
+ this.opts.manager.setTorExitCheck((ip) => this.opts.tor.has(ip));
46276
+ this.opts.bus.on("sshd", this.onLine);
46277
+ if (this.opts.keyLoginWatch !== false) {
46278
+ this.opts.bus.on("event", this.onEvent);
46279
+ this.loadHistory();
46280
+ }
46281
+ 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"}`);
46282
+ }
46283
+ stop() {
46284
+ this.opts.tor.stop();
46285
+ this.opts.bus.off("sshd", this.onLine);
46286
+ this.opts.bus.off("event", this.onEvent);
46287
+ }
46288
+ emit(event) {
46289
+ try {
46290
+ insertEvent(event);
46291
+ } catch {
46292
+ }
46293
+ this.opts.bus.publish(event);
46294
+ }
46295
+ /** One sshd line: a Tor exit anywhere in it is an intrusion attempt. */
46296
+ checkTorLine(line2) {
46297
+ const ip = line2.ip;
46298
+ if (!this.opts.tor.has(ip)) return false;
46299
+ if (isProtected(ip, DEFAULT_PROTECTED) || this.opts.manager.isFleetAddress(ip)) return false;
46300
+ const at = this.now();
46301
+ const last = this.torAlerted.get(ip) ?? 0;
46302
+ const accepted = /Accepted \S+ for /.test(line2.message);
46303
+ if (!accepted && at - last < TOR_REALERT_MS) return false;
46304
+ this.torAlerted.set(ip, at);
46305
+ if (this.torAlerted.size > 1e4) this.torAlerted.clear();
46306
+ const ban = this.opts.manager.blockTorSsh;
46307
+ const user = /for (?:invalid user )?(\S+) from/.exec(line2.message)?.[1];
46308
+ const what = accepted ? `LOGGED IN${user ? ` as ${user}` : ""}` : "connection attempt";
46309
+ this.emit({
46310
+ timestamp: line2.timestamp,
46311
+ module: "ssh-intrusion",
46312
+ category: "auth",
46313
+ severity: accepted || ban ? "critical" : "high",
46314
+ message: `SSH from Tor exit ${ip} (${what})${ban ? ": banned" : ""}`,
46315
+ source_ip: ip,
46316
+ details: {
46317
+ rule_id: "ssh-from-tor",
46318
+ description: "Nobody we operate for uses SSH through Tor. A Tor login means a stolen key or password.",
46319
+ tor_exit: true,
46320
+ accepted,
46321
+ ...user ? { ssh_user: user } : {},
46322
+ ...ban ? { remediation: TOR_REMEDIATION } : {},
46323
+ evidence: { at: line2.timestamp.toISOString(), module: "ssh-guard", message: line2.raw.slice(0, 500) }
46324
+ }
46325
+ });
46326
+ return true;
46327
+ }
46328
+ loadHistory() {
46329
+ const saved = readJson2(this.opts.historyPath);
46330
+ if (saved) {
46331
+ this.history = saved;
46332
+ this.baselineReady = true;
46333
+ return;
46334
+ }
46335
+ const out = this.run("journalctl", ["_COMM=sshd", "_COMM=sshd-session", "--since=-30d", "-o", "short-unix", "--no-pager", "--grep", "Accepted publickey"]);
46336
+ const iso = (ms) => new Date(ms).toISOString();
46337
+ let pairs = 0;
46338
+ for (const [fp, ips] of parseKeyLoginsByFingerprint(out ?? "")) {
46339
+ for (const [ip, at] of ips) {
46340
+ if (this.opts.tor.has(ip)) continue;
46341
+ (this.history[fp] ??= {})[ip] = { first: iso(at), last: iso(at), count: 1 };
46342
+ pairs++;
46343
+ }
46344
+ }
46345
+ this.save();
46346
+ this.baselineReady = true;
46347
+ 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)`);
46348
+ }
46349
+ save() {
46350
+ try {
46351
+ writeJson2(this.opts.historyPath, this.history);
46352
+ } catch (err) {
46353
+ this.opts.log(`[ssh-intrusion] could not save key-login history: ${err.message}`);
46354
+ }
46355
+ }
46356
+ /** Which account a key is authorized for, and its comment (cached 5 minutes). */
46357
+ keyInfo(fp) {
46358
+ if (this.now() - this.keyComments.at > 3e5) {
46359
+ const snap2 = takeSnapshot(this.io);
46360
+ const byFp = /* @__PURE__ */ new Map();
46361
+ for (const [user, keys] of Object.entries(snap2.keys)) {
46362
+ for (const [f, k] of Object.entries(keys)) if (!byFp.has(f)) byFp.set(f, { user, comment: k.comment });
46363
+ }
46364
+ this.keyComments = { at: this.now(), byFp };
46365
+ }
46366
+ return this.keyComments.byFp.get(fp) ?? null;
46367
+ }
46368
+ async checkKeyLogin(event) {
46369
+ if (event.module !== "ssh-guard" || !this.baselineReady) return null;
46370
+ const fp = event.details?.fingerprint;
46371
+ const ip = event.source_ip;
46372
+ if (typeof fp !== "string" || !ip || isProtected(ip, DEFAULT_PROTECTED)) return null;
46373
+ const seen = this.history[fp] ?? {};
46374
+ const isNew = !seen[ip];
46375
+ const nowIso = new Date(this.now()).toISOString();
46376
+ seen[ip] = { first: seen[ip]?.first ?? nowIso, last: nowIso, count: (seen[ip]?.count ?? 0) + 1 };
46377
+ this.history[fp] = seen;
46378
+ this.save();
46379
+ const tor = this.opts.tor.has(ip);
46380
+ const fleet = this.opts.manager.isFleetAddress(ip);
46381
+ if (fleet) return null;
46382
+ const key = this.keyInfo(fp);
46383
+ const automation = key ? isAutomationKeyComment(key.comment) : false;
46384
+ let info2 = null;
46385
+ try {
46386
+ info2 = await this.asn.lookup(ip);
46387
+ } catch {
46388
+ info2 = null;
46389
+ }
46390
+ const kind = tor ? "tor" : classifyAsn(info2);
46391
+ const network = describeNetwork(info2, kind);
46392
+ const user = typeof event.details?.ssh_user === "string" ? event.details.ssh_user : /accepted for (\S+)/i.exec(event.message)?.[1] ?? "unknown";
46393
+ const keyLabel = `${fp}${key?.comment ? ` (${key.comment})` : ""}`;
46394
+ const known = Object.keys(seen).filter((a) => a !== ip).length;
46395
+ const anonymous = kind === "hosting" || kind === "vpn" || kind === "tor";
46396
+ const hostingHit = !automation && anonymous;
46397
+ const pairKey = `${fp}|${ip}`;
46398
+ const hostingDue = hostingHit && this.now() - (this.hostingAlerted.get(pairKey) ?? 0) >= HOSTING_REALERT_MS;
46399
+ if (!isNew && !hostingDue) return null;
46400
+ if (tor && this.opts.manager.blockTorSsh) return null;
46401
+ let ruleId;
46402
+ let severity;
46403
+ let message;
46404
+ if (hostingHit) {
46405
+ this.hostingAlerted.set(pairKey, this.now());
46406
+ ruleId = "ssh-human-key-hosting-login";
46407
+ severity = "high";
46408
+ 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" : ""}`;
46409
+ } else if (automation && kind === "ci") {
46410
+ ruleId = "ssh-key-new-ip";
46411
+ severity = "info";
46412
+ message = `SSH deploy key logged in as ${user} from a new CI address ${ip} (${network}), expected`;
46413
+ } else {
46414
+ ruleId = "ssh-key-new-ip";
46415
+ severity = "high";
46416
+ message = `SSH key logged in as ${user} from an address it never used: ${ip}, ${network}${known ? `; ${known} address(es) known for this key` : ""}`;
46417
+ }
46418
+ const out = {
46419
+ timestamp: event.timestamp,
46420
+ module: "ssh-intrusion",
46421
+ category: "auth",
46422
+ severity,
46423
+ message,
46424
+ details: {
46425
+ rule_id: ruleId,
46426
+ account: user,
46427
+ login_ip: ip,
46428
+ fingerprint: fp,
46429
+ key_comment: key?.comment ?? null,
46430
+ key_kind: automation ? "automation" : "person",
46431
+ network_kind: kind,
46432
+ ...info2 ? { asn: info2.asn, as_name: info2.name, as_country: info2.country } : {},
46433
+ first_time_for_key: isNew,
46434
+ known_addresses_for_key: known,
46435
+ evidence: { at: event.timestamp.toISOString(), module: "ssh-guard", message: `Accepted publickey for ${user} from ${ip} ${fp}` }
46436
+ }
46437
+ };
46438
+ this.emit(out);
46439
+ return out;
46440
+ }
46441
+ };
46442
+
46443
+ // src/daemon/workers/lightning-watch.ts
46444
+ var import_node_fs41 = require("fs");
46445
+ var DEFAULT_CLN_LOGS = [
46446
+ "/home/lightning/.lightning/cln.log",
46447
+ "/root/.lightning/cln.log",
46448
+ "/var/lib/clightning/cln.log",
46449
+ "/home/lightning/.lightning/bitcoin/cln.log"
46450
+ ];
46451
+ 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)/;
46452
+ function parseChannelClose(line2) {
46453
+ const m = CLOSE_RE.exec(line2);
46454
+ if (!m) return null;
46455
+ const at = new Date(m[1]);
46456
+ 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) };
46457
+ }
46458
+ var BURST_WINDOW_MS = 10 * 6e4;
46459
+ var BURST_REALERT_MS = 30 * 6e4;
46460
+ var ChannelCloseDetector = class {
46461
+ recent = [];
46462
+ lastBurst = 0;
46463
+ /** Events for one log line (none, a close, or a close and a burst). */
46464
+ feed(line2) {
46465
+ const close = parseChannelClose(line2);
46466
+ if (!close) return [];
46467
+ const t = close.at.getTime();
46468
+ this.recent = this.recent.filter((c) => t - c.at.getTime() < BURST_WINDOW_MS && c.channel !== close.channel);
46469
+ this.recent.push(close);
46470
+ const out = [{
46471
+ timestamp: close.at,
46472
+ severity: "high",
46473
+ message: `Lightning channel ${close.channel} closing (${close.to})`,
46474
+ details: { rule_id: "ln-channel-close", peer: close.peer, to_state: close.to, evidence: { at: close.at.toISOString(), module: "lightning", message: close.line } }
46475
+ }];
46476
+ if (this.recent.length >= 2 && t - this.lastBurst >= BURST_REALERT_MS) {
46477
+ this.lastBurst = t;
46478
+ out.push({
46479
+ timestamp: close.at,
46480
+ severity: "critical",
46481
+ 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.`,
46482
+ details: { rule_id: "ln-channel-close-burst", channels: this.recent.map((c) => c.channel), evidence: { at: close.at.toISOString(), module: "lightning", message: close.line } }
46483
+ });
46484
+ }
46485
+ return out;
46486
+ }
46487
+ };
46488
+ var LightningWatch = class {
46489
+ constructor(opts) {
46490
+ this.opts = opts;
46491
+ }
46492
+ opts;
46493
+ tails = [];
46494
+ timer = null;
46495
+ detector = new ChannelCloseDetector();
46496
+ start() {
46497
+ if (this.opts.enabled === false) return [];
46498
+ const found = [];
46499
+ for (const path2 of this.opts.paths?.length ? this.opts.paths : DEFAULT_CLN_LOGS) {
46500
+ if (!(0, import_node_fs41.existsSync)(path2)) continue;
46501
+ try {
46502
+ (0, import_node_fs41.accessSync)(path2, import_node_fs41.constants.R_OK);
46503
+ } catch {
46504
+ continue;
46505
+ }
46506
+ this.tails.push(new LogTail(path2));
46507
+ found.push(path2);
46508
+ }
46509
+ if (!found.length) return [];
46510
+ this.timer = setInterval(() => this.poll(), 2e3);
46511
+ this.timer.unref?.();
46512
+ this.opts.log(`[lightning] watching channel closes in ${found.join(", ")}`);
46513
+ return found;
46514
+ }
46515
+ stop() {
46516
+ if (this.timer) clearInterval(this.timer);
46517
+ this.timer = null;
46518
+ this.tails = [];
46519
+ }
46520
+ poll() {
46521
+ for (const tail of this.tails) {
46522
+ tail.poll((line2) => {
46523
+ for (const e of this.detector.feed(line2)) {
46524
+ const event = { module: "lightning", category: "system", ...e };
46525
+ try {
46526
+ insertEvent(event);
46527
+ } catch {
46528
+ }
46529
+ this.opts.bus.publish(event);
46530
+ }
46531
+ });
46532
+ }
46533
+ }
46534
+ };
46535
+
46536
+ // src/core/tor-exits.ts
46537
+ var import_node_fs42 = require("fs");
46538
+ var import_node_path32 = require("path");
46539
+ var import_node_net15 = require("net");
46540
+ var TOR_BULK_EXIT_LIST_URL = "https://check.torproject.org/torbulkexitlist";
46541
+ function parseTorExitList(text) {
46542
+ const out = /* @__PURE__ */ new Set();
46543
+ for (const raw of text.split("\n")) {
46544
+ const line2 = raw.trim();
46545
+ if (!line2 || line2.startsWith("#")) continue;
46546
+ const ip = line2.split(/\s+/)[0];
46547
+ if ((0, import_node_net15.isIP)(ip)) out.add(normalizeIp(ip));
46548
+ }
46549
+ return out;
46550
+ }
46551
+ function normalizeIp(ip) {
46552
+ const bare = ip.trim().replace(/^\[|\]$/g, "").replace(/%.*$/, "");
46553
+ const mapped = /^::ffff:(\d{1,3}(?:\.\d{1,3}){3})$/i.exec(bare);
46554
+ return mapped ? mapped[1] : bare.toLowerCase();
46555
+ }
46556
+ var TorExitList = class _TorExitList {
46557
+ constructor(opts) {
46558
+ this.opts = opts;
46559
+ this.url = opts.url ?? TOR_BULK_EXIT_LIST_URL;
46560
+ this.refreshMs = Math.max(15 * 6e4, opts.refreshMs ?? 36e5);
46561
+ this.fetchImpl = opts.fetchImpl ?? fetch;
46562
+ this.log = opts.log ?? (() => {
46563
+ });
46564
+ this.now = opts.now ?? Date.now;
46565
+ }
46566
+ opts;
46567
+ exits = /* @__PURE__ */ new Set();
46568
+ updatedAt = 0;
46569
+ timer = null;
46570
+ url;
46571
+ refreshMs;
46572
+ fetchImpl;
46573
+ log;
46574
+ now;
46575
+ /** Fewer than this many exits is a broken download, not the Tor network (it has ~1,000+). */
46576
+ static MIN_PLAUSIBLE = 100;
46577
+ /** Load the cache, then refresh now and every `refreshMs`. */
46578
+ start() {
46579
+ this.loadCache();
46580
+ void this.refresh();
46581
+ this.timer = setInterval(() => void this.refresh(), this.refreshMs);
46582
+ this.timer.unref?.();
46583
+ }
46584
+ stop() {
46585
+ if (this.timer) clearInterval(this.timer);
46586
+ this.timer = null;
46587
+ }
46588
+ has(ip) {
46589
+ if (!ip) return false;
46590
+ return this.exits.has(normalizeIp(ip));
46591
+ }
46592
+ get size() {
46593
+ return this.exits.size;
46594
+ }
46595
+ /** When the list in memory was downloaded (ms), 0 if never. */
46596
+ get updated() {
46597
+ return this.updatedAt;
46598
+ }
46599
+ /** Replace the list directly (tests, and the CLI reading the cache). */
46600
+ load(ips, at = this.now()) {
46601
+ this.exits = new Set([...ips].map(normalizeIp));
46602
+ this.updatedAt = at;
46603
+ }
46604
+ loadCache() {
46605
+ try {
46606
+ if (!(0, import_node_fs42.existsSync)(this.opts.cachePath)) return false;
46607
+ const parsed = parseTorExitList((0, import_node_fs42.readFileSync)(this.opts.cachePath, "utf-8"));
46608
+ if (parsed.size === 0) return false;
46609
+ this.load(parsed, (0, import_node_fs42.statSync)(this.opts.cachePath).mtimeMs);
46610
+ this.log(`[tor] loaded ${parsed.size} Tor exit addresses from cache (${new Date(this.updatedAt).toISOString()})`);
46611
+ return true;
46612
+ } catch (err) {
46613
+ this.log(`[tor] could not read the exit list cache: ${err.message}`);
46614
+ return false;
46615
+ }
46616
+ }
46617
+ async refresh() {
46618
+ let text;
46619
+ try {
46620
+ const res = await this.fetchImpl(this.url, {
46621
+ signal: AbortSignal.timeout(3e4),
46622
+ headers: { "User-Agent": "threatcrush-daemon (tor exit list)" }
46623
+ });
46624
+ if (!res.ok) {
46625
+ this.log(`[tor] exit list download failed: HTTP ${res.status}; keeping ${this.exits.size} cached`);
46626
+ return false;
46627
+ }
46628
+ text = await res.text();
46629
+ } catch (err) {
46630
+ this.log(`[tor] exit list download failed: ${err.message}; keeping ${this.exits.size} cached`);
46631
+ return false;
46632
+ }
46633
+ const parsed = parseTorExitList(text);
46634
+ if (parsed.size < _TorExitList.MIN_PLAUSIBLE) {
46635
+ this.log(`[tor] exit list download had only ${parsed.size} addresses; keeping ${this.exits.size} cached`);
46636
+ return false;
46637
+ }
46638
+ const before2 = this.exits.size;
46639
+ this.load(parsed);
46640
+ try {
46641
+ (0, import_node_fs42.mkdirSync)((0, import_node_path32.dirname)(this.opts.cachePath), { recursive: true });
46642
+ (0, import_node_fs42.writeFileSync)(`${this.opts.cachePath}.tmp`, [...parsed].join("\n") + "\n");
46643
+ (0, import_node_fs42.renameSync)(`${this.opts.cachePath}.tmp`, this.opts.cachePath);
46644
+ } catch (err) {
46645
+ this.log(`[tor] could not save the exit list cache: ${err.message}`);
46646
+ }
46647
+ if (before2 !== parsed.size || before2 === 0) this.log(`[tor] loaded ${parsed.size} Tor exit addresses from ${this.url}`);
46648
+ return true;
46649
+ }
46650
+ };
46651
+
45782
46652
  // src/daemon/rules/engine.ts
45783
46653
  var MAX_WINDOW_ENTRIES = 1e3;
45784
46654
  function live(window) {
@@ -45960,8 +46830,8 @@ var RuleEngine = class {
45960
46830
  };
45961
46831
 
45962
46832
  // src/daemon/rules/loader.ts
45963
- var import_node_fs40 = require("fs");
45964
- var import_node_path31 = require("path");
46833
+ var import_node_fs43 = require("fs");
46834
+ var import_node_path33 = require("path");
45965
46835
 
45966
46836
  // src/daemon/rules/default-rules.ts
45967
46837
  var AT_CRS_THRESHOLD = { field: "severity", operator: "regex", value: "^(high|critical)$" };
@@ -46431,11 +47301,11 @@ var RULES_DIR = "/etc/threatcrush/rules.d";
46431
47301
  function loadAllRules(customDir) {
46432
47302
  const rules = [...DEFAULT_RULES];
46433
47303
  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"));
47304
+ if ((0, import_node_fs43.existsSync)(dir)) {
47305
+ const files = (0, import_node_fs43.readdirSync)(dir).filter((f) => f.endsWith(".json"));
46436
47306
  for (const file of files) {
46437
47307
  try {
46438
- const raw = (0, import_node_fs40.readFileSync)((0, import_node_path31.join)(dir, file), "utf-8");
47308
+ const raw = (0, import_node_fs43.readFileSync)((0, import_node_path33.join)(dir, file), "utf-8");
46439
47309
  const parsed = JSON.parse(raw);
46440
47310
  const customRules = Array.isArray(parsed) ? parsed : [parsed];
46441
47311
  for (const rule of customRules) {
@@ -46466,24 +47336,24 @@ function loadAllRules(customDir) {
46466
47336
  }
46467
47337
 
46468
47338
  // 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");
47339
+ var import_node_child_process14 = require("child_process");
47340
+ var import_node_fs44 = require("fs");
47341
+ var import_node_path34 = require("path");
47342
+ var import_node_net16 = require("net");
46473
47343
  function assertValidFirewallIp(ip) {
46474
- if ((0, import_node_net13.isIP)(ip) !== 4) {
47344
+ if ((0, import_node_net16.isIP)(ip) !== 4) {
46475
47345
  throw new Error(`Invalid IPv4 address: ${ip}`);
46476
47346
  }
46477
47347
  }
46478
47348
  function assertBannableIp(ip) {
46479
- if ((0, import_node_net13.isIP)(ip) === 0) {
47349
+ if ((0, import_node_net16.isIP)(ip) === 0) {
46480
47350
  throw new Error(`Invalid IP address: ${ip}`);
46481
47351
  }
46482
47352
  }
46483
47353
  function writeIfAbsent(path2, contents) {
46484
- (0, import_node_fs41.mkdirSync)((0, import_node_path32.dirname)(path2), { recursive: true });
47354
+ (0, import_node_fs44.mkdirSync)((0, import_node_path34.dirname)(path2), { recursive: true });
46485
47355
  try {
46486
- (0, import_node_fs41.writeFileSync)(path2, contents, { flag: "wx" });
47356
+ (0, import_node_fs44.writeFileSync)(path2, contents, { flag: "wx" });
46487
47357
  } catch (err) {
46488
47358
  if (err.code !== "EEXIST") throw err;
46489
47359
  }
@@ -46502,11 +47372,11 @@ var Fail2banAdapter = class {
46502
47372
  enforces = true;
46503
47373
  jailReady = false;
46504
47374
  isAvailable() {
46505
- const result = (0, import_node_child_process13.spawnSync)("fail2ban-client", ["ping"], { stdio: "pipe" });
47375
+ const result = (0, import_node_child_process14.spawnSync)("fail2ban-client", ["ping"], { stdio: "pipe" });
46506
47376
  return result.status === 0;
46507
47377
  }
46508
47378
  client(args) {
46509
- return (0, import_node_child_process13.execFileSync)("fail2ban-client", args, {
47379
+ return (0, import_node_child_process14.execFileSync)("fail2ban-client", args, {
46510
47380
  encoding: "utf-8",
46511
47381
  stdio: ["ignore", "pipe", "pipe"]
46512
47382
  });
@@ -46582,7 +47452,7 @@ var Fail2banAdapter = class {
46582
47452
  const status = this.client(["status", this.jail]);
46583
47453
  const line2 = status.split("\n").find((l) => /Banned IP list:/i.test(l));
46584
47454
  if (!line2) return [];
46585
- return line2.split(":").slice(1).join(":").trim().split(/\s+/).filter((s) => (0, import_node_net13.isIP)(s) !== 0);
47455
+ return line2.split(":").slice(1).join(":").trim().split(/\s+/).filter((s) => (0, import_node_net16.isIP)(s) !== 0);
46586
47456
  } catch {
46587
47457
  return [];
46588
47458
  }
@@ -46592,45 +47462,45 @@ var Fail2banAdapter = class {
46592
47462
  function parseBannedList(output) {
46593
47463
  const found = [];
46594
47464
  for (const match of output.matchAll(/['"]([^'"]+)['"]/g)) {
46595
- if ((0, import_node_net13.isIP)(match[1]) !== 0) found.push(match[1]);
47465
+ if ((0, import_node_net16.isIP)(match[1]) !== 0) found.push(match[1]);
46596
47466
  }
46597
47467
  if (found.length > 0) return found;
46598
- return output.replace(/[[\],]/g, " ").split(/\s+/).filter((s) => (0, import_node_net13.isIP)(s) !== 0);
47468
+ return output.replace(/[[\],]/g, " ").split(/\s+/).filter((s) => (0, import_node_net16.isIP)(s) !== 0);
46599
47469
  }
46600
47470
  var NftablesAdapter = class {
46601
47471
  name = "nftables";
46602
47472
  table = "threatcrush";
46603
47473
  set = "blocklist";
46604
47474
  isAvailable() {
46605
- const result = (0, import_node_child_process13.spawnSync)("nft", ["--version"], { stdio: "pipe" });
47475
+ const result = (0, import_node_child_process14.spawnSync)("nft", ["--version"], { stdio: "pipe" });
46606
47476
  return result.status === 0;
46607
47477
  }
46608
47478
  ensureSetup() {
46609
47479
  try {
46610
- (0, import_node_child_process13.execSync)(`nft list table inet ${this.table} 2>/dev/null`, { stdio: "pipe" });
47480
+ (0, import_node_child_process14.execSync)(`nft list table inet ${this.table} 2>/dev/null`, { stdio: "pipe" });
46611
47481
  } 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`);
47482
+ (0, import_node_child_process14.execSync)(`nft add table inet ${this.table}`);
47483
+ (0, import_node_child_process14.execSync)(`nft add set inet ${this.table} ${this.set} '{ type ipv4_addr; flags timeout; }'`);
47484
+ (0, import_node_child_process14.execSync)(`nft add chain inet ${this.table} input '{ type filter hook input priority -1; policy accept; }'`);
47485
+ (0, import_node_child_process14.execSync)(`nft add rule inet ${this.table} input ip saddr @${this.set} drop`);
46616
47486
  }
46617
47487
  }
46618
47488
  async block(ip) {
46619
47489
  assertValidFirewallIp(ip);
46620
47490
  this.ensureSetup();
46621
- (0, import_node_child_process13.execSync)(`nft add element inet ${this.table} ${this.set} '{ ${ip} }'`);
47491
+ (0, import_node_child_process14.execSync)(`nft add element inet ${this.table} ${this.set} '{ ${ip} }'`);
46622
47492
  }
46623
47493
  async unblock(ip) {
46624
47494
  assertValidFirewallIp(ip);
46625
47495
  try {
46626
- (0, import_node_child_process13.execSync)(`nft delete element inet ${this.table} ${this.set} '{ ${ip} }'`);
47496
+ (0, import_node_child_process14.execSync)(`nft delete element inet ${this.table} ${this.set} '{ ${ip} }'`);
46627
47497
  } catch {
46628
47498
  }
46629
47499
  }
46630
47500
  async isBlocked(ip) {
46631
47501
  assertValidFirewallIp(ip);
46632
47502
  try {
46633
- const output = (0, import_node_child_process13.execSync)(`nft list set inet ${this.table} ${this.set}`, { encoding: "utf-8" });
47503
+ const output = (0, import_node_child_process14.execSync)(`nft list set inet ${this.table} ${this.set}`, { encoding: "utf-8" });
46634
47504
  return output.includes(ip);
46635
47505
  } catch {
46636
47506
  return false;
@@ -46638,7 +47508,7 @@ var NftablesAdapter = class {
46638
47508
  }
46639
47509
  async listBlocked() {
46640
47510
  try {
46641
- const output = (0, import_node_child_process13.execSync)(`nft list set inet ${this.table} ${this.set}`, { encoding: "utf-8" });
47511
+ const output = (0, import_node_child_process14.execSync)(`nft list set inet ${this.table} ${this.set}`, { encoding: "utf-8" });
46642
47512
  const match = output.match(/elements\s*=\s*\{([^}]*)\}/);
46643
47513
  if (!match) return [];
46644
47514
  return match[1].split(",").map((s) => s.trim().split(/\s/)[0]).filter(Boolean);
@@ -46651,34 +47521,34 @@ var IptablesAdapter = class {
46651
47521
  name = "iptables";
46652
47522
  chain = "THREATCRUSH";
46653
47523
  isAvailable() {
46654
- const result = (0, import_node_child_process13.spawnSync)("iptables", ["--version"], { stdio: "pipe" });
47524
+ const result = (0, import_node_child_process14.spawnSync)("iptables", ["--version"], { stdio: "pipe" });
46655
47525
  return result.status === 0;
46656
47526
  }
46657
47527
  ensureChain() {
46658
47528
  try {
46659
- (0, import_node_child_process13.execSync)(`iptables -n -L ${this.chain} 2>/dev/null`, { stdio: "pipe" });
47529
+ (0, import_node_child_process14.execSync)(`iptables -n -L ${this.chain} 2>/dev/null`, { stdio: "pipe" });
46660
47530
  } 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}`);
47531
+ (0, import_node_child_process14.execSync)(`iptables -N ${this.chain}`);
47532
+ (0, import_node_child_process14.execSync)(`iptables -I INPUT 1 -j ${this.chain}`);
46663
47533
  }
46664
47534
  }
46665
47535
  async block(ip) {
46666
47536
  assertValidFirewallIp(ip);
46667
47537
  this.ensureChain();
46668
47538
  if (await this.isBlocked(ip)) return;
46669
- (0, import_node_child_process13.execSync)(`iptables -A ${this.chain} -s ${ip} -j DROP`);
47539
+ (0, import_node_child_process14.execSync)(`iptables -A ${this.chain} -s ${ip} -j DROP`);
46670
47540
  }
46671
47541
  async unblock(ip) {
46672
47542
  assertValidFirewallIp(ip);
46673
47543
  try {
46674
- (0, import_node_child_process13.execSync)(`iptables -D ${this.chain} -s ${ip} -j DROP`);
47544
+ (0, import_node_child_process14.execSync)(`iptables -D ${this.chain} -s ${ip} -j DROP`);
46675
47545
  } catch {
46676
47546
  }
46677
47547
  }
46678
47548
  async isBlocked(ip) {
46679
47549
  assertValidFirewallIp(ip);
46680
47550
  try {
46681
- const output = (0, import_node_child_process13.execSync)(`iptables -n -L ${this.chain}`, { encoding: "utf-8" });
47551
+ const output = (0, import_node_child_process14.execSync)(`iptables -n -L ${this.chain}`, { encoding: "utf-8" });
46682
47552
  return output.includes(ip);
46683
47553
  } catch {
46684
47554
  return false;
@@ -46686,7 +47556,7 @@ var IptablesAdapter = class {
46686
47556
  }
46687
47557
  async listBlocked() {
46688
47558
  try {
46689
- const output = (0, import_node_child_process13.execSync)(`iptables -n -L ${this.chain}`, { encoding: "utf-8" });
47559
+ const output = (0, import_node_child_process14.execSync)(`iptables -n -L ${this.chain}`, { encoding: "utf-8" });
46690
47560
  const ips = [];
46691
47561
  for (const line2 of output.split("\n")) {
46692
47562
  const match = line2.match(/DROP\s+all\s+--\s+(\d+\.\d+\.\d+\.\d+)/);
@@ -46742,22 +47612,22 @@ function detectFirewallAdapter(backend = "auto") {
46742
47612
  }
46743
47613
 
46744
47614
  // 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");
47615
+ var import_node_fs45 = require("fs");
47616
+ var import_node_child_process15 = require("child_process");
47617
+ var import_node_net17 = require("net");
46748
47618
  init_paths();
46749
47619
  init_backoff();
46750
47620
 
46751
47621
  // src/daemon/firewall/crawlers.ts
46752
- var import_node_dns = require("dns");
47622
+ var import_node_dns2 = require("dns");
46753
47623
  var CRAWLER_DOMAINS = ["googlebot.com", "google.com", "search.msn.com", "applebot.apple.com"];
46754
47624
  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)
47625
+ reverse: (ip) => import_node_dns2.promises.reverse(ip),
47626
+ lookup: async (host) => (await import_node_dns2.promises.lookup(host, { all: true })).map((a) => a.address)
46757
47627
  };
46758
47628
  var TIMEOUT_MS2 = 2e3;
46759
47629
  var CACHE_MS = 6 * 36e5;
46760
- function withTimeout(p) {
47630
+ function withTimeout2(p) {
46761
47631
  return Promise.race([
46762
47632
  p,
46763
47633
  new Promise((_, reject) => setTimeout(() => reject(new Error("dns timeout")), TIMEOUT_MS2).unref())
@@ -46774,9 +47644,9 @@ function crawlerVerifier(resolver = systemResolver) {
46774
47644
  if (hit && hit.until > Date.now()) return hit.host;
46775
47645
  let host = null;
46776
47646
  try {
46777
- const names = await withTimeout(resolver.reverse(ip));
47647
+ const names = await withTimeout2(resolver.reverse(ip));
46778
47648
  for (const name of names.filter(inCrawlerDomain)) {
46779
- const addrs = await withTimeout(resolver.lookup(name));
47649
+ const addrs = await withTimeout2(resolver.lookup(name));
46780
47650
  if (addrs.includes(ip)) {
46781
47651
  host = name.replace(/\.$/, "");
46782
47652
  break;
@@ -46804,7 +47674,8 @@ var DEFAULT_CONFIG2 = {
46804
47674
  protect_current_ssh_client: true,
46805
47675
  protect_recent_operators: true,
46806
47676
  operator_memory_seconds: 30 * 86400,
46807
- spare_verified_crawlers: true
47677
+ spare_verified_crawlers: true,
47678
+ block_tor_ssh: true
46808
47679
  };
46809
47680
  var defaultDiscovery = {
46810
47681
  sshPeers: () => [currentSshClient(), ...establishedSshPeers()].filter((ip) => Boolean(ip)),
@@ -46813,19 +47684,19 @@ var defaultDiscovery = {
46813
47684
  const snapshot = takeSnapshot({
46814
47685
  readFile: (p) => {
46815
47686
  try {
46816
- return (0, import_node_fs42.readFileSync)(p, "utf-8");
47687
+ return (0, import_node_fs45.readFileSync)(p, "utf-8");
46817
47688
  } catch {
46818
47689
  return null;
46819
47690
  }
46820
47691
  },
46821
47692
  readDir: (p) => {
46822
47693
  try {
46823
- return (0, import_node_fs42.readdirSync)(p);
47694
+ return (0, import_node_fs45.readdirSync)(p);
46824
47695
  } catch {
46825
47696
  return null;
46826
47697
  }
46827
47698
  },
46828
- exists: (p) => (0, import_node_fs42.existsSync)(p)
47699
+ exists: (p) => (0, import_node_fs45.existsSync)(p)
46829
47700
  });
46830
47701
  const out = /* @__PURE__ */ new Set();
46831
47702
  for (const keys of Object.values(snapshot.keys)) {
@@ -46834,7 +47705,7 @@ var defaultDiscovery = {
46834
47705
  return out;
46835
47706
  },
46836
47707
  keyLoginJournal: (sinceSeconds) => new Promise((resolve8) => {
46837
- (0, import_node_child_process14.execFile)(
47708
+ (0, import_node_child_process15.execFile)(
46838
47709
  "journalctl",
46839
47710
  ["_COMM=sshd", "_COMM=sshd-session", `--since=-${Math.ceil(sinceSeconds / 86400)}d`, "-o", "short-unix", "--no-pager", "--grep", "Accepted publickey"],
46840
47711
  { maxBuffer: 32 * 1024 * 1024, timeout: 6e4 },
@@ -46842,7 +47713,7 @@ var defaultDiscovery = {
46842
47713
  );
46843
47714
  })
46844
47715
  };
46845
- var SEVERITY_RANK7 = {
47716
+ var SEVERITY_RANK8 = {
46846
47717
  info: 0,
46847
47718
  low: 1,
46848
47719
  medium: 2,
@@ -46899,16 +47770,56 @@ var RemediationManager = class {
46899
47770
  operators = {};
46900
47771
  expiryTimer = null;
46901
47772
  operatorTimer = null;
47773
+ /** True for a Tor exit address; such an address is never an operator. */
47774
+ isTorExit = () => false;
46902
47775
  /** Remembered operator addresses and when each was last seen. */
46903
47776
  getOperators() {
46904
47777
  return { ...this.operators };
46905
47778
  }
47779
+ /**
47780
+ * Teach the manager which addresses are Tor exits. They are never
47781
+ * remembered as operators and never protected as a live session: on dev2
47782
+ * the 2026-10-27 intruder logged in with a stolen key from Tor, which made
47783
+ * the exit an "operator" that nothing could ban for 30 days.
47784
+ */
47785
+ setTorExitCheck(check2) {
47786
+ this.isTorExit = check2;
47787
+ let dropped = 0;
47788
+ this.protectedList = this.protectedList.filter((a) => !(0, import_node_net17.isIP)(a) || !check2(a) || this.pinned.has(a) || this.config.allowlist.includes(a));
47789
+ for (const ip of Object.keys(this.operators)) {
47790
+ if (!check2(ip)) continue;
47791
+ delete this.operators[ip];
47792
+ this.protectedList = this.protectedList.filter((a) => a !== ip || this.pinned.has(a) || this.config.allowlist.includes(a));
47793
+ dropped++;
47794
+ }
47795
+ if (dropped) {
47796
+ this.logLine(`[firewall] forgot ${dropped} remembered operator address(es) that are Tor exits`);
47797
+ this.saveState();
47798
+ }
47799
+ }
47800
+ /** Tor SSH bans on (setting) — the cloud may change it unless config pinned it. */
47801
+ get blockTorSsh() {
47802
+ return this.config.enabled && this.config.block_tor_ssh;
47803
+ }
47804
+ setBlockTorSsh(on) {
47805
+ this.config.block_tor_ssh = on;
47806
+ }
47807
+ /**
47808
+ * Our own addresses: built-ins, shared infrastructure, gateways, the
47809
+ * operator's `[remediation] protected` and the dashboard's org allowlist
47810
+ * (Known IPs). Not remembered operators or live sessions.
47811
+ */
47812
+ isFleetAddress(ip) {
47813
+ return isProtected(ip, [...this.pinned, ...this.config.allowlist]);
47814
+ }
46906
47815
  /**
46907
47816
  * An address an operator really came from: never ban it, remember it, and
46908
47817
  * lift a ban that is already on it — the operator is the one who needs in.
46909
47818
  */
46910
47819
  noteOperator(ip, at, remember = true) {
46911
47820
  if (Date.now() - at > this.config.operator_memory_seconds * 1e3) return;
47821
+ if (this.isTorExit(ip) && !this.isFleetAddress(ip)) return;
47822
+ if (this.blocklist.some((b) => b.ip === ip && b.strict)) return;
46912
47823
  if (!this.protectedList.includes(ip)) this.protectedList.push(ip);
46913
47824
  if (!remember || !this.config.protect_recent_operators || isProtected(ip, DEFAULT_PROTECTED)) return;
46914
47825
  const known = this.operators[ip] ?? 0;
@@ -46958,17 +47869,21 @@ var RemediationManager = class {
46958
47869
  }
46959
47870
  async handleDetection(event) {
46960
47871
  if (!this.config.enabled) return;
46961
- const eventRank = SEVERITY_RANK7[event.severity] ?? 0;
46962
- const minRank = SEVERITY_RANK7[this.config.min_severity] ?? 3;
47872
+ const eventRank = SEVERITY_RANK8[event.severity] ?? 0;
47873
+ const minRank = SEVERITY_RANK8[this.config.min_severity] ?? 3;
46963
47874
  if (eventRank < minRank) return;
46964
- if (isSuccessfulAuth(event.message)) return;
47875
+ const remediation = event.details?.remediation;
47876
+ if (isSuccessfulAuth(event.message) && remediation?.ban_on_login !== true) return;
46965
47877
  if (event.details?.rule_id) {
46966
- const remediation = event.details?.remediation;
46967
47878
  if (remediation?.action !== "block") return;
46968
47879
  }
46969
47880
  const ip = event.source_ip;
46970
- if (!ip || (0, import_node_net14.isIP)(ip) === 0) return;
46971
- if (this.isAllowlisted(ip)) return;
47881
+ if (!ip || (0, import_node_net17.isIP)(ip) === 0) return;
47882
+ const strict = remediation?.override_operator_protection === true;
47883
+ if (strict ? this.isFleetAddress(ip) : this.isAllowlisted(ip)) {
47884
+ if (strict) this.logLine(`[remediation] not banning ${ip}: it is one of our own addresses (${event.message})`);
47885
+ return;
47886
+ }
46972
47887
  if (this.blocklist.some((b) => b.ip === ip)) return;
46973
47888
  if (this.config.spare_verified_crawlers) {
46974
47889
  const crawler = await this.verifyCrawler(ip);
@@ -46978,7 +47893,13 @@ var RemediationManager = class {
46978
47893
  }
46979
47894
  }
46980
47895
  const ruleId = event.details?.rule_id;
46981
- await this.ban(ip, event.message, { ruleId, source: "auto" });
47896
+ await this.ban(ip, event.message, {
47897
+ ruleId,
47898
+ source: "auto",
47899
+ enforceInDryRun: remediation?.enforce_in_dry_run === true,
47900
+ strict,
47901
+ ...remediation?.max_ban ? { ttlSeconds: this.config.max_ban_seconds } : {}
47902
+ });
46982
47903
  }
46983
47904
  /**
46984
47905
  * Ban `ip`. With no explicit TTL the length comes from the doubling ladder:
@@ -46986,8 +47907,8 @@ var RemediationManager = class {
46986
47907
  * 4th offence and so on, clamped to `max_ban_seconds`.
46987
47908
  */
46988
47909
  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)) {
47910
+ if ((0, import_node_net17.isIP)(ip) === 0) return { ok: false, error: `not an IP address: ${ip}` };
47911
+ if (opts.strict ? this.isFleetAddress(ip) : this.isAllowlisted(ip)) {
46991
47912
  return { ok: false, error: `${ip} is protected and can never be blocked` };
46992
47913
  }
46993
47914
  const now = Date.now();
@@ -46995,7 +47916,8 @@ var RemediationManager = class {
46995
47916
  if (existing && !opts.ttlSeconds) {
46996
47917
  return { ok: false, error: `${ip} is already banned` };
46997
47918
  }
46998
- if (!this.config.dry_run) {
47919
+ const dryRun = this.config.dry_run && !(opts.enforceInDryRun && this.adapter.enforces !== false);
47920
+ if (!dryRun) {
46999
47921
  try {
47000
47922
  await this.adapter.block(ip);
47001
47923
  } catch (err) {
@@ -47028,14 +47950,19 @@ var RemediationManager = class {
47028
47950
  rule_id: opts.ruleId,
47029
47951
  blocked_at: now,
47030
47952
  expires_at: now + ttl * 1e3,
47031
- dry_run: this.config.dry_run,
47953
+ dry_run: dryRun,
47032
47954
  strikes: strike,
47033
- source: opts.source ?? "manual"
47955
+ source: opts.source ?? "manual",
47956
+ ...opts.strict ? { strict: true } : {}
47034
47957
  };
47958
+ if (opts.strict) {
47959
+ delete this.operators[ip];
47960
+ this.protectedList = this.protectedList.filter((a) => a !== ip || this.pinned.has(a) || this.config.allowlist.includes(a));
47961
+ }
47035
47962
  this.blocklist = this.blocklist.filter((b) => b.ip !== ip);
47036
47963
  this.blocklist.push(entry);
47037
47964
  this.saveState();
47038
- const mode = this.config.dry_run ? "[DRY-RUN] " : "";
47965
+ const mode = dryRun ? "[DRY-RUN] " : this.config.dry_run ? "[ENFORCED IN DRY-RUN] " : "";
47039
47966
  const label = `${mode}Banned ${ip} for ${formatDuration(ttl)} (offence #${strike}): ${reason}`;
47040
47967
  this.logLine(`[firewall] ${label}`);
47041
47968
  this.bus.publish({
@@ -47050,7 +47977,7 @@ var RemediationManager = class {
47050
47977
  rule_id: opts.ruleId,
47051
47978
  reason,
47052
47979
  origin: opts.origin,
47053
- dry_run: this.config.dry_run,
47980
+ dry_run: dryRun,
47054
47981
  ttl_seconds: ttl,
47055
47982
  strikes: strike,
47056
47983
  source: entry.source,
@@ -47133,10 +48060,13 @@ var RemediationManager = class {
47133
48060
  * Saying so up front beats a dashboard that looks armed and is not.
47134
48061
  */
47135
48062
  privilegeWarning() {
47136
- if (!this.config.enabled || this.config.dry_run) return void 0;
48063
+ if (!this.config.enabled) return void 0;
47137
48064
  if (this.adapter.enforces === false) return void 0;
47138
48065
  const uid = typeof process.getuid === "function" ? process.getuid() : 0;
47139
48066
  if (uid === 0) return void 0;
48067
+ if (this.config.dry_run) {
48068
+ 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;
48069
+ }
47140
48070
  return `daemon runs as uid ${uid} and cannot write ${this.adapter.name} rules \u2014 bans will fail`;
47141
48071
  }
47142
48072
  addToAllowlist(ip) {
@@ -47165,10 +48095,11 @@ var RemediationManager = class {
47165
48095
  */
47166
48096
  async reconcile() {
47167
48097
  const now = Date.now();
47168
- const lifted = this.blocklist.filter((b) => this.isAllowlisted(b.ip));
48098
+ const guarded = (b) => b.strict ? this.isFleetAddress(b.ip) : this.isAllowlisted(b.ip);
48099
+ const lifted = this.blocklist.filter(guarded);
47169
48100
  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));
48101
+ const live2 = this.blocklist.filter((b) => b.expires_at > now && !guarded(b));
48102
+ const stale = this.blocklist.filter((b) => b.expires_at <= now || guarded(b));
47172
48103
  for (const entry of stale) {
47173
48104
  if (!entry.dry_run) {
47174
48105
  try {
@@ -47195,8 +48126,8 @@ var RemediationManager = class {
47195
48126
  }
47196
48127
  }
47197
48128
  }
47198
- if (this.config.dry_run) return;
47199
48129
  for (const entry of live2) {
48130
+ if (entry.dry_run) continue;
47200
48131
  if (applied?.includes(entry.ip)) continue;
47201
48132
  try {
47202
48133
  await this.adapter.block(entry.ip);
@@ -47253,7 +48184,8 @@ var RemediationManager = class {
47253
48184
  if (saved && typeof saved === "object" && this.config.protect_recent_operators) {
47254
48185
  const cutoff = Date.now() - this.config.operator_memory_seconds * 1e3;
47255
48186
  for (const [ip, at] of Object.entries(saved)) {
47256
- if (typeof at !== "number" || at < cutoff || !(0, import_node_net14.isIP)(ip)) continue;
48187
+ if (typeof at !== "number" || at < cutoff || !(0, import_node_net17.isIP)(ip)) continue;
48188
+ if (this.blocklist.some((b) => b.ip === ip && b.strict)) continue;
47257
48189
  this.operators[ip] = at;
47258
48190
  if (!this.protectedList.includes(ip)) this.protectedList.push(ip);
47259
48191
  }
@@ -47277,7 +48209,7 @@ var RemediationManager = class {
47277
48209
  }
47278
48210
  logLine(line2) {
47279
48211
  try {
47280
- (0, import_node_fs42.appendFileSync)(PATHS.logFile, `${(/* @__PURE__ */ new Date()).toISOString()} ${line2}
48212
+ (0, import_node_fs45.appendFileSync)(PATHS.logFile, `${(/* @__PURE__ */ new Date()).toISOString()} ${line2}
47281
48213
  `);
47282
48214
  } catch {
47283
48215
  }
@@ -47310,6 +48242,7 @@ function remediationSettings(section) {
47310
48242
  }
47311
48243
  const operatorMemory = parseDuration(section.operator_memory);
47312
48244
  if (operatorMemory) settings.operator_memory_seconds = operatorMemory;
48245
+ if (typeof section.block_tor_ssh === "boolean") settings.block_tor_ssh = section.block_tor_ssh;
47313
48246
  if (typeof section.spare_verified_crawlers === "boolean") {
47314
48247
  settings.spare_verified_crawlers = section.spare_verified_crawlers;
47315
48248
  }
@@ -47320,19 +48253,19 @@ function remediationSettings(section) {
47320
48253
  init_backoff();
47321
48254
 
47322
48255
  // src/daemon/watchdog-service.ts
47323
- var import_node_fs43 = require("fs");
47324
- var import_node_path33 = require("path");
48256
+ var import_node_fs46 = require("fs");
48257
+ var import_node_path35 = require("path");
47325
48258
  function defaultShareGid() {
47326
48259
  const isRoot4 = process.platform === "linux" && typeof process.getuid === "function" && process.getuid() === 0;
47327
48260
  if (!isRoot4) return void 0;
47328
48261
  try {
47329
- return (0, import_node_fs43.statSync)("/var/log/auth.log").gid;
48262
+ return (0, import_node_fs46.statSync)("/var/log/auth.log").gid;
47330
48263
  } catch {
47331
48264
  return void 0;
47332
48265
  }
47333
48266
  }
47334
48267
  function startWatchdog(opts) {
47335
- const dir = opts.config?.dir ?? (0, import_node_path33.join)(opts.stateDir, WATCHDOG_DIRNAME);
48268
+ const dir = opts.config?.dir ?? (0, import_node_path35.join)(opts.stateDir, WATCHDOG_DIRNAME);
47336
48269
  const base = { dir, logged: 0, answered: 0, errored: 0 };
47337
48270
  if (opts.config?.enabled === false) {
47338
48271
  opts.log("[watchdog] off ([watchdog] enabled = false)");
@@ -47426,7 +48359,7 @@ async function flushTelemetry(timeoutMs = 2e3) {
47426
48359
  }
47427
48360
 
47428
48361
  // src/core/node-runtime.ts
47429
- var import_node_child_process15 = require("child_process");
48362
+ var import_node_child_process16 = require("child_process");
47430
48363
  var MIN_DAEMON_NODE_MAJOR = 22;
47431
48364
  function nodeMajor(version) {
47432
48365
  const m = String(version ?? "").trim().replace(/^v/, "").match(/^(\d+)\./);
@@ -47440,23 +48373,23 @@ function daemonNodeProblem(version) {
47440
48373
  }
47441
48374
  function versionOfNode(path2) {
47442
48375
  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 });
48376
+ const res = (0, import_node_child_process16.spawnSync)(path2, ["-p", "process.versions.node"], { encoding: "utf-8", timeout: 5e3 });
47444
48377
  return res.status === 0 ? res.stdout.trim() : null;
47445
48378
  }
47446
48379
 
47447
48380
  // src/daemon/index.ts
47448
48381
  function readVersion2() {
47449
48382
  try {
47450
- const pkg = JSON.parse((0, import_node_fs44.readFileSync)((0, import_node_path34.join)(__dirname, "..", "package.json"), "utf-8"));
48383
+ const pkg = JSON.parse((0, import_node_fs47.readFileSync)((0, import_node_path36.join)(__dirname, "..", "package.json"), "utf-8"));
47451
48384
  return pkg.version || "0.0.0";
47452
48385
  } catch {
47453
48386
  return "0.0.0";
47454
48387
  }
47455
48388
  }
47456
48389
  async function runHardeningChecks() {
47457
- const { stdout } = await (0, import_node_util4.promisify)(import_node_child_process16.execFile)(
48390
+ const { stdout } = await (0, import_node_util4.promisify)(import_node_child_process17.execFile)(
47458
48391
  process.execPath,
47459
- [(0, import_node_path34.join)(__dirname, "index.js"), "harden", "--json", "--no-upload"],
48392
+ [(0, import_node_path36.join)(__dirname, "index.js"), "harden", "--json", "--no-upload"],
47460
48393
  { timeout: 12e4, maxBuffer: 4 * 1024 * 1024 }
47461
48394
  );
47462
48395
  const parsed = JSON.parse(stdout.slice(stdout.indexOf("{")));
@@ -47468,9 +48401,9 @@ async function runHardeningChecks() {
47468
48401
  return patches ? [...findings2, patches] : findings2;
47469
48402
  }
47470
48403
  async function runPatchCheck() {
47471
- const { stdout } = await (0, import_node_util4.promisify)(import_node_child_process16.execFile)(
48404
+ const { stdout } = await (0, import_node_util4.promisify)(import_node_child_process17.execFile)(
47472
48405
  process.execPath,
47473
- [(0, import_node_path34.join)(__dirname, "index.js"), "patches", "--json", "--no-upload"],
48406
+ [(0, import_node_path36.join)(__dirname, "index.js"), "patches", "--json", "--no-upload"],
47474
48407
  { timeout: 3e5, maxBuffer: 16 * 1024 * 1024 }
47475
48408
  );
47476
48409
  const parsed = JSON.parse(stdout.slice(stdout.indexOf("{")));
@@ -47478,7 +48411,7 @@ async function runPatchCheck() {
47478
48411
  }
47479
48412
  function logLine(line2) {
47480
48413
  try {
47481
- (0, import_node_fs44.appendFileSync)(PATHS.logFile, `${(/* @__PURE__ */ new Date()).toISOString()} ${line2}
48414
+ (0, import_node_fs47.appendFileSync)(PATHS.logFile, `${(/* @__PURE__ */ new Date()).toISOString()} ${line2}
47482
48415
  `);
47483
48416
  } catch {
47484
48417
  }
@@ -47503,9 +48436,9 @@ async function runDaemon() {
47503
48436
  logLine(`[daemon] starting threatcrushd v${version} mode=${PATHS.mode}`);
47504
48437
  const restartDaemon = () => {
47505
48438
  if (PATHS.mode === "system") {
47506
- (0, import_node_child_process16.spawn)("systemctl", ["restart", "threatcrushd"], { detached: true, stdio: "ignore" }).unref();
48439
+ (0, import_node_child_process17.spawn)("systemctl", ["restart", "threatcrushd"], { detached: true, stdio: "ignore" }).unref();
47507
48440
  } else {
47508
- (0, import_node_child_process16.spawn)(process.execPath, process.argv.slice(1), { detached: true, stdio: "ignore" }).unref();
48441
+ (0, import_node_child_process17.spawn)(process.execPath, process.argv.slice(1), { detached: true, stdio: "ignore" }).unref();
47509
48442
  setTimeout(() => process.exit(0), 500).unref();
47510
48443
  }
47511
48444
  };
@@ -47520,7 +48453,11 @@ async function runDaemon() {
47520
48453
  } catch (err) {
47521
48454
  logLine(`[daemon] state db unavailable: ${err.message}`);
47522
48455
  }
47523
- const config = loadConfig((0, import_node_fs44.existsSync)(PATHS.configFile) ? PATHS.configFile : void 0);
48456
+ const loaded = loadDaemonConfig(PATHS.configFile, (0, import_node_path36.join)(PATHS.stateDir, "threatcrushd.conf.last-good"));
48457
+ const config = loaded.config;
48458
+ if (loaded.error) {
48459
+ logLine(`[daemon] CONFIG ERROR: ${loaded.error}; ${loaded.usedLastGood ? "running on the last config that parsed" : "no earlier good copy, running on DEFAULTS (no protected list)"}`);
48460
+ }
47524
48461
  configureAttackDetection(config.detection);
47525
48462
  const retentionSeconds = parseDuration(config.storage?.event_retention) ?? DEFAULT_EVENT_RETENTION_SECONDS;
47526
48463
  const maxEvents = config.storage?.max_events ?? DEFAULT_MAX_EVENTS;
@@ -47584,7 +48521,7 @@ async function runDaemon() {
47584
48521
  const threatFeeds = new ThreatFeeds({
47585
48522
  settings: { ...feedSettings, allow: [...feedSettings.allow, ...remediation.getAllowlist()] },
47586
48523
  enforcing: !remediationStatus.dry_run && firewallAdapter.enforces !== false,
47587
- cachePath: (0, import_node_path34.join)(PATHS.stateDir, "threat-feeds.json"),
48524
+ cachePath: (0, import_node_path36.join)(PATHS.stateDir, "threat-feeds.json"),
47588
48525
  bus,
47589
48526
  log: logLine
47590
48527
  });
@@ -47592,13 +48529,45 @@ async function runDaemon() {
47592
48529
  const privilegeWatch = new PrivilegeWatch({
47593
48530
  settings: privilegeSettings(config.privileged),
47594
48531
  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"),
48532
+ snapshotPath: (0, import_node_path36.join)(PATHS.stateDir, "privileges.json"),
48533
+ loginsPath: (0, import_node_path36.join)(PATHS.stateDir, "login-countries.json"),
48534
+ cursorPath: (0, import_node_path36.join)(PATHS.stateDir, "sudo-cursor.json"),
47598
48535
  log: logLine
47599
48536
  });
47600
48537
  privilegeWatch.start();
47601
- new AlertDispatcher(bus, config);
48538
+ const torExits = new TorExitList({
48539
+ cachePath: (0, import_node_path36.join)(PATHS.stateDir, "tor-exits.txt"),
48540
+ url: config.remediation?.tor_exit_list_url,
48541
+ log: logLine
48542
+ });
48543
+ const sshIntrusion = new SshIntrusionWatch({
48544
+ bus,
48545
+ manager: remediation,
48546
+ tor: torExits,
48547
+ historyPath: (0, import_node_path36.join)(PATHS.stateDir, "key-logins.json"),
48548
+ keyLoginWatch: config.privileged?.key_login_watch !== false,
48549
+ log: logLine
48550
+ });
48551
+ sshIntrusion.start();
48552
+ const lightningWatch = new LightningWatch({
48553
+ bus,
48554
+ enabled: config.lightning?.enabled !== false,
48555
+ paths: Array.isArray(config.lightning?.log_paths) ? config.lightning.log_paths.map(String) : void 0,
48556
+ log: logLine
48557
+ });
48558
+ lightningWatch.start();
48559
+ let cloudSyncRef = null;
48560
+ new AlertDispatcher(bus, config, { cloudHealthy: () => cloudSyncRef?.healthy ?? false, log: logLine });
48561
+ if (loaded.error) {
48562
+ setTimeout(() => bus.publish({
48563
+ timestamp: /* @__PURE__ */ new Date(),
48564
+ module: "daemon",
48565
+ category: "system",
48566
+ severity: "critical",
48567
+ message: `threatcrushd.conf does not parse; ${loaded.usedLastGood ? "running on the last good copy" : "running on defaults with NO protected list"}: ${loaded.error}`.slice(0, 500),
48568
+ details: { rule_id: "daemon-config-invalid", used_last_good: loaded.usedLastGood }
48569
+ }), 15e3).unref?.();
48570
+ }
47602
48571
  const runsWorker = new RunsWorker(bus, {
47603
48572
  enabled: config.cloud?.enabled !== false && config.cloud?.runs === true,
47604
48573
  scanRoots: Array.isArray(config.cloud?.run_scan_paths) ? config.cloud.run_scan_paths.filter((p) => typeof p === "string") : [],
@@ -47620,14 +48589,15 @@ async function runDaemon() {
47620
48589
  cloudSync = new CloudSync({
47621
48590
  bus,
47622
48591
  version,
47623
- hostname: (0, import_node_os13.hostname)(),
48592
+ hostname: (0, import_node_os14.hostname)(),
47624
48593
  minSeverity,
47625
- spoolPath: (0, import_node_path34.join)(PATHS.stateDir, "cloud-spool.jsonl"),
48594
+ spoolPath: (0, import_node_path36.join)(PATHS.stateDir, "cloud-spool.jsonl"),
47626
48595
  log: logLine,
47627
48596
  ruleModules: new Set(ruleEngine.getRules().flatMap((rule) => rule.source_types)),
47628
48597
  runHardening: runHardeningChecks
47629
48598
  });
47630
48599
  cloudSync.start();
48600
+ cloudSyncRef = cloudSync;
47631
48601
  remediationConsumer = new RemediationConsumer(remediation, {
47632
48602
  log: logLine,
47633
48603
  restartDaemon,
@@ -47635,7 +48605,15 @@ async function runDaemon() {
47635
48605
  updateNow: () => autoUpdateRef ? autoUpdateRef.check({ force: true, restartDelayMs: 3e3 }) : Promise.resolve("updater not started")
47636
48606
  });
47637
48607
  remediationConsumer.start();
47638
- allowlistSync = new AllowlistSync(remediation, { log: logLine });
48608
+ const torPinned = typeof config.remediation?.block_tor_ssh === "boolean";
48609
+ allowlistSync = new AllowlistSync(remediation, {
48610
+ log: logLine,
48611
+ onOrgSettings: ({ block_tor_ssh }) => {
48612
+ if (torPinned || typeof block_tor_ssh !== "boolean" || block_tor_ssh === remediation.blockTorSsh) return;
48613
+ remediation.setBlockTorSsh(block_tor_ssh);
48614
+ logLine(`[ssh-intrusion] Tor SSH ban ${block_tor_ssh ? "ON" : "OFF"} (org setting from the dashboard)`);
48615
+ }
48616
+ });
47639
48617
  allowlistSync.start();
47640
48618
  const link = currentLink();
47641
48619
  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 +48624,8 @@ async function runDaemon() {
47646
48624
  const autoUpdate = autoUpdateRef = new AutoUpdate({
47647
48625
  version,
47648
48626
  settings: updateSettings(config.update),
47649
- pkgRoot: (0, import_node_path34.join)(__dirname, ".."),
47650
- statePath: (0, import_node_path34.join)(PATHS.stateDir, "auto-update.json"),
48627
+ pkgRoot: (0, import_node_path36.join)(__dirname, ".."),
48628
+ statePath: (0, import_node_path36.join)(PATHS.stateDir, "auto-update.json"),
47651
48629
  bus,
47652
48630
  log: logLine,
47653
48631
  restartDaemon
@@ -47702,6 +48680,14 @@ async function runDaemon() {
47702
48680
  privilegeWatch.stop();
47703
48681
  } catch {
47704
48682
  }
48683
+ try {
48684
+ sshIntrusion.stop();
48685
+ } catch {
48686
+ }
48687
+ try {
48688
+ lightningWatch.stop();
48689
+ } catch {
48690
+ }
47705
48691
  try {
47706
48692
  await ipc.stop();
47707
48693
  } catch {
@@ -47737,7 +48723,7 @@ var SYSTEM_SOCKET = "/var/run/threatcrush/threatcrushd.sock";
47737
48723
  function isRoot2() {
47738
48724
  return typeof process.getuid === "function" && process.getuid() === 0;
47739
48725
  }
47740
- var DAEMON_ENTRY = (0, import_node_path35.join)(__dirname, "daemon.js");
48726
+ var DAEMON_ENTRY = (0, import_node_path37.join)(__dirname, "daemon.js");
47741
48727
  async function daemonForeground() {
47742
48728
  await runDaemon();
47743
48729
  }
@@ -47758,7 +48744,7 @@ async function daemonStart() {
47758
48744
  return;
47759
48745
  }
47760
48746
  ensureRuntimeDirs();
47761
- if (!(0, import_node_fs45.existsSync)(DAEMON_ENTRY)) {
48747
+ if (!(0, import_node_fs48.existsSync)(DAEMON_ENTRY)) {
47762
48748
  console.log(source_default.red(` Daemon entry not found at ${DAEMON_ENTRY}.`));
47763
48749
  console.log(source_default.dim(" Reinstall with `threatcrush update` or `pnpm run build` in the cli package."));
47764
48750
  return;
@@ -47766,8 +48752,8 @@ async function daemonStart() {
47766
48752
  let out;
47767
48753
  let err;
47768
48754
  try {
47769
- out = (0, import_node_fs46.openSync)(PATHS.logFile, "a");
47770
- err = (0, import_node_fs46.openSync)(PATHS.logFile, "a");
48755
+ out = (0, import_node_fs49.openSync)(PATHS.logFile, "a");
48756
+ err = (0, import_node_fs49.openSync)(PATHS.logFile, "a");
47771
48757
  } catch (e) {
47772
48758
  const code = e.code;
47773
48759
  console.log(source_default.red(` \u2717 Cannot write daemon log at ${PATHS.logFile} (${code ?? "error"}).`));
@@ -47780,7 +48766,7 @@ async function daemonStart() {
47780
48766
  }
47781
48767
  return;
47782
48768
  }
47783
- const child = (0, import_node_child_process17.spawn)(process.execPath, [DAEMON_ENTRY], {
48769
+ const child = (0, import_node_child_process18.spawn)(process.execPath, [DAEMON_ENTRY], {
47784
48770
  detached: true,
47785
48771
  stdio: ["ignore", out, err],
47786
48772
  env: { ...process.env, THREATCRUSH_DAEMON: "1" }
@@ -47855,41 +48841,41 @@ async function waitForExit(pid, timeoutMs) {
47855
48841
  }
47856
48842
  async function releaseStaleSocket() {
47857
48843
  const deadline = Date.now() + 2e3;
47858
- while ((0, import_node_fs45.existsSync)(PATHS.socket) && Date.now() < deadline) {
48844
+ while ((0, import_node_fs48.existsSync)(PATHS.socket) && Date.now() < deadline) {
47859
48845
  await new Promise((r) => setTimeout(r, 50));
47860
48846
  }
47861
- if ((0, import_node_fs45.existsSync)(PATHS.socket)) {
48847
+ if ((0, import_node_fs48.existsSync)(PATHS.socket)) {
47862
48848
  try {
47863
- (0, import_node_fs45.unlinkSync)(PATHS.socket);
48849
+ (0, import_node_fs48.unlinkSync)(PATHS.socket);
47864
48850
  } catch {
47865
48851
  }
47866
48852
  }
47867
48853
  }
47868
48854
 
47869
48855
  // 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");
48856
+ var import_node_child_process19 = require("child_process");
48857
+ var import_node_fs50 = require("fs");
48858
+ var import_node_path38 = require("path");
48859
+ var import_node_os15 = require("os");
47874
48860
  var UNIT_PATH = "/etc/systemd/system/threatcrushd.service";
47875
48861
  var DAEMON_UNIT_NAME = "threatcrushd.service";
47876
48862
  function resolveTemplate() {
47877
- const templatePath = (0, import_node_path36.join)(__dirname, "systemd", "threatcrushd.service");
47878
- if (!(0, import_node_fs47.existsSync)(templatePath)) {
48863
+ const templatePath = (0, import_node_path38.join)(__dirname, "systemd", "threatcrushd.service");
48864
+ if (!(0, import_node_fs50.existsSync)(templatePath)) {
47879
48865
  throw new Error(`systemd unit template not found at ${templatePath}`);
47880
48866
  }
47881
- return (0, import_node_fs47.readFileSync)(templatePath, "utf-8");
48867
+ return (0, import_node_fs50.readFileSync)(templatePath, "utf-8");
47882
48868
  }
47883
48869
  function stableBinPath(binPath) {
47884
48870
  const stable = binPath.replace(/\/\.pnpm\/[^/]+\/node_modules\//, "/node_modules/");
47885
48871
  if (stable === binPath) return binPath;
47886
- return (0, import_node_fs47.existsSync)(stable) ? stable : binPath;
48872
+ return (0, import_node_fs50.existsSync)(stable) ? stable : binPath;
47887
48873
  }
47888
48874
  function resolveBinPath() {
47889
48875
  const arg = process.argv[1];
47890
- if (arg && (0, import_node_fs47.existsSync)(arg)) return stableBinPath(arg);
48876
+ if (arg && (0, import_node_fs50.existsSync)(arg)) return stableBinPath(arg);
47891
48877
  try {
47892
- return (0, import_node_child_process18.execSync)("command -v threatcrush", { encoding: "utf-8" }).trim();
48878
+ return (0, import_node_child_process19.execSync)("command -v threatcrush", { encoding: "utf-8" }).trim();
47893
48879
  } catch {
47894
48880
  return "threatcrush";
47895
48881
  }
@@ -47897,11 +48883,11 @@ function resolveBinPath() {
47897
48883
  function stableNodePath(execPath) {
47898
48884
  const stable = execPath.replace(/(\/installs\/node\/)[^/]+\//, "$1latest/");
47899
48885
  if (stable === execPath) return execPath;
47900
- return (0, import_node_fs47.existsSync)(stable) ? stable : execPath;
48886
+ return (0, import_node_fs50.existsSync)(stable) ? stable : execPath;
47901
48887
  }
47902
48888
  function looksLikeNodeScript(path2) {
47903
48889
  try {
47904
- const head = (0, import_node_fs47.readFileSync)(path2, "utf-8").slice(0, 120);
48890
+ const head = (0, import_node_fs50.readFileSync)(path2, "utf-8").slice(0, 120);
47905
48891
  return /^#!.*\bnode\b/.test(head);
47906
48892
  } catch {
47907
48893
  return false;
@@ -47928,20 +48914,20 @@ function isRoot3() {
47928
48914
  return typeof process.getuid === "function" && process.getuid() === 0;
47929
48915
  }
47930
48916
  function reexecWithSudo(args) {
47931
- if ((0, import_node_child_process18.spawnSync)("sudo", ["--version"], { stdio: "pipe" }).status !== 0) return false;
48917
+ if ((0, import_node_child_process19.spawnSync)("sudo", ["--version"], { stdio: "pipe" }).status !== 0) return false;
47932
48918
  console.log(source_default.dim(" This needs root \u2014 sudo will ask for your password.\n"));
47933
48919
  const bin = resolveBinPath();
47934
48920
  const argv = looksLikeNodeScript(bin) ? [stableNodePath(process.execPath), bin, ...args] : [bin, ...args];
47935
- const result = (0, import_node_child_process18.spawnSync)("sudo", argv, { stdio: "inherit" });
48921
+ const result = (0, import_node_child_process19.spawnSync)("sudo", argv, { stdio: "inherit" });
47936
48922
  return result.status === 0;
47937
48923
  }
47938
48924
  function callerHome() {
47939
48925
  const user = process.env.SUDO_USER;
47940
48926
  if (!user) return null;
47941
48927
  try {
47942
- const line2 = (0, import_node_child_process18.execSync)(`getent passwd ${user}`, { encoding: "utf-8" }).trim();
48928
+ const line2 = (0, import_node_child_process19.execSync)(`getent passwd ${user}`, { encoding: "utf-8" }).trim();
47943
48929
  const home = line2.split(":")[5];
47944
- return home && (0, import_node_fs47.existsSync)(home) ? home : null;
48930
+ return home && (0, import_node_fs50.existsSync)(home) ? home : null;
47945
48931
  } catch {
47946
48932
  return null;
47947
48933
  }
@@ -47949,13 +48935,13 @@ function callerHome() {
47949
48935
  function stopUserModeDaemon() {
47950
48936
  const home = callerHome();
47951
48937
  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;
48938
+ const runDir = (0, import_node_path38.join)(home, ".threatcrush", "run");
48939
+ const pidFile = (0, import_node_path38.join)(runDir, "threatcrushd.pid");
48940
+ const socket = (0, import_node_path38.join)(runDir, "threatcrushd.sock");
48941
+ if (!(0, import_node_fs50.existsSync)(pidFile) && !(0, import_node_fs50.existsSync)(socket)) return;
47956
48942
  let pid = null;
47957
48943
  try {
47958
- pid = Number.parseInt((0, import_node_fs47.readFileSync)(pidFile, "utf-8").trim(), 10);
48944
+ pid = Number.parseInt((0, import_node_fs50.readFileSync)(pidFile, "utf-8").trim(), 10);
47959
48945
  } catch {
47960
48946
  pid = null;
47961
48947
  }
@@ -47968,13 +48954,13 @@ function stopUserModeDaemon() {
47968
48954
  }
47969
48955
  for (const path2 of [socket, pidFile]) {
47970
48956
  try {
47971
- if ((0, import_node_fs47.existsSync)(path2)) (0, import_node_fs47.rmSync)(path2);
48957
+ if ((0, import_node_fs50.existsSync)(path2)) (0, import_node_fs50.rmSync)(path2);
47972
48958
  } catch {
47973
48959
  }
47974
48960
  }
47975
48961
  }
47976
48962
  function unitIsActive() {
47977
- const result = (0, import_node_child_process18.spawnSync)("systemctl", ["is-active", "--quiet", DAEMON_UNIT_NAME], { stdio: "pipe" });
48963
+ const result = (0, import_node_child_process19.spawnSync)("systemctl", ["is-active", "--quiet", DAEMON_UNIT_NAME], { stdio: "pipe" });
47978
48964
  return result.status === 0;
47979
48965
  }
47980
48966
  async function installServiceCommand() {
@@ -47985,8 +48971,8 @@ async function installServiceCommand() {
47985
48971
  return;
47986
48972
  }
47987
48973
  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")
48974
+ hasSystemctl: (0, import_node_child_process19.spawnSync)("sh", ["-c", "command -v systemctl"], { stdio: "ignore" }).status === 0,
48975
+ booted: (0, import_node_fs50.existsSync)("/run/systemd/system")
47990
48976
  });
47991
48977
  if (noSystemd) {
47992
48978
  console.log(source_default.red(` \u2717 systemd isn't available here: ${noSystemd}.`));
@@ -48008,7 +48994,7 @@ async function installServiceCommand() {
48008
48994
  const isNodeScript = looksLikeNodeScript(binPath);
48009
48995
  let nodePath = stableNodePath(process.execPath);
48010
48996
  if (isNodeScript && nodeVersionDir(binPath)) {
48011
- binPath = (0, import_node_fs47.realpathSync)(binPath);
48997
+ binPath = (0, import_node_fs50.realpathSync)(binPath);
48012
48998
  nodePath = process.execPath;
48013
48999
  }
48014
49000
  if (isNodeScript) {
@@ -48021,9 +49007,9 @@ async function installServiceCommand() {
48021
49007
  }
48022
49008
  }
48023
49009
  const exec = execStartCommand(binPath, nodePath, isNodeScript);
48024
- const configDir = (0, import_node_path36.join)((0, import_node_os14.homedir)(), ".threatcrush");
49010
+ const configDir = (0, import_node_path38.join)((0, import_node_os15.homedir)(), ".threatcrush");
48025
49011
  const unit = renderUnit(resolveTemplate(), { exec, binPath, configDir });
48026
- (0, import_node_fs47.writeFileSync)(UNIT_PATH, unit, { mode: 420 });
49012
+ (0, import_node_fs50.writeFileSync)(UNIT_PATH, unit, { mode: 420 });
48027
49013
  console.log(source_default.green(` \u2713 Installed unit file: ${UNIT_PATH}`));
48028
49014
  console.log(source_default.dim(` ExecStart=${exec}`));
48029
49015
  const nodeDir = nodeVersionDir(nodePath);
@@ -48038,8 +49024,8 @@ async function installServiceCommand() {
48038
49024
  installLogrotate();
48039
49025
  stopUserModeDaemon();
48040
49026
  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" });
49027
+ (0, import_node_child_process19.execSync)("systemctl daemon-reload", { stdio: "inherit" });
49028
+ (0, import_node_child_process19.execSync)(`systemctl enable --now ${DAEMON_UNIT_NAME}`, { stdio: "inherit" });
48043
49029
  } catch (err) {
48044
49030
  console.log(source_default.yellow(` ! systemctl error: ${err.message}`));
48045
49031
  console.log(source_default.dim(` Logs: journalctl -u ${DAEMON_UNIT_NAME} -n 50`));
@@ -48076,9 +49062,9 @@ function renderLogrotate(logDir = "/var/log/threatcrush") {
48076
49062
  ].join("\n");
48077
49063
  }
48078
49064
  function installLogrotate() {
48079
- if (!(0, import_node_fs47.existsSync)((0, import_node_path36.dirname)(LOGROTATE_PATH))) return;
49065
+ if (!(0, import_node_fs50.existsSync)((0, import_node_path38.dirname)(LOGROTATE_PATH))) return;
48080
49066
  try {
48081
- (0, import_node_fs47.writeFileSync)(LOGROTATE_PATH, renderLogrotate(), { mode: 420 });
49067
+ (0, import_node_fs50.writeFileSync)(LOGROTATE_PATH, renderLogrotate(), { mode: 420 });
48082
49068
  console.log(source_default.green(` \u2713 Log rotation: ${LOGROTATE_PATH} (daily or 200M, keeps 7)`));
48083
49069
  } catch (err) {
48084
49070
  console.log(source_default.yellow(` ! Could not install log rotation: ${err.message}`));
@@ -48100,20 +49086,20 @@ function ensureSystemDirs(configDir) {
48100
49086
  ];
48101
49087
  let admGid2 = null;
48102
49088
  try {
48103
- admGid2 = (0, import_node_fs47.statSync)("/var/log/auth.log").gid;
49089
+ admGid2 = (0, import_node_fs50.statSync)("/var/log/auth.log").gid;
48104
49090
  } catch {
48105
49091
  }
48106
49092
  for (const { path: path2, groupWritable, sticky } of dirs) {
48107
49093
  try {
48108
- (0, import_node_fs47.mkdirSync)(path2, { recursive: true });
49094
+ (0, import_node_fs50.mkdirSync)(path2, { recursive: true });
48109
49095
  } catch {
48110
49096
  }
48111
49097
  try {
48112
49098
  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" });
49099
+ (0, import_node_fs50.chmodSync)(path2, sticky ? 1533 : 509);
49100
+ (0, import_node_child_process19.execSync)(`chgrp adm ${path2}`, { stdio: "ignore" });
48115
49101
  } else {
48116
- (0, import_node_fs47.chmodSync)(path2, 493);
49102
+ (0, import_node_fs50.chmodSync)(path2, 493);
48117
49103
  }
48118
49104
  } catch {
48119
49105
  }
@@ -48133,29 +49119,29 @@ async function uninstallServiceCommand() {
48133
49119
  return;
48134
49120
  }
48135
49121
  try {
48136
- (0, import_node_child_process18.execSync)("systemctl stop threatcrushd.service", { stdio: "inherit" });
49122
+ (0, import_node_child_process19.execSync)("systemctl stop threatcrushd.service", { stdio: "inherit" });
48137
49123
  } catch {
48138
49124
  }
48139
49125
  try {
48140
- (0, import_node_child_process18.execSync)("systemctl disable threatcrushd.service", { stdio: "inherit" });
49126
+ (0, import_node_child_process19.execSync)("systemctl disable threatcrushd.service", { stdio: "inherit" });
48141
49127
  } catch {
48142
49128
  }
48143
49129
  try {
48144
- if ((0, import_node_fs47.existsSync)(UNIT_PATH)) {
48145
- (0, import_node_child_process18.execSync)(`rm -f ${UNIT_PATH}`);
49130
+ if ((0, import_node_fs50.existsSync)(UNIT_PATH)) {
49131
+ (0, import_node_child_process19.execSync)(`rm -f ${UNIT_PATH}`);
48146
49132
  console.log(source_default.green(` \u2713 Removed unit file: ${UNIT_PATH}`));
48147
49133
  }
48148
49134
  } catch {
48149
49135
  }
48150
49136
  try {
48151
- (0, import_node_child_process18.execSync)("systemctl daemon-reload", { stdio: "inherit" });
49137
+ (0, import_node_child_process19.execSync)("systemctl daemon-reload", { stdio: "inherit" });
48152
49138
  } catch {
48153
49139
  }
48154
49140
  console.log(source_default.green(" \u2713 threatcrushd service removed."));
48155
49141
  }
48156
49142
 
48157
49143
  // src/commands/save.ts
48158
- var import_node_fs48 = require("fs");
49144
+ var import_node_fs51 = require("fs");
48159
49145
  var import_toml5 = __toESM(require_toml());
48160
49146
  init_cli_config();
48161
49147
  init_paths();
@@ -48194,9 +49180,9 @@ async function saveCommand(opts = {}) {
48194
49180
  }
48195
49181
  const path2 = opts.config ?? PATHS.configFile;
48196
49182
  let config = {};
48197
- if ((0, import_node_fs48.existsSync)(path2)) {
49183
+ if ((0, import_node_fs51.existsSync)(path2)) {
48198
49184
  try {
48199
- config = import_toml5.default.parse((0, import_node_fs48.readFileSync)(path2, "utf-8"));
49185
+ config = import_toml5.default.parse((0, import_node_fs51.readFileSync)(path2, "utf-8"));
48200
49186
  } catch (err) {
48201
49187
  console.log(source_default.red(` \u2717 ${path2} is not valid TOML: ${err.message}
48202
49188
  `));
@@ -48309,8 +49295,8 @@ function welcomeCommand() {
48309
49295
  }
48310
49296
 
48311
49297
  // src/commands/properties.ts
48312
- var import_node_fs49 = require("fs");
48313
- var import_node_path37 = require("path");
49298
+ var import_node_fs52 = require("fs");
49299
+ var import_node_path39 = require("path");
48314
49300
  var import_node_readline4 = __toESM(require("readline"));
48315
49301
  init_cli_config();
48316
49302
  var API_URL6 = process.env.THREATCRUSH_API_URL || "https://threatcrush.com";
@@ -48640,8 +49626,8 @@ async function propertiesRunsCommand(opts) {
48640
49626
  }
48641
49627
  }
48642
49628
  function parseImportFile(path2) {
48643
- const ext = (0, import_node_path37.extname)(path2).toLowerCase();
48644
- const raw = (0, import_node_fs49.readFileSync)(path2, "utf-8");
49629
+ const ext = (0, import_node_path39.extname)(path2).toLowerCase();
49630
+ const raw = (0, import_node_fs52.readFileSync)(path2, "utf-8");
48645
49631
  if (ext === ".json") {
48646
49632
  const parsed = JSON.parse(raw);
48647
49633
  if (!Array.isArray(parsed)) throw new Error("JSON must be an array of objects");
@@ -48836,19 +49822,19 @@ async function rulesCommand(opts) {
48836
49822
  }
48837
49823
 
48838
49824
  // src/commands/harden.ts
48839
- var import_node_fs50 = require("fs");
48840
- var import_node_child_process19 = require("child_process");
49825
+ var import_node_fs53 = require("fs");
49826
+ var import_node_child_process20 = require("child_process");
48841
49827
  init_cli_config();
48842
49828
  function tryExec(cmd) {
48843
49829
  try {
48844
- return (0, import_node_child_process19.execSync)(cmd, { encoding: "utf-8", stdio: ["pipe", "pipe", "pipe"] });
49830
+ return (0, import_node_child_process20.execSync)(cmd, { encoding: "utf-8", stdio: ["pipe", "pipe", "pipe"] });
48845
49831
  } catch {
48846
49832
  return null;
48847
49833
  }
48848
49834
  }
48849
49835
  function tryRead(path2) {
48850
49836
  try {
48851
- return (0, import_node_fs50.readFileSync)(path2, "utf-8");
49837
+ return (0, import_node_fs53.readFileSync)(path2, "utf-8");
48852
49838
  } catch {
48853
49839
  return null;
48854
49840
  }
@@ -48952,8 +49938,8 @@ function checkSshWeakConfig() {
48952
49938
  };
48953
49939
  }
48954
49940
  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");
49941
+ 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");
49942
+ const dnfAuto = (0, import_node_fs53.existsSync)("/etc/dnf/automatic.conf");
48957
49943
  if (unattended || dnfAuto) {
48958
49944
  return {
48959
49945
  key: "auto-updates",
@@ -49079,7 +50065,7 @@ function checkFail2ban() {
49079
50065
  explanation: "fail2ban is installed and running."
49080
50066
  };
49081
50067
  }
49082
- if ((0, import_node_fs50.existsSync)("/etc/fail2ban/fail2ban.conf")) {
50068
+ if ((0, import_node_fs53.existsSync)("/etc/fail2ban/fail2ban.conf")) {
49083
50069
  return {
49084
50070
  key: checkKey,
49085
50071
  status: "warn",
@@ -49265,9 +50251,9 @@ async function hardenCommand(opts) {
49265
50251
  }
49266
50252
 
49267
50253
  // 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");
50254
+ var import_node_fs54 = require("fs");
50255
+ var import_node_path40 = require("path");
50256
+ var import_node_child_process21 = require("child_process");
49271
50257
  var import_node_util5 = require("util");
49272
50258
 
49273
50259
  // src/core/patches/dpkg-version.ts
@@ -49327,7 +50313,7 @@ var STALE_AFTER_MS = 2 * 864e5;
49327
50313
  var SEVERITIES2 = ["info", "low", "medium", "high", "critical"];
49328
50314
  var RANK = { info: 0, low: 1, medium: 2, high: 3, critical: 4 };
49329
50315
  var defaultExec = async (file, args) => {
49330
- const { stdout } = await (0, import_node_util5.promisify)(import_node_child_process20.execFile)(file, args, {
50316
+ const { stdout } = await (0, import_node_util5.promisify)(import_node_child_process21.execFile)(file, args, {
49331
50317
  timeout: 12e4,
49332
50318
  maxBuffer: 32 * 1024 * 1024,
49333
50319
  env: { ...process.env, LC_ALL: "C" }
@@ -49426,9 +50412,9 @@ async function osvRecords(doFetch, ecosystem, source, version) {
49426
50412
  function newestReleaseMtime(dir) {
49427
50413
  try {
49428
50414
  let newest = 0;
49429
- for (const name of (0, import_node_fs51.readdirSync)(dir)) {
50415
+ for (const name of (0, import_node_fs54.readdirSync)(dir)) {
49430
50416
  if (!/Release$/.test(name)) continue;
49431
- newest = Math.max(newest, (0, import_node_fs51.statSync)((0, import_node_path38.join)(dir, name)).mtimeMs);
50417
+ newest = Math.max(newest, (0, import_node_fs54.statSync)((0, import_node_path40.join)(dir, name)).mtimeMs);
49432
50418
  }
49433
50419
  return newest > 0 ? new Date(newest) : null;
49434
50420
  } catch {
@@ -49445,7 +50431,7 @@ async function checkPatches(opts = {}) {
49445
50431
  let osText = opts.osRelease;
49446
50432
  if (osText === void 0) {
49447
50433
  try {
49448
- osText = (0, import_node_fs51.readFileSync)("/etc/os-release", "utf-8");
50434
+ osText = (0, import_node_fs54.readFileSync)("/etc/os-release", "utf-8");
49449
50435
  } catch {
49450
50436
  osText = "";
49451
50437
  }
@@ -49671,27 +50657,27 @@ async function patchesCommand(opts) {
49671
50657
  }
49672
50658
 
49673
50659
  // src/commands/feeds.ts
49674
- var import_node_net15 = require("net");
49675
- var import_node_path40 = require("path");
50660
+ var import_node_net18 = require("net");
50661
+ var import_node_path42 = require("path");
49676
50662
  init_paths();
49677
50663
 
49678
50664
  // 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");
50665
+ var import_node_child_process22 = require("child_process");
50666
+ var import_node_fs55 = require("fs");
50667
+ var import_node_path41 = require("path");
49682
50668
  var realIO = {
49683
- exists: (p) => (0, import_node_fs52.existsSync)(p),
50669
+ exists: (p) => (0, import_node_fs55.existsSync)(p),
49684
50670
  read: (p) => {
49685
50671
  try {
49686
- return (0, import_node_fs52.readFileSync)(p, "utf-8");
50672
+ return (0, import_node_fs55.readFileSync)(p, "utf-8");
49687
50673
  } catch {
49688
50674
  return null;
49689
50675
  }
49690
50676
  },
49691
- write: (p, c) => (0, import_node_fs52.writeFileSync)(p, c),
49692
- remove: (p) => (0, import_node_fs52.rmSync)(p, { force: true }),
50677
+ write: (p, c) => (0, import_node_fs55.writeFileSync)(p, c),
50678
+ remove: (p) => (0, import_node_fs55.rmSync)(p, { force: true }),
49693
50679
  run: (cmd, args) => {
49694
- const r = (0, import_node_child_process21.spawnSync)(cmd, args, { encoding: "utf-8", timeout: 3e4 });
50680
+ const r = (0, import_node_child_process22.spawnSync)(cmd, args, { encoding: "utf-8", timeout: 3e4 });
49695
50681
  return { code: r.status ?? 1, out: `${r.stdout ?? ""}${r.stderr ?? ""}`.trim() };
49696
50682
  }
49697
50683
  };
@@ -49699,17 +50685,17 @@ var APPARMOR_LOCAL = "/etc/apparmor.d/local/usr.sbin.unbound";
49699
50685
  var APPARMOR_PROFILE = "/etc/apparmor.d/usr.sbin.unbound";
49700
50686
  function hookContent(resolver, stateDir) {
49701
50687
  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)}"
50688
+ return resolver === "dnsmasq" ? `${head}addn-hosts=${(0, import_node_path41.join)(stateDir, RESOLVER_FILES.hosts)}
50689
+ ` : `${head}include: "${(0, import_node_path41.join)(stateDir, RESOLVER_FILES.unbound)}"
49704
50690
  `;
49705
50691
  }
49706
50692
  function apparmorRule(stateDir) {
49707
- return ` ${(0, import_node_path39.join)(stateDir, RESOLVER_FILES.unbound)} r, # threatcrush`;
50693
+ return ` ${(0, import_node_path41.join)(stateDir, RESOLVER_FILES.unbound)} r, # threatcrush`;
49708
50694
  }
49709
50695
  function detectResolvers(io = realIO) {
49710
50696
  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");
50697
+ if (io.exists((0, import_node_path41.dirname)(RESOLVER_HOOKS.dnsmasq)) && io.run("dnsmasq", ["--version"]).code === 0) found.push("dnsmasq");
50698
+ if (io.exists((0, import_node_path41.dirname)(RESOLVER_HOOKS.unbound)) && io.run("unbound-checkconf", ["-h"]).code !== 127) found.push("unbound");
49713
50699
  return found;
49714
50700
  }
49715
50701
  function check(resolver, io) {
@@ -49722,7 +50708,7 @@ function restartIfActive(resolver, io) {
49722
50708
  }
49723
50709
  function installHook(resolver, stateDir, io = realIO) {
49724
50710
  const hook = RESOLVER_HOOKS[resolver];
49725
- const file = (0, import_node_path39.join)(stateDir, resolver === "dnsmasq" ? RESOLVER_FILES.hosts : RESOLVER_FILES.unbound);
50711
+ const file = (0, import_node_path41.join)(stateDir, resolver === "dnsmasq" ? RESOLVER_FILES.hosts : RESOLVER_FILES.unbound);
49726
50712
  if (!io.exists(file)) io.write(file, resolver === "dnsmasq" ? hostsBlocklist([]) : unboundBlocklist([]));
49727
50713
  io.write(hook, hookContent(resolver, stateDir));
49728
50714
  if (resolver === "unbound" && io.exists(APPARMOR_LOCAL)) {
@@ -49783,8 +50769,8 @@ function resolverCommand(sub, stateDir, io = realIO) {
49783
50769
  }
49784
50770
  return failed ? 1 : 0;
49785
50771
  }
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));
50772
+ const hosts = io.read((0, import_node_path41.join)(stateDir, RESOLVER_FILES.hosts));
50773
+ const unbound = io.read((0, import_node_path41.join)(stateDir, RESOLVER_FILES.unbound));
49788
50774
  console.log(` resolvers here: ${found.join(", ") || "none that can block (systemd-resolved only?)"}`);
49789
50775
  for (const r of ["dnsmasq", "unbound"]) {
49790
50776
  console.log(` ${r.padEnd(8)} hook ${io.exists(RESOLVER_HOOKS[r]) ? source_default.green("installed") : source_default.gray("not installed")}`);
@@ -49796,11 +50782,11 @@ function resolverCommand(sub, stateDir, io = realIO) {
49796
50782
  // src/commands/feeds.ts
49797
50783
  async function loadSet() {
49798
50784
  for (const dir of [SYSTEM_PATHS.stateDir, USER_PATHS.stateDir]) {
49799
- const path2 = (0, import_node_path40.join)(dir, "threat-feeds.json");
50785
+ const path2 = (0, import_node_path42.join)(dir, "threat-feeds.json");
49800
50786
  const set = readFeedCache(path2);
49801
50787
  if (set) return { set, from: path2 };
49802
50788
  }
49803
- const settings = threatFeedSettings(loadConfig((0, import_node_path40.join)(SYSTEM_PATHS.configDir, "threatcrushd.conf")).threat_feeds);
50789
+ const settings = threatFeedSettings(loadConfig((0, import_node_path42.join)(SYSTEM_PATHS.configDir, "threatcrushd.conf")).threat_feeds);
49804
50790
  return { set: await fetchFeeds(settings), from: "abuse.ch (live; no daemon cache readable)" };
49805
50791
  }
49806
50792
  async function feedsCommand(action, value, opts) {
@@ -49815,8 +50801,8 @@ async function feedsCommand(action, value, opts) {
49815
50801
  process.exitCode = 2;
49816
50802
  return;
49817
50803
  }
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);
50804
+ const ipHit = (0, import_node_net18.isIP)(value) ? matchIp(value, set) : null;
50805
+ const domainHit = (0, import_node_net18.isIP)(value) ? null : matchDomain(value, set);
49820
50806
  const listed = ipHit ?? domainHit?.indicator ?? null;
49821
50807
  if (opts.json) {
49822
50808
  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 +50829,76 @@ async function feedsCommand(action, value, opts) {
49843
50829
  console.log(source_default.gray("\n Blocking egress needs [threat_feeds] block = true and [remediation] in enforce mode."));
49844
50830
  }
49845
50831
 
50832
+ // src/commands/tor.ts
50833
+ var import_node_fs56 = require("fs");
50834
+ var import_node_net19 = require("net");
50835
+ var import_node_path43 = require("path");
50836
+ init_paths();
50837
+ async function torCommand(action, value, opts) {
50838
+ let exits = /* @__PURE__ */ new Set();
50839
+ let from = "";
50840
+ let updated = null;
50841
+ for (const dir of [SYSTEM_PATHS.stateDir, USER_PATHS.stateDir]) {
50842
+ const path2 = (0, import_node_path43.join)(dir, "tor-exits.txt");
50843
+ try {
50844
+ if (!(0, import_node_fs56.existsSync)(path2)) continue;
50845
+ exits = parseTorExitList((0, import_node_fs56.readFileSync)(path2, "utf-8"));
50846
+ from = path2;
50847
+ updated = (0, import_node_fs56.statSync)(path2).mtime;
50848
+ break;
50849
+ } catch {
50850
+ }
50851
+ }
50852
+ if (!exits.size) {
50853
+ try {
50854
+ const res = await fetch(TOR_BULK_EXIT_LIST_URL, { signal: AbortSignal.timeout(2e4) });
50855
+ if (res.ok) {
50856
+ exits = parseTorExitList(await res.text());
50857
+ from = `${TOR_BULK_EXIT_LIST_URL} (live; no daemon cache readable)`;
50858
+ updated = /* @__PURE__ */ new Date();
50859
+ }
50860
+ } catch {
50861
+ }
50862
+ }
50863
+ const remediation = loadConfig((0, import_node_path43.join)(SYSTEM_PATHS.configDir, "threatcrushd.conf")).remediation;
50864
+ const ban = remediation?.block_tor_ssh !== false && remediation?.enabled !== false;
50865
+ if (action === "check") {
50866
+ if (!value || !(0, import_node_net19.isIP)(value)) {
50867
+ console.error("Usage: threatcrush tor check <ip>");
50868
+ process.exitCode = 2;
50869
+ return;
50870
+ }
50871
+ const listed = exits.has(normalizeIp(value));
50872
+ if (opts.json) console.log(JSON.stringify({ ip: value, tor_exit: listed, list_size: exits.size, from }, null, 2));
50873
+ else console.log(listed ? `${source_default.red("TOR EXIT")} ${value}` : `${source_default.green("not a Tor exit")} ${value}`);
50874
+ process.exitCode = listed ? 1 : 0;
50875
+ return;
50876
+ }
50877
+ const status = {
50878
+ exits: exits.size,
50879
+ from,
50880
+ updated_at: updated?.toISOString() ?? null,
50881
+ block_tor_ssh: ban,
50882
+ pinned_in_config: typeof remediation?.block_tor_ssh === "boolean"
50883
+ };
50884
+ if (opts.json) {
50885
+ console.log(JSON.stringify(status, null, 2));
50886
+ return;
50887
+ }
50888
+ console.log(`Tor exits known: ${source_default.bold(String(status.exits))}${status.updated_at ? ` (updated ${status.updated_at})` : ""}`);
50889
+ console.log(`Source: ${status.from || "none (daemon not running yet, and the list could not be fetched)"}`);
50890
+ 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)"}`);
50891
+ }
50892
+
49846
50893
  // 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");
50894
+ var import_node_os16 = require("os");
50895
+ var import_node_fs57 = require("fs");
50896
+ var import_node_path44 = require("path");
49850
50897
  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");
50898
+ var CONFIG_PATH4 = (0, import_node_path44.join)((0, import_node_os16.homedir)(), ".threatcrush", "config.json");
49852
50899
  function readConfig3() {
49853
50900
  try {
49854
- return JSON.parse((0, import_node_fs53.readFileSync)(CONFIG_PATH4, "utf-8"));
50901
+ return JSON.parse((0, import_node_fs57.readFileSync)(CONFIG_PATH4, "utf-8"));
49855
50902
  } catch {
49856
50903
  return {};
49857
50904
  }
@@ -50039,7 +51086,7 @@ async function reputationSubscribeCommand(opts) {
50039
51086
  }
50040
51087
 
50041
51088
  // src/commands/privileged.ts
50042
- var import_node_fs54 = require("fs");
51089
+ var import_node_fs58 = require("fs");
50043
51090
  init_paths();
50044
51091
  var SEV2 = {
50045
51092
  critical: source_default.red.bold,
@@ -50052,19 +51099,19 @@ async function privilegedCommand(opts) {
50052
51099
  const snapshot = takeSnapshot({
50053
51100
  readFile: (p) => {
50054
51101
  try {
50055
- return (0, import_node_fs54.readFileSync)(p, "utf-8");
51102
+ return (0, import_node_fs58.readFileSync)(p, "utf-8");
50056
51103
  } catch {
50057
51104
  return null;
50058
51105
  }
50059
51106
  },
50060
51107
  readDir: (p) => {
50061
51108
  try {
50062
- return (0, import_node_fs54.readdirSync)(p);
51109
+ return (0, import_node_fs58.readdirSync)(p);
50063
51110
  } catch {
50064
51111
  return null;
50065
51112
  }
50066
51113
  },
50067
- exists: (p) => (0, import_node_fs54.existsSync)(p)
51114
+ exists: (p) => (0, import_node_fs58.existsSync)(p)
50068
51115
  });
50069
51116
  let events = [];
50070
51117
  let ledgerNote = "";
@@ -50246,7 +51293,7 @@ async function allowlistCommand(opts) {
50246
51293
  }
50247
51294
 
50248
51295
  // src/commands/abuse.ts
50249
- var import_node_fs55 = require("fs");
51296
+ var import_node_fs59 = require("fs");
50250
51297
  init_paths();
50251
51298
  function rows(records) {
50252
51299
  if (records.length === 0) {
@@ -50306,7 +51353,7 @@ function abuseRetractCommand(id, opts = {}) {
50306
51353
  );
50307
51354
  }
50308
51355
  function abuseStatusCommand(opts = {}) {
50309
- const config = loadConfig((0, import_node_fs55.existsSync)(PATHS.configFile) ? PATHS.configFile : void 0);
51356
+ const config = loadConfig((0, import_node_fs59.existsSync)(PATHS.configFile) ? PATHS.configFile : void 0);
50310
51357
  const cfg = resolveConfig(config.abuse_reporter);
50311
51358
  const hasKey2 = Boolean(cfg.keys.abuseipdb || cfg.keys.stopforumspam);
50312
51359
  const active2 = cfg.enabled && (cfg.dryRun || hasKey2);
@@ -50329,11 +51376,11 @@ function abuseStatusCommand(opts = {}) {
50329
51376
  init_paths();
50330
51377
 
50331
51378
  // src/upgrade.ts
50332
- var import_node_child_process22 = require("child_process");
51379
+ var import_node_child_process23 = require("child_process");
50333
51380
  var PACKAGE_MANAGERS = ["npm", "pnpm", "yarn", "bun"];
50334
51381
  var defaultRunner = (cmd) => {
50335
51382
  try {
50336
- return (0, import_node_child_process22.execSync)(cmd, { encoding: "utf-8", stdio: ["pipe", "pipe", "pipe"] });
51383
+ return (0, import_node_child_process23.execSync)(cmd, { encoding: "utf-8", stdio: ["pipe", "pipe", "pipe"] });
50337
51384
  } catch {
50338
51385
  return null;
50339
51386
  }
@@ -50474,9 +51521,9 @@ function installUserAgent(target = globalThis) {
50474
51521
  }
50475
51522
 
50476
51523
  // 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");
51524
+ var import_node_child_process24 = require("child_process");
51525
+ var import_node_os17 = require("os");
51526
+ var import_node_path45 = require("path");
50480
51527
  init_cli_config();
50481
51528
  function uploadDisabled(upload, env3 = process.env) {
50482
51529
  if (upload === false) return true;
@@ -50495,8 +51542,8 @@ function cleanUrl(raw) {
50495
51542
  return raw.split(/[?#]/)[0];
50496
51543
  }
50497
51544
  }
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);
51545
+ 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()) {
51546
+ const abs = (0, import_node_path45.resolve)(path2);
50500
51547
  try {
50501
51548
  const root = run(["rev-parse", "--show-toplevel"]);
50502
51549
  const sub = abs === root ? "." : abs.slice(root.length + 1);
@@ -50509,9 +51556,9 @@ function repoTarget(path2, run = (args) => (0, import_node_child_process23.execF
50509
51556
  const m = /^(?:[a-z+]+:\/\/)?(?:[^@/]+@)?([^/:]+)[:/](.+?)(?:\.git)?\/?$/i.exec(remote);
50510
51557
  if (m) return { target: `${m[1]}/${m[2]}`, root, sub };
50511
51558
  }
50512
- return { target: `${(0, import_node_os16.hostname)()}:${root}`, root, sub };
51559
+ return { target: `${(0, import_node_os17.hostname)()}:${root}`, root, sub };
50513
51560
  } catch {
50514
- return { target: `${(0, import_node_os16.hostname)()}:${abs}`, root: abs, sub: "." };
51561
+ return { target: `${(0, import_node_os17.hostname)()}:${abs}`, root: abs, sub: "." };
50515
51562
  }
50516
51563
  }
50517
51564
  async function uploadResult(result, opts) {
@@ -50868,25 +51915,25 @@ ${source_default.dim(" C R U S H")}
50868
51915
  var API_URL8 = process.env.THREATCRUSH_API_URL || "https://threatcrush.com";
50869
51916
  var PKG_NAME2 = "@profullstack/threatcrush";
50870
51917
  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");
51918
+ var INSTALL_CONFIG_PATH = (0, import_node_path46.join)((0, import_node_os18.homedir)(), ".threatcrush", "install.json");
50872
51919
  function detectPackageManager() {
50873
51920
  try {
50874
- const npmGlobal = (0, import_node_child_process24.execSync)("npm ls -g --depth=0 --json 2>/dev/null", { encoding: "utf-8" });
51921
+ const npmGlobal = (0, import_node_child_process25.execSync)("npm ls -g --depth=0 --json 2>/dev/null", { encoding: "utf-8" });
50875
51922
  if (npmGlobal.includes(PKG_NAME2)) return "npm";
50876
51923
  } catch {
50877
51924
  }
50878
51925
  try {
50879
- (0, import_node_child_process24.execSync)("pnpm --version", { stdio: "pipe" });
51926
+ (0, import_node_child_process25.execSync)("pnpm --version", { stdio: "pipe" });
50880
51927
  return "pnpm";
50881
51928
  } catch {
50882
51929
  }
50883
51930
  try {
50884
- (0, import_node_child_process24.execSync)("yarn --version", { stdio: "pipe" });
51931
+ (0, import_node_child_process25.execSync)("yarn --version", { stdio: "pipe" });
50885
51932
  return "yarn";
50886
51933
  } catch {
50887
51934
  }
50888
51935
  try {
50889
- (0, import_node_child_process24.execSync)("bun --version", { stdio: "pipe" });
51936
+ (0, import_node_child_process25.execSync)("bun --version", { stdio: "pipe" });
50890
51937
  return "bun";
50891
51938
  } catch {
50892
51939
  }
@@ -50894,14 +51941,14 @@ function detectPackageManager() {
50894
51941
  }
50895
51942
  function readInstallConfig() {
50896
51943
  try {
50897
- return JSON.parse((0, import_node_fs56.readFileSync)(INSTALL_CONFIG_PATH, "utf-8"));
51944
+ return JSON.parse((0, import_node_fs60.readFileSync)(INSTALL_CONFIG_PATH, "utf-8"));
50898
51945
  } catch {
50899
51946
  return {};
50900
51947
  }
50901
51948
  }
50902
51949
  function packageLooksInstalled(pm, pkgName) {
50903
51950
  try {
50904
- const output = (0, import_node_child_process24.execSync)(globalListCommand(pm, pkgName), {
51951
+ const output = (0, import_node_child_process25.execSync)(globalListCommand(pm, pkgName), {
50905
51952
  encoding: "utf-8",
50906
51953
  stdio: ["pipe", "pipe", "pipe"]
50907
51954
  });
@@ -51004,14 +52051,14 @@ async function promoteUnprivilegedDaemon() {
51004
52051
  function restartSystemdDaemon() {
51005
52052
  const asRoot = typeof process.getuid === "function" && process.getuid() === 0;
51006
52053
  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;
52054
+ if (!asRoot && (0, import_node_child_process25.spawnSync)("sudo", ["--version"], { stdio: "pipe" }).status !== 0) return false;
51008
52055
  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;
52056
+ if ((0, import_node_child_process25.spawnSync)(cmd, args, { stdio: "inherit" }).status !== 0) return false;
52057
+ return (0, import_node_child_process25.spawnSync)("systemctl", ["is-active", "--quiet", DAEMON_UNIT], { stdio: "pipe" }).status === 0;
51011
52058
  }
51012
52059
  function execQuiet(cmd) {
51013
52060
  try {
51014
- return (0, import_node_child_process24.execSync)(cmd, { encoding: "utf-8", stdio: ["pipe", "pipe", "pipe"] });
52061
+ return (0, import_node_child_process25.execSync)(cmd, { encoding: "utf-8", stdio: ["pipe", "pipe", "pipe"] });
51015
52062
  } catch {
51016
52063
  return null;
51017
52064
  }
@@ -51252,6 +52299,9 @@ program2.command("patches").description("List OS packages with a security update
51252
52299
  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
52300
  await feedsCommand(action, value, opts);
51254
52301
  });
52302
+ 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) => {
52303
+ await torCommand(action, value, opts);
52304
+ });
51255
52305
  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
52306
  if (!indicators?.length) {
51257
52307
  reputationCmd.help();
@@ -51304,7 +52354,7 @@ program2.command("uninstall-service").description("Remove the threatcrushd syste
51304
52354
  program2.command("logs").description("Tail daemon logs").action(async () => {
51305
52355
  console.log(LOGO2);
51306
52356
  const logPath2 = PATHS.logFile;
51307
- if (!(0, import_node_fs56.existsSync)(logPath2)) {
52357
+ if (!(0, import_node_fs60.existsSync)(logPath2)) {
51308
52358
  console.log(source_default.yellow(` No log file found at ${logPath2}`));
51309
52359
  console.log(source_default.dim(" Start the daemon first with `threatcrush start`\n"));
51310
52360
  return;
@@ -51312,7 +52362,7 @@ program2.command("logs").description("Tail daemon logs").action(async () => {
51312
52362
  console.log(source_default.green(` Tailing ${logPath2}...
51313
52363
  `));
51314
52364
  console.log(source_default.gray(" Press Ctrl+C to stop\n"));
51315
- (0, import_node_child_process24.execSync)(`tail -f ${logPath2}`, { stdio: "inherit" });
52365
+ (0, import_node_child_process25.execSync)(`tail -f ${logPath2}`, { stdio: "inherit" });
51316
52366
  });
51317
52367
  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
52368
  console.log(LOGO2);
@@ -51324,7 +52374,7 @@ program2.command("update").description("Update ThreatCrush CLI and installed bun
51324
52374
  for (const cmd of commands2) {
51325
52375
  console.log(source_default.green(` \u2192 ${cmd}
51326
52376
  `));
51327
- (0, import_node_child_process24.execSync)(cmd, { stdio: "inherit" });
52377
+ (0, import_node_child_process25.execSync)(cmd, { stdio: "inherit" });
51328
52378
  }
51329
52379
  console.log(source_default.green("\n \u2713 Modules updated successfully!\n"));
51330
52380
  await reportIfStillStale();
@@ -51349,7 +52399,7 @@ program2.command("update").description("Update ThreatCrush CLI and installed bun
51349
52399
  for (const cmd of commands) {
51350
52400
  console.log(source_default.green(` \u2192 ${cmd}
51351
52401
  `));
51352
- (0, import_node_child_process24.execSync)(cmd, { stdio: "inherit" });
52402
+ (0, import_node_child_process25.execSync)(cmd, { stdio: "inherit" });
51353
52403
  }
51354
52404
  console.log(source_default.green("\n \u2713 ThreatCrush updated successfully!\n"));
51355
52405
  if (installMode === "desktop") {
@@ -51400,7 +52450,7 @@ program2.command("remove").description("Uninstall ThreatCrush and the installed
51400
52450
  for (const cmd of commands) {
51401
52451
  console.log(source_default.green(` \u2192 ${cmd}
51402
52452
  `));
51403
- (0, import_node_child_process24.execSync)(cmd, { stdio: "inherit" });
52453
+ (0, import_node_child_process25.execSync)(cmd, { stdio: "inherit" });
51404
52454
  }
51405
52455
  console.log(source_default.green("\n \u2713 ThreatCrush has been uninstalled.\n"));
51406
52456
  console.log(source_default.dim(" We're sorry to see you go! \u{1F44B}\n"));
@@ -51477,10 +52527,10 @@ storeCmd.command("search <query>").description("Search for modules in the store"
51477
52527
  });
51478
52528
  storeCmd.command("publish <url>").description("Publish a module from a git URL or web URL").action(async (url) => {
51479
52529
  console.log(LOGO2);
51480
- const configPath = (0, import_node_path43.join)((0, import_node_os17.homedir)(), ".threatcrush", "config.json");
52530
+ const configPath = (0, import_node_path46.join)((0, import_node_os18.homedir)(), ".threatcrush", "config.json");
51481
52531
  let email = "";
51482
52532
  try {
51483
- const config = JSON.parse((0, import_node_fs56.readFileSync)(configPath, "utf-8"));
52533
+ const config = JSON.parse((0, import_node_fs60.readFileSync)(configPath, "utf-8"));
51484
52534
  email = config.email || "";
51485
52535
  } catch {
51486
52536
  }
@@ -51497,9 +52547,9 @@ storeCmd.command("publish <url>").description("Publish a module from a git URL o
51497
52547
  return;
51498
52548
  }
51499
52549
  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));
52550
+ const dir = (0, import_node_path46.join)((0, import_node_os18.homedir)(), ".threatcrush");
52551
+ if (!(0, import_node_fs60.existsSync)(dir)) (0, import_node_fs60.mkdirSync)(dir, { recursive: true });
52552
+ (0, import_node_fs60.writeFileSync)(configPath, JSON.stringify({ email }, null, 2));
51503
52553
  console.log(source_default.dim(` Saved email to ${configPath}`));
51504
52554
  } catch {
51505
52555
  }